diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..09c1e19
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,1854 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "aligned"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "377e4c0ba83e4431b10df45c1d4666f178ea9c552cac93e60c3a88bf32785923"
+dependencies = [
+ "as-slice",
+]
+
+[[package]]
+name = "aligned-vec"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b"
+dependencies = [
+ "equator",
+]
+
+[[package]]
+name = "alloc-no-stdlib"
+version = "2.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"
+
+[[package]]
+name = "alloc-stdlib"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece"
+dependencies = [
+ "alloc-no-stdlib",
+]
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.100"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a23eb6b1614318a8071c9b2521f36b424b2c83db5eb3a0fead4a6c0809af6e61"
+
+[[package]]
+name = "arbitrary"
+version = "1.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d036a3c4ab069c7b410a2ce876bd74808d2d0888a82667669f8e783a898bf1"
+
+[[package]]
+name = "arg_enum_proc_macro"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
+[[package]]
+name = "as-slice"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516"
+dependencies = [
+ "stable_deref_trait",
+]
+
+[[package]]
+name = "async-compression"
+version = "0.4.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0e86f6d3dc9dc4352edeea6b8e499e13e3f5dc3b964d7ca5fd411415a3498473"
+dependencies = [
+ "compression-codecs",
+ "compression-core",
+ "futures-core",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "autocfg"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
+
+[[package]]
+name = "av-scenechange"
+version = "0.14.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394"
+dependencies = [
+ "aligned",
+ "anyhow",
+ "arg_enum_proc_macro",
+ "arrayvec",
+ "log",
+ "num-rational",
+ "num-traits",
+ "pastey",
+ "rayon",
+ "thiserror",
+ "v_frame",
+ "y4m",
+]
+
+[[package]]
+name = "av1-grain"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8"
+dependencies = [
+ "anyhow",
+ "arrayvec",
+ "log",
+ "nom",
+ "num-rational",
+ "v_frame",
+]
+
+[[package]]
+name = "avif-serialize"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47c8fbc0f831f4519fe8b810b6a7a91410ec83031b8233f730a0480029f6a23f"
+dependencies = [
+ "arrayvec",
+]
+
+[[package]]
+name = "axum"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b098575ebe77cb6d14fc7f32749631a6e44edbef6b796f89b020e99ba20d425"
+dependencies = [
+ "axum-core",
+ "bytes",
+ "form_urlencoded",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "itoa",
+ "matchit",
+ "memchr",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde_core",
+ "serde_json",
+ "serde_path_to_error",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "axum-core"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59446ce19cd142f8833f856eb31f3eb097812d1479ab224f54d72428ca21ea22"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "bit_field"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6"
+
+[[package]]
+name = "bitflags"
+version = "2.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
+
+[[package]]
+name = "bitstream-io"
+version = "4.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60d4bd9d1db2c6bdf285e223a7fa369d5ce98ec767dec949c6ca62863ce61757"
+dependencies = [
+ "core2",
+]
+
+[[package]]
+name = "brotli"
+version = "8.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560"
+dependencies = [
+ "alloc-no-stdlib",
+ "alloc-stdlib",
+ "brotli-decompressor",
+]
+
+[[package]]
+name = "brotli-decompressor"
+version = "5.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03"
+dependencies = [
+ "alloc-no-stdlib",
+ "alloc-stdlib",
+]
+
+[[package]]
+name = "built"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4ad8f11f288f48ca24471bbd51ac257aaeaaa07adae295591266b792902ae64"
+
+[[package]]
+name = "bumpalo"
+version = "3.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46c5e41b57b8bba42a04676d81cb89e9ee8e859a1a66f80a5a72e1cb76b34d43"
+
+[[package]]
+name = "bytemuck"
+version = "1.24.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4"
+
+[[package]]
+name = "byteorder-lite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
+
+[[package]]
+name = "bytes"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b35204fbdc0b3f4446b89fc1ac2cf84a8a68971995d0bf2e925ec7cd960f9cb3"
+
+[[package]]
+name = "cc"
+version = "1.2.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd405d82c84ff7f35739f175f67d8b9fb7687a0e84ccdc78bd3568839827cf07"
+dependencies = [
+ "find-msvc-tools",
+ "jobserver",
+ "libc",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "chrono"
+version = "0.4.42"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "145052bdd345b87320e369255277e3fb5152762ad123a901ef5c262dd38fe8d2"
+dependencies = [
+ "iana-time-zone",
+ "js-sys",
+ "num-traits",
+ "wasm-bindgen",
+ "windows-link",
+]
+
+[[package]]
+name = "color_quant"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
+
+[[package]]
+name = "compression-codecs"
+version = "0.4.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "302266479cb963552d11bd042013a58ef1adc56768016c8b82b4199488f2d4ad"
+dependencies = [
+ "brotli",
+ "compression-core",
+ "flate2",
+ "memchr",
+ "zstd",
+ "zstd-safe",
+]
+
+[[package]]
+name = "compression-core"
+version = "0.4.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75984efb6ed102a0d42db99afb6c1948f0380d1d91808d5529916e6c08b49d8d"
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "core2"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b49ba7ef1ad6107f8824dbe97de947cbaac53c44e7f9756a1fba0d37c1eec505"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "either"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
+
+[[package]]
+name = "equator"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc"
+dependencies = [
+ "equator-macro",
+]
+
+[[package]]
+name = "equator-macro"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "exr"
+version = "1.74.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4300e043a56aa2cb633c01af81ca8f699a321879a7854d3896a0ba89056363be"
+dependencies = [
+ "bit_field",
+ "half",
+ "lebe",
+ "miniz_oxide",
+ "rayon-core",
+ "smallvec",
+ "zune-inflate",
+]
+
+[[package]]
+name = "fax"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f05de7d48f37cd6730705cbca900770cab77a89f413d23e100ad7fad7795a0ab"
+dependencies = [
+ "fax_derive",
+]
+
+[[package]]
+name = "fax_derive"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a0aca10fb742cb43f9e7bb8467c91aa9bcb8e3ffbc6a6f7389bb93ffc920577d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "fdeflate"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
+dependencies = [
+ "simd-adler32",
+]
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a3076410a55c90011c298b04d0cfa770b00fa04e1e3c97d3f6c9de105a03844"
+
+[[package]]
+name = "flate2"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bfe33edd8e85a12a67454e37f8c75e730830d83e313556ab9ebf9ee7fbeb3bfb"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide",
+]
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
+
+[[package]]
+name = "futures-sink"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e575fab7d1e0dcb8d0c7bcf9a63ee213816ab51902e6d244a95819acacf1d4f7"
+
+[[package]]
+name = "futures-task"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
+
+[[package]]
+name = "futures-util"
+version = "0.3.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "pin-utils",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "wasip2",
+]
+
+[[package]]
+name = "gif"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f954a9e9159ec994f73a30a12b96a702dde78f5547bcb561174597924f7d4162"
+dependencies = [
+ "color_quant",
+ "weezl",
+]
+
+[[package]]
+name = "half"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+ "zerocopy",
+]
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "http"
+version = "1.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
+[[package]]
+name = "hyper"
+version = "1.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "http",
+ "http-body",
+ "httparse",
+ "httpdate",
+ "itoa",
+ "pin-project-lite",
+ "pin-utils",
+ "smallvec",
+ "tokio",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52e9a2a24dc5c6821e71a7030e1e14b7b632acac55c40e9d2e082c621261bb56"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "hyper",
+ "pin-project-lite",
+ "tokio",
+ "tower-service",
+]
+
+[[package]]
+name = "iana-time-zone"
+version = "0.1.64"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb"
+dependencies = [
+ "android_system_properties",
+ "core-foundation-sys",
+ "iana-time-zone-haiku",
+ "js-sys",
+ "log",
+ "wasm-bindgen",
+ "windows-core",
+]
+
+[[package]]
+name = "iana-time-zone-haiku"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "image"
+version = "0.25.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6506c6c10786659413faa717ceebcb8f70731c0a60cbae39795fdf114519c1a"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "color_quant",
+ "exr",
+ "gif",
+ "image-webp",
+ "moxcms",
+ "num-traits",
+ "png",
+ "qoi",
+ "ravif",
+ "rayon",
+ "rgb",
+ "tiff",
+ "zune-core 0.5.0",
+ "zune-jpeg 0.5.5",
+]
+
+[[package]]
+name = "image-webp"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
+dependencies = [
+ "byteorder-lite",
+ "quick-error",
+]
+
+[[package]]
+name = "imgref"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7c5cedc30da3a610cac6b4ba17597bdf7152cf974e8aab3afb3d54455e371c8"
+
+[[package]]
+name = "interpolate_name"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "itertools"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285"
+dependencies = [
+ "either",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c"
+
+[[package]]
+name = "jobserver"
+version = "0.1.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
+dependencies = [
+ "getrandom",
+ "libc",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.82"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b011eec8cc36da2aab2d5cff675ec18454fad408585853910a202391cf9f8e65"
+dependencies = [
+ "once_cell",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "lebe"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8"
+
+[[package]]
+name = "libc"
+version = "0.2.177"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976"
+
+[[package]]
+name = "libfuzzer-sys"
+version = "0.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5037190e1f70cbeef565bd267599242926f724d3b8a9f510fd7e0b540cfa4404"
+dependencies = [
+ "arbitrary",
+ "cc",
+]
+
+[[package]]
+name = "log"
+version = "0.4.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34080505efa8e45a4b816c349525ebe327ceaa8559756f0356cba97ef3bf7432"
+
+[[package]]
+name = "loop9"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062"
+dependencies = [
+ "imgref",
+]
+
+[[package]]
+name = "matchit"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
+
+[[package]]
+name = "maud"
+version = "0.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8156733e27020ea5c684db5beac5d1d611e1272ab17901a49466294b84fc217e"
+dependencies = [
+ "itoa",
+ "maud_macros",
+]
+
+[[package]]
+name = "maud_macros"
+version = "0.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7261b00f3952f617899bc012e3dbd56e4f0110a038175929fa5d18e5a19913ca"
+dependencies = [
+ "proc-macro2",
+ "proc-macro2-diagnostics",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "maybe-rayon"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519"
+dependencies = [
+ "cfg-if",
+ "rayon",
+]
+
+[[package]]
+name = "memchr"
+version = "2.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f52b00d39961fc5b2736ea853c9cc86238e165017a493d1d5c8eac6bdc4cc273"
+
+[[package]]
+name = "mime"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "mio"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69d83b0086dc8ecf3ce9ae2874b2d1290252e2a30720bea58a5c6639b0092873"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "moxcms"
+version = "0.7.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fbdd3d7436f8b5e892b8b7ea114271ff0fa00bc5acae845d53b07d498616ef6"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
+[[package]]
+name = "new_debug_unreachable"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
+
+[[package]]
+name = "nom"
+version = "8.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "noop_proc_macro"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8"
+
+[[package]]
+name = "num-bigint"
+version = "0.4.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-derive"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "num-integer"
+version = "0.1.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "num-rational"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824"
+dependencies = [
+ "num-bigint",
+ "num-integer",
+ "num-traits",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
+
+[[package]]
+name = "paste"
+version = "1.0.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a"
+
+[[package]]
+name = "pastey"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec"
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
+
+[[package]]
+name = "pin-utils"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+
+[[package]]
+name = "pkg-config"
+version = "0.3.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
+
+[[package]]
+name = "png"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97baced388464909d42d89643fe4361939af9b7ce7a31ee32a168f832a70f2a0"
+dependencies = [
+ "bitflags",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide",
+]
+
+[[package]]
+name = "ppv-lite86"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.103"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ee95bc4ef87b8d5ba32e8b7714ccc834865276eab0aed5c9958d00ec45f49e8"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "proc-macro2-diagnostics"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+ "version_check",
+]
+
+[[package]]
+name = "profiling"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eb8486b569e12e2c32ad3e204dbaba5e4b5b216e9367044f25f1dba42341773"
+dependencies = [
+ "profiling-procmacros",
+]
+
+[[package]]
+name = "profiling-procmacros"
+version = "1.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52717f9a02b6965224f95ca2a81e2e0c5c43baacd28ca057577988930b6c3d5b"
+dependencies = [
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "pxfm"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3cbdf373972bf78df4d3b518d07003938e2c7d1fb5891e55f9cb6df57009d84"
+dependencies = [
+ "num-traits",
+]
+
+[[package]]
+name = "qoi"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001"
+dependencies = [
+ "bytemuck",
+]
+
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
+[[package]]
+name = "quote"
+version = "1.0.42"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a338cc41d27e6cc6dce6cefc13a0729dfbb81c262b1f519331575dd80ef3067f"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "rand"
+version = "0.9.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
+dependencies = [
+ "rand_chacha",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_chacha"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
+dependencies = [
+ "ppv-lite86",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
+dependencies = [
+ "getrandom",
+]
+
+[[package]]
+name = "rav1e"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b"
+dependencies = [
+ "aligned-vec",
+ "arbitrary",
+ "arg_enum_proc_macro",
+ "arrayvec",
+ "av-scenechange",
+ "av1-grain",
+ "bitstream-io",
+ "built",
+ "cfg-if",
+ "interpolate_name",
+ "itertools",
+ "libc",
+ "libfuzzer-sys",
+ "log",
+ "maybe-rayon",
+ "new_debug_unreachable",
+ "noop_proc_macro",
+ "num-derive",
+ "num-traits",
+ "paste",
+ "profiling",
+ "rand",
+ "rand_chacha",
+ "simd_helpers",
+ "thiserror",
+ "v_frame",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "ravif"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef69c1990ceef18a116855938e74793a5f7496ee907562bd0857b6ac734ab285"
+dependencies = [
+ "avif-serialize",
+ "imgref",
+ "loop9",
+ "quick-error",
+ "rav1e",
+ "rayon",
+ "rgb",
+]
+
+[[package]]
+name = "rayon"
+version = "1.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "368f01d005bf8fd9b1206fb6fa653e6c4a81ceb1466406b81792d87c5677a58f"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "rgb"
+version = "0.8.52"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c6a884d2998352bb4daf0183589aec883f16a6da1f4dde84d8e2e9a5409a1ce"
+
+[[package]]
+name = "rustversion"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
+
+[[package]]
+name = "ryu"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "28d3b2b1366ec20994f1fd18c3c594f05c5dd4bc44d8bb0c1c632c8d6829481f"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.145"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "402a6f66d8c709116cf22f558eab210f5a50187f702eb4d7e5ef38d9a7f1c79c"
+dependencies = [
+ "itoa",
+ "memchr",
+ "ryu",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde_path_to_error"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
+dependencies = [
+ "itoa",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde_urlencoded"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
+dependencies = [
+ "form_urlencoded",
+ "itoa",
+ "ryu",
+ "serde",
+]
+
+[[package]]
+name = "servable"
+version = "0.0.1"
+dependencies = [
+ "axum",
+ "chrono",
+ "image",
+ "maud",
+ "rand",
+ "serde",
+ "serde_urlencoded",
+ "strum",
+ "thiserror",
+ "tokio",
+ "tower",
+ "tower-http",
+ "tracing",
+]
+
+[[package]]
+name = "shlex"
+version = "1.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
+
+[[package]]
+name = "simd-adler32"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe"
+
+[[package]]
+name = "simd_helpers"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6"
+dependencies = [
+ "quote",
+]
+
+[[package]]
+name = "smallvec"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
+
+[[package]]
+name = "socket2"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17129e116933cf371d018bb80ae557e889637989d8638274fb25622827b03881"
+dependencies = [
+ "libc",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "strum"
+version = "0.27.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af23d6f6c1a224baef9d3f61e287d2761385a5b88fdab4eb4c6f11aeb54c4bcf"
+dependencies = [
+ "strum_macros",
+]
+
+[[package]]
+name = "strum_macros"
+version = "0.27.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7695ce3845ea4b33927c055a39dc438a45b059f7c1b3d91d38d10355fb8cbca7"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.111"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "390cc9a294ab71bdb1aa2e99d13be9c753cd2d7bd6560c77118597410c4d2e87"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+
+[[package]]
+name = "thiserror"
+version = "2.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tiff"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af9605de7fee8d9551863fd692cce7637f548dbd9db9180fcc07ccc6d26c336f"
+dependencies = [
+ "fax",
+ "flate2",
+ "half",
+ "quick-error",
+ "weezl",
+ "zune-jpeg 0.4.21",
+]
+
+[[package]]
+name = "tokio"
+version = "1.48.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408"
+dependencies = [
+ "libc",
+ "mio",
+ "pin-project-lite",
+ "socket2",
+ "tokio-macros",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af407857209536a95c8e56f8231ef2c2e2aff839b22e07a1ffcbc617e9db9fa5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2efa149fe76073d6e8fd97ef4f4eca7b67f599660115591483572e406e165594"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "tower"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d039ad9159c98b70ecfd540b2573b97f7f52c3e8d9f8ad57a24b916a536975f9"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9cf146f99d442e8e68e585f5d798ccd3cad9a7835b917e09728880a862706456"
+dependencies = [
+ "async-compression",
+ "bitflags",
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+ "tokio",
+ "tokio-util",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.41"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0"
+dependencies = [
+ "log",
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.35"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a04e24fab5c89c6a36eb8558c9656f30d81de51dfa4d3b45f26b21d61fa0a6c"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5"
+
+[[package]]
+name = "v_frame"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2"
+dependencies = [
+ "aligned-vec",
+ "num-traits",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasip2"
+version = "1.0.1+wasi-0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da95793dfc411fbbd93f5be7715b0578ec61fe87cb1a42b12eb625caa5c5ea60"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04264334509e04a7bf8690f2384ef5265f05143a4bff3889ab7a3269adab59c2"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "420bc339d9f322e562942d52e115d57e950d12d88983a14c79b86859ee6c7ebc"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.105"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "76f218a38c84bcb33c25ec7059b07847d465ce0e0a76b995e134a45adcb6af76"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
+[[package]]
+name = "windows-core"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.59.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
+ "windows_x86_64_gnullvm",
+ "windows_x86_64_msvc",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "wit-bindgen"
+version = "0.46.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
+
+[[package]]
+name = "y4m"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448"
+
+[[package]]
+name = "zerocopy"
+version = "0.8.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea879c944afe8a2b25fef16bb4ba234f47c694565e97383b36f3a878219065c"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf955aa904d6040f70dc8e9384444cb1030aed272ba3cb09bbc4ab9e7c1f34f5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn",
+]
+
+[[package]]
+name = "zstd"
+version = "0.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e91ee311a569c327171651566e07972200e76fcfe2242a4fa446149a3881c08a"
+dependencies = [
+ "zstd-safe",
+]
+
+[[package]]
+name = "zstd-safe"
+version = "7.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f49c4d5f0abb602a93fb8736af2a4f4dd9512e36f7f570d66e65ff867ed3b9d"
+dependencies = [
+ "zstd-sys",
+]
+
+[[package]]
+name = "zstd-sys"
+version = "2.0.16+zstd.1.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
+dependencies = [
+ "cc",
+ "pkg-config",
+]
+
+[[package]]
+name = "zune-core"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f423a2c17029964870cfaabb1f13dfab7d092a62a29a89264f4d36990ca414a"
+
+[[package]]
+name = "zune-core"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "111f7d9820f05fd715df3144e254d6fc02ee4088b0644c0ffd0efc9e6d9d2773"
+
+[[package]]
+name = "zune-inflate"
+version = "0.2.54"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02"
+dependencies = [
+ "simd-adler32",
+]
+
+[[package]]
+name = "zune-jpeg"
+version = "0.4.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29ce2c8a9384ad323cf564b67da86e21d3cfdff87908bc1223ed5c99bc792713"
+dependencies = [
+ "zune-core 0.4.12",
+]
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc6fb7703e32e9a07fb3f757360338b3a567a5054f21b5f52a666752e333d58e"
+dependencies = [
+ "zune-core 0.5.0",
+]
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..d0cc86e
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,85 @@
+[workspace]
+members = ["crates/*"]
+resolver = "2"
+
+[workspace.package]
+rust-version = "1.90.0"
+edition = "2024"
+version = "0.0.1"
+license = "GPL-3.0"
+repository = "https://github.com/rm-dr/servable"
+readme = "README.md"
+authors = ["rm-dr"]
+
+[workspace.lints.rust]
+unused_import_braces = "deny"
+unit_bindings = "deny"
+single_use_lifetimes = "deny"
+non_ascii_idents = "deny"
+macro_use_extern_crate = "deny"
+elided_lifetimes_in_paths = "deny"
+absolute_paths_not_starting_with_crate = "deny"
+explicit_outlives_requirements = "warn"
+unused_crate_dependencies = "warn"
+redundant_lifetimes = "warn"
+missing_docs = "warn"
+
+[workspace.lints.clippy]
+todo = "deny"
+uninlined_format_args = "allow"
+result_large_err = "allow"
+too_many_arguments = "allow"
+upper_case_acronyms = "deny"
+needless_return = "allow"
+new_without_default = "allow"
+tabs_in_doc_comments = "allow"
+dbg_macro = "deny"
+allow_attributes = "deny"
+create_dir = "deny"
+filetype_is_file = "deny"
+integer_division = "allow"
+lossy_float_literal = "deny"
+map_err_ignore = "deny"
+mutex_atomic = "deny"
+needless_raw_strings = "deny"
+str_to_string = "deny"
+string_add = "deny"
+string_to_string = "deny"
+use_debug = "allow"
+verbose_file_reads = "deny"
+large_types_passed_by_value = "deny"
+wildcard_dependencies = "deny"
+negative_feature_names = "deny"
+redundant_feature_names = "deny"
+multiple_crate_versions = "deny"
+missing_safety_doc = "warn"
+identity_op = "allow"
+print_stderr = "deny"
+print_stdout = "deny"
+comparison_chain = "allow"
+unimplemented = "deny"
+unwrap_used = "warn"
+expect_used = "warn"
+type_complexity = "allow"
+cargo_common_metadata = "deny"
+
+
+#
+# MARK: dependencies
+#
+
+[workspace.dependencies]
+
+axum = "0.8.7"
+chrono = "0.4.42"
+image = "0.25.9"
+maud = "0.27.0"
+rand = "0.9.0"
+serde = { version = "1.0.228", features = ["derive"] }
+serde_urlencoded = "0.7.1"
+strum = { version = "0.27.2", features = ["derive"] }
+thiserror = "2.0.17"
+tokio = "1.48.0"
+tower = "0.5.2"
+tower-http = { version = "0.6.7", features = ["compression-full"] }
+tracing = "0.1.41"
diff --git a/clippy.toml b/clippy.toml
new file mode 100644
index 0000000..92095fd
--- /dev/null
+++ b/clippy.toml
@@ -0,0 +1 @@
+allowed-duplicate-crates = ["windows-sys"]
diff --git a/crates/servable/Cargo.toml b/crates/servable/Cargo.toml
new file mode 100644
index 0000000..0ff3a47
--- /dev/null
+++ b/crates/servable/Cargo.toml
@@ -0,0 +1,38 @@
+[package]
+name = "servable"
+description = "A tiny web stack featuring htmx, Axum, Rust, and Maud."
+keywords = ["htmx", "web", "webui", "maud", "framework"]
+categories = ["web-programming", "web-programming::http-server"]
+rust-version = { workspace = true }
+edition = { workspace = true }
+version = { workspace = true }
+license = { workspace = true }
+repository = { workspace = true }
+readme = { workspace = true }
+authors = { workspace = true }
+
+[lints]
+workspace = true
+
+[dependencies]
+axum = { workspace = true }
+chrono = { workspace = true }
+maud = { workspace = true }
+serde = { workspace = true }
+serde_urlencoded = { workspace = true }
+tower = { workspace = true }
+tracing = { workspace = true }
+rand = { workspace = true }
+
+tokio = { workspace = true, optional = true }
+image = { workspace = true, optional = true }
+strum = { workspace = true, optional = true }
+thiserror = { workspace = true, optional = true }
+
+[dev-dependencies]
+tower-http = { workspace = true }
+
+[features]
+default = []
+image = ["dep:image", "dep:strum", "dep:thiserror", "dep:tokio"]
+"htmx-2.0.8" = []
diff --git a/crates/servable/htmx/htmx-2.0.8.min.js b/crates/servable/htmx/htmx-2.0.8.min.js
new file mode 100644
index 0000000..faafa3e
--- /dev/null
+++ b/crates/servable/htmx/htmx-2.0.8.min.js
@@ -0,0 +1 @@
+var htmx=function(){"use strict";const Q={onLoad:null,process:null,on:null,off:null,trigger:null,ajax:null,find:null,findAll:null,closest:null,values:function(e,t){const n=dn(e,t||"post");return n.values},remove:null,addClass:null,removeClass:null,toggleClass:null,takeClass:null,swap:null,defineExtension:null,removeExtension:null,logAll:null,logNone:null,logger:null,config:{historyEnabled:true,historyCacheSize:10,refreshOnHistoryMiss:false,defaultSwapStyle:"innerHTML",defaultSwapDelay:0,defaultSettleDelay:20,includeIndicatorStyles:true,indicatorClass:"htmx-indicator",requestClass:"htmx-request",addedClass:"htmx-added",settlingClass:"htmx-settling",swappingClass:"htmx-swapping",allowEval:true,allowScriptTags:true,inlineScriptNonce:"",inlineStyleNonce:"",attributesToSettle:["class","style","width","height"],withCredentials:false,timeout:0,wsReconnectDelay:"full-jitter",wsBinaryType:"blob",disableSelector:"[hx-disable], [data-hx-disable]",scrollBehavior:"instant",defaultFocusScroll:false,getCacheBusterParam:false,globalViewTransitions:false,methodsThatUseUrlParams:["get","delete"],selfRequestsOnly:true,ignoreTitle:false,scrollIntoViewOnBoost:true,triggerSpecsCache:null,disableInheritance:false,responseHandling:[{code:"204",swap:false},{code:"[23]..",swap:true},{code:"[45]..",swap:false,error:true}],allowNestedOobSwaps:true,historyRestoreAsHxRequest:true,reportValidityOfForms:false},parseInterval:null,location:location,_:null,version:"2.0.8"};Q.onLoad=V;Q.process=Ft;Q.on=xe;Q.off=be;Q.trigger=ae;Q.ajax=Ln;Q.find=f;Q.findAll=x;Q.closest=g;Q.remove=_;Q.addClass=K;Q.removeClass=G;Q.toggleClass=W;Q.takeClass=Z;Q.swap=ze;Q.defineExtension=_n;Q.removeExtension=zn;Q.logAll=j;Q.logNone=$;Q.parseInterval=d;Q._=e;const n={addTriggerHandler:St,bodyContains:se,canAccessLocalStorage:X,findThisElement:Se,filterValues:yn,swap:ze,hasAttribute:s,getAttributeValue:a,getClosestAttributeValue:ne,getClosestMatch:q,getExpressionVars:Rn,getHeaders:mn,getInputValues:dn,getInternalData:oe,getSwapSpecification:bn,getTriggerSpecs:st,getTarget:Ee,makeFragment:D,mergeObjects:le,makeSettleInfo:Sn,oobSwap:Te,querySelectorExt:ue,settleImmediately:Yt,shouldCancel:ht,triggerEvent:ae,triggerErrorEvent:fe,withExtensions:Vt};const de=["get","post","put","delete","patch"];const R=de.map(function(e){return"[hx-"+e+"], [data-hx-"+e+"]"}).join(", ");function d(e){if(e==undefined){return undefined}let t=NaN;if(e.slice(-2)=="ms"){t=parseFloat(e.slice(0,-2))}else if(e.slice(-1)=="s"){t=parseFloat(e.slice(0,-1))*1e3}else if(e.slice(-1)=="m"){t=parseFloat(e.slice(0,-1))*1e3*60}else{t=parseFloat(e)}return isNaN(t)?undefined:t}function ee(e,t){return e instanceof Element&&e.getAttribute(t)}function s(e,t){return!!e.hasAttribute&&(e.hasAttribute(t)||e.hasAttribute("data-"+t))}function a(e,t){return ee(e,t)||ee(e,"data-"+t)}function u(e){const t=e.parentElement;if(!t&&e.parentNode instanceof ShadowRoot)return e.parentNode;return t}function te(){return document}function y(e,t){return e.getRootNode?e.getRootNode({composed:t}):te()}function q(e,t){while(e&&!t(e)){e=u(e)}return e||null}function o(e,t,n){const r=a(t,n);const o=a(t,"hx-disinherit");var i=a(t,"hx-inherit");if(e!==t){if(Q.config.disableInheritance){if(i&&(i==="*"||i.split(" ").indexOf(n)>=0)){return r}else{return null}}if(o&&(o==="*"||o.split(" ").indexOf(n)>=0)){return"unset"}}return r}function ne(t,n){let r=null;q(t,function(e){return!!(r=o(t,ce(e),n))});if(r!=="unset"){return r}}function h(e,t){return e instanceof Element&&e.matches(t)}function A(e){const t=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i;const n=t.exec(e);if(n){return n[1].toLowerCase()}else{return""}}function L(e){if("parseHTMLUnsafe"in Document){return Document.parseHTMLUnsafe(e)}const t=new DOMParser;return t.parseFromString(e,"text/html")}function N(e,t){while(t.childNodes.length>0){e.append(t.childNodes[0])}}function r(e){const t=te().createElement("script");ie(e.attributes,function(e){t.setAttribute(e.name,e.value)});t.textContent=e.textContent;t.async=false;if(Q.config.inlineScriptNonce){t.nonce=Q.config.inlineScriptNonce}return t}function i(e){return e.matches("script")&&(e.type==="text/javascript"||e.type==="module"||e.type==="")}function I(e){Array.from(e.querySelectorAll("script")).forEach(e=>{if(i(e)){const t=r(e);const n=e.parentNode;try{n.insertBefore(t,e)}catch(e){H(e)}finally{e.remove()}}})}function D(e){const t=e.replace(/
]*)?>[\s\S]*?<\/head>/i,"");const n=A(t);let r;if(n==="html"){r=new DocumentFragment;const i=L(e);N(r,i.body);r.title=i.title}else if(n==="body"){r=new DocumentFragment;const i=L(t);N(r,i.body);r.title=i.title}else{const i=L(''+t+"");r=i.querySelector("template").content;r.title=i.title;var o=r.querySelector("title");if(o&&o.parentNode===r){o.remove();r.title=o.innerText}}if(r){if(Q.config.allowScriptTags){I(r)}else{r.querySelectorAll("script").forEach(e=>e.remove())}}return r}function re(e){if(e){e()}}function t(e,t){return Object.prototype.toString.call(e)==="[object "+t+"]"}function P(e){return typeof e==="function"}function k(e){return t(e,"Object")}function oe(e){const t="htmx-internal-data";let n=e[t];if(!n){n=e[t]={}}return n}function M(t){const n=[];if(t){for(let e=0;e=0}function se(e){return e.getRootNode({composed:true})===document}function B(e){return e.trim().split(/\s+/)}function le(e,t){for(const n in t){if(t.hasOwnProperty(n)){e[n]=t[n]}}return e}function v(e){try{return JSON.parse(e)}catch(e){H(e);return null}}function X(){const e="htmx:sessionStorageTest";try{sessionStorage.setItem(e,e);sessionStorage.removeItem(e);return true}catch(e){return false}}function U(e){const t=new URL(e,"http://x");if(t){e=t.pathname+t.search}if(e!="/"){e=e.replace(/\/+$/,"")}return e}function e(e){return On(te().body,function(){return eval(e)})}function V(t){const e=Q.on("htmx:load",function(e){t(e.detail.elt)});return e}function j(){Q.logger=function(e,t,n){if(console){console.log(t,e,n)}}}function $(){Q.logger=null}function f(e,t){if(typeof e!=="string"){return e.querySelector(t)}else{return f(te(),e)}}function x(e,t){if(typeof e!=="string"){return e.querySelectorAll(t)}else{return x(te(),e)}}function b(){return window}function _(e,t){e=w(e);if(t){b().setTimeout(function(){_(e);e=null},t)}else{u(e).removeChild(e)}}function ce(e){return e instanceof Element?e:null}function z(e){return e instanceof HTMLElement?e:null}function J(e){return typeof e==="string"?e:null}function p(e){return e instanceof Element||e instanceof Document||e instanceof DocumentFragment?e:null}function K(e,t,n){e=ce(w(e));if(!e){return}if(n){b().setTimeout(function(){K(e,t);e=null},n)}else{e.classList&&e.classList.add(t)}}function G(e,t,n){let r=ce(w(e));if(!r){return}if(n){b().setTimeout(function(){G(r,t);r=null},n)}else{if(r.classList){r.classList.remove(t);if(r.classList.length===0){r.removeAttribute("class")}}}}function W(e,t){e=w(e);e.classList.toggle(t)}function Z(e,t){e=w(e);ie(e.parentElement.children,function(e){G(e,t)});K(ce(e),t)}function g(e,t){e=ce(w(e));if(e){return e.closest(t)}return null}function l(e,t){return e.substring(0,t.length)===t}function Y(e,t){return e.substring(e.length-t.length)===t}function pe(e){const t=e.trim();if(l(t,"<")&&Y(t,"/>")){return t.substring(1,t.length-2)}else{return t}}function m(t,r,n){if(r.indexOf("global ")===0){return m(t,r.slice(7),true)}t=w(t);const o=[];{let t=0;let n=0;for(let e=0;e"){t--}}if(n0){const r=pe(o.shift());let e;if(r.indexOf("closest ")===0){e=g(ce(t),pe(r.slice(8)))}else if(r.indexOf("find ")===0){e=f(p(t),pe(r.slice(5)))}else if(r==="next"||r==="nextElementSibling"){e=ce(t).nextElementSibling}else if(r.indexOf("next ")===0){e=ge(t,pe(r.slice(5)),!!n)}else if(r==="previous"||r==="previousElementSibling"){e=ce(t).previousElementSibling}else if(r.indexOf("previous ")===0){e=me(t,pe(r.slice(9)),!!n)}else if(r==="document"){e=document}else if(r==="window"){e=window}else if(r==="body"){e=document.body}else if(r==="root"){e=y(t,!!n)}else if(r==="host"){e=t.getRootNode().host}else{s.push(r)}if(e){i.push(e)}}if(s.length>0){const e=s.join(",");const c=p(y(t,!!n));i.push(...M(c.querySelectorAll(e)))}return i}var ge=function(t,e,n){const r=p(y(t,n)).querySelectorAll(e);for(let e=0;e=0;e--){const o=r[e];if(o.compareDocumentPosition(t)===Node.DOCUMENT_POSITION_FOLLOWING){return o}}};function ue(e,t){if(typeof e!=="string"){return m(e,t)[0]}else{return m(te().body,e)[0]}}function w(e,t){if(typeof e==="string"){return f(p(t)||document,e)}else{return e}}function ye(e,t,n,r){if(P(t)){return{target:te().body,event:J(e),listener:t,options:n}}else{return{target:w(e),event:J(t),listener:n,options:r}}}function xe(t,n,r,o){Gn(function(){const e=ye(t,n,r,o);e.target.addEventListener(e.event,e.listener,e.options)});const e=P(n);return e?n:r}function be(t,n,r){Gn(function(){const e=ye(t,n,r);e.target.removeEventListener(e.event,e.listener)});return P(n)?n:r}const ve=te().createElement("output");function we(t,n){const e=ne(t,n);if(e){if(e==="this"){return[Se(t,n)]}else{const r=m(t,e);const o=/(^|,)(\s*)inherit(\s*)($|,)/.test(e);if(o){const i=ce(q(t,function(e){return e!==t&&s(ce(e),n)}));if(i){r.push(...we(i,n))}}if(r.length===0){H('The selector "'+e+'" on '+n+" returned no matches!");return[ve]}else{return r}}}}function Se(e,t){return ce(q(e,function(e){return a(ce(e),t)!=null}))}function Ee(e){const t=ne(e,"hx-target");if(t){if(t==="this"){return Se(e,"hx-target")}else{return ue(e,t)}}else{const n=oe(e);if(n.boosted){return te().body}else{return e}}}function Ce(e){return Q.config.attributesToSettle.includes(e)}function Oe(t,n){ie(Array.from(t.attributes),function(e){if(!n.hasAttribute(e.name)&&Ce(e.name)){t.removeAttribute(e.name)}});ie(n.attributes,function(e){if(Ce(e.name)){t.setAttribute(e.name,e.value)}})}function He(t,e){const n=Jn(e);for(let e=0;e0){s=e.substring(0,e.indexOf(":"));n=e.substring(e.indexOf(":")+1)}else{s=e}o.removeAttribute("hx-swap-oob");o.removeAttribute("data-hx-swap-oob");const r=m(t,n,false);if(r.length){ie(r,function(e){let t;const n=o.cloneNode(true);t=te().createDocumentFragment();t.appendChild(n);if(!He(s,e)){t=p(n)}const r={shouldSwap:true,target:e,fragment:t};if(!ae(e,"htmx:oobBeforeSwap",r))return;e=r.target;if(r.shouldSwap){qe(t);$e(s,e,e,t,i);Re()}ie(i.elts,function(e){ae(e,"htmx:oobAfterSwap",r)})});o.parentNode.removeChild(o)}else{o.parentNode.removeChild(o);fe(te().body,"htmx:oobErrorNoTarget",{content:o})}return e}function Re(){const e=f("#--htmx-preserve-pantry--");if(e){for(const t of[...e.children]){const n=f("#"+t.id);n.parentNode.moveBefore(t,n);n.remove()}e.remove()}}function qe(e){ie(x(e,"[hx-preserve], [data-hx-preserve]"),function(e){const t=a(e,"id");const n=te().getElementById(t);if(n!=null){if(e.moveBefore){let e=f("#--htmx-preserve-pantry--");if(e==null){te().body.insertAdjacentHTML("afterend","");e=f("#--htmx-preserve-pantry--")}e.moveBefore(n,null)}else{e.parentNode.replaceChild(n,e)}}})}function Ae(l,e,c){ie(e.querySelectorAll("[id]"),function(t){const n=ee(t,"id");if(n&&n.length>0){const r=n.replace("'","\\'");const o=t.tagName.replace(":","\\:");const e=p(l);const i=e&&e.querySelector(o+"[id='"+r+"']");if(i&&i!==e){const s=t.cloneNode();Oe(t,i);c.tasks.push(function(){Oe(t,s)})}}})}function Le(e){return function(){G(e,Q.config.addedClass);Ft(ce(e));Ne(p(e));ae(e,"htmx:load")}}function Ne(e){const t="[autofocus]";const n=z(h(e,t)?e:e.querySelector(t));if(n!=null){n.focus()}}function c(e,t,n,r){Ae(e,n,r);while(n.childNodes.length>0){const o=n.firstChild;K(ce(o),Q.config.addedClass);e.insertBefore(o,t);if(o.nodeType!==Node.TEXT_NODE&&o.nodeType!==Node.COMMENT_NODE){r.tasks.push(Le(o))}}}function Ie(e,t){let n=0;while(n0}function ze(h,d,p,g){if(!g){g={}}let m=null;let n=null;let e=function(){re(g.beforeSwapCallback);h=w(h);const r=g.contextElement?y(g.contextElement,false):te();const e=document.activeElement;let t={};t={elt:e,start:e?e.selectionStart:null,end:e?e.selectionEnd:null};const o=Sn(h);if(p.swapStyle==="textContent"){h.textContent=d}else{let n=D(d);o.title=g.title||n.title;if(g.historyRequest){n=n.querySelector("[hx-history-elt],[data-hx-history-elt]")||n}if(g.selectOOB){const i=g.selectOOB.split(",");for(let t=0;t0){b().setTimeout(n,p.settleDelay)}else{n()}};let t=Q.config.globalViewTransitions;if(p.hasOwnProperty("transition")){t=p.transition}const r=g.contextElement||te();if(t&&ae(r,"htmx:beforeTransition",g.eventInfo)&&typeof Promise!=="undefined"&&document.startViewTransition){const o=new Promise(function(e,t){m=e;n=t});const i=e;e=function(){document.startViewTransition(function(){i();return o})}}try{if(p?.swapDelay&&p.swapDelay>0){b().setTimeout(e,p.swapDelay)}else{e()}}catch(e){fe(r,"htmx:swapError",g.eventInfo);re(n);throw e}}function Je(e,t,n){const r=e.getResponseHeader(t);if(r.indexOf("{")===0){const o=v(r);for(const i in o){if(o.hasOwnProperty(i)){let e=o[i];if(k(e)){n=e.target!==undefined?e.target:n}else{e={value:e}}ae(n,i,e)}}}else{const s=r.split(",");for(let e=0;e0){const s=o[0];if(s==="]"){e--;if(e===0){if(n===null){t=t+"true"}o.shift();t+=")})";try{const l=On(r,function(){return Function(t)()},function(){return true});l.source=t;return l}catch(e){fe(te().body,"htmx:syntax:error",{error:e,source:t});return null}}}else if(s==="["){e++}if(tt(s,n,i)){t+="(("+i+"."+s+") ? ("+i+"."+s+") : (window."+s+"))"}else{t=t+s}n=o.shift()}}}function O(e,t){let n="";while(e.length>0&&!t.test(e[0])){n+=e.shift()}return n}function rt(e){let t;if(e.length>0&&Ye.test(e[0])){e.shift();t=O(e,Qe).trim();e.shift()}else{t=O(e,E)}return t}const ot="input, textarea, select";function it(e,t,n){const r=[];const o=et(t);do{O(o,C);const l=o.length;const c=O(o,/[,\[\s]/);if(c!==""){if(c==="every"){const u={trigger:"every"};O(o,C);u.pollInterval=d(O(o,/[,\[\s]/));O(o,C);var i=nt(e,o,"event");if(i){u.eventFilter=i}r.push(u)}else{const f={trigger:c};var i=nt(e,o,"event");if(i){f.eventFilter=i}O(o,C);while(o.length>0&&o[0]!==","){const a=o.shift();if(a==="changed"){f.changed=true}else if(a==="once"){f.once=true}else if(a==="consume"){f.consume=true}else if(a==="delay"&&o[0]===":"){o.shift();f.delay=d(O(o,E))}else if(a==="from"&&o[0]===":"){o.shift();if(Ye.test(o[0])){var s=rt(o)}else{var s=O(o,E);if(s==="closest"||s==="find"||s==="next"||s==="previous"){o.shift();const h=rt(o);if(h.length>0){s+=" "+h}}}f.from=s}else if(a==="target"&&o[0]===":"){o.shift();f.target=rt(o)}else if(a==="throttle"&&o[0]===":"){o.shift();f.throttle=d(O(o,E))}else if(a==="queue"&&o[0]===":"){o.shift();f.queue=O(o,E)}else if(a==="root"&&o[0]===":"){o.shift();f[a]=rt(o)}else if(a==="threshold"&&o[0]===":"){o.shift();f[a]=O(o,E)}else{fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}r.push(f)}}if(o.length===l){fe(e,"htmx:syntax:error",{token:o.shift()})}O(o,C)}while(o[0]===","&&o.shift());if(n){n[t]=r}return r}function st(e){const t=a(e,"hx-trigger");let n=[];if(t){const r=Q.config.triggerSpecsCache;n=r&&r[t]||it(e,t,r)}if(n.length>0){return n}else if(h(e,"form")){return[{trigger:"submit"}]}else if(h(e,'input[type="button"], input[type="submit"]')){return[{trigger:"click"}]}else if(h(e,ot)){return[{trigger:"change"}]}else{return[{trigger:"click"}]}}function lt(e){oe(e).cancelled=true}function ct(e,t,n){const r=oe(e);r.timeout=b().setTimeout(function(){if(se(e)&&r.cancelled!==true){if(!pt(n,e,Xt("hx:poll:trigger",{triggerSpec:n,target:e}))){t(e)}ct(e,t,n)}},n.pollInterval)}function ut(e){return location.hostname===e.hostname&&ee(e,"href")&&ee(e,"href").indexOf("#")!==0}function ft(e){return g(e,Q.config.disableSelector)}function at(t,n,e){if(t instanceof HTMLAnchorElement&&ut(t)&&(t.target===""||t.target==="_self")||t.tagName==="FORM"&&String(ee(t,"method")).toLowerCase()!=="dialog"){n.boosted=true;let r,o;if(t.tagName==="A"){r="get";o=ee(t,"href")}else{const i=ee(t,"method");r=i?i.toLowerCase():"get";o=ee(t,"action");if(o==null||o===""){o=location.href}if(r==="get"&&o.includes("?")){o=o.replace(/\?[^#]+/,"")}}e.forEach(function(e){gt(t,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)},n,e,true)})}}function ht(e,t){if(e.type==="submit"&&t.tagName==="FORM"){return true}else if(e.type==="click"){const n=t.closest('input[type="submit"], button');if(n&&n.form&&n.type==="submit"){return true}const r=t.closest("a");const o=/^#.+/;if(r&&r.href&&!o.test(r.getAttribute("href"))){return true}}return false}function dt(e,t){return oe(e).boosted&&e instanceof HTMLAnchorElement&&t.type==="click"&&(t.ctrlKey||t.metaKey)}function pt(e,t,n){const r=e.eventFilter;if(r){try{return r.call(t,n)!==true}catch(e){const o=r.source;fe(te().body,"htmx:eventFilter:error",{error:e,source:o});return true}}return false}function gt(l,c,e,u,f){const a=oe(l);let t;if(u.from){t=m(l,u.from)}else{t=[l]}if(u.changed){if(!("lastValue"in a)){a.lastValue=new WeakMap}t.forEach(function(e){if(!a.lastValue.has(u)){a.lastValue.set(u,new WeakMap)}a.lastValue.get(u).set(e,e.value)})}ie(t,function(i){const s=function(e){if(!se(l)){i.removeEventListener(u.trigger,s);return}if(dt(l,e)){return}if(f||ht(e,i)){e.preventDefault()}if(pt(u,l,e)){return}const t=oe(e);t.triggerSpec=u;if(t.handledFor==null){t.handledFor=[]}if(t.handledFor.indexOf(l)<0){t.handledFor.push(l);if(u.consume){e.stopPropagation()}if(u.target&&e.target){if(!h(ce(e.target),u.target)){return}}if(u.once){if(a.triggeredOnce){return}else{a.triggeredOnce=true}}if(u.changed){const n=e.target;const r=n.value;const o=a.lastValue.get(u);if(o.has(n)&&o.get(n)===r){return}o.set(n,r)}if(a.delayed){clearTimeout(a.delayed)}if(a.throttle){return}if(u.throttle>0){if(!a.throttle){ae(l,"htmx:trigger");c(l,e);a.throttle=b().setTimeout(function(){a.throttle=null},u.throttle)}}else if(u.delay>0){a.delayed=b().setTimeout(function(){ae(l,"htmx:trigger");c(l,e)},u.delay)}else{ae(l,"htmx:trigger");c(l,e)}}};if(e.listenerInfos==null){e.listenerInfos=[]}e.listenerInfos.push({trigger:u.trigger,listener:s,on:i});i.addEventListener(u.trigger,s)})}let mt=false;let yt=null;function xt(){if(!yt){yt=function(){mt=true};window.addEventListener("scroll",yt);window.addEventListener("resize",yt);setInterval(function(){if(mt){mt=false;ie(te().querySelectorAll("[hx-trigger*='revealed'],[data-hx-trigger*='revealed']"),function(e){bt(e)})}},200)}}function bt(e){if(!s(e,"data-hx-revealed")&&F(e)){e.setAttribute("data-hx-revealed","true");const t=oe(e);if(t.initHash){ae(e,"revealed")}else{e.addEventListener("htmx:afterProcessNode",function(){ae(e,"revealed")},{once:true})}}}function vt(e,t,n,r){const o=function(){if(!n.loaded){n.loaded=true;ae(e,"htmx:trigger");t(e)}};if(r>0){b().setTimeout(o,r)}else{o()}}function wt(t,n,e){let i=false;ie(de,function(r){if(s(t,"hx-"+r)){const o=a(t,"hx-"+r);i=true;n.path=o;n.verb=r;e.forEach(function(e){St(t,e,n,function(e,t){const n=ce(e);if(ft(n)){S(n);return}he(r,o,n,t)})})}});return i}function St(r,e,t,n){if(e.trigger==="revealed"){xt();gt(r,n,t,e);bt(ce(r))}else if(e.trigger==="intersect"){const o={};if(e.root){o.root=ue(r,e.root)}if(e.threshold){o.threshold=parseFloat(e.threshold)}const i=new IntersectionObserver(function(t){for(let e=0;e0){t.polling=true;ct(ce(r),n,e)}else{gt(r,n,t,e)}}function Et(e){const t=ce(e);if(!t){return false}const n=t.attributes;for(let e=0;e", "+e).join(""));return o}else{return[]}}function Rt(e){const t=At(e.target);const n=Nt(e);if(n){n.lastButtonClicked=t}}function qt(e){const t=Nt(e);if(t){t.lastButtonClicked=null}}function At(e){return g(ce(e),"button, input[type='submit']")}function Lt(e){return e.form||g(e,"form")}function Nt(e){const t=At(e.target);if(!t){return}const n=Lt(t);if(!n){return}return oe(n)}function It(e){e.addEventListener("click",Rt);e.addEventListener("focusin",Rt);e.addEventListener("focusout",qt)}function Dt(t,e,n){const r=oe(t);if(!Array.isArray(r.onHandlers)){r.onHandlers=[]}let o;const i=function(e){On(t,function(){if(ft(t)){return}if(!o){o=new Function("event",n)}o.call(t,e)})};t.addEventListener(e,i);r.onHandlers.push({event:e,listener:i})}function Pt(t){Pe(t);for(let e=0;eQ.config.historyCacheSize){i.shift()}while(i.length>0){try{sessionStorage.setItem("htmx-history-cache",JSON.stringify(i));break}catch(e){fe(te().body,"htmx:historyCacheError",{cause:e,cache:i});i.shift()}}}function Jt(t){if(!X()){return null}t=U(t);const n=v(sessionStorage.getItem("htmx-history-cache"))||[];for(let e=0;e=200&&this.status<400){r.response=this.response;ae(te().body,"htmx:historyCacheMissLoad",r);ze(r.historyElt,r.response,n,{contextElement:r.historyElt,historyRequest:true});$t(r.path);ae(te().body,"htmx:historyRestore",{path:e,cacheMiss:true,serverResponse:r.response})}else{fe(te().body,"htmx:historyCacheMissLoadError",r)}};if(ae(te().body,"htmx:historyCacheMiss",r)){t.send()}}function en(e){Gt();e=e||location.pathname+location.search;const t=Jt(e);if(t){const n={swapStyle:"innerHTML",swapDelay:0,settleDelay:0,scroll:t.scroll};const r={path:e,item:t,historyElt:_t(),swapSpec:n};if(ae(te().body,"htmx:historyCacheHit",r)){ze(r.historyElt,t.content,n,{contextElement:r.historyElt,title:t.title});$t(r.path);ae(te().body,"htmx:historyRestore",r)}}else{if(Q.config.refreshOnHistoryMiss){Q.location.reload(true)}else{Qt(e)}}}function tn(e){let t=we(e,"hx-indicator");if(t==null){t=[e]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.classList.add.call(e.classList,Q.config.requestClass)});return t}function nn(e){let t=we(e,"hx-disabled-elt");if(t==null){t=[]}ie(t,function(e){const t=oe(e);t.requestCount=(t.requestCount||0)+1;e.setAttribute("disabled","");e.setAttribute("data-disabled-by-htmx","")});return t}function rn(e,t){ie(e.concat(t),function(e){const t=oe(e);t.requestCount=(t.requestCount||1)-1});ie(e,function(e){const t=oe(e);if(t.requestCount===0){e.classList.remove.call(e.classList,Q.config.requestClass)}});ie(t,function(e){const t=oe(e);if(t.requestCount===0){e.removeAttribute("disabled");e.removeAttribute("data-disabled-by-htmx")}})}function on(t,n){for(let e=0;en.indexOf(e)<0)}else{e=e.filter(e=>e!==n)}r.delete(t);ie(e,e=>r.append(t,e))}}function un(e){if(e instanceof HTMLSelectElement&&e.multiple){return M(e.querySelectorAll("option:checked")).map(function(e){return e.value})}if(e instanceof HTMLInputElement&&e.files){return M(e.files)}return e.value}function fn(t,n,r,e,o){if(e==null||on(t,e)){return}else{t.push(e)}if(sn(e)){const i=ee(e,"name");ln(i,un(e),n);if(o){an(e,r)}}if(e instanceof HTMLFormElement){ie(e.elements,function(e){if(t.indexOf(e)>=0){cn(e.name,un(e),n)}else{t.push(e)}if(o){an(e,r)}});new FormData(e).forEach(function(e,t){if(e instanceof File&&e.name===""){return}ln(t,e,n)})}}function an(e,t){const n=e;if(n.willValidate){ae(n,"htmx:validation:validate");if(!n.checkValidity()){if(ae(n,"htmx:validation:failed",{message:n.validationMessage,validity:n.validity})&&!t.length&&Q.config.reportValidityOfForms){n.reportValidity()}t.push({elt:n,message:n.validationMessage,validity:n.validity})}}}function hn(n,e){for(const t of e.keys()){n.delete(t)}e.forEach(function(e,t){n.append(t,e)});return n}function dn(e,t){const n=[];const r=new FormData;const o=new FormData;const i=[];const s=oe(e);if(s.lastButtonClicked&&!se(s.lastButtonClicked)){s.lastButtonClicked=null}let l=e instanceof HTMLFormElement&&e.noValidate!==true||a(e,"hx-validate")==="true";if(s.lastButtonClicked){l=l&&s.lastButtonClicked.formNoValidate!==true}if(t!=="get"){fn(n,o,i,Lt(e),l)}fn(n,r,i,e,l);if(s.lastButtonClicked||e.tagName==="BUTTON"||e.tagName==="INPUT"&&ee(e,"type")==="submit"){const u=s.lastButtonClicked||e;const f=ee(u,"name");ln(f,u.value,o)}const c=we(e,"hx-include");ie(c,function(e){fn(n,r,i,ce(e),l);if(!h(e,"form")){ie(p(e).querySelectorAll(ot),function(e){fn(n,r,i,e,l)})}});hn(r,o);return{errors:i,formData:r,values:kn(r)}}function pn(e,t,n){if(e!==""){e+="&"}if(String(n)==="[object Object]"){n=JSON.stringify(n)}const r=encodeURIComponent(n);e+=encodeURIComponent(t)+"="+r;return e}function gn(e){e=Dn(e);let n="";e.forEach(function(e,t){n=pn(n,t,e)});return n}function mn(e,t,n){const r={"HX-Request":"true","HX-Trigger":ee(e,"id"),"HX-Trigger-Name":ee(e,"name"),"HX-Target":a(t,"id"),"HX-Current-URL":location.href};Cn(e,"hx-headers",false,r);if(n!==undefined){r["HX-Prompt"]=n}if(oe(e).boosted){r["HX-Boosted"]="true"}return r}function yn(n,e){const t=ne(e,"hx-params");if(t){if(t==="none"){return new FormData}else if(t==="*"){return n}else if(t.indexOf("not ")===0){ie(t.slice(4).split(","),function(e){e=e.trim();n.delete(e)});return n}else{const r=new FormData;ie(t.split(","),function(t){t=t.trim();if(n.has(t)){n.getAll(t).forEach(function(e){r.append(t,e)})}});return r}}else{return n}}function xn(e){return!!ee(e,"href")&&ee(e,"href").indexOf("#")>=0}function bn(e,t){const n=t||ne(e,"hx-swap");const r={swapStyle:oe(e).boosted?"innerHTML":Q.config.defaultSwapStyle,swapDelay:Q.config.defaultSwapDelay,settleDelay:Q.config.defaultSettleDelay};if(Q.config.scrollIntoViewOnBoost&&oe(e).boosted&&!xn(e)){r.show="top"}if(n){const s=B(n);if(s.length>0){for(let e=0;e0?o.join(":"):null;r.scroll=u;r.scrollTarget=i}else if(l.indexOf("show:")===0){const f=l.slice(5);var o=f.split(":");const a=o.pop();var i=o.length>0?o.join(":"):null;r.show=a;r.showTarget=i}else if(l.indexOf("focus-scroll:")===0){const h=l.slice("focus-scroll:".length);r.focusScroll=h=="true"}else if(e==0){r.swapStyle=l}else{H("Unknown modifier in hx-swap: "+l)}}}}return r}function vn(e){return ne(e,"hx-encoding")==="multipart/form-data"||h(e,"form")&&ee(e,"enctype")==="multipart/form-data"}function wn(t,n,r){let o=null;Vt(n,function(e){if(o==null){o=e.encodeParameters(t,r,n)}});if(o!=null){return o}else{if(vn(n)){return hn(new FormData,Dn(r))}else{return gn(r)}}}function Sn(e){return{tasks:[],elts:[e]}}function En(e,t){const n=e[0];const r=e[e.length-1];if(t.scroll){var o=null;if(t.scrollTarget){o=ce(ue(n,t.scrollTarget))}if(t.scroll==="top"&&(n||o)){o=o||n;o.scrollTop=0}if(t.scroll==="bottom"&&(r||o)){o=o||r;o.scrollTop=o.scrollHeight}if(typeof t.scroll==="number"){b().setTimeout(function(){window.scrollTo(0,t.scroll)},0)}}if(t.show){var o=null;if(t.showTarget){let e=t.showTarget;if(t.showTarget==="window"){e="body"}o=ce(ue(n,e))}if(t.show==="top"&&(n||o)){o=o||n;o.scrollIntoView({block:"start",behavior:Q.config.scrollBehavior})}if(t.show==="bottom"&&(r||o)){o=o||r;o.scrollIntoView({block:"end",behavior:Q.config.scrollBehavior})}}}function Cn(r,e,o,i,s){if(i==null){i={}}if(r==null){return i}const l=a(r,e);if(l){let e=l.trim();let t=o;if(e==="unset"){return null}if(e.indexOf("javascript:")===0){e=e.slice(11);t=true}else if(e.indexOf("js:")===0){e=e.slice(3);t=true}if(e.indexOf("{")!==0){e="{"+e+"}"}let n;if(t){n=On(r,function(){if(s){return Function("event","return ("+e+")").call(r,s)}else{return Function("return ("+e+")").call(r)}},{})}else{n=v(e)}for(const c in n){if(n.hasOwnProperty(c)){if(i[c]==null){i[c]=n[c]}}}}return Cn(ce(u(r)),e,o,i,s)}function On(e,t,n){if(Q.config.allowEval){return t()}else{fe(e,"htmx:evalDisallowedError");return n}}function Hn(e,t,n){return Cn(e,"hx-vars",true,n,t)}function Tn(e,t,n){return Cn(e,"hx-vals",false,n,t)}function Rn(e,t){return le(Hn(e,t),Tn(e,t))}function qn(t,n,r){if(r!==null){try{t.setRequestHeader(n,r)}catch(e){t.setRequestHeader(n,encodeURIComponent(r));t.setRequestHeader(n+"-URI-AutoEncoded","true")}}}function An(t){if(t.responseURL){try{const e=new URL(t.responseURL);return e.pathname+e.search}catch(e){fe(te().body,"htmx:badResponseUrl",{url:t.responseURL})}}}function T(e,t){return t.test(e.getAllResponseHeaders())}function Ln(t,n,r){t=t.toLowerCase();if(r){if(r instanceof Element||typeof r==="string"){return he(t,n,null,null,{targetOverride:w(r)||ve,returnPromise:true})}else{let e=w(r.target);if(r.target&&!e||r.source&&!e&&!w(r.source)){e=ve}return he(t,n,w(r.source),r.event,{handler:r.handler,headers:r.headers,values:r.values,targetOverride:e,swapOverride:r.swap,select:r.select,returnPromise:true,push:r.push,replace:r.replace,selectOOB:r.selectOOB})}}else{return he(t,n,null,null,{returnPromise:true})}}function Nn(e){const t=[];while(e){t.push(e);e=e.parentElement}return t}function In(e,t,n){const r=new URL(t,location.protocol!=="about:"?location.href:window.origin);const o=location.protocol!=="about:"?location.origin:window.origin;const i=o===r.origin;if(Q.config.selfRequestsOnly){if(!i){return false}}return ae(e,"htmx:validateUrl",le({url:r,sameHost:i},n))}function Dn(e){if(e instanceof FormData)return e;const t=new FormData;for(const n in e){if(e.hasOwnProperty(n)){if(e[n]&&typeof e[n].forEach==="function"){e[n].forEach(function(e){t.append(n,e)})}else if(typeof e[n]==="object"&&!(e[n]instanceof Blob)){t.append(n,JSON.stringify(e[n]))}else{t.append(n,e[n])}}}return t}function Pn(r,o,e){return new Proxy(e,{get:function(t,e){if(typeof e==="number")return t[e];if(e==="length")return t.length;if(e==="push"){return function(e){t.push(e);r.append(o,e)}}if(typeof t[e]==="function"){return function(){t[e].apply(t,arguments);r.delete(o);t.forEach(function(e){r.append(o,e)})}}if(t[e]&&t[e].length===1){return t[e][0]}else{return t[e]}},set:function(e,t,n){e[t]=n;r.delete(o);e.forEach(function(e){r.append(o,e)});return true}})}function kn(o){return new Proxy(o,{get:function(e,t){if(typeof t==="symbol"){const r=Reflect.get(e,t);if(typeof r==="function"){return function(){return r.apply(o,arguments)}}else{return r}}if(t==="toJSON"){return()=>Object.fromEntries(o)}if(t in e){if(typeof e[t]==="function"){return function(){return o[t].apply(o,arguments)}}}const n=o.getAll(t);if(n.length===0){return undefined}else if(n.length===1){return n[0]}else{return Pn(e,t,n)}},set:function(t,n,e){if(typeof n!=="string"){return false}t.delete(n);if(e&&typeof e.forEach==="function"){e.forEach(function(e){t.append(n,e)})}else if(typeof e==="object"&&!(e instanceof Blob)){t.append(n,JSON.stringify(e))}else{t.append(n,e)}return true},deleteProperty:function(e,t){if(typeof t==="string"){e.delete(t)}return true},ownKeys:function(e){return Reflect.ownKeys(Object.fromEntries(e))},getOwnPropertyDescriptor:function(e,t){return Reflect.getOwnPropertyDescriptor(Object.fromEntries(e),t)}})}function he(t,n,r,o,i,k){let s=null;let l=null;i=i!=null?i:{};if(i.returnPromise&&typeof Promise!=="undefined"){var e=new Promise(function(e,t){s=e;l=t})}if(r==null){r=te().body}const M=i.handler||Vn;const F=i.select||null;if(!se(r)){re(s);return e}const c=i.targetOverride||ce(Ee(r));if(c==null||c==ve){fe(r,"htmx:targetError",{target:ne(r,"hx-target")});re(l);return e}let u=oe(r);const f=u.lastButtonClicked;if(f){const A=ee(f,"formaction");if(A!=null){n=A}const L=ee(f,"formmethod");if(L!=null){if(de.includes(L.toLowerCase())){t=L}else{re(s);return e}}}const a=ne(r,"hx-confirm");if(k===undefined){const K=function(e){return he(t,n,r,o,i,!!e)};const G={target:c,elt:r,path:n,verb:t,triggeringEvent:o,etc:i,issueRequest:K,question:a};if(ae(r,"htmx:confirm",G)===false){re(s);return e}}let h=r;let d=ne(r,"hx-sync");let p=null;let B=false;if(d){const N=d.split(":");const I=N[0].trim();if(I==="this"){h=Se(r,"hx-sync")}else{h=ce(ue(r,I))}d=(N[1]||"drop").trim();u=oe(h);if(d==="drop"&&u.xhr&&u.abortable!==true){re(s);return e}else if(d==="abort"){if(u.xhr){re(s);return e}else{B=true}}else if(d==="replace"){ae(h,"htmx:abort")}else if(d.indexOf("queue")===0){const W=d.split(" ");p=(W[1]||"last").trim()}}if(u.xhr){if(u.abortable){ae(h,"htmx:abort")}else{if(p==null){if(o){const D=oe(o);if(D&&D.triggerSpec&&D.triggerSpec.queue){p=D.triggerSpec.queue}}if(p==null){p="last"}}if(u.queuedRequests==null){u.queuedRequests=[]}if(p==="first"&&u.queuedRequests.length===0){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="all"){u.queuedRequests.push(function(){he(t,n,r,o,i)})}else if(p==="last"){u.queuedRequests=[];u.queuedRequests.push(function(){he(t,n,r,o,i)})}re(s);return e}}const g=new XMLHttpRequest;u.xhr=g;u.abortable=B;const m=function(){u.xhr=null;u.abortable=false;if(u.queuedRequests!=null&&u.queuedRequests.length>0){const e=u.queuedRequests.shift();e()}};const X=ne(r,"hx-prompt");if(X){var y=prompt(X);if(y===null||!ae(r,"htmx:prompt",{prompt:y,target:c})){re(s);m();return e}}if(a&&!k){if(!confirm(a)){re(s);m();return e}}let x=mn(r,c,y);if(t!=="get"&&!vn(r)){x["Content-Type"]="application/x-www-form-urlencoded"}if(i.headers){x=le(x,i.headers)}const U=dn(r,t);let b=U.errors;const V=U.formData;if(i.values){hn(V,Dn(i.values))}const j=Dn(Rn(r,o));const v=hn(V,j);let w=yn(v,r);if(Q.config.getCacheBusterParam&&t==="get"){w.set("org.htmx.cache-buster",ee(c,"id")||"true")}if(n==null||n===""){n=location.href}const S=Cn(r,"hx-request");const $=oe(r).boosted;let E=Q.config.methodsThatUseUrlParams.indexOf(t)>=0;const C={boosted:$,useUrlParams:E,formData:w,parameters:kn(w),unfilteredFormData:v,unfilteredParameters:kn(v),headers:x,elt:r,target:c,verb:t,errors:b,withCredentials:i.credentials||S.credentials||Q.config.withCredentials,timeout:i.timeout||S.timeout||Q.config.timeout,path:n,triggeringEvent:o};if(!ae(r,"htmx:configRequest",C)){re(s);m();return e}n=C.path;t=C.verb;x=C.headers;w=Dn(C.parameters);b=C.errors;E=C.useUrlParams;if(b&&b.length>0){ae(r,"htmx:validation:halted",C);re(s);m();return e}const _=n.split("#");const z=_[0];const O=_[1];let H=n;if(E){H=z;const Z=!w.keys().next().done;if(Z){if(H.indexOf("?")<0){H+="?"}else{H+="&"}H+=gn(w);if(O){H+="#"+O}}}if(!In(r,H,C)){fe(r,"htmx:invalidPath",C);re(l);m();return e}g.open(t.toUpperCase(),H,true);g.overrideMimeType("text/html");g.withCredentials=C.withCredentials;g.timeout=C.timeout;if(S.noHeaders){}else{for(const P in x){if(x.hasOwnProperty(P)){const Y=x[P];qn(g,P,Y)}}}const T={xhr:g,target:c,requestConfig:C,etc:i,boosted:$,select:F,pathInfo:{requestPath:n,finalRequestPath:H,responsePath:null,anchor:O}};g.onload=function(){try{const t=Nn(r);T.pathInfo.responsePath=An(g);M(r,T);if(T.keepIndicators!==true){rn(R,q)}ae(r,"htmx:afterRequest",T);ae(r,"htmx:afterOnLoad",T);if(!se(r)){let e=null;while(t.length>0&&e==null){const n=t.shift();if(se(n)){e=n}}if(e){ae(e,"htmx:afterRequest",T);ae(e,"htmx:afterOnLoad",T)}}re(s)}catch(e){fe(r,"htmx:onLoadError",le({error:e},T));throw e}finally{m()}};g.onerror=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendError",T);re(l);m()};g.onabort=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:sendAbort",T);re(l);m()};g.ontimeout=function(){rn(R,q);fe(r,"htmx:afterRequest",T);fe(r,"htmx:timeout",T);re(l);m()};if(!ae(r,"htmx:beforeRequest",T)){re(s);m();return e}var R=tn(r);var q=nn(r);ie(["loadstart","loadend","progress","abort"],function(t){ie([g,g.upload],function(e){e.addEventListener(t,function(e){ae(r,"htmx:xhr:"+t,{lengthComputable:e.lengthComputable,loaded:e.loaded,total:e.total})})})});ae(r,"htmx:beforeSend",T);const J=E?null:wn(g,r,w);g.send(J);return e}function Mn(e,t){const n=t.xhr;let r=null;let o=null;if(T(n,/HX-Push:/i)){r=n.getResponseHeader("HX-Push");o="push"}else if(T(n,/HX-Push-Url:/i)){r=n.getResponseHeader("HX-Push-Url");o="push"}else if(T(n,/HX-Replace-Url:/i)){r=n.getResponseHeader("HX-Replace-Url");o="replace"}if(r){if(r==="false"){return{}}else{return{type:o,path:r}}}const i=t.pathInfo.finalRequestPath;const s=t.pathInfo.responsePath;const l=t.etc.push||ne(e,"hx-push-url");const c=t.etc.replace||ne(e,"hx-replace-url");const u=oe(e).boosted;let f=null;let a=null;if(l){f="push";a=l}else if(c){f="replace";a=c}else if(u){f="push";a=s||i}if(a){if(a==="false"){return{}}if(a==="true"){a=s||i}if(t.pathInfo.anchor&&a.indexOf("#")===-1){a=a+"#"+t.pathInfo.anchor}return{type:f,path:a}}else{return{}}}function Fn(e,t){var n=new RegExp(e.code);return n.test(t.toString(10))}function Bn(e){for(var t=0;t`+`.${t}{opacity:0;visibility: hidden} `+`.${n} .${t}, .${n}.${t}{opacity:1;visibility: visible;transition: opacity 200ms ease-in}`+"")}}function Zn(){const e=te().querySelector('meta[name="htmx-config"]');if(e){return v(e.content)}else{return null}}function Yn(){const e=Zn();if(e){Q.config=le(Q.config,e)}}Gn(function(){Yn();Wn();let e=te().body;Ft(e);const t=te().querySelectorAll("[hx-trigger='restored'],[data-hx-trigger='restored']");e.addEventListener("htmx:abort",function(e){const t=e.detail.elt||e.target;const n=oe(t);if(n&&n.xhr){n.xhr.abort()}});const n=window.onpopstate?window.onpopstate.bind(window):null;window.onpopstate=function(e){if(e.state&&e.state.htmx){en();ie(t,function(e){ae(e,"htmx:restored",{document:te(),triggerEvent:ae})})}else{if(n){n(e)}}};b().setTimeout(function(){ae(e,"htmx:load",{});e=null},0)});return Q}();
\ No newline at end of file
diff --git a/crates/servable/htmx/json-enc-1.9.12.js b/crates/servable/htmx/json-enc-1.9.12.js
new file mode 100644
index 0000000..f37a9c5
--- /dev/null
+++ b/crates/servable/htmx/json-enc-1.9.12.js
@@ -0,0 +1,11 @@
+htmx.defineExtension('json-enc', {
+ onEvent: function (name, evt) {
+ if (name === "htmx:configRequest") {
+ evt.detail.headers['Content-Type'] = "application/json";
+ }
+ },
+ encodeParameters: function (xhr, parameters, elt) {
+ xhr.overrideMimeType('text/json');
+ return (JSON.stringify(parameters));
+ }
+});
\ No newline at end of file
diff --git a/crates/servable/src/lib.rs b/crates/servable/src/lib.rs
new file mode 100644
index 0000000..8604905
--- /dev/null
+++ b/crates/servable/src/lib.rs
@@ -0,0 +1,56 @@
+#![doc = include_str!("../README.md")]
+
+pub mod mime;
+
+mod types;
+
+use rand::{Rng, distr::Alphanumeric};
+pub use types::*;
+
+mod router;
+pub use router::*;
+
+mod servable;
+pub use servable::*;
+
+#[cfg(test)] // Used in doctests
+use tower_http as _;
+
+//
+//
+//
+
+#[cfg(feature = "image")]
+pub mod transform;
+
+/// A unique string that can be used for cache-busting.
+///
+/// Note that this string changes every time this code is started,
+/// even if the data inside the program did not change.
+pub static CACHE_BUST_STR: std::sync::LazyLock = std::sync::LazyLock::new(|| {
+ rand::rng()
+ .sample_iter(&Alphanumeric)
+ .take(10)
+ .map(char::from)
+ .collect()
+});
+
+//
+//
+//
+
+/// HTMX 2.0.8, minified
+#[cfg(feature = "htmx-2.0.8")]
+pub const HTMX_2_0_8: servable::StaticAsset = servable::StaticAsset {
+ bytes: include_str!("../htmx/htmx-2.0.8.min.js").as_bytes(),
+ mime: mime::MimeType::Javascript,
+};
+
+/// HTMX json extension, 1.19.2.
+/// Compatible with:
+/// - [HTMX_2_0_8]
+#[cfg(feature = "htmx-2.0.8")]
+pub const EXT_JSON_1_19_12: servable::StaticAsset = servable::StaticAsset {
+ bytes: include_str!("../htmx/json-enc-1.9.12.js").as_bytes(),
+ mime: mime::MimeType::Javascript,
+};
diff --git a/crates/servable/src/mime.rs b/crates/servable/src/mime.rs
new file mode 100644
index 0000000..476f569
--- /dev/null
+++ b/crates/servable/src/mime.rs
@@ -0,0 +1,811 @@
+//! Strongly-typed MIME types via [MimeType].
+
+use serde::{Deserialize, Deserializer, Serialize, Serializer};
+use std::{fmt::Display, str::FromStr};
+use tracing::debug;
+
+/// A media type, conveniently parsed
+#[derive(Debug, PartialEq, Eq, Clone)]
+pub enum MimeType {
+ /// A mimetype we didn't recognize
+ Other(String),
+
+ /// An unstructured binary blob (application/octet-stream)
+ Blob,
+
+ // MARK: Audio
+ /// AAC audio file (audio/aac)
+ Aac,
+ /// FLAC audio file (audio/flac)
+ Flac,
+ /// MIDI audio file (audio/midi)
+ Midi,
+ /// MP3 audio file (audio/mpeg)
+ Mp3,
+ /// OGG audio file (audio/ogg)
+ Oga,
+ /// Opus audio file in Ogg container (audio/ogg)
+ Opus,
+ /// Waveform Audio Format (audio/wav)
+ Wav,
+ /// WEBM audio file (audio/webm)
+ Weba,
+
+ // MARK: Video
+ /// AVI: Audio Video Interleave (video/x-msvideo)
+ Avi,
+ /// MP4 video file (video/mp4)
+ Mp4,
+ /// MPEG video file (video/mpeg)
+ Mpeg,
+ /// OGG video file (video/ogg)
+ Ogv,
+ /// MPEG transport stream (video/mp2t)
+ Ts,
+ /// WEBM video file (video/webm)
+ WebmVideo,
+ /// 3GPP audio/video container (video/3gpp)
+ ThreeGp,
+ /// 3GPP2 audio/video container (video/3gpp2)
+ ThreeG2,
+
+ // MARK: Images
+ /// Animated Portable Network Graphics (image/apng)
+ Apng,
+ /// AVIF image (image/avif)
+ Avif,
+ /// Windows OS/2 Bitmap Graphics (image/bmp)
+ Bmp,
+ /// Graphics Interchange Format (image/gif)
+ Gif,
+ /// Icon format (image/vnd.microsoft.icon)
+ Ico,
+ /// JPEG image (image/jpeg)
+ Jpg,
+ /// Portable Network Graphics (image/png)
+ Png,
+ /// Quite ok Image Format
+ Qoi,
+ /// Scalable Vector Graphics (image/svg+xml)
+ Svg,
+ /// Tagged Image File Format (image/tiff)
+ Tiff,
+ /// WEBP image (image/webp)
+ Webp,
+
+ // MARK: Text
+ /// Plain text (text/plain)
+ Text,
+ /// Cascading Style Sheets (text/css)
+ Css,
+ /// Comma-separated values (text/csv)
+ Csv,
+ /// HyperText Markup Language (text/html)
+ Html,
+ /// JavaScript (text/javascript)
+ Javascript,
+ /// JSON format (application/json)
+ Json,
+ /// JSON-LD format (application/ld+json)
+ JsonLd,
+ /// XML (application/xml)
+ Xml,
+
+ // MARK: Documents
+ /// Adobe Portable Document Format (application/pdf)
+ Pdf,
+ /// Rich Text Format (application/rtf)
+ Rtf,
+
+ // MARK: Archives
+ /// Archive document, multiple files embedded (application/x-freearc)
+ Arc,
+ /// BZip archive (application/x-bzip)
+ Bz,
+ /// BZip2 archive (application/x-bzip2)
+ Bz2,
+ /// GZip Compressed Archive (application/gzip)
+ Gz,
+ /// Java Archive (application/java-archive)
+ Jar,
+ /// OGG (application/ogg)
+ Ogg,
+ /// RAR archive (application/vnd.rar)
+ Rar,
+ /// 7-zip archive (application/x-7z-compressed)
+ SevenZ,
+ /// Tape Archive (application/x-tar)
+ Tar,
+ /// ZIP archive (application/zip)
+ Zip,
+
+ // MARK: Fonts
+ /// MS Embedded OpenType fonts (application/vnd.ms-fontobject)
+ Eot,
+ /// OpenType font (font/otf)
+ Otf,
+ /// TrueType Font (font/ttf)
+ Ttf,
+ /// Web Open Font Format (font/woff)
+ Woff,
+ /// Web Open Font Format 2 (font/woff2)
+ Woff2,
+
+ // MARK: Applications
+ /// AbiWord document (application/x-abiword)
+ Abiword,
+ /// Amazon Kindle eBook format (application/vnd.amazon.ebook)
+ Azw,
+ /// CD audio (application/x-cdf)
+ Cda,
+ /// C-Shell script (application/x-csh)
+ Csh,
+ /// Microsoft Word (application/msword)
+ Doc,
+ /// Microsoft Word OpenXML (application/vnd.openxmlformats-officedocument.wordprocessingml.document)
+ Docx,
+ /// Electronic publication (application/epub+zip)
+ Epub,
+ /// iCalendar format (text/calendar)
+ Ics,
+ /// Apple Installer Package (application/vnd.apple.installer+xml)
+ Mpkg,
+ /// OpenDocument presentation (application/vnd.oasis.opendocument.presentation)
+ Odp,
+ /// OpenDocument spreadsheet (application/vnd.oasis.opendocument.spreadsheet)
+ Ods,
+ /// OpenDocument text document (application/vnd.oasis.opendocument.text)
+ Odt,
+ /// Hypertext Preprocessor (application/x-httpd-php)
+ Php,
+ /// Microsoft PowerPoint (application/vnd.ms-powerpoint)
+ Ppt,
+ /// Microsoft PowerPoint OpenXML (application/vnd.openxmlformats-officedocument.presentationml.presentation)
+ Pptx,
+ /// Bourne shell script (application/x-sh)
+ Sh,
+ /// Microsoft Visio (application/vnd.visio)
+ Vsd,
+ /// XHTML (application/xhtml+xml)
+ Xhtml,
+ /// Microsoft Excel (application/vnd.ms-excel)
+ Xls,
+ /// Microsoft Excel OpenXML (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)
+ Xlsx,
+ /// XUL (application/vnd.mozilla.xul+xml)
+ Xul,
+}
+
+// MARK: ser/de
+
+/*
+impl utoipa::ToSchema for MimeType {
+ fn name() -> std::borrow::Cow<'static, str> {
+ std::borrow::Cow::Borrowed("MimeType")
+ }
+}
+impl utoipa::PartialSchema for MimeType {
+ fn schema() -> utoipa::openapi::RefOr {
+ utoipa::openapi::Schema::Object(
+ utoipa::openapi::schema::ObjectBuilder::new()
+ .schema_type(utoipa::openapi::schema::SchemaType::Type(Type::String))
+ .description(Some(
+ "A media type string (e.g., 'application/json', 'text/plain')",
+ ))
+ .examples(Some("application/json"))
+ .build(),
+ )
+ .into()
+ }
+}
+*/
+
+impl Serialize for MimeType {
+ fn serialize(&self, serializer: S) -> Result
+ where
+ S: Serializer,
+ {
+ serializer.serialize_str(&self.to_string())
+ }
+}
+
+impl<'de> Deserialize<'de> for MimeType {
+ fn deserialize(deserializer: D) -> Result
+ where
+ D: Deserializer<'de>,
+ {
+ let s = String::deserialize(deserializer)?;
+ Ok(MimeType::from_str(&s).unwrap())
+ }
+}
+
+//
+// MARK: misc
+//
+
+impl Default for MimeType {
+ fn default() -> Self {
+ Self::Blob
+ }
+}
+
+impl From for MimeType {
+ fn from(value: String) -> Self {
+ Self::from_str(&value).unwrap()
+ }
+}
+
+impl From<&str> for MimeType {
+ fn from(value: &str) -> Self {
+ Self::from_str(value).unwrap()
+ }
+}
+
+impl From<&MimeType> for String {
+ fn from(value: &MimeType) -> Self {
+ value.to_string()
+ }
+}
+
+//
+// MARK: fromstr
+//
+
+impl MimeType {
+ /// Parse a mimetype from a string that may contain
+ /// whitespace or ";" parameters.
+ ///
+ /// Parameters are discarded, write your own parser if you need them.
+ pub fn from_header(s: &str) -> Result::Err> {
+ let s = s.trim();
+ let semi = s.find(';').unwrap_or(s.len());
+ let space = s.find(' ').unwrap_or(s.len());
+ let limit = semi.min(space);
+ let s = &s[0..limit];
+ let s = s.trim();
+
+ return Self::from_str(s);
+ }
+}
+
+impl FromStr for MimeType {
+ type Err = std::convert::Infallible;
+
+ // Must match `display` below, but may provide other alternatives.
+ fn from_str(s: &str) -> Result {
+ Ok(match s {
+ "application/octet-stream" => Self::Blob,
+
+ // Audio
+ "audio/aac" => Self::Aac,
+ "audio/flac" => Self::Flac,
+ "audio/midi" | "audio/x-midi" => Self::Midi,
+ "audio/mpeg" => Self::Mp3,
+ "audio/ogg" => Self::Oga,
+ "audio/wav" => Self::Wav,
+ "audio/webm" => Self::Weba,
+
+ // Video
+ "video/x-msvideo" => Self::Avi,
+ "video/mp4" => Self::Mp4,
+ "video/mpeg" => Self::Mpeg,
+ "video/ogg" => Self::Ogv,
+ "video/mp2t" => Self::Ts,
+ "video/webm" => Self::WebmVideo,
+ "video/3gpp" => Self::ThreeGp,
+ "video/3gpp2" => Self::ThreeG2,
+
+ // Images
+ "image/apng" => Self::Apng,
+ "image/avif" => Self::Avif,
+ "image/bmp" => Self::Bmp,
+ "image/gif" => Self::Gif,
+ "image/vnd.microsoft.icon" => Self::Ico,
+ "image/jpeg" | "image/jpg" => Self::Jpg,
+ "image/png" => Self::Png,
+ "image/svg+xml" => Self::Svg,
+ "image/tiff" => Self::Tiff,
+ "image/webp" => Self::Webp,
+ "image/qoi" => Self::Qoi,
+
+ // Text
+ "text/plain" => Self::Text,
+ "text/css" => Self::Css,
+ "text/csv" => Self::Csv,
+ "text/html" => Self::Html,
+ "text/javascript" => Self::Javascript,
+ "application/json" => Self::Json,
+ "application/ld+json" => Self::JsonLd,
+ "application/xml" | "text/xml" => Self::Xml,
+
+ // Documents
+ "application/pdf" => Self::Pdf,
+ "application/rtf" => Self::Rtf,
+
+ // Archives
+ "application/x-freearc" => Self::Arc,
+ "application/x-bzip" => Self::Bz,
+ "application/x-bzip2" => Self::Bz2,
+ "application/gzip" | "application/x-gzip" => Self::Gz,
+ "application/java-archive" => Self::Jar,
+ "application/ogg" => Self::Ogg,
+ "application/vnd.rar" => Self::Rar,
+ "application/x-7z-compressed" => Self::SevenZ,
+ "application/x-tar" => Self::Tar,
+ "application/zip" | "application/x-zip-compressed" => Self::Zip,
+
+ // Fonts
+ "application/vnd.ms-fontobject" => Self::Eot,
+ "font/otf" => Self::Otf,
+ "font/ttf" => Self::Ttf,
+ "font/woff" => Self::Woff,
+ "font/woff2" => Self::Woff2,
+
+ // Applications
+ "application/x-abiword" => Self::Abiword,
+ "application/vnd.amazon.ebook" => Self::Azw,
+ "application/x-cdf" => Self::Cda,
+ "application/x-csh" => Self::Csh,
+ "application/msword" => Self::Doc,
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document" => Self::Docx,
+ "application/epub+zip" => Self::Epub,
+ "text/calendar" => Self::Ics,
+ "application/vnd.apple.installer+xml" => Self::Mpkg,
+ "application/vnd.oasis.opendocument.presentation" => Self::Odp,
+ "application/vnd.oasis.opendocument.spreadsheet" => Self::Ods,
+ "application/vnd.oasis.opendocument.text" => Self::Odt,
+ "application/x-httpd-php" => Self::Php,
+ "application/vnd.ms-powerpoint" => Self::Ppt,
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation" => {
+ Self::Pptx
+ }
+ "application/x-sh" => Self::Sh,
+ "application/vnd.visio" => Self::Vsd,
+ "application/xhtml+xml" => Self::Xhtml,
+ "application/vnd.ms-excel" => Self::Xls,
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" => Self::Xlsx,
+ "application/vnd.mozilla.xul+xml" => Self::Xul,
+
+ _ => {
+ debug!(message = "Encountered unknown mimetype", mime_string = s);
+ Self::Other(s.into())
+ }
+ })
+ }
+}
+
+//
+// MARK: display
+//
+
+impl Display for MimeType {
+ /// Get a string representation of this mimetype.
+ ///
+ /// The following always holds:
+ /// ```rust
+ /// # use servable::mime::MimeType;
+ /// # let x = MimeType::Blob;
+ /// assert_eq!(MimeType::from(x.to_string()), x);
+ /// ```
+ ///
+ /// The following might not hold:
+ /// ```rust
+ /// # use servable::mime::MimeType;
+ /// # let y = "application/custom";
+ /// // MimeType::from(y).to_string() may not equal y
+ /// ```
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Blob => write!(f, "application/octet-stream"),
+
+ // Audio
+ Self::Aac => write!(f, "audio/aac"),
+ Self::Flac => write!(f, "audio/flac"),
+ Self::Midi => write!(f, "audio/midi"),
+ Self::Mp3 => write!(f, "audio/mpeg"),
+ Self::Oga => write!(f, "audio/ogg"),
+ Self::Opus => write!(f, "audio/ogg"),
+ Self::Wav => write!(f, "audio/wav"),
+ Self::Weba => write!(f, "audio/webm"),
+
+ // Video
+ Self::Avi => write!(f, "video/x-msvideo"),
+ Self::Mp4 => write!(f, "video/mp4"),
+ Self::Mpeg => write!(f, "video/mpeg"),
+ Self::Ogv => write!(f, "video/ogg"),
+ Self::Ts => write!(f, "video/mp2t"),
+ Self::WebmVideo => write!(f, "video/webm"),
+ Self::ThreeGp => write!(f, "video/3gpp"),
+ Self::ThreeG2 => write!(f, "video/3gpp2"),
+
+ // Images
+ Self::Apng => write!(f, "image/apng"),
+ Self::Avif => write!(f, "image/avif"),
+ Self::Bmp => write!(f, "image/bmp"),
+ Self::Gif => write!(f, "image/gif"),
+ Self::Ico => write!(f, "image/vnd.microsoft.icon"),
+ Self::Jpg => write!(f, "image/jpeg"),
+ Self::Png => write!(f, "image/png"),
+ Self::Svg => write!(f, "image/svg+xml"),
+ Self::Tiff => write!(f, "image/tiff"),
+ Self::Webp => write!(f, "image/webp"),
+ Self::Qoi => write!(f, "image/qoi"),
+
+ // Text
+ Self::Text => write!(f, "text/plain"),
+ Self::Css => write!(f, "text/css"),
+ Self::Csv => write!(f, "text/csv"),
+ Self::Html => write!(f, "text/html"),
+ Self::Javascript => write!(f, "text/javascript"),
+ Self::Json => write!(f, "application/json"),
+ Self::JsonLd => write!(f, "application/ld+json"),
+ Self::Xml => write!(f, "application/xml"),
+
+ // Documents
+ Self::Pdf => write!(f, "application/pdf"),
+ Self::Rtf => write!(f, "application/rtf"),
+
+ // Archives
+ Self::Arc => write!(f, "application/x-freearc"),
+ Self::Bz => write!(f, "application/x-bzip"),
+ Self::Bz2 => write!(f, "application/x-bzip2"),
+ Self::Gz => write!(f, "application/gzip"),
+ Self::Jar => write!(f, "application/java-archive"),
+ Self::Ogg => write!(f, "application/ogg"),
+ Self::Rar => write!(f, "application/vnd.rar"),
+ Self::SevenZ => write!(f, "application/x-7z-compressed"),
+ Self::Tar => write!(f, "application/x-tar"),
+ Self::Zip => write!(f, "application/zip"),
+
+ // Fonts
+ Self::Eot => write!(f, "application/vnd.ms-fontobject"),
+ Self::Otf => write!(f, "font/otf"),
+ Self::Ttf => write!(f, "font/ttf"),
+ Self::Woff => write!(f, "font/woff"),
+ Self::Woff2 => write!(f, "font/woff2"),
+
+ // Applications
+ Self::Abiword => write!(f, "application/x-abiword"),
+ Self::Azw => write!(f, "application/vnd.amazon.ebook"),
+ Self::Cda => write!(f, "application/x-cdf"),
+ Self::Csh => write!(f, "application/x-csh"),
+ Self::Doc => write!(f, "application/msword"),
+ Self::Docx => write!(
+ f,
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
+ ),
+ Self::Epub => write!(f, "application/epub+zip"),
+ Self::Ics => write!(f, "text/calendar"),
+ Self::Mpkg => write!(f, "application/vnd.apple.installer+xml"),
+ Self::Odp => write!(f, "application/vnd.oasis.opendocument.presentation"),
+ Self::Ods => write!(f, "application/vnd.oasis.opendocument.spreadsheet"),
+ Self::Odt => write!(f, "application/vnd.oasis.opendocument.text"),
+ Self::Php => write!(f, "application/x-httpd-php"),
+ Self::Ppt => write!(f, "application/vnd.ms-powerpoint"),
+ Self::Pptx => write!(
+ f,
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation"
+ ),
+ Self::Sh => write!(f, "application/x-sh"),
+ Self::Vsd => write!(f, "application/vnd.visio"),
+ Self::Xhtml => write!(f, "application/xhtml+xml"),
+ Self::Xls => write!(f, "application/vnd.ms-excel"),
+ Self::Xlsx => write!(
+ f,
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
+ ),
+ Self::Xul => write!(f, "application/vnd.mozilla.xul+xml"),
+
+ Self::Other(x) => write!(f, "{x}"),
+ }
+ }
+}
+
+impl MimeType {
+ //
+ // MARK: from extension
+ //
+
+ /// Try to guess a file's mime type from its extension.
+ /// `ext` should NOT start with a dot.
+ pub fn from_extension(ext: &str) -> Option {
+ Some(match ext {
+ // Audio
+ "aac" => Self::Aac,
+ "flac" => Self::Flac,
+ "mid" | "midi" => Self::Midi,
+ "mp3" => Self::Mp3,
+ "oga" => Self::Oga,
+ "opus" => Self::Opus,
+ "wav" => Self::Wav,
+ "weba" => Self::Weba,
+
+ // Video
+ "avi" => Self::Avi,
+ "mp4" => Self::Mp4,
+ "mpeg" => Self::Mpeg,
+ "ogv" => Self::Ogv,
+ "ts" => Self::Ts,
+ "webm" => Self::WebmVideo,
+ "3gp" => Self::ThreeGp,
+ "3g2" => Self::ThreeG2,
+
+ // Images
+ "apng" => Self::Apng,
+ "avif" => Self::Avif,
+ "bmp" => Self::Bmp,
+ "gif" => Self::Gif,
+ "ico" => Self::Ico,
+ "jpg" | "jpeg" => Self::Jpg,
+ "png" => Self::Png,
+ "svg" => Self::Svg,
+ "tif" | "tiff" => Self::Tiff,
+ "webp" => Self::Webp,
+ "qoi" => Self::Qoi,
+
+ // Text
+ "txt" => Self::Text,
+ "css" => Self::Css,
+ "csv" => Self::Csv,
+ "htm" | "html" => Self::Html,
+ "js" | "mjs" => Self::Javascript,
+ "json" => Self::Json,
+ "jsonld" => Self::JsonLd,
+ "xml" => Self::Xml,
+
+ // Documents
+ "pdf" => Self::Pdf,
+ "rtf" => Self::Rtf,
+
+ // Archives
+ "arc" => Self::Arc,
+ "bz" => Self::Bz,
+ "bz2" => Self::Bz2,
+ "gz" => Self::Gz,
+ "jar" => Self::Jar,
+ "ogx" => Self::Ogg,
+ "rar" => Self::Rar,
+ "7z" => Self::SevenZ,
+ "tar" => Self::Tar,
+ "zip" => Self::Zip,
+
+ // Fonts
+ "eot" => Self::Eot,
+ "otf" => Self::Otf,
+ "ttf" => Self::Ttf,
+ "woff" => Self::Woff,
+ "woff2" => Self::Woff2,
+
+ // Applications
+ "abw" => Self::Abiword,
+ "azw" => Self::Azw,
+ "cda" => Self::Cda,
+ "csh" => Self::Csh,
+ "doc" => Self::Doc,
+ "docx" => Self::Docx,
+ "epub" => Self::Epub,
+ "ics" => Self::Ics,
+ "mpkg" => Self::Mpkg,
+ "odp" => Self::Odp,
+ "ods" => Self::Ods,
+ "odt" => Self::Odt,
+ "php" => Self::Php,
+ "ppt" => Self::Ppt,
+ "pptx" => Self::Pptx,
+ "sh" => Self::Sh,
+ "vsd" => Self::Vsd,
+ "xhtml" => Self::Xhtml,
+ "xls" => Self::Xls,
+ "xlsx" => Self::Xlsx,
+ "xul" => Self::Xul,
+
+ _ => return None,
+ })
+ }
+
+ //
+ // MARK: to extension
+ //
+
+ /// Get the extension we use for files with this type.
+ /// Never includes a dot.
+ pub fn extension(&self) -> Option<&'static str> {
+ match self {
+ Self::Blob => None,
+ Self::Other(_) => None,
+
+ // Audio
+ Self::Aac => Some("aac"),
+ Self::Flac => Some("flac"),
+ Self::Midi => Some("midi"),
+ Self::Mp3 => Some("mp3"),
+ Self::Oga => Some("oga"),
+ Self::Opus => Some("opus"),
+ Self::Wav => Some("wav"),
+ Self::Weba => Some("weba"),
+
+ // Video
+ Self::Avi => Some("avi"),
+ Self::Mp4 => Some("mp4"),
+ Self::Mpeg => Some("mpeg"),
+ Self::Ogv => Some("ogv"),
+ Self::Ts => Some("ts"),
+ Self::WebmVideo => Some("webm"),
+ Self::ThreeGp => Some("3gp"),
+ Self::ThreeG2 => Some("3g2"),
+
+ // Images
+ Self::Apng => Some("apng"),
+ Self::Avif => Some("avif"),
+ Self::Bmp => Some("bmp"),
+ Self::Gif => Some("gif"),
+ Self::Ico => Some("ico"),
+ Self::Jpg => Some("jpg"),
+ Self::Png => Some("png"),
+ Self::Svg => Some("svg"),
+ Self::Tiff => Some("tiff"),
+ Self::Webp => Some("webp"),
+ Self::Qoi => Some("qoi"),
+
+ // Text
+ Self::Text => Some("txt"),
+ Self::Css => Some("css"),
+ Self::Csv => Some("csv"),
+ Self::Html => Some("html"),
+ Self::Javascript => Some("js"),
+ Self::Json => Some("json"),
+ Self::JsonLd => Some("jsonld"),
+ Self::Xml => Some("xml"),
+
+ // Documents
+ Self::Pdf => Some("pdf"),
+ Self::Rtf => Some("rtf"),
+
+ // Archives
+ Self::Arc => Some("arc"),
+ Self::Bz => Some("bz"),
+ Self::Bz2 => Some("bz2"),
+ Self::Gz => Some("gz"),
+ Self::Jar => Some("jar"),
+ Self::Ogg => Some("ogx"),
+ Self::Rar => Some("rar"),
+ Self::SevenZ => Some("7z"),
+ Self::Tar => Some("tar"),
+ Self::Zip => Some("zip"),
+
+ // Fonts
+ Self::Eot => Some("eot"),
+ Self::Otf => Some("otf"),
+ Self::Ttf => Some("ttf"),
+ Self::Woff => Some("woff"),
+ Self::Woff2 => Some("woff2"),
+
+ // Applications
+ Self::Abiword => Some("abw"),
+ Self::Azw => Some("azw"),
+ Self::Cda => Some("cda"),
+ Self::Csh => Some("csh"),
+ Self::Doc => Some("doc"),
+ Self::Docx => Some("docx"),
+ Self::Epub => Some("epub"),
+ Self::Ics => Some("ics"),
+ Self::Mpkg => Some("mpkg"),
+ Self::Odp => Some("odp"),
+ Self::Ods => Some("ods"),
+ Self::Odt => Some("odt"),
+ Self::Php => Some("php"),
+ Self::Ppt => Some("ppt"),
+ Self::Pptx => Some("pptx"),
+ Self::Sh => Some("sh"),
+ Self::Vsd => Some("vsd"),
+ Self::Xhtml => Some("xhtml"),
+ Self::Xls => Some("xls"),
+ Self::Xlsx => Some("xlsx"),
+ Self::Xul => Some("xul"),
+ }
+ }
+
+ //
+ // MARK: is_text
+ //
+
+ /// Returns true if this MIME type is always plain text.
+ pub fn is_text(&self) -> bool {
+ match self {
+ // Text types
+ Self::Text => true,
+ Self::Css => true,
+ Self::Csv => true,
+ Self::Html => true,
+ Self::Javascript => true,
+ Self::Json => true,
+ Self::JsonLd => true,
+ Self::Xml => true,
+ Self::Svg => true,
+ Self::Ics => true,
+ Self::Xhtml => true,
+
+ // Script types
+ Self::Csh => true,
+ Self::Php => true,
+ Self::Sh => true,
+
+ // All other types are not plain text
+ Self::Other(_) => false,
+ Self::Blob => false,
+
+ // Audio
+ Self::Aac => false,
+ Self::Flac => false,
+ Self::Midi => false,
+ Self::Mp3 => false,
+ Self::Oga => false,
+ Self::Opus => false,
+ Self::Wav => false,
+ Self::Weba => false,
+
+ // Video
+ Self::Avi => false,
+ Self::Mp4 => false,
+ Self::Mpeg => false,
+ Self::Ogv => false,
+ Self::Ts => false,
+ Self::WebmVideo => false,
+ Self::ThreeGp => false,
+ Self::ThreeG2 => false,
+
+ // Images
+ Self::Apng => false,
+ Self::Avif => false,
+ Self::Bmp => false,
+ Self::Gif => false,
+ Self::Ico => false,
+ Self::Jpg => false,
+ Self::Png => false,
+ Self::Qoi => false,
+ Self::Tiff => false,
+ Self::Webp => false,
+
+ // Documents
+ Self::Pdf => false,
+ Self::Rtf => false,
+
+ // Archives
+ Self::Arc => false,
+ Self::Bz => false,
+ Self::Bz2 => false,
+ Self::Gz => false,
+ Self::Jar => false,
+ Self::Ogg => false,
+ Self::Rar => false,
+ Self::SevenZ => false,
+ Self::Tar => false,
+ Self::Zip => false,
+
+ // Fonts
+ Self::Eot => false,
+ Self::Otf => false,
+ Self::Ttf => false,
+ Self::Woff => false,
+ Self::Woff2 => false,
+
+ // Applications
+ Self::Abiword => false,
+ Self::Azw => false,
+ Self::Cda => false,
+ Self::Doc => false,
+ Self::Docx => false,
+ Self::Epub => false,
+ Self::Mpkg => false,
+ Self::Odp => false,
+ Self::Ods => false,
+ Self::Odt => false,
+ Self::Ppt => false,
+ Self::Pptx => false,
+ Self::Vsd => false,
+ Self::Xls => false,
+ Self::Xlsx => false,
+ Self::Xul => false,
+ }
+ }
+}
diff --git a/crates/servable/src/router.rs b/crates/servable/src/router.rs
new file mode 100644
index 0000000..ba47349
--- /dev/null
+++ b/crates/servable/src/router.rs
@@ -0,0 +1,296 @@
+use axum::{
+ Router,
+ body::Body,
+ http::{HeaderMap, HeaderValue, Method, Request, StatusCode, header},
+ response::{IntoResponse, Response},
+};
+use chrono::TimeDelta;
+use std::{
+ collections::{BTreeMap, HashMap},
+ convert::Infallible,
+ net::SocketAddr,
+ pin::Pin,
+ sync::Arc,
+ task::{Context, Poll},
+ time::Instant,
+};
+use tower::Service;
+use tracing::trace;
+
+use crate::{
+ ClientInfo, RenderContext, Rendered, RenderedBody,
+ mime::MimeType,
+ servable::{Servable, ServableWithRoute},
+};
+
+struct Default404 {}
+
+impl Servable for Default404 {
+ fn head<'a>(
+ &'a self,
+ _ctx: &'a RenderContext,
+ ) -> Pin> + 'a + Send + Sync>> {
+ Box::pin(async {
+ return Rendered {
+ code: StatusCode::NOT_FOUND,
+ body: (),
+ ttl: Some(TimeDelta::days(1)),
+ immutable: true,
+ headers: HeaderMap::new(),
+ mime: Some(MimeType::Html),
+ };
+ })
+ }
+
+ fn render<'a>(
+ &'a self,
+ ctx: &'a RenderContext,
+ ) -> Pin> + 'a + Send + Sync>> {
+ Box::pin(async { self.head(ctx).await.with_body(RenderedBody::Empty) })
+ }
+}
+
+/// A set of related [Servable]s under one route.
+///
+/// Use as follows:
+/// ```rust
+/// use servable::{ServableRouter, StaticAsset, mime::MimeType};
+/// use axum::Router;
+/// use tower_http::compression::{CompressionLayer, predicate::DefaultPredicate};
+///
+/// // Add compression, for example.
+/// // Also consider CORS and timeout.
+/// let compression: CompressionLayer = CompressionLayer::new()
+/// .br(true)
+/// .deflate(true)
+/// .gzip(true)
+/// .zstd(true)
+/// .compress_when(DefaultPredicate::new());
+///
+/// let route = ServableRouter::new()
+/// .add_page(
+/// "/page",
+/// StaticAsset {
+/// bytes: "I am a page".as_bytes(),
+/// mime: MimeType::Text,
+/// },
+/// );
+///
+/// let router: Router<()> = route
+/// .into_router()
+/// .layer(compression.clone());
+/// ```
+#[derive(Clone)]
+pub struct ServableRouter {
+ pages: Arc>>,
+ notfound: Arc,
+}
+
+impl ServableRouter {
+ /// Create a new, empty [ServableRouter]
+ #[inline(always)]
+ pub fn new() -> Self {
+ Self {
+ pages: Arc::new(HashMap::new()),
+ notfound: Arc::new(Default404 {}),
+ }
+ }
+
+ /// Set this server's "not found" page
+ #[inline(always)]
+ pub fn with_404(mut self, page: S) -> Self {
+ self.notfound = Arc::new(page);
+ self
+ }
+
+ /// Add a [Servable] to this server at the given route.
+ /// - panics if route does not start with a `/`, ends with a `/`, or contains `//`.
+ /// - urls are normalized, routes that violate this condition will never be served.
+ /// - `/` is an exception, it is valid.
+ /// - panics if called after this service is started
+ /// - overwrites existing pages
+ #[inline(always)]
+ pub fn add_page(mut self, route: impl Into, page: S) -> Self {
+ let route = route.into();
+
+ if !route.starts_with("/") {
+ panic!("route must start with /")
+ };
+
+ if route.ends_with("/") && route != "/" {
+ panic!("route must not end with /")
+ };
+
+ if route.contains("//") {
+ panic!("route must not contain //")
+ };
+
+ #[expect(clippy::expect_used)]
+ Arc::get_mut(&mut self.pages)
+ .expect("add_pages called after service was started")
+ .insert(route, Arc::new(page));
+
+ self
+ }
+
+ /// Add a [ServableWithRoute] to this server.
+ /// Behaves exactly like [Self::add_page].
+ #[inline(always)]
+ pub fn add_page_with_route(
+ self,
+ servable_with_route: &'static ServableWithRoute,
+ ) -> Self {
+ self.add_page(servable_with_route.route(), servable_with_route)
+ }
+
+ /// Convenience method.
+ /// Turns this service into a router.
+ ///
+ /// Equivalent to:
+ /// ```ignore
+ /// Router::new().fallback_service(self)
+ /// ```
+ #[inline(always)]
+ pub fn into_router(self) -> Router {
+ Router::new().fallback_service(self)
+ }
+}
+
+//
+// MARK: impl Service
+//
+
+impl Service> for ServableRouter {
+ type Response = Response;
+ type Error = Infallible;
+ type Future =
+ Pin> + Send + 'static>>;
+
+ fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> {
+ Poll::Ready(Ok(()))
+ }
+
+ fn call(&mut self, req: Request) -> Self::Future {
+ if req.method() != Method::GET && req.method() != Method::HEAD {
+ let mut headers = HeaderMap::with_capacity(1);
+ headers.insert(header::ACCEPT, HeaderValue::from_static("GET,HEAD"));
+ return Box::pin(async {
+ Ok((StatusCode::METHOD_NOT_ALLOWED, headers).into_response())
+ });
+ }
+
+ let pages = self.pages.clone();
+ let notfound = self.notfound.clone();
+ Box::pin(async move {
+ let addr = req.extensions().get::().copied();
+ let route = req.uri().path().to_owned();
+ let headers = req.headers().clone();
+ let query: BTreeMap =
+ serde_urlencoded::from_str(req.uri().query().unwrap_or("")).unwrap_or_default();
+
+ let start = Instant::now();
+ let client_info = ClientInfo::from_headers(&headers);
+ let ua = headers
+ .get("user-agent")
+ .and_then(|x| x.to_str().ok())
+ .unwrap_or("");
+
+ trace!(
+ message = "Serving route",
+ route,
+ addr = ?addr,
+ user_agent = ua,
+ device_type = ?client_info.device_type
+ );
+
+ // Normalize url with redirect
+ if (route.ends_with('/') && route != "/") || route.contains("//") {
+ let mut new_route = route.clone();
+ while new_route.contains("//") {
+ new_route = new_route.replace("//", "/");
+ }
+ let new_route = new_route.trim_matches('/');
+
+ trace!(
+ message = "Redirecting",
+ route,
+ new_route,
+ addr = ?addr,
+ user_agent = ua,
+ device_type = ?client_info.device_type
+ );
+
+ let mut headers = HeaderMap::with_capacity(1);
+ match HeaderValue::from_str(&format!("/{new_route}")) {
+ Ok(x) => headers.append(header::LOCATION, x),
+ Err(_) => return Ok(StatusCode::BAD_REQUEST.into_response()),
+ };
+ return Ok((StatusCode::PERMANENT_REDIRECT, headers).into_response());
+ }
+
+ let ctx = RenderContext {
+ client_info,
+ route,
+ query,
+ };
+
+ let page = pages.get(&ctx.route).unwrap_or(¬found);
+ let mut rend = match req.method() == Method::HEAD {
+ true => page.head(&ctx).await.with_body(RenderedBody::Empty),
+ false => page.render(&ctx).await,
+ };
+
+ // Tweak headers
+ {
+ if !rend.headers.contains_key(header::CACHE_CONTROL) {
+ let max_age = rend.ttl.map(|x| x.num_seconds()).unwrap_or(1).max(1);
+
+ let mut value = String::new();
+ if rend.immutable {
+ value.push_str("immutable, ");
+ }
+
+ value.push_str("public, ");
+ value.push_str(&format!("max-age={}, ", max_age));
+
+ #[expect(clippy::unwrap_used)]
+ rend.headers.insert(
+ header::CACHE_CONTROL,
+ HeaderValue::from_str(value.trim().trim_end_matches(',')).unwrap(),
+ );
+ }
+
+ if !rend.headers.contains_key("Accept-CH") {
+ rend.headers
+ .insert("Accept-CH", HeaderValue::from_static("Sec-CH-UA-Mobile"));
+ }
+
+ if !rend.headers.contains_key(header::CONTENT_TYPE)
+ && let Some(mime) = &rend.mime
+ {
+ #[expect(clippy::unwrap_used)]
+ rend.headers.insert(
+ header::CONTENT_TYPE,
+ HeaderValue::from_str(&mime.to_string()).unwrap(),
+ );
+ }
+ }
+
+ trace!(
+ message = "Served route",
+ route = ctx.route,
+ addr = ?addr,
+ user_agent = ua,
+ device_type = ?client_info.device_type,
+ time_ns = start.elapsed().as_nanos()
+ );
+
+ Ok(match rend.body {
+ RenderedBody::Static(d) => (rend.code, rend.headers, d).into_response(),
+ RenderedBody::Bytes(d) => (rend.code, rend.headers, d).into_response(),
+ RenderedBody::String(s) => (rend.code, rend.headers, s).into_response(),
+ RenderedBody::Empty => (rend.code, rend.headers).into_response(),
+ })
+ })
+ }
+}
diff --git a/crates/servable/src/servable/asset.rs b/crates/servable/src/servable/asset.rs
new file mode 100644
index 0000000..1596afe
--- /dev/null
+++ b/crates/servable/src/servable/asset.rs
@@ -0,0 +1,213 @@
+use axum::http::{HeaderMap, StatusCode};
+use chrono::TimeDelta;
+use std::pin::Pin;
+
+use crate::{RenderContext, Rendered, RenderedBody, mime::MimeType, servable::Servable};
+
+const TTL: Option = Some(TimeDelta::days(1));
+
+/// A static blob of bytes
+pub struct StaticAsset {
+ /// The data to return
+ pub bytes: &'static [u8],
+
+ /// The type of `bytes`
+ pub mime: MimeType,
+}
+
+#[cfg(feature = "image")]
+impl Servable for StaticAsset {
+ fn head<'a>(
+ &'a self,
+ ctx: &'a RenderContext,
+ ) -> Pin> + 'a + Send + Sync>> {
+ Box::pin(async {
+ use crate::transform::TransformerChain;
+ use std::str::FromStr;
+
+ let is_image = TransformerChain::mime_is_image(&self.mime);
+
+ let transform = match (is_image, ctx.query.get("t")) {
+ (false, _) | (_, None) => None,
+
+ (true, Some(x)) => match TransformerChain::from_str(x) {
+ Ok(x) => Some(x),
+ Err(_err) => {
+ return Rendered {
+ code: StatusCode::BAD_REQUEST,
+ body: (),
+ ttl: TTL,
+ immutable: true,
+
+ headers: HeaderMap::new(),
+ mime: None,
+ };
+ }
+ },
+ };
+
+ match transform {
+ Some(transform) => {
+ return Rendered {
+ code: StatusCode::OK,
+ body: (),
+ ttl: TTL,
+ immutable: true,
+
+ headers: HeaderMap::new(),
+ mime: Some(
+ transform
+ .output_mime(&self.mime)
+ .unwrap_or(self.mime.clone()),
+ ),
+ };
+ }
+
+ None => {
+ return Rendered {
+ code: StatusCode::OK,
+ body: (),
+ ttl: TTL,
+ immutable: true,
+
+ headers: HeaderMap::new(),
+ mime: Some(self.mime.clone()),
+ };
+ }
+ }
+ })
+ }
+
+ fn render<'a>(
+ &'a self,
+ ctx: &'a RenderContext,
+ ) -> Pin> + 'a + Send + Sync>> {
+ Box::pin(async {
+ use crate::transform::TransformerChain;
+ use std::str::FromStr;
+ use tracing::{error, trace};
+
+ // Automatically provide transformation if this is an image
+ let is_image = TransformerChain::mime_is_image(&self.mime);
+
+ let transform = match (is_image, ctx.query.get("t")) {
+ (false, _) | (_, None) => None,
+
+ (true, Some(x)) => match TransformerChain::from_str(x) {
+ Ok(x) => Some(x),
+ Err(err) => {
+ return Rendered {
+ code: StatusCode::BAD_REQUEST,
+ body: RenderedBody::String(err),
+ ttl: TTL,
+ immutable: true,
+
+ headers: HeaderMap::new(),
+ mime: None,
+ };
+ }
+ },
+ };
+
+ match transform {
+ Some(transform) => {
+ trace!(message = "Transforming image", ?transform);
+
+ let task = {
+ let mime = Some(self.mime.clone());
+ let bytes = self.bytes;
+ tokio::task::spawn_blocking(move || {
+ transform.transform_bytes(bytes, mime.as_ref())
+ })
+ };
+
+ let res = match task.await {
+ Ok(x) => x,
+ Err(error) => {
+ error!(message = "Error while transforming image", ?error);
+ return Rendered {
+ code: StatusCode::INTERNAL_SERVER_ERROR,
+ body: RenderedBody::String(format!(
+ "Error while transforming image: {error:?}"
+ )),
+ ttl: None,
+ immutable: true,
+
+ headers: HeaderMap::new(),
+ mime: None,
+ };
+ }
+ };
+
+ match res {
+ Ok((mime, bytes)) => {
+ return Rendered {
+ code: StatusCode::OK,
+ body: RenderedBody::Bytes(bytes),
+ ttl: TTL,
+ immutable: true,
+
+ headers: HeaderMap::new(),
+ mime: Some(mime),
+ };
+ }
+
+ Err(err) => {
+ return Rendered {
+ code: StatusCode::INTERNAL_SERVER_ERROR,
+ body: RenderedBody::String(format!("{err}")),
+ ttl: TTL,
+ immutable: true,
+
+ headers: HeaderMap::new(),
+ mime: None,
+ };
+ }
+ }
+ }
+
+ None => {
+ return Rendered {
+ code: StatusCode::OK,
+ body: RenderedBody::Static(self.bytes),
+ ttl: TTL,
+ immutable: true,
+ headers: HeaderMap::new(),
+ mime: Some(self.mime.clone()),
+ };
+ }
+ }
+ })
+ }
+}
+
+#[cfg(not(feature = "image"))]
+impl Servable for StaticAsset {
+ fn head<'a>(
+ &'a self,
+ _ctx: &'a RenderContext,
+ ) -> Pin> + 'a + Send + Sync>> {
+ Box::pin(async {
+ return Rendered {
+ code: StatusCode::OK,
+ body: (),
+ ttl: TTL,
+ immutable: true,
+
+ headers: HeaderMap::new(),
+ mime: Some(self.mime.clone()),
+ };
+ })
+ }
+
+ fn render<'a>(
+ &'a self,
+ ctx: &'a RenderContext,
+ ) -> Pin> + 'a + Send + Sync>> {
+ Box::pin(async {
+ self.head(ctx)
+ .await
+ .with_body(RenderedBody::Static(self.bytes))
+ })
+ }
+}
diff --git a/crates/servable/src/servable/html.rs b/crates/servable/src/servable/html.rs
new file mode 100644
index 0000000..544beea
--- /dev/null
+++ b/crates/servable/src/servable/html.rs
@@ -0,0 +1,302 @@
+use axum::http::{HeaderMap, StatusCode};
+use chrono::TimeDelta;
+use maud::{DOCTYPE, Markup, PreEscaped, html};
+use serde::Deserialize;
+use std::{hash::Hash, pin::Pin, sync::Arc};
+
+use crate::{RenderContext, Rendered, RenderedBody, mime::MimeType, servable::Servable};
+
+#[expect(missing_docs)]
+#[derive(Debug, Clone, Hash, PartialEq, Eq, Deserialize)]
+pub struct PageMetadata {
+ /// The title of this page.
+ /// Browsers display this on the page's tab.
+ pub title: String,
+
+ /// The page author (metadata only)
+ pub author: Option,
+
+ /// The page description (metadata only)
+ pub description: Option,
+
+ /// The page image.
+ /// Browsers display this on the page's tab.
+ pub image: Option,
+}
+
+impl Default for PageMetadata {
+ fn default() -> Self {
+ Self {
+ title: "Untitled page".into(),
+ author: None,
+ description: None,
+ image: None,
+ }
+ }
+}
+
+#[expect(missing_docs)]
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub enum ScriptSource {
+ /// Raw script data
+ Inline(S),
+
+ /// Load script from a url
+ Linked(S),
+}
+
+/// A complete, dynamically-rendered blob of HTML.
+#[derive(Clone)]
+pub struct HtmlPage {
+ /// This page's metadata
+ pub meta: PageMetadata,
+
+ /// If true, the contents of this page never change
+ pub immutable: bool,
+
+ /// How long this page's html may be cached.
+ /// This controls the maximum age of a page shown to the user.
+ ///
+ /// If `None`, this page is never cached.
+ pub ttl: Option,
+
+ /// A function that generates this page's html.
+ ///
+ /// This should return the contents of this page's tag,
+ /// or the contents of a wrapper element (defined in the page server struct).
+ ///
+ /// This closure must never return `` or ``.
+ pub render: Arc<
+ dyn Send
+ + Sync
+ + 'static
+ + for<'a> Fn(
+ &'a HtmlPage,
+ &'a RenderContext,
+ ) -> Pin + Send + Sync + 'a>>,
+ >,
+
+ /// The response code that should accompany this html
+ pub response_code: StatusCode,
+
+ /// Scripts to include in this page. Order is preserved.
+ pub scripts: Vec>,
+
+ /// Styles to include in this page. Order is preserved.
+ pub styles: Vec>,
+
+ /// `name`, `content` for extra `` tags
+ pub extra_meta: Vec<(String, String)>,
+}
+
+impl Default for HtmlPage {
+ fn default() -> Self {
+ HtmlPage {
+ // No cache by default
+ ttl: None,
+ immutable: false,
+
+ meta: Default::default(),
+ render: Arc::new(|_, _| Box::pin(async { html!() })),
+ response_code: StatusCode::OK,
+ scripts: Vec::new(),
+ styles: Vec::new(),
+ extra_meta: Vec::new(),
+ }
+ }
+}
+
+impl HtmlPage {
+ /// Set `self.meta`
+ #[inline(always)]
+ pub fn with_meta(mut self, meta: PageMetadata) -> Self {
+ self.meta = meta;
+ self
+ }
+
+ /// Set `self.generate`
+ #[inline(always)]
+ pub fn with_render<
+ R: Send
+ + Sync
+ + 'static
+ + for<'a> Fn(
+ &'a HtmlPage,
+ &'a RenderContext,
+ ) -> Pin + Send + Sync + 'a>>,
+ >(
+ mut self,
+ render: R,
+ ) -> Self {
+ self.render = Arc::new(render);
+ self
+ }
+
+ /// Set `self.immutable`
+ #[inline(always)]
+ pub fn with_immutable(mut self, immutable: bool) -> Self {
+ self.immutable = immutable;
+ self
+ }
+
+ /// Set `self.html_ttl`
+ #[inline(always)]
+ pub fn with_ttl(mut self, ttl: Option) -> Self {
+ self.ttl = ttl;
+ self
+ }
+
+ /// Set `self.response_code`
+ #[inline(always)]
+ pub fn with_code(mut self, response_code: StatusCode) -> Self {
+ self.response_code = response_code;
+ self
+ }
+
+ /// Add an inline script to this page (after existing scripts)
+ #[inline(always)]
+ pub fn with_script_inline(mut self, script: impl Into) -> Self {
+ self.scripts.push(ScriptSource::Inline(script.into()));
+ self
+ }
+
+ /// Add a linked script to this page (after existing scripts)
+ #[inline(always)]
+ pub fn with_script_linked(mut self, url: impl Into) -> Self {
+ self.scripts.push(ScriptSource::Linked(url.into()));
+ self
+ }
+
+ /// Add a script to this page (after existing scripts)
+ #[inline(always)]
+ pub fn with_script(mut self, script: ScriptSource>) -> Self {
+ let script = match script {
+ ScriptSource::Inline(x) => ScriptSource::Inline(x.into()),
+ ScriptSource::Linked(x) => ScriptSource::Linked(x.into()),
+ };
+
+ self.scripts.push(script);
+ self
+ }
+
+ /// Add an inline script to this page (after existing styles)
+ #[inline(always)]
+ pub fn with_style_inline(mut self, style: impl Into) -> Self {
+ self.styles.push(ScriptSource::Inline(style.into()));
+ self
+ }
+
+ /// Add a linked style to this page (after existing styles)
+ #[inline(always)]
+ pub fn with_style_linked(mut self, url: impl Into) -> Self {
+ self.styles.push(ScriptSource::Linked(url.into()));
+ self
+ }
+
+ /// Add a style to this page (after existing scripts)
+ #[inline(always)]
+ pub fn with_style(mut self, style: ScriptSource>) -> Self {
+ let style = match style {
+ ScriptSource::Inline(x) => ScriptSource::Inline(x.into()),
+ ScriptSource::Linked(x) => ScriptSource::Linked(x.into()),
+ };
+
+ self.scripts.push(style);
+ self
+ }
+
+ /// Add a `` to this page (after existing `s`)
+ #[inline(always)]
+ pub fn with_extra_meta(mut self, key: impl Into, value: impl Into) -> Self {
+ self.extra_meta.push((key.into(), value.into()));
+ self
+ }
+}
+
+impl Servable for HtmlPage {
+ fn head<'a>(
+ &'a self,
+ _ctx: &'a RenderContext,
+ ) -> Pin> + 'a + Send + Sync>> {
+ Box::pin(async {
+ return Rendered {
+ code: self.response_code,
+ body: (),
+ ttl: self.ttl,
+ immutable: self.immutable,
+ headers: HeaderMap::new(),
+ mime: Some(MimeType::Html),
+ };
+ })
+ }
+
+ fn render<'a>(
+ &'a self,
+ ctx: &'a RenderContext,
+ ) -> Pin> + 'a + Send + Sync>> {
+ Box::pin(async {
+ let inner_html = (self.render)(self, ctx).await;
+
+ let html = html! {
+ (DOCTYPE)
+ html {
+ head {
+ meta charset="UTF-8";
+ meta name="viewport" content="width=device-width, initial-scale=1,user-scalable=no";
+ meta content="text/html; charset=UTF-8" http-equiv="content-type";
+ meta property="og:type" content="website";
+ @for (name, content) in &self.extra_meta {
+ meta name=(name) content=(content);
+ }
+
+ //
+ // Metadata
+ //
+ title { (PreEscaped(self.meta.title.clone())) }
+ meta property="og:site_name" content=(self.meta.title);
+ meta name="title" content=(self.meta.title);
+ meta property="og:title" content=(self.meta.title);
+ meta property="twitter:title" content=(self.meta.title);
+
+ @if let Some(author) = &self.meta.author {
+ meta name="author" content=(author);
+ }
+
+ @if let Some(desc) = &self.meta.description {
+ meta name="description" content=(desc);
+ meta property="og:description" content=(desc);
+ meta property="twitter:description" content=(desc);
+ }
+
+ @if let Some(image) = &self.meta.image {
+ meta content=(image) property="og:image";
+ link rel="shortcut icon" href=(image) type="image/x-icon";
+ }
+
+ //
+ // Scripts & styles
+ //
+
+ @for style in &self.styles {
+ @match style {
+ ScriptSource::Linked(x) => link rel="stylesheet" type="text/css" href=(x);,
+ ScriptSource::Inline(x) => style { (PreEscaped(x)) }
+ }
+ }
+
+ @for script in &self.scripts {
+ @match script {
+ ScriptSource::Linked(x) => script src=(x) {},
+ ScriptSource::Inline(x) => script { (PreEscaped(x)) }
+ }
+ }
+ }
+
+ body { main { (inner_html) } }
+ }
+ };
+
+ return self.head(ctx).await.with_body(RenderedBody::String(html.0));
+ })
+ }
+}
diff --git a/crates/servable/src/servable/mod.rs b/crates/servable/src/servable/mod.rs
new file mode 100644
index 0000000..401bb15
--- /dev/null
+++ b/crates/servable/src/servable/mod.rs
@@ -0,0 +1,123 @@
+//! This module provides the [Servable] trait,
+//! as well as a few helper structs that implement it.
+
+mod asset;
+
+pub use asset::*;
+
+mod html;
+pub use html::*;
+
+mod redirect;
+pub use redirect::*;
+
+/// Something that may be served over http. If implementing this trait,
+/// refer to sample implementations in [redirect::Redirect], [asset::StaticAsset] and [html::HtmlPage].
+pub trait Servable: Send + Sync {
+ /// Return the same response as [Servable::render], but with an empty body.
+ ///
+ /// This method is used to respond to `HEAD` requests.
+ fn head<'a>(
+ &'a self,
+ ctx: &'a crate::RenderContext,
+ ) -> std::pin::Pin> + 'a + Send + Sync>>;
+
+ /// Render this page. Must return the same metadata as [Servable::head].
+ /// Consider using [crate::Rendered::with_body] and [Servable::head] to implement this fn.
+ ///
+ /// This method is used to respond to `GET` requests.
+ fn render<'a>(
+ &'a self,
+ ctx: &'a crate::RenderContext,
+ ) -> std::pin::Pin<
+ Box> + 'a + Send + Sync>,
+ >;
+}
+
+//
+// MARK: ServableWithRoute
+//
+
+/// A [Servable] and the route it is available at
+pub struct ServableWithRoute {
+ /// The resource
+ servable: S,
+
+ /// The route this resource is available at
+ route: std::sync::LazyLock,
+}
+
+impl ServableWithRoute {
+ /// Create a new [ServableWithRoute]
+ pub const fn new(route_init: fn() -> std::string::String, servable: S) -> Self {
+ Self {
+ servable,
+ route: std::sync::LazyLock::new(route_init),
+ }
+ }
+
+ /// Get the route associated with this resource
+ pub fn route(&self) -> &str {
+ &self.route
+ }
+}
+
+impl Servable for ServableWithRoute {
+ #[inline(always)]
+ fn head<'a>(
+ &'a self,
+ ctx: &'a crate::RenderContext,
+ ) -> std::pin::Pin> + 'a + Send + Sync>> {
+ self.servable.head(ctx)
+ }
+
+ #[inline(always)]
+ fn render<'a>(
+ &'a self,
+ ctx: &'a crate::RenderContext,
+ ) -> std::pin::Pin<
+ Box> + 'a + Send + Sync>,
+ > {
+ self.servable.render(ctx)
+ }
+}
+
+impl Servable for &'static S {
+ #[inline(always)]
+ fn head<'a>(
+ &'a self,
+ ctx: &'a crate::RenderContext,
+ ) -> std::pin::Pin> + 'a + Send + Sync>> {
+ (*self).head(ctx)
+ }
+
+ #[inline(always)]
+ fn render<'a>(
+ &'a self,
+ ctx: &'a crate::RenderContext,
+ ) -> std::pin::Pin<
+ Box> + 'a + Send + Sync>,
+ > {
+ (*self).render(ctx)
+ }
+}
+
+impl Servable for std::sync::LazyLock {
+ #[inline(always)]
+ fn head<'a>(
+ &'a self,
+ ctx: &'a crate::RenderContext,
+ ) -> std::pin::Pin> + 'a + Send + Sync>> {
+ (**self).head(ctx)
+ }
+
+ #[inline(always)]
+ fn render<'a>(
+ &'a self,
+ ctx: &'a crate::RenderContext,
+ ) -> std::pin::Pin<
+ Box> + 'a + Send + Sync>,
+ > {
+ (**self).render(ctx)
+ }
+}
diff --git a/crates/servable/src/servable/redirect.rs b/crates/servable/src/servable/redirect.rs
new file mode 100644
index 0000000..35a7870
--- /dev/null
+++ b/crates/servable/src/servable/redirect.rs
@@ -0,0 +1,75 @@
+use std::pin::Pin;
+
+use axum::http::{
+ HeaderMap, HeaderValue, StatusCode,
+ header::{self, InvalidHeaderValue},
+};
+
+use crate::{RenderContext, Rendered, RenderedBody, servable::Servable};
+
+#[expect(missing_docs)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RedirectCode {
+ /// Reply with an http 307 (temporary redirect)
+ Http307,
+
+ /// Reply with an http 308 (permanent redirect)
+ Http308,
+}
+
+/// A simple http edirect
+pub struct Redirect {
+ to: HeaderValue,
+ code: RedirectCode,
+}
+
+impl Redirect {
+ /// Create a new [Redirect] to the given route.
+ /// Returns an http 308 (permanent redirect)
+ pub fn new(to: impl Into) -> Result {
+ Ok(Self {
+ to: HeaderValue::from_str(&to.into())?,
+ code: RedirectCode::Http308,
+ })
+ }
+
+ /// Create a new [Redirect] to the given route.
+ /// Returns an http 307 (temporary redirect)
+ pub fn new_307(to: impl Into) -> Result {
+ Ok(Self {
+ to: HeaderValue::from_str(&to.into())?,
+ code: RedirectCode::Http307,
+ })
+ }
+}
+
+impl Servable for Redirect {
+ fn head<'a>(
+ &'a self,
+ _ctx: &'a RenderContext,
+ ) -> Pin> + 'a + Send + Sync>> {
+ Box::pin(async {
+ let mut headers = HeaderMap::with_capacity(1);
+ headers.append(header::LOCATION, self.to.clone());
+
+ return Rendered {
+ code: match self.code {
+ RedirectCode::Http307 => StatusCode::TEMPORARY_REDIRECT,
+ RedirectCode::Http308 => StatusCode::PERMANENT_REDIRECT,
+ },
+ headers,
+ body: (),
+ ttl: None,
+ immutable: true,
+ mime: None,
+ };
+ })
+ }
+
+ fn render<'a>(
+ &'a self,
+ ctx: &'a RenderContext,
+ ) -> Pin> + 'a + Send + Sync>> {
+ Box::pin(async { self.head(ctx).await.with_body(RenderedBody::Empty) })
+ }
+}
diff --git a/crates/servable/src/transform/chain.rs b/crates/servable/src/transform/chain.rs
new file mode 100644
index 0000000..59f9155
--- /dev/null
+++ b/crates/servable/src/transform/chain.rs
@@ -0,0 +1,176 @@
+use image::{DynamicImage, ImageFormat};
+use serde::{Deserialize, Deserializer, de};
+use std::{fmt::Display, hash::Hash, io::Cursor, str::FromStr};
+use thiserror::Error;
+
+use super::transformers::{ImageTransformer, TransformerEnum};
+use crate::mime::MimeType;
+
+#[expect(missing_docs)]
+#[derive(Debug, Error)]
+pub enum TransformBytesError {
+ /// We tried to transform non-image data
+ #[error("{0} is not a valid image type")]
+ NotAnImage(String),
+
+ /// We encountered an error while processing
+ /// an image.
+ #[error("error while processing image")]
+ ImageError(#[from] image::ImageError),
+}
+
+/// A sequence of transformations to apply to an image
+#[derive(Debug, Clone)]
+pub struct TransformerChain {
+ steps: Vec,
+}
+
+impl TransformerChain {
+ /// Returns `true` if `mime` is a type that can be transformed
+ #[inline(always)]
+ pub fn mime_is_image(mime: &MimeType) -> bool {
+ ImageFormat::from_mime_type(mime.to_string()).is_some()
+ }
+
+ /// Transform the given image using this chain
+ #[inline(always)]
+ pub fn transform_image(&self, mut image: DynamicImage) -> DynamicImage {
+ for step in &self.steps {
+ match step {
+ TransformerEnum::Format { .. } => {}
+ TransformerEnum::MaxDim(t) => t.transform(&mut image),
+ TransformerEnum::Crop(t) => t.transform(&mut image),
+ }
+ }
+
+ return image;
+ }
+
+ /// Return the mime this chain will produce when given an image
+ /// with type `input_mime`. If this returns `None`, the input mime
+ /// cannot be transformed.
+ #[inline(always)]
+ pub fn output_mime(&self, input_mime: &MimeType) -> Option {
+ let mime = self
+ .steps
+ .last()
+ .and_then(|x| match x {
+ TransformerEnum::Format { format } => Some(MimeType::from(format.to_mime_type())),
+ _ => None,
+ })
+ .unwrap_or(input_mime.clone());
+
+ let fmt = ImageFormat::from_mime_type(mime.to_string());
+ fmt.map(|_| mime)
+ }
+
+ /// Transform `image_bytes` using this chain.
+ /// Returns `(output_type, output_bytes)`.
+ ///
+ /// `image_format` tells us the type of `image_bytes`.
+ /// If it is `None`, we try to infer it.
+ pub fn transform_bytes(
+ &self,
+ image_bytes: &[u8],
+ image_format: Option<&MimeType>,
+ ) -> Result<(MimeType, Vec), TransformBytesError> {
+ let format: ImageFormat = match image_format {
+ Some(x) => ImageFormat::from_mime_type(x.to_string())
+ .ok_or(TransformBytesError::NotAnImage(x.to_string()))?,
+ None => image::guess_format(image_bytes)?,
+ };
+
+ let out_format = self
+ .steps
+ .last()
+ .and_then(|x| match x {
+ TransformerEnum::Format { format } => Some(format),
+ _ => None,
+ })
+ .unwrap_or(&format);
+
+ let img = image::load_from_memory_with_format(image_bytes, format)?;
+ let img = self.transform_image(img);
+
+ let out_mime = MimeType::from(out_format.to_mime_type());
+ let mut out_bytes = Cursor::new(Vec::new());
+ img.write_to(&mut out_bytes, *out_format)?;
+
+ return Ok((out_mime, out_bytes.into_inner()));
+ }
+}
+
+impl FromStr for TransformerChain {
+ type Err = String;
+ fn from_str(s: &str) -> Result {
+ let steps_str = s.split(";");
+
+ let mut steps = Vec::new();
+ for s in steps_str {
+ let s = s.trim();
+ if s.is_empty() {
+ continue;
+ }
+
+ let step = s.parse();
+ match step {
+ Ok(x) => steps.push(x),
+ Err(msg) => return Err(format!("invalid step `{s}`: {msg}")),
+ }
+ }
+
+ let n_format = steps
+ .iter()
+ .filter(|x| matches!(x, TransformerEnum::Format { .. }))
+ .count();
+ if n_format > 2 {
+ return Err("provide at most one format()".to_owned());
+ }
+
+ if n_format == 1 && !matches!(steps.last(), Some(TransformerEnum::Format { .. })) {
+ return Err("format() must be last".to_owned());
+ }
+
+ return Ok(Self { steps });
+ }
+}
+
+impl<'de> Deserialize<'de> for TransformerChain {
+ fn deserialize(deserializer: D) -> Result
+ where
+ D: Deserializer<'de>,
+ {
+ let s = String::deserialize(deserializer)?;
+ Self::from_str(&s).map_err(de::Error::custom)
+ }
+}
+
+impl Display for TransformerChain {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ let mut first = true;
+ for step in &self.steps {
+ if first {
+ write!(f, "{step}")?;
+ first = false
+ } else {
+ write!(f, ";{step}")?;
+ }
+ }
+
+ return Ok(());
+ }
+}
+
+impl PartialEq for TransformerChain {
+ fn eq(&self, other: &Self) -> bool {
+ self.to_string() == other.to_string()
+ }
+}
+
+impl Eq for TransformerChain {}
+
+impl Hash for TransformerChain {
+ fn hash(&self, state: &mut H) {
+ self.to_string().hash(state);
+ }
+}
diff --git a/crates/servable/src/transform/mod.rs b/crates/servable/src/transform/mod.rs
new file mode 100644
index 0000000..cea3ac0
--- /dev/null
+++ b/crates/servable/src/transform/mod.rs
@@ -0,0 +1,9 @@
+//! Provides simple server-side image optimization
+//! using query parameters.
+
+mod pixeldim;
+
+pub mod transformers;
+
+mod chain;
+pub use chain::*;
diff --git a/crates/servable/src/transform/pixeldim.rs b/crates/servable/src/transform/pixeldim.rs
new file mode 100644
index 0000000..b742c21
--- /dev/null
+++ b/crates/servable/src/transform/pixeldim.rs
@@ -0,0 +1,68 @@
+use serde::{Deserialize, Deserializer};
+use std::fmt;
+use std::str::FromStr;
+
+// TODO: parse -, + (100vw - 10px)
+// TODO: parse 100vw [min] 10
+// TODO: parse 100vw [max] 10
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum PixelDim {
+ Pixels(u32),
+ WidthPercent(f32),
+ HeightPercent(f32),
+}
+
+impl FromStr for PixelDim {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result {
+ let numeric_end = s.find(|c: char| !c.is_ascii_digit() && c != '.');
+
+ let (quantity, unit) = numeric_end.map(|x| s.split_at(x)).unwrap_or((s, "px"));
+ let quantity = quantity.trim();
+ let unit = unit.trim();
+
+ match unit {
+ "vw" => Ok(PixelDim::WidthPercent(
+ quantity
+ .parse()
+ .map_err(|_err| format!("invalid quantity {quantity}"))?,
+ )),
+
+ "vh" => Ok(PixelDim::HeightPercent(
+ quantity
+ .parse()
+ .map_err(|_err| format!("invalid quantity {quantity}"))?,
+ )),
+
+ "px" => Ok(PixelDim::Pixels(
+ quantity
+ .parse()
+ .map_err(|_err| format!("invalid quantity {quantity}"))?,
+ )),
+
+ _ => Err(format!("invalid unit {unit}")),
+ }
+ }
+}
+
+impl<'de> Deserialize<'de> for PixelDim {
+ fn deserialize(deserializer: D) -> Result
+ where
+ D: Deserializer<'de>,
+ {
+ let s = String::deserialize(deserializer)?;
+ FromStr::from_str(&s).map_err(serde::de::Error::custom)
+ }
+}
+
+impl fmt::Display for PixelDim {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ PixelDim::Pixels(px) => write!(f, "{px}"),
+ PixelDim::WidthPercent(p) => write!(f, "{p:.2}vw"),
+ PixelDim::HeightPercent(p) => write!(f, "{p:.2}vh"),
+ }
+ }
+}
diff --git a/crates/servable/src/transform/transformers/crop.rs b/crates/servable/src/transform/transformers/crop.rs
new file mode 100644
index 0000000..f517313
--- /dev/null
+++ b/crates/servable/src/transform/transformers/crop.rs
@@ -0,0 +1,188 @@
+use image::DynamicImage;
+use serde::{Deserialize, Serialize};
+use std::{fmt::Display, str::FromStr};
+use strum::{Display, EnumString};
+
+use super::super::{pixeldim::PixelDim, transformers::ImageTransformer};
+
+#[expect(missing_docs)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, EnumString, Serialize, Deserialize, Display)]
+pub enum Direction {
+ #[serde(rename = "n")]
+ #[strum(to_string = "n")]
+ #[strum(serialize = "north")]
+ North,
+
+ #[serde(rename = "e")]
+ #[strum(serialize = "e")]
+ #[strum(serialize = "east")]
+ East,
+
+ #[serde(rename = "s")]
+ #[strum(serialize = "s")]
+ #[strum(serialize = "south")]
+ South,
+
+ #[serde(rename = "w")]
+ #[strum(to_string = "w")]
+ #[strum(serialize = "west")]
+ West,
+
+ #[serde(rename = "c")]
+ #[strum(serialize = "c")]
+ #[strum(serialize = "center")]
+ Center,
+
+ #[serde(rename = "ne")]
+ #[strum(serialize = "ne")]
+ #[strum(serialize = "northeast")]
+ NorthEast,
+
+ #[serde(rename = "se")]
+ #[strum(serialize = "se")]
+ #[strum(serialize = "southeast")]
+ SouthEast,
+
+ #[serde(rename = "nw")]
+ #[strum(serialize = "nw")]
+ #[strum(serialize = "northwest")]
+ NorthWest,
+
+ #[serde(rename = "sw")]
+ #[strum(serialize = "sw")]
+ #[strum(serialize = "southwest")]
+ SouthWest,
+}
+
+/// Crop an image to (at most) the given size.
+/// See [Self::new] for details.
+#[derive(Debug, Clone, PartialEq)]
+pub struct CropTransformer {
+ w: PixelDim,
+ h: PixelDim,
+ float: Direction,
+}
+
+impl CropTransformer {
+ /// Create a new [CropTransformer] with the given parameters.
+ ///
+ /// A [CropTransformer] creates an image of size `w x h`, but...
+ /// - does not reduce width if `w` is greater than image width
+ /// - does not reduce height if `h` is greater than image height
+ /// - does nothing if `w` or `h` is less than or equal to zero.
+ pub fn new(w: PixelDim, h: PixelDim, float: Direction) -> Self {
+ Self { w, h, float }
+ }
+
+ fn crop_dim(&self, img_width: u32, img_height: u32) -> (u32, u32) {
+ let crop_width = match self.w {
+ PixelDim::Pixels(w) => w,
+ PixelDim::WidthPercent(pct) => ((img_width as f32) * pct / 100.0) as u32,
+ PixelDim::HeightPercent(pct) => ((img_height as f32) * pct / 100.0) as u32,
+ };
+
+ let crop_height = match self.h {
+ PixelDim::Pixels(h) => h,
+ PixelDim::WidthPercent(pct) => ((img_width as f32) * pct / 100.0) as u32,
+ PixelDim::HeightPercent(pct) => ((img_height as f32) * pct / 100.0) as u32,
+ };
+
+ (crop_width, crop_height)
+ }
+
+ #[expect(clippy::integer_division)]
+ fn crop_pos(
+ &self,
+ img_width: u32,
+ img_height: u32,
+ crop_width: u32,
+ crop_height: u32,
+ ) -> (u32, u32) {
+ match self.float {
+ Direction::North => {
+ let x = (img_width - crop_width) / 2;
+ let y = 0;
+ (x, y)
+ }
+ Direction::East => {
+ let x = img_width - crop_width;
+ let y = (img_height - crop_height) / 2;
+ (x, y)
+ }
+ Direction::South => {
+ let x = (img_width - crop_width) / 2;
+ let y = img_height - crop_height;
+ (x, y)
+ }
+ Direction::West => {
+ let x = 0;
+ let y = (img_height - crop_height) / 2;
+ (x, y)
+ }
+ Direction::Center => {
+ let x = (img_width - crop_width) / 2;
+ let y = (img_height - crop_height) / 2;
+ (x, y)
+ }
+ Direction::NorthEast => {
+ let x = img_width - crop_width;
+ let y = 0;
+ (x, y)
+ }
+ Direction::SouthEast => {
+ let x = img_width - crop_width;
+ let y = img_height - crop_height;
+ (x, y)
+ }
+ Direction::NorthWest => {
+ let x = 0;
+ let y = 0;
+ (x, y)
+ }
+ Direction::SouthWest => {
+ let x = 0;
+ let y = img_height - crop_height;
+ (x, y)
+ }
+ }
+ }
+}
+
+impl Display for CropTransformer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "crop({},{},{})", self.w, self.h, self.float)
+ }
+}
+
+impl ImageTransformer for CropTransformer {
+ fn parse_args(args: &str) -> Result {
+ let args: Vec<&str> = args.split(",").collect();
+ if args.len() != 3 {
+ return Err(format!("expected 3 args, got {}", args.len()));
+ }
+
+ let w = args[0].trim().parse::()?;
+ let h = args[1].trim().parse::()?;
+
+ let direction = args[2].trim();
+ let direction = Direction::from_str(direction)
+ .map_err(|_err| format!("invalid direction {direction}"))?;
+
+ Ok(Self {
+ w,
+ h,
+ float: direction,
+ })
+ }
+
+ fn transform(&self, input: &mut DynamicImage) {
+ let (img_width, img_height) = (input.width(), input.height());
+ let (crop_width, crop_height) = self.crop_dim(img_width, img_height);
+
+ if (crop_width < img_width || crop_height < img_height) && crop_width > 0 && crop_height > 0
+ {
+ let (x, y) = self.crop_pos(img_width, img_height, crop_width, crop_height);
+ *input = input.crop(x, y, crop_width, crop_height);
+ }
+ }
+}
diff --git a/crates/servable/src/transform/transformers/maxdim.rs b/crates/servable/src/transform/transformers/maxdim.rs
new file mode 100644
index 0000000..a207b1f
--- /dev/null
+++ b/crates/servable/src/transform/transformers/maxdim.rs
@@ -0,0 +1,86 @@
+use image::{DynamicImage, imageops::FilterType};
+use std::fmt::Display;
+
+use super::super::{pixeldim::PixelDim, transformers::ImageTransformer};
+
+/// Scale an image until it fits in a configured bounding box.
+#[derive(Debug, Clone, PartialEq)]
+pub struct MaxDimTransformer {
+ w: PixelDim,
+ h: PixelDim,
+}
+
+impl MaxDimTransformer {
+ /// Create a new [MaxDimTransformer] that scales an image down
+ /// until it fits in a box of dimension `w x h`.
+ ///
+ /// Images are never scaled up.
+ pub fn new(w: PixelDim, h: PixelDim) -> Self {
+ Self { w, h }
+ }
+
+ fn target_dim(&self, img_width: u32, img_height: u32) -> (u32, u32) {
+ let max_width = match self.w {
+ PixelDim::Pixels(w) => Some(w),
+ PixelDim::WidthPercent(pct) => Some(((img_width as f32) * pct / 100.0) as u32),
+ PixelDim::HeightPercent(_) => None,
+ };
+
+ let max_height = match self.h {
+ PixelDim::Pixels(h) => Some(h),
+ PixelDim::HeightPercent(pct) => Some(((img_height as f32) * pct / 100.0) as u32),
+ PixelDim::WidthPercent(_) => None,
+ };
+
+ if max_width.map(|x| img_width <= x).unwrap_or(true)
+ && max_height.map(|x| img_height <= x).unwrap_or(true)
+ {
+ return (img_width, img_height);
+ }
+
+ let width_ratio = max_width
+ .map(|x| x as f32 / img_width as f32)
+ .unwrap_or(1.0);
+
+ let height_ratio = max_height
+ .map(|x| x as f32 / img_height as f32)
+ .unwrap_or(1.0);
+
+ let ratio = width_ratio.min(height_ratio);
+
+ (
+ (img_width as f32 * ratio) as u32,
+ (img_height as f32 * ratio) as u32,
+ )
+ }
+}
+
+impl Display for MaxDimTransformer {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "maxdim({},{})", self.w, self.h)
+ }
+}
+
+impl ImageTransformer for MaxDimTransformer {
+ fn parse_args(args: &str) -> Result {
+ let args: Vec<&str> = args.split(",").collect();
+ if args.len() != 2 {
+ return Err(format!("expected 2 args, got {}", args.len()));
+ }
+
+ let w = args[0].parse::()?;
+ let h = args[1].parse::()?;
+
+ Ok(Self { w, h })
+ }
+
+ fn transform(&self, input: &mut DynamicImage) {
+ let (img_width, img_height) = (input.width(), input.height());
+ let (target_width, target_height) = self.target_dim(img_width, img_height);
+
+ // Only resize if needed
+ if target_width != img_width || target_height != img_height {
+ *input = input.resize(target_width, target_height, FilterType::Lanczos3);
+ }
+ }
+}
diff --git a/crates/servable/src/transform/transformers/mod.rs b/crates/servable/src/transform/transformers/mod.rs
new file mode 100644
index 0000000..a777f5b
--- /dev/null
+++ b/crates/servable/src/transform/transformers/mod.rs
@@ -0,0 +1,171 @@
+//! Defines all transformation steps we can apply to an image
+
+use image::{DynamicImage, ImageFormat};
+use std::fmt;
+use std::fmt::{Debug, Display};
+use std::str::FromStr;
+
+mod crop;
+pub use crop::*;
+
+mod maxdim;
+pub use maxdim::*;
+
+/// A single transformation that may be applied to an image.
+pub trait ImageTransformer
+where
+ Self: PartialEq,
+ Self: Sized + Clone,
+ Self: Display + Debug,
+{
+ /// Transform the given image in place
+ fn transform(&self, input: &mut DynamicImage);
+
+ /// Parse an arg string.
+ ///
+ /// `name({arg_string})`
+ fn parse_args(args: &str) -> Result;
+}
+
+use serde::{Deserialize, Deserializer};
+
+/// An enum of all [`ImageTransformer`]s
+#[derive(Debug, Clone, PartialEq)]
+pub enum TransformerEnum {
+ /// Usage: `maxdim(w, h)`
+ ///
+ /// Scale the image so its width is smaller than `w`
+ /// and its height is smaller than `h`. Aspect ratio is preserved.
+ ///
+ /// To only limit the size of one dimension, use `vw` or `vh`.
+ /// For example, `maxdim(50,100vh)` will not limit width.
+ MaxDim(MaxDimTransformer),
+
+ /// Usage: `crop(w, h, float)`
+ ///
+ /// Crop the image to at most `w` by `h` pixels,
+ /// floating the crop area in the specified direction.
+ ///
+ /// Directions are one of:
+ /// - Cardinal: n,e,s,w
+ /// - Diagonal: ne,nw,se,sw,
+ /// - Centered: c
+ ///
+ /// Examples:
+ /// - `crop(100vw, 50)` gets the top 50 pixels of the image \
+ /// (or fewer, if the image's height is smaller than 50)
+ ///
+ /// To only limit the size of one dimension, use `vw` or `vh`.
+ /// For example, `maxdim(50,100vh)` will not limit width.
+ Crop(CropTransformer),
+
+ /// Usage: `format(format)`
+ ///
+ /// Transcode the image to the given format.
+ /// This step must be last, and cannot be provided
+ /// more than once.
+ ///
+ /// Valid formats:
+ /// - bmp
+ /// - gif
+ /// - ico
+ /// - jpeg or jpg
+ /// - png
+ /// - qoi
+ /// - webp
+ ///
+ /// Example:
+ /// - `format(png)`
+ ///
+ /// When transcoding an animated gif, the first frame is taken
+ /// and all others are thrown away. This happens even if we
+ /// transcode from a gif to a gif.
+ Format {
+ /// The format to produce
+ format: ImageFormat,
+ },
+}
+
+impl FromStr for TransformerEnum {
+ type Err = String;
+
+ fn from_str(s: &str) -> Result {
+ let s = s.trim();
+
+ let (name, args) = {
+ let name_len = match s.find('(') {
+ Some(x) => x + 1,
+ None => {
+ return Err(format!(
+ "invalid transformation {s}. Must look like name(args)."
+ ));
+ }
+ };
+
+ let mut balance = 1;
+ let mut end = name_len;
+ for i in s[name_len..].bytes() {
+ match i {
+ b')' => balance -= 1,
+ b'(' => balance += 1,
+ _ => {}
+ }
+
+ if balance == 0 {
+ break;
+ }
+
+ end += 1;
+ }
+
+ if balance != 0 {
+ return Err(format!("mismatched parenthesis in {s}"));
+ }
+
+ let name = s[0..name_len - 1].trim();
+ let args = s[name_len..end].trim();
+ let trail = s[end + 1..].trim();
+ if !trail.is_empty() {
+ return Err(format!(
+ "invalid transformation {s}. Must look like name(args)."
+ ));
+ }
+
+ (name, args)
+ };
+
+ match name {
+ "maxdim" => Ok(Self::MaxDim(MaxDimTransformer::parse_args(args)?)),
+ "crop" => Ok(Self::Crop(CropTransformer::parse_args(args)?)),
+
+ "format" => Ok(TransformerEnum::Format {
+ format: ImageFormat::from_extension(args)
+ .ok_or(format!("invalid image format {args}"))?,
+ }),
+
+ _ => Err(format!("unknown transformation {name}")),
+ }
+ }
+}
+
+impl<'de> Deserialize<'de> for TransformerEnum {
+ fn deserialize(deserializer: D) -> Result
+ where
+ D: Deserializer<'de>,
+ {
+ let s = String::deserialize(deserializer)?;
+ s.parse().map_err(serde::de::Error::custom)
+ }
+}
+
+impl Display for TransformerEnum {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ TransformerEnum::MaxDim(x) => Display::fmt(x, f),
+ TransformerEnum::Crop(x) => Display::fmt(x, f),
+ TransformerEnum::Format { format } => {
+ write!(f, "format({})", format.extensions_str()[0])
+ }
+ }
+ }
+}
diff --git a/crates/servable/src/types.rs b/crates/servable/src/types.rs
new file mode 100644
index 0000000..c4231a6
--- /dev/null
+++ b/crates/servable/src/types.rs
@@ -0,0 +1,148 @@
+use axum::http::{HeaderMap, StatusCode};
+use chrono::TimeDelta;
+use std::collections::BTreeMap;
+
+use crate::mime::MimeType;
+
+//
+// MARK: rendered
+//
+
+/// The contents of a response
+/// produced by a [crate::servable::Servable]
+#[derive(Clone)]
+pub enum RenderedBody {
+ /// Static raw bytes
+ Static(&'static [u8]),
+
+ /// Dynamic raw bytes
+ Bytes(Vec),
+
+ /// A UTF-8 string
+ String(String),
+
+ /// No body. Equivalent to `Self::Static(&[])`.
+ Empty,
+}
+
+trait RenderedBodyTypeSealed {}
+impl RenderedBodyTypeSealed for () {}
+impl RenderedBodyTypeSealed for RenderedBody {}
+
+/// A utility trait, used to control the
+/// kind of body [Rendered] contains.
+///
+/// This trait is only implemented by two types:
+/// - `()`, when a request must return an empty body (i.e, HEAD)
+/// - [RenderedBody], when a request should return a full response (i.e, GET)
+#[expect(private_bounds)]
+pub trait RenderedBodyType: RenderedBodyTypeSealed {}
+impl RenderedBodyType for T {}
+
+/// An asset to return from an http route
+#[derive(Clone)]
+pub struct Rendered {
+ /// The code to return
+ pub code: StatusCode,
+
+ /// The headers to return
+ pub headers: HeaderMap,
+
+ /// The content to return
+ pub body: T,
+
+ /// The type of `self.body`
+ pub mime: Option,
+
+ /// How long to cache this response.
+ /// If none, don't cache.
+ pub ttl: Option,
+
+ /// If true, the data at this route will never change.
+ pub immutable: bool,
+}
+
+impl Rendered<()> {
+ /// Turn this [Rendered] into a [Rendered] with a body.
+ pub fn with_body(self, body: RenderedBody) -> Rendered {
+ Rendered {
+ code: self.code,
+ headers: self.headers,
+ body,
+ mime: self.mime,
+ ttl: self.ttl,
+ immutable: self.immutable,
+ }
+ }
+}
+
+/// Additional context available to [crate::servable::Servable]s
+/// when generating their content
+#[derive(Debug, Clone, PartialEq, Eq, Hash)]
+pub struct RenderContext {
+ /// Information about the request
+ pub client_info: ClientInfo,
+
+ /// The route that was requested.
+ /// Starts with a /.
+ pub route: String,
+
+ /// This request's query parameters
+ pub query: BTreeMap,
+}
+
+/// The type of device that requested a page
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub enum DeviceType {
+ /// This is a mobile device, like a phone.
+ Mobile,
+
+ /// This is a device with a large screen
+ /// and a mouse, like a laptop.
+ Desktop,
+}
+
+impl Default for DeviceType {
+ fn default() -> Self {
+ Self::Desktop
+ }
+}
+
+/// Inferred information about the client
+/// that requested a certain route.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub struct ClientInfo {
+ /// The type of device that is viewing this page.
+ ///
+ /// We do our best to detect this value automatically,
+ /// but we may be wrong.
+ pub device_type: DeviceType,
+}
+
+impl ClientInfo {
+ pub(crate) fn from_headers(headers: &HeaderMap) -> Self {
+ let ua = headers
+ .get("user-agent")
+ .and_then(|x| x.to_str().ok())
+ .unwrap_or("");
+
+ let ch_mobile = headers
+ .get("Sec-CH-UA-Mobile")
+ .and_then(|x| x.to_str().ok())
+ .unwrap_or("");
+
+ let mut device_type = None;
+
+ if device_type.is_none() && ch_mobile.contains("1") {
+ device_type = Some(DeviceType::Mobile);
+ }
+
+ if device_type.is_none() && ua.contains("Mobile") {
+ device_type = Some(DeviceType::Mobile);
+ }
+
+ Self {
+ device_type: device_type.unwrap_or_default(),
+ }
+ }
+}