Error pages: 404, 403, crash and server-rendered pages in the app's style
In the app: an unknown address shows a 404 inside the menu with the address, "Maybe you were looking for" suggestions (misspellings, partial names, moved pages) and a Ctrl+K search button; a page the role can't open shows a 403 "No access"; a render crash is caught by an error boundary (menu stays, clears on navigation, outer boundary for the sign-in and wall); missing servers, incidents and dead status links use the same page. On the server: unknown /api, /auth, /agent and /metrics addresses and missing files now get a JSON 404 instead of the app's front page with a 200; browsers get self-contained 404, 500 and sign-in-failed pages in the sign-in card's look, light or dark, English or Swedish. Swedish translations added. Tests in server/test/errorPages.test.ts. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b8ce337dfb
commit
8ffae62281
16 files changed
+662
-31
No files matched your search
+11
-1
@@ -95,6 +95,7 @@ import { alertsBulkRouter, inventoryBulkRouter, serversBulkRouter } from "./rout
|
||||
import { publicCalendarRouter } from "./routes/publicCalendar.js";
|
||||
import { heartbeatPingRouter } from "./routes/heartbeatPing.js";
|
||||
import { apiErrorHandler } from "./utils/apiErrorHandler.js";
|
||||
import { notFoundHandler } from "./utils/errorPage.js";
|
||||
import { securityHeaders } from "./utils/securityHeaders.js";
|
||||
import { sameOriginGuard } from "./utils/sameOriginGuard.js";
|
||||
|
||||
@@ -102,6 +103,9 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
|
||||
const webDist = join(__dirname, "..", "..", "web", "dist");
|
||||
const agentDir = join(__dirname, "..", "..", "agent");
|
||||
|
||||
/** The addresses the server answers itself (the API, sign-in, the agent files, the metrics): never one of the app's pages. */
|
||||
const isServerPath = (path: string) => /^\/(api|auth|agent|metrics)(\/|$)/.test(path);
|
||||
|
||||
/**
|
||||
* The whole web application, ready to listen. It lives apart from index.ts (which also runs migrations and starts the
|
||||
* schedulers) so the tests can run the real thing — the order of the middleware below is part of what they check.
|
||||
@@ -249,9 +253,15 @@ export function createApp() {
|
||||
|
||||
if (existsSync(webDist)) {
|
||||
app.use(express.static(webDist));
|
||||
app.get("*", (_req, res) => res.sendFile(join(webDist, "index.html")));
|
||||
// Every page of the app is drawn by the app, so an address that is one of its pages gets index.html. What is not one — the server's own namespaces, and anything that names a file (a script
|
||||
// or an image that isn't there) — must not be answered with a page and a 200: it falls through to the 404 below.
|
||||
app.get("*", (req, res, next) => {
|
||||
if (isServerPath(req.path) || /\.[a-z0-9]+$/i.test(req.path)) return next();
|
||||
res.sendFile(join(webDist, "index.html"));
|
||||
});
|
||||
}
|
||||
|
||||
app.use(notFoundHandler);
|
||||
app.use(apiErrorHandler);
|
||||
return app;
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import { recordAudit } from "../services/audit.js";
|
||||
import { verifyIdTokenSignature } from "./idToken.js";
|
||||
import { rateLimit } from "../utils/rateLimit.js";
|
||||
import { pictureFromClaims } from "../services/avatars.js";
|
||||
import { sendErrorPage } from "../utils/errorPage.js";
|
||||
|
||||
export const authRouter = Router();
|
||||
|
||||
@@ -19,14 +20,6 @@ export const authRouter = Router();
|
||||
// audit log, so without a limit one script could fill the disk and the log.
|
||||
const signInLimiter = rateLimit({ windowMs: 60_000, max: 20, message: "Too many sign-in attempts. Wait a minute and try again." });
|
||||
|
||||
const SIGN_IN_FAILED_PAGE = `<!doctype html>
|
||||
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Sign-in failed</title></head>
|
||||
<body style="font-family: system-ui, sans-serif; max-width: 32rem; margin: 4rem auto; padding: 0 1rem; line-height: 1.5">
|
||||
<h1>Sign-in failed</h1>
|
||||
<p>Something went wrong while signing you in. <a href="/auth/login">Try again</a>.</p>
|
||||
<p>If it keeps failing, ask an administrator to look at the audit log.</p>
|
||||
</body></html>`;
|
||||
|
||||
/**
|
||||
* A sign-in that didn't work: the person gets a plain explanation (never the reason — that tells an attacker what to adjust),
|
||||
* and the reason goes to the server log and, unless it's just a stale page, the audit log.
|
||||
@@ -47,7 +40,7 @@ async function failSignIn(req: Request, res: Response, reason: string, err?: unk
|
||||
}
|
||||
}
|
||||
delete req.session.pendingAuth; // a failed attempt's state and verifier can't be tried again
|
||||
res.status(400).type("html").send(SIGN_IN_FAILED_PAGE);
|
||||
sendErrorPage(req, res, 400, "sign_in_failed");
|
||||
}
|
||||
|
||||
authRouter.get("/login", signInLimiter, async (req, res, next) => {
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import type { NextFunction, Request, Response } from "express";
|
||||
import { sendErrorPage, wantsPage } from "./errorPage.js";
|
||||
|
||||
/**
|
||||
* The app's last-resort error handler. A body that's too large or isn't valid JSON is the caller's doing, so it's answered
|
||||
* as such (413 / 400) rather than as a server error — an agent whose report is too big then sees "payload_too_large", not a
|
||||
* vague 500.
|
||||
*/
|
||||
export function apiErrorHandler(err: unknown, _req: Request, res: Response, _next: NextFunction) {
|
||||
export function apiErrorHandler(err: unknown, req: Request, res: Response, _next: NextFunction) {
|
||||
const status = (err as { status?: unknown } | null)?.status;
|
||||
if (status === 413) return res.status(413).json({ error: "payload_too_large" });
|
||||
if (status === 400 && (err as { type?: unknown }).type === "entity.parse.failed") return res.status(400).json({ error: "invalid_json" });
|
||||
console.error(err);
|
||||
if (wantsPage(req)) return sendErrorPage(req, res, 500, "server_error");
|
||||
res.status(500).json({ error: "internal_error" });
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* The pages the server itself answers with when the app can't: a path that is nothing (outside the app's own routes — those the app draws), a failure while answering a browser, a sign-in
|
||||
* that didn't work. Self-contained (no script bundle to load — it may be the bundle that is missing) and made to look like the sign-in page: the card, the logo, the app's colours, light or
|
||||
* dark as the person last chose. English or Swedish, from the browser's language.
|
||||
*/
|
||||
import type { Request, Response, NextFunction } from "express";
|
||||
|
||||
export type ErrorPageKind = "not_found" | "server_error" | "sign_in_failed";
|
||||
|
||||
const TEXT = {
|
||||
en: {
|
||||
not_found: { title: "Page not found", message: "There is nothing at this address. The link may be old, or the page may have moved." },
|
||||
server_error: { title: "Something went wrong", message: "The server couldn't answer that. Try again in a moment; if it keeps happening, the server log has the details." },
|
||||
sign_in_failed: { title: "Sign-in failed", message: "Something went wrong while signing you in. If it keeps failing, ask an administrator to look at the audit log." },
|
||||
home: "Go to the dashboard",
|
||||
retry: "Try again",
|
||||
},
|
||||
sv: {
|
||||
not_found: { title: "Sidan hittades inte", message: "Det finns inget på den här adressen. Länken kan vara gammal, eller så har sidan flyttats." },
|
||||
server_error: { title: "Något gick fel", message: "Servern kunde inte svara på det. Försök igen om en stund; om det fortsätter finns detaljerna i serverloggen." },
|
||||
sign_in_failed: { title: "Inloggningen misslyckades", message: "Något gick fel när du loggades in. Om det fortsätter, be en administratör titta i granskningsloggen." },
|
||||
home: "Gå till översikten",
|
||||
retry: "Försök igen",
|
||||
},
|
||||
} as const;
|
||||
|
||||
type Language = keyof typeof TEXT;
|
||||
|
||||
const CODE: Record<ErrorPageKind, string> = { not_found: "404", server_error: "500", sign_in_failed: "!" };
|
||||
|
||||
const escapeHtml = (s: string) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]!);
|
||||
|
||||
/** Swedish when that is the browser's first choice, else English. */
|
||||
export function pickLanguage(acceptLanguage: string | undefined): Language {
|
||||
return /^\s*sv\b/i.test(acceptLanguage ?? "") ? "sv" : "en";
|
||||
}
|
||||
|
||||
// The look of the sign-in page (web/src/styles.css), in the colours of Tabler's light and dark themes.
|
||||
const STYLE = `
|
||||
:root{color-scheme:light dark;--bg:#f6f8fb;--surface:#fff;--text:#182433;--muted:#667382;--primary:#066fd1;--shadow:0 1px 3px rgba(24,36,51,.12)}
|
||||
[data-bs-theme=dark]{--bg:#151f2c;--surface:#182433;--text:#dce1e7;--muted:#9aa4b2;--primary:#4299e1;--shadow:0 1px 3px rgba(0,0,0,.4)}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;min-height:100vh;display:flex;align-items:center;justify-content:center;padding:1rem;background:var(--bg);color:var(--text);font-family:system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",sans-serif;line-height:1.5}
|
||||
.card{width:100%;max-width:30rem;padding:2rem;text-align:center;background:var(--surface);border-radius:4px;box-shadow:var(--shadow)}
|
||||
.logo{display:block;width:100%;overflow:hidden;margin:-.5rem 0 .75rem}
|
||||
.logo img{display:block;width:122%;max-width:none;height:auto;margin:-16% -11%}
|
||||
.code{font-size:4.5rem;font-weight:700;line-height:1;color:var(--muted);opacity:.45}
|
||||
h1{margin:.75rem 0 .25rem;font-size:1.5rem}
|
||||
p{margin:0 0 1.5rem;color:var(--muted)}
|
||||
.actions{display:flex;flex-wrap:wrap;justify-content:center;gap:.5rem}
|
||||
a.btn{display:inline-block;padding:.4375rem 1rem;border:1px solid var(--primary);border-radius:4px;background:var(--primary);color:#fff;font-size:.875rem;text-decoration:none}
|
||||
a.btn.plain{background:transparent;color:var(--primary)}
|
||||
a.btn:focus-visible{outline:2px solid var(--primary);outline-offset:2px}
|
||||
`;
|
||||
|
||||
// The same choice of theme as the app's own page (web/index.html): what the person picked, else what their system prefers.
|
||||
const THEME_SCRIPT = `(function(){try{var s=localStorage.getItem("hlm-theme");var d=s==="light"||s==="dark"?s:matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";document.documentElement.setAttribute("data-bs-theme",d)}catch(e){}})()`;
|
||||
|
||||
export function errorPageHtml(kind: ErrorPageKind, language: Language = "en"): string {
|
||||
const text = TEXT[language];
|
||||
const { title, message } = text[kind];
|
||||
// A failed sign-in is tried again from the start; the others go home.
|
||||
const primary = kind === "sign_in_failed" ? `<a class="btn" href="/auth/login">${escapeHtml(text.retry)}</a>` : kind === "server_error" ? `<a class="btn" href="">${escapeHtml(text.retry)}</a>` : "";
|
||||
const home = `<a class="btn${primary ? " plain" : ""}" href="/">${escapeHtml(text.home)}</a>`;
|
||||
return `<!doctype html>
|
||||
<html lang="${language}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>${escapeHtml(title)} · Homelab Manager</title>
|
||||
<script>${THEME_SCRIPT}</script><style>${STYLE}</style></head>
|
||||
<body><main class="card">
|
||||
<span class="logo"><img src="/logo.webp" alt="Homelab Manager" width="901" height="460"></span>
|
||||
<div class="code" aria-hidden="true">${CODE[kind]}</div>
|
||||
<h1>${escapeHtml(title)}</h1>
|
||||
<p>${escapeHtml(message)}</p>
|
||||
<div class="actions">${primary}${home}</div>
|
||||
</main></body></html>`;
|
||||
}
|
||||
|
||||
/** Whether the one asking is a browser opening a page, rather than the app's own code (or a script) asking for data. */
|
||||
export function wantsPage(req: Request): boolean {
|
||||
return !req.path.startsWith("/api/") && req.accepts(["json", "html"]) === "html";
|
||||
}
|
||||
|
||||
/** Sends the page for `kind` with `status`, in the language the browser asks for. */
|
||||
export function sendErrorPage(req: Request, res: Response, status: number, kind: ErrorPageKind): void {
|
||||
res.status(status).type("html").send(errorPageHtml(kind, pickLanguage(req.headers["accept-language"])));
|
||||
}
|
||||
|
||||
/**
|
||||
* The last thing that answers: nothing above knew this path. An address in the app's own namespace (/api, /auth, /agent, /metrics), or from code that wants data, gets the plain JSON 404 the
|
||||
* rest of the API gives; a browser gets the page.
|
||||
*/
|
||||
export function notFoundHandler(req: Request, res: Response, _next: NextFunction): void {
|
||||
if (wantsPage(req)) return sendErrorPage(req, res, 404, "not_found");
|
||||
res.status(404).json({ error: "not_found", message: "No such address." });
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* The pages for what isn't there or went wrong: the server's own 404 and 500 pages and what decides whether a browser or the app's code is answered, that an address which is not a page
|
||||
* no longer gets the app's front page with a 200, and the app's own 404 / 403 / crash pages and the "maybe you were looking for" list.
|
||||
*
|
||||
* Run with: npm test --workspace server
|
||||
*/
|
||||
import { test, describe, before, after } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { AddressInfo } from "node:net";
|
||||
import type { Server } from "node:http";
|
||||
|
||||
const dir = mkdtempSync(join(tmpdir(), "hm-errorpages-"));
|
||||
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
||||
process.env.SESSION_DIR = join(dir, "sessions");
|
||||
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
||||
|
||||
const { createApp } = await import("../src/app.js");
|
||||
const { errorPageHtml, pickLanguage } = await import("../src/utils/errorPage.js");
|
||||
const { suggestPages, distance } = await import("../../web/src/utils/pageSuggestions.js");
|
||||
|
||||
const WEB = new URL("../../web/src/", import.meta.url);
|
||||
const read = (path: string) => readFileSync(new URL(path, WEB), "utf8");
|
||||
|
||||
describe("the page the server answers with", () => {
|
||||
test("says what happened, looks like the sign-in page, and leads home", () => {
|
||||
const html = errorPageHtml("not_found");
|
||||
assert.match(html, /<title>Page not found · Homelab Manager<\/title>/);
|
||||
assert.match(html, />404</);
|
||||
assert.match(html, /src="\/logo\.webp"/);
|
||||
assert.match(html, /href="\/">Go to the dashboard</);
|
||||
assert.match(html, /hlm-theme/, "the theme the person chose in the app");
|
||||
assert.doesNotMatch(html, /href="\/auth\/login"/);
|
||||
});
|
||||
|
||||
test("a failed sign-in offers to try again, a failure offers the same page again, neither says why", () => {
|
||||
assert.match(errorPageHtml("sign_in_failed"), /href="\/auth\/login">Try again</);
|
||||
assert.match(errorPageHtml("server_error"), /href="">Try again</);
|
||||
assert.doesNotMatch(errorPageHtml("sign_in_failed"), /ECONN|stack|Error:/);
|
||||
});
|
||||
|
||||
test("is in Swedish for a browser that asks for it, and the language is the first one asked for", () => {
|
||||
assert.equal(pickLanguage("sv-SE,sv;q=0.9,en;q=0.8"), "sv");
|
||||
assert.equal(pickLanguage("sv"), "sv");
|
||||
assert.equal(pickLanguage("en-GB,en;q=0.9,sv;q=0.8"), "en");
|
||||
assert.equal(pickLanguage(undefined), "en");
|
||||
assert.equal(pickLanguage("svg"), "en");
|
||||
assert.match(errorPageHtml("not_found", "sv"), /Sidan hittades inte/);
|
||||
assert.match(errorPageHtml("not_found", "sv"), /<html lang="sv">/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("an address that is nothing", () => {
|
||||
let server: Server;
|
||||
let base = "";
|
||||
const get = (path: string, accept?: string, language?: string) => fetch(`${base}${path}`, { headers: { ...(accept ? { accept } : {}), ...(language ? { "accept-language": language } : {}) } });
|
||||
|
||||
before(async () => {
|
||||
server = await new Promise<Server>((resolve) => {
|
||||
const s = createApp().listen(0, "127.0.0.1", () => resolve(s));
|
||||
});
|
||||
base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
after(() => {
|
||||
server.close();
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Windows keeps the database file locked until the process exits.
|
||||
}
|
||||
});
|
||||
|
||||
test("under /api it is a JSON 404, for a browser as well — never the app's front page", async () => {
|
||||
for (const accept of [undefined, "application/json", "text/html,application/xhtml+xml,*/*;q=0.8"]) {
|
||||
const res = await get("/api/no-such-thing", accept);
|
||||
assert.equal(res.status, 404, String(accept));
|
||||
assert.match(res.headers.get("content-type") ?? "", /json/);
|
||||
assert.equal((await res.json()).error, "not_found");
|
||||
}
|
||||
});
|
||||
|
||||
test("the other addresses of the server's own (sign-in, the agent files, metrics) are not pages either", async () => {
|
||||
for (const path of ["/auth/no-such-thing", "/agent/no-such-file.sh", "/metrics/no-such-thing"]) {
|
||||
const res = await get(path, "application/json");
|
||||
assert.equal(res.status, 404, path);
|
||||
assert.equal((await res.json()).error, "not_found", path);
|
||||
}
|
||||
});
|
||||
|
||||
test("a browser opening one outside the app is given the page, in its language", async () => {
|
||||
const res = await get("/auth/no-such-thing", "text/html,application/xhtml+xml,*/*;q=0.8", "sv-SE,sv;q=0.9");
|
||||
assert.equal(res.status, 404);
|
||||
assert.match(res.headers.get("content-type") ?? "", /html/);
|
||||
assert.match(await res.text(), /Sidan hittades inte/);
|
||||
});
|
||||
|
||||
test("something that names a file which is not there is a 404, not the front page with a 200", async () => {
|
||||
const res = await get("/assets/no-such-file.js");
|
||||
assert.equal(res.status, 404);
|
||||
assert.doesNotMatch(await res.text(), /<div id="root">/);
|
||||
});
|
||||
|
||||
test("another method on an unknown address is a 404 too", async () => {
|
||||
const res = await fetch(`${base}/api/no-such-thing`, { method: "POST", headers: { "content-type": "application/json", origin: base }, body: "{}" });
|
||||
assert.ok([403, 404].includes(res.status), String(res.status));
|
||||
});
|
||||
|
||||
test("the app's own pages still get the app (it draws their 404 itself)", { skip: !existsSync(new URL("../../web/dist/index.html", import.meta.url)) }, async () => {
|
||||
for (const path of ["/", "/servers", "/servers/3", "/alerts/incidents/9", "/share/status/abc-DEF_123", "/no-such-page"]) {
|
||||
const res = await get(path, "text/html");
|
||||
assert.equal(res.status, 200, path);
|
||||
assert.match(await res.text(), /<div id="root">/, path);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("what the app draws for itself", () => {
|
||||
test("an unknown address is a 404 page inside the menu, at the top level and under Settings", () => {
|
||||
const app = read("App.tsx");
|
||||
assert.match(app, /<Route path="\*" element=\{<NotFound user=\{user\} \/>\} \/>\s*<\/Routes>/, "the end of the list of pages");
|
||||
assert.match(app, /<Route path="notifications"[\s\S]*<Route path="\*" element=\{<NotFound user=\{user\} \/>\} \/>\s*<\/Route>/, "under /settings");
|
||||
});
|
||||
|
||||
test("a page the role doesn't open is a 403 page, and a page that fails is caught so the menu stays", () => {
|
||||
const app = read("App.tsx");
|
||||
assert.match(app, /<ForbiddenPage minRole=/);
|
||||
assert.doesNotMatch(app, /alert-danger">\{t\("You don't have permission/);
|
||||
assert.match(app, /<ErrorBoundary resetKey=\{pathname\}>/);
|
||||
assert.match(read("main.tsx"), /<ErrorBoundary standalone>/, "and a crash outside the frame too");
|
||||
assert.match(read("components/ErrorPage.tsx"), /componentDidUpdate[\s\S]*prev\.resetKey !== this\.props\.resetKey/, "going to another page clears the failure");
|
||||
});
|
||||
|
||||
test("a server, an incident and a status link that are gone say so with the same page", () => {
|
||||
assert.match(read("pages/ServerDetail.tsx"), /404[\s\S]*<MissingPage title=\{t\("Server not found"\)\}/);
|
||||
assert.match(read("pages/IncidentDetail.tsx"), /<MissingPage title=\{t\("Incident not found"\)\}/);
|
||||
assert.match(read("pages/SharedStatus.tsx"), /<ErrorPage code="404" title=\{t\("This link doesn't work any more"\)\}/);
|
||||
});
|
||||
|
||||
test("the pages are styled", () => {
|
||||
const css = read("styles.css");
|
||||
for (const rule of [".error-page", ".error-code", ".error-title", ".error-actions", ".error-card"]) assert.ok(css.includes(rule), rule);
|
||||
});
|
||||
});
|
||||
|
||||
describe("maybe you were looking for", () => {
|
||||
const pages = [
|
||||
{ to: "/", label: "Dashboard" },
|
||||
{ to: "/servers", label: "Servers" },
|
||||
{ to: "/alerts", label: "Alerts" },
|
||||
{ to: "/network/devices", label: "Network devices" },
|
||||
{ to: "/settings", label: "Settings" },
|
||||
{ to: "/proxmox", label: "Proxmox" },
|
||||
{ to: "/uptime-kuma", label: "Uptime Kuma" },
|
||||
];
|
||||
const first = (path: string) => suggestPages(path, pages).map((p) => p.to);
|
||||
|
||||
test("a part of a name, a misspelling and a page that has moved are all recognised", () => {
|
||||
assert.deepEqual(first("/server"), ["/servers"]);
|
||||
assert.equal(first("/sevrers")[0], "/servers");
|
||||
assert.ok(!suggestPages("/sevrers", [...pages, { to: "/secrets", label: "Secrets" }]).some((p) => p.to === "/secrets"), "a different word two slips away is not a suggestion");
|
||||
assert.equal(first("/alert")[0], "/alerts");
|
||||
assert.equal(first("/settings/no-such-tab")[0], "/settings");
|
||||
assert.equal(first("/network/devicess")[0], "/network/devices");
|
||||
assert.equal(first("/uptimekuma")[0], "/uptime-kuma");
|
||||
assert.equal(first("/Proxmox/")[0], "/proxmox");
|
||||
});
|
||||
|
||||
test("a query or a fragment is not part of the address, and an address with nothing like it suggests nothing", () => {
|
||||
assert.equal(first("/servers?status=offline")[0], "/servers");
|
||||
assert.deepEqual(first("/zzzz"), []);
|
||||
assert.deepEqual(first("/"), []);
|
||||
assert.deepEqual(first("/qx/yw"), []);
|
||||
});
|
||||
|
||||
test("at most three, none twice, best first", () => {
|
||||
const many = [...pages, { to: "/servers", label: "Servers again" }, { to: "/servers/compare", label: "Compare servers" }, { to: "/servers/x", label: "Server x" }, { to: "/servers/y", label: "Server y" }];
|
||||
const found = suggestPages("/servers", many).map((p) => p.to);
|
||||
assert.equal(found.length, 3);
|
||||
assert.equal(new Set(found).size, 3);
|
||||
assert.equal(found[0], "/servers");
|
||||
});
|
||||
|
||||
test("the distance between two words counts the single-letter changes", () => {
|
||||
assert.equal(distance("servers", "servers"), 0);
|
||||
assert.equal(distance("sevrers", "servers"), 1, "two letters swapped is one slip");
|
||||
assert.equal(distance("sevrers", "secrets"), 2);
|
||||
assert.equal(distance("alert", "alerts"), 1);
|
||||
assert.equal(distance("", "abc"), 3);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user