From 09e7f1f9064ff0ab2109e116b88239115be666db Mon Sep 17 00:00:00 2001 From: Semyon Novikov Date: Wed, 3 Jul 2024 10:50:26 +0500 Subject: [PATCH] Fix up validatePageName routine (#912) * Fix up validatePageName routine File extensions can contain numbers too. My main motivation was to enable myself hosting `woff2` files right from my space, like I do for `ttf` files. Also added some tests. * Fix up typo and add more numeric samples * Add missing semicolons (sorry, I'm not really js/ts programmer) * Make linter happy --- plug-api/lib/page_ref.test.ts | 24 ++++++++++++++++++++++-- plug-api/lib/page_ref.ts | 2 +- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/plug-api/lib/page_ref.test.ts b/plug-api/lib/page_ref.test.ts index b827a83a..49995d31 100644 --- a/plug-api/lib/page_ref.test.ts +++ b/plug-api/lib/page_ref.test.ts @@ -1,5 +1,5 @@ -import { encodePageRef, parsePageRef } from "./page_ref.ts"; -import { assertEquals } from "$std/testing/asserts.ts"; +import { encodePageRef, parsePageRef, validatePageName } from "./page_ref.ts"; +import { assertEquals, assertThrows, AssertionError } from "$std/testing/asserts.ts"; Deno.test("Page utility functions", () => { // Base cases @@ -26,4 +26,24 @@ Deno.test("Page utility functions", () => { assertEquals(encodePageRef({ page: "foo", pos: 10 }), "foo@10"); assertEquals(encodePageRef({ page: "foo", anchor: "bar" }), "foo$bar"); assertEquals(encodePageRef({ page: "foo", header: "bar" }), "foo#bar"); + + // Page name validation + + try { + validatePageName("perfectly fine page name"); + } catch (error) { + throw new AssertionError(`Something is very wrong with the validatePageName function: ${error}`); + } + + assertThrows(() => validatePageName(""), Error); + assertThrows(() => validatePageName(".hidden"), Error); + assertThrows(() => validatePageName(".."), Error); + + for (const extension of ["md", "txt", "exe", "cc", "ts"]) { + assertThrows(() => validatePageName(`extensions-are-not-welcome.${extension}`), Error); + } + + for (const extension of ["db2", "woff2", "sqlite3", "42", "0"]) { + assertThrows(() => validatePageName(`extensions-can-contain-numbers-too.${extension}`), Error); + } }); diff --git a/plug-api/lib/page_ref.ts b/plug-api/lib/page_ref.ts index be3ec938..ab70af1f 100644 --- a/plug-api/lib/page_ref.ts +++ b/plug-api/lib/page_ref.ts @@ -6,7 +6,7 @@ export function validatePageName(name: string) { if (name.startsWith(".")) { throw new Error("Page name cannot start with a '.'"); } - if (/\.[a-zA-Z]+$/.test(name)) { + if (/\.[a-zA-Z0-9]+$/.test(name)) { throw new Error("Page name can not end with a file extension"); } }