Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+830
View File
@@ -0,0 +1,830 @@
"use strict";
// Behavioral regression tests for the Store panel's two async races:
//
// Finding 9 (Plugins/Mods search): a query typed while a search was in
// flight was dropped, and the next "Load more" paged the NEW query into
// the OLD result list. The fix (mrPluginsLoadSeq generation counter +
// pendingReset re-run, module-level debounce) is already in bot.js; these
// tests execute it and pin the race semantics so a refactor cannot quietly
// reintroduce the dropped query or the mixed result set.
//
// Finding 10 (provider version view): openProviderDetails had no staleness
// guard, so a slow live-fallback provider (e.g. Paper resolving ~200
// version metadatas) painted its list over whichever view the user opened
// afterwards, and an install in that window targeted a list the user never
// opened. The fix claims the store panel with storeViewSeq before painting
// and re-checks the claim after every await.
//
// bot.js is a browser IIFE (DOM + fetch bound at module scope), so the whole
// file cannot load under Node. Instead these tests slice the REAL state
// declarations and function bodies out of bot.js by anchor windows — the same
// convention as the other bot-*.test.js files — and evaluate them in a vm
// sandbox with a minimal DOM/fetch stub. The race logic under test (sequence
// checks, offset/query bookkeeping, pendingReset re-run, panel claims) is the
// genuine bot.js code, not a reimplementation; only the DOM leaves and the
// network are faked. If a function under test is renamed or moved, its
// anchor assertion fails loudly rather than testing a stale copy.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const ROOT = path.join(__dirname, "..");
const BOT_JS = path.join(ROOT, "public", "js", "bot.js");
const botSrc = fs.readFileSync(BOT_JS, "utf8");
function sourceWindow(src, startAnchor, endAnchor, label) {
const start = src.indexOf(startAnchor);
assert.notStrictEqual(start, -1, `${label || "window"}: start anchor not found: ${startAnchor}`);
const end = src.indexOf(endAnchor, start + startAnchor.length);
assert.notStrictEqual(end, -1, `${label || "window"}: end anchor not found: ${endAnchor}`);
return src.slice(start, end);
}
// ---------------------------------------------------------------------------
// Extraction: the real bot.js code under test
// ---------------------------------------------------------------------------
function extractBotStoreCode() {
return [
// Module state: store panel vars (currentStoreTab, storeProvidersCache,
// storeCurrentProvider, storeViewSeq, claimStorePanel) and the Modrinth
// search vars (mrPluginsState, mrPluginsLoadSeq, mrPluginsSearchTimer).
sourceWindow(botSrc, "let currentStoreTab = 'versions';", "let papermcVersionsCache = null;", "store state"),
sourceWindow(botSrc, "let mrPluginsState = {", "let mrAllProjectVersions", "plugins state"),
// Store views.
sourceWindow(botSrc, "async function openStoreModal() {", "function closeStoreModal() {", "openStoreModal"),
sourceWindow(botSrc, "function closeStoreModal() {", "function compareMcVersionsDesc(", "closeStoreModal"),
sourceWindow(botSrc, "async function fetchStoreProviders() {", "async function fetchStoreVersions(providerId) {", "fetchStoreProviders"),
sourceWindow(botSrc, "async function fetchStoreVersions(providerId) {", "async function fetchPythonVersions() {", "fetchStoreVersions"),
sourceWindow(botSrc, "async function renderStoreProvidersView(", "async function applyVersion(", "renderStoreProvidersView"),
sourceWindow(botSrc, "async function openProviderDetails(", "function renderPluginsPlaceholder() {", "openProviderDetails"),
sourceWindow(botSrc, "function renderPluginsPlaceholder() {", "function renderPluginsUI() {", "renderPluginsPlaceholder"),
sourceWindow(botSrc, "function renderPluginsUI() {", "async function loadModrinthPlugins(", "renderPluginsUI"),
sourceWindow(botSrc, "async function loadModrinthPlugins(", "function renderModrinthCard(", "loadModrinthPlugins"),
// The Versions/Plugins tab click handlers (the real navigation paths).
sourceWindow(botSrc, "if (storeTabVersions) storeTabVersions.addEventListener", "function focusConsole() {", "store tab handlers"),
].join("\n\n");
}
// ---------------------------------------------------------------------------
// Sandbox: minimal DOM + controllable network + real timers
// ---------------------------------------------------------------------------
const PROLOGUE = `
"use strict";
const __h = globalThis.__h;
function __makeEl(tag) {
const el = {
tagName: tag,
children: [],
className: "",
textContent: "",
style: {},
type: "",
value: "",
placeholder: "",
disabled: false,
handlers: {},
dataset: {},
appendChild(child) { el.children.push(child); return child; },
addEventListener(type, fn) { (el.handlers[type] = el.handlers[type] || []).push(fn); },
querySelector() { return __makeEl("div"); },
querySelectorAll() { return []; },
classList: { add() {}, remove() {}, toggle() {}, contains() { return false; } },
};
// Setting innerHTML in a real DOM replaces every child; the reset paths
// (grid.innerHTML = "" / "Loading...") rely on that.
Object.defineProperty(el, "innerHTML", {
get() { return el.__innerHTML || ""; },
set(v) { el.__innerHTML = String(v); el.children.length = 0; },
});
return el;
}
const __els = new Map();
function __el(id) {
if (!__els.has(id)) __els.set(id, __makeEl("#" + id));
return __els.get(id);
}
globalThis.__el = __el;
const document = {
createElement: (tag) => __makeEl(tag),
createDocumentFragment: () => __makeEl("#fragment"),
getElementById: (id) => (__els.has(id) ? __els.get(id) : null),
};
const storeContent = __el("storeContent");
const storeTabVersions = __el("storeTabVersions");
const storeTabPlugins = __el("storeTabPlugins");
const storeModal = { id: "storeModal" };
let serverInfo = null;
let pendingStoreOpen = false;
const bot = "srv-test";
function setActiveStoreTab(tab) { __h.tabs.push(tab); }
function resolveStoreTemplate() { return { template: __h.template }; }
function storeTemplateQuery() { return ""; }
function hasPerm() { return true; }
function showStoreToast(message, kind) { __h.toasts.push({ message: String(message), kind }); }
function showModalElement() { __h.shown++; }
function updateStoreVisibility() {}
function openStorePrefModal() { __h.prefOpened++; }
function loadServerInfo() { return Promise.resolve().then(() => __h.loadServerInfoImpl()); }
function animateClose(_el, cb) { __h.closes++; if (cb) cb(); }
function escapeHtml(s) {
return String(s == null ? "" : s).replace(/[&<>"']/g, (c) => (
{ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]
));
}
// Install path stubs: the version-row handler resolves the template, asks
// for confirmation, then calls applyVersion. All three are recorded.
function storeConfirm() { return Promise.resolve(__h.confirm); }
function templateDisplayName() { return "Minecraft"; }
function applyVersion(providerId, versionId, displayLabel) {
__h.applies.push({ providerId: String(providerId), versionId: String(versionId), label: String(displayLabel) });
return Promise.resolve({ ok: true });
}
async function fetch(url) {
__h.fetches.push(String(url));
return globalThis.__fetchImpl(String(url));
}
// Live-fallback resolvers used by the real fetchStoreVersions on a cache
// miss; each test wires only the ones it expects to run.
function fetchVanillaVersions() { return __h.live.vanilla(); }
function fetchPapermcVersions() { return __h.live.paper(); }
function fetchPurpurVersions() { return Promise.reject(new Error("unexpected purpur resolver")); }
function fetchVelocityVersions() { return Promise.reject(new Error("unexpected velocity resolver")); }
function fetchWaterfallVersions() { return Promise.reject(new Error("unexpected waterfall resolver")); }
function fetchFoliaVersions() { return Promise.reject(new Error("unexpected folia resolver")); }
function fetchLeavesVersions() { return Promise.reject(new Error("unexpected leaves resolver")); }
function fetchSpigotVersions() { return Promise.reject(new Error("unexpected spigot resolver")); }
// Renders a Modrinth hit into the target as a card carrying the hit and
// the project type it was searched under, mirroring what the real
// renderModrinthCard hands the grid. Every invocation is recorded: the
// generation counter's contract is that a superseded response is discarded
// BEFORE rendering, so the render call itself is the distinguishing
// observable (the grid self-wipes in the same tick via the pendingReset
// re-run, so settled DOM state alone cannot tell the two apart).
function renderModrinthCard(hit, target, projectType) {
__h.cardRenders.push({ hit, projectType });
const card = __makeEl("div");
card.__hit = hit;
card.__projectType = projectType;
target.appendChild(card);
}
`;
const EPILOGUE = `
globalThis.__snap = () => ({
storeViewSeq,
storeCurrentProvider,
storeProvidersCache,
currentStoreTab,
serverInfo,
pendingStoreOpen,
mrPluginsState,
mrPluginsLoadSeq,
mrPluginsSearchTimer,
});
globalThis.__setServerInfo = (v) => { serverInfo = v; };
`;
function makeHarness({ template = "minecraft" } = {}) {
const hooks = {
template,
tabs: [],
toasts: [],
fetches: [],
applies: [],
cardRenders: [],
shown: 0,
closes: 0,
prefOpened: 0,
confirm: true,
loadServerInfoImpl: () => ({}),
live: {
vanilla: () => Promise.reject(new Error("unexpected vanilla resolver")),
paper: () => Promise.reject(new Error("unexpected paper resolver")),
},
};
const sandbox = { setTimeout, clearTimeout, console };
sandbox.__h = hooks;
sandbox.__fetchImpl = () => Promise.reject(new Error("no route configured for this fetch"));
vm.createContext(sandbox);
vm.runInContext(PROLOGUE + "\n\n" + extractBotStoreCode() + "\n\n" + EPILOGUE, sandbox, {
timeout: 4000,
filename: "bot-store-sandbox.js",
});
// The real renderPluginsUI reads its widgets out of the document after
// painting the markup; register them so the sandboxed getElementById finds
// them and binds their handlers.
for (const id of [
"mrPluginSearch", "mrPluginReload", "mrPluginLoadMore", "mrPluginGrid",
"mrTypePlugin", "mrTypeMod",
]) {
sandbox.__el(id);
}
return { sandbox, hooks, el: (id) => sandbox.__el(id), snap: () => sandbox.__snap() };
}
// ---------------------------------------------------------------------------
// Node-side helpers
// ---------------------------------------------------------------------------
function makeRouter() {
const calls = [];
const routes = [];
// First matching route wins: register specific routes (query=…, facet=…)
// BEFORE the generic browse route.
const impl = (url) => {
calls.push(url);
const route = routes.find(([match]) => match(url));
if (!route) return Promise.reject(new Error("unrouted fetch: " + url));
return route[1](url);
};
return {
calls,
impl,
on: (match, respond) => routes.push([match, respond]),
modrinthBrowsing: (u) => u.includes("api.modrinth.com/v2/search"),
storeProviders: (u) => /\/api\/servers\/srv-test\/versions$/.test(u),
storeVersions: (id) => (u) => u.endsWith(`/api/servers/srv-test/versions/${id}`),
};
}
function defer() {
let resolve;
let reject;
const promise = new Promise((res, rej) => { resolve = res; reject = rej; });
return { promise, resolve, reject };
}
const okJson = (body) => ({ ok: true, status: 200, json: async () => body });
const cacheMiss = () => ({ ok: false, status: 404, json: async () => ({}) });
function makeHits(prefix, count) {
return Array.from({ length: count }, (_, i) => ({
project_id: `${prefix}-${i}`,
title: `${prefix} card ${i}`,
description: "hit",
downloads: i,
icon_url: "",
}));
}
function makeVersions(prefix, count) {
return Array.from({ length: count }, (_, i) => ({
id: `${prefix}-${i}`,
name: `${prefix}-${i}`,
label: `${prefix}-${i}`,
}));
}
async function flush() {
for (let i = 0; i < 4; i += 1) await new Promise((resolve) => setImmediate(resolve));
}
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
function collectWhere(el, pred, out = []) {
if (!el || typeof el !== "object") return out;
if (pred(el)) out.push(el);
for (const child of el.children || []) collectWhere(child, pred, out);
return out;
}
function allText(el, out = []) {
if (!el || typeof el !== "object") return out;
if (typeof el.textContent === "string" && el.textContent) out.push(el.textContent);
for (const child of el.children || []) allText(child, out);
return out;
}
const gridCards = (grid) => collectWhere(grid, (e) => e && e.__hit);
const versionRows = (root) => collectWhere(root, (e) => e && e.className === "store-version-row");
const SEARCH_DEBOUNCE_MS = 450; // the real debounce is 400ms
// ---------------------------------------------------------------------------
// Finding 9: the Plugins/Mods search races
// ---------------------------------------------------------------------------
test("a query typed while a search is in flight still runs and Load more pages it onto its own list", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
const dEssentials = defer();
const dWorldedit = defer();
const dWorldeditPage2 = defer();
router.on((u) => u.includes("query=essentials"), () => dEssentials.promise);
// The paged worldedit fetch gets its own deferred (registered before the
// offset=0 search route, which would otherwise also match it).
router.on((u) => u.includes("query=worldedit") && !u.includes("offset=0"), () => dWorldeditPage2.promise);
router.on((u) => u.includes("query=worldedit"), () => dWorldedit.promise);
router.on(router.modrinthBrowsing, () => Promise.resolve(okJson({ hits: makeHits("browse", 24) })));
const search = h.el("mrPluginSearch");
const reload = h.el("mrPluginReload");
const loadMore = h.el("mrPluginLoadMore");
h.sandbox.renderPluginsUI();
await flush();
const state = h.snap().mrPluginsState;
assert.strictEqual(state.loading, false, "initial browse should have completed");
assert.strictEqual(state.offset, 24, "initial browse filled one page");
assert.strictEqual(gridCards(h.el("mrPluginGrid")).length, 24);
// First search: "essentials" (debounce fires, fetch goes out, stays pending).
search.value = "essentials";
search.handlers.input[0]();
await wait(SEARCH_DEBOUNCE_MS);
assert.strictEqual(router.calls.filter((u) => u.includes("query=essentials")).length, 1,
"the essentials search must be in flight");
// Second query typed mid-flight: must supersede, not be dropped.
search.value = "worldedit";
search.handlers.input[0]();
await wait(SEARCH_DEBOUNCE_MS);
assert.strictEqual(h.snap().mrPluginsState.query, "worldedit");
assert.ok(!router.calls.some((u) => u.includes("query=worldedit")),
"no worldedit fetch may start while essentials is still in flight");
// The in-flight essentials response lands: it must be discarded and the
// worldedit search re-run from offset 0 — not dropped, not appended.
dEssentials.resolve(okJson({ hits: makeHits("essentials", 24) }));
await flush();
// The generation counter's contract: the superseded continuation must not
// hand a single stale card to the renderer. (Settled DOM state alone
// cannot prove this — the pendingReset re-run wipes the grid in the same
// tick — so the render call is the observable that matters.)
const staleRenderAttempts = h.hooks.cardRenders.filter(
(r) => String(r.hit && r.hit.title).startsWith("essentials")
);
assert.strictEqual(staleRenderAttempts.length, 0,
`a superseded search response must be discarded before rendering; ${staleRenderAttempts.length} stale cards reached the renderer`);
// And the same-tick wipe property: by the time the stale continuation has
// fully unwound, the grid is the re-run's loading state — no stale hits
// remain visible, not even for one paint frame.
assert.strictEqual(gridCards(h.el("mrPluginGrid")).length, 0,
"no stale card may remain in the grid once the superseded load unwinds");
assert.match(h.el("mrPluginGrid").innerHTML, /Loading plugins from Modrinth/,
"the re-run's loading state must replace the stale content");
const pagedEssentials = router.calls.filter(
(u) => u.includes("query=essentials") && !u.includes("offset=0")
);
assert.strictEqual(pagedEssentials.length, 0, "no paged essentials fetch may ever be issued");
const worldeditFetches = router.calls.filter((u) => u.includes("query=worldedit"));
assert.strictEqual(worldeditFetches.length, 1, "the worldedit search must run exactly once");
assert.ok(worldeditFetches[0].includes("offset=0"), "the worldedit search restarts from offset 0");
dWorldedit.resolve(okJson({ hits: makeHits("worldedit", 2) }));
await flush();
let cards = gridCards(h.el("mrPluginGrid"));
assert.strictEqual(cards.length, 2, "the grid shows exactly the worldedit page");
assert.ok(cards.every((c) => c.__hit.title.startsWith("worldedit")),
"no essentials card may remain in the grid");
assert.strictEqual(h.snap().mrPluginsState.offset, 2);
// Load more pages the worldedit query onto the worldedit list.
loadMore.handlers.click[0]();
await flush();
const paged = router.calls.filter(
(u) => u.includes("query=worldedit") && !u.includes("offset=0")
);
assert.strictEqual(paged.length, 1);
assert.ok(paged[0].includes("offset=2"), `Load more must page worldedit from offset 2, got ${paged[0]}`);
dWorldeditPage2.resolve(okJson({ hits: makeHits("worldedit", 1) }));
await flush();
cards = gridCards(h.el("mrPluginGrid"));
assert.strictEqual(cards.length, 3, "the worldedit page appends onto the worldedit list");
assert.ok(cards.every((c) => c.__hit.title.startsWith("worldedit")),
"no result set mixing may occur after Load more");
assert.strictEqual(h.snap().mrPluginsState.pendingReset, false);
assert.strictEqual(reload.handlers.click.length, 1, "Refresh handler stays wired");
});
test("Refresh clicked while a search is in flight is not swallowed", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
const dEssentials = defer();
router.on((u) => u.includes("query=essentials"), () => dEssentials.promise);
router.on(router.modrinthBrowsing, () => Promise.resolve(okJson({ hits: makeHits("browse", 5) })));
const search = h.el("mrPluginSearch");
const reload = h.el("mrPluginReload");
h.sandbox.renderPluginsUI();
await flush();
search.value = "essentials";
search.handlers.input[0]();
await wait(SEARCH_DEBOUNCE_MS);
assert.ok(router.calls.some((u) => u.includes("query=essentials")), "search in flight");
reload.handlers.click[0]();
assert.strictEqual(h.snap().mrPluginsState.query, "", "Refresh resets the query immediately");
assert.strictEqual(search.value, "", "Refresh clears the input immediately");
// The stale essentials response must be discarded and the unfiltered
// browse re-run — the old code swallowed this click entirely.
dEssentials.resolve(okJson({ hits: makeHits("essentials", 24) }));
await flush();
const refetches = router.calls.slice(2);
assert.strictEqual(refetches.length, 1, "exactly one re-run fetch after Refresh");
assert.ok(!refetches[0].includes("query="), `the re-run must be the unfiltered browse, got ${refetches[0]}`);
const cards = gridCards(h.el("mrPluginGrid"));
assert.strictEqual(cards.length, 5);
assert.ok(cards.every((c) => c.__hit.title.startsWith("browse")),
"the grid must show the refreshed browse list, not the stale search");
});
test("Load more clicked while a load is in flight neither fetches nor mixes", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
let pageCount = 0;
const dBrowse = defer();
router.on(router.modrinthBrowsing, () => (pageCount++ === 0 ? dBrowse.promise : Promise.resolve(okJson({ hits: makeHits("page2", 1) }))));
const loadMore = h.el("mrPluginLoadMore");
h.sandbox.renderPluginsUI();
await flush();
loadMore.handlers.click[0]();
await flush();
assert.strictEqual(router.calls.length, 1, "Load more while loading must not fetch");
assert.strictEqual(gridCards(h.el("mrPluginGrid")).length, 0, "and must not paint anything");
dBrowse.resolve(okJson({ hits: makeHits("browse", 2) }));
await flush();
assert.strictEqual(h.snap().mrPluginsState.offset, 2);
// Now it pages normally.
loadMore.handlers.click[0]();
await flush();
assert.ok(router.calls[1].includes("offset=2"), `second page must start at offset 2, got ${router.calls[1]}`);
const cards = gridCards(h.el("mrPluginGrid"));
assert.strictEqual(cards.length, 3, "the second page appends onto the first");
});
test("re-rendering the tab while a load is in flight supersedes it and re-runs cleanly", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
const dFirst = defer();
let renderCount = 0;
router.on(router.modrinthBrowsing, () => (renderCount++ === 0 ? dFirst.promise : Promise.resolve(okJson({ hits: makeHits("fresh", 2) }))));
h.sandbox.renderPluginsUI();
h.sandbox.renderPluginsUI(); // second render while the first load is in flight
await flush();
assert.strictEqual(router.calls.length, 1, "the re-render must not start a second fetch while loading");
dFirst.resolve(okJson({ hits: makeHits("stale", 24) }));
await flush();
assert.strictEqual(router.calls.length, 2, "the superseded initial load must re-run once it unwinds");
const cards = gridCards(h.el("mrPluginGrid"));
assert.strictEqual(cards.length, 2);
assert.ok(cards.every((c) => c.__hit.title.startsWith("fresh")),
"the re-rendered grid must show only the re-run's results");
});
test("flipping Plugins/Mods while a load is in flight re-runs under the new facet and type", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
const dMods = defer();
const dPlugins = defer();
const dBrowse = defer();
let pluginFacetFetches = 0;
router.on((u) => u.includes("project_type%3Amod"), () => dMods.promise);
// The initial browse and the re-run share the plugin facet; the first
// plugin-facet fetch is the browse, the second is the re-run.
router.on((u) => u.includes("project_type%3Aplugin"), () => (pluginFacetFetches++ === 0 ? dBrowse.promise : dPlugins.promise));
router.on(router.modrinthBrowsing, () => Promise.resolve(okJson({ hits: makeHits("browse", 3) })));
h.sandbox.renderPluginsUI();
await flush();
dBrowse.resolve(okJson({ hits: makeHits("browse", 3) }));
await flush();
assert.strictEqual(h.snap().mrPluginsState.loading, false, "initial browse settled");
h.el("mrTypeMod").handlers.click[0]();
await flush();
assert.ok(router.calls[1].includes("project_type%3Amod"), "the mod search must use the mod facet");
// Flip back while the mod search is still in flight.
h.el("mrTypePlugin").handlers.click[0]();
await flush();
assert.strictEqual(router.calls.length, 2, "no plugin fetch may start while the mod load is in flight");
dMods.resolve(okJson({ hits: makeHits("modhit", 4) }));
await flush();
assert.ok(router.calls[2].includes("project_type%3Aplugin"),
"the re-run must use the plugin facet the user flipped to");
dPlugins.resolve(okJson({ hits: makeHits("plug", 2) }));
await flush();
const cards = gridCards(h.el("mrPluginGrid"));
assert.strictEqual(cards.length, 2);
assert.ok(cards.every((c) => c.__projectType === "plugin"),
"cards must carry the facet of the list they were searched under");
});
// ---------------------------------------------------------------------------
// Finding 10: the provider version view races
// ---------------------------------------------------------------------------
test("a slow provider fetch cannot overwrite a newer provider view, and installs still target the open view", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
const dProviders = defer();
const dPaper = defer();
router.on(router.storeVersions("paper"), () => Promise.resolve(cacheMiss())); // cache miss -> live fallback
router.on(router.storeProviders, () => dProviders.promise);
router.on(router.storeVersions("vanilla"), () => Promise.resolve(okJson({
versions: makeVersions("vanilla-build", 1),
})));
h.hooks.live.paper = () => dPaper.promise; // the slow ~200-version resolve
const paperProvider = { id: "paper", name: "Paper", description: "d" };
const vanillaProvider = { id: "vanilla", name: "Vanilla", description: "d" };
// The user opens Paper; its live resolve hangs.
const paperView = h.sandbox.openProviderDetails(paperProvider);
assert.strictEqual(h.el("storeContent").innerHTML, '<div class="store-loading">Loading versions...</div>');
// They go back to the Versions tab and open Vanilla instead.
h.el("storeTabVersions").handlers.click[0]();
dProviders.resolve(okJson({ providers: [vanillaProvider, paperProvider] }));
await flush();
const providersGrid = h.el("storeContent").children[0];
assert.strictEqual(providersGrid.className, "store-content-grid", "the providers grid is painted");
const vanillaCard = providersGrid.children.find((card) => allText(card).includes("Vanilla"));
assert.ok(vanillaCard, "the vanilla provider card exists");
vanillaCard.handlers.click[0]();
await flush();
const content = h.el("storeContent");
const rows = versionRows(content);
assert.strictEqual(rows.length, 1, "the vanilla version list is painted");
assert.strictEqual(h.snap().storeCurrentProvider, vanillaProvider,
"the current provider must track the view the user actually opened");
// Paper's slow response finally lands: it must be discarded wholesale.
dPaper.resolve({ versions: makeVersions("paper-build", 200) });
await flush();
await paperView;
const texts = allText(content).join(" | ");
assert.ok(!texts.includes("paper-build"), "the stale paper list must not be painted");
assert.strictEqual(versionRows(content).length, 1, "the vanilla view must survive");
assert.strictEqual(h.snap().storeCurrentProvider, vanillaProvider);
// The painted row installs the provider whose list is actually open.
rows[0].handlers.click[0]();
await flush();
assert.strictEqual(h.hooks.applies.length, 1);
assert.strictEqual(h.hooks.applies[0].providerId, "vanilla",
"the install must target the provider of the view the user opened");
assert.match(h.hooks.applies[0].versionId, /^vanilla-build-/);
});
test("a slow provider failing after being superseded paints no error over the newer view", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
const dPaper = defer();
router.on(router.storeVersions("paper"), () => Promise.resolve(cacheMiss()));
router.on(router.storeVersions("vanilla"), () => Promise.resolve(okJson({
versions: makeVersions("vanilla-build", 1),
})));
h.hooks.live.paper = () => dPaper.promise;
const paperView = h.sandbox.openProviderDetails({ id: "paper", name: "Paper" });
await flush();
h.sandbox.openProviderDetails({ id: "vanilla", name: "Vanilla" });
await flush();
dPaper.reject(new Error("paper api exploded"));
await flush();
await paperView;
const content = h.el("storeContent");
assert.ok(!allText(content).join(" ").includes("Failed to load versions"),
"the stale failure must not overwrite the newer view");
assert.strictEqual(versionRows(content).length, 1, "the vanilla view survives the stale error");
});
test("closing the store modal invalidates an in-flight version fetch", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
const dPaper = defer();
router.on(router.storeVersions("paper"), () => Promise.resolve(cacheMiss()));
h.hooks.live.paper = () => dPaper.promise;
const paperView = h.sandbox.openProviderDetails({ id: "paper", name: "Paper" });
await flush();
h.sandbox.closeStoreModal();
assert.strictEqual(h.hooks.closes, 1, "the modal close ran");
dPaper.resolve({ versions: makeVersions("paper-build", 200) });
await flush();
await paperView;
const content = h.el("storeContent");
assert.strictEqual(content.children.length, 0, "nothing may be painted into the closed modal");
assert.ok(!allText(content).join(" ").includes("paper-build"));
});
test("opening the Plugins tab while a version fetch is in flight claims the panel", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
const dPaper = defer();
const dSearch = defer();
router.on(router.storeVersions("paper"), () => Promise.resolve(cacheMiss()));
router.on(router.modrinthBrowsing, () => dSearch.promise);
h.hooks.live.paper = () => dPaper.promise;
const paperView = h.sandbox.openProviderDetails({ id: "paper", name: "Paper" });
await flush();
h.el("storeTabPlugins").handlers.click[0]();
await flush();
const content = h.el("storeContent");
assert.ok(content.innerHTML.includes("mr-plugins-root"), "the Plugins/Mods tab is painted");
dPaper.resolve({ versions: makeVersions("paper-build", 200) });
await flush();
await paperView;
assert.ok(content.innerHTML.includes("mr-plugins-root"), "the plugins view must survive the stale response");
assert.strictEqual(versionRows(content).length, 0, "no provider rows may leak into the plugins tab");
// The plugins tab itself still works after the discarded paint attempt.
dSearch.resolve(okJson({ hits: makeHits("browse", 2) }));
await flush();
assert.strictEqual(gridCards(h.el("mrPluginGrid")).length, 2);
});
test("an overlapping openStoreModal cannot paint its late providers over the newer session", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
h.sandbox.__setServerInfo({ template: "minecraft" });
let openCount = 0;
const dFirst = defer();
const dSecond = defer();
router.on(router.storeProviders, () => (openCount++ === 0 ? dFirst.promise : dSecond.promise));
router.on(router.storeVersions("vanilla"), () => Promise.resolve(okJson({
versions: makeVersions("vanilla-build", 1),
})));
h.sandbox.openStoreModal();
h.sandbox.openStoreModal();
await flush();
assert.strictEqual(router.calls.filter(router.storeProviders).length, 2, "both opens fetched providers");
dSecond.resolve(okJson({ providers: [{ id: "vanilla", name: "Vanilla" }] }));
await flush();
const providersGrid = h.el("storeContent").children[0];
assert.strictEqual(providersGrid.className, "store-content-grid", "the newest open painted the grid");
dFirst.resolve(okJson({ providers: [{ id: "paper", name: "Paper" }] }));
await flush();
assert.ok(!allText(h.el("storeContent")).join(" ").includes("Paper"),
"the stale open must not repaint the providers grid");
});
test("a superseded openStoreModal whose providers fetch fails paints no error over the newer open", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
h.sandbox.__setServerInfo({ template: "minecraft" });
let openCount = 0;
const dStale = defer();
const dFresh = defer();
router.on(router.storeProviders, () => (openCount++ === 0 ? dStale.promise : dFresh.promise));
router.on(router.storeVersions("vanilla"), () => Promise.resolve(okJson({
versions: makeVersions("vanilla-build", 1),
})));
h.sandbox.openStoreModal(); // stale open, fetch pending
h.sandbox.openStoreModal(); // fresh open claims the panel
await flush();
// The stale open's fetch resolves with a server error: the check between
// the fetch and the error paint must discard it.
dStale.resolve({ ok: false, status: 500, json: async () => ({}) });
await flush();
assert.ok(!allText(h.el("storeContent")).join(" ").includes("Failed to load providers"),
"the stale open's failure must not paint over the newer open");
assert.strictEqual(h.el("storeContent").innerHTML,
'<div class="store-loading">Loading providers...</div>',
"the newer open's loading state must be untouched");
dFresh.resolve(okJson({ providers: [{ id: "vanilla", name: "Vanilla" }] }));
await flush();
assert.strictEqual(h.el("storeContent").children[0].className, "store-content-grid",
"the fresh open still completes normally");
});
test("a superseded openStoreModal whose response parses late paints no providers over the newer open", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
h.sandbox.__setServerInfo({ template: "minecraft" });
let openCount = 0;
const dStaleJson = defer();
const dFresh = defer();
router.on(router.storeProviders, () => {
const i = openCount++;
if (i === 0) return Promise.resolve({ ok: true, status: 200, json: () => dStaleJson.promise });
return dFresh.promise;
});
router.on(router.storeVersions("vanilla"), () => Promise.resolve(okJson({
versions: makeVersions("vanilla-build", 1),
})));
h.sandbox.openStoreModal(); // stale open: fetch ok, response parse suspended
await flush();
h.sandbox.openStoreModal(); // fresh open claims the panel while the parse is pending
await flush();
// The stale parse lands while the fresh open's fetch is still in flight:
// the check between r.json() and the providers read must discard it.
dStaleJson.resolve(okJson({ providers: [{ id: "paper", name: "Paper" }] }));
await flush();
assert.ok(!allText(h.el("storeContent")).join(" ").includes("Paper"),
"the stale parsed providers must not paint over the newer open");
assert.strictEqual(h.el("storeContent").innerHTML,
'<div class="store-loading">Loading providers...</div>',
"the newer open's loading state must be untouched");
dFresh.resolve(okJson({ providers: [{ id: "vanilla", name: "Vanilla" }] }));
await flush();
assert.strictEqual(h.el("storeContent").children[0].className, "store-content-grid",
"the fresh open still completes normally");
});
test("a providers render superseded by a modal reopen cannot paint late", async () => {
const h = makeHarness();
const router = makeRouter();
h.sandbox.__fetchImpl = router.impl;
h.sandbox.__setServerInfo({ template: "minecraft" });
let providersFetchCount = 0;
const dStale = defer();
router.on(router.storeProviders, () => (providersFetchCount++ === 0 ? dStale.promise : Promise.resolve(okJson({
providers: [{ id: "vanilla", name: "Vanilla" }],
}))));
router.on(router.storeVersions("vanilla"), () => Promise.resolve(okJson({
versions: makeVersions("vanilla-build", 1),
})));
h.sandbox.renderStoreProvidersView(); // providers fetch in flight (stale)
h.sandbox.closeStoreModal();
h.sandbox.openStoreModal();
await flush();
assert.strictEqual(h.el("storeContent").children[0].className, "store-content-grid",
"the reopened modal painted the fresh providers grid");
dStale.resolve(okJson({ providers: [{ id: "paper", name: "Paper" }] }));
await flush();
assert.ok(!allText(h.el("storeContent")).join(" ").includes("Paper"),
"the stale providers response must be discarded");
// The providers grid's back button re-renders the list on demand.
h.sandbox.openProviderDetails({ id: "vanilla", name: "Vanilla" });
await flush();
const backBtn = collectWhere(h.el("storeContent"), (e) => e.className === "store-back-btn")[0];
assert.ok(backBtn, "the version view has a back button");
backBtn.handlers.click[0]();
await flush();
assert.strictEqual(h.el("storeContent").children[0].className, "store-content-grid",
"Back repaints the providers grid");
assert.strictEqual(h.snap().storeCurrentProvider, null, "Back clears the current provider");
});