margin-notes 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.
@@ -0,0 +1,17 @@
1
+ # Python-generated files
2
+ __pycache__/
3
+ *.py[oc]
4
+ build/
5
+ dist/
6
+ wheels/
7
+ *.egg-info
8
+
9
+ # Virtual environments
10
+ .venv
11
+
12
+ # Tools
13
+ .pytest_cache/
14
+ .ruff_cache/
15
+
16
+ # Notes written while trying margin-notes on its own files
17
+ *.notes.json
@@ -0,0 +1,15 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-11-18)
4
+
5
+ First release.
6
+
7
+ - Browse a folder or open a single document; Markdown and HTML get a review overlay.
8
+ - Highlight passages and comment on them, or add general notes. Notes save immediately to
9
+ `<document>.notes.json` beside each document, in document order, with a plain-language
10
+ `about` field describing the format.
11
+ - Markdown rendering: GitHub-flavoured tables, task lists, footnotes, definition lists, alerts,
12
+ heading anchors, front-matter titles, Pygments highlighting, light and dark themes, MathJax
13
+ math and mermaid diagrams.
14
+ - `--host` to bind beyond localhost (with a warning), `--port` with automatic fallback.
15
+ - Dotfiles and paths outside the served folder are never served.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 John B Nelson
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.
@@ -0,0 +1,172 @@
1
+ Metadata-Version: 2.5
2
+ Name: margin-notes
3
+ Version: 0.1.0
4
+ Summary: Review HTML and Markdown in your browser: highlight passages, comment, and save the notes as JSON beside each document.
5
+ Project-URL: Homepage, https://github.com/jbn/margin-notes
6
+ Project-URL: Repository, https://github.com/jbn/margin-notes
7
+ Project-URL: Issues, https://github.com/jbn/margin-notes/issues
8
+ Project-URL: Changelog, https://github.com/jbn/margin-notes/blob/main/CHANGELOG.md
9
+ Author-email: John B Nelson <jbn@abreka.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: annotation,comments,highlight,html,markdown,mathjax,mermaid,review
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Environment :: Web Environment
15
+ Classifier: Framework :: FastAPI
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Intended Audience :: Science/Research
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Programming Language :: Python :: 3.14
26
+ Classifier: Topic :: Documentation
27
+ Classifier: Topic :: Text Processing :: Markup :: HTML
28
+ Classifier: Topic :: Text Processing :: Markup :: Markdown
29
+ Classifier: Typing :: Typed
30
+ Requires-Python: >=3.10
31
+ Requires-Dist: fastapi>=0.110
32
+ Requires-Dist: linkify-it-py>=2.0
33
+ Requires-Dist: markdown-it-py>=3.0
34
+ Requires-Dist: mdit-py-plugins>=0.4
35
+ Requires-Dist: pygments>=2.14
36
+ Requires-Dist: uvicorn>=0.29
37
+ Description-Content-Type: text/markdown
38
+
39
+ # margin-notes
40
+
41
+ [![CI](https://github.com/jbn/margin-notes/actions/workflows/ci.yml/badge.svg)](https://github.com/jbn/margin-notes/actions/workflows/ci.yml)
42
+ [![PyPI](https://img.shields.io/pypi/v/margin-notes)](https://pypi.org/project/margin-notes/)
43
+ [![Python](https://img.shields.io/pypi/pyversions/margin-notes)](https://pypi.org/project/margin-notes/)
44
+ [![License: MIT](https://img.shields.io/github/license/jbn/margin-notes)](https://github.com/jbn/margin-notes/blob/main/LICENSE)
45
+
46
+ Review HTML and Markdown documents in your browser. Select a passage, leave a comment, and the
47
+ notes save as JSON next to the document, ready for a person or an LLM agent to act on.
48
+
49
+ ![A Markdown design proposal open in margin-notes, with three highlighted passages, a comment being written, and the notes panel listing each note by section](https://raw.githubusercontent.com/jbn/margin-notes/main/docs/screenshot.png)
50
+
51
+ It replaces `python -m http.server` when the reason you're serving a folder is to read and
52
+ critique what's in it.
53
+
54
+ ```sh
55
+ uvx margin-notes # browse the current folder
56
+ uvx margin-notes docs/design.md # open one document
57
+ uvx margin-notes ~/reports --host 0.0.0.0 --port 9000
58
+ ```
59
+
60
+ ## What it does
61
+
62
+ - **Any folder.** A listing shows Markdown and HTML documents first, with a count of the notes on each.
63
+ Other files (images, PDFs, data) are served as-is, so relative links and images work.
64
+ - **HTML** is served unchanged with a small review overlay added. Its own scripts and styles still run.
65
+ - **Markdown** is rendered GitHub-style: tables, task lists, footnotes, definition lists, heading
66
+ anchors, front matter (`title:` becomes the page title), alerts (`> [!NOTE]`, `[!TIP]`,
67
+ `[!IMPORTANT]`, `[!WARNING]`, `[!CAUTION]`), Pygments syntax highlighting, light and dark themes.
68
+ - **Math** with MathJax: `$inline$`, `$$display$$` and ```` ```math ```` fences. MathJax only
69
+ loads on pages that contain math, so prices like `$5 and $10` are left alone.
70
+ - **Diagrams** in ```` ```mermaid ```` fences.
71
+ - Add `?raw=1` to any document URL to get the source.
72
+ - **Reviewing:** select text and click **💬 Comment**. ⌘↵ saves and Esc cancels. Click a highlight to
73
+ edit or delete it. **Notes** (bottom right) lists every note in document order and has
74
+ **+ General note** for comments about the whole document. Every change saves immediately.
75
+
76
+ MathJax and mermaid load from jsDelivr, so math and diagrams need internet access. Everything
77
+ else works offline.
78
+
79
+ ## The notes file
80
+
81
+ `report.md` gets `report.md.notes.json` beside it. Using the full filename keeps `report.md` and
82
+ `report.html` in one folder from sharing a file.
83
+
84
+ ```json
85
+ {
86
+ "about": "Review notes on report.md. Notes are in document order. ...",
87
+ "document": "report.md",
88
+ "document_path": "/abs/path/report.md",
89
+ "document_sha256": "…",
90
+ "updated_at": "2026-11-17T13:43:20-08:00",
91
+ "notes": [
92
+ {
93
+ "id": "nmwl7ygt5zh7r",
94
+ "quote": "links five constants",
95
+ "section": "Euler and friends",
96
+ "comment": "which five?",
97
+ "created_at": "2026-11-17T13:43:19-08:00",
98
+ "updated_at": "2026-11-17T13:43:20-08:00",
99
+ "anchor": { "exact": "links five constants", "prefix": "…", "suffix": "…", "start": 35 }
100
+ }
101
+ ]
102
+ }
103
+ ```
104
+
105
+ - `quote` is the highlighted text and `section` is the nearest heading above it. A note with a
106
+ null `quote` is a general comment.
107
+ - `anchor` re-finds the highlight using the exact text and its surroundings. A highlight whose
108
+ text has since been edited out shows as **not found** in the notes panel.
109
+ - `about` describes the format in plain words, so an agent handed the file needs no other
110
+ instructions.
111
+ - If `document_sha256` no longer matches the file, the document changed after the review.
112
+ - Deleting the last note removes the file.
113
+
114
+ Several people can review the same document at once. Each save changes one note on the server,
115
+ so reviewers don't overwrite each other.
116
+
117
+ ## Options
118
+
119
+ ```
120
+ margin-notes [PATH] [--host HOST] [-p PORT] [--no-open] [--version]
121
+ ```
122
+
123
+ | Option | Default | |
124
+ |---|---|---|
125
+ | `PATH` | `.` | A folder to browse, or a document to open |
126
+ | `--host` | `127.0.0.1` | `0.0.0.0` makes it reachable from your network |
127
+ | `-p`, `--port` | `8765` | The first port to try; it moves up if that one is busy |
128
+ | `--no-open` | | Don't open a browser |
129
+
130
+ **Security:** there is no authentication. Bound to anything other than localhost, anyone who can
131
+ reach the port can read every file under the folder and add notes. Dotfiles and dot-directories
132
+ (`.git`, `.env`) are never served, and nothing outside the folder is reachable, including
133
+ through symlinks.
134
+
135
+ ## Development
136
+
137
+ ```sh
138
+ uv sync --all-groups
139
+ uv run pytest # unit tests, plus browser tests when Playwright has a browser
140
+ uv run playwright install chromium # once, if you have no Chrome or Chromium
141
+ uv run pytest -m "not browser" # skip the browser tests
142
+ uv run ruff check && uv run ruff format --check
143
+ uv run margin-notes . # try it on this repository
144
+ ```
145
+
146
+ The browser tests (`tests/test_browser.py`) drive the overlay in Chromium through Playwright:
147
+ selecting text, anchoring repeated phrases, editing, deleting, general notes, and highlights
148
+ that no longer match. They need no network.
149
+
150
+ ### Releasing
151
+
152
+ 0. Optional dry run: run the **Release** workflow by hand from the Actions tab. It builds and
153
+ publishes to [TestPyPI](https://test.pypi.org/project/margin-notes/). Check the page, then
154
+ run the uploaded wheel. Only the wheel comes from TestPyPI; its dependencies come from PyPI,
155
+ because TestPyPI holds unrelated packages under real names (such as a broken `fastapi 1.0`):
156
+
157
+ ```sh
158
+ uvx --refresh --from "margin-notes @ $(curl -s https://test.pypi.org/pypi/margin-notes/json \
159
+ | python3 -c 'import json,sys; print(next(u["url"] for u in json.load(sys.stdin)["urls"] if u["filename"].endswith(".whl")))')" \
160
+ margin-notes --version
161
+ ```
162
+ 1. Bump `__version__` in `src/margin_notes/__init__.py` and add a section to `CHANGELOG.md`.
163
+ 2. Commit, then tag and push: `git tag v0.1.0 && git push --tags`.
164
+ 3. `.github/workflows/release.yml` checks that the tag matches the version, runs the tests,
165
+ builds, and publishes to PyPI.
166
+
167
+ Both indexes publish through trusted publishers, so no token lives in GitHub. Set each up once,
168
+ for repository `jbn/margin-notes` and workflow `release.yml`: at
169
+ <https://test.pypi.org/manage/account/publishing/> with environment `testpypi`, and at
170
+ <https://pypi.org/manage/account/publishing/> with environment `pypi`.
171
+
172
+ To publish from your own machine instead, run `uv build && uv publish`.
@@ -0,0 +1,134 @@
1
+ # margin-notes
2
+
3
+ [![CI](https://github.com/jbn/margin-notes/actions/workflows/ci.yml/badge.svg)](https://github.com/jbn/margin-notes/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/margin-notes)](https://pypi.org/project/margin-notes/)
5
+ [![Python](https://img.shields.io/pypi/pyversions/margin-notes)](https://pypi.org/project/margin-notes/)
6
+ [![License: MIT](https://img.shields.io/github/license/jbn/margin-notes)](https://github.com/jbn/margin-notes/blob/main/LICENSE)
7
+
8
+ Review HTML and Markdown documents in your browser. Select a passage, leave a comment, and the
9
+ notes save as JSON next to the document, ready for a person or an LLM agent to act on.
10
+
11
+ ![A Markdown design proposal open in margin-notes, with three highlighted passages, a comment being written, and the notes panel listing each note by section](https://raw.githubusercontent.com/jbn/margin-notes/main/docs/screenshot.png)
12
+
13
+ It replaces `python -m http.server` when the reason you're serving a folder is to read and
14
+ critique what's in it.
15
+
16
+ ```sh
17
+ uvx margin-notes # browse the current folder
18
+ uvx margin-notes docs/design.md # open one document
19
+ uvx margin-notes ~/reports --host 0.0.0.0 --port 9000
20
+ ```
21
+
22
+ ## What it does
23
+
24
+ - **Any folder.** A listing shows Markdown and HTML documents first, with a count of the notes on each.
25
+ Other files (images, PDFs, data) are served as-is, so relative links and images work.
26
+ - **HTML** is served unchanged with a small review overlay added. Its own scripts and styles still run.
27
+ - **Markdown** is rendered GitHub-style: tables, task lists, footnotes, definition lists, heading
28
+ anchors, front matter (`title:` becomes the page title), alerts (`> [!NOTE]`, `[!TIP]`,
29
+ `[!IMPORTANT]`, `[!WARNING]`, `[!CAUTION]`), Pygments syntax highlighting, light and dark themes.
30
+ - **Math** with MathJax: `$inline$`, `$$display$$` and ```` ```math ```` fences. MathJax only
31
+ loads on pages that contain math, so prices like `$5 and $10` are left alone.
32
+ - **Diagrams** in ```` ```mermaid ```` fences.
33
+ - Add `?raw=1` to any document URL to get the source.
34
+ - **Reviewing:** select text and click **💬 Comment**. ⌘↵ saves and Esc cancels. Click a highlight to
35
+ edit or delete it. **Notes** (bottom right) lists every note in document order and has
36
+ **+ General note** for comments about the whole document. Every change saves immediately.
37
+
38
+ MathJax and mermaid load from jsDelivr, so math and diagrams need internet access. Everything
39
+ else works offline.
40
+
41
+ ## The notes file
42
+
43
+ `report.md` gets `report.md.notes.json` beside it. Using the full filename keeps `report.md` and
44
+ `report.html` in one folder from sharing a file.
45
+
46
+ ```json
47
+ {
48
+ "about": "Review notes on report.md. Notes are in document order. ...",
49
+ "document": "report.md",
50
+ "document_path": "/abs/path/report.md",
51
+ "document_sha256": "…",
52
+ "updated_at": "2026-11-17T13:43:20-08:00",
53
+ "notes": [
54
+ {
55
+ "id": "nmwl7ygt5zh7r",
56
+ "quote": "links five constants",
57
+ "section": "Euler and friends",
58
+ "comment": "which five?",
59
+ "created_at": "2026-11-17T13:43:19-08:00",
60
+ "updated_at": "2026-11-17T13:43:20-08:00",
61
+ "anchor": { "exact": "links five constants", "prefix": "…", "suffix": "…", "start": 35 }
62
+ }
63
+ ]
64
+ }
65
+ ```
66
+
67
+ - `quote` is the highlighted text and `section` is the nearest heading above it. A note with a
68
+ null `quote` is a general comment.
69
+ - `anchor` re-finds the highlight using the exact text and its surroundings. A highlight whose
70
+ text has since been edited out shows as **not found** in the notes panel.
71
+ - `about` describes the format in plain words, so an agent handed the file needs no other
72
+ instructions.
73
+ - If `document_sha256` no longer matches the file, the document changed after the review.
74
+ - Deleting the last note removes the file.
75
+
76
+ Several people can review the same document at once. Each save changes one note on the server,
77
+ so reviewers don't overwrite each other.
78
+
79
+ ## Options
80
+
81
+ ```
82
+ margin-notes [PATH] [--host HOST] [-p PORT] [--no-open] [--version]
83
+ ```
84
+
85
+ | Option | Default | |
86
+ |---|---|---|
87
+ | `PATH` | `.` | A folder to browse, or a document to open |
88
+ | `--host` | `127.0.0.1` | `0.0.0.0` makes it reachable from your network |
89
+ | `-p`, `--port` | `8765` | The first port to try; it moves up if that one is busy |
90
+ | `--no-open` | | Don't open a browser |
91
+
92
+ **Security:** there is no authentication. Bound to anything other than localhost, anyone who can
93
+ reach the port can read every file under the folder and add notes. Dotfiles and dot-directories
94
+ (`.git`, `.env`) are never served, and nothing outside the folder is reachable, including
95
+ through symlinks.
96
+
97
+ ## Development
98
+
99
+ ```sh
100
+ uv sync --all-groups
101
+ uv run pytest # unit tests, plus browser tests when Playwright has a browser
102
+ uv run playwright install chromium # once, if you have no Chrome or Chromium
103
+ uv run pytest -m "not browser" # skip the browser tests
104
+ uv run ruff check && uv run ruff format --check
105
+ uv run margin-notes . # try it on this repository
106
+ ```
107
+
108
+ The browser tests (`tests/test_browser.py`) drive the overlay in Chromium through Playwright:
109
+ selecting text, anchoring repeated phrases, editing, deleting, general notes, and highlights
110
+ that no longer match. They need no network.
111
+
112
+ ### Releasing
113
+
114
+ 0. Optional dry run: run the **Release** workflow by hand from the Actions tab. It builds and
115
+ publishes to [TestPyPI](https://test.pypi.org/project/margin-notes/). Check the page, then
116
+ run the uploaded wheel. Only the wheel comes from TestPyPI; its dependencies come from PyPI,
117
+ because TestPyPI holds unrelated packages under real names (such as a broken `fastapi 1.0`):
118
+
119
+ ```sh
120
+ uvx --refresh --from "margin-notes @ $(curl -s https://test.pypi.org/pypi/margin-notes/json \
121
+ | python3 -c 'import json,sys; print(next(u["url"] for u in json.load(sys.stdin)["urls"] if u["filename"].endswith(".whl")))')" \
122
+ margin-notes --version
123
+ ```
124
+ 1. Bump `__version__` in `src/margin_notes/__init__.py` and add a section to `CHANGELOG.md`.
125
+ 2. Commit, then tag and push: `git tag v0.1.0 && git push --tags`.
126
+ 3. `.github/workflows/release.yml` checks that the tag matches the version, runs the tests,
127
+ builds, and publishes to PyPI.
128
+
129
+ Both indexes publish through trusted publishers, so no token lives in GitHub. Set each up once,
130
+ for repository `jbn/margin-notes` and workflow `release.yml`: at
131
+ <https://test.pypi.org/manage/account/publishing/> with environment `testpypi`, and at
132
+ <https://pypi.org/manage/account/publishing/> with environment `pypi`.
133
+
134
+ To publish from your own machine instead, run `uv build && uv publish`.
@@ -0,0 +1,89 @@
1
+ [project]
2
+ name = "margin-notes"
3
+ dynamic = ["version"]
4
+ description = "Review HTML and Markdown in your browser: highlight passages, comment, and save the notes as JSON beside each document."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [
9
+ { name = "John B Nelson", email = "jbn@abreka.com" }
10
+ ]
11
+ requires-python = ">=3.10"
12
+ dependencies = [
13
+ "fastapi>=0.110",
14
+ "linkify-it-py>=2.0",
15
+ "markdown-it-py>=3.0",
16
+ "mdit-py-plugins>=0.4",
17
+ "pygments>=2.14",
18
+ "uvicorn>=0.29",
19
+ ]
20
+ keywords = ["markdown", "html", "review", "annotation", "highlight", "comments", "mathjax", "mermaid"]
21
+ classifiers = [
22
+ "Development Status :: 4 - Beta",
23
+ "Environment :: Web Environment",
24
+ "Framework :: FastAPI",
25
+ "Intended Audience :: Developers",
26
+ "Intended Audience :: Science/Research",
27
+ "Operating System :: OS Independent",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3 :: Only",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Programming Language :: Python :: 3.13",
34
+ "Programming Language :: Python :: 3.14",
35
+ "Topic :: Documentation",
36
+ "Topic :: Text Processing :: Markup :: HTML",
37
+ "Topic :: Text Processing :: Markup :: Markdown",
38
+ "Typing :: Typed",
39
+ ]
40
+
41
+ [project.urls]
42
+ Homepage = "https://github.com/jbn/margin-notes"
43
+ Repository = "https://github.com/jbn/margin-notes"
44
+ Issues = "https://github.com/jbn/margin-notes/issues"
45
+ Changelog = "https://github.com/jbn/margin-notes/blob/main/CHANGELOG.md"
46
+
47
+ [project.scripts]
48
+ margin-notes = "margin_notes.cli:main"
49
+
50
+ [build-system]
51
+ requires = ["hatchling>=1.27"]
52
+ build-backend = "hatchling.build"
53
+
54
+ [tool.hatch.version]
55
+ path = "src/margin_notes/__init__.py"
56
+
57
+ [tool.hatch.build.targets.sdist]
58
+ include = ["src", "tests", "README.md", "CHANGELOG.md", "LICENSE"]
59
+
60
+ [dependency-groups]
61
+ dev = [
62
+ "httpx>=0.28.1",
63
+ "pytest>=8",
64
+ "ruff>=0.8",
65
+ ]
66
+ browser = [
67
+ "playwright>=1.45",
68
+ ]
69
+
70
+ [tool.pytest.ini_options]
71
+ testpaths = ["tests"]
72
+ addopts = "-ra"
73
+ markers = ["browser: drives a real browser through Playwright (skipped when unavailable)"]
74
+ filterwarnings = [
75
+ "error",
76
+ # Newer Starlette's TestClient nudges toward httpx2; harmless for tests.
77
+ "ignore:Using `httpx` with `starlette.testclient` is deprecated",
78
+ ]
79
+
80
+ [tool.ruff]
81
+ line-length = 120
82
+ target-version = "py310"
83
+
84
+ [tool.ruff.lint]
85
+ select = ["E", "F", "W", "I", "B", "UP", "SIM", "RUF"]
86
+ ignore = ["RUF001"] # ambiguous unicode in UI strings (…, ×) is intentional
87
+
88
+ [tool.ruff.lint.isort]
89
+ known-local-folder = ["conftest"]
@@ -0,0 +1,3 @@
1
+ """Highlight and comment on HTML and Markdown documents; notes save beside each one as JSON."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,103 @@
1
+ """Command line: `margin-notes [PATH] [--host HOST] [--port PORT]`."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import contextlib
7
+ import ipaddress
8
+ import socket
9
+ import sys
10
+ import threading
11
+ import webbrowser
12
+ from pathlib import Path
13
+ from urllib.parse import quote
14
+
15
+ from . import __version__
16
+ from .server import create_app, is_reviewable
17
+
18
+
19
+ def free_port(host: str, start: int) -> int:
20
+ family = socket.AF_INET6 if ":" in host else socket.AF_INET
21
+ for port in range(start, start + 50):
22
+ with socket.socket(family) as s:
23
+ try:
24
+ s.bind((host, port))
25
+ return port
26
+ except OSError:
27
+ continue
28
+ raise SystemExit(f"margin-notes: no free port in {start}-{start + 49} on {host}")
29
+
30
+
31
+ def lan_address() -> str | None:
32
+ # A UDP "connect" picks the outbound interface without sending anything.
33
+ try:
34
+ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
35
+ s.connect(("192.0.2.1", 9))
36
+ return s.getsockname()[0]
37
+ except OSError:
38
+ return None
39
+
40
+
41
+ def is_loopback(host: str) -> bool:
42
+ if host == "localhost":
43
+ return True
44
+ try:
45
+ return ipaddress.ip_address(host).is_loopback
46
+ except ValueError:
47
+ return False
48
+
49
+
50
+ def main(argv: list[str] | None = None) -> None:
51
+ ap = argparse.ArgumentParser(
52
+ prog="margin-notes",
53
+ description="Serve a folder or a document, highlight and comment on HTML and Markdown, "
54
+ "and save the notes as <document>.notes.json beside each one.",
55
+ )
56
+ ap.add_argument(
57
+ "path", nargs="?", default=".", type=Path, help="a folder to browse or a document to open (default: .)"
58
+ )
59
+ ap.add_argument(
60
+ "--host", default="127.0.0.1", help="interface to bind; 0.0.0.0 exposes it to your network (default: 127.0.0.1)"
61
+ )
62
+ ap.add_argument("-p", "--port", type=int, default=8765, help="first port to try (default: 8765)")
63
+ ap.add_argument("--no-open", action="store_true", help="don't open a browser")
64
+ ap.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
65
+ args = ap.parse_args(argv)
66
+ if hasattr(sys.stdout, "reconfigure"):
67
+ sys.stdout.reconfigure(line_buffering=True) # show the banner even when piped
68
+
69
+ import uvicorn # deferred so --help and --version stay fast
70
+
71
+ target = args.path.expanduser().resolve()
72
+ if not target.exists():
73
+ raise SystemExit(f"margin-notes: no such file or folder: {target}")
74
+ if target.is_dir():
75
+ root, start_path = target, "/"
76
+ else:
77
+ root, start_path = target.parent, "/" + quote(target.name)
78
+ if not is_reviewable(target):
79
+ print(f"margin-notes: {target.name} isn't Markdown or HTML; it will be served as-is.", file=sys.stderr)
80
+
81
+ port = free_port(args.host, args.port)
82
+ browse_host = "127.0.0.1" if args.host in ("0.0.0.0", "::", "") else args.host
83
+ url = f"http://{f'[{browse_host}]' if ':' in browse_host else browse_host}:{port}{start_path}"
84
+
85
+ print(f"margin-notes {__version__}")
86
+ print(f" serving {root}")
87
+ print(f" open {url}")
88
+ if args.host in ("0.0.0.0", "::"):
89
+ lan = lan_address()
90
+ if lan:
91
+ print(f" network http://{lan}:{port}{start_path}")
92
+ if not is_loopback(args.host):
93
+ print(
94
+ " warning anyone who can reach this address can read every file under the folder "
95
+ "and add notes. There is no authentication.",
96
+ file=sys.stderr,
97
+ )
98
+ print(" Ctrl-C to stop")
99
+
100
+ if not args.no_open:
101
+ threading.Timer(1.0, webbrowser.open, args=(url,)).start()
102
+ with contextlib.suppress(KeyboardInterrupt):
103
+ uvicorn.run(create_app(root), host=args.host, port=port, log_level="warning")
@@ -0,0 +1,112 @@
1
+ """The `<document>.notes.json` file that sits beside each reviewed document."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import re
9
+ import tempfile
10
+ import threading
11
+ from datetime import datetime
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ ABOUT = (
16
+ "Review notes on {doc}. Notes are in document order. Each note has `quote` (the "
17
+ "highlighted text, whitespace collapsed), `section` (the nearest heading before it), "
18
+ "and `comment` (the reviewer's remark; may be empty for a bare highlight). A note "
19
+ "with a null `quote` is a general comment on the whole document. `anchor` holds the "
20
+ "exact text and surrounding context used to re-find the highlight. If "
21
+ "`document_sha256` no longer matches the file, the document changed after review."
22
+ )
23
+
24
+
25
+ def _file_mode() -> int:
26
+ mask = os.umask(0) # reading the umask means setting it; do it once, at import
27
+ os.umask(mask)
28
+ return 0o666 & ~mask
29
+
30
+
31
+ FILE_MODE = _file_mode()
32
+ NOTE_ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
33
+
34
+
35
+ def notes_path(doc: Path) -> Path:
36
+ return doc.with_name(f"{doc.name}.notes.json")
37
+
38
+
39
+ def now() -> str:
40
+ return datetime.now().astimezone().isoformat(timespec="seconds")
41
+
42
+
43
+ def _order(note: dict[str, Any]) -> tuple:
44
+ anchor = note.get("anchor")
45
+ if isinstance(anchor, dict):
46
+ return (1, anchor.get("start") or 0, "")
47
+ return (0, 0, str(note.get("created_at", "")))
48
+
49
+
50
+ def validate(note: Any) -> dict[str, Any]:
51
+ if not isinstance(note, dict) or not isinstance(note.get("id"), str) or not NOTE_ID.match(note["id"]):
52
+ raise ValueError("a note is an object with an `id` of letters, digits, _ or -")
53
+ return {k: v for k, v in note.items() if not k.startswith("_")}
54
+
55
+
56
+ class NoteStore:
57
+ """Read-modify-write under one lock, so concurrent reviewers never clobber each other."""
58
+
59
+ def __init__(self) -> None:
60
+ self._lock = threading.Lock()
61
+
62
+ def read(self, doc: Path) -> list[dict[str, Any]]:
63
+ path = notes_path(doc)
64
+ if not path.exists():
65
+ return []
66
+ data = json.loads(path.read_text(encoding="utf-8"))
67
+ return list(data.get("notes", []))
68
+
69
+ def count(self, doc: Path) -> int:
70
+ try:
71
+ return len(self.read(doc))
72
+ except (OSError, ValueError):
73
+ return 0
74
+
75
+ def upsert(self, doc: Path, note: dict[str, Any]) -> list[dict[str, Any]]:
76
+ note = validate(note)
77
+ with self._lock:
78
+ notes = [n for n in self.read(doc) if n.get("id") != note["id"]]
79
+ notes.append(note)
80
+ return self._write(doc, notes)
81
+
82
+ def delete(self, doc: Path, note_id: str) -> list[dict[str, Any]]:
83
+ with self._lock:
84
+ notes = self.read(doc)
85
+ kept = [n for n in notes if n.get("id") != note_id]
86
+ return self._write(doc, kept) if len(kept) != len(notes) else notes
87
+
88
+ def _write(self, doc: Path, notes: list[dict[str, Any]]) -> list[dict[str, Any]]:
89
+ notes.sort(key=_order)
90
+ path = notes_path(doc)
91
+ if not notes and path.exists():
92
+ path.unlink()
93
+ return notes
94
+ data = {
95
+ "about": ABOUT.format(doc=doc.name),
96
+ "document": doc.name,
97
+ "document_path": str(doc),
98
+ "document_sha256": hashlib.sha256(doc.read_bytes()).hexdigest(),
99
+ "updated_at": now(),
100
+ "notes": notes,
101
+ }
102
+ fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".notes-", suffix=".tmp")
103
+ try:
104
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
105
+ json.dump(data, f, indent=2, ensure_ascii=False)
106
+ f.write("\n")
107
+ os.chmod(tmp, FILE_MODE) # mkstemp creates 0600; use ordinary permissions
108
+ os.replace(tmp, path)
109
+ except BaseException:
110
+ Path(tmp).unlink(missing_ok=True)
111
+ raise
112
+ return notes