|
| 1 | +# SPDX-License-Identifier: Apache-2.0 |
| 2 | +# SPDX-FileCopyrightText: Copyright the Vortex contributors |
| 3 | + |
| 4 | +"""Add Cloudflare Pages' HTML URL handling to a Build Output API config. |
| 5 | +
|
| 6 | +Pages serves `page.html` at `/page` and `dir/index.html` at `/dir/`, and |
| 7 | +redirects every other spelling of those URLs to them. Sphinx output relies |
| 8 | +on this: its links are relative, so a directory page must be served with |
| 9 | +its trailing slash, and links shared since the docs moved to Pages use the |
| 10 | +URLs without `.html`. |
| 11 | +
|
| 12 | +Usage: pages-html-routes.py OUTPUT_DIR |
| 13 | +
|
| 14 | +OUTPUT_DIR is a `.vercel/output` directory holding `static/` and a |
| 15 | +`config.json` whose routes only set headers. The routes this script adds |
| 16 | +follow those header routes. |
| 17 | +""" |
| 18 | + |
| 19 | +import json |
| 20 | +import re |
| 21 | +import sys |
| 22 | +from pathlib import Path |
| 23 | + |
| 24 | + |
| 25 | +def redirect(src: str, location: str, status: int = 308) -> dict: |
| 26 | + return {"src": src, "status": status, "headers": {"Location": location}} |
| 27 | + |
| 28 | + |
| 29 | +def html_routes(static: Path) -> list[dict]: |
| 30 | + # Vercel serves `dir/index.html` at `/dir` as well as `/dir/`, and only a |
| 31 | + # route per directory can tell a directory from a page. |
| 32 | + directories = sorted( |
| 33 | + index.parent.relative_to(static).as_posix() for index in static.rglob("index.html") if index.parent != static |
| 34 | + ) |
| 35 | + # Whether `/x` or `/x/` is canonical depends on whether this build has |
| 36 | + # `x.html` or `x/index.html`. Those redirects are temporary (307), so a |
| 37 | + # browser that cached one cannot loop after the docs are reorganized. |
| 38 | + return [ |
| 39 | + *(redirect(f"^/{re.escape(d)}$", f"/{d}/", 307) for d in directories), |
| 40 | + redirect(r"^/index(?:\.html)?$", "/"), |
| 41 | + redirect(r"^/(.+)/index(?:\.html)?$", "/$1/"), |
| 42 | + redirect(r"^/(.+)\.html$", "/$1"), |
| 43 | + {"handle": "filesystem"}, |
| 44 | + # Only reached when no file or directory matched. |
| 45 | + redirect(r"^/(.+)/$", "/$1", 307), |
| 46 | + {"src": r"^/(.+)$", "dest": "/$1.html", "check": True}, |
| 47 | + ] |
| 48 | + |
| 49 | + |
| 50 | +def main(output: Path) -> None: |
| 51 | + config_path = output / "config.json" |
| 52 | + config = json.loads(config_path.read_text()) |
| 53 | + routes = config.get("routes", []) |
| 54 | + if any("handle" in route for route in routes): |
| 55 | + sys.exit(f"{config_path}: routes must only set headers when HTML handling is added") |
| 56 | + config["routes"] = routes + html_routes(output / "static") |
| 57 | + config_path.write_text(json.dumps(config, indent=2) + "\n") |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + main(Path(sys.argv[1])) |
0 commit comments