videogen/apps/watch/tests/watch.test.ts
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

218 lines
10 KiB
TypeScript

import { mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it, vi } from "vitest";
import config, { isTvBuild } from "../app.config";
import { ApiError, createClient } from "../src/api/client";
import { getResume, startPlayback, storefront, tvCode } from "../src/api/ott";
import { readConfig } from "../src/config";
import { refreshInMs, resumeFrom, shouldSave, StartupTimer } from "../src/player/playback";
import { deviceId, MAX_RECENT, parseChannel, readSession, recentChannels, rememberChannel, writeSession, type KeyValue } from "../src/session/store";
import { move, reachable, START } from "../src/tv/focus-grid";
import { backsToChannels, reachableScreens, SCREENS } from "../src/tv/routes";
import { pollOnce } from "../src/tv/signin";
// @ts-expect-error - plain ESM script without types
import { check, classify } from "../scripts/licence-check.mjs";
const ROOT = join(__dirname, "..");
function memoryKv(): KeyValue & { data: Map<string, string> } {
const data = new Map<string, string>();
return {
data,
getItemAsync: async (k) => data.get(k) ?? null,
setItemAsync: async (k, v) => void data.set(k, v),
deleteItemAsync: async (k) => void data.delete(k),
};
}
function fetchStub(routes: Record<string, { status: number; body: unknown }>) {
const calls: { url: string; init?: RequestInit }[] = [];
const fn = vi.fn(async (url: string, init?: RequestInit) => {
calls.push({ url, init });
const hit = Object.entries(routes).find(([suffix]) => url.endsWith(suffix));
const { status, body } = hit ? hit[1] : { status: 404, body: {} };
return { ok: status < 400, status, json: async () => body } as Response;
});
return { fn, calls };
}
describe("app config", () => {
it("builds phone and TV targets from one project", () => {
const phone = config({ config: {} } as never, {});
const tv = config({ config: {} } as never, { EXPO_TV: "1", EXPO_PUBLIC_API_BASE: "https://api.example/api/v1" });
const names = (c: typeof phone) => (c.plugins ?? []).map((p) => (Array.isArray(p) ? p[0] : p));
expect(names(phone)).toContain("react-native-google-cast");
expect(names(phone)).not.toContain("@react-native-tvos/config-tv");
expect(names(tv)).toContain("@react-native-tvos/config-tv");
expect(tv.orientation).toBe("landscape");
expect(tv.extra?.tv).toBe(true);
expect(readConfig(tv.extra as Record<string, unknown>).apiBase).toBe("https://api.example/api/v1");
expect(isTvBuild({})).toBe(false);
expect(phone.ios?.bundleIdentifier).toBe("com.arhansuba.menivor.watch");
});
it("uses react-native-tvos, and no GPL package is declared", () => {
const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"));
expect(pkg.dependencies["react-native"]).toMatch(/^npm:react-native-tvos@/);
expect(pkg.dependencies["expo-video"]).toBeTruthy();
});
});
describe("API client", () => {
it("sends the viewer session in a header and reads the envelope", async () => {
const { fn, calls } = fetchStub({ "/ott/c/maya": { status: 200, body: { status: 200, data: { handle: "maya", titles: [] } } },
"/ott/play/t1": { status: 402, body: { status: 402, message: "This title is for members of the channel.", data: { code: "members_only" } } } });
const api = createClient("https://api.example/api/v1/", fn);
expect((await storefront(api, "maya")).handle).toBe("maya");
await expect(startPlayback(api, "t1", "dev1", "vs-1")).rejects.toMatchObject({ status: 402, code: "members_only",
message: "This title is for members of the channel." });
expect((calls[1]?.init?.headers as Record<string, string>)["X-OTT-Viewer"]).toBe("vs-1");
expect(calls[1]?.url).toBe("https://api.example/api/v1/ott/play/t1");
});
it("says no connection in plain words", async () => {
const api = createClient("https://api.example", async () => { throw new TypeError("network"); });
await expect(getResume(api, "maya", "vs", "t1")).rejects.toBeInstanceOf(ApiError);
});
});
describe("sessions and channels", () => {
it("keeps one session per channel and forgets expired ones", async () => {
const kv = memoryKv();
await writeSession(kv, "maya", "vs-1", Date.now() / 1000 + 60);
expect(await readSession(kv, "maya")).toBe("vs-1");
expect(await readSession(kv, "zed")).toBeNull();
await writeSession(kv, "old", "vs-0", Date.now() / 1000 - 1);
expect(await readSession(kv, "old")).toBeNull();
});
it("remembers recent channels and parses links", async () => {
const kv = memoryKv();
for (let i = 0; i < MAX_RECENT + 2; i += 1) await rememberChannel(kv, `ch-${i}`);
await rememberChannel(kv, "ch-3");
const list = await recentChannels(kv);
expect(list[0]).toBe("ch-3");
expect(list).toHaveLength(MAX_RECENT);
expect(parseChannel(" https://menivor.com/c/Maya-Films ")).toBe("maya-films");
expect(parseChannel("menivor-watch://c/zed-tv")).toBe("zed-tv");
expect(parseChannel("no spaces allowed")).toBeNull();
expect(await deviceId(kv, () => "a")).toBe("a");
expect(await deviceId(kv, () => "b")).toBe("a");
});
});
describe("remote navigation", () => {
it("reaches every tile of uneven rails with the arrows", () => {
const rows = [5, 0, 2, 7];
const seen = reachable(rows);
expect(seen.size).toBe(5 + 2 + 7);
let state = move(rows, START, "right");
state = move(rows, state, "right");
state = move(rows, state, "down");
expect([state.row, state.col]).toEqual([2, 1]);
state = move(rows, state, "up");
expect([state.row, state.col]).toEqual([0, 2]);
});
it("reaches every screen from the channel list and backs out to it", () => {
expect([...reachableScreens()].sort()).toEqual(["channels", "home", "sign-in", "title"]);
for (const screen of Object.keys(SCREENS) as (keyof typeof SCREENS)[]) {
expect(backsToChannels(screen)).not.toBeNull();
expect(SCREENS[screen].preferredFocus).toBeTruthy();
}
});
it("every screen gives the remote a first focus", () => {
const files = ["app/index.tsx", "app/c/[handle]/index.tsx", "app/c/[handle]/sign-in.tsx", "src/player/WatchPlayer.tsx"];
for (const file of files) expect(readFileSync(join(ROOT, file), "utf8")).toMatch(/hasTVPreferredFocus|preferred=/);
});
});
describe("playback timing", () => {
it("refreshes the grant a minute early and resumes where the viewer stopped", () => {
expect(refreshInMs(1_000_600, 1_000_000_000)).toBe(540_000);
expect(refreshInMs(10, 1_000_000_000)).toBe(0);
expect(resumeFrom({ position_s: 312, finished: false })).toBe(312);
expect(resumeFrom({ position_s: 590, finished: true })).toBe(0);
expect(shouldSave(null, 5, 100)).toBe(true);
expect(shouldSave(100, 20, 105)).toBe(false);
expect(shouldSave(100, 20, 110)).toBe(true);
});
it("measures press to first frame against the 3 s target", () => {
let now = 1000;
const timer = new StartupTimer(() => now);
expect(timer.withinTarget()).toBeNull();
timer.press();
now = 3400;
expect(timer.firstFrame()).toBe(2400);
now = 9000;
expect(timer.firstFrame()).toBe(2400);
expect(timer.withinTarget()).toBe(true);
});
});
describe("TV sign-in", () => {
it("waits, then keeps the session the phone approved", async () => {
const code = { user_code: "K7M-4QX", device_token: "d".repeat(40), expires_in: 600, interval: 5 };
const pending = createClient("https://api.example", fetchStub({ "/tv-codes/poll": { status: 428, body: { message: "Waiting for your phone." } } }).fn);
expect(await pollOnce(pending, "maya", code)).toBeNull();
const done = createClient("https://api.example", fetchStub({ "/tv-codes/poll": { status: 200, body: { data: { session: "vs-tv", expires_at: 1, viewer: { id: "v", display_name: "ana" } } } } }).fn);
expect(await pollOnce(done, "maya", code)).toMatchObject({ step: "done", session: { session: "vs-tv" } });
const gone = createClient("https://api.example", fetchStub({ "/tv-codes/poll": { status: 410, body: {} } }).fn);
expect(await pollOnce(gone, "maya", code)).toEqual({ step: "expired" });
const start = createClient("https://api.example", fetchStub({ "/tv-codes": { status: 200, body: { data: code } } }).fn);
expect((await tvCode(start, "maya")).user_code).toBe("K7M-4QX");
});
});
describe("licence check", () => {
it("classifies licence expressions", () => {
expect(classify("MIT")).toBe("ok");
expect(classify("(MIT OR GPL-3.0)")).toBe("ok");
expect(classify("GPL-3.0-only")).toBe("copyleft");
expect(classify("LGPL-2.1")).toBe("copyleft");
expect(classify("AGPL-3.0-or-later")).toBe("copyleft");
expect(classify("")).toBe("unknown");
});
it("fails a tree that ships a GPL package", () => {
const dir = mkdtempSync(join(tmpdir(), "watch-lic-"));
const add = (path: string, licence: unknown) => {
mkdirSync(join(dir, path), { recursive: true });
writeFileSync(join(dir, path, "package.json"), JSON.stringify({ name: path.split("/node_modules/").pop(), version: "1.0.0", license: licence }));
};
add("expo-video", "MIT");
add("@scope/tool", "Apache-2.0");
add("expo-video/node_modules/nested-gpl", "GPL-3.0");
add("odd", undefined);
const result = check(dir);
expect(result.count).toBe(4);
expect(result.copyleft.map((p: { name: string }) => p.name)).toEqual(["nested-gpl"]);
expect(result.unknown.map((p: { name: string }) => p.name)).toEqual(["odd"]);
});
});
describe("copy", () => {
it("has no emoji and no competitor or tool names in the app", () => {
const files: string[] = [];
const walk = (dir: string) => {
for (const name of readdirSync(dir)) {
const full = join(dir, name);
if (statSync(full).isDirectory()) walk(full);
else if (/\.(tsx?|json)$/.test(name)) files.push(full);
}
};
walk(join(ROOT, "app"));
walk(join(ROOT, "src"));
const emoji = /[\u{1F300}-\u{1FAFF}\u{2600}-\u{27BF}\u{1F000}-\u{1F2FF}]/u;
const names = /\b(netflix|youtube|muvi|higgsfield|vimeo|uscreen|kling|sora|runway|indie)\b/i;
for (const file of files) {
const text = readFileSync(file, "utf8");
expect(emoji.test(text), file).toBe(false);
expect(names.test(text), file).toBe(false);
}
});
});