|
| 1 | +import { describe, expect, it } from "vitest"; |
| 2 | +import type { AppState } from "../../lib/bridge"; |
| 3 | +import { emptyProfile, type Profile } from "../../lib/schema"; |
| 4 | +import { |
| 5 | + mapFetchedSubscriptionProfiles, |
| 6 | + nextActiveIdAfterSubscriptionUpdate, |
| 7 | +} from "../state-mutations"; |
| 8 | + |
| 9 | +function vless(overrides: Partial<Extract<Profile, { protocol: "vless" }>>): Profile { |
| 10 | + return { ...(emptyProfile("vless") as Extract<Profile, { protocol: "vless" }>), ...overrides }; |
| 11 | +} |
| 12 | + |
| 13 | +function stateWith(profiles: Profile[], activeId: string | null): AppState { |
| 14 | + return { profiles, activeId } as AppState; |
| 15 | +} |
| 16 | + |
| 17 | +const sub = { id: "s1", groupId: undefined } as never; |
| 18 | + |
| 19 | +describe("nextActiveIdAfterSubscriptionUpdate", () => { |
| 20 | + it("keeps the active id when the active profile is not from this subscription", () => { |
| 21 | + const active = vless({ id: "p1", subId: "other" }); |
| 22 | + const fresh = mapFetchedSubscriptionProfiles([vless({ remarks: "X" })], sub, null); |
| 23 | + expect(nextActiveIdAfterSubscriptionUpdate(stateWith([active], "p1"), "s1", fresh)).toBe("p1"); |
| 24 | + }); |
| 25 | + |
| 26 | + it("matches the re-created active profile by exact identity", () => { |
| 27 | + const active = vless({ id: "p1", subId: "s1", remarks: "Node", address: "ex.com", port: 443 }); |
| 28 | + const fresh = mapFetchedSubscriptionProfiles( |
| 29 | + [vless({ remarks: "Node", address: "ex.com", port: 443 })], |
| 30 | + sub, |
| 31 | + null, |
| 32 | + ); |
| 33 | + const next = nextActiveIdAfterSubscriptionUpdate(stateWith([active], "p1"), "s1", fresh); |
| 34 | + expect(next).toBe(fresh[0].id); |
| 35 | + }); |
| 36 | + |
| 37 | + it("falls back to the same-name profile when the endpoint (port) changed", () => { |
| 38 | + const active = vless({ id: "p1", subId: "s1", remarks: "Node", address: "ex.com", port: 443 }); |
| 39 | + const fresh = mapFetchedSubscriptionProfiles( |
| 40 | + [vless({ remarks: "Node", address: "ex.com", port: 8443 })], |
| 41 | + sub, |
| 42 | + null, |
| 43 | + ); |
| 44 | + const next = nextActiveIdAfterSubscriptionUpdate(stateWith([active], "p1"), "s1", fresh); |
| 45 | + expect(next).toBe(fresh[0].id); |
| 46 | + }); |
| 47 | + |
| 48 | + it("returns null when the active profile no longer exists in the update", () => { |
| 49 | + const active = vless({ id: "p1", subId: "s1", remarks: "Gone" }); |
| 50 | + const fresh = mapFetchedSubscriptionProfiles([vless({ remarks: "Other" })], sub, null); |
| 51 | + expect(nextActiveIdAfterSubscriptionUpdate(stateWith([active], "p1"), "s1", fresh)).toBeNull(); |
| 52 | + }); |
| 53 | +}); |
0 commit comments