File size: 2,488 Bytes
3806142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2e7f3ce
 
 
 
 
 
 
 
 
 
3806142
 
2e7f3ce
3806142
 
 
48a7b17
 
 
 
 
3806142
 
 
2e7f3ce
3806142
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
"""SpaceForge FastAPI application — API + static frontend."""
from __future__ import annotations

import sys
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles

_ROOT = Path(__file__).resolve().parents[2]
if str(_ROOT) not in sys.path:
    sys.path.insert(0, str(_ROOT))

from backend.app.api.routes import router
from backend.app.config import STATIC_DIR
from backend.app.services.builds import build_manager


@asynccontextmanager
async def lifespan(app: FastAPI):
    build_manager.start_cleaner()
    yield


app = FastAPI(
    title="SpaceForge",
    description="Package Hugging Face Spaces as widgets, PWAs, extensions, and desktop projects.",
    version="0.1.0",
    lifespan=lifespan,
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(router)

_static = STATIC_DIR
if not _static.exists():
    alt = _ROOT / "frontend" / "dist"
    if alt.exists():
        _static = alt

if _static.exists():
    assets = _static / "assets"
    if assets.exists():
        app.mount("/assets", StaticFiles(directory=str(assets)), name="assets")

    def _index_response() -> FileResponse:
        return FileResponse(
            _static / "index.html",
            headers={
                "Cache-Control": "no-cache, no-store, must-revalidate",
                "Pragma": "no-cache",
                "Expires": "0",
            },
        )

    @app.get("/")
    async def index() -> FileResponse:
        return _index_response()

    @app.get("/{full_path:path}")
    async def spa_fallback(full_path: str) -> FileResponse:
        # Never SPA-fallback API/docs — return real 404 JSON/HTML from FastAPI
        if full_path.startswith(("api/", "api", "docs", "openapi.json", "redoc")):
            from fastapi import HTTPException

            raise HTTPException(status_code=404, detail="Not found")
        candidate = _static / full_path
        if full_path and candidate.exists() and candidate.is_file():
            return FileResponse(candidate)
        return _index_response()
else:

    @app.get("/")
    async def index_fallback() -> dict:
        return {
            "service": "SpaceForge",
            "status": "ok",
            "ui": "frontend not built — open /api/health /docs",
        }