import type { EventType } from "./eventTypes"; import type { EventVisibility } from "./visibility"; import { resolveEventVisibility } from "./visibility"; import { broadcast } from "@/lib/realtime/bus"; import type { Permission } from "@/permissions"; interface GameEventInput { type: EventType; message: string; actor?: number; structure?: number; targetCollection?: | "users" | "missions" | "maps" | "campaigns" | "factions" | "technologies" | "assets" | "resources" | "structures" | "vehicles" | "game-structures" | "game-vehicles" | "game-npcs" | "npc-staffing" | "shipments" | "bank-accounts" | "bank-transactions" | "ledger-entries" | "locker-storages" | "loadouts" | "market-listings" | "market-negotiations" | "evaluations" | "tickets" | "wiki-pages" | "wiki-revisions" | "wiki-templates" | "game-servers" | "assignment-transfers" | "market-state" | "voice-scripts" | "voice-submissions" | "story-beats" | "story-beat-states" | "custom-minefields" | "custom-minefield-scores" | "custom-radio-tests" | "custom-radio-test-scores" | "ribbon-submissions" | "promotion-nominations" | "leadership-transfers" | "player-flags" | "reinforcement-pools" | "form-submissions" | "mission-map-markers" | "contribution-entries"; targetId?: number; data?: Record; /** * Override the per-type visibility default (see `EVENT_VISIBILITY_POLICIES`). * Omit to use the type's policy, which falls back to "public". */ visibility?: EventVisibility; /** Any-of permission gate for restricted events. See `visibility`. */ requiredPermissions?: Permission[]; } export async function emitGameEvent( payload: Awaited>, event: GameEventInput, ) { const policy = resolveEventVisibility(event.type, { visibility: event.visibility, requiredPermissions: event.requiredPermissions, }); try { await payload.create({ collection: "game-event-logs", data: { system: true, timestamp: new Date().toISOString(), type: event.type, actor: event.actor, message: event.message, data: event.data, targetCollection: event.targetCollection, targetId: event.targetId, structure: event.structure, visibility: policy.visibility, requiredPermissions: policy.requiredPermissions, }, depth: 0, // Bins and tests run without an authenticated user; create access on // game-event-logs requires one, so system events would be silently dropped. overrideAccess: true, }); // Public events broadcast their metadata; restricted events broadcast an // opaque nudge so the SSE stream itself never leaks who did what. The // client listener ignores the payload and refetches through access- // filtered queries anyway. broadcast( "game-event", policy.visibility === "restricted" ? { restricted: true } : { type: event.type, actor: event.actor ?? null, targetCollection: event.targetCollection ?? null, targetId: event.targetId ?? null, }, ); } catch (err) { console.error("[EventLog] Failed to emit event:", err); } }