stilo-cli 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- stilo_cli-0.1.0/.gitignore +19 -0
- stilo_cli-0.1.0/LICENSE +21 -0
- stilo_cli-0.1.0/PKG-INFO +75 -0
- stilo_cli-0.1.0/README.md +61 -0
- stilo_cli-0.1.0/pyproject.toml +58 -0
- stilo_cli-0.1.0/src/stilo/__init__.py +6 -0
- stilo_cli-0.1.0/src/stilo/__main__.py +7 -0
- stilo_cli-0.1.0/src/stilo/cli/__init__.py +18 -0
- stilo_cli-0.1.0/src/stilo/cli/commands.py +80 -0
- stilo_cli-0.1.0/src/stilo/server/__init__.py +5 -0
- stilo_cli-0.1.0/src/stilo/server/app.py +78 -0
- stilo_cli-0.1.0/src/stilo/server/storage.py +140 -0
- stilo_cli-0.1.0/src/stilo/web/assets/index-4AKEJowe.css +1 -0
- stilo_cli-0.1.0/src/stilo/web/assets/index-CM5cmnCe.js +889 -0
- stilo_cli-0.1.0/src/stilo/web/assets/texl_wasm_bg-DqOV-p_i.wasm +0 -0
- stilo_cli-0.1.0/src/stilo/web/index.html +20 -0
stilo_cli-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 OnLabs.org
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
stilo_cli-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: stilo-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Stilo: edit and render a folder of linked Texl documents
|
|
5
|
+
Project-URL: Homepage, https://www.onlabs.org/stilo/
|
|
6
|
+
Project-URL: Source, https://github.com/onlabsorg/stilo
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Requires-Python: >=3.11
|
|
10
|
+
Requires-Dist: fastapi>=0.115
|
|
11
|
+
Requires-Dist: pytexl>=0.4
|
|
12
|
+
Requires-Dist: uvicorn>=0.30
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
|
|
15
|
+
# Stilo
|
|
16
|
+
|
|
17
|
+
Stilo is the editor for [Texl](https://github.com/onlabsorg/texl) documents:
|
|
18
|
+
living documents that compute their content and link to each other. It
|
|
19
|
+
edits a folder of `.texl` files in the browser, as a stack of cells that
|
|
20
|
+
feels familiar to Word and Excel users, and renders them from the command
|
|
21
|
+
line.
|
|
22
|
+
|
|
23
|
+
Stilo is single-user and open source (MIT). Use it on your own folder,
|
|
24
|
+
locally or on a server of your own; collaboration between people and
|
|
25
|
+
organisations (accounts, permissions, release and accept) is the job of a
|
|
26
|
+
platform built on top of it.
|
|
27
|
+
|
|
28
|
+
> This repository used to hold the olojs version of Stilo, a CLI for
|
|
29
|
+
> olo-docs. That code is kept under the tag `olojs-v0.19.4`.
|
|
30
|
+
|
|
31
|
+
## Getting started
|
|
32
|
+
|
|
33
|
+
Requires Python 3.11 or later. Install the `stilo` command from PyPI, with
|
|
34
|
+
[uv](https://docs.astral.sh/uv/) or pip:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
uv tool install stilo-cli # or: pip install stilo-cli
|
|
38
|
+
stilo serve my-folder # http://127.0.0.1:8000
|
|
39
|
+
stilo render my-folder/report.texl
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
To try the sample documents, or to work on Stilo itself, use a checkout
|
|
43
|
+
(Node.js 22+ builds the web app):
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
git clone https://github.com/onlabsorg/stilo.git && cd stilo
|
|
47
|
+
cd web && npm install && npm run build && cd ..
|
|
48
|
+
uv run stilo serve examples
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Open <http://127.0.0.1:8000/projects/beam/beam-check.texl>. See the
|
|
52
|
+
[getting started guide](https://www.onlabs.org/stilo/book/getting-started.html)
|
|
53
|
+
and the developer guide.
|
|
54
|
+
|
|
55
|
+
## Parts
|
|
56
|
+
|
|
57
|
+
| Folder | What |
|
|
58
|
+
|-----------|---------------------------------------------------------------|
|
|
59
|
+
| `web/` | The web app's source (Lit, Vite): navigation, side panes and the editor (`web/src/editor/`, the `<texl-editor>` component) |
|
|
60
|
+
| `src/stilo/` | The Python package `stilo`: `server/` (FastAPI, one folder of documents), `cli/` (the `stilo` command, `render` and `serve`), `web/` (the built web app) |
|
|
61
|
+
| `tests/` | The Python tests |
|
|
62
|
+
| `pyproject.toml` | The package `stilo`, the only one published (on PyPI: `stilo-cli`) |
|
|
63
|
+
| `docs/` | The documentation (manual, editor manual, landing page), published on <https://www.onlabs.org/stilo/>; `docs/build.sh` builds it into `target/site` |
|
|
64
|
+
| `examples/` | Sample documents |
|
|
65
|
+
|
|
66
|
+
## Documentation
|
|
67
|
+
|
|
68
|
+
<https://www.onlabs.org/stilo/>: getting started, the `stilo` command, the
|
|
69
|
+
web editor (with an interactive editor manual), the protocol, the editor
|
|
70
|
+
component and a developer guide. See also [CONTRIBUTING.md](https://github.com/onlabsorg/stilo/blob/main/CONTRIBUTING.md)
|
|
71
|
+
and [CHANGELOG.md](https://github.com/onlabsorg/stilo/blob/main/CHANGELOG.md).
|
|
72
|
+
|
|
73
|
+
## License
|
|
74
|
+
|
|
75
|
+
[MIT](https://github.com/onlabsorg/stilo/blob/main/LICENSE)
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
# Stilo
|
|
2
|
+
|
|
3
|
+
Stilo is the editor for [Texl](https://github.com/onlabsorg/texl) documents:
|
|
4
|
+
living documents that compute their content and link to each other. It
|
|
5
|
+
edits a folder of `.texl` files in the browser, as a stack of cells that
|
|
6
|
+
feels familiar to Word and Excel users, and renders them from the command
|
|
7
|
+
line.
|
|
8
|
+
|
|
9
|
+
Stilo is single-user and open source (MIT). Use it on your own folder,
|
|
10
|
+
locally or on a server of your own; collaboration between people and
|
|
11
|
+
organisations (accounts, permissions, release and accept) is the job of a
|
|
12
|
+
platform built on top of it.
|
|
13
|
+
|
|
14
|
+
> This repository used to hold the olojs version of Stilo, a CLI for
|
|
15
|
+
> olo-docs. That code is kept under the tag `olojs-v0.19.4`.
|
|
16
|
+
|
|
17
|
+
## Getting started
|
|
18
|
+
|
|
19
|
+
Requires Python 3.11 or later. Install the `stilo` command from PyPI, with
|
|
20
|
+
[uv](https://docs.astral.sh/uv/) or pip:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
uv tool install stilo-cli # or: pip install stilo-cli
|
|
24
|
+
stilo serve my-folder # http://127.0.0.1:8000
|
|
25
|
+
stilo render my-folder/report.texl
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
To try the sample documents, or to work on Stilo itself, use a checkout
|
|
29
|
+
(Node.js 22+ builds the web app):
|
|
30
|
+
|
|
31
|
+
```bash
|
|
32
|
+
git clone https://github.com/onlabsorg/stilo.git && cd stilo
|
|
33
|
+
cd web && npm install && npm run build && cd ..
|
|
34
|
+
uv run stilo serve examples
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
Open <http://127.0.0.1:8000/projects/beam/beam-check.texl>. See the
|
|
38
|
+
[getting started guide](https://www.onlabs.org/stilo/book/getting-started.html)
|
|
39
|
+
and the developer guide.
|
|
40
|
+
|
|
41
|
+
## Parts
|
|
42
|
+
|
|
43
|
+
| Folder | What |
|
|
44
|
+
|-----------|---------------------------------------------------------------|
|
|
45
|
+
| `web/` | The web app's source (Lit, Vite): navigation, side panes and the editor (`web/src/editor/`, the `<texl-editor>` component) |
|
|
46
|
+
| `src/stilo/` | The Python package `stilo`: `server/` (FastAPI, one folder of documents), `cli/` (the `stilo` command, `render` and `serve`), `web/` (the built web app) |
|
|
47
|
+
| `tests/` | The Python tests |
|
|
48
|
+
| `pyproject.toml` | The package `stilo`, the only one published (on PyPI: `stilo-cli`) |
|
|
49
|
+
| `docs/` | The documentation (manual, editor manual, landing page), published on <https://www.onlabs.org/stilo/>; `docs/build.sh` builds it into `target/site` |
|
|
50
|
+
| `examples/` | Sample documents |
|
|
51
|
+
|
|
52
|
+
## Documentation
|
|
53
|
+
|
|
54
|
+
<https://www.onlabs.org/stilo/>: getting started, the `stilo` command, the
|
|
55
|
+
web editor (with an interactive editor manual), the protocol, the editor
|
|
56
|
+
component and a developer guide. See also [CONTRIBUTING.md](https://github.com/onlabsorg/stilo/blob/main/CONTRIBUTING.md)
|
|
57
|
+
and [CHANGELOG.md](https://github.com/onlabsorg/stilo/blob/main/CHANGELOG.md).
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
[MIT](https://github.com/onlabsorg/stilo/blob/main/LICENSE)
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
# The Python project of Stilo and its only published package, `stilo` (on
|
|
2
|
+
# PyPI `stilo-cli`: `stilo` is refused as too close to an existing name):
|
|
3
|
+
#
|
|
4
|
+
# src/stilo/cli the `stilo` command
|
|
5
|
+
# src/stilo/server the server (never imports the CLI)
|
|
6
|
+
# src/stilo/web the built web app, written by `npm run build` in web/
|
|
7
|
+
# (git-ignored; built into the package when present —
|
|
8
|
+
# the release workflow checks that the wheel has it)
|
|
9
|
+
#
|
|
10
|
+
# Build:
|
|
11
|
+
#
|
|
12
|
+
# cd web && npm ci && npm run build && cd ..
|
|
13
|
+
# uv build # dist/stilo_cli-<version>.tar.gz and .whl
|
|
14
|
+
|
|
15
|
+
[project]
|
|
16
|
+
name = "stilo-cli"
|
|
17
|
+
version = "0.1.0"
|
|
18
|
+
description = "Stilo: edit and render a folder of linked Texl documents"
|
|
19
|
+
readme = "README.md"
|
|
20
|
+
license = "MIT"
|
|
21
|
+
license-files = ["LICENSE"]
|
|
22
|
+
requires-python = ">=3.11"
|
|
23
|
+
dependencies = [
|
|
24
|
+
"fastapi>=0.115",
|
|
25
|
+
"pytexl>=0.4",
|
|
26
|
+
"uvicorn>=0.30",
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
[project.scripts]
|
|
30
|
+
stilo = "stilo.cli:main"
|
|
31
|
+
|
|
32
|
+
[project.urls]
|
|
33
|
+
Homepage = "https://www.onlabs.org/stilo/"
|
|
34
|
+
Source = "https://github.com/onlabsorg/stilo"
|
|
35
|
+
|
|
36
|
+
[dependency-groups]
|
|
37
|
+
dev = [
|
|
38
|
+
"httpx>=0.27",
|
|
39
|
+
"pytest>=8",
|
|
40
|
+
]
|
|
41
|
+
|
|
42
|
+
[build-system]
|
|
43
|
+
requires = ["hatchling"]
|
|
44
|
+
build-backend = "hatchling.build"
|
|
45
|
+
|
|
46
|
+
[tool.hatch.build.targets.sdist]
|
|
47
|
+
only-include = ["src/stilo", "README.md", "LICENSE"]
|
|
48
|
+
|
|
49
|
+
[tool.hatch.build.targets.wheel]
|
|
50
|
+
packages = ["src/stilo"]
|
|
51
|
+
|
|
52
|
+
# src/stilo/web is git-ignored: include it anyway when it is there. Not a
|
|
53
|
+
# forced include, so that editable installs (`uv run`) work without it.
|
|
54
|
+
[tool.hatch.build]
|
|
55
|
+
artifacts = ["src/stilo/web/"]
|
|
56
|
+
|
|
57
|
+
[tool.pytest.ini_options]
|
|
58
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
"""Stilo: edit and render a folder of linked Texl documents.
|
|
2
|
+
|
|
3
|
+
Subpackages: `stilo.cli` (the `stilo` command), `stilo.server` (the HTTP
|
|
4
|
+
server), and `web/` (the built web app, not Python: written by `npm run
|
|
5
|
+
build` in `web/`). The server never imports the CLI.
|
|
6
|
+
"""
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"""The `stilo` command line: one subcommand per entry in `COMMANDS`."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
|
|
5
|
+
from .commands import COMMANDS
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def main(argv=None) -> int:
|
|
9
|
+
parser = argparse.ArgumentParser(
|
|
10
|
+
prog="stilo", description="Edit and render a folder of linked Texl documents.")
|
|
11
|
+
subparsers = parser.add_subparsers(dest="command", required=True)
|
|
12
|
+
for command in COMMANDS:
|
|
13
|
+
sub = subparsers.add_parser(command.name, help=command.help)
|
|
14
|
+
command.add_arguments(sub)
|
|
15
|
+
sub.set_defaults(run=command.run)
|
|
16
|
+
args = parser.parse_args(argv)
|
|
17
|
+
return args.run(args)
|
|
18
|
+
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""The `stilo` subcommands.
|
|
2
|
+
|
|
3
|
+
Each command is a `Command`: a name, a help line, a function that adds its
|
|
4
|
+
arguments to a parser and a function that runs it. `COMMANDS` lists them in
|
|
5
|
+
the order `stilo --help` shows them; a plugin system can later add its own.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import asyncio
|
|
9
|
+
import sys
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Callable
|
|
13
|
+
|
|
14
|
+
import pytexl
|
|
15
|
+
import uvicorn
|
|
16
|
+
|
|
17
|
+
from stilo.server import create_app
|
|
18
|
+
|
|
19
|
+
# The built web app, `stilo/web`: written there by `npm run build` in a
|
|
20
|
+
# checkout, shipped there in the package
|
|
21
|
+
WEB_DIST = Path(__file__).resolve().parents[1] / "web"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class Command:
|
|
26
|
+
name: str
|
|
27
|
+
help: str
|
|
28
|
+
add_arguments: Callable
|
|
29
|
+
run: Callable # (args) -> exit status
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def render_arguments(parser):
|
|
33
|
+
parser.add_argument("file", type=Path,
|
|
34
|
+
help="document to render; relative imports resolve from its folder")
|
|
35
|
+
parser.add_argument("-o", "--output", type=Path,
|
|
36
|
+
help="output file (default: standard output)")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def render(args) -> int:
|
|
40
|
+
"""Renders a document to standard output or a file, like `texl`."""
|
|
41
|
+
path = args.file.resolve()
|
|
42
|
+
doc = asyncio.run(pytexl.Engine().load(path.as_uri()))
|
|
43
|
+
if doc is None:
|
|
44
|
+
print(f"stilo: {args.file}: could not be loaded", file=sys.stderr)
|
|
45
|
+
return 1
|
|
46
|
+
if args.output:
|
|
47
|
+
try:
|
|
48
|
+
args.output.write_text(doc.rendering, encoding="utf-8")
|
|
49
|
+
except OSError as e:
|
|
50
|
+
print(f"stilo: {args.output}: {e}", file=sys.stderr)
|
|
51
|
+
return 1
|
|
52
|
+
else:
|
|
53
|
+
sys.stdout.write(doc.rendering)
|
|
54
|
+
return 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def serve_arguments(parser):
|
|
58
|
+
parser.add_argument("folder", type=Path, nargs="?", default=Path("."),
|
|
59
|
+
help="folder of the documents (default: the current folder)")
|
|
60
|
+
parser.add_argument("--host", default="127.0.0.1",
|
|
61
|
+
help="address to listen on (default: 127.0.0.1)")
|
|
62
|
+
parser.add_argument("--port", type=int, default=8000)
|
|
63
|
+
parser.add_argument("--web", type=Path, default=WEB_DIST,
|
|
64
|
+
help="built web app (default: the one installed with stilo)")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def serve(args) -> int:
|
|
68
|
+
"""Serves a folder of documents and the Stilo web app over HTTP."""
|
|
69
|
+
if not args.folder.is_dir():
|
|
70
|
+
print(f"stilo: {args.folder}: not a folder", file=sys.stderr)
|
|
71
|
+
return 1
|
|
72
|
+
print(f"Stilo: serving {args.folder.resolve()} at http://{args.host}:{args.port}/")
|
|
73
|
+
uvicorn.run(create_app(args.folder, args.web), host=args.host, port=args.port)
|
|
74
|
+
return 0
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
COMMANDS = [
|
|
78
|
+
Command("render", "render a Texl document", render_arguments, render),
|
|
79
|
+
Command("serve", "serve a folder of Texl documents with the web app", serve_arguments, serve),
|
|
80
|
+
]
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"""HTTP layer: protocol v0 (docs/src/protocol.md) and the web app's files."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
from fastapi import FastAPI, Query, Request
|
|
8
|
+
from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response
|
|
9
|
+
from fastapi.staticfiles import StaticFiles
|
|
10
|
+
|
|
11
|
+
from .storage import Storage, StorageError
|
|
12
|
+
|
|
13
|
+
TEXT = "text/plain; charset=utf-8"
|
|
14
|
+
|
|
15
|
+
# Document contents change and the editor fetches imports on every rendering:
|
|
16
|
+
# browsers must not reuse a stored copy without asking the server again.
|
|
17
|
+
NO_CACHE = {"Cache-Control": "no-cache"}
|
|
18
|
+
|
|
19
|
+
NO_BUILD = """<!doctype html><meta charset="utf-8"><title>Stilo</title>
|
|
20
|
+
<p>The web app is not built. Run <code>npm run build</code> in <code>web/</code>
|
|
21
|
+
of the Stilo checkout, or use the Vite dev server (<code>npm run dev</code>).</p>"""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
|
|
25
|
+
"""The server app for the documents under `root`. `web_dist` is the built
|
|
26
|
+
web app (`stilo/web` in the CLI); without it, app pages show a notice."""
|
|
27
|
+
storage = Storage(root)
|
|
28
|
+
app = FastAPI(title="Stilo server", version="0.1.0")
|
|
29
|
+
|
|
30
|
+
@app.exception_handler(StorageError)
|
|
31
|
+
async def storage_error(request: Request, error: StorageError):
|
|
32
|
+
return JSONResponse({"error": str(error)}, status_code=error.status)
|
|
33
|
+
|
|
34
|
+
@app.api_route("/_api/files/{path:path}", methods=["GET", "HEAD"])
|
|
35
|
+
async def get_file(path: str):
|
|
36
|
+
content, tag = storage.read(path)
|
|
37
|
+
return Response(content, media_type=TEXT, headers={"ETag": tag, **NO_CACHE})
|
|
38
|
+
|
|
39
|
+
@app.post("/_api/files/{path:path}", status_code=201)
|
|
40
|
+
async def create_file(path: str, request: Request):
|
|
41
|
+
tag = storage.create(path, await request.body())
|
|
42
|
+
return Response(status_code=201,
|
|
43
|
+
headers={"ETag": tag, "Location": f"/_api/files/{path}"})
|
|
44
|
+
|
|
45
|
+
@app.put("/_api/files/{path:path}")
|
|
46
|
+
async def update_file(path: str, request: Request):
|
|
47
|
+
tag = storage.update(path, await request.body(), request.headers.get("if-match"))
|
|
48
|
+
return Response(status_code=200, headers={"ETag": tag})
|
|
49
|
+
|
|
50
|
+
@app.get("/_api/tree/{path:path}")
|
|
51
|
+
async def get_tree(path: str, depth: int | None = Query(None, ge=1)):
|
|
52
|
+
return storage.tree(path, depth)
|
|
53
|
+
|
|
54
|
+
@app.api_route("/_api/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
|
|
55
|
+
async def unknown_api(path: str):
|
|
56
|
+
return JSONResponse({"error": f"unknown endpoint: /_api/{path}"}, status_code=404)
|
|
57
|
+
|
|
58
|
+
dist = Path(web_dist) if web_dist else None
|
|
59
|
+
if dist and (dist / "index.html").is_file():
|
|
60
|
+
# The bundle is built with base "/_app/" (web/vite.config.js).
|
|
61
|
+
app.mount("/_app", StaticFiles(directory=dist), name="app")
|
|
62
|
+
|
|
63
|
+
# Every other path is a document's public URL. Browsers asking for HTML
|
|
64
|
+
# get the web app, which reads the open document from the URL path (and
|
|
65
|
+
# the navigation root from ?root=); any other client (texl.import) gets
|
|
66
|
+
# the file itself.
|
|
67
|
+
@app.api_route("/{path:path}", methods=["GET", "HEAD"], include_in_schema=False)
|
|
68
|
+
async def page(path: str, request: Request):
|
|
69
|
+
vary = {"Vary": "Accept"}
|
|
70
|
+
if "text/html" not in request.headers.get("accept", ""):
|
|
71
|
+
content, tag = storage.read(path)
|
|
72
|
+
return Response(content, media_type=TEXT,
|
|
73
|
+
headers={"ETag": tag, **NO_CACHE, **vary})
|
|
74
|
+
if dist and (dist / "index.html").is_file():
|
|
75
|
+
return FileResponse(dist / "index.html", media_type="text/html", headers=vary)
|
|
76
|
+
return HTMLResponse(NO_BUILD, headers=vary)
|
|
77
|
+
|
|
78
|
+
return app
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""File-system storage of Texl documents (protocol v0, see docs/src/protocol.md).
|
|
2
|
+
|
|
3
|
+
Paths are relative to the storage root, with "/" separators. Every public
|
|
4
|
+
method validates its path and raises a StorageError subclass that the HTTP
|
|
5
|
+
layer maps to a status code.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import os
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
DOCUMENT_SUFFIX = ".texl"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class StorageError(Exception):
|
|
19
|
+
status = 500
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class BadRequest(StorageError):
|
|
23
|
+
status = 400
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class NotFound(StorageError):
|
|
27
|
+
status = 404
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Conflict(StorageError):
|
|
31
|
+
status = 409
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class PreconditionFailed(StorageError):
|
|
35
|
+
status = 412
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def etag(content: bytes) -> str:
|
|
39
|
+
"""Strong ETag of a file's content, quoted as HTTP requires."""
|
|
40
|
+
return '"' + hashlib.sha256(content).hexdigest() + '"'
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class Storage:
|
|
44
|
+
def __init__(self, root: Path | str):
|
|
45
|
+
self.root = Path(root).resolve()
|
|
46
|
+
if not self.root.is_dir():
|
|
47
|
+
raise ValueError(f"storage root is not a folder: {self.root}")
|
|
48
|
+
|
|
49
|
+
# -- paths ---------------------------------------------------------------
|
|
50
|
+
|
|
51
|
+
def resolve(self, path: str) -> Path:
|
|
52
|
+
"""The absolute file-system path of `path`, refusing paths that are
|
|
53
|
+
malformed, hidden, reserved or outside the root."""
|
|
54
|
+
segments = path.strip("/").split("/") if path.strip("/") else []
|
|
55
|
+
for segment in segments:
|
|
56
|
+
if segment in ("", ".", "..") or segment.startswith("."):
|
|
57
|
+
raise BadRequest(f"invalid path: {path!r}")
|
|
58
|
+
if segments and segments[0].startswith("_"):
|
|
59
|
+
raise BadRequest(f"reserved path: {path!r}")
|
|
60
|
+
target = self.root.joinpath(*segments).resolve()
|
|
61
|
+
if not target.is_relative_to(self.root):
|
|
62
|
+
raise BadRequest(f"path outside the root: {path!r}")
|
|
63
|
+
return target
|
|
64
|
+
|
|
65
|
+
def relative(self, target: Path) -> str:
|
|
66
|
+
return target.relative_to(self.root).as_posix() if target != self.root else ""
|
|
67
|
+
|
|
68
|
+
# -- files ---------------------------------------------------------------
|
|
69
|
+
|
|
70
|
+
def read(self, path: str) -> tuple[bytes, str]:
|
|
71
|
+
target = self.resolve(path)
|
|
72
|
+
if target.is_dir():
|
|
73
|
+
raise BadRequest(f"not a file: {path!r}")
|
|
74
|
+
if not target.is_file():
|
|
75
|
+
raise NotFound(f"no such file: {path!r}")
|
|
76
|
+
content = target.read_bytes()
|
|
77
|
+
return content, etag(content)
|
|
78
|
+
|
|
79
|
+
def create(self, path: str, content: bytes) -> str:
|
|
80
|
+
target = self._writable(path)
|
|
81
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
82
|
+
try:
|
|
83
|
+
with open(target, "xb") as file:
|
|
84
|
+
file.write(content)
|
|
85
|
+
except FileExistsError:
|
|
86
|
+
raise Conflict(f"already exists: {path!r}") from None
|
|
87
|
+
return etag(content)
|
|
88
|
+
|
|
89
|
+
def update(self, path: str, content: bytes, if_match: str | None = None) -> str:
|
|
90
|
+
target = self._writable(path)
|
|
91
|
+
if not target.is_file():
|
|
92
|
+
raise NotFound(f"no such file: {path!r}")
|
|
93
|
+
if if_match is not None and if_match != etag(target.read_bytes()):
|
|
94
|
+
raise PreconditionFailed(f"changed since it was read: {path!r}")
|
|
95
|
+
# Write a sibling and rename it over the target, so readers never see
|
|
96
|
+
# a half-written document.
|
|
97
|
+
temp = target.with_name(f".{target.name}.tmp")
|
|
98
|
+
temp.write_bytes(content)
|
|
99
|
+
os.replace(temp, target)
|
|
100
|
+
return etag(content)
|
|
101
|
+
|
|
102
|
+
def _writable(self, path: str) -> Path:
|
|
103
|
+
target = self.resolve(path)
|
|
104
|
+
if target.suffix != DOCUMENT_SUFFIX:
|
|
105
|
+
raise BadRequest(f"only {DOCUMENT_SUFFIX} files can be written: {path!r}")
|
|
106
|
+
if target.is_dir():
|
|
107
|
+
raise BadRequest(f"is a folder: {path!r}")
|
|
108
|
+
return target
|
|
109
|
+
|
|
110
|
+
# -- tree ----------------------------------------------------------------
|
|
111
|
+
|
|
112
|
+
def tree(self, path: str, depth: int | None = None) -> dict:
|
|
113
|
+
target = self.resolve(path)
|
|
114
|
+
if target.is_file():
|
|
115
|
+
raise BadRequest(f"not a folder: {path!r}")
|
|
116
|
+
if not target.is_dir():
|
|
117
|
+
raise NotFound(f"no such folder: {path!r}")
|
|
118
|
+
return self._folder(target, depth)
|
|
119
|
+
|
|
120
|
+
def _folder(self, folder: Path, depth: int | None) -> dict:
|
|
121
|
+
node = {"name": folder.name if folder != self.root else "",
|
|
122
|
+
"path": self.relative(folder), "type": "folder"}
|
|
123
|
+
if depth is not None and depth <= 0:
|
|
124
|
+
return node
|
|
125
|
+
folders, files = [], []
|
|
126
|
+
for entry in sorted(folder.iterdir(), key=lambda e: e.name):
|
|
127
|
+
if entry.name.startswith(".") or (folder == self.root and entry.name.startswith("_")):
|
|
128
|
+
continue
|
|
129
|
+
if not entry.resolve().is_relative_to(self.root):
|
|
130
|
+
continue
|
|
131
|
+
if entry.is_dir():
|
|
132
|
+
folders.append(self._folder(entry, None if depth is None else depth - 1))
|
|
133
|
+
elif entry.is_file() and entry.suffix == DOCUMENT_SUFFIX:
|
|
134
|
+
stat = entry.stat()
|
|
135
|
+
modified = datetime.fromtimestamp(stat.st_mtime, timezone.utc)
|
|
136
|
+
files.append({"name": entry.name, "path": self.relative(entry), "type": "file",
|
|
137
|
+
"size": stat.st_size,
|
|
138
|
+
"modified": modified.strftime("%Y-%m-%dT%H:%M:%SZ")})
|
|
139
|
+
node["children"] = folders + files
|
|
140
|
+
return node
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
:root{--font:"Inter", system-ui, -apple-system, "Segoe UI", sans-serif;--radius:8px;--bar-height:3rem;--nav-width:16rem;--pane-width:20rem;--transition:.16s ease}:root[data-theme=light]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--bg:#f4f5f7;--surface:#fff;--surface-2:#f8f9fb;--border:#e3e6eb;--text:#1d2330;--text-muted:#687085;--hover:#0f172a0f;--active:#2563eb1a;--accent:#2563eb;--danger:#c2410c;--shadow:0 1px 3px #0000000f, 0 6px 24px #0000000f}:root[data-theme=dark]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--bg:#14161b;--surface:#1b1e24;--surface-2:#22262e;--border:#2d323c;--text:#e4e7ec;--text-muted:#8b93a3;--hover:#ffffff0f;--active:#60a5fa24;--accent:#60a5fa;--danger:#fb923c;--shadow:0 1px 3px #0000004d, 0 6px 24px #00000040;--texl-paper:#1b1e24;--texl-line:#262a32;--texl-margin-line:#34507f;--texl-line-number:#4a5160;--texl-line-number-active:#8b93a3;--texl-accent:#60a5fa;--texl-selected-bg:#60a5fa12;--texl-selected-ring:#60a5fa66;--texl-edit-bg:#22262e;--texl-comment:#e0a64b;--texl-hover-bg:#ffffff12;--texl-icon-active:#c4c9d4;--texl-menu-bg:#22262e;--texl-menu-border:#2d323c;--texl-menu-text:#e4e7ec;--texl-menu-icon:#8b93a3;--texl-menu-active-bg:#60a5fa24}html,body{height:100%;margin:0}body{background:var(--bg);color:var(--text);font-family:var(--font);-webkit-font-smoothing:antialiased;font-size:14px}
|