import assert from "node:assert/strict"; import test from "node:test"; import { chartLibraryFromCloudOthers, chartLibrarySessionBranch, keepLocalChartLibraryOnCloudFailure, } from "../src/lib/chart-library-session.ts"; type RecordShape = { id: string; role: "self" | "other" }; function upsertSelf(library: RecordShape[], profile: unknown): RecordShape[] { const others = library.filter((record) => record.role !== "self"); if (!profile) return others; return [{ id: "self", role: "self" }, ...others]; } test("clearing the account empties the chart library session", () => { assert.equal(chartLibrarySessionBranch(null, "acct-1"), "clear"); assert.equal(chartLibrarySessionBranch("", "acct-1"), "clear"); }); test("switching accounts hydrates local then cloud instead of writing the previous library", () => { assert.equal(chartLibrarySessionBranch("acct-2", "acct-1"), "hydrate-then-persist"); }); test("a later profile change on the same account still upserts self", () => { assert.equal(chartLibrarySessionBranch("acct-1", "acct-1"), "persist-self"); const current: RecordShape[] = [{ id: "other-1", role: "other" }]; assert.deepEqual(upsertSelf(current, { name: "self" }), [ { id: "self", role: "self" }, { id: "other-1", role: "other" }, ]); }); test("a successful cloud read keeps only non-self records before upserting self", () => { const cloud: RecordShape[] = [ { id: "stale-self", role: "self" }, { id: "other-1", role: "other" }, ]; assert.deepEqual(chartLibraryFromCloudOthers(cloud, { name: "self" }, upsertSelf), [ { id: "self", role: "self" }, { id: "other-1", role: "other" }, ]); }); test("a failed cloud read leaves the local library in place", () => { const local: RecordShape[] = [{ id: "self", role: "self" }, { id: "other-1", role: "other" }]; assert.equal(keepLocalChartLibraryOnCloudFailure(local), local); });