diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 20854dc..1c68db2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -100,10 +100,10 @@ jobs: run: npm run build && npm run linkcheck - name: lip demo (VitePress-style, folder locales) - run: npm run build:lip && node kit/scripts/linkcheck.mjs dist-lip --base /lip/ --site-origin https://docs.levimc.org + run: npm run build:lip && node kit/scripts/linkcheck.mjs dist-lip --base /lip/ --site-origin https://levimc.org - name: single-locale docs demo - run: npm run build:single && node kit/scripts/linkcheck.mjs dist-single --base /Single/ --site-origin https://docs.levimc.org + run: npm run build:single && node kit/scripts/linkcheck.mjs dist-single --base /Single/ --site-origin https://levimc.org - name: plain app demo (levimc.org / levimc.org/mods shape) run: npm run build:app diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index f9ab2ec..8c8b421 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,142 +1,141 @@ -name: Deploy to GitHub Pages - -on: - push: - branches: - - main - # LeviMC Mods (/mods/) is a snapshot of its repositories' tags (mods/repos.txt), so rebuild to pick up new - # versions. - schedule: - - cron: "17 * * * *" - workflow_dispatch: - -permissions: - contents: read - pages: write - id-token: write - -concurrency: - group: pages - cancel-in-progress: false - -jobs: - build: - runs-on: ubuntu-latest - outputs: - kit-changed: ${{ steps.kit.outputs.changed }} - steps: - - uses: actions/checkout@v7 - - - uses: actions/setup-node@v7 - with: - node-version: 24 - cache: npm - - - run: npm ci - - # levimc-kit lives here (kit/) and is published with the site at https://levimc.org/kit/v2/, where every - # other LeviMC site fetches it when it builds. --stamp puts the kit's build hash into this site's pages too. - - id: kit - run: | - node kit/scripts/publish-kit.mjs .kit/publish --stamp - new=$(jq -r .build .kit/publish/v2/manifest.json) - old=$(curl -fsSL https://levimc.org/kit/v2/manifest.json | jq -r .build || echo none) - echo "kit build: $old → $new" - echo "changed=$([ "$new" != "$old" ] && echo true || echo false)" >> "$GITHUB_OUTPUT" - - - run: npm run typecheck - - # Blog content (Hexo permalinks, slugs, rendering) and the kit's preference tests. - - run: npm test - - # Client build, SSR build and prerender: one static HTML file per route - # (projects/index.html, …) plus 404.html, sitemap.xml and robots.txt. - - run: npm run build - - - run: cp -r .kit/publish dist/kit - - # LeviMC Mods: its own app in mods/ (pnpm), built with this kit and deployed at /mods/. The token lets its build - # read each package repository from GitHub's GraphQL API (renamed repositories, stars, release dates, license). - - uses: pnpm/action-setup@v5 - with: - package_json_file: mods/package.json - - # What earlier builds read from the mods' repositories (mods/.cache, see mods/src/server/registry.ts), so this one - # reads only new tags. Without it, everything is read again (about a minute). - - uses: actions/cache/restore@v6 - with: - path: mods/.cache - key: mods-registry-${{ github.run_id }} - restore-keys: mods-registry- - - - working-directory: mods - run: | - pnpm install --frozen-lockfile - pnpm build - env: - GITHUB_TOKEN: ${{ github.token }} - - # Saved only when it changed (the key is its hash). - - uses: actions/cache/save@v6 - with: - path: mods/.cache - key: mods-registry-${{ hashFiles('mods/.cache/registry.json') }} - - # The pages and the JSON from before version 4 at /mods/, the JSON (version 4) at /api/v4/mods/, and the - # release versions (versions/versions.json, kept by versions.yml) at /api/v4/mc/versions/. - - run: | - cp -r mods/dist dist/mods - test ! -e dist/api - cp -r mods/dist-api dist/api - test ! -e dist/api/v4/mc/versions - mkdir -p dist/api/v4/mc/versions - cp versions/versions.json dist/api/v4/mc/versions/index.json - - # Internal links, redirect-needing links and #anchors (GitHub Pages semantics). - - run: npm run linkcheck - - - uses: actions/configure-pages@v6 - - - uses: actions/upload-pages-artifact@v5 - with: - path: dist - - deploy: - needs: build - runs-on: ubuntu-latest - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - id: deployment - uses: actions/deploy-pages@v5 - - # A new kit is live: rebuild every other LeviMC site now, so the change reaches them within minutes. Needs the - # KIT_SYNC_TOKEN secret (a fine-grained token with "Actions: read and write" on the repositories below); - # without it, each site still picks the new kit up with its hourly check. - sync: - needs: [build, deploy] - if: needs.build.outputs.kit-changed == 'true' - runs-on: ubuntu-latest - steps: - - env: - GH_TOKEN: ${{ secrets.KIT_SYNC_TOKEN }} - run: | - if [ -z "$GH_TOKEN" ]; then - echo "::notice::KIT_SYNC_TOKEN is not set: the sites rebuild with the new kit at their next hourly check" - exit 0 - fi - status=0 - while read -r repo workflow; do - echo "→ $repo ($workflow)" - gh workflow run "$workflow" -R "LiteLDev/$repo" || status=1 - done <<'EOF' - liteldev.github.io deploy.yml - LeviLamina build-docs.yml - LegacyScriptEngine build_docs.yml - lip build-docs.yml - LeviLauncher docs.yml - BeDD docs.yml - bedboo docs.yml - EOF - exit $status +name: Deploy to GitHub Pages + +on: + push: + branches: + - main + # LeviMC Mods (/mods/) is a snapshot of its repositories' tags (mods/repos.txt), so rebuild to pick up new + # versions. + schedule: + - cron: "17 * * * *" + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +concurrency: + group: pages + cancel-in-progress: false + +jobs: + build: + runs-on: ubuntu-latest + outputs: + kit-changed: ${{ steps.kit.outputs.changed }} + steps: + - uses: actions/checkout@v7 + + - uses: actions/setup-node@v7 + with: + node-version: 24 + cache: npm + + - run: npm ci + + # levimc-kit lives here (kit/) and is published with the site at https://levimc.org/kit/v2/, where every + # other LeviMC site fetches it when it builds. --stamp puts the kit's build hash into this site's pages too. + - id: kit + run: | + node kit/scripts/publish-kit.mjs .kit/publish --stamp + new=$(jq -r .build .kit/publish/v2/manifest.json) + old=$(curl -fsSL https://levimc.org/kit/v2/manifest.json | jq -r .build || echo none) + echo "kit build: $old → $new" + echo "changed=$([ "$new" != "$old" ] && echo true || echo false)" >> "$GITHUB_OUTPUT" + + - run: npm run typecheck + + # Blog content (Hexo permalinks, slugs, rendering) and the kit's preference tests. + - run: npm test + + # Client build, SSR build and prerender: one static HTML file per route + # (projects/index.html, …) plus 404.html, sitemap.xml and robots.txt. + - run: npm run build + + - run: cp -r .kit/publish dist/kit + + # LeviMC Mods: its own app in mods/ (pnpm), built with this kit and deployed at /mods/. The token lets its build + # read each package repository from GitHub's GraphQL API (renamed repositories, stars, release dates, license). + - uses: pnpm/action-setup@v5 + with: + package_json_file: mods/package.json + + # What earlier builds read from the mods' repositories (mods/.cache, see mods/src/server/registry.ts), so this one + # reads only new tags. Without it, everything is read again (about a minute). + - uses: actions/cache/restore@v6 + with: + path: mods/.cache + key: mods-registry-${{ github.run_id }} + restore-keys: mods-registry- + + - working-directory: mods + run: | + pnpm install --frozen-lockfile + pnpm build + env: + GITHUB_TOKEN: ${{ github.token }} + + # Saved only when it changed (the key is its hash). + - uses: actions/cache/save@v6 + with: + path: mods/.cache + key: mods-registry-${{ hashFiles('mods/.cache/registry.json') }} + + # The pages and the JSON from before version 4 at /mods/, the JSON (version 4) at /api/v4/mods/, and the + # release versions (versions/versions.json, kept by versions.yml) at /api/v4/mc/versions/. + - run: | + cp -r mods/dist dist/mods + test ! -e dist/api + cp -r mods/dist-api dist/api + test ! -e dist/api/v4/mc/versions + mkdir -p dist/api/v4/mc/versions + cp versions/versions.json dist/api/v4/mc/versions/index.json + + # Internal links, redirect-needing links and #anchors (GitHub Pages semantics). + - run: npm run linkcheck + + - uses: actions/configure-pages@v6 + + - uses: actions/upload-pages-artifact@v5 + with: + path: dist + + deploy: + needs: build + runs-on: ubuntu-latest + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - id: deployment + uses: actions/deploy-pages@v5 + + # A new kit is live: rebuild every other LeviMC site now, so the change reaches them within minutes. Needs the + # KIT_SYNC_TOKEN secret (a fine-grained token with "Actions: read and write" on the repositories below); + # without it, each site still picks the new kit up with its hourly check. + sync: + needs: [build, deploy] + if: needs.build.outputs.kit-changed == 'true' + runs-on: ubuntu-latest + steps: + - env: + GH_TOKEN: ${{ secrets.KIT_SYNC_TOKEN }} + run: | + if [ -z "$GH_TOKEN" ]; then + echo "::notice::KIT_SYNC_TOKEN is not set: the sites rebuild with the new kit at their next hourly check" + exit 0 + fi + status=0 + while read -r repo workflow; do + echo "→ $repo ($workflow)" + gh workflow run "$workflow" -R "LiteLDev/$repo" || status=1 + done <<'EOF' + LeviLamina build-docs.yml + LegacyScriptEngine build_docs.yml + lip build-docs.yml + LeviLauncher docs.yml + BeDD docs.yml + bedboo docs.yml + EOF + exit $status diff --git a/MIGRATION.md b/MIGRATION.md new file mode 100644 index 0000000..cadf828 --- /dev/null +++ b/MIGRATION.md @@ -0,0 +1,66 @@ +# The project docs moved from docs.levimc.org to levimc.org (2026-11-15) + +`https://docs.levimc.org//…` is now `https://levimc.org//…`. The pages, their paths and their +repositories stayed as they were. + +## How it works + +GitHub Pages serves a project repository's site (LeviLamina, LegacyScriptEngine, lip, LeviLauncher, BeDD, bedboo) +at `//` below the **organisation site's** custom domain. The organisation site used to be +LiteLDev/liteldev.github.io with the domain docs.levimc.org, and levimc.org was a project site with a domain of its +own. Now this repository *is* the organisation site (renamed from `levimc.org` to `liteldev.github.io`) with the +domain levimc.org, so every project site appears at `levimc.org//` without any change to how it is built. + +This repository took over what the old organisation site did: `legacy/` publishes the redirect pages of the retired +docs sites (`/LeviLaunchroid/`, `/preloader-android/`, `/LiteXLoader/`), and `404.html` forwards other forms of +those URLs and wrongly cased project paths (`/levilamina/` → `/LeviLamina/`). + +The old organisation repository is now **LiteLDev/docs.levimc.org**, a project site with the domain +docs.levimc.org. It publishes only a page that forwards every URL to the same path, query and `#anchor` on +levimc.org (`location.replace`). That is a client-side redirect, served with status 404. For a real 301, put the `docs` +record behind Cloudflare's proxy and add a Redirect Rule: hostname equals `docs.levimc.org` → dynamic redirect +`concat("https://levimc.org", http.request.uri.path)`, 301, preserve the query string. + +Things to know: + +* **Project paths win.** A repository with Pages owns `//` on levimc.org. No route of this site may start + with a repository's name, and no repository named like a route (`blog`, `mods`, `api`, `kit`, `about`, …) may + turn Pages on. LiteLoader.NET and liteloaderbds-documentation have Pages on and appear at + `levimc.org/LiteLoader.NET/` and `levimc.org/liteloaderbds-documentation/`. +* **Same origin.** Docs and levimc.org share cookies and localStorage. levimc.org's router leaves the docs paths + alone (`isAppPath`, `src/components/SiteHeader.tsx`). +* Each project repository points its canonical URLs, sitemap and `linkcheck --site-origin` at `https://levimc.org`. + +## What was done + +1. Opened a PR in each project repository that changes `https://docs.levimc.org` to `https://levimc.org`: + `hostname` / `sitemap.hostname` in `docs.config.ts`, `linkcheck --site-origin`, the hourly kit check, and links + in the docs, READMEs and code. +2. Removed the domain levimc.org from LiteLDev/levimc.org's Pages and docs.levimc.org from LiteLDev/liteldev.github.io's. +3. Renamed LiteLDev/liteldev.github.io → LiteLDev/docs.levimc.org, and LiteLDev/levimc.org → LiteLDev/liteldev.github.io. +4. Set the domain levimc.org on LiteLDev/liteldev.github.io and merged LiteLDev/levimc.org#99 (this change). After the + certificate was issued, turned on *Enforce HTTPS*. +5. Set the domain docs.levimc.org on LiteLDev/docs.levimc.org and deployed its forwarding page. +6. Merged the project PRs (the docs rebuild with their new canonical URLs). + +## Checks + +```sh +for p in "" LeviLamina/ LeviLamina/api/ LegacyScriptEngine/ lip/ LeviLauncher/ BeDD/ bedboo/ mods/ blog/; do + curl -s -o /dev/null -w "%{http_code} https://levimc.org/$p\n" "https://levimc.org/$p" +done +curl -s https://levimc.org/LeviLaunchroid/api/hook | grep -o 'rel="canonical" href="[^"]*"' +node legacy/build.test.mjs --live # every legacy redirect target answers 200 without a redirect +curl -s https://docs.levimc.org/LeviLamina/ | grep -o 'location.replace([^)]*)' +``` + +Then, in Google Search Console, submit the docs sitemaps (`https://levimc.org//sitemap.xml`; `robots.txt` +lists them too). *Change of Address* expects 301s from docs.levimc.org, so it needs the Cloudflare rule above. + +## Rolling back + +1. Remove the domain from LiteLDev/liteldev.github.io's Pages and from LiteLDev/docs.levimc.org's. +2. Rename LiteLDev/liteldev.github.io back to `levimc.org`, and give it the domain levimc.org again. +3. Rename LiteLDev/docs.levimc.org back to `liteldev.github.io`, revert its last commit, and set its domain to + docs.levimc.org. +4. Revert LiteLDev/levimc.org#99 and the project PRs. diff --git a/README.md b/README.md index e156589..3752905 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ styled with the shared LeviMC design system, levimc-kit, which lives here in [`k **levimc-kit is the one source of the LeviMC chrome** — the bar on top (Home · Projects ▾ · Mods · Blog · Community · About, language · theme · GitHub), the footer, the theme and the docs engine — for every LeviMC site: levimc.org -(and LeviMC Mods at levimc.org/mods/, see below), docs.levimc.org and the project docs (LeviLamina with its Doxygen API, LegacyScriptEngine, lip, +(and LeviMC Mods at levimc.org/mods/, see below) and the project docs at levimc.org// (LeviLamina with its Doxygen API, LegacyScriptEngine, lip, LeviLauncher for Windows and Android). Every deploy publishes it at (`kit/scripts/publish-kit.mjs`); the other sites fetch it when they build (`scripts/fetch-kit.mjs`, run by their package install) and never edit it. After a deploy that changed the kit, the `sync` job rebuilds every site (with the `KIT_SYNC_TOKEN` secret: a @@ -74,6 +74,10 @@ npm run smoke:kit - `content/blog/`, `blog/`, `src/blog/` — the blog (see below) - `prerender.mjs` — writes `dist//index.html`, `404.html`, `sitemap.xml`, `robots.txt`; modulepreloads each page's chunk (from Vite's manifest) and a blog post's markdown chunk +- `legacy/` — the redirect pages of retired docs sites (`/LeviLaunchroid/…`, `/preloader-android/…`, + `/LiteXLoader/…`) and the forwarding map at the top of `404.html` (other forms of those URLs, and wrongly cased + project paths like `/levilamina/` → `/LeviLamina/`). `node legacy/build.mjs dist` (the last step of `npm run build`) + writes them; the table is `legacy/redirects.mjs`. They moved here from LiteLDev/liteldev.github.io with the docs. ## Blog @@ -150,6 +154,15 @@ the latest release, so the history is that file: `.github/workflows/versions.yml `node versions/update.mjs` adds the release Mojang names now, and a new one is committed and deployed. A new key is a line in `DOWNLOADS` in `versions/update.mjs` and a list in the file. `npm test` checks the file's shape. +## Project docs + +Each project's docs are published by its own repository at `levimc.org//` (LeviLamina, LegacyScriptEngine, +lip, LeviLauncher, BeDD, bedboo): GitHub Pages serves a project repository's site below the organisation site's +domain, and this repository is the organisation site. A path that a project with Pages owns is never this site's, so +no route here may start with a repository's name. `robots.txt` lists their sitemaps; the bar and footer load them +in full (`isAppPath` in `src/components/SiteHeader.tsx`). They were at docs.levimc.org until the move described in +[MIGRATION.md](MIGRATION.md); docs.levimc.org (LiteLDev/docs.levimc.org) forwards every URL to the same path here. + ## LeviChan A small LeviChan head peeks over the top edge of the home hero's showcase card (`src/levichan/LeviChanPeek.tsx`). diff --git a/kit/README.md b/kit/README.md index 7ababeb..e8cdd34 100644 --- a/kit/README.md +++ b/kit/README.md @@ -1,7 +1,7 @@ # levimc-kit The shared design system and static docs engine for every LeviMC website — levimc.org (with LeviMC Mods at /mods/) and -the project docs at `docs.levimc.org//` (LeviLamina, LegacyScriptEngine, lip, LeviLauncher — Windows and +the project docs at `levimc.org//` (LeviLamina, LegacyScriptEngine, lip, LeviLauncher — Windows and Android in one site — Be.D.D. and bedboo), plus the Doxygen API reference. **Design concept: "Impression, Craft".** Monet's Giverny rendered as if built in Minecraft. @@ -96,14 +96,14 @@ levimc-kit/ │ ├── kit.css kit-chrome.css kit-nojs-dark.css │ ├── kit.js (built from kit.src.js) theme-init.js theme-init-static.js theme-init-doxygen.js │ ├── globalbar.html footer.html i18n/{globalbar,footer}..html -│ ├── pages/index.html pages/404.html docs.levimc.org root redirect + themed 404 +│ ├── pages/index.html pages/404.html former docs.levimc.org root redirect + themed 404 │ ├── doxygen/header.html footer.html doxygen-kit.css gen-header.mjs header-parts.json patch-navtree.mjs │ └── icons/ grass.svg levimc.svg nojs-dark.mjs snippets.tsx build-static.mjs ├── scripts/ publish-kit · fetch-kit · chrome-parity · serve-pages · linkcheck · url-parity · text-parity · smoke · shot · vendor · mkdocs-nav ├── tests/ prefs.test.mjs (node --test: cookies, locale mapping, inline scripts) · │ static.test.mjs (no-JS dark CSS, kit.js: footer year, chrome-only translation) · │ render.test.mjs (rendering budget of the CSS, backdrop tiles, hero files) · -│ cross-site.e2e.mjs (Playwright: preferences shared by levimc.org + docs.levimc.org) +│ cross-site.e2e.mjs (Playwright: preferences shared by levimc.org and a docs site at levimc.org//) ├── demo/ demo sites (not published): docs (suffix/directory/pymdownx), lip (folder/html/vitepress), │ single (the docs as a single-locale site), app/ (plain Vite + React app, the │ levimc.org / levimc.org/mods shape); pinned package-lock.json @@ -266,7 +266,7 @@ GitHub Actions (Pages): - uses: actions/setup-node@v4 with: { node-version: 24 } - run: npm ci && npm run build -- run: node kit/scripts/linkcheck.mjs dist --base // --site-origin https://docs.levimc.org +- run: node kit/scripts/linkcheck.mjs dist --base // --site-origin https://levimc.org - uses: actions/upload-pages-artifact@v5 with: { path: dist } ``` @@ -328,7 +328,7 @@ export default defineDocsConfig({ … }); | `sidebar` | `'tabs'` (default) \| `'tree'` \| `false` \| `SidebarConfig` \| `{ [locale]: SidebarConfig }` | `'tabs'` = the LeviMC model: every top-level `nav` entry is a section (a tab) and its tree is the sidebar of its pages. The object forms (VitePress array / `{ '/guide/': [...] }` multi-sidebar) are **deprecated** (kit 2.19, build warning) but keep working | | `layouts` | `{ name: './path/Component.tsx' }` | custom page layouts for `layout: ` frontmatter (props: `CustomLayoutProps` from `kit/docs/app/layout-api.ts`) | | `lastUpdated` | `true` | `git log` timestamp per file; silently absent without git history | -| `hostname` | `'https://docs.levimc.org'` | canonical / og:url / hreflang origin (defaults to `sitemap.hostname`) | +| `hostname` | `'https://levimc.org'` | canonical / og:url / hreflang origin (defaults to `sitemap.hostname`) | | `sitemap` | `{ hostname }` \| `false` | | | `head` | `[[tag, attrs, content?], …]` | extra head tags (VitePress format) | | `outline` | `[2, 4]` (python-markdown) / `[2, 3]` (commonmark) | "On this page" levels (`outline: false` in frontmatter hides it) | @@ -349,7 +349,7 @@ export default defineDocsConfig({ … }); { 'Install': 'user_guides/install.md' } // titled (translated via navTranslations) { 'User Guides': [ … ] } // group { 'About': 'https://levimc.org/about/' } // external -{ 'Doxygen API': 'https://docs.levimc.org/LeviLamina/api/' } // same site, no docs page (or '/LeviLamina/api/'): +{ 'Doxygen API': 'https://levimc.org/LeviLamina/api/' } // same site, no docs page (or '/LeviLamina/api/'): // opened in place like a page, no external mark { text: 'Guide', link: '/guide/quick-start' } // VitePress (root-absolute, locale prefix allowed) { text: 'Developer', items: [ … ], collapsed: true } // VitePress group / dropdown @@ -624,7 +624,7 @@ Theme and language are one choice for all of levimc.org and *.levimc.org (`compo the base language, otherwise English. The same algorithm runs inline (`PREFS_CORE_JS`) in the docs root redirect and kit.js; `tests/prefs.test.mjs` keeps both in step. * `tests/cross-site.e2e.mjs` proves the sharing in Chromium with the real cookie rules of - https://levimc.org and https://docs.levimc.org (requests answered from local builds). + https://levimc.org and https://levimc.org (requests answered from local builds). ## Components @@ -664,7 +664,7 @@ Canonical cross-site URLs (exact, no redirect): Home `https://levimc.org/`, Proj GitHub organisation) `https://github.com/LiteLDev`, Community `https://levimc.org/community/`, About `https://levimc.org/about/`, Mods (LeviMC Mods, id `mods`) `https://levimc.org/mods/`, Blog `https://levimc.org/blog/`, GitHub `https://github.com/LiteLDev`, -Docs `https://docs.levimc.org/{LeviLamina,LegacyScriptEngine,lip,LeviLauncher,BeDD,bedboo}/`, +Docs `https://levimc.org/{LeviLamina,LegacyScriptEngine,lip,LeviLauncher,BeDD,bedboo}/`, Discord `https://discord.gg/v5R5P4vRZk`, Telegram `https://t.me/LiteLoader`, X `https://x.com/levimc_org`, YouTube `https://www.youtube.com/@LeviLamina`, `mailto:contact@levimc.org`. lip's repository is `https://github.com/LiteLDev/lip` (`futrime/lip` redirects). @@ -691,12 +691,12 @@ YouTube `https://www.youtube.com/@LeviLamina`, `mailto:contact@levimc.org`. lip' docs header and layout (below). * `theme-init.js` (React apps), `theme-init-static.js` (static pages: also hides the chrome for ≤ 1.5 s while kit.js translates it, so it never flashes in English), `theme-init-doxygen.js` — blocking head scripts. -* `pages/index.html` (docs.levimc.org root → levimc.org redirect, redirect tags before any stylesheet, with +* `pages/index.html` (the former docs.levimc.org root → levimc.org redirect, redirect tags before any stylesheet, with project cards) and `pages/404.html` (the one 404 of every site: `.kit-notfound` card with the red "Error 404" label, title `Page not found - LeviMC Docs`, the levimc.org action, then the projects with docs): skip link, generator meta, no-JS dark theme, footer year, the LeviMC mark as favicon; they reference assets under - `/levimc-kit/` (copy `kit.css`, `kit.js`, `kit-nojs-dark.css`, `icons/`, `levimc.svg` there; liteldev.github.io's - `scripts/build-site.mjs` copies exactly what they reference). + `/levimc-kit/` (copy `kit.css`, `kit.js`, `kit-nojs-dark.css`, `icons/`, `levimc.svg` there; levimc.org's + `legacy/build.mjs` builds its legacy redirect pages from `pages/404.html` and copies exactly what they reference). ### LeviLamina Doxygen (`docs/api/`) @@ -776,15 +776,15 @@ All are Node ESM with no dependencies beyond Playwright (where noted). node kit/scripts/serve-pages.mjs dist --base /LeviLamina/ --port 4173 # internal links (+ redirects + #anchors); --external checks every external URL with curl -node kit/scripts/linkcheck.mjs dist --base /LeviLamina/ --site-origin https://docs.levimc.org \ +node kit/scripts/linkcheck.mjs dist --base /LeviLamina/ --site-origin https://levimc.org \ [--external] [--allow-redirect-hosts aka.ms,discord.gg,qm.qq.com] [--ignore-paths /LeviLamina/api/] [--json out.json] # every live URL (sitemap.xml, else crawl) must answer 200 with 0 redirects locally; # --anchors also requires every live heading id (old #deep-links) to exist on the local page -node kit/scripts/url-parity.mjs --live https://docs.levimc.org/LeviLamina/ --local http://127.0.0.1:4173/LeviLamina/ --anchors +node kit/scripts/url-parity.mjs --live https://levimc.org/LeviLamina/ --local http://127.0.0.1:4173/LeviLamina/ --anchors # word-level text diff of the main content, live vs local (Playwright) -node kit/scripts/text-parity.mjs --live https://docs.levimc.org/LeviLamina/ --local http://127.0.0.1:4173/LeviLamina/ \ +node kit/scripts/text-parity.mjs --live https://levimc.org/LeviLamina/ --local http://127.0.0.1:4173/LeviLamina/ \ [--paths a/,b/ | --paths-file f] [--live-selector 'article.md-content__inner' | '.vp-doc'] [--json out.json] # a path may differ per side: --paths 'daemon/overview.html=>daemon/overview/' @@ -870,13 +870,13 @@ External link verdicts: `ok`, `ok-redirect` (`/releases/latest` and allow-listed 1. Vendor the kit; add `package.json` (template), `tsconfig.json`, `vite.config.ts`, `.gitignore`. 2. `node kit/scripts/mkdocs-nav.mjs mkdocs.yml` → paste into `docs.config.ts`. Keep `urlStyle: 'directory'`, `i18n.mode: 'suffix'` (locales `en` default + `zh`, `lang: 'zh'` like the live site), `slug: 'pymdownx'`, - `markdown.compat: 'python-markdown'`, `sidebar: 'tabs'`, `hostname`/`sitemap: { hostname: 'https://docs.levimc.org' }`. + `markdown.compat: 'python-markdown'`, `sidebar: 'tabs'`, `hostname`/`sitemap: { hostname: 'https://levimc.org' }`. 3. `exclude: ['overrides/**']` (theme overrides are not content). Delete `mkdocs.yml`, `requirements.txt`, `overrides/` once the port is merged (the language-redirect script there is replaced by the kit's). 4. `logo`/`favicon` paths stay as in `theme.logo`/`theme.favicon` (they are copied verbatim). 5. `editLink: 'https://github.com/LiteLDev//edit///:path'`. -6. Fix nav entries pointing at external own-site URLs: `https://docs.levimc.org/LeviLamina/api` → - `https://docs.levimc.org/LeviLamina/api/`; `https://levimc.org/about` → `https://levimc.org/about/`. +6. Fix nav entries pointing at external own-site URLs: `https://levimc.org/LeviLamina/api` → + `https://levimc.org/LeviLamina/api/`; `https://levimc.org/about` → `https://levimc.org/about/`. 7. `npm run build` — fix every warning (unresolved links, missing anchors). Known in LeviLamina today: `build_guide(.zh).md` links `architecture.md` (should be `../architecture.md`) and `how_to_guides/testing_guide.md` (missing page). @@ -961,6 +961,22 @@ External link verdicts: `ok`, `ok-redirect` (`/releases/latest` and allow-listed ## Changelog +### 2.20.0 — unreleased + +**The project docs move from docs.levimc.org to levimc.org.** Each project's docs stay in its own repository and +keep their path: `https://docs.levimc.org//…` becomes `https://levimc.org//…` +(levimc.org's `MIGRATION.md` has the switch-over steps; docs.levimc.org forwards every URL to the same path). +* `PROJECTS[].docs` / `DOCS_PROJECTS[].url`, and so the Projects menu, the static chrome (`static/`), the Doxygen + header and the 404 cards, link `https://levimc.org//`. +* Docs links are same-origin links on levimc.org now: an app that passes `siteOrigin` + `linkComponent` must exclude + the docs paths in `isAppPath` (levimc.org's does), or its router would render its own 404 for them. Docs sites pass + no `siteOrigin` and need no change. +* `scripts/linkcheck.mjs --other-sites /mods/,/LeviLamina/`: own-origin paths that another build publishes are checked + as external URLs (with `--external`) instead of as files of this dist. +* `tests/cross-site.e2e.mjs` serves the docs build at `https://levimc.org//`. +* Migration for docs sites: set `hostname` / `sitemap.hostname` to `'https://levimc.org'` and + `linkcheck --site-origin https://levimc.org`, on the day of the switch (`demo/` and `package.template.json` show it). + ### 2.19.1 — 2026-11-08 **The Doxygen tree opens faster, and the drawer never shows an empty API Reference section.** @@ -1051,7 +1067,7 @@ layout thrash, icons resized to WebP at build time. ### 2.18.0 — 2026-11-06 **bedboo is back, with docs.** `LiteLDev/bedboo`, a Minecraft Bedrock Edition bot library with a mineflayer-compatible -API, is documented at `https://docs.levimc.org/bedboo/`; it rejoins Core after LeviLauncher, so the Projects menu +API, is documented at `https://levimc.org/bedboo/`; it rejoins Core after LeviLauncher, so the Projects menu (the projects with docs) lists it, and levimc.org has its project card again. * `ProjectId` `'bedboo'` (`projectBlurbs.bedboo` in every chrome language), with `docs`; `DocsProjectId` includes `'bedboo'`, so `DOCS_PROJECTS` (the docs.levimc.org root's cards) lists five projects. Its logo is @@ -1079,7 +1095,7 @@ are no longer listed under Core or Official mods, nor as levimc.org project card ### 2.15.0 — 2026-10-30 **Be.D.D. has its own docs and is no longer a mod.** Be.D.D. is a standalone testing toolkit now, documented at -`https://docs.levimc.org/BeDD/`, and has left LeviMC Mods: its Projects menu row and project card lead to its docs. +`https://levimc.org/BeDD/`, and has left LeviMC Mods: its Projects menu row and project card lead to its docs. * `PROJECTS`: `BeDD` has `docs` instead of `mod`; `DocsProjectId` includes `'BeDD'`, so `DOCS_PROJECTS` (the docs.levimc.org root's cards) lists it after LeviLauncher. * Compatible: sites only rebuild. @@ -1171,7 +1187,7 @@ LeviLauncher card), its `projectBlurbs` says "Bedrock launcher for Windows and A ### 2.8.0 — 2026-10-29 **The API reference is a tab of the docs.** A nav link to this site that is no docs page — e.g. LeviLamina's -Doxygen output merged into `dist/api/`, written `https://docs.levimc.org/LeviLamina/api/` (own `hostname` + `base`) +Doxygen output merged into `dist/api/`, written `https://levimc.org/LeviLamina/api/` (own `hostname` + `base`) or `/LeviLamina/api/` — is now a link of the site: opened in place like a page, without the external mark or a new tab (before, the first form was an external link and the second a build warning). Such links are not part of the previous / next page links. diff --git a/kit/VERSION b/kit/VERSION index b8e248f..7329e21 100644 --- a/kit/VERSION +++ b/kit/VERSION @@ -1 +1 @@ -2.19.1 +2.20.0 diff --git a/kit/components/GlobalBar.tsx b/kit/components/GlobalBar.tsx index 10a54ec..bf606eb 100644 --- a/kit/components/GlobalBar.tsx +++ b/kit/components/GlobalBar.tsx @@ -18,9 +18,9 @@ export interface GlobalBarLanguages { } export interface GlobalBarProps { - /** Which LeviMC site this is (highlights its tab; docs.levimc.org: 'projects'). */ + /** Which LeviMC site this is (highlights its tab; a project's docs, levimc.org//: 'projects'). */ current?: SiteId; - /** On docs.levimc.org: which project's docs are open (marked in the Projects menu; implies current='projects'). */ + /** On a project's docs (levimc.org//): which project's docs are open (marked in the Projects menu; implies current='projects'). */ currentProject?: ProjectId | string; /** @deprecated kit 1.x name of `currentProject`. */ currentDocs?: ProjectId | string; @@ -215,7 +215,7 @@ function chromeLanguageOptions(): LocaleOption[] { } /** - * The bar at the very top of every LeviMC site (levimc.org, levimc.org/mods/, docs.levimc.org/*, the Doxygen API + * The bar at the very top of every LeviMC site (levimc.org, levimc.org/mods/, the project docs at levimc.org//, the Doxygen API * pages and the static pages): the same brand, the same tabs (Home · Projects ▾ · Mods · Blog · Community · About) * and, on the right, the same controls (language, theme, GitHub → LiteLDev) everywhere. Only the current tab (and * on docs pages the current project in the Projects menu) and the language menu's options differ per site. Menus are
, so the bar works diff --git a/kit/components/projects.ts b/kit/components/projects.ts index ac19c48..8b5974c 100644 --- a/kit/components/projects.ts +++ b/kit/components/projects.ts @@ -22,7 +22,7 @@ export const LINKS = { /** * Tabs of the GlobalBar. `projects` is the Projects menu (kit 2: it replaces the Docs menu and the former - * levimc.org/projects/ page); on docs.levimc.org it is the current tab, with the open project marked in it. + * levimc.org/projects/ page); on a project's docs (levimc.org//) it is the current tab, with the open project marked in it. */ export type SiteId = 'home' | 'projects' | 'community' | 'about' | 'mods' | 'blog'; @@ -61,24 +61,24 @@ const modPage = (repo: string) => `${LINKS.mods}github.com/LiteLDev/${repo}/`; /** * Every LeviMC project, in the order of the Projects menu (grouped by `group`, see PROJECT_GROUPS). This is the one - * list of projects: the bar's Projects menu, the docs.levimc.org root and levimc.org's project cards all read it. + * list of projects: the bar's Projects menu, the docs' 404 page and levimc.org's project cards all read it. */ export const PROJECTS: readonly Project[] = [ - { id: 'LeviLamina', name: 'LeviLamina', group: 'core', repo: 'https://github.com/LiteLDev/LeviLamina', docs: 'https://docs.levimc.org/LeviLamina/', logo: logo('LeviLamina'), icon: 'grass' }, + { id: 'LeviLamina', name: 'LeviLamina', group: 'core', repo: 'https://github.com/LiteLDev/LeviLamina', docs: 'https://levimc.org/LeviLamina/', logo: logo('LeviLamina'), icon: 'grass' }, { id: 'LegacyScriptEngine', name: 'LegacyScriptEngine', group: 'core', repo: 'https://github.com/LiteLDev/LegacyScriptEngine', - docs: 'https://docs.levimc.org/LegacyScriptEngine/', + docs: 'https://levimc.org/LegacyScriptEngine/', logo: logo('LegacyScriptEngine'), icon: 'bookQuill', }, { id: 'LeviStone', name: 'LeviStone', group: 'core', repo: 'https://github.com/LiteLDev/LeviStone', logo: logo('LeviStone'), icon: 'emerald' }, - { id: 'lip', name: 'lip', group: 'core', repo: 'https://github.com/LiteLDev/lip', docs: 'https://docs.levimc.org/lip/', logo: logo('lip'), icon: 'chest' }, - { id: 'LeviLauncher', name: 'LeviLauncher', group: 'core', repo: 'https://github.com/LiteLDev/LeviLauncher', docs: 'https://docs.levimc.org/LeviLauncher/', logo: logo('LeviLauncher'), icon: 'map' }, - { id: 'BeDD', name: 'Be.D.D.', group: 'core', repo: 'https://github.com/LiteLDev/BeDD', docs: 'https://docs.levimc.org/BeDD/', logo: logo('BeDD'), icon: 'monitor' }, - { id: 'bedboo', name: 'bedboo', group: 'core', repo: 'https://github.com/LiteLDev/bedboo', docs: 'https://docs.levimc.org/bedboo/', logo: logo('bedboo'), icon: 'pickaxe' }, + { id: 'lip', name: 'lip', group: 'core', repo: 'https://github.com/LiteLDev/lip', docs: 'https://levimc.org/lip/', logo: logo('lip'), icon: 'chest' }, + { id: 'LeviLauncher', name: 'LeviLauncher', group: 'core', repo: 'https://github.com/LiteLDev/LeviLauncher', docs: 'https://levimc.org/LeviLauncher/', logo: logo('LeviLauncher'), icon: 'map' }, + { id: 'BeDD', name: 'Be.D.D.', group: 'core', repo: 'https://github.com/LiteLDev/BeDD', docs: 'https://levimc.org/BeDD/', logo: logo('BeDD'), icon: 'monitor' }, + { id: 'bedboo', name: 'bedboo', group: 'core', repo: 'https://github.com/LiteLDev/bedboo', docs: 'https://levimc.org/bedboo/', logo: logo('bedboo'), icon: 'pickaxe' }, { id: 'LeviOptimize', name: 'LeviOptimize', group: 'mods', repo: 'https://github.com/LiteLDev/LeviOptimize', mod: modPage('LeviOptimize'), logo: logo('LeviOptimize'), icon: 'potion' }, { id: 'LeviAntiCheat', name: 'LeviAntiCheat', group: 'mods', repo: 'https://github.com/LiteLDev/LeviAntiCheat', mod: modPage('LeviAntiCheat'), logo: logo('LeviAntiCheat'), icon: 'torch' }, { id: 'MoreDimensions', name: 'MoreDimensions', group: 'mods', repo: 'https://github.com/LiteLDev/MoreDimensions', mod: modPage('MoreDimensions'), logo: logo('MoreDimensions'), icon: 'compass' }, @@ -91,7 +91,7 @@ export function projectHome(p: Project): string { export const PROJECT_GROUPS: readonly ProjectGroupId[] = ['core', 'mods']; -/** The projects that have a documentation site (docs.levimc.org//). */ +/** The projects that have a documentation site (levimc.org//, published by the project's repository). */ export type DocsProjectId = 'LeviLamina' | 'LegacyScriptEngine' | 'lip' | 'LeviLauncher' | 'BeDD' | 'bedboo'; export interface DocsProject { @@ -104,7 +104,7 @@ export interface DocsProject { icon: PixelIconName; } -/** The projects with docs, in menu order (the docs.levimc.org root's cards). */ +/** The projects with docs, in menu order (the cards of the docs' 404 page). */ export const DOCS_PROJECTS: readonly DocsProject[] = PROJECTS.filter((p) => p.docs).map((p) => ({ id: p.id as DocsProjectId, name: p.name, diff --git a/kit/components/version.ts b/kit/components/version.ts index 2d75895..50a176d 100644 --- a/kit/components/version.ts +++ b/kit/components/version.ts @@ -1,5 +1,5 @@ // The kit version (keep in sync with ../VERSION; static/build-static.mjs and the tests check it). -export const KIT_VERSION = '2.19.1'; +export const KIT_VERSION = '2.20.0'; /** * Content hash of the published kit (scripts/publish-kit.mjs stamps it into the copy levimc.org publishes, and into * levimc.org's own build): every site that fetched the same kit shows the same build, so a stale deployment is diff --git a/kit/demo/docs.config.ts b/kit/demo/docs.config.ts index 43721e3..639ff41 100644 --- a/kit/demo/docs.config.ts +++ b/kit/demo/docs.config.ts @@ -22,8 +22,8 @@ export default defineDocsConfig({ : undefined, }, contentDir: 'content', - hostname: 'https://docs.levimc.org', - sitemap: { hostname: 'https://docs.levimc.org' }, + hostname: 'https://levimc.org', + sitemap: { hostname: 'https://levimc.org' }, i18n: { mode: 'suffix', defaultLocale: 'en', diff --git a/kit/demo/lip.config.ts b/kit/demo/lip.config.ts index 4590e34..f4bcbf7 100644 --- a/kit/demo/lip.config.ts +++ b/kit/demo/lip.config.ts @@ -95,8 +95,8 @@ export default defineDocsConfig({ outDir: 'dist-lip', repo: 'https://github.com/LiteLDev/lip', editLink: 'https://github.com/LiteLDev/lip/edit/main/docs/:path', - hostname: 'https://docs.levimc.org', - sitemap: { hostname: 'https://docs.levimc.org' }, + hostname: 'https://levimc.org', + sitemap: { hostname: 'https://levimc.org' }, i18n: { mode: 'folder', defaultLocale: 'root', diff --git a/kit/demo/package.json b/kit/demo/package.json index 7e1a652..36012ec 100644 --- a/kit/demo/package.json +++ b/kit/demo/package.json @@ -16,7 +16,7 @@ "preview:lip": "node kit/scripts/serve-pages.mjs dist-lip --base /lip/ --port 4174", "preview:single": "node kit/scripts/serve-pages.mjs dist-single --base /Single/ --port 4176", "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.app.json", - "linkcheck": "node kit/scripts/linkcheck.mjs dist --base /Demo/ --site-origin https://docs.levimc.org", + "linkcheck": "node kit/scripts/linkcheck.mjs dist --base /Demo/ --site-origin https://levimc.org", "smoke": "node kit/scripts/smoke.mjs --url http://127.0.0.1:4173/Demo/", "smoke:single": "node kit/scripts/smoke.mjs --url http://127.0.0.1:4176/Single/", "build:app": "vite build app && vite build app --ssr src/entry-server.tsx --outDir .kit/ssr && node app/prerender.mjs", diff --git a/kit/demo/showcase/Showcase.tsx b/kit/demo/showcase/Showcase.tsx index 89870a2..531550c 100644 --- a/kit/demo/showcase/Showcase.tsx +++ b/kit/demo/showcase/Showcase.tsx @@ -209,9 +209,9 @@ export default function Showcase({ route, page, site }: CustomLayoutProps) {
- - - + + +
diff --git a/kit/package.template.json b/kit/package.template.json index 993aa09..f8b25f1 100644 --- a/kit/package.template.json +++ b/kit/package.template.json @@ -10,7 +10,7 @@ "build": "node kit/docs/build.mjs", "preview": "node kit/scripts/serve-pages.mjs dist --base // --port 4173", "typecheck": "tsc --noEmit", - "linkcheck": "node kit/scripts/linkcheck.mjs dist --base // --site-origin https://docs.levimc.org", + "linkcheck": "node kit/scripts/linkcheck.mjs dist --base // --site-origin https://levimc.org", "smoke": "node kit/scripts/smoke.mjs --url http://127.0.0.1:4173//", "smoke:app": "node kit/scripts/smoke.mjs --app --url http://127.0.0.1:4173/", "ssg:build": "vite build && vite build --ssr src/entry-server.tsx --outDir .kit/ssr && node prerender.mjs" diff --git a/kit/scripts/chrome-parity.mjs b/kit/scripts/chrome-parity.mjs index 5af1f6e..4eb7701 100644 --- a/kit/scripts/chrome-parity.mjs +++ b/kit/scripts/chrome-parity.mjs @@ -14,12 +14,11 @@ const DEFAULT_URLS = [ 'https://levimc.org/', 'https://levimc.org/blog/', 'https://levimc.org/mods/', - 'https://docs.levimc.org/', - 'https://docs.levimc.org/LeviLamina/', - 'https://docs.levimc.org/LeviLamina/api/index.html', - 'https://docs.levimc.org/LegacyScriptEngine/', - 'https://docs.levimc.org/lip/', - 'https://docs.levimc.org/LeviLauncher/', + 'https://levimc.org/LeviLamina/', + 'https://levimc.org/LeviLamina/api/index.html', + 'https://levimc.org/LegacyScriptEngine/', + 'https://levimc.org/lip/', + 'https://levimc.org/LeviLauncher/', ]; const urls = process.argv.slice(2).filter((a) => !a.startsWith('--')); const list = urls.length ? urls : DEFAULT_URLS; diff --git a/kit/scripts/linkcheck.mjs b/kit/scripts/linkcheck.mjs index 122de00..4d9f29a 100644 --- a/kit/scripts/linkcheck.mjs +++ b/kit/scripts/linkcheck.mjs @@ -1,13 +1,16 @@ #!/usr/bin/env node // Link checker for a built static site, with GitHub Pages semantics. // -// node linkcheck.mjs --base // --site-origin https://docs.levimc.org +// node linkcheck.mjs --base // --site-origin https://levimc.org // [--external] [--allow-redirect-hosts aka.ms,discord.gg,qm.qq.com] -// [--ignore-paths /LeviLamina/api/,/other/] [--json report.json] [--concurrency 8] [--quiet] +// [--ignore-paths /LeviLamina/api/,/other/] [--other-sites /mods/,/LeviLamina/] +// [--json report.json] [--concurrency 8] [--quiet] // // Internal links (relative, root-relative and absolute links to ) are resolved against // the dist folder exactly like GitHub Pages serves it (see serve-pages.mjs): broken targets, targets that // only work through a redirect (e.g. missing trailing slash) and missing #anchors are errors. +// --ignore-paths skips links below those paths; --other-sites treats them as external URLs (paths of the same +// origin that another build publishes: levimc.org// is each project's docs, not part of levimc.org's dist). // With --external every external URL is fetched once with curl (honours HTTP(S)_PROXY), following // redirects manually; redirects are reported unless the URL ends in /releases/latest or the host is // allow-listed. Exit code is 1 when there are internal errors (external problems are reported only, @@ -21,7 +24,7 @@ import { resolvePagesPath } from './serve-pages.mjs'; const args = process.argv.slice(2); const opt = (n, d) => (args.includes(n) ? args[args.indexOf(n) + 1] : d); const flag = (n) => args.includes(n); -const VALUE_OPTS = new Set(['--base', '--site-origin', '--allow-redirect-hosts', '--ignore-paths', '--json', '--concurrency']); +const VALUE_OPTS = new Set(['--base', '--site-origin', '--allow-redirect-hosts', '--ignore-paths', '--other-sites', '--json', '--concurrency']); const positional = args.filter((a, i) => !a.startsWith('--') && !VALUE_OPTS.has(args[i - 1])); const dist = resolve(positional[0] ?? 'dist'); let base = opt('--base', '/'); @@ -33,6 +36,7 @@ const allowHosts = (opt('--allow-redirect-hosts', 'aka.ms,discord.gg,qm.qq.com,t .map((s) => s.trim().toLowerCase()) .filter(Boolean); const ignorePaths = (opt('--ignore-paths', '') || '').split(',').filter(Boolean); +const otherSites = (opt('--other-sites', '') || '').split(',').filter(Boolean); const quiet = flag('--quiet'); const concurrency = Number(opt('--concurrency', '8')); @@ -116,8 +120,9 @@ for (const file of files) { continue; } const isOwn = u.origin === 'http://site.invalid' || (origin && u.origin === origin); - if (!isOwn || !u.pathname.startsWith(base) || ignorePaths.some((p) => u.pathname.startsWith(p))) { - if (isOwn && ignorePaths.some((p) => u.pathname.startsWith(p))) { + const other = isOwn && otherSites.some((p) => u.pathname.startsWith(p)); + if (!isOwn || other || !u.pathname.startsWith(base) || ignorePaths.some((p) => u.pathname.startsWith(p))) { + if (isOwn && !other && ignorePaths.some((p) => u.pathname.startsWith(p))) { internal.ignored++; continue; } diff --git a/kit/scripts/smoke.mjs b/kit/scripts/smoke.mjs index 41384c8..d80469b 100644 --- a/kit/scripts/smoke.mjs +++ b/kit/scripts/smoke.mjs @@ -330,7 +330,7 @@ await check('phone (390px): bar controls visible, one menu with the bar links, n await p.keyboard.press('Escape'); } for (const [key, url] of CANONICAL_TABS) if (url) assert(links.some((h) => h === url || new URL(h).pathname === new URL(url).pathname), `menu lacks ${key}`); - assert(links.filter((h) => h.startsWith('https://docs.levimc.org/')).length >= 4, 'menu lacks the docs projects'); + assert(links.filter((h) => /^https:\/\/levimc\.org\/(LeviLamina|LegacyScriptEngine|lip|LeviLauncher|BeDD|bedboo)\/$/.test(h)).length >= 4, 'menu lacks the docs projects'); const sideways = await p.evaluate(() => document.documentElement.scrollWidth > window.innerWidth + 1); assert(!sideways, 'horizontal page scroll at 390px'); assert(!e.length, e.join(' | ')); diff --git a/kit/scripts/text-parity.mjs b/kit/scripts/text-parity.mjs index 57d8e77..05f8e92 100644 --- a/kit/scripts/text-parity.mjs +++ b/kit/scripts/text-parity.mjs @@ -4,7 +4,7 @@ // glyphs, line-number gutters, copy buttons, code title bars, tab label bars, footnote back-links), // normalises whitespace and runs a word-level diff (CJK is compared per character). // -// node text-parity.mjs --live https://docs.levimc.org/LeviLamina/ --local http://127.0.0.1:4173/Demo/ +// node text-parity.mjs --live https://levimc.org/LeviLamina/ --local http://127.0.0.1:4173/Demo/ // [--paths a/,b/ | --paths-file list.txt] [--live-selector 'article.md-content__inner' | '.vp-doc'] // [--local-selector '[data-doc-content]'] [--json report.json] [--max-hunks 12] // diff --git a/kit/scripts/url-parity.mjs b/kit/scripts/url-parity.mjs index 4b81385..fa47473 100644 --- a/kit/scripts/url-parity.mjs +++ b/kit/scripts/url-parity.mjs @@ -2,8 +2,8 @@ // URL parity between the live site and a local build: every URL that exists today must still answer // 200 — with zero redirects — on the new build. // -// node url-parity.mjs --live https://docs.levimc.org/LeviLamina/ --local http://127.0.0.1:4173/LeviLamina/ -// [--paths a/,b/c/ | --paths-file list.txt] [--extra https://docs.levimc.org/LeviLamina/x/ ...] +// node url-parity.mjs --live https://levimc.org/LeviLamina/ --local http://127.0.0.1:4173/LeviLamina/ +// [--paths a/,b/c/ | --paths-file list.txt] [--extra https://levimc.org/LeviLamina/x/ ...] // [--no-sitemap] [--max 1500] [--anchors] [--json report.json] // // --anchors also compares the heading ids of every page (old deep links like page/#some-heading must keep diff --git a/kit/static/build-static.mjs b/kit/static/build-static.mjs index 7eafb25..18cf6f2 100644 --- a/kit/static/build-static.mjs +++ b/kit/static/build-static.mjs @@ -1,361 +1,361 @@ -#!/usr/bin/env node -// Builds the non-React chrome in static/ (run from an app that has the kit's dependencies installed): -// globalbar.html, footer.html GlobalBar (language + theme menus, GitHub) and SiteFooter as plain HTML (en) -// i18n/globalbar..html … the same for every UI locale -// theme-init.js, theme-init-doxygen.js pre-paint scripts (theme + language preference; load blocking in ) -// theme-init-static.js the same for static pages whose chrome kit.js translates -// kit.js vanilla runtime: theme/language menus, chrome translation, menus, year -// kit.css compiled Tailwind v4 + full kit theme (covers all static markup) -// kit-chrome.css chrome only, no preflight, layers unwrapped (Doxygen) -// kit-nojs-dark.css kit.css's dark theme for readers without JavaScript -// pages/index.html, pages/404.html docs.levimc.org root: redirect page + themed 404 -// doxygen/header.html, doxygen/footer.html Doxygen HTML_HEADER / HTML_FOOTER with the kit chrome -// -// Usage: node kit/static/build-static.mjs [--out ] [--asset-base /levimc-kit/] -import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath, pathToFileURL } from 'node:url'; -import { build, createServer } from 'vite'; -import react from '@vitejs/plugin-react'; -import tailwindcss from '@tailwindcss/vite'; -import { noJsDarkCss } from './nojs-dark.mjs'; - -const here = dirname(fileURLToPath(import.meta.url)); -const args = process.argv.slice(2); -const out = resolve(args.includes('--out') ? args[args.indexOf('--out') + 1] : here); -const assetBase = args.includes('--asset-base') ? args[args.indexOf('--asset-base') + 1] : '/levimc-kit/'; -mkdirSync(join(out, 'i18n'), { recursive: true }); -mkdirSync(join(out, 'pages'), { recursive: true }); -mkdirSync(join(out, 'doxygen'), { recursive: true }); - -// ---------------------------------------------------------------- 1. snippets via SSR -const server = await createServer({ root: here, configFile: false, logLevel: 'error', server: { middlewareMode: true }, appType: 'custom', plugins: [react()] }); -const snippets = await server.ssrLoadModule(join(here, 'snippets.tsx')); -const theme = await server.ssrLoadModule(join(here, '../components/theme.ts')); -const prefs = await server.ssrLoadModule(join(here, '../components/prefs.ts')); -const i18n = await server.ssrLoadModule(join(here, '../components/i18n.ts')); -const projects = await server.ssrLoadModule(join(here, '../components/projects.ts')); -const fonts = await server.ssrLoadModule(join(here, '../components/fonts.ts')); -const version = await server.ssrLoadModule(join(here, '../components/version.ts')); -// docs-engine labels (resources heading, 404 title); optional so the static build also runs on an older kit -const docsStrings = await server.ssrLoadModule(join(here, '../docs/shared/strings.ts')).then((m) => m.docsStrings, () => null); -await server.close(); - -const VERSION = readFileSync(join(here, '../VERSION'), 'utf8').trim(); -if (VERSION !== version.KIT_VERSION) throw new Error(`VERSION (${VERSION}) and components/version.ts (${version.KIT_VERSION}) differ`); -const GENERATOR = ``; - -const banner = (what) => `\n`; -writeFileSync(join(out, 'globalbar.html'), banner('GlobalBar') + snippets.globalBarHtml({ locale: 'en' }) + '\n'); -writeFileSync(join(out, 'footer.html'), banner('SiteFooter') + snippets.footerHtml({ locale: 'en' }) + '\n'); -for (const loc of i18n.UI_LOCALES) { - writeFileSync(join(out, 'i18n', `globalbar.${loc}.html`), banner(`GlobalBar ${loc}`) + snippets.globalBarHtml({ locale: loc }) + '\n'); - writeFileSync(join(out, 'i18n', `footer.${loc}.html`), banner(`SiteFooter ${loc}`) + snippets.footerHtml({ locale: loc }) + '\n'); -} -const staticInit = theme.createThemeInitScript({ chromeLocales: i18n.UI_LOCALES }); -const doxygenInit = theme.createThemeInitScript({ doxygen: true, chromeLocales: i18n.UI_LOCALES }); -writeFileSync(join(out, 'theme-init.js'), theme.createThemeInitScript() + '\n'); -writeFileSync(join(out, 'theme-init-static.js'), staticInit + '\n'); -writeFileSync(join(out, 'theme-init-doxygen.js'), doxygenInit + '\n'); - -// ---------------------------------------------------------------- 2. kit.js (static/kit.src.js + preferences + chrome strings) -const CHROME_KEYS = [ - 'home', 'projects', 'docs', 'mods', 'blog', 'community', 'about', 'network', 'menu', 'theme', 'themeAuto', 'themeLight', 'themeDark', - 'language', 'tagline', 'footerConnect', 'email', 'supportUs', 'allRepositories', 'skipToContent', -]; -const chromeStrings = Object.fromEntries( - i18n.UI_LOCALES.map((loc) => { - const t = i18n.UI_STRINGS[loc]; - return [loc, { ...Object.fromEntries(CHROME_KEYS.map((k) => [k, t[k]])), projectBlurbs: t.projectBlurbs, projectGroups: t.projectGroups }]; - }), -); -const json = (v) => JSON.stringify(v).replace(/ prefs.PREFS_CORE_JS) - .replace('/*__STRINGS__*/ {}', () => json(chromeStrings)) - .replace('/*__NAMES__*/ {}', () => json(i18n.UI_LOCALE_NAMES)); -writeFileSync(join(out, 'kit.js'), `/* levimc-kit ${VERSION} · generated by static/build-static.mjs from static/kit.src.js — do not edit */\n` + kitJs); - -// ---------------------------------------------------------------- 3. pages (docs.levimc.org root) -const esc = (s) => String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); -// `first`: tags that must run before any stylesheet (a redirect does not wait for kit.css and the web fonts) -const head = (title, { first = '', extra = '' } = {}) => `${first ? `\n ${first}` : ''} - - ${title} - ${GENERATOR} - - - ${fonts.FONT_HEAD_HTML} - - - ${extra ? `\n ${extra}` : ''}`; -const icon = (name) => `${assetBase}icons/${name.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase())}.svg`; -// the cards are page content (English, like the rest of the page): kit.js translates only the chrome -const docsCards = projects.DOCS_PROJECTS.map( - (p) => - `${p.name} ${esc(i18n.UI_STRINGS.en.projectBlurbs[p.id])}`, -).join('\n '); -const page = ({ title, first, extraHead, main, mainClass = 'kit-static-main' }) => ` - - - ${head(title, { first, extra: extraHead })} - - - ${esc(i18n.UI_STRINGS.en.skipToContent)} - - -
- ${snippets.globalBarHtml({ locale: 'en', current: 'projects' })} -
-${main} -
- ${snippets.footerHtml({ locale: 'en' })} -
- - - -`; -writeFileSync( - join(out, 'pages', 'index.html'), - page({ - title: 'LeviMC Docs', - first: `\n \n `, - main: `
-

docs.levimc.org

-

Redirecting to levimc.org…

-

Project documentation lives under docs.levimc.org/<Project>/:

-
- ${docsCards} -
-
`, - }), -); -// the 404 of docs.levimc.org (unknown project paths): the one 404 look of every LeviMC site (chrome.css .kit-notfound: -// compass, red "Error 404" label, title, text, actions), plus the projects with docs, like levimc.org's 404 -const en = i18n.UI_STRINGS.en; -writeFileSync( - join(out, 'pages', '404.html'), - page({ - title: `${esc(docsStrings ? docsStrings('en').pageNotFound : 'Page not found')} - LeviMC Docs`, - extraHead: '', - mainClass: 'kit-notfound', - main: `
- -

Error 404

-

${esc(en.notFoundTitle)}

-

${esc(en.notFoundText)}

- -

Or open the docs of a project:

-
- ${docsCards} -
-
`, - }), -); - -// ---------------------------------------------------------------- 4. Doxygen header/footer templates -// The API reference of LeviLamina (the only Doxygen site) carries the docs pages' header: the LeviMC bar (its -// language menu lists the docs' locales, its menu button opens the drawer), the project row (the docs SiteHeader -// markup: brand, section tabs with API Reference current, search = Doxygen's search box in the docs trigger's frame, -// resources) and the docs drawer. doxygen/gen-header.mjs renders header.html from the docs build's -// dist/_kit/nav.json (CI); the React-rendered parts it needs are written to doxygen/header-parts.json here, and -// doxygen/header.html is rendered from the fallback below (LeviLamina's sections) for local use. -const DOX_PROJECT = 'LeviLamina'; -const DOX_BASE = '/LeviLamina/'; -const DOX_REPO = 'https://github.com/LiteLDev/LeviLamina'; -const doxOnGithub = (lang) => (docsStrings ? docsStrings(lang).onGithub : '{name} on GitHub').replace('{name}', DOX_PROJECT); -const doxLocale = (lang, label, prefix, tabs) => ({ - lang, - label, - prefix, - title: DOX_PROJECT, - home: DOX_BASE + prefix, - tabs: tabs.map(([text, path, shared]) => ({ text, link: DOX_BASE + (shared ? '' : prefix) + path })), - resources: [{ kind: 'github', text: doxOnGithub(lang), link: DOX_REPO }], -}); -// the shape of the docs build's _kit/nav.json (same locales, sections and resources as LeviLamina's docs.config.ts) -const doxFallbackNav = { - en: doxLocale('en', 'English', '', [ - ['User Guides', 'user_guides/install/'], - ['Developer Guides', 'developer_guides/tutorials/create_your_first_mod/'], - ['API Guides', 'api_reference/'], - ['API Reference', 'api/', true], - ['Maintainer Guides', 'maintainer_guides/cpp_style_guide/'], - ]), - zh: doxLocale('zh', '简体中文', 'zh/', [ - ['用户指南', 'user_guides/install/'], - ['开发者指南', 'developer_guides/tutorials/create_your_first_mod/'], - ['API 指南', 'api_reference/'], - ['API 参考', 'api/', true], - ['维护者指南', 'maintainer_guides/cpp_style_guide/'], - ]), - 'zh-Hant': doxLocale('zh-Hant', '繁體中文', 'zh-Hant/', [ - ['用戶指南', 'user_guides/install/'], - ['開發者指南', 'developer_guides/tutorials/create_your_first_mod/'], - ['API 指南', 'api_reference/'], - ['API 參考', 'api/', true], - ['維護者指南', 'maintainer_guides/cpp_style_guide/'], - ]), -}; -// the bar with a placeholder language menu: gen-header fills in the docs' locales (buttons, see header-parts.langItem) -const KIT_SENTINEL = '__KIT_LANG__'; -let doxBar = snippets.globalBarHtml({ - locale: 'en', - currentProject: DOX_PROJECT, - menu: false, - drawerMenu: true, - languages: { options: [{ code: KIT_SENTINEL, label: KIT_SENTINEL, lang: KIT_SENTINEL }], current: KIT_SENTINEL }, -}); -const langItemRe = /`; - const end = doxBar.lastIndexOf(''); - if (end < 0) throw new Error('build-static: GlobalBar markup changed (menu button)'); - doxBar = doxBar.slice(0, end) + menuBtn + doxBar.slice(end); -} -const pickStrings = (loc) => { - const t = i18n.UI_STRINGS[loc]; - const d = docsStrings ? docsStrings(loc) : { resources: 'Resources' }; - return { mainNav: t.mainNav, search: t.search, menu: t.menu, close: t.close, onThisPage: t.onThisPage, network: t.network, skipToContent: t.skipToContent, resources: d.resources }; -}; -// inline after the row, before the first paint (the docs' navFitScript, measuring #top's row): the first state and -// the natural widths (window.__kitNavFit) kit.js computes every later state from -const doxFitScript = - `(function(){try{var d=document.documentElement,i=document.querySelector("#top > .kit-site-header-inner"),u=i&&i.querySelector(".kit-site-nav > ul"),` + - `t=i&&i.querySelector(".kit-search-trigger"),S=["search","tabs","drawer"],k,c,m,a,z;if(!u)return;d.removeAttribute("data-kit-nav-fit");a=u.firstElementChild;z=u.lastElementChild;` + - `if(u.clientWidth>0&&a&&z){c=getComputedStyle(i);m={w:i.clientWidth-parseFloat(c.paddingLeft)-parseFloat(c.paddingRight),need:z.getBoundingClientRect().right-a.getBoundingClientRect().left,have:u.clientWidth,` + - `trig:t?t.offsetWidth:0,rem:parseFloat(getComputedStyle(d).fontSize)||16,compact:matchMedia("(max-width: 1180px)").matches,` + - `loading:!!document.fonts&&document.fonts.status!=="loaded"};window.__kitNavFit=m}` + - `for(k=0;k/g, '/>'), - fitScript: doxFitScript, - uiLocales: i18n.UI_LOCALES, - strings: Object.fromEntries(i18n.UI_LOCALES.map((loc) => [loc, pickStrings(loc)])), - gbar: doxBar, - langItem, - langCheck, - networkList: snippets.globalNavListHtml({ locale: 'en', currentProject: DOX_PROJECT, brandHeading: true }), - icons: { - search: snippets.pixelIconHtml('search'), - close: snippets.pixelIconHtml('close'), - external: snippets.pixelIconHtml('external'), - github: snippets.brandIconHtml('github', 18), - github16: snippets.brandIconHtml('github', 16), - }, - fallbackNav: doxFallbackNav, -}; -writeFileSync(join(out, 'doxygen', 'header-parts.json'), JSON.stringify(headerParts, null, 1) + '\n'); -const { renderDoxygenHeader } = await import(pathToFileURL(join(here, 'doxygen', 'gen-header.mjs')).href); -writeFileSync(join(out, 'doxygen', 'header.html'), renderDoxygenHeader(doxFallbackNav, headerParts, { source: 'the kit fallback nav (build-static.mjs)' })); -// The credit links to https://www.doxygen.nl/index.html (www.doxygen.org/index.html answers 301 → http → 301 https). -const doxFooter = ` - - - - - - - - - - - -`; -writeFileSync(join(out, 'doxygen', 'footer.html'), doxFooter); - -// ---------------------------------------------------------------- 5. kit.css (Tailwind v4) + the no-JS dark theme -const tmp = join(out, '.css-build'); -await build({ - root: here, - configFile: false, - logLevel: 'warn', - plugins: [tailwindcss()], - build: { - outDir: tmp, - emptyOutDir: true, - cssMinify: true, - rollupOptions: { input: join(here, 'static-entry.css'), output: { assetFileNames: 'kit[extname]' } }, - }, -}); -const cssFile = readdirSync(tmp).find((f) => f.endsWith('.css')); -renameSync(join(tmp, cssFile), join(out, 'kit.css')); -rmSync(tmp, { recursive: true, force: true }); -writeFileSync(join(out, 'kit-nojs-dark.css'), noJsDarkCss(readFileSync(join(out, 'kit.css'), 'utf8'))); - -// kit-chrome.css: chrome only, no preflight, cascade layers unwrapped (for Doxygen and other foreign pages) -await build({ - root: here, - configFile: false, - logLevel: 'warn', - plugins: [tailwindcss()], - build: { - outDir: tmp, - emptyOutDir: true, - cssMinify: true, - rollupOptions: { input: join(here, 'chrome-entry.css'), output: { assetFileNames: 'kit-chrome[extname]' } }, - }, -}); -const chromeFile = readdirSync(tmp).find((f) => f.endsWith('.css')); -writeFileSync(join(out, 'kit-chrome.css'), unwrapLayers(readFileSync(join(tmp, chromeFile), 'utf8'))); -rmSync(tmp, { recursive: true, force: true }); - -/** Remove `@layer a,b;` statements and unwrap `@layer x { … }` blocks (brace matching, strings respected). */ -function unwrapLayers(css) { - let s = css.replace(/@layer\s+[\w-]+(\s*,\s*[\w-]+)*\s*;/g, ''); - for (;;) { - const m = /@layer\s+[\w-]+\s*\{/.exec(s); - if (!m) break; - let depth = 1; - let i = m.index + m[0].length; - let quote = null; - for (; i < s.length && depth > 0; i++) { - const c = s[i]; - if (quote) { - if (c === '\\') i++; - else if (c === quote) quote = null; - } else if (c === '"' || c === "'") quote = c; - else if (c === '{') depth++; - else if (c === '}') depth--; - } - s = s.slice(0, m.index) + s.slice(m.index + m[0].length, i - 1) + s.slice(i); - } - return s; -} -console.log(`static: wrote globalbar/footer snippets (${i18n.UI_LOCALES.length} locales), theme-init*.js, kit.js, pages/, doxygen/, kit.css, kit-chrome.css and kit-nojs-dark.css → ${out}`); -// copy pixel icons next to the pages (pages reference icons/*.svg) -mkdirSync(join(out, 'icons'), { recursive: true }); -for (const f of readdirSync(join(here, '../assets/icons'))) writeFileSync(join(out, 'icons', f), readFileSync(join(here, '../assets/icons', f))); -writeFileSync(join(out, 'grass.svg'), readFileSync(join(here, '../assets/icons/grass.svg'))); -// the LeviMC mark: the static pages' favicon (levimc.org's own) -writeFileSync(join(out, 'levimc.svg'), readFileSync(join(here, '../assets/levimc-mark.svg'))); +#!/usr/bin/env node +// Builds the non-React chrome in static/ (run from an app that has the kit's dependencies installed): +// globalbar.html, footer.html GlobalBar (language + theme menus, GitHub) and SiteFooter as plain HTML (en) +// i18n/globalbar..html … the same for every UI locale +// theme-init.js, theme-init-doxygen.js pre-paint scripts (theme + language preference; load blocking in ) +// theme-init-static.js the same for static pages whose chrome kit.js translates +// kit.js vanilla runtime: theme/language menus, chrome translation, menus, year +// kit.css compiled Tailwind v4 + full kit theme (covers all static markup) +// kit-chrome.css chrome only, no preflight, layers unwrapped (Doxygen) +// kit-nojs-dark.css kit.css's dark theme for readers without JavaScript +// pages/index.html, pages/404.html former docs.levimc.org root (redirect page) + themed 404 (legacy/build.mjs) +// doxygen/header.html, doxygen/footer.html Doxygen HTML_HEADER / HTML_FOOTER with the kit chrome +// +// Usage: node kit/static/build-static.mjs [--out ] [--asset-base /levimc-kit/] +import { mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { build, createServer } from 'vite'; +import react from '@vitejs/plugin-react'; +import tailwindcss from '@tailwindcss/vite'; +import { noJsDarkCss } from './nojs-dark.mjs'; + +const here = dirname(fileURLToPath(import.meta.url)); +const args = process.argv.slice(2); +const out = resolve(args.includes('--out') ? args[args.indexOf('--out') + 1] : here); +const assetBase = args.includes('--asset-base') ? args[args.indexOf('--asset-base') + 1] : '/levimc-kit/'; +mkdirSync(join(out, 'i18n'), { recursive: true }); +mkdirSync(join(out, 'pages'), { recursive: true }); +mkdirSync(join(out, 'doxygen'), { recursive: true }); + +// ---------------------------------------------------------------- 1. snippets via SSR +const server = await createServer({ root: here, configFile: false, logLevel: 'error', server: { middlewareMode: true }, appType: 'custom', plugins: [react()] }); +const snippets = await server.ssrLoadModule(join(here, 'snippets.tsx')); +const theme = await server.ssrLoadModule(join(here, '../components/theme.ts')); +const prefs = await server.ssrLoadModule(join(here, '../components/prefs.ts')); +const i18n = await server.ssrLoadModule(join(here, '../components/i18n.ts')); +const projects = await server.ssrLoadModule(join(here, '../components/projects.ts')); +const fonts = await server.ssrLoadModule(join(here, '../components/fonts.ts')); +const version = await server.ssrLoadModule(join(here, '../components/version.ts')); +// docs-engine labels (resources heading, 404 title); optional so the static build also runs on an older kit +const docsStrings = await server.ssrLoadModule(join(here, '../docs/shared/strings.ts')).then((m) => m.docsStrings, () => null); +await server.close(); + +const VERSION = readFileSync(join(here, '../VERSION'), 'utf8').trim(); +if (VERSION !== version.KIT_VERSION) throw new Error(`VERSION (${VERSION}) and components/version.ts (${version.KIT_VERSION}) differ`); +const GENERATOR = ``; + +const banner = (what) => `\n`; +writeFileSync(join(out, 'globalbar.html'), banner('GlobalBar') + snippets.globalBarHtml({ locale: 'en' }) + '\n'); +writeFileSync(join(out, 'footer.html'), banner('SiteFooter') + snippets.footerHtml({ locale: 'en' }) + '\n'); +for (const loc of i18n.UI_LOCALES) { + writeFileSync(join(out, 'i18n', `globalbar.${loc}.html`), banner(`GlobalBar ${loc}`) + snippets.globalBarHtml({ locale: loc }) + '\n'); + writeFileSync(join(out, 'i18n', `footer.${loc}.html`), banner(`SiteFooter ${loc}`) + snippets.footerHtml({ locale: loc }) + '\n'); +} +const staticInit = theme.createThemeInitScript({ chromeLocales: i18n.UI_LOCALES }); +const doxygenInit = theme.createThemeInitScript({ doxygen: true, chromeLocales: i18n.UI_LOCALES }); +writeFileSync(join(out, 'theme-init.js'), theme.createThemeInitScript() + '\n'); +writeFileSync(join(out, 'theme-init-static.js'), staticInit + '\n'); +writeFileSync(join(out, 'theme-init-doxygen.js'), doxygenInit + '\n'); + +// ---------------------------------------------------------------- 2. kit.js (static/kit.src.js + preferences + chrome strings) +const CHROME_KEYS = [ + 'home', 'projects', 'docs', 'mods', 'blog', 'community', 'about', 'network', 'menu', 'theme', 'themeAuto', 'themeLight', 'themeDark', + 'language', 'tagline', 'footerConnect', 'email', 'supportUs', 'allRepositories', 'skipToContent', +]; +const chromeStrings = Object.fromEntries( + i18n.UI_LOCALES.map((loc) => { + const t = i18n.UI_STRINGS[loc]; + return [loc, { ...Object.fromEntries(CHROME_KEYS.map((k) => [k, t[k]])), projectBlurbs: t.projectBlurbs, projectGroups: t.projectGroups }]; + }), +); +const json = (v) => JSON.stringify(v).replace(/ prefs.PREFS_CORE_JS) + .replace('/*__STRINGS__*/ {}', () => json(chromeStrings)) + .replace('/*__NAMES__*/ {}', () => json(i18n.UI_LOCALE_NAMES)); +writeFileSync(join(out, 'kit.js'), `/* levimc-kit ${VERSION} · generated by static/build-static.mjs from static/kit.src.js — do not edit */\n` + kitJs); + +// ---------------------------------------------------------------- 3. pages (former docs.levimc.org root, legacy redirects) +const esc = (s) => String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); +// `first`: tags that must run before any stylesheet (a redirect does not wait for kit.css and the web fonts) +const head = (title, { first = '', extra = '' } = {}) => `${first ? `\n ${first}` : ''} + + ${title} + ${GENERATOR} + + + ${fonts.FONT_HEAD_HTML} + + + ${extra ? `\n ${extra}` : ''}`; +const icon = (name) => `${assetBase}icons/${name.replace(/[A-Z]/g, (m) => '-' + m.toLowerCase())}.svg`; +// the cards are page content (English, like the rest of the page): kit.js translates only the chrome +const docsCards = projects.DOCS_PROJECTS.map( + (p) => + `${p.name} ${esc(i18n.UI_STRINGS.en.projectBlurbs[p.id])}`, +).join('\n '); +const page = ({ title, first, extraHead, main, mainClass = 'kit-static-main' }) => ` + + + ${head(title, { first, extra: extraHead })} + + + ${esc(i18n.UI_STRINGS.en.skipToContent)} + + +
+ ${snippets.globalBarHtml({ locale: 'en', current: 'projects' })} +
+${main} +
+ ${snippets.footerHtml({ locale: 'en' })} +
+ + + +`; +writeFileSync( + join(out, 'pages', 'index.html'), + page({ + title: 'LeviMC Docs', + first: `\n \n `, + main: `
+

docs.levimc.org

+

Redirecting to levimc.org…

+

Project documentation lives under levimc.org/<Project>/:

+
+ ${docsCards} +
+
`, + }), +); +// the 404 of the legacy docs pages (legacy/build.mjs): the one 404 look of every LeviMC site (chrome.css .kit-notfound: +// compass, red "Error 404" label, title, text, actions), plus the projects with docs, like levimc.org's 404 +const en = i18n.UI_STRINGS.en; +writeFileSync( + join(out, 'pages', '404.html'), + page({ + title: `${esc(docsStrings ? docsStrings('en').pageNotFound : 'Page not found')} - LeviMC Docs`, + extraHead: '', + mainClass: 'kit-notfound', + main: `
+ +

Error 404

+

${esc(en.notFoundTitle)}

+

${esc(en.notFoundText)}

+ +

Or open the docs of a project:

+
+ ${docsCards} +
+
`, + }), +); + +// ---------------------------------------------------------------- 4. Doxygen header/footer templates +// The API reference of LeviLamina (the only Doxygen site) carries the docs pages' header: the LeviMC bar (its +// language menu lists the docs' locales, its menu button opens the drawer), the project row (the docs SiteHeader +// markup: brand, section tabs with API Reference current, search = Doxygen's search box in the docs trigger's frame, +// resources) and the docs drawer. doxygen/gen-header.mjs renders header.html from the docs build's +// dist/_kit/nav.json (CI); the React-rendered parts it needs are written to doxygen/header-parts.json here, and +// doxygen/header.html is rendered from the fallback below (LeviLamina's sections) for local use. +const DOX_PROJECT = 'LeviLamina'; +const DOX_BASE = '/LeviLamina/'; +const DOX_REPO = 'https://github.com/LiteLDev/LeviLamina'; +const doxOnGithub = (lang) => (docsStrings ? docsStrings(lang).onGithub : '{name} on GitHub').replace('{name}', DOX_PROJECT); +const doxLocale = (lang, label, prefix, tabs) => ({ + lang, + label, + prefix, + title: DOX_PROJECT, + home: DOX_BASE + prefix, + tabs: tabs.map(([text, path, shared]) => ({ text, link: DOX_BASE + (shared ? '' : prefix) + path })), + resources: [{ kind: 'github', text: doxOnGithub(lang), link: DOX_REPO }], +}); +// the shape of the docs build's _kit/nav.json (same locales, sections and resources as LeviLamina's docs.config.ts) +const doxFallbackNav = { + en: doxLocale('en', 'English', '', [ + ['User Guides', 'user_guides/install/'], + ['Developer Guides', 'developer_guides/tutorials/create_your_first_mod/'], + ['API Guides', 'api_reference/'], + ['API Reference', 'api/', true], + ['Maintainer Guides', 'maintainer_guides/cpp_style_guide/'], + ]), + zh: doxLocale('zh', '简体中文', 'zh/', [ + ['用户指南', 'user_guides/install/'], + ['开发者指南', 'developer_guides/tutorials/create_your_first_mod/'], + ['API 指南', 'api_reference/'], + ['API 参考', 'api/', true], + ['维护者指南', 'maintainer_guides/cpp_style_guide/'], + ]), + 'zh-Hant': doxLocale('zh-Hant', '繁體中文', 'zh-Hant/', [ + ['用戶指南', 'user_guides/install/'], + ['開發者指南', 'developer_guides/tutorials/create_your_first_mod/'], + ['API 指南', 'api_reference/'], + ['API 參考', 'api/', true], + ['維護者指南', 'maintainer_guides/cpp_style_guide/'], + ]), +}; +// the bar with a placeholder language menu: gen-header fills in the docs' locales (buttons, see header-parts.langItem) +const KIT_SENTINEL = '__KIT_LANG__'; +let doxBar = snippets.globalBarHtml({ + locale: 'en', + currentProject: DOX_PROJECT, + menu: false, + drawerMenu: true, + languages: { options: [{ code: KIT_SENTINEL, label: KIT_SENTINEL, lang: KIT_SENTINEL }], current: KIT_SENTINEL }, +}); +const langItemRe = /`; + const end = doxBar.lastIndexOf(''); + if (end < 0) throw new Error('build-static: GlobalBar markup changed (menu button)'); + doxBar = doxBar.slice(0, end) + menuBtn + doxBar.slice(end); +} +const pickStrings = (loc) => { + const t = i18n.UI_STRINGS[loc]; + const d = docsStrings ? docsStrings(loc) : { resources: 'Resources' }; + return { mainNav: t.mainNav, search: t.search, menu: t.menu, close: t.close, onThisPage: t.onThisPage, network: t.network, skipToContent: t.skipToContent, resources: d.resources }; +}; +// inline after the row, before the first paint (the docs' navFitScript, measuring #top's row): the first state and +// the natural widths (window.__kitNavFit) kit.js computes every later state from +const doxFitScript = + `(function(){try{var d=document.documentElement,i=document.querySelector("#top > .kit-site-header-inner"),u=i&&i.querySelector(".kit-site-nav > ul"),` + + `t=i&&i.querySelector(".kit-search-trigger"),S=["search","tabs","drawer"],k,c,m,a,z;if(!u)return;d.removeAttribute("data-kit-nav-fit");a=u.firstElementChild;z=u.lastElementChild;` + + `if(u.clientWidth>0&&a&&z){c=getComputedStyle(i);m={w:i.clientWidth-parseFloat(c.paddingLeft)-parseFloat(c.paddingRight),need:z.getBoundingClientRect().right-a.getBoundingClientRect().left,have:u.clientWidth,` + + `trig:t?t.offsetWidth:0,rem:parseFloat(getComputedStyle(d).fontSize)||16,compact:matchMedia("(max-width: 1180px)").matches,` + + `loading:!!document.fonts&&document.fonts.status!=="loaded"};window.__kitNavFit=m}` + + `for(k=0;k/g, '/>'), + fitScript: doxFitScript, + uiLocales: i18n.UI_LOCALES, + strings: Object.fromEntries(i18n.UI_LOCALES.map((loc) => [loc, pickStrings(loc)])), + gbar: doxBar, + langItem, + langCheck, + networkList: snippets.globalNavListHtml({ locale: 'en', currentProject: DOX_PROJECT, brandHeading: true }), + icons: { + search: snippets.pixelIconHtml('search'), + close: snippets.pixelIconHtml('close'), + external: snippets.pixelIconHtml('external'), + github: snippets.brandIconHtml('github', 18), + github16: snippets.brandIconHtml('github', 16), + }, + fallbackNav: doxFallbackNav, +}; +writeFileSync(join(out, 'doxygen', 'header-parts.json'), JSON.stringify(headerParts, null, 1) + '\n'); +const { renderDoxygenHeader } = await import(pathToFileURL(join(here, 'doxygen', 'gen-header.mjs')).href); +writeFileSync(join(out, 'doxygen', 'header.html'), renderDoxygenHeader(doxFallbackNav, headerParts, { source: 'the kit fallback nav (build-static.mjs)' })); +// The credit links to https://www.doxygen.nl/index.html (www.doxygen.org/index.html answers 301 → http → 301 https). +const doxFooter = ` + + + + + + + + + + + +`; +writeFileSync(join(out, 'doxygen', 'footer.html'), doxFooter); + +// ---------------------------------------------------------------- 5. kit.css (Tailwind v4) + the no-JS dark theme +const tmp = join(out, '.css-build'); +await build({ + root: here, + configFile: false, + logLevel: 'warn', + plugins: [tailwindcss()], + build: { + outDir: tmp, + emptyOutDir: true, + cssMinify: true, + rollupOptions: { input: join(here, 'static-entry.css'), output: { assetFileNames: 'kit[extname]' } }, + }, +}); +const cssFile = readdirSync(tmp).find((f) => f.endsWith('.css')); +renameSync(join(tmp, cssFile), join(out, 'kit.css')); +rmSync(tmp, { recursive: true, force: true }); +writeFileSync(join(out, 'kit-nojs-dark.css'), noJsDarkCss(readFileSync(join(out, 'kit.css'), 'utf8'))); + +// kit-chrome.css: chrome only, no preflight, cascade layers unwrapped (for Doxygen and other foreign pages) +await build({ + root: here, + configFile: false, + logLevel: 'warn', + plugins: [tailwindcss()], + build: { + outDir: tmp, + emptyOutDir: true, + cssMinify: true, + rollupOptions: { input: join(here, 'chrome-entry.css'), output: { assetFileNames: 'kit-chrome[extname]' } }, + }, +}); +const chromeFile = readdirSync(tmp).find((f) => f.endsWith('.css')); +writeFileSync(join(out, 'kit-chrome.css'), unwrapLayers(readFileSync(join(tmp, chromeFile), 'utf8'))); +rmSync(tmp, { recursive: true, force: true }); + +/** Remove `@layer a,b;` statements and unwrap `@layer x { … }` blocks (brace matching, strings respected). */ +function unwrapLayers(css) { + let s = css.replace(/@layer\s+[\w-]+(\s*,\s*[\w-]+)*\s*;/g, ''); + for (;;) { + const m = /@layer\s+[\w-]+\s*\{/.exec(s); + if (!m) break; + let depth = 1; + let i = m.index + m[0].length; + let quote = null; + for (; i < s.length && depth > 0; i++) { + const c = s[i]; + if (quote) { + if (c === '\\') i++; + else if (c === quote) quote = null; + } else if (c === '"' || c === "'") quote = c; + else if (c === '{') depth++; + else if (c === '}') depth--; + } + s = s.slice(0, m.index) + s.slice(m.index + m[0].length, i - 1) + s.slice(i); + } + return s; +} +console.log(`static: wrote globalbar/footer snippets (${i18n.UI_LOCALES.length} locales), theme-init*.js, kit.js, pages/, doxygen/, kit.css, kit-chrome.css and kit-nojs-dark.css → ${out}`); +// copy pixel icons next to the pages (pages reference icons/*.svg) +mkdirSync(join(out, 'icons'), { recursive: true }); +for (const f of readdirSync(join(here, '../assets/icons'))) writeFileSync(join(out, 'icons', f), readFileSync(join(here, '../assets/icons', f))); +writeFileSync(join(out, 'grass.svg'), readFileSync(join(here, '../assets/icons/grass.svg'))); +// the LeviMC mark: the static pages' favicon (levimc.org's own) +writeFileSync(join(out, 'levimc.svg'), readFileSync(join(here, '../assets/levimc-mark.svg'))); diff --git a/kit/static/doxygen/footer.html b/kit/static/doxygen/footer.html index a246c36..09e937b 100644 --- a/kit/static/doxygen/footer.html +++ b/kit/static/doxygen/footer.html @@ -1,4 +1,4 @@ - + diff --git a/kit/static/doxygen/header-parts.json b/kit/static/doxygen/header-parts.json index 114e439..9d196bb 100644 --- a/kit/static/doxygen/header-parts.json +++ b/kit/static/doxygen/header-parts.json @@ -1,6 +1,6 @@ { - "version": "2.19.1", - "generator": "levimc-kit 2.19.1", + "version": "2.20.0", + "generator": "levimc-kit 2.20.0", "themeInit": "(function(){try{var PC={theme:\"levimc_theme\",lang:\"levimc_lang\"},PS={theme:\"levimc-theme\",lang:\"levimc-lang\"};function pv(k,v){return k===\"theme\"?(v===\"auto\"||v===\"light\"||v===\"dark\"):/^[A-Za-z]{2,3}(-[A-Za-z0-9]{1,8})*$/.test(v||\"\")}function pls(){try{return window.localStorage}catch(e){return null}}function wc(k,v){try{var h=location.hostname.toLowerCase().replace(/\\.$/,\"\"),d=h===\"levimc.org\"||h.slice(-11)===\".levimc.org\";document.cookie=PC[k]+\"=\"+encodeURIComponent(v)+\"; Path=/; Max-Age=31536000; SameSite=Lax\"+(d?\"; Domain=levimc.org\":\"\")+(location.protocol===\"https:\"?\"; Secure\":\"\")}catch(e){}}function rp(k){var v=null,s,i,c;try{c=document.cookie.split(\";\");for(i=0;i0&&c[i].slice(0,j).replace(/^\\s+|\\s+$/g,\"\")===PC[k]){v=decodeURIComponent(c[i].slice(j+1).replace(/^\\s+|\\s+$/g,\"\"));break}}}catch(e){v=null}if(v!==null&&pv(k,v))return v;s=pls();try{v=s&&s.getItem(PS[k])}catch(e){v=null}if(v&&pv(k,v)){wc(k,v);return v}return null}function wp(k,v){if(!pv(k,v))return;wc(k,v);var s=pls();try{s&&s.setItem(PS[k],v)}catch(e){}}function ml(t,L){if(!t)return -1;t=String(t).toLowerCase().replace(/_/g,\"-\");var b=t.split(\"-\")[0],i,z=-1,tr=/^zh-(tw|hk|mo|hant)\\b/;for(i=0;i", "fitScript": "(function(){try{var d=document.documentElement,i=document.querySelector(\"#top > .kit-site-header-inner\"),u=i&&i.querySelector(\".kit-site-nav > ul\"),t=i&&i.querySelector(\".kit-search-trigger\"),S=[\"search\",\"tabs\",\"drawer\"],k,c,m,a,z;if(!u)return;d.removeAttribute(\"data-kit-nav-fit\");a=u.firstElementChild;z=u.lastElementChild;if(u.clientWidth>0&&a&&z){c=getComputedStyle(i);m={w:i.clientWidth-parseFloat(c.paddingLeft)-parseFloat(c.paddingRight),need:z.getBoundingClientRect().right-a.getBoundingClientRect().left,have:u.clientWidth,trig:t?t.offsetWidth:0,rem:parseFloat(getComputedStyle(d).fontSize)||16,compact:matchMedia(\"(max-width: 1180px)\").matches,loading:!!document.fonts&&document.fonts.status!==\"loaded\"};window.__kitNavFit=m}for(k=0;k", + "gbar": "", "langItem": "", "langCheck": "", - "networkList": "", + "networkList": "", "icons": { "search": "", "close": "", diff --git a/kit/static/doxygen/header.html b/kit/static/doxygen/header.html index 9194689..fd1f204 100644 --- a/kit/static/doxygen/header.html +++ b/kit/static/doxygen/header.html @@ -1,11 +1,11 @@ - + - + $title - LeviLamina API @@ -39,7 +39,7 @@
- +
diff --git a/kit/static/footer.html b/kit/static/footer.html index 5274d62..26311d2 100644 --- a/kit/static/footer.html +++ b/kit/static/footer.html @@ -1,2 +1,2 @@ - +
diff --git a/kit/static/globalbar.html b/kit/static/globalbar.html index 40dd384..15ceee2 100644 --- a/kit/static/globalbar.html +++ b/kit/static/globalbar.html @@ -1,2 +1,2 @@ - - + + diff --git a/kit/static/i18n/footer.de.html b/kit/static/i18n/footer.de.html index 718ca87..37265a8 100644 --- a/kit/static/i18n/footer.de.html +++ b/kit/static/i18n/footer.de.html @@ -1,2 +1,2 @@ - +
diff --git a/kit/static/i18n/footer.en.html b/kit/static/i18n/footer.en.html index aafdf7f..66c8d2c 100644 --- a/kit/static/i18n/footer.en.html +++ b/kit/static/i18n/footer.en.html @@ -1,2 +1,2 @@ - +
diff --git a/kit/static/i18n/footer.es.html b/kit/static/i18n/footer.es.html index 8d9b2bf..3b4c794 100644 --- a/kit/static/i18n/footer.es.html +++ b/kit/static/i18n/footer.es.html @@ -1,2 +1,2 @@ - +
diff --git a/kit/static/i18n/footer.fr.html b/kit/static/i18n/footer.fr.html index 03bdb85..9624b50 100644 --- a/kit/static/i18n/footer.fr.html +++ b/kit/static/i18n/footer.fr.html @@ -1,2 +1,2 @@ - +
diff --git a/kit/static/i18n/footer.ja.html b/kit/static/i18n/footer.ja.html index 09e435f..3547916 100644 --- a/kit/static/i18n/footer.ja.html +++ b/kit/static/i18n/footer.ja.html @@ -1,2 +1,2 @@ - +
diff --git a/kit/static/i18n/footer.ko.html b/kit/static/i18n/footer.ko.html index 0194e2e..422a8a6 100644 --- a/kit/static/i18n/footer.ko.html +++ b/kit/static/i18n/footer.ko.html @@ -1,2 +1,2 @@ - +
diff --git a/kit/static/i18n/footer.ru.html b/kit/static/i18n/footer.ru.html index df3f7c2..c8a5fbf 100644 --- a/kit/static/i18n/footer.ru.html +++ b/kit/static/i18n/footer.ru.html @@ -1,2 +1,2 @@ - +
diff --git a/kit/static/i18n/footer.zh-CN.html b/kit/static/i18n/footer.zh-CN.html index ddf6e8a..c8eb790 100644 --- a/kit/static/i18n/footer.zh-CN.html +++ b/kit/static/i18n/footer.zh-CN.html @@ -1,2 +1,2 @@ - +
diff --git a/kit/static/i18n/footer.zh-HK.html b/kit/static/i18n/footer.zh-HK.html index 862cd1d..d2d0522 100644 --- a/kit/static/i18n/footer.zh-HK.html +++ b/kit/static/i18n/footer.zh-HK.html @@ -1,2 +1,2 @@ - +
diff --git a/kit/static/i18n/globalbar.de.html b/kit/static/i18n/globalbar.de.html index 60f933e..b72429b 100644 --- a/kit/static/i18n/globalbar.de.html +++ b/kit/static/i18n/globalbar.de.html @@ -1,2 +1,2 @@ - - + + diff --git a/kit/static/i18n/globalbar.en.html b/kit/static/i18n/globalbar.en.html index 224c41e..665f3f5 100644 --- a/kit/static/i18n/globalbar.en.html +++ b/kit/static/i18n/globalbar.en.html @@ -1,2 +1,2 @@ - - + + diff --git a/kit/static/i18n/globalbar.es.html b/kit/static/i18n/globalbar.es.html index 86771a8..575aaf5 100644 --- a/kit/static/i18n/globalbar.es.html +++ b/kit/static/i18n/globalbar.es.html @@ -1,2 +1,2 @@ - - + + diff --git a/kit/static/i18n/globalbar.fr.html b/kit/static/i18n/globalbar.fr.html index e07d325..33a5625 100644 --- a/kit/static/i18n/globalbar.fr.html +++ b/kit/static/i18n/globalbar.fr.html @@ -1,2 +1,2 @@ - - + + diff --git a/kit/static/i18n/globalbar.ja.html b/kit/static/i18n/globalbar.ja.html index b0182de..5067a40 100644 --- a/kit/static/i18n/globalbar.ja.html +++ b/kit/static/i18n/globalbar.ja.html @@ -1,2 +1,2 @@ - - + + diff --git a/kit/static/i18n/globalbar.ko.html b/kit/static/i18n/globalbar.ko.html index 40ca697..bdce411 100644 --- a/kit/static/i18n/globalbar.ko.html +++ b/kit/static/i18n/globalbar.ko.html @@ -1,2 +1,2 @@ - - + + diff --git a/kit/static/i18n/globalbar.ru.html b/kit/static/i18n/globalbar.ru.html index a2e4628..0a03e86 100644 --- a/kit/static/i18n/globalbar.ru.html +++ b/kit/static/i18n/globalbar.ru.html @@ -1,2 +1,2 @@ - - + + diff --git a/kit/static/i18n/globalbar.zh-CN.html b/kit/static/i18n/globalbar.zh-CN.html index 0b65c29..4bf563e 100644 --- a/kit/static/i18n/globalbar.zh-CN.html +++ b/kit/static/i18n/globalbar.zh-CN.html @@ -1,2 +1,2 @@ - - + + diff --git a/kit/static/i18n/globalbar.zh-HK.html b/kit/static/i18n/globalbar.zh-HK.html index 4a4dc73..65229a3 100644 --- a/kit/static/i18n/globalbar.zh-HK.html +++ b/kit/static/i18n/globalbar.zh-HK.html @@ -1,2 +1,2 @@ - - + + diff --git a/kit/static/kit.js b/kit/static/kit.js index d6eb68f..0417dac 100644 --- a/kit/static/kit.js +++ b/kit/static/kit.js @@ -1,4 +1,4 @@ -/* levimc-kit 2.19.1 · generated by static/build-static.mjs from static/kit.src.js — do not edit */ +/* levimc-kit 2.20.0 · generated by static/build-static.mjs from static/kit.src.js — do not edit */ /* levimc-kit vanilla runtime for pages without React (static pages, Doxygen): the GlobalBar's theme and language menus,
menus, and the footer year. static/build-static.mjs builds kit.js from this file (it fills in the shared preference code and the chrome strings). Include once, deferred: diff --git a/kit/static/pages/404.html b/kit/static/pages/404.html index b453c40..a13cb60 100644 --- a/kit/static/pages/404.html +++ b/kit/static/pages/404.html @@ -4,7 +4,7 @@ Page not found - LeviMC Docs - + @@ -18,7 +18,7 @@
- +
@@ -30,12 +30,12 @@

This page wandered off

Or open the docs of a project:

diff --git a/kit/static/pages/index.html b/kit/static/pages/index.html index 80f66c2..7de916d 100644 --- a/kit/static/pages/index.html +++ b/kit/static/pages/index.html @@ -7,7 +7,7 @@ LeviMC Docs - + @@ -20,19 +20,19 @@
- +

docs.levimc.org

Redirecting to levimc.org…

-

Project documentation lives under docs.levimc.org/<Project>/:

+

Project documentation lives under levimc.org/<Project>/:

diff --git a/kit/tests/cross-site.e2e.mjs b/kit/tests/cross-site.e2e.mjs index e60dbd8..6519d30 100644 --- a/kit/tests/cross-site.e2e.mjs +++ b/kit/tests/cross-site.e2e.mjs @@ -1,7 +1,7 @@ #!/usr/bin/env node -// End-to-end check that theme + language preferences are shared across levimc.org and *.levimc.org, under -// the browser's real cookie rules for those origins: Chromium loads https://levimc.org/ (a plain app build) -// and https://docs.levimc.org// (a docs build) and every request for those hosts is answered from the +// End-to-end check that theme + language preferences are shared across the LeviMC sites, under the browser's +// real cookie rules: Chromium loads https://levimc.org/ (a plain app build) and https://levimc.org// (a docs +// build, published by its own repository on the same origin) and every request for that host is answered from the // local builds with GitHub Pages semantics (Playwright request routing — no DNS, TLS or server needed; // anything else, e.g. Google Fonts, is blocked). // @@ -25,15 +25,16 @@ if (!appDist || !docsDist) { const require = createRequire(process.env.LEVIMC_PW_DIR ? process.env.LEVIMC_PW_DIR + '/' : import.meta.url); const { chromium } = require('playwright'); -const SITES = { 'levimc.org': [appDist, '/'], 'docs.levimc.org': [docsDist, docsBase] }; +/** The build that serves a URL: the docs below their base, the app everywhere else (like GitHub Pages' project sites). */ +const siteOf = (url) => (url.hostname !== 'levimc.org' ? null : url.pathname.startsWith(docsBase) ? [docsDist, docsBase] : [appDist, '/']); const APP = 'https://levimc.org/'; -const DOCS = `https://docs.levimc.org${docsBase}`; +const DOCS = `https://levimc.org${docsBase}`; const browser = await chromium.launch(); const ctx = await browser.newContext({ colorScheme: 'light', locale: 'en-US', viewport: { width: 1280, height: 800 } }); await ctx.route('**/*', async (route) => { const url = new URL(route.request().url()); - const site = SITES[url.hostname]; + const site = siteOf(url); if (!site) return route.abort(); const r = resolvePagesPath(site[0], site[1], url.pathname); if (r.status === 301) return route.fulfill({ status: 301, headers: { location: r.location } }); @@ -75,13 +76,13 @@ await check('levimc.org: Dark + 繁體中文 are stored on the parent domain (Do assert(days > 360 && days < 370, `${name} expires in ${days.toFixed(1)} days`); } }); -await check('docs.levimc.org: the next load is dark and the root redirects to the zh locale', async () => { +await check(`levimc.org${docsBase}: the next load is dark and the root redirects to the zh locale`, async () => { await load(DOCS); const s = await page.evaluate(() => ({ dark: document.documentElement.classList.contains('dark'), pref: document.documentElement.dataset.themePref, lang: document.documentElement.lang, path: location.pathname })); assert(s.dark && s.pref === 'dark', `theme ${JSON.stringify(s)}`); assert(s.lang.startsWith('zh') && s.path !== new URL(DOCS).pathname, `language ${JSON.stringify(s)}`); }); -await check('docs.levimc.org: choosing English + Light there applies on levimc.org after reload', async () => { +await check(`levimc.org${docsBase}: choosing English + Light there applies on levimc.org/ after reload`, async () => { await page.click('[data-kit-locale-switcher]'); await page.click('.kit-gbar [role="menuitemradio"][hreflang^="en"]'); await page.waitForFunction(() => document.documentElement.lang.startsWith('en')); diff --git a/kit/tests/prefs.test.mjs b/kit/tests/prefs.test.mjs index 07f8f75..10574b4 100644 --- a/kit/tests/prefs.test.mjs +++ b/kit/tests/prefs.test.mjs @@ -18,7 +18,7 @@ import { KIT_VERSION } from '../components/version.ts'; // ------------------------------------------------------------------ a tiny browser for the inline scripts /** Cookie jar with Domain / host-only semantics, as document.cookie exposes it to one host. */ -function browserEnv({ url = 'https://docs.levimc.org/', cookies = [], storage = {}, languages = ['en-US'], referrer = '', dark = false } = {}) { +function browserEnv({ url = 'https://levimc.org/', cookies = [], storage = {}, languages = ['en-US'], referrer = '', dark = false } = {}) { const u = new URL(url); const jar = cookies.map((c) => ({ ...c })); const visible = () => jar.filter((c) => (c.domain ? u.hostname === c.domain || u.hostname.endsWith('.' + c.domain) : c.host === u.hostname) && (!c.secure || u.protocol === 'https:')); @@ -177,7 +177,7 @@ test('pre-paint: the cookie wins over localStorage', () => { assert.ok(!env.classes.has('dark')); }); test('pre-paint: a localStorage-only choice (kit 1.0) moves into the parent-domain cookie once', () => { - const env = run(init, browserEnv({ url: 'https://docs.levimc.org/lip/', storage: { 'levimc-theme': 'dark', 'levimc-lang': 'zh-CN' } })); + const env = run(init, browserEnv({ url: 'https://levimc.org/lip/', storage: { 'levimc-theme': 'dark', 'levimc-lang': 'zh-CN' } })); assert.equal(env.attrs['data-theme-pref'], 'dark'); const theme = env.jar.find((c) => c.name === 'levimc_theme'); assert.deepEqual([theme.value, theme.domain, theme.secure, theme.sameSite, theme.maxAge], ['dark', 'levimc.org', true, 'Lax', 31536000]); @@ -251,7 +251,7 @@ const SITE = { ], }; const redirect = localeRedirectScript(SITE); -const at = (path, o = {}) => run(redirect, browserEnv({ url: 'https://docs.levimc.org' + path, ...o })); +const at = (path, o = {}) => run(redirect, browserEnv({ url: 'https://levimc.org' + path, ...o })); const pref = (v) => [{ name: 'levimc_lang', value: v, domain: 'levimc.org' }]; test('redirect: only the site root; the stored preference maps to the nearest locale', () => { assert.equal(at('/LeviLauncher/', { cookies: pref('zh-TW') }).replaced, '/LeviLauncher/zh-HK/'); @@ -262,9 +262,9 @@ test('redirect: only the site root; the stored preference maps to the nearest lo assert.equal(at('/LeviLauncher/', { cookies: pref('pt-BR'), languages: ['ja'] }).replaced, null, 'unmatched preference → English, not the browser'); }); test('redirect: the stored preference wins even after an in-site link (LeviLaunchroid patch 7)', () => { - assert.equal(at('/LeviLauncher/', { cookies: pref('ja-JP'), referrer: 'https://docs.levimc.org/LeviLauncher/zh-CN/' }).replaced, '/LeviLauncher/ja-JP/'); + assert.equal(at('/LeviLauncher/', { cookies: pref('ja-JP'), referrer: 'https://levimc.org/LeviLauncher/zh-CN/' }).replaced, '/LeviLauncher/ja-JP/'); // without a preference an in-site link to the root is followed as written - assert.equal(at('/LeviLauncher/', { languages: ['zh-CN'], referrer: 'https://docs.levimc.org/LeviLauncher/zh-CN/' }).replaced, null); + assert.equal(at('/LeviLauncher/', { languages: ['zh-CN'], referrer: 'https://levimc.org/LeviLauncher/zh-CN/' }).replaced, null); assert.equal(at('/LeviLauncher/', { languages: ['zh-CN'], referrer: 'https://levimc.org/' }).replaced, '/LeviLauncher/zh-CN/'); }); test('redirect: no preference → the first matching browser language; kit 1.0 per-site key is migrated', () => { diff --git a/legacy/build.mjs b/legacy/build.mjs new file mode 100644 index 0000000..b1b2ca9 --- /dev/null +++ b/legacy/build.mjs @@ -0,0 +1,340 @@ +#!/usr/bin/env node +// Adds the legacy documentation redirects to the built site (dist/, after `npm run build`): what +// LiteLDev/liteldev.github.io served under docs.levimc.org before the project docs moved to levimc.org//. +// Its sources are levimc-kit's static pages (kit/static) and the redirect table in legacy/redirects.mjs. +// +// node legacy/build.mjs dist +// +// Output (in ): +// 404.html the site's own 404 (prerendered), with the forwarding map inserted before anything else +// (legacy URLs, wrongly cased project paths) +// /… one redirect page per legacy URL, plus the old site's verbatim files +// (legacy/redirects.mjs, legacy/files//) +// _kit/… the kit assets these pages reference (kit.css, kit.js, kit-nojs-dark.css, sprites) +import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, join, relative, resolve } from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { uiStrings } from '../kit/components/i18n.ts'; +import { KIT_GENERATOR } from '../kit/components/version.ts'; +import { MOVED_SITES, ORIGIN, PROJECT_SITES } from './redirects.mjs'; + +const repo = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const KIT_STATIC = join(repo, 'kit', 'static'); +const LEGACY_FILES = join(repo, 'legacy', 'files'); +/** Where the pages load kit assets from (dist/_kit/ → https://levimc.org/_kit/). */ +export const ASSET_BASE = '/_kit/'; +/** kit/static/kit-nojs-dark.css: the kit's dark theme, loaded only without JavaScript in a dark system theme. */ +export const NOJS_DARK_CSS = 'kit-nojs-dark.css'; +const KIT_TEMPLATE_BASE = '/levimc-kit/'; +const BANNER = ''; + +// ------------------------------------------------------------------------------------------------ routing +// These functions are also inlined into the generated pages (Function#toString, whitespace collapsed), so +// they stay ES5 and contain no comments. + +/** Normalises the part of an old URL below the old site root to a page key ("zh-CN/api/hook.html" → "zh-cn/api/hook"). */ +export function legacyKey(rest) { + return rest + .toLowerCase() + .replace(/\/+$/, '') + .replace(/(^|\/)index(\.html)?$/, '') + .replace(/\.html$/, '') + .replace(/\/+$/, '') + .replace(/^\/+/, ''); +} + +/** + * The #anchor to append to a forwarded URL: 0 drops it, 1 keeps it, an object { oldId: newId } renames the + * old heading ids it lists and keeps any other. + * @param {string} hash location.hash ("" or "#…", percent-encoded) + * @param {0 | 1 | Record} mode + */ +export function legacyHash(hash, mode) { + if (!mode || !hash) return ''; + if (mode === 1) return hash; + var id = hash.slice(1); + try { + id = decodeURIComponent(id); + } catch (e) { + id = hash.slice(1); + } + return Object.prototype.hasOwnProperty.call(mode, id) ? '#' + mode[id] : hash; +} + +/** + * Where dist/404.html forwards a request, or null to show the 404 page: old URLs of a moved site go to the + * new page (or the locale home); wrongly cased project paths (/levilamina/x) go to the project + * (/LeviLamina/x), because project sites are case-sensitive on GitHub Pages. + * @param {string} pathname location.pathname (percent-encoded) + * @param {string} search location.search + * @param {string} hash location.hash + * @param {{ o: string, m: { f: string, t: string, p: Record]>, d: [string, string][] }[], c: string[] }} D + */ +export function legacyForward(pathname, search, hash, D) { + var path = pathname; + try { + path = decodeURIComponent(pathname); + } catch (e) { + path = pathname; + } + var lower = path.toLowerCase(); + for (var i = 0; i < D.m.length; i++) { + var site = D.m[i]; + if (lower !== site.f.slice(0, -1) && lower.indexOf(site.f) !== 0) continue; + var key = legacyKey(lower.slice(site.f.length)); + if (Object.prototype.hasOwnProperty.call(site.p, key)) return D.o + site.t + site.p[key][0] + legacyHash(hash, site.p[key][1]); + for (var j = 0; j < site.d.length; j++) { + var prefix = site.d[j][0]; + if (!prefix || key === prefix || key.indexOf(prefix + '/') === 0) return D.o + site.t + site.d[j][1]; + } + } + var parts = pathname.split('/'); + var first = path.split('/')[1] || ''; + for (var k = 0; k < D.c.length; k++) { + var name = D.c[k]; + if (first !== name && first.toLowerCase() === name.toLowerCase()) return D.o + '/' + name + '/' + parts.slice(2).join('/') + search + hash; + } + return null; +} + +/** A page's `hash` setting (legacy/redirects.mjs) as legacyHash() reads it. */ +export function hashMode(hash) { + if (hash === true) return 1; + if (!hash) return 0; + const renames = {}; + for (const [to, olds] of Object.entries(hash)) { + for (const old of olds) { + if (Object.hasOwn(renames, old)) throw new Error(`old anchor #${old} is mapped twice`); + renames[old] = to; + } + } + return renames; +} + +/** The compact table legacyForward() reads. */ +export function forwardTable() { + return { + o: ORIGIN, + m: MOVED_SITES.map((s) => { + const p = {}; + for (const [from, to, , , hash] of s.pages) p[legacyKey(from)] = [to, hashMode(hash)]; + for (const [from, to] of s.aliases ?? []) if (!Object.hasOwn(p, legacyKey(from))) p[legacyKey(from)] = [to, 0]; + return { f: s.from.toLowerCase(), t: s.to, p, d: (s.fallbacks ?? [['', '']]).map(([from, to]) => [legacyKey(from), to]) }; + }), + c: PROJECT_SITES, + }; +} + +/** Old page key → the file GitHub Pages serves for it ("" → index.html, "api/" → api/index.html, "api/hook" → api/hook.html). */ +export function stubFile(siteFrom, page) { + const dir = siteFrom.replace(/^\/|\/$/g, ''); + if (page === '' || page.endsWith('/')) return `${dir}/${page}index.html`; + return `${dir}/${page}.html`; +} + +// ------------------------------------------------------------------------------------------------ pages +const esc = (s) => String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); +const scriptJson = (v) => JSON.stringify(v).replace(/ fn.toString().replace(/\n\s*/g, ' '); +const kitFiles = new Map(); +/** A kit/static text file (cached: every redirect page reuses the same snippets). */ +const read = (rel) => { + if (!kitFiles.has(rel)) kitFiles.set(rel, readFileSync(join(KIT_STATIC, rel), 'utf8')); + return kitFiles.get(rel); +}; +/** Drop the "generated by build-static.mjs" banner line of a kit snippet. */ +const snippet = (rel) => read(rel).replace(/^\n/, '').trim(); + +/** The kit GlobalBar of a docs page (the Projects tab current, optionally a project in it) in a UI locale. */ +export function globalBar(locale, currentProject) { + let html = snippet(`i18n/globalbar.${locale}.html`); + // Same attributes GlobalBar.tsx renders with currentProject (aria-current="page"): the Projects tab in the bar + // and in its phone menu, and the project's row in both Projects lists. + html = html.replace('', ''); + html = html.replace('', ''); + if (currentProject) { + const item = ``; + html = html.split(item).join(``); + } + return html; +} + +const footer = (locale) => snippet(`i18n/footer.${locale}.html`); + +/** A kit sprite from kit/static/icons as inline SVG (inherits currentColor, like the React PixelIcon). */ +function inlineIcon(name) { + return read(`icons/${name}.svg`) + .trim() + .replace(' xmlns="http://www.w3.org/2000/svg"', '') + .replace(/[^<]*<\/title>/, '') + .replace(/^<svg\b([^>]*)>/, '<svg$1 focusable="false" class="kit-pixel-icon" aria-hidden="true">'); +} + +/** Replace exactly one occurrence (a kit template that changed shape fails loudly instead of drifting). */ +function replaceOnce(html, from, to, what) { + const n = typeof from === 'string' ? html.split(from).length - 1 : (html.match(new RegExp(from.source, 'g')) ?? []).length; + if (n !== 1) throw new Error(`a kit/static/pages template changed shape: expected one ${what}, found ${n}`); + return html.replace(from, () => to); +} + +/** A kit page template with its assets under ASSET_BASE; the generator meta names this kit (it lives in this repository). */ +const kitTemplate = (name) => + read(`pages/${name}`) + .split(KIT_TEMPLATE_BASE) + .join(ASSET_BASE) + .replace(/<meta name="generator" content="levimc-kit [^"]*">/, () => `<meta name="generator" content="${KIT_GENERATOR}">`); + +/** Put redirect tags right after <meta charset>, before any stylesheet, so the redirect is instant. */ +function hoistIntoHead(html, tags) { + const charset = '<meta charset="utf-8">'; + if (!html.includes(charset)) throw new Error('template without <meta charset="utf-8">'); + return html.replace(charset, () => [charset, BANNER, ...tags].join('\n ')); +} + +/** The kit's skip link in the page's language (kit.js re-translates it when the visitor prefers another one). */ +function skipLink(html, lang) { + const en = `<a class="kit-skip-link" href="#kit-main" data-kit-t="skipToContent">${esc(uiStrings('en').skipToContent)}</a>`; + return replaceOnce(html, en, en.replace(/>[^<]*<\/a>$/, `>${esc(uiStrings(lang).skipToContent)}</a>`), 'skip link'); +} + +/** The forwarding map that runs first on the 404 page: forwards legacy URLs and wrongly cased project paths. */ +export function forwardScript() { + return ( + `<script>(function(){${inline(legacyKey)}${inline(legacyHash)}${inline(legacyForward)}` + + `try{var u=legacyForward(location.pathname,location.search,location.hash,${scriptJson(forwardTable())});` + + `if(u&&u!==location.href){var d=document.documentElement;d.style.visibility="hidden";` + + `setTimeout(function(){d.style.visibility=""},3000);location.replace(u)}}catch(e){}})();</script>` + ); +} + +/** The site's 404 page with the forwarding map right after <meta charset>, before any stylesheet or script. */ +export function patchNotFound(html) { + if (html.includes('function legacyForward')) throw new Error('404.html already has the forwarding map'); + const charset = /<meta charset="utf-8"\s*\/?>/i.exec(html); + if (!charset) throw new Error('404.html without <meta charset="utf-8">'); + return html.replace(charset[0], () => `${charset[0]} + ${forwardScript()}`); +} + +// Text of the redirect pages (visible only without JavaScript or for the moment before the redirect). +// Same structure as the kit's root redirect page: the heading links the target. +const STUB_TEXT = { + en: { + title: (page) => `Moved: ${page} - LeviMC Docs`, + eyebrow: 'Page moved', + heading: (link) => `Redirecting to ${link}…`, + text: (s) => `The ${s.oldName} docs are now part of the ${s.newName} documentation.`, + button: 'Continue', + }, + 'zh-CN': { + title: (page) => `已迁移:${page} - LeviMC Docs`, + eyebrow: 'Page moved', + heading: (link) => `正在跳转到 ${link}…`, + text: (s) => `${s.oldName} 文档已并入 ${s.newName} 文档。`, + button: '继续', + }, + 'zh-HK': { + title: (page) => `已遷移:${page} - LeviMC Docs`, + eyebrow: 'Page moved', + heading: (link) => `正在跳轉到 ${link}…`, + text: (s) => `${s.oldName} 文檔已併入 ${s.newName} 文檔。`, + button: '繼續', + }, +}; + +/** The redirect script of a stub page: the target plus the old #anchor as `hash` says. */ +function stubRedirect(url, hash) { + const mode = hashMode(hash); + if (mode === 0) return `<script>location.replace(${scriptJson(url)});</script>`; + if (mode === 1) return `<script>location.replace(${scriptJson(url)}+location.hash);</script>`; + return `<script>(function(){${inline(legacyHash)}location.replace(${scriptJson(url)}+legacyHash(location.hash,${scriptJson(mode)}))})();</script>`; +} + +/** + * A redirect page: the kit's static 404 page (same head, backdrop and shell) with the GlobalBar and footer in + * the page's language, a "Redirecting to …" card instead of the project grid, and the redirect tags first. + */ +function stubPage(site, [, to, lang, pageTitle, hash], notFound) { + const url = ORIGIN + site.to + to; + const t = STUB_TEXT[lang]; + if (!t) throw new Error(`no stub text for ${lang}`); + const link = `<a href="${esc(url)}">${esc(pageTitle)}</a>`; + const main = `<main id="kit-main" class="kit-static-main"> + <section class="kit-static-card px-card kit-painted"> + <div class="kit-notfound-compass kit-slot" aria-hidden="true"><img src="${ASSET_BASE}icons/pickaxe.svg" width="64" height="64" alt="" class="pixelated"></div> + <p class="kit-pixel-label kit-static-eyebrow">${esc(t.eyebrow)}</p> + <h1 class="kit-static-title">${t.heading(link)}</h1> + <p class="kit-static-text">${esc(t.text(site))}</p> + <p class="kit-static-actions"><a class="mc-btn mc-btn-primary" href="${esc(url)}">${esc(t.button)}${inlineIcon('arrow-right')}</a></p> + </section> + </main>`; + let html = notFound; + html = replaceOnce(html, '<html lang="en">', `<html lang="${esc(lang)}">`, '<html lang="en">'); + html = replaceOnce(html, /<title>[^<]*<\/title>/, `<title>${esc(t.title(pageTitle))}`, ''); + html = replaceOnce(html, /\n\s*<meta name="robots" content="noindex">/, '', 'robots meta'); + html = replaceOnce(html, globalBar('en'), globalBar(lang, site.to.replace(/\//g, '')), 'GlobalBar'); + html = replaceOnce(html, footer('en'), footer(lang), 'footer'); + html = replaceOnce(html, /<main id="kit-main"[^>]*>[\s\S]*?<\/main>/, main, '<main>'); + return hoistIntoHead(skipLink(html, lang), [ + `<link rel="canonical" href="${esc(url)}">`, + `<meta http-equiv="refresh" content="0; url=${esc(url)}">`, + stubRedirect(url, hash), + ]); +} + +/** Every redirect page of a moved site: [old page, new page, lang, title, hash] for its pages and directory aliases. */ +export function stubEntries(site) { + const entries = [...site.pages]; + for (const [from, to] of site.aliases ?? []) { + if (!from.endsWith('/')) continue; // a file alias: only the 404 forwards it + const page = site.pages.find((p) => p[1] === to); + if (!page) throw new Error(`alias ${site.from}${from} → ${to}: no page with that target`); + entries.push([from, to, page[2], page[3], false]); + } + return entries; +} + +// ------------------------------------------------------------------------------------------------ build +/** Every file the generator adds, as dist-relative path → contents (404.html is patched separately). */ +export function generate() { + const files = new Map(); + const add = (rel, body) => { + if (files.has(rel)) throw new Error(`two sources for ${rel}`); + files.set(rel, body); + }; + const notFound = kitTemplate('404.html'); + for (const site of MOVED_SITES) { + if (!/^\/[A-Za-z0-9._-]+\/$/.test(site.from) || /^\/(_kit|\.+)\/$/.test(site.from)) throw new Error(`MOVED_SITES.from must be one path segment like "/old-site/": ${site.from}`); + for (const entry of stubEntries(site)) add(stubFile(site.from, entry[0]), stubPage(site, entry, notFound)); + const dir = site.from.slice(1, -1); + for (const rel of site.files ?? []) add(`${dir}/${rel}`, readFileSync(join(LEGACY_FILES, dir, rel))); + } + // Copy exactly the kit assets the pages reference. + const assets = new Set(); + for (const [rel, body] of files) if (rel.endsWith('.html')) for (const m of body.matchAll(/["'(]\/_kit\/([^"')\s?#]+)/g)) assets.add(m[1]); + for (const rel of [...assets].sort()) if (!files.has(`_kit/${rel}`)) add(`_kit/${rel}`, readFileSync(join(KIT_STATIC, rel))); + return files; +} + +function main() { + const outArg = process.argv[2]; + if (!outArg || outArg.startsWith('--')) { + console.error('Usage: node legacy/build.mjs <dist>'); + process.exit(2); + } + const out = resolve(outArg); + const notFound = join(out, '404.html'); + if (!existsSync(notFound)) throw new Error(`${notFound} is missing: run the site build first`); + const files = generate(); + // The site build owns everything else: a legacy path that it publishes too is a conflict, not an overwrite. + for (const rel of files.keys()) if (existsSync(join(out, rel))) throw new Error(`${join(out, rel)} exists already: a legacy path collides with the site`); + for (const [rel, body] of files) { + mkdirSync(dirname(join(out, rel)), { recursive: true }); + writeFileSync(join(out, rel), body); + } + writeFileSync(notFound, patchNotFound(readFileSync(notFound, 'utf8'))); + console.log(`legacy: wrote ${files.size} files and the 404 forwarding map to ${relative(process.cwd(), out) || out}`); +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) main(); diff --git a/legacy/build.test.mjs b/legacy/build.test.mjs new file mode 100644 index 0000000..767a1f1 --- /dev/null +++ b/legacy/build.test.mjs @@ -0,0 +1,327 @@ +// Tests for legacy/build.mjs (part of `npm test`). +// Add --live (node legacy/build.test.mjs --live) to also check every redirect target on the live site. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { execFileSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import vm from 'node:vm'; +import { + ASSET_BASE, + NOJS_DARK_CSS, + forwardScript, + forwardTable, + generate, + globalBar, + hashMode, + legacyForward, + legacyHash, + legacyKey, + patchNotFound, + stubEntries, + stubFile, +} from './build.mjs'; +import { MOVED_SITES, ORIGIN, PROJECT_SITES } from './redirects.mjs'; + +const repo = join(dirname(fileURLToPath(import.meta.url)), '..'); +const D = forwardTable(); +const fwd = (path, hash = '', search = '') => legacyForward(path, search, hash, D); +const files = generate(); +const html = [...files].filter(([f]) => f.endsWith('.html')); +// the Android native mod docs in LeviLamina's docs, and LeviLauncher's guide with the Android tab preselected +// (formerly docs.levimc.org/LeviLaunchroid/, now levimc.org/LeviLaunchroid/) +const L = `${ORIGIN}/LeviLamina/developer_guides/android/`; +const LZ = `${ORIGIN}/LeviLamina/zh/developer_guides/android/`; +const LH = `${ORIGIN}/LeviLamina/zh-Hant/developer_guides/android/`; +const G = `${ORIGIN}/LeviLauncher/guide/`; +const GZ = `${ORIGIN}/LeviLauncher/zh-CN/guide/`; +const GH = `${ORIGIN}/LeviLauncher/zh-HK/guide/`; +const QS = '?platform=android'; +const LSE = `${ORIGIN}/LegacyScriptEngine/`; + +/** Run a page's redirect script (the first inline <script> that calls location.replace) at `href`. */ +function redirectOf(page, pathname, hash = '') { + const script = [...page.matchAll(/<script>([^<]*location\.replace[\s\S]*?)<\/script>/g)][0]; + assert.ok(script, 'redirect script'); + let replaced = null; + vm.runInNewContext(script[1], { + location: { pathname, search: '', hash, href: `${ORIGIN}${pathname}${hash}`, replace: (u) => (replaced = u) }, + document: { documentElement: { style: {} } }, + setTimeout: () => {}, + }); + return replaced; +} + +test('legacyKey normalises every URL form GitHub Pages served', () => { + assert.equal(legacyKey(''), ''); + assert.equal(legacyKey('index'), ''); + assert.equal(legacyKey('index.html'), ''); + assert.equal(legacyKey('zh-CN/'), 'zh-cn'); + assert.equal(legacyKey('zh-CN/index.html'), 'zh-cn'); + assert.equal(legacyKey('api/hook'), 'api/hook'); + assert.equal(legacyKey('api/hook.html'), 'api/hook'); + assert.equal(legacyKey('api/hook/'), 'api/hook'); + assert.equal(legacyKey('api/hook/index.html'), 'api/hook'); + assert.equal(legacyKey('API/Hook.HTML'), 'api/hook'); + assert.equal(legacyKey('myindex'), 'myindex'); +}); + +test('legacyHash drops, keeps or renames the old #anchor', () => { + const map = hashMode({ functions: ['pl-hook', 'signatures'], 注意: ['注意事项'] }); + assert.deepEqual(map, { 'pl-hook': 'functions', signatures: 'functions', 注意事项: '注意' }); + assert.equal(legacyHash('#a', 0), ''); + assert.equal(legacyHash('#a', 1), '#a'); + assert.equal(legacyHash('', 1), ''); + assert.equal(legacyHash('', map), ''); + assert.equal(legacyHash('#pl-hook', map), '#functions'); + assert.equal(legacyHash('#purpose', map), '#purpose'); // survives on the new page: unchanged + assert.equal(legacyHash('#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B9', map), '#注意'); // browsers percent-encode the hash + assert.equal(legacyHash('#注意事项', map), '#注意'); + assert.equal(legacyHash('#%E0%A4%A', map), '#%E0%A4%A'); // malformed escape: kept as is + assert.equal(legacyHash('#constructor', map), '#constructor'); + assert.equal(legacyHash('#', map), '#'); + assert.throws(() => hashMode({ a: ['x'], b: ['x'] }), /mapped twice/); +}); + +test('404 forwarding: preloader-android pages', () => { + assert.equal(fwd('/preloader-android'), L); + assert.equal(fwd('/preloader-android/'), L); + assert.equal(fwd('/preloader-android/index.html', '#x'), `${L}#x`); + assert.equal(fwd('/preloader-android/api/hook'), `${L}api/hook/`); + assert.equal(fwd('/preloader-android/api/hook.html', '#pl_hook'), `${L}api/hook/#pl_hook`); + assert.equal(fwd('/preloader-android/api/hook/'), `${L}api/hook/`); + assert.equal(fwd('/Preloader-Android/API/hook'), `${L}api/hook/`); + assert.equal(fwd('/preloader-android/zh-CN'), LZ); + assert.equal(fwd('/preloader-android/zh-CN/'), LZ); + assert.equal(fwd('/preloader-android/zh-CN/api/types-and-macros.html'), `${LZ}api/types_and_macros/`); + // rewritten API pages: old section ids with an equivalent are renamed, ids that still exist are kept + assert.equal(fwd('/preloader-android/api/hook', '#pl-hook'), `${L}api/hook/#functions`); + assert.equal(fwd('/preloader-android/api/hook', '#common-mistakes'), `${L}api/hook/#common-mistakes`); + assert.equal(fwd('/preloader-android/api/mod.html', '#headers'), `${L}api/mod/#header`); + assert.equal(fwd('/preloader-android/zh-CN/api/hook', '#%E9%93%BE%E5%BC%8F-hook-%E8%A1%8C%E4%B8%BA'), `${LZ}api/hook/#类型`); + // guide pages moved to a different page: the old #anchor is dropped + assert.equal(fwd('/preloader-android/guide/getting-started', '#manifest-json'), L); + assert.equal(fwd('/preloader-android/zh-CN/guide/compatibility.html', '#abi'), LZ); + // aliases and fallbacks + assert.equal(fwd('/preloader-android/api/'), `${L}api/mod/`); + assert.equal(fwd('/preloader-android/api/', '#x'), `${L}api/mod/`); + assert.equal(fwd('/preloader-android/zh-CN/guide'), LZ); + assert.equal(fwd('/preloader-android/assets/app.123.js'), L); + assert.equal(fwd('/preloader-android/zh-CN/nope/deeper'), LZ); + assert.equal(fwd('/preloader-android/zh-cnx'), L); + // query strings of the old site carried nothing + assert.equal(fwd('/preloader-android/api/mod', '', '?q=1'), `${L}api/mod/`); + // percent-encoded paths + assert.equal(fwd('/preloader%2Dandroid/api/hook'), `${L}api/hook/`); + // Object.prototype names are not pages + assert.equal(fwd('/preloader-android/constructor'), L); + assert.equal(fwd('/preloader-android/__proto__'), L); + assert.equal(fwd('/preloader-android/zh-CN/hasOwnProperty'), LZ); +}); + +test('404 forwarding: LeviLaunchroid user pages go to LeviLauncher\'s guide, developer pages to LeviLamina\'s', () => { + assert.equal(fwd('/LeviLaunchroid'), `${G}quick-start${QS}`); + assert.equal(fwd('/LeviLaunchroid/'), `${G}quick-start${QS}`); + assert.equal(fwd('/LeviLaunchroid/index.html', '#features'), `${G}quick-start${QS}`); + assert.equal(fwd('/LeviLaunchroid/guide/features'), `${G}version-management${QS}`); + assert.equal(fwd('/LeviLaunchroid/guide/compatibility', '#native-mods'), `${G}faq-community-feedback`); + assert.equal(fwd('/LeviLaunchroid/privacy-policy'), `${ORIGIN}/LeviLauncher/privacy-policy`); + assert.equal(fwd('/LeviLaunchroid/guide/developer', '#mod-menu'), `${L}#mod-menu`); + assert.equal(fwd('/LeviLaunchroid/api/hook.html', '#signatures'), `${L}api/hook/#signatures`); + assert.equal(fwd('/levilaunchroid/API/Mod-Menu'), `${L}api/mod_menu/`); + assert.equal(fwd('/LeviLaunchroid/zh-CN/'), `${GZ}quick-start${QS}`); + assert.equal(fwd('/LeviLaunchroid/zh-CN/api/types-and-macros'), `${LZ}api/types_and_macros/`); + // zh-Hant became LeviLauncher's zh-HK and LeviLamina's zh-Hant + assert.equal(fwd('/LeviLaunchroid/zh-Hant/'), `${GH}quick-start${QS}`); + assert.equal(fwd('/LeviLaunchroid/zh-Hant/guide/build.html'), LH); + assert.equal(fwd('/LeviLaunchroid/zh-Hant/api/patch'), `${LH}api/patch/`); + // aliases and fallbacks + assert.equal(fwd('/LeviLaunchroid/api/'), `${L}api/mod/`); + assert.equal(fwd('/LeviLaunchroid/zh-Hant/guide'), `${GH}quick-start${QS}`); + assert.equal(fwd('/LeviLaunchroid/assets/app.123.js'), `${G}quick-start${QS}`); + assert.equal(fwd('/LeviLaunchroid/zh-CN/nope'), `${GZ}quick-start${QS}`); +}); + +test('404 forwarding: LiteXLoader (docsify) goes to the LegacyScriptEngine docs, without its #/ route', () => { + assert.equal(fwd('/LiteXLoader'), LSE); + assert.equal(fwd('/LiteXLoader/'), LSE); + assert.equal(fwd('/LiteXLoader/', '#/zh_CN/Usage'), LSE); + assert.equal(fwd('/LiteXLoader/index.html', '#/'), LSE); + assert.equal(fwd('/litexloader/zh_CN/Usage.md'), LSE); + assert.equal(fwd('/LiteXLoaderX/'), null); +}); + +test('404 forwarding: wrongly cased project paths, nothing else', () => { + assert.equal(fwd('/levilamina/'), `${ORIGIN}/LeviLamina/`); + assert.equal(fwd('/levilamina'), `${ORIGIN}/LeviLamina/`); + assert.equal(fwd('/LIP/zh-CN/user-guide.html', '#a', '?x=1'), `${ORIGIN}/lip/zh-CN/user-guide.html?x=1#a`); + assert.equal(fwd('/legacyscriptengine/apis/'), `${ORIGIN}/LegacyScriptEngine/apis/`); + assert.equal(fwd('/bedd/'), `${ORIGIN}/BeDD/`); + assert.equal(fwd('/BedBoo/x'), `${ORIGIN}/bedboo/x`); + assert.deepEqual(PROJECT_SITES, ['LeviLamina', 'LegacyScriptEngine', 'lip', 'LeviLauncher', 'BeDD', 'bedboo']); + for (const p of PROJECT_SITES) assert.equal(fwd(`/${p}/missing`), null, `${p} has the right case`); + assert.equal(fwd('/'), null); + assert.equal(fwd('/random/path'), null); + assert.equal(fwd('/LiteLoader.NET/'), null); + assert.equal(fwd('/preloader'), null); + assert.equal(fwd('/_kit/kit.css'), null); + // levimc.org's own pages are never forwarded + for (const p of ['/about/', '/blog/nope/', '/mods/x/', '/community/', '/kit/v2/x'] ) assert.equal(fwd(p), null, p); +}); + +test('every old page and directory alias has a redirect page with canonical, meta refresh, location.replace and a visible link', () => { + let stubs = 0; + for (const site of MOVED_SITES) { + for (const [from, to, lang, , hash] of stubEntries(site)) { + const file = stubFile(site.from, from); + const page = files.get(file); + assert.ok(page, `missing ${file}`); + stubs++; + const url = ORIGIN + site.to + to; + const old = site.from + from; + assert.match(page, new RegExp(`^<!doctype html>\\n<html lang="${lang}">`)); + assert.ok(page.includes(`<link rel="canonical" href="${url}">`), file); + assert.ok(page.includes(`<meta http-equiv="refresh" content="0; url=${url}">`), file); + assert.ok(page.includes(`class="mc-btn mc-btn-primary" href="${url}"`), file); + assert.ok(page.includes(`<h1 class="kit-static-title">`) && page.includes(`<a href="${url}">`), file); + // the redirect comes before any stylesheet so it is not blocked by CSS + assert.ok(page.indexOf('location.replace') < page.indexOf('rel="stylesheet"'), file); + // and it treats the old #anchor like the 404 forwarder does + const mode = hashMode(hash); + assert.equal(redirectOf(page, old), url, file); + assert.equal(redirectOf(page, old, '#zz'), url + legacyHash('#zz', mode), file); + if (typeof mode === 'object') for (const [oldId, newId] of Object.entries(mode)) assert.equal(redirectOf(page, old, `#${encodeURIComponent(oldId)}`), `${url}#${newId}`, `${file}#${oldId}`); + // the 404 forwards the other forms of the same old URL to the same target + assert.equal(fwd(old), url, old); + assert.equal(fwd(old, '#zz'), url + legacyHash('#zz', mode), `${old}#zz`); + if (from && !from.endsWith('/')) assert.equal(fwd(`${old}.html`), url, `${old}.html`); + if (from.endsWith('/') && from) assert.equal(fwd(old.slice(0, -1)), url, old.slice(0, -1)); + } + } + assert.equal(stubs, 22 + 4 + 1 + 46 + 6); + assert.equal([...files.keys()].filter((f) => f.endsWith('.html') && f.startsWith('preloader-android/')).length, 26); + for (const dir of ['api', 'guide', 'zh-CN/api', 'zh-CN/guide']) assert.ok(files.has(`preloader-android/${dir}/index.html`), `${dir}/ answers 200`); + assert.ok(files.has('LiteXLoader/index.html')); + assert.equal([...files.keys()].filter((f) => f.endsWith('.html') && f.startsWith('LeviLaunchroid/')).length, 52); + for (const dir of ['api', 'guide', 'zh-CN/api', 'zh-CN/guide', 'zh-Hant/api', 'zh-Hant/guide']) assert.ok(files.has(`LeviLaunchroid/${dir}/index.html`), `${dir}/ answers 200`); +}); + +test('the old site\'s files are published verbatim', () => { + const icon = files.get('preloader-android/appicon.png'); + assert.ok(Buffer.isBuffer(icon)); + // docs/public/appicon.png of LiteLDev/preloader-android@a29b5a6702 (= LeviLaunchroid's appicon.png) + assert.equal(createHash('sha256').update(icon).digest('hex'), 'cffec87041c9e91fb640029d5f3bf032dd081bced928dd5547bd13db09912438'); + // docs/public/appicon.png of LiteLDev/LeviLaunchroid, the same image + assert.deepEqual(files.get('LeviLaunchroid/appicon.png'), icon); +}); + +test('404.html runs the forwarding map before rendering', () => { + // the shape of the site's prerendered 404.html (index.html: <meta charset="UTF-8" />, then the stylesheets) + const site404 = `<!doctype html> +<html lang="en"> + <head> + <meta charset="UTF-8" /> + <link rel="stylesheet" href="/assets/x.css"> + <meta name="robots" content="noindex"> + </head> +</html> +`; + const page = patchNotFound(site404); + assert.ok(page.includes(forwardScript())); + assert.throws(() => patchNotFound(page), /already/); + assert.throws(() => patchNotFound('<html><head></head></html>'), /charset/); + const script = /<script>(\(function\(\)\{function legacyKey[\s\S]*?)<\/script>/.exec(page); + assert.ok(script, 'forward script present'); + assert.ok(page.indexOf(script[0]) < page.indexOf('rel="stylesheet"'), 'before CSS'); + const run = (pathname, hash = '') => { + let replaced = null; + const style = {}; + vm.runInNewContext(script[1], { + location: { pathname, search: '', hash, href: `${ORIGIN}${pathname}${hash}`, replace: (u) => (replaced = u) }, + document: { documentElement: { style } }, + setTimeout: () => {}, + }); + return { replaced, hidden: style.visibility === 'hidden' }; + }; + assert.deepEqual(run('/preloader-android/zh-CN/api/hook.html', '#x'), { replaced: `${LZ}api/hook/#x`, hidden: true }); + assert.deepEqual(run('/preloader-android/api/signature', '#c-batch-example'), { replaced: `${L}api/signature/#example`, hidden: true }); + assert.deepEqual(run('/LiteXLoader/', '#/zh_CN/Usage'), { replaced: LSE, hidden: true }); + assert.deepEqual(run('/Levilauncher/'), { replaced: `${ORIGIN}/LeviLauncher/`, hidden: true }); + assert.deepEqual(run('/does-not-exist'), { replaced: null, hidden: false }); +}); + +test('every page: the kit chrome — skip link, no-JS dark theme, generator, footer year, Mods and Blog links', () => { + for (const [f, page] of html) { + const lang = /<html lang="([^"]+)">/.exec(page)[1]; + const skip = lang.startsWith('zh-') ? '跳到正文' : 'Skip to content'; // zh-CN and zh-HK (old zh-Hant pages) + assert.ok(page.includes(`<body>\n <a class="kit-skip-link" href="#kit-main" data-kit-t="skipToContent">${skip}</a>\n`), `${f}: skip link first in <body>`); + assert.ok(page.includes('<main id="kit-main"'), `${f}: skip link target`); + assert.ok(page.includes(`<noscript><link rel="stylesheet" href="${ASSET_BASE}${NOJS_DARK_CSS}" media="(prefers-color-scheme: dark)"></noscript>`), f); + assert.ok(page.indexOf(NOJS_DARK_CSS) > page.indexOf(`${ASSET_BASE}kit.css`), `${f}: after kit.css`); + assert.match(page, /<meta name="generator" content="levimc-kit \d+\.\d+\.\d+[^"]*">/, `${f}: generator`); + assert.match(page, /<span>© <span data-kit-year="">\d{4}<\/span> LeviMC<\/span>/, f); + // the GlobalBar: canonical tabs, Mods label, the blog on levimc.org, language + theme menus, GitHub + const mods = { 'zh-CN': '模组', 'zh-HK': '模組' }[lang] ?? 'Mods'; + assert.ok(page.includes(`<a class="kit-gbar-link" href="https://levimc.org/mods/"><span data-kit-t="mods">${mods}</span></a>`), `${f}: Mods tab`); + assert.ok(page.includes('<a class="kit-gbar-link" href="https://levimc.org/blog/">'), `${f}: Blog tab`); + assert.ok(!page.includes('blog.levimc.org'), `${f}: blog.levimc.org`); + for (const hook of ['data-kit-locale-switcher', 'data-kit-theme-toggle', 'data-kit-theme-value="auto"', 'data-kit-lang-value="zh-HK"', 'kit-gbar-github']) + assert.ok(page.includes(hook), `${f}: ${hook}`); + assert.ok(!page.includes('>Packages<') && !page.includes('>包<'), `${f}: old Packages label`); + } +}); + +test('kit.js (from kit/static) runs the menus, the cross-site preferences and the footer year', () => { + const js = files.get('_kit/kit.js').toString(); + assert.equal(js, readFileSync(join(repo, 'kit/static/kit.js'), 'utf8')); + for (const needle of ['levimc_theme', 'levimc_lang', 'Domain=levimc.org', '[data-kit-year]', '[data-kit-theme-value]', '[data-kit-lang-value]']) assert.ok(js.includes(needle), needle); +}); + +test('kit-nojs-dark.css is the kit\'s (kit.css\'s .dark rules as :root rules)', () => { + const css = files.get(`_kit/${NOJS_DARK_CSS}`); + assert.equal(css.toString(), readFileSync(join(repo, 'kit/static', NOJS_DARK_CSS), 'utf8')); + assert.ok(css.toString().includes('--color-canvas:#0f1b26'), 'dark tokens'); + assert.ok(!/\.dark(?![\w-])/.test(css.toString().replace(/^\/\*[^\n]*\*\/\n/, '')), 'no .dark selector left'); +}); + +test('kit assets: every /_kit/ reference is published, nothing else', () => { + const refs = new Set(); + for (const [, body] of html) for (const m of body.matchAll(/\/_kit\/([^"')\s?#]+)/g)) refs.add(`_kit/${m[1]}`); + const published = [...files.keys()].filter((f) => f.startsWith('_kit/')); + assert.deepEqual(published.sort(), [...refs].sort()); + for (const f of ['_kit/kit.css', '_kit/kit.js', '_kit/levimc.svg', '_kit/icons/pickaxe.svg', `_kit/${NOJS_DARK_CSS}`]) assert.ok(files.has(f), f); + assert.equal(ASSET_BASE, '/_kit/'); + for (const [f, body] of html) assert.ok(!body.includes('/levimc-kit/'), f); +}); + +test('static GlobalBar reproduces the kit rendering for the Projects tab', () => { + const kit404 = readFileSync(join(repo, 'kit/static/pages/404.html'), 'utf8'); + assert.ok(kit404.includes(globalBar('en')), 'en GlobalBar with aria-current on Projects matches kit/static/pages/404.html'); + const zh = globalBar('zh-CN', 'LeviLauncher'); + // Projects in the bar and in the phone menu + LeviLauncher in both Projects lists + assert.equal(zh.match(/aria-current="page"/g).length, 4); +}); + +test('CLI rejects a missing <dist>', () => { + assert.throws(() => execFileSync(process.execPath, [join(repo, 'legacy/build.mjs')], { stdio: 'pipe' }), (e) => e.status === 2); +}); + +test('live: every redirect target answers 200 with no redirect and has every mapped heading id', { skip: !process.argv.includes('--live') && !process.env.LIVE }, () => { + const targets = new Map(); + const need = (url, ids = []) => targets.set(url, [...(targets.get(url) ?? []), ...ids]); + for (const site of MOVED_SITES) { + for (const [, to, , , hash] of site.pages) need(ORIGIN + site.to + to, hash && hash !== true ? Object.keys(hash) : []); + for (const [, to] of site.aliases ?? []) need(ORIGIN + site.to + to); + for (const [, to] of site.fallbacks ?? []) need(ORIGIN + site.to + to); + } + for (const p of PROJECT_SITES) need(`${ORIGIN}/${p}/`); + for (const [url, ids] of targets) { + const out = execFileSync('curl', ['-s', '-o', '/dev/null', '--max-time', '30', '-w', '%{http_code} %{num_redirects} %{redirect_url}', url], { encoding: 'utf8' }); + assert.equal(out.trim(), '200 0', url); + if (!ids.length) continue; + const page = execFileSync('curl', ['-s', '--max-time', '30', url], { encoding: 'utf8' }); + for (const id of ids) assert.ok(page.includes(`id="${id}"`), `${url}#${id}`); + } +}); diff --git a/legacy/files/LeviLaunchroid/appicon.png b/legacy/files/LeviLaunchroid/appicon.png new file mode 100644 index 0000000..160a6ff Binary files /dev/null and b/legacy/files/LeviLaunchroid/appicon.png differ diff --git a/legacy/files/preloader-android/appicon.png b/legacy/files/preloader-android/appicon.png new file mode 100644 index 0000000..160a6ff Binary files /dev/null and b/legacy/files/preloader-android/appicon.png differ diff --git a/legacy/redirects.mjs b/legacy/redirects.mjs new file mode 100644 index 0000000..4605412 --- /dev/null +++ b/legacy/redirects.mjs @@ -0,0 +1,232 @@ +// Legacy documentation URLs that levimc.org forwards (moved here from LiteLDev/liteldev.github.io, which served +// them under docs.levimc.org before the project docs moved to levimc.org/<Repo>/). +// +// GitHub Pages serves this repository (the organisation site) for every path of levimc.org that no project +// repository with Pages owns (project repos own /<Repo>/). legacy/build.mjs turns this table into +// * a real redirect page for every old URL (dist/<from>/…, meta refresh + location.replace + canonical), and +// * the forwarding map that dist/404.html runs before rendering (old URL variants, aliases, wrong case). +// +// All targets are canonical, redirect-free URLs (answer 200 directly); `node legacy/build.test.mjs --live` +// verifies them, and every mapped heading id, against the live site. + +import { DOCS_PROJECTS } from '../kit/components/projects.ts'; + +export const ORIGIN = 'https://levimc.org'; + +/** + * Documentation sites that moved. `pages` lists every page the old site published (VitePress `cleanUrls`: + * `api/hook` was served from `api/hook.html`; `''` and `zh-CN/` are the locale home pages): + * [old page, new page, lang, title of the new page, hash] + * `hash` says what happens to the old #anchor: + * false dropped (the new page is a different page); + * true forwarded unchanged; + * { newId: [oldId, …] } forwarded, and the listed old ids are renamed to the new page's id. The old + * pages were rewritten, so most old headings no longer exist: the map covers the + * sections that have an equivalent on the new page; any other #anchor is forwarded + * unchanged and lands at the top of the page. + * `aliases` are extra old paths (never published, but obvious guesses): directories get a redirect page too + * (GitHub Pages answers `/x` with a 301 to `/x/` for every directory), everything else only the 404 forwards. + * `files` are published verbatim from legacy/<site>/ (files the old site served, e.g. images hot-linked from + * elsewhere), so they keep answering 200 with the same bytes. + * `fallbacks` send anything else under the old site to the matching locale's home (first matching prefix). + */ +export const MOVED_SITES = [ + { + // LiteLDev/LeviLaunchroid docs/ (levimc-kit, base /LeviLaunchroid/, cleanUrls; locales: root = English, + // zh-CN/, zh-Hant/ converted from zh-CN). LeviLauncher is one name for the Windows and the Android launcher: the + // user pages became part of LeviLauncher's one guide (Windows / Android tabs; ?platform=android preselects the + // Android tab), the developer pages (native mods, Preloader API) moved to LeviLamina's docs + // (developer_guides/android/, unchanged, so their #anchors are kept). zh-Hant → LeviLauncher's zh-HK and + // LeviLamina's zh-Hant. Pages on LeviLaunchroid is disabled, so these paths reach this site. + from: '/LeviLaunchroid/', + to: '/', + oldName: 'LeviLauncher for Android', + newName: 'LeviLauncher', + pages: [ + ['', 'LeviLauncher/guide/quick-start?platform=android', 'en', 'Get Started in 5 Minutes', false], + ['guide/getting-started', 'LeviLauncher/guide/quick-start?platform=android', 'en', 'Get Started in 5 Minutes', false], + ['guide/features', 'LeviLauncher/guide/version-management?platform=android', 'en', 'Version Management', false], + ['guide/compatibility', 'LeviLauncher/guide/faq-community-feedback', 'en', 'FAQ, Community & Feedback', false], + ['guide/developer', 'LeviLamina/developer_guides/android/', 'en', 'Native Mod Quick Start', true], + ['guide/build', 'LeviLamina/developer_guides/android/', 'en', 'Native Mod Quick Start', false], + ['api/mod', 'LeviLamina/developer_guides/android/api/mod/', 'en', 'Mod API', true], + ['api/mod-menu', 'LeviLamina/developer_guides/android/api/mod_menu/', 'en', 'Mod Menu API', true], + ['api/config', 'LeviLamina/developer_guides/android/api/config/', 'en', 'Config API', true], + ['api/input', 'LeviLamina/developer_guides/android/api/input/', 'en', 'Input API', true], + ['api/hook', 'LeviLamina/developer_guides/android/api/hook/', 'en', 'Hook API', true], + ['api/signature', 'LeviLamina/developer_guides/android/api/signature/', 'en', 'Signature API', true], + ['api/patch', 'LeviLamina/developer_guides/android/api/patch/', 'en', 'Patch API', true], + ['api/memory-hook-macros', 'LeviLamina/developer_guides/android/api/memory_hook_macros/', 'en', 'Memory Hook Example', true], + ['api/types-and-macros', 'LeviLamina/developer_guides/android/api/types_and_macros/', 'en', 'SDK Headers and Macros', { pl_export: ['pl-export'], pl_register_mod: ['pl-register-mod'] }], + ['privacy-policy', 'LeviLauncher/privacy-policy', 'en', 'Privacy Policy', true], + ['zh-CN/', 'LeviLauncher/zh-CN/guide/quick-start?platform=android', 'zh-CN', '5 分钟上手', false], + ['zh-CN/guide/getting-started', 'LeviLauncher/zh-CN/guide/quick-start?platform=android', 'zh-CN', '5 分钟上手', false], + ['zh-CN/guide/features', 'LeviLauncher/zh-CN/guide/version-management?platform=android', 'zh-CN', '版本管理', false], + ['zh-CN/guide/compatibility', 'LeviLauncher/zh-CN/guide/faq-community-feedback', 'zh-CN', '常见问题、社区与反馈', false], + ['zh-CN/guide/developer', 'LeviLamina/zh/developer_guides/android/', 'zh-CN', '原生模组快速开始', true], + ['zh-CN/guide/build', 'LeviLamina/zh/developer_guides/android/', 'zh-CN', '原生模组快速开始', false], + ['zh-CN/api/mod', 'LeviLamina/zh/developer_guides/android/api/mod/', 'zh-CN', 'Mod API', true], + ['zh-CN/api/mod-menu', 'LeviLamina/zh/developer_guides/android/api/mod_menu/', 'zh-CN', 'Mod Menu API', true], + ['zh-CN/api/config', 'LeviLamina/zh/developer_guides/android/api/config/', 'zh-CN', 'Config API', true], + ['zh-CN/api/input', 'LeviLamina/zh/developer_guides/android/api/input/', 'zh-CN', 'Input API', true], + ['zh-CN/api/hook', 'LeviLamina/zh/developer_guides/android/api/hook/', 'zh-CN', 'Hook API', true], + ['zh-CN/api/signature', 'LeviLamina/zh/developer_guides/android/api/signature/', 'zh-CN', 'Signature API', true], + ['zh-CN/api/patch', 'LeviLamina/zh/developer_guides/android/api/patch/', 'zh-CN', 'Patch API', true], + ['zh-CN/api/memory-hook-macros', 'LeviLamina/zh/developer_guides/android/api/memory_hook_macros/', 'zh-CN', 'Memory Hook 示例', true], + ['zh-CN/api/types-and-macros', 'LeviLamina/zh/developer_guides/android/api/types_and_macros/', 'zh-CN', 'SDK 头文件与宏', { pl_export: ['pl-export'], pl_register_mod: ['pl-register-mod'] }], + ['zh-Hant/', 'LeviLauncher/zh-HK/guide/quick-start?platform=android', 'zh-HK', '5 分鐘上手', false], + ['zh-Hant/guide/getting-started', 'LeviLauncher/zh-HK/guide/quick-start?platform=android', 'zh-HK', '5 分鐘上手', false], + ['zh-Hant/guide/features', 'LeviLauncher/zh-HK/guide/version-management?platform=android', 'zh-HK', '版本管理', false], + ['zh-Hant/guide/compatibility', 'LeviLauncher/zh-HK/guide/faq-community-feedback', 'zh-HK', '常見問題、社群與回饋', false], + ['zh-Hant/guide/developer', 'LeviLamina/zh-Hant/developer_guides/android/', 'zh-HK', '原生模組快速開始', true], + ['zh-Hant/guide/build', 'LeviLamina/zh-Hant/developer_guides/android/', 'zh-HK', '原生模組快速開始', false], + ['zh-Hant/api/mod', 'LeviLamina/zh-Hant/developer_guides/android/api/mod/', 'zh-HK', 'Mod API', true], + ['zh-Hant/api/mod-menu', 'LeviLamina/zh-Hant/developer_guides/android/api/mod_menu/', 'zh-HK', 'Mod Menu API', true], + ['zh-Hant/api/config', 'LeviLamina/zh-Hant/developer_guides/android/api/config/', 'zh-HK', 'Config API', true], + ['zh-Hant/api/input', 'LeviLamina/zh-Hant/developer_guides/android/api/input/', 'zh-HK', 'Input API', true], + ['zh-Hant/api/hook', 'LeviLamina/zh-Hant/developer_guides/android/api/hook/', 'zh-HK', 'Hook API', true], + ['zh-Hant/api/signature', 'LeviLamina/zh-Hant/developer_guides/android/api/signature/', 'zh-HK', 'Signature API', true], + ['zh-Hant/api/patch', 'LeviLamina/zh-Hant/developer_guides/android/api/patch/', 'zh-HK', 'Patch API', true], + ['zh-Hant/api/memory-hook-macros', 'LeviLamina/zh-Hant/developer_guides/android/api/memory_hook_macros/', 'zh-HK', 'Memory Hook 示例', true], + ['zh-Hant/api/types-and-macros', 'LeviLamina/zh-Hant/developer_guides/android/api/types_and_macros/', 'zh-HK', 'SDK 頭文件與宏', { pl_export: ['pl-export'], pl_register_mod: ['pl-register-mod'] }], + ], + aliases: [ + ['api/', 'LeviLamina/developer_guides/android/api/mod/'], + ['guide/', 'LeviLauncher/guide/quick-start?platform=android'], + ['zh-CN/api/', 'LeviLamina/zh/developer_guides/android/api/mod/'], + ['zh-CN/guide/', 'LeviLauncher/zh-CN/guide/quick-start?platform=android'], + ['zh-Hant/api/', 'LeviLamina/zh-Hant/developer_guides/android/api/mod/'], + ['zh-Hant/guide/', 'LeviLauncher/zh-HK/guide/quick-start?platform=android'], + ], + // docs/public/appicon.png of LiteLDev/LeviLaunchroid (its favicon and logo; LeviLauncher's differs). + files: ['appicon.png'], + fallbacks: [ + ['zh-CN/', 'LeviLauncher/zh-CN/guide/quick-start?platform=android'], + ['zh-Hant/', 'LeviLauncher/zh-HK/guide/quick-start?platform=android'], + ['', 'LeviLauncher/guide/quick-start?platform=android'], + ], + }, + { + // LiteLDev/preloader-android docs/ at a29b5a6702 (VitePress, base /preloader-android/, cleanUrls, + // locales: root = English, zh-CN/). The SDK docs now live in LeviLamina's docs (developer_guides/android/; formerly + // LeviLaunchroid's docs, see above), rewritten for the C++ pl:: API (the old pages documented the C pl_* API); + // Pages on preloader-android is disabled, so these paths reach this site. + from: '/preloader-android/', + to: '/LeviLamina/', + oldName: 'Preloader Android', + newName: 'LeviLamina', + pages: [ + ['', 'developer_guides/android/', 'en', 'Native Mod Quick Start', true], + ['guide/getting-started', 'developer_guides/android/', 'en', 'Native Mod Quick Start', false], + ['guide/build', 'developer_guides/android/', 'en', 'Native Mod Quick Start', false], + ['guide/compatibility', 'developer_guides/android/', 'en', 'Native Mod Quick Start', false], + ['api/mod', 'developer_guides/android/api/mod/', 'en', 'Mod API', { + 'mod-api': ['mod-entry-api'], + header: ['headers'], + registration: ['signatures', 'example'], + lifecycle: ['return-value'], + nativemod: ['fields', 'parameters'], + }], + ['api/input', 'developer_guides/android/api/input/', 'en', 'Input API', { + header: ['headers'], + functions: ['signatures', 'getpreloaderinput', 'registertouchcallback', 'registerkeyeventcallback', 'showkeyboard-hidekeyboard'], + }], + ['api/hook', 'developer_guides/android/api/hook/', 'en', 'Hook API', { + header: ['headers'], + types: ['chain-behavior'], + functions: ['signatures', 'pl-hook', 'pl-unhook'], + }], + ['api/signature', 'developer_guides/android/api/signature/', 'en', 'Signature API', { + header: ['headers'], + functions: ['signatures', 'pl-resolve-signature'], + example: ['c-example', 'c-batch-example'], + }], + ['api/patch', 'developer_guides/android/api/patch/', 'en', 'Patch API', { + functions: ['signatures', 'pl-patch-write-bytes-writebytes', 'pl-patch-read-bytes-readbytes', 'pl-patch-revert-revert', 'pl-patch-revert-all-revertall'], + example: ['c-example', 'c-example-1'], + }], + ['api/memory-hook-macros', 'developer_guides/android/api/memory_hook_macros/', 'en', 'Memory Hook Example', { + 'memory-hook-example': ['memory-hook-macros'], + headers: ['header'], + example: ['static-function-example'], + }], + ['api/types-and-macros', 'developer_guides/android/api/types_and_macros/', 'en', 'SDK Headers and Macros', { + 'sdk-headers-and-macros': ['types-and-macros'], + 'public-headers': ['headers'], + pl_export: ['plapi', 'pl-export'], + pl_register_mod: ['pl-register-mod'], + }], + ['zh-CN/', 'zh/developer_guides/android/', 'zh-CN', '原生模组快速开始', true], + ['zh-CN/guide/getting-started', 'zh/developer_guides/android/', 'zh-CN', '原生模组快速开始', false], + ['zh-CN/guide/build', 'zh/developer_guides/android/', 'zh-CN', '原生模组快速开始', false], + ['zh-CN/guide/compatibility', 'zh/developer_guides/android/', 'zh-CN', '原生模组快速开始', false], + ['zh-CN/api/mod', 'zh/developer_guides/android/api/mod/', 'zh-CN', 'Mod API', { + 'mod-api': ['mod-入口-api'], + 注册: ['类型签名', '最小示例'], + 生命周期: ['返回值'], + nativemod: ['字段说明', '参数'], + 注意: ['注意事项'], + }], + ['zh-CN/api/input', 'zh/developer_guides/android/api/input/', 'zh-CN', 'Input API', { + 函数: ['类型签名', 'getpreloaderinput', 'registertouchcallback', 'registerkeyeventcallback', 'showkeyboard-hidekeyboard'], + 示例: ['示例-1'], + 注意: ['注意事项'], + }], + ['zh-CN/api/hook', 'zh/developer_guides/android/api/hook/', 'zh-CN', 'Hook API', { + 类型: ['链式-hook-行为'], + 函数: ['类型签名', 'pl-hook', 'pl-unhook'], + }], + ['zh-CN/api/signature', 'zh/developer_guides/android/api/signature/', 'zh-CN', 'Signature API', { + 函数: ['类型签名', 'pl-resolve-signature'], + 示例: ['c-示例', 'c-批量示例'], + }], + ['zh-CN/api/patch', 'zh/developer_guides/android/api/patch/', 'zh-CN', 'Patch API', { + 函数: ['类型签名', 'pl-patch-write-bytes-writebytes', 'pl-patch-read-bytes-readbytes', 'pl-patch-revert-revert', 'pl-patch-revert-all-revertall'], + 示例: ['c-示例', 'c-示例-1'], + 注意: ['注意事项'], + }], + ['zh-CN/api/memory-hook-macros', 'zh/developer_guides/android/api/memory_hook_macros/', 'zh-CN', 'Memory Hook 示例', { + 'memory-hook-示例': ['memory-hook-宏'], + 示例: ['静态函数示例', '自动注册示例', '直接地址示例'], + 注意: ['注意事项'], + }], + ['zh-CN/api/types-and-macros', 'zh/developer_guides/android/api/types_and_macros/', 'zh-CN', 'SDK 头文件与宏', { + 'sdk-头文件与宏': ['types-与宏'], + 公开头文件: ['头文件'], + pl_export: ['宏', 'plapi', 'pl-export'], + pl_register_mod: ['pl-register-mod'], + }], + ], + aliases: [ + ['api/', 'developer_guides/android/api/mod/'], + ['guide/', 'developer_guides/android/'], + ['zh-CN/api/', 'zh/developer_guides/android/api/mod/'], + ['zh-CN/guide/', 'zh/developer_guides/android/'], + ], + // docs/public/appicon.png at a29b5a6702 (the old favicon and logo; byte-identical to LeviLaunchroid's). + files: ['appicon.png'], + fallbacks: [ + ['zh-CN/', 'zh/developer_guides/android/'], + ['', 'developer_guides/android/'], + ], + }, + { + // LiteXLoader's docsify site (formerly liteldev.github.io/LiteXLoader/, which GitHub 301s to the organisation site; still + // linked from READMEs). LiteXLoader became LLSE, now LegacyScriptEngine. The repository is gone, and its + // pages were docsify `#/…` routes on one index.html, so every old URL goes to the LegacyScriptEngine docs + // home (which picks the reader's language) and the hash is dropped. + from: '/LiteXLoader/', + to: '/LegacyScriptEngine/', + oldName: 'LiteXLoader', + newName: 'LegacyScriptEngine', + pages: [['', '', 'en', 'LegacyScriptEngine docs', false]], + fallbacks: [['', '']], + }, +]; + +/** + * Project sites published by their own repositories (the projects with docs). Their paths are case-sensitive on + * GitHub Pages, so a wrongly cased link (/levilamina/…) reaches this site's 404; it forwards to the correctly cased + * path. + */ +export const PROJECT_SITES = DOCS_PROJECTS.map((p) => p.id); diff --git a/mods/README.md b/mods/README.md index eab36a4..3d37220 100644 --- a/mods/README.md +++ b/mods/README.md @@ -249,7 +249,7 @@ them untouched. Only the pages (and LeviLauncher) read them, through `src/data/f - the featured tags below come first, with an icon and a translated name, and each stands for its group: a few common tags that mean the same are shown and filtered as it, with the mod's own tag in grey beside the name. -To be found under a featured tag, give the mod that tag — lip's [recommended tags](https://docs.levimc.org/lip/guides/creating_packages.html#recommended-tags) +To be found under a featured tag, give the mod that tag — lip's [recommended tags](https://levimc.org/lip/guides/creating_packages.html#recommended-tags) are the same list. The other names are only how the site groups what mods already use; they are no reason to use them instead. diff --git a/mods/src/i18n.ts b/mods/src/i18n.ts index 56379e6..05f60e0 100644 --- a/mods/src/i18n.ts +++ b/mods/src/i18n.ts @@ -76,7 +76,7 @@ const en = { installHint: "Run this in your server folder with lip:", // lip manages server folders only; clients install packages through LeviLauncher clientHint: "On a client, install it through", - clientHintUrl: "https://docs.levimc.org/LeviLauncher/guide/mods-integrations?platform=windows", + clientHintUrl: "https://levimc.org/LeviLauncher/guide/mods-integrations?platform=windows", variant: "Variant", version: "Version", defaultVariant: "Default", @@ -227,7 +227,7 @@ const zhCN: Strings = { installTitle: (name) => `安装 ${name}`, installHint: "在服务端目录中用 lip 运行:", clientHint: "在客户端上,请通过以下方式安装:", - clientHintUrl: "https://docs.levimc.org/LeviLauncher/zh-CN/guide/mods-integrations?platform=windows", + clientHintUrl: "https://levimc.org/LeviLauncher/zh-CN/guide/mods-integrations?platform=windows", variant: "变体", version: "版本", defaultVariant: "默认", @@ -371,7 +371,7 @@ const zhHant: Strings = { installTitle: (name) => `安裝 ${name}`, installHint: "在伺服器目錄中用 lip 執行:", clientHint: "在用戶端上,請透過以下方式安裝:", - clientHintUrl: "https://docs.levimc.org/LeviLauncher/zh-HK/guide/mods-integrations?platform=windows", + clientHintUrl: "https://levimc.org/LeviLauncher/zh-HK/guide/mods-integrations?platform=windows", variant: "變體", defaultVariant: "預設", downloadFromGitHub: "從 GitHub 下載", diff --git a/mods/src/lib/markdown.test.ts b/mods/src/lib/markdown.test.ts index 2b44766..06a1060 100644 --- a/mods/src/lib/markdown.test.ts +++ b/mods/src/lib/markdown.test.ts @@ -45,7 +45,7 @@ test("srcset URLs resolve like image sources", () => { assert.equal(resolveSrcSet(`${chart} 2x,docs/x.png`, BASES), `${chart} 2x, ${BASES.raw}docs/x.png`); assert.equal( resolveSrcSet("https://lamina.levimc.org/logo.svg", BASES), - "https://docs.levimc.org/LeviLamina/logo.svg", + "https://levimc.org/LeviLamina/logo.svg", ); }); @@ -62,8 +62,8 @@ test("percent-encoded anchors are spelled like heading ids", () => { assert.equal(link("#%E0%A4%A"), "#%E0%A4%A"); }); -test("retired documentation hosts point at pages that exist on docs.levimc.org", () => { - const LL = "https://docs.levimc.org/LeviLamina/"; +test("retired documentation hosts point at pages that exist on levimc.org", () => { + const LL = "https://levimc.org/LeviLamina/"; const cases: [string, string][] = [ ["https://lamina.levimc.org/", LL], ["https://lamina.levimc.org", LL], @@ -79,23 +79,23 @@ test("retired documentation hosts point at pages that exist on docs.levimc.org", ], // A page that is not known to exist goes to the docs home, not to a 404. ["https://lamina.levimc.org/no/such/page/#x", LL], - ["http://lse.levimc.org", "https://docs.levimc.org/LegacyScriptEngine/"], - ["https://lse.liteldev.com", "https://docs.levimc.org/LegacyScriptEngine/"], - ["https://legacy-script-engine.levimc.org", "https://docs.levimc.org/LegacyScriptEngine/"], - ["https://lip.levimc.org/guide/", "https://docs.levimc.org/lip/"], - ["https://lip.futrime.com", "https://docs.levimc.org/lip/"], + ["http://lse.levimc.org", "https://levimc.org/LegacyScriptEngine/"], + ["https://lse.liteldev.com", "https://levimc.org/LegacyScriptEngine/"], + ["https://legacy-script-engine.levimc.org", "https://levimc.org/LegacyScriptEngine/"], + ["https://lip.levimc.org/guide/", "https://levimc.org/lip/"], + ["https://lip.futrime.com", "https://levimc.org/lip/"], [ "https://lip.docs.litebds.com/en/#/tutorials/create_a_lip_tooth", - "https://docs.levimc.org/lip/guides/creating_packages.html", + "https://levimc.org/lip/guides/creating_packages.html", ], - ["https://lip.docs.litebds.com/zh-cn/#/", "https://docs.levimc.org/lip/"], - ["https://levilauncher.levimc.org/", "https://docs.levimc.org/LeviLauncher/"], + ["https://lip.docs.litebds.com/zh-cn/#/", "https://levimc.org/lip/"], + ["https://levilauncher.levimc.org/", "https://levimc.org/LeviLauncher/"], ["https://levimc.org/software/levilamina", LL], ]; for (const [from, to] of cases) assert.equal(link(from), to, from); // Look-alikes stay as they are. assert.equal(link("https://lamina.levimc.org.example/"), "https://lamina.levimc.org.example/"); - assert.equal(link("https://docs.levimc.org/LeviLamina/"), LL); + assert.equal(link("https://levimc.org/LeviLamina/"), LL); }); test("LiteLDev repositories and pages that moved", () => { @@ -214,7 +214,7 @@ test("links to renamed mod repositories skip GitHub's redirect", () => { }); test("avatars on retired hosts and renamed repositories are rewritten, others kept", () => { - assert.equal(resolveAvatarUrl("https://lamina.levimc.org/logo.svg"), "https://docs.levimc.org/LeviLamina/logo.svg"); + assert.equal(resolveAvatarUrl("https://lamina.levimc.org/logo.svg"), "https://levimc.org/LeviLamina/logo.svg"); assert.equal( resolveAvatarUrl("https://github.com/lwenk/Stats/raw/main/logo.png", { "lwenk/stats": "LeafKnife/Stats" }), "https://raw.githubusercontent.com/LeafKnife/Stats/main/logo.png", diff --git a/mods/src/lib/markdown.ts b/mods/src/lib/markdown.ts index 93b7232..4c4fa04 100644 --- a/mods/src/lib/markdown.ts +++ b/mods/src/lib/markdown.ts @@ -21,7 +21,7 @@ const OWN_RENAMES: RepositoryRenames = { /** * Retired documentation hosts of LeviMC projects. None of them resolves any - * more; their pages live under docs.levimc.org now. Only pages known to exist + * more; their pages live under levimc.org/<Project>/ now. Only pages known to exist * there keep their path (`paths`: old path → new path); any other path goes to * the project's docs home, so a rewritten link never ends on a 404. */ @@ -34,7 +34,7 @@ interface RetiredDocs { const RETIRED_DOCS: RetiredDocs[] = [ { hosts: ["lamina.levimc.org", "levilamina.liteldev.com"], - home: "https://docs.levimc.org/LeviLamina/", + home: "https://levimc.org/LeviLamina/", paths: { // The Quickstart became the install guide (LeviLamina's own README // switched to it in 1.9.3). @@ -48,11 +48,11 @@ const RETIRED_DOCS: RetiredDocs[] = [ }, { hosts: ["lse.levimc.org", "lse.liteldev.com", "legacy-script-engine.levimc.org"], - home: "https://docs.levimc.org/LegacyScriptEngine/", + home: "https://levimc.org/LegacyScriptEngine/", }, { hosts: ["lip.levimc.org", "lip.futrime.com", "lip.docs.litebds.com"], - home: "https://docs.levimc.org/lip/", + home: "https://levimc.org/lip/", paths: { // lip's old docs routed in the fragment: `/en/#/tutorials/…`. "en/#/tutorials/create_a_lip_tooth": "guides/creating_packages.html", @@ -60,7 +60,7 @@ const RETIRED_DOCS: RetiredDocs[] = [ }, { hosts: ["levilauncher.levimc.org"], - home: "https://docs.levimc.org/LeviLauncher/", + home: "https://levimc.org/LeviLauncher/", }, ]; @@ -69,7 +69,7 @@ const RETIRED_DOCS: RetiredDocs[] = [ * paths in LiteLDev repositories, and a third-party host that is gone. */ const MOVED_PAGES: [RegExp, string][] = [ - [/^https?:\/\/levimc\.org\/software\/levilamina\/?(?=[?#]|$)/i, "https://docs.levimc.org/LeviLamina/"], + [/^https?:\/\/levimc\.org\/software\/levilamina\/?(?=[?#]|$)/i, "https://levimc.org/LeviLamina/"], // `develop` was merged into `main`; this one is a directory, which GitHub shows under `tree/`. [ /^https?:\/\/(?:www\.)?github\.com\/LiteLDev\/LeviLamina\/(?:blob|tree)\/develop\/src\/ll\/api\/i18n\/?(?=[?#]|$)/i, diff --git a/package.json b/package.json index 48becae..685e7d6 100644 --- a/package.json +++ b/package.json @@ -8,11 +8,11 @@ }, "scripts": { "dev": "vite", - "build": "vite build && vite build --ssr src/entry-server.tsx --outDir .kit/ssr && node prerender.mjs", + "build": "vite build && vite build --ssr src/entry-server.tsx --outDir .kit/ssr && node prerender.mjs && node legacy/build.mjs dist", "preview": "node kit/scripts/serve-pages.mjs dist --base / --port 4173", "typecheck": "tsc --noEmit", - "test": "node --test \"blog/*.test.ts\" \"kit/tests/*.test.mjs\" \"versions/*.test.mjs\"", - "linkcheck": "node kit/scripts/linkcheck.mjs dist --base / --site-origin https://levimc.org", + "test": "node --test \"blog/*.test.ts\" \"kit/tests/*.test.mjs\" \"versions/*.test.mjs\" \"legacy/*.test.mjs\"", + "linkcheck": "node kit/scripts/linkcheck.mjs dist --base / --site-origin https://levimc.org --other-sites /LeviLamina/,/LegacyScriptEngine/,/lip/,/LeviLauncher/,/BeDD/,/bedboo/", "smoke": "node scripts/smoke.mjs --url http://127.0.0.1:4173/", "smoke:kit": "node kit/scripts/smoke.mjs --app --url http://127.0.0.1:4173/ --pages about/,community/,support/ --current about && node kit/scripts/smoke.mjs --app --url http://127.0.0.1:4173/ --pages blog/,blog/2023/07/26/original-fix-BeeCrash/,blog/archives/ --current blog" }, diff --git a/prerender.mjs b/prerender.mjs index 8ba0f8e..a53300c 100644 --- a/prerender.mjs +++ b/prerender.mjs @@ -4,7 +4,7 @@ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { prerenderRoutes } from './kit/ssg/prerender.mjs'; -const { ROUTE_PATHS, NOT_FOUND_PATH, SITE_ORIGIN, MODS_PATH, ROUTE_MODULES, routeIdOf } = await import('./.kit/ssr/entry-server.js'); +const { ROUTE_PATHS, NOT_FOUND_PATH, SITE_ORIGIN, MODS_PATH, ROUTE_MODULES, routeIdOf, DOCS_PROJECTS } = await import('./.kit/ssr/entry-server.js'); const { files } = await prerenderRoutes({ routes: ROUTE_PATHS, notFound: NOT_FOUND_PATH }); @@ -65,10 +65,9 @@ for (const route of ROUTE_PATHS) { const urls = ROUTE_PATHS.map((p) => ` <url><loc>${SITE_ORIGIN}${encodeURI(p)}</loc></url>`).join('\n'); writeFileSync('dist/sitemap.xml', `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n${urls}\n</urlset>\n`); -// LeviMC Mods writes its own sitemap (every mod page); its listing's query URLs (/mods/?cat=…) are all one page. -writeFileSync( - 'dist/robots.txt', - `User-agent: *\nAllow: /\nDisallow: ${MODS_PATH}*?*\n\nSitemap: ${SITE_ORIGIN}/sitemap.xml\nSitemap: ${SITE_ORIGIN}${MODS_PATH}sitemap.xml\n`, -); +// LeviMC Mods writes its own sitemap (every mod page); its listing's query URLs (/mods/?cat=…) are all one page. Each +// project's docs (levimc.org/<Project>/, published by its repository) write theirs too: robots.txt exists only here. +const sitemaps = [`${SITE_ORIGIN}/sitemap.xml`, `${SITE_ORIGIN}${MODS_PATH}sitemap.xml`, ...DOCS_PROJECTS.map((p) => `${p.url}sitemap.xml`)]; +writeFileSync('dist/robots.txt', `User-agent: *\nAllow: /\nDisallow: ${MODS_PATH}*?*\n\n${sitemaps.map((u) => `Sitemap: ${u}\n`).join('')}`); console.log(`prerendered ${files.length} pages (${preloaded} with modulepreloaded page/post chunks) + sitemap.xml (${ROUTE_PATHS.length} URLs), robots.txt`); diff --git a/scripts/smoke.mjs b/scripts/smoke.mjs index 5847841..3807fdc 100644 --- a/scripts/smoke.mjs +++ b/scripts/smoke.mjs @@ -382,8 +382,8 @@ await check('header: one bar, every destination once; Projects menu opens; cross assert((await page.locator('.kit-gbar-link[aria-current="page"]').innerText()) === 'About', 'About not current'); await page.click('.kit-gbar-projects > summary'); const panel = page.locator('.kit-gbar-projects-panel'); - assert(await panel.locator('a.kit-proj-main[href="https://docs.levimc.org/LeviLamina/"]').isVisible(), 'LeviLamina leads to its docs'); - assert((await panel.locator('a.kit-proj-main').evaluateAll((as) => as.every((a) => a.href.startsWith('https://docs.levimc.org/')))), 'Projects menu lists a project without docs'); + assert(await panel.locator('a.kit-proj-main[href="https://levimc.org/LeviLamina/"]').isVisible(), 'LeviLamina leads to its docs'); + assert((await panel.locator('a.kit-proj-main').evaluateAll((as) => as.every((a) => /^https:\/\/levimc\.org\/(LeviLamina|LegacyScriptEngine|lip|LeviLauncher|BeDD|bedboo)\/$/.test(a.href)))), 'Projects menu lists a project without docs'); assert((await panel.locator('.kit-proj-link').count()) === 0, 'Projects menu rows carry extra links'); await page.keyboard.press('Escape'); await ctx.close(); diff --git a/src/components/CodeCard.tsx b/src/components/CodeCard.tsx index 9b0dbaf..99aa522 100644 --- a/src/components/CodeCard.tsx +++ b/src/components/CodeCard.tsx @@ -3,7 +3,7 @@ import { HotbarTabs } from '../../kit/components'; import { SHIKI_PALETTES } from '../../kit/docs/node/markdown/shiki-themes.ts'; // Token colours come from the kit's Shiki palettes (the same ones the docs use), so the snippet matches -// the code blocks on docs.levimc.org in both themes. A token only carries its role class; the palette is set +// the code blocks of the project docs in both themes. A token only carries its role class; the palette is set // once on the block as custom properties, which src/styles.css maps onto --shiki-light / --shiki-dark. type Role = 'comment' | 'keyword' | 'type' | 'func' | 'string' | 'param' | 'punct'; const PALETTE_KEY: Record<Role, keyof typeof SHIKI_PALETTES.light> = { diff --git a/src/components/SiteHeader.tsx b/src/components/SiteHeader.tsx index d7bf188..d2d70a9 100644 --- a/src/components/SiteHeader.tsx +++ b/src/components/SiteHeader.tsx @@ -1,5 +1,5 @@ import { Link } from 'react-router'; -import { GlobalBar, type LinkLikeProps, type SiteId } from '../../kit/components'; +import { DOCS_PROJECTS, GlobalBar, type LinkLikeProps, type SiteId } from '../../kit/components'; import { useI18n, LOCALES } from '../i18n'; import { MODS_PATH, SITE_ORIGIN, type RouteId } from '../routes'; @@ -12,8 +12,10 @@ export function RouterLink({ href, children, ...rest }: LinkLikeProps) { ); } -/** LeviMC Mods (/mods/) is a separate app on this origin: its links load in full. */ -export const isAppPath = (path: string) => !path.startsWith(MODS_PATH); +/** Paths of this origin that other sites serve: LeviMC Mods (/mods/, a separate app) and each project's docs + * (/<Project>/, published by the project's repository). Their links load in full. */ +const OTHER_SITES = [MODS_PATH, ...DOCS_PROJECTS.map((p) => new URL(p.url).pathname)]; +export const isAppPath = (path: string) => !OTHER_SITES.some((prefix) => path.startsWith(prefix)); /** The bar tab of each page (Support Us has none: it is linked from the footer). */ const BAR_TAB: Partial<Record<RouteId, SiteId>> = { diff --git a/src/entry-server.tsx b/src/entry-server.tsx index f27db72..dceea96 100644 --- a/src/entry-server.tsx +++ b/src/entry-server.tsx @@ -9,6 +9,7 @@ import { preloadBlogPath } from './blog/data'; export { ROUTE_PATHS, NOT_FOUND_PATH, SITE_ORIGIN, MODS_PATH, ROUTE_MODULES, routeIdOf } from './routes'; export { BLOG_ROUTES } from './blog/data'; +export { DOCS_PROJECTS } from '../kit/components'; export async function render(url: string) { await Promise.all([preloadRoute(url), preloadBlogPath(url)]); diff --git a/src/pages/NotFound.tsx b/src/pages/NotFound.tsx index 25b91a3..be7766a 100644 --- a/src/pages/NotFound.tsx +++ b/src/pages/NotFound.tsx @@ -5,7 +5,7 @@ import { pathOf } from '../routes'; /** * Themed 404 (also prerendered to 404.html, which GitHub Pages serves for unknown paths). The same card as the - * docs' 404 (red "Error 404" label, title, text, two actions) plus, like docs.levimc.org's 404, the projects with + * docs' 404 (red "Error 404" label, title, text, two actions) plus, like the docs' 404, the projects with * documentation, so a mistyped docs link still gets somewhere. */ export default function NotFound() { diff --git a/src/styles.css b/src/styles.css index e8889f6..2181a1d 100644 --- a/src/styles.css +++ b/src/styles.css @@ -1438,7 +1438,7 @@ min-height: 60vh; } - /* the 404: the docs' card, wide enough for the projects grid under its actions (as docs.levimc.org's 404) */ + /* the 404: the docs' card, wide enough for the projects grid under its actions (as the docs' 404) */ .lm-notfound .kit-notfound-card { width: min(46rem, 100%); max-width: none;