commit 9d910eb14752a1f96397227f524fbf04c7ad133f Author: neil Date: Sun Nov 1 23:32:22 2026 -0800 Tools site: Markdown editor, JSON editor, 24-hour pastebin Single FastAPI container with a registry-driven single-page front end, so new tools are one module plus one registry entry. Runs as one container behind a reverse proxy. Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..35e9e92 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +data/ +.venv/ diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..2c64b42 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,31 @@ +# CLAUDE.md + +See `README.md` for what this is and how it's deployed. This file is how to extend it. + +## Adding a tool + +1. **Front end:** create `app/static/js/tools/.js` exporting `mount(root, ctx)`: + - append the UI to `root`; start with `el('div.tool', {}, toolbar, …)` so it fills the view + (`.toolbar`, `.btn`, `.segmented`, `.pane`, `.statusbar` are the shared building blocks in + `css/style.css`); + - `ctx.rest` is the path after the tool's own (`/paste/abc` → `abc`), `ctx.query` the search + params, `ctx.navigate(path)` client-side navigation, `ctx.setTitle(text)` the top-bar suffix; + - return a cleanup function if you add global listeners or timers. +2. **Register it** in `app/static/js/registry.js` (id, name, path, category, icon, description, + `load`). The sidebar, home grid, `/`-search and router all come from that list. Add a new + category to `CATEGORY_ORDER` if it should not sort last. +3. **Server side, only if needed:** add `app/tools/.py` exposing `router` (a FastAPI + `APIRouter`) with routes under `/api//…`, and optional `async startup()`/`shutdown()`. + `main.py` mounts every module in `tools/` automatically. Persistent files go under + `$DATA_DIR` (`/data`, bind-mounted from `/opt/tools/data`). Keep it light: this runs on the + shared server (container capped at 192 MB / 0.5 CPU). +4. Prefer running in the browser. Vendor any library into `static/vendor/` (pinned version in + the filename comment or README); the CSP allows scripts from `'self'` only, no CDNs. + +## Conventions + +- Persist per-browser state with `store` from `ui.js` (namespaced, never throws), and flush + debounced saves on leave (`onLeave`, `debounce(...).flush`). +- Never render user content as HTML without DOMPurify (the Markdown preview) or `textContent`. +- Run `node --test tests/` and check the page in a browser before deploying; `deploy.sh` refuses + to deploy if the tests fail. diff --git a/README.md b/README.md new file mode 100644 index 0000000..37b234c --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +# tools + +Small browser tools at **https://tools.neilbantoc.dev**: + +| Tool | Path | Runs | +| --- | --- | --- | +| Markdown: edit, side by side, or full-page preview | `/markdown` | in the browser | +| JSON editor: validate, format, compact, sort keys, editable live tree | `/json` | in the browser | +| Pastebin with 24-hour expiry | `/paste`, `/paste/`, `/raw/` | server (SQLite) | + +Drafts (Markdown, JSON, an unsent paste) are saved in the browser's localStorage. +`/markdown?paste=` and `/json?paste=` open a paste in those tools without +overwriting the local draft; Markdown's **Share** button makes such a link. + +## Layout + +``` +app/ + main.py FastAPI: mounts every tools/*.py router, serves the single-page app + tools/paste.py pastebin API (+ startup/shutdown hooks for its expiry sweep) + static/ + index.html app shell + js/registry.js the tool list (sidebar, home page and routing all read it) + js/app.js router, nav, theme + js/ui.js shared helpers (el, toast, copy/download, store, segmented, …) + js/tools/*.js one module per tool + vendor/ marked 18.1.2, DOMPurify 3.4.17 (vendored, no CDN) +compose.yml production container (host network, 127.0.0.1:8090) +deploy.sh tests, copies to /opt/tools on the server, rebuilds, waits for healthy +tests/ node --test tests/ (JSON parser/printer) +``` + +No build step: the browser loads the ES modules directly. + +## Run locally + +```sh +docker build -t tools:dev app +docker run --rm --network host -e PORT=18090 -v "$PWD/data:/data" tools:dev +# http://127.0.0.1:18090 +``` + +`data/` must be writable by uid 10001 (`sudo chown 10001 data` or `chmod 777 data` locally). + +## Deploy + +```sh +./deploy.sh # HOST=root@ +HOST=root@ ./deploy.sh +``` + +On the server: `/opt/tools/{compose.yml,app/,data/}`, container `tools`, listening on +`127.0.0.1:8090` only. Put a reverse proxy or tunnel connector +on the same host in front of it. + +## Pastebin limits + +1 MiB per paste, 256 MiB of live pastes in total, 30 new pastes per IP per hour. Expired +pastes stop being served immediately and are deleted every 5 minutes. `/raw/` is served +as `text/plain` with a sandboxing CSP, so a paste can never run as a page on this origin. +Each paste gets a delete token, kept in the creating browser's localStorage. diff --git a/app/Dockerfile b/app/Dockerfile new file mode 100644 index 0000000..7d4d3f8 --- /dev/null +++ b/app/Dockerfile @@ -0,0 +1,12 @@ +FROM python:3.12-slim +WORKDIR /app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY main.py ./ +COPY tools ./tools +COPY static ./static +RUN useradd --system --uid 10001 tools && mkdir -p /data && chown tools /data +USER tools +ENV DATA_DIR=/data PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 +# HOST/PORT come from compose; uvicorn trusts X-Forwarded-* only from loopback (the local proxy/tunnel). +CMD ["sh", "-c", "exec uvicorn main:app --host ${HOST:-127.0.0.1} --port ${PORT:-8090} --proxy-headers --forwarded-allow-ips 127.0.0.1 --no-server-header"] diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..7f0df97 --- /dev/null +++ b/app/main.py @@ -0,0 +1,92 @@ +"""tools.neilbantoc.dev: a small set of browser tools behind one FastAPI app. + +Most tools run entirely in the browser (static/js/tools/*.js). A tool that needs a +server side adds a module under tools/ that exposes `router` (an APIRouter) and, +optionally, `startup()`/`shutdown()` coroutines. Every such module is mounted +automatically; see CLAUDE.md for the full recipe. +""" + +import contextlib +import importlib +import pkgutil +from pathlib import Path + +from fastapi import FastAPI, Request +from fastapi.middleware.gzip import GZipMiddleware +from fastapi.responses import FileResponse, JSONResponse +from fastapi.staticfiles import StaticFiles + +import tools + +STATIC = Path(__file__).parent / "static" + +TOOL_MODULES = [ + importlib.import_module(f"tools.{m.name}") + for m in pkgutil.iter_modules(tools.__path__) + if not m.name.startswith("_") +] + + +@contextlib.asynccontextmanager +async def lifespan(_app: FastAPI): + for mod in TOOL_MODULES: + if hasattr(mod, "startup"): + await mod.startup() + yield + for mod in TOOL_MODULES: + if hasattr(mod, "shutdown"): + await mod.shutdown() + + +app = FastAPI(lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=None) +app.add_middleware(GZipMiddleware, minimum_size=1024) + +for mod in TOOL_MODULES: + app.include_router(mod.router) + + +class Assets(StaticFiles): + """Static files that browsers revalidate on every load (cheap 304s), so a deploy shows up at once.""" + + async def get_response(self, path, scope): + resp = await super().get_response(path, scope) + resp.headers["Cache-Control"] = "no-cache" + return resp + + +app.mount("/assets", Assets(directory=STATIC), name="assets") + +CSP = ( + "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; " + "script-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" +) + + +@app.middleware("http") +async def security_headers(request: Request, call_next): + resp = await call_next(request) + resp.headers.setdefault("Content-Security-Policy", CSP) + resp.headers.setdefault("X-Content-Type-Options", "nosniff") + resp.headers.setdefault("Referrer-Policy", "same-origin") + return resp + + +@app.get("/healthz", include_in_schema=False) +def healthz(): + return {"ok": True} + + +@app.get("/favicon.ico", include_in_schema=False) +def favicon(): + return FileResponse(STATIC / "favicon.svg", media_type="image/svg+xml") + + +@app.api_route("/api/{rest:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"], include_in_schema=False) +def api_not_found(rest: str): + return JSONResponse({"detail": "not found"}, status_code=404) + + +@app.get("/{path:path}", include_in_schema=False) +def spa(path: str): + # Client-side routing: every other path is a page of the single-page app. + return FileResponse(STATIC / "index.html", headers={"Cache-Control": "no-cache"}) diff --git a/app/requirements.txt b/app/requirements.txt new file mode 100644 index 0000000..c9d1db1 --- /dev/null +++ b/app/requirements.txt @@ -0,0 +1,2 @@ +fastapi==0.115.* +uvicorn==0.32.* diff --git a/app/static/css/style.css b/app/static/css/style.css new file mode 100644 index 0000000..3cfc9df --- /dev/null +++ b/app/static/css/style.css @@ -0,0 +1,279 @@ +/* ---------- tokens ---------- */ +:root { + --bg: #f7f7f8; + --surface: #ffffff; + --surface-2: #f0f1f3; + --border: #dfe1e5; + --text: #1c1e21; + --muted: #646a73; + --accent: #3b6ef5; + --accent-text: #ffffff; + --accent-soft: #e6edfe; + --danger: #c93a3a; + --ok: #1f8a4c; + --sel: #dce6ff; + --tok-key: #8a3ab9; + --tok-string: #0b7a3e; + --tok-number: #1b5fd1; + --tok-bool: #b5560b; + --tok-null: #8a8f98; + --code-bg: #f3f4f6; + --shadow: 0 6px 24px rgba(15, 20, 30, 0.12); + --mono: ui-monospace, SFMono-Regular, Menlo, Consolas, 'Liberation Mono', monospace; + --sans: system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; + --radius: 8px; + --topbar: 48px; + --sidebar: 216px; + color-scheme: light; +} +@media (prefers-color-scheme: dark) { + :root:not([data-theme='light']) { + --bg: #131417; + --surface: #1b1d21; + --surface-2: #24272c; + --border: #33373e; + --text: #e6e7e9; + --muted: #9aa0a9; + --accent: #6b93ff; + --accent-text: #0d1220; + --accent-soft: #232f4d; + --danger: #ff7b7b; + --ok: #5fd08f; + --sel: #2a3a63; + --tok-key: #d39cf5; + --tok-string: #8bd49c; + --tok-number: #82aaff; + --tok-bool: #f4a85e; + --tok-null: #8a8f98; + --code-bg: #24272c; + --shadow: 0 6px 24px rgba(0, 0, 0, 0.45); + color-scheme: dark; + } +} +:root[data-theme='dark'] { + --bg: #131417; + --surface: #1b1d21; + --surface-2: #24272c; + --border: #33373e; + --text: #e6e7e9; + --muted: #9aa0a9; + --accent: #6b93ff; + --accent-text: #0d1220; + --accent-soft: #232f4d; + --danger: #ff7b7b; + --ok: #5fd08f; + --sel: #2a3a63; + --tok-key: #d39cf5; + --tok-string: #8bd49c; + --tok-number: #82aaff; + --tok-bool: #f4a85e; + --tok-null: #8a8f98; + --code-bg: #24272c; + --shadow: 0 6px 24px rgba(0, 0, 0, 0.45); + color-scheme: dark; +} + +/* ---------- base ---------- */ +*, *::before, *::after { box-sizing: border-box; } +html, body { height: 100%; margin: 0; } +body { background: var(--bg); color: var(--text); font: 14px/1.5 var(--sans); -webkit-font-smoothing: antialiased; } +a { color: var(--accent); } +button, input, select, textarea { font: inherit; color: inherit; } +[hidden] { display: none !important; } +.mono { font-family: var(--mono); font-size: 13px; } +.muted { color: var(--muted); } +.small { font-size: 12px; } +.strong { font-weight: 600; } +.nowrap { white-space: nowrap; } +.spacer { flex: 1; } +.error-text { color: var(--danger); } +:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; } + +/* ---------- shell ---------- */ +.shell { + display: grid; + grid-template-columns: var(--sidebar) minmax(0, 1fr); + grid-template-rows: var(--topbar) minmax(0, 1fr); + grid-template-areas: 'top top' 'side main'; + height: 100vh; + height: 100dvh; +} +.topbar { + grid-area: top; + display: flex; + align-items: center; + gap: 10px; + padding: 0 12px; + background: var(--surface); + border-bottom: 1px solid var(--border); +} +.brand { display: flex; align-items: center; gap: 8px; color: var(--text); text-decoration: none; font-weight: 650; font-size: 15px; } +.brand-mark { display: grid; place-items: center; width: 26px; height: 26px; border-radius: 7px; background: var(--accent); color: var(--accent-text); font-size: 14px; } +.topbar-title { color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; min-width: 0; } +.topbar-title:not(:empty)::before { content: '/'; margin-right: 10px; opacity: 0.5; } +.icon-btn { display: inline-grid; place-items: center; width: 34px; height: 34px; border: 1px solid transparent; border-radius: var(--radius); background: transparent; cursor: pointer; font-size: 16px; } +.icon-btn:hover { background: var(--surface-2); } +.menu-btn { display: none; } + +.sidebar { grid-area: side; overflow-y: auto; padding: 12px 10px; background: var(--surface); border-right: 1px solid var(--border); } +.nav-filter { width: 100%; padding: 7px 10px; margin-bottom: 10px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--bg); } +.nav-group { margin-top: 14px; } +.nav-heading { padding: 0 8px 4px; font-size: 11px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--muted); } +.nav-item { display: flex; align-items: center; gap: 10px; padding: 6px 8px; border-radius: 6px; color: var(--text); text-decoration: none; } +.nav-item:hover { background: var(--surface-2); } +.nav-item.active { background: var(--accent-soft); color: var(--accent); font-weight: 600; } +.nav-icon { display: inline-grid; place-items: center; min-width: 26px; height: 22px; border-radius: 5px; background: var(--surface-2); font: 600 11px var(--mono); color: var(--muted); } +.nav-item.active .nav-icon { background: var(--accent); color: var(--accent-text); } +.scrim { display: none; } + +.view { grid-area: main; min-width: 0; min-height: 0; overflow: auto; } +.loading, .empty { padding: 48px 24px; text-align: center; color: var(--muted); } +.empty .btn { margin-top: 8px; } + +/* ---------- home ---------- */ +.home { max-width: 960px; margin: 0 auto; padding: 32px 24px 48px; } +.home h1 { margin: 0 0 4px; font-size: 26px; } +.home-filter { width: 100%; max-width: 380px; margin: 18px 0 20px; padding: 9px 12px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); } +.card-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; } +.tool-card { display: flex; gap: 14px; padding: 16px; border: 1px solid var(--border); border-radius: 10px; background: var(--surface); color: var(--text); text-decoration: none; transition: border-color 0.12s, transform 0.12s; } +.tool-card:hover { border-color: var(--accent); transform: translateY(-1px); } +.tool-card-icon { flex: none; display: grid; place-items: center; width: 42px; height: 42px; border-radius: 9px; background: var(--accent-soft); color: var(--accent); font: 700 14px var(--mono); } +.tool-card-name { font-weight: 600; margin-bottom: 2px; } +.tool-card-desc { color: var(--muted); font-size: 13px; } + +/* ---------- shared tool chrome ---------- */ +.tool { display: flex; flex-direction: column; height: 100%; min-height: 0; } +.toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 8px 12px; background: var(--surface); border-bottom: 1px solid var(--border); } +.divider { width: 1px; height: 22px; margin: 0 4px; background: var(--border); } +.btn { + display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 11px; + border: 1px solid var(--border); border-radius: 6px; background: var(--surface); color: var(--text); + cursor: pointer; text-decoration: none; font-size: 13px; white-space: nowrap; +} +.btn:hover { background: var(--surface-2); } +.btn:disabled { opacity: 0.6; cursor: default; } +.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-text); font-weight: 600; } +.btn.primary:hover { filter: brightness(1.07); } +.btn.danger { color: var(--danger); } +.btn.small { height: 26px; padding: 0 8px; font-size: 12px; } +.select { height: 30px; padding: 0 6px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); font-size: 13px; } +.segmented { display: inline-flex; padding: 2px; border-radius: 7px; background: var(--surface-2); } +.segmented button { height: 26px; padding: 0 12px; border: 0; border-radius: 5px; background: transparent; color: var(--muted); cursor: pointer; font-size: 13px; } +.segmented button[aria-checked='true'] { background: var(--surface); color: var(--text); font-weight: 600; box-shadow: 0 1px 2px rgba(0, 0, 0, 0.12); } +.pane { min-width: 0; min-height: 0; overflow: auto; background: var(--surface); } +.statusbar { display: flex; align-items: center; gap: 4px; padding: 5px 12px; border-top: 1px solid var(--border); background: var(--surface); font-size: 12px; min-height: 28px; } +.statusbar.ok { color: var(--ok); } +.statusbar.error { color: var(--danger); } +.linklike { padding: 0; border: 0; background: none; color: inherit; font-weight: 600; text-decoration: underline; cursor: pointer; } +textarea { tab-size: 4; } + +.toasts { position: fixed; right: 16px; bottom: 16px; z-index: 50; display: flex; flex-direction: column; gap: 8px; align-items: flex-end; pointer-events: none; } +.toast { max-width: min(420px, calc(100vw - 32px)); padding: 9px 14px; border-radius: var(--radius); background: var(--text); color: var(--bg); box-shadow: var(--shadow); font-size: 13px; animation: toast-in 0.15s ease-out; transition: opacity 0.3s, transform 0.3s; } +.toast.error { background: var(--danger); color: #fff; } +.toast.out { opacity: 0; transform: translateY(6px); } +@keyframes toast-in { from { opacity: 0; transform: translateY(6px); } } + +/* ---------- split workspaces (markdown + json) ---------- */ +.md-workspace, .json-workspace { flex: 1; min-height: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: var(--border); } +.md-workspace[data-mode='edit'], .md-workspace[data-mode='preview'], +.json-workspace[data-mode='text'], .json-workspace[data-mode='tree'] { grid-template-columns: 1fr; } +.md-workspace[data-mode='edit'] .md-preview-pane, +.md-workspace[data-mode='preview'] .md-edit-pane, +.json-workspace[data-mode='text'] .json-tree-pane, +.json-workspace[data-mode='tree'] .json-text-pane { display: none; } + +/* markdown */ +.md-edit-pane { display: flex; overflow: hidden; } +.md-input { flex: 1; width: 100%; padding: 16px 18px; border: 0; outline: none; resize: none; background: var(--surface); line-height: 1.6; } +.md-workspace[data-mode='edit'] .md-input { max-width: 900px; margin: 0 auto; } +.md-preview { padding: 16px 24px 48px; } +.md-workspace[data-mode='preview'] .md-preview { max-width: 820px; margin: 0 auto; padding: 32px 32px 80px; } + +.prose { font-size: 15px; line-height: 1.65; overflow-wrap: break-word; } +.prose > :first-child { margin-top: 0; } +.prose h1, .prose h2, .prose h3, .prose h4 { margin: 1.4em 0 0.5em; line-height: 1.25; } +.prose h1 { font-size: 1.9em; padding-bottom: 0.25em; border-bottom: 1px solid var(--border); } +.prose h2 { font-size: 1.45em; padding-bottom: 0.2em; border-bottom: 1px solid var(--border); } +.prose h3 { font-size: 1.2em; } +.prose p, .prose ul, .prose ol, .prose blockquote, .prose pre, .prose table { margin: 0 0 1em; } +.prose ul, .prose ol { padding-left: 1.6em; } +.prose li + li { margin-top: 0.25em; } +.prose li > input[type='checkbox'] { margin: 0 0.4em 0 -1.3em; vertical-align: middle; } +.prose li:has(> input[type='checkbox']) { list-style: none; } +.prose code { padding: 0.15em 0.35em; border-radius: 4px; background: var(--code-bg); font: 0.88em var(--mono); } +.prose pre { padding: 12px 14px; border-radius: var(--radius); background: var(--code-bg); overflow: auto; } +.prose pre code { padding: 0; background: none; font-size: 13px; } +.prose blockquote { padding: 0 1em; border-left: 3px solid var(--border); color: var(--muted); } +.prose table { border-collapse: collapse; display: block; overflow-x: auto; } +.prose th, .prose td { padding: 6px 12px; border: 1px solid var(--border); } +.prose th { background: var(--surface-2); } +.prose img { max-width: 100%; } +.prose hr { border: 0; border-top: 1px solid var(--border); margin: 2em 0; } + +/* json: text pane */ +.json-text-pane { overflow: hidden; display: flex; } +.editor-wrap { flex: 1; display: flex; min-width: 0; } +.gutter { position: relative; flex: none; min-width: 44px; padding: 10px 8px 60px 6px; overflow: hidden; background: var(--surface-2); color: var(--muted); text-align: right; line-height: 20px; user-select: none; } +.gutter-nums { white-space: pre; } +.gutter-error { position: absolute; left: 0; right: 0; height: 20px; margin-top: 10px; background: color-mix(in srgb, var(--danger) 25%, transparent); border-left: 3px solid var(--danger); } +.json-input { flex: 1; min-width: 0; padding: 10px 12px; border: 0; outline: none; resize: none; background: var(--surface); line-height: 20px; white-space: pre; overflow: auto; } + +/* json: tree pane */ +.json-tree-pane { display: flex; flex-direction: column; overflow: hidden; } +.tree-bar { display: flex; align-items: center; gap: 6px; padding: 6px 10px; border-bottom: 1px solid var(--border); } +.path-chip { max-width: 55%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; padding: 2px 8px; border: 1px solid var(--border); border-radius: 5px; background: var(--surface-2); cursor: pointer; font-size: 12px; } +.json-tree { flex: 1; overflow: auto; padding: 6px 0 40px; line-height: 22px; } +.json-tree.stale { opacity: 0.45; } +.tree-row { position: relative; display: flex; align-items: center; padding-left: calc(var(--depth) * 18px + 6px); padding-right: 64px; white-space: nowrap; cursor: default; } +.tree-row:hover { background: var(--surface-2); } +.tree-row.selected { background: var(--sel); } +.tree-row.closing { cursor: default; } +.tree-row.closing:hover { background: none; } +.twisty, .twisty-space { flex: none; width: 18px; } +.twisty { height: 18px; padding: 0; border: 0; background: none; color: var(--muted); cursor: pointer; font-size: 11px; } +.t-key { color: var(--tok-key); } +.t-index { color: var(--muted); } +.t-punct, .t-count { color: var(--muted); white-space: pre; } +.t-count { font-style: italic; font-size: 12px; } +.t-val { overflow: hidden; text-overflow: ellipsis; } +.t-string { color: var(--tok-string); } +.t-number { color: var(--tok-number); } +.t-boolean { color: var(--tok-bool); } +.t-null { color: var(--tok-null); } +.t-key, .t-val { cursor: text; border-radius: 3px; } +.t-key:hover, .t-val:hover { outline: 1px dashed var(--border); } +.row-actions { position: absolute; right: 8px; display: none; gap: 2px; } +.tree-row:hover > .row-actions, .tree-row.selected > .row-actions { display: flex; } +.mini { width: 22px; height: 20px; padding: 0; border: 1px solid var(--border); border-radius: 4px; background: var(--surface); color: var(--muted); cursor: pointer; line-height: 1; } +.mini:hover { color: var(--text); } +.inline-edit { height: 22px; padding: 0 4px; border: 1px solid var(--accent); border-radius: 3px; background: var(--surface); outline: none; } +.more { margin: 4px 0 4px calc(var(--depth) * 18px + 24px); } + +/* ---------- paste ---------- */ +.paste-body { flex: 1; min-height: 0; overflow: auto; padding: 16px; display: flex; flex-direction: column; gap: 8px; } +.paste-input { flex: 1 0 280px; width: 100%; padding: 12px 14px; border: 1px solid var(--border); border-radius: var(--radius); background: var(--surface); resize: vertical; line-height: 1.5; outline: none; } +.paste-input:focus { border-color: var(--accent); } +.section-title { margin: 16px 0 6px; font-size: 13px; text-transform: uppercase; letter-spacing: 0.05em; color: var(--muted); } +.paste-item { display: flex; align-items: center; gap: 12px; padding: 6px 10px; border: 1px solid var(--border); border-radius: 6px; background: var(--surface); margin-bottom: 6px; } +.paste-preview { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.paste-view { flex: 1; min-height: 0; display: flex; overflow: auto; background: var(--surface); line-height: 20px; } +.paste-lines { flex: none; padding: 12px 10px 40px; background: var(--surface-2); color: var(--muted); text-align: right; white-space: pre; user-select: none; position: sticky; left: 0; } +.paste-text { flex: 1; margin: 0; padding: 12px 14px 40px; font: inherit; white-space: pre; } +.paste-view.wrap .paste-text { white-space: pre-wrap; overflow-wrap: anywhere; } +.paste-view.wrap .paste-lines { display: none; } + +/* ---------- narrow screens ---------- */ +@media (max-width: 800px) { + .shell { grid-template-columns: minmax(0, 1fr); grid-template-areas: 'top' 'main'; } + .menu-btn { display: inline-block; } + .sidebar { position: fixed; z-index: 30; top: var(--topbar); bottom: 0; left: 0; width: min(280px, 85vw); transform: translateX(-100%); transition: transform 0.18s ease-out; box-shadow: var(--shadow); } + .drawer-open .sidebar { transform: none; } + .drawer-open .scrim { display: block; position: fixed; inset: var(--topbar) 0 0 0; z-index: 20; background: rgba(0, 0, 0, 0.35); } + /* one row that scrolls sideways, so the editor keeps the screen */ + .toolbar { padding: 8px; flex-wrap: nowrap; overflow-x: auto; scrollbar-width: none; } + .toolbar > * { flex: none; } + .toolbar > .spacer { flex: 1 0 8px; } + .home { padding: 20px 16px 40px; } + .md-workspace[data-mode='split'], .json-workspace[data-mode='split'] { grid-template-columns: 1fr; grid-template-rows: 1fr 1fr; } + .md-workspace[data-mode='preview'] .md-preview { padding: 20px 16px 60px; } +} diff --git a/app/static/favicon.svg b/app/static/favicon.svg new file mode 100644 index 0000000..6ffe93a --- /dev/null +++ b/app/static/favicon.svg @@ -0,0 +1 @@ + diff --git a/app/static/index.html b/app/static/index.html new file mode 100644 index 0000000..fe649bd --- /dev/null +++ b/app/static/index.html @@ -0,0 +1,30 @@ + + + + + + + Tools + + + + + +
+
+ + ⌘ tools + + + +
+ +
+
+
+
+ + diff --git a/app/static/js/app.js b/app/static/js/app.js new file mode 100644 index 0000000..0834afd --- /dev/null +++ b/app/static/js/app.js @@ -0,0 +1,210 @@ +// App shell: navigation, routing, theme. Tools themselves live in js/tools/*.js. +// +// A tool module exports mount(el, ctx) and may return a cleanup function. +// ctx = { +// rest, // path after the tool's own path, e.g. "abc123" for /paste/abc123 +// query, // URLSearchParams of the current URL +// navigate, // navigate('/paste/abc') — client-side navigation +// setTitle, // setTitle('abc123') — extra text in the top bar and tab title +// } +import { TOOLS, CATEGORY_ORDER } from './registry.js'; +import { el, store } from './ui.js'; + +const view = document.getElementById('view'); +const navList = document.getElementById('nav-list'); +const navFilter = document.getElementById('nav-filter'); +const titleEl = document.getElementById('topbar-title'); +let cleanup = null; +let routeSeq = 0; + +// ---------- theme ---------- + +const THEMES = ['auto', 'light', 'dark']; +const svg = (d) => ``; +const THEME_ICON = { + auto: svg(''), + light: svg(''), + dark: svg(''), +}; +const themeBtn = document.getElementById('theme-btn'); +function applyTheme(t) { + if (t === 'auto') delete document.documentElement.dataset.theme; + else document.documentElement.dataset.theme = t; + themeBtn.innerHTML = THEME_ICON[t]; + themeBtn.title = `Theme: ${t}`; +} +let theme = store.get('theme', 'auto'); +applyTheme(theme); +themeBtn.addEventListener('click', () => { + theme = THEMES[(THEMES.indexOf(theme) + 1) % THEMES.length]; + store.set('theme', theme); + applyTheme(theme); +}); + +// ---------- navigation ---------- + +function grouped(tools) { + const groups = new Map(); + for (const t of tools) { + if (!groups.has(t.category)) groups.set(t.category, []); + groups.get(t.category).push(t); + } + const rank = (c) => (CATEGORY_ORDER.includes(c) ? CATEGORY_ORDER.indexOf(c) : 999); + return [...groups].sort(([a], [b]) => rank(a) - rank(b) || a.localeCompare(b)); +} + +function matches(t, q) { + q = q.trim().toLowerCase(); + return !q || `${t.name} ${t.description} ${t.category}`.toLowerCase().includes(q); +} + +function renderNav() { + const q = navFilter.value; + navList.replaceChildren( + el('a.nav-item.nav-home', { href: '/', dataset: { path: '/' } }, el('span.nav-icon', {}, '⌂'), 'All tools'), + ...grouped(TOOLS.filter((t) => matches(t, q))).map(([cat, tools]) => + el('div.nav-group', {}, + el('div.nav-heading', {}, cat), + tools.map((t) => el('a.nav-item', { href: t.path, dataset: { path: t.path } }, el('span.nav-icon', {}, t.icon), t.name)), + ), + ), + ); + markActive(); +} + +function markActive() { + const tool = findTool(location.pathname); + for (const a of navList.querySelectorAll('.nav-item')) { + const on = tool ? a.dataset.path === tool.path : a.dataset.path === '/'; + a.classList.toggle('active', on); + if (on) a.setAttribute('aria-current', 'page'); + else a.removeAttribute('aria-current'); + } +} + +navFilter.addEventListener('input', renderNav); +navFilter.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + const first = TOOLS.find((t) => matches(t, navFilter.value)); + if (first) { + navFilter.value = ''; + renderNav(); + navigate(first.path); + } + } else if (e.key === 'Escape') { + navFilter.value = ''; + renderNav(); + navFilter.blur(); + } +}); +document.addEventListener('keydown', (e) => { + const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement?.tagName) || document.activeElement?.isContentEditable; + if (e.key === '/' && !typing) { + e.preventDefault(); + setDrawer(true); + navFilter.focus(); + } +}); + +// Mobile drawer +const menuBtn = document.getElementById('menu-btn'); +function setDrawer(open) { + document.body.classList.toggle('drawer-open', open); + menuBtn.setAttribute('aria-expanded', String(open)); +} +menuBtn.addEventListener('click', () => setDrawer(!document.body.classList.contains('drawer-open'))); +document.getElementById('scrim').addEventListener('click', () => setDrawer(false)); + +// ---------- routing ---------- + +function findTool(pathname) { + return TOOLS.find((t) => pathname === t.path || pathname.startsWith(`${t.path}/`)); +} + +export function navigate(path, { replace = false } = {}) { + if (path === location.pathname + location.search) return; + history[replace ? 'replaceState' : 'pushState']({}, '', path); + route(); +} + +document.addEventListener('click', (e) => { + const a = e.target.closest('a[href]'); + if (!a || a.target || a.hasAttribute('download') || e.defaultPrevented) return; + if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; + const url = new URL(a.href, location.href); + if (url.origin !== location.origin || url.pathname.startsWith('/raw/') || url.pathname.startsWith('/api/')) return; + e.preventDefault(); + setDrawer(false); + navigate(url.pathname + url.search); +}); +window.addEventListener('popstate', route); + +function setTitle(tool, extra) { + titleEl.textContent = tool ? [tool.name, extra].filter(Boolean).join(' · ') : ''; + document.title = tool ? `${[extra, tool.name].filter(Boolean).join(' · ')} — tools` : 'tools'; +} + +async function route() { + const seq = ++routeSeq; + if (cleanup) { + try { cleanup(); } catch (err) { console.error(err); } + cleanup = null; + } + markActive(); + const tool = findTool(location.pathname); + document.body.dataset.tool = tool ? tool.id : 'home'; + if (!tool) { + if (location.pathname !== '/') history.replaceState({}, '', '/'); + setTitle(null); + renderHome(); + return; + } + setTitle(tool); + view.replaceChildren(el('div.loading', {}, 'Loading…')); + try { + const mod = await tool.load(); + if (seq !== routeSeq) return; // navigated away while loading + view.replaceChildren(); + const ctx = { + rest: location.pathname.slice(tool.path.length).replace(/^\//, ''), + query: new URLSearchParams(location.search), + navigate, + setTitle: (extra) => setTitle(tool, extra), + }; + cleanup = (await mod.mount(view, ctx)) || null; + } catch (err) { + console.error(err); + if (seq === routeSeq) view.replaceChildren(el('div.empty', {}, `Couldn't load ${tool.name}: ${err.message}`)); + } +} + +function renderHome() { + const filter = el('input.home-filter', { type: 'search', placeholder: 'Find a tool…', 'aria-label': 'Find a tool' }); + const grid = el('div.card-grid'); + const draw = () => + grid.replaceChildren( + ...TOOLS.filter((t) => matches(t, filter.value)).map((t) => + el('a.tool-card', { href: t.path }, + el('div.tool-card-icon', {}, t.icon), + el('div', {}, el('div.tool-card-name', {}, t.name), el('div.tool-card-desc', {}, t.description)), + ), + ), + ); + filter.addEventListener('input', draw); + filter.addEventListener('keydown', (e) => { + const first = e.key === 'Enter' && grid.querySelector('a'); + if (first) navigate(new URL(first.href).pathname); + }); + draw(); + view.replaceChildren( + el('div.home', {}, + el('h1', {}, 'Tools'), + el('p.muted', {}, 'Small utilities that run in your browser. Only pastes are stored on the server, and only for 24 hours.'), + filter, + grid, + ), + ); +} + +renderNav(); +route(); diff --git a/app/static/js/registry.js b/app/static/js/registry.js new file mode 100644 index 0000000..125380c --- /dev/null +++ b/app/static/js/registry.js @@ -0,0 +1,37 @@ +// The list of tools. The sidebar, the home page and the router are all built from it. +// +// To add a tool: create js/tools/.js exporting mount(el, ctx) (see app.js for ctx), +// then add an entry here. A tool owns every path under its `path`, so /paste/abc123 +// goes to the paste tool with ctx.rest = "abc123". +export const TOOLS = [ + { + id: 'markdown', + name: 'Markdown', + path: '/markdown', + category: 'Text', + icon: 'M↓', + description: 'Write Markdown with a live preview: side by side, editor only or full-page preview.', + load: () => import('./tools/markdown.js'), + }, + { + id: 'json', + name: 'JSON editor', + path: '/json', + category: 'Data', + icon: '{ }', + description: 'Validate, prettify and compact JSON, with a live tree view you can edit.', + load: () => import('./tools/json.js'), + }, + { + id: 'paste', + name: 'Pastebin', + path: '/paste', + category: 'Sharing', + icon: '⎘', + description: 'Share text with a short link. Pastes are deleted after 24 hours.', + load: () => import('./tools/paste.js'), + }, +]; + +// Sidebar groups appear in this order; unknown categories go last, alphabetically. +export const CATEGORY_ORDER = ['Text', 'Data', 'Sharing']; diff --git a/app/static/js/tools/json-core.js b/app/static/js/tools/json-core.js new file mode 100644 index 0000000..dde2b76 --- /dev/null +++ b/app/static/js/tools/json-core.js @@ -0,0 +1,234 @@ +// JSON parser and printer that work on source tokens rather than JS values, so +// formatting never changes the data: numbers keep their exact digits (no precision +// loss on big integers), strings keep their original escapes, duplicate keys survive. +// +// Node shapes (start/end are offsets into the source text): +// {type:'object', entries:[{key, keyRaw, keyStart, keyEnd, value}], start, end} +// {type:'array', items:[node], start, end} +// {type:'string', value, raw, start, end} +// {type:'number', raw, start, end} +// {type:'boolean', value, start, end} / {type:'null', start, end} + +export class JsonSyntaxError extends Error { + constructor(message, pos, text) { + const { line, col } = lineCol(text, pos); + super(message); + this.pos = pos; + this.line = line; + this.col = col; + } +} + +export function lineCol(text, pos) { + let line = 1; + let last = -1; + for (let i = text.indexOf('\n'); i !== -1 && i < pos; i = text.indexOf('\n', i + 1)) { + line++; + last = i; + } + return { line, col: pos - last }; +} + +const STRING_RE = /"(?:[^"\\\u0000-\u001f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"/y; +const NUMBER_RE = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y; + +export function parse(text) { + let i = text.charCodeAt(0) === 0xfeff ? 1 : 0; + + const fail = (msg, at = i) => { + throw new JsonSyntaxError(msg, at, text); + }; + const describe = (at) => { + if (at >= text.length) return 'end of input'; + const ch = text[at]; + return ch === '\n' ? 'line break' : `'${ch}'`; + }; + + function ws() { + for (;;) { + const c = text.charCodeAt(i); + if (c === 32 || c === 10 || c === 13 || c === 9) i++; + else if (c === 47 && (text[i + 1] === '/' || text[i + 1] === '*')) fail("Comments aren't allowed in JSON"); + else return; + } + } + + function string() { + STRING_RE.lastIndex = i; + const m = STRING_RE.exec(text); + if (!m) { + // Find the exact problem for a useful message. + for (let j = i + 1; j < text.length; j++) { + const c = text.charCodeAt(j); + if (c === 34) break; + if (c === 10) fail('Unterminated string (strings cannot span lines; use \\n)', j); + if (c < 32) fail('Control character in string; escape it', j); + if (c === 92) { + const e = text[j + 1]; + if (e === 'u') { + if (!/^[0-9a-fA-F]{4}$/.test(text.slice(j + 2, j + 6))) fail('Invalid \\u escape: needs four hex digits', j); + j += 5; + } else if ('"\\/bfnrt'.includes(e) && e !== undefined) j++; + else fail(`Invalid escape '\\${e ?? ''}'`, j); + } + } + fail('Unterminated string'); + } + const start = i; + i += m[0].length; + return { type: 'string', raw: m[0], value: JSON.parse(m[0]), start, end: i }; + } + + function value(depth) { + if (depth > 2000) fail('Nested too deeply (more than 2000 levels)'); + ws(); + const start = i; + const c = text[i]; + if (c === '{') { + i++; + const entries = []; + ws(); + if (text[i] === '}') return { type: 'object', entries, start, end: ++i }; + for (;;) { + ws(); + if (text[i] !== '"') { + if (text[i] === '}' && entries.length) fail('Trailing comma before }', i); + if (text[i] === "'") fail('Strings must use double quotes'); + fail(i >= text.length ? 'Unexpected end of input: object is not closed' : `Expected a "quoted" key, found ${describe(i)}`); + } + const k = string(); + ws(); + if (text[i] !== ':') fail(`Expected ':' after key, found ${describe(i)}`); + i++; + const v = value(depth + 1); + entries.push({ key: k.value, keyRaw: k.raw, keyStart: k.start, keyEnd: k.end, value: v }); + ws(); + if (text[i] === ',') { i++; continue; } + if (text[i] === '}') return { type: 'object', entries, start, end: ++i }; + fail(i >= text.length ? 'Unexpected end of input: object is not closed' : `Expected ',' or '}', found ${describe(i)}`); + } + } + if (c === '[') { + i++; + const items = []; + ws(); + if (text[i] === ']') return { type: 'array', items, start, end: ++i }; + for (;;) { + ws(); + if (text[i] === ']' && items.length) fail('Trailing comma before ]', i); + items.push(value(depth + 1)); + ws(); + if (text[i] === ',') { i++; continue; } + if (text[i] === ']') return { type: 'array', items, start, end: ++i }; + fail(i >= text.length ? 'Unexpected end of input: array is not closed' : `Expected ',' or ']', found ${describe(i)}`); + } + } + if (c === '"') return string(); + if (c === "'") fail('Strings must use double quotes'); + if (c === '-' || (c >= '0' && c <= '9')) { + NUMBER_RE.lastIndex = i; + const m = NUMBER_RE.exec(text); + if (!m) fail('Invalid number'); + i += m[0].length; + if (/[0-9.eE]/.test(text[i] || '')) fail('Invalid number (leading zeros and trailing dots are not allowed)', start); + return { type: 'number', raw: m[0], start, end: i }; + } + for (const [word, node] of [['true', { type: 'boolean', value: true }], ['false', { type: 'boolean', value: false }], ['null', { type: 'null' }]]) { + if (text.startsWith(word, i)) { + i += word.length; + return { ...node, start, end: i }; + } + } + if (i >= text.length) fail('Unexpected end of input: expected a value'); + const word = /^[A-Za-z_$][\w$]*/.exec(text.slice(i, i + 40)); + if (word) fail(`Unexpected '${word[0]}': ${['undefined', 'NaN', 'Infinity', 'True', 'False', 'None'].includes(word[0]) ? "not valid in JSON" : 'strings must be "quoted"'}`); + fail(`Unexpected ${describe(i)}`); + } + + ws(); + if (i >= text.length) fail('Empty document'); + let root; + try { + root = value(0); + } catch (err) { + if (err instanceof RangeError) throw new JsonSyntaxError('Nested too deeply', i, text); + throw err; + } + ws(); + if (i < text.length) fail(`Unexpected ${describe(i)} after the end of the JSON value`); + return root; +} + +/** Prints a node. indent '' = compact (no whitespace at all), else e.g. ' ', ' ', '\t'. */ +export function stringify(node, indent = ' ') { + const out = []; + const sep = indent ? ': ' : ':'; + function walk(n, pad) { + switch (n.type) { + case 'object': { + if (!n.entries.length) return out.push('{}'); + const inner = pad + indent; + out.push('{'); + n.entries.forEach((e, idx) => { + if (idx) out.push(','); + if (indent) out.push('\n', inner); + out.push(e.keyRaw, sep); + walk(e.value, inner); + }); + if (indent) out.push('\n', pad); + return out.push('}'); + } + case 'array': { + if (!n.items.length) return out.push('[]'); + const inner = pad + indent; + out.push('['); + n.items.forEach((item, idx) => { + if (idx) out.push(','); + if (indent) out.push('\n', inner); + walk(item, inner); + }); + if (indent) out.push('\n', pad); + return out.push(']'); + } + case 'string': + case 'number': + return out.push(n.raw); + case 'boolean': + return out.push(String(n.value)); + case 'null': + return out.push('null'); + } + } + walk(node, ''); + return out.join(''); +} + +/** A copy with object keys sorted (by code point), recursively. */ +export function sortKeys(node) { + if (node.type === 'object') { + const entries = node.entries + .map((e) => ({ ...e, value: sortKeys(e.value) })) + .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)); + return { ...node, entries }; + } + if (node.type === 'array') return { ...node, items: node.items.map(sortKeys) }; + return node; +} + +/** Turns text typed into the tree editor into a node: valid JSON as-is, anything else as a string. */ +export function nodeFromInput(text) { + try { + return parse(text); + } catch { + return stringNode(text); + } +} + +export function stringNode(value) { + return { type: 'string', value, raw: JSON.stringify(value) }; +} + +/** JavaScript-style path for display, e.g. $.users[0]["first name"] */ +export function pathToString(path) { + return '$' + path.map((p) => (typeof p === 'number' ? `[${p}]` : /^[A-Za-z_$][\w$]*$/.test(p) ? `.${p}` : `[${JSON.stringify(p)}]`)).join(''); +} diff --git a/app/static/js/tools/json.js b/app/static/js/tools/json.js new file mode 100644 index 0000000..e35ce54 --- /dev/null +++ b/app/static/js/tools/json.js @@ -0,0 +1,460 @@ +// JSON editor: a text pane and a live tree pane that stay in sync. +// Text edits re-render the tree as you type; tree edits rewrite the text (undoable). +import { parse, stringify, sortKeys, nodeFromInput, stringNode, pathToString, JsonSyntaxError } from './json-core.js'; +import { el, segmented, store, copyText, downloadText, openTextFile, debounce, formatBytes, tabIndent, toast, onLeave } from '../ui.js'; + +const SAMPLE = `{ + "name": "tools", + "version": 1, + "bigNumber": 12345678901234567890, + "tags": ["markdown", "json", "paste"], + "nested": { "ok": true, "nothing": null, "items": [{ "id": 1 }, { "id": 2 }] } +} +`; +const INDENTS = { '2': ' ', '4': ' ', tab: '\t' }; +const PAGE = 200; // children shown per expanded node before "show more" +const TREE_LIVE_LIMIT = 5_000_000; // bytes; above this the tree updates on pause, not per keystroke + +export async function mount(root, ctx) { + let mode = store.get('json:mode', window.innerWidth < 800 ? 'text' : 'split'); + let indentKey = store.get('json:indent', '2'); + let ast = null; + let error = null; + let selectedPath = null; + // Open/closed overrides by path key; without one, the root and its children start open. + let opened = new Set(); + let closed = new Set(); + const shown = new Map(); // path key -> how many children are visible + + // ---------- layout ---------- + + const editor = el('textarea.json-input.mono', { spellcheck: false, wrap: 'off', 'aria-label': 'JSON text', placeholder: 'Paste or type JSON…' }); + tabIndent(editor); + const gutter = el('div.gutter.mono', { 'aria-hidden': 'true' }); + const gutterNums = el('div.gutter-nums'); + const errorMark = el('div.gutter-error'); + gutter.append(gutterNums, errorMark); + const tree = el('div.json-tree.mono', { role: 'tree', 'aria-label': 'JSON tree' }); + const status = el('div.statusbar'); + + const modes = segmented([['text', 'Text'], ['split', 'Split'], ['tree', 'Tree']], mode, setMode, 'View mode'); + const indentSel = el('select.select', { title: 'Indentation for Format', 'aria-label': 'Indentation', onchange: () => { + indentKey = indentSel.value; + store.set('json:indent', indentKey); + } }, + el('option', { value: '2' }, '2 spaces'), el('option', { value: '4' }, '4 spaces'), el('option', { value: 'tab' }, 'Tabs')); + indentSel.value = indentKey; + + const toolbar = el('div.toolbar', {}, + modes, + el('span.divider'), + el('button.btn.primary', { onclick: format, title: 'Prettify (Ctrl+Shift+F)' }, 'Format'), + indentSel, + el('button.btn', { onclick: compact, title: 'Remove all whitespace outside keys and values (Ctrl+Shift+M)' }, 'Compact'), + el('button.btn', { onclick: sort, title: 'Sort object keys A→Z, recursively' }, 'Sort keys'), + el('span.spacer'), + el('button.btn', { onclick: openFile }, 'Open'), + el('button.btn', { onclick: () => downloadText(editor.value, 'data.json', 'application/json') }, 'Download'), + el('button.btn', { onclick: () => copyText(editor.value) }, 'Copy'), + el('button.btn', { onclick: () => replaceText(''), title: 'Clear (undo with Ctrl+Z)' }, 'Clear'), + ); + const treeBar = el('div.tree-bar', {}, + el('button.btn.small', { onclick: () => expandAll(true) }, 'Expand all'), + el('button.btn.small', { onclick: () => expandAll(false) }, 'Collapse all'), + el('span.spacer'), + ); + const pathBox = el('button.path-chip.mono', { title: 'Copy path', hidden: true, onclick: () => copyText(pathBox.textContent, 'Path copied') }); + treeBar.append(pathBox); + + const workspace = el('div.json-workspace', {}, + el('div.pane.json-text-pane', {}, el('div.editor-wrap', {}, gutter, editor)), + el('div.pane.json-tree-pane', {}, treeBar, tree), + ); + root.append(el('div.tool.json-tool', {}, toolbar, workspace, status)); + + // ---------- text pane ---------- + + let lineCount = 0; + function updateGutter() { + let n = 1; + for (let i = editor.value.indexOf('\n'); i !== -1; i = editor.value.indexOf('\n', i + 1)) n++; + if (n !== lineCount) { + lineCount = n; + gutterNums.textContent = Array.from({ length: n }, (_, k) => k + 1).join('\n'); + } + syncGutter(); + } + function syncGutter() { + gutter.scrollTop = editor.scrollTop; + } + editor.addEventListener('scroll', syncGutter); + // When the text shrinks the browser clamps the editor's scroll without always firing + // 'scroll', so re-sync after layout too. + editor.addEventListener('input', () => requestAnimationFrame(syncGutter)); + + /** Replaces the whole text in a way the browser's undo (Ctrl+Z) can reverse. */ + function replaceText(text) { + editor.focus({ preventScroll: true }); + editor.select(); + // execCommand types into whatever has focus; when the text pane is hidden (Tree + // mode) the editor can't take focus, so set the value directly (not undoable). + if (document.activeElement !== editor || !document.execCommand('insertText', false, text)) { + editor.value = text; + editor.dispatchEvent(new Event('input')); + } + editor.setSelectionRange(0, 0); + editor.scrollTop = 0; + } + + function lineHeight() { + return parseFloat(getComputedStyle(editor).lineHeight) || 20; + } + function selectRange(start, end) { + if (mode === 'tree') return; + const before = editor.value.slice(0, start); + const line = before.split('\n').length; + editor.focus({ preventScroll: true }); + editor.setSelectionRange(start, end); + editor.scrollTop = Math.max(0, (line - 1) * lineHeight() - editor.clientHeight / 3); + } + + // ---------- parsing & status ---------- + + function reparse() { + const text = editor.value; + try { + ast = text.trim() ? parse(text) : null; + error = null; + } catch (err) { + if (!(err instanceof JsonSyntaxError)) throw err; + error = err; + // Keep showing the last good tree (dimmed) so it doesn't flicker while typing. + } + renderStatus(); + renderTree(); + updateGutter(); + } + + function renderStatus() { + const size = formatBytes(new Blob([editor.value]).size); + errorMark.hidden = !error; + if (error) { + errorMark.style.top = `${(error.line - 1) * lineHeight()}px`; + status.className = 'statusbar error'; + status.replaceChildren( + el('button.linklike', { onclick: () => selectRange(error.pos, Math.min(error.pos + 1, editor.value.length)), title: 'Go to the error' }, + `Line ${error.line}, column ${error.col}`), + `: ${error.message}`, + el('span.spacer'), + el('span.muted', {}, size), + ); + } else if (!ast) { + status.className = 'statusbar'; + status.replaceChildren(el('span.muted', {}, 'Empty')); + } else { + status.className = 'statusbar ok'; + status.replaceChildren('✓ Valid JSON', el('span.muted', {}, ` · ${summary(ast)}`), el('span.spacer'), el('span.muted', {}, size)); + } + } + + function summary(n) { + if (n.type === 'object') return `object, ${n.entries.length} key${n.entries.length === 1 ? '' : 's'}`; + if (n.type === 'array') return `array, ${n.items.length} item${n.items.length === 1 ? '' : 's'}`; + return n.type; + } + + // ---------- toolbar actions ---------- + + function current() { + if (error) { + toast(`Fix the error first: line ${error.line}, column ${error.col}`, 'error'); + selectRange(error.pos, error.pos + 1); + return null; + } + return ast; + } + function format() { + const a = current(); + if (a) replaceText(stringify(a, INDENTS[indentKey]) + '\n'); + } + function compact() { + const a = current(); + if (a) replaceText(stringify(a, '')); + } + function sort() { + const a = current(); + if (a) replaceText(stringify(sortKeys(a), INDENTS[indentKey]) + '\n'); + } + async function openFile() { + const f = await openTextFile('.json,application/json,text/plain'); + if (f) replaceText(f.text); + } + + // ---------- tree ---------- + + const key = (path) => path.map((p) => '/' + String(p).replace(/~/g, '~0').replace(/\//g, '~1')).join(''); + const isOpen = (path) => { + const k = key(path); + return closed.has(k) ? false : opened.has(k) || path.length <= 1; + }; + function setOpen(path, open) { + const k = key(path); + (open ? opened : closed).add(k); + (open ? closed : opened).delete(k); + } + + function renderTree() { + if (mode === 'text') return; + tree.classList.toggle('stale', !!error); + if (!ast) { + tree.replaceChildren(el('div.empty', {}, error ? 'Fix the JSON to see the tree.' : 'Nothing to show yet.')); + return; + } + const scroll = tree.scrollTop; + tree.replaceChildren(renderNode(ast, [], null, null)); + tree.scrollTop = scroll; + } + + function renderNode(node, path, label, parent) { + const isContainer = node.type === 'object' || node.type === 'array'; + const row = el('div.tree-row', { role: 'treeitem', tabIndex: -1 }); + const pk = key(path); + if (selectedPath === pk) row.classList.add('selected'); + row.style.setProperty('--depth', path.length); + + const open = isContainer && isOpen(path); + if (isContainer) { + row.setAttribute('aria-expanded', String(open)); + row.append(el('button.twisty', { tabIndex: -1, 'aria-label': open ? 'Collapse' : 'Expand', onclick: (e) => { + e.stopPropagation(); + setOpen(path, !open); + renderTree(); + } }, open ? '▾' : '▸')); + } else row.append(el('span.twisty-space')); + + if (label != null) { + if (typeof label === 'number') row.append(el('span.t-index', {}, String(label)), el('span.t-punct', {}, ': ')); + else row.append(editable(el('span.t-key', { title: 'Double-click to rename' }, label), label, (v) => renameKey(parent, path, v)), el('span.t-punct', {}, ': ')); + } + + if (isContainer) { + const n = node.type === 'object' ? node.entries.length : node.items.length; + row.append(el('span.t-punct', {}, node.type === 'object' ? '{' : '['), + el('span.t-count', {}, open ? '' : ` ${n} ${node.type === 'object' ? (n === 1 ? 'key' : 'keys') : n === 1 ? 'item' : 'items'} `), + el('span.t-punct', {}, open ? '' : node.type === 'object' ? '}' : ']')); + } else { + const shownText = node.type === 'string' ? node.value : node.type === 'number' ? node.raw : String(node.value ?? 'null'); + const display = node.type === 'string' ? JSON.stringify(shownText.length > 2000 ? shownText.slice(0, 2000) + '…' : shownText) : shownText; + row.append(editable(el(`span.t-val.t-${node.type}`, { title: 'Double-click to edit' }, display), shownText, (v) => editValue(path, node, v))); + } + + const actions = el('span.row-actions'); + if (isContainer) actions.append(el('button.mini', { title: node.type === 'object' ? 'Add a key' : 'Add an item', onclick: (e) => { e.stopPropagation(); addChild(path, node); } }, '+')); + if (path.length) actions.append(el('button.mini', { title: 'Delete', onclick: (e) => { e.stopPropagation(); removeAt(path); } }, '×')); + row.append(actions); + + row.addEventListener('click', () => { + selectedPath = pk; + tree.querySelectorAll('.tree-row.selected').forEach((r) => r.classList.remove('selected')); + row.classList.add('selected'); + pathBox.hidden = false; + pathBox.textContent = pathToString(path); + if (!error && node.start != null) selectRange(node.start, node.end); + }); + + if (!open) return row; + const children = node.type === 'object' ? node.entries.map((e) => [e.key, e.value]) : node.items.map((v, i) => [i, v]); + const limit = shown.get(pk) || PAGE; + const box = el('div.tree-children', { role: 'group' }); + for (const [k, v] of children.slice(0, limit)) box.append(renderNode(v, [...path, k], k, node)); + if (children.length > limit) { + box.append(el('button.btn.small.more', { style: `--depth:${path.length + 1}`, onclick: () => { shown.set(pk, limit + PAGE * 5); renderTree(); } }, + `Show more (${children.length - limit} hidden)`)); + } + const close = el('div.tree-row.closing', {}, el('span.twisty-space'), el('span.t-punct', {}, node.type === 'object' ? '}' : ']')); + close.style.setProperty('--depth', path.length); + return el('div', {}, row, box, close); + } + + /** Double-click (or Enter on the focused row) turns a span into an inline input. */ + function editable(span, initial, commit) { + span.addEventListener('dblclick', (e) => { + e.stopPropagation(); + const input = el('input.inline-edit.mono', { value: initial, size: Math.max(4, Math.min(60, initial.length + 2)) }); + let done = false; + const finish = (save) => { + if (done) return; + done = true; + if (save && input.value !== initial) commit(input.value); + else input.replaceWith(span); + }; + input.addEventListener('keydown', (ev) => { + ev.stopPropagation(); + // preventDefault: committing focuses the text pane, and the Enter must not land there. + if (ev.key === 'Enter') { ev.preventDefault(); finish(true); } + if (ev.key === 'Escape') { ev.preventDefault(); finish(false); } + }); + input.addEventListener('blur', () => finish(true)); + span.replaceWith(input); + input.focus(); + input.select(); + }); + return span; + } + + // Tree edits: change the AST, then rewrite the text formatted with the current indent. + function getAt(path) { + let n = ast; + for (const p of path) n = n.type === 'object' ? n.entries.find((e) => e.key === p)?.value : n.items[p]; + return n; + } + function parentAndIndex(path) { + const parent = getAt(path.slice(0, -1)); + const last = path[path.length - 1]; + const idx = parent.type === 'object' ? parent.entries.findIndex((e) => e.key === last) : last; + return [parent, idx]; + } + function commitAst() { + replaceText(stringify(ast, INDENTS[indentKey]) + '\n'); + } + function guard() { + if (error) { + toast('Fix the JSON text before editing the tree', 'error'); + renderTree(); + return false; + } + return true; + } + function editValue(path, node, text) { + if (!guard()) return; + // Strings stay strings; other values are re-read as JSON (so "12" → 12, "abc" → "abc"). + const next = node.type === 'string' ? stringNode(text) : nodeFromInput(text.trim()); + if (!path.length) ast = next; + else { + const [parent, idx] = parentAndIndex(path); + if (parent.type === 'object') parent.entries[idx].value = next; + else parent.items[idx] = next; + } + commitAst(); + } + function renameKey(parent, path, newKey) { + if (!guard()) return; + const [obj, idx] = parentAndIndex(path); + if (obj.entries.some((e, i) => i !== idx && e.key === newKey)) return toast(`Key "${newKey}" already exists`, 'error'), renderTree(); + obj.entries[idx].key = newKey; + obj.entries[idx].keyRaw = JSON.stringify(newKey); + remapExpanded(path, [...path.slice(0, -1), newKey]); + commitAst(); + } + function remapExpanded(from, to) { + const a = key(from), b = key(to); + const move = (set) => new Set([...set].map((k) => (k === a || k.startsWith(a + '/') ? b + k.slice(a.length) : k))); + opened = move(opened); + closed = move(closed); + } + function addChild(path, node) { + if (!guard()) return; + const target = getAt(path); + if (target.type === 'object') { + let k = 'key', i = 1; + while (target.entries.some((e) => e.key === k)) k = `key${++i}`; + target.entries.push({ key: k, keyRaw: JSON.stringify(k), value: { type: 'null' } }); + } else target.items.push({ type: 'null' }); + setOpen(path, true); + commitAst(); + } + function removeAt(path) { + if (!guard()) return; + const [parent, idx] = parentAndIndex(path); + if (parent.type === 'object') parent.entries.splice(idx, 1); + else parent.items.splice(idx, 1); + selectedPath = null; + pathBox.hidden = true; + commitAst(); + } + function expandAll(open) { + if (!ast) return; + opened = new Set(); + closed = new Set(); + shown.clear(); + let count = 0; + (function walk(n, path) { + if (count > 5000 || (n.type !== 'object' && n.type !== 'array')) return; + count++; + if (open) opened.add(key(path)); + else if (path.length) closed.add(key(path)); + if (n.type === 'object') n.entries.forEach((e) => walk(e.value, [...path, e.key])); + else n.items.forEach((v, i) => walk(v, [...path, i])); + })(ast, []); + if (open && count > 5000) toast('Large document: expanded the first 5000 nodes'); + renderTree(); + } + + // ---------- modes, input, shortcuts ---------- + + function setMode(m) { + mode = m; + workspace.dataset.mode = m; + modes.set(m); + store.set('json:mode', m); + renderTree(); + } + + // A paste opened via ?paste= is never written over this browser's own draft. + let fromPaste = false; + const save = debounce(() => { + if (!fromPaste && editor.value.length < 2_000_000) store.set('json:text', editor.value); + }, 500); + const slowParse = debounce(reparse, 400); + editor.addEventListener('input', () => { + updateGutter(); + if (editor.value.length > TREE_LIVE_LIMIT) slowParse(); + else reparse(); + save(); + }); + + function onKey(e) { + if (!(e.ctrlKey || e.metaKey) || !e.shiftKey) return; + const k = e.key.toLowerCase(); + if (k === 'f') { e.preventDefault(); format(); } + if (k === 'm') { e.preventDefault(); compact(); } + } + document.addEventListener('keydown', onKey); + + // Pasting a whole document into an empty editor formats it straight away. + editor.addEventListener('paste', (e) => { + if (editor.value.trim()) return; + const text = e.clipboardData?.getData('text/plain'); + if (!text) return; + try { + const a = parse(text); + e.preventDefault(); + document.execCommand('insertText', false, stringify(a, INDENTS[indentKey]) + '\n'); + } catch {} + }); + + editor.value = store.get('json:text', SAMPLE); + const pasteId = ctx.query.get('paste'); + if (pasteId) { + try { + const r = await fetch(`/api/paste/${encodeURIComponent(pasteId)}`); + const body = await r.json(); + if (!r.ok) throw new Error(body.detail); + editor.value = body.content; + fromPaste = true; + ctx.setTitle(`paste ${pasteId}`); + toast('Opened a shared paste; edits here are not saved'); + } catch (err) { + toast(`Couldn't load paste: ${err.message}`, 'error'); + } + } + setMode(mode); + reparse(); + + const off = onLeave(save.flush); + return () => { + save.flush(); + off(); + document.removeEventListener('keydown', onKey); + }; +} diff --git a/app/static/js/tools/markdown.js b/app/static/js/tools/markdown.js new file mode 100644 index 0000000..a445fa8 --- /dev/null +++ b/app/static/js/tools/markdown.js @@ -0,0 +1,159 @@ +// Markdown editor with live preview. Modes: edit only, side by side, full-page preview. +import { marked } from '../../vendor/marked.esm.js'; +import DOMPurify from '../../vendor/purify.es.mjs'; +import { el, segmented, store, copyText, downloadText, openTextFile, debounce, tabIndent, toast, onLeave } from '../ui.js'; +import { createPaste } from './paste.js'; + +const SAMPLE = `# Markdown + +Type on the left, see it rendered on the right. Switch to **Preview** for a full-page view. + +## Formatting + +*Italic*, **bold**, ~~strikethrough~~, \`inline code\` and [links](https://example.com). + +> Blockquotes look like this. + +- [x] Task lists +- [ ] Nested lists + 1. one + 2. two + +| Column | Another | Right | +| ------ | :-----: | ----: | +| tables | aligned | 42 | + +\`\`\`js +function hello(name) { + return \`Hello, \${name}!\`; +} +\`\`\` + +--- + +Your text is saved in this browser as you type. +`; + +marked.use({ gfm: true }); + +DOMPurify.addHook('afterSanitizeAttributes', (node) => { + if (node.tagName === 'A' && node.getAttribute('href') && !node.getAttribute('href').startsWith('#')) { + node.setAttribute('target', '_blank'); + node.setAttribute('rel', 'noopener noreferrer'); + } +}); + +export function render(md) { + return DOMPurify.sanitize(marked.parse(md)); +} + +export async function mount(root, ctx) { + let mode = store.get('md:mode', window.innerWidth < 800 ? 'edit' : 'split'); + const editor = el('textarea.md-input.mono', { + spellcheck: true, + 'aria-label': 'Markdown', + placeholder: 'Write Markdown here…', + }); + tabIndent(editor); + const preview = el('article.md-preview.prose', { 'aria-label': 'Preview' }); + const stats = el('span.muted.small'); + + const modes = segmented( + [['edit', 'Edit', 'Editor only'], ['split', 'Split', 'Editor and preview side by side'], ['preview', 'Preview', 'Full-page preview']], + mode, + setMode, + 'View mode', + ); + + const workspace = el('div.md-workspace', {}, + el('div.pane.md-edit-pane', {}, editor), + el('div.pane.md-preview-pane', {}, preview), + ); + + const toolbar = el('div.toolbar', {}, + modes, + el('span.spacer'), + stats, + el('button.btn', { onclick: openFile, title: 'Open a .md file' }, 'Open'), + el('button.btn', { onclick: () => downloadText(editor.value, 'document.md', 'text/markdown'), title: 'Download as .md' }, 'Download'), + el('button.btn', { onclick: () => copyText(render(editor.value), 'HTML copied'), title: 'Copy the rendered HTML' }, 'Copy HTML'), + el('button.btn', { onclick: share, title: 'Create a 24-hour paste and copy its link' }, 'Share'), + ); + + root.append(el('div.tool.md-tool', {}, toolbar, workspace)); + + function update() { + preview.innerHTML = render(editor.value); + const words = (editor.value.match(/\S+/g) || []).length; + stats.textContent = `${words} word${words === 1 ? '' : 's'}`; + } + // A shared paste opened via ?paste= is never written over this browser's own draft. + let fromPaste = false; + const save = debounce(() => !fromPaste && store.set('md:text', editor.value), 400); + const live = debounce(update, 60); + editor.addEventListener('input', () => { + live(); + save(); + }); + + function setMode(m) { + mode = m; + workspace.dataset.mode = m; + modes.set(m); + if (!fromPaste) store.set('md:mode', m); + if (m !== 'edit') update(); + if (m !== 'preview') editor.focus({ preventScroll: true }); + } + + // Keep the preview roughly in step with the editor while scrolling side by side. + let syncing = null; + const sync = (from, to) => () => { + if (mode !== 'split' || (syncing && syncing !== from)) return; + syncing = from; + const max = from.scrollHeight - from.clientHeight; + to.scrollTop = max > 0 ? (from.scrollTop / max) * (to.scrollHeight - to.clientHeight) : 0; + clearTimeout(sync.t); + sync.t = setTimeout(() => (syncing = null), 80); + }; + const previewPane = workspace.querySelector('.md-preview-pane'); + editor.addEventListener('scroll', sync(editor, previewPane)); + previewPane.addEventListener('scroll', sync(previewPane, editor)); + + async function openFile() { + const f = await openTextFile('.md,.markdown,.txt,text/markdown,text/plain'); + if (!f) return; + editor.value = f.text; + update(); + save(); + } + + async function share() { + if (!editor.value.trim()) return toast('Nothing to share', 'error'); + const p = await createPaste(editor.value); + if (p) copyText(`${location.origin}/markdown?paste=${p.id}`, 'Link copied (expires in 24 h)'); + } + + // Load: ?paste= opens a paste here; otherwise the saved draft, otherwise the sample. + const pasteId = ctx.query.get('paste'); + editor.value = store.get('md:text', SAMPLE); + if (pasteId) { + try { + const r = await fetch(`/api/paste/${encodeURIComponent(pasteId)}`); + if (!r.ok) throw new Error((await r.json()).detail); + editor.value = (await r.json()).content; + ctx.setTitle(`paste ${pasteId}`); + fromPaste = true; + mode = 'preview'; + toast('Opened a shared paste; edits here are not saved', 'info'); + } catch (err) { + toast(`Couldn't load paste: ${err.message}`, 'error'); + } + } + setMode(mode); + update(); + const off = onLeave(save.flush); + return () => { + save.flush(); + off(); + }; +} diff --git a/app/static/js/tools/paste.js b/app/static/js/tools/paste.js new file mode 100644 index 0000000..fee511b --- /dev/null +++ b/app/static/js/tools/paste.js @@ -0,0 +1,165 @@ +// Pastebin: /paste to create, /paste/ to view. Pastes expire 24 h after creation. +// Pastes made in this browser are remembered locally (with their delete tokens). +import { el, store, copyText, downloadText, toast, timeLeft, formatBytes } from '../ui.js'; + +const MAX_BYTES = 1024 * 1024; + +function mine() { + const now = Date.now() / 1000; + return (store.get('paste:mine', []) || []).filter((p) => p.expires_at > now); +} +function remember(p, preview) { + store.set('paste:mine', [{ id: p.id, expires_at: p.expires_at, delete_token: p.delete_token, preview }, ...mine()].slice(0, 50)); +} +function forget(id) { + store.set('paste:mine', mine().filter((p) => p.id !== id)); +} + +/** Creates a paste and remembers it locally. Resolves with {id, expires_at, delete_token} or null. */ +export async function createPaste(content) { + try { + const r = await fetch('/api/paste', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ content }), + }); + const body = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(body.detail || `HTTP ${r.status}`); + remember(body, content.slice(0, 80).replace(/\s+/g, ' ')); + return body; + } catch (err) { + toast(`Couldn't create paste: ${err.message}`, 'error'); + return null; + } +} + +async function deletePaste(id, token) { + const r = await fetch(`/api/paste/${encodeURIComponent(id)}`, { method: 'DELETE', headers: { 'X-Delete-Token': token } }); + if (r.ok || r.status === 404) forget(id); + return r.ok; +} + +export async function mount(root, ctx) { + const timers = []; + const cleanup = () => timers.forEach(clearInterval); + if (ctx.rest) await renderView(root, ctx, ctx.rest, timers); + else renderCreate(root, ctx, timers); + return cleanup; +} + +function renderCreate(root, ctx, timers) { + const ta = el('textarea.paste-input.mono', { placeholder: 'Paste or type text…', spellcheck: false, 'aria-label': 'Paste content' }); + ta.value = store.get('paste:draft', ''); + const info = el('span.muted.small'); + const btn = el('button.btn.primary', { onclick: submit }, 'Create paste'); + const updateInfo = () => { + const n = new Blob([ta.value]).size; + info.textContent = `${formatBytes(n)} of 1 MB · expires 24 h after creation`; + info.classList.toggle('error-text', n > MAX_BYTES); + }; + ta.addEventListener('input', () => { + updateInfo(); + store.set('paste:draft', ta.value); + }); + ta.addEventListener('keydown', (e) => { + if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) submit(); + }); + + async function submit() { + if (!ta.value.trim()) return toast('Nothing to paste', 'error'); + if (new Blob([ta.value]).size > MAX_BYTES) return toast('Paste is larger than 1 MB', 'error'); + btn.disabled = true; + const p = await createPaste(ta.value); + btn.disabled = false; + if (!p) return; + store.set('paste:draft', ''); + copyText(`${location.origin}/paste/${p.id}`, 'Link copied'); + ctx.navigate(`/paste/${p.id}`); + } + + const list = el('div.paste-list'); + function drawList() { + const items = mine(); + list.replaceChildren( + ...(items.length + ? [el('h2.section-title', {}, 'Your recent pastes'), + ...items.map((p) => + el('div.paste-item', {}, + el('a.mono', { href: `/paste/${p.id}` }, p.id), + el('span.paste-preview.muted', {}, p.preview || ''), + el('span.muted.small.nowrap', {}, timeLeft(p.expires_at)), + el('button.btn.small', { title: 'Delete now', onclick: async () => { + if (await deletePaste(p.id, p.delete_token)) toast('Deleted'); + drawList(); + } }, 'Delete'), + ))] + : []), + ); + } + drawList(); + timers.push(setInterval(drawList, 30000)); + updateInfo(); + + root.append( + el('div.tool.paste-tool', {}, + el('div.toolbar', {}, el('strong', {}, 'New paste'), el('span.spacer'), info, btn), + el('div.paste-body', {}, ta, el('div.hint.muted.small', {}, 'Ctrl+Enter to create. Anyone with the link can read it until it expires. Don\'t paste secrets.'), list), + ), + ); + ta.focus(); +} + +async function renderView(root, ctx, id, timers) { + ctx.setTitle(id); + let p; + try { + const r = await fetch(`/api/paste/${encodeURIComponent(id)}`); + p = await r.json(); + if (!r.ok) throw new Error(p.detail || `HTTP ${r.status}`); + } catch (err) { + forget(id); + root.append(el('div.empty', {}, el('p', {}, err.message), el('a.btn.primary', { href: '/paste' }, 'New paste'))); + return; + } + const own = mine().find((m) => m.id === id); + const left = el('span.muted.small', {}, timeLeft(p.expires_at)); + timers.push(setInterval(() => (left.textContent = timeLeft(p.expires_at)), 30000)); + + const lines = p.content.split('\n'); + const wrapBtn = el('button.btn', { onclick: () => { + view.classList.toggle('wrap'); + store.set('paste:wrap', view.classList.contains('wrap')); + } }, 'Wrap'); + const view = el('div.paste-view.mono', {}, + el('div.paste-lines', { 'aria-hidden': 'true' }, lines.map((_, i) => i + 1).join('\n')), + el('pre.paste-text', {}, p.content), + ); + if (store.get('paste:wrap', false)) view.classList.add('wrap'); + + root.append( + el('div.tool.paste-tool', {}, + el('div.toolbar', {}, + el('span.mono.strong', {}, id), + el('span.muted.small', {}, `${formatBytes(p.size)} · ${lines.length} line${lines.length === 1 ? '' : 's'}`), + left, + el('span.spacer'), + el('button.btn', { onclick: () => copyText(`${location.origin}/paste/${id}`, 'Link copied') }, 'Copy link'), + el('button.btn', { onclick: () => copyText(p.content) }, 'Copy text'), + el('a.btn', { href: `/raw/${id}`, target: '_blank', rel: 'noopener' }, 'Raw'), + el('button.btn', { onclick: () => downloadText(p.content, `${id}.txt`) }, 'Download'), + el('a.btn', { href: `/markdown?paste=${id}`, title: 'Render this paste as Markdown' }, 'As Markdown'), + el('a.btn', { href: `/json?paste=${id}`, title: 'Open this paste in the JSON editor' }, 'As JSON'), + wrapBtn, + own && el('button.btn.danger', { onclick: async () => { + if (!confirm('Delete this paste now?')) return; + if (await deletePaste(id, own.delete_token)) { + toast('Deleted'); + ctx.navigate('/paste'); + } else toast("Couldn't delete", 'error'); + } }, 'Delete'), + el('a.btn.primary', { href: '/paste' }, 'New'), + ), + view, + ), + ); +} diff --git a/app/static/js/ui.js b/app/static/js/ui.js new file mode 100644 index 0000000..4c7fde7 --- /dev/null +++ b/app/static/js/ui.js @@ -0,0 +1,159 @@ +// Small helpers shared by every tool. + +/** el('button.primary', {onclick}, 'Save') — tag with optional .classes, props/attrs, children. */ +export function el(spec, props = {}, ...children) { + const [tag, ...classes] = spec.split('.'); + const node = document.createElement(tag || 'div'); + if (classes.length) node.className = classes.join(' '); + for (const [k, v] of Object.entries(props || {})) { + if (v == null || v === false) continue; + if (k.startsWith('on') && typeof v === 'function') node.addEventListener(k.slice(2), v); + else if (k === 'dataset') Object.assign(node.dataset, v); + else if (k in node && typeof v !== 'string') node[k] = v; + else node.setAttribute(k, v === true ? '' : v); + } + for (const c of children.flat()) if (c != null && c !== false) node.append(c); + return node; +} + +export function toast(message, kind = 'info') { + const box = document.getElementById('toasts'); + const t = el(`div.toast.${kind}`, { role: kind === 'error' ? 'alert' : 'status' }, message); + box.append(t); + setTimeout(() => t.classList.add('out'), kind === 'error' ? 5000 : 2200); + setTimeout(() => t.remove(), kind === 'error' ? 5400 : 2600); +} + +export async function copyText(text, what = 'Copied') { + try { + await navigator.clipboard.writeText(text); + } catch { + const ta = el('textarea', { value: text, style: 'position:fixed;opacity:0' }); + document.body.append(ta); + ta.select(); + document.execCommand('copy'); + ta.remove(); + } + toast(what); +} + +export function downloadText(text, filename, type = 'text/plain') { + const url = URL.createObjectURL(new Blob([text], { type: `${type};charset=utf-8` })); + const a = el('a', { href: url, download: filename }); + document.body.append(a); + a.click(); + a.remove(); + setTimeout(() => URL.revokeObjectURL(url), 1000); +} + +/** Opens a file picker and resolves with {name, text}, or null if cancelled. */ +export function openTextFile(accept = '') { + return new Promise((resolve) => { + const input = el('input', { type: 'file', accept }); + input.addEventListener('change', async () => { + const f = input.files[0]; + resolve(f ? { name: f.name, text: await f.text() } : null); + }); + input.addEventListener('cancel', () => resolve(null)); + input.click(); + }); +} + +// localStorage can be missing or throw (private windows, blocked storage); never let that break a tool. +export const store = { + get(key, fallback = null) { + try { + const v = localStorage.getItem(`tools:${key}`); + return v == null ? fallback : JSON.parse(v); + } catch { + return fallback; + } + }, + set(key, value) { + try { + localStorage.setItem(`tools:${key}`, JSON.stringify(value)); + } catch {} + }, +}; + +export function formatBytes(n) { + if (n < 1024) return `${n} B`; + if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`; + return `${(n / 1024 / 1024).toFixed(2)} MB`; +} + +export function timeLeft(expiresAtSec) { + const s = Math.max(0, Math.round(expiresAtSec - Date.now() / 1000)); + if (s <= 0) return 'expired'; + if (s < 60) return `${s}s left`; + if (s < 3600) return `${Math.floor(s / 60)}m left`; + return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m left`; +} + +/** Debounced fn; .flush() runs a pending call now (e.g. before the page unloads). */ +export function debounce(fn, ms) { + let t, pending; + const d = (...args) => { + clearTimeout(t); + pending = args; + t = setTimeout(d.flush, ms); + }; + d.flush = () => { + clearTimeout(t); + if (pending) { + const args = pending; + pending = null; + fn(...args); + } + }; + return d; +} + +/** Runs fn when the page is hidden/unloaded; returns a function that removes the listener. */ +export function onLeave(fn) { + window.addEventListener('pagehide', fn); + return () => window.removeEventListener('pagehide', fn); +} + +/** A segmented control: segmented([['edit','Edit'],...], current, onChange). */ +export function segmented(options, current, onChange, label = '') { + const wrap = el('div.segmented', { role: 'radiogroup', 'aria-label': label }); + const buttons = options.map(([value, text, title]) => + el('button', { + type: 'button', + role: 'radio', + title: title || text, + 'aria-checked': String(value === current), + onclick: () => set(value, true), + }, text), + ); + function set(value, fire) { + options.forEach(([v], i) => buttons[i].setAttribute('aria-checked', String(v === value))); + if (fire) onChange(value); + } + wrap.append(...buttons); + wrap.set = (v) => set(v, false); + return wrap; +} + +/** Makes Tab / Shift+Tab indent and outdent in a textarea instead of moving focus. */ +export function tabIndent(ta, unit = ' ') { + ta.addEventListener('keydown', (e) => { + if (e.key !== 'Tab' || e.ctrlKey || e.metaKey || e.altKey) return; + e.preventDefault(); + const { selectionStart: s, selectionEnd: end, value } = ta; + const lineStart = value.lastIndexOf('\n', s - 1) + 1; + if (s === end && !e.shiftKey) { + document.execCommand('insertText', false, unit) || ta.setRangeText(unit, s, end, 'end'); + return; + } + const block = value.slice(lineStart, end); + const lines = block.split('\n'); + const out = e.shiftKey + ? lines.map((l) => (l.startsWith(unit) ? l.slice(unit.length) : l.replace(/^\t| {1,2}/, ''))) + : lines.map((l) => unit + l); + ta.setSelectionRange(lineStart, end); + document.execCommand('insertText', false, out.join('\n')) || ta.setRangeText(out.join('\n'), lineStart, end, 'select'); + ta.setSelectionRange(lineStart, lineStart + out.join('\n').length); + }); +} diff --git a/app/static/vendor/dompurify.LICENSE b/app/static/vendor/dompurify.LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/app/static/vendor/dompurify.LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/app/static/vendor/marked.LICENSE b/app/static/vendor/marked.LICENSE new file mode 100644 index 0000000..4bd2d4a --- /dev/null +++ b/app/static/vendor/marked.LICENSE @@ -0,0 +1,44 @@ +# License information + +## Contribution License Agreement + +If you contribute code to this project, you are implicitly allowing your code +to be distributed under the MIT license. You are also implicitly verifying that +all code is your original work. `` + +## Marked + +Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/) +Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +## Markdown + +Copyright © 2004, John Gruber +http://daringfireball.net/ +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. +* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage. diff --git a/app/static/vendor/marked.esm.js b/app/static/vendor/marked.esm.js new file mode 100644 index 0000000..64d94af --- /dev/null +++ b/app/static/vendor/marked.esm.js @@ -0,0 +1,81 @@ +/** + * marked v18.1.2 - a markdown parser + * Copyright (c) 2018-2026, MarkedJS. (MIT License) + * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License) + * https://github.com/markedjs/marked + */ + +/** + * DO NOT EDIT THIS FILE + * The code in this file is generated from files in ./src/ + */ + +function v(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var y=v();function ee(a){y=a}var B={exec:()=>null};function I(a){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=a(n),e[n]=s),s}}function c(a,e=""){let t=typeof a=="string"?a:a.source,n={replace:(s,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(T.caret,"$1"),t=t.replace(s,o),n},getRegex:()=>new RegExp(t,e)};return n}var Me=((a="")=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,blockquoteMarkerWhitespace:/^( {0,3}>)([ \t]+)/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:a=>new RegExp(`^( {0,3}${a})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:I(a=>new RegExp(`^ {0,${a}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:I(a=>new RegExp(`^ {0,${a}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:I(a=>new RegExp(`^ {0,${a}}(?:\`\`\`|~~~)`)),headingBeginRegex:I(a=>new RegExp(`^ {0,${a}}#{1,6}(?:\\s|$)`)),pedanticHeadingBeginRegex:I(a=>new RegExp(`^ {0,${a}}#`)),htmlBeginRegex:I(a=>new RegExp(`^ {0,${a}}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|new RegExp(`^ {0,${a}}>`))},Ce=/^(?:[ \t]*(?:\n|$))+/,Ee=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ie=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,U=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Be=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ne=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,me=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,xe=c(me).replace(/bull/g,ne).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),De=c(me).replace(/bull/g,ne).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),re=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,qe=/^[^\n]+/,se=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,Ze=c(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",se).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ve=c(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ne).getRegex(),K="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",ie=/|$))/,He=c("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|[^\\n]*\\n*|$)|[^\\n]*\\n*|$)||$)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",ie).replace("tag",K).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),be=a=>c(re).replace("hr",U).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",a).replace("html"," {0,3}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?| ?(?:(?![ \t]*(?:\n|$))(paragraph)|[^\n]*)(?:\n|$))+/).replace("paragraph",Ne).getRegex(),oe={blockquote:Qe,code:Ee,def:Ze,fences:Ie,heading:Be,hr:U,html:He,lheading:xe,list:ve,newline:Ce,paragraph:Ge,table:B,text:qe},ke=c("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",U).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html"," {0,3}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html"," {0,3}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?| *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",ie).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:B,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:c(re).replace("hr",U).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",xe).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ue=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ke=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Re=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,We=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Me?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Oe=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,tt=c(Oe,"u").replace(/punct/g,$).getRegex(),nt=c(Oe,"u").replace(/punct/g,Te).getRegex(),rt=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,st=c(rt,"u").replace(/openQuote/g,Ve).replace(/punct/g,$).getRegex(),we="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",it=c(we,"gu").replace(/notPunctSpace/g,W).replace(/punctSpace/g,H).replace(/punct/g,$).getRegex(),ot=c(we,"gu").replace(/notPunctSpace/g,Ye).replace(/punctSpace/g,Je).replace(/punct/g,Te).getRegex(),at="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",lt=c(at,"gu").replace(/notPunctSpace/g,W).replace(/punctSpace/g,H).replace(/punct/g,$).getRegex(),ut=c("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,W).replace(/punctSpace/g,H).replace(/punct/g,$).getRegex(),pt="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",ct=c(pt,"gu").replace(/notPunctSpace/g,W).replace(/punctSpace/g,H).replace(/punct/g,$).getRegex(),ht=c(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,$).getRegex(),dt="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",kt=c(dt,"gu").replace(/notPunctSpace/g,W).replace(/punctSpace/g,H).replace(/punct/g,$).getRegex(),gt=c(/\\(punct)/,"gu").replace(/punct/g,$).getRegex(),ft=c(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,$).getRegex(),mt=c(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),xt=c(ie).replace("(?:-->|$)","-->").getRegex(),bt=c("^comment|^|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",xt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Pe=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,Y=c(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",Pe).getRegex(),Rt=c(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",Y).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Tt=c(/^!?\[(label)\]\[(ref)\]/).replace("label",Y).replace("ref",se).getRegex(),Ot=c(/^!?\[(ref)\](?:\[\])?/).replace("ref",se).getRegex(),ge=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,wt=c(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",Pe).getRegex(),Pt=c("reflink|nolink(?!\\()","g").replace("reflink",c(/^!?\[(label)\]\[(ref)\]/).replace("label",wt).replace("ref",ge).getRegex()).replace("nolink",c(/^!?\[(ref)\](?:\[\])?/).replace("ref",ge).getRegex()).getRegex(),fe=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,yt=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,St=c(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,yt).getRegex(),ae={_backpedal:B,anyPunctuation:gt,anyPunctuationOutsideCode:ft,autolink:mt,blockSkip:et,br:Re,code:Ke,del:B,delLDelim:B,delRDelim:B,emStrongLDelim:tt,emStrongRDelimAst:it,emStrongRDelimUnd:ut,escape:Ue,link:Rt,nolink:Ot,punctuation:Xe,reflink:Tt,reflinkSearch:Pt,tag:bt,text:We,url:B},_t={...ae,emStrongLDelim:st,emStrongRDelimAst:lt,emStrongRDelimUnd:ct,link:c(/^!?\[(label)\]\((.*?)\)/).replace("label",Y).getRegex(),reflink:c(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",Y).getRegex()},te={...ae,emStrongRDelimAst:ot,emStrongLDelim:nt,delLDelim:ht,delRDelim:kt,url:c(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",St).replace("protocol",fe).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:c(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},ye=a=>Lt[a];function P(a,e){if(e){if(T.escapeTest.test(a))return a.replace(T.escapeReplace,ye)}else if(T.escapeTestNoEncode.test(a))return a.replace(T.escapeReplaceNoEncode,ye);return a}function Se(a){return T.numericCharacterReference.test(a)?a.replace(T.numericCharacterReferenceOrAmpersand,(e,t,n)=>{if(t===void 0&&n===void 0)return"&";let s=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return s===0||s>1114111||s>=55296&&s<=57343?"\uFFFD":s===38?"&":String.fromCodePoint(s)}):a}function le(a){try{a=encodeURI(a).replace(T.percentDecode,"%")}catch{return null}return a}function ue(a,e){let t=a.replace(T.findPipe,(r,o,i)=>{let l=!1,u=o;for(;--u>=0&&i[u]==="\\";)l=!l;return l?"|":" |"}),n=t.split(T.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length=0&&T.blankLine.test(e[t]);)t--;return e.length-t<=2?a:e.slice(0,t+1).join(` +`)}function N(a){return a.trim().toLowerCase().toUpperCase().toLowerCase()}function ce(a,e){if(a.indexOf(e[0])===-1&&a.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n0?-2:-1}function V(a,e=0){let t=e,n="";for(let s of a)if(s===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=s,t++;return n}function _e(a,e,t,n,s){let r=e.href,o=e.title||null,i=a[1].replace(s.other.outputLinkReplace,"$1"),l=a[0].charAt(0)==="!",u=n.state.inLink,h=n.state.linkEmitted,p=n.state.inRawBlock;n.state.inLink=!0,n.state.linkEmitted=!1;let d=n.inlineTokens(i),g=n.state.linkEmitted;if(n.state.linkEmitted=h,n.state.inLink=u,!l){if(g){n.state.inRawBlock=p;return}n.state.linkEmitted=!0}return{type:l?"image":"link",raw:t,href:r,title:o,text:i,tokens:d}}function At(a,e,t){let n=a.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(` +`).map(r=>{let o=r.match(t.other.beginningSpace);if(o===null)return r;let[i]=o;return r.slice(Math.min(i.length,s.length))}).join(` +`)}function $e(a,e,t,n){if(!e.includes("<"))return!1;for(let s=0;se.length-s)return!0;s+=o[0].length-1}}return!1}var _=class{options;rules;lexer;constructor(e){this.options=e||y}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:pe(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=At(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=z(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceTabChar.test(s))&&(n=s.trim())}return{type:"heading",raw:z(t[0],` +`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:z(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=z(t[0],` +`).split(` +`),s="",r="",o=[];for(;n.length>0;){let i=!1,l=[],u;for(u=0;ub+V(x,b.length)).replace(this.rules.other.blockquoteSetextReplace,` + $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s} +${h}`:h,r=r?`${r} +${p}`:p;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,o,!0),this.lexer.state.top=d,n.length===0)break;let g=o.at(-1);if(g?.type==="code"||g?.type==="heading"||g?.type==="hr"||g?.type==="html")break;if(g?.type==="blockquote"){let k=g,b=n.join(` +`),x=k.raw+` +`+b.replace(this.rules.other.blockquoteSetextReplace2,""),f=this.blockquote(x);o[o.length-1]=f;let S=x.substring(f.raw.length).replace(/^\n/,""),R=S?S.split(` +`).length:0,C=R?n.slice(0,-R):n;C.length>0&&(s=`${s} +${C.join(` +`)}`),r=r.substring(0,r.length-k.text.length)+f.text;break}else if(g?.type==="list"){let k=g,b=k.raw+` +`+n.join(` +`),x=this.list(b);o[o.length-1]=x;let f=x.raw.length>k.raw.length?b.slice(k.raw.length+1,x.raw.length).split(` +`).length:0;if(f>0){let S=n.slice(0,f).join(` +`);s=`${s} +${S}`,r=`${r} +${S}`}n=n.slice(f);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=e,s=()=>n.length-e.length,r=t[1].trim(),o=r.length>1,i={type:"list",raw:"",ordered:o,start:o?+r.slice(0,-1):"",loose:!1,items:[]};r=o?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=o?r:"[*+-]");let l=this.rules.other.listItemRegex(r),u=!1;for(;e;){let p=!1,d="";if(!(t=l.exec(e))||this.rules.block.hr.test(e))break;let g=s();e=e.substring(t[0].length);let k=t[2].split(` +`,1)[0],b=t[1].length,x=this.options.pedantic?V(k,b):k.replace(this.rules.other.leadingSpaceTab,Q=>V(Q,b)),f=e.split(` +`,1)[0],S=!x.trim(),R=0;if(this.options.pedantic?(R=2,d=x.trimStart()):S?R=b+1:(R=x.search(this.rules.other.nonSpaceChar),R=R>4?1:R,d=x.slice(R),R+=b),S&&this.rules.other.blankLine.test(f)&&(e=e.substring(f.length+1),p=!0),!p){let Q=this.rules.other.nextBulletRegex(R),E=this.rules.other.hrRegex(R),j=this.rules.other.fencesBeginRegex(R),F=this.options.pedantic?this.rules.other.pedanticHeadingBeginRegex(R):this.rules.other.headingBeginRegex(R),Le=this.rules.other.htmlBeginRegex(R),Ae=this.rules.other.blockquoteBeginRegex(R);for(;e;){let he=e.split(` +`,1)[0],Z;if(f=he,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),Z=f):Z=f.replace(this.rules.other.leadingSpaceTab,de=>V(de)),j.test(f)||F.test(f)||Le.test(f)||Ae.test(f)||Q.test(f)||E.test(f))break;if(Z.search(this.rules.other.nonSpaceChar)>=R||!f.trim())d+=` +`+Z.slice(R);else{if(S||x.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||j.test(x)||F.test(x)||E.test(x))break;let ze=!this.options.pedantic&&/^ {0,3}(?:=+|-+) *$/.test(f)&&this.rules.block.lheading.test(`${x} +${f}`)?` ${Z.replace(/^ {0,3}/,"")}`:f;d+=` +`+ze}S=!f.trim(),e=e.substring(he.length+1),x=Z.slice(R)}}let C=n.slice(g,s());i.loose||(u?i.loose=!0:this.rules.other.doubleBlankLine.test(C)&&(u=!0)),i.items.push({type:"list_item",raw:C,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]})}let h=i.items.at(-1);if(h)h.raw=h.raw.trimEnd(),h.text=h.text.trimEnd();else return;i.raw=n.slice(0,s()).trimEnd();for(let p of i.items)if(this.lexer.state.top=!1,p.tokens=this.lexer.blockTokens(p.text,[]),!i.loose){let d=p.tokens.filter(k=>k.type==="space"),g=d.length>0&&d.some(k=>this.rules.other.anyLine.test(k.raw));i.loose=g}for(let p of i.items){let d=p.tokens[0];if(p.task&&(d?.type==="text"||d?.type==="paragraph")){p.text=p.text.replace(this.rules.other.listReplaceTask,""),d.raw=d.raw.replace(this.rules.other.listReplaceTask,""),d.text=d.text.replace(this.rules.other.listReplaceTask,"");for(let k=this.lexer.inlineQueue.length-1;k>=0;k--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[k].src)){this.lexer.inlineQueue[k].src=this.lexer.inlineQueue[k].src.replace(this.rules.other.listReplaceTask,"");break}let g=this.rules.other.listTaskCheckbox.exec(p.raw);if(g){let k={type:"checkbox",raw:g[0]+" ",checked:g[0]!=="[ ]"};p.checked=k.checked,i.loose?p.tokens[0]&&["paragraph","text"].includes(p.tokens[0].type)&&"tokens"in p.tokens[0]&&p.tokens[0].tokens?(p.tokens[0].raw=k.raw+p.tokens[0].raw,p.tokens[0].text=k.raw+p.tokens[0].text,p.tokens[0].tokens.unshift(k)):p.tokens.unshift({type:"paragraph",raw:k.raw,text:k.raw,tokens:[k]}):p.tokens.unshift(k)}}else p.task&&(p.task=!1)}if(i.loose)for(let p of i.items){p.loose=!0;for(let d of p.tokens)d.type==="text"&&(d.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=pe(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){if(!this.rules.other.startAngleBracket.test(t[2])&&ce(t[2],"()")!==-1)return;let n=N(t[1]).replace(this.rules.other.multipleSpaceGlobal," "),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:z(t[0],` +`),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=ue(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(` +`):[],o={type:"table",raw:z(t[0],` +`),header:[],align:[],rows:[]};if(n.length===s.length){for(let i of s)this.rules.other.tableAlignRight.test(i)?o.align.push("right"):this.rules.other.tableAlignCenter.test(i)?o.align.push("center"):this.rules.other.tableAlignLeft.test(i)?o.align.push("left"):o.align.push(null);for(let i=0;i({text:l,tokens:this.lexer.inline(l),header:!1,align:o.align[u]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:z(t[0],` +`),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===` +`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){if(this.lexer.state.linkParenPossible===!1)return;let t=this.rules.inline.link.exec(e);if(t){let n=t[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&$e(e,t[1],n,this.rules))return;let s=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let i=z(s.slice(0,-1),"\\");if((s.length-i.length)%2===0)return}else{let i=ce(t[2],"()");if(i===-2)return;if(i>-1){let u=(t[0].indexOf("!")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,u).trim(),t[3]=""}}let r=t[2],o="";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(r);i&&(r=i[1],o=i[3])}else o=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?r=r.slice(1):r=r.slice(1,-1)),_e(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=n[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&$e(e,n[1],s,this.rules))return;let r=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),o=t[N(r)];if(!o){let i=n[0].charAt(0);return{type:"text",raw:i,text:i}}return _e(n,o,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||!s[1]&&!s[2]&&!s[3]&&!s[4])return;let r=s[0][0],o=n===r,i=t.length-e.length,l=i;for(;!this.options.pedantic&&l>0&&t[l-1]===r;)l--;let u=[...t.slice(Math.max(0,l-2),l)].at(-1)??"",h=u==="*"||u==="_"||!!this.rules.inline.punctuation.exec(u);l0)continue;b=Math.min(b,b+x+f);let Q=[...s[0]][0].length,E=e.slice(0,g+s.index+Q+b);if(Math.min(g,b)%2){let F=E.slice(1,-1);return{type:"em",raw:E,text:F,tokens:this.lexer.inlineTokens(F)}}let j=E.slice(2,-2);return{type:"strong",raw:E,text:j,tokens:this.lexer.inlineTokens(j)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.delLDelim.exec(e);if(!s)return;if(!(s[1]||"")||!n||this.rules.inline.punctuation.exec(n)){let o=[...s[0]].length-1,i,l,u=o,h=this.rules.inline.delRDelim;for(h.lastIndex=0,t=t.slice(-1*e.length+o);(s=h.exec(t))!==null;){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(l=[...i].length,l!==o))continue;if(s[3]||s[4]){u+=l;continue}if(u-=l,u>0)continue;l=Math.min(l,l+u);let p=[...s[0]][0].length,d=e.slice(0,o+s.index+p+l),g=d.slice(o,-o);return{type:"del",raw:d,text:g,tokens:this.lexer.inlineTokens(g)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],text:n,href:s,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:n?t[0]:Se(t[0]),escaped:n}}}};var O=class a{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||y,this.options.tokenizer=this.options.tokenizer||new _,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0};let t={other:T,block:X.normal,inline:G.normal};this.options.pedantic?(t.block=X.pedantic,t.inline=G.pedantic):this.options.gfm&&(t.block=X.gfm,this.options.breaks?t.inline=G.breaks:t.inline=G.gfm),this.tokenizer.rules=t}static get rules(){return{block:X,inline:G}}static lex(e,t){return new a(t).lex(e)}static lexInline(e,t){return new a(t).inlineTokens(e)}lex(e){e=e.replace(T.carriageReturn,` +`),this.blockTokens(e,this.tokens);for(let t=0;t(r=i.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let i=t.at(-1);r.raw.length===1&&i!==void 0?i.raw+=` +`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="paragraph"||i?.type==="text"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+r.raw,i.text+=` +`+r.text,this.inlineQueue.at(-1).src=i.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="paragraph"||i?.type==="text"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+r.raw,i.text+=` +`+r.raw,this.inlineQueue.at(-1).src=i.text):(this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title}),t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let o=e;if(this.options.extensions?.startBlock){let i=1/0,l=e.slice(1),u;this.options.extensions.startBlock.forEach(h=>{u=h.call({lexer:this},l),typeof u=="number"&&u>=0&&(i=Math.min(i,u))}),i<1/0&&i>=0&&(o=e.substring(0,i+1))}if(this.state.top&&(r=this.tokenizer.paragraph(o))){let i=t.at(-1);n&&i?.type==="paragraph"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+r.raw,i.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):t.push(r),n=o.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="text"?(i.raw+=(i.raw.endsWith(` +`)?"":` +`)+r.raw,i.text+=` +`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes("["))return!1;let t=this.tokenizer.rules.inline.link;for(let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(n[0])&&e.charAt(n.index-1)!=="!")return!0;for(let n of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let s=n[0],r=s.lastIndexOf("[");if(!(s.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,N(s.slice(r+1,-1))))&&!(r>1&&this.linkInText(s.slice(1,r-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=n&&e.includes(")");try{return this.#e(e,t)}finally{this.state.linkParenPossible=n}}#e(e,t){let n=e.includes("*")||e.includes("_")||e.includes("~")||this.options.hooks?.emStrongMask||this.tokenizer.emStrong!==_.prototype.emStrong||this.tokenizer.del!==_.prototype.del?this.#t(e):e,s=!1,r="",o=1/0;for(;e;){if(e.length(i=u.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.escape(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.tag(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.link(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(i.raw.length);let u=t.at(-1);i.type==="text"&&u?.type==="text"?(u.raw+=i.raw,u.text+=i.text):t.push(i);continue}if(i=this.tokenizer.emStrong(e,n,r)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.codespan(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.br(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.del(e,n,r)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.autolink(e)){e=e.substring(i.raw.length),t.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(e))){e=e.substring(i.raw.length),t.push(i);continue}let l=e;if(this.options.extensions?.startInline){let u=1/0,h=e.slice(1),p;this.options.extensions.startInline.forEach(d=>{p=d.call({lexer:this},h),typeof p=="number"&&p>=0&&(u=Math.min(u,p))}),u<1/0&&u>=0&&(l=e.substring(0,u+1))}if(i=this.tokenizer.inlineText(l)){e=e.substring(i.raw.length),i.raw.slice(-1)!=="_"&&(r=i.raw.slice(-1)),s=!0;let u=t.at(-1);u?.type==="text"?(u.raw+=i.raw,u.text+=i.text):t.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}#t(e){let t=e;if(this.tokens.links&&e.includes("[")){let n=this.tokenizer.rules.inline.reflinkSearch,s=r=>{let o=r.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,N(r.slice(o+1,-1))))return r;if(o>1&&r.charAt(0)!=="!"){let i=r.slice(1,o-1);if(this.linkInText(i))return"["+i.replace(n,s)+"]["+"a".repeat(r.length-o-2)+"]"}return"["+"a".repeat(r.length-2)+"]"};t=t.replace(n,s)}return t=t.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(n,s,r)=>r?"+".repeat(n.length):s?s+n.slice(s.length,-s.length).replace(/`/g,"+")+s:n),t=t.replace(this.tokenizer.rules.inline.blockSkip,(n,s,r)=>{let o=r?r.length:0;return n.slice(0,o)+"["+"a".repeat(n.length-o-2)+"]"}),t=this.options.hooks?.emStrongMask?.call({lexer:this},t)??t,t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}};var L=class{options;parser;constructor(e){this.options=e||y}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(T.notSpaceStart)?.[0],r=e?e.replace(T.endingNewline,"")+` +`:"";return s?'
'+(n?r:P(r,!0))+`
+`:"
"+(n?r:P(r,!0))+`
+`}blockquote({tokens:e}){return`
+${this.parser.parse(e)}
+`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`${this.parser.parseInline(e)} +`}hr(e){return`
+`}list(e){let t=e.ordered,n=e.start,s="";for(let i=0;i +`+s+" +`}listitem(e){return`
  • ${this.parser.parse(e.tokens)}
  • +`}checkbox({checked:e}){return" '}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t="",n="";for(let r=0;r${s}`),` + +`+t+` +`+s+`
    +`}tablerow({text:e}){return` +${e} +`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+` +`}strong({tokens:e}){return`${this.parser.parseInline(e)}`}em({tokens:e}){return`${this.parser.parseInline(e)}`}codespan({text:e}){return`${P(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,text:n,tokens:s,autolink:r}){let o=r?P(n,!0):this.parser.parseInline(s),i=le(e);if(i===null)return o;e=P(i,r);let l='
    ",l}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=le(e);if(r===null)return P(n);e=r;let o=`${P(n)}{let i=r[o].flat(1/0);D(n,this.walkTokens(i,t))}):r.tokens&&D(n,this.walkTokens(r.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...i){let l=r.renderer.apply(this,i);return l===!1&&(l=o.apply(this,i)),l}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new L(this.defaults);for(let o in n.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let i=o,l=n.renderer[i],u=r[i];r[i]=(...h)=>{let p=l.apply(r,h);return p===!1&&(p=u.apply(r,h)),p||""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new _(this.defaults);for(let o in n.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let i=o,l=n.tokenizer[i],u=r[i];r[i]=(...h)=>{let p=l.apply(r,h);return p===!1&&(p=u.apply(r,h)),p}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new A;for(let o in n.hooks){if(!(o in r))throw new Error(`hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let i=o,l=n.hooks[i],u=r[i];A.passThroughHooks.has(o)?r[i]=h=>{if(r.options.async&&A.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await l.call(r,h);return u.call(r,d)})();let p=l.call(r,h);return u.call(r,p)}:r[i]=(...h)=>{if(r.options.async)return(async()=>{let d=await l.apply(r,h);return d===!1&&(d=await u.apply(r,h)),d})();let p=l.apply(r,h);return p===!1&&(p=u.apply(r,h)),p}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,o=n.walkTokens;s.walkTokens=function(i){let l=[];return l.push(o.call(this,i)),r&&D(l,r.call(this,i)),l}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return O.lex(e,t??this.defaults)}parser(e,t){return w.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let r={...s},o={...this.defaults,...r},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let l=o.hooks?await o.hooks.preprocess(n):n,h=await(o.hooks?await o.hooks.provideLexer(e):e?O.lex:O.lexInline)(l,o),p=o.hooks?await o.hooks.processAllTokens(h):h;o.walkTokens&&await Promise.all(this.walkTokens(p,o.walkTokens));let g=await(o.hooks?await o.hooks.provideParser(e):e?w.parse:w.parseInline)(p,o);return o.hooks?await o.hooks.postprocess(g):g})().catch(i);try{o.hooks&&(n=o.hooks.preprocess(n));let u=(o.hooks?o.hooks.provideLexer(e):e?O.lex:O.lexInline)(n,o);o.hooks&&(u=o.hooks.processAllTokens(u)),o.walkTokens&&this.walkTokens(u,o.walkTokens);let p=(o.hooks?o.hooks.provideParser(e):e?w.parse:w.parseInline)(u,o);return o.hooks&&(p=o.hooks.postprocess(p)),p}catch(l){return i(l)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let s="

    An error occurred:

    "+P(n.message+"",!0)+"
    ";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}};var q=new J;function m(a,e){return q.parse(a,e)}m.options=m.setOptions=function(a){return q.setOptions(a),m.defaults=q.defaults,ee(m.defaults),m};m.getDefaults=v;m.defaults=y;function zt(...a){return q.use(...a),m.defaults=q.defaults,ee(m.defaults),m}m.use=zt;m.walkTokens=function(a,e){return q.walkTokens(a,e)};m.parseInline=q.parseInline;m.Parser=w;m.parser=w.parse;m.Renderer=L;m.TextRenderer=M;m.Lexer=O;m.lexer=O.lex;m.Tokenizer=_;m.Hooks=A;m.parse=m;var Tn=m.options,On=m.setOptions,wn=m.walkTokens,Pn=m.parseInline,yn=m,Sn=w.parse,_n=O.lex;export{A as Hooks,O as Lexer,J as Marked,w as Parser,L as Renderer,M as TextRenderer,_ as Tokenizer,y as defaults,v as getDefaults,_n as lexer,m as marked,Tn as options,yn as parse,Pn as parseInline,Sn as parser,On as setOptions,zt as use,wn as walkTokens}; diff --git a/app/static/vendor/purify.es.mjs b/app/static/vendor/purify.es.mjs new file mode 100644 index 0000000..26d8256 --- /dev/null +++ b/app/static/vendor/purify.es.mjs @@ -0,0 +1,9 @@ +/** + * Minified by jsDelivr using Terser v5.48.0. + * Original file: /npm/dompurify@3.4.17/dist/purify.es.mjs + * + * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files + */ +/*! @license DOMPurify 3.4.17 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.17/LICENSE */ +function _OverloadYield(e,t){this.v=e,this.k=t}function _arrayLikeToArray(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n2?n-2:0),o=2;o1?t-1:0),r=1;r1?n-1:0),o=1;o2&&void 0!==arguments[2]?arguments[2]:stringToLowerCase;if(setPrototypeOf&&setPrototypeOf(e,null),!arrayIsArray(t))return e;let r=t.length;for(;r--;){let o=t[r];if("string"==typeof o){const e=n(o);e!==o&&(isFrozen(t)||(t[r]=e),o=e)}e[o]=!0}return e}function cleanArray(e){for(let t=0;t/g),TMPLIT_EXPR=seal(/\${[\w\W]*/g),DATA_ATTR=seal(/^data-[\-\w.\u00B7-\uFFFF]+$/),ARIA_ATTR=seal(/^aria-[\-\w]+$/),IS_ALLOWED_URI=seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),IS_SCRIPT_OR_DATA=seal(/^(?:\w+script|data):/i),ATTR_WHITESPACE=seal(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),DOCTYPE_NAME=seal(/^html$/i),CUSTOM_ELEMENT=seal(/^[a-z][.\w]*(-[.\w]+)+$/i),ELEMENT_MARKUP_PROBE=seal(/<[/\w!]/g),COMMENT_MARKUP_PROBE=seal(/<[/\w]/g),FALLBACK_TAG_CLOSE=seal(/<\/no(script|embed|frames)/i),SELF_CLOSING_TAG=seal(/\/>/i),NODE_TYPE={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},LITERAL_TEXT_ELEMENTS=freeze(addToSet({},["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"])),getGlobal=function(){return"undefined"==typeof window?null:window},_createTrustedTypesPolicy=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let n=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(n=t.getAttribute(r));const o="dompurify"+(n?"#"+n:"");try{return e.createPolicy(o,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+o+" could not be created."),null}},_createHooksMap=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},_resolveSetOption=function(e,t,n,r){return objectHasOwnProperty(e,t)&&arrayIsArray(e[t])?addToSet(r.base?clone(r.base):{},e[t],r.transform):n},_resolveObjectOption=function(e,t,n){const r=objectHasOwnProperty(e,t)?e[t]:void 0;return r&&"object"==typeof r?clone(r):n()};function createDOMPurify(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:getGlobal();const t=e=>createDOMPurify(e);if(t.version="3.4.17",t.removed=[],!e||!e.document||e.document.nodeType!==NODE_TYPE.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const r=n,o=r.currentScript;e.DocumentFragment;const a=e.HTMLTemplateElement,i=e.Node,l=e.Element,s=e.NodeFilter;void 0===e.NamedNodeMap&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const c=e.DOMParser,u=e.trustedTypes,p=l.prototype,f=lookupGetter(p,"cloneNode"),d=lookupGetter(p,"remove"),m=lookupGetter(p,"removeAttributeNode"),y=lookupGetter(p,"nextSibling"),g=lookupGetter(p,"childNodes"),h=lookupGetter(p,"parentNode"),T=lookupGetter(p,"shadowRoot"),E=lookupGetter(p,"attributes"),b=i&&i.prototype?lookupGetter(i.prototype,"nodeType"):null,S=i&&i.prototype?lookupGetter(i.prototype,"nodeName"):null,_=i&&i.prototype?lookupGetter(i.prototype,"ownerDocument"):null,A=function(e){return b?b(e):e.nodeType},O=function(e){return S?S(e):e.nodeName},v=lookupAccessor(p,"namespaceURI"),w=function(e){return v?v(e):e.namespaceURI};if("function"==typeof a){const e=n.createElement("template");e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let x,P,N="",R=!1,D=0;const C=function(){if(D>0)throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or createScriptURL) must not call DOMPurify.sanitize, as that causes infinite recursion. Do not pass a policy whose callbacks wrap DOMPurify as TRUSTED_TYPES_POLICY; see the "DOMPurify and Trusted Types" section of the README.')},k=function(e){C(),D++;try{return x.createHTML(e)}finally{D--}},L=n,I=L.implementation,M=L.createNodeIterator,z=L.createDocumentFragment,F=L.getElementsByTagName,H=r.importNode;let U=_createHooksMap();t.isSupported="function"==typeof entries&&"function"==typeof h&&I&&void 0!==I.createHTMLDocument;const j=MUSTACHE_EXPR,Y=ERB_EXPR,G=TMPLIT_EXPR,B=DATA_ATTR,W=ARIA_ATTR,$=IS_SCRIPT_OR_DATA,K=ATTR_WHITESPACE,X=CUSTOM_ELEMENT;let q=IS_ALLOWED_URI,V=null;const Z=addToSet({},[...html$1,...svg$1,...svgFilters,...mathMl$1,...text]);let J=null;const Q=addToSet({},[...html,...svg,...mathMl,...xml]);let ee=Object.seal(create(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),te=null,ne=null;const re=Object.seal(create(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let oe=!0,ae=!0,ie=!1,le=!0,se=!1,ce=!0,ue=!1,pe=!1,fe=null,de=null,me=!1,ye=!1,ge=!1,he=!1,Te=!0,Ee=!1;const be="user-content-";let Se=!0,_e=!1,Ae=null,Oe={},ve=null;const we=addToSet({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let xe=null;const Pe=addToSet({},["audio","video","img","source","image","track"]);let Ne=null;const Re=addToSet({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),De="http://www.w3.org/1998/Math/MathML",Ce="http://www.w3.org/2000/svg",ke="http://www.w3.org/1999/xhtml";let Le=ke,Ie=!1,Me=null;const ze=addToSet({},[De,Ce,ke],stringToString),Fe=freeze(["mi","mo","mn","ms","mtext"]);let He=addToSet({},Fe);const Ue=freeze(["annotation-xml"]);let je=addToSet({},Ue);const Ye=addToSet({},["title","style","font","a","script"]);let Ge=null;const Be=["application/xhtml+xml","text/html"];let We=null,$e=null;const Ke=n.createElement("form"),Xe=function(e){return e instanceof RegExp||e instanceof Function},qe=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if($e&&$e===e)return;e&&"object"==typeof e||(e={}),e=clone(e),Ge=-1===Be.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,We="application/xhtml+xml"===Ge?stringToString:stringToLowerCase,V=_resolveSetOption(e,"ALLOWED_TAGS",Z,{transform:We}),J=_resolveSetOption(e,"ALLOWED_ATTR",Q,{transform:We}),Me=_resolveSetOption(e,"ALLOWED_NAMESPACES",ze,{transform:stringToString}),Ne=_resolveSetOption(e,"ADD_URI_SAFE_ATTR",Re,{transform:We,base:Re}),xe=_resolveSetOption(e,"ADD_DATA_URI_TAGS",Pe,{transform:We,base:Pe}),ve=_resolveSetOption(e,"FORBID_CONTENTS",we,{transform:We}),te=_resolveSetOption(e,"FORBID_TAGS",clone({}),{transform:We}),ne=_resolveSetOption(e,"FORBID_ATTR",clone({}),{transform:We}),Oe=!!objectHasOwnProperty(e,"USE_PROFILES")&&(e.USE_PROFILES&&"object"==typeof e.USE_PROFILES?clone(e.USE_PROFILES):e.USE_PROFILES),oe=!1!==e.ALLOW_ARIA_ATTR,ae=!1!==e.ALLOW_DATA_ATTR,ie=e.ALLOW_UNKNOWN_PROTOCOLS||!1,le=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,se=e.SAFE_FOR_TEMPLATES||!1,ce=!1!==e.SAFE_FOR_XML,ue=e.WHOLE_DOCUMENT||!1,ye=e.RETURN_DOM||!1,ge=e.RETURN_DOM_FRAGMENT||!1,he=e.RETURN_TRUSTED_TYPE||!1,me=e.FORCE_BODY||!1,Te=!1!==e.SANITIZE_DOM,Ee=e.SANITIZE_NAMED_PROPS||!1,Se=!1!==e.KEEP_CONTENT,_e=e.IN_PLACE||!1,q=isRegex(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:IS_ALLOWED_URI,Le="string"==typeof e.NAMESPACE?e.NAMESPACE:ke,He=_resolveObjectOption(e,"MATHML_TEXT_INTEGRATION_POINTS",()=>addToSet({},Fe)),je=_resolveObjectOption(e,"HTML_INTEGRATION_POINTS",()=>addToSet({},Ue));const t=_resolveObjectOption(e,"CUSTOM_ELEMENT_HANDLING",()=>create(null));if(ee=create(null),objectHasOwnProperty(t,"tagNameCheck")&&Xe(t.tagNameCheck)&&(ee.tagNameCheck=t.tagNameCheck),objectHasOwnProperty(t,"attributeNameCheck")&&Xe(t.attributeNameCheck)&&(ee.attributeNameCheck=t.attributeNameCheck),objectHasOwnProperty(t,"allowCustomizedBuiltInElements")&&"boolean"==typeof t.allowCustomizedBuiltInElements&&(ee.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),seal(ee),se&&(ae=!1),ge&&(ye=!0),Oe&&(V=addToSet({},text),J=create(null),!0===Oe.html&&(addToSet(V,html$1),addToSet(J,html)),!0===Oe.svg&&(addToSet(V,svg$1),addToSet(J,svg),addToSet(J,xml)),!0===Oe.svgFilters&&(addToSet(V,svgFilters),addToSet(J,svg),addToSet(J,xml)),!0===Oe.mathMl&&(addToSet(V,mathMl$1),addToSet(J,mathMl),addToSet(J,xml))),re.tagCheck=null,re.attributeCheck=null,objectHasOwnProperty(e,"ADD_TAGS")&&("function"==typeof e.ADD_TAGS?re.tagCheck=e.ADD_TAGS:arrayIsArray(e.ADD_TAGS)&&(V===Z&&(V=clone(V)),addToSet(V,e.ADD_TAGS,We))),objectHasOwnProperty(e,"ADD_ATTR")&&("function"==typeof e.ADD_ATTR?re.attributeCheck=e.ADD_ATTR:arrayIsArray(e.ADD_ATTR)&&(J===Q&&(J=clone(J)),addToSet(J,e.ADD_ATTR,We))),objectHasOwnProperty(e,"ADD_FORBID_CONTENTS")&&arrayIsArray(e.ADD_FORBID_CONTENTS)&&(ve===we&&(ve=clone(ve)),addToSet(ve,e.ADD_FORBID_CONTENTS,We)),Se&&(V["#text"]=!0),ue&&addToSet(V,["html","head","body"]),V.table&&(addToSet(V,["tbody"]),delete te.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const t=x;x=e.TRUSTED_TYPES_POLICY;try{N=k("")}catch(e){throw x=t,e}}else null===e.TRUSTED_TYPES_POLICY?(x=void 0,N=""):(void 0===x&&(R||(P=_createTrustedTypesPolicy(u,o),R=!0),x=P),x&&"string"==typeof N&&(N=k("")));freeze&&freeze(e),$e=e},Ve=addToSet({},[...svg$1,...svgFilters,...svgDisallowed]),Ze=addToSet({},[...mathMl$1,...mathMlDisallowed]),Je=function(e){const t=w(e),n=stringToLowerCase(O(e)),r=h(e);let o,a;return r&&A(r)===NODE_TYPE.element?(o={namespaceURI:w(r)},a=stringToLowerCase(O(r))):(o={namespaceURI:Le},a="template"),!!Me[t]&&(t===Ce?function(e,t,n){return t.namespaceURI===ke?"svg"===e:t.namespaceURI===De?"svg"===e&&("annotation-xml"===n||He[n]):Boolean(Ve[e])}(n,o,a):t===De?function(e,t,n){return t.namespaceURI===ke?"math"===e:t.namespaceURI===Ce?"math"===e&&je[n]:Boolean(Ze[e])}(n,o,a):t===ke?function(e,t,n){return!(t.namespaceURI===Ce&&!je[n])&&!(t.namespaceURI===De&&!He[n])&&!Ze[e]&&(Ye[e]||!Ve[e])}(n,o,a):!("application/xhtml+xml"!==Ge||!Me[t]))},Qe=function(e){arrayPush(t.removed,{element:e});try{h(e).removeChild(e)}catch(t){if(d(e),!h(e))throw typeErrorCreate("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},et=function(e,t,n){try{m(e,t)}catch(t){try{e.removeAttribute(n)}catch(e){}}},tt=function(e){at(e);const t=g(e);t&&arrayForEach(arraySlice(t),e=>{try{d(e)}catch(e){}});const n=A(e)===NODE_TYPE.element?E(e):null;if(n)for(let t=n.length-1;t>=0;--t){const r=n[t],o=r&&r.name;"string"==typeof o&&et(e,r,o)}},nt=function(e,n,r){if(!r)try{r=n.getAttributeNode(e)}catch(e){r=null}arrayPush(t.removed,{attribute:r||null,from:n});try{r?m(n,r):n.removeAttribute(e)}catch(t){try{n.removeAttribute(e)}catch(e){}}if("is"===e)if(ye||ge)try{Qe(n)}catch(e){}else try{n.setAttribute(e,"")}catch(e){}},rt=function(e){const t=E(e);if(t)for(let n=t.length-1;n>=0;--n){const r=t[n],o=r&&r.name;"string"!=typeof o||J[We(o)]||et(e,r,o)}},ot=function(e,t){let n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];const r=[e];for(;r.length>0;){const e=r.pop();if(!1===t(e))continue;if(n&&A(e)===NODE_TYPE.element){const t=T(e);gt(t)&&r.push(t)}const o=g(e);if(o)for(let e=o.length-1;e>=0;--e)r.push(o[e])}},at=function(e){ot(e,e=>{A(e)===NODE_TYPE.element&&rt(e)})},it=function(e){const t=[];return ot(e,e=>{t.push(e)},!0),t},lt=function(e,n){let r=!1;return arrayForEach(t.removed,t=>{t.element&&(r=r||t.element===e,at(t.element))}),function(e,t){const n=setCreate();arrayForEach(it(e),e=>{A(e)===NODE_TYPE.element&&setAdd(n,e)}),arrayForEach(t,e=>{A(e)!==NODE_TYPE.element||setHas(n,e)||rt(e)})}(e,n),r},st=function(e,t,n,r){const o=pt(e);let a;for(;a=o.nextNode();)setHas(r,a)&&!setHas(Ae,a)&&(t&&Tt(U.uponSanitizeShadowNode,a,null),_t(a,n),Nt(a,n),gt(a.content)&&Rt(a.content))},ct=function(e,t){return!!ce&&("patchsrc"===e||"for"===e&&"label"!==t&&"output"!==t)},ut=function(e){let t=null,r=null;if(me)e=""+e;else{const t=stringMatch(e,/^[\r\n\t ]+/);r=t&&t[0]}"application/xhtml+xml"===Ge&&Le===ke&&(e=''+e+"");const o=x?k(e):e;if(Le===ke)try{t=(new c).parseFromString(o,Ge)}catch(e){}if(!t||!t.documentElement){t=I.createDocument(Le,"template",null);try{t.documentElement.innerHTML=Ie?N:o}catch(e){}}const a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Le===ke?F.call(t,ue?"html":"body")[0]:ue?t.documentElement:a},pt=function(e){const t=_?_(e):e.ownerDocument;return M.call(t||e,e,s.SHOW_ELEMENT|s.SHOW_COMMENT|s.SHOW_TEXT|s.SHOW_PROCESSING_INSTRUCTION|s.SHOW_CDATA_SECTION,null)},ft=function(e){return e=stringReplace(e,j," "),e=stringReplace(e,Y," "),e=stringReplace(e,G," ")},dt=function(e){var t;mt(e);const n=null===(t=e.querySelectorAll)||void 0===t?void 0:t.call(e,"template");n&&arrayForEach(n,e=>{gt(e.content)&&dt(e.content)})},mt=function(e){e.normalize();const t=_?_(e):e.ownerDocument,n=M.call(t||e,e,s.SHOW_TEXT|s.SHOW_COMMENT|s.SHOW_CDATA_SECTION|s.SHOW_PROCESSING_INSTRUCTION,null);let r=n.nextNode();for(;r;)r.data=ft(r.data),r=n.nextNode()},yt=function(e){const t=S?S(e):null;return"string"==typeof t&&("form"===We(t)&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||e.attributes!==E(e)||"function"!=typeof e.removeAttribute||"function"!=typeof e.removeAttributeNode||"function"!=typeof e.getAttributeNode||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes||e.nodeType!==b(e)||e.childNodes!==g(e)))},gt=function(e){if(!b||"object"!=typeof e||null===e)return!1;try{return b(e)===NODE_TYPE.documentFragment}catch(e){return!1}},ht=function(e){if(!b||"object"!=typeof e||null===e)return!1;try{return"number"==typeof b(e)}catch(e){return!1}};function Tt(e,n,r){0!==e.length&&arrayForEach(e,e=>{e.call(t,n,r,$e)})}const Et=function(e,t){if(e instanceof RegExp)return regExpTest(e,t);if(e instanceof Function){for(var n=arguments.length,r=new Array(n>2?n-2:0),o=2;o=0;--o){const a=e===n?f(r[o],!0):r[o];t.insertBefore(a,y(e))}}return Qe(e),!0}(e,o,n);return!(!1!==t||(Tt(U.afterSanitizeElements,e,null),!St(e,n)))||t}if(A(e)===NODE_TYPE.element&&!Je(e))return Qe(e),!0;if(("noscript"===o||"noembed"===o||"noframes"===o)&®ExpTest(FALLBACK_TAG_CLOSE,e.innerHTML))return Qe(e),!0;if(se&&e.nodeType===NODE_TYPE.text){const n=ft(e.textContent);e.textContent!==n&&(arrayPush(t.removed,{element:e.cloneNode()}),e.textContent=n)}return Tt(U.afterSanitizeElements,e,null),St(e,n)},At=function(e,t,r){if(ne[t])return!1;if(ct(t,e))return!1;if(Te&&("id"===t||"name"===t)&&(r in n||r in Ke))return!1;const o=J[t]||re.attributeCheck instanceof Function&&re.attributeCheck(t,e);return!(!ae||!regExpTest(B,t))||(!(!oe||!regExpTest(W,t))||(o?!!Ne[t]||(!!regExpTest(q,stringReplace(r,K,""))||(!("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==stringIndexOf(r,"data:")||!xe[e])||(!(!ie||regExpTest($,stringReplace(r,K,"")))||!r))):vt(e)&&Et(ee.tagNameCheck,e)&&Et(ee.attributeNameCheck,t,e)||"is"===t&&ee.allowCustomizedBuiltInElements&&Et(ee.tagNameCheck,r)))},Ot=addToSet({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),vt=function(e){return!Ot[stringToLowerCase(e)]&®ExpTest(X,e)},wt=function(e,t,n,r){if(x&&"object"==typeof u&&"function"==typeof u.getAttributeType&&!n)switch(u.getAttributeType(e,t)){case"TrustedHTML":return k(r);case"TrustedScriptURL":return function(e){C(),D++;try{return x.createScriptURL(e)}finally{D--}}(r)}return r},xt=function(e,t,n,r){try{return n?e.setAttributeNS(n,t,r):e.setAttribute(t,r),!yt(e)||(Qe(e),!1)}catch(n){return nt(t,e),!1}},Pt=function(e,t){return!(!ce||!regExpTest(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,t))||"attributename"===stringToLowerCase(e)&&null!==stringMatch(t,"href")},Nt=function(e,n){if(Tt(U.beforeSanitizeAttributes,e,null),St(e,n))return;const r=e.attributes;if(!r||yt(e))return;J=bt(U.uponSanitizeAttribute,J,Q,de);const o={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:J,forceKeepAttr:void 0};let a=r.length;const i=We(e.nodeName);for(;a--;){const n=r[a],l=n.name,s=n.namespaceURI,c=n.value,u=We(l),p=c;let f="value"===l?p:stringTrim(p),d=!1;o.attrName=u,o.attrValue=f,o.keepAttr=!0,o.forceKeepAttr=void 0,Tt(U.uponSanitizeAttribute,e,o),f=o.attrValue,!Ee||"id"!==u&&"name"!==u||0===stringIndexOf(f,be)||(nt(l,e,n),f=be+f,d=!0),Pt(l,f)?nt(l,e,n):o.forceKeepAttr||(o.keepAttr&&(le||!regExpTest(SELF_CLOSING_TAG,f))?(se&&(f=ft(f)),At(i,u,f)?(f=wt(i,u,s,f),f!==p&&xt(e,l,s,f)&&d&&arrayPop(t.removed)):nt(l,e,n)):nt(l,e,n))}Tt(U.afterSanitizeAttributes,e,null),St(e,n)},Rt=function(e){let t=null;const n=pt(e);for(Tt(U.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(Tt(U.uponSanitizeShadowNode,t,null),_t(t,e),Nt(t,e),gt(t.content)&&Rt(t.content),A(t)===NODE_TYPE.element){const e=T(t);gt(e)&&(Dt(e),Rt(e))}se&&mt(e),Tt(U.afterSanitizeShadowDOM,e,null)},Dt=function(e){const t=[{node:e,shadow:null}];for(;t.length>0;){const e=t.pop();if(e.shadow){Rt(e.shadow);continue}const n=e.node,r=A(n)===NODE_TYPE.element,o=g(n);if(o)for(let e=o.length-1;e>=0;--e)t.push({node:o[e],shadow:null});if(r){const e=S?S(n):null;if("string"==typeof e&&"template"===We(e)){const e=n.content;gt(e)&&t.push({node:e,shadow:null})}}if(r){const e=T(n);gt(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=null,a=null,i=null,l=null;if(Ie=!e,Ie&&(e="\x3c!--\x3e"),"string"!=typeof e&&!ht(e)&&"string"!=typeof(e=stringifyValue(e)))throw typeErrorCreate("dirty is not a string, aborting");if(!t.isSupported)return e;pe?(V=fe,J=de):qe(n),(U.uponSanitizeElement.length>0||U.uponSanitizeAttribute.length>0)&&(V=clone(V)),U.uponSanitizeAttribute.length>0&&(J=clone(J)),t.removed=[];const s=_e&&"string"!=typeof e&&ht(e);let c=[];const u=Ae;if(s){p=e,ce&&ot(p,e=>{const t=A(e);if(t===NODE_TYPE.processingInstruction||t===NODE_TYPE.comment&®ExpTest(COMMENT_MARKUP_PROBE,e.data)){try{d(e)}catch(e){}return!1}if(t===NODE_TYPE.element){const t=e,n=We(O(e));try{t.hasAttribute&&t.hasAttribute("patchsrc")&&t.removeAttribute("patchsrc"),t.hasAttribute&&t.hasAttribute("for")&&ct("for",n)&&t.removeAttribute("for")}catch(e){}}return!0});const t=O(e);if("string"==typeof t){const n=We(t);if(!V[n]||te[n])throw tt(e),typeErrorCreate("root node is forbidden and cannot be sanitized in-place")}if(yt(e))throw tt(e),typeErrorCreate("root node is clobbered and cannot be sanitized in-place");c=it(e),Ae=setCreate()}else if(ht(e))o=ut("\x3c!----\x3e"),a=o.ownerDocument.importNode(e,!0),a.nodeType===NODE_TYPE.element&&"BODY"===a.nodeName||"HTML"===a.nodeName?o=a:o.appendChild(a),Dt(o);else{if(!ye&&!se&&!ue&&-1===e.indexOf("<"))return x&&he?k(e):e;if(o=ut(e),!o)return ye?null:he?N:""}var p;o&&me&&Qe(o.firstChild);const f=s?e:o;try{s&&Dt(e);const t=pt(f);for(;i=t.nextNode();)_t(i,f),Nt(i,f),gt(i.content)&&Rt(i.content);s&&function(e,t){const n=Ae;let r=null;const o=()=>(r||(r=setCreate(),arrayForEach(t,e=>{setAdd(r,e)})),r);for(let t=0;;t++){const r=it(e),a=[e];let i=!1;if(arrayForEach(r,e=>{A(e)===NODE_TYPE.documentFragment?arrayPush(a,e):i||setHas(n,e)||(i=setHas(o(),e))}),!i)return;if(t>=8)throw typeErrorCreate("the tree kept changing during in-place sanitization; refusing to return it");arrayForEach(a,(t,n)=>{st(t,n>0,e,o())})}}(e,c)}catch(t){throw s&&(tt(e),lt(e,c)),t}finally{Ae=u}if(s){if(lt(e,c))throw typeErrorCreate("a node selected for removal could not be safely returned; refusing to sanitize in place");return se&&dt(e),e}if(ye){if(se&&dt(o),ge)for(l=z.call(o.ownerDocument);o.firstChild;)l.appendChild(o.firstChild);else l=o;return(J.shadowroot||J.shadowrootmode)&&(l=H.call(r,l,!0)),l}let m=ue?o.outerHTML:o.innerHTML;return ue&&V["!doctype"]&&o.ownerDocument&&o.ownerDocument.doctype&&o.ownerDocument.doctype.name&®ExpTest(DOCTYPE_NAME,o.ownerDocument.doctype.name)&&(m="\n"+m),se&&(m=ft(m)),x&&he?k(m):m},t.setConfig=function(){qe(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),pe=!0,fe=V,de=J},t.clearConfig=function(){$e=null,pe=!1,fe=null,de=null,x=P,N=""},t.isValidAttribute=function(e,t,n){$e||qe({});const r=We(e),o=We(t);return("string"!=typeof n||!(Pt(t,n)||!le&®ExpTest(SELF_CLOSING_TAG,n)))&&At(r,o,n)},t.addHook=function(e,t){"function"==typeof t&&objectHasOwnProperty(U,e)&&arrayPush(U[e],t)},t.removeHook=function(e,t){if(objectHasOwnProperty(U,e)){if(void 0!==t){const n=arrayLastIndexOf(U[e],t);return-1===n?void 0:arraySplice(U[e],n,1)[0]}return arrayPop(U[e])}},t.removeHooks=function(e){objectHasOwnProperty(U,e)&&(U[e]=[])},t.removeAllHooks=function(){U=_createHooksMap()},t}var purify_default=createDOMPurify();export{purify_default as default}; diff --git a/app/tools/__init__.py b/app/tools/__init__.py new file mode 100644 index 0000000..9290b70 --- /dev/null +++ b/app/tools/__init__.py @@ -0,0 +1 @@ +"""Server-side parts of tools. Each non-underscore module here must expose `router`.""" diff --git a/app/tools/paste.py b/app/tools/paste.py new file mode 100644 index 0000000..86d384f --- /dev/null +++ b/app/tools/paste.py @@ -0,0 +1,180 @@ +"""Pastebin: anonymous text pastes that expire 24 hours after creation. + +Storage is one SQLite file in $DATA_DIR. Expired pastes are invisible at once and +deleted by a sweep every few minutes. Anti-abuse is deliberately simple: a size cap +per paste, a cap on total live storage, and a per-IP creation rate limit. +""" + +import asyncio +import json +import os +import secrets +import sqlite3 +import threading +import time +from collections import defaultdict, deque +from pathlib import Path + +from fastapi import APIRouter, HTTPException, Request +from fastapi.responses import PlainTextResponse + +TTL = 24 * 3600 +MAX_BYTES = 1024 * 1024 # per paste +MAX_TOTAL_BYTES = 256 * 1024 * 1024 # all live pastes together +RATE_LIMIT = 30 # creations per IP ... +RATE_WINDOW = 3600 # ... per this many seconds +SWEEP_EVERY = 300 + +DB_PATH = Path(os.environ.get("DATA_DIR", "./data")) / "paste.db" + +router = APIRouter() +_lock = threading.Lock() +_recent: dict[str, deque] = defaultdict(deque) +_sweeper: asyncio.Task | None = None + + +def _db() -> sqlite3.Connection: + conn = sqlite3.connect(DB_PATH, timeout=10) + conn.row_factory = sqlite3.Row + return conn + + +def _init(): + DB_PATH.parent.mkdir(parents=True, exist_ok=True) + with _db() as c: + c.execute("PRAGMA journal_mode=WAL") + c.execute( + """CREATE TABLE IF NOT EXISTS pastes ( + id TEXT PRIMARY KEY, + content TEXT NOT NULL, + size INTEGER NOT NULL, + created_at INTEGER NOT NULL, + expires_at INTEGER NOT NULL, + delete_token TEXT NOT NULL + )""" + ) + c.execute("CREATE INDEX IF NOT EXISTS pastes_expires ON pastes(expires_at)") + + +def _sweep() -> int: + with _db() as c: + return c.execute("DELETE FROM pastes WHERE expires_at <= ?", (int(time.time()),)).rowcount + + +async def _sweep_loop(): + while True: + await asyncio.to_thread(_sweep) + await asyncio.sleep(SWEEP_EVERY) + + +async def startup(): + global _sweeper + _init() + _sweeper = asyncio.create_task(_sweep_loop()) + + +async def shutdown(): + if _sweeper: + _sweeper.cancel() + + +def client_ip(request: Request) -> str: + # uvicorn runs with --proxy-headers --forwarded-allow-ips 127.0.0.1, so behind + # a reverse proxy that connects over loopback this is already the visitor's address. + return request.client.host if request.client else "" + + +def _rate_limited(ip: str) -> bool: + now = time.monotonic() + with _lock: + q = _recent[ip] + while q and q[0] <= now - RATE_WINDOW: + q.popleft() + if len(q) >= RATE_LIMIT: + return True + q.append(now) + if len(_recent) > 10000: # drop idle entries so the map can't grow forever + for k in [k for k, v in _recent.items() if not v]: + del _recent[k] + return False + + +def _get(pid: str) -> sqlite3.Row: + with _db() as c: + row = c.execute( + "SELECT id, content, size, created_at, expires_at FROM pastes WHERE id = ? AND expires_at > ?", + (pid, int(time.time())), + ).fetchone() + if not row: + raise HTTPException(404, "This paste doesn't exist or has expired.") + return row + + +@router.post("/api/paste", status_code=201) +async def create(request: Request): + body = bytearray() + async for chunk in request.stream(): + body += chunk + if len(body) > MAX_BYTES + 64 * 1024: + raise HTTPException(413, "Paste is larger than 1 MiB.") + try: + data = json.loads(body) + content = data["content"] + assert isinstance(content, str) + except Exception: + raise HTTPException(400, 'Expected JSON: {"content": ""}') + size = len(content.encode()) + if not content.strip(): + raise HTTPException(400, "Paste is empty.") + if size > MAX_BYTES: + raise HTTPException(413, "Paste is larger than 1 MiB.") + if _rate_limited(client_ip(request)): + raise HTTPException(429, f"Too many pastes; the limit is {RATE_LIMIT} per hour.") + + now = int(time.time()) + pid, token = secrets.token_urlsafe(6), secrets.token_urlsafe(18) + with _lock, _db() as c: + used = c.execute("SELECT COALESCE(SUM(size), 0) FROM pastes WHERE expires_at > ?", (now,)).fetchone()[0] + if used + size > MAX_TOTAL_BYTES: + raise HTTPException(507, "The pastebin is full right now; try again later.") + c.execute( + "INSERT INTO pastes (id, content, size, created_at, expires_at, delete_token) VALUES (?, ?, ?, ?, ?, ?)", + (pid, content, size, now, now + TTL, token), + ) + return {"id": pid, "expires_at": now + TTL, "delete_token": token} + + +@router.get("/api/paste/{pid}") +def read(pid: str): + row = _get(pid) + return { + "id": row["id"], + "content": row["content"], + "size": row["size"], + "created_at": row["created_at"], + "expires_at": row["expires_at"], + } + + +@router.delete("/api/paste/{pid}", status_code=204) +def delete(pid: str, request: Request): + token = request.headers.get("x-delete-token", "") + with _db() as c: + row = c.execute("SELECT delete_token FROM pastes WHERE id = ?", (pid,)).fetchone() + if not row or not secrets.compare_digest(row["delete_token"], token): + raise HTTPException(404, "Not found, or wrong delete token.") + c.execute("DELETE FROM pastes WHERE id = ?", (pid,)) + + +@router.get("/raw/{pid}", response_class=PlainTextResponse) +def raw(pid: str): + row = _get(pid) + return PlainTextResponse( + row["content"], + headers={ + # Never let a paste act as a web page on this origin. + "Content-Security-Policy": "default-src 'none'; sandbox", + "X-Robots-Tag": "noindex", + "Cache-Control": "no-store", + }, + ) diff --git a/compose.yml b/compose.yml new file mode 100644 index 0000000..97d2a2f --- /dev/null +++ b/compose.yml @@ -0,0 +1,33 @@ +# Host networking + loopback bind: only a proxy or tunnel on the same host can reach it. +# It listens on 127.0.0.1:8090. +name: tools +services: + tools: + build: ./app + image: tools:latest + container_name: tools + restart: unless-stopped + network_mode: host + environment: + HOST: 127.0.0.1 + PORT: "8090" + volumes: + - ./data:/data + # Small and capped: it shares a small server with other workloads. + mem_limit: 192m + cpus: 0.5 + read_only: true + tmpfs: + - /tmp + security_opt: + - no-new-privileges:true + healthcheck: + test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8090/healthz', timeout=3)"] + interval: 30s + timeout: 5s + retries: 3 + logging: + driver: json-file + options: + max-size: 5m + max-file: "2" diff --git a/deploy.sh b/deploy.sh new file mode 100755 index 0000000..560854b --- /dev/null +++ b/deploy.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Deploy this checkout (including uncommitted changes) over SSH: +# HOST=root@ ./deploy.sh +# HOST=root@ ./deploy.sh # elsewhere +# Copies app/ and compose.yml to /opt/tools, rebuilds and restarts the container, +# then waits for it to report healthy. Paste data in /opt/tools/data is kept. +set -euo pipefail +HOST=${HOST:?set HOST=root@} +cd "$(dirname "$0")" +node --test tests/ >/dev/null || { echo "tests failed; not deploying" >&2; exit 1; } +tar -czf - --exclude=__pycache__ --exclude=data app compose.yml | + ssh "$HOST" 'set -e; mkdir -p /opt/tools && rm -rf /opt/tools/app && tar -xzf - -C /opt/tools' +ssh "$HOST" bash -s <<'REMOTE' +set -euo pipefail +cd /opt/tools +mkdir -p data && chown 10001:10001 data && chmod 700 data +docker compose up -d --build --remove-orphans +for i in $(seq 1 30); do + s=$(docker inspect -f '{{.State.Health.Status}}' tools 2>/dev/null || echo none) + [ "$s" = healthy ] && { echo "tools is healthy on 127.0.0.1:8090"; docker image prune -f >/dev/null; exit 0; } + sleep 2 +done +echo "tools did not become healthy:" >&2; docker logs --tail 50 tools >&2; exit 1 +REMOTE diff --git a/tests/json-core.test.mjs b/tests/json-core.test.mjs new file mode 100644 index 0000000..657600c --- /dev/null +++ b/tests/json-core.test.mjs @@ -0,0 +1,81 @@ +// node --test tests/ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { parse, stringify, sortKeys, nodeFromInput, JsonSyntaxError } from '../app/static/js/tools/json-core.js'; + +const sample = '{ "a" : 1, "big": 12345678901234567890, "f": 1.50e+10, "s": "x\\u00e9\\n y", "nested": { "arr": [ 1 , [ ], { } , true, false, null ] } }'; + +test('compact strips only structural whitespace', () => { + assert.equal(stringify(parse(sample), ''), '{"a":1,"big":12345678901234567890,"f":1.50e+10,"s":"x\\u00e9\\n y","nested":{"arr":[1,[],{},true,false,null]}}'); +}); + +test('pretty matches JSON.stringify for ordinary values', () => { + const plain = '{"a":[1,2,{"b":null}],"c":"d","e":{},"f":[]}'; + assert.equal(stringify(parse(plain), ' '), JSON.stringify(JSON.parse(plain), null, 2)); + assert.equal(stringify(parse(plain), '\t'), JSON.stringify(JSON.parse(plain), null, '\t')); +}); + +test('round trip is stable and value-preserving', () => { + const pretty = stringify(parse(sample), ' '); + assert.equal(stringify(parse(pretty), ''), stringify(parse(sample), '')); + assert.deepEqual(JSON.parse(pretty), JSON.parse(sample)); +}); + +test('duplicate keys and BOM survive', () => { + assert.equal(stringify(parse('{"a":1,"a":2}'), ''), '{"a":1,"a":2}'); +}); + +test('sortKeys', () => { + assert.equal(stringify(sortKeys(parse('{"b":1,"a":{"d":1,"c":2}}')), ''), '{"a":{"c":2,"d":1},"b":1}'); +}); + +const bad = { + '{"a":1,}': /Trailing comma/, + '[1,2,]': /Trailing comma/, + "{'a':1}": /double quotes/, + '{a:1}': /quoted/, + '{"a":1 "b":2}': /Expected ',' or '}'/, + '[1 2]': /Expected ',' or '\]'/, + '{"a": undefined}': /not valid in JSON/, + '01': /leading zeros/, + '"abc': /Unterminated/, + '"a\\x"': /Invalid escape/, + '{"a":1} x': /after the end/, + '// c\n{}': /Comments/, + '': /Empty/, + '{"a":': /end of input/, +}; +for (const [input, re] of Object.entries(bad)) { + test(`rejects ${JSON.stringify(input)}`, () => { + assert.throws(() => parse(input), (e) => e instanceof JsonSyntaxError && re.test(e.message)); + }); +} + +test('error position', () => { + try { parse('{\n "a": 1,\n "b" 2\n}'); } catch (e) { assert.equal(e.line, 3); assert.equal(e.col, 7); return; } + assert.fail('no error'); +}); + +test('deep nesting is an error, not a crash', () => { + assert.throws(() => parse('['.repeat(5000) + ']'.repeat(5000)), JsonSyntaxError); +}); + +test('nodeFromInput', () => { + assert.equal(nodeFromInput('42').type, 'number'); + assert.equal(nodeFromInput('hello').raw, '"hello"'); + assert.equal(nodeFromInput('true').type, 'boolean'); +}); + +test('agrees with JSON.parse on validity for fuzzed inputs', () => { + const pieces = ['{', '}', '[', ']', ',', ':', '"a"', '1', '-0.5e3', 'true', 'null', ' ', '\n', '"\\u12"', '01', '1.']; + let seed = 1; + const rnd = (n) => ((seed = (seed * 1103515245 + 12345) & 0x7fffffff) % n); + for (let k = 0; k < 20000; k++) { + let s = ''; + for (let j = rnd(8) + 1; j > 0; j--) s += pieces[rnd(pieces.length)]; + let ok = true; try { JSON.parse(s); } catch { ok = false; } + let mine = true; try { parse(s); } catch { mine = false; } + assert.equal(mine, ok, `disagree on ${JSON.stringify(s)}`); + if (ok) assert.deepEqual(JSON.parse(stringify(parse(s), ' ')), JSON.parse(s)); + } +}); diff --git a/tests/package.json b/tests/package.json new file mode 100644 index 0000000..089153b --- /dev/null +++ b/tests/package.json @@ -0,0 +1 @@ +{"type":"module"}