|
16 | 16 | import json |
17 | 17 | import logging |
18 | 18 | import os |
| 19 | +import re |
19 | 20 | import socket |
20 | 21 | import threading |
21 | 22 | from collections.abc import Iterable |
22 | 23 | from urllib.parse import urlparse |
23 | 24 |
|
24 | 25 | from fastapi import FastAPI, HTTPException, Request |
25 | | -from fastapi.responses import FileResponse, JSONResponse, Response, StreamingResponse |
| 26 | +from fastapi.responses import ( |
| 27 | + FileResponse, |
| 28 | + HTMLResponse, |
| 29 | + JSONResponse, |
| 30 | + Response, |
| 31 | + StreamingResponse, |
| 32 | +) |
26 | 33 | from pydantic import BaseModel, Field |
27 | 34 |
|
28 | 35 | from codewiki import __version__ |
|
34 | 41 |
|
35 | 42 | # Never served: the dependency graph / caches under temp/ and dotfiles. |
36 | 43 | _HIDDEN_PREFIXES = ("temp/", ".") |
| 44 | +SERVE_MARKER = '<meta name="codewiki-serve" content="1">' |
37 | 45 |
|
38 | 46 |
|
39 | 47 | class AskRequest(BaseModel): |
@@ -241,6 +249,19 @@ def static(path: str): |
241 | 249 | full = os.path.realpath(os.path.join(docs_dir, rel)) |
242 | 250 | if not full.startswith(os.path.realpath(docs_dir) + os.sep) or not os.path.isfile(full): |
243 | 251 | raise HTTPException(404) |
| 252 | + if full.endswith(".html"): |
| 253 | + # Tell the page it is served by `codewiki serve`, so its chat uses this origin. |
| 254 | + # Elsewhere (GitHub Pages) probing the own origin's /api/health only 404s. |
| 255 | + with open(full, encoding="utf-8") as f: |
| 256 | + html = f.read() |
| 257 | + html = re.sub( |
| 258 | + r"<head(?:\s[^>]*)?>", |
| 259 | + lambda m: m.group(0) + SERVE_MARKER, |
| 260 | + html, |
| 261 | + count=1, |
| 262 | + flags=re.I, |
| 263 | + ) |
| 264 | + return HTMLResponse(html) |
244 | 265 | return FileResponse(full) |
245 | 266 |
|
246 | 267 | return app |
|
0 commit comments