From a9ef5a3c0f203b3c4a86385014b82b2635081024 Mon Sep 17 00:00:00 2001 From: Jason Amo-Mensah Date: Fri, 4 Dec 2026 17:33:29 -0500 Subject: [PATCH 1/6] clean url --- .github/workflows/clean-urls.yml | 49 ++++++++ .github/workflows/update-search-index.yml | 2 + .gitignore | 1 + .vscode/settings.json | 4 + README.md | 8 +- docs/clean-urls.md | 138 ++++++++++++++++++++++ html/components/header.html | 2 +- js/events.js | 6 +- js/homepage.js | 10 +- js/load-components.js | 43 ++----- js/news.js | 2 +- js/redirect.js | 9 ++ js/script.js | 10 +- js/site-urls.js | 19 +++ package.json | 7 +- scripts/build-search-index.mjs | 15 ++- scripts/build-site.mjs | 67 +++++++++++ scripts/clean-urls.test.mjs | 79 +++++++++++++ scripts/preview-site.mjs | 22 ++++ scripts/site-routes.mjs | 80 +++++++++++++ scripts/validate-site.mjs | 78 ++++++++++++ 21 files changed, 591 insertions(+), 60 deletions(-) create mode 100644 .github/workflows/clean-urls.yml create mode 100644 .gitignore create mode 100644 .vscode/settings.json create mode 100644 docs/clean-urls.md create mode 100644 js/redirect.js create mode 100644 js/site-urls.js create mode 100644 scripts/build-site.mjs create mode 100644 scripts/clean-urls.test.mjs create mode 100644 scripts/preview-site.mjs create mode 100644 scripts/site-routes.mjs create mode 100644 scripts/validate-site.mjs diff --git a/.github/workflows/clean-urls.yml b/.github/workflows/clean-urls.yml new file mode 100644 index 0000000..4d0ca2f --- /dev/null +++ b/.github/workflows/clean-urls.yml @@ -0,0 +1,49 @@ +name: Clean URLs + +on: + pull_request: + push: + branches: [main] + workflow_dispatch: + inputs: + deploy: + description: 'Publish the validated clean-URL site (requires approved Pages setup)' + type: boolean + default: false + +permissions: + contents: read + +concurrency: + group: clean-urls-${{ github.ref }} + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 20 + - run: npm run build + - run: npm run test:urls + - run: npm run validate:urls + - run: npm run validate:events + - uses: actions/upload-pages-artifact@v4 + with: + path: _site + + deploy: + if: github.event_name == 'workflow_dispatch' && inputs.deploy && github.ref == 'refs/heads/main' + needs: build + runs-on: ubuntu-latest + permissions: + pages: write + id-token: write + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/deploy-pages@v4 + id: deployment diff --git a/.github/workflows/update-search-index.yml b/.github/workflows/update-search-index.yml index 8e5f225..4886c17 100644 --- a/.github/workflows/update-search-index.yml +++ b/.github/workflows/update-search-index.yml @@ -8,6 +8,8 @@ on: - "data/events.json" - "data/news.json" - "scripts/build-search-index.mjs" + - "scripts/site-routes.mjs" + - "js/site-urls.js" permissions: contents: write diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..57510a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +_site/ diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..1b20549 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "liveServer.settings.root": "/_site", + "liveServer.settings.port": 5500 +} diff --git a/README.md b/README.md index e9e24a6..bbc8324 100644 --- a/README.md +++ b/README.md @@ -4,13 +4,15 @@ Repository to host the Imageomics Institute's website. The Imageomics Institute ## Local Hosting -To host the website locally, navigate to the root of the repository and run: +Build the static site and serve its generated clean URLs: ```bash -python -m http.server 8080 +npm run preview ``` -Then open in your browser of choice. +Open . VS Code Go Live is also configured to serve `_site/`; +run `npm run build` before starting it. See [clean URL maintenance, validation, +deployment, and rollback](docs/clean-urls.md). ## Acknowledgments diff --git a/docs/clean-urls.md b/docs/clean-urls.md new file mode 100644 index 0000000..c390452 --- /dev/null +++ b/docs/clean-urls.md @@ -0,0 +1,138 @@ +# Clean URLs + +The site remains plain HTML, CSS, and JavaScript. A dependency-free Node 20 build +creates `_site/` for static GitHub Pages hosting. No client router, framework, +server rewrite rules, or DNS changes are needed. Source pages stay in `html/`; +the root home page stays `index.html`. + +## Build and preview + +```sh +npm run build +npm run test:urls +npm run validate:urls +npm run validate:events +npm run preview +``` + +Open **http://127.0.0.1:5500/**. `npm run preview` rebuilds before serving `_site/`. +Stop it with Ctrl+C. Rebuild after editing source pages or data. If using VS Code +Go Live instead, this workspace's `.vscode/settings.json` points Live Server at +`/_site` on port 5500. Run `npm run build` first and restart Go Live after changing +its root setting. Use either Go Live or `npm run preview`, since both use port 5500. +The generated home-page logo points to `/`, never `/index.html`. + +Do not serve the repository source as the published clean-URL site. Directory +routes and redirects exist in `_site/`, which is ignored by Git and regenerated. + +## URL generation + +| Source | Generated file | Public link | +| --- | --- | --- | +| `index.html` | `_site/index.html` | `/` | +| `html/news.html` | `_site/news/index.html` | `/news/` | +| `html/about/vision.html` | `_site/about/vision/index.html` | `/about/vision/` | +| `html/news/story.html` | `_site/news/story/index.html` | `/news/story/` | +| `html/events/conference/index.html` | `_site/events/conference/index.html` | `/events/conference/` | + +Add pages anywhere beneath `html/`, using existing templates and quoted URL +attributes. They are discovered automatically; no route list is maintained. +Fragments under `html/components/` remain fragments. The build rejects duplicate +routes, generated-file conflicts, redirect cycles, and missing redirect targets. + +Existing conference aliases resolve directly to their final destinations. +Every original page under `html/` gets a redirect file at the same path, including +existing directory indexes. Old bookmarks retain query strings and anchors with +JavaScript enabled. Redirects use `location.replace` to keep Back working. Meta +refresh and a visible link provide fallback navigation without JavaScript; +arbitrary query/fragment preservation requires JavaScript. Explicit `index.html` +requests normalize to the containing directory through an early inline script. +GitHub Pages does not offer configurable HTTP 301 rules: legacy redirect files +return HTTP 200, with canonical tags pointing to their final clean destinations. + +The build resolves page-relative assets against the original source location, +rewrites internal links and responsive image references, normalizes generated +news/events data, and updates canonical/OG/Twitter URLs and `sitemap.xml`. +CSS/JavaScript/images/documents are copied without changing their bytes. The +search build still indexes only linked content and adds structured news/events +text, but emits clean result URLs. `npm run build:search` remains available for +the existing search-index workflow; the full build writes the index into `_site` +without overwriting a maintainer's local `data/search-index.json` edits. + +Author news/events JSON exactly as before, with URLs relative to `html/` and +image paths relative to the listing source. The generated JSON uses root-relative +clean URLs and asset paths. This preserves the existing event validator. + +The site assumes hosting at a domain root (`https://imageomics.org/`); project +subdirectory previews need a different path-prefix strategy. External links, +query strings, fragments, and download filenames are preserved. + +## Validation + +`test:urls` covers future page discovery, URL mapping, legacy alias chains, +conflicts, redirect loops, missing destinations, query/fragment preservation, +and explicit `index.html` bookmarks. `validate:urls` checks generated pages, +local references and anchors, structured links, canonical tags, sitemap entries, +legacy redirects, body content preservation, and byte-identical copied assets. +`validate:events` continues checking source event metadata, pages, and images. +Two historical issues are reported separately: a malformed Zoom registration +link in the February 2024 event, and the old `/allhands` registration link. +They are unchanged by this implementation. + +Local acceptance checks passed for 276 generated routes, 275 legacy redirects, +3,742 local references in the clean PR snapshot, and 105 event records. Chrome verified logo and news-card +clicks, header search suggestions, search pagination, active navigation, mobile +navigation, nested refreshes, and legacy news/conference/search/home bookmarks +with queries and fragments. All 552 clean and legacy route requests returned +HTTP 200; the preview's missing-trailing-slash redirect retained its query. +No local HTTP errors or uncaught JavaScript exceptions were observed in those +browser flows. Existing body content and copied assets passed integrity checks. + +External links are not exhaustively +availability-checked; many historical third-party resources can change. + +## GitHub Pages rollout — requires approval + +The local repository currently has search-index and event-validation workflows, +with no checked-in deployment workflow. Repository Pages settings are not tracked +in Git; confirm and record the current publishing source, custom domain, +last successful deployment, and rollback commit before rollout. + +`.github/workflows/clean-urls.yml` builds and validates on PRs and main pushes, +and uploads `_site/` as a Pages artifact. It deploys **only** through a manual +workflow dispatch on `main` with the `deploy` input explicitly checked. Normal +pushes, PRs, and default manual runs do not deploy. Existing workflows remain; +the search workflow additionally watches its new shared URL dependencies. + +After approval: + +1. Record the previous successful deployment and Pages configuration. Protect + the `github-pages` environment so only main and approved reviewers can deploy. +2. If Pages currently publishes a source branch, switch Settings → Pages → Build + and deployment → Source to **GitHub Actions** before merging source changes. + This prevents branch-based publishing from serving unbuilt source files. + Keep the custom domain and DNS unchanged. The previous deployed site remains + the live version until a new deployment succeeds. +3. Merge the reviewed change, inspect the passing workflow/artifact, then manually + run **Clean URLs** on `main` with `deploy` checked. Approve the environment gate. +4. Verify the production logo, clean pages, old bookmarks, search, listings, + responsive assets, query strings, and anchor links. + +When ready for automatic publication of future changes, explicitly approve a +separate workflow change to enable the deploy job on successful main builds. +Until then, publishing content updates also requires the manual deploy action. +Do not merge this implementation into an active branch-based publisher without +first completing the approved publishing-source transition. + +## Rollback + +Before rollout, retain the old successful artifact or source commit and publishing +configuration. If the generated deployment has a problem, restore the previous +artifact via its deployment workflow, or revert the complete clean-URL change +and restore the previously recorded branch-based publishing source. Revert source +changes before restoring branch publishing so raw clean-URL source is not served. +Keep DNS and the domain unchanged. If clean URLs have already been distributed, +retain compatibility aliases for them when preparing the rollback artifact. + +Before deployment, rollback is simply discarding this feature's changes and +returning to the original branch; the existing production deployment is untouched. diff --git a/html/components/header.html b/html/components/header.html index 852c35b..d46c76a 100644 --- a/html/components/header.html +++ b/html/components/header.html @@ -1,6 +1,6 @@
diff --git a/js/events.js b/js/events.js index 94ef40a..97e486f 100644 --- a/js/events.js +++ b/js/events.js @@ -10,7 +10,7 @@ document.addEventListener('DOMContentLoaded', async () => { let eventItems; try { - const response = await fetch("../data/events.json"); + const response = await fetch("/data/events.json"); if (!response.ok) throw new Error(`Request failed with status ${response.status}`); eventItems = await response.json(); @@ -96,7 +96,7 @@ document.addEventListener('DOMContentLoaded', async () => { }; const COURSE_SESSION_URL_MARKER = 'ai-and-ecology-course-'; - const COURSE_SERIES_URL = 'tools-resources/experiential-introduction-ai-ecology-course-2026-2027.html'; + const COURSE_SERIES_URL = '/tools-resources/experiential-introduction-ai-ecology-course-2026-2027/'; const FEATURED_UPCOMING_WINDOW_DAYS = 14; const MILLISECONDS_PER_DAY = 24 * 60 * 60 * 1000; @@ -156,7 +156,7 @@ document.addEventListener('DOMContentLoaded', async () => { const today = getToday(); const featureCandidates = items.flatMap((item) => item.seriesItems?.length ? item.seriesItems : [item]); const conference = featureCandidates.find((item) => - item.url === 'events/2027-imageomics-conference.html' && !isPastEvent(item)); + item.url === '/events/2027-imageomics-conference/' && !isPastEvent(item)); if (conference) { return { item: conference, status: 'Save the Date!' }; } diff --git a/js/homepage.js b/js/homepage.js index 6cb264c..532f0b0 100644 --- a/js/homepage.js +++ b/js/homepage.js @@ -57,7 +57,7 @@ function getPageUrl(item) { if (/^https?:\/\//.test(item.url || '')) return item.url; - return `html/${String(item.url || '').replace(/^\/?html\//, '')}`; + return window.ImageomicsUrls.page(item.url); } function makeSnippet(value, maximumLength = 135) { @@ -180,7 +180,7 @@ category: 'Save the date · May 24–26, 2027', title: '2027 Imageomics Conference', description: 'Mark your calendars for the 2027 Imageomics Conference, taking place May 24–26, 2027, at The Ohio State University in Columbus, Ohio!', - url: 'events/2027-imageomics-conference.html', + url: '/events/2027-imageomics-conference/', image: 'images/events-images/imageomics-conference-2027-save-the-date.png', imageFit: 'contain', cta: 'View conference details' @@ -214,7 +214,7 @@ category: 'Conference and workshop', title: 'FloraPalooza 2026', description: 'A collaborative workshop exploring how plant imagery can answer biological and ecological questions at scale.', - url: 'news/florapalooza-2026.html', + url: '/news/florapalooza-2026/', image: 'images/news-images/florapalooza-2026.png', imageFit: 'contain', cta: 'Explore the workshop' @@ -236,7 +236,7 @@ if (!upcomingEvent) return [...featuredItems]; - const conference = featuredItems.find((item) => item.url === 'events/2027-imageomics-conference.html'); + const conference = featuredItems.find((item) => item.url === '/events/2027-imageomics-conference/'); if (upcomingEvent.url === conference?.url) return [...featuredItems]; return [ @@ -275,7 +275,7 @@ const getStoryUrl = (story) => { if (/^https?:\/\//.test(story.url || '')) return story.url; - return `html/${String(story.url || '').replace(/^\/?html\//, '')}`; + return window.ImageomicsUrls.page(story.url); }; const createSlide = (story, isClone = false) => { diff --git a/js/load-components.js b/js/load-components.js index 358bead..0856807 100644 --- a/js/load-components.js +++ b/js/load-components.js @@ -2,35 +2,10 @@ (function() { 'use strict'; - const COMPONENT_CACHE_VERSION = '14'; + const COMPONENT_CACHE_VERSION = 'clean-urls-1'; - function getPathPrefix() { - const path = window.location.pathname; - - if (path.endsWith('/') || (path.endsWith('/index.html') && !path.includes('/html/'))) { - return ''; - } - - const htmlIndex = path.indexOf('/html/'); - if (htmlIndex !== -1) { - const afterHtml = path.substring(htmlIndex + 6); - const depth = (afterHtml.match(/\//g) || []).length; - return '../'.repeat(depth + 1); - } - - return '../'; - } - - function adjustPaths(html, prefix) { - if (!prefix) return html; - - html = html.replace(/src="(images|css|js|html)\//g, `src="${prefix}$1/`); - html = html.replace(/href="(images|css|js|html)\//g, `href="${prefix}$1/`); - html = html.replace(/href="index\.html"/g, `href="${prefix}index.html"`); - html = html.replace(/href="\.\.\/index\.html"/g, `href="${prefix}index.html"`); - - return html; - } + const script = document.querySelector('script[src*="js/load-components.js"]'); + const siteRoot = new URL('../', script?.src || new URL('/js/load-components.js', window.location.href)); function getCachedComponent(url) { try { @@ -62,8 +37,7 @@ return; } - const prefix = getPathPrefix(); - target.innerHTML = adjustPaths(html, prefix); + target.innerHTML = html; if (targetId === 'header-placeholder') { if (typeof window.initHamburger === 'function') { @@ -115,21 +89,20 @@ }); } - function ensureFavicon(prefix) { + function ensureFavicon() { if (document.querySelector('link[rel~="icon"]')) return; const favicon = document.createElement('link'); favicon.rel = 'icon'; favicon.type = 'image/png'; - favicon.href = `${prefix}images/Imageomics-logo.png`; + favicon.href = new URL('images/Imageomics-logo.png', siteRoot).href; document.head.appendChild(favicon); } function initComponents() { - const prefix = getPathPrefix(); - const componentsPath = `${prefix}html/components/`; + const componentsPath = new URL('html/components/', siteRoot).href; - ensureFavicon(prefix); + ensureFavicon(); loadComponent(`${componentsPath}header.html`, 'header-placeholder'); loadComponent(`${componentsPath}footer.html`, 'footer-placeholder'); } diff --git a/js/news.js b/js/news.js index bc9d8a0..6f57167 100644 --- a/js/news.js +++ b/js/news.js @@ -13,7 +13,7 @@ document.addEventListener('DOMContentLoaded', async () => { let unsortedNewsItems; try { - const response = await fetch("../data/news.json"); + const response = await fetch("/data/news.json"); if (!response.ok) throw new Error(`Request failed with status ${response.status}`); unsortedNewsItems = await response.json(); diff --git a/js/redirect.js b/js/redirect.js new file mode 100644 index 0000000..a17e735 --- /dev/null +++ b/js/redirect.js @@ -0,0 +1,9 @@ +// Runs before meta refresh. Retain query strings/fragments and avoid a Back loop. +(function () { + 'use strict'; + const canonical = document.querySelector('link[rel="canonical"]'); + if (!canonical) return; + const target = new URL(canonical.href); + const destination = target.pathname + (window.location.search || target.search) + (window.location.hash || target.hash); + if (destination !== window.location.pathname + window.location.search + window.location.hash) window.location.replace(destination); +})(); diff --git a/js/script.js b/js/script.js index 63060f1..eef8c02 100644 --- a/js/script.js +++ b/js/script.js @@ -36,7 +36,7 @@ document.addEventListener('DOMContentLoaded', () => { const wholeTermPattern = (term) => `(? { - if (url === 'index.html') return 'Home'; + if (url === '/') return 'Home'; const section = url.split('/')[1] || ''; return { about: 'About', @@ -443,7 +443,7 @@ document.addEventListener('DOMContentLoaded', () => { section.textContent = page.section; const path = document.createElement('span'); path.className = 'search-result-path'; - path.textContent = page.url === 'index.html' ? 'imageomics.org' : page.url.replace(/^html\//, '').replace(/\.html$/, ''); + path.textContent = page.url === '/' ? 'imageomics.org' : page.url; meta.append(section, path); const title = document.createElement('div'); @@ -521,7 +521,7 @@ document.addEventListener('DOMContentLoaded', () => { links[activeResultIndex >= 0 ? activeResultIndex : 0].click(); } else if (searchBar.value.trim()) { window.clearTimeout(searchTimer); - const target = new URL('html/search.html', siteRootUrl); + const target = new URL('search/', siteRootUrl); target.searchParams.set('q', searchBar.value.trim()); window.location.assign(target.href); } else { @@ -843,7 +843,7 @@ document.addEventListener('DOMContentLoaded', () => { } }); - const sectionMatch = currentPath.match(/\/html\/(about|research|tools-resources|events|news|conference)(?:\/|\.html$)/); + const sectionMatch = currentPath.match(/^\/(about|research|tools-resources|events|news|conference)\//); if (!sectionMatch) return; const section = sectionMatch[1] === 'conference' ? 'events' : sectionMatch[1]; @@ -858,7 +858,7 @@ document.addEventListener('DOMContentLoaded', () => { return; } - const sectionIndexPath = `/html/${section}.html`; + const sectionIndexPath = `/${section}/`; const sectionLink = Array.from(links).find((link) => getLinkPath(link).endsWith(sectionIndexPath)); if (sectionLink) { sectionLink.classList.add('is-current'); diff --git a/js/site-urls.js b/js/site-urls.js new file mode 100644 index 0000000..acc1df2 --- /dev/null +++ b/js/site-urls.js @@ -0,0 +1,19 @@ +// Shared by Node build tools and browser code; no runtime dependencies. +(function (root) { + 'use strict'; + function cleanPath(pathname) { + if (pathname.startsWith('/html/components/')) return pathname; + const page = pathname.replace(/^\/html\//, '/'); + if (page.endsWith('/index.html')) return page.slice(0, -10); + if (page.endsWith('.html')) return page.slice(0, -5) + '/'; + return page; + } + function page(value) { + if (!value || /^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i.test(value)) return value; + const url = new URL(value, 'https://imageomics.org/html/'); + return cleanPath(url.pathname) + url.search + url.hash; + } + const api = { cleanPath, page }; + if (typeof module !== 'undefined' && module.exports) module.exports = api; + else root.ImageomicsUrls = api; +})(typeof window === 'undefined' ? globalThis : window); diff --git a/package.json b/package.json index 2094014..1718693 100644 --- a/package.json +++ b/package.json @@ -1,8 +1,11 @@ { "private": true, "scripts": { - "build": "npm run build:search", + "build": "node scripts/build-site.mjs && node scripts/build-search-index.mjs _site/data/search-index.json", "build:search": "node scripts/build-search-index.mjs", - "validate:events": "node scripts/validate-events.mjs" + "validate:events": "node scripts/validate-events.mjs", + "validate:urls": "node scripts/validate-site.mjs", + "test:urls": "node --test scripts/clean-urls.test.mjs", + "preview": "npm run build && node scripts/preview-site.mjs" } } diff --git a/scripts/build-search-index.mjs b/scripts/build-search-index.mjs index 56fd326..3942628 100644 --- a/scripts/build-search-index.mjs +++ b/scripts/build-search-index.mjs @@ -1,9 +1,12 @@ import { readdir, readFile, writeFile } from 'node:fs/promises'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; +import { readRoutes, origin as siteOrigin } from './site-routes.mjs'; const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); -const outputPath = path.join(projectRoot, 'data', 'search-index.json'); +const outputPath = process.argv[2] ? path.resolve(process.argv[2]) : path.join(projectRoot, 'data', 'search-index.json'); +const routes = await readRoutes(); +const canonicalSources = new Map([...routes.values()].filter((route) => !route.alias).map((route) => [route.url, route.source.slice(1)])); const structuredContentPaths = [ path.join(projectRoot, 'data', 'events.json'), path.join(projectRoot, 'data', 'news.json') @@ -110,19 +113,20 @@ for (const filePath of htmlFiles.sort()) { const relativePath = path.relative(projectRoot, filePath).split(path.sep).join('/'); const html = await readFile(filePath, 'utf8'); markupByUrl.set(relativePath, html); - if (excludedPaths.has(relativePath)) continue; + if (excludedPaths.has(relativePath) || routes.get('/' + relativePath)?.alias) continue; documents.push(extractDocument(html, relativePath)); } -const siteOrigin = 'https://imageomics.org'; function resolvePageUrl(value, sourcePath) { try { const url = new URL(decodeEntities(value), `${siteOrigin}/${sourcePath}`); if (url.origin !== siteOrigin) return null; let pagePath = decodeURIComponent(url.pathname).replace(/^\/+/, ''); if (!pagePath || pagePath.endsWith('/')) pagePath += 'index.html'; - return markupByUrl.has(pagePath) ? pagePath : null; + const route = routes.get('/' + pagePath); + const clean = route ? route.target : url.pathname; + return canonicalSources.get(clean) || (markupByUrl.has(pagePath) ? pagePath : null); } catch { return null; } @@ -176,6 +180,7 @@ while (pending.length) { pending.push(...(listingLinks.get(pagePath) || [])); } -const linkedDocuments = documents.filter((document) => reachable.has(document.url)); +const linkedDocuments = documents.filter((document) => reachable.has(document.url)) + .map((document) => ({ ...document, url: routes.get('/' + document.url).target })); await writeFile(outputPath, `${JSON.stringify(linkedDocuments)}\n`, 'utf8'); console.log(`Indexed ${linkedDocuments.length} linked HTML pages in ${path.relative(projectRoot, outputPath)}; excluded ${documents.length - linkedDocuments.length} unlinked pages.`); diff --git a/scripts/build-site.mjs b/scripts/build-site.mjs new file mode 100644 index 0000000..144d2cf --- /dev/null +++ b/scripts/build-site.mjs @@ -0,0 +1,67 @@ +import { cp, mkdir, readFile, writeFile, rm, stat } from 'node:fs/promises'; +import path from 'node:path'; +import { root, output, origin, walk, readRoutes, rewriteHtml, rewriteUrl, escapeAttribute } from './site-routes.mjs'; + +const routes = await readRoutes(); +// Output is fixed and ignored; never remove or rewrite authoring source files. +await rm(output, { recursive: true, force: true }); +await mkdir(output, { recursive: true }); +async function write(relative, content) { + const file = path.join(output, relative); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, content); +} +// Copy every non-page resource, including future document/asset directories. +const excluded = new Set(['.git', '.github', '.vscode', '_site', 'node_modules', 'scripts', 'package.json', 'package-lock.json', 'README.md', 'LICENSE', 'CITATION.cff']); +for (const file of await walk(root, excluded)) { + const relative = path.relative(root, file).split(path.sep).join('/'); + if (relative.split('/').some((part) => part.startsWith('.') || excluded.has(part))) continue; + if (routes.has('/' + relative)) continue; + await mkdir(path.dirname(path.join(output, relative)), { recursive: true }); + await cp(file, path.join(output, relative)); +} +const redirect = (target) => ` +Page moved | Imageomics Institute + + + +

Continue to this page.

+`; +const locations = []; +for (const route of routes.values()) { + const destination = path.join(route.url, 'index.html'); + // Fail instead of silently replacing an asset with a generated page. + try { await stat(path.join(output, destination)); throw new Error(`Output collision at ${destination}`); } + catch (error) { if (error.code !== 'ENOENT') throw error; } + if (route.alias) await write(destination, redirect(route.target)); + else { + let html = rewriteHtml(route.html, route.source, routes); + html = html.replace(/\s*]*rel=["']canonical["'][^>]*>/gi, ''); + html = html.replace(/]*>/gi, (tag) => { + if (!/\b(?:property|name)=["'](?:og:url|twitter:url)["']/i.test(tag)) return tag; + return tag.replace(/\bcontent=(["'])(.*?)\1/i, `content="${origin}${route.url}"`); + }); + html = html.replace(/]*>/i, (head) => `${head}\n \n `); + html = html.replace('', ` \n`); + await write(destination, html); + if (route.url !== '/search/') locations.push(origin + route.url); + } + if (route.source !== '/index.html') await write(route.source, redirect(route.target)); +} +for (const file of await walk(path.join(root, 'html/components'))) { + if (!file.endsWith('.html')) continue; + const relative = path.relative(root, file).split(path.sep).join('/'); + // Header/footer URLs are authored relative to the site root; the saved popup is relative to /html/. + const source = file.endsWith('conference-registration-popup.html') ? '/' + relative : '/index.html'; + await write(relative, rewriteHtml(await readFile(file, 'utf8'), source, routes)); +} +for (const name of ['news', 'events']) { + const records = JSON.parse(await readFile(path.join(root, `data/${name}.json`), 'utf8')); + for (const record of records) for (const field of ['url', 'image']) { + if (record[field]) record[field] = rewriteUrl(record[field], `/html/${name}.html`, routes); + } + await write(`data/${name}.json`, JSON.stringify(records, null, 2) + '\n'); +} +await write('.nojekyll', ''); +await write('sitemap.xml', `\n\n${locations.sort().map((url) => ` ${escapeAttribute(url)}`).join('\n')}\n\n`); +console.log(`Built ${routes.size} clean routes and ${routes.size - 1} legacy redirects in _site/.`); diff --git a/scripts/clean-urls.test.mjs b/scripts/clean-urls.test.mjs new file mode 100644 index 0000000..48c55b1 --- /dev/null +++ b/scripts/clean-urls.test.mjs @@ -0,0 +1,79 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, mkdir, writeFile, readFile, rm } from 'node:fs/promises'; +import os from 'node:os'; +import path from 'node:path'; +import vm from 'node:vm'; +import { cleanPath, readRoutes, rewriteUrl, root } from './site-routes.mjs'; +import urls from '../js/site-urls.js'; + +async function fixture(t, files) { + const directory = await mkdtemp(path.join(os.tmpdir(), 'imageomics-route-test-')); + t.after(() => rm(directory, { recursive: true, force: true })); + for (const [name, value] of Object.entries({ 'index.html': 'Home', ...files })) { + const file = path.join(directory, name); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, value); + } + return directory; +} +test('clean paths include future pages, directory indexes, and dotted slugs', () => { + for (const [source, expected] of [ + ['/index.html', '/'], ['/html/news.html', '/news/'], ['/html/about/vision.html', '/about/vision/'], + ['/html/future/deep/page.html', '/future/deep/page/'], ['/html/events/conference/index.html', '/events/conference/'], + ['/html/news/dr.-name..html', '/news/dr.-name./'] + ]) assert.equal(cleanPath(source), expected); + assert.equal(cleanPath('/html/components/header.html'), '/html/components/header.html'); + assert.equal(urls.page('news/story.html?year=2026#section'), '/news/story/?year=2026#section'); + assert.equal(urls.page('https://example.org/paper.html'), 'https://example.org/paper.html'); +}); +test('new source files are discovered and existing aliases resolve in one hop', async (t) => { + const directory = await fixture(t, { + 'html/future/page.html': 'New page', + 'html/old.html': '', + 'html/older.html': '' + }); + const routes = await readRoutes(directory); + assert.equal(routes.get('/html/future/page.html').url, '/future/page/'); + assert.equal(routes.get('/html/older.html').target, '/future/page/'); + assert.equal(rewriteUrl('older.html?q=ai&page=2#section', '/html/news.html', routes), '/future/page/?q=ai&page=2#section'); + assert.equal(rewriteUrl('//imageomics.org/html/older.html', '/index.html', routes), '/future/page/'); + assert.equal(rewriteUrl('../images/x.png', '/html/news.html', routes), '/images/x.png'); + assert.equal(rewriteUrl('https://external.org/news.html', '/index.html', routes), 'https://external.org/news.html'); +}); +test('duplicate routes, redirect loops, and missing destinations fail the build', async (t) => { + const collision = await fixture(t, { 'html/news.html': 'News', 'html/news/index.html': 'Duplicate' }); + await assert.rejects(readRoutes(collision), /collision/); + const overlap = await fixture(t, { 'html/html/news.html': 'Nested', 'html/news/index.html': 'Index' }); + await assert.rejects(readRoutes(overlap), /collision/); + const cycle = await fixture(t, { + 'html/a.html': '', + 'html/b.html': '' + }); + await assert.rejects(readRoutes(cycle), /loop/); + const missing = await fixture(t, { 'html/a.html': '' }); + await assert.rejects(readRoutes(missing), /Missing redirect/); +}); +test('legacy redirects preserve queries/fragments and never loop', async () => { + const code = await readFile(path.join(root, 'js/redirect.js'), 'utf8'); + for (const target of ['/', '/news/', '/events/conference/']) { + let replacement; + const location = { pathname: '/html/old.html', search: '?q=ai&page=2', hash: '#section', replace(value) { replacement = value; } }; + const document = { querySelector: () => ({ href: 'https://imageomics.org' + target }) }; + vm.runInNewContext(code, { URL, document, window: { location } }); + assert.equal(replacement, target + '?q=ai&page=2#section'); + location.pathname = target; replacement = undefined; + vm.runInNewContext(code, { URL, document, window: { location } }); + assert.equal(replacement, undefined); + } +}); +test('explicit index.html bookmarks normalize to directory URLs', async () => { + const html = await readFile(path.join(root, '_site/index.html'), 'utf8'); + const code = html.match(/\n `); + html = html.replace(/]*>/i, (head) => `${head}\n `); html = html.replace('', ` \n`); await write(destination, html); if (route.url !== '/search/') locations.push(origin + route.url); diff --git a/scripts/clean-urls.test.mjs b/scripts/clean-urls.test.mjs index 48c55b1..7186201 100644 --- a/scripts/clean-urls.test.mjs +++ b/scripts/clean-urls.test.mjs @@ -37,6 +37,7 @@ test('new source files are discovered and existing aliases resolve in one hop', assert.equal(routes.get('/html/future/page.html').url, '/future/page/'); assert.equal(routes.get('/html/older.html').target, '/future/page/'); assert.equal(rewriteUrl('older.html?q=ai&page=2#section', '/html/news.html', routes), '/future/page/?q=ai&page=2#section'); + assert.equal(rewriteUrl('/future/page/?q=ai#s', '/index.html', routes), '/future/page/?q=ai#s'); assert.equal(rewriteUrl('//imageomics.org/html/older.html', '/index.html', routes), '/future/page/'); assert.equal(rewriteUrl('../images/x.png', '/html/news.html', routes), '/images/x.png'); assert.equal(rewriteUrl('https://external.org/news.html', '/index.html', routes), 'https://external.org/news.html'); @@ -68,12 +69,18 @@ test('legacy redirects preserve queries/fragments and never loop', async () => { } }); test('explicit index.html bookmarks normalize to directory URLs', async () => { - const html = await readFile(path.join(root, '_site/index.html'), 'utf8'); - const code = html.match(/