Open History to see the last commit
1import * as Arr from "effect/Array";
2import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";
3
4/**
5 * Reduce a single shell stream event into an existing snapshot, returning a new
6 * snapshot with the event's changes applied. This is a pure reducer that both
7 * web and mobile can use to keep their local shell snapshot in sync.
8 *
9 * Returns the original snapshot reference unchanged if the event is not
10 * recognized (forward-compatible).
11 */
12export function applyShellStreamEvent(
13 snapshot: OrchestrationShellSnapshot,
14 event: OrchestrationShellStreamEvent,
15): OrchestrationShellSnapshot {
16 if (event.sequence <= snapshot.snapshotSequence) return snapshot;
17
18 switch (event.kind) {
19 case "project-upserted": {
20 const projects = snapshot.projects.some((p) => p.id === event.project.id)
21 ? Arr.map(snapshot.projects, (p) => (p.id === event.project.id ? event.project : p))
22 : Arr.append(snapshot.projects, event.project);
23 return { ...snapshot, projects, snapshotSequence: event.sequence };
24 }
25 case "project-removed":
26 return {
27 ...snapshot,
28 projects: Arr.filter(snapshot.projects, (p) => p.id !== event.projectId),
29 snapshotSequence: event.sequence,
30 };
31 case "thread-upserted": {
32 const threads = snapshot.threads.some((t) => t.id === event.thread.id)
33 ? Arr.map(snapshot.threads, (t) => (t.id === event.thread.id ? event.thread : t))
34 : Arr.append(snapshot.threads, event.thread);
35 return { ...snapshot, threads, snapshotSequence: event.sequence };
36 }
37 case "thread-removed":
38 return {
39 ...snapshot,
40 threads: Arr.filter(snapshot.threads, (t) => t.id !== event.threadId),
41 snapshotSequence: event.sequence,
42 };
43 default:
44 return snapshot;
45 }
46}