diff --git a/README.md b/README.md index ee71e03..2b14a86 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # LuPhoto -LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders, cuts every photo into WebP tiles at several resolutions with libvips (at most 512 px, at least a 3 × 3 grid per level), and publishes a static site in which the browser stitches the visible tiles back together on a canvas. A one-time robot check unlocks the tile maps; see [Protection](#protection). Design: [docs/DESIGN.md](docs/DESIGN.md). +LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders, cuts every photo into WebP tiles at several resolutions with libvips (at most 512 px, at least a 3 × 3 grid per level), and publishes a static site in which the browser stitches the visible tiles back together on a canvas. Covers are always open; photo tile maps are unlocked per photo by keys the daemon hands out at `/k`, with a press-and-hold check only for visitors who look automated; see [Protection](#protection). Design: [docs/DESIGN.md](docs/DESIGN.md). ## Commands @@ -12,7 +12,7 @@ luphoto [-config /etc/luphoto/config.toml] |---|---| | `build` | Process the albums once, publish a new build, exit. | | `serve` | Build, watch the albums folder, rebuild after changes, and serve the site over HTTP on `server.listen`. | -| `export` | Build, watch and rebuild; no HTTP. Point Caddy or nginx at `/current`. | +| `export` | Build, watch and rebuild. Point Caddy or nginx at `/current`. With `protection.gate = "server"` it also listens on `server.listen`, serving only the key endpoint `/k`, which the web server must proxy. | | `run` | `serve` or `export`, whichever `server.mode` says. The systemd unit uses this. | | `version` | Print the version. | @@ -75,7 +75,9 @@ Unknown fields are errors, so typos are caught. |---|---|---| | `server.mode` | `"export"` | What `luphoto run` does: `"serve"` or `"export"`. | | `server.listen` | `"127.0.0.1:8080"` | Address of the built-in HTTP server. | -| `server.base_url` | `"https://photos.luciochen.com"` | Used for canonical and Open Graph URLs. | +| `server.base_url` | `"https://photos.luciochen.com"` | Used for canonical and Open Graph URLs; its host is also accepted as `Origin` on `/k`. | +| `server.trusted_proxies` | `["127.0.0.1/32", "::1/128"]` | CIDRs (or single addresses) of reverse proxies whose `client_ip_header` is believed. | +| `server.client_ip_header` | `"X-Forwarded-For"` | Header carrying the visitor's address, read only when the direct peer is in `trusted_proxies` (the right-most untrusted address wins). Behind a Cloudflare Tunnel use `"CF-Connecting-IP"`. Empty: always use the peer address. | | `paths.albums` | `"/srv/luphoto/albums"` | Album folders. Read only. | | `paths.output` | root or systemd: `/var/lib/luphoto/site`, else `$XDG_DATA_HOME/luphoto/site` | Builds, tiles, `current`. The site key and per-photo records go to `state/` next to it. | | `paths.cache` | root or systemd: `/var/cache/luphoto`, else the user cache dir | Temporary vips files. | @@ -96,24 +98,35 @@ Unknown fields are errors, so typos are caught. | `build.workers` | `2` | Photos processed in parallel. vips threads per photo = CPUs ÷ workers. | | `build.keep_builds` | `3` | Builds kept; tile folders and decoys no kept build uses are deleted. | | `protection.block_context_menu` | `true` | Disable the context menu on photos. | -| `protection.hotlink_allow` | `["photos.luciochen.com"]` | Hosts allowed as `Referer` for `/t/*`; empty Referers and the site's own host are always allowed. | +| `protection.hotlink_allow` | `["photos.luciochen.com"]` | Hosts allowed as `Referer` for `/t/*` and as `Origin` for `/k`; empty Referers on `/t/*` and the site's own host are always allowed. | | `protection.decoys` | `4` | Decoy tiles per real tile in each photo folder (0–16); 0 turns decoys off. | -| `protection.gate` | `true` | Show the press-and-hold robot check before photos unlock. `false` publishes the key in the clear and shows no check. | -| `protection.pow_bits` | `20` | Proof-of-work size for the robot check (10–26); each extra bit doubles the average work. | +| `protection.gate` | `"server"` | `"server"`: photo keys come from the daemon's `/k`, with the risk checks below. `"off"`: every photo key is published in the album manifest and `/k` is never called (pure static hosting). The old `true`/`false` still read as `"server"`/`"off"`. | +| `protection.pow_bits` | `20` | Base proof-of-work size of a challenge (10–26); each extra bit doubles the average work. | +| `protection.photo_limit` | `400` | Photo keys one address may unlock per `window` before it is challenged again; more than 4 × this in a window is answered 429. | +| `protection.min_entropy` | `20` | Interaction score (0–100) below which a visitor counts as low-entropy. | +| `protection.landing_limit` | `5` | Low-entropy direct landings per address per `window` before every request without a pass is challenged (1–10000). | +| `protection.window` | `"10m"` | Sliding window of the per-address counters (1m–24h). | +| `protection.pass_ttl` | `"12h"` | Lifetime of the pass a solved challenge earns (1m–720h). | The watcher ignores dotfiles (including rsync's `.name.XXXXXX` temp files), `*.part`, `*.tmp` and editor backups. vips runs at `nice +5` so processing does not starve the web server. ## Protection -Everything stays static files, so export mode, Caddy, nginx and Cloudflare caching of `/t/` keep working. What a build adds on top of hashed tile names: +Everything except the small key endpoint `/k` stays static files, so export mode, Caddy, nginx and Cloudflare caching of `/t/` keep working. What a build adds on top of hashed tile names: - **Small tiles.** Every level of every photo and cover is cut into at least a 3 × 3 grid (`images.min_grid`), so no single file is a usable picture, not even the small levels. - **Decoys.** Each photo folder `/t//` also holds `protection.decoys` × as many decoy files as it has real tiles: hard links (copies if linking fails) to real tiles of other photos, from other albums first, with tile sizes as close as possible. A decoy name is an HMAC of the photo, level, slot and source tile, so a name never changes its bytes and `/t/` stays immutable. Decoys are chosen after all photos are processed; unchanged photos keep their decoys from build to build. - **Sealed maps.** The album manifest and index carry only layout (sizes, tile grid, captions, EXIF). Which file sits where lives in one small JSON per photo and cover, `/a//p/..json`, fetched when that photo is near: per level the shuffled pool of real and decoy ids, plus a `sealed` payload (the blurred seed, the cell-scramble seed, the grid→pool map and tile byte sizes) encrypted with a SHA-256 counter-mode keystream. -- **Robot check.** Each build picks a random salt and a random `n` below 2^`pow_bits`. The key is SHA-256("luphoto-key" | salt | n); only a 16-byte check value is published. On the first visit a small card asks the visitor to press and hold for 0.9 s while a Web Worker finds `n` (at 20 bits about 0.1–0.25 s in desktop V8; phones are several times slower). The pass is kept in `localStorage` for that build. Until it is unlocked, each photo shows a jumble of tiles drawn from its pool. +- **Keys.** Each build gets a random 32-byte secret in `builds//.secret` (mode 0600, never served). Every photo's pool is sealed with its own key, HMAC-SHA-256(secret, "photo|" + photo hash). Covers are sealed with one public cover key per build, HMAC(secret, "cover|"), published in the index JSON and every manifest, so the index and the next-album strip always draw without a check. With `gate = "off"` the manifest also lists every photo key. +- **Key endpoint.** The album page asks `POST /k` for the keys of the current photo and its neighbours, at most 8 per request: one request when the page loads, then one more only when the visitor moves past the photos it covers, never for photos far away. The first grant also returns a page token (30 minutes, bound to the address, build and album); later requests from that page send it, so one page load counts as at most one landing. The daemon answers it in serve mode and, in export mode, on `server.listen` (proxy `/k` there; it must never be cached). It accepts only requests whose `Origin` (or `Referer`) is the site's host, `server.base_url`'s host or a `hotlink_allow` host, for the current build or any kept build, and grants only hashes of the album named in the request. +- **When the prompt appears.** The main page never asks. Following a link to an album or straight to a photo (`/a//#7`) does not ask either, as long as the address behaves. The press-and-hold card (0.9 s, while a Web Worker solves a proof of work) is shown when: + - a collection is opened from the index or the next-album card and the visitor's interaction score is below `min_entropy` and no pass is stored (the score counts mouse path, direction changes and distinct 8 px cells, touch gestures that move, scrolling and key presses, summed over the tab's session); + - an address has made `landing_limit` low-entropy landings (album page loads, a new tab or a reload each counting once, opened without a recent click from the site) within `window`, after which every request from it without a pass is challenged; + - an address has unlocked more than `photo_limit` photos since its last solved challenge within `window`. +- **Per-address limits.** IPv4 addresses are counted per /32, IPv6 per /64, in memory (per-minute counters over `window`, at most 200 000 addresses, least recently seen dropped first). A solved challenge earns a pass bound to that address for `pass_ttl`, which skips the entropy checks but not `photo_limit`; it resets the address's landing and photo counters. Each challenge solved within the window adds one bit of work (up to +6 over `pow_bits`), and more than 4 × `photo_limit` photos in a window are refused with 429 and `Retry-After` regardless of passes. - **Cell scrambling** (`images.scramble_cells`, on by default), the hotlink rule on `/t/*`, no context menu, and `robots.txt` with `Disallow: /t/` and `Disallow: /a/*/p/`. -Limits: this raises the cost of bulk downloading; it does not prevent it. A determined scraper that drives a real browser, or reimplements the client, can solve the check in a fraction of a second, decrypt the maps and stitch the tiles; and decoys are byte-identical copies of other photos' tiles, so a crawler that downloads every folder can tell which files are shared. Every visitor's browser must be able to draw the photos, so it always has everything needed to do so. +Limits: this raises the cost of bulk downloading; it does not prevent it. The interaction score is reported by the browser, so a bot can fake it; such a bot is bounded only by `photo_limit` per address and the escalating proof of work (about 0.25 s at 20 bits and 15 s at 26 bits in desktop V8, phones several times slower), and by the 429 cap. Many addresses multiply its budget. A determined scraper that drives a real browser, or reimplements the client, can still decrypt the maps and stitch the tiles; and decoys are byte-identical copies of other photos' tiles, so a crawler that downloads every folder can tell which files are shared. Every visitor's browser must be able to draw the photos, so it always has everything needed to do so. ## Install @@ -151,7 +164,7 @@ rsync writes to dotted temp names and renames at the end, which the watcher igno ## Web server - **Serve mode**: LuPhoto serves `current` itself with the right headers (immutable caching for `/t/`, `/og/`, `/assets/`; one minute for HTML and JSON; CSP; hotlink 403 on `/t/*`; precompressed gzip; no directory listings; `404.html` for missing paths). Put Caddy (`packaging/Caddyfile.serve`), nginx (`packaging/nginx.serve.conf`) or a Cloudflare Tunnel in front. -- **Export mode**: serve `/var/lib/luphoto/site/current` with `packaging/Caddyfile` or `packaging/nginx.conf`. Each build writes `.gz` files next to HTML, JSON, JS, CSS and SVG for `precompressed gzip` / `gzip_static`. Each build also writes `robots.txt`; serve mode serves the same file. +- **Export mode**: serve `/var/lib/luphoto/site/current` with `packaging/Caddyfile` or `packaging/nginx.conf`, and proxy `/k` to `luphoto run` on `server.listen` (both examples do; the daemon serves nothing else there). Without that proxy, photos stay jumbled unless `protection.gate = "off"`. Each build writes `.gz` files next to HTML, JSON, JS, CSS and SVG for `precompressed gzip` / `gzip_static`. Each build also writes `robots.txt`; serve mode serves the same file. - **Cloudflare**: `packaging/cloudflared.yml` and `packaging/cloudflare.md` (cache rules). ## Building from source @@ -192,6 +205,7 @@ This type-checks with `tsc --noEmit` (strict) and bundles with esbuild. Fonts ar builds//index.html, 404.html, robots.txt, index..json, a//index.html, a//manifest..json, a//p/..json, assets/, t -> ../../t, og -> ../../og (plus .gz copies) builds//.refs every pool id per photo folder, read by the cleanup to find stale decoys (never served) + builds//.secret the build's 32-byte key secret, mode 0600, read by /k (never served) t//.webp real tiles and decoys (hard links), unordered og/.jpg state/ diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 1aece26..3b56c19 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -2,7 +2,7 @@ LuPhoto serves photos.luciochen.com. It is one Go program that reads album folders from disk, cuts every photo into tiles of at most 512 px (at least 3 × 3 per level) at several resolutions, and publishes a fully static, Lucio-branded site that a browser stitches back together on a canvas. No editing, comments, likes, themes, templating or camera RAW support. -Decisions: name LuPhoto (binary, user and paths lowercase `luphoto`), Go, no resolution cap, hashed tile names in v1, cell scrambling on by default, decoy tiles and a sealed tile map behind a one-time robot check, JPEGs not listed in album.json are hidden. +Decisions: name LuPhoto (binary, user and paths lowercase `luphoto`), Go, no resolution cap, hashed tile names in v1, cell scrambling on by default, decoy tiles and per-photo sealed tile maps whose keys a risk-based key endpoint hands out (covers always open, a press-and-hold check only for visitors who look automated), JPEGs not listed in album.json are hidden. ## Architecture @@ -11,7 +11,7 @@ uploads (rsync/SFTP) -> /srv/luphoto/albums -> watcher (debounce) -> processor ( -> serve mode (built-in HTTP) or export mode (folder for Caddy/nginx) -> Cloudflare Tunnel + cache -> browser canvas stitches visible tiles ``` -- Commands: `luphoto build` runs once; `luphoto serve` builds, watches and serves; `luphoto export` builds into the output folder and keeps watching; `luphoto run` does `serve` or `export` as `server.mode` says (the systemd unit uses it); `luphoto version`. `-config` flag, default `/etc/luphoto/config.toml`. Rebuilds never overlap: changes during a build cause one follow-up build. +- Commands: `luphoto build` runs once; `luphoto serve` builds, watches and serves; `luphoto export` builds into the output folder and keeps watching, and with `gate = "server"` listens on `server.listen` for `/k` only; `luphoto run` does `serve` or `export` as `server.mode` says (the systemd unit uses it); `luphoto version`. `-config` flag, default `/etc/luphoto/config.toml`. Rebuilds never overlap: changes during a build cause one follow-up build. - Tiling with libvips CLI (`vips`), installed by `apt install libvips-tools`. Support libvips 8.12 (Ubuntu 22.04) and 8.15 (Ubuntu 24.04): metadata stripping is `strip` on 8.12 and `keep=none` on 8.15+. - Front-end: plain TypeScript, no framework, bundled with esbuild, embedded in the binary with `go:embed`. Fixed Lucio brand. - Speed and memory matter: photos are processed in parallel by a bounded worker pool; hashing, EXIF reading and tile renaming run concurrently; the browser fetches tiles concurrently and decodes off the main thread. @@ -58,23 +58,39 @@ uploads (rsync/SFTP) -> /srv/luphoto/albums -> watcher (debounce) -> processor ( 5. Seed: a 48 px (long edge) WebP, kept in the per-photo record and published only inside the sealed payload. 6. No resolution cap: the full-resolution level is stored; the loader never fetches beyond screen size × max_dpr. 7. Tile paths: `/t//.webp`. photo-hash = first 16 hex of SHA-256 over the original bytes + a processing-settings fingerprint (which includes `min_grid` and `scramble_cells`). tile-id = first 16 hex of HMAC-SHA-256(site key, photo-hash|level|x|y). The site key is generated once and kept in the state folder. Each folder also holds decoys (below), so on disk and in developer tools a folder is an unordered pile of patches from many photos. -8. Album manifest `/a//manifest..json`: layout only. Per photo width, height, per level width, height, tile size, cols, rows (and overlap when not 0), caption, title, alt, EXIF, slides, plus the build's `gate` record. Covers are pyramids too and are described in `/index..json`. Tile ids, byte sizes, the seed and the scramble seed are not in it. +8. Album manifest `/a//manifest..json`: layout only. Per photo width, height, per level width, height, tile size, cols, rows (and overlap when not 0), caption, title, alt, EXIF, slides, plus the build's `gate` record `{build, mode, cover, min_entropy}` (and `keys` when the gate is off). Covers are pyramids too and are described in `/index..json`. Tile ids, byte sizes, the seed and the scramble seed are not in it. -Incremental: a photo is reprocessed only when its photo-hash is new. Each build writes `builds//` (HTML, manifests, per-photo pool files, assets, `404.html`, `robots.txt`, `.refs`, and a `.gz` copy of every HTML, JSON, JS, CSS and SVG file for precompressed serving) next to a shared `t/` tile folder and a shared `og/` folder of 1200×630 Open Graph JPEGs cut around each album cover (the only non-tiled images; derived, small, metadata stripped); the `current` symlink flips only when the build is complete. Keep the last `keep_builds` builds; delete tile folders no kept build references, and inside live folders delete files no kept build's `.refs` lists. Write everything to temporary names and rename, so readers never see partial files (pool files are written straight into the unpublished stage folder). +Incremental: a photo is reprocessed only when its photo-hash is new. Build ids are `YYYYMMDD-HHMMSS-micro-random` and always sort after every existing build, even within one second (keep_builds and the key endpoint rely on it). Each build writes `builds//` (HTML, manifests, per-photo pool files, assets, `404.html`, `robots.txt`, `.refs`, `.secret`, and a `.gz` copy of every HTML, JSON, JS, CSS and SVG file for precompressed serving) next to a shared `t/` tile folder and a shared `og/` folder of 1200×630 Open Graph JPEGs cut around each album cover (the only non-tiled images; derived, small, metadata stripped); the `current` symlink flips only when the build is complete. Keep the last `keep_builds` builds; delete tile folders no kept build references, and inside live folders delete files no kept build's `.refs` lists. Write everything to temporary names and rename, so readers never see partial files (pool files are written straight into the unpublished stage folder). Storage: about 1.33× the top level, roughly 6–10 MB of tiles per Z8 photo. Decoys are hard links and cost directory entries, not bytes; small low-level tiles cost some filesystem block overhead. ## Protection step (per build, after all photos are processed) -1. Gate: random 16-byte salt and random n < 2^`pow_bits`. Key s = SHA-256("luphoto-key" | salt | n as 4 bytes big-endian). Published in the index and every manifest: `{build, salt, bits, check}` with check = first 16 bytes of SHA-256("luphoto-check" | salt | n). With `gate = false`: `{build, key}` and no robot check, same code path. +1. Keys: a random 32-byte build secret, written to `builds//.secret` (0600; dotfiles are never served). Photo key = HMAC-SHA-256(secret, "photo|" + photo-hash); cover key = HMAC-SHA-256(secret, "cover|"), one per build, public. The index and every manifest carry `{build, mode, cover, min_entropy}`; with `gate = "off"` each manifest also carries `keys: {hash: hex}` for its photos, so a purely static host works with the same code path. 2. Decoys: all live pyramids (photos and covers of every published album, carried albums included) are indexed by tile size; each pyramid's primary album is the first album, in index order, that uses it. For each level with R real tiles, `decoys` × R slots are filled from the bucket whose tile size is closest to the level's, taking candidates from other albums first, then other photos of the same album, then (single-pyramid site only) the photo itself. A slot's source is the next tile on a ring ordered by tile id after a target drawn from a PRNG keyed by HMAC(site key, "pick"|hash|level), skipping ineligible or already used tiles, so selections are stable while the site does not change. Decoy name = first 16 hex of HMAC-SHA-256(site key, "decoy"|photo-hash|level|slot|source tile id). The file is a hard link to the source tile (a copy if linking fails); names already present in the folder are reused (one `ReadDir` per folder). 3. Pool: per level the real ids and decoy names, shuffled with a PRNG keyed by HMAC(site key, "pool"|hash|level), written as one string of 16-hex ids. -4. Seal: plaintext = "luphoto-sealed-1" (16 bytes) + JSON `{seed, scramble, levels: [{map, bytes}]}` where `map` turns a row-major grid index into a pool index. Ciphertext = plaintext XOR keystream, block i = SHA-256(s | nonce | i as 4 bytes big-endian), 12-byte random nonce in front, base64. +4. Seal: plaintext = "luphoto-sealed-1" (16 bytes) + JSON `{seed, scramble, levels: [{map, bytes}]}` where `map` turns a row-major grid index into a pool index. Ciphertext = plaintext XOR keystream, block i = SHA-256(key | nonce | i as 4 bytes big-endian), 12-byte random nonce in front, base64; key = the photo key, or the cover key for covers. 5. `/a//p/..json` = `{levels: [pool strings], sealed}` for every photo and the cover of each album; build-named like the manifests, so a new build never pairs with a cached pool. `builds//.refs` lists every pool id per folder (8-byte binary) for the cleanup. +## Key endpoint `POST /k` + +Served by the daemon in serve mode, and in export mode on `server.listen` (nothing else is served there; the web server proxies `/k`). `Cache-Control: no-store`, JSON, body at most 4 KB, POST only. Rejected with 403 unless `Origin` (or `Referer` when `Origin` is absent) names the request's host, `base_url`'s host or a `hotlink_allow` host. 404 when the gate is off. + +- Request: `{build, album, photos: [≤ 8 photo hashes], context: "nav" | "land", entropy: 0..100, pass?, page?, challenge?: {token, nonce}}`. Unknown or GC'd build, unknown album, a bad context or entropy: 400. Hashes not in that album of that build are dropped. Builds are found by their `.secret`, cached in memory, re-read after every build the daemon runs and at most every 2 s on a miss (so builds made by a separate `luphoto build` are found too); album membership is read from the build's manifest once per album. +- Responses: `{keys: {hash: hex}, pass?, page?, stale?}`; `{challenge: {token, bits}, stale?}`; 429 `{error}` with `Retry-After`. `stale: true` means the pass sent is not valid for this address and should be dropped. +- Client address: the TCP peer, unless the peer is in `trusted_proxies`, then the right-most address in `client_ip_header` that is not itself a trusted proxy. Bucket: IPv4 /32, IPv6 /64. +- State per bucket, in memory: 16 slots of `{photos, low-entropy landings, challenges solved}` over `window` (one slot per minute up to 16 minutes, wider beyond), plus the slot and count at the last solve. 16 shards, each a map into a slice with an intrusive LRU list, 200 000 buckets in all; the oldest bucket is reused when full. No allocation per request beyond a new bucket. +- Tokens: 24 bytes, base64url (32 characters): 4-byte time, 1 byte, 19 bytes of HMAC-SHA-256 over kind | bucket | the first 5 bytes, keyed by the site key. Challenge token: issue time and bits; valid 5 minutes, once (a ring of the last 32 768 solved tokens). Pass: expiry and version. Page token: expiry 30 minutes ahead, the MAC also covering build and album; returned with every grant that did not carry a valid one for the same album. +- Proof of work: SHA-256(token as 32 ASCII bytes | nonce as 8 bytes big-endian) has at least `bits` leading zero bits. One 64-byte block, so the browser precomputes the state after the 8 constant words. +- Decision, in order: + 1. More than 4 × `photo_limit` photos unlocked in the window: 429. + 2. A valid, unused, solved challenge: reset the bucket's landing count and restart its photo count, count one solve, grant, and issue a pass for `pass_ttl`. + 3. Challenge, with `pow_bits` + min(6, solves in the window) bits, when photos unlocked since the last solve in the window exceed `photo_limit`; or, without a valid pass or page token for this album, when the context is `nav` and entropy < `min_entropy`, or when the window holds `landing_limit` low-entropy landings. + 4. Grant keys for the requested photos and count them; a `land` request without a pass or page token and with entropy < `min_entropy` counts as a low-entropy landing, so each page load counts once. + ## Loading in the browser -0. Gate: if the gate is on and `localStorage` has no pass for this build, the robot-check card is shown at once and a Web Worker (the tile worker script, a separate instance) brute-forces n with an allocation-free SHA-256 (midstate of the first 7 rounds and the constant schedule words precomputed). Each photo's pool file is fetched when the photo or cover is near. Until unlocked, or when a pool cannot be opened, the photo shows its probe level filled with random pool entries drawn into the grid cells (one fetch per cell at most). After unlocking, pools are decrypted lazily on the main thread (a few hundred SHA-256 blocks per photo), the seed fades in over the jumble, and the real tiles follow as below. +0. Keys. Covers open with the public cover key at once. On an album page the viewer asks `/k` for the current photo and its neighbours (`context` "nav" when the page was opened by a guarded click within the last 30 s, else "land"; the session's interaction score; the stored pass) in one request of up to 8 (one behind to six ahead), and waits for it; it asks again, with one more batch of up to 8 looking at most nine ahead, only when a photo within one behind or three ahead of the current one has no key. At most one request is in flight and nothing is queued beyond the latest batch. The page token from the first grant is kept in memory and sent with every later request; a returned pass goes to `localStorage`; a `stale` one is dropped. If the answer is a challenge, the hold card is shown over the album while a Web Worker (the tile worker script, a separate instance) solves it with an allocation-free SHA-256; after the hold and the solution the request is repeated with the answer. Each photo's pool file is fetched when the photo is near. While its key is on the way the photo draws nothing for up to 400 ms; after that, or while a challenge is up, it shows its probe level filled with random pool entries drawn into the grid cells (one fetch per cell at most). When the key arrives, the pool is decrypted on the main thread (a few hundred SHA-256 blocks), the seed fades in over the jumble, and the real tiles follow as below. With the gate off the keys come from the manifest and `/k` is never called. 1. Seed: draw the seed scaled and blurred. 2. Needed level: smallest level whose width ≥ displayed width × min(devicePixelRatio, max_dpr). 3. Probe: fetch 1–2 tiles of the level about 1/8 of the needed one; measure throughput; blend with earlier measurements kept in sessionStorage. @@ -96,19 +112,25 @@ Lucio brand (source of truth: ../LUCIO_ip): graphite #111114 ground, paper #F3F1 ## Discouraging saves -No `` for photos, only canvas. Output never contains an original. Right-click, drag, selection and long-press callouts are disabled. Hashed tile names, at least 3 × 3 tiles per level, decoys and sealed maps behind the robot check (above). `scramble_cells` (on by default): shuffle the full 64 px cells inside each tile with a per-photo key (HMAC of the site key and photo-hash, then a seeded Fisher–Yates per tile; tiles under two cells wide or high are left alone; tile overlap is 0 when on); the scramble seed travels only inside the sealed payload, and the client restores each tile once when it decodes it, before it is cached and drawn. Hotlink: Referer check on `/t/*` in the built-in server and the Caddy/nginx examples; an empty Referer and the site's own host are allowed. `robots.txt` disallows `/t/` and `/a/*/p/`. +No `` for photos, only canvas. Output never contains an original. Right-click, drag, selection and long-press callouts are disabled. Hashed tile names, at least 3 × 3 tiles per level, decoys and per-photo sealed maps whose keys come from `/k` (above). `scramble_cells` (on by default): shuffle the full 64 px cells inside each tile with a per-photo key (HMAC of the site key and photo-hash, then a seeded Fisher–Yates per tile; tiles under two cells wide or high are left alone; tile overlap is 0 when on); the scramble seed travels only inside the sealed payload, and the client restores each tile once when it decodes it, before it is cached and drawn. Hotlink: Referer check on `/t/*` in the built-in server and the Caddy/nginx examples; an empty Referer and the site's own host are allowed. `robots.txt` disallows `/t/` and `/a/*/p/`. -Robot check card (index and album pages, only without a pass for the current build): graphite-2 card, mono eyebrow "Photos · Lucio", the line "Press and hold to see the photos" in Bricolage Grotesque, and an 88 px round button with a beam progress ring. Holding for 900 ms (pointer, or Space/Enter while focused) completes it; releasing early resets the ring. If the worker is still searching, the ring turns indeterminate until it finishes. The rest of the page is `inert` while the card is up; focus starts on the button and returns to the page afterwards. The pass `{build, s}` is kept in `localStorage` (memory if storage is blocked); a pass that fails to open a pool is dropped and the card comes back. Reduced motion: no spin, no fade. +Interaction score: passive listeners on every page count mouse path length, direction changes over 30° between 8 px segments, distinct 8 px cells (a 4096-bit hashed set), touch gestures that move (or that the browser turns into a pan), wheel and scroll events (at most one per 100 ms) and key presses, trusted events only, with no allocation per event. Score = min(25, path ÷ 120) + min(35, 2.5 × turns) + min(20, cells ÷ 6) + min(45, 8 × gestures) + min(15, 1.5 × scrolls) + min(20, 2 × keys), capped at 100, kept for the tab's session in `sessionStorage` (memory if blocked). -Limits: this raises the cost of bulk downloading; it cannot stop a scraper that drives a real browser or reimplements the client, and decoys are byte-identical to tiles of other photos, so crawling every folder reveals which files are shared. +Guarded links: the index strips and the album end card's next-album link. A plain click with a score ≥ `min_entropy`, or with a stored pass, navigates normally and leaves a "nav" flag (slug and time) in `sessionStorage`. Otherwise the click is held back, the card is shown on the current page, a challenge for that album is requested at once (`photos: []`, context "nav") and solved while the visitor holds; then the pass is stored and the page navigates with the flag. Esc closes the card on these pages. Modified clicks (new tab) are not guarded; the new tab lands as "land". + +Hold card: graphite-2 card, mono eyebrow "Photos · Lucio", the line "Press and hold to see the photos" in Bricolage Grotesque, and an 88 px round button with a beam progress ring. Holding for 900 ms (pointer, or Space/Enter while focused) completes it; releasing early resets the ring. Then the ring turns indeterminate until the worker has a solution and the server has answered. A pointer that cannot be captured still works. The rest of the page is `inert` while the card is up; focus starts on the button and returns to the page afterwards. The pass is kept in `localStorage` (memory if storage is blocked). It is never shown on load of the index. Reduced motion: no spin, no fade. + +Limits: this raises the cost of bulk downloading; it cannot stop a scraper that drives a real browser or reimplements the client. The score is self-reported, so a bot that fakes it is bounded only by `photo_limit` per address, the escalating proof of work and the 429 cap; and decoys are byte-identical to tiles of other photos, so crawling every folder reveals which files are shared. ## Config `/etc/luphoto/config.toml` ```toml [server] -mode = "export" -listen = "127.0.0.1:8080" -base_url = "https://photos.luciochen.com" +mode = "export" +listen = "127.0.0.1:8080" +base_url = "https://photos.luciochen.com" +trusted_proxies = ["127.0.0.1/32", "::1/128"] +client_ip_header = "X-Forwarded-For" [paths] albums = "/srv/luphoto/albums" @@ -141,8 +163,13 @@ keep_builds = 3 block_context_menu = true hotlink_allow = ["photos.luciochen.com"] decoys = 4 -gate = true +gate = "server" pow_bits = 20 +photo_limit = 400 +min_entropy = 20 +landing_limit = 5 +window = "10m" +pass_ttl = "12h" ``` Defaults when a path is missing: running as root or under systemd uses `/var/lib/luphoto/site` and `/var/cache/luphoto`; otherwise `$XDG_DATA_HOME/luphoto/site` and `$XDG_CACHE_HOME/luphoto` (Go `os.UserCacheDir` equivalents). The site key and the per-photo processing records live in the state folder (`state/`) next to the output. SIGHUP re-reads the config and rebuilds. The watcher ignores `.part`, `.tmp`, dotfiles and rsync temp names. @@ -151,8 +178,8 @@ Defaults when a path is missing: running as root or under systemd uses `/var/lib - `.deb` via nfpm: binary, `/etc/luphoto/config.toml`, systemd unit, `luphoto` user, `/srv/luphoto/albums`. Depends on `libvips-tools`. Ubuntu 22.04/24.04, Debian 12; other distros: tarball + unit file. - systemd: read-only albums, read-write output and cache only, NoNewPrivileges, ProtectSystem=strict. -- Cloudflare Tunnel; cache rule `/t/*` for a month; HTML and manifests short TTL; manifests are build-named, so no purging. -- Caddy (export): root `/var/lib/luphoto/site/current`, `/t/*` `public, max-age=31536000, immutable`, `/a/*` `max-age=60`, `/og/*` and `/assets/*` immutable too, HTML and index JSON `max-age=60`, CSP `default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'`, `nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, hotlink 403 on `/t/*`, precompressed gzip, no directory listings, `404.html` for missing paths, GET/HEAD only. Serve mode: `reverse_proxy 127.0.0.1:8080`, the built-in server sends the same headers. nginx equivalent provided. +- Cloudflare Tunnel; cache rule `/t/*` for a month; HTML and manifests short TTL; manifests are build-named, so no purging; `/k` bypasses the cache. Set `client_ip_header = "CF-Connecting-IP"` and keep the tunnel's source (loopback) in `trusted_proxies`. +- Caddy (export): root `/var/lib/luphoto/site/current`, `/t/*` `public, max-age=31536000, immutable`, `/a/*` `max-age=60`, `/og/*` and `/assets/*` immutable too, HTML and index JSON `max-age=60`, CSP `default-src 'self'; img-src 'self' blob: data:; font-src 'self'; worker-src 'self'; frame-ancestors 'none'`, `nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, hotlink 403 on `/t/*`, precompressed gzip, no directory listings, `404.html` for missing paths, GET/HEAD only, except `/k`, which is proxied to the daemon on `server.listen` with the client address in `X-Forwarded-For`. Serve mode: `reverse_proxy 127.0.0.1:8080`, the built-in server sends the same headers. nginx equivalent provided. ## Milestones diff --git a/internal/app/app.go b/internal/app/app.go index f7905d3..be5c1d9 100644 --- a/internal/app/app.go +++ b/internal/app/app.go @@ -3,6 +3,8 @@ package app import ( "context" "log" + "net/http" + "net/url" "os" "os/signal" "sync" @@ -12,7 +14,10 @@ import ( "github.com/luciochen233/luphoto/internal/build" "github.com/luciochen233/luphoto/internal/config" + "github.com/luciochen233/luphoto/internal/keys" + "github.com/luciochen233/luphoto/internal/process" "github.com/luciochen233/luphoto/internal/server" + "github.com/luciochen233/luphoto/internal/site" "github.com/luciochen233/luphoto/internal/watch" ) @@ -24,7 +29,9 @@ type daemon struct { logger *log.Logger cfg atomic.Pointer[config.Config] builds chan string + keys *keys.Service handler *server.Handler + root http.Handler server *server.Server watchCancel context.CancelFunc watchDone chan struct{} @@ -36,6 +43,17 @@ type daemon struct { func Run(ctx context.Context, mode, configPath string, cfg *config.Config, logger *log.Logger) error { d := &daemon{mode: mode, configPath: configPath, logger: logger, builds: make(chan string, 1)} d.cfg.Store(cfg) + siteKey, err := process.SiteKey(cfg.State) + if err != nil { + return err + } + d.keys = keys.New(siteKey, keySettings(cfg)) + if mode == "serve" { + d.handler = server.NewHandler(handlerSettings(cfg), d.keys) + d.root = d.handler + } else { + d.root = keys.Only(d.keys) + } var builder sync.WaitGroup builder.Add(1) @@ -45,13 +63,15 @@ func Run(ctx context.Context, mode, configPath string, cfg *config.Config, logge }() d.requestBuild("startup") - if mode == "serve" { - d.handler = server.NewHandler(handlerSettings(cfg)) - srv, err := server.Start(cfg.Server.Listen, d.handler, logger) + if d.listens(cfg) { + srv, err := server.Start(cfg.Server.Listen, d.root, logger) if err != nil { return err } d.server = srv + if mode != "serve" { + logger.Printf("export: serving only %s on %s", site.KeyPath, cfg.Server.Listen) + } } d.syncWatcher(ctx, cfg) @@ -76,10 +96,35 @@ func Run(ctx context.Context, mode, configPath string, cfg *config.Config, logge } } +func (d *daemon) listens(cfg *config.Config) bool { + return d.mode == "serve" || string(cfg.Protection.Gate) == site.GateServer +} + func handlerSettings(cfg *config.Config) server.Settings { return server.Settings{Output: cfg.Paths.Output, HotlinkAllow: cfg.Protection.HotlinkAllow} } +func keySettings(cfg *config.Config) keys.Settings { + trusted, _ := config.ParsePrefixes(cfg.Server.TrustedProxies) + hosts := append([]string(nil), cfg.Protection.HotlinkAllow...) + if u, err := url.Parse(cfg.Server.BaseURL); err == nil && u.Hostname() != "" { + hosts = append(hosts, u.Hostname()) + } + p := cfg.Protection + return keys.Settings{ + Output: cfg.Paths.Output, + Gate: string(p.Gate), + Hosts: hosts, + Trusted: trusted, + IPHeader: cfg.Server.ClientIPHeader, + PowBits: p.PowBits, + PhotoLimit: p.PhotoLimit, + MinEntropy: p.MinEntropy, + LandingLimit: p.LandingLimit, + Window: p.Window.Duration, + PassTTL: p.PassTTL.Duration, + } +} func (d *daemon) requestBuild(reason string) { select { case d.builds <- reason: @@ -104,6 +149,7 @@ func (d *daemon) buildLoop(ctx context.Context) { d.logger.Printf("build failed: %v; previous build stays live", err) continue } + d.keys.Reload() d.logger.Print(summary.String()) } } @@ -166,8 +212,25 @@ func (d *daemon) reload(ctx context.Context) { if next.Server.Mode != previous.Server.Mode { d.logger.Printf("reload: server.mode changed to %q; restart the service to switch modes", next.Server.Mode) } - if d.server != nil && next.Server.Listen != previous.Server.Listen { - srv, err := server.Start(next.Server.Listen, d.handler, d.logger) + want := d.listens(next) + switch { + case !want && d.server != nil: + old := d.server + d.server = nil + go func() { + if err := old.Shutdown(shutdownTimeout); err != nil { + d.logger.Printf("reload: closing listener: %v", err) + } + }() + case want && d.server == nil: + srv, err := server.Start(next.Server.Listen, d.root, d.logger) + if err != nil { + d.logger.Printf("reload: cannot listen on %s: %v", next.Server.Listen, err) + } else { + d.server = srv + } + case want && next.Server.Listen != previous.Server.Listen: + srv, err := server.Start(next.Server.Listen, d.root, d.logger) if err != nil { d.logger.Printf("reload: cannot listen on %s, keeping %s: %v", next.Server.Listen, previous.Server.Listen, err) next.Server.Listen = previous.Server.Listen @@ -185,6 +248,7 @@ func (d *daemon) reload(ctx context.Context) { if d.handler != nil { d.handler.Update(handlerSettings(next)) } + d.keys.Update(keySettings(next)) d.syncWatcher(ctx, next) d.logger.Printf("reload: config %s applied", d.configPath) d.requestBuild("SIGHUP") diff --git a/internal/build/build.go b/internal/build/build.go index 9f213b6..4ee324f 100644 --- a/internal/build/build.go +++ b/internal/build/build.go @@ -14,6 +14,7 @@ import ( "path/filepath" "runtime" "sort" + "strconv" "strings" "sync" "time" @@ -246,7 +247,7 @@ func (b *builder) run(ctx context.Context) (*Summary, error) { } sum.Cached = len(records) - sum.Processed - id, err := newBuildID() + id, err := b.newBuildID() if err != nil { return nil, err } @@ -298,19 +299,33 @@ func (b *builder) run(ctx context.Context) (*Summary, error) { } sum.Albums = len(manifests) - gate, err := protect.NewGate(b.cfg.Protection.PowBits, b.cfg.Protection.Gate) + secret, err := protect.NewSecret() if err != nil { return nil, err } + keyer := protect.NewKeyer(secret) + coverKey := keyer.Cover() + covers := make(map[string]bool, len(manifests)) + for _, m := range manifests { + covers[m.Cover.Hash] = true + } + keys := make(map[string][32]byte, len(lives)) + for _, l := range lives { + if covers[l.rec.Hash] { + keys[l.rec.Hash] = coverKey + } else { + keys[l.rec.Hash] = keyer.Photo(l.rec.Hash) + } + } poolStart := time.Now() - pools, linked, err := b.pools(lives, gate) + pools, linked, err := b.pools(lives, keys) if err != nil { return nil, fmt.Errorf("decoys: %w", err) } sum.DecoysLinked = linked b.log.Printf("protect: %d pools sealed, %d decoys linked in %s", len(pools), linked, round(time.Since(poolStart))) - if err := b.writeBuild(id, manifests, gate, lives, pools); err != nil { + if err := b.writeBuild(id, manifests, secret, keys, coverKey, lives, pools); err != nil { return nil, err } if err := fsutil.SymlinkAtomic(filepath.Join("builds", id), b.current); err != nil { @@ -461,15 +476,43 @@ func (b *builder) carryOver(previous, slug, id string) (*site.Manifest, []*proce return &m, records } -func newBuildID() (string, error) { +func buildStamp(t time.Time) string { + return t.Format("20060102-150405") + fmt.Sprintf("-%06d", t.Nanosecond()/1000) +} + +func (b *builder) newBuildID() (string, error) { var suffix [3]byte if _, err := rand.Read(suffix[:]); err != nil { return "", err } - return time.Now().UTC().Format("20060102-150405") + "-" + hex.EncodeToString(suffix[:]), nil + t := time.Now().UTC().Truncate(time.Microsecond) + if entries, err := os.ReadDir(b.builds); err == nil { + for _, entry := range entries { + if last, ok := parseStamp(entry.Name()); ok && !t.After(last) { + t = last.Add(time.Microsecond) + } + } + } + return buildStamp(t) + "-" + hex.EncodeToString(suffix[:]), nil } -func (b *builder) writeBuild(id string, manifests []*site.Manifest, gate *protect.Gate, lives []*live, pools map[string]*pool) error { +func parseStamp(name string) (time.Time, bool) { + if len(name) < 15 { + return time.Time{}, false + } + t, err := time.Parse("20060102-150405", name[:15]) + if err != nil { + return time.Time{}, false + } + if len(name) >= 23 && name[15] == '-' && name[22] == '-' { + if micro, err := strconv.Atoi(name[16:22]); err == nil { + return t.Add(time.Duration(micro) * time.Microsecond), true + } + } + return t.Add(time.Second - time.Microsecond), true +} + +func (b *builder) writeBuild(id string, manifests []*site.Manifest, secret []byte, keys map[string][32]byte, coverKey [32]byte, lives []*live, pools map[string]*pool) error { stage := fsutil.TempName(filepath.Join(b.builds, id)) if err := os.MkdirAll(filepath.Join(stage, "a"), 0o755); err != nil { return err @@ -495,15 +538,14 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest, gate *protec MaxDPR: b.cfg.Loading.MaxDPR, Concurrency: b.cfg.Loading.Concurrency, BlockContextMenu: b.cfg.Protection.BlockContextMenu, - Gate: gate.Enabled, + Gate: string(b.cfg.Protection.Gate), + MinEntropy: b.cfg.Protection.MinEntropy, BaseURL: strings.TrimRight(b.cfg.Server.BaseURL, "/"), } - public := &site.Gate{Build: id} - if gate.Enabled { - public.Salt, public.Bits, public.Check = gate.SaltHex(), gate.Bits, gate.CheckHex() - } else { - public.Key = gate.KeyHex() + public := &site.Gate{Build: id, Mode: page.Gate, Cover: hex.EncodeToString(coverKey[:]), MinEntropy: page.MinEntropy} + if err := fsutil.WriteFileAtomic(filepath.Join(stage, protect.SecretName), secret, 0o600); err != nil { + return err } if err := fsutil.WriteFileAtomic(filepath.Join(stage, "robots.txt"), []byte(site.Robots), 0o644); err != nil { return err @@ -515,6 +557,15 @@ func (b *builder) writeBuild(id string, manifests []*site.Manifest, gate *protec index := &site.Index{Build: id, Tiles: b.tiles(), Gate: public, Albums: []site.IndexAlbum{}} for _, m := range manifests { m.Gate = public + if public.Mode == site.GateOff { + open := *public + open.Keys = make(map[string]string, len(m.Photos)) + for _, p := range m.Photos { + k := keys[p.Hash] + open.Keys[p.Hash] = hex.EncodeToString(k[:]) + } + m.Gate = &open + } if m.Hidden { continue } diff --git a/internal/build/protect.go b/internal/build/protect.go index 06855cc..fc8d772 100644 --- a/internal/build/protect.go +++ b/internal/build/protect.go @@ -142,7 +142,7 @@ func (idx *decoyIndex) pick(owner int32, size int) (*bucket, tier, int) { return nil, nil, 0 } -func (b *builder) pools(lives []*live, gate *protect.Gate) (map[string]*pool, int, error) { +func (b *builder) pools(lives []*live, keys map[string][32]byte) (map[string]*pool, int, error) { idx := newDecoyIndex(lives) out := make([]*pool, len(lives)) errs := make([]error, len(lives)) @@ -159,7 +159,7 @@ func (b *builder) pools(lives []*live, gate *protect.Gate) (map[string]*pool, in if i >= len(lives) { return } - p, n, err := b.pool(idx, int32(i), keyed, gate) + p, n, err := b.pool(idx, int32(i), keyed, keys[lives[i].rec.Hash]) out[i], errs[i] = p, err linked.Add(int64(n)) } @@ -181,7 +181,7 @@ type link struct { source string } -func (b *builder) pool(idx *decoyIndex, owner int32, keyed *process.Keyed, gate *protect.Gate) (*pool, int, error) { +func (b *builder) pool(idx *decoyIndex, owner int32, keyed *process.Keyed, key [32]byte) (*pool, int, error) { rec := idx.lives[owner].rec hash := rec.Hash decoys := b.cfg.Protection.Decoys @@ -254,7 +254,7 @@ func (b *builder) pool(idx *decoyIndex, owner int32, keyed *process.Keyed, gate if err != nil { return nil, made, err } - public.Sealed, err = protect.Seal(gate.Key, plain) + public.Sealed, err = protect.Seal(key, plain) if err != nil { return nil, made, err } diff --git a/internal/config/config.go b/internal/config/config.go index 5edb158..3658b48 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "io/fs" + "net/netip" "os" "path/filepath" "sort" @@ -28,9 +29,11 @@ type Config struct { } type Server struct { - Mode string `toml:"mode"` - Listen string `toml:"listen"` - BaseURL string `toml:"base_url"` + Mode string `toml:"mode"` + Listen string `toml:"listen"` + BaseURL string `toml:"base_url"` + TrustedProxies []string `toml:"trusted_proxies"` + ClientIPHeader string `toml:"client_ip_header"` } type Paths struct { @@ -74,8 +77,31 @@ type Protection struct { BlockContextMenu bool `toml:"block_context_menu"` HotlinkAllow []string `toml:"hotlink_allow"` Decoys int `toml:"decoys"` - Gate bool `toml:"gate"` + Gate GateMode `toml:"gate"` PowBits int `toml:"pow_bits"` + PhotoLimit int `toml:"photo_limit"` + MinEntropy int `toml:"min_entropy"` + LandingLimit int `toml:"landing_limit"` + Window Duration `toml:"window"` + PassTTL Duration `toml:"pass_ttl"` +} + +type GateMode string + +func (g *GateMode) UnmarshalTOML(value any) error { + switch v := value.(type) { + case string: + *g = GateMode(strings.TrimSpace(v)) + case bool: + if v { + *g = "server" + } else { + *g = "off" + } + default: + return fmt.Errorf("protection.gate must be \"server\" or \"off\"") + } + return nil } type Duration struct { @@ -98,9 +124,11 @@ func (d Duration) MarshalText() ([]byte, error) { func Defaults() Config { return Config{ Server: Server{ - Mode: "export", - Listen: "127.0.0.1:8080", - BaseURL: "https://photos.luciochen.com", + Mode: "export", + Listen: "127.0.0.1:8080", + BaseURL: "https://photos.luciochen.com", + TrustedProxies: []string{"127.0.0.1/32", "::1/128"}, + ClientIPHeader: "X-Forwarded-For", }, Paths: Paths{ Albums: "/srv/luphoto/albums", @@ -131,8 +159,13 @@ func Defaults() Config { BlockContextMenu: true, HotlinkAllow: []string{"photos.luciochen.com"}, Decoys: 4, - Gate: true, + Gate: "server", PowBits: 20, + PhotoLimit: 400, + MinEntropy: 20, + LandingLimit: 5, + Window: Duration{10 * time.Minute}, + PassTTL: Duration{12 * time.Hour}, }, } } @@ -288,9 +321,38 @@ func (c *Config) Validate() error { if c.Protection.Decoys < 0 || c.Protection.Decoys > 16 { add("protection.decoys must be between 0 and 16") } - if c.Protection.PowBits < 10 || c.Protection.PowBits > 26 { + p := c.Protection + switch p.Gate { + case "server", "off": + default: + add("protection.gate must be \"server\" or \"off\", got %q", p.Gate) + } + if p.PowBits < 10 || p.PowBits > 26 { add("protection.pow_bits must be between 10 and 26") } + if p.PhotoLimit < 1 || p.PhotoLimit > 1000000 { + add("protection.photo_limit must be between 1 and 1000000") + } + if p.MinEntropy < 0 || p.MinEntropy > 100 { + add("protection.min_entropy must be between 0 and 100") + } + if p.LandingLimit < 1 || p.LandingLimit > 10000 { + add("protection.landing_limit must be between 1 and 10000") + } + if p.Window.Duration < time.Minute || p.Window.Duration > 24*time.Hour { + add("protection.window must be between 1m and 24h") + } + if p.PassTTL.Duration < time.Minute || p.PassTTL.Duration > 30*24*time.Hour { + add("protection.pass_ttl must be between 1m and 720h") + } + if _, err := ParsePrefixes(c.Server.TrustedProxies); err != nil { + add("server.trusted_proxies: %v", err) + } + if h := c.Server.ClientIPHeader; h != "" && strings.IndexFunc(h, func(r rune) bool { + return !(r == '-' || r >= '0' && r <= '9' || r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z') + }) >= 0 { + add("server.client_ip_header %q is not a header name", h) + } for _, host := range c.Protection.HotlinkAllow { if host == "" || strings.ContainsAny(host, "/ ") { add("protection.hotlink_allow entry %q is not a host name", host) @@ -302,6 +364,31 @@ func (c *Config) Validate() error { return nil } +func ParsePrefixes(values []string) ([]netip.Prefix, error) { + out := make([]netip.Prefix, 0, len(values)) + for _, value := range values { + value = strings.TrimSpace(value) + if strings.Contains(value, "/") { + prefix, err := netip.ParsePrefix(value) + if err != nil { + return nil, fmt.Errorf("%q is not a CIDR", value) + } + if prefix.Addr().Is4In6() { + prefix = netip.PrefixFrom(prefix.Addr().Unmap(), max(0, prefix.Bits()-96)) + } + out = append(out, prefix.Masked()) + continue + } + addr, err := netip.ParseAddr(value) + if err != nil { + return nil, fmt.Errorf("%q is not an address or CIDR", value) + } + addr = addr.Unmap() + out = append(out, netip.PrefixFrom(addr, addr.BitLen())) + } + return out, nil +} + func within(parent, child string) bool { rel, err := filepath.Rel(parent, child) if err != nil { diff --git a/internal/keys/builds.go b/internal/keys/builds.go new file mode 100644 index 0000000..e6f6252 --- /dev/null +++ b/internal/keys/builds.go @@ -0,0 +1,127 @@ +package keys + +import ( + "os" + "path/filepath" + "strings" + "sync" + "time" + + "github.com/luciochen233/luphoto/internal/fsutil" + "github.com/luciochen233/luphoto/internal/protect" + "github.com/luciochen233/luphoto/internal/site" +) + +const ( + rescanEvery = 2 * time.Second + albumCache = 4096 +) + +type album map[string]struct{} + +type buildInfo struct { + id string + dir string + secret []byte + mu sync.Mutex + albums map[string]album +} + +type builds struct { + mu sync.RWMutex + root string + byID map[string]*buildInfo + scanned time.Time +} + +func validID(id string) bool { + if id == "" || len(id) > 64 { + return false + } + for i := 0; i < len(id); i++ { + c := id[i] + if !(c >= '0' && c <= '9' || c >= 'a' && c <= 'f' || c == '-') { + return false + } + } + return true +} + +func validSlug(slug string) bool { + return slug != "" && len(slug) <= 255 && !strings.HasPrefix(slug, ".") && !strings.ContainsAny(slug, "/\\\x00") +} + +func (b *builds) reload(root string) { + next := map[string]*buildInfo{} + b.mu.RLock() + old := b.byID + same := b.root == root + b.mu.RUnlock() + dir := filepath.Join(root, "builds") + entries, _ := os.ReadDir(dir) + for _, entry := range entries { + id := entry.Name() + if !entry.IsDir() || !validID(id) { + continue + } + if info, ok := old[id]; ok && same { + next[id] = info + continue + } + secret, err := protect.ReadSecret(filepath.Join(dir, id)) + if err != nil { + continue + } + next[id] = &buildInfo{id: id, dir: filepath.Join(dir, id), secret: secret, albums: map[string]album{}} + } + b.mu.Lock() + b.root = root + b.byID = next + b.scanned = time.Now() + b.mu.Unlock() +} + +func (b *builds) get(root, id string) *buildInfo { + if !validID(id) { + return nil + } + b.mu.RLock() + info := b.byID[id] + fresh := time.Since(b.scanned) < rescanEvery && b.root == root + b.mu.RUnlock() + if info != nil || fresh { + return info + } + b.reload(root) + b.mu.RLock() + info = b.byID[id] + b.mu.RUnlock() + return info +} + +func (info *buildInfo) album(slug string) album { + if !validSlug(slug) { + return nil + } + info.mu.Lock() + defer info.mu.Unlock() + if a, ok := info.albums[slug]; ok { + return a + } + var m struct { + Photos []struct { + Hash string `json:"hash"` + } `json:"photos"` + } + var a album + if err := fsutil.ReadJSON(filepath.Join(info.dir, "a", slug, site.ManifestName(info.id)), &m); err == nil { + a = make(album, len(m.Photos)) + for _, p := range m.Photos { + a[p.Hash] = struct{}{} + } + } + if a != nil || len(info.albums) < albumCache { + info.albums[slug] = a + } + return a +} diff --git a/internal/keys/keys.go b/internal/keys/keys.go new file mode 100644 index 0000000..e79732d --- /dev/null +++ b/internal/keys/keys.go @@ -0,0 +1,448 @@ +package keys + +import ( + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/binary" + "encoding/hex" + "encoding/json" + "hash" + "net" + "net/http" + "net/netip" + "net/url" + "strconv" + "strings" + "sync" + "sync/atomic" + "time" + + "github.com/luciochen233/luphoto/internal/protect" + "github.com/luciochen233/luphoto/internal/site" +) + +const ( + bodyLimit = 4 << 10 + maxPhotos = 8 + tokenRaw = 24 + tokenLen = 32 + macLen = tokenRaw - 5 + challengeTTL = 5 * time.Minute + clockSkew = 30 * time.Second + usedCapacity = 1 << 15 + maxNonce = 1 << 53 + contextNav = "nav" + contextLand = "land" + challengeKind = 'c' + passKind = 'p' + pageKind = 'g' + pageTTL = 30 * time.Minute +) + +type Settings struct { + Output string + Gate string + Hosts []string + Trusted []netip.Prefix + IPHeader string + PowBits int + PhotoLimit int + MinEntropy int + LandingLimit int + Window time.Duration + PassTTL time.Duration +} + +type Service struct { + settings atomic.Pointer[Settings] + table atomic.Pointer[table] + macs sync.Pool + builds builds + used used +} + +type used struct { + mu sync.Mutex + seen map[[macLen]byte]struct{} + ring [][macLen]byte + next int +} + +func (u *used) add(mac [macLen]byte) bool { + u.mu.Lock() + defer u.mu.Unlock() + if _, ok := u.seen[mac]; ok { + return false + } + if len(u.ring) < usedCapacity { + u.ring = append(u.ring, mac) + } else { + delete(u.seen, u.ring[u.next]) + u.ring[u.next] = mac + u.next = (u.next + 1) % usedCapacity + } + u.seen[mac] = struct{}{} + return true +} + +func New(siteKey []byte, settings Settings) *Service { + s := &Service{} + key := append([]byte(nil), siteKey...) + s.macs.New = func() any { return hmac.New(sha256.New, key) } + s.used.seen = make(map[[macLen]byte]struct{}) + s.Update(settings) + return s +} + +func (s *Service) Update(settings Settings) { + hosts := make([]string, 0, len(settings.Hosts)) + for _, h := range settings.Hosts { + if h = strings.ToLower(strings.TrimSpace(h)); h != "" { + hosts = append(hosts, h) + } + } + settings.Hosts = hosts + previous := s.settings.Swap(&settings) + if previous == nil || previous.Window != settings.Window || s.table.Load() == nil { + s.table.Store(newTable(settings.Window)) + } + if previous == nil || previous.Output != settings.Output { + s.builds.reload(settings.Output) + } +} + +func (s *Service) Reload() { + if set := s.settings.Load(); set != nil { + s.builds.reload(set.Output) + } +} + +func (s *Service) sign(kind byte, bucket [16]byte, head []byte, scope ...string) [32]byte { + mac := s.macs.Get().(hash.Hash) + mac.Reset() + var buf [1 + 16 + 5]byte + buf[0] = kind + copy(buf[1:], bucket[:]) + copy(buf[17:], head) + mac.Write(buf[:]) + for _, part := range scope { + mac.Write([]byte{0}) + mac.Write([]byte(part)) + } + var out [32]byte + mac.Sum(out[:0]) + s.macs.Put(mac) + return out +} + +func (s *Service) token(kind byte, bucket [16]byte, stamp uint32, extra byte, scope ...string) string { + var raw [tokenRaw]byte + binary.BigEndian.PutUint32(raw[:4], stamp) + raw[4] = extra + sum := s.sign(kind, bucket, raw[:5], scope...) + copy(raw[5:], sum[:macLen]) + return base64.RawURLEncoding.EncodeToString(raw[:]) +} + +func (s *Service) open(kind byte, bucket [16]byte, text string, scope ...string) (uint32, byte, [macLen]byte, bool) { + var raw [tokenRaw]byte + var mac [macLen]byte + if len(text) != tokenLen { + return 0, 0, mac, false + } + if n, err := base64.RawURLEncoding.Decode(raw[:], []byte(text)); err != nil || n != tokenRaw { + return 0, 0, mac, false + } + sum := s.sign(kind, bucket, raw[:5], scope...) + if !hmac.Equal(sum[:macLen], raw[5:]) { + return 0, 0, mac, false + } + copy(mac[:], raw[5:]) + return binary.BigEndian.Uint32(raw[:4]), raw[4], mac, true +} + +func (s *Service) passValid(bucket [16]byte, text string, now time.Time, ttl time.Duration) bool { + expiry, _, _, ok := s.open(passKind, bucket, text) + if !ok { + return false + } + at := time.Unix(int64(expiry), 0) + return now.Before(at) && at.Sub(now) <= ttl+clockSkew +} + +func (s *Service) pageValid(bucket [16]byte, text, build, album string, now time.Time) bool { + if text == "" { + return false + } + expiry, _, _, ok := s.open(pageKind, bucket, text, build, album) + if !ok { + return false + } + at := time.Unix(int64(expiry), 0) + return now.Before(at) && at.Sub(now) <= pageTTL+clockSkew +} + +func (s *Service) solved(bucket [16]byte, c *challengeAnswer, now time.Time) bool { + if c == nil || c.Nonce > maxNonce { + return false + } + issued, bits, mac, ok := s.open(challengeKind, bucket, c.Token) + if !ok || bits < 1 || bits > 32 { + return false + } + at := time.Unix(int64(issued), 0) + if now.Sub(at) > challengeTTL || at.Sub(now) > clockSkew { + return false + } + var msg [tokenLen + 8]byte + copy(msg[:], c.Token) + binary.BigEndian.PutUint64(msg[tokenLen:], c.Nonce) + sum := sha256.Sum256(msg[:]) + if binary.BigEndian.Uint32(sum[:4])>>(32-uint(bits)) != 0 { + return false + } + return s.used.add(mac) +} + +type challengeAnswer struct { + Token string `json:"token"` + Nonce uint64 `json:"nonce"` +} + +type request struct { + Build string `json:"build"` + Album string `json:"album"` + Photos []string `json:"photos"` + Context string `json:"context"` + Entropy float64 `json:"entropy"` + Pass string `json:"pass"` + Page string `json:"page"` + Challenge *challengeAnswer `json:"challenge"` +} + +type granted struct { + Keys map[string]string `json:"keys"` + Pass string `json:"pass,omitempty"` + Page string `json:"page,omitempty"` + Stale bool `json:"stale,omitempty"` +} + +type puzzle struct { + Token string `json:"token"` + Bits int `json:"bits"` +} + +type challenged struct { + Challenge puzzle `json:"challenge"` + Stale bool `json:"stale,omitempty"` +} + +type failure struct { + Error string `json:"error"` +} + +func reply(w http.ResponseWriter, status int, body any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + enc := json.NewEncoder(w) + enc.SetEscapeHTML(false) + _ = enc.Encode(body) +} + +func (s *Service) ServeHTTP(w http.ResponseWriter, r *http.Request) { + header := w.Header() + header.Set("Cache-Control", "no-store") + set := s.settings.Load() + if set.Gate != site.GateServer { + reply(w, http.StatusNotFound, failure{"off"}) + return + } + if r.Method != http.MethodPost { + header.Set("Allow", "POST") + reply(w, http.StatusMethodNotAllowed, failure{"method"}) + return + } + if !allowedOrigin(r, set.Hosts) { + reply(w, http.StatusForbidden, failure{"origin"}) + return + } + r.Body = http.MaxBytesReader(w, r.Body, bodyLimit) + var req request + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + reply(w, http.StatusBadRequest, failure{"body"}) + return + } + if len(req.Photos) > maxPhotos || (req.Context != contextNav && req.Context != contextLand) || !(req.Entropy >= 0 && req.Entropy <= 100) { + reply(w, http.StatusBadRequest, failure{"request"}) + return + } + info := s.builds.get(set.Output, req.Build) + if info == nil { + reply(w, http.StatusBadRequest, failure{"build"}) + return + } + members := info.album(req.Album) + if members == nil { + reply(w, http.StatusBadRequest, failure{"album"}) + return + } + photos := req.Photos[:0] + for _, h := range req.Photos { + if _, ok := members[h]; !ok { + continue + } + dup := false + for _, seen := range photos { + if seen == h { + dup = true + break + } + } + if !dup { + photos = append(photos, h) + } + } + now := time.Now() + bucket := bucketOf(clientIP(r, set)) + pass := req.Pass != "" && s.passValid(bucket, req.Pass, now, set.PassTTL) + stale := req.Pass != "" && !pass + page := s.pageValid(bucket, req.Page, req.Build, req.Album, now) + solved := s.solved(bucket, req.Challenge, now) + out := s.table.Load().decide(bucket, now, input{ + nav: req.Context == contextNav, + low: req.Entropy < float64(set.MinEntropy), + pass: pass, + page: page, + solved: solved, + photos: len(photos), + photoLimit: set.PhotoLimit, + landings: set.LandingLimit, + powBits: set.PowBits, + }) + switch out.verdict { + case limited: + header.Set("Retry-After", strconv.Itoa(max(1, int((out.retry+time.Second-1)/time.Second)))) + reply(w, http.StatusTooManyRequests, failure{"limit"}) + case challenge: + reply(w, http.StatusOK, challenged{Challenge: puzzle{Token: s.token(challengeKind, bucket, uint32(now.Unix()), byte(out.bits)), Bits: out.bits}, Stale: stale}) + default: + body := granted{Keys: make(map[string]string, len(photos)), Stale: stale && !solved} + keyer := protect.NewKeyer(info.secret) + for _, h := range photos { + k := keyer.Photo(h) + body.Keys[h] = hex.EncodeToString(k[:]) + } + if solved { + body.Pass = s.token(passKind, bucket, uint32(now.Add(set.PassTTL).Unix()), 1) + } + if !page { + body.Page = s.token(pageKind, bucket, uint32(now.Add(pageTTL).Unix()), 1, req.Build, req.Album) + } + reply(w, http.StatusOK, body) + } +} + +func Only(keys http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + header := w.Header() + header.Set("X-Content-Type-Options", "nosniff") + header.Set("Referrer-Policy", "strict-origin-when-cross-origin") + if r.URL.Path != site.KeyPath { + header.Set("Cache-Control", "no-store") + http.NotFound(w, r) + return + } + keys.ServeHTTP(w, r) + }) +} + +func hostOf(hostport string) string { + if h, _, err := net.SplitHostPort(hostport); err == nil { + return strings.ToLower(h) + } + return strings.ToLower(strings.Trim(hostport, "[]")) +} + +func allowedOrigin(r *http.Request, hosts []string) bool { + source := r.Header.Get("Origin") + if source == "" { + source = r.Header.Get("Referer") + } + if source == "" || source == "null" { + return false + } + u, err := url.Parse(source) + if err != nil || u.Host == "" || (u.Scheme != "http" && u.Scheme != "https") { + return false + } + host := strings.ToLower(u.Hostname()) + if host == hostOf(r.Host) { + return true + } + for _, allowed := range hosts { + if host == allowed { + return true + } + } + return false +} + +func trusted(addr netip.Addr, prefixes []netip.Prefix) bool { + for _, p := range prefixes { + if p.Contains(addr) { + return true + } + } + return false +} + +func clientIP(r *http.Request, set *Settings) netip.Addr { + var peer netip.Addr + if ap, err := netip.ParseAddrPort(r.RemoteAddr); err == nil { + peer = ap.Addr().Unmap() + } else if a, err := netip.ParseAddr(r.RemoteAddr); err == nil { + peer = a.Unmap() + } + if set.IPHeader == "" || !peer.IsValid() || !trusted(peer, set.Trusted) { + return peer + } + values := r.Header.Values(set.IPHeader) + var leftmost netip.Addr + for i := len(values) - 1; i >= 0; i-- { + rest := values[i] + for rest != "" { + part := rest + if at := strings.LastIndexByte(rest, ','); at >= 0 { + part, rest = rest[at+1:], rest[:at] + } else { + rest = "" + } + addr, err := netip.ParseAddr(strings.TrimSpace(part)) + if err != nil { + if ap, err := netip.ParseAddrPort(strings.TrimSpace(part)); err == nil { + addr = ap.Addr() + } else { + return peer + } + } + addr = addr.Unmap() + if !trusted(addr, set.Trusted) { + return addr + } + leftmost = addr + } + } + if leftmost.IsValid() { + return leftmost + } + return peer +} + +func bucketOf(addr netip.Addr) [16]byte { + key := addr.As16() + if addr.Is6() { + clear(key[8:]) + } + return key +} diff --git a/internal/keys/table.go b/internal/keys/table.go new file mode 100644 index 0000000..83209cb --- /dev/null +++ b/internal/keys/table.go @@ -0,0 +1,219 @@ +package keys + +import ( + "math" + "sync" + "time" +) + +const ( + slotCount = 16 + shardCount = 16 + maxBuckets = 200000 +) + +type slot struct { + photos uint32 + low uint16 + solved uint16 +} + +type bucket struct { + key [16]byte + at int64 + solveAt int64 + solveBase uint32 + prev int32 + next int32 + slots [slotCount]slot +} + +type shard struct { + mu sync.Mutex + index map[[16]byte]int32 + items []bucket + head int32 + tail int32 +} + +type table struct { + width int64 + span int64 + limit int + shards [shardCount]shard +} + +func newTable(window time.Duration) *table { + width := max(int64(time.Minute), (int64(window)+slotCount-1)/slotCount) + width = (width + int64(time.Minute) - 1) / int64(time.Minute) * int64(time.Minute) + span := min(int64(slotCount), (int64(window)+width-1)/width) + t := &table{width: width, span: span, limit: maxBuckets / shardCount} + for i := range t.shards { + t.shards[i].index = make(map[[16]byte]int32) + t.shards[i].head = -1 + t.shards[i].tail = -1 + } + return t +} + +func (s *shard) unlink(i int32) { + b := &s.items[i] + if b.prev >= 0 { + s.items[b.prev].next = b.next + } else { + s.head = b.next + } + if b.next >= 0 { + s.items[b.next].prev = b.prev + } else { + s.tail = b.prev + } + b.prev, b.next = -1, -1 +} + +func (s *shard) front(i int32) { + b := &s.items[i] + b.prev = -1 + b.next = s.head + if s.head >= 0 { + s.items[s.head].prev = i + } + s.head = i + if s.tail < 0 { + s.tail = i + } +} + +func (s *shard) get(key [16]byte, limit int, now int64) *bucket { + if i, ok := s.index[key]; ok { + if s.head != i { + s.unlink(i) + s.front(i) + } + return &s.items[i] + } + var i int32 + if len(s.items) < limit { + s.items = append(s.items, bucket{}) + i = int32(len(s.items) - 1) + } else { + i = s.tail + s.unlink(i) + delete(s.index, s.items[i].key) + } + s.items[i] = bucket{key: key, at: now, solveAt: math.MinInt64 / 2, prev: -1, next: -1} + s.index[key] = i + s.front(i) + return &s.items[i] +} + +func (b *bucket) advance(now int64) { + if now <= b.at { + return + } + if now-b.at >= slotCount { + b.slots = [slotCount]slot{} + } else { + for at := b.at + 1; at <= now; at++ { + b.slots[at%slotCount] = slot{} + } + } + b.at = now +} + +type input struct { + nav bool + low bool + pass bool + page bool + solved bool + photos int + photoLimit int + landings int + powBits int +} + +type verdict int + +const ( + grant verdict = iota + challenge + limited +) + +type outcome struct { + verdict verdict + bits int + retry time.Duration +} + +func shardOf(key [16]byte) int { + h := uint32(2166136261) + for _, c := range key { + h = (h ^ uint32(c)) * 16777619 + } + return int(h % shardCount) +} + +func (t *table) decide(key [16]byte, now time.Time, in input) outcome { + s := &t.shards[shardOf(key)] + s.mu.Lock() + defer s.mu.Unlock() + cur := now.UnixNano() / t.width + b := s.get(key, t.limit, cur) + b.advance(cur) + var photos, since, low, solved uint64 + for i := int64(0); i < t.span; i++ { + at := cur - i + sl := &b.slots[at%slotCount] + photos += uint64(sl.photos) + low += uint64(sl.low) + solved += uint64(sl.solved) + if at >= b.solveAt { + since += uint64(sl.photos) + } + } + if b.solveAt > cur-t.span { + since -= min(since, uint64(b.solveBase)) + } else { + since = photos + } + limit := uint64(in.photoLimit) + if photos > 4*limit { + return outcome{verdict: limited, retry: t.retry(b, cur, now, photos-4*limit)} + } + here := &b.slots[cur%slotCount] + if in.solved { + for i := range b.slots { + b.slots[i].low = 0 + } + if here.solved < math.MaxUint16 { + here.solved++ + } + b.solveAt = cur + b.solveBase = here.photos + here.photos += uint32(in.photos) + return outcome{verdict: grant} + } + admitted := in.pass || in.page + if since > limit || (!admitted && in.nav && in.low) || (!admitted && low >= uint64(in.landings)) { + return outcome{verdict: challenge, bits: min(32, in.powBits+int(min(6, solved)))} + } + here.photos += uint32(in.photos) + if !admitted && !in.nav && in.low && here.low < math.MaxUint16 { + here.low++ + } + return outcome{verdict: grant} +} + +func (t *table) retry(b *bucket, cur int64, now time.Time, excess uint64) time.Duration { + var dropped uint64 + for i := t.span - 1; i >= 0; i-- { + at := cur - i + dropped += uint64(b.slots[at%slotCount].photos) + if dropped >= excess { + return time.Duration((at+t.span)*t.width - now.UnixNano()) + } + } + return time.Duration(t.width) +} diff --git a/internal/process/processor.go b/internal/process/processor.go index 6d31c6d..35d0dc2 100644 --- a/internal/process/processor.go +++ b/internal/process/processor.go @@ -96,7 +96,7 @@ func New(ctx context.Context, cfg *config.Config) (*Processor, error) { return nil, err } } - key, err := loadOrCreateKey(filepath.Join(cfg.State, "site.key")) + key, err := SiteKey(cfg.State) if err != nil { return nil, err } @@ -150,7 +150,11 @@ func (p *Processor) VipsVersion() string { return p.vips.Version } -func loadOrCreateKey(path string) ([]byte, error) { +func SiteKey(state string) ([]byte, error) { + path := filepath.Join(state, "site.key") + if err := os.MkdirAll(state, 0o755); err != nil { + return nil, err + } key, err := os.ReadFile(path) if err == nil { if len(key) != 32 { diff --git a/internal/protect/protect.go b/internal/protect/protect.go index 325a977..3cbd2ca 100644 --- a/internal/protect/protect.go +++ b/internal/protect/protect.go @@ -1,63 +1,72 @@ package protect import ( + "crypto/hmac" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/binary" - "encoding/hex" + "fmt" + "hash" + "os" + "path/filepath" ) const ( - SealMagic = "luphoto-sealed-1" - NonceSize = 12 - keyLabel = "luphoto-key" - chkLabel = "luphoto-check" + SealMagic = "luphoto-sealed-1" + NonceSize = 12 + SecretName = ".secret" + SecretSize = 32 ) -type Gate struct { - Salt [16]byte - N uint32 - Bits int - Key [32]byte - Check [16]byte - Enabled bool -} - -func NewGate(bits int, enabled bool) (*Gate, error) { - g := &Gate{Bits: bits, Enabled: enabled} - var raw [4]byte - if _, err := rand.Read(g.Salt[:]); err != nil { +func NewSecret() ([]byte, error) { + secret := make([]byte, SecretSize) + if _, err := rand.Read(secret); err != nil { return nil, err } - if _, err := rand.Read(raw[:]); err != nil { + return secret, nil +} + +func ReadSecret(buildDir string) ([]byte, error) { + secret, err := os.ReadFile(filepath.Join(buildDir, SecretName)) + if err != nil { return nil, err } - g.N = binary.BigEndian.Uint32(raw[:]) & (uint32(1)<{(function(n){let t={from:"Guoliang",to:"Lucio",letters:[{ch:"G",kind:"keep",shared:"M8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50",fullA:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",fullB:"M8.50 0.00L8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50L80.00 91.50",out:[{d:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00",P:79.21,j:"end"},{d:"M58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",P:73.21,j:"start"}],in:[{d:"M8.50 22.00L8.50 0.00",P:22,j:"start"},{d:"M58.00 91.50L80.00 91.50",P:22,j:"start"}],x0:0,x1:0,dot:null},{ch:"u",kind:"keep",shared:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullA:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullB:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",out:[],in:[],x0:88.8,x1:88,dot:null},{ch:"o",kind:"keep",shared:"M38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullB:"M60.00 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50L60.00 91.50",out:[{d:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50",P:60.41,j:"both"}],in:[{d:"M38.00 46.50L60.00 46.50",P:22,j:"start"},{d:"M38.00 91.50L60.00 91.50",P:22,j:"start"}],x0:159,x1:158.2,dot:null},{ch:"l",kind:"fade",d:"M8.50 0.00L8.50 100.00",x0:230.8,x1:230.8,dot:null},{ch:"i",kind:"keep",shared:"M8.50 38.00L8.50 100.00",fullA:"M8.50 38.00L8.50 100.00",fullB:"M8.50 38.00L8.50 100.00",out:[],in:[],x0:262.8,x1:227.9,dot:[0,14,17]},{ch:"a",kind:"fade",d:"M38.00 91.50L51.50 91.50L51.50 78.00L51.50 60.00L51.50 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",x0:291.6,x1:291.6,dot:null},{ch:"n",kind:"fade",d:"M51.50 100.00L51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00L8.50 100.00",x0:362.7,x1:362.7,dot:null},{ch:"g",kind:"keep",shared:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M0.00 127.50L38.00 127.50A13.50 13.50 0 0 0 51.50 114.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00",fullB:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",out:[{d:"M51.50 60.00L51.50 114.00A13.50 13.50 0 0 1 38.00 127.50L0.00 127.50",P:113.21,j:"start"}],in:[],x0:432.9,x1:256.7,dot:null}],pad:17,vbw:526.9,vbh:170,stroke:17,raysT:"translate(0.000 22.727) scale(0.7727)"},e="M47.6 70.7L71.9 61.1L71.1 58.2L45.2 62.0ZM44.9 61.5L61.2 40.9L59.1 38.8L38.5 55.1ZM38.0 54.8L41.8 28.9L38.9 28.1L29.3 52.4Z",i="http://www.w3.org/2000/svg",s=(u,g)=>{let d=document.createElementNS(i,u);for(let v in g)d.setAttribute(v,g[v]);return d},r=()=>n.matchMedia&&n.matchMedia("(prefers-reduced-motion: reduce)").matches,o=u=>Math.max(0,Math.min(1,u)),a=u=>u*u*(3-2*u),h=.5;function l(u,g){let d=0,v=0,f=null,M=0;function S(L){let w=(L-M)/g;M=L,d=dp(1),reverse:()=>p(0),toggle:()=>p(v?0:1),set:L=>{cancelAnimationFrame(f),f=null,v=d=L,u(d)},stop:()=>{cancelAnimationFrame(f),f=null},get t(){return d}}}function c(u,g,d,v){let f=o(v)*g;if(u.style.visibility=f<.05?"hidden":"visible",d==="both"){let M=f/2;u.setAttribute("stroke-dasharray",M.toFixed(2)+" "+Math.max(0,g-2*M).toFixed(2)+" "+M.toFixed(2)),u.setAttribute("stroke-dashoffset","0")}else d==="end"?(u.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*g+20).toFixed(2)),u.setAttribute("stroke-dashoffset",(-(g-f)).toFixed(2))):(u.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*g+20).toFixed(2)),u.setAttribute("stroke-dashoffset","0"))}function b(u,g={}){let d=Object.assign({trigger:"hover",color:"currentColor",rays:"#FFF3CF",duration:450,autoDelay:1800},g),v=s("svg",{viewBox:"0 0 "+t.vbw+" "+t.vbh,role:"img","aria-label":"Guoliang Chen, Lucio"});v.style.display="block",v.style.width="100%",v.style.height="auto";let f=s("g",{transform:"translate("+t.pad+" "+t.pad+")",fill:"none",stroke:d.color,"stroke-width":t.stroke,"stroke-linejoin":"miter","stroke-linecap":"butt"});v.appendChild(f);let M=t.letters.map(w=>{let k=s("g",{transform:"translate("+w.x0+" 0)"});f.appendChild(k);let E=Object.assign({g:k,outEls:[],inEls:[]},w);if(w.kind==="fade")E.fadeEl=s("path",{d:w.d}),k.appendChild(E.fadeEl);else{E.fullA=s("path",{d:w.fullA}),k.appendChild(E.fullA),E.fullB=s("path",{d:w.fullB}),k.appendChild(E.fullB),w.shared&&k.appendChild(s("path",{d:w.shared}));for(let A of w.out){let T=s("path",{d:A.d});k.appendChild(T),E.outEls.push([T,A])}for(let A of w.in){let T=s("path",{d:A.d});k.appendChild(T),E.inEls.push([T,A])}}return w.dot&&(E.dotEl=s("rect",{x:w.dot[0],y:w.dot[1],width:w.dot[2],height:w.dot[2],rx:w.dot[2]*.22,fill:d.color,stroke:"none"}),k.appendChild(E.dotEl)),E}),S=s("path",{d:e,fill:d.rays,stroke:"none",opacity:0});f.appendChild(S),u.appendChild(v);function p(w){let k=a(o(w/h)),E=a(o((w-h)/(1-h)));for(let A of M){if(A.kind==="fade")A.fadeEl.setAttribute("opacity",(1-k).toFixed(3)),A.dotEl&&A.dotEl.setAttribute("opacity",(1-k).toFixed(3));else{for(let[T,C]of A.outEls)c(T,C.P,C.j,1-k);for(let[T,C]of A.inEls)c(T,C.P,C.j,k);A.fullA.style.visibility=k<=.001?"visible":"hidden",A.fullB.style.visibility=k>=.999?"visible":"hidden"}A.g.setAttribute("transform","translate("+(A.x0+(A.x1-A.x0)*E).toFixed(2)+" 0)")}S.setAttribute("transform","translate("+(M[0].x0+(M[0].x1-M[0].x0)*E).toFixed(2)+" 0) "+t.raysT),S.setAttribute("opacity",o((w-.8)/.2).toFixed(3))}let L=l(p,d.duration);return p(0),d.trigger==="hover"&&(u.addEventListener("mouseenter",L.play),u.addEventListener("mouseleave",L.reverse),u.addEventListener("focus",L.play),u.addEventListener("blur",L.reverse)),d.trigger==="click"&&u.addEventListener("click",L.toggle),d.trigger==="auto"&&setInterval(L.toggle,d.autoDelay+d.duration),Object.assign(L,{svg:v})}let y={C:[0,.75],L:[.25,.75],U:[.25,1],I:[.75,1],O:[.75,1.75]};function m(u,g,d){let v=g/2,f=d-v,M=v+f,S=f*Math.SQRT1_2,p=w=>w.toFixed(3);return{d:"M"+p(u-M+S)+" "+p(M-S)+"A"+p(f)+" "+p(f)+" 0 0 0 "+p(u-M)+" "+p(v)+"H"+p(M)+"A"+p(f)+" "+p(f)+" 0 0 0 "+p(v)+" "+p(M)+"V"+p(u-M)+"A"+p(f)+" "+p(f)+" 0 0 0 "+p(M)+" "+p(u-v)+"H"+p(u-M)+"A"+p(f)+" "+p(f)+" 0 0 0 "+p(u-v)+" "+p(u-M)+"V"+p(M)+"A"+p(f)+" "+p(f)+" 0 0 0 "+p(u-M+S)+" "+p(M-S)+"Z",P:4*(u-2*M)+2*Math.PI*f}}function x(u,g={}){let d=Object.assign({sequence:"LUCIO",color:"#F3F1EC",track:"#26262D",rays:"#FFF3CF",hold:480,morph:640,size:96,stroke:.17,radius:.22},g),v=120,f=v*d.stroke,M=v*d.radius,S=m(v,f,M),p=s("svg",{viewBox:"0 0 "+v+" "+v,width:d.size,height:d.size,role:"img","aria-label":"Loading"});d.track&&p.appendChild(s("path",{d:S.d,fill:"none",stroke:d.track,"stroke-width":f}));let L=s("path",{d:S.d,fill:"none",stroke:d.color,"stroke-width":f,"stroke-linecap":"butt"}),w=f/22,k=s("path",{d:e,fill:d.rays,transform:"translate("+(f-22*w).toFixed(3)+" "+(v-f-78*w).toFixed(3)+") scale("+w.toFixed(4)+")",opacity:0});p.appendChild(L),p.appendChild(k);let E=(R,U)=>{let P=Math.min(1,Math.max(0,U-R))*S.P;L.setAttribute("stroke-dasharray",P.toFixed(3)+" "+Math.max(0,S.P-P).toFixed(3)),L.setAttribute("stroke-dashoffset",(-R*S.P).toFixed(3))},A=(R,U)=>{let[P,K]=y[U];for(let H=-1;H<6;H++)if(P+H>=R[0]-1e-6&&K+H>=R[1]-1e-6)return[P+H,K+H];return[P,K]},T=d.sequence.split(""),C=0,I=y[T[0]].slice(),bt,gt,St=!1;E(I[0],I[1]),k.setAttribute("opacity",T[0]==="L"?1:0);function Tt(){if(St)return;let R=(C+1)%T.length,U=A(I,T[R]),P=I.slice(),K=T[C]==="L",H=T[R]==="L",Ct=()=>{I=U;let $=Math.floor(I[0]);I[0]-=$,I[1]-=$,C=R,E(I[0],I[1]),k.setAttribute("opacity",H?1:0),gt=setTimeout(Tt,d.hold)};if(r()){Ct();return}let ae=performance.now(),Pt=$=>{let F=Math.min(1,($-ae)/d.morph),It=F<.5?4*F*F*F:1-Math.pow(-2*F+2,3)/2;E(P[0]+(U[0]-P[0])*It,P[1]+(U[1]-P[1])*It),k.setAttribute("opacity",H?Math.max(0,(F-.6)/.4).toFixed(3):K?Math.max(0,1-F*2.5).toFixed(3):0),F<1?bt=requestAnimationFrame(Pt):Ct()};bt=requestAnimationFrame(Pt)}return gt=setTimeout(Tt,d.hold),u.appendChild(p),{svg:p,stop:()=>{St=!0,cancelAnimationFrame(bt),clearTimeout(gt)}}}n.LucioMorph={wordmark:b,loader:x}})(window);var B={graphite:"#111114",graphite3:"#26262D",paper:"#F3F1EC",beam:"#FFF3CF"};function yt(){return window.LucioMorph??null}function D(n,t){let e=yt();if(!e)return null;let i=document.createElement("span");i.className="wordmark-svg",i.setAttribute("aria-hidden","true"),n.appendChild(i);let s=e.wordmark(i,{trigger:"manual",color:B.paper,rays:B.beam});return s.svg.setAttribute("aria-hidden","true"),s.svg.removeAttribute("role"),t||s.set(1),n.classList.add("has-svg"),s}function zt(){let n=document.getElementById("chop-template");if(!(n instanceof HTMLTemplateElement))return null;let t=n.content.firstElementChild;return t?t.cloneNode(!0):null}function he(n){let t=n.seed+"|"+n.level+"|"+n.x+"|"+n.y,e=2166136261;for(let i=0;i>>0;return e}function le(n,t){let e=new Array(n);for(let r=0;r{i=i+1831565813|0;let r=Math.imul(i^i>>>15,1|i);return r=r+Math.imul(r^r>>>7,61|r)^r,((r^r>>>14)>>>0)/4294967296};for(let r=n-1;r>0;r--){let o=Math.floor(s()*(r+1)),a=e[r];e[r]=e[o],e[o]=a}return e}function Rt(n,t,e,i,s){n.drawImage(t,0,0);let r=s.cell,o=Math.floor(e/r),a=Math.floor(i/r);if(o<2||a<2)return;let h=o*a,l=le(h,he(s));for(let c=0;c"u"||e==="")return;let i=(navigator.hardwareConcurrency??2)>=4?2:1;for(let s=0;sthis.onReply(a.data,o),r.onerror=()=>this.dropWorker(o),this.workers.push(r)}catch{break}}request(t,e,i,s,r){return s.aborted?Promise.reject(new z):new Promise((o,a)=>{let h=this.byId.get(t);h?i{c.waiters.delete(l)&&(a(new z),c.waiters.size===0&&setTimeout(()=>{c.waiters.size===0&&this.byKey.get(c.key)===c&&this.cancel(c)},0))},{once:!0}),this.pump()})}cancelAll(){for(let t of[...this.byKey.values()]){let e=[...t.waiters];t.waiters.clear();for(let i of e)i.reject(new z);this.cancel(t)}}cancel(t){if(this.forget(t),!t.running){let e=this.queue.indexOf(t);e>=0&&this.queue.splice(e,1);return}t.running=!1,this.running--,t.controller?t.controller.abort():t.worker>=0&&this.workers[t.worker]&&this.workers[t.worker].postMessage({type:"abort",key:t.key}),this.pump()}forget(t){this.byId.get(t.id)===t&&this.byId.delete(t.id),this.byKey.delete(t.key)}pump(){for(;this.running0;){let t=0;for(let i=1;i0&&(!t.scramble||this.workersUnscramble)){let i=e[this.nextWorker++%e.length];t.worker=i,this.workers[i].postMessage({type:"fetch",key:t.key,url:t.url,scramble:t.scramble});return}this.runOnMainThread(t)}runOnMainThread(t){t.worker=-1,t.controller=new AbortController,this.fetchOnMainThread(t,t.controller.signal)}liveWorkers(){let t=[];return this.workers.forEach((e,i)=>{e&&t.push(i)}),t}dropWorker(t){let e=this.workers[t];if(e){e.terminate(),delete this.workers[t];for(let i of this.byKey.values())i.running&&i.worker===t&&this.runOnMainThread(i)}}async fetchOnMainThread(t,e){let i=performance.now();try{let s=await fetch(t.url,{signal:e,credentials:"same-origin"});if(!s.ok)throw new Error("HTTP "+s.status);let r=await s.blob(),o=performance.now()-i,a=await wt(r);t.scramble&&(a=await ce(a,t.scramble)),this.onReply({key:t.key,ok:!0,bitmap:a,bytes:r.size,ms:o},-1)}catch(s){this.onReply({key:t.key,ok:!1,bytes:0,ms:0,error:String(s)},-1)}}onReply(t,e){let i=this.byKey.get(t.key);if(!i||!i.running||i.worker!==e){t.bitmap&&q(t.bitmap);return}if(!t.ok&&e>=0&&(t.error==="unsupported-bitmap"||t.error==="unsupported-offscreen")){t.error==="unsupported-bitmap"?this.dropWorker(e):(this.workersUnscramble=!1,this.runOnMainThread(i));return}i.running=!1,this.running--,this.forget(i);let s=[...i.waiters];if(i.waiters.clear(),t.ok&&t.bitmap){let r={bitmap:t.bitmap,bytes:t.bytes,ms:t.ms};for(let o of s)o.resolve(r);s.length===0&&q(t.bitmap)}else{let r=new Error(t.error??"tile failed");for(let o of s)o.reject(r)}this.pump()}};var Ht=1024*1024;function de(){let n=navigator.deviceMemory;if(typeof n=="number"&&n<=4)return!0;let t=typeof matchMedia=="function"&&matchMedia("(pointer: coarse)").matches,e=Math.min(screen.width,screen.height);return t&&e<=820}function Ft(){return de()?120*Ht:250*Ht}var st=class{constructor(t){this.budget=t;this.entries=new Map;this.used=0}get(t){let e=this.entries.get(t);return e&&(this.entries.delete(t),this.entries.set(t,e)),e}has(t){return this.entries.has(t)}put(t,e){let i=this.entries.get(t);if(i){i.bitmap!==e&&q(e);return}let s=e.width*e.height*4;this.entries.set(t,{bitmap:e,bytes:s,at:performance.now()}),this.used+=s,this.trim(this.budget)}trim(t){for(;this.used>t&&this.entries.size>0;){let e=this.entries.keys().next();if(e.done)return;let i=this.entries.get(e.value);this.entries.delete(e.value),i&&(this.used-=i.bytes,q(i.bitmap))}}};var ue=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Y=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function qt(n,t){for(let e=t;e<64;e++){let i=n[e-15],s=n[e-2],r=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,o=(s>>>17|s<<15)^(s>>>19|s<<13)^s>>>10;n[e]=n[e-16]+r+n[e-7]+o|0}}function Lt(n,t,e,i){let s=n[0],r=n[1],o=n[2],a=n[3],h=n[4],l=n[5],c=n[6],b=n[7];for(let y=e;y>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7))+(h&l^~h&c)+ue[y]+t[y]|0,x=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&r^s&o^r&o)|0;b=c,c=l,l=h,h=a+m|0,a=o,o=r,r=s,s=m+x|0}n[0]=s,n[1]=r,n[2]=o,n[3]=a,n[4]=h,n[5]=l,n[6]=c,n[7]=b}var xt=new Int32Array(64),Mt=new Int32Array(8),N=new Int32Array(8);function Nt(n,t=new Uint8Array(32)){N.set(Y);let e=n.length,i=Math.ceil((e+9)/64);for(let s=0;s=r+56){let b=l-r-56;c=b<3?0:b===3?e>>>29&255:e*8>>>(7-b)*8&255}a=a<<8|c}xt[o]=a}qt(xt,16),Mt.set(N),Lt(Mt,xt,0,64);for(let o=0;o<8;o++)N[o]=N[o]+Mt[o]|0}for(let s=0;s<8;s++)t[s*4]=N[s]>>>24,t[s*4+1]=N[s]>>>16&255,t[s*4+2]=N[s]>>>8&255,t[s*4+3]=N[s]&255;return t}var me=new TextEncoder;function Ut(n,t,e){let i=me.encode(n),s=new Uint8Array(i.length+t.length+4);s.set(i),s.set(t,i.length);let r=i.length+t.length;return s[r]=e>>>24,s[r+1]=e>>>16&255,s[r+2]=e>>>8&255,s[r+3]=e&255,s}function Dt(n,t){return Nt(Ut("luphoto-key",n,t))}var ot=class{constructor(t,e){this.w=new Int32Array(64);this.mid=new Int32Array(8);this.s=new Int32Array(8);this.target=new Int32Array(4);let i=new Uint8Array(64);i.set(Ut("luphoto-check",t,0)),i[33]=128,i[62]=33*8>>>8,i[63]=33*8&255;let s=this.w;for(let r=0;r<16;r++)s[r]=i[r*4]<<24|i[r*4+1]<<16|i[r*4+2]<<8|i[r*4+3];this.saltTail=i[28]<<24;for(let r=16;r<22;r++){let o=s[r-15],a=s[r-2],h=(o>>>7|o<<25)^(o>>>18|o<<14)^o>>>3,l=(a>>>17|a<<15)^(a>>>19|a<<13)^a>>>10;s[r]=s[r-16]+h+s[r-7]+l|0}this.mid.set(Y),Lt(this.mid,s,0,7);for(let r=0;r<4;r++)this.target[r]=e[r*4]<<24|e[r*4+1]<<16|e[r*4+2]<<8|e[r*4+3]}run(t,e){let i=this.w,s=this.s,r=this.mid,o=this.target[0],a=this.saltTail;for(let h=t;h>>8,i[8]=(h&255)<<24|8388608,qt(i,22),s.set(r),Lt(s,i,7,64),(Y[0]+s[0]|0)===o&&(Y[1]+s[1]|0)===this.target[1]&&(Y[2]+s[2]|0)===this.target[2]&&(Y[3]+s[3]|0)===this.target[3])return h;return-1}},rt="luphoto-sealed-1",nt=12;function j(n){let t=new Uint8Array(n.length>>>1);for(let e=0;e>>24,i[45]=o>>>16&255,i[46]=o>>>8&255,i[47]=o&255,Nt(i,s);let h=Math.min(32,r.length-a);for(let l=0;lthis.onHeld())}onUnlock(t){this.listeners.push(t)}configure(t){if(!this.info){if(this.info=t,t.key){this.found=j(t.key),this.unlock(!1);return}if(this.key&&t.build!==this.build){this.reset();return}this.key||this.search()}}reject(t){t!==this.key||!this.stored||!this.info||this.info.key||this.reset()}abandon(){this.card?.dismiss(),this.card=null,this.worker?.terminate(),this.worker=null}reset(){Yt(null),this.key=null,this.stored=!1,this.held=!1,this.found=null,this.card||(this.card=new at(()=>this.onHeld())),this.search()}search(){let t=this.info;if(!t||!t.salt||!t.check||!t.bits||this.worker)return;let e=j(t.salt),i=r=>{if(this.worker?.terminate(),this.worker=null,r<0){this.card?.fail();return}this.found=Dt(e,r),this.held&&this.unlock(!0)},s=()=>this.searchHere(e,j(t.check??""),t.bits??0,i);if(typeof Worker>"u"||!this.workerUrl){s();return}try{let r=new Worker(this.workerUrl);this.worker=r,r.onmessage=o=>{typeof o.data.pow=="number"&&this.worker===r&&i(o.data.pow)},r.onerror=()=>{this.worker===r&&(r.terminate(),this.worker=null,s())},r.postMessage({type:"pow",salt:t.salt,check:t.check,bits:t.bits})}catch{this.worker=null,s()}}searchHere(t,e,i,s){let r=new ot(t,e),o=2**i,a=0,h=()=>{let l=Math.min(o,a+fe),c=r.run(a,l);if(a=l,c>=0||a>=o){s(c);return}setTimeout(h,0)};setTimeout(h,0)}onHeld(){this.held=!0,this.found?this.unlock(!0):this.card?.wait()}unlock(t){if(this.found){this.key=this.found,this.stored=!1,t&&this.enabled&&Yt({build:this.info?.build??this.build,s:Wt(this.key)}),this.card?.dismiss(),this.card=null;for(let e of this.listeners)e()}}},at=class{constructor(t){this.onHeld=t;this.inert=[];this.start=0;this.frame=0;this.holding=!1;this.finished=!1;this.restore=document.activeElement;let e=document.createElement("div");e.className="gate",e.setAttribute("role","dialog"),e.setAttribute("aria-modal","true"),e.setAttribute("aria-labelledby","gate-line");let i=document.createElement("div");i.className="gate-card";let s=document.createElement("p");s.className="gate-eyebrow",s.textContent="Photos \xB7 Lucio";let r=document.createElement("p");r.className="gate-line",r.id="gate-line",r.textContent=ve;let o=document.createElement("button");o.type="button",o.className="gate-hold",o.setAttribute("aria-label","Hold to see the photos"),o.setAttribute("aria-describedby","gate-status");let a=document.createElementNS(Bt,"svg");a.setAttribute("viewBox","0 0 64 64"),a.setAttribute("aria-hidden","true"),a.setAttribute("focusable","false");let h=(b,y)=>{let m=document.createElementNS(Bt,"circle");return m.setAttribute("class",b),m.setAttribute("cx","32"),m.setAttribute("cy","32"),m.setAttribute("r",y),m},l=h("gate-ring","28");l.setAttribute("pathLength","100"),a.append(h("gate-track","28"),l,h("gate-dot","6")),o.appendChild(a);let c=document.createElement("p");c.className="visually-hidden",c.id="gate-status",c.setAttribute("aria-live","polite"),i.append(s,r,o,c),e.appendChild(i),this.root=e,this.button=o,this.ring=l,this.status=c,this.text=r;for(let b of Array.from(document.body.children))b.hasAttribute("inert")||(b.setAttribute("inert",""),this.inert.push(b));document.body.appendChild(e),document.documentElement.classList.add("has-gate"),this.bind(),o.focus({preventScroll:!0})}bind(){let t=this.button;t.addEventListener("pointerdown",e=>{e.pointerType==="mouse"&&e.button!==0||(e.preventDefault(),t.setPointerCapture(e.pointerId),this.press())});for(let e of["pointerup","pointercancel","lostpointercapture"])t.addEventListener(e,()=>this.release());t.addEventListener("keydown",e=>{(e.key===" "||e.key==="Enter")&&(e.preventDefault(),e.repeat||this.press())}),t.addEventListener("keyup",e=>{(e.key===" "||e.key==="Enter")&&(e.preventDefault(),this.release())}),t.addEventListener("blur",()=>this.release()),t.addEventListener("click",e=>e.preventDefault()),t.addEventListener("contextmenu",e=>e.preventDefault()),this.root.addEventListener("transitionend",e=>{e.target===this.root&&this.root.classList.contains("is-leaving")&&this.root.remove()})}setProgress(t){this.ring.style.setProperty("stroke-dashoffset",String(100-Math.max(0,Math.min(1,t))*100))}press(){if(this.holding||this.finished)return;this.holding=!0,this.start=performance.now(),this.button.classList.add("is-pressed"),this.status.textContent="Keep holding";let t=e=>{if(!this.holding)return;let i=(e-this.start)/pe;if(this.setProgress(i),i>=1){this.holding=!1,this.finished=!0,this.frame=0,this.button.classList.remove("is-pressed"),this.onHeld();return}this.frame=requestAnimationFrame(t)};this.frame=requestAnimationFrame(t)}release(){this.holding&&(this.holding=!1,cancelAnimationFrame(this.frame),this.frame=0,this.button.classList.remove("is-pressed"),this.setProgress(0),this.status.textContent="")}wait(){this.root.classList.add("is-waiting"),this.setProgress(.28),this.status.textContent="One moment"}fail(){this.root.classList.remove("is-waiting"),this.finished=!0,this.setProgress(0),this.button.disabled=!0,this.text.textContent="Something went wrong. Reload the page to try again.",this.status.textContent=this.text.textContent}dismiss(){cancelAnimationFrame(this.frame);let t=this.root.contains(document.activeElement);for(let e of this.inert)e.removeAttribute("inert");document.documentElement.classList.remove("has-gate"),this.root.classList.add("is-leaving"),window.setTimeout(()=>this.root.remove(),400),t&&(this.restore instanceof HTMLElement&&this.restore!==document.body&&this.restore.isConnected?this.restore:document.querySelector("main"))?.focus({preventScroll:!0})}};var ge=400,X=class{constructor(t,e=()=>!0){this.canShow=e;this.handle=null;this.loader=null;this.timer=0;this.hideTimer=0;this.visible=!1;this.element=document.createElement("div"),this.element.className="busy",this.element.setAttribute("role","status"),this.element.setAttribute("aria-label","Loading"),t.appendChild(this.element)}watch(t){if(t===this.loader){this.update(t);return}this.loader=t,clearTimeout(this.timer),this.timer=0,this.hide(),this.update(t)}update(t){if(!t||t!==this.loader)return;let e=t.status;if(!e.active||e.sharp){clearTimeout(this.timer),this.timer=0,this.hide();return}if(!this.visible&&this.timer===0){let i=Math.max(0,ge-(performance.now()-e.started));this.timer=window.setTimeout(()=>this.check(),i)}}check(){this.timer=0;let t=this.loader;if(!(!t||!t.status.active||t.status.sharp)){if(!this.canShow()){this.timer=window.setTimeout(()=>this.check(),100);return}this.show()}}show(){if(!this.visible){if(clearTimeout(this.hideTimer),this.visible=!0,!this.handle){let t=yt();t&&(this.handle=t.loader(this.element,{size:56,color:B.paper,track:B.graphite3,rays:B.beam}),this.handle.svg.setAttribute("aria-hidden","true"))}this.element.classList.add("is-visible")}}hide(){this.visible&&(this.visible=!1,this.element.classList.remove("is-visible"),clearTimeout(this.hideTimer),this.hideTimer=window.setTimeout(()=>{!this.visible&&this.handle&&(this.handle.stop(),this.handle.svg.remove(),this.handle=null)},300))}},ht=class{constructor(t){this.loader=null;this.shown=!1;this.value=-1;this.element=document.createElement("div"),this.element.className="progress",this.element.setAttribute("aria-hidden","true"),t.appendChild(this.element)}watch(t){this.loader=t,this.value=-1,this.update(t)}update(t){if(!t||t!==this.loader)return;let e=t.status,i=e.active&&!e.sharp&&e.planned>0,s=e.planned>0?Math.min(1,e.done/e.planned):0;i!==this.shown&&(this.shown=i,this.element.classList.toggle("is-visible",i));let r=Math.round(s*1e3)/1e3;r!==this.value&&(this.value=r,this.element.style.transform="scaleX("+(i?r:1)+")")}};function lt(n,t,e){let i=t*e;for(let s=0;s=i)return s;return n.levels.length-1}function J(n,t){let e=n.tile_size,i=Math.max(0,t.u0*n.width),s=Math.min(n.width,t.u1*n.width),r=Math.max(0,t.v0*n.height),o=Math.min(n.height,t.v1*n.height);return s<=i||o<=r?null:{x0:Math.min(n.cols-1,Math.floor(i/e)),x1:Math.min(n.cols-1,Math.ceil(s/e)-1),y0:Math.min(n.rows-1,Math.floor(r/e)),y1:Math.min(n.rows-1,Math.ceil(o/e)-1)}}function Xt(n,t,e){let i=n.levels[t],s=i.tile_size,r=J(i,e);if(!r)return[];let o=(e.u0+e.u1)/2*i.width,a=(e.v0+e.v1)/2*i.height,h=[];for(let l=r.y0;l<=r.y1;l++)for(let c=r.x0;c<=r.x1;c++){let b=(c*s+Math.min((c+1)*s,i.width))/2,y=(l*s+Math.min((l+1)*s,i.height))/2;h.push({level:t,x:c,y:l,index:l*i.cols+c,distance:(b-o)**2+(y-a)**2})}return h.sort((l,c)=>l.distance-c.distance),h.map(({level:l,x:c,y:b,index:y})=>({level:l,x:c,y:b,index:y}))}function Vt(n,t,e,i,s,r){let o=n.tile_size,a=Math.round(i+t*o*r),h=Math.round(i+Math.min((t+1)*o,n.width)*r),l=Math.round(s+e*o*r),c=Math.round(s+Math.min((e+1)*o,n.height)*r);return h<=a||c<=l?null:{dx:a,dy:l,dw:h-a,dh:c-l}}function Zt(n,t,e,i,s,r,o,a){let h=e.tile_size,l=e.overlap??0,c=i*h,b=Math.min((i+1)*h,e.width),y=s*h,m=Math.min((s+1)*h,e.height),x=i>0?c-l:0,u=s>0?y-l:0,g=Math.round(r+c*a),d=Math.round(r+b*a),v=Math.round(o+y*a),f=Math.round(o+m*a);if(d<=g||f<=v)return;let M=Math.max(x,(g-r)/a),S=Math.min(x+t.width,(d-r)/a),p=Math.max(u,(v-o)/a),L=Math.min(u+t.height,(f-o)/a);S<=M||L<=p||n.drawImage(t,M-x,p-u,S-M,L-p,g,v,d-g,f-v)}var Kt="luphoto.throughput";function jt(){try{let n=Number(sessionStorage.getItem(Kt));return Number.isFinite(n)&&n>0?n:null}catch{return null}}function _t(){return jt()??1e3}function Gt(n){let t=jt(),e=t===null?n:t*(1-.5)+n*.5;try{sessionStorage.setItem(Kt,String(e))}catch{return e}return e}var W=180,Jt=400,ye=2e3,O=16,Et="j:";function we(n,t){return new Promise((e,i)=>{if(t.aborted){i(new z);return}let s=setTimeout(()=>{t.removeEventListener("abort",r),e()},n),r=()=>{clearTimeout(s),i(new z)};t.addEventListener("abort",r,{once:!0})})}function xe(n,t,e){return t.aborted?Promise.resolve(e):new Promise(i=>{let s=()=>i(e);t.addEventListener("abort",s,{once:!0}),n.then(r=>{t.removeEventListener("abort",s),i(r)})})}var Qt=3,ct=4,V=class{constructor(t,e,i){this.pyramid=t;this.poolUrl=e;this.env=i;this.seedImage=null;this.seedPromise=null;this.seedAt=0;this.pool=null;this.sealed="";this.poolPromise=null;this.poolRetryAt=0;this.opened=null;this.ids=null;this.triedKey=null;this.jumbleLevel=-1;this.jumble=[];this.session=null;this.prefetchController=null;this.finalLevel=-1;this.targetLevel=-1;this.status={active:!1,started:0,planned:0,done:0,sharp:!1}}tileUrl(t){let e=this.env.tiles;return e.path+this.pyramid.hash+"/"+t+"."+e.format}ensurePool(){return this.pool?Promise.resolve(!0):(this.poolPromise||(this.poolPromise=fetch(this.poolUrl,{credentials:"same-origin"}).then(t=>t.ok?t.json():Promise.reject(new Error("pool"))).then(t=>{let e=this.pyramid.levels;if(!Array.isArray(t.levels)||t.levels.length!==e.length||typeof t.sealed!="string")throw new Error("pool");for(let i=0;i(this.poolPromise=null,this.poolRetryAt=performance.now()+ye,!1))),this.poolPromise)}open(){if(this.opened)return!0;let t=this.env.gate.key,e=this.pool;if(!t||!e||t===this.triedKey)return!1;this.triedKey=t;let i=Ot(t,this.sealed),s=null;if(i)try{s=JSON.parse(new TextDecoder().decode(i))}catch{s=null}let r=this.pyramid.levels;if(!s||!Array.isArray(s.levels)||s.levels.length!==r.length)return this.env.gate.reject(t),!1;let o=[];for(let a=0;a=0&&y=this.poolRetryAt&&this.ensurePool();return}this.opened||this.open()}ensureSeed(){return this.opened?(this.seedPromise||(this.seedPromise=this.decodeSeed().then(()=>{this.seedAt=performance.now(),this.env.requestDraw()},()=>{})),this.seedPromise):Promise.resolve()}async decodeSeed(){let t=this.opened?.seed;if(!t)return;let e=await wt(new Blob([kt(t)],{type:"image/"+this.env.tiles.format})),i=document.createElement("canvas");i.width=e.width*ct,i.height=e.height*ct;let s=i.getContext("2d");if(!s){this.seedImage=e;return}s.imageSmoothingEnabled=!0,s.imageSmoothingQuality="high","filter"in s&&(s.filter="blur("+ct*.75+"px)");let r=ct*2;s.drawImage(e,-r,-r,i.width+r*2,i.height+r*2),q(e),this.seedImage=i}async request(t,e,i,s,r){let o=this.tileUrl(e),a;try{a=await this.env.scheduler.request(t,o,i,s,r)}catch(h){if(s.aborted||h instanceof z)throw h;await we(Jt+Math.random()*Jt,s),a=await this.env.scheduler.request(t,o,i,s,r)}return this.env.cache.put(t,a.bitmap),this.env.requestDraw(),a}fetchTile(t,e,i){let s=this.ids,r=this.opened;if(!s||!r)return Promise.reject(new z);let o=s[t.level][t.index],a=this.env.tiles,h=a.cell??64,l=a.scrambled&&r.scramble&&this.pyramid.levels[t.level].tile_size>=2*h?{seed:r.scramble,level:t.level,x:t.x,y:t.y,cell:h}:void 0;return this.request(o,o,e,i,l)}fetchJumble(t,e,i){return this.request(Et+t,t,e,i)}uncached(t,e){let i=this.ids;return i?Xt(this.pyramid,t,e).filter(s=>!this.env.cache.has(i[t][s.index])):[]}uncachedBytes(t,e){let i=this.opened?.levels[t].bytes??[],s=0;for(let r of this.uncached(t,e))s+=i[r.index]??0;return s}chooseJumble(t,e){let i=this.pool;if(!i)return[];if(this.jumbleLevel<0){let s=this.probeLevel(t,e),r=this.pyramid.levels[s].cols*this.pyramid.levels[s].rows,o=i[s].length/O,a=new Array(r);for(let h=0;h!this.env.cache.has(Et+s))}probeLevel(t,e){return Math.max(0,lt(this.pyramid,t.displayWidth,e)-Qt)}notify(){this.env.onStatus?.(this)}track(t,e){return this.status.planned+=t.length,this.notify(),Promise.allSettled(t.map(i=>i().finally(()=>{this.session===e&&(this.status.done++,this.notify())})))}start(t,e,i){this.stopSession();let s=new AbortController;this.session=s,this.targetLevel=-1,this.status.active=!0,this.status.started=performance.now(),this.status.planned=0,this.status.done=0,this.status.sharp=!1,this.notify(),this.run(t,e,s).then(()=>{this.session===s&&(this.session=null,this.status.active=!1,this.notify()),(!s.signal.aborted||s.signal.reason==="deadline")&&i()})}async run(t,e,i){let s=i.signal,r=performance.now(),o=this.env.settings.budgetMs,a=setTimeout(()=>i.abort("deadline"),o);try{let h=await xe(this.ensurePool(),s,!1);if(s.aborted)return;if(!h||!this.open()){let g=this.chooseJumble(t,e);await this.track(g.map(d=>()=>this.fetchJumble(d,et,s)),i);return}if(await this.ensureSeed(),s.aborted)return;let l=lt(this.pyramid,t.displayWidth,e),c=Math.max(0,l-Qt),b=this.uncached(c,t).slice(0,2);if(b.length>0){let g=await this.track(b.map(f=>()=>this.fetchTile(f,et,s)),i),d=0,v=0;for(let f of g)f.status==="fulfilled"&&(d+=f.value.bytes,v=Math.max(v,f.value.ms));d>0&&v>0&&Gt(d/v)}if(s.aborted)return;this.finalLevel=Math.max(this.finalLevel,c);let y=_t(),m=o-(performance.now()-r),x=c;for(let g=l;g>c;g--)if(this.uncachedBytes(g,t)/y<=m*.8){x=g;break}let u=[];x-c>=2&&u.push(Math.floor((c+x)/2)),x>c&&u.push(x),this.finalLevel=x,this.targetLevel=x,this.env.requestDraw();for(let g of u)if(await this.track(this.uncached(g,t).map(d=>()=>this.fetchTile(d,et,s)),i),s.aborted)return}finally{clearTimeout(a)}}prefetchProbe(t,e){let s=this.resetPrefetch().signal;this.ensurePool().then(async r=>{if(!(s.aborted||!r)){if(!this.open()){for(let o of this.chooseJumble(t,e))this.fetchJumble(o,it,s).catch(()=>{});return}if(await this.ensureSeed(),!s.aborted)for(let o of this.uncached(this.probeLevel(t,e),t))this.fetchTile(o,it,s).catch(()=>{})}})}prefetchLevel(t,e){if(e<0||!this.opened)return;let i=this.resetPrefetch().signal;for(let s of this.uncached(e,t))this.fetchTile(s,it,i).catch(()=>{})}resetPrefetch(){return this.prefetchController?.abort(),this.prefetchController=new AbortController,this.prefetchController}stopPrefetch(){this.prefetchController?.abort(),this.prefetchController=null}stopSession(){this.session&&(this.session.abort("superseded"),this.session=null,this.status.active=!1,this.notify())}stop(){this.stopSession(),this.stopPrefetch()}drawJumble(t,e){if(this.jumbleLevel<0)return!1;let{g:i,originX:s,originY:r,width:o,now:a}=t,h=this.pyramid.levels[this.jumbleLevel],l=J(h,e);if(!l)return!1;let c=o/h.width,b=this.env.cache,y=!1;i.imageSmoothingEnabled=!0,i.imageSmoothingQuality="medium";for(let m=l.y0;m<=l.y1;m++)for(let x=l.x0;x<=l.x1;x++){let u=b.get(Et+this.jumble[m*h.cols+x]),g=u?Vt(h,x,m,s,r,c):null;if(!u||!g)continue;let d=a-u.at;d=0&&v<0;p--){let L=J(u[p],m);if(!L)continue;let w=!0;for(let k=L.y0;k<=L.y1&&w;k++)for(let E=L.x0;E<=L.x1;E++){let A=x.get(g[p][k*u[p].cols+E]);if(!A||t.now-A.at=0&&p=0?Math.min(this.targetLevel,d):d,S=g!==null&&v>=M;if(S!==this.status.sharp&&(this.status.sharp=S,queueMicrotask(()=>this.notify())),!g)return f;for(let p=Math.max(0,v);p<=d;p++){let L=u[p],w=J(L,m);if(!w)continue;let k=r/L.width;e.imageSmoothingEnabled=!0,e.imageSmoothingQuality=k<1?"high":"medium";for(let E=w.y0;E<=w.y1;E++)for(let A=w.x0;A<=w.x1;A++){let T=x.get(g[p][E*L.cols+A]);if(!T)continue;let C=t.now-T.at;Cthis.requestDraw(),onStatus:()=>this.onStatus(this)})}get isOpen(){return this.expanded}get isNear(){return this.near}layout(t){let e=this.cover,i=Math.max(t.width/e.width,t.open/e.height),s=e.width*i,r=e.height*i,o=(t.open-r)/2,a=o+this.focusY*r,h=Math.max(0,Math.min(t.open-t.closed,a-t.closed/2)),l=this.geometry;this.geometry={width:t.width,closed:t.closed,open:t.open,dpr:t.dpr,coverWidth:s,coverHeight:r,x:(t.width-s)/2,y:o,band:h},this.canvas&&(this.sizeCanvas(this.canvasOpen),this.drawNow()),this.near&&l&&(l.width!==t.width||l.closed!==t.closed||l.open!==t.open||l.dpr!==t.dpr)&&this.startSession()}attach(){if(this.canvas)return;let t=document.createElement("canvas");t.className="strip-canvas",t.setAttribute("aria-hidden","true");let e=t.getContext("2d",{alpha:!1});e&&(this.canvas=t,this.g=e,this.element.prepend(t),this.sizeCanvas(this.expanded),this.drawNow())}detach(){this.canvas&&(cancelAnimationFrame(this.frame),this.frame=0,this.canvas.width=0,this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.g=null)}setNear(t){t!==this.near&&(this.near=t,t?this.startSession():this.loader.stop())}setOpen(t){if(t===this.expanded)return;this.expanded=t,this.element.classList.toggle("is-open",t),clearTimeout(this.settleTimer);let e=this.geometry,i=this.canvas;t?i&&this.canvasOpen?(i.style.transition="",i.style.transform="translate3d(0,0,0)"):i&&e&&(this.sizeCanvas(!0),i.style.transition="none",i.style.transform="translate3d(0,"+-e.band+"px,0)",this.drawNow(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.expanded&&this.canvas===i&&(i.style.transition="",i.style.transform="translate3d(0,0,0)")})})):i&&e&&(i.style.transition="",i.style.transform="translate3d(0,"+-e.band+"px,0)",this.settleTimer=window.setTimeout(()=>{!this.expanded&&this.canvas===i&&(this.sizeCanvas(!1),this.drawNow())},Me)),this.near&&this.startSession()}sizeCanvas(t){let e=this.canvas,i=this.geometry;if(!e||!i)return;this.canvasOpen=t;let s=t?i.open:i.closed,r=Math.max(1,Math.round(i.width*i.dpr)),o=Math.max(1,Math.round(s*i.dpr));(e.width!==r||e.height!==o)&&(e.width=r,e.height=o),e.style.height=s+"px",t||(e.style.transition="none",e.style.transform="translate3d(0,0,0)")}view(){let t=this.geometry;if(!t)return null;let e=this.expanded?0:t.band,i=this.expanded?t.open:t.closed;return{displayWidth:t.coverWidth,u0:Math.max(0,-t.x/t.coverWidth),u1:Math.min(1,(t.width-t.x)/t.coverWidth),v0:Math.max(0,(e-t.y)/t.coverHeight),v1:Math.min(1,(e+i-t.y)/t.coverHeight)}}startSession(){let t=this.view();!t||!this.geometry||this.loader.start(t,this.geometry.dpr,()=>{})}requestDraw(){this.frame===0&&this.canvas&&(this.frame=requestAnimationFrame(t=>{this.frame=0,this.draw(t)&&this.requestDraw()}))}drawNow(){this.draw(performance.now())&&this.requestDraw()}draw(t){let e=this.g,i=this.canvas,s=this.geometry;if(!e||!i||!s)return!1;e.setTransform(1,0,0,1,0,0),e.globalAlpha=1,e.fillStyle="#111114",e.fillRect(0,0,i.width,i.height);let r=this.canvasOpen?0:-s.band;return this.loader.draw({g:e,originX:s.x*s.dpr,originY:(s.y+r)*s.dpr,width:s.coverWidth*s.dpr,height:s.coverHeight*s.dpr,canvasWidth:i.width,canvasHeight:i.height,displayWidth:s.coverWidth,dpr:s.dpr,now:t})}};function $t(n){let t=n.dataset,e=(i,s)=>{let r=Number(i);return Number.isFinite(r)&&r>0?r:s};return{page:t.page??"",build:t.build??"",slug:t.album??"",manifestUrl:t.manifest??"",indexUrl:t.index??"",workerUrl:t.worker??"",budgetMs:e(t.budgetMs,3e3),maxDpr:e(t.maxDpr,2),concurrency:Math.max(1,Math.round(e(t.concurrency,6))),blockContextMenu:t.blockContextMenu!=="false",gate:t.gate!=="false"}}function Q(n,t,e){return"/a/"+encodeURIComponent(t)+"/p/"+e+"."+n+".json"}var Le=24,dt=class{constructor(t,e,i,s){this.root=t;this.settings=i;this.env=s;this.strips=[];this.onScreen=new Set;this.inView=new Set;this.suspended=!1;this.wordmark=null;this.opened=null;this.scrollFrame=0;this.sizeKey="";let r=Array.from(t.querySelectorAll("a.strip")),o=new Map(e.albums.map(h=>[h.slug,h]));for(let h of r){let l=o.get(h.dataset.slug??"");!l||!l.cover||this.strips.push(new Z(h,l.cover,l.collapsed_focus_y??.5,Q(e.build,l.slug,l.cover.hash),s,c=>this.onStripStatus(c)))}this.hoverMode=matchMedia("(hover: hover) and (pointer: fine)");let a=document.querySelector(".site-header .wordmark");if(this.indicator=new X(document.body,()=>!this.wordmarkMoving()),a){this.wordmark=D(a,!0);let h=()=>{this.wordmark&&!this.indicator.visible&&this.wordmark.play()},l=()=>this.wordmark?.reverse();a.addEventListener("mouseenter",h),a.addEventListener("mouseleave",l),a.addEventListener("focus",h),a.addEventListener("blur",l)}document.documentElement.classList.add("has-strips"),this.measure(),this.observe(),this.bind(),s.gate.onUnlock(()=>{if(!this.suspended)for(let h of this.strips)h.isNear&&h.startSession(),h.requestDraw()})}suspend(t){if(!this.suspended){this.suspended=!0;for(let e of this.strips)e.loader.stop(),t&&e.detach();this.env.scheduler.cancelAll(),this.env.cache.trim(t?0:this.env.cache.budget/4)}}resume(){if(this.suspended){this.suspended=!1;for(let t of this.strips)this.inView.has(t)&&t.attach(),t.isNear&&t.startSession()}}wordmarkMoving(){let t=this.wordmark?.t??0;return t>0&&t<1}measure(){let t=this.root.clientWidth||window.innerWidth,e=window.innerHeight,i=Math.round(Math.min(t*6/32,e*.28)),s=Math.round(Math.min(t*9/32,e*.62)),r=Math.min(window.devicePixelRatio||1,this.settings.maxDpr),o=t+"x"+i+"x"+s+"@"+r;if(o!==this.sizeKey){this.sizeKey=o,this.root.style.setProperty("--strip-closed",i+"px"),this.root.style.setProperty("--strip-open",s+"px");for(let a of this.strips)a.layout({width:t,closed:i,open:s,dpr:r})}}observe(){let t=new Map(this.strips.map(r=>[r.element,r])),e=new IntersectionObserver(r=>{for(let o of r)t.get(o.target)?.setNear(o.isIntersecting)},{rootMargin:"100% 0px"}),i=new IntersectionObserver(r=>{for(let o of r){let a=t.get(o.target);a&&(o.isIntersecting?(this.inView.add(a),this.suspended||a.attach()):(this.inView.delete(a),a.detach()))}},{rootMargin:"25% 0px"}),s=new IntersectionObserver(r=>{for(let o of r){let a=t.get(o.target);a&&(o.isIntersecting?this.onScreen.add(a):this.onScreen.delete(a))}this.watchFirst(),this.scheduleCentre()});for(let r of this.strips)e.observe(r.element),i.observe(r.element),s.observe(r.element)}watchFirst(){let t=this.strips.find(e=>this.onScreen.has(e))??null;this.indicator.watch(t?t.loader:null)}onStripStatus(t){this.indicator.update(t.loader)}bind(){for(let t of this.strips){let e=t.element;e.addEventListener("mouseenter",()=>{this.hoverMode.matches&&this.open(t)}),e.addEventListener("mouseleave",()=>{this.hoverMode.matches&&this.opened===t&&this.open(null)}),e.addEventListener("focus",()=>this.open(t)),e.addEventListener("blur",()=>{this.opened===t&&!this.hoverMode.matches?this.scheduleCentre():this.opened===t&&this.open(null)}),e.addEventListener("dragstart",i=>i.preventDefault()),this.settings.blockContextMenu&&e.addEventListener("contextmenu",i=>i.preventDefault())}window.addEventListener("scroll",()=>this.scheduleCentre(),{passive:!0}),new ResizeObserver(()=>{this.measure(),this.scheduleCentre()}).observe(this.root)}open(t){t!==this.opened&&(this.opened?.setOpen(!1),this.opened=t,t?.setOpen(!0))}scheduleCentre(){this.hoverMode.matches||this.scrollFrame!==0||(this.scrollFrame=requestAnimationFrame(()=>{this.scrollFrame=0,this.pickCentre()}))}pickCentre(){if(this.hoverMode.matches)return;let t=window.innerHeight/2,e=null,i=1/0,s=1/0;for(let r of this.onScreen){let o=r.element.getBoundingClientRect(),a=Math.abs(o.top+o.height/2-t);a=1)return mt(e)+"s";let i=1/e;return i<10&&Math.abs(i-Math.round(i))>.05?"1/"+mt(i):"1/"+Math.round(i)}function Te(n,t,e,i){let s=[te(n+1)+" / "+te(t)],r=e.exif;if(i&&r){let o=Ae(r);o&&s.push(o),r.lens&&s.push(Ee(r.lens)),r.focal_length&&s.push(mt(r.focal_length)+"mm"),r.f_number&&s.push("f/"+mt(r.f_number)),r.exposure&&s.push(Se(r.exposure)),r.iso&&s.push("ISO "+r.iso)}return s.join(" \xB7 ")}function Ce(n,t){n.textContent="",t.split(/\r?\n/).forEach((e,i)=>{i>0&&n.appendChild(document.createElement("br"));let s=e.split("*"),r=(s.length-1)%2===0;s.forEach((o,a)=>{let h=a%2===1;if(h&&(r||a!==s.length-1)){let l=document.createElement("em");l.textContent=o,n.appendChild(l)}else n.appendChild(document.createTextNode((h?"*":"")+o))})})}var pt=class{constructor(t){this.visible=!1;this.placement="";this.element=document.createElement("section"),this.element.className="caption",this.element.setAttribute("aria-label","Caption"),this.meta=document.createElement("p"),this.meta.className="caption-meta",this.title=document.createElement("h2"),this.title.className="caption-title",this.text=document.createElement("p"),this.text.className="caption-text",this.element.append(this.meta,this.title,this.text),t.appendChild(this.element)}set(t,e,i,s){this.meta.textContent=Te(e,i,t,s),this.title.textContent=t.title??"",this.title.hidden=!t.title,ut(this.title,t.title??""),Ce(this.text,t.caption??""),this.text.hidden=!t.caption,ut(this.text,t.caption??"")}show(t){t!==this.visible&&(this.visible=t,this.element.classList.toggle("is-visible",t))}place(t,e,i){let s=Math.round(t)+","+Math.round(e)+","+Math.round(i);if(s===this.placement)return;this.placement=s;let r=this.element.style;r.width=Math.round(e)+"px",r.transform="translate3d("+Math.round(t)+"px,"+-Math.round(i)+"px,0)"}};var ft=24,ee=10,Pe=300,Ie=.35,ie=.35,ze=.2,Re=2500,He=120,Fe=16,qe=.002,Ne=.01;function Ue(n,t,e,i){let s=3*n,r=3*(e-n)-s,o=1-s-r,a=3*t,h=3*(i-t)-a,l=1-a-h,c=m=>((o*m+r)*m+s)*m,b=m=>((l*m+h)*m+a)*m,y=m=>(3*o*m+2*r)*m+s;return m=>{if(m<=0)return 0;if(m>=1)return 1;let x=m;for(let d=0;d<8;d++){let v=c(x)-m,f=y(x);if(Math.abs(v)<1e-5)return b(x);if(Math.abs(f)<1e-6)break;x-=v/f}let u=0,g=1;x=m;for(let d=0;d<24;d++){let v=c(x);if(Math.abs(v-m)<1e-5)break;vthis.onUnlock())}buildEndCard(){let t=document.createElement("section");t.className="end-card",t.setAttribute("aria-label","End of album");let e=document.createElement("a");e.className="next-album",e.href="/";let i=document.createElement("span");i.className="next-strip";let s=document.createElement("span");s.className="next-text";let r=document.createElement("span");r.className="next-eyebrow",r.textContent="All albums";let o=document.createElement("span");o.className="next-title",s.append(r,o),i.appendChild(s),e.appendChild(i);let a=document.createElement("div");a.className="signoff";let h=zt();h&&a.appendChild(h);let l=document.createElement("p");return l.className="signature",l.textContent="\u2014 Lucio",a.appendChild(l),t.append(e,a),t}loader(t){let e=this.loaders[t];if(!e){let i=this.manifest.photos[t];e=new V(i,Q(this.manifest.build,this.manifest.slug,i.hash),{...this.env,requestDraw:()=>this.requestDraw(),onStatus:s=>{this.indicator.update(s),this.progress.update(s)}}),this.loaders[t]=e}return e}measure(){let t=this.stage.getBoundingClientRect();this.vw=Math.max(1,t.width),this.vh=Math.max(1,t.height),this.ox=t.left,this.oy=t.top,this.dpr=Math.min(window.devicePixelRatio||1,this.settings.maxDpr);let e=Math.max(1,Math.round(this.vw*this.dpr)),i=Math.max(1,Math.round(this.vh*this.dpr));(this.canvas.width!==e||this.canvas.height!==i)&&(this.canvas.width=e,this.canvas.height=i),this.layouts=[],this.stops=[];let s=0;this.manifest.photos.forEach((r,o)=>{let a=Math.max(1,r.slides||1),h=Math.min(this.vw/(r.width/a),this.vh/r.height),l=r.width*h,c=r.height*h,b=l/a,y=s+ft/2+(this.vw-b)/2;this.layouts.push({scale:h,width:l,height:c,section:b,slides:a,start:s,left:y,top:(this.vh-c)/2});for(let m=0;m{this.pointerId===null&&document.body.classList.add("is-idle")},Re)}stopForHash(){let t=/^#(\d+)$/.exec(location.hash);if(!t)return 0;let e=Math.min(this.manifest.photos.length,Math.max(1,Number(t[1])))-1,i=this.stops.findIndex(s=>s.photo===e);return i<0?0:i}bind(){let t=this.stage;t.addEventListener("pointerdown",e=>this.onPointerDown(e)),t.addEventListener("pointermove",e=>this.onPointerMove(e)),t.addEventListener("pointerup",e=>this.onPointerUp(e,!1)),t.addEventListener("pointercancel",e=>this.onPointerUp(e,!0)),t.addEventListener("pointerleave",e=>{e.pointerType==="mouse"&&this.pointerId===null&&(this.hover=!1,this.updateCaption())}),t.addEventListener("wheel",e=>this.onWheel(e),{passive:!1}),t.addEventListener("gesturestart",e=>{e.preventDefault(),this.gestureZoom=this.zoom}),t.addEventListener("gesturechange",e=>this.onGesture(e)),t.addEventListener("gestureend",e=>e.preventDefault()),t.addEventListener("dragstart",e=>e.preventDefault()),t.addEventListener("selectstart",e=>e.preventDefault()),this.settings.blockContextMenu&&t.addEventListener("contextmenu",e=>e.preventDefault()),window.addEventListener("keydown",e=>this.onKey(e)),window.addEventListener("hashchange",()=>{let e=this.stopForHash();this.stops[e].photo!==this.stops[this.current].photo?this.jump(e):this.clearZoom()&&(this.startSession(),this.updateCaption())}),new ResizeObserver(()=>this.onResize()).observe(t),this.fade.addEventListener("transitionend",()=>{this.fade.style.opacity==="0"&&(this.fade.width=1,this.fade.height=1)})}onResize(){let t=this.vw+"x"+this.vh+"@"+this.dpr;this.measure(),t!==this.vw+"x"+this.vh+"@"+this.dpr&&(this.clearZoom(),this.tween=null,this.camera=this.stops[this.current].camera,this.requestDraw(),clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout(()=>this.startSession(),200))}onKey(t){if(t.altKey||t.ctrlKey||t.metaKey)return;this.wake();let e=t.target;if(!(e&&(e.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(e.tagName)))){switch(t.key){case"ArrowRight":this.go(this.current+1);break;case"ArrowLeft":this.go(this.current-1);break;case"Home":this.go(0);break;case"End":this.go(this.stops.length-2);break;case"Escape":this.zoomPhoto>=0?this.go(this.current):location.assign("/");break;case"i":case"I":this.pinned=!this.pinned,this.updateCaption();break;default:return}t.preventDefault()}}onPointerDown(t){if(!(t.pointerType==="mouse"&&t.button!==0)){if(this.pointerId!==null){this.secondId===null&&t.pointerType!=="mouse"&&this.pointerType!=="mouse"&&!this.stale&&(this.zoomPhoto>=0||!this.dragging&&this.enterZoom())&&(this.secondId=t.pointerId,this.bx=t.clientX,this.by=t.clientY,this.pinching=!0,this.dragging=!0,this.stage.setPointerCapture(t.pointerId));return}t.target.closest("a, button")||(this.pointerId=t.pointerId,this.pointerType=t.pointerType,this.dragging=!1,this.stale=!1,this.downX=t.clientX,this.downY=t.clientY,this.ax=t.clientX,this.ay=t.clientY,this.downT=t.timeStamp,this.tween=null,this.downCamera=this.camera,this.samples=[{t:t.timeStamp,x:t.clientX}],this.stage.setPointerCapture(t.pointerId))}}onPointerMove(t){if(t.pointerType==="mouse"&&this.wake(),this.pointerId===null){t.pointerType==="mouse"&&(this.hover=this.inCaptionZone(t.clientX,t.clientY),this.updateCaption());return}if(this.pinching&&(t.pointerId===this.pointerId||t.pointerId===this.secondId)){this.pinchMove(t.pointerId,t.clientX,t.clientY);return}if(t.pointerId!==this.pointerId||this.stale)return;let e=t.clientX-this.downX,i=t.clientY-this.downY;if(!this.dragging&&Math.hypot(e,i)>=ee&&(this.dragging=!0,this.stage.classList.add("is-dragging"),this.updateCaption()),!this.dragging){this.ax=t.clientX,this.ay=t.clientY;return}if(this.zoomPhoto>=0){this.zx+=t.clientX-this.ax,this.zy+=t.clientY-this.ay,this.ax=t.clientX,this.ay=t.clientY,this.settleZoom();return}for(this.samples.push({t:t.timeStamp,x:t.clientX});this.samples.length>2&&t.timeStamp-this.samples[0].t>100;)this.samples.shift();this.camera=this.rubber(this.downCamera-e),this.requestDraw()}onPointerUp(t,e){if(this.pinching&&(t.pointerId===this.pointerId||t.pointerId===this.secondId)){this.endPinch(t.pointerId);return}if(t.pointerId!==this.pointerId)return;this.stage.hasPointerCapture(t.pointerId)&&this.stage.releasePointerCapture(t.pointerId),this.pointerId=null;let i=this.dragging;if(this.dragging=!1,this.stage.classList.remove("is-dragging"),this.stale){this.stale=!1;return}let s=Math.hypot(t.clientX-this.downX,t.clientY-this.downY);if(!e&&!i&&s=0)return;let r=0,o=this.samples[0],a=this.samples[this.samples.length-1];o&&a&&a.t>o.t&&t.timeStamp-a.t<100&&(r=(a.x-o.x)/(a.t-o.t));let h=this.nearestStop(this.camera);if(!e&&Math.abs(r)>Ie)if(r<0){let l=this.stops.findIndex(c=>c.camera>this.camera+1);h=l<0?this.stops.length-1:l}else{let l=0;this.stops.forEach((c,b)=>{c.camera=0)return;let i=this.photoRect(e.photo);t.clientX>=i.left&&t.clientX<=i.right&&t.clientY>=i.top&&t.clientY<=i.bottom&&(this.pinned=!this.pinned,this.updateCaption())}onWheel(t){if(t.preventDefault(),this.pinching||this.dragging&&this.zoomPhoto<0)return;let e=t.deltaY;if(t.deltaMode===1?e*=Fe:t.deltaMode===2&&(e*=this.vh),e===0)return;let i=Math.max(-1,Math.min(1,e*(t.ctrlKey?Ne:qe))),s=t.clientX-this.ox,r=t.clientY-this.oy;this.zoomTo(this.zoom*Math.exp(-i),s,r,s,r)}onGesture(t){if(t.preventDefault(),this.pointerId!==null||!t.scale)return;let e=(t.clientX??this.ox+this.vw/2)-this.ox,i=(t.clientY??this.oy+this.vh/2)-this.oy;this.zoomTo(this.gestureZoom*t.scale,e,i,e,i)}pinchMove(t,e,i){let s=(this.ax+this.bx)/2-this.ox,r=(this.ay+this.by)/2-this.oy,o=Math.hypot(this.ax-this.bx,this.ay-this.by);t===this.pointerId?(this.ax=e,this.ay=i):(this.bx=e,this.by=i);let a=Math.hypot(this.ax-this.bx,this.ay-this.by),h=o>1&&a>1?this.zoom*a/o:this.zoom;this.zoomTo(h,s,r,(this.ax+this.bx)/2-this.ox,(this.ay+this.by)/2-this.oy)}endPinch(t){this.stage.hasPointerCapture(t)&&this.stage.releasePointerCapture(t),t===this.pointerId&&(this.pointerId=this.secondId,this.ax=this.bx,this.ay=this.by),this.secondId=null,this.pinching=!1,this.dragging=!0,this.zoomPhoto>=0&&this.settleZoom()}enterZoom(){let t=this.stops[this.current];if(t.photo<0||this.suspended)return!1;let e=this.layouts[t.photo],i=this.manifest.photos[t.photo].width/(window.devicePixelRatio||1)/e.width;return i<=1.001?!1:(this.tween=null,this.camera=t.camera,this.zoomPhoto=t.photo,this.zoomMax=i,this.zoom=1,this.zx=e.left-(this.camera-this.vw/2),this.zy=e.top,this.slackX=this.zx-this.clampAxis(this.zx,e.width,this.vw,0),this.slackY=this.zy-this.clampAxis(this.zy,e.height,this.vh,0),this.updateCaption(),!0)}zoomTo(t,e,i,s,r){if(this.zoomPhoto<0&&(t<=1||!this.enterZoom()))return;let o=Math.max(1,Math.min(this.zoomMax,t)),a=o/this.zoom;this.zx=s-(e-this.zx)*a,this.zy=r-(i-this.zy)*a,this.zoom=o,this.settleZoom()}settleZoom(){let t=this.layouts[this.zoomPhoto];if(this.zx=this.clampAxis(this.zx,t.width*this.zoom,this.vw,this.slackX),this.zy=this.clampAxis(this.zy,t.height*this.zoom,this.vh,this.slackY),this.requestDraw(),this.zoom<=1&&!this.pinching){this.camera=t.left+this.vw/2-this.zx,this.go(this.nearestStop(this.camera));return}clearTimeout(this.zoomTimer),this.zoomTimer=window.setTimeout(()=>this.startZoomSession(),He)}clampAxis(t,e,i,s){let r=(i-e)/2,o=Math.min(i-e,r),a=Math.max(0,r),h=s*Math.max(0,2-this.zoom);return h>0?a+=h:o+=h,Math.min(a,Math.max(o,t))}clearZoom(){return this.zoomPhoto<0?!1:(this.zoomPhoto=-1,this.zoom=1,this.gestureZoom=1,clearTimeout(this.zoomTimer),this.zoomTimer=0,this.pointerId!==null&&(this.stale=!0,this.pinching=!1,this.secondId=null),this.requestDraw(),!0)}levelDpr(){return this.zoomPhoto>=0&&this.zoom>=this.zoomMax*.999?Math.max(this.dpr,window.devicePixelRatio||1):this.dpr}startZoomSession(){if(this.zoomTimer=0,this.suspended||this.zoomPhoto<0)return;let t=this.layouts[this.zoomPhoto],e=t.width*this.zoom,i=t.height*this.zoom,s=Math.max(0,this.zx),r=Math.min(this.vw,this.zx+e),o=Math.max(0,this.zy),a=Math.min(this.vh,this.zy+i);r<=s||a<=o||this.loader(this.zoomPhoto).start({displayWidth:e,u0:(s-this.zx)/e,u1:(r-this.zx)/e,v0:(o-this.zy)/i,v1:(a-this.zy)/i},this.levelDpr(),()=>{})}rubber(t){let e=this.stops[0].camera,i=this.stops[this.stops.length-1].camera;return ti?i+(t-i)*ie:t}nearestStop(t){let e=0;return this.stops.forEach((i,s)=>{Math.abs(i.camera-t){this.current=e,this.camera=r});else{let o=Math.abs(r-this.camera);o>.5?this.tween={from:this.camera,to:r,start:performance.now(),duration:240+200*Math.min(1,o/this.vw)}:this.camera=r,this.current=e}e!==i?this.activate(i):(s&&this.startSession(),this.updateCaption()),this.requestDraw()}jump(t){let e=this.current;this.clearZoom(),this.tween=null,this.crossfade(()=>{this.current=t,this.camera=this.stops[t].camera}),this.activate(e),this.requestDraw()}crossfade(t){let e=this.fade;(e.width!==this.canvas.width||e.height!==this.canvas.height)&&(e.width=this.canvas.width,e.height=this.canvas.height);let i=e.getContext("2d");i&&i.drawImage(this.canvas,0,0),e.style.transition="none",e.style.opacity="1",t(),this.render(performance.now()),requestAnimationFrame(()=>{requestAnimationFrame(()=>{e.style.transition="",e.style.opacity="0"})})}activate(t){let e=this.stops[this.current],i=t>=0?this.stops[t]:null;if(i&&i.photo>=0&&i.photo!==e.photo&&this.loaders[i.photo]?.stop(),this.loaders.forEach((s,r)=>{s&&r!==e.photo&&r!==e.photo+1&&s.stopPrefetch()}),e.photo<0&&(this.indicator.watch(null),this.progress.watch(null)),this.describe(e.photo,t>=0),e.photo>=0){let s=this.manifest.photos[e.photo];this.caption.set(s,e.photo,this.manifest.photos.length,this.manifest.show_exif),(t>=0||location.hash!=="")&&location.hash!=="#"+(e.photo+1)&&history.replaceState(history.state,"","#"+(e.photo+1)),this.startSession()}this.syncNextStrip(),this.updateCaption()}describe(t,e){let i=this.manifest.photos.length,s;if(t<0){let r=this.nextLink.querySelector(".next-title")?.textContent??"";s="End of album."+(r?" Next album: "+r+".":"")}else{let r=this.manifest.photos[t],o=r.alt||r.title||"";s="Photo "+(t+1)+" of "+i+(o?": "+o:"")}this.canvas.setAttribute("aria-label",s),clearTimeout(this.announceTimer),e&&(this.announceTimer=window.setTimeout(()=>{this.announcer.textContent=s},500))}suspend(t){if(!this.suspended){this.suspended=!0,this.tween=null;for(let e of this.loaders)e?.stop();this.nextStrip?.loader.stop(),this.env.scheduler.cancelAll(),this.env.cache.trim(t?0:this.env.cache.budget/4),t&&(this.nextStrip?.detach(),this.canvas.width=1,this.canvas.height=1,this.fade.width=1,this.fade.height=1)}}resume(){this.suspended&&(this.suspended=!1,this.clearZoom(),this.canvas.width=0,this.measure(),this.camera=this.stops[this.current].camera,this.syncNextStrip(),this.startSession(),this.requestDraw())}onUnlock(){this.suspended||(this.zoomPhoto>=0?this.startZoomSession():this.startSession(),this.nextStrip&&(this.nextStrip.isNear&&this.nextStrip.startSession(),this.nextStrip.requestDraw()),this.requestDraw())}startSession(){let t=this.stops[this.current];if(t.photo<0)return;let e=this.current,i=this.loader(t.photo);i.start(this.viewAt(t),this.dpr,()=>{this.current===e&&this.prefetchAround(e)}),this.indicator.watch(i),this.progress.watch(i)}prefetchAround(t){let e=this.stops[t],i=this.stops[t+1];if(!(!i||i.photo<0)){if(i.photo===e.photo){let s=this.loader(e.photo);s.prefetchLevel(this.viewAt(i),s.finalLevel);let r=this.stops.find(o=>o.photo===e.photo+1);r&&this.loader(r.photo).prefetchProbe(this.viewAt(r),this.dpr);return}this.loader(i.photo).prefetchProbe(this.viewAt(i),this.dpr)}}viewAt(t){let e=this.layouts[t.photo],i=t.camera-this.vw/2,s=Math.max(i,e.left),r=Math.min(i+this.vw,e.left+e.width),o=Math.max(0,e.top),a=Math.min(this.vh,e.top+e.height);return{displayWidth:e.width,u0:(s-e.left)/e.width,u1:(r-e.left)/e.width,v0:(o-e.top)/e.height,v1:(a-e.top)/e.height}}photoRect(t){let e=this.layouts[t],i=e.left-(this.camera-this.vw/2);return{left:Math.max(0,i),right:Math.min(this.vw,i+e.width),top:Math.max(0,e.top),bottom:Math.min(this.vh,e.top+e.height)}}inCaptionZone(t,e){let i=this.stops[this.current];if(i.photo<0)return!1;let s=this.stage.getBoundingClientRect(),r=t-s.left,o=e-s.top,a=this.layouts[i.photo],h=this.photoRect(i.photo),l=a.top+a.height*(1-ze);return r>=h.left&&r<=h.right&&o>=l&&o<=h.bottom}updateCaption(){let t=this.stops[this.current],e=t.photo>=0&&this.zoomPhoto<0&&!this.dragging&&(this.pinned||this.hover);if(e){let i=this.photoRect(t.photo);this.caption.place(i.left,i.right-i.left,this.vh-i.bottom)}this.caption.show(e),document.body.classList.toggle("has-caption",e)}loadNextAlbum(){this.indexRequested||!this.settings.indexUrl||(this.indexRequested=!0,fetch(this.settings.indexUrl,{credentials:"same-origin"}).then(t=>t.ok?t.json():Promise.reject(new Error("index"))).then(t=>this.showNextAlbum(t)).catch(()=>{this.indexRequested=!1}))}showNextAlbum(t){let e=t.albums;if(e.length===0)return;let i=e.findIndex(a=>a.slug===this.manifest.slug),s=e[(i+1)%e.length];if(!s||s.slug===this.manifest.slug)return;this.nextLink.href="/a/"+encodeURIComponent(s.slug)+"/";let r=this.nextLink.querySelector(".next-eyebrow"),o=this.nextLink.querySelector(".next-title");r&&(r.textContent="Next album"+(s.date?" \xB7 "+s.date:"")),o&&(o.textContent=s.title,ut(o,s.title)),s.cover&&(this.nextStrip=new Z(this.nextFrame,s.cover,s.collapsed_focus_y??.5,Q(t.build,s.slug,s.cover.hash),{...this.env,tiles:t.tiles},()=>{}),this.nextLink.classList.add("has-strip"),this.layoutNextStrip(),this.syncNextStrip())}requestDraw(){this.frame===0&&(this.frame=requestAnimationFrame(t=>{this.frame=0,this.render(t)}))}render(t){let e=!1;if(this.tween){let y=Math.min(1,(t-this.tween.start)/this.tween.duration);this.camera=this.tween.from+(this.tween.to-this.tween.from)*De(y),y>=1?(this.tween=null,this.updateCaption()):e=!0}let i=this.g,s=this.canvas.width,r=this.canvas.height;i.setTransform(1,0,0,1,0,0),i.globalAlpha=1,i.fillStyle="#111114",i.fillRect(0,0,s,r);let o=this.camera-this.vw/2,a=o+this.vw,h=this.dpr,l=this.stops[this.current].photo,c=Math.max(0,(l<0?this.layouts.length-1:l)-2),b=this.zoomPhoto>=0?-1:Math.min(this.layouts.length-1,(l<0?this.layouts.length-1:l)+2);if(this.zoomPhoto>=0){let y=this.layouts[this.zoomPhoto],m=y.width*this.zoom;this.loader(this.zoomPhoto).draw({g:i,originX:this.zx*h,originY:this.zy*h,width:m*h,height:y.height*this.zoom*h,canvasWidth:s,canvasHeight:r,displayWidth:m,dpr:this.levelDpr(),now:t})&&(e=!0)}for(let y=c;y<=b;y++){let m=this.layouts[y];m.left+m.widtha||this.loader(y).draw({g:i,originX:(m.left-o)*h,originY:m.top*h,width:m.width*h,height:m.height*h,canvasWidth:s,canvasHeight:r,displayWidth:m.width,dpr:h,now:t})&&(e=!0)}this.endCard.style.transform="translate3d("+Math.round(this.endLeft-o)+"px,0,0)",this.caption.element.classList.contains("is-visible")&&this.tween&&this.updateCaption(),e&&this.requestDraw()}};async function re(n){let t=await fetch(n,{credentials:"same-origin"});if(!t.ok)throw new Error(n+" "+t.status);return await t.json()}function ne(n){return{scheduler:new tt(n.concurrency,n.workerUrl),cache:new st(Ft())}}async function We(n,t,e){let i=await re(t.manifestUrl);if(i.photos.length===0){e.abandon();return}e.configure(i.gate);let{scheduler:s,cache:r}=ne(t);document.documentElement.classList.add("has-viewer"),oe(new vt(n,i,t,{scheduler:s,cache:r,settings:t,gate:e,tiles:i.tiles}))}async function Oe(n,t,e){let i=await re(t.indexUrl);if(i.albums.length===0){e.abandon();return}e.configure(i.gate);let{scheduler:s,cache:r}=ne(t);oe(new dt(n,i,t,{scheduler:s,cache:r,settings:t,gate:e,tiles:i.tiles}))}function oe(n){document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?n.suspend(!1):n.resume()}),window.addEventListener("pagehide",()=>n.suspend(!0)),window.addEventListener("pageshow",t=>{t.persisted&&n.resume()})}function Be(){document.documentElement.classList.remove("has-viewer"),document.querySelector(".load-error")?.removeAttribute("hidden")}function se(){let n=$t(document.body);if(n.page==="album"){let t=document.getElementById("stage");if(t){let e=new G(n.build,n.gate,n.workerUrl);We(t,n,e).catch(()=>{e.abandon(),Be()})}}else if(n.page==="notfound"){let t=document.querySelector(".site-header .wordmark");t&&D(t,!1)}else if(n.page==="index"){let t=document.getElementById("strips");if(t){let e=new G(n.build,n.gate,n.workerUrl);Oe(t,n,e).catch(()=>{e.abandon(),document.documentElement.classList.remove("has-strips");let i=document.querySelector(".site-header .wordmark");i&&!i.classList.contains("has-svg")&&D(i,!1)})}}}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",se,{once:!0}):se();})(); +"use strict";(()=>{(function(n){let t={from:"Guoliang",to:"Lucio",letters:[{ch:"G",kind:"keep",shared:"M8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50",fullA:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",fullB:"M8.50 0.00L8.50 22.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L58.00 91.50L80.00 91.50",out:[{d:"M80.00 8.50L58.00 8.50L22.00 8.50A13.50 13.50 0 0 0 8.50 22.00",P:79.21,j:"end"},{d:"M58.00 91.50A13.50 13.50 0 0 0 71.50 78.00L71.50 56.00L41.50 56.00",P:73.21,j:"start"}],in:[{d:"M8.50 22.00L8.50 0.00",P:22,j:"start"},{d:"M58.00 91.50L80.00 91.50",P:22,j:"start"}],x0:0,x1:0,dot:null},{ch:"u",kind:"keep",shared:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullA:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",fullB:"M8.50 38.00L8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00L51.50 38.00",out:[],in:[],x0:88.8,x1:88,dot:null},{ch:"o",kind:"keep",shared:"M38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullB:"M60.00 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50L60.00 91.50",out:[{d:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50",P:60.41,j:"both"}],in:[{d:"M38.00 46.50L60.00 46.50",P:22,j:"start"},{d:"M38.00 91.50L60.00 91.50",P:22,j:"start"}],x0:159,x1:158.2,dot:null},{ch:"l",kind:"fade",d:"M8.50 0.00L8.50 100.00",x0:230.8,x1:230.8,dot:null},{ch:"i",kind:"keep",shared:"M8.50 38.00L8.50 100.00",fullA:"M8.50 38.00L8.50 100.00",fullB:"M8.50 38.00L8.50 100.00",out:[],in:[],x0:262.8,x1:227.9,dot:[0,14,17]},{ch:"a",kind:"fade",d:"M38.00 91.50L51.50 91.50L51.50 78.00L51.50 60.00L51.50 46.50L38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",x0:291.6,x1:291.6,dot:null},{ch:"n",kind:"fade",d:"M51.50 100.00L51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00L8.50 100.00",x0:362.7,x1:362.7,dot:null},{ch:"g",kind:"keep",shared:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",fullA:"M0.00 127.50L38.00 127.50A13.50 13.50 0 0 0 51.50 114.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00",fullB:"M38.00 91.50A13.50 13.50 0 0 0 51.50 78.00L51.50 60.00A13.50 13.50 0 0 0 38.00 46.50L22.00 46.50A13.50 13.50 0 0 0 8.50 60.00L8.50 78.00A13.50 13.50 0 0 0 22.00 91.50L38.00 91.50",out:[{d:"M51.50 60.00L51.50 114.00A13.50 13.50 0 0 1 38.00 127.50L0.00 127.50",P:113.21,j:"start"}],in:[],x0:432.9,x1:256.7,dot:null}],pad:17,vbw:526.9,vbh:170,stroke:17,raysT:"translate(0.000 22.727) scale(0.7727)"},e="M47.6 70.7L71.9 61.1L71.1 58.2L45.2 62.0ZM44.9 61.5L61.2 40.9L59.1 38.8L38.5 55.1ZM38.0 54.8L41.8 28.9L38.9 28.1L29.3 52.4Z",i="http://www.w3.org/2000/svg",s=(u,y)=>{let d=document.createElementNS(i,u);for(let v in y)d.setAttribute(v,y[v]);return d},r=()=>n.matchMedia&&n.matchMedia("(prefers-reduced-motion: reduce)").matches,o=u=>Math.max(0,Math.min(1,u)),a=u=>u*u*(3-2*u),h=.5;function l(u,y){let d=0,v=0,f=null,M=0;function A(L){let x=(L-M)/y;M=L,d=dp(1),reverse:()=>p(0),toggle:()=>p(v?0:1),set:L=>{cancelAnimationFrame(f),f=null,v=d=L,u(d)},stop:()=>{cancelAnimationFrame(f),f=null},get t(){return d}}}function c(u,y,d,v){let f=o(v)*y;if(u.style.visibility=f<.05?"hidden":"visible",d==="both"){let M=f/2;u.setAttribute("stroke-dasharray",M.toFixed(2)+" "+Math.max(0,y-2*M).toFixed(2)+" "+M.toFixed(2)),u.setAttribute("stroke-dashoffset","0")}else d==="end"?(u.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*y+20).toFixed(2)),u.setAttribute("stroke-dashoffset",(-(y-f)).toFixed(2))):(u.setAttribute("stroke-dasharray",f.toFixed(2)+" "+(2*y+20).toFixed(2)),u.setAttribute("stroke-dashoffset","0"))}function g(u,y={}){let d=Object.assign({trigger:"hover",color:"currentColor",rays:"#FFF3CF",duration:450,autoDelay:1800},y),v=s("svg",{viewBox:"0 0 "+t.vbw+" "+t.vbh,role:"img","aria-label":"Guoliang Chen, Lucio"});v.style.display="block",v.style.width="100%",v.style.height="auto";let f=s("g",{transform:"translate("+t.pad+" "+t.pad+")",fill:"none",stroke:d.color,"stroke-width":t.stroke,"stroke-linejoin":"miter","stroke-linecap":"butt"});v.appendChild(f);let M=t.letters.map(x=>{let k=s("g",{transform:"translate("+x.x0+" 0)"});f.appendChild(k);let S=Object.assign({g:k,outEls:[],inEls:[]},x);if(x.kind==="fade")S.fadeEl=s("path",{d:x.d}),k.appendChild(S.fadeEl);else{S.fullA=s("path",{d:x.fullA}),k.appendChild(S.fullA),S.fullB=s("path",{d:x.fullB}),k.appendChild(S.fullB),x.shared&&k.appendChild(s("path",{d:x.shared}));for(let E of x.out){let T=s("path",{d:E.d});k.appendChild(T),S.outEls.push([T,E])}for(let E of x.in){let T=s("path",{d:E.d});k.appendChild(T),S.inEls.push([T,E])}}return x.dot&&(S.dotEl=s("rect",{x:x.dot[0],y:x.dot[1],width:x.dot[2],height:x.dot[2],rx:x.dot[2]*.22,fill:d.color,stroke:"none"}),k.appendChild(S.dotEl)),S}),A=s("path",{d:e,fill:d.rays,stroke:"none",opacity:0});f.appendChild(A),u.appendChild(v);function p(x){let k=a(o(x/h)),S=a(o((x-h)/(1-h)));for(let E of M){if(E.kind==="fade")E.fadeEl.setAttribute("opacity",(1-k).toFixed(3)),E.dotEl&&E.dotEl.setAttribute("opacity",(1-k).toFixed(3));else{for(let[T,P]of E.outEls)c(T,P.P,P.j,1-k);for(let[T,P]of E.inEls)c(T,P.P,P.j,k);E.fullA.style.visibility=k<=.001?"visible":"hidden",E.fullB.style.visibility=k>=.999?"visible":"hidden"}E.g.setAttribute("transform","translate("+(E.x0+(E.x1-E.x0)*S).toFixed(2)+" 0)")}A.setAttribute("transform","translate("+(M[0].x0+(M[0].x1-M[0].x0)*S).toFixed(2)+" 0) "+t.raysT),A.setAttribute("opacity",o((x-.8)/.2).toFixed(3))}let L=l(p,d.duration);return p(0),d.trigger==="hover"&&(u.addEventListener("mouseenter",L.play),u.addEventListener("mouseleave",L.reverse),u.addEventListener("focus",L.play),u.addEventListener("blur",L.reverse)),d.trigger==="click"&&u.addEventListener("click",L.toggle),d.trigger==="auto"&&setInterval(L.toggle,d.autoDelay+d.duration),Object.assign(L,{svg:v})}let b={C:[0,.75],L:[.25,.75],U:[.25,1],I:[.75,1],O:[.75,1.75]};function m(u,y,d){let v=y/2,f=d-v,M=v+f,A=f*Math.SQRT1_2,p=x=>x.toFixed(3);return{d:"M"+p(u-M+A)+" "+p(M-A)+"A"+p(f)+" "+p(f)+" 0 0 0 "+p(u-M)+" "+p(v)+"H"+p(M)+"A"+p(f)+" "+p(f)+" 0 0 0 "+p(v)+" "+p(M)+"V"+p(u-M)+"A"+p(f)+" "+p(f)+" 0 0 0 "+p(M)+" "+p(u-v)+"H"+p(u-M)+"A"+p(f)+" "+p(f)+" 0 0 0 "+p(u-v)+" "+p(u-M)+"V"+p(M)+"A"+p(f)+" "+p(f)+" 0 0 0 "+p(u-M+A)+" "+p(M-A)+"Z",P:4*(u-2*M)+2*Math.PI*f}}function w(u,y={}){let d=Object.assign({sequence:"LUCIO",color:"#F3F1EC",track:"#26262D",rays:"#FFF3CF",hold:480,morph:640,size:96,stroke:.17,radius:.22},y),v=120,f=v*d.stroke,M=v*d.radius,A=m(v,f,M),p=s("svg",{viewBox:"0 0 "+v+" "+v,width:d.size,height:d.size,role:"img","aria-label":"Loading"});d.track&&p.appendChild(s("path",{d:A.d,fill:"none",stroke:d.track,"stroke-width":f}));let L=s("path",{d:A.d,fill:"none",stroke:d.color,"stroke-width":f,"stroke-linecap":"butt"}),x=f/22,k=s("path",{d:e,fill:d.rays,transform:"translate("+(f-22*x).toFixed(3)+" "+(v-f-78*x).toFixed(3)+") scale("+x.toFixed(4)+")",opacity:0});p.appendChild(L),p.appendChild(k);let S=(R,D)=>{let C=Math.min(1,Math.max(0,D-R))*A.P;L.setAttribute("stroke-dasharray",C.toFixed(3)+" "+Math.max(0,A.P-C).toFixed(3)),L.setAttribute("stroke-dashoffset",(-R*A.P).toFixed(3))},E=(R,D)=>{let[C,j]=b[D];for(let q=-1;q<6;q++)if(C+q>=R[0]-1e-6&&j+q>=R[1]-1e-6)return[C+q,j+q];return[C,j]},T=d.sequence.split(""),P=0,I=b[T[0]].slice(),Lt,kt,Yt=!1;S(I[0],I[1]),k.setAttribute("opacity",T[0]==="L"?1:0);function Xt(){if(Yt)return;let R=(P+1)%T.length,D=E(I,T[R]),C=I.slice(),j=T[P]==="L",q=T[R]==="L",Bt=()=>{I=D;let Q=Math.floor(I[0]);I[0]-=Q,I[1]-=Q,P=R,S(I[0],I[1]),k.setAttribute("opacity",q?1:0),kt=setTimeout(Xt,d.hold)};if(r()){Bt();return}let Le=performance.now(),_t=Q=>{let H=Math.min(1,(Q-Le)/d.morph),jt=H<.5?4*H*H*H:1-Math.pow(-2*H+2,3)/2;S(C[0]+(D[0]-C[0])*jt,C[1]+(D[1]-C[1])*jt),k.setAttribute("opacity",q?Math.max(0,(H-.6)/.4).toFixed(3):j?Math.max(0,1-H*2.5).toFixed(3):0),H<1?Lt=requestAnimationFrame(_t):Bt()};Lt=requestAnimationFrame(_t)}return kt=setTimeout(Xt,d.hold),u.appendChild(p),{svg:p,stop:()=>{Yt=!0,cancelAnimationFrame(Lt),clearTimeout(kt)}}}n.LucioMorph={wordmark:g,loader:w}})(window);var O={graphite:"#111114",graphite3:"#26262D",paper:"#F3F1EC",beam:"#FFF3CF"};function Et(){return window.LucioMorph??null}function K(n,t){let e=Et();if(!e)return null;let i=document.createElement("span");i.className="wordmark-svg",i.setAttribute("aria-hidden","true"),n.appendChild(i);let s=e.wordmark(i,{trigger:"manual",color:O.paper,rays:O.beam});return s.svg.setAttribute("aria-hidden","true"),s.svg.removeAttribute("role"),t||s.set(1),n.classList.add("has-svg"),s}function Vt(){let n=document.getElementById("chop-template");if(!(n instanceof HTMLTemplateElement))return null;let t=n.content.firstElementChild;return t?t.cloneNode(!0):null}function ke(n){let t=n.seed+"|"+n.level+"|"+n.x+"|"+n.y,e=2166136261;for(let i=0;i>>0;return e}function Ee(n,t){let e=new Array(n);for(let r=0;r{i=i+1831565813|0;let r=Math.imul(i^i>>>15,1|i);return r=r+Math.imul(r^r>>>7,61|r)^r,((r^r>>>14)>>>0)/4294967296};for(let r=n-1;r>0;r--){let o=Math.floor(s()*(r+1)),a=e[r];e[r]=e[o],e[o]=a}return e}function Zt(n,t,e,i,s){n.drawImage(t,0,0);let r=s.cell,o=Math.floor(e/r),a=Math.floor(i/r);if(o<2||a<2)return;let h=o*a,l=Ee(h,ke(s));for(let c=0;c"u"||e==="")return;let i=(navigator.hardwareConcurrency??2)>=4?2:1;for(let s=0;sthis.onReply(a.data,o),r.onerror=()=>this.dropWorker(o),this.workers.push(r)}catch{break}}request(t,e,i,s,r){return s.aborted?Promise.reject(new z):new Promise((o,a)=>{let h=this.byId.get(t);h?i{c.waiters.delete(l)&&(a(new z),c.waiters.size===0&&setTimeout(()=>{c.waiters.size===0&&this.byKey.get(c.key)===c&&this.cancel(c)},0))},{once:!0}),this.pump()})}cancelAll(){for(let t of[...this.byKey.values()]){let e=[...t.waiters];t.waiters.clear();for(let i of e)i.reject(new z);this.cancel(t)}}cancel(t){if(this.forget(t),!t.running){let e=this.queue.indexOf(t);e>=0&&this.queue.splice(e,1);return}t.running=!1,this.running--,t.controller?t.controller.abort():t.worker>=0&&this.workers[t.worker]&&this.workers[t.worker].postMessage({type:"abort",key:t.key}),this.pump()}forget(t){this.byId.get(t.id)===t&&this.byId.delete(t.id),this.byKey.delete(t.key)}pump(){for(;this.running0;){let t=0;for(let i=1;i0&&(!t.scramble||this.workersUnscramble)){let i=e[this.nextWorker++%e.length];t.worker=i,this.workers[i].postMessage({type:"fetch",key:t.key,url:t.url,scramble:t.scramble});return}this.runOnMainThread(t)}runOnMainThread(t){t.worker=-1,t.controller=new AbortController,this.fetchOnMainThread(t,t.controller.signal)}liveWorkers(){let t=[];return this.workers.forEach((e,i)=>{e&&t.push(i)}),t}dropWorker(t){let e=this.workers[t];if(e){e.terminate(),delete this.workers[t];for(let i of this.byKey.values())i.running&&i.worker===t&&this.runOnMainThread(i)}}async fetchOnMainThread(t,e){let i=performance.now();try{let s=await fetch(t.url,{signal:e,credentials:"same-origin"});if(!s.ok)throw new Error("HTTP "+s.status);let r=await s.blob(),o=performance.now()-i,a=await At(r);t.scramble&&(a=await Se(a,t.scramble)),this.onReply({key:t.key,ok:!0,bitmap:a,bytes:r.size,ms:o},-1)}catch(s){this.onReply({key:t.key,ok:!1,bytes:0,ms:0,error:String(s)},-1)}}onReply(t,e){let i=this.byKey.get(t.key);if(!i||!i.running||i.worker!==e){t.bitmap&&N(t.bitmap);return}if(!t.ok&&e>=0&&(t.error==="unsupported-bitmap"||t.error==="unsupported-offscreen")){t.error==="unsupported-bitmap"?this.dropWorker(e):(this.workersUnscramble=!1,this.runOnMainThread(i));return}i.running=!1,this.running--,this.forget(i);let s=[...i.waiters];if(i.waiters.clear(),t.ok&&t.bitmap){let r={bitmap:t.bitmap,bytes:t.bytes,ms:t.ms};for(let o of s)o.resolve(r);s.length===0&&N(t.bitmap)}else{let r=new Error(t.error??"tile failed");for(let o of s)o.reject(r)}this.pump()}};var Gt=1024*1024;function Ae(){let n=navigator.deviceMemory;if(typeof n=="number"&&n<=4)return!0;let t=typeof matchMedia=="function"&&matchMedia("(pointer: coarse)").matches,e=Math.min(screen.width,screen.height);return t&&e<=820}function Jt(){return Ae()?120*Gt:250*Gt}var et=class{constructor(t){this.budget=t;this.entries=new Map;this.used=0}get(t){let e=this.entries.get(t);return e&&(this.entries.delete(t),this.entries.set(t,e)),e}has(t){return this.entries.has(t)}put(t,e){let i=this.entries.get(t);if(i){i.bitmap!==e&&N(e);return}let s=e.width*e.height*4;this.entries.set(t,{bitmap:e,bytes:s,at:performance.now()}),this.used+=s,this.trim(this.budget)}trim(t){for(;this.used>t&&this.entries.size>0;){let e=this.entries.keys().next();if(e.done)return;let i=this.entries.get(e.value);this.entries.delete(e.value),i&&(this.used-=i.bytes,N(i.bitmap))}}};var Qt="luphoto.entropy";var Te=Math.cos(Math.PI/6),Pe=100,Ce=10,Tt=class{constructor(){this.path=0;this.turns=0;this.cells=0;this.gestures=0;this.scrolls=0;this.keys=0;this.seen=new Uint32Array(128);this.lastX=0;this.lastY=0;this.hasLast=!1;this.segX=0;this.segY=0;this.prevX=0;this.prevY=0;this.hasPrev=!1;this.touchId=-1;this.touchX=0;this.touchY=0;this.touchMoved=!1;this.lastScroll=-1/0;this.memory=null;this.load();let t={passive:!0,capture:!0};addEventListener("pointermove",e=>this.onMove(e),t),addEventListener("pointerdown",e=>this.onDown(e),t),addEventListener("pointerup",e=>this.onUp(e),t),addEventListener("pointercancel",e=>this.onCancel(e),t),addEventListener("wheel",e=>this.onScroll(e),t),addEventListener("scroll",e=>this.onScroll(e),t),addEventListener("keydown",e=>this.onKey(e),t),addEventListener("pagehide",()=>this.save()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&this.save()})}onMove(t){if(!t.isTrusted)return;let e=t.clientX,i=t.clientY;if(t.pointerType!=="mouse"){t.pointerId===this.touchId&&!this.touchMoved&&Math.abs(e-this.touchX)+Math.abs(i-this.touchY)>Ce&&(this.touchMoved=!0);return}let s=((e>>3)*73856093^(i>>3)*19349663)&4095,r=1<<(s&31);if(this.seen[s>>>5]&r||(this.seen[s>>>5]|=r,this.cells++),!this.hasLast){this.lastX=e,this.lastY=i,this.hasLast=!0;return}let o=e-this.lastX,a=i-this.lastY;if(this.lastX=e,this.lastY=i,o===0&&a===0)return;this.path+=Math.sqrt(o*o+a*a),this.segX+=o,this.segY+=a;let h=Math.sqrt(this.segX*this.segX+this.segY*this.segY);if(!(h<8)){if(this.hasPrev){let l=Math.sqrt(this.prevX*this.prevX+this.prevY*this.prevY);(this.segX*this.prevX+this.segY*this.prevY)/(h*l)=Pe&&(this.lastScroll=t.timeStamp,this.scrolls++)}onKey(t){t.isTrusted&&!t.repeat&&this.keys++}score(){let e=Math.min(25,this.path/120)+Math.min(35,this.turns*2.5)+Math.min(20,this.cells/6)+Math.min(45,this.gestures*8)+Math.min(15,this.scrolls*1.5)+Math.min(20,this.keys*2);return this.save(),Math.min(100,Math.round(e))}load(){let t=null;try{let i=sessionStorage.getItem(Qt);t=i?JSON.parse(i):null}catch{t=this.memory}if(!t)return;let e=i=>typeof i=="number"&&Number.isFinite(i)&&i>0?i:0;this.path=e(t.p),this.turns=e(t.t),this.cells=e(t.c),this.gestures=e(t.g),this.scrolls=e(t.s),this.keys=e(t.k)}save(){let t={p:Math.round(this.path),t:this.turns,c:this.cells,g:this.gestures,s:this.scrolls,k:this.keys};this.memory=t;try{sessionStorage.setItem(Qt,JSON.stringify(t))}catch{return}}},Pt=null;function Ct(){Pt??(Pt=new Tt)}function it(){return Ct(),Pt?Pt.score():0}var Ie=new Int32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Rt=new Int32Array([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]);function $t(n,t){for(let e=t;e<64;e++){let i=n[e-15],s=n[e-2],r=(i>>>7|i<<25)^(i>>>18|i<<14)^i>>>3,o=(s>>>17|s<<15)^(s>>>19|s<<13)^s>>>10;n[e]=n[e-16]+r+n[e-7]+o|0}}function qt(n,t,e,i){let s=n[0],r=n[1],o=n[2],a=n[3],h=n[4],l=n[5],c=n[6],g=n[7];for(let b=e;b>>6|h<<26)^(h>>>11|h<<21)^(h>>>25|h<<7))+(h&l^~h&c)+Ie[b]+t[b]|0,w=((s>>>2|s<<30)^(s>>>13|s<<19)^(s>>>22|s<<10))+(s&r^s&o^r&o)|0;g=c,c=l,l=h,h=a+m|0,a=o,o=r,r=s,s=m+w|0}n[0]=s,n[1]=r,n[2]=o,n[3]=a,n[4]=h,n[5]=l,n[6]=c,n[7]=g}var It=new Int32Array(64),zt=new Int32Array(8),F=new Int32Array(8);function ze(n,t=new Uint8Array(32)){F.set(Rt);let e=n.length,i=Math.ceil((e+9)/64);for(let s=0;s=r+56){let g=l-r-56;c=g<3?0:g===3?e>>>29&255:e*8>>>(7-g)*8&255}a=a<<8|c}It[o]=a}$t(It,16),zt.set(F),qt(zt,It,0,64);for(let o=0;o<8;o++)F[o]=F[o]+zt[o]|0}for(let s=0;s<8;s++)t[s*4]=F[s]>>>24,t[s*4+1]=F[s]>>>16&255,t[s*4+2]=F[s]>>>8&255,t[s*4+3]=F[s]&255;return t}var ot=4294967296,nt=class{constructor(t,e){this.w=new Int32Array(64);this.mid=new Int32Array(8);this.s=new Int32Array(8);let i=this.w;for(let s=0;s<8;s++)i[s]=t.charCodeAt(s*4)<<24|t.charCodeAt(s*4+1)<<16|t.charCodeAt(s*4+2)<<8|t.charCodeAt(s*4+3);i[10]=-2147483648,i[15]=320,this.mid.set(Rt),qt(this.mid,i,0,8),this.shift=32-Math.max(1,Math.min(32,e))}run(t,e,i){let s=this.w,r=this.s,o=this.mid,a=this.shift,h=Rt[0];s[8]=t|0;for(let l=e;l>>a))return l;return-1}},st="luphoto-sealed-1",rt=12;function at(n){let t=new Uint8Array(n.length>>>1);for(let e=0;e>>24,i[45]=o>>>16&255,i[46]=o>>>8&255,i[47]=o&255,ze(i,s);let h=Math.min(32,r.length-a);for(let l=0;l=0&&i<=Re}catch{return!1}}async function Z(n){let t=await fetch("/k",{method:"POST",credentials:"same-origin",cache:"no-store",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!t.ok)throw new Y(t.status,Number(t.headers.get("Retry-After"))||0);return await t.json()}function Nt(n){return new Promise(t=>{let e=new nt(n.token,n.bits),i=0,s=0,r=()=>{let o=Math.min(ot,s+He),a=e.run(i,s,o);if(a>=0){t(i*ot+a);return}s=o,s>=ot&&(i++,s=0),setTimeout(r,0)};setTimeout(r,0)})}function De(n,t){return n.token.length!==32||!(n.bits>=1&&n.bits<=32)?Promise.reject(new Error("puzzle")):typeof Worker>"u"||!t?Nt(n):new Promise((e,i)=>{let s;try{s=new Worker(t)}catch{e(Nt(n));return}s.onmessage=r=>{let o=r.data.pow;typeof o=="number"&&(s.terminate(),o<0?i(new Error("puzzle")):e(o))},s.onerror=()=>{s.terminate(),e(Nt(n))},s.postMessage({type:"pow",token:n.token,bits:n.bits})})}var ht=null;function Wt(n,t,e,i){if(ht)return ht.then(()=>null);let s=new Promise(r=>{let o=()=>{},a=new Promise(c=>{o=c}),h=new Ut(()=>{o(),h.wait()},i?()=>r(null):null);(async()=>{let c=await n;for(;c.challenge;){let g=c.challenge,b=De(g,e);await a,c=await t({token:g.token,nonce:await b})}return c})().then(c=>{h.dismiss(),r(c)},()=>{h.fail(),r(null)})});return ht=s,s.then(()=>{ht=null}),s}function dt(n,t,e){n.addEventListener("click",i=>{let s=t();if(i.defaultPrevented||i.button!==0||i.metaKey||i.ctrlKey||i.shiftKey||i.altKey||!s)return;if(e.score()>=e.minEntropy()||lt()){ie(s);return}i.preventDefault();let r=n.href,o=()=>({build:e.build,album:s,photos:[],context:"nav",entropy:e.score()});Wt(Z(o()),a=>Z({...o(),challenge:a}),e.workerUrl,!0).then(a=>{a&&(a.pass&&ct(a.pass),ie(s),location.assign(r))})})}function Ke(n,t){try{n.setPointerCapture(t)}catch{return}}var Ut=class{constructor(t,e){this.onHeld=t;this.onCancel=e;this.inert=[];this.start=0;this.frame=0;this.holding=!1;this.finished=!1;this.gone=!1;this.onEscape=t=>{t.key==="Escape"&&!this.gone&&(t.preventDefault(),t.stopPropagation(),this.dismiss(),this.onCancel?.())};this.restore=document.activeElement;let i=document.createElement("div");i.className="gate",i.setAttribute("role","dialog"),i.setAttribute("aria-modal","true"),i.setAttribute("aria-labelledby","gate-line");let s=document.createElement("div");s.className="gate-card";let r=document.createElement("p");r.className="gate-eyebrow",r.textContent="Photos \xB7 Lucio";let o=document.createElement("p");o.className="gate-line",o.id="gate-line",o.textContent=Ne;let a=document.createElement("button");a.type="button",a.className="gate-hold",a.setAttribute("aria-label","Hold to see the photos"),a.setAttribute("aria-describedby","gate-status");let h=document.createElementNS(ee,"svg");h.setAttribute("viewBox","0 0 64 64"),h.setAttribute("aria-hidden","true"),h.setAttribute("focusable","false");let l=(b,m)=>{let w=document.createElementNS(ee,"circle");return w.setAttribute("class",b),w.setAttribute("cx","32"),w.setAttribute("cy","32"),w.setAttribute("r",m),w},c=l("gate-ring","28");c.setAttribute("pathLength","100"),h.append(l("gate-track","28"),c,l("gate-dot","6")),a.appendChild(h);let g=document.createElement("p");g.className="visually-hidden",g.id="gate-status",g.setAttribute("aria-live","polite"),s.append(r,o,a,g),i.appendChild(s),this.root=i,this.button=a,this.ring=c,this.status=g,this.text=o;for(let b of Array.from(document.body.children))b.hasAttribute("inert")||(b.setAttribute("inert",""),this.inert.push(b));document.body.appendChild(i),document.documentElement.classList.add("has-gate"),this.bind(),a.focus({preventScroll:!0})}bind(){let t=this.button;t.addEventListener("pointerdown",e=>{e.pointerType==="mouse"&&e.button!==0||(e.preventDefault(),Ke(t,e.pointerId),this.press())});for(let e of["pointerup","pointercancel","lostpointercapture"])t.addEventListener(e,()=>this.release());t.addEventListener("keydown",e=>{(e.key===" "||e.key==="Enter")&&(e.preventDefault(),e.repeat||this.press())}),t.addEventListener("keyup",e=>{(e.key===" "||e.key==="Enter")&&(e.preventDefault(),this.release())}),t.addEventListener("blur",()=>this.release()),t.addEventListener("click",e=>e.preventDefault()),t.addEventListener("contextmenu",e=>e.preventDefault()),this.root.addEventListener("transitionend",e=>{e.target===this.root&&this.root.classList.contains("is-leaving")&&this.root.remove()}),this.onCancel&&document.addEventListener("keydown",this.onEscape,!0)}setProgress(t){this.ring.style.setProperty("stroke-dashoffset",String(100-Math.max(0,Math.min(1,t))*100))}press(){if(this.holding||this.finished)return;this.holding=!0,this.start=performance.now(),this.button.classList.add("is-pressed"),this.status.textContent="Keep holding";let t=e=>{if(!this.holding)return;let i=(e-this.start)/qe;if(this.setProgress(i),i>=1){this.holding=!1,this.finished=!0,this.frame=0,this.button.classList.remove("is-pressed"),this.onHeld();return}this.frame=requestAnimationFrame(t)};this.frame=requestAnimationFrame(t)}release(){this.holding&&(this.holding=!1,cancelAnimationFrame(this.frame),this.frame=0,this.button.classList.remove("is-pressed"),this.setProgress(0),this.status.textContent="")}wait(){this.root.classList.add("is-waiting"),this.setProgress(.28),this.status.textContent="One moment"}fail(){this.root.classList.remove("is-waiting"),this.finished=!0,this.setProgress(0),this.button.disabled=!0,this.text.textContent="Something went wrong. Reload the page to try again.",this.status.textContent=this.text.textContent}dismiss(){if(this.gone)return;this.gone=!0,document.removeEventListener("keydown",this.onEscape,!0),cancelAnimationFrame(this.frame);let t=this.root.contains(document.activeElement);for(let e of this.inert)e.removeAttribute("inert");document.documentElement.classList.remove("has-gate"),this.root.classList.add("is-leaving"),window.setTimeout(()=>this.root.remove(),400),t&&(this.restore instanceof HTMLElement&&this.restore!==document.body&&this.restore.isConnected?this.restore:document.querySelector("main"))?.focus({preventScroll:!0})}};var Ue=400,X=class{constructor(t,e=()=>!0){this.canShow=e;this.handle=null;this.loader=null;this.timer=0;this.hideTimer=0;this.visible=!1;this.element=document.createElement("div"),this.element.className="busy",this.element.setAttribute("role","status"),this.element.setAttribute("aria-label","Loading"),t.appendChild(this.element)}watch(t){if(t===this.loader){this.update(t);return}this.loader=t,clearTimeout(this.timer),this.timer=0,this.hide(),this.update(t)}update(t){if(!t||t!==this.loader)return;let e=t.status;if(!e.active||e.sharp){clearTimeout(this.timer),this.timer=0,this.hide();return}if(!this.visible&&this.timer===0){let i=Math.max(0,Ue-(performance.now()-e.started));this.timer=window.setTimeout(()=>this.check(),i)}}check(){this.timer=0;let t=this.loader;if(!(!t||!t.status.active||t.status.sharp)){if(!this.canShow()){this.timer=window.setTimeout(()=>this.check(),100);return}this.show()}}show(){if(!this.visible){if(clearTimeout(this.hideTimer),this.visible=!0,!this.handle){let t=Et();t&&(this.handle=t.loader(this.element,{size:56,color:O.paper,track:O.graphite3,rays:O.beam}),this.handle.svg.setAttribute("aria-hidden","true"))}this.element.classList.add("is-visible")}}hide(){this.visible&&(this.visible=!1,this.element.classList.remove("is-visible"),clearTimeout(this.hideTimer),this.hideTimer=window.setTimeout(()=>{!this.visible&&this.handle&&(this.handle.stop(),this.handle.svg.remove(),this.handle=null)},300))}},ut=class{constructor(t){this.loader=null;this.shown=!1;this.value=-1;this.element=document.createElement("div"),this.element.className="progress",this.element.setAttribute("aria-hidden","true"),t.appendChild(this.element)}watch(t){this.loader=t,this.value=-1,this.update(t)}update(t){if(!t||t!==this.loader)return;let e=t.status,i=e.active&&!e.sharp&&e.planned>0,s=e.planned>0?Math.min(1,e.done/e.planned):0;i!==this.shown&&(this.shown=i,this.element.classList.toggle("is-visible",i));let r=Math.round(s*1e3)/1e3;r!==this.value&&(this.value=r,this.element.style.transform="scaleX("+(i?r:1)+")")}};function pt(n,t,e){let i=t*e;for(let s=0;s=i)return s;return n.levels.length-1}function G(n,t){let e=n.tile_size,i=Math.max(0,t.u0*n.width),s=Math.min(n.width,t.u1*n.width),r=Math.max(0,t.v0*n.height),o=Math.min(n.height,t.v1*n.height);return s<=i||o<=r?null:{x0:Math.min(n.cols-1,Math.floor(i/e)),x1:Math.min(n.cols-1,Math.ceil(s/e)-1),y0:Math.min(n.rows-1,Math.floor(r/e)),y1:Math.min(n.rows-1,Math.ceil(o/e)-1)}}function re(n,t,e){let i=n.levels[t],s=i.tile_size,r=G(i,e);if(!r)return[];let o=(e.u0+e.u1)/2*i.width,a=(e.v0+e.v1)/2*i.height,h=[];for(let l=r.y0;l<=r.y1;l++)for(let c=r.x0;c<=r.x1;c++){let g=(c*s+Math.min((c+1)*s,i.width))/2,b=(l*s+Math.min((l+1)*s,i.height))/2;h.push({level:t,x:c,y:l,index:l*i.cols+c,distance:(g-o)**2+(b-a)**2})}return h.sort((l,c)=>l.distance-c.distance),h.map(({level:l,x:c,y:g,index:b})=>({level:l,x:c,y:g,index:b}))}function ne(n,t,e,i,s,r){let o=n.tile_size,a=Math.round(i+t*o*r),h=Math.round(i+Math.min((t+1)*o,n.width)*r),l=Math.round(s+e*o*r),c=Math.round(s+Math.min((e+1)*o,n.height)*r);return h<=a||c<=l?null:{dx:a,dy:l,dw:h-a,dh:c-l}}function oe(n,t,e,i,s,r,o,a){let h=e.tile_size,l=e.overlap??0,c=i*h,g=Math.min((i+1)*h,e.width),b=s*h,m=Math.min((s+1)*h,e.height),w=i>0?c-l:0,u=s>0?b-l:0,y=Math.round(r+c*a),d=Math.round(r+g*a),v=Math.round(o+b*a),f=Math.round(o+m*a);if(d<=y||f<=v)return;let M=Math.max(w,(y-r)/a),A=Math.min(w+t.width,(d-r)/a),p=Math.max(u,(v-o)/a),L=Math.min(u+t.height,(f-o)/a);A<=M||L<=p||n.drawImage(t,M-w,p-u,A-M,L-p,y,v,d-y,f-v)}var ae="luphoto.throughput";function he(){try{let n=Number(sessionStorage.getItem(ae));return Number.isFinite(n)&&n>0?n:null}catch{return null}}function le(){return he()??1e3}function ce(n){let t=he(),e=t===null?n:t*(1-.5)+n*.5;try{sessionStorage.setItem(ae,String(e))}catch{return e}return e}var U=180,de=400,We=2e3,W=16,Ot="j:";function Oe(n,t){return new Promise((e,i)=>{if(t.aborted){i(new z);return}let s=setTimeout(()=>{t.removeEventListener("abort",r),e()},n),r=()=>{clearTimeout(s),i(new z)};t.addEventListener("abort",r,{once:!0})})}function Ye(n,t,e){return t.aborted?Promise.resolve(e):new Promise(i=>{let s=()=>i(e);t.addEventListener("abort",s,{once:!0}),n.then(r=>{t.removeEventListener("abort",s),i(r)})})}var ue=3,mt=4,B=class{constructor(t,e,i){this.pyramid=t;this.poolUrl=e;this.env=i;this.seedImage=null;this.seedPromise=null;this.seedAt=0;this.pool=null;this.sealed="";this.poolPromise=null;this.poolRetryAt=0;this.opened=null;this.ids=null;this.triedKey=null;this.jumbleLevel=-1;this.jumble=[];this.settling=!1;this.session=null;this.prefetchController=null;this.finalLevel=-1;this.targetLevel=-1;this.status={active:!1,started:0,planned:0,done:0,sharp:!1}}get stalled(){return!this.opened&&!this.settling}tileUrl(t){let e=this.env.tiles;return e.path+this.pyramid.hash+"/"+t+"."+e.format}ensurePool(){return this.pool?Promise.resolve(!0):(this.poolPromise||(this.poolPromise=fetch(this.poolUrl,{credentials:"same-origin"}).then(t=>t.ok?t.json():Promise.reject(new Error("pool"))).then(t=>{let e=this.pyramid.levels;if(!Array.isArray(t.levels)||t.levels.length!==e.length||typeof t.sealed!="string")throw new Error("pool");for(let i=0;i(this.poolPromise=null,this.poolRetryAt=performance.now()+We,!1))),this.poolPromise)}open(){if(this.opened)return!0;let t=this.env.keys.key(this.pyramid.hash),e=this.pool;if(!t||!e||t===this.triedKey)return!1;this.triedKey=t;let i=te(t,this.sealed),s=null;if(i)try{s=JSON.parse(new TextDecoder().decode(i))}catch{s=null}let r=this.pyramid.levels;if(!s||!Array.isArray(s.levels)||s.levels.length!==r.length)return!1;let o=[];for(let a=0;a=0&&b=this.poolRetryAt&&this.ensurePool();return}this.opened||this.open()}ensureSeed(){return this.opened?(this.seedPromise||(this.seedPromise=this.decodeSeed().then(()=>{this.seedAt=performance.now(),this.env.requestDraw()},()=>{})),this.seedPromise):Promise.resolve()}async decodeSeed(){let t=this.opened?.seed;if(!t)return;let e=await At(new Blob([Ht(t)],{type:"image/"+this.env.tiles.format})),i=document.createElement("canvas");i.width=e.width*mt,i.height=e.height*mt;let s=i.getContext("2d");if(!s){this.seedImage=e;return}s.imageSmoothingEnabled=!0,s.imageSmoothingQuality="high","filter"in s&&(s.filter="blur("+mt*.75+"px)");let r=mt*2;s.drawImage(e,-r,-r,i.width+r*2,i.height+r*2),N(e),this.seedImage=i}async request(t,e,i,s,r){let o=this.tileUrl(e),a;try{a=await this.env.scheduler.request(t,o,i,s,r)}catch(h){if(s.aborted||h instanceof z)throw h;await Oe(de+Math.random()*de,s),a=await this.env.scheduler.request(t,o,i,s,r)}return this.env.cache.put(t,a.bitmap),this.env.requestDraw(),a}fetchTile(t,e,i){let s=this.ids,r=this.opened;if(!s||!r)return Promise.reject(new z);let o=s[t.level][t.index],a=this.env.tiles,h=a.cell??64,l=a.scrambled&&r.scramble&&this.pyramid.levels[t.level].tile_size>=2*h?{seed:r.scramble,level:t.level,x:t.x,y:t.y,cell:h}:void 0;return this.request(o,o,e,i,l)}fetchJumble(t,e,i){return this.request(Ot+t,t,e,i)}uncached(t,e){let i=this.ids;return i?re(this.pyramid,t,e).filter(s=>!this.env.cache.has(i[t][s.index])):[]}uncachedBytes(t,e){let i=this.opened?.levels[t].bytes??[],s=0;for(let r of this.uncached(t,e))s+=i[r.index]??0;return s}chooseJumble(t,e){let i=this.pool;if(!i)return[];if(this.jumbleLevel<0){let s=this.probeLevel(t,e),r=this.pyramid.levels[s].cols*this.pyramid.levels[s].rows,o=i[s].length/W,a=new Array(r);for(let h=0;h!this.env.cache.has(Ot+s))}probeLevel(t,e){return Math.max(0,pt(this.pyramid,t.displayWidth,e)-ue)}notify(){this.env.onStatus?.(this)}track(t,e){return this.status.planned+=t.length,this.notify(),Promise.allSettled(t.map(i=>i().finally(()=>{this.session===e&&(this.status.done++,this.notify())})))}start(t,e,i){this.stopSession();let s=new AbortController;this.session=s,this.targetLevel=-1,this.status.active=!0,this.status.started=performance.now(),this.status.planned=0,this.status.done=0,this.status.sharp=!1,this.notify(),this.run(t,e,s).then(()=>{this.session===s&&(this.session=null,this.status.active=!1,this.notify()),(!s.signal.aborted||s.signal.reason==="deadline")&&i()})}async run(t,e,i){let s=i.signal,r=performance.now(),o=this.env.settings.budgetMs,a=setTimeout(()=>i.abort("deadline"),o);try{let h=await Ye(this.ensurePool(),s,!1);if(s.aborted||h&&!this.open()&&(this.settling=!0,await this.env.keys.settle(this.pyramid.hash,s),this.settling=!1,s.aborted))return;if(!h||!this.open()){let y=this.chooseJumble(t,e);await this.track(y.map(d=>()=>this.fetchJumble(d,tt,s)),i);return}if(await this.ensureSeed(),s.aborted)return;let l=pt(this.pyramid,t.displayWidth,e),c=Math.max(0,l-ue),g=this.uncached(c,t).slice(0,2);if(g.length>0){let y=await this.track(g.map(f=>()=>this.fetchTile(f,tt,s)),i),d=0,v=0;for(let f of y)f.status==="fulfilled"&&(d+=f.value.bytes,v=Math.max(v,f.value.ms));d>0&&v>0&&ce(d/v)}if(s.aborted)return;this.finalLevel=Math.max(this.finalLevel,c);let b=le(),m=o-(performance.now()-r),w=c;for(let y=l;y>c;y--)if(this.uncachedBytes(y,t)/b<=m*.8){w=y;break}let u=[];w-c>=2&&u.push(Math.floor((c+w)/2)),w>c&&u.push(w),this.finalLevel=w,this.targetLevel=w,this.env.requestDraw();for(let y of u)if(await this.track(this.uncached(y,t).map(d=>()=>this.fetchTile(d,tt,s)),i),s.aborted)return}finally{clearTimeout(a)}}prefetchProbe(t,e){let s=this.resetPrefetch().signal;this.ensurePool().then(async r=>{if(!(s.aborted||!r||!this.open())&&(await this.ensureSeed(),!s.aborted))for(let o of this.uncached(this.probeLevel(t,e),t))this.fetchTile(o,St,s).catch(()=>{})})}prefetchLevel(t,e){if(e<0||!this.opened)return;let i=this.resetPrefetch().signal;for(let s of this.uncached(e,t))this.fetchTile(s,St,i).catch(()=>{})}resetPrefetch(){return this.prefetchController?.abort(),this.prefetchController=new AbortController,this.prefetchController}stopPrefetch(){this.prefetchController?.abort(),this.prefetchController=null}stopSession(){this.session&&(this.session.abort("superseded"),this.session=null,this.status.active=!1,this.notify())}stop(){this.stopSession(),this.stopPrefetch()}drawJumble(t,e){if(this.jumbleLevel<0)return!1;let{g:i,originX:s,originY:r,width:o,now:a}=t,h=this.pyramid.levels[this.jumbleLevel],l=G(h,e);if(!l)return!1;let c=o/h.width,g=this.env.cache,b=!1;i.imageSmoothingEnabled=!0,i.imageSmoothingQuality="medium";for(let m=l.y0;m<=l.y1;m++)for(let w=l.x0;w<=l.x1;w++){let u=g.get(Ot+this.jumble[m*h.cols+w]),y=u?ne(h,w,m,s,r,c):null;if(!u||!y)continue;let d=a-u.at;d=0&&v<0;p--){let L=G(u[p],m);if(!L)continue;let x=!0;for(let k=L.y0;k<=L.y1&&x;k++)for(let S=L.x0;S<=L.x1;S++){let E=w.get(y[p][k*u[p].cols+S]);if(!E||t.now-E.at=0&&p=0?Math.min(this.targetLevel,d):d,A=y!==null&&v>=M;if(A!==this.status.sharp&&(this.status.sharp=A,queueMicrotask(()=>this.notify())),!y)return f;for(let p=Math.max(0,v);p<=d;p++){let L=u[p],x=G(L,m);if(!x)continue;let k=r/L.width;e.imageSmoothingEnabled=!0,e.imageSmoothingQuality=k<1?"high":"medium";for(let S=x.y0;S<=x.y1;S++)for(let E=x.x0;E<=x.x1;E++){let T=w.get(y[p][S*L.cols+E]);if(!T)continue;let P=t.now-T.at;Pthis.requestDraw(),onStatus:()=>this.onStatus(this)})}get isOpen(){return this.expanded}get isNear(){return this.near}layout(t){let e=this.cover,i=Math.max(t.width/e.width,t.open/e.height),s=e.width*i,r=e.height*i,o=(t.open-r)/2,a=o+this.focusY*r,h=Math.max(0,Math.min(t.open-t.closed,a-t.closed/2)),l=this.geometry;this.geometry={width:t.width,closed:t.closed,open:t.open,dpr:t.dpr,coverWidth:s,coverHeight:r,x:(t.width-s)/2,y:o,band:h},this.canvas&&(this.sizeCanvas(this.canvasOpen),this.drawNow()),this.near&&l&&(l.width!==t.width||l.closed!==t.closed||l.open!==t.open||l.dpr!==t.dpr)&&this.startSession()}attach(){if(this.canvas)return;let t=document.createElement("canvas");t.className="strip-canvas",t.setAttribute("aria-hidden","true");let e=t.getContext("2d",{alpha:!1});e&&(this.canvas=t,this.g=e,this.element.prepend(t),this.sizeCanvas(this.expanded),this.drawNow())}detach(){this.canvas&&(cancelAnimationFrame(this.frame),this.frame=0,this.canvas.width=0,this.canvas.height=0,this.canvas.remove(),this.canvas=null,this.g=null)}setNear(t){t!==this.near&&(this.near=t,t?this.startSession():this.loader.stop())}setOpen(t){if(t===this.expanded)return;this.expanded=t,this.element.classList.toggle("is-open",t),clearTimeout(this.settleTimer);let e=this.geometry,i=this.canvas;t?i&&this.canvasOpen?(i.style.transition="",i.style.transform="translate3d(0,0,0)"):i&&e&&(this.sizeCanvas(!0),i.style.transition="none",i.style.transform="translate3d(0,"+-e.band+"px,0)",this.drawNow(),requestAnimationFrame(()=>{requestAnimationFrame(()=>{this.expanded&&this.canvas===i&&(i.style.transition="",i.style.transform="translate3d(0,0,0)")})})):i&&e&&(i.style.transition="",i.style.transform="translate3d(0,"+-e.band+"px,0)",this.settleTimer=window.setTimeout(()=>{!this.expanded&&this.canvas===i&&(this.sizeCanvas(!1),this.drawNow())},Xe)),this.near&&this.startSession()}sizeCanvas(t){let e=this.canvas,i=this.geometry;if(!e||!i)return;this.canvasOpen=t;let s=t?i.open:i.closed,r=Math.max(1,Math.round(i.width*i.dpr)),o=Math.max(1,Math.round(s*i.dpr));(e.width!==r||e.height!==o)&&(e.width=r,e.height=o),e.style.height=s+"px",t||(e.style.transition="none",e.style.transform="translate3d(0,0,0)")}view(){let t=this.geometry;if(!t)return null;let e=this.expanded?0:t.band,i=this.expanded?t.open:t.closed;return{displayWidth:t.coverWidth,u0:Math.max(0,-t.x/t.coverWidth),u1:Math.min(1,(t.width-t.x)/t.coverWidth),v0:Math.max(0,(e-t.y)/t.coverHeight),v1:Math.min(1,(e+i-t.y)/t.coverHeight)}}startSession(){let t=this.view();!t||!this.geometry||this.loader.start(t,this.geometry.dpr,()=>{})}requestDraw(){this.frame===0&&this.canvas&&(this.frame=requestAnimationFrame(t=>{this.frame=0,this.draw(t)&&this.requestDraw()}))}drawNow(){this.draw(performance.now())&&this.requestDraw()}draw(t){let e=this.g,i=this.canvas,s=this.geometry;if(!e||!i||!s)return!1;e.setTransform(1,0,0,1,0,0),e.globalAlpha=1,e.fillStyle="#111114",e.fillRect(0,0,i.width,i.height);let r=this.canvasOpen?0:-s.band;return this.loader.draw({g:e,originX:s.x*s.dpr,originY:(s.y+r)*s.dpr,width:s.coverWidth*s.dpr,height:s.coverHeight*s.dpr,canvasWidth:i.width,canvasHeight:i.height,displayWidth:s.coverWidth,dpr:s.dpr,now:t})}};function pe(n){let t=n.dataset,e=(i,s)=>{let r=Number(i);return Number.isFinite(r)&&r>0?r:s};return{page:t.page??"",build:t.build??"",slug:t.album??"",manifestUrl:t.manifest??"",indexUrl:t.index??"",workerUrl:t.worker??"",budgetMs:e(t.budgetMs,3e3),maxDpr:e(t.maxDpr,2),concurrency:Math.max(1,Math.round(e(t.concurrency,6))),blockContextMenu:t.blockContextMenu!=="false",gate:t.gate==="off"?"off":"server",minEntropy:t.minEntropy&&Number.isFinite(Number(t.minEntropy))?Number(t.minEntropy):20}}function J(n,t,e){return"/a/"+encodeURIComponent(t)+"/p/"+e+"."+n+".json"}var Be=24,ft=class{constructor(t,e,i,s){this.root=t;this.settings=i;this.env=s;this.strips=[];this.onScreen=new Set;this.inView=new Set;this.suspended=!1;this.wordmark=null;this.opened=null;this.scrollFrame=0;this.sizeKey="";let r=Array.from(t.querySelectorAll("a.strip")),o=new Map(e.albums.map(h=>[h.slug,h]));for(let h of r){let l=o.get(h.dataset.slug??"");!l||!l.cover||this.strips.push(new _(h,l.cover,l.collapsed_focus_y??.5,J(e.build,l.slug,l.cover.hash),s,c=>this.onStripStatus(c)))}this.hoverMode=matchMedia("(hover: hover) and (pointer: fine)");let a=document.querySelector(".site-header .wordmark");if(this.indicator=new X(document.body,()=>!this.wordmarkMoving()),a){this.wordmark=K(a,!0);let h=()=>{this.wordmark&&!this.indicator.visible&&this.wordmark.play()},l=()=>this.wordmark?.reverse();a.addEventListener("mouseenter",h),a.addEventListener("mouseleave",l),a.addEventListener("focus",h),a.addEventListener("blur",l)}document.documentElement.classList.add("has-strips"),this.measure(),this.observe(),this.bind()}suspend(t){if(!this.suspended){this.suspended=!0;for(let e of this.strips)e.loader.stop(),t&&e.detach();this.env.scheduler.cancelAll(),this.env.cache.trim(t?0:this.env.cache.budget/4)}}resume(){if(this.suspended){this.suspended=!1;for(let t of this.strips)this.inView.has(t)&&t.attach(),t.isNear&&t.startSession()}}wordmarkMoving(){let t=this.wordmark?.t??0;return t>0&&t<1}measure(){let t=this.root.clientWidth||window.innerWidth,e=window.innerHeight,i=Math.round(Math.min(t*6/32,e*.28)),s=Math.round(Math.min(t*9/32,e*.62)),r=Math.min(window.devicePixelRatio||1,this.settings.maxDpr),o=t+"x"+i+"x"+s+"@"+r;if(o!==this.sizeKey){this.sizeKey=o,this.root.style.setProperty("--strip-closed",i+"px"),this.root.style.setProperty("--strip-open",s+"px");for(let a of this.strips)a.layout({width:t,closed:i,open:s,dpr:r})}}observe(){let t=new Map(this.strips.map(r=>[r.element,r])),e=new IntersectionObserver(r=>{for(let o of r)t.get(o.target)?.setNear(o.isIntersecting)},{rootMargin:"100% 0px"}),i=new IntersectionObserver(r=>{for(let o of r){let a=t.get(o.target);a&&(o.isIntersecting?(this.inView.add(a),this.suspended||a.attach()):(this.inView.delete(a),a.detach()))}},{rootMargin:"25% 0px"}),s=new IntersectionObserver(r=>{for(let o of r){let a=t.get(o.target);a&&(o.isIntersecting?this.onScreen.add(a):this.onScreen.delete(a))}this.watchFirst(),this.scheduleCentre()});for(let r of this.strips)e.observe(r.element),i.observe(r.element),s.observe(r.element)}watchFirst(){let t=this.strips.find(e=>this.onScreen.has(e))??null;this.indicator.watch(t?t.loader:null)}onStripStatus(t){this.indicator.update(t.loader)}bind(){for(let t of this.strips){let e=t.element;e.addEventListener("mouseenter",()=>{this.hoverMode.matches&&this.open(t)}),e.addEventListener("mouseleave",()=>{this.hoverMode.matches&&this.opened===t&&this.open(null)}),e.addEventListener("focus",()=>this.open(t)),e.addEventListener("blur",()=>{this.opened===t&&!this.hoverMode.matches?this.scheduleCentre():this.opened===t&&this.open(null)}),e.addEventListener("dragstart",i=>i.preventDefault()),this.settings.blockContextMenu&&e.addEventListener("contextmenu",i=>i.preventDefault())}window.addEventListener("scroll",()=>this.scheduleCentre(),{passive:!0}),new ResizeObserver(()=>{this.measure(),this.scheduleCentre()}).observe(this.root)}open(t){t!==this.opened&&(this.opened?.setOpen(!1),this.opened=t,t?.setOpen(!0))}scheduleCentre(){this.hoverMode.matches||this.scrollFrame!==0||(this.scrollFrame=requestAnimationFrame(()=>{this.scrollFrame=0,this.pickCentre()}))}pickCentre(){if(this.hoverMode.matches)return;let t=window.innerHeight/2,e=null,i=1/0,s=1/0;for(let r of this.onScreen){let o=r.element.getBoundingClientRect(),a=Math.abs(o.top+o.height/2-t);at,settle:()=>Promise.resolve()}}var _e=8,je=400,Ve=2e3,me=/^[0-9a-f]{64}$/,vt=class{constructor(t,e,i,s){this.gate=t;this.slug=e;this.context=i;this.workerUrl=s;this.keys=new Map;this.inflight=new Set;this.waiters=new Set;this.listeners=[];this.queue=[];this.busy=!1;this.blocked=!1;this.failed=!1;this.pausedUntil=0;this.page="";if(this.server=t.mode!=="off",!this.server)for(let[r,o]of Object.entries(t.keys??{}))me.test(o)&&this.keys.set(r,at(o))}onKeys(t){this.listeners.push(t)}key(t){return this.keys.get(t)??null}has(t){return this.keys.has(t)}want(t,e){if(!this.server||t.every(s=>this.keys.has(s)||this.inflight.has(s)))return;let i=s=>!this.keys.has(s)&&!this.inflight.has(s);this.queue=Array.from(new Set(t.concat(e))).filter(i),this.pump()}settle(t,e){return new Promise(i=>{if(this.keys.has(t)||this.blocked||this.failed||e.aborted){i();return}let s=()=>{clearTimeout(o),this.waiters.delete(r),e.removeEventListener("abort",s),i()},r=()=>{(this.keys.has(t)||this.blocked||this.failed)&&s()},o=window.setTimeout(s,je);this.waiters.add(r),e.addEventListener("abort",s,{once:!0})})}wake(){for(let t of Array.from(this.waiters))t()}body(t,e){let i={build:this.gate.build,album:this.slug,photos:t,context:this.context,entropy:it()};return e&&(i.pass=e),this.page&&(i.page=this.page),i}pump(){if(this.busy||this.blocked||this.failed||this.queue.length===0||performance.now(){this.queue=Array.from(new Set(e.concat(this.queue))).filter(i=>!this.keys.has(i)&&!this.inflight.has(i)),this.pump()},t)}async send(t){this.busy=!0;for(let s of t)this.inflight.add(s);let e=[],i=0;try{let s=lt(),r=await Z(this.body(t,s));if(this.absorb(r,s),r.challenge){this.blocked=!0,this.wake();let o=await Wt(Promise.resolve(r),a=>Z({...this.body(t,""),challenge:a}),this.workerUrl,!1);this.blocked=!1,o?this.absorb(o,""):this.failed=!0}}catch(s){s instanceof Y&&s.status===429?(i=Math.max(1,s.retryAfter)*1e3,e=t):s instanceof Y&&s.status>=400&&s.status<500?this.failed=!0:(i=Ve,e=t)}finally{for(let s of t)this.inflight.delete(s);this.busy=!1,this.wake()}i>0?this.pause(i,e.filter(s=>!this.keys.has(s))):this.pump()}absorb(t,e){t.stale&&e&<()===e&&ct(null),t.pass&&ct(t.pass),t.page&&(this.page=t.page);let i=[];for(let[s,r]of Object.entries(t.keys??{}))me.test(r)&&!this.keys.has(s)&&(this.keys.set(s,at(r)),i.push(s));if(i.length>0){this.wake();for(let s of this.listeners)s(i)}}};var Ze=/[㐀-鿿豈-﫿]/;function bt(n,t){Ze.test(t)?n.lang="zh":n.removeAttribute("lang")}function fe(n){return n<10?"0"+n:String(n)}function Ge(n){let t=(n.model??"").trim(),e=(n.make??"").trim(),i=e.split(/\s+/)[0]??"";i&&t.toLowerCase().startsWith(i.toLowerCase()+" ")&&(t=t.slice(i.length+1).trim());let s=/^([A-Za-z]{1,3}) (\d+[A-Za-z0-9]*)$/.exec(t);return s&&(t=s[1]+s[2]),t||e}function Je(n){let t=/(\d+(?:\.\d+)?(?:-\d+(?:\.\d+)?)?)\s*mm\s*(?:F|f\/?)\s*([\d.]+(?:-[\d.]+)?)/.exec(n);return t?t[1]+" f/"+t[2]:n.trim()}function yt(n){return String(Math.round(n*10)/10)}function Qe(n){let t=n.trim();if(t.includes("/")||t.endsWith("s"))return t;let e=Number(t);if(!Number.isFinite(e)||e<=0)return t;if(e>=1)return yt(e)+"s";let i=1/e;return i<10&&Math.abs(i-Math.round(i))>.05?"1/"+yt(i):"1/"+Math.round(i)}function $e(n,t,e,i){let s=[fe(n+1)+" / "+fe(t)],r=e.exif;if(i&&r){let o=Ge(r);o&&s.push(o),r.lens&&s.push(Je(r.lens)),r.focal_length&&s.push(yt(r.focal_length)+"mm"),r.f_number&&s.push("f/"+yt(r.f_number)),r.exposure&&s.push(Qe(r.exposure)),r.iso&&s.push("ISO "+r.iso)}return s.join(" \xB7 ")}function ti(n,t){n.textContent="",t.split(/\r?\n/).forEach((e,i)=>{i>0&&n.appendChild(document.createElement("br"));let s=e.split("*"),r=(s.length-1)%2===0;s.forEach((o,a)=>{let h=a%2===1;if(h&&(r||a!==s.length-1)){let l=document.createElement("em");l.textContent=o,n.appendChild(l)}else n.appendChild(document.createTextNode((h?"*":"")+o))})})}var wt=class{constructor(t){this.visible=!1;this.placement="";this.element=document.createElement("section"),this.element.className="caption",this.element.setAttribute("aria-label","Caption"),this.meta=document.createElement("p"),this.meta.className="caption-meta",this.title=document.createElement("h2"),this.title.className="caption-title",this.text=document.createElement("p"),this.text.className="caption-text",this.element.append(this.meta,this.title,this.text),t.appendChild(this.element)}set(t,e,i,s){this.meta.textContent=$e(e,i,t,s),this.title.textContent=t.title??"",this.title.hidden=!t.title,bt(this.title,t.title??""),ti(this.text,t.caption??""),this.text.hidden=!t.caption,bt(this.text,t.caption??"")}show(t){t!==this.visible&&(this.visible=t,this.element.classList.toggle("is-visible",t))}place(t,e,i){let s=Math.round(t)+","+Math.round(e)+","+Math.round(i);if(s===this.placement)return;this.placement=s;let r=this.element.style;r.width=Math.round(e)+"px",r.transform="translate3d("+Math.round(t)+"px,"+-Math.round(i)+"px,0)"}};var xt=24,ve=10,ei=300,ii=.35,ge=.35,si=.2,ri=2500,ni=120,oi=16,ai=.002,hi=.01;function li(n,t,e,i){let s=3*n,r=3*(e-n)-s,o=1-s-r,a=3*t,h=3*(i-t)-a,l=1-a-h,c=m=>((o*m+r)*m+s)*m,g=m=>((l*m+h)*m+a)*m,b=m=>(3*o*m+2*r)*m+s;return m=>{if(m<=0)return 0;if(m>=1)return 1;let w=m;for(let d=0;d<8;d++){let v=c(w)-m,f=b(w);if(Math.abs(v)<1e-5)return g(w);if(Math.abs(f)<1e-6)break;w-=v/f}let u=0,y=1;w=m;for(let d=0;d<24;d++){let v=c(w);if(Math.abs(v-m)<1e-5)break;vthis.onKeys(h)),o&&dt(this.nextLink,()=>this.nextSlug,o),this.bind(),this.activate(-1),this.requestDraw(),this.wake(),this.loadNextAlbum()}buildEndCard(){let t=document.createElement("section");t.className="end-card",t.setAttribute("aria-label","End of album");let e=document.createElement("a");e.className="next-album",e.href="/";let i=document.createElement("span");i.className="next-strip";let s=document.createElement("span");s.className="next-text";let r=document.createElement("span");r.className="next-eyebrow",r.textContent="All albums";let o=document.createElement("span");o.className="next-title",s.append(r,o),i.appendChild(s),e.appendChild(i);let a=document.createElement("div");a.className="signoff";let h=Vt();h&&a.appendChild(h);let l=document.createElement("p");return l.className="signature",l.textContent="\u2014 Lucio",a.appendChild(l),t.append(e,a),t}loader(t){let e=this.loaders[t];if(!e){let i=this.manifest.photos[t];e=new B(i,J(this.manifest.build,this.manifest.slug,i.hash),{...this.env,requestDraw:()=>this.requestDraw(),onStatus:s=>{this.indicator.update(s),this.progress.update(s)}}),this.loaders[t]=e}return e}measure(){let t=this.stage.getBoundingClientRect();this.vw=Math.max(1,t.width),this.vh=Math.max(1,t.height),this.ox=t.left,this.oy=t.top,this.dpr=Math.min(window.devicePixelRatio||1,this.settings.maxDpr);let e=Math.max(1,Math.round(this.vw*this.dpr)),i=Math.max(1,Math.round(this.vh*this.dpr));(this.canvas.width!==e||this.canvas.height!==i)&&(this.canvas.width=e,this.canvas.height=i),this.layouts=[],this.stops=[];let s=0;this.manifest.photos.forEach((r,o)=>{let a=Math.max(1,r.slides||1),h=Math.min(this.vw/(r.width/a),this.vh/r.height),l=r.width*h,c=r.height*h,g=l/a,b=s+xt/2+(this.vw-g)/2;this.layouts.push({scale:h,width:l,height:c,section:g,slides:a,start:s,left:b,top:(this.vh-c)/2});for(let m=0;m{this.pointerId===null&&document.body.classList.add("is-idle")},ri)}stopForHash(){let t=/^#(\d+)$/.exec(location.hash);if(!t)return 0;let e=Math.min(this.manifest.photos.length,Math.max(1,Number(t[1])))-1,i=this.stops.findIndex(s=>s.photo===e);return i<0?0:i}bind(){let t=this.stage;t.addEventListener("pointerdown",e=>this.onPointerDown(e)),t.addEventListener("pointermove",e=>this.onPointerMove(e)),t.addEventListener("pointerup",e=>this.onPointerUp(e,!1)),t.addEventListener("pointercancel",e=>this.onPointerUp(e,!0)),t.addEventListener("pointerleave",e=>{e.pointerType==="mouse"&&this.pointerId===null&&(this.hover=!1,this.updateCaption())}),t.addEventListener("wheel",e=>this.onWheel(e),{passive:!1}),t.addEventListener("gesturestart",e=>{e.preventDefault(),this.gestureZoom=this.zoom}),t.addEventListener("gesturechange",e=>this.onGesture(e)),t.addEventListener("gestureend",e=>e.preventDefault()),t.addEventListener("dragstart",e=>e.preventDefault()),t.addEventListener("selectstart",e=>e.preventDefault()),this.settings.blockContextMenu&&t.addEventListener("contextmenu",e=>e.preventDefault()),window.addEventListener("keydown",e=>this.onKey(e)),window.addEventListener("hashchange",()=>{let e=this.stopForHash();this.stops[e].photo!==this.stops[this.current].photo?this.jump(e):this.clearZoom()&&(this.startSession(),this.updateCaption())}),new ResizeObserver(()=>this.onResize()).observe(t),this.fade.addEventListener("transitionend",()=>{this.fade.style.opacity==="0"&&(this.fade.width=1,this.fade.height=1)})}onResize(){let t=this.vw+"x"+this.vh+"@"+this.dpr;this.measure(),t!==this.vw+"x"+this.vh+"@"+this.dpr&&(this.clearZoom(),this.tween=null,this.camera=this.stops[this.current].camera,this.requestDraw(),clearTimeout(this.resizeTimer),this.resizeTimer=window.setTimeout(()=>this.startSession(),200))}onKey(t){if(t.altKey||t.ctrlKey||t.metaKey)return;this.wake();let e=t.target;if(!(e&&(e.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(e.tagName)))){switch(t.key){case"ArrowRight":this.go(this.current+1);break;case"ArrowLeft":this.go(this.current-1);break;case"Home":this.go(0);break;case"End":this.go(this.stops.length-2);break;case"Escape":this.zoomPhoto>=0?this.go(this.current):location.assign("/");break;case"i":case"I":this.pinned=!this.pinned,this.updateCaption();break;default:return}t.preventDefault()}}onPointerDown(t){if(!(t.pointerType==="mouse"&&t.button!==0)){if(this.pointerId!==null){this.secondId===null&&t.pointerType!=="mouse"&&this.pointerType!=="mouse"&&!this.stale&&(this.zoomPhoto>=0||!this.dragging&&this.enterZoom())&&(this.secondId=t.pointerId,this.bx=t.clientX,this.by=t.clientY,this.pinching=!0,this.dragging=!0,this.stage.setPointerCapture(t.pointerId));return}t.target.closest("a, button")||(this.pointerId=t.pointerId,this.pointerType=t.pointerType,this.dragging=!1,this.stale=!1,this.downX=t.clientX,this.downY=t.clientY,this.ax=t.clientX,this.ay=t.clientY,this.downT=t.timeStamp,this.tween=null,this.downCamera=this.camera,this.samples=[{t:t.timeStamp,x:t.clientX}],this.stage.setPointerCapture(t.pointerId))}}onPointerMove(t){if(t.pointerType==="mouse"&&this.wake(),this.pointerId===null){t.pointerType==="mouse"&&(this.hover=this.inCaptionZone(t.clientX,t.clientY),this.updateCaption());return}if(this.pinching&&(t.pointerId===this.pointerId||t.pointerId===this.secondId)){this.pinchMove(t.pointerId,t.clientX,t.clientY);return}if(t.pointerId!==this.pointerId||this.stale)return;let e=t.clientX-this.downX,i=t.clientY-this.downY;if(!this.dragging&&Math.hypot(e,i)>=ve&&(this.dragging=!0,this.stage.classList.add("is-dragging"),this.updateCaption()),!this.dragging){this.ax=t.clientX,this.ay=t.clientY;return}if(this.zoomPhoto>=0){this.zx+=t.clientX-this.ax,this.zy+=t.clientY-this.ay,this.ax=t.clientX,this.ay=t.clientY,this.settleZoom();return}for(this.samples.push({t:t.timeStamp,x:t.clientX});this.samples.length>2&&t.timeStamp-this.samples[0].t>100;)this.samples.shift();this.camera=this.rubber(this.downCamera-e),this.requestDraw()}onPointerUp(t,e){if(this.pinching&&(t.pointerId===this.pointerId||t.pointerId===this.secondId)){this.endPinch(t.pointerId);return}if(t.pointerId!==this.pointerId)return;this.stage.hasPointerCapture(t.pointerId)&&this.stage.releasePointerCapture(t.pointerId),this.pointerId=null;let i=this.dragging;if(this.dragging=!1,this.stage.classList.remove("is-dragging"),this.stale){this.stale=!1;return}let s=Math.hypot(t.clientX-this.downX,t.clientY-this.downY);if(!e&&!i&&s=0)return;let r=0,o=this.samples[0],a=this.samples[this.samples.length-1];o&&a&&a.t>o.t&&t.timeStamp-a.t<100&&(r=(a.x-o.x)/(a.t-o.t));let h=this.nearestStop(this.camera);if(!e&&Math.abs(r)>ii)if(r<0){let l=this.stops.findIndex(c=>c.camera>this.camera+1);h=l<0?this.stops.length-1:l}else{let l=0;this.stops.forEach((c,g)=>{c.camera=0)return;let i=this.photoRect(e.photo);t.clientX>=i.left&&t.clientX<=i.right&&t.clientY>=i.top&&t.clientY<=i.bottom&&(this.pinned=!this.pinned,this.updateCaption())}onWheel(t){if(t.preventDefault(),this.pinching||this.dragging&&this.zoomPhoto<0)return;let e=t.deltaY;if(t.deltaMode===1?e*=oi:t.deltaMode===2&&(e*=this.vh),e===0)return;let i=Math.max(-1,Math.min(1,e*(t.ctrlKey?hi:ai))),s=t.clientX-this.ox,r=t.clientY-this.oy;this.zoomTo(this.zoom*Math.exp(-i),s,r,s,r)}onGesture(t){if(t.preventDefault(),this.pointerId!==null||!t.scale)return;let e=(t.clientX??this.ox+this.vw/2)-this.ox,i=(t.clientY??this.oy+this.vh/2)-this.oy;this.zoomTo(this.gestureZoom*t.scale,e,i,e,i)}pinchMove(t,e,i){let s=(this.ax+this.bx)/2-this.ox,r=(this.ay+this.by)/2-this.oy,o=Math.hypot(this.ax-this.bx,this.ay-this.by);t===this.pointerId?(this.ax=e,this.ay=i):(this.bx=e,this.by=i);let a=Math.hypot(this.ax-this.bx,this.ay-this.by),h=o>1&&a>1?this.zoom*a/o:this.zoom;this.zoomTo(h,s,r,(this.ax+this.bx)/2-this.ox,(this.ay+this.by)/2-this.oy)}endPinch(t){this.stage.hasPointerCapture(t)&&this.stage.releasePointerCapture(t),t===this.pointerId&&(this.pointerId=this.secondId,this.ax=this.bx,this.ay=this.by),this.secondId=null,this.pinching=!1,this.dragging=!0,this.zoomPhoto>=0&&this.settleZoom()}enterZoom(){let t=this.stops[this.current];if(t.photo<0||this.suspended)return!1;let e=this.layouts[t.photo],i=this.manifest.photos[t.photo].width/(window.devicePixelRatio||1)/e.width;return i<=1.001?!1:(this.tween=null,this.camera=t.camera,this.zoomPhoto=t.photo,this.zoomMax=i,this.zoom=1,this.zx=e.left-(this.camera-this.vw/2),this.zy=e.top,this.slackX=this.zx-this.clampAxis(this.zx,e.width,this.vw,0),this.slackY=this.zy-this.clampAxis(this.zy,e.height,this.vh,0),this.updateCaption(),!0)}zoomTo(t,e,i,s,r){if(this.zoomPhoto<0&&(t<=1||!this.enterZoom()))return;let o=Math.max(1,Math.min(this.zoomMax,t)),a=o/this.zoom;this.zx=s-(e-this.zx)*a,this.zy=r-(i-this.zy)*a,this.zoom=o,this.settleZoom()}settleZoom(){let t=this.layouts[this.zoomPhoto];if(this.zx=this.clampAxis(this.zx,t.width*this.zoom,this.vw,this.slackX),this.zy=this.clampAxis(this.zy,t.height*this.zoom,this.vh,this.slackY),this.requestDraw(),this.zoom<=1&&!this.pinching){this.camera=t.left+this.vw/2-this.zx,this.go(this.nearestStop(this.camera));return}clearTimeout(this.zoomTimer),this.zoomTimer=window.setTimeout(()=>this.startZoomSession(),ni)}clampAxis(t,e,i,s){let r=(i-e)/2,o=Math.min(i-e,r),a=Math.max(0,r),h=s*Math.max(0,2-this.zoom);return h>0?a+=h:o+=h,Math.min(a,Math.max(o,t))}clearZoom(){return this.zoomPhoto<0?!1:(this.zoomPhoto=-1,this.zoom=1,this.gestureZoom=1,clearTimeout(this.zoomTimer),this.zoomTimer=0,this.pointerId!==null&&(this.stale=!0,this.pinching=!1,this.secondId=null),this.requestDraw(),!0)}levelDpr(){return this.zoomPhoto>=0&&this.zoom>=this.zoomMax*.999?Math.max(this.dpr,window.devicePixelRatio||1):this.dpr}startZoomSession(){if(this.zoomTimer=0,this.suspended||this.zoomPhoto<0)return;let t=this.layouts[this.zoomPhoto],e=t.width*this.zoom,i=t.height*this.zoom,s=Math.max(0,this.zx),r=Math.min(this.vw,this.zx+e),o=Math.max(0,this.zy),a=Math.min(this.vh,this.zy+i);r<=s||a<=o||this.loader(this.zoomPhoto).start({displayWidth:e,u0:(s-this.zx)/e,u1:(r-this.zx)/e,v0:(o-this.zy)/i,v1:(a-this.zy)/i},this.levelDpr(),()=>{})}rubber(t){let e=this.stops[0].camera,i=this.stops[this.stops.length-1].camera;return ti?i+(t-i)*ge:t}nearestStop(t){let e=0;return this.stops.forEach((i,s)=>{Math.abs(i.camera-t){this.current=e,this.camera=r});else{let o=Math.abs(r-this.camera);o>.5?this.tween={from:this.camera,to:r,start:performance.now(),duration:240+200*Math.min(1,o/this.vw)}:this.camera=r,this.current=e}e!==i?this.activate(i):(s&&this.startSession(),this.updateCaption()),this.requestDraw()}jump(t){let e=this.current;this.clearZoom(),this.tween=null,this.crossfade(()=>{this.current=t,this.camera=this.stops[t].camera}),this.activate(e),this.requestDraw()}crossfade(t){let e=this.fade;(e.width!==this.canvas.width||e.height!==this.canvas.height)&&(e.width=this.canvas.width,e.height=this.canvas.height);let i=e.getContext("2d");i&&i.drawImage(this.canvas,0,0),e.style.transition="none",e.style.opacity="1",t(),this.render(performance.now()),requestAnimationFrame(()=>{requestAnimationFrame(()=>{e.style.transition="",e.style.opacity="0"})})}activate(t){let e=this.stops[this.current],i=t>=0?this.stops[t]:null;if(i&&i.photo>=0&&i.photo!==e.photo&&this.loaders[i.photo]?.stop(),this.loaders.forEach((s,r)=>{s&&r!==e.photo&&r!==e.photo+1&&s.stopPrefetch()}),e.photo<0&&(this.indicator.watch(null),this.progress.watch(null)),this.describe(e.photo,t>=0),e.photo>=0){let s=this.manifest.photos[e.photo];this.caption.set(s,e.photo,this.manifest.photos.length,this.manifest.show_exif),(t>=0||location.hash!=="")&&location.hash!=="#"+(e.photo+1)&&history.replaceState(history.state,"","#"+(e.photo+1))}this.wantKeys(),e.photo>=0&&this.startSession(),this.syncNextStrip(),this.updateCaption()}describe(t,e){let i=this.manifest.photos.length,s;if(t<0){let r=this.nextLink.querySelector(".next-title")?.textContent??"";s="End of album."+(r?" Next album: "+r+".":"")}else{let r=this.manifest.photos[t],o=r.alt||r.title||"";s="Photo "+(t+1)+" of "+i+(o?": "+o:"")}this.canvas.setAttribute("aria-label",s),clearTimeout(this.announceTimer),e&&(this.announceTimer=window.setTimeout(()=>{this.announcer.textContent=s},500))}suspend(t){if(!this.suspended){this.suspended=!0,this.tween=null;for(let e of this.loaders)e?.stop();this.nextStrip?.loader.stop(),this.env.scheduler.cancelAll(),this.env.cache.trim(t?0:this.env.cache.budget/4),t&&(this.nextStrip?.detach(),this.canvas.width=1,this.canvas.height=1,this.fade.width=1,this.fade.height=1)}}resume(){this.suspended&&(this.suspended=!1,this.clearZoom(),this.canvas.width=0,this.measure(),this.camera=this.stops[this.current].camera,this.syncNextStrip(),this.startSession(),this.requestDraw())}wantKeys(){let t=this.manifest.photos,e=this.stops[this.current],i=e.photo<0?t.length-1:e.photo,s=r=>{let o=[];for(let a of r){let h=i+a;h>=0&&hr>=0&&r=0?i(this.zoomPhoto)&&this.loader(this.zoomPhoto).stalled&&this.startZoomSession():s.photo>=0&&i(s.photo)&&this.loader(s.photo).stalled?this.startSession():s.photo>=0&&i(s.photo+1)&&!this.loader(s.photo).status.active&&this.prefetchAround(this.current),this.requestDraw()}startSession(){let t=this.stops[this.current];if(t.photo<0)return;let e=this.current,i=this.loader(t.photo);i.start(this.viewAt(t),this.dpr,()=>{this.current===e&&this.prefetchAround(e)}),this.indicator.watch(i),this.progress.watch(i)}prefetchAround(t){let e=this.stops[t],i=this.stops[t+1];if(!(!i||i.photo<0)){if(i.photo===e.photo){let s=this.loader(e.photo);s.prefetchLevel(this.viewAt(i),s.finalLevel);let r=this.stops.find(o=>o.photo===e.photo+1);r&&this.loader(r.photo).prefetchProbe(this.viewAt(r),this.dpr);return}this.loader(i.photo).prefetchProbe(this.viewAt(i),this.dpr)}}viewAt(t){let e=this.layouts[t.photo],i=t.camera-this.vw/2,s=Math.max(i,e.left),r=Math.min(i+this.vw,e.left+e.width),o=Math.max(0,e.top),a=Math.min(this.vh,e.top+e.height);return{displayWidth:e.width,u0:(s-e.left)/e.width,u1:(r-e.left)/e.width,v0:(o-e.top)/e.height,v1:(a-e.top)/e.height}}photoRect(t){let e=this.layouts[t],i=e.left-(this.camera-this.vw/2);return{left:Math.max(0,i),right:Math.min(this.vw,i+e.width),top:Math.max(0,e.top),bottom:Math.min(this.vh,e.top+e.height)}}inCaptionZone(t,e){let i=this.stops[this.current];if(i.photo<0)return!1;let s=this.stage.getBoundingClientRect(),r=t-s.left,o=e-s.top,a=this.layouts[i.photo],h=this.photoRect(i.photo),l=a.top+a.height*(1-si);return r>=h.left&&r<=h.right&&o>=l&&o<=h.bottom}updateCaption(){let t=this.stops[this.current],e=t.photo>=0&&this.zoomPhoto<0&&!this.dragging&&(this.pinned||this.hover);if(e){let i=this.photoRect(t.photo);this.caption.place(i.left,i.right-i.left,this.vh-i.bottom)}this.caption.show(e),document.body.classList.toggle("has-caption",e)}loadNextAlbum(){this.indexRequested||!this.settings.indexUrl||(this.indexRequested=!0,fetch(this.settings.indexUrl,{credentials:"same-origin"}).then(t=>t.ok?t.json():Promise.reject(new Error("index"))).then(t=>this.showNextAlbum(t)).catch(()=>{this.indexRequested=!1}))}showNextAlbum(t){let e=t.albums;if(e.length===0)return;let i=e.findIndex(a=>a.slug===this.manifest.slug),s=e[(i+1)%e.length];if(!s||s.slug===this.manifest.slug)return;this.nextLink.href="/a/"+encodeURIComponent(s.slug)+"/",this.nextSlug=s.slug;let r=this.nextLink.querySelector(".next-eyebrow"),o=this.nextLink.querySelector(".next-title");r&&(r.textContent="Next album"+(s.date?" \xB7 "+s.date:"")),o&&(o.textContent=s.title,bt(o,s.title)),s.cover&&(this.nextStrip=new _(this.nextFrame,s.cover,s.collapsed_focus_y??.5,J(t.build,s.slug,s.cover.hash),{...this.env,keys:gt(t.gate.cover),tiles:t.tiles},()=>{}),this.nextLink.classList.add("has-strip"),this.layoutNextStrip(),this.syncNextStrip())}requestDraw(){this.frame===0&&(this.frame=requestAnimationFrame(t=>{this.frame=0,this.render(t)}))}render(t){let e=!1;if(this.tween){let b=Math.min(1,(t-this.tween.start)/this.tween.duration);this.camera=this.tween.from+(this.tween.to-this.tween.from)*ci(b),b>=1?(this.tween=null,this.updateCaption()):e=!0}let i=this.g,s=this.canvas.width,r=this.canvas.height;i.setTransform(1,0,0,1,0,0),i.globalAlpha=1,i.fillStyle="#111114",i.fillRect(0,0,s,r);let o=this.camera-this.vw/2,a=o+this.vw,h=this.dpr,l=this.stops[this.current].photo,c=Math.max(0,(l<0?this.layouts.length-1:l)-2),g=this.zoomPhoto>=0?-1:Math.min(this.layouts.length-1,(l<0?this.layouts.length-1:l)+2);if(this.zoomPhoto>=0){let b=this.layouts[this.zoomPhoto],m=b.width*this.zoom;this.loader(this.zoomPhoto).draw({g:i,originX:this.zx*h,originY:this.zy*h,width:m*h,height:b.height*this.zoom*h,canvasWidth:s,canvasHeight:r,displayWidth:m,dpr:this.levelDpr(),now:t})&&(e=!0)}for(let b=c;b<=g;b++){let m=this.layouts[b];m.left+m.widtha||this.loader(b).draw({g:i,originX:(m.left-o)*h,originY:m.top*h,width:m.width*h,height:m.height*h,canvasWidth:s,canvasHeight:r,displayWidth:m.width,dpr:h,now:t})&&(e=!0)}this.endCard.style.transform="translate3d("+Math.round(this.endLeft-o)+"px,0,0)",this.caption.element.classList.contains("is-visible")&&this.tween&&this.updateCaption(),e&&this.requestDraw()}};async function ye(n){let t=await fetch(n,{credentials:"same-origin"});if(!t.ok)throw new Error(n+" "+t.status);return await t.json()}function we(n){return{scheduler:new $(n.concurrency,n.workerUrl),cache:new et(Jt())}}function xe(n,t){return n.gate==="off"?null:{build:n.build,workerUrl:n.workerUrl,minEntropy:t,score:it}}async function di(n,t,e){let i=await ye(t.manifestUrl);if(i.photos.length===0)return;let s=new vt(i.gate,i.slug,e?"nav":"land",t.workerUrl),{scheduler:r,cache:o}=we(t);document.documentElement.classList.add("has-viewer");let a=i.gate.min_entropy??t.minEntropy;Me(new Mt(n,i,t,{scheduler:r,cache:o,settings:t,keys:s,tiles:i.tiles},s,xe(t,()=>a)))}async function ui(n,t,e){let i=await ye(t.indexUrl);if(typeof i.gate.min_entropy=="number"&&e(i.gate.min_entropy),i.albums.length===0)return;let{scheduler:s,cache:r}=we(t);Me(new ft(n,i,t,{scheduler:s,cache:r,settings:t,keys:gt(i.gate.cover),tiles:i.tiles}))}function Me(n){document.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"?n.suspend(!1):n.resume()}),window.addEventListener("pagehide",()=>n.suspend(!0)),window.addEventListener("pageshow",t=>{t.persisted&&n.resume()})}function pi(){document.documentElement.classList.remove("has-viewer"),document.querySelector(".load-error")?.removeAttribute("hidden")}function be(){Ct();let n=pe(document.body);if(n.page==="album"){let t=document.getElementById("stage");t&&di(t,n,se(n.slug)).catch(pi)}else if(n.page==="notfound"){let t=document.querySelector(".site-header .wordmark");t&&K(t,!1)}else if(n.page==="index"){let t=document.getElementById("strips");if(t){let e=n.minEntropy,i=xe(n,()=>e);if(i)for(let s of Array.from(t.querySelectorAll("a.strip")))dt(s,()=>s.dataset.slug??"",i);ui(t,n,s=>{e=s}).catch(()=>{document.documentElement.classList.remove("has-strips");let s=document.querySelector(".site-header .wordmark");s&&!s.classList.contains("has-svg")&&K(s,!1)})}}}document.readyState==="loading"?document.addEventListener("DOMContentLoaded",be,{once:!0}):be();})(); diff --git a/internal/site/static/worker.js b/internal/site/static/worker.js index 8afaeb3..dffddef 100644 --- a/internal/site/static/worker.js +++ b/internal/site/static/worker.js @@ -1 +1 @@ -"use strict";(()=>{function v(t){let a=t.seed+"|"+t.level+"|"+t.x+"|"+t.y,o=2166136261;for(let r=0;r>>0;return o}function M(t,a){let o=new Array(t);for(let e=0;e{r=r+1831565813|0;let e=Math.imul(r^r>>>15,1|r);return e=e+Math.imul(e^e>>>7,61|e)^e,((e^e>>>14)>>>0)/4294967296};for(let e=t-1;e>0;e--){let s=Math.floor(n()*(e+1)),i=o[e];o[e]=o[s],o[s]=i}return o}function A(t,a,o,r,n){t.drawImage(a,0,0);let e=n.cell,s=Math.floor(o/e),i=Math.floor(r/e);if(s<2||i<2)return;let c=s*i,f=M(c,v(n));for(let l=0;l>>7|r<<25)^(r>>>18|r<<14)^r>>>3,s=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10;t[o]=t[o-16]+e+t[o-7]+s|0}}function k(t,a,o,r){let n=t[0],e=t[1],s=t[2],i=t[3],c=t[4],f=t[5],l=t[6],b=t[7];for(let u=o;u>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7))+(c&f^~c&l)+U[u]+a[u]|0,h=((n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10))+(n&e^n&s^e&s)|0;b=l,l=f,f=c,c=i+d|0,i=s,s=e,e=n,n=d+h|0}t[0]=n,t[1]=e,t[2]=s,t[3]=i,t[4]=c,t[5]=f,t[6]=l,t[7]=b}var H=new Int32Array(64),j=new Int32Array(8),F=new Int32Array(8);var C=new TextEncoder;function B(t,a,o){let r=C.encode(t),n=new Uint8Array(r.length+a.length+4);n.set(r),n.set(a,r.length);let e=r.length+a.length;return n[e]=o>>>24,n[e+1]=o>>>16&255,n[e+2]=o>>>8&255,n[e+3]=o&255,n}var y=class{constructor(a,o){this.w=new Int32Array(64);this.mid=new Int32Array(8);this.s=new Int32Array(8);this.target=new Int32Array(4);let r=new Uint8Array(64);r.set(B("luphoto-check",a,0)),r[33]=128,r[62]=33*8>>>8,r[63]=33*8&255;let n=this.w;for(let e=0;e<16;e++)n[e]=r[e*4]<<24|r[e*4+1]<<16|r[e*4+2]<<8|r[e*4+3];this.saltTail=r[28]<<24;for(let e=16;e<22;e++){let s=n[e-15],i=n[e-2],c=(s>>>7|s<<25)^(s>>>18|s<<14)^s>>>3,f=(i>>>17|i<<15)^(i>>>19|i<<13)^i>>>10;n[e]=n[e-16]+c+n[e-7]+f|0}this.mid.set(m),k(this.mid,n,0,7);for(let e=0;e<4;e++)this.target[e]=o[e*4]<<24|o[e*4+1]<<16|o[e*4+2]<<8|o[e*4+3]}run(a,o){let r=this.w,n=this.s,e=this.mid,s=this.target[0],i=this.saltTail;for(let c=a;c>>8,r[8]=(c&255)<<24|8388608,S(r,22),n.set(e),k(n,r,7,64),(m[0]+n[0]|0)===s&&(m[1]+n[1]|0)===this.target[1]&&(m[2]+n[2]|0)===this.target[2]&&(m[3]+n[3]|0)===this.target[3])return c;return-1}};function p(t){let a=new Uint8Array(t.length>>>1);for(let o=0;o{let a=t.data;if(a.type==="pow"){let o=new y(p(a.salt),p(a.check));x.postMessage({pow:o.run(0,2**a.bits)});return}if(a.type==="abort"){g.get(a.key)?.abort(),g.delete(a.key);return}E(a)};function T(t,a){if(!w)throw new Error("unsupported-offscreen");let o=new w(t.width,t.height),r=o.getContext("2d");if(!r)throw new Error("unsupported-offscreen");return A(r,t,t.width,t.height,a),t.close(),o.transferToImageBitmap()}async function E(t){if(!O){x.postMessage({key:t.key,ok:!1,bytes:0,ms:0,error:"unsupported-bitmap"});return}if(t.scramble&&!w){x.postMessage({key:t.key,ok:!1,bytes:0,ms:0,error:"unsupported-offscreen"});return}let a=new AbortController;g.set(t.key,a);let o=performance.now();try{let r=await fetch(t.url,{signal:a.signal,credentials:"same-origin"});if(!r.ok)throw new Error("HTTP "+r.status);let n=await r.blob(),e=performance.now()-o,s=await createImageBitmap(n);if(t.scramble&&(s=T(s,t.scramble)),a.signal.aborted)throw s.close(),new Error("aborted");x.postMessage({key:t.key,ok:!0,bitmap:s,bytes:n.size,ms:e},[s])}catch(r){let n=r instanceof Error?r.message:String(r);x.postMessage({key:t.key,ok:!1,bytes:0,ms:0,error:n})}finally{g.delete(t.key)}}})(); +"use strict";(()=>{function M(e){let a=e.seed+"|"+e.level+"|"+e.x+"|"+e.y,o=2166136261;for(let n=0;n>>0;return o}function v(e,a){let o=new Array(e);for(let t=0;t{n=n+1831565813|0;let t=Math.imul(n^n>>>15,1|n);return t=t+Math.imul(t^t>>>7,61|t)^t,((t^t>>>14)>>>0)/4294967296};for(let t=e-1;t>0;t--){let c=Math.floor(r()*(t+1)),l=o[t];o[t]=o[c],o[c]=l}return o}function w(e,a,o,n,r){e.drawImage(a,0,0);let t=r.cell,c=Math.floor(o/t),l=Math.floor(n/t);if(c<2||l<2)return;let s=c*l,i=v(s,M(r));for(let f=0;f>>7|n<<25)^(n>>>18|n<<14)^n>>>3,c=(r>>>17|r<<15)^(r>>>19|r<<13)^r>>>10;e[o]=e[o-16]+t+e[o-7]+c|0}}function k(e,a,o,n){let r=e[0],t=e[1],c=e[2],l=e[3],s=e[4],i=e[5],f=e[6],b=e[7];for(let x=o;x>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7))+(s&i^~s&f)+C[x]+a[x]|0,h=((r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10))+(r&t^r&c^t&c)|0;b=f,f=i,i=s,s=l+m|0,l=c,c=t,t=r,r=m+h|0}e[0]=r,e[1]=t,e[2]=c,e[3]=l,e[4]=s,e[5]=i,e[6]=f,e[7]=b}var E=new Int32Array(64),T=new Int32Array(8),j=new Int32Array(8);var p=4294967296,d=class{constructor(a,o){this.w=new Int32Array(64);this.mid=new Int32Array(8);this.s=new Int32Array(8);let n=this.w;for(let r=0;r<8;r++)n[r]=a.charCodeAt(r*4)<<24|a.charCodeAt(r*4+1)<<16|a.charCodeAt(r*4+2)<<8|a.charCodeAt(r*4+3);n[10]=-2147483648,n[15]=320,this.mid.set(A),k(this.mid,n,0,8),this.shift=32-Math.max(1,Math.min(32,o))}run(a,o,n){let r=this.w,t=this.s,c=this.mid,l=this.shift,s=A[0];r[8]=a|0;for(let i=o;i>>l))return i;return-1}};var u=self,y=new Map,U=typeof createImageBitmap=="function",g=self.OffscreenCanvas;u.onmessage=e=>{let a=e.data;if(a.type==="pow"){let o=new d(a.token,a.bits);for(let n=0;n<2097152;n++){let r=o.run(n,0,p);if(r>=0){u.postMessage({pow:n*p+r});return}}u.postMessage({pow:-1});return}if(a.type==="abort"){y.get(a.key)?.abort(),y.delete(a.key);return}O(a)};function B(e,a){if(!g)throw new Error("unsupported-offscreen");let o=new g(e.width,e.height),n=o.getContext("2d");if(!n)throw new Error("unsupported-offscreen");return w(n,e,e.width,e.height,a),e.close(),o.transferToImageBitmap()}async function O(e){if(!U){u.postMessage({key:e.key,ok:!1,bytes:0,ms:0,error:"unsupported-bitmap"});return}if(e.scramble&&!g){u.postMessage({key:e.key,ok:!1,bytes:0,ms:0,error:"unsupported-offscreen"});return}let a=new AbortController;y.set(e.key,a);let o=performance.now();try{let n=await fetch(e.url,{signal:a.signal,credentials:"same-origin"});if(!n.ok)throw new Error("HTTP "+n.status);let r=await n.blob(),t=performance.now()-o,c=await createImageBitmap(r);if(e.scramble&&(c=B(c,e.scramble)),a.signal.aborted)throw c.close(),new Error("aborted");u.postMessage({key:e.key,ok:!0,bitmap:c,bytes:r.size,ms:t},[c])}catch(n){let r=n instanceof Error?n.message:String(n);u.postMessage({key:e.key,ok:!1,bytes:0,ms:0,error:r})}finally{y.delete(e.key)}}})(); diff --git a/internal/site/templates/head.html b/internal/site/templates/head.html index 06c6282..8255a1b 100644 --- a/internal/site/templates/head.html +++ b/internal/site/templates/head.html @@ -24,7 +24,7 @@ {{- end}} -{{define "body-data"}} data-build="{{.Build}}" data-index="{{.IndexURL}}" data-worker="{{.Assets.Worker.URL}}" data-budget-ms="{{.BudgetMS}}" data-max-dpr="{{.MaxDPR}}" data-concurrency="{{.Concurrency}}" data-block-context-menu="{{.BlockContextMenu}}" data-gate="{{.Gate}}"{{end}} +{{define "body-data"}} data-build="{{.Build}}" data-index="{{.IndexURL}}" data-worker="{{.Assets.Worker.URL}}" data-budget-ms="{{.BudgetMS}}" data-max-dpr="{{.MaxDPR}}" data-concurrency="{{.Concurrency}}" data-block-context-menu="{{.BlockContextMenu}}" data-gate="{{.Gate}}" data-min-entropy="{{.MinEntropy}}"{{end}} {{define "footer"}}