v3: api/ gets one layout rule and keeps to it, and whatever crosses the wire is defined once, in shared/ — api/model/interfaces.ts and src/model.ts declared the same 40 types by hand and had drifted: the error envelope, email required on one side and optional on the other, Invitee/InviteTreeEntry and LinkPreview/UrlPreviewResponse for one shape each. The validation limits, the role permissions, the chat length cap, the @mention pattern and the Bandcamp and YouTube player responses were copied too, behind "keep in sync" comments. shared/ now holds them once, one file per domain (api, category, chat, comment, dump, follow, mention, notification, permissions, player, playlist, search, user, validation, ws), and imports nothing from either half. The server sends Dates; the client reads Wire<T>, the same type with every Date an ISO string, and turns it back with src/utils/shared/deserialize.ts. APIErrorCode becomes a const object, since the frontend's erasableSyntaxOnly rejects an enum. The shared types showed two real gaps: the avatar upload and GET /api/users/me return the full self user and the frontend read them as public users, and a stored session may predate media tokens, so the client keeps it as its own Session type. The backend rule: each folder holds one kind of module, each file is named after its domain. routes/ parse and answer; services/ hold the logic and every SQL query (lib/auth.ts's token check moves to user-service); remote/ is the only place that fetches from other sites — the guarded fetch and the HTML scraping out of rich-content-service, public-address, the Bandcamp and YouTube resolvers, the link providers, the image proxy (fetch, checks and cache, out of routes/preview.ts) and the Twemoji glyphs (out of lib/site-icons.ts). model/ holds per table a row type, its guard and its mappers; validators/ the request guards; db/connection.ts the handle and transaction(), db/startup.ts the purges and default admin that db.ts ran on import, called at the same moment. Tests mirror the source one file per module, test/<layer>/<module>.test.ts, with shared/'s under shared/test/ (deno task test runs both); the test that covered the bandcamp and soundcloud providers together is two now, and the backend can() has its own, so 202 tests. deno lint src/ is clean too: window.* becomes globalThis.*, and test bodies and act() callbacks that never awaited lose their async. The README states the rule. No behaviour changes; the catalogues only move their source references.
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 50s
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 50s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -2,7 +2,7 @@ import { describe, expect, test, vi } from "vitest";
|
||||
import { screen } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { CategorySelect } from "../../../components/category/CategorySelect.tsx";
|
||||
import type { Category } from "../../../model.ts";
|
||||
import type { Category } from "../../../../shared/category.ts";
|
||||
import { makeCategory } from "../../fixtures.ts";
|
||||
import { renderWithContexts } from "../../render.tsx";
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
|
||||
import { screen } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { CategorySwitcher } from "../../../components/category/CategorySwitcher.tsx";
|
||||
import type { Category } from "../../../model.ts";
|
||||
import type { Category } from "../../../../shared/category.ts";
|
||||
import { makeCategory } from "../../fixtures.ts";
|
||||
import { currentPath, renderWithContexts } from "../../render.tsx";
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test, vi } from "vitest";
|
||||
import { act, screen, waitFor, within } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { ChatModal } from "../../../components/chat/ChatModal.tsx";
|
||||
import type { AuthResponse, ChatMessage } from "../../../model.ts";
|
||||
import type { ChatMessage } from "../../../../shared/chat.ts";
|
||||
import { calls, fail, route } from "../../fetch.ts";
|
||||
import { makeChatMessage, makeSession, wire } from "../../fixtures.ts";
|
||||
import { renderApp } from "../../render.tsx";
|
||||
@@ -304,7 +304,7 @@ describe("ChatModal: replies, edits, deletes", () => {
|
||||
|
||||
test("moderators can delete anyone's", async () => {
|
||||
await setup([theirs()], {
|
||||
session: makeSession({ id: "mod", role: "moderator" }) as AuthResponse,
|
||||
session: makeSession({ id: "mod", role: "moderator" }),
|
||||
});
|
||||
const t = screen.getByText("anything").closest(
|
||||
".chat-message",
|
||||
|
||||
@@ -3,7 +3,8 @@ import { screen, waitFor, within } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { useState } from "react";
|
||||
import { CommentThread } from "../../../components/comment/CommentThread.tsx";
|
||||
import type { AuthResponse, Comment } from "../../../model.ts";
|
||||
import type { Session } from "../../../utils/auth/storage.ts";
|
||||
import type { Comment } from "../../../../shared/comment.ts";
|
||||
import { calls, fail, route } from "../../fetch.ts";
|
||||
import { makeComment, makeSession, wire } from "../../fixtures.ts";
|
||||
import { renderWithContexts } from "../../render.tsx";
|
||||
@@ -11,7 +12,7 @@ import { renderWithContexts } from "../../render.tsx";
|
||||
const me = makeSession({ id: "me", username: "me" });
|
||||
const mod = makeSession({ id: "mod", username: "mod", role: "moderator" });
|
||||
|
||||
function setup(initial: Comment[], session: AuthResponse | null = me, ws = {}) {
|
||||
function setup(initial: Comment[], session: Session | null = me, ws = {}) {
|
||||
const user = userEvent.setup();
|
||||
function Harness() {
|
||||
const [comments, setComments] = useState(initial);
|
||||
|
||||
@@ -255,7 +255,7 @@ describe("DumpCreateModal: a link", () => {
|
||||
await screen.findByLabelText("Title");
|
||||
});
|
||||
|
||||
test("a link pasted anywhere in the modal lands in the link field", async () => {
|
||||
test("a link pasted anywhere in the modal lands in the link field", () => {
|
||||
previewRoutes();
|
||||
setup();
|
||||
act(() => {
|
||||
@@ -387,7 +387,7 @@ describe("DumpCreateModal: a file", () => {
|
||||
expect(fd.get("title")).toBe("my song-final");
|
||||
expect(fd.get("isPrivate")).toBe("false");
|
||||
expect(fd.get("categoryIds")).toBe("[]");
|
||||
await act(async () =>
|
||||
await act(() =>
|
||||
FakeXHR.last.respond(201, {
|
||||
success: true,
|
||||
data: wire(makeDump({ id: "f" })),
|
||||
|
||||
@@ -226,7 +226,7 @@ describe("image upload", () => {
|
||||
expect(box).toHaveAttribute("aria-busy", "true");
|
||||
fireEvent.keyDown(box, { key: "Enter" });
|
||||
expect(onKeyDown).not.toHaveBeenCalled();
|
||||
await act(async () =>
|
||||
await act(() =>
|
||||
pending.resolve(
|
||||
new Response(JSON.stringify({ success: true, data: { id: "z" } })),
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
|
||||
import { screen } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { FeedTabBar } from "../../../components/feed/FeedTabBar.tsx";
|
||||
import type { Category } from "../../../model.ts";
|
||||
import type { Category } from "../../../../shared/category.ts";
|
||||
import { makeCategory, makeSession } from "../../fixtures.ts";
|
||||
import { currentPath, renderWithContexts } from "../../render.tsx";
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import { useState } from "react";
|
||||
import { AppHeader } from "../../../components/layout/AppHeader.tsx";
|
||||
import { AuthContext } from "../../../contexts/auth/AuthContext.ts";
|
||||
import { defaultWSValue, WSContext } from "../../../contexts/ws/WSContext.ts";
|
||||
import type { AuthResponse } from "../../../model.ts";
|
||||
import type { Session } from "../../../utils/auth/storage.ts";
|
||||
import { makeSession } from "../../fixtures.ts";
|
||||
import { currentPath, renderWithContexts } from "../../render.tsx";
|
||||
|
||||
@@ -64,7 +64,7 @@ describe("AppHeader", () => {
|
||||
|
||||
// Leaving search needs the real history stack (React Router keeps its
|
||||
// index in history.state), so these use a BrowserRouter.
|
||||
function Browser({ session }: { session?: AuthResponse }) {
|
||||
function Browser({ session }: { session?: Session }) {
|
||||
const [authResponse, setAuthResponse] = useState(session ?? null);
|
||||
function Loc() {
|
||||
const l = useLocation();
|
||||
@@ -86,10 +86,10 @@ describe("AppHeader", () => {
|
||||
);
|
||||
}
|
||||
const loc = () => screen.getByTestId("loc").textContent;
|
||||
afterEach(() => window.history.replaceState(null, "", "/"));
|
||||
afterEach(() => globalThis.history.replaceState(null, "", "/"));
|
||||
|
||||
test("several searches, then ✕, return to where search began", async () => {
|
||||
window.history.replaceState(null, "", "/start");
|
||||
globalThis.history.replaceState(null, "", "/start");
|
||||
const user = userEvent.setup();
|
||||
render(<Browser />);
|
||||
await user.click(screen.getByRole("button", { name: "Search" }));
|
||||
@@ -105,7 +105,7 @@ describe("AppHeader", () => {
|
||||
});
|
||||
|
||||
test("Escape on the results page reverts the query instead of leaving", async () => {
|
||||
window.history.replaceState(null, "", "/search?q=cats");
|
||||
globalThis.history.replaceState(null, "", "/search?q=cats");
|
||||
const user = userEvent.setup();
|
||||
render(<Browser />);
|
||||
const bar = screen.getAllByRole("searchbox")[0];
|
||||
@@ -116,7 +116,7 @@ describe("AppHeader", () => {
|
||||
});
|
||||
|
||||
test("✕ on results that opened the session goes home", async () => {
|
||||
window.history.replaceState(null, "", "/search?q=cats");
|
||||
globalThis.history.replaceState(null, "", "/search?q=cats");
|
||||
const user = userEvent.setup();
|
||||
render(<Browser />);
|
||||
await user.click(screen.getByRole("button", { name: "Cancel search" }));
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
|
||||
import { screen } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { UserMenu } from "../../../components/layout/UserMenu.tsx";
|
||||
import { makeUser } from "../../fixtures.ts";
|
||||
import { makeSession } from "../../fixtures.ts";
|
||||
import { currentPath, renderWithContexts } from "../../render.tsx";
|
||||
|
||||
describe("UserMenu", () => {
|
||||
@@ -10,7 +10,7 @@ describe("UserMenu", () => {
|
||||
const user = userEvent.setup();
|
||||
renderWithContexts(
|
||||
<>
|
||||
<UserMenu user={makeUser({ username: "ann" })} />
|
||||
<UserMenu user={makeSession({ username: "ann" }).user} />
|
||||
<p>outside</p>
|
||||
</>,
|
||||
);
|
||||
|
||||
@@ -88,7 +88,7 @@ describe("MediaPlayer", () => {
|
||||
expect(onPlayStateChange).toHaveBeenLastCalledWith(true);
|
||||
});
|
||||
|
||||
test("time, duration, seeking and the end", async () => {
|
||||
test("time, duration, seeking and the end", () => {
|
||||
const onTimeUpdate = vi.fn();
|
||||
const onEnded = vi.fn();
|
||||
const { container } = renderWithContexts(
|
||||
@@ -179,7 +179,7 @@ describe("MediaPlayer", () => {
|
||||
);
|
||||
act(() => seekRef.current!(33));
|
||||
expect(media(container).currentTime).toBe(33);
|
||||
await act(async () => toggleRef.current!());
|
||||
await act(() => toggleRef.current!());
|
||||
expect(screen.getByRole("button", { name: "Pause" })).toBeInTheDocument();
|
||||
unmount();
|
||||
expect(seekRef.current).toBeNull();
|
||||
|
||||
@@ -78,7 +78,7 @@ describe("AuthProvider", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("follows sign-in and sign-out from other tabs", async () => {
|
||||
test("follows sign-in and sign-out from other tabs", () => {
|
||||
route("GET /api/users/me", () => ok(null));
|
||||
const { result } = renderHook(useAuth, { wrapper: authWrapper });
|
||||
expect(result.current.user).toBeNull();
|
||||
@@ -114,7 +114,7 @@ describe("AuthProvider", () => {
|
||||
const { result } = renderHook(useAuth, { wrapper: authWrapper });
|
||||
const second = { ...first, token: makeToken() };
|
||||
act(() => result.current.login(second));
|
||||
await act(async () => pending.resolve(new Response(null, { status: 401 })));
|
||||
await act(() => pending.resolve(new Response(null, { status: 401 })));
|
||||
expect(result.current.token).toBe(second.token);
|
||||
expect(JSON.parse(localStorage.getItem(AUTH_STORAGE_KEY)!).token).toBe(
|
||||
second.token,
|
||||
|
||||
@@ -9,7 +9,7 @@ import { makeSession } from "../../fixtures.ts";
|
||||
import { currentPath, renderApp } from "../../render.tsx";
|
||||
|
||||
describe("ChatProvider", () => {
|
||||
test("opens only for signed-in users", async () => {
|
||||
test("opens only for signed-in users", () => {
|
||||
const guest = renderHook(useChat, {
|
||||
wrapper: ({ children }) => (
|
||||
<AuthProvider>
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
type PlayerItem,
|
||||
PlayerTimeContext,
|
||||
} from "../../../contexts/player/PlayerContext.ts";
|
||||
import type { AuthResponse } from "../../../model.ts";
|
||||
import type { Session } from "../../../utils/auth/storage.ts";
|
||||
import { STREAM_STALE_MS } from "../../../utils/player/streamSources.ts";
|
||||
import { calls, deferred, fail, route } from "../../fetch.ts";
|
||||
import { makeSession } from "../../fixtures.ts";
|
||||
@@ -51,8 +51,8 @@ const albumResponse = (indexes: number[]) => ({
|
||||
})),
|
||||
});
|
||||
|
||||
let setSession: (s: AuthResponse | null) => void = () => {};
|
||||
function wrapperFor(initial: AuthResponse | null) {
|
||||
let setSession: (s: Session | null) => void = () => {};
|
||||
function wrapperFor(initial: Session | null) {
|
||||
return function Wrapper({ children }: { children: ReactNode }) {
|
||||
const [authResponse, setAuthResponse] = useState(initial);
|
||||
setSession = setAuthResponse;
|
||||
@@ -64,7 +64,7 @@ function wrapperFor(initial: AuthResponse | null) {
|
||||
};
|
||||
}
|
||||
|
||||
function setup(session: AuthResponse | null = null) {
|
||||
function setup(session: Session | null = null) {
|
||||
const hook = renderHook(() => ({
|
||||
...useContext(PlayerContext),
|
||||
...useContext(PlayerTimeContext),
|
||||
@@ -355,7 +355,7 @@ describe("expiring streams", () => {
|
||||
act(() => p().play(stream(0)));
|
||||
act(() => p().onError());
|
||||
act(() => p().play(embed(9)));
|
||||
await act(async () =>
|
||||
await act(() =>
|
||||
pending.resolve(
|
||||
new Response(
|
||||
JSON.stringify({ success: true, data: albumResponse([0]) }),
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { useContext } from "react";
|
||||
import { type ReactNode, useContext } from "react";
|
||||
import { AuthProvider } from "../../../contexts/auth/AuthProvider.tsx";
|
||||
import { WSProvider } from "../../../contexts/ws/WSProvider.tsx";
|
||||
import { AvatarOverrideContext } from "../../../contexts/ws/AvatarOverrideContext.ts";
|
||||
|
||||
@@ -97,7 +97,7 @@ export function calls(spec: string): RecordedRequest[] {
|
||||
return requests.filter((r) => r.method === method && pattern.test(r.path));
|
||||
}
|
||||
|
||||
async function readBody(body: BodyInit | null | undefined): Promise<unknown> {
|
||||
function readBody(body: BodyInit | null | undefined): unknown {
|
||||
if (body == null) return undefined;
|
||||
if (typeof body === "string") {
|
||||
try {
|
||||
@@ -128,7 +128,7 @@ async function fetchStub(
|
||||
url,
|
||||
path: url.pathname,
|
||||
headers: new Headers(init.headers),
|
||||
body: await readBody(init.body),
|
||||
body: readBody(init.body),
|
||||
params: {},
|
||||
};
|
||||
requests.push(req);
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import type {
|
||||
AuthResponse,
|
||||
Category,
|
||||
ChatMessage,
|
||||
Comment,
|
||||
Dump,
|
||||
Notification,
|
||||
Playlist,
|
||||
PublicUser,
|
||||
} from "../model.ts";
|
||||
import type { AuthResponse, PublicUser, SelfUser } from "../../shared/user.ts";
|
||||
import type { Session } from "../utils/auth/storage.ts";
|
||||
import type { Category } from "../../shared/category.ts";
|
||||
import type { ChatMessage } from "../../shared/chat.ts";
|
||||
import type { Comment } from "../../shared/comment.ts";
|
||||
import type { Dump } from "../../shared/dump.ts";
|
||||
import type { Notification } from "../../shared/notification.ts";
|
||||
import type { Playlist } from "../../shared/playlist.ts";
|
||||
import { AUTH_STORAGE_KEY } from "../utils/auth/storage.ts";
|
||||
|
||||
let seq = 0;
|
||||
@@ -37,8 +35,9 @@ export function makeUser(over: Partial<PublicUser> = {}): PublicUser {
|
||||
};
|
||||
}
|
||||
|
||||
export function makeSession(over: Partial<PublicUser> = {}): AuthResponse {
|
||||
const user = makeUser(over);
|
||||
export function makeSession(over: Partial<SelfUser> = {}): AuthResponse {
|
||||
const base = makeUser(over);
|
||||
const user = { ...base, email: over.email ?? `${base.username}@x.test` };
|
||||
return {
|
||||
token: makeToken({ sub: user.id }),
|
||||
mediaToken: `media-${user.id}`,
|
||||
@@ -47,7 +46,7 @@ export function makeSession(over: Partial<PublicUser> = {}): AuthResponse {
|
||||
}
|
||||
|
||||
/** Puts a session in storage, where AuthProvider picks it up on mount. */
|
||||
export function storeSession(session: AuthResponse) {
|
||||
export function storeSession(session: Session) {
|
||||
localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(session));
|
||||
}
|
||||
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { afterEach, describe, expect, test, vi } from "vitest";
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { useState } from "react";
|
||||
import { type ReactNode, useState } from "react";
|
||||
import { AuthContext } from "../../../contexts/auth/AuthContext.ts";
|
||||
import type { AuthResponse } from "../../../model.ts";
|
||||
import type { Session } from "../../../utils/auth/storage.ts";
|
||||
import { useAuth, useRequiredAuth } from "../../../hooks/auth/useAuth.ts";
|
||||
import { AUTH_STORAGE_KEY } from "../../../utils/auth/storage.ts";
|
||||
import { calls, route } from "../../fetch.ts";
|
||||
import { makeSession, makeToken, storeSession } from "../../fixtures.ts";
|
||||
|
||||
function wrapperFor(initial: AuthResponse | null) {
|
||||
function wrapperFor(initial: Session | null) {
|
||||
return function Wrapper({ children }: { children: ReactNode }) {
|
||||
const [authResponse, setAuthResponse] = useState(initial);
|
||||
return (
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
WSContext,
|
||||
type WSContextValue,
|
||||
} from "../../../contexts/ws/WSContext.ts";
|
||||
import type { Dump } from "../../../model.ts";
|
||||
import type { Dump } from "../../../../shared/dump.ts";
|
||||
import { useDumpListSync } from "../../../hooks/dump/useDumpListSync.ts";
|
||||
import { makeDump } from "../../fixtures.ts";
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import { useUserDumpFeed } from "../../../hooks/dump/useUserDumpFeed.ts";
|
||||
import { calls, fail, route } from "../../fetch.ts";
|
||||
import { makeDump, makeSession, makeUser, page, wire } from "../../fixtures.ts";
|
||||
import { FakeIntersectionObserver } from "../../setup.ts";
|
||||
import type { Session } from "../../../utils/auth/storage.ts";
|
||||
|
||||
describe("useUserDumpFeed", () => {
|
||||
const ann = makeUser({ username: "ann" });
|
||||
@@ -15,7 +16,7 @@ describe("useUserDumpFeed", () => {
|
||||
) {
|
||||
const session = opts.session ?? null;
|
||||
function Wrapper({ children }: { children: ReactNode }) {
|
||||
const [authResponse, setAuthResponse] = useState(session);
|
||||
const [authResponse, setAuthResponse] = useState<Session | null>(session);
|
||||
return (
|
||||
<MemoryRouter>
|
||||
<AuthContext.Provider value={{ authResponse, setAuthResponse }}>
|
||||
|
||||
@@ -90,7 +90,7 @@ describe("useMentionAutocomplete", () => {
|
||||
const { hook, type } = setup();
|
||||
await type("@al");
|
||||
await type("@alz");
|
||||
await act(async () =>
|
||||
await act(() =>
|
||||
slow.resolve(new Response(JSON.stringify({ success: true, data: users })))
|
||||
);
|
||||
expect(hook.result.current.mentionOpen).toBe(false);
|
||||
|
||||
@@ -6,7 +6,8 @@ import {
|
||||
WSContext,
|
||||
type WSContextValue,
|
||||
} from "../../../contexts/ws/WSContext.ts";
|
||||
import type { Dump, Playlist } from "../../../model.ts";
|
||||
import type { Dump } from "../../../../shared/dump.ts";
|
||||
import type { Playlist } from "../../../../shared/playlist.ts";
|
||||
import { useDumpListSync } from "../../../hooks/dump/useDumpListSync.ts";
|
||||
import { usePositionAwareSync } from "../../../hooks/feed/usePositionAwareSync.ts";
|
||||
import { makeDump, makePlaylist } from "../../fixtures.ts";
|
||||
|
||||
@@ -40,7 +40,7 @@ describe("useYouTubePlaylist", () => {
|
||||
getPlaylistIndex = () => player.index;
|
||||
destroy = player.destroy;
|
||||
}
|
||||
window.YT = { Player };
|
||||
globalThis.window.YT = { Player };
|
||||
return player;
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
WSContext,
|
||||
type WSContextValue,
|
||||
} from "../../../contexts/ws/WSContext.ts";
|
||||
import type { Playlist } from "../../../model.ts";
|
||||
import type { Playlist } from "../../../../shared/playlist.ts";
|
||||
import { usePlaylistListSync } from "../../../hooks/playlist/usePlaylistListSync.ts";
|
||||
import { makePlaylist } from "../../fixtures.ts";
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test } from "vitest";
|
||||
import { screen, waitFor } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { Notifications } from "../../pages/Notifications.tsx";
|
||||
import type { Notification } from "../../model.ts";
|
||||
import type { Notification } from "../../../shared/notification.ts";
|
||||
import { calls, deferred, fail, route } from "../fetch.ts";
|
||||
import { makeNotification, makeSession, page, wire } from "../fixtures.ts";
|
||||
import { renderApp } from "../render.tsx";
|
||||
|
||||
@@ -9,7 +9,8 @@ import {
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { Route } from "react-router";
|
||||
import { PlaylistDetail } from "../../pages/PlaylistDetail.tsx";
|
||||
import type { Dump, Playlist } from "../../model.ts";
|
||||
import type { Dump } from "../../../shared/dump.ts";
|
||||
import type { Playlist } from "../../../shared/playlist.ts";
|
||||
import { calls, fail, route } from "../fetch.ts";
|
||||
import { makeDump, makePlaylist, makeSession, wire } from "../fixtures.ts";
|
||||
import { currentPath, renderApp } from "../render.tsx";
|
||||
|
||||
@@ -2,7 +2,7 @@ import { describe, expect, test, vi } from "vitest";
|
||||
import { screen, waitFor, within } from "@testing-library/react";
|
||||
import { userEvent } from "@testing-library/user-event";
|
||||
import { UserPublicProfile } from "../../pages/UserPublicProfile.tsx";
|
||||
import type { PublicUser } from "../../model.ts";
|
||||
import type { PublicUser } from "../../../shared/user.ts";
|
||||
import { calls, fail, route } from "../fetch.ts";
|
||||
import {
|
||||
makeCategory,
|
||||
|
||||
@@ -4,7 +4,8 @@ import { I18nProvider } from "@lingui/react";
|
||||
import { i18n } from "@lingui/core";
|
||||
import { MemoryRouter, Route, Routes, useLocation } from "react-router";
|
||||
|
||||
import type { AuthResponse, Category } from "../model.ts";
|
||||
import type { Session } from "../utils/auth/storage.ts";
|
||||
import type { Category } from "../../shared/category.ts";
|
||||
import { AuthContext } from "../contexts/auth/AuthContext.ts";
|
||||
import { AuthProvider } from "../contexts/auth/AuthProvider.tsx";
|
||||
import {
|
||||
@@ -92,7 +93,7 @@ function Router(
|
||||
// ── Stubbed contexts ─────────────────────────────────────────────────────────
|
||||
|
||||
export interface StubOptions extends RouterOptions {
|
||||
session?: AuthResponse | null;
|
||||
session?: Session | null;
|
||||
/** Any of the socket's three contexts' fields; each goes to its own. */
|
||||
ws?: Partial<WSContextValue & WSChatContextValue & WSPresenceContextValue>;
|
||||
follows?: Partial<FollowContextValue>;
|
||||
@@ -101,7 +102,7 @@ export interface StubOptions extends RouterOptions {
|
||||
}
|
||||
|
||||
function StubAuth(
|
||||
{ session, children }: { session: AuthResponse | null; children: ReactNode },
|
||||
{ session, children }: { session: Session | null; children: ReactNode },
|
||||
) {
|
||||
const [authResponse, setAuthResponse] = useState(session);
|
||||
return (
|
||||
@@ -192,7 +193,7 @@ export function renderWithContexts(
|
||||
|
||||
export interface AppOptions extends RouterOptions {
|
||||
/** Signed in as this session (stored before mount, as after a login). */
|
||||
session?: AuthResponse | null;
|
||||
session?: Session | null;
|
||||
categories?: Category[];
|
||||
}
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
hasThumbnail,
|
||||
type JournalShape,
|
||||
} from "../../../utils/feed/journalLayout.ts";
|
||||
import type { Dump } from "../../../model.ts";
|
||||
import type { Dump } from "../../../../shared/dump.ts";
|
||||
import { makeDump } from "../../fixtures.ts";
|
||||
|
||||
const HOUR = 3_600_000;
|
||||
|
||||
@@ -5,8 +5,10 @@ import {
|
||||
STREAM_STALE_MS,
|
||||
} from "../../../utils/player/streamSources.ts";
|
||||
import { calls, route } from "../../fetch.ts";
|
||||
import type { PlayerItem } from "../../../contexts/player/PlayerContext.ts";
|
||||
import { playerItemKey } from "../../../contexts/player/PlayerContext.ts";
|
||||
import {
|
||||
type PlayerItem,
|
||||
playerItemKey,
|
||||
} from "../../../contexts/player/PlayerContext.ts";
|
||||
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ import { calls, fail, route } from "../../fetch.ts";
|
||||
describe("extractPeaks", () => {
|
||||
test("decodes once per URL and takes each block's peak", async () => {
|
||||
const data = new Float32Array([0.1, -0.5, 0.2, 0.9, -0.3, 0.4]);
|
||||
const decode = vi.fn(async () => ({ getChannelData: () => data }));
|
||||
const decode = vi.fn(() => Promise.resolve({ getChannelData: () => data }));
|
||||
const close = vi.fn();
|
||||
vi.stubGlobal(
|
||||
"AudioContext",
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { friendlyFetchError } from "../../../utils/shared/api.ts";
|
||||
import {
|
||||
friendlyFetchError,
|
||||
parseAPIResponse,
|
||||
} from "../../../utils/shared/api.ts";
|
||||
|
||||
describe("friendlyFetchError", () => {
|
||||
test("a TypeError is a connection problem", () => {
|
||||
@@ -12,3 +15,19 @@ describe("friendlyFetchError", () => {
|
||||
expect(friendlyFetchError("weird")).toBe("An unexpected error occurred.");
|
||||
});
|
||||
});
|
||||
|
||||
describe("parseAPIResponse", () => {
|
||||
test("accepts either envelope", () => {
|
||||
expect(parseAPIResponse({ success: true, data: 1 })).toEqual({
|
||||
success: true,
|
||||
data: 1,
|
||||
});
|
||||
expect(parseAPIResponse({ success: false, error: { message: "x" } }))
|
||||
.toMatchObject({ success: false });
|
||||
});
|
||||
test("rejects anything else", () => {
|
||||
expect(() => parseAPIResponse(null)).toThrow(/Unexpected/);
|
||||
expect(() => parseAPIResponse({ data: 1 })).toThrow(/Unexpected/);
|
||||
expect(() => parseAPIResponse("ok")).toThrow(/Unexpected/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,24 +7,7 @@ import {
|
||||
deserializeNotification,
|
||||
deserializePlaylistMembership,
|
||||
deserializePlaylistWithDumps,
|
||||
parseAPIResponse,
|
||||
} from "../model.ts";
|
||||
|
||||
describe("parseAPIResponse", () => {
|
||||
test("accepts either envelope", () => {
|
||||
expect(parseAPIResponse({ success: true, data: 1 })).toEqual({
|
||||
success: true,
|
||||
data: 1,
|
||||
});
|
||||
expect(parseAPIResponse({ success: false, error: { message: "x" } }))
|
||||
.toMatchObject({ success: false });
|
||||
});
|
||||
test("rejects anything else", () => {
|
||||
expect(() => parseAPIResponse(null)).toThrow(/Unexpected/);
|
||||
expect(() => parseAPIResponse({ data: 1 })).toThrow(/Unexpected/);
|
||||
expect(() => parseAPIResponse("ok")).toThrow(/Unexpected/);
|
||||
});
|
||||
});
|
||||
} from "../../../utils/shared/deserialize.ts";
|
||||
|
||||
describe("deserializers", () => {
|
||||
const createdAt = "2026-03-01T10:00:00.000Z";
|
||||
@@ -80,7 +63,14 @@ describe("deserializers", () => {
|
||||
test("nested values are revived too", () => {
|
||||
const auth = deserializeAuthResponse({
|
||||
token: "t",
|
||||
user: { id: "u", username: "u", role: "user", createdAt },
|
||||
mediaToken: "m",
|
||||
user: {
|
||||
id: "u",
|
||||
username: "u",
|
||||
role: "user",
|
||||
createdAt,
|
||||
email: "u@x.test",
|
||||
},
|
||||
});
|
||||
expect(auth.user.createdAt).toBeInstanceOf(Date);
|
||||
|
||||
@@ -11,8 +11,9 @@ class FakeAudioContext {
|
||||
constructor() {
|
||||
FakeAudioContext.instances.push(this);
|
||||
}
|
||||
resume = vi.fn(async () => {
|
||||
resume = vi.fn(() => {
|
||||
this.state = "running";
|
||||
return Promise.resolve();
|
||||
});
|
||||
createOscillator() {
|
||||
this.oscillators++;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { IncomingWSMessage } from "../model.ts";
|
||||
import type { Wire } from "../../shared/api.ts";
|
||||
import type { ServerToClientMessage } from "../../shared/ws.ts";
|
||||
import { act } from "@testing-library/react";
|
||||
|
||||
/**
|
||||
@@ -66,7 +67,7 @@ export class FakeWebSocket extends EventTarget {
|
||||
});
|
||||
}
|
||||
|
||||
receive(msg: IncomingWSMessage | Record<string, unknown>) {
|
||||
receive(msg: Wire<ServerToClientMessage> | Record<string, unknown>) {
|
||||
act(() => {
|
||||
this.onmessage?.(
|
||||
new MessageEvent("message", { data: JSON.stringify(msg) }),
|
||||
@@ -87,7 +88,9 @@ export class FakeWebSocket extends EventTarget {
|
||||
|
||||
/** Opens the socket and sends a welcome, as the server does on connect. */
|
||||
welcome(
|
||||
overrides: Partial<Extract<IncomingWSMessage, { type: "welcome" }>> = {},
|
||||
overrides: Partial<
|
||||
Extract<Wire<ServerToClientMessage>, { type: "welcome" }>
|
||||
> = {},
|
||||
) {
|
||||
this.open();
|
||||
this.receive({
|
||||
|
||||
Reference in New Issue
Block a user