Merge pull request #4567 from rommapp/claude/v2-spa-launch-view

feat(v2): open the EmulatorJS and js-dos launch views without a page load
This commit is contained in:
Zurdi
2026-09-17 13:49:01 +02:00
committed by GitHub
23 changed files with 1156 additions and 185 deletions

View File

@@ -18,6 +18,7 @@ map $http_x_forwarded_proto $forwardscheme {
# EmulatorJS and js-dos player paths, to enable SharedArrayBuffer support, which
# is needed for multi-threaded cores. Not $uri: try_files rewrites it to
# /index.html before add_header runs, so the query string is matched explicitly.
# The dev server mirrors these entries in frontend/scripts/playerIsolationHeaders.ts.
map $request_uri $coep_header {
default "";
~^/rom/.*/(ejs|jsdos)(\?|$) "require-corp";

View File

@@ -862,6 +862,19 @@ All synthesized with sine/noise blend, exponential envelopes, low-pass filter, a
- Fullscreen support
- Background color customization
### Cross-origin isolation (v2 players)
Threaded EmulatorJS cores need `SharedArrayBuffer`, which browsers expose only in a cross-origin isolated document. Nginx attaches `Cross-Origin-Opener-Policy: same-origin` and `Cross-Origin-Embedder-Policy: require-corp` to the player URLs alone (`docker/nginx/templates/default.conf.template`), because under that policy the rest of the app cannot embed third-party images (provider covers in Match ROM).
A v2 player view is reached by SPA navigation, so it is not isolated on arrival. Two composables cover that:
- `useIsolatedLaunch(player, romId, isIntent)` reloads the view into an isolated document when a launch needs it. The view defines the `Intent` the reload cannot carry in the URL, calls `relaunch(intent)` when `hasSharedArrayBuffer()` is false, and boots from `intent` on mount. `relaunch()` returns false, and the view reports the context instead, when the reload would not help: outside a secure context (the headers alone never expose `SharedArrayBuffer`), where storage refused to keep the selection, or from a view that already came from such a reload.
- `usePlayerExit(runtimeBound)` leaves the view by a full navigation when the document is isolated, or when the player's runtime cannot be injected twice (EmulatorJS declares top-level classes), so the app resumes in a fresh document. Otherwise leaving is an SPA navigation. `guard` is the `onBeforeRouteLeave` form, `leave(path)` the programmatic one, and `departing` tells an unload prompt that this exit is the view's own.
To add an EmulatorJS core that needs threads, add it to `areThreadsRequiredForEJSCore` in `utils/index.ts`; nothing else changes. To add a player that needs isolation, use both composables the way `v2/views/Player/EmulatorJS.vue` does, and track `runtimeBound` from the moment the runtime is injected rather than from the global it eventually defines. A player whose runtime needs no `SharedArrayBuffer` (js-dos) only needs `usePlayerExit()`.
The dev server has no nginx in front of it, so `scripts/playerIsolationHeaders.ts` answers the same URLs with the same headers. It is one entry per entry of the nginx map, and the two are meant to be edited together.
### Platform Detection
`utils/index.ts` provides:

View File

@@ -0,0 +1,36 @@
/**
* playerIsolationHeaders: the dev server's twin of the nginx COOP/COEP map.
*
* Threaded EmulatorJS cores need SharedArrayBuffer, which only a cross-origin
* isolated document exposes, and only the player URLs may be isolated, since
* the rest of the app embeds third-party images that COEP would block.
*/
import type { Plugin } from "vite";
// One entry per entry of the map in docker/nginx/templates/default.conf.template,
// matched against the request URI as it is there, since try_files rewrites the
// path to /index.html before nginx reaches the headers.
export const ISOLATED_PLAYER_URLS = [
/^\/rom\/.*\/(ejs|jsdos)(\?|$)/,
/^\/console\/rom\/[0-9]+\/play/,
];
/** Whether a request URI addresses a player document that must be isolated. */
export function isIsolatedPlayerUrl(url: string): boolean {
return ISOLATED_PLAYER_URLS.some((pattern) => pattern.test(url));
}
export function playerIsolationHeaders(): Plugin {
return {
name: "romm:player-isolation-headers",
configureServer(server) {
server.middlewares.use((req, res, next) => {
if (isIsolatedPlayerUrl(req.url ?? "")) {
res.setHeader("Cross-Origin-Embedder-Policy", "require-corp");
res.setHeader("Cross-Origin-Opener-Policy", "same-origin");
}
next();
});
},
};
}

View File

@@ -602,7 +602,9 @@ export function getSupportedEJSCores(
}
/**
* Check if a given EJS core requires threads enabled.
* Whether an EJS core ships only as a threaded build; a core added here gets
* the cross-origin isolated document it needs from the v2 launch view (see
* `useIsolatedLaunch`).
*
* @param core The core name.
* @returns True if threads are required, false otherwise.

View File

@@ -354,7 +354,8 @@ function clearAllStatus() {
}
// Modified and non-primary clicks on a launch anchor stay with the browser
// (new tab); plain ones still go through `play()` for its full-document load.
// (new tab); plain ones still go through `play()` for its confirmation and
// cover morph.
function onClick(e: MouseEvent) {
if (props.action === "more" || props.action === "status") return;
if (linkHref.value && (e.button !== 0 || opensInNewContext(e))) return;

View File

@@ -18,6 +18,8 @@ export function useActivityPresence(
start: () => void;
stopHeartbeat: () => void;
emitStop: () => void;
/** End the session: stop beating and announce it, in that order. */
stop: () => void;
} {
const auth = storeAuth();
@@ -38,18 +40,29 @@ export function useActivityPresence(
immediate: false,
});
// A stop is addressed to the device, not to a rom, so one sent without a
// session would clear whatever else that device is playing.
let started = false;
function start(): void {
const romId = getRomId();
if (!auth.user || romId == null) return;
if (!socket.connected) socket.connect();
socket.emit("activity:start", { rom_id: romId, device_id: deviceId() });
started = true;
resume();
}
function emitStop(): void {
if (!auth.user) return;
if (!auth.user || !started) return;
started = false;
socket.emit("activity:stop", { device_id: deviceId() });
}
return { start, stopHeartbeat: pause, emitStop };
function stop(): void {
pause();
emitStop();
}
return { start, stopHeartbeat: pause, emitStop, stop };
}

View File

@@ -1,19 +1,10 @@
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActionKey } from "@/__generated__";
import type { SimpleRom } from "@/stores/roms";
import { useGameActions } from "./index";
// Controllable stubs shared with the mocked modules below.
const push = vi.fn();
const locationAssign = vi.fn();
const confirmFn = vi.fn();
const startScan = vi.fn(() => true);
const snackbarInfo = vi.fn();
@@ -26,7 +17,6 @@ const streamContainer = { value: null as object | null };
const joinableSession = {
value: null as { host_username: string | null } | null,
};
let originalLocation: Location;
// Granted action keys — `null` means "everything" (the default).
const grantedActions: { value: Set<ActionKey> | null } = { value: null };
@@ -134,24 +124,8 @@ function makeRom(status: SimpleRom["rom_user"]["status"] = null): SimpleRom {
} as unknown as SimpleRom;
}
beforeAll(() => {
originalLocation = window.location;
Object.defineProperty(window, "location", {
configurable: true,
value: { ...originalLocation, assign: locationAssign },
});
});
afterAll(() => {
Object.defineProperty(window, "location", {
configurable: true,
value: originalLocation,
});
});
beforeEach(() => {
push.mockClear();
locationAssign.mockClear();
confirmFn.mockClear();
startScan.mockClear();
snackbarInfo.mockClear();
@@ -259,8 +233,7 @@ describe("useGameActions.play — launch confirmation", () => {
const actions = useGameActions(() => makeRom(null));
await actions.play();
expect(confirmFn).not.toHaveBeenCalled();
expect(locationAssign).toHaveBeenCalledWith("/rom/1/ejs");
expect(push).not.toHaveBeenCalled();
expect(push).toHaveBeenCalledWith("/rom/1/ejs");
});
it.each(["retired", "never_playing"] as const)(
@@ -270,7 +243,6 @@ describe("useGameActions.play — launch confirmation", () => {
const actions = useGameActions(() => makeRom(status));
await actions.play();
expect(confirmFn).toHaveBeenCalledTimes(1);
expect(locationAssign).not.toHaveBeenCalled();
expect(push).not.toHaveBeenCalled();
},
);
@@ -280,8 +252,7 @@ describe("useGameActions.play — launch confirmation", () => {
const actions = useGameActions(() => makeRom("retired"));
await actions.play();
expect(confirmFn).toHaveBeenCalledTimes(1);
expect(locationAssign).toHaveBeenCalledWith("/rom/1/ejs");
expect(push).not.toHaveBeenCalled();
expect(push).toHaveBeenCalledWith("/rom/1/ejs");
});
it("skips the prompt when the preference is disabled", async () => {
@@ -289,8 +260,7 @@ describe("useGameActions.play — launch confirmation", () => {
const actions = useGameActions(() => makeRom("never_playing"));
await actions.play();
expect(confirmFn).not.toHaveBeenCalled();
expect(locationAssign).toHaveBeenCalledWith("/rom/1/ejs");
expect(push).not.toHaveBeenCalled();
expect(push).toHaveBeenCalledWith("/rom/1/ejs");
});
it("prefers streaming over EmulatorJS", async () => {
@@ -300,7 +270,6 @@ describe("useGameActions.play — launch confirmation", () => {
await actions.play();
expect(push).toHaveBeenCalledWith("/rom/1/stream");
expect(locationAssign).not.toHaveBeenCalled();
});
it("goes to EmulatorJS when asked for the local player, stream or not", async () => {
@@ -311,8 +280,7 @@ describe("useGameActions.play — launch confirmation", () => {
await actions.play("local");
expect(locationAssign).toHaveBeenCalledWith("/rom/1/ejs");
expect(push).not.toHaveBeenCalled();
expect(push).toHaveBeenCalledWith("/rom/1/ejs");
});
it("goes to the stream when asked for it", async () => {
@@ -322,7 +290,6 @@ describe("useGameActions.play — launch confirmation", () => {
await actions.play("stream");
expect(push).toHaveBeenCalledWith("/rom/1/stream");
expect(locationAssign).not.toHaveBeenCalled();
});
it("launches nothing when the asked-for player cannot run it", async () => {
@@ -331,7 +298,6 @@ describe("useGameActions.play — launch confirmation", () => {
await actions.play("stream");
expect(push).not.toHaveBeenCalled();
expect(locationAssign).not.toHaveBeenCalled();
});
it("still confirms a shelved game whichever player is asked for", async () => {
@@ -345,7 +311,7 @@ describe("useGameActions.play — launch confirmation", () => {
expect(push).not.toHaveBeenCalled();
});
it("keeps SPA navigation for Ruffle", async () => {
it("goes to Ruffle for a Flash rom", async () => {
canPlayEJS.value = false;
canPlayRuffle.value = true;
const actions = useGameActions(() => makeRom());
@@ -353,10 +319,9 @@ describe("useGameActions.play — launch confirmation", () => {
await actions.play();
expect(push).toHaveBeenCalledWith("/rom/1/ruffle");
expect(locationAssign).not.toHaveBeenCalled();
});
it("keeps SPA navigation for PICO-8", async () => {
it("goes to PICO-8 for a cartridge", async () => {
canPlayEJS.value = false;
canPlayPico8.value = true;
const actions = useGameActions(() => makeRom());
@@ -364,17 +329,15 @@ describe("useGameActions.play — launch confirmation", () => {
await actions.play();
expect(push).toHaveBeenCalledWith("/rom/1/pico8");
expect(locationAssign).not.toHaveBeenCalled();
});
it("full-loads js-dos ahead of EmulatorJS for its platforms", async () => {
it("prefers js-dos over EmulatorJS for its platforms", async () => {
canPlayJsDos.value = true;
const actions = useGameActions(() => makeRom());
await actions.play();
expect(locationAssign).toHaveBeenCalledWith("/rom/1/jsdos");
expect(push).not.toHaveBeenCalled();
expect(push).toHaveBeenCalledWith("/rom/1/jsdos");
});
it("offers neither streaming nor download without a file behind the rom", () => {

View File

@@ -49,11 +49,6 @@ export type PlayTarget = "auto" | "local" | "stream";
type PlayerSlug = "stream" | "jsdos" | "ejs" | "pico8" | "ruffle";
// EmulatorJS and js-dos need SharedArrayBuffer. Nginx only attaches the
// necessary COOP/COEP headers to the player document, so an SPA navigation
// cannot enable cross-origin isolation: these load the document directly.
const ISOLATED_PLAYERS: ReadonlySet<PlayerSlug> = new Set(["jsdos", "ejs"]);
// Validate flashpoint game IDs are UUIDs
const FLASHPOINT_ID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
@@ -327,25 +322,20 @@ export function useGameActions(
if (!ok) return;
}
const launch = launchTarget(player);
if (!launch) return;
const target = launch.path;
if (ISOLATED_PLAYERS.has(launch.player)) {
window.location.assign(target);
return;
}
const target = playPath(player);
if (!target) return;
// The launch "load" flourish (disc/cartridge insert) lives on the
// player view itself — see EmulatorJS's onPlay — so navigation is
// player view itself (see EmulatorJS's onPlay), so navigation is
// immediate here. When the caller supplies a cover element (the gallery
// card / detail hero), morph it into the player's hero cover — same
// card / detail hero), morph it into the player's hero cover: the same
// `rom-cover-<id>` tag the player paints statically. Degrades to a plain
// push where view transitions aren't available.
const el = options.coverEl?.();
if (el) {
// Await the push inside the transition so the browser snapshots the
// player view *after* it has rendered its hero cover (which carries the
// same `rom-cover-<id>` tag) — otherwise there's no element to morph to.
// same `rom-cover-<id>` tag); otherwise there's no element to morph to.
morphTransition({ el, name: `rom-cover-${rom.id}` }, async () => {
await router.push(target);
});
@@ -359,9 +349,8 @@ export function useGameActions(
// container's own emulator and save library). The caller says which it
// wants; "auto" keeps the single-button surfaces working by preferring
// the stream, as they did before either could be asked for by name.
function launchTarget(
player: PlayTarget,
): { player: PlayerSlug; path: string } | null {
/** Path `play(player)` opens; surfaces rendering the launch as a link point at it too. */
function playPath(player: PlayTarget = "auto"): string | null {
const rom = getRom();
if (!rom) return null;
let slug: PlayerSlug | null = null;
@@ -371,12 +360,7 @@ export function useGameActions(
else if (canPlayEJS.value) slug = "ejs";
else if (canPlayPico8.value) slug = "pico8";
else if (canPlayRuffle.value) slug = "ruffle";
return slug ? { player: slug, path: `/rom/${rom.id}/${slug}` } : null;
}
/** Path `play(player)` would open, for surfaces that render the launch as a link. */
function playPath(player: PlayTarget = "auto"): string | null {
return launchTarget(player)?.path ?? null;
return slug ? `/rom/${rom.id}/${slug}` : null;
}
// Joining is its own navigation: the stream view claims a container when it

View File

@@ -0,0 +1,161 @@
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
import { useIsolatedLaunch } from "./index";
interface Intent {
saveId: number | null;
}
function isIntent(value: unknown): value is Intent {
return (
typeof value === "object" &&
value !== null &&
"saveId" in value &&
(value.saveId === null || typeof value.saveId === "number")
);
}
const KEY = "player:7:ejs:launch";
const reload = vi.fn();
let originalLocation: Location;
const realStorage = window.sessionStorage;
/** Stand in for a browser that denies storage access outright. */
function blockStorage() {
const denied = () => {
throw new Error("storage is blocked");
};
Object.defineProperty(window, "sessionStorage", {
configurable: true,
value: { getItem: denied, setItem: denied, removeItem: denied },
});
}
function launch() {
return useIsolatedLaunch<Intent>("ejs", 7, isIntent);
}
function setSecureContext(secure: boolean) {
Object.defineProperty(window, "isSecureContext", {
configurable: true,
value: secure,
});
}
beforeAll(() => {
originalLocation = window.location;
Object.defineProperty(window, "location", {
configurable: true,
value: { ...originalLocation, reload },
});
});
afterAll(() => {
Object.defineProperty(window, "location", {
configurable: true,
value: originalLocation,
});
});
beforeEach(() => {
reload.mockClear();
Object.defineProperty(window, "sessionStorage", {
configurable: true,
value: realStorage,
});
sessionStorage.clear();
setSecureContext(true);
});
describe("useIsolatedLaunch", () => {
it("opens without an intent", () => {
const first = launch();
expect(first.intent).toBeNull();
expect(first.relaunching.value).toBe(false);
});
it("keeps the intent and reloads the document", () => {
const first = launch();
expect(first.relaunch({ saveId: 3 })).toBe(true);
expect(first.relaunching.value).toBe(true);
expect(reload).toHaveBeenCalledOnce();
expect(sessionStorage.getItem(KEY)).toBe('{"saveId":3}');
});
it("hands the intent to the reloaded view once", () => {
launch().relaunch({ saveId: 3 });
expect(launch().intent).toEqual({ saveId: 3 });
expect(launch().intent).toBeNull();
});
// A second reload could not isolate the document either, so the view is
// told to report the context instead of looping.
it("refuses to reload again from the reloaded view", () => {
launch().relaunch({ saveId: 3 });
reload.mockClear();
const reloaded = launch();
expect(reloaded.relaunch({ saveId: 4 })).toBe(false);
expect(reload).not.toHaveBeenCalled();
expect(reloaded.relaunching.value).toBe(false);
});
// The headers cannot expose SharedArrayBuffer over plain HTTP, so the round
// trip would only delay the same error.
it("refuses to reload outside a secure context", () => {
setSecureContext(false);
const first = launch();
expect(first.relaunch({ saveId: 3 })).toBe(false);
expect(reload).not.toHaveBeenCalled();
expect(sessionStorage.getItem(KEY)).toBeNull();
});
it("refuses to reload when the selection cannot be kept", () => {
const first = launch();
blockStorage();
expect(first.relaunch({ saveId: 3 })).toBe(false);
expect(reload).not.toHaveBeenCalled();
expect(first.relaunching.value).toBe(false);
});
// A player has to open even where storage access is denied outright.
it("opens with no intent when storage cannot be read", () => {
blockStorage();
expect(launch().intent).toBeNull();
});
it("keeps players and games apart", () => {
launch().relaunch({ saveId: 3 });
expect(useIsolatedLaunch<Intent>("jsdos", 7, isIntent).intent).toBeNull();
expect(useIsolatedLaunch<Intent>("ejs", 8, isIntent).intent).toBeNull();
expect(launch().intent).toEqual({ saveId: 3 });
});
it.each([
["not JSON", "{"],
["another shape", JSON.stringify({ core: "snes9x" })],
])("drops a stored value that is %s", (_label, raw) => {
sessionStorage.setItem(KEY, raw);
expect(launch().intent).toBeNull();
expect(sessionStorage.getItem(KEY)).toBeNull();
});
});

View File

@@ -0,0 +1,80 @@
// useIsolatedLaunch: reloading a player view into a cross-origin isolated
// document, which is the only kind that exposes SharedArrayBuffer. Nginx
// attaches the COOP/COEP headers to the player URLs, so reloading the view is
// what isolates it, and the pre-play selection crosses as an intent kept per
// tab.
//
// In a player whose runtime, or one of its cores, needs it:
// const { intent, relaunching, relaunch } =
// useIsolatedLaunch<MyIntent>("myplayer", romId, isMyIntent);
// on Play: if (!hasSharedArrayBuffer()) {
// if (!relaunch(currentIntent())) reportInsecureContext();
// return;
// }
// on mount: if (intent) { apply(intent); boot(); }
// Pair it with usePlayerExit, which drops the isolation on the way out.
import { ref, type Ref } from "vue";
export function hasSharedArrayBuffer(): boolean {
return typeof window.SharedArrayBuffer === "function";
}
export function useIsolatedLaunch<Intent>(
player: string,
romId: number,
isIntent: (value: unknown) => value is Intent,
): {
/** What the view stored before reloading, or null when it opened normally. */
intent: Intent | null;
/** True once a reload is under way, so the Play control stays busy. */
relaunching: Ref<boolean>;
/**
* Keep `intent` and reload into the isolated document. False when the reload
* would not help: the context is not secure (the headers alone never expose
* SharedArrayBuffer), the selection could not be kept, or this view already
* came from such a reload. The caller reports the context instead.
*/
relaunch: (intent: Intent) => boolean;
} {
const key = `player:${romId}:${player}:launch`;
const intent = takeIntent(key, isIntent);
const relaunching = ref(false);
function relaunch(next: Intent): boolean {
if (intent !== null || !window.isSecureContext) return false;
if (!keepIntent(key, next)) return false;
relaunching.value = true;
window.location.reload();
return true;
}
return { intent, relaunching, relaunch };
}
// Storage access can be denied outright, and a player has to open and run
// regardless, so both sides treat that as "no intent".
function keepIntent(key: string, intent: unknown): boolean {
try {
sessionStorage.setItem(key, JSON.stringify(intent));
return true;
} catch {
return false;
}
}
/** The intent under `key`, cleared on read so it boots only once. */
function takeIntent<Intent>(
key: string,
isIntent: (value: unknown) => value is Intent,
): Intent | null {
try {
const raw = sessionStorage.getItem(key);
if (raw === null) return null;
sessionStorage.removeItem(key);
const parsed: unknown = JSON.parse(raw);
return isIntent(parsed) ? parsed : null;
} catch {
return null;
}
}

View File

@@ -0,0 +1,113 @@
import {
afterAll,
afterEach,
beforeAll,
describe,
expect,
it,
vi,
} from "vitest";
import { usePlayerExit } from "./index";
const push = vi.fn();
const locationReplace = vi.fn();
let originalLocation: Location;
vi.mock("vue-router", () => ({
useRouter: () => ({ push }),
}));
function setIsolated(isolated: boolean) {
Object.defineProperty(window, "crossOriginIsolated", {
configurable: true,
value: isolated,
});
}
beforeAll(() => {
originalLocation = window.location;
Object.defineProperty(window, "location", {
configurable: true,
value: { ...originalLocation, replace: locationReplace },
});
});
afterAll(() => {
Object.defineProperty(window, "location", {
configurable: true,
value: originalLocation,
});
});
afterEach(() => {
push.mockClear();
locationReplace.mockClear();
setIsolated(false);
});
describe("usePlayerExit", () => {
it("leaves within the app when nothing binds the document", () => {
const exit = usePlayerExit();
exit.leave("/rom/1");
expect(push).toHaveBeenCalledWith("/rom/1");
expect(locationReplace).not.toHaveBeenCalled();
expect(exit.departing.value).toBe(false);
});
it("replaces the document when it is cross-origin isolated", () => {
setIsolated(true);
const exit = usePlayerExit();
exit.leave("/rom/1");
expect(locationReplace).toHaveBeenCalledWith("/rom/1");
expect(push).not.toHaveBeenCalled();
});
it("replaces the document once a runtime is bound to it", () => {
const exit = usePlayerExit(() => true);
exit.leave("/rom/1");
expect(locationReplace).toHaveBeenCalledWith("/rom/1");
expect(push).not.toHaveBeenCalled();
});
it("lets a route departure through when nothing binds the document", () => {
const exit = usePlayerExit();
expect(exit.guard({ fullPath: "/platform/2" })).toBe(true);
expect(locationReplace).not.toHaveBeenCalled();
});
it("turns a route departure into a full navigation when bound", () => {
setIsolated(true);
const exit = usePlayerExit();
expect(exit.guard({ fullPath: "/platform/2" })).toBe(false);
expect(locationReplace).toHaveBeenCalledWith("/platform/2");
});
// The view arms an unload prompt while a game is up, and the exit it asked
// for must not be what triggers it.
it.each([
[
"an exit",
(exit: ReturnType<typeof usePlayerExit>) => exit.leave("/rom/1"),
],
[
"a route departure",
(exit: ReturnType<typeof usePlayerExit>) =>
exit.guard({ fullPath: "/rom/1" }),
],
])("announces %s that replaces the document", (_label, act) => {
setIsolated(true);
const exit = usePlayerExit();
act(exit);
expect(exit.departing.value).toBe(true);
});
});

View File

@@ -0,0 +1,46 @@
// usePlayerExit: how a player view hands the tab back to the app.
//
// Two things bind a player to its document: cross-origin isolation, which
// outlives every SPA navigation after it and blocks the third-party images the
// app embeds elsewhere, and a runtime that cannot be injected twice. Either
// leaves the app a fresh document to resume in; otherwise leaving is an SPA
// navigation.
import { ref, type Ref } from "vue";
import { useRouter, type RouteLocationNormalized } from "vue-router";
export function usePlayerExit(
/** True once the view injected a runtime the document cannot take twice. */
runtimeBound: () => boolean = () => false,
): {
/** True once an exit is replacing the document, so an unload prompt can stand down. */
departing: Ref<boolean>;
/** Go to `path`, by a full navigation when the document is bound. */
leave: (path: string) => void;
/** `onBeforeRouteLeave` guard: lets a departure through unless bound. */
guard: (to: Pick<RouteLocationNormalized, "fullPath">) => boolean;
} {
const router = useRouter();
const departing = ref(false);
function documentBound(): boolean {
return window.crossOriginIsolated || runtimeBound();
}
function replaceDocument(path: string): void {
departing.value = true;
window.location.replace(path);
}
function leave(path: string): void {
if (documentBound()) replaceDocument(path);
else void router.push(path);
}
function guard(to: Pick<RouteLocationNormalized, "fullPath">): boolean {
if (!documentBound()) return true;
replaceDocument(to.fullPath);
return false;
}
return { departing, leave, guard };
}

View File

@@ -38,6 +38,7 @@ import {
watch,
} from "vue";
import { useI18n } from "vue-i18n";
import { onBeforeRouteLeave } from "vue-router";
import type { FirmwareSchema, SaveSchema, StateSchema } from "@/__generated__";
import firmwareApi from "@/services/api/firmware";
import romApi from "@/services/api/rom";
@@ -60,7 +61,12 @@ import { useCoverArt } from "@/v2/composables/useCoverArt";
import { useFullscreenFallback } from "@/v2/composables/useFullscreenFallback";
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
import { useInputModality } from "@/v2/composables/useInputModality";
import {
hasSharedArrayBuffer,
useIsolatedLaunch,
} from "@/v2/composables/useIsolatedLaunch";
import { usePlaySession } from "@/v2/composables/usePlaySession";
import { usePlayerExit } from "@/v2/composables/usePlayerExit";
import { usePlayerHero } from "@/v2/composables/usePlayerHero";
import { usePlayerNav } from "@/v2/composables/usePlayerNav";
import { useSnackbar } from "@/v2/composables/useSnackbar";
@@ -98,6 +104,12 @@ import {
} from "@/v2/utils/saveSlots";
import { isJsResource, loadScript } from "@/v2/utils/scriptLoader";
import { rememberCore, resolveRememberedCore } from "./coreStorage";
import {
isLaunchIntent,
launchIntentFor,
resolveLaunchIntent,
type LaunchIntent,
} from "./launchIntent";
import {
defaultResumeSelection,
newerThanPick,
@@ -147,9 +159,25 @@ const selectedCore = ref<string | null>(null);
const selectedFirmware = ref<FirmwareSchema | null>(null);
const supportedCores = ref<string[]>([]);
const gameRunning = ref(false);
// Threaded cores need SharedArrayBuffer, so their launch may first have to
// reload the view into a cross-origin isolated document.
const {
intent: storedIntent,
relaunching,
relaunch: relaunchIsolated,
} = useIsolatedLaunch<LaunchIntent>("ejs", romId, isLaunchIntent);
useUnloadGuard(gameRunning);
// The EmulatorJS loader declares top-level classes, so a document it reached
// cannot host another launch. Tracked from the injection, which a departure
// taken mid-load would otherwise outrun.
let runtimeInjected = false;
const exit = usePlayerExit(() => runtimeInjected);
// A departure while a game runs is deliberate, so the unload prompt stays
// quiet for the full navigation it turns into.
useUnloadGuard(() => gameRunning.value && !exit.departing.value);
useStageActive(gameRunning);
onBeforeRouteLeave(exit.guard);
// Stage-scoped so the non-passive listener never taxes touches elsewhere.
const stageRef = ref<HTMLElement | null>(null);
@@ -159,6 +187,14 @@ useEventListener(stageRef, "touchstart", suppressVirtualGamepadZoneTouch, {
const presence = useActivityPresence(() => rom.value?.id);
function endSession() {
playSession.flush();
presence.stop();
}
// A full navigation out of the view unmounts nothing, so the session also
// closes on pagehide; flush() is idempotent, so no path records it twice.
useEventListener(window, "pagehide", endSession);
declare global {
interface Navigator {
keyboard: {
@@ -235,14 +271,21 @@ useEventListener(document, "fullscreenchange", () => {
});
async function onPlay() {
// Threaded cores need SharedArrayBuffer, which browsers only expose on a
// secure context (HTTPS or localhost), whatever headers the server sends.
if (rom.value) {
rememberCore(romId, rom.value.platform_slug, selectedCore.value);
rememberDisc(romId, selectedDisc.value);
}
// Threaded cores need SharedArrayBuffer, which only a cross-origin isolated
// secure context exposes, so the launch may have to reload into one first.
if (
selectedCore.value &&
areThreadsRequiredForEJSCore(selectedCore.value) &&
typeof window.SharedArrayBuffer !== "function"
!hasSharedArrayBuffer()
) {
snackbar.error(t("play.https-required"));
if (!relaunchIsolated(currentIntent())) {
snackbar.error(t("play.https-required"));
}
return;
}
@@ -254,10 +297,6 @@ async function onPlay() {
await new Promise((resolve) => setTimeout(resolve, insertMs));
}
if (rom.value) {
rememberCore(rom.value.id, rom.value.platform_slug, selectedCore.value);
rememberDisc(rom.value.id, selectedDisc.value);
}
gameRunning.value = true;
window.EJS_fullscreenOnLoaded = fullscreenOnPlay.value;
playing.value = true;
@@ -273,6 +312,7 @@ async function onPlay() {
throw new Error(`Loader at ${loaderUrl} did not return JavaScript`);
}
window.EJS_pathtodata = path;
runtimeInjected = true;
await loadScript(loaderUrl);
}
@@ -292,6 +332,29 @@ async function onPlay() {
}
}
function currentIntent(): LaunchIntent {
return launchIntentFor({
resume: resume.value,
firmware: selectedFirmware.value,
slot: slotChoice.value,
customSlot: customSlot.value,
});
}
// What the view had selected before the reload, re-applied over the defaults.
function applyLaunchIntent(intent: LaunchIntent, current: DetailedRom) {
const selection = resolveLaunchIntent(intent, {
saves: current.user_saves,
states: compatibleStates.value,
firmware: firmwareOptions.value,
});
resume.value = selection.resume;
isSavesTabSelected.value = !selection.resume.state;
slotChoice.value = selection.slot;
customSlot.value = selection.customSlot;
selectedFirmware.value = selection.firmware;
}
// A slotted save fixes the write slot, and it stays put for the session
// even when a state later displaces the save.
function selectSave(save: SaveSchema) {
@@ -384,6 +447,13 @@ onMounted(async () => {
configBiosFile: coreOptions["bios_file"],
});
if (storedIntent) {
applyLaunchIntent(storedIntent, romResponse.data);
await nextTick();
void onPlay();
return;
}
// Land gamepad/keyboard users on the primary action without an extra Tab.
if (
shouldClaimFocusOnModality(
@@ -415,9 +485,7 @@ watch(gameRunning, (running, prev) => {
presence.start();
}
if (prev && !running) {
playSession.flush();
presence.stopHeartbeat();
presence.emitStop();
endSession();
nextTick(focusPlayButton);
}
});
@@ -434,9 +502,7 @@ onBeforeUnmount(() => {
// Leaving the player (back nav / route change) ends the session even if
// the user never exited the game to the config screen first. flush() is
// idempotent, so an exit that already flushed via the watch is a no-op.
playSession.flush();
presence.stopHeartbeat();
presence.emitStop();
endSession();
// Hand the keyboard and gamepad back to the UI; the flag otherwise
// stays true and pad/hotkey navigation is dead until a reload.
playing.value = false;
@@ -577,8 +643,8 @@ const saveSlot = computed(() => chosenSlot(slotChoice.value, customSlot.value));
block
prepend-icon="mdi-play"
class="r-v2-ejs__play"
:loading="!rom"
:disabled="!rom"
:loading="!rom || relaunching"
:disabled="!rom || relaunching"
@click="onPlay"
>
{{ t("play.play") }}

View File

@@ -15,9 +15,10 @@ import JsDos from "./JsDos.vue";
const mocks = vi.hoisted(() => ({
flushPlaySession: vi.fn(),
getRom: vi.fn(),
loadRuntime: vi.fn(),
locationReplace: vi.fn(),
playSessionStart: vi.fn(),
push: vi.fn(),
push: vi.fn(() => Promise.resolve()),
confirm: vi.fn(),
galleryRom: null as Record<string, unknown> | null,
routeLeaveGuard: null as ((to: { fullPath: string }) => unknown) | null,
@@ -102,6 +103,12 @@ vi.mock("@/v2/stores/galleryRoms", () => ({
default: () => ({ getRomById: () => mocks.galleryRom }),
}));
// The runtime is a document-level singleton with its own suite; here it only
// has to say which base the emulator payloads follow.
vi.mock("./jsDosRuntime", () => ({
loadJsDosRuntime: mocks.loadRuntime,
}));
const rom = {
id: 1,
name: "Windows Game",
@@ -111,16 +118,24 @@ const rom = {
rom_user: { status: null },
};
const LOCAL_BASE = "/assets/jsdos";
const CDN_BASE = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist";
let originalLocation: Location;
function setIsolated(isolated: boolean) {
Object.defineProperty(window, "crossOriginIsolated", {
configurable: true,
value: isolated,
});
}
beforeAll(() => {
originalLocation = window.location;
Object.defineProperty(window, "location", {
configurable: true,
value: { ...originalLocation, replace: mocks.locationReplace },
});
vi.spyOn(document.body, "appendChild").mockImplementation((node) => node);
vi.spyOn(document.head, "appendChild").mockImplementation((node) => node);
vi.spyOn(console, "error").mockImplementation(() => undefined);
});
@@ -133,34 +148,10 @@ afterAll(() => {
});
});
function stubRuntimeProbe(contentType: string, ok = true) {
vi.stubGlobal(
"fetch",
vi.fn().mockResolvedValue({
ok,
headers: { get: () => contentType },
clone: () => ({ text: async () => "" }),
}),
);
}
function injectedUrls(): string[] {
return [document.head.appendChild, document.body.appendChild].flatMap((spy) =>
vi
.mocked(spy)
.mock.calls.map(
([node]) =>
(node as Element).getAttribute?.("src") ??
(node as Element).getAttribute?.("href") ??
"",
)
.filter(Boolean),
);
}
beforeEach(() => {
vi.clearAllMocks();
stubRuntimeProbe("text/javascript");
setIsolated(false);
mocks.loadRuntime.mockResolvedValue(LOCAL_BASE);
mocks.galleryRom = null;
mocks.routeLeaveGuard = null;
mocks.userId = 7;
@@ -187,14 +178,16 @@ function mountView(): VueWrapper {
});
}
// The runtime script defines `Dos` once it has loaded, so the stub lands
// after the mount has injected it.
async function mountPlayer(handle: JsDosProps): Promise<VueWrapper> {
const wrapper = mountView();
await flushPromises();
window.Dos = vi.fn(
(_element: HTMLDivElement, _options: Partial<JsDosOptions>) => handle,
);
const wrapper = mountView();
await flushPromises();
await wrapper.get(".r-v2-player__play").trigger("click");
await nextTick();
await flushPromises();
return wrapper;
}
@@ -207,48 +200,45 @@ function makeHandle(saveResult = true) {
}
describe("JsDos runtime loading", () => {
const CDN = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist";
it("serves the runtime from the local assets when they are present", async () => {
it("starts loading the runtime alongside the ROM payload", async () => {
mountView();
await flushPromises();
expect(injectedUrls()).toEqual(
expect.arrayContaining([
"/assets/jsdos/js-dos.css",
"/assets/jsdos/js-dos.js",
]),
);
});
// Slim images and the Vite dev server ship no local copy, and both answer a
// missing asset with 200 + index.html rather than a 404.
it("falls back to the pinned CDN when the local path serves index.html", async () => {
stubRuntimeProbe("text/html");
mountView();
await flushPromises();
expect(injectedUrls()).toEqual(
expect.arrayContaining([`${CDN}/js-dos.css`, `${CDN}/js-dos.js`]),
);
expect(mocks.loadRuntime).toHaveBeenCalled();
});
it("points the emulator payloads at whichever base served the runtime", async () => {
stubRuntimeProbe("text/html");
mocks.loadRuntime.mockResolvedValue(CDN_BASE);
const wrapper = await mountPlayer(makeHandle());
const options = vi.mocked(window.Dos!).mock.calls[0]![1];
expect(options.pathPrefix).toBe(`${CDN}/emulators/`);
expect(options.pathPrefix).toBe(`${CDN_BASE}/emulators/`);
wrapper.unmount();
});
it("reports a runtime that never arrived", async () => {
mocks.loadRuntime.mockRejectedValue(new Error("network"));
const wrapper = mountView();
await flushPromises();
await wrapper.get(".r-v2-player__play").trigger("click");
await flushPromises();
expect(mocks.snackbarError).toHaveBeenCalledWith(
"play.stream-error-generic",
);
expect(mocks.setPlaying).not.toHaveBeenCalledWith(true);
wrapper.unmount();
});
});
describe("JsDos player exit", () => {
it("reports when the runtime has not loaded", async () => {
it("reports when the runtime defined no factory", async () => {
const wrapper = mountView();
await flushPromises();
await wrapper.get(".r-v2-player__play").trigger("click");
await flushPromises();
expect(mocks.snackbarError).toHaveBeenCalledWith(
"play.stream-error-generic",
@@ -273,7 +263,7 @@ describe("JsDos player exit", () => {
wrapper.unmount();
});
it("hard-navigates after saving without awaiting stop", async () => {
it("leaves within the app after saving without awaiting stop", async () => {
const handle = makeHandle();
const wrapper = await mountPlayer(handle);
@@ -282,13 +272,49 @@ describe("JsDos player exit", () => {
expect(handle.save).toHaveBeenCalledOnce();
expect(handle.stop).toHaveBeenCalledOnce();
expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1");
expect(mocks.push).toHaveBeenCalledWith("/rom/1");
expect(mocks.locationReplace).not.toHaveBeenCalled();
expect(mocks.flushPlaySession).toHaveBeenCalledOnce();
expect(mocks.setPlaying).toHaveBeenLastCalledWith(false);
wrapper.unmount();
expect(handle.stop).toHaveBeenCalledOnce();
});
// A player document opened directly is cross-origin isolated, and the rest
// of the app cannot embed third-party images under that policy.
it("replaces an isolated document after saving", async () => {
setIsolated(true);
const handle = makeHandle();
const wrapper = await mountPlayer(handle);
await wrapper.get(".r-v2-player__quit").trigger("click");
await flushPromises();
expect(handle.save).toHaveBeenCalledOnce();
expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1");
expect(mocks.push).not.toHaveBeenCalled();
wrapper.unmount();
});
it("lets a departure from the launch view through", async () => {
const wrapper = mountView();
await flushPromises();
expect(mocks.routeLeaveGuard?.({ fullPath: "/platform/2" })).toBe(true);
expect(mocks.locationReplace).not.toHaveBeenCalled();
wrapper.unmount();
});
it("replaces an isolated document on departure from the launch view", async () => {
setIsolated(true);
const wrapper = mountView();
await flushPromises();
expect(mocks.routeLeaveGuard?.({ fullPath: "/platform/2" })).toBe(false);
expect(mocks.locationReplace).toHaveBeenCalledWith("/platform/2");
wrapper.unmount();
});
it("keeps the player open when the final save is not confirmed", async () => {
const handle = makeHandle(false);
const wrapper = await mountPlayer(handle);
@@ -300,6 +326,7 @@ describe("JsDos player exit", () => {
"play.stream-save-unconfirmed",
);
expect(handle.stop).not.toHaveBeenCalled();
expect(mocks.push).not.toHaveBeenCalled();
expect(mocks.locationReplace).not.toHaveBeenCalled();
expect(mocks.flushPlaySession).not.toHaveBeenCalled();
expect(mocks.setPlaying).not.toHaveBeenCalledWith(false);
@@ -320,7 +347,7 @@ describe("JsDos player exit", () => {
expect(handle.stop).toHaveBeenCalledOnce();
expect(mocks.flushPlaySession).toHaveBeenCalledOnce();
expect(mocks.setPlaying).toHaveBeenLastCalledWith(false);
expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1");
expect(mocks.push).toHaveBeenCalledWith("/rom/1");
wrapper.unmount();
});
@@ -336,7 +363,7 @@ describe("JsDos player exit", () => {
"play.stream-save-unconfirmed",
);
expect(handle.stop).not.toHaveBeenCalled();
expect(mocks.locationReplace).not.toHaveBeenCalled();
expect(mocks.push).not.toHaveBeenCalled();
wrapper.unmount();
});
@@ -356,7 +383,7 @@ describe("JsDos player exit", () => {
finishSave?.(true);
await flushPromises();
expect(mocks.locationReplace).toHaveBeenCalledOnce();
expect(mocks.push).toHaveBeenCalledOnce();
wrapper.unmount();
});
@@ -376,12 +403,12 @@ describe("JsDos player exit", () => {
finishSave?.(true);
await flushPromises();
expect(mocks.locationReplace).toHaveBeenCalledOnce();
expect(mocks.locationReplace).toHaveBeenCalledWith("/rom/1");
expect(mocks.push).toHaveBeenCalledOnce();
expect(mocks.push).toHaveBeenCalledWith("/rom/1");
wrapper.unmount();
});
it("converts route departure into a saved hard navigation", async () => {
it("saves before following a route departure", async () => {
const handle = makeHandle();
const wrapper = await mountPlayer(handle);
@@ -389,7 +416,7 @@ describe("JsDos player exit", () => {
await flushPromises();
expect(handle.save).toHaveBeenCalledOnce();
expect(mocks.locationReplace).toHaveBeenCalledWith("/platform/2");
expect(mocks.push).toHaveBeenCalledWith("/platform/2");
wrapper.unmount();
});

View File

@@ -14,18 +14,11 @@ import { useConfirm } from "@/v2/composables/useConfirm";
import { useFullscreenFallback } from "@/v2/composables/useFullscreenFallback";
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
import { usePlaySession } from "@/v2/composables/usePlaySession";
import { usePlayerExit } from "@/v2/composables/usePlayerExit";
import { usePlayerHero } from "@/v2/composables/usePlayerHero";
import { useSnackbar } from "@/v2/composables/useSnackbar";
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
import { isJsResource, loadScript } from "@/v2/utils/scriptLoader";
const JSDOS_LOCAL_BASE = "/assets/jsdos";
// Fallback for slim images and the dev server, which ship no local copy. Pinned
// to the image's JSDOS_VERSION; jsDelivr sends the CORP the player's COEP needs.
const JSDOS_CDN_BASE = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist";
// Where the runtime actually came from, so the emulator payloads follow it.
let jsDosAssetBase = JSDOS_LOCAL_BASE;
import { loadJsDosRuntime } from "./jsDosRuntime";
const { t } = useI18n();
const authStore = storeAuth();
@@ -35,6 +28,7 @@ useFullscreenFallback();
const playSession = usePlaySession();
const snackbar = useSnackbar();
const confirm = useConfirm();
const exit = usePlayerExit();
const rom = shallowRef<DetailedRom | null>(null);
const gameRunning = ref(false);
@@ -45,25 +39,22 @@ let dos: JsDosProps | null = null;
const { romId, heroRom, title, platformLabel } = usePlayerHero(rom);
async function loadRuntime() {
jsDosAssetBase = (await isJsResource(`${JSDOS_LOCAL_BASE}/js-dos.js`))
? JSDOS_LOCAL_BASE
: JSDOS_CDN_BASE;
const css = document.createElement("link");
css.rel = "stylesheet";
css.href = `${jsDosAssetBase}/js-dos.css`;
document.head.appendChild(css);
await loadScript(`${jsDosAssetBase}/js-dos.js`);
}
async function onPlay() {
// Preserve narrowing across nextTick().
const dosFactory = window.Dos;
const currentRom = rom.value;
const userId = authStore.user?.id;
if (!currentRom || userId == null) return;
// Resolves at once when the mount-time load already landed, and waits for it
// otherwise, so the emulator payloads always follow the base it served from.
let assetBase: string;
try {
assetBase = await loadJsDosRuntime();
} catch {
snackbar.error(t("play.stream-error-generic"));
return;
}
// Preserve narrowing across nextTick().
const dosFactory = window.Dos;
if (!dosFactory) {
snackbar.error(t("play.stream-error-generic"));
return;
@@ -84,7 +75,7 @@ async function onPlay() {
url: getDownloadPath({ rom: currentRom }),
backend: "dosboxX",
backendLocked: true,
pathPrefix: `${jsDosAssetBase}/emulators/`,
pathPrefix: `${assetBase}/emulators/`,
autoStart: true,
autoSave: true,
// js-dos calls exitFullscreen() unguarded when this is false, which
@@ -147,7 +138,7 @@ async function leavePlayer(destination: string) {
}
teardown();
window.location.replace(destination);
exit.leave(destination);
}
function onlyQuit() {
@@ -159,13 +150,15 @@ useUnloadGuard(() => !!dos && !quitting.value);
onMounted(async () => {
// The runtime reads nothing from the ROM payload, so let both loads overlap
// instead of holding the 300 KB bundle behind the API roundtrip.
void loadRuntime().catch((e) => console.error(e));
void loadJsDosRuntime().catch((e: unknown) => console.error(e));
const romResponse = await romApi.getRom({ romId });
rom.value = romResponse.data;
});
onBeforeRouteLeave((to) => {
// With nothing running there is nothing to save first.
if (!dos) return exit.guard(to);
void leavePlayer(to.fullPath);
return false;
});

View File

@@ -76,6 +76,7 @@ vi.mock("@/v2/composables/useActivityPresence", () => ({
start: vi.fn(),
stopHeartbeat: vi.fn(),
emitStop: vi.fn(),
stop: vi.fn(),
}),
}));

View File

@@ -654,8 +654,7 @@ watch(gameRunning, (running, prev) => {
nextTick(focusStream);
}
if (prev && !running) {
presence.stopHeartbeat();
presence.emitStop();
presence.stop();
nextTick(focusPlayButton);
}
});

View File

@@ -0,0 +1,97 @@
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
const mocks = vi.hoisted(() => ({
isJsResource: vi.fn(),
loadScript: vi.fn(),
}));
vi.mock("@/v2/utils/scriptLoader", () => ({
isJsResource: mocks.isJsResource,
loadScript: mocks.loadScript,
}));
const LOCAL = "/assets/jsdos";
const CDN = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist";
// The loader is a module-level singleton, so each case starts from a document
// that has never loaded it.
async function loadFresh() {
vi.resetModules();
return import("./jsDosRuntime");
}
// Intercepted rather than inserted: a real <link> would have the test
// environment go out and fetch the stylesheet.
beforeAll(() => {
vi.spyOn(document.head, "appendChild").mockImplementation((node) => node);
});
afterAll(() => {
vi.restoreAllMocks();
});
function stylesheets(): string[] {
return vi
.mocked(document.head.appendChild)
.mock.calls.map(([node]) => (node as Element).getAttribute("href") ?? "");
}
beforeEach(() => {
vi.clearAllMocks();
mocks.isJsResource.mockResolvedValue(true);
mocks.loadScript.mockResolvedValue(undefined);
});
describe("loadJsDosRuntime", () => {
it("serves the runtime from the local assets when they are present", async () => {
const { loadJsDosRuntime } = await loadFresh();
await expect(loadJsDosRuntime()).resolves.toBe(LOCAL);
expect(mocks.loadScript).toHaveBeenCalledWith(`${LOCAL}/js-dos.js`);
expect(stylesheets()).toContain(`${LOCAL}/js-dos.css`);
});
// Slim images and the Vite dev server ship no local copy, and both answer a
// missing asset with 200 + index.html rather than a 404.
it("falls back to the pinned CDN when the local path serves no JavaScript", async () => {
mocks.isJsResource.mockResolvedValue(false);
const { loadJsDosRuntime } = await loadFresh();
await expect(loadJsDosRuntime()).resolves.toBe(CDN);
expect(mocks.loadScript).toHaveBeenCalledWith(`${CDN}/js-dos.js`);
expect(stylesheets()).toContain(`${CDN}/js-dos.css`);
});
// Views can mount in the same document either side of the first load
// resolving, and neither order may inject a second runtime.
it("injects once however many views ask", async () => {
const { loadJsDosRuntime } = await loadFresh();
const concurrent = await Promise.all([
loadJsDosRuntime(),
loadJsDosRuntime(),
]);
await expect(loadJsDosRuntime()).resolves.toBe(LOCAL);
expect(concurrent).toEqual([LOCAL, LOCAL]);
expect(mocks.loadScript).toHaveBeenCalledOnce();
});
it("lets a later view retry after a failed load", async () => {
mocks.loadScript.mockRejectedValueOnce(new Error("network"));
const { loadJsDosRuntime } = await loadFresh();
await expect(loadJsDosRuntime()).rejects.toThrow("network");
await expect(loadJsDosRuntime()).resolves.toBe(LOCAL);
expect(mocks.loadScript).toHaveBeenCalledTimes(2);
});
});

View File

@@ -0,0 +1,37 @@
// The js-dos runtime is a document-level singleton: one injection and one asset
// base however many launch views mount. Held as the in-flight promise, so a
// view mounting while another is still loading waits for that load instead of
// injecting a second copy of a runtime that declares its own globals.
import { isJsResource, loadScript } from "@/v2/utils/scriptLoader";
const LOCAL_BASE = "/assets/jsdos";
// Fallback for slim images and the dev server, which ship no local copy. Pinned
// to the image's JSDOS_VERSION; jsDelivr sends the CORP a directly opened player
// document needs under its COEP.
const CDN_BASE = "https://cdn.jsdelivr.net/npm/js-dos@8.4.1/dist";
let pending: Promise<string> | null = null;
/** Load the runtime, resolving with the base the emulator payloads follow. */
export function loadJsDosRuntime(): Promise<string> {
pending ??= inject().catch((error: unknown) => {
// A failed load is not the document's verdict, so let the next mount retry.
pending = null;
throw error;
});
return pending;
}
async function inject(): Promise<string> {
const base = (await isJsResource(`${LOCAL_BASE}/js-dos.js`))
? LOCAL_BASE
: CDN_BASE;
const css = document.createElement("link");
css.rel = "stylesheet";
css.href = `${base}/js-dos.css`;
document.head.appendChild(css);
await loadScript(`${base}/js-dos.js`);
return base;
}

View File

@@ -0,0 +1,136 @@
import { describe, expect, it } from "vitest";
import type { FirmwareSchema, SaveSchema, StateSchema } from "@/__generated__";
import { existingSlot } from "@/v2/utils/saveSlots";
import {
isLaunchIntent,
launchIntentFor,
resolveLaunchIntent,
type LaunchIntent,
type LaunchOptions,
type LaunchSelection,
} from "./launchIntent";
function makeSave(overrides: Partial<SaveSchema> = {}): SaveSchema {
return { id: 3, slot: "slot-2", ...overrides } as SaveSchema;
}
function makeState(overrides: Partial<StateSchema> = {}): StateSchema {
return { id: 5, emulator: "snes9x", ...overrides } as StateSchema;
}
function makeFirmware(overrides: Partial<FirmwareSchema> = {}): FirmwareSchema {
return { id: 12, file_name: "bios.bin", ...overrides } as FirmwareSchema;
}
const save = makeSave();
const state = makeState();
const firmware = makeFirmware();
const OPTIONS: LaunchOptions = {
saves: [save],
states: [state],
firmware: [firmware],
};
const SELECTION: LaunchSelection = {
resume: { save, state: null },
firmware,
slot: existingSlot("slot-2"),
customSlot: "",
};
const INTENT: LaunchIntent = {
saveId: 3,
stateId: null,
firmwareId: 12,
slot: existingSlot("slot-2"),
customSlot: "",
};
const EMPTY: LaunchSelection = {
resume: { save: null, state: null },
firmware: null,
slot: { kind: "new" },
customSlot: "my slot",
};
describe("launchIntentFor", () => {
it("names the selection by id", () => {
expect(launchIntentFor(SELECTION)).toEqual(INTENT);
});
it("names a state pick over a save", () => {
expect(
launchIntentFor({ ...SELECTION, resume: { save: null, state } }),
).toEqual({ ...INTENT, saveId: null, stateId: 5 });
});
it("carries a cleared selection", () => {
expect(launchIntentFor(EMPTY)).toEqual({
saveId: null,
stateId: null,
firmwareId: null,
slot: { kind: "new" },
customSlot: "my slot",
});
});
});
describe("resolveLaunchIntent", () => {
it("round-trips a selection through its intent", () => {
expect(resolveLaunchIntent(launchIntentFor(SELECTION), OPTIONS)).toEqual(
SELECTION,
);
});
it("round-trips a cleared selection", () => {
expect(resolveLaunchIntent(launchIntentFor(EMPTY), OPTIONS)).toEqual(EMPTY);
});
// A save deleted from another tab, or a state the reloaded core cannot read,
// is simply not offered any more.
it.each([
["save", { ...INTENT, saveId: 99 }, "save"],
["state", { ...INTENT, saveId: null, stateId: 99 }, "state"],
])("drops a %s that is no longer offered", (_label, intent, key) => {
const resolved = resolveLaunchIntent(intent as LaunchIntent, OPTIONS);
expect(resolved.resume[key as "save" | "state"]).toBeNull();
});
it("drops firmware that is no longer offered", () => {
expect(
resolveLaunchIntent({ ...INTENT, firmwareId: 99 }, OPTIONS).firmware,
).toBeNull();
});
it("keeps the slot the session writes to", () => {
const resolved = resolveLaunchIntent(
{ ...INTENT, slot: { kind: "new" }, customSlot: "speedrun" },
OPTIONS,
);
expect(resolved.slot).toEqual({ kind: "new" });
expect(resolved.customSlot).toBe("speedrun");
});
});
describe("isLaunchIntent", () => {
it("accepts what the view stores", () => {
expect(isLaunchIntent(INTENT)).toBe(true);
});
it("accepts a cleared selection", () => {
expect(isLaunchIntent(launchIntentFor(EMPTY))).toBe(true);
});
it.each([
["nothing", null],
["another shape", { core: "snes9x" }],
["a string id", { ...INTENT, saveId: "3" }],
["a bare slot name", { ...INTENT, slot: "slot-2" }],
["a missing slot name", { ...INTENT, customSlot: undefined }],
])("rejects %s", (_label, value) => {
expect(isLaunchIntent(value)).toBe(false);
});
});

View File

@@ -0,0 +1,84 @@
// What the EmulatorJS launch view carries across the reload that isolates the
// document (see useIsolatedLaunch). Only ids travel, so they are resolved again
// against what the server offers; the core and the disc persist per game.
import type { FirmwareSchema, SaveSchema, StateSchema } from "@/__generated__";
import { isSlotChoice, type SlotChoice } from "@/v2/utils/saveSlots";
import type { ResumeSelection } from "./resumeSelection";
/** The pre-play selection a reload has to preserve. */
export interface LaunchSelection {
resume: ResumeSelection;
firmware: FirmwareSchema | null;
slot: SlotChoice;
customSlot: string;
}
/** That selection as ids, which is all a stored intent can hold. */
export interface LaunchIntent {
saveId: number | null;
stateId: number | null;
firmwareId: number | null;
slot: SlotChoice;
customSlot: string;
}
/** What the view offers to pick from, on the other side of the reload. */
export interface LaunchOptions {
saves: readonly SaveSchema[];
states: readonly StateSchema[];
firmware: readonly FirmwareSchema[];
}
export function launchIntentFor(selection: LaunchSelection): LaunchIntent {
return {
saveId: selection.resume.save?.id ?? null,
stateId: selection.resume.state?.id ?? null,
firmwareId: selection.firmware?.id ?? null,
slot: selection.slot,
customSlot: selection.customSlot,
};
}
/** The selection an intent names, dropping whatever is no longer offered. */
export function resolveLaunchIntent(
intent: LaunchIntent,
options: LaunchOptions,
): LaunchSelection {
return {
resume: {
save: byId(options.saves, intent.saveId),
state: byId(options.states, intent.stateId),
},
firmware: byId(options.firmware, intent.firmwareId),
slot: intent.slot,
customSlot: intent.customSlot,
};
}
function byId<T extends { id: number }>(
items: readonly T[],
id: number | null,
): T | null {
return items.find((item) => item.id === id) ?? null;
}
function isOptionalId(value: unknown): value is number | null {
return value === null || typeof value === "number";
}
export function isLaunchIntent(value: unknown): value is LaunchIntent {
return (
typeof value === "object" &&
value !== null &&
"saveId" in value &&
isOptionalId(value.saveId) &&
"stateId" in value &&
isOptionalId(value.stateId) &&
"firmwareId" in value &&
isOptionalId(value.firmwareId) &&
"slot" in value &&
isSlotChoice(value.slot) &&
"customSlot" in value &&
typeof value.customSlot === "string"
);
}

View File

@@ -0,0 +1,116 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it, vi } from "vitest";
import {
ISOLATED_PLAYER_URLS,
isIsolatedPlayerUrl,
playerIsolationHeaders,
} from "../scripts/playerIsolationHeaders";
type Middleware = (
req: { url?: string },
res: { setHeader: (name: string, value: string) => void },
next: () => void,
) => void;
/** Drive the plugin's server hook and hand back the middleware it registered. */
function middleware(): Middleware {
let registered: Middleware | undefined;
const { configureServer } = playerIsolationHeaders() as unknown as {
configureServer: (server: {
middlewares: { use: (fn: Middleware) => void };
}) => void;
};
configureServer({
middlewares: {
use: (fn) => {
registered = fn;
},
},
});
if (!registered) throw new Error("no middleware registered");
return registered;
}
function headersFor(url: string | undefined): Record<string, string> {
const headers: Record<string, string> = {};
const next = vi.fn();
middleware()(
{ url },
{
setHeader: (name, value) => {
headers[name] = value;
},
},
next,
);
expect(next).toHaveBeenCalledOnce();
return headers;
}
const ISOLATED = {
"Cross-Origin-Embedder-Policy": "require-corp",
"Cross-Origin-Opener-Policy": "same-origin",
};
describe("isIsolatedPlayerUrl", () => {
it.each([
"/rom/1/ejs",
"/rom/1/jsdos",
// The v2 players carry their state in the query, and nginx matches the
// request URI, so the query string has to be allowed for explicitly.
"/rom/1/ejs?core=snes9x",
"/console/rom/1/play",
])("isolates %s", (url) => {
expect(isIsolatedPlayerUrl(url)).toBe(true);
});
it.each([
"/rom/1",
"/rom/1/pico8",
"/rom/1/ruffle",
"/rom/1/stream",
"/platform/2",
"/api/roms/1/content/game.zip",
"/assets/emulatorjs/data/loader.js",
])("leaves %s alone", (url) => {
expect(isIsolatedPlayerUrl(url)).toBe(false);
});
});
describe("playerIsolationHeaders", () => {
it("isolates a player document", () => {
expect(headersFor("/rom/1/ejs")).toEqual(ISOLATED);
});
it("leaves every other document embeddable", () => {
expect(headersFor("/rom/1")).toEqual({});
});
it("passes a request with no URL through", () => {
expect(headersFor(undefined)).toEqual({});
});
});
// The dev server and nginx have to isolate the same documents, and nothing
// generates one list from the other, so the drift is what is tested.
describe("the nginx map it mirrors", () => {
// Vitest roots at frontend/, so the template sits one level above it.
const template = readFileSync(
resolve(process.cwd(), "../docker/nginx/templates/default.conf.template"),
"utf8",
);
it("isolates exactly the same URLs", () => {
const nginx = [
...template.matchAll(/^\s*~(\S+)\s+"(?:require-corp|same-origin)";/gm),
].map((entry) => entry[1]);
// nginx patterns are unescaped, since the delimiter is whitespace there.
const mirrored = ISOLATED_PLAYER_URLS.map((pattern) =>
pattern.source.replaceAll("\\/", "/"),
);
expect(nginx.length).toBeGreaterThan(0);
expect(new Set(nginx)).toEqual(new Set(mirrored));
});
});

View File

@@ -6,6 +6,7 @@ import { defineConfig, loadEnv } from "vite";
import mkcert from "vite-plugin-mkcert";
import { VitePWA } from "vite-plugin-pwa";
import vuetify, { transformAssetUrls } from "vite-plugin-vuetify";
import { playerIsolationHeaders } from "./scripts/playerIsolationHeaders";
import { precompress } from "./scripts/precompress";
// Vuetify components to preoptimize for faster dev startup
@@ -149,6 +150,7 @@ export default defineConfig(({ mode }) => {
},
}),
precompress(),
playerIsolationHeaders(),
httpsMode &&
mkcert({
savePath: "/app/.vite-plugin-mkcert",