Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

browserHistoryStore.test.ts

244 lines10.2 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
2​
3import { EnvironmentId, ThreadId } from "@t3tools/contracts";
4​
5const { readPreparedConnection } = vi.hoisted(() => ({
6 readPreparedConnection: vi.fn<() => { httpBaseUrl: string } | null>(() => null),
7}));
8​
9vi.mock("~/state/session", () => ({ readPreparedConnection }));
10​
11import {
12 BROWSER_HISTORY_MAX_PROJECTS,
13 type BrowserHistoryEntry,
14 mergeBrowserHistoryState,
15 migratePersistedBrowserHistoryState,
16 normalizeHistoryUrl,
17 recordVisitForThread,
18 resetBrowserHistoryForTests,
19 setTitleForThreadUrl,
20 upsertHistoryEntry,
21 useBrowserHistoryStore,
22} from "./browserHistoryStore";
23​
24function entry(overrides: Partial<BrowserHistoryEntry> = {}): BrowserHistoryEntry {
25 return { url: "http://localhost:3000/", lastVisitedAt: 1000, ...overrides };
27​
28beforeEach(() => readPreparedConnection.mockReturnValue(null));
29afterEach(() => vi.restoreAllMocks());
30​
31describe("normalizeHistoryUrl", () => {
32 it("normalizes bare loopback hosts to http and keeps path/query", () => {
33 expect(normalizeHistoryUrl("localhost:3000/admin?tab=1")).toBe(
34 "http://localhost:3000/admin?tab=1",
35 );
36 });
37​
38 it("preserves hash routes and strips credentials", () => {
39 expect(normalizeHistoryUrl("http://localhost:3000/app#/route")).toBe(
40 "http://localhost:3000/app#/route",
41 );
42 expect(normalizeHistoryUrl("https://user:secret@example.com/")).toBe("https://example.com/");
43 });
44​
45 it("rejects non-http(s), unparseable, and oversized urls", () => {
46 expect(normalizeHistoryUrl("ftp://example.com")).toBeNull();
47 expect(normalizeHistoryUrl("")).toBeNull();
48 expect(normalizeHistoryUrl(`http://localhost/${"a".repeat(2048)}`)).toBeNull();
49 });
50});
51​
52describe("upsertHistoryEntry", () => {
53 it("with insertOrdered, replaying an older visit for an existing entry keeps its newer timestamp", () => {
54 const existing = [entry({ url: "http://a.test/", lastVisitedAt: 2000 })];
55 const next = upsertHistoryEntry(existing, "http://a.test/", 1000, { insertOrdered: true });
56 expect(next).toEqual([{ url: "http://a.test/", lastVisitedAt: 2000 }]);
57 });
58});
59​
60describe("migratePersistedBrowserHistoryState", () => {
61 it("drops malformed state and invalid entries", () => {
62 expect(migratePersistedBrowserHistoryState(null)).toEqual({ byProjectKey: {} });
63 expect(migratePersistedBrowserHistoryState({ byProjectKey: 42 })).toEqual({ byProjectKey: {} });
64 const migrated = migratePersistedBrowserHistoryState({
65 byProjectKey: {
66 good: [
67 { url: "http://a.test/", lastVisitedAt: 100, title: "A" },
68 { url: "", lastVisitedAt: 100 },
69 { url: "ftp://ghost.test/", lastVisitedAt: 100 },
70 { url: "http://b.test/", lastVisitedAt: Number.NaN },
71 "junk",
72 ],
73 bad: "junk",
74 },
75 });
76 expect(migrated.byProjectKey["good"]).toEqual([
77 { url: "http://a.test/", lastVisitedAt: 100, title: "A" },
78 ]);
79 expect(migrated.byProjectKey["bad"]).toBeUndefined();
80 });
81​
82 it("restores MRU ordering, deduplicates normalized urls, and enforces project bounds", () => {
83 const byProjectKey = Object.fromEntries(
84 Array.from({ length: BROWSER_HISTORY_MAX_PROJECTS + 1 }, (_, index) => [
85 `project-${index}`,
86 [{ url: `http://project-${index}.test/`, lastVisitedAt: index }],
87 ]),
88 );
89 byProjectKey["project-1"] = [
90 { url: "a.test/", lastVisitedAt: 1 },
91 { url: "http://newer.test/", lastVisitedAt: 3 },
92 { url: "https://a.test/", lastVisitedAt: 2 },
93 ];
94​
95 const migrated = migratePersistedBrowserHistoryState({ byProjectKey });
96​
97 expect(Object.keys(migrated.byProjectKey)).toHaveLength(BROWSER_HISTORY_MAX_PROJECTS);
98 expect(migrated.byProjectKey["project-0"]).toBeUndefined();
99 expect(migrated.byProjectKey["project-1"]).toEqual([
100 { url: "http://newer.test/", lastVisitedAt: 3 },
101 { url: "https://a.test/", lastVisitedAt: 2 },
102 ]);
103 });
104});
105​
106const threadRef = {
107 environmentId: EnvironmentId.make("env-1"),
108 threadId: ThreadId.make("thread-1"),
109};
110​
111describe("useBrowserHistoryStore", () => {
112 beforeEach(() => {
113 resetBrowserHistoryForTests();
114 });
115​
116 it("sets titles update-only via the thread helper", () => {
117 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
118 setTitleForThreadUrl(threadRef, "http://a.test/", "Should not create");
119 expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
120 recordVisitForThread(threadRef, "http://a.test/#/settings", 1);
121 setTitleForThreadUrl(threadRef, "http://a.test/#/settings", "My App");
122 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("My App");
123 });
124​
125 it("sets a title against a settled url that differs from the stored one only by a trailing slash", () => {
126 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
127 recordVisitForThread(threadRef, "http://a.test/community", 1);
128 setTitleForThreadUrl(threadRef, "http://a.test/community/", "Community");
129 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]).toMatchObject({
130 url: "http://a.test/community",
131 title: "Community",
132 });
133​
134 useBrowserHistoryStore.setState({ byProjectKey: {} });
135 recordVisitForThread(threadRef, "http://a.test/community/", 1);
136 setTitleForThreadUrl(threadRef, "http://a.test/community", "Community");
137 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]).toMatchObject({
138 url: "http://a.test/community/",
139 title: "Community",
140 });
141 });
142​
143 it("matches a requested localhost URL to the resolved environment host", () => {
144 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
145 recordVisitForThread(threadRef, "http://localhost:5173/app", 1);
146 setTitleForThreadUrl(threadRef, "http://192.168.64.2:5173/app", "Local App", "192.168.64.2");
147 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("Local App");
148 });
149​
150 it("deduplicates loopback aliases and the resolved environment host", () => {
151 readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://192.168.64.2:3773" });
152 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
153 recordVisitForThread(threadRef, "http://localhost:5173/app", 1);
154 recordVisitForThread(threadRef, "http://127.0.0.1:5173/app", 2);
155 recordVisitForThread(threadRef, "http://192.168.64.2:5173/app", 3);
156 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]).toEqual([
157 { url: "http://localhost:5173/app", lastVisitedAt: 3 },
158 ]);
159​
160 useBrowserHistoryStore.setState({ byProjectKey: {} });
161 recordVisitForThread(threadRef, "http://192.168.64.2:5173/app", 4);
162 recordVisitForThread(threadRef, "http://localhost:5173/app", 5);
163 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]).toEqual([
164 { url: "http://localhost:5173/app", lastVisitedAt: 5 },
165 ]);
166 });
167});
168​
169describe("pendingVisitsByThreadKey", () => {
170 beforeEach(() => {
171 resetBrowserHistoryForTests();
172 });
173​
174 it("queues a visit recorded before registration and drains it in order on registration", () => {
175 recordVisitForThread(threadRef, "http://a.test/", 1);
176 recordVisitForThread(threadRef, "http://b.test/", 2);
177 expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
178 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
179 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.map((e) => e.url)).toEqual([
180 "http://b.test/",
181 "http://a.test/",
182 ]);
183 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.lastVisitedAt).toBe(2);
184 expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[1]?.lastVisitedAt).toBe(1);
185 expect(useBrowserHistoryStore.getState().pendingVisitsByThreadKey).toEqual({});
186 });
187​
188 it("slots a replayed visit by timestamp instead of hoisting it above a newer live visit", () => {
189 const otherThreadRef = {
190 environmentId: EnvironmentId.make("env-1"),
191 threadId: ThreadId.make("thread-2"),
192 };
193 useBrowserHistoryStore.getState().registerThreadProject(otherThreadRef, "proj-a");
194 recordVisitForThread(otherThreadRef, "http://newer.test/", 2000);
195 recordVisitForThread(threadRef, "http://older.test/", 1000);
196 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
197​
198 const entries = useBrowserHistoryStore.getState().byProjectKey["proj-a"];
199 expect(entries?.map((e) => e.url)).toEqual(["http://newer.test/", "http://older.test/"]);
200 expect(entries?.[0]?.lastVisitedAt).toBe(2000);
201 });
202});
203​
204describe("pendingTitlesByThreadKey", () => {
205 beforeEach(() => {
206 resetBrowserHistoryForTests();
207 });
208​
209 it("buffers a title set before registration and applies it once the matching visit drains", () => {
210 recordVisitForThread(threadRef, "http://a.test/", 1);
211 setTitleForThreadUrl(threadRef, "http://a.test/", "My App");
212 expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
213​
214 useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
215​
216 const entries = useBrowserHistoryStore.getState().byProjectKey["proj-a"];
217 expect(entries?.[0]).toMatchObject({ url: "http://a.test/", title: "My App" });
218 expect(useBrowserHistoryStore.getState().pendingTitlesByThreadKey).toEqual({});
219 });
220});
221​
222describe("mergeBrowserHistoryState", () => {
223 it("sanitizes same-version corrupt persisted data and preserves actions", () => {
224 // `migrate` only runs when versions differ; `merge` runs on every rehydrate.
225 const current = useBrowserHistoryStore.getState();
226 const merged = mergeBrowserHistoryState(
227 {
228 byProjectKey: {
229 a: [{ url: "ftp://bad.test/", lastVisitedAt: 1 }],
230 b: [{ url: "http://ok.test/", lastVisitedAt: 5 }],
231 },
232 projectKeyByThreadKey: { good: "b", stale: "a", malformed: 42 },
233 },
234 current,
235 );
236 expect(merged.byProjectKey).toEqual({
237 b: [{ url: "http://ok.test/", lastVisitedAt: 5 }],
238 });
239 expect(typeof merged.recordVisit).toBe("function");
240 expect(merged.projectKeyByThreadKey).toEqual({ good: "b" });
241 expect(merged.pendingVisitsByThreadKey).toEqual({});
242 expect(merged.pendingTitlesByThreadKey).toEqual({});
243 });
244});