staticware 0.1.0__py3-none-any.whl

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.
staticware/__init__.py ADDED
@@ -0,0 +1,5 @@
1
+ """Top-level package for Staticware."""
2
+
3
+ from staticware.middleware import HashedStatic, StaticRewriteMiddleware
4
+
5
+ __all__ = ["HashedStatic", "StaticRewriteMiddleware"]
@@ -0,0 +1,310 @@
1
+ """ASGI middleware for static file serving with content-based cache busting.
2
+
3
+ Zero dependencies beyond the Python standard library. Works with any ASGI
4
+ framework: Starlette, FastAPI, Air, Litestar, Django, or raw ASGI.
5
+
6
+ from staticware import HashedStatic, StaticRewriteMiddleware
7
+
8
+ static = HashedStatic("static")
9
+
10
+ # Wrap any ASGI app to rewrite /static/styles.css -> /static/styles.a1b2c3d4.css
11
+ app = StaticRewriteMiddleware(your_app, static=static)
12
+
13
+ # In templates:
14
+ static.url("styles.css") # -> /static/styles.a1b2c3d4.css
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import mimetypes
21
+ import re
22
+ from pathlib import Path
23
+ from collections.abc import Awaitable, Callable
24
+ from typing import Any
25
+
26
+ # ASGI protocol types — inlined so we depend on nothing.
27
+ type Scope = dict[str, Any]
28
+ type Receive = Callable[[], Awaitable[dict[str, Any]]]
29
+ type Send = Callable[[dict[str, Any]], Awaitable[None]]
30
+ type ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]
31
+
32
+
33
+ class HashedStatic:
34
+ """Serve static files with content-hashed filenames.
35
+
36
+ Computes SHA-256 hashes of every file in ``directory`` at startup.
37
+ Requests for hashed filenames (``styles.a1b2c3d4.css``) get
38
+ ``Cache-Control: public, max-age=31536000, immutable``.
39
+ Requests for original filenames still work, without aggressive caching.
40
+
41
+ This is a mountable ASGI app *and* a URL resolver::
42
+
43
+ static = HashedStatic("static")
44
+
45
+ # Mount it however your framework mounts sub-apps:
46
+ app.mount("/static", static)
47
+
48
+ # Resolve URLs:
49
+ static.url("styles.css") # /static/styles.a1b2c3d4.css
50
+ static.url("images/logo.png") # /static/images/logo.7e4f9a01.png
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ directory: str | Path,
56
+ *,
57
+ prefix: str = "/static",
58
+ hash_length: int = 8,
59
+ ) -> None:
60
+ self.directory = Path(directory).resolve()
61
+ self.prefix = prefix.rstrip("/")
62
+ self.hash_length = hash_length
63
+
64
+ # original relative path -> hashed relative path
65
+ self.file_map: dict[str, str] = {}
66
+ # hashed relative path -> original relative path
67
+ self._reverse: dict[str, str] = {}
68
+ # original relative path -> ETag value (quoted hash)
69
+ self._etags: dict[str, bytes] = {}
70
+
71
+ self._hash_files()
72
+
73
+ def _hash_files(self) -> None:
74
+ """Walk directory and build the hash map for every file."""
75
+ if not self.directory.exists():
76
+ return
77
+
78
+ for file_path in self.directory.rglob("*"):
79
+ if not file_path.is_file():
80
+ continue
81
+ if not file_path.resolve().is_relative_to(self.directory):
82
+ continue
83
+
84
+ relative = file_path.relative_to(self.directory).as_posix()
85
+ content = file_path.read_bytes()
86
+ hash_val = hashlib.sha256(content).hexdigest()[: self.hash_length]
87
+
88
+ # styles.css -> styles.a1b2c3d4.css
89
+ # Makefile -> Makefile.a1b2c3d4
90
+ # .gitignore -> .gitignore.a1b2c3d4
91
+ name = file_path.name
92
+ dot = name.rfind(".")
93
+ if dot > 0:
94
+ hashed_name = f"{name[:dot]}.{hash_val}{name[dot:]}"
95
+ else:
96
+ hashed_name = f"{name}.{hash_val}"
97
+ parent = str(Path(relative).parent)
98
+ if parent != ".":
99
+ hashed = f"{parent}/{hashed_name}"
100
+ else:
101
+ hashed = hashed_name
102
+
103
+ self.file_map[relative] = hashed
104
+ self._reverse[hashed] = relative
105
+ self._etags[relative] = f'"{hash_val}"'.encode('latin-1')
106
+
107
+ def url(self, path: str) -> str:
108
+ """Return the cache-busted URL for a static file path.
109
+
110
+ Unknown paths are returned unchanged (with the prefix).
111
+ """
112
+ path = path.lstrip("/")
113
+ hashed = self.file_map.get(path, path)
114
+ return f"{self.prefix}/{hashed}"
115
+
116
+ # ── ASGI app ────────────────────────────────────────────────────────
117
+
118
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
119
+ """Serve a static file. Mount this under the prefix in your framework."""
120
+ if scope["type"] != "http":
121
+ return
122
+
123
+ request_path: str = scope["path"]
124
+ root_path: str = scope.get("root_path", "")
125
+
126
+ if root_path:
127
+ # Framework mount: use root_path to derive the local path.
128
+ if request_path.startswith(root_path + "/"):
129
+ # Starlette-style: path still includes the mount prefix.
130
+ relative_path = request_path[len(root_path) + 1 :]
131
+ else:
132
+ # Litestar-style: framework already stripped the prefix.
133
+ relative_path = request_path.lstrip("/")
134
+ else:
135
+ # Standalone raw ASGI: use self.prefix to find the local path.
136
+ if not request_path.startswith(self.prefix + "/"):
137
+ await _send_text(send, 404, b"Not Found")
138
+ return
139
+ relative_path = request_path[len(self.prefix) + 1 :]
140
+
141
+ # Hashed filename — serve with immutable caching
142
+ original_path = self._reverse.get(relative_path)
143
+ if original_path:
144
+ file_path = (self.directory / original_path).resolve()
145
+ if file_path.is_relative_to(self.directory) and file_path.exists():
146
+ await _send_file(
147
+ send,
148
+ file_path,
149
+ extra_headers=[
150
+ (b"cache-control", b"public, max-age=31536000, immutable"),
151
+ ],
152
+ )
153
+ return
154
+
155
+ # Original filename — serve without aggressive caching
156
+ file_path = (self.directory / relative_path).resolve()
157
+ if not file_path.is_relative_to(self.directory):
158
+ await _send_text(send, 404, b"Not Found")
159
+ return
160
+ if file_path.exists() and file_path.is_file():
161
+ etag = self._etags.get(relative_path)
162
+ if etag:
163
+ # Check for conditional request (If-None-Match)
164
+ for hdr_name, hdr_value in scope.get("headers", []):
165
+ if hdr_name == b"if-none-match" and hdr_value == etag:
166
+ await _send_text(send, 304, b"")
167
+ return
168
+ await _send_file(
169
+ send, file_path, extra_headers=[(b"etag", etag)]
170
+ )
171
+ else:
172
+ await _send_file(send, file_path)
173
+ return
174
+
175
+ await _send_text(send, 404, b"Not Found")
176
+
177
+
178
+ class StaticRewriteMiddleware:
179
+ """ASGI middleware that rewrites static paths in HTML responses.
180
+
181
+ Wraps any ASGI app. When the response content-type is ``text/html``,
182
+ rewrites occurrences of ``/static/styles.css`` to their hashed
183
+ equivalents. Non-HTML responses pass through untouched.
184
+
185
+ Works with any templating system, component library, or hand-written
186
+ HTML — no template function needed (though ``static.url()`` is there
187
+ if you want it).
188
+
189
+ app = StaticRewriteMiddleware(app, static=static)
190
+ """
191
+
192
+ def __init__(self, app: ASGIApp, *, static: HashedStatic) -> None:
193
+ self.app = app
194
+ self.static = static
195
+ escaped = re.escape(static.prefix)
196
+ self._pattern = re.compile(escaped + r"/([^\"'>\s)#?]+)")
197
+
198
+ def _replace(self, match: re.Match[str]) -> str:
199
+ path = match.group(1)
200
+ if path in self.static.file_map:
201
+ return f"{self.static.prefix}/{self.static.file_map[path]}"
202
+ return match.group(0)
203
+
204
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
205
+ if scope["type"] != "http":
206
+ await self.app(scope, receive, send)
207
+ return
208
+
209
+ response_start: dict[str, Any] | None = None
210
+ body_parts: list[bytes] = []
211
+ is_html = False
212
+
213
+ async def send_wrapper(message: dict[str, Any]) -> None:
214
+ nonlocal response_start, is_html
215
+
216
+ if message["type"] == "http.response.start":
217
+ response_start = message
218
+ headers = dict(message.get("headers", []))
219
+ content_type = headers.get(b"content-type", b"").decode("latin-1")
220
+ is_html = "text/html" in content_type
221
+ if not is_html:
222
+ # Not HTML — send the start immediately and short-circuit.
223
+ await send(message)
224
+ return
225
+
226
+ if message["type"] == "http.response.body":
227
+ if response_start is None:
228
+ raise RuntimeError(
229
+ "http.response.body received before http.response.start"
230
+ )
231
+ if not is_html:
232
+ await send(message)
233
+ return
234
+
235
+ body = message.get("body", b"")
236
+ more_body = message.get("more_body", False)
237
+ body_parts.append(body)
238
+
239
+ if not more_body:
240
+ full_body = b"".join(body_parts)
241
+ try:
242
+ text = full_body.decode("utf-8")
243
+ text = self._pattern.sub(self._replace, text)
244
+ full_body = text.encode("utf-8")
245
+ except UnicodeDecodeError:
246
+ pass
247
+
248
+ if response_start is None:
249
+ raise RuntimeError(
250
+ "http.response.body received before http.response.start"
251
+ )
252
+ new_headers = [
253
+ (k, str(len(full_body)).encode("latin-1"))
254
+ if k == b"content-length"
255
+ else (k, v)
256
+ for k, v in response_start.get("headers", [])
257
+ ]
258
+ response_start["headers"] = new_headers
259
+ await send(response_start)
260
+ await send({"type": "http.response.body", "body": full_body})
261
+ return
262
+
263
+ await self.app(scope, receive, send_wrapper)
264
+
265
+
266
+ # ── Raw ASGI helpers ────────────────────────────────────────────────────
267
+
268
+
269
+ async def _send_file(
270
+ send: Send,
271
+ path: Path,
272
+ *,
273
+ extra_headers: list[tuple[bytes, bytes]] | None = None,
274
+ ) -> None:
275
+ """Send a file as a raw ASGI response."""
276
+ content = path.read_bytes()
277
+ content_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream"
278
+
279
+ headers: list[tuple[bytes, bytes]] = [
280
+ (b"content-type", content_type.encode("latin-1")),
281
+ (b"content-length", str(len(content)).encode("latin-1")),
282
+ ]
283
+ if extra_headers:
284
+ headers.extend(extra_headers)
285
+
286
+ await send({
287
+ "type": "http.response.start",
288
+ "status": 200,
289
+ "headers": headers,
290
+ })
291
+ await send({
292
+ "type": "http.response.body",
293
+ "body": content,
294
+ })
295
+
296
+
297
+ async def _send_text(send: Send, status: int, body: bytes) -> None:
298
+ """Send a plain-text ASGI response."""
299
+ await send({
300
+ "type": "http.response.start",
301
+ "status": status,
302
+ "headers": [
303
+ (b"content-type", b"text/plain"),
304
+ (b"content-length", str(len(body)).encode("latin-1")),
305
+ ],
306
+ })
307
+ await send({
308
+ "type": "http.response.body",
309
+ "body": body,
310
+ })
staticware/py.typed ADDED
@@ -0,0 +1 @@
1
+ # Marker file for PEP 561
@@ -0,0 +1,104 @@
1
+ Metadata-Version: 2.4
2
+ Name: staticware
3
+ Version: 0.1.0
4
+ Summary: ASGI middleware for static file serving with content-based cache busting
5
+ Project-URL: Bugs, https://github.com/feldroy/staticware/issues
6
+ Project-URL: Changelog, https://github.com/feldroy/staticware/releases
7
+ Project-URL: Documentation, https://feldroy.github.io/staticware/
8
+ Project-URL: Homepage, https://github.com/feldroy/staticware
9
+ Project-URL: Source, https://github.com/feldroy/staticware
10
+ Author-email: "Audrey M. Roy Greenfeld" <audrey@feldroy.com>
11
+ Maintainer-email: "Audrey M. Roy Greenfeld" <audrey@feldroy.com>
12
+ License: MIT
13
+ License-File: LICENSE
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: License :: OSI Approved :: MIT License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Programming Language :: Python :: 3.14
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.12
23
+ Description-Content-Type: text/markdown
24
+
25
+ # Staticware
26
+
27
+ ![PyPI version](https://img.shields.io/pypi/v/staticware.svg)
28
+
29
+ ASGI middleware for static file serving with content-based cache busting. Zero runtime dependencies.
30
+
31
+ * Created by **[Audrey M. Roy Greenfeld](https://audrey.feldroy.com)**
32
+ * GitHub: https://github.com/audreyfeldroy
33
+ * PyPI: https://pypi.org/user/audreyr/
34
+ * PyPI package: https://pypi.org/project/staticware/
35
+ * Free software: MIT License
36
+
37
+ ## Features
38
+
39
+ * Serves static files over ASGI with content-hashed filenames for cache busting
40
+ * Hashed filenames get `Cache-Control: public, max-age=31536000, immutable`
41
+ * Original filenames still work, without aggressive caching
42
+ * `StaticRewriteMiddleware` automatically rewrites static paths in HTML responses
43
+ * `static.url()` resolves cache-busted URLs for use in templates
44
+ * Works with any ASGI framework: Starlette, FastAPI, Air, Litestar, Django, or raw ASGI
45
+ * Zero runtime dependencies
46
+
47
+ ## Quick Start
48
+
49
+ ```python
50
+ from staticware import HashedStatic, StaticRewriteMiddleware
51
+
52
+ # Point at your static files directory
53
+ static = HashedStatic("static")
54
+
55
+ # Mount it however your framework mounts sub-apps:
56
+ app.mount("/static", static)
57
+
58
+ # Wrap any ASGI app to rewrite static paths in HTML responses
59
+ app = StaticRewriteMiddleware(app, static=static)
60
+
61
+ # In templates, resolve cache-busted URLs:
62
+ static.url("styles.css") # /static/styles.a1b2c3d4.css
63
+ static.url("images/logo.png") # /static/images/logo.7e4f9a01.png
64
+ ```
65
+
66
+ ## Documentation
67
+
68
+ Documentation is built with [Zensical](https://zensical.org/) and deployed to GitHub Pages.
69
+
70
+ * **Live site:** https://feldroy.github.io/staticware/
71
+ * **Preview locally:** `just docs-serve` (serves at http://localhost:8000)
72
+ * **Build:** `just docs-build`
73
+
74
+ API documentation is auto-generated from docstrings using [mkdocstrings](https://mkdocstrings.github.io/).
75
+
76
+ Docs deploy automatically on push to `main` via GitHub Actions. To enable this, go to your repo's Settings > Pages and set the source to **GitHub Actions**.
77
+
78
+ ## Development
79
+
80
+ To set up for local development:
81
+
82
+ ```bash
83
+ git clone git@github.com:feldroy/staticware.git
84
+ cd staticware
85
+ uv sync
86
+ ```
87
+
88
+ Run tests:
89
+
90
+ ```bash
91
+ uv run pytest
92
+ ```
93
+
94
+ Run quality checks (format, lint, type check, test):
95
+
96
+ ```bash
97
+ just qa
98
+ ```
99
+
100
+ ## Author
101
+
102
+ Staticware was created in 2026 by Audrey M. Roy Greenfeld.
103
+
104
+ Built with [Cookiecutter](https://github.com/cookiecutter/cookiecutter) and the [audreyfeldroy/cookiecutter-pypackage](https://github.com/audreyfeldroy/cookiecutter-pypackage) project template.
@@ -0,0 +1,7 @@
1
+ staticware/__init__.py,sha256=zbw4qTdL35GQHxJDZtr0m1yJW5BJ2ubBZo8Le8KRDdI,168
2
+ staticware/middleware.py,sha256=DSVbjNs5EOeMK4qS9hIMyeRp1Vpe7X7hHUT2FOUKmLc,11517
3
+ staticware/py.typed,sha256=8PjyZ1aVoQpRVvt71muvuq5qE-jTFZkK-GLHkhdebmc,26
4
+ staticware-0.1.0.dist-info/METADATA,sha256=t2CTdIPAFoa1IcSHuEGcEA6uGOcRDpNijpUO84WXA9Q,3532
5
+ staticware-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
6
+ staticware-0.1.0.dist-info/licenses/LICENSE,sha256=bmXNe-6xu11QuI5rXH3hBOesEquzT2lKLMZg6nAUQkk,1081
7
+ staticware-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026, Audrey M. Roy Greenfeld
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.