Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,474 @@
|
||||
"use strict";
|
||||
|
||||
// Regression tests for the URL-uploader Esc + re-entrancy fixes (findings 7 & 8).
|
||||
//
|
||||
// Finding 7 — Esc destroyed the page underneath the dialog. The document
|
||||
// keydown chain in bot.js enumerated every stackable modal EXCEPT
|
||||
// urlUploaderModal, and the uploader opens on top of the Files page without
|
||||
// closing it (an .activity-modal at z-index 100000 over the .modal-overlay
|
||||
// pages at z-index 10000). Esc therefore matched the filesModal branch and
|
||||
// closed the whole Files page out from under the open dialog — whose close
|
||||
// button is titled "Close (Esc)" in bot.ejs and could never be discharged
|
||||
// with Esc.
|
||||
//
|
||||
// Finding 8 — double-submit and in-flight clobbering. startUrlUpload had no
|
||||
// re-entrancy guard: the input's Enter key reaches the handler directly (no
|
||||
// disabled button to stop it), the dialog lingers ~360 ms in the DOM during
|
||||
// its close animation, and nothing checked uploadBatchActive — so a second
|
||||
// Enter within that window re-POSTed /upload-url, a URL upload could start
|
||||
// over a running file batch (showProgressWheel() wiping its per-file progress
|
||||
// list), and the URL flow's failure path (hideProgressWheel →
|
||||
// closeProgressPopup → requestUploadCancel) aborted the batch's in-flight
|
||||
// XHR, leaving it running with no progress UI and no cancel affordance. The
|
||||
// reverse race existed too: a file batch started during a URL upload would
|
||||
// clobber the URL wheel, and the URL flow's completion path (setProgress(100)
|
||||
// → auto-hide → closeProgressPopup → requestUploadCancel) would abort the
|
||||
// batch.
|
||||
//
|
||||
// bot.js is a browser closure that cannot execute under Node, so — like the
|
||||
// other bot.js regression tests here — these pin the structural contract of
|
||||
// the fix: branch presence and ordering in the Esc chain, guard placement
|
||||
// inside startUrlUpload and uploadFilesSequential, the single shared flag,
|
||||
// and the CSS/animation mechanics the guards depend on.
|
||||
|
||||
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 { gzipSync } = require("node:zlib");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const BOT_JS = path.join(ROOT, "public", "js", "bot.js");
|
||||
const BOT_EJS = path.join(ROOT, "views", "bot.ejs");
|
||||
const BOT_CSS = path.join(ROOT, "public", "css", "bot.css");
|
||||
|
||||
const botSrc = fs.readFileSync(BOT_JS, "utf8");
|
||||
const botEjs = fs.readFileSync(BOT_EJS, "utf8");
|
||||
const botCss = fs.readFileSync(BOT_CSS, "utf8");
|
||||
|
||||
const PROGRESS_PREDICATE =
|
||||
"if (progressPopup && progressPopup.style.display === 'block') { closeProgressPopup(); return; }";
|
||||
const ESC_UPLOADER_BRANCH =
|
||||
"if (urlUploaderModal && urlUploaderModal.classList.contains('show')) { closeUrlUploaderModal(); return; }";
|
||||
|
||||
function escapeChainWindow() {
|
||||
const at = botSrc.indexOf(PROGRESS_PREDICATE);
|
||||
assert.notStrictEqual(at, -1, "the Esc chain must still contain the progressPopup check");
|
||||
const handlerStart = botSrc.lastIndexOf("if (e.key === 'Escape') {", at);
|
||||
assert.notStrictEqual(handlerStart, -1, "progressPopup check must live inside an Escape branch");
|
||||
// Brace-match the whole Escape branch instead of slicing a fixed length:
|
||||
// a fixed slice would start failing spuriously once the chain grew long
|
||||
// enough to push its later branches past the cut.
|
||||
const open = botSrc.indexOf("{", handlerStart);
|
||||
let depth = 0;
|
||||
for (let i = open; i < botSrc.length; i++) {
|
||||
if (botSrc[i] === "{") depth++;
|
||||
else if (botSrc[i] === "}") {
|
||||
depth--;
|
||||
if (depth === 0) return botSrc.slice(handlerStart, i + 1);
|
||||
}
|
||||
}
|
||||
assert.fail("could not find the end of the Escape branch");
|
||||
}
|
||||
|
||||
function urlUploaderSection() {
|
||||
const start = botSrc.indexOf("// ============= URL Uploader =============");
|
||||
assert.notStrictEqual(start, -1, "the URL Uploader section must still exist");
|
||||
const end = botSrc.indexOf("// ============= /URL Uploader =============", start);
|
||||
assert.notStrictEqual(end, -1, "the URL Uploader section must still be terminated");
|
||||
return botSrc.slice(start, end);
|
||||
}
|
||||
|
||||
function startUrlUploadBody() {
|
||||
const section = urlUploaderSection();
|
||||
const at = section.indexOf("async function startUrlUpload()");
|
||||
assert.notStrictEqual(at, -1, "startUrlUpload must still exist");
|
||||
const end = section.indexOf("if (urlUploaderBtn) {", at);
|
||||
assert.notStrictEqual(end, -1, "the URL-uploader bindings after startUrlUpload must still exist");
|
||||
return section.slice(at, end);
|
||||
}
|
||||
|
||||
function uploadFilesSequentialBody() {
|
||||
const at = botSrc.indexOf("async function uploadFilesSequential(");
|
||||
assert.notStrictEqual(at, -1, "uploadFilesSequential must still exist");
|
||||
const end = botSrc.indexOf("function normalizeInput(raw)", at);
|
||||
assert.notStrictEqual(end, -1, "the function after uploadFilesSequential must still exist");
|
||||
return botSrc.slice(at, end);
|
||||
}
|
||||
|
||||
function functionBody(name, args) {
|
||||
const marker = `function ${name}(${args})`;
|
||||
const at = botSrc.indexOf(marker);
|
||||
assert.notStrictEqual(at, -1, `${name} must still exist`);
|
||||
// Brace-match the body: these functions contain nested blocks, so slicing
|
||||
// to the first '}' would truncate them.
|
||||
const open = botSrc.indexOf("{", at);
|
||||
let depth = 0;
|
||||
for (let i = open; i < botSrc.length; i++) {
|
||||
if (botSrc[i] === "{") depth++;
|
||||
else if (botSrc[i] === "}") {
|
||||
depth--;
|
||||
if (depth === 0) return botSrc.slice(at, i + 1);
|
||||
}
|
||||
}
|
||||
assert.fail(`could not find the end of ${name}`);
|
||||
}
|
||||
|
||||
test("an upload refresh preserves a Files navigation that is still loading", async () => {
|
||||
assert.match(uploadFilesSequentialBody(), /\bloadExplorer\(\)/);
|
||||
const start = botSrc.indexOf("let explorerLoadGeneration = 0;");
|
||||
const end = botSrc.indexOf("if (selectAllToggle)", start);
|
||||
assert.ok(start >= 0 && end > start);
|
||||
const requests = [];
|
||||
const rendered = [];
|
||||
const entriesEl = {};
|
||||
const selected = new Set(["old/example.txt"]);
|
||||
let renameResets = 0;
|
||||
const noop = () => {};
|
||||
const load = vm.runInNewContext(`let currentPath = "old"; ${botSrc.slice(start, end)}; loadExplorer;`, {
|
||||
apiExplore: (folder) => new Promise((resolve, reject) => requests.push({ folder, resolve, reject })),
|
||||
renderFileBreadcrumb: (folder) => rendered.push(folder),
|
||||
hasPerm: () => true,
|
||||
entriesEl,
|
||||
normalizeExplorerEntry: noop,
|
||||
compareExplorerEntries: noop,
|
||||
cancelActiveInlineRename: () => { renameResets++; },
|
||||
clearSelection: () => selected.clear(),
|
||||
console: { error: noop },
|
||||
escapeHtml: String,
|
||||
taskStartupSelect: null,
|
||||
});
|
||||
|
||||
const navigation = load("new");
|
||||
const refresh = load();
|
||||
assert.deepStrictEqual(requests.map(({ folder }) => folder), ["new", "new"]);
|
||||
requests[1].resolve({ path: "new" });
|
||||
await refresh;
|
||||
assert.strictEqual(selected.size, 0);
|
||||
selected.add("new/example.txt");
|
||||
requests[0].resolve({ path: "old" });
|
||||
assert.strictEqual(await navigation, null);
|
||||
assert.deepStrictEqual(rendered, ["new"]);
|
||||
assert.strictEqual(selected.size, 1);
|
||||
assert.strictEqual(renameResets, 1);
|
||||
|
||||
const unavailable = load("unavailable");
|
||||
requests[2].reject(new Error("folder unavailable"));
|
||||
await unavailable;
|
||||
assert.match(entriesEl.innerHTML, /folder unavailable/);
|
||||
assert.strictEqual(selected.size, 0);
|
||||
assert.strictEqual(renameResets, 2);
|
||||
});
|
||||
|
||||
test("the browser checks per-file size but does not reject from a stale disk snapshot", () => {
|
||||
const validate = vm.runInNewContext(`${functionBody("validateUploadCandidate", "file")} validateUploadCandidate;`, {
|
||||
NODE_MAX_UPLOAD_BYTES: 1024,
|
||||
finiteUploadNumber: Number,
|
||||
formatBytes: String,
|
||||
SERVER_DISK_LIMIT_BYTES: 1024,
|
||||
SERVER_DISK_USED_BYTES: 1024,
|
||||
getKnownReplacementBytes: () => 0,
|
||||
});
|
||||
assert.doesNotThrow(() => validate({ name: "same.txt", size: 1024 }));
|
||||
assert.throws(() => validate({ name: "same.txt", size: 1025 }), /max single-file upload size/);
|
||||
});
|
||||
|
||||
test("both mini uploaders require the latest destination listing to succeed", async () => {
|
||||
for (const [inputName, loadName, pathName, render] of [
|
||||
["miniFmUpload", "miniFmLatestLoad", "miniFmPath", "renderMiniFm"],
|
||||
["imgViewerMiniFmUpload", "imgViewerLatestLoad", "imgViewerMiniFmPath", "renderImgViewerMiniFm"],
|
||||
]) {
|
||||
const start = botSrc.indexOf(`if (${inputName}) {\n ${inputName}.addEventListener('change'`);
|
||||
const end = botSrc.indexOf("\n }", start);
|
||||
assert.ok(start >= 0 && end > start);
|
||||
const uploads = [], alerts = [], renders = [];
|
||||
let run;
|
||||
const input = { files: [{ name: "fixture.txt" }], value: "fixture.txt", addEventListener: (_, listener) => { run = listener; } };
|
||||
const noop = () => {};
|
||||
const context = {
|
||||
[inputName]: input, [loadName]: Promise.resolve(false), [pathName]: "old", [render]: (folder) => renders.push(folder),
|
||||
hasPerm: () => true, fileListHasDirectory: () => false,
|
||||
uploadBatchActive: false, urlUploadInFlight: false, popupClose: null,
|
||||
alert: (message) => alerts.push(message),
|
||||
apiUploadWithProgress: async (file, folder) => { uploads.push([file.name, folder]); },
|
||||
showProgressWheel: noop, initUploadProgressList: noop, updateUploadProgressList: noop,
|
||||
setProgress: noop, loadExplorer: noop, scheduleProgressWheelHide: noop, flashFilesBar: noop,
|
||||
setTimeout: (callback) => callback(),
|
||||
};
|
||||
vm.runInNewContext(`${uploadFilesSequentialBody()}\n${botSrc.slice(start, end + 4)}`, context);
|
||||
await run();
|
||||
assert.deepStrictEqual(uploads, []);
|
||||
assert.deepStrictEqual(renders, []);
|
||||
assert.match(alerts[0], /Could not load the upload destination/);
|
||||
assert.strictEqual(input.value, "");
|
||||
|
||||
let finishStale;
|
||||
context[loadName] = new Promise((resolve) => { finishStale = resolve; });
|
||||
const pending = run();
|
||||
context[pathName] = "new";
|
||||
context[loadName] = Promise.resolve(true);
|
||||
finishStale(false);
|
||||
await pending;
|
||||
assert.deepStrictEqual(uploads, [["fixture.txt", "new"]]);
|
||||
assert.deepStrictEqual(renders, ["new"]);
|
||||
}
|
||||
});
|
||||
|
||||
test("both Unarchive controls offer the daemon's supported archive suffixes", () => {
|
||||
const filter = botSrc.match(/const EXPLORER_ARCHIVE_EXTENSION = .*;/);
|
||||
assert.ok(filter);
|
||||
assert.strictEqual([...botSrc.matchAll(/EXPLORER_ARCHIVE_EXTENSION\.test\(/g)].length, 2);
|
||||
const supported = vm.runInNewContext(`${filter[0]} EXPLORER_ARCHIVE_EXTENSION;`);
|
||||
const daemonSrc = fs.readFileSync(path.join(ROOT, "main.go"), "utf8");
|
||||
const detectArchiveType = daemonSrc.match(/^func detectArchiveType\(.*?^}/ms);
|
||||
assert.ok(detectArchiveType);
|
||||
const suffixes = [...detectArchiveType[0].matchAll(/strings\.HasSuffix\(l, "([^"]+)"\)/g)];
|
||||
assert.ok(suffixes.length);
|
||||
for (const [, suffix] of suffixes) {
|
||||
assert.ok(supported.test(`example${suffix.toUpperCase()}`), suffix);
|
||||
}
|
||||
for (const suffix of [".bz2", ".gz", ".xz", ".jar", ".zip.txt"]) {
|
||||
assert.ok(!supported.test(`example${suffix}`), suffix);
|
||||
}
|
||||
});
|
||||
|
||||
test("SVG previews use an image data URL and reject oversized decoded content", async () => {
|
||||
const image = { removeAttribute: () => { image.src = undefined; } };
|
||||
const classes = new Set();
|
||||
const svg = '<svg xmlns="http://www.w3.org/2000/svg"/>';
|
||||
const show = vm.runInNewContext(`let imgViewerSvgRequest = null; async ${functionBody("showImgViewerImage", "rel")} showImgViewerImage;`, {
|
||||
imgViewerImage: image,
|
||||
imgViewerConfirm: null,
|
||||
imgViewerCanvas: {
|
||||
classList: { add: (name) => classes.add(name), remove: (...names) => names.forEach((name) => classes.delete(name)) },
|
||||
},
|
||||
IMG_VIEWER_SVG_LIMIT: 128,
|
||||
buildFileViewUrl: (name) => name,
|
||||
AbortController, Blob, TransformStream, DecompressionStream,
|
||||
fetch: async (name) => new Response(gzipSync(name === "valid.svgz" ? svg : " ".repeat(129))),
|
||||
FileReader: class {
|
||||
async readAsDataURL(blob) {
|
||||
this.result = `data:${blob.type};base64,${Buffer.from(await blob.arrayBuffer()).toString("base64")}`;
|
||||
this.onload();
|
||||
}
|
||||
},
|
||||
});
|
||||
await show("valid.svgz");
|
||||
assert.strictEqual(image.src, `data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`);
|
||||
await show("large.svgz");
|
||||
assert.strictEqual(image.src, undefined);
|
||||
assert.ok(classes.has("error"));
|
||||
});
|
||||
|
||||
// ---------- Finding 7: Esc must close the uploader, never the Files page ----------
|
||||
|
||||
test("Esc closes the URL uploader before any page it stacks above", () => {
|
||||
const chain = escapeChainWindow();
|
||||
|
||||
// The uploader is an .activity-modal (z-index 100000) opened on top of the
|
||||
// Files page (a .modal-overlay at z-index 10000) without closing it, so its
|
||||
// branch must sit after the other z-100000 overlays and before the
|
||||
// modal-overlay pages — editorModal and filesModal in particular.
|
||||
const order = [
|
||||
["progressPopup", PROGRESS_PREDICATE],
|
||||
["imageViewerModal", "if (imageViewerModal && imageViewerModal.classList.contains('show')) { closeImageViewer(); return; }"],
|
||||
["aiHelpModal", "if (aiHelpModal && isPageOpen(aiHelpModal)) { closeAiHelpModal(); return; }"],
|
||||
["urlUploaderModal", ESC_UPLOADER_BRANCH],
|
||||
["editorModal", "if (editorModal && editorModal.classList.contains('show')) { closeEditorModal(); return; }"],
|
||||
["filesModal", "if (filesModal && isPageOpen(filesModal)) { closeFilesModal(); return; }"],
|
||||
["taskModal", "if (taskModal && taskModal.classList.contains('show')) { closeTaskModal(); return; }"],
|
||||
];
|
||||
let prev = -1;
|
||||
for (const [name, predicate] of order) {
|
||||
const at = chain.indexOf(predicate);
|
||||
assert.notStrictEqual(at, -1, `the Esc chain must still handle ${name}`);
|
||||
assert.ok(at > prev, `${name} must be checked after the element before it (the uploader stacks above the pages, Esc must hit the dialog first)`);
|
||||
prev = at;
|
||||
}
|
||||
});
|
||||
|
||||
test("no pre-existing Esc handler was dropped by the insertion", () => {
|
||||
const chain = escapeChainWindow();
|
||||
// closeInfoModal() is intentionally absent: the info modal (element,
|
||||
// declaration and open/close handlers) was removed from bot.ejs/bot.js, and
|
||||
// its leftover Esc branch referenced the now-undeclared infoModal
|
||||
// identifier — an uncaught ReferenceError on every Esc that reached it.
|
||||
for (const closer of [
|
||||
"closeProgressPopup()", "closeImageViewer()", "closeAiHelpModal()", "closeUrlUploaderModal()",
|
||||
"closeEditorModal()", "closeFilesModal()", "closeTaskModal()",
|
||||
"closeModrinthPluginModal()", "closeStoreModal()", "closeActivityModal()", "closeBackupsModal()",
|
||||
"closeBackupCreateModal()", "closeResourceStatsPopup()",
|
||||
]) {
|
||||
assert.ok(chain.includes(closer), `Esc chain lost a handler: ${closer}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the uploader's 'Close (Esc)' close button is discharged by the same closer Esc now routes to", () => {
|
||||
// The template promises Esc on the X button; that promise is only honest if
|
||||
// both the click binding and the keydown branch land on closeUrlUploaderModal.
|
||||
assert.ok(
|
||||
botEjs.includes('<button class="activity-close" id="urlUploaderClose" title="Close (Esc)">'),
|
||||
'bot.ejs must keep the "Close (Esc)" close button the Esc chain now honors'
|
||||
);
|
||||
assert.ok(
|
||||
botSrc.includes("if (urlUploaderClose) urlUploaderClose.addEventListener('click', closeUrlUploaderModal);"),
|
||||
"the close button must stay bound to closeUrlUploaderModal"
|
||||
);
|
||||
assert.ok(
|
||||
botSrc.includes(ESC_UPLOADER_BRANCH),
|
||||
"the Esc branch must close the dialog via closeUrlUploaderModal"
|
||||
);
|
||||
});
|
||||
|
||||
test("stacking rationale: .activity-modal renders above the .modal-overlay pages the uploader opens over", () => {
|
||||
// The uploader-before-pages order is correct only while this z-relationship
|
||||
// holds. Pin the numbers so a restyle that changes stacking forces a
|
||||
// re-derivation of the Esc order too.
|
||||
const activityBlock = botCss.slice(botCss.indexOf(".activity-modal {"), botCss.indexOf("}", botCss.indexOf(".activity-modal {")));
|
||||
const activityZ = parseInt((activityBlock.match(/z-index:\s*(\d+)/) || [])[1], 10);
|
||||
assert.ok(Number.isFinite(activityZ), "the first .activity-modal { rule in bot.css no longer carries a z-index — re-point this lookup at the rule that does before trusting the Esc order");
|
||||
assert.equal(activityZ, 100000, ".activity-modal z-index drifted — re-derive the uploader's Esc precedence if it is no longer top-most");
|
||||
|
||||
const overlayBlock = botCss.slice(botCss.indexOf(".modal-overlay {"), botCss.indexOf("}", botCss.indexOf(".modal-overlay {")));
|
||||
const overlayZ = parseInt((overlayBlock.match(/z-index:\s*(\d+)/) || [])[1], 10);
|
||||
assert.ok(Number.isFinite(overlayZ), "the first .modal-overlay { rule in bot.css no longer carries a z-index — re-point this lookup at the rule that does before trusting the Esc order");
|
||||
assert.ok(
|
||||
activityZ > overlayZ,
|
||||
`.activity-modal (${activityZ}) must stack above .modal-overlay (${overlayZ}) — the uploader branch must precede the page branches`
|
||||
);
|
||||
});
|
||||
|
||||
// ---------- Finding 8: re-entrancy, close-animation window, batch exclusion ----------
|
||||
|
||||
test("URL upload uses the folder shown when the dialog opened", async () => {
|
||||
const start = botSrc.indexOf("const urlUploaderBtn = document.getElementById('urlUploaderBtn');");
|
||||
const end = botSrc.indexOf("if (urlUploaderBtn) {", start);
|
||||
assert.ok(start >= 0 && end > start);
|
||||
for (const remote of [false, true]) {
|
||||
const elements = {
|
||||
urlUploaderModal: { classList: { contains: () => false } },
|
||||
urlUploaderInput: {},
|
||||
urlUploaderTargetPath: {},
|
||||
};
|
||||
const requests = [];
|
||||
const noop = () => {};
|
||||
const context = {
|
||||
document: { getElementById: (id) => elements[id] },
|
||||
currentPath: "visible/folder",
|
||||
REMOTE_MODE: remote, NODE_API_BASE: "/api/nodes/server/fixture", bot: "fixture",
|
||||
URL, hasPerm: () => true, uploadBatchActive: false, progressWheelOwner: null,
|
||||
alert: assert.fail, setTimeout: noop, showModalElement: noop, animateClose: noop,
|
||||
showProgressWheel: noop, startSimulatedProgress: noop, setProgress: noop,
|
||||
hideProgressWheel: noop, scheduleProgressWheelHide: noop, flashFilesBar: noop,
|
||||
loadExplorer: noop, ensureServerActionToken: async () => "fixture-token",
|
||||
fetch: async (endpoint, options) => {
|
||||
requests.push([endpoint, JSON.parse(options.body).path]);
|
||||
return { ok: true, json: async () => ({ ok: true }) };
|
||||
},
|
||||
};
|
||||
const submit = vm.runInNewContext(`${botSrc.slice(start, end)}; openUrlUploaderModal(); startUrlUpload;`, context);
|
||||
assert.strictEqual(elements.urlUploaderTargetPath.textContent, "/visible/folder");
|
||||
context.currentPath = "new/folder";
|
||||
elements.urlUploaderInput.value = "https://example.test/fixture.txt";
|
||||
await submit();
|
||||
assert.deepStrictEqual(requests, [[remote ? "/api/nodes/server/fixture/upload-url" : "/upload-url", "visible/folder"]]);
|
||||
}
|
||||
});
|
||||
|
||||
test("startUrlUpload refuses re-entry before doing anything else", () => {
|
||||
const body = startUrlUploadBody();
|
||||
const guard = body.indexOf("if (urlUploadInFlight) return;");
|
||||
const closingGuard = body.indexOf("urlUploaderModal.classList.contains('closing')");
|
||||
const perm = body.indexOf("hasPerm('files_upload')");
|
||||
const firstFetch = body.indexOf("fetch(");
|
||||
for (const [name, at] of [["in-flight guard", guard], [".closing guard", closingGuard], ["perm check", perm]]) {
|
||||
assert.notStrictEqual(at, -1, `startUrlUpload lost its ${name}`);
|
||||
assert.ok(at < firstFetch, `the ${name} must run before the POST is issued`);
|
||||
}
|
||||
assert.ok(guard < closingGuard, "the in-flight guard must be the first statement (the Enter key reaches the handler with no disabled button to stop it)");
|
||||
assert.ok(closingGuard < perm, "the .closing guard must precede any work: the dialog stays in the DOM and focused for ~360ms of close animation after a submit");
|
||||
});
|
||||
|
||||
test("the in-flight flag is set only after validation and cleared on every settle path", () => {
|
||||
// Exactly one declaration: the guard must not be shadowable into a
|
||||
// per-call variable that fails to exclude the batch path.
|
||||
assert.equal(
|
||||
botSrc.split("let urlUploadInFlight").length - 1, 1,
|
||||
"urlUploadInFlight must be declared exactly once (module-closure scope, no shadowing)"
|
||||
);
|
||||
|
||||
const body = startUrlUploadBody();
|
||||
const validate = body.indexOf("normalizeUserUrl(urlUploaderInput.value)");
|
||||
const set = body.indexOf("urlUploadInFlight = true;");
|
||||
const closeModal = body.indexOf("closeUrlUploaderModal();");
|
||||
assert.notStrictEqual(set, -1, "startUrlUpload must set the flag");
|
||||
assert.ok(set > validate, "the flag must be set only after URL validation passes — a failed validation must not latch the flag and refuse every future attempt");
|
||||
assert.ok(set < closeModal, "the flag must be set before the dialog starts closing");
|
||||
|
||||
// Cleared in finally, not in the failure branches only: the two failure
|
||||
// paths return from inside the try, and success must clear the flag too so
|
||||
// uploadFilesSequential is unblocked the moment the request settles.
|
||||
assert.equal(body.split("urlUploadInFlight = false;").length - 1, 1, "the flag must be cleared in exactly one place");
|
||||
const finallyAt = body.indexOf("} finally {");
|
||||
const clearAt = body.indexOf("urlUploadInFlight = false;");
|
||||
assert.notStrictEqual(finallyAt, -1, "the flag reset must live in a finally block");
|
||||
assert.ok(clearAt > finallyAt, "the flag reset must live in the finally block (covers both failure returns and success)");
|
||||
});
|
||||
|
||||
test("startUrlUpload refuses to start while a file batch owns the progress wheel", () => {
|
||||
const body = startUrlUploadBody();
|
||||
const batchGuard = body.indexOf("if (uploadBatchActive) {");
|
||||
const showWheel = body.indexOf("showProgressWheel(2, baseMsg)");
|
||||
assert.notStrictEqual(batchGuard, -1, "startUrlUpload must check uploadBatchActive");
|
||||
assert.notStrictEqual(showWheel, -1, "startUrlUpload must still show the progress wheel");
|
||||
assert.ok(batchGuard < showWheel, "the batch guard must run before showProgressWheel, which would wipe the batch's per-file progress list");
|
||||
// Refusal keeps the dialog open and shows the reason in it — not an alert
|
||||
// after the dialog has already closed.
|
||||
const guardBlock = body.slice(batchGuard, body.indexOf("}", batchGuard));
|
||||
assert.match(guardBlock, /setUrlUploaderError\(/, "the refusal must surface inside the still-open dialog via setUrlUploaderError");
|
||||
assert.ok(guardBlock.indexOf("closeUrlUploaderModal") === -1, "the refusal must not close the dialog");
|
||||
});
|
||||
|
||||
test("uploadFilesSequential refuses to start while a URL upload is in flight", () => {
|
||||
const body = uploadFilesSequentialBody();
|
||||
const batchGuard = body.indexOf("if (uploadBatchActive) {");
|
||||
const urlGuard = body.indexOf("if (urlUploadInFlight) {");
|
||||
const showWheel = body.indexOf("showProgressWheel(0,");
|
||||
assert.notStrictEqual(batchGuard, -1, "the existing uploadBatchActive guard must survive");
|
||||
assert.notStrictEqual(urlGuard, -1, "uploadFilesSequential must check urlUploadInFlight — the reverse race (batch started mid-URL-upload) clobbers the URL wheel and the URL completion path aborts the batch XHR");
|
||||
assert.notStrictEqual(showWheel, -1, "uploadFilesSequential must still show the progress wheel");
|
||||
assert.ok(urlGuard > batchGuard, "the URL-upload guard belongs next to the batch guard");
|
||||
assert.ok(urlGuard < showWheel, "the guard must run before showProgressWheel clobbers the URL upload's wheel");
|
||||
});
|
||||
|
||||
test("the Enter key and the confirm button route through the same guarded handler (no second request path)", () => {
|
||||
const section = urlUploaderSection();
|
||||
// One definition, and exactly the two known bindings route to it (confirm
|
||||
// click + input Enter). A new call site or a second fetch in this section
|
||||
// would be a request path that bypasses the guards.
|
||||
assert.equal(section.split("async function startUrlUpload()").length - 1, 1, "startUrlUpload must have exactly one definition");
|
||||
assert.equal(section.split("fetch(").length - 1, 1, "the URL-uploader section must contain exactly one fetch call — the guarded one in startUrlUpload");
|
||||
assert.ok(
|
||||
section.includes("urlUploaderConfirm.addEventListener('click', startUrlUpload);"),
|
||||
"the confirm button must keep routing through the guarded startUrlUpload"
|
||||
);
|
||||
const enterBinding = section.indexOf("urlUploaderInput.addEventListener('keydown'");
|
||||
assert.notStrictEqual(enterBinding, -1, "the input's Enter binding must survive");
|
||||
assert.ok(section.slice(enterBinding, enterBinding + 200).includes("startUrlUpload();"), "Enter must keep routing through the guarded startUrlUpload");
|
||||
});
|
||||
|
||||
test("the .closing guard depends on animateClose marking synchronously and showModalElement clearing it on reopen", () => {
|
||||
const animateClose = functionBody("animateClose", "el, onComplete");
|
||||
const addAt = animateClose.indexOf("el.classList.add('closing');");
|
||||
const timerAt = animateClose.indexOf("setTimeout(finish, 360)");
|
||||
assert.notStrictEqual(addAt, -1, "animateClose must mark the dialog with .closing");
|
||||
assert.notStrictEqual(timerAt, -1, "animateClose must keep its 360ms fallback timer");
|
||||
assert.ok(timerAt > addAt, ".closing must be added synchronously, before the fallback timer is armed — the double-submit window must open the moment a submit closes the dialog");
|
||||
|
||||
const showModal = functionBody("showModalElement", "el, display = 'flex'");
|
||||
assert.ok(
|
||||
showModal.includes("el.classList.remove('closing');"),
|
||||
"showModalElement must clear .closing on reopen — otherwise a refused dialog could never submit again"
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user