diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 884d202..23aee5b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,8 +18,27 @@ jobs: - run: uv run ruff check . - run: uv run ruff format --check . - run: uv run pytest - - name: Frontend script parses - if: runner.os == 'Linux' + + frontend: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v5 + - uses: actions/setup-node@v4 + with: + node-version: 22 + cache: npm + - run: uv sync --frozen + - run: npm ci + - name: Scripts parse + run: for f in static/js/*.js scripts/*.js scripts/*.mjs; do node --check "$f"; done + - name: Vendored files and compiled CSS are up to date + run: | + npm run build + git diff --exit-code -- static/vendor static/css + - run: npx playwright install --with-deps chromium + - name: UI smoke test (fake data) run: | - python3 -c "import re;s=open('static/index.html',encoding='utf-8').read();open('/tmp/app.js','w').write(re.findall(r'',s,re.S)[-1])" - node --check /tmp/app.js + uv run python scripts/fake_server.py & + for i in $(seq 1 30); do curl -sf http://127.0.0.1:8001/api/health && break; sleep 1; done + node scripts/ui_smoke.js diff --git a/CLAUDE.md b/CLAUDE.md index 2eba8f8..a24dee5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,6 +16,11 @@ uv run python -m watchstock # run the app at http://127.0.0.1:8000 (opens b uv run python -m watchstock --no-browser uv run pytest # tests (no network needed) uv run ruff check . && uv run ruff format --check . + +# frontend tooling (developers only; outputs are committed, end users never need Node) +npm ci +npm run build # re-vendor pinned libs + recompile Tailwind CSS +uv run python scripts/fake_server.py & node scripts/ui_smoke.js # browser test, fake data ``` End users run `start.bat` (Windows). It installs `uv` if missing; `uv` fetches @@ -37,8 +42,16 @@ the right Python and dependencies by itself. Nothing needs to be pre-installed. - Single user, bound to `127.0.0.1`. No accounts, no auth. Don't add them back. - SQLite via stdlib `sqlite3`, schema changes as new entries in `db.MIGRATIONS` (never edit an applied migration). -- Frontend: plain HTML/CSS/JS, **no build step required to run**. Third-party JS is - vendored and pinned under `static/vendor/` (see HANDOFF for status). +- Frontend: plain HTML/CSS/JS, **no build step required to run**. `static/js/*.js` are + classic scripts sharing one global scope, loaded in the order listed in `index.html`; + top-level code may only call functions from earlier files (startup lives in `main.js`). + Third-party JS/fonts are vendored and pinned in `static/vendor/` via `npm run vendor`. + Tailwind is precompiled to `static/css/tailwind.css`. After adding Tailwind classes, + run `npm run build:css`; CI fails if the committed CSS is stale. +- LLM output is untrusted: render markdown only through `renderMarkdown()` (DOMPurify). + Never assign model text to `innerHTML` directly. Escape external text with `esc()`. +- Money: use `fmtMoney`/`fmtBig` with `priceCurrency()` for prices and + `statementCurrency()` for statement values. Never hardcode `$`. - Keep the UI simple. Every new panel must earn its place for a portfolio owner. ## Workflow diff --git a/README.md b/README.md index 40e7f15..c9b579a 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,8 @@ uv sync uv run python -m watchstock # run uv run pytest # tests, no network needed uv run python scripts/fake_server.py # UI with fake data on :8001 +npm ci && node scripts/ui_smoke.js # browser test against the fake server +npm run build # after changing vendored libs or Tailwind classes ``` ## License diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bd4aba9..53ea14a 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,7 +1,7 @@ # Architecture ``` -Browser (static/index.html, vanilla JS) +Browser (static/index.html + static/js/*.js, plain scripts, no build step) │ JSON over /api/* ▼ watchstock/app.py FastAPI app factory, error → 502 mapping, static files @@ -21,6 +21,28 @@ watchstock/app.py FastAPI app factory, error → 502 mapping, static └── openrouter.py chat completions ``` +## Frontend (`static/`) + +| file | role | +|---|---| +| `index.html` | markup only; loads CSS, vendored libs, then `js/*.js` in order | +| `css/tailwind.css` | precompiled Tailwind (generated from `tailwind.config.js`; `npm run build:css`) | +| `css/app.css` | fonts, theme variables, component styles, markdown (`.prose`) styles | +| `vendor/` | pinned Chart.js, marked, DOMPurify, Inter font (`npm run vendor`) | +| `js/core.js` | `api()`, `esc()`, `renderMarkdown()`, money formatting, DOM handles, toast | +| `js/charts.js` | Chart.js helpers | +| `js/scores.js` | breakdown popover + safety modal | +| `js/settings.js` | settings modal | +| `js/home.js` | indices, market news, movers, watchlist, search history | +| `js/dashboard.js` | sidebar, finance tab, metric cards, news tab | +| `js/analysis.js` | AI report rendering/requesting, JSON export | +| `js/chat.js` | chat panel and the UI actions the model may request | +| `js/search.js` | layout, autocomplete, `executeSearch`/`loadStock`, refresh, overlay | +| `js/main.js` | startup calls (runs last) | + +Classic scripts share one global scope (see D11). `scripts/ui_smoke.js` drives the real +UI against `scripts/fake_server.py` in CI. + ## Request flow: opening a stock 1. UI calls `GET /api/stocks/MSFT?name=...` (`refresh=true` from the REFRESH button). diff --git a/docs/DECISIONS.md b/docs/DECISIONS.md index e65d8de..c610427 100644 --- a/docs/DECISIONS.md +++ b/docs/DECISIONS.md @@ -67,3 +67,15 @@ cached snapshots in the old shape are refetched instead of breaking the UI. Windows console QuickEdit mode blocks any process writing to a console the user has clicked into, which looks like a freeze. Logs go to `data/watchstock.log`; the console only shows the startup banner. The browser opens after `/api/health` answers. + +## D11 — Frontend: split classic scripts, vendored libs, precompiled Tailwind (2026-11-04) +The 2,400-line `index.html` is now `index.html` + `css/app.css` + ten files in `js/`. +They're classic scripts sharing one global scope, not ES modules: the markup uses inline +`onclick` handlers that need globals, and modules would mean rewriting every handler +for no user-visible gain. Converting to modules later is mechanical if it's ever needed. +Chart.js, marked, DOMPurify and the Inter font are vendored at pinned versions +(`package.json`, `scripts/vendor.mjs`): the app no longer depends on CDNs, and an +unpinned CDN update can't break it again (that's how the report links broke). Tailwind's +Play CDN (a runtime compiler, not meant for production) is replaced by a precompiled +`static/css/tailwind.css`, which CI checks is up to date. Node is a developer-only tool. +All LLM markdown goes through DOMPurify, with images forbidden. diff --git a/docs/HANDOFF.md b/docs/HANDOFF.md index a1b753a..f4c6825 100644 --- a/docs/HANDOFF.md +++ b/docs/HANDOFF.md @@ -46,12 +46,19 @@ Read this first. Update it at the end of every batch or before your context runs - [x] Default model `nvidia/nemotron-3.5-super-vl:free` (owner's choice for trials); LLM timeout 150 s - [x] Snapshot `schema` version (D9): old cached snapshots are refetched, not rendered broken -### Batch 3 — Frontend cleanup -- Split `static/index.html` into `index.html` + `css/` + `js/` ES modules -- Vendor + pin Chart.js, marked, DOMPurify; sanitise LLM HTML; fix marked link renderer (broken in marked ≥13) -- Tailwind Play CDN → decide (D6) -- Show data age ("as of"), currency-aware formatting, simpler settings -- Drop the chat's HTML-injection UI action +### Batch 3 — Frontend cleanup *(branch `batch-3-frontend`, PR #3, stacked on #2)* ✅ +- [x] `static/index.html` split into `css/app.css` + 10 classic scripts in `js/` (D11) +- [x] Chart.js 4.6.1, marked 18.1.3, DOMPurify 3.4.17, Inter 5.3.0 vendored + pinned; no CDNs left + except TradingView and logos +- [x] Tailwind Play CDN → precompiled `css/tailwind.css` (Tailwind 3.4.19); CI checks it's fresh +- [x] All LLM markdown sanitised (`renderMarkdown`, images forbidden); chat's raw-HTML + `update_tab_content` action removed +- [x] Currency-aware money (`fmtMoney`/`fmtBig`): prices in `currency`, FCF in `financialCurrency`, + GBp/ZAc/ILA minor units, compact $3.08T style; watchlist quotes carry currency +- [x] Plain-language wording (Analyze, New AI report, Ask about this stock, disclaimer line) +- [x] Markdown styles for AI text (headings, lists, quotes) +- [x] `scripts/ui_smoke.js` is now a pass/fail browser test (sanitising, currencies, breakdowns, + watchlist, refresh, chat, no-key hint, failure toast) and runs in CI ### Batch 4 — Portfolio - Holdings (ticker, shares, cost basis, currency), P/L, allocation by sector/country, @@ -62,18 +69,19 @@ Read this first. Update it at the end of every batch or before your context runs - Industry peer comparison; thesis tracking ("why I bought" checked against new data) ## Status -Batches 1 and 2 done. PR #1 and PR #2 (stacked) green on CI and waiting for the owner to -merge. Files copied to the owner's folder. Next: batch 3 (frontend cleanup). +Batches 1-3 done. PRs #1, #2, #3 (stacked) wait for the owner to merge; files are copied +to the owner's folder after each batch. Next: batch 4 (portfolio). Notes for the next agent: -- The chat still supports `update_tab_content` on the frontend (raw HTML). The backend - prompt no longer offers it; remove the frontend handler in batch 3 with DOMPurify. -- The Tailwind Play CDN, Chart.js and marked still load from CDNs (marked unpinned; the - link renderer uses the >=13 token API). Batch 3 vendors them into `static/vendor/`. -- For screenshots in the sandbox: run `scripts/fake_server.py`, then `scripts/ui_smoke.js` - (header explains how it serves CDN scripts from npm copies). -- Money is still formatted with `$` everywhere in the frontend; statement values (FCF, - revenue) should use `financialCurrency`, prices `currency`. Batch 3. +- Batch 4 plan: `holdings` table (ticker, shares, avg cost, currency, opened_at, notes) via a new + migration; `/api/portfolio` returning positions with live quotes, P/L, weights, sector/country + allocation (sector from the cached snapshot, else a light `fetch_profile`), concentration flags + (single position > 20%, sector > 40%), projected annual dividends. UI: a "Portfolio" view on the + home screen next to the watchlist; keep it to one table + two small allocation charts. + Multi-currency totals: show per-currency subtotals rather than inventing FX conversion; dad is + mostly USD. +- For screenshots/tests: `scripts/fake_server.py` + `node scripts/ui_smoke.js` (needs + `PLAYWRIGHT_BROWSERS_PATH` pointing at a Chromium matching playwright 1.63.0). - The old hackathon DB (`watchstock.db` at repo root) is not migrated; the new DB is `data/watchstock.db`. @@ -92,6 +100,12 @@ Batch 2: - [ ] Request a second report on the same stock → "Since the Last Report" section appears - [ ] If anything misbehaves: send `data\watchstock.log` +Batch 3: +- [ ] Looks the same as before (fonts, layout, colours), with nothing loaded from CDNs +- [ ] AI report: headings/bullets readable, links clickable +- [ ] `TLV.RO` shows prices in RON (e.g. "RON 29.50"), MSFT in $ +- [ ] Market cap shows compact (e.g. "$3.08T") + ## Open questions for the owner - (answered) Dad holds mostly US stocks → currency formatting stays in batch 3, no rush. - (answered) Default model: `nvidia/nemotron-3.5-super-vl:free` for now. diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..8dca1bd --- /dev/null +++ b/package-lock.json @@ -0,0 +1,1108 @@ +{ + "name": "watchstock-frontend-tooling", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "watchstock-frontend-tooling", + "devDependencies": { + "@fontsource/inter": "5.3.0", + "chart.js": "4.6.1", + "dompurify": "3.4.17", + "marked": "18.1.3", + "playwright": "1.63.0", + "tailwindcss": "3.4.19" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.3.0.tgz", + "integrity": "sha512-U4+70Pc5ZS9osnCBCE5Jha/ciHM+Yp+CNMNC/7HvYbNRk1Ldd+f7qO65W5qfhu/TCv+/ozljlXXe9Nj8419DMA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@fontsource/inter": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/@fontsource/inter/-/inter-5.3.0.tgz", + "integrity": "sha512-RofMylZmjlJEfELXeNHFWBRcSs75rGU/6bV2S2jfnvv/3rPXPGe0LgUJTklcHZ9lM4OZmAVFhcJPnACfb91A3g==", + "dev": true, + "license": "OFL-1.1", + "funding": { + "url": "https://github.com/sponsors/ayuhito" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@kurkle/color": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/@kurkle/color/-/color-0.3.4.tgz", + "integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "dev": true, + "license": "MIT", + "optional": true + }, + "node_modules/any-promise": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/any-promise/-/any-promise-1.3.0.tgz", + "integrity": "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==", + "dev": true, + "license": "MIT" + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dev": true, + "license": "ISC", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", + "integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==", + "dev": true, + "license": "MIT" + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/camelcase-css": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", + "integrity": "sha512-QOSvevhslijgYwRx6Rv7zKdMF8lbRmx+uQGx2+vDc+KI/eBnsy9kit5aj23AgGu3pa4t9AgwbnXWqS+iOY+2aA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/chart.js": { + "version": "4.6.1", + "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.6.1.tgz", + "integrity": "sha512-hJyniucsFmq//EvXYvJ6c6mahPoI3kaxdjVH8awTaJ/fDNWeSqqqArixMJWkWNN6fcYvPU3HneSANFNYtRi61g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@kurkle/color": "^0.3.0" + }, + "engines": { + "pnpm": ">=8" + } + }, + "node_modules/chokidar": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chokidar/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/commander": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz", + "integrity": "sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/cssesc": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", + "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", + "dev": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/didyoumean": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/didyoumean/-/didyoumean-1.2.2.tgz", + "integrity": "sha512-gxtyfqMg7GKyhQmb056K7M3xszy/myH8w+B4RT+QXBQsvAOdc3XymqDDPHx1BgPgsdAA5SIifona89YtRATDzw==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/dlv": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/dlv/-/dlv-1.1.3.tgz", + "integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==", + "dev": true, + "license": "MIT" + }, + "node_modules/dompurify": { + "version": "3.4.17", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz", + "integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==", + "dev": true, + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/fast-glob": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz", + "integrity": "sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.8" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fastq": { + "version": "1.20.3", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.3.tgz", + "integrity": "sha512-XKv5nnLs6nLF71NgiKJLIZFLkPyIEuOselLG7ujZnGrRfQK8HpvY+WqKhAJUAdLomwVHErVS4LfxFlPq0/FTAw==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/hasown": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dev": true, + "license": "MIT", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-core-module": { + "version": "2.18.0", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.18.0.tgz", + "integrity": "sha512-qyax9fgaKOEC4qK8WZn7Q4IcoZC9RC1O1fFxRcRTq/oMMkWT/uXpqpXa12kzWR409zAt1drYN9N9BO26UmBCmw==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/jiti": { + "version": "1.21.7", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-1.21.7.tgz", + "integrity": "sha512-/imKNG4EbWNrVjoNC/1H5/9GFy+tqjGBHCaSsN+P2RnPqjsLmv6UD3Ej+Kj8nBWaRAwyk7kK5ZUc+OEatnTR3A==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "bin/jiti.js" + } + }, + "node_modules/lilconfig": { + "version": "3.1.4", + "resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.4.tgz", + "integrity": "sha512-zJZyBmQhArDRefuWTypZxwDpFDIYmrj8ypSBvwGD5P13Y95s6DjzKgu4DVdGbeQa5PDEsAOCAPNk4X+QOR006w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/antonk52" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "dev": true, + "license": "MIT" + }, + "node_modules/marked": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/marked/-/marked-18.1.3.tgz", + "integrity": "sha512-9ChMH8EVVgjgID49nsL6IWxWk5c6GtAsq/xw7U1ggkjkU5AGuv68oLTVlFRtvcUYZtpbNyjyvGo3YDu0fGapiw==", + "dev": true, + "license": "MIT", + "bin": { + "marked": "bin/marked.js" + }, + "engines": { + "node": ">= 20" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mz": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/mz/-/mz-2.7.0.tgz", + "integrity": "sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0", + "object-assign": "^4.0.1", + "thenify-all": "^1.0.0" + } + }, + "node_modules/nanoid": { + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-hash": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-3.0.0.tgz", + "integrity": "sha512-RSn9F68PjH9HqtltsSnqYC1XXoWe9Bju5+213R98cNGttag9q9yAOTzdbsqvIa7aNm5WffBZFpWYr2aWrklWAw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pirates": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", + "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/playwright": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.63.0.tgz", + "integrity": "sha512-+7ziBLidS4NaNCdt57SUDT+wYmmd5fmiQejUic/kb+YsYSCPyOOE9sebzMjNmQrsnNpDJqd4WHvV/8lfKfUDUg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.63.0" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.63.0", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.63.0.tgz", + "integrity": "sha512-rYCsBF/M5HjUch52bbtVONEFjv6Xu8sm8h72dNlR5bzIE1fvC/bxgspzkjSfU+MweEMmPM8KJebG6nnyxo5mCg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/postcss": { + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.20", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/postcss-import": { + "version": "15.1.0", + "resolved": "https://registry.npmjs.org/postcss-import/-/postcss-import-15.1.0.tgz", + "integrity": "sha512-hpr+J05B2FVYUAXHeK1YyI267J/dDDhMU6B6civm8hSY1jYJnBXxzKDKDswzJmtLHryrjhnDjqqp/49t8FALew==", + "dev": true, + "license": "MIT", + "dependencies": { + "postcss-value-parser": "^4.0.0", + "read-cache": "^1.0.0", + "resolve": "^1.1.7" + }, + "engines": { + "node": ">=14.0.0" + }, + "peerDependencies": { + "postcss": "^8.0.0" + } + }, + "node_modules/postcss-js": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/postcss-js/-/postcss-js-4.1.0.tgz", + "integrity": "sha512-oIAOTqgIo7q2EOwbhb8UalYePMvYoIeRY2YKntdpFQXNosSu3vLrniGgmH9OKs/qAkfoj5oB3le/7mINW1LCfw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "camelcase-css": "^2.0.1" + }, + "engines": { + "node": "^12 || ^14 || >= 16" + }, + "peerDependencies": { + "postcss": "^8.4.21" + } + }, + "node_modules/postcss-load-config": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-6.0.1.tgz", + "integrity": "sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "lilconfig": "^3.1.1" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "jiti": ">=1.21.0", + "postcss": ">=8.0.9", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + }, + "postcss": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/postcss-nested": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/postcss-nested/-/postcss-nested-6.2.0.tgz", + "integrity": "sha512-HQbt28KulC5AJzG+cZtj9kvKB93CFCdLvog1WFLf1D+xmMvPGlBstkpTEZfK5+AN9hfJocyBFCNiqyS48bpgzQ==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "postcss-selector-parser": "^6.1.1" + }, + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.2.14" + } + }, + "node_modules/postcss-selector-parser": { + "version": "6.1.5", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-6.1.5.tgz", + "integrity": "sha512-TEHFzb5KRDKaOgJ4TYE+0jyJtFbjLvkdVOu0fZ2b6MTWzoqZd4Le+61aEppWkvTlYePgOX4ATL1wsAIPMLTw6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/postcss-value-parser": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/postcss-value-parser/-/postcss-value-parser-4.2.0.tgz", + "integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/read-cache": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/read-cache/-/read-cache-1.0.2.tgz", + "integrity": "sha512-/peqiBB/n07gQGLsWaHho3WfvUyRscw0gYTsEFMhrIe/nWLkYaf5SbKYjGYqtRV3aPwykJgF2VEMo1ac4bnsGA==", + "dev": true, + "license": "MIT" + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dev": true, + "license": "MIT", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/resolve": { + "version": "1.22.14", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.14.tgz", + "integrity": "sha512-1ZjYvR9sbkiwC5+9QHetqW5HmA2pHRMaoupD01t2HlYnV/vydC2zPwLixhsMieSWVZt0JJRg5LVIk0Ow1D/TrA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "is-core-module": "^2.18.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/sucrase": { + "version": "3.35.1", + "resolved": "https://registry.npmjs.org/sucrase/-/sucrase-3.35.1.tgz", + "integrity": "sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.2", + "commander": "^4.0.0", + "lines-and-columns": "^1.1.6", + "mz": "^2.7.0", + "pirates": "^4.0.1", + "tinyglobby": "^0.2.11", + "ts-interface-checker": "^0.1.9" + }, + "bin": { + "sucrase": "bin/sucrase", + "sucrase-node": "bin/sucrase-node" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tailwindcss": { + "version": "3.4.19", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.19.tgz", + "integrity": "sha512-3ofp+LL8E+pK/JuPLPggVAIaEuhvIz4qNcf3nA1Xn2o/7fb7s/TYpHhwGDv1ZU3PkBluUVaF8PyCHcm48cKLWQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "arg": "^5.0.2", + "chokidar": "^3.6.0", + "didyoumean": "^1.2.2", + "dlv": "^1.1.3", + "fast-glob": "^3.3.2", + "glob-parent": "^6.0.2", + "is-glob": "^4.0.3", + "jiti": "^1.21.7", + "lilconfig": "^3.1.3", + "micromatch": "^4.0.8", + "normalize-path": "^3.0.0", + "object-hash": "^3.0.0", + "picocolors": "^1.1.1", + "postcss": "^8.4.47", + "postcss-import": "^15.1.0", + "postcss-js": "^4.0.1", + "postcss-load-config": "^4.0.2 || ^5.0 || ^6.0", + "postcss-nested": "^6.2.0", + "postcss-selector-parser": "^6.1.2", + "resolve": "^1.22.8", + "sucrase": "^3.35.0" + }, + "bin": { + "tailwind": "lib/cli.js", + "tailwindcss": "lib/cli.js" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/thenify": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", + "integrity": "sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==", + "dev": true, + "license": "MIT", + "dependencies": { + "any-promise": "^1.0.0" + } + }, + "node_modules/thenify-all": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/thenify-all/-/thenify-all-1.6.0.tgz", + "integrity": "sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==", + "dev": true, + "license": "MIT", + "dependencies": { + "thenify": ">= 3.1.0 < 4" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-interface-checker": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/ts-interface-checker/-/ts-interface-checker-0.1.13.tgz", + "integrity": "sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..3dfdba4 --- /dev/null +++ b/package.json @@ -0,0 +1,18 @@ +{ + "name": "watchstock-frontend-tooling", + "private": true, + "description": "Developer-only tooling. End users never need Node: everything it produces is committed.", + "scripts": { + "vendor": "node scripts/vendor.mjs", + "build:css": "tailwindcss -c tailwind.config.js -i static/css/tailwind.input.css -o static/css/tailwind.css --minify", + "build": "npm run vendor && npm run build:css" + }, + "devDependencies": { + "@fontsource/inter": "5.3.0", + "chart.js": "4.6.1", + "dompurify": "3.4.17", + "marked": "18.1.3", + "playwright": "1.63.0", + "tailwindcss": "3.4.19" + } +} diff --git a/pyproject.toml b/pyproject.toml index e9b337a..5e43cba 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "watchstock" -version = "0.3.0" +version = "0.4.0" description = "Personal stock analysis terminal: Yahoo Finance data, explainable scores, optional LLM analysis." readme = "README.md" requires-python = ">=3.12" diff --git a/scripts/fake_server.py b/scripts/fake_server.py index b7325a6..48407d0 100644 --- a/scripts/fake_server.py +++ b/scripts/fake_server.py @@ -29,6 +29,13 @@ def fetch_profile(ticker): if ticker == "FAIL": raise yahoo.MarketDataError("429 Too Many Requests (fake)") p = copy.deepcopy(SAMPLE_PROFILE) + m = p["metrics"] + if ticker.endswith(".RO"): # Bucharest: everything in RON + p["name"] = "Banca Transilvania S.A." + m.update(currency="RON", financialCurrency="RON", currentPrice=29.5, marketCap=2.4e10) + elif ticker == "TSM": # US-listed, statements in TWD + p["name"] = "Taiwan Semiconductor Manufacturing" + m.update(currency="USD", financialCurrency="TWD", freeCashflow=9e11, marketCap=1.1e12) p["upgrades_downgrades"] = [ {"date": "2026-10-2" + str(i), "firm": f"Firm {i}", "from_grade": "Hold", "to_grade": "Buy", "action": "up"} for i in range(7) @@ -86,7 +93,10 @@ def search(query, limit=6): "executive_summary": "Fake report: strong franchise, fair-to-rich valuation.", "verdict": {"action": "BUY", "confidence": 68, "horizon": "12 months"}, "recommended_action": "Accumulate on pullbacks.", - "financial_deep_dive": "## Margins\n**Operating margin 45%**. See [source](https://example.com).", + # The is a deliberate XSS probe: the UI must sanitise it away. + "financial_deep_dive": "## Margins\n**Operating margin 45%**. See [source](https://example.com)." + '\n\n' + "", "news_impact_analysis": "## News\n- Cloud growth beat.", "risk_scenarios": "## Bull Case\nUp.\n## Base Case\nFlat.\n## Bear Case\nDown.", "charts": [{"chart_type": "bar", "labels": ["P/E", "Fwd P/E"], "values": [33.4, 29.3], @@ -97,7 +107,10 @@ def search(query, limit=6): def complete(messages, *, api_key, model, json_mode=True): if "COMPANY CONTEXT" in messages[0]["content"]: return json.dumps({"reply_text": "Fake chat answer.", "ui_action": None}) - return json.dumps(REPORT) + report = dict(REPORT) + if "previous_report" in messages[-1]["content"]: + report["changes_since_last"] = "- Nothing material changed (fake)." + return json.dumps(report) def install_fakes(): diff --git a/scripts/ui_smoke.js b/scripts/ui_smoke.js index 6a39fa7..0756fd4 100644 --- a/scripts/ui_smoke.js +++ b/scripts/ui_smoke.js @@ -1,78 +1,119 @@ -// UI smoke test + screenshots against scripts/fake_server.py (port 8001). +// End-to-end UI smoke test against scripts/fake_server.py (port 8001). // -// The sandbox can't reach CDNs, so CDN scripts are served from local npm copies: -// mkdir /tmp/mk && cd /tmp/mk && npm i marked chart.js @tailwindcss/browser@4 -// NODE_PATH=$(npm root -g) NM=/tmp/mk/node_modules OUT=/tmp/shots node scripts/ui_smoke.js -// (@tailwindcss/browser v4 only approximates the v3 Play CDN the page uses.) -// Prints UI state + console errors as JSON; screenshots go to $OUT. +// uv run python scripts/fake_server.py & # fake Yahoo + LLM, throwaway DB +// npm ci && node scripts/ui_smoke.js # OUT=/some/dir to also save screenshots +// +// Exits non-zero if any check fails or the page throws. All app assets are local, so +// only external extras (TradingView, logos, favicons) are blocked. const { chromium } = require('playwright'); -const fs = require('fs'); -const NM = process.env.NM; -const local = { - 'cdn.tailwindcss.com': NM + '/@tailwindcss/browser/dist/index.global.js', - 'marked': NM + '/marked/lib/marked.umd.js', - 'chart.js': NM + '/chart.js/dist/chart.umd.min.js', -}; + +const BASE = process.env.BASE_URL || 'http://127.0.0.1:8001'; +const OUT = process.env.OUT; +const failures = []; +const check = (name, ok, detail = '') => { if (!ok) failures.push(`${name}${detail ? ': ' + detail : ''}`); }; + (async () => { const browser = await chromium.launch(); const page = await browser.newPage({ viewport: { width: 1440, height: 900 } }); const errors = []; - page.on('pageerror', e => errors.push('pageerror: ' + e.message)); - page.on('console', m => { if (m.type() === 'error') errors.push('console: ' + m.text()); }); - await page.route('**/*', route => { - const url = route.request().url(); - if (url.startsWith('http://127.0.0.1')) return route.continue(); - for (const [k, f] of Object.entries(local)) if (url.includes(k)) return route.fulfill({ path: f, contentType: 'application/javascript' }); - return route.abort(); + page.on('pageerror', e => errors.push(e.message)); + page.on('console', m => { + const t = m.text(); + if (m.type() === 'error' && !/ERR_FAILED|status of 502|Too Many Requests/.test(t)) errors.push(t); }); - await page.goto('http://127.0.0.1:8001/'); - await page.waitForTimeout(1500); - await page.screenshot({ path: process.env.OUT + '/home.png' }); + await page.route('**/*', r => (r.request().url().startsWith(BASE) ? r.continue() : r.abort())); + const shot = async name => OUT && page.screenshot({ path: `${OUT}/${name}.png` }); + const text = sel => page.evaluate(s => document.querySelector(s)?.innerText ?? null, sel); + + // Home + await page.goto(BASE + '/'); + await page.waitForTimeout(1200); + check('indices render', /S&P 500/.test(await text('#indicesBar'))); + // Explicitly load the face (browsers fetch fonts lazily) and confirm it came from /static/vendor. + check('Inter font loaded', await page.evaluate(async () => (await document.fonts.load('600 12px Inter')).length > 0)); + check('tailwind css applied', await page.evaluate(() => getComputedStyle(document.querySelector('#initialView')).position === 'absolute')); + await shot('home'); + + // Open a stock: report renders, sanitised await page.evaluate(() => quickSearch('Microsoft Corporation', 'MSFT')); await page.waitForTimeout(2500); - await page.screenshot({ path: process.env.OUT + '/dash_ai.png' }); - await page.click('.tab-btn[data-target="tab-finance"]').catch(e => errors.push('no finance tab ' + e.message)); - await page.waitForTimeout(500); - await page.screenshot({ path: process.env.OUT + '/dash_finance.png' }); - await page.click('.tab-btn[data-target="tab-news"]').catch(e => errors.push('no news tab')); - await page.waitForTimeout(300); - await page.screenshot({ path: process.env.OUT + '/dash_news.png' }); - // watchlist star + refresh + bad ticker - await page.click('#btnWatchlist'); - await page.waitForTimeout(500); - await page.click('#btnForceUpdate'); - await page.waitForTimeout(1500); - const state = await page.evaluate(() => ({ - asOf: document.getElementById('asOfLabel').textContent, - ticker: document.getElementById('sbTicker').textContent, - wl: document.getElementById('watchlistPanel').innerText.slice(0, 60), - model: document.getElementById('aiModelLabel').textContent, - link: document.querySelector('#financialDeepDiveContent a')?.outerHTML, - })); - // score breakdown popover + safety modal + check('ticker shown', (await text('#sbTicker')) === 'MSFT'); + check('price in USD', /^\$414\.00$/.test(await text('#sbPrice')), await text('#sbPrice')); + check('market cap compact', /^\$3\.08T$/.test(await text('#sbMarketCap')), await text('#sbMarketCap')); + check('as-of label', /data /.test(await text('#asOfLabel'))); + const deepDive = await page.evaluate(() => document.getElementById('financialDeepDiveContent').innerHTML); + check('markdown link rendered', / window.__xss)), deepDive); + check('since-last-report hidden on first report', await page.evaluate(() => document.getElementById('changesSection').classList.contains('hidden'))); + await shot('dashboard_ai'); + + // Finance tab: breakdown popover, safety modal, dividend await page.click('.tab-btn[data-target="tab-finance"]'); await page.click('[data-score-key="quality"]'); - await page.waitForTimeout(300); - state.popover = await page.evaluate(() => document.getElementById('popoverContent').innerText.slice(0, 160)); - await page.screenshot({ path: process.env.OUT + '/popover.png' }); + check('quality breakdown', /Net margin 36\.0%/.test(await text('#popoverContent')), await text('#popoverContent')); + await shot('popover'); await page.evaluate(() => { hideScoreBreakdown(); showScoreExplanation('long_term'); }); - await page.waitForTimeout(300); - state.safetyModal = await page.evaluate(() => document.getElementById('scoreModalBody').innerText.slice(0, 160)); - await page.screenshot({ path: process.env.OUT + '/safety.png' }); + check('safety modal', /Debt\/Equity 0\.30x/.test(await text('#scoreModalBody'))); await page.evaluate(() => closeScoreModal()); - state.dividendCard = await page.evaluate(() => [...document.querySelectorAll('#metricCards > div')].map(d => d.innerText).find(t => /dividend/i.test(t))); - // no API key: analysis must not auto-run + const dividend = await page.evaluate(() => [...document.querySelectorAll('#metricCards > div')].map(d => d.innerText).find(t => /dividend/i.test(t)) || ''); + check('dividend yield as percent', /0\.88%/.test(dividend), dividend); + const fcf = await page.evaluate(() => [...document.querySelectorAll('#metricCards > div')].map(d => d.innerText).find(t => /free cash/i.test(t)) || ''); + check('FCF in statement currency', /\$70B/.test(fcf), fcf); + + // Watchlist + refresh + await page.click('#btnWatchlist'); + await page.waitForTimeout(500); + check('watchlist add', /MSFT/.test(await text('#watchlistPanel'))); + await page.click('#btnForceUpdate'); + await page.waitForTimeout(1500); + check('refresh keeps stock', (await text('#sbTicker')) === 'MSFT'); + + // Non-USD stock: currencies and TradingView symbol + await page.evaluate(() => quickSearch('Banca Transilvania', 'TLV.RO')); + await page.waitForTimeout(2000); + check('RON price', /RON/.test(await text('#sbPrice')), await text('#sbPrice')); + check('tradingview symbol', await page.evaluate(() => currentRawData.tradingview_symbol === 'BVB:TLV')); + await page.evaluate(() => quickSearch('Taiwan Semiconductor', 'TSM')); + await page.waitForTimeout(2000); + const tsmFcf = await page.evaluate(() => [...document.querySelectorAll('#metricCards > div')].map(d => d.innerText).find(t => /free cash/i.test(t)) || ''); + check('TSM FCF in TWD', /NT\$|TWD/.test(tsmFcf), tsmFcf); + + // Second report shows "since the last report" + await page.evaluate(() => quickSearch('Microsoft Corporation', 'MSFT')); + await page.waitForTimeout(1500); + await page.evaluate(() => requestAnalysis()); + await page.waitForTimeout(2000); + check('since-last-report shown', await page.evaluate(() => !document.getElementById('changesSection').classList.contains('hidden'))); + + // Chat + await page.fill('#oldChatInput', 'Is it cheap?'); + await page.press('#oldChatInput', 'Enter'); + await page.waitForTimeout(1500); + check('chat reply', /Fake chat answer/.test(await text('#chatHistory'))); + await shot('chat'); + + // No API key: no auto report, hint instead await page.evaluate(async () => { await api('/api/settings', { method: 'PUT', body: { llm_api_key: '' } }); await refreshLlmStatus(); }); await page.evaluate(() => quickSearch('Apple', 'AAPL')); await page.waitForTimeout(1500); - state.noKeySummary = await page.evaluate(() => document.getElementById('aiSummary').innerText); + check('no-key hint', /AI analysis is off/.test(await text('#aiSummary')), await text('#aiSummary')); + + // Upstream failure: toast, previous stock stays await page.evaluate(() => quickSearch('Fail Corp', 'FAIL')); await page.waitForTimeout(1500); - state.toast = await page.evaluate(() => document.getElementById('toastMsg').textContent); - state.tickerAfterFail = await page.evaluate(() => document.getElementById('sbTicker').textContent); + check('failure toast', /429/.test(await text('#toastMsg'))); + check('previous stock kept', (await text('#sbTicker')) === 'AAPL'); + + // Settings modal await page.evaluate(() => openSettings()); - await page.waitForTimeout(500); - await page.screenshot({ path: process.env.OUT + '/settings.png' }); - console.log(JSON.stringify({ state, errors }, null, 1)); + await page.waitForTimeout(300); + await shot('settings'); + await browser.close(); -})(); + for (const e of errors) failures.push('page error: ' + e); + if (failures.length) { + console.error('UI smoke FAILED:\n - ' + failures.join('\n - ')); + process.exit(1); + } + console.log('UI smoke passed'); +})().catch(e => { console.error(e); process.exit(1); }); diff --git a/scripts/vendor.mjs b/scripts/vendor.mjs new file mode 100644 index 0000000..e089255 --- /dev/null +++ b/scripts/vendor.mjs @@ -0,0 +1,26 @@ +// Copy pinned third-party browser files from node_modules into static/vendor/. +// Versions are pinned in package.json. Run: npm ci && npm run vendor +import { copyFileSync, mkdirSync } from "node:fs"; +import { dirname } from "node:path"; + +const files = { + "node_modules/chart.js/dist/chart.umd.min.js": "static/vendor/chart.umd.min.js", + "node_modules/chart.js/LICENSE.md": "static/vendor/licenses/chart.js.LICENSE.md", + "node_modules/marked/lib/marked.umd.js": "static/vendor/marked.umd.js", + "node_modules/marked/LICENSE": "static/vendor/licenses/marked.LICENSE", + "node_modules/dompurify/dist/purify.min.js": "static/vendor/purify.min.js", + "node_modules/dompurify/LICENSE": "static/vendor/licenses/dompurify.LICENSE", + "node_modules/@fontsource/inter/LICENSE": "static/vendor/licenses/inter.LICENSE", +}; +// latin + latin-ext (Romanian diacritics: ă â î ș ț) +for (const subset of ["latin", "latin-ext"]) { + for (const w of [400, 500, 600, 700]) { + files[`node_modules/@fontsource/inter/files/inter-${subset}-${w}-normal.woff2`] = + `static/vendor/fonts/inter-${subset}-${w}-normal.woff2`; + } +} +for (const [from, to] of Object.entries(files)) { + mkdirSync(dirname(to), { recursive: true }); + copyFileSync(from, to); + console.log(`${from} -> ${to}`); +} diff --git a/static/css/app.css b/static/css/app.css new file mode 100644 index 0000000..626dc42 --- /dev/null +++ b/static/css/app.css @@ -0,0 +1,137 @@ +/* WatchStock styles (beyond Tailwind utilities). */ + +/* Inter, self-hosted (static/vendor/fonts) so the app looks right offline. */ +@font-face { font-family: 'Inter'; font-style: normal; font-weight: 400; font-display: swap; + src: url('/static/vendor/fonts/inter-latin-400-normal.woff2') format('woff2'); unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; } +@font-face { font-family: 'Inter'; font-style: normal; font-weight: 500; font-display: swap; + src: url('/static/vendor/fonts/inter-latin-500-normal.woff2') format('woff2'); unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; } +@font-face { font-family: 'Inter'; font-style: normal; font-weight: 600; font-display: swap; + src: url('/static/vendor/fonts/inter-latin-600-normal.woff2') format('woff2'); unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; } +@font-face { font-family: 'Inter'; font-style: normal; font-weight: 700; font-display: swap; + src: url('/static/vendor/fonts/inter-latin-700-normal.woff2') format('woff2'); unicode-range: U+0000-00FF,U+0131,U+0152-0153,U+02BB-02BC,U+02C6,U+02DA,U+02DC,U+0304,U+0308,U+0329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD; } +@font-face { font-family: 'Inter'; font-style: normal; font-weight: 400; font-display: swap; + src: url('/static/vendor/fonts/inter-latin-ext-400-normal.woff2') format('woff2'); unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF; } +@font-face { font-family: 'Inter'; font-style: normal; font-weight: 500; font-display: swap; + src: url('/static/vendor/fonts/inter-latin-ext-500-normal.woff2') format('woff2'); unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF; } +@font-face { font-family: 'Inter'; font-style: normal; font-weight: 600; font-display: swap; + src: url('/static/vendor/fonts/inter-latin-ext-600-normal.woff2') format('woff2'); unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF; } +@font-face { font-family: 'Inter'; font-style: normal; font-weight: 700; font-display: swap; + src: url('/static/vendor/fonts/inter-latin-ext-700-normal.woff2') format('woff2'); unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF; } + +/* Markdown from the AI report and chat (Tailwind's typography plugin isn't used). */ +.prose h1, .prose h2 { font-size: 1rem; font-weight: 700; color: #fff; margin: 1.1em 0 0.5em; } +.prose h3, .prose h4 { font-size: 0.9rem; font-weight: 700; color: #e0e0e0; margin: 1em 0 0.4em; } +.prose p { margin: 0 0 0.75em; } +.prose ul, .prose ol { margin: 0 0 0.75em 1.25em; } +.prose ul { list-style: disc; } +.prose ol { list-style: decimal; } +.prose li { margin: 0.2em 0; } +.prose strong { color: #fff; font-weight: 600; } +.prose a { color: var(--accent); text-decoration: underline; } +.prose blockquote { border-left: 3px solid #ff9800; padding: 0.3em 0 0.3em 0.9em; margin: 0.75em 0; color: #ffcc80; background: #1a1a1a; } +.prose code { font-family: monospace; font-size: 0.85em; background: #222; padding: 0.1em 0.3em; } +.prose table { border-collapse: collapse; margin: 0.75em 0; font-size: 0.85em; } +.prose th, .prose td { border: 1px solid #333; padding: 0.3em 0.6em; text-align: left; } + +:root { + --bg-main: #121212; + --bg-panel: #1e1e1e; + --bg-lighter: #252526; + --border-color: #333333; + --text-main: #e0e0e0; + --text-muted: #a0a0a0; + --accent: #5e9ddc; +} + +body { + font-family: 'Inter', sans-serif; + background-color: var(--bg-main); + color: var(--text-main); + margin: 0; + overflow: hidden; /* Total 100vh layout */ +} + +/* Scrollbar customizing for dark mode */ +::-webkit-scrollbar { width: 8px; height: 8px; } +::-webkit-scrollbar-track { background: var(--bg-main); } +::-webkit-scrollbar-thumb { background: var(--border-color); border-radius: 4px; } +::-webkit-scrollbar-thumb:hover { background: #555; } + +/* Typography */ +.prose { color: var(--text-main); } +.prose h1, .prose h2, .prose h3 { color: #fff; border-color: var(--border-color); } +.prose a { color: var(--accent); text-decoration: none; } +.prose a:hover { text-decoration: underline; } +.prose strong { color: #fff; } + +/* Autocomplete dropdown */ +.dropdown { + position: absolute; top: calc(100% + 4px); left: 0; right: 0; + background: var(--bg-panel); border: 1px solid var(--border-color); border-radius: 8px; + box-shadow: 0 10px 25px rgba(0,0,0,0.5); + max-height: 250px; overflow-y: auto; z-index: 50; display: none; +} +.dropdown-item { padding: 12px 16px; cursor: pointer; border-bottom: 1px solid var(--border-color); color: var(--text-main); } +.dropdown-item:hover { background-color: var(--bg-lighter); } + +/* Base UI Elements */ +.panel { background-color: var(--bg-panel); border: 1px solid var(--border-color); border-radius: 0; } + +.tab-btn { + padding: 0.6rem 1.7rem; color: var(--text-muted); font-weight: 600; cursor: pointer; + background: var(--bg-main); border: 1px solid var(--border-color); border-radius: 0; + transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1); +} +.tab-btn:hover { color: var(--text-main); border-color: var(--accent); } +.tab-btn.active { color: var(--bg-main); background: var(--text-main); border-color: var(--text-main); } + +.tab-content { display: none; height: 100%; overflow-y: auto; padding: 1.5rem; padding-bottom: 90px; } +.tab-content.active { display: block; } + +.section-label { font-size: 0.7rem; letter-spacing: 1px; text-transform: uppercase; color: #888; font-weight: bold; margin-bottom: 1rem; } + +/* Loader */ +.pulse-loader { + animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite; +} +@keyframes pulse { + 0%, 100% { opacity: 1; } + 50% { opacity: 0.5; } +} +.spinner { border: 3px solid rgba(255,255,255,0.1); border-radius: 50%; border-top: 3px solid var(--accent); width: 24px; height: 24px; animation: spin 1s linear infinite; display: inline-block;} +@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } + +/* Icon-only action buttons */ +.action-icon-btn { + width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; + background: transparent; border: 1px solid var(--border-color); color: var(--text-muted); + cursor: pointer; transition: all 0.2s; flex-shrink: 0; +} +.action-icon-btn:hover { background: var(--bg-lighter); color: var(--text-main); border-color: var(--accent); } + +/* Search Overlay */ +#searchOverlay { + position: fixed; inset: 0; z-index: 1000; + background: rgba(0,0,0,0.75); backdrop-filter: blur(6px); + display: flex; align-items: flex-start; justify-content: center; + padding-top: 20vh; + opacity: 0; pointer-events: none; + transition: opacity 0.25s ease; +} +#searchOverlay.visible { + opacity: 1; pointer-events: all; +} +#searchOverlay .search-box { + width: 100%; max-width: 560px; + transform: translateY(-20px); + transition: transform 0.25s ease; +} +#searchOverlay.visible .search-box { + transform: translateY(0); +} +#searchOverlay input { + background: var(--bg-panel); border: 1px solid var(--accent); + color: var(--text-main); padding: 14px 20px; width: 100%; font-size: 1rem; + outline: none; font-family: 'Inter', sans-serif; +} +#searchOverlay label { color: var(--text-muted); font-size: 0.7rem; letter-spacing: 2px; text-transform: uppercase; margin-bottom: 8px; display: block; } diff --git a/static/css/tailwind.css b/static/css/tailwind.css new file mode 100644 index 0000000..32b14ff --- /dev/null +++ b/static/css/tailwind.css @@ -0,0 +1 @@ +*,:after,:before{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x:0;--tw-border-spacing-y:0;--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness:proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59,130,246,.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000;--tw-shadow:0 0 #0000;--tw-shadow-colored:0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }/*! tailwindcss v3.4.19 | MIT License | https://tailwindcss.com*/*,:after,:before{box-sizing:border-box;border:0 solid #e5e7eb}:after,:before{--tw-content:""}:host,html{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dd,dl,figure,h1,h2,h3,h4,h5,h6,hr,p,pre{margin:0}fieldset{margin:0}fieldset,legend{padding:0}menu,ol,ul{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}[role=button],button{cursor:pointer}:disabled{cursor:default}audio,canvas,embed,iframe,img,object,svg,video{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media (min-width:640px){.\!container{max-width:640px!important}.container{max-width:640px}}@media (min-width:768px){.\!container{max-width:768px!important}.container{max-width:768px}}@media (min-width:1024px){.\!container{max-width:1024px!important}.container{max-width:1024px}}@media (min-width:1280px){.\!container{max-width:1280px!important}.container{max-width:1280px}}@media (min-width:1536px){.\!container{max-width:1536px!important}.container{max-width:1536px}}.visible{visibility:visible}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.-right-\[41px\]{right:-41px}.right-2{right:.5rem}.right-6{right:1.5rem}.top-4{top:1rem}.z-20{z-index:20}.z-30{z-index:30}.z-40{z-index:40}.z-50{z-index:50}.mb-10{margin-bottom:2.5rem}.mb-2{margin-bottom:.5rem}.mb-3{margin-bottom:.75rem}.mb-4{margin-bottom:1rem}.mb-5{margin-bottom:1.25rem}.mb-6{margin-bottom:1.5rem}.mr-2{margin-right:.5rem}.mt-1{margin-top:.25rem}.mt-2{margin-top:.5rem}.mt-4{margin-top:1rem}.mt-6{margin-top:1.5rem}.mt-8{margin-top:2rem}.block{display:block}.inline{display:inline}.flex{display:flex}.grid{display:grid}.hidden{display:none}.h-1{height:.25rem}.h-10{height:2.5rem}.h-12{height:3rem}.h-3{height:.75rem}.h-4{height:1rem}.h-5{height:1.25rem}.h-8{height:2rem}.h-full{height:100%}.h-screen{height:100vh}.min-h-0{min-height:0}.w-0{width:0}.w-1{width:.25rem}.w-10{width:2.5rem}.w-12{width:3rem}.w-3{width:.75rem}.w-32{width:8rem}.w-4{width:1rem}.w-5{width:1.25rem}.w-8{width:2rem}.w-full{width:100%}.w-screen{width:100vw}.min-w-0{min-width:0}.max-w-\[70\%\]{max-width:70%}.max-w-sm{max-width:24rem}.flex-1{flex:1 1 0%}.flex-shrink{flex-shrink:1}.flex-shrink-0{flex-shrink:0}.rotate-90{--tw-rotate:90deg}.rotate-90,.transform{transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.cursor-col-resize{cursor:col-resize}.cursor-pointer{cursor:pointer}.resize{resize:both}.flex-row{flex-direction:row}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-start{align-items:flex-start}.items-center{align-items:center}.items-baseline{align-items:baseline}.justify-center{justify-content:center}.justify-between{justify-content:space-between}.gap-0\.5{gap:.125rem}.gap-1{gap:.25rem}.gap-10{gap:2.5rem}.gap-2{gap:.5rem}.gap-3{gap:.75rem}.gap-4{gap:1rem}.gap-5{gap:1.25rem}.gap-6{gap:1.5rem}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.truncate{overflow:hidden;text-overflow:ellipsis}.truncate,.whitespace-nowrap{white-space:nowrap}.rounded-lg{border-radius:.5rem}.rounded-none{border-radius:0}.border{border-width:1px}.border-2{border-width:2px}.border-4{border-width:4px}.border-b{border-bottom-width:1px}.border-l{border-left-width:1px}.border-l-0{border-left-width:0}.border-l-2{border-left-width:2px}.border-l-\[3px\]{border-left-width:3px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-\[\#333\]{--tw-border-opacity:1;border-color:rgb(51 51 51/var(--tw-border-opacity,1))}.border-\[\#444\]{--tw-border-opacity:1;border-color:rgb(68 68 68/var(--tw-border-opacity,1))}.border-\[\#555\]{--tw-border-opacity:1;border-color:rgb(85 85 85/var(--tw-border-opacity,1))}.border-gray-600{--tw-border-opacity:1;border-color:rgb(75 85 99/var(--tw-border-opacity,1))}.bg-\[\#121212\]{--tw-bg-opacity:1;background-color:rgb(18 18 18/var(--tw-bg-opacity,1))}.bg-\[\#1a1a1a\]{--tw-bg-opacity:1;background-color:rgb(26 26 26/var(--tw-bg-opacity,1))}.bg-\[\#1e1e1e\]{--tw-bg-opacity:1;background-color:rgb(30 30 30/var(--tw-bg-opacity,1))}.bg-\[\#333\]{--tw-bg-opacity:1;background-color:rgb(51 51 51/var(--tw-bg-opacity,1))}.bg-gray-800{--tw-bg-opacity:1;background-color:rgb(31 41 55/var(--tw-bg-opacity,1))}.bg-transparent{background-color:transparent}.bg-white{--tw-bg-opacity:1;background-color:rgb(255 255 255/var(--tw-bg-opacity,1))}.object-contain{-o-object-fit:contain;object-fit:contain}.p-1{padding:.25rem}.p-3{padding:.75rem}.p-4{padding:1rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-5{padding-left:1.25rem;padding-right:1.25rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.px-8{padding-left:2rem;padding-right:2rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-10{padding-top:2.5rem;padding-bottom:2.5rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.pb-40{padding-bottom:10rem}.pb-6{padding-bottom:1.5rem}.pl-4{padding-left:1rem}.pt-1{padding-top:.25rem}.text-center{text-align:center}.text-right{text-align:right}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.text-2xl{font-size:1.5rem;line-height:2rem}.text-\[0\.65rem\]{font-size:.65rem}.text-\[0\.95rem\]{font-size:.95rem}.text-\[10px\]{font-size:10px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-black{font-weight:900}.font-bold{font-weight:700}.font-light{font-weight:300}.font-medium{font-weight:500}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.leading-relaxed{line-height:1.625}.tracking-tight{letter-spacing:-.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-\[\#a0a0a0\]{--tw-text-opacity:1;color:rgb(160 160 160/var(--tw-text-opacity,1))}.text-\[\#e0e0e0\]{--tw-text-opacity:1;color:rgb(224 224 224/var(--tw-text-opacity,1))}.text-gray-500{--tw-text-opacity:1;color:rgb(107 114 128/var(--tw-text-opacity,1))}.text-white{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.placeholder-gray-500::-moz-placeholder{--tw-placeholder-opacity:1;color:rgb(107 114 128/var(--tw-placeholder-opacity,1))}.placeholder-gray-500::placeholder{--tw-placeholder-opacity:1;color:rgb(107 114 128/var(--tw-placeholder-opacity,1))}.opacity-0{opacity:0}.shadow-2xl{--tw-shadow:0 25px 50px -12px rgba(0,0,0,.25);--tw-shadow-colored:0 25px 50px -12px var(--tw-shadow-color)}.shadow-2xl,.shadow-lg{box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow:0 10px 15px -3px rgba(0,0,0,.1),0 4px 6px -4px rgba(0,0,0,.1);--tw-shadow-colored:0 10px 15px -3px var(--tw-shadow-color),0 4px 6px -4px var(--tw-shadow-color)}.shadow-sm{--tw-shadow:0 1px 2px 0 rgba(0,0,0,.05);--tw-shadow-colored:0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow,0 0 #0000),var(--tw-ring-shadow,0 0 #0000),var(--tw-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,-webkit-backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter,-webkit-backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.hover\:scale-110:hover{--tw-scale-x:1.1;--tw-scale-y:1.1;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:bg-\[\#252526\]:hover{--tw-bg-opacity:1;background-color:rgb(37 37 38/var(--tw-bg-opacity,1))}.hover\:bg-\[\#333\]:hover{--tw-bg-opacity:1;background-color:rgb(51 51 51/var(--tw-bg-opacity,1))}.hover\:bg-\[\#555\]:hover{--tw-bg-opacity:1;background-color:rgb(85 85 85/var(--tw-bg-opacity,1))}.hover\:bg-opacity-80:hover{--tw-bg-opacity:0.8}.hover\:text-red-500:hover{--tw-text-opacity:1;color:rgb(239 68 68/var(--tw-text-opacity,1))}.hover\:text-white:hover{--tw-text-opacity:1;color:rgb(255 255 255/var(--tw-text-opacity,1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-75:hover{opacity:.75}.hover\:opacity-80:hover{opacity:.8}.hover\:opacity-90:hover{opacity:.9}.focus\:border-\[\#5e9ddc\]:focus{--tw-border-opacity:1;border-color:rgb(94 157 220/var(--tw-border-opacity,1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px} \ No newline at end of file diff --git a/static/css/tailwind.input.css b/static/css/tailwind.input.css new file mode 100644 index 0000000..b5c61c9 --- /dev/null +++ b/static/css/tailwind.input.css @@ -0,0 +1,3 @@ +@tailwind base; +@tailwind components; +@tailwind utilities; diff --git a/static/index.html b/static/index.html index 46f6eb9..a6b7d11 100644 --- a/static/index.html +++ b/static/index.html @@ -4,114 +4,13 @@ WatchStock - - - - - + + + + + + @@ -174,18 +73,18 @@
-
-
@@ -411,7 +310,6 @@

@@ -423,11 +321,11 @@

-

Generative AI Insights

-

Evaluated natively by OpenRouter LLM

+

AI Analysis

+

AI-written from the data on this page. It can be wrong; not financial advice.

@@ -492,7 +390,7 @@

- ` : ''} -
` : '') + - (aScore ? `
-
ANALYST SCORE
-
${aScore.score}/100
-
` : ''); - } - - function renderSmartMoneySection(metrics, sScore, insiderTxns) { - if (!metrics) return; - const ins = metrics.heldPercentInsiders; - const inst = metrics.heldPercentInstitutions; - const short = metrics.shortPercentOfFloat; - const shortR = metrics.shortRatio; - - const flags = sScore?.flags || []; - - const _isBuy = tx => /purchase|bought|acqui|open market p|\bp\b/i.test(tx); - const _isSell = tx => /sale|sold|dispos|\bs\b/i.test(tx); - const _txnColor = t => { - const tx = t.transaction || ''; - return _isBuy(tx) ? '#4caf50' : _isSell(tx) ? '#f44336' : '#888'; - }; - const _txnLabel = t => { - const tx = t.transaction || ''; - return _isBuy(tx) ? 'BUY' : _isSell(tx) ? 'SELL' : (tx || '?'); - }; - const _txnRow = t => { - const color = _txnColor(t); - const label = _txnLabel(t); - const val = t.value ? '$' + (Math.abs(t.value) / 1e6).toFixed(1) + 'M' : ''; - const isUnknown = label === '?' || label === ''; - const safeText = (t.text || '').replace(/"/g, '"').replace(/No description in data — try UPDATE DATA to refresh.'; - const pillStyle = `font-size:0.6rem; font-weight:700; padding:1px 6px; flex-shrink:0; margin-top:1px; cursor:pointer; letter-spacing:0.5px;`; - const pillColor = isUnknown ? '#f5c518' : color; - const pillHtml = `${isUnknown ? '?' : label}`; - return `
- ${pillHtml} -
-
- ${t.insider || ''} - ${val} -
-
- ${t.title ? `${t.title}` : ''} - ${t.date?.slice(0,10) || ''} -
- -
-
`; - }; - const allTxns = (insiderTxns || []); - const txnList = allTxns.slice(0, 5).map(_txnRow).join(''); - const txnExtra = allTxns.slice(5).map(_txnRow).join(''); - - document.getElementById('smartMoneyData').innerHTML = - metricRow('Insider Ownership', ins != null ? (ins * 100).toFixed(1) + '%' : '—') + - metricRow('Institutional Ownership', inst != null ? (inst * 100).toFixed(1) + '%' : '—') + - metricRow('Short % of Float', short != null ? (short * 100).toFixed(1) + '%' : '—', - short > 0.15 ? '⚠ high' : short > 0.10 ? 'elevated' : '') + - metricRow('Short Ratio (days)', shortR?.toFixed(1)) + - (flags.length ? flags.map(f => `
⚠ ${f}
`).join('') : '') + - (txnList ? `
-
RECENT INSIDER TRANSACTIONS
- ${txnList} - ${txnExtra ? ` - ` : ''} -
` : '') + - (sScore ? `
-
SMART MONEY SCORE
-
${sScore.score}/100
-
` : ''); - } - - // --- Navigation History --- - function addToNavHistory(company, ticker, safetyScore) { - // Add to front of array, dedupe - searchHistory = searchHistory.filter(h => h.ticker !== ticker); - searchHistory.unshift({ company, ticker, time: new Date(), score: safetyScore || null }); - if (searchHistory.length > 10) searchHistory.pop(); - saveUserHistory(); - renderNavHistory(); - } - - function getScoreDotColor(score) { - if (score === null || score === undefined) return '#555'; - if (score >= 65) return '#22c55e'; // green - if (score >= 40) return '#f59e0b'; // amber - return '#ef4444'; // red - } - - function renderNavHistory() { - const navHistory = document.getElementById('navHistory'); - navHistory.innerHTML = ''; - if (searchHistory.length === 0) { - navHistory.innerHTML = '
No searches yet.
'; - return; - } - searchHistory.forEach(h => { - const item = document.createElement('div'); - item.style.cssText = 'display:flex; justify-content:space-between; align-items:center; padding:6px 8px; cursor:pointer; border-bottom:1px solid #2a2a2a; transition: background 0.15s;'; - item.onmouseenter = () => item.style.background = '#252526'; - item.onmouseleave = () => item.style.background = 'transparent'; - - const timeStr = new Date(h.time).toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'}); - const dotColor = getScoreDotColor(h.score); - item.innerHTML = ` -
- - ${h.ticker} - ${h.company} -
- ${timeStr} - `; - item.addEventListener('click', () => { - companyInput.value = h.company; - tickerInput.value = h.ticker; - executeSearch(h.company, h.ticker); - }); - navHistory.appendChild(item); - }); - } - - // --- 1. VIEWS & LAYOUT CONTROL --- - - function toggleSidebar() { - const isCollapsed = sidebar.style.marginLeft === '-260px'; - if (isCollapsed) { - sidebar.style.marginLeft = '0px'; - sidebarIcon.innerHTML = ''; - } else { - sidebar.style.marginLeft = '-260px'; - sidebarIcon.innerHTML = ''; - } - } - - // Tabs logic - document.querySelectorAll('.tab-btn').forEach(btn => { - btn.addEventListener('click', () => { - // Remove active from all - document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); - document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); - // Add active to current - btn.classList.add('active'); - document.getElementById(btn.getAttribute('data-target')).classList.add('active'); - }); - }); - - // --- 2. AUTOCOMPLETE --- - - // --- Reusable Autocomplete --- - function initAutocomplete(inputEl, dropdownEl, companyTarget, tickerTarget) { - let timer; - inputEl.addEventListener('input', function() { - const query = this.value.trim(); - if (query.length < 3) { - dropdownEl.style.display = 'none'; - clearTimeout(timer); - return; - } - clearTimeout(timer); - timer = setTimeout(async () => { - try { - const data = await api(`/api/search?q=${encodeURIComponent(query)}`); - - if (data.length === 0) { - dropdownEl.innerHTML = '
No results found.
'; - } else { - dropdownEl.innerHTML = ''; - data.forEach(item => { - const div = document.createElement('div'); - div.className = 'dropdown-item flex justify-between items-center'; - div.innerHTML = ` - ${item.name} - ${item.ticker} - `; - div.addEventListener('click', () => { - companyTarget.value = item.name; - tickerTarget.value = item.ticker; - dropdownEl.style.display = 'none'; - }); - dropdownEl.appendChild(div); - }); - } - dropdownEl.style.display = 'block'; - } catch (error) { - console.error(error); - } - }, 150); - }); - } - - // Attach autocomplete to BOTH inputs - initAutocomplete(companyInput, dropdown, companyInput, tickerInput); - - const overlayDropdown = document.getElementById('overlayDropdown'); - const overlayCompanyInputEl = document.getElementById('overlayCompanyInput'); - const overlayTickerInputEl = document.getElementById('overlayTickerInput'); - initAutocomplete(overlayCompanyInputEl, overlayDropdown, overlayCompanyInputEl, overlayTickerInputEl); - - document.addEventListener('click', e => { - if (!companyInput.contains(e.target) && !dropdown.contains(e.target)) { - dropdown.style.display = 'none'; - } - if (overlayDropdown && !overlayCompanyInputEl.contains(e.target) && !overlayDropdown.contains(e.target)) { - overlayDropdown.style.display = 'none'; - } - }); - - // --- 3. MAIN SEARCH TRIGGER --- - - // Core search function — callable from initial search, overlay, and chat actions - async function executeSearch(company, ticker) { - if (!company && !ticker) return; - - // Show dashboard if not already visible - const isInitial = !initialView.classList.contains('hidden'); - if (isInitial) { - initialView.classList.add('opacity-0'); - await new Promise(r => setTimeout(r, 500)); - initialView.classList.add('hidden'); - dashboardView.classList.remove('hidden'); - void dashboardView.offsetWidth; - dashboardView.classList.remove('opacity-0'); - } - - loadingOverlay.classList.remove('hidden'); - try { - if (!ticker) { - const matches = await api(`/api/search?q=${encodeURIComponent(company)}`); - if (!matches.length) throw new Error(`No stock found for "${company}".`); - ticker = matches[0].ticker; - company = matches[0].name; - } - await loadStock(ticker, company, false); - } catch (err) { - console.error(err); - showToast(err.message, 6000); - if (!currentRawData) { // first search failed: go back to the home screen - dashboardView.classList.add('hidden', 'opacity-0'); - initialView.classList.remove('hidden', 'opacity-0'); - } - } finally { - loadingOverlay.classList.add('hidden'); - } - } - - // Fetch one stock snapshot and render it. Throws on failure. - async function loadStock(ticker, company, refresh) { - const params = new URLSearchParams({ name: company || '' }); - if (refresh) params.set('refresh', 'true'); - const data = await api(`/api/stocks/${encodeURIComponent(ticker)}?${params}`); - currentRawData = data; - populateDashboard(data); - updateAsOf(data); - - let avgScore = null; - if (data.safety) { - const st = data.safety.short_term?.score || 0; - const lt = data.safety.long_term?.score || 0; - avgScore = Math.round((st + lt) / 2); - } - addToNavHistory(data.company_name, data.ticker, avgScore); - if (data.warnings?.length) showToast(data.warnings.join(' '), 6000); - - // Show the stored report if there is one; otherwise generate one in the background. - if (data.ai_analysis) renderAiAnalysis(data.ai_analysis); - else if (llmConfigured) requestAnalysis(); - else showNoKeyHint(); - } - - // Whether an OpenRouter key is saved. Without one we don't auto-request reports. - let llmConfigured = true; - async function refreshLlmStatus() { - try { llmConfigured = (await api('/api/settings')).llm_api_key_set; } catch (e) {} - } - - function showNoKeyHint() { - document.getElementById('aiLoading').classList.add('hidden'); - aiSummary.innerText = 'AI analysis is off. Add an OpenRouter API key in Settings (gear icon), then press "Request Synthesis".'; - aiAction.innerText = ''; - aiAnalysisResult.classList.remove('hidden'); - } - - function updateAsOf(data) { - const el = document.getElementById('asOfLabel'); - if (!el) return; - el.textContent = data.as_of ? `data ${timeAgo(data.as_of)}${data.stale ? ' · offline' : ''}` : ''; - el.style.color = data.stale ? '#ff9800' : '#666'; - el.title = data.as_of ? 'Fetched ' + new Date(data.as_of).toLocaleString() : ''; - } - - searchBtn.addEventListener('click', () => { - const company = companyInput.value.trim(); - const ticker = tickerInput.value.trim(); - if (!company) { - alert("Please enter a company name."); - companyInput.focus(); - return; - } - executeSearch(company, ticker); - }); - - // --- 4. POPULATE DASHBOARD --- - - function populateDashboard(data) { - // Destroy all existing Chart.js instances and remove appended chart wrappers - document.querySelectorAll('canvas').forEach(c => { - const chart = Chart.getChart(c); - if (chart) chart.destroy(); - }); - dynamicChartInstance = null; - - // Reset logo glow - document.getElementById('companyLogoBox').style.boxShadow = 'none'; - - // Reset AI Analysis tab to its original structure (remove appended Agent Insight / chart divs) - const aiResult = document.getElementById('aiAnalysisResult'); - aiResult.querySelectorAll('.mt-8').forEach(el => el.remove()); - aiResult.classList.add('hidden'); - - // Reset verdict badge to placeholder state - const verdictBadge = document.getElementById('verdictBadge'); - if (verdictBadge) { verdictBadge.textContent = '—'; verdictBadge.style.borderColor = '#444'; verdictBadge.style.color = '#666'; verdictBadge.style.background = 'transparent'; } - document.getElementById('verdictConfidenceRow')?.classList.add('hidden'); - document.getElementById('verdictHorizonRow')?.classList.add('hidden'); - - // Clear charts grid - const chartsGrid = document.getElementById('chartsGrid'); - if (chartsGrid) { chartsGrid.querySelectorAll('canvas').forEach(c => { const ch = Chart.getChart(c); if (ch) ch.destroy(); }); chartsGrid.innerHTML = ''; } - document.getElementById('chartsSection')?.classList.add('hidden'); - - // Reset text sections - document.getElementById('newsImpactSection')?.classList.add('hidden'); - document.getElementById('financialDeepDiveSection')?.classList.add('hidden'); - document.getElementById('changesSection')?.classList.add('hidden'); - document.getElementById('riskScenariosSection')?.classList.add('hidden'); - - // Build Sidebar - sbTicker.innerText = data.ticker || 'N/A'; - updateWatchlistStar(data.ticker); - sbLogoInitials.innerText = (data.ticker || data.company_name.substring(0,2)).substring(0,2).toUpperCase(); - - const sbLogoImg = document.getElementById('sbLogoImg'); - sbLogoImg.classList.add('hidden'); - sbLogoInitials.style.display = 'block'; - - if (data.company_domain) { - // Try multiple logo sources with fallback chain - const domain = data.company_domain; - const logoSources = [ - `https://img.logo.dev/${domain}?token=pk_anonymous&size=128`, - `https://www.google.com/s2/favicons?domain=${domain}&sz=128`, - `https://logo.clearbit.com/${domain}` - ]; - - let sourceIdx = 0; - function tryNextLogo() { - if (sourceIdx >= logoSources.length) { - sbLogoImg.classList.add('hidden'); - sbLogoInitials.style.display = 'block'; - return; - } - sbLogoImg.src = logoSources[sourceIdx]; - sourceIdx++; - } - - sbLogoImg.onload = () => { - sbLogoImg.classList.remove('hidden'); - sbLogoInitials.style.display = 'none'; - }; - sbLogoImg.onerror = () => tryNextLogo(); - tryNextLogo(); - } - - const metrics = data.financial_data?.metrics || {}; - const cap = metrics.marketCap ? '$' + (metrics.marketCap/1e9).toFixed(2) + 'B' : 'N/A'; - sbMarketCap.innerText = cap; - const price = metrics.currentPrice; - sbPrice.innerText = price != null ? '$' + parseFloat(price).toFixed(2) : 'N/A'; - - // --- TradingView Widget --- - const tvContainer = document.getElementById('tradingViewContainer'); - tvContainer.innerHTML = ''; - if (data.ticker) { - tvContainer.style.display = 'block'; - const tvScript = document.createElement('script'); - tvScript.src = 'https://s3.tradingview.com/external-embedding/embed-widget-advanced-chart.js'; - tvScript.type = 'text/javascript'; - tvScript.async = true; - tvScript.innerHTML = JSON.stringify({ - "autosize": true, "symbol": data.tradingview_symbol || data.ticker, "interval": "D", - "timezone": "Etc/UTC", "theme": "dark", "style": "1", - "locale": "en", "allow_symbol_change": false, - "backgroundColor": "rgba(19, 23, 34, 1)", - "gridColor": "rgba(51, 51, 51, 0.3)", - "hide_top_toolbar": false, "hide_legend": true, - "save_image": false, "height": "100%", "width": "100%" - }); - tvContainer.appendChild(tvScript); - } else { - tvContainer.style.display = 'none'; - } - - // ---- Opportunity Score banner ---- - renderOpportunityScore(data.scores); - - // ---- Three-column deep dive ---- - renderValuationSection(metrics, data.scores?.valuation); - renderAnalystSection(data.financial_data?.analyst_data, data.scores?.analyst, data.financial_data?.upgrades_downgrades); - renderSmartMoneySection(metrics, data.scores?.smart_money, data.financial_data?.insider_transactions); - - // ---- Fundamentals metric cards ---- - const metricCards = document.getElementById('metricCards'); - metricCards.innerHTML = ''; - const cardKeys = [ - 'currentRatio','quickRatio','profitMargins','operatingMargins', - 'revenueGrowth','earningsGrowth','trailingEps','forwardEps', - 'debtToEquity','freeCashflow','dividendYield','beta','marketCap' - ]; - cardKeys.forEach(key => { - const def = METRIC_DESCRIPTIONS[key]; - if (!def) return; - const val = metrics[key]; - if (val == null) return; - const card = document.createElement('div'); - card.style.cssText = 'background:#1a1a1a; border:1px solid #333; padding:14px 16px; transition:border-color 0.2s; cursor:default;'; - card.onmouseenter = () => card.style.borderColor = '#555'; - card.onmouseleave = () => card.style.borderColor = '#333'; - const tier = METRIC_HEALTH[key]?.(val) ?? 'neutral'; - const vColor = HEALTH_COLOR[tier]; - card.innerHTML = ` -
${def.label}
-
${def.format(val)}
-
${def.desc}
- `; - metricCards.appendChild(card); - }); - - // Officers string (Only CEO) - sbCEOList.innerHTML = ''; - if (data.financial_data?.key_officers) { - data.financial_data.key_officers.slice(0, 1).forEach(o => { - let wpLink = `https://en.wikipedia.org/wiki/Special:Search?search=${encodeURIComponent(o.name)}`; - sbCEOList.innerHTML += `${o.name}${o.title}`; - }); - } - - // Sidebar Risk Badges - if (data.safety) { - sidebarRiskScores.classList.remove('hidden'); - const st = data.safety.short_term.score; - const lt = data.safety.long_term.score; - sbStCircle.innerText = st; - sbStCircle.style.color = `hsl(${st * 1.2}, 100%, 50%)`; - sbStCircle.style.borderColor = `hsl(${st * 1.2}, 100%, 40%)`; - - sbLtCircle.innerText = lt; - sbLtCircle.style.color = `hsl(${lt * 1.2}, 100%, 50%)`; - sbLtCircle.style.borderColor = `hsl(${lt * 1.2}, 100%, 40%)`; - - // Logo glow based on average safety - const avg = (st + lt) / 2; - const glowHue = avg * 1.2; // 0=red, 60=yellow, 120=green - document.getElementById('companyLogoBox').style.boxShadow = `0 0 12px hsla(${glowHue}, 100%, 45%, 0.4)`; - } - - // financeContent kept hidden for agentic-chat tab injection compatibility - - // News — headlines from Yahoo Finance for this ticker - newsContent.innerHTML = ''; - const news = data.news || []; - if (news.length === 0) { - newsContent.innerHTML = '

No recent news found for this stock.

'; - } - news.forEach(item => { - let domain = ''; - try { domain = new URL(item.url).hostname; } catch (e) {} - const card = document.createElement('div'); - card.style.cssText = 'border:1px solid #333; padding:16px; margin-bottom:12px; background:#1a1a1a; transition: border-color 0.2s;'; - card.onmouseenter = () => card.style.borderColor = '#555'; - card.onmouseleave = () => card.style.borderColor = '#333'; - card.innerHTML = ` -
- ${domain ? `` : ''} - ${esc(item.title)} -
- ${item.summary ? `

${esc(item.summary)}

` : ''} -
${esc(item.publisher)}${item.published_at ? ' · ' + timeAgo(item.published_at) : ''}
- `; - newsContent.appendChild(card); - }); - } - - const VERDICT_COLORS = { - 'STRONG BUY': { border: '#52b788', color: '#52b788', bg: 'rgba(82,183,136,0.12)' }, - 'BUY': { border: '#69db7c', color: '#69db7c', bg: 'rgba(105,219,124,0.12)' }, - 'HOLD': { border: '#ffd43b', color: '#ffd43b', bg: 'rgba(255,212,59,0.12)' }, - 'REDUCE': { border: '#ff8c42', color: '#ff8c42', bg: 'rgba(255,140,66,0.12)' }, - 'STRONG SELL': { border: '#ff4444', color: '#ff4444', bg: 'rgba(255,68,68,0.12)' }, - 'SELL': { border: '#ff6b6b', color: '#ff6b6b', bg: 'rgba(255,107,107,0.12)' }, - }; - - // --- Render AI Analysis (from cache or API) --- - function renderAiAnalysis(aiData) { - if (!aiData) return; - - aiSummary.innerText = aiData.executive_summary || "No summary provided."; - const modelLabel = document.getElementById('aiModelLabel'); - if (modelLabel && aiData.model) { - modelLabel.textContent = `Analysed by ${aiData.model}` + (aiData.created_at ? ` · ${new Date(aiData.created_at).toLocaleString()}` : ''); - } - - // Verdict badge - const verdict = aiData.verdict || {}; - const rawAction = (verdict.action || aiData.recommended_action || '').toUpperCase(); - let colors = { border: '#444', color: '#666', bg: 'transparent' }; - let badgeText = rawAction || '—'; - for (const [key, val] of Object.entries(VERDICT_COLORS)) { - if (rawAction.includes(key)) { colors = val; badgeText = key; break; } - } - const verdictBadge = document.getElementById('verdictBadge'); - verdictBadge.textContent = badgeText; - verdictBadge.style.borderColor = colors.border; - verdictBadge.style.color = colors.color; - verdictBadge.style.background = colors.bg; - - const confRow = document.getElementById('verdictConfidenceRow'); - if (verdict.confidence != null) { - document.getElementById('verdictConfidenceBar').style.background = colors.border; - document.getElementById('verdictConfidenceBar').style.width = verdict.confidence + '%'; - document.getElementById('verdictConfidenceVal').textContent = verdict.confidence + '/100'; - confRow.classList.remove('hidden'); - } else { - confRow.classList.add('hidden'); - } - - const horizonRow = document.getElementById('verdictHorizonRow'); - if (verdict.horizon) { - document.getElementById('verdictHorizon').textContent = verdict.horizon; - horizonRow.classList.remove('hidden'); - } else { - horizonRow.classList.add('hidden'); - } - - aiAction.innerText = aiData.recommended_action || ''; - - // What changed since the previous report (only when there was one) - const changesSection = document.getElementById('changesSection'); - if (aiData.changes_since_last) { - document.getElementById('changesContent').innerHTML = marked.parse(aiData.changes_since_last); - changesSection.classList.remove('hidden'); - } else { - changesSection.classList.add('hidden'); - } - - // Financial Deep Dive - const deepDiveSection = document.getElementById('financialDeepDiveSection'); - const deepDiveContent = document.getElementById('financialDeepDiveContent'); - if (aiData.financial_deep_dive) { - deepDiveContent.innerHTML = marked.parse(aiData.financial_deep_dive); - deepDiveSection.classList.remove('hidden'); - } else { - deepDiveSection.classList.add('hidden'); - } - - // News Impact Analysis - const newsImpactSection = document.getElementById('newsImpactSection'); - const newsImpactContent = document.getElementById('newsImpactContent'); - if (aiData.news_impact_analysis) { - newsImpactContent.innerHTML = marked.parse(aiData.news_impact_analysis); - newsImpactSection.classList.remove('hidden'); - } else { - newsImpactSection.classList.add('hidden'); - } - - // Risk Scenarios - const riskSection = document.getElementById('riskScenariosSection'); - const riskContent = document.getElementById('riskScenariosContent'); - if (aiData.risk_scenarios) { - riskContent.innerHTML = marked.parse(aiData.risk_scenarios); - riskSection.classList.remove('hidden'); - } else { - riskSection.classList.add('hidden'); - } - - // Charts — support new `charts` array OR legacy `dynamic_ui_config` - const chartsSection = document.getElementById('chartsSection'); - const chartsGrid = document.getElementById('chartsGrid'); - const chartConfigs = aiData.charts || (aiData.dynamic_ui_config ? [aiData.dynamic_ui_config] : []); - - chartsGrid.querySelectorAll('canvas').forEach(c => { const ch = Chart.getChart(c); if (ch) ch.destroy(); }); - chartsGrid.innerHTML = ''; - dynamicChartInstance = null; - - if (chartConfigs.length > 0) { - chartConfigs.forEach((cfg, i) => { - const uid = 'aiChart_' + i; - const wrapper = document.createElement('div'); - wrapper.className = 'bg-[#1a1a1a] border border-[#333] p-4'; - const canvas = document.createElement('canvas'); - canvas.id = uid; - canvas.style.maxHeight = '240px'; - wrapper.appendChild(canvas); - chartsGrid.appendChild(wrapper); - }); - chartConfigs.forEach((cfg, i) => { - const instance = createChart('aiChart_' + i, cfg); - if (i === 0) dynamicChartInstance = instance; - }); - chartsSection.classList.remove('hidden'); - } else { - chartsSection.classList.add('hidden'); - } - - // Show the result panel, hide loading - const aiLoading = document.getElementById('aiLoading'); - aiLoading.classList.add('hidden'); - aiLoading.classList.add('opacity-0'); - aiAnalysisResult.classList.remove('hidden'); - - // Store on raw data for chat context - if (currentRawData) currentRawData.ai_analysis = aiData; - } - - // --- 5. AI GENERATION LOGIC --- - - async function requestAnalysis() { - if (!currentRawData || btnAiAnalyze.disabled) return; - const ticker = currentRawData.ticker; - - btnAiAnalyze.disabled = true; - const orgHtml = btnAiAnalyze.innerHTML; - btnAiAnalyze.innerHTML = '
Standby...'; - - aiAnalysisResult.classList.add('hidden'); - const aiLoading = document.getElementById('aiLoading'); - const aiProgressBar = document.getElementById('aiProgressBar'); - aiLoading.classList.remove('hidden'); - void aiLoading.offsetWidth; // trigger reflow - aiLoading.classList.remove('opacity-0'); - - let width = 0; - const progressInterval = setInterval(() => { - width += (100 - width) * 0.15; - aiProgressBar.style.width = width + '%'; - }, 300); - - try { - const data = await api(`/api/stocks/${encodeURIComponent(ticker)}/analysis`, { method: 'POST' }); - if (currentRawData?.ticker === ticker) renderAiAnalysis(data); - } catch (err) { - if (currentRawData?.ticker === ticker) { - aiLoading.classList.add('hidden'); - aiSummary.innerText = 'Analysis failed: ' + err.message; - aiAction.innerText = ''; - aiAnalysisResult.classList.remove('hidden'); - } - } finally { - clearInterval(progressInterval); - aiProgressBar.style.width = '100%'; - setTimeout(() => { - aiLoading.classList.add('hidden'); - aiLoading.classList.add('opacity-0'); - btnAiAnalyze.disabled = false; - btnAiAnalyze.innerHTML = orgHtml; - }, 400); - } - } - - btnAiAnalyze.addEventListener('click', requestAnalysis); - - // Downloads - function downloadJSON() { - if (!currentRawData) return; - const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(currentRawData, null, 2)); - const anchor = document.createElement('a'); - anchor.href = dataStr; - anchor.download = `Terminal_${currentRawData.ticker || 'Export'}.json`; - anchor.click(); - } - - // --- 6. CHAT & RESIZE LOGIC --- - const oldChatBar = document.getElementById('oldChatBar'); - const oldChatInput = document.getElementById('oldChatInput'); - const oldChatSendBtn = document.getElementById('oldChatSendBtn'); - - const rightChatPanel = document.getElementById('rightChatPanel'); - const chatResizer = document.getElementById('chatResizer'); - const closeRightChatBtn = document.getElementById('closeRightChatBtn'); - const rightChatInput = document.getElementById('rightChatInput'); - const rightChatSendBtn = document.getElementById('rightChatSendBtn'); - const chatHistory = document.getElementById('chatHistory'); - let conversationMessages = []; // Tracks full chat history for multi-turn LLM context - - // Launch Right Chat Sequence - function triggerChatOpen(initialMsg) { - if (!initialMsg) return; - - oldChatBar.style.display = 'none'; - rightChatPanel.style.display = 'flex'; - chatResizer.style.display = 'block'; - chatResizer.classList.remove('hidden'); - - // Auto-switch to AI Analysis tab - switchToAiTab(); - - rightChatInput.focus(); - appendChatMessage("USER", initialMsg); - sendChatToLLM(initialMsg); - } - - function switchToAiTab() { - document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); - document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); - const aiBtn = document.querySelector('.tab-btn[data-target="tab-ai"]'); - if (aiBtn) aiBtn.classList.add('active'); - const aiTab = document.getElementById('tab-ai'); - if (aiTab) aiTab.classList.add('active'); - } - - function appendChatMessage(role, text, isMarkdown) { - const div = document.createElement('div'); - div.className = 'w-full flex-shrink-0 flex flex-col gap-1'; - - const isUser = role === 'USER'; - - const roleLabel = document.createElement('span'); - roleLabel.className = 'text-[10px] font-bold tracking-wider'; - roleLabel.style.color = isUser ? '#e0e0e0' : 'var(--accent)'; - roleLabel.innerText = role; - - const pBox = document.createElement('div'); - if (isUser) { - pBox.className = 'p-3 text-sm font-light text-[#e0e0e0] bg-[#1a1a1a] border-l-2 border-[#555]'; - pBox.innerText = text; - // Track user message for conversation history - conversationMessages.push({ role: 'user', content: text }); - } else { - pBox.className = 'p-3 text-sm text-[#e0e0e0] bg-[#121212] border border-[#333]'; - if (isMarkdown) { - pBox.innerHTML = marked.parse(text); - } else { - pBox.innerText = text; - } - } - - div.appendChild(roleLabel); - div.appendChild(pBox); - chatHistory.appendChild(div); - chatHistory.scrollTop = chatHistory.scrollHeight; - return pBox; - } - - async function sendChatToLLM(question) { - // Show thinking indicator - const thinkingBox = appendChatMessage("SYSTEM", "Analyzing..."); - thinkingBox.innerHTML = '
Processing query...
'; - - try { - const result = await api('/api/chat', { - method: 'POST', - body: { - question: question, - stock: currentRawData, - history: conversationMessages, - existing_chart_titles: getExistingChartTitles(), - }, - }); - - if (!result) { - thinkingBox.innerText = "No response."; - } else { - const replyText = result.reply_text || result.answer || "No response."; - thinkingBox.innerHTML = marked.parse(replyText); - conversationMessages.push({ role: 'assistant', content: replyText }); - - // Handle ui_action — could be an object or nested inside reply - let uiAction = result.ui_action; - - // Fallback: if LLM embedded action JSON in reply_text, try to extract it - if (!uiAction && typeof replyText === 'string') { - const actionMatch = replyText.match(/\{"action"\s*:\s*"[^"]+"/); - if (actionMatch) { - try { - const jsonStart = replyText.indexOf(actionMatch[0]); - let depth = 0, end = jsonStart; - for (let i = jsonStart; i < replyText.length; i++) { - if (replyText[i] === '{') depth++; - if (replyText[i] === '}') depth--; - if (depth === 0) { end = i + 1; break; } - } - uiAction = JSON.parse(replyText.substring(jsonStart, end)); - } catch(e) {} - } - } - - if (uiAction) { - handleUiAction(uiAction); - } - // Support array of actions (ui_actions) - if (result.ui_actions && Array.isArray(result.ui_actions)) { - result.ui_actions.forEach(a => handleUiAction(a)); - } - } - } catch(err) { - thinkingBox.innerText = "Error: " + err.message; - thinkingBox.style.color = '#ff6b6b'; - } - chatHistory.scrollTop = chatHistory.scrollHeight; - } - - // Handle dynamic UI actions from chat LLM - function handleUiAction(action) { - if (!action || !action.action) return; - - if (action.action === 'update_chart') { - if (action.labels && action.values) { - // Ensure the canvas exists — it may have been destroyed by update_tab_content - let canvas = document.getElementById('dynamicChart'); - if (!canvas) { - // Recreate the chart container inside AI analysis result - const aiResult = document.getElementById('aiAnalysisResult'); - if (aiResult) { - const wrapper = document.createElement('div'); - wrapper.className = 'pl-4 border-l-[3px]'; - wrapper.style.borderLeftColor = 'var(--accent)'; - wrapper.innerHTML = ` -

Dynamic Metric Plot

-
- -
`; - aiResult.appendChild(wrapper); - canvas = document.getElementById('dynamicChart'); - } - } - if (!canvas) return; - - if (dynamicChartInstance) dynamicChartInstance.destroy(); - dynamicChartInstance = createChart('dynamicChart', action); - // Make sure AI result is visible and switch to AI tab - document.getElementById('aiAnalysisResult')?.classList.remove('hidden'); - switchToAiTab(); - } - } else if (action.action === 'switch_tab') { - const targetTab = action.tab || 'tab-ai'; - document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); - document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); - const btn = document.querySelector(`.tab-btn[data-target="${targetTab}"]`); - if (btn) btn.classList.add('active'); - const tab = document.getElementById(targetTab); - if (tab) tab.classList.add('active'); - } else if (action.action === 'search_company') { - // LLM wants to search another company - const newCompany = action.company_name || ''; - const newTicker = action.ticker || ''; - if (newCompany && newTicker) { - appendChatMessage('SYSTEM', `Switching to ${newCompany} (${newTicker})...`); - conversationMessages = []; - companyInput.value = newCompany; - tickerInput.value = newTicker; - executeSearch(newCompany, newTicker); - } - } else if (action.action === 'update_tab_content') { - // Agentic UI: LLM appends styled HTML content to a tab (preserves existing) - const tabMap = { - 'tab-ai': 'aiAnalysisResult', - 'tab-finance': 'financeContent', - 'tab-news': 'newsContent', - 'ai-analysis': 'aiAnalysisResult', - 'finance': 'financeContent', - 'news': 'newsContent' - }; - const containerId = tabMap[action.target_tab] || 'aiAnalysisResult'; - const container = document.getElementById(containerId); - if (container && action.new_content) { - // Wrap injected content in the standard terminal styling - const wrapper = document.createElement('div'); - wrapper.className = 'pl-4 border-l-[3px] mt-8'; - wrapper.style.borderLeftColor = '#a78bfa'; - wrapper.innerHTML = `

Agent Insight

${action.new_content}
`; - - if (action.content_type === 'replace') { - container.innerHTML = ''; - container.appendChild(wrapper); - } else { - // Default: append (preserve existing analysis) - container.appendChild(wrapper); - } - container.classList.remove('hidden'); - // Switch to the target tab - const tabId = action.target_tab?.startsWith('tab-') ? action.target_tab : 'tab-' + action.target_tab; - const tabBtn = document.querySelector(`.tab-btn[data-target="${tabId}"]`); - if (tabBtn) tabBtn.click(); - } - } else if (action.action === 'append_new_chart') { - // Append a brand-new chart to the AI Analysis tab (or specified tab) - const cfg = action.chart_config || action; - if (cfg.labels && cfg.values) { - const tabMap = { 'tab-ai': 'aiAnalysisResult', 'tab-finance': 'financeContent', 'tab-news': 'newsContent', 'ai-analysis': 'aiAnalysisResult' }; - const containerId = tabMap[action.target_tab] || 'aiAnalysisResult'; - const container = document.getElementById(containerId); - if (!container) return; - - const uniqueId = 'dynamicChart_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5); - - const wrapper = document.createElement('div'); - wrapper.className = 'pl-4 border-l-[3px] mt-8'; - wrapper.style.borderLeftColor = 'var(--accent)'; - wrapper.innerHTML = ` -

${cfg.title || 'Chart'}

-
- -
`; - container.appendChild(wrapper); - container.classList.remove('hidden'); - - createChart(uniqueId, cfg); - switchToAiTab(); - } - } else if (action.action === 'highlight_risk') { - // Flash risk indicators - const circles = [document.getElementById('sbStCircle'), document.getElementById('sbLtCircle')]; - circles.forEach(c => { - if (c) { - c.style.transition = 'transform 0.3s, box-shadow 0.3s'; - c.style.transform = 'scale(1.3)'; - c.style.boxShadow = '0 0 15px rgba(255,100,100,0.6)'; - setTimeout(() => { c.style.transform = 'scale(1)'; c.style.boxShadow = 'none'; }, 2000); - } - }); - } - } - - // Force Update: bypass cache and re-fetch fresh data - async function forceUpdateSupplier() { - if (!currentRawData) return; - const btn = document.getElementById('btnForceUpdate'); - btn.innerText = 'REFRESHING...'; - btn.style.opacity = '0.5'; - btn.disabled = true; - try { - await loadStock(currentRawData.ticker, currentRawData.company_name, true); - } catch (err) { - showToast(err.message, 6000); - } finally { - btn.innerText = 'REFRESH'; - btn.style.opacity = '1'; - btn.disabled = false; - } - } - - oldChatSendBtn.addEventListener('click', () => { - const val = oldChatInput.value.trim(); - if(val) { oldChatInput.value = ''; triggerChatOpen(val); } - }); - - oldChatInput.addEventListener('keypress', (e) => { - if (e.key === 'Enter') { - const val = oldChatInput.value.trim(); - if(val) { oldChatInput.value = ''; triggerChatOpen(val); } - } - }); - - rightChatSendBtn.addEventListener('click', () => { - const val = rightChatInput.value.trim(); - if(val) { - rightChatInput.value = ''; - appendChatMessage("USER", val); - sendChatToLLM(val); - } - }); - - rightChatInput.addEventListener('keypress', (e) => { - if (e.key === 'Enter') { - const val = rightChatInput.value.trim(); - if(val) { - rightChatInput.value = ''; - appendChatMessage("USER", val); - sendChatToLLM(val); - } - } - }); - - closeRightChatBtn.addEventListener('click', () => { - rightChatPanel.style.display = 'none'; - chatResizer.classList.add('hidden'); - oldChatBar.style.display = 'flex'; - }); - - // --- DRAG TO RESIZE LOGIC --- - let isResizing = false; - - chatResizer.addEventListener('mousedown', (e) => { - e.preventDefault(); // Prevents defaults on mousedown - isResizing = true; - document.body.style.userSelect = 'none'; // Prevent text selection during resize - document.body.style.cursor = 'col-resize'; - }); - - document.addEventListener('mousemove', (e) => { - if (!isResizing) return; - - // Right Panel is clamped on the right bounding box - // Distance from Right Edge = Window Width - current MouseX - let newWidth = window.innerWidth - e.clientX; - - // Clamp between 250px and 800px per specifications - if (newWidth < 250) newWidth = 250; - if (newWidth > 800) newWidth = 800; - - rightChatPanel.style.width = newWidth + 'px'; - }); - - document.addEventListener('mouseup', () => { - if (isResizing) { - isResizing = false; - document.body.style.userSelect = ''; - document.body.style.cursor = ''; - } - }); - - // --- 7. TOPBAR SEARCH OVERLAY --- - const searchOverlay = document.getElementById('searchOverlay'); - const overlayCompanyInput = document.getElementById('overlayCompanyInput'); - const overlayTickerInput = document.getElementById('overlayTickerInput'); - const overlaySearchBtn = document.getElementById('overlaySearchBtn'); - const topbarSearchBtn = document.getElementById('topbarSearchBtn'); - - function openSearchOverlay() { - searchOverlay.classList.add('visible'); - setTimeout(() => overlayCompanyInput.focus(), 50); - } - - function closeSearchOverlay(e) { - // Close only if clicking backdrop (not inner box) - if (e && e.target !== searchOverlay) return; - searchOverlay.classList.remove('visible'); - } - - function triggerOverlaySearch() { - const company = overlayCompanyInput.value.trim(); - const ticker = overlayTickerInput.value.trim(); - if (!company) { overlayCompanyInput.focus(); return; } - searchOverlay.classList.remove('visible'); - companyInput.value = company; - tickerInput.value = ticker; - executeSearch(company, ticker); - } - - topbarSearchBtn.addEventListener('click', openSearchOverlay); - overlaySearchBtn.addEventListener('click', triggerOverlaySearch); - - overlayCompanyInput.addEventListener('keydown', (e) => { - if (e.key === 'Enter') triggerOverlaySearch(); - if (e.key === 'Escape') searchOverlay.classList.remove('visible'); - }); - overlayTickerInput.addEventListener('keydown', (e) => { - if (e.key === 'Enter') triggerOverlaySearch(); - if (e.key === 'Escape') searchOverlay.classList.remove('visible'); - }); - - document.addEventListener('keydown', (e) => { - if (e.key === 'Escape') searchOverlay.classList.remove('visible'); - }); - - + + + + + + + + + + diff --git a/static/js/analysis.js b/static/js/analysis.js new file mode 100644 index 0000000..591e1f4 --- /dev/null +++ b/static/js/analysis.js @@ -0,0 +1,191 @@ +// AI report: rendering, requesting a new one, JSON export. +// Plain script (not a module): all files share one global scope and load in the +// order listed in index.html. Top-level code may only call functions from earlier files. + +const VERDICT_COLORS = { + 'STRONG BUY': { border: '#52b788', color: '#52b788', bg: 'rgba(82,183,136,0.12)' }, + 'BUY': { border: '#69db7c', color: '#69db7c', bg: 'rgba(105,219,124,0.12)' }, + 'HOLD': { border: '#ffd43b', color: '#ffd43b', bg: 'rgba(255,212,59,0.12)' }, + 'REDUCE': { border: '#ff8c42', color: '#ff8c42', bg: 'rgba(255,140,66,0.12)' }, + 'STRONG SELL': { border: '#ff4444', color: '#ff4444', bg: 'rgba(255,68,68,0.12)' }, + 'SELL': { border: '#ff6b6b', color: '#ff6b6b', bg: 'rgba(255,107,107,0.12)' }, +}; + +// --- Render AI Analysis (from cache or API) --- +function renderAiAnalysis(aiData) { + if (!aiData) return; + + aiSummary.innerText = aiData.executive_summary || "No summary provided."; + const modelLabel = document.getElementById('aiModelLabel'); + if (modelLabel && aiData.model) { + modelLabel.textContent = `Analysed by ${aiData.model}` + (aiData.created_at ? ` · ${new Date(aiData.created_at).toLocaleString()}` : ''); + } + + // Verdict badge + const verdict = aiData.verdict || {}; + const rawAction = (verdict.action || aiData.recommended_action || '').toUpperCase(); + let colors = { border: '#444', color: '#666', bg: 'transparent' }; + let badgeText = rawAction || '—'; + for (const [key, val] of Object.entries(VERDICT_COLORS)) { + if (rawAction.includes(key)) { colors = val; badgeText = key; break; } + } + const verdictBadge = document.getElementById('verdictBadge'); + verdictBadge.textContent = badgeText; + verdictBadge.style.borderColor = colors.border; + verdictBadge.style.color = colors.color; + verdictBadge.style.background = colors.bg; + + const confRow = document.getElementById('verdictConfidenceRow'); + if (verdict.confidence != null) { + document.getElementById('verdictConfidenceBar').style.background = colors.border; + document.getElementById('verdictConfidenceBar').style.width = verdict.confidence + '%'; + document.getElementById('verdictConfidenceVal').textContent = verdict.confidence + '/100'; + confRow.classList.remove('hidden'); + } else { + confRow.classList.add('hidden'); + } + + const horizonRow = document.getElementById('verdictHorizonRow'); + if (verdict.horizon) { + document.getElementById('verdictHorizon').textContent = verdict.horizon; + horizonRow.classList.remove('hidden'); + } else { + horizonRow.classList.add('hidden'); + } + + aiAction.innerText = aiData.recommended_action || ''; + + // What changed since the previous report (only when there was one) + const changesSection = document.getElementById('changesSection'); + if (aiData.changes_since_last) { + document.getElementById('changesContent').innerHTML = renderMarkdown(aiData.changes_since_last); + changesSection.classList.remove('hidden'); + } else { + changesSection.classList.add('hidden'); + } + + // Financial Deep Dive + const deepDiveSection = document.getElementById('financialDeepDiveSection'); + const deepDiveContent = document.getElementById('financialDeepDiveContent'); + if (aiData.financial_deep_dive) { + deepDiveContent.innerHTML = renderMarkdown(aiData.financial_deep_dive); + deepDiveSection.classList.remove('hidden'); + } else { + deepDiveSection.classList.add('hidden'); + } + + // News Impact Analysis + const newsImpactSection = document.getElementById('newsImpactSection'); + const newsImpactContent = document.getElementById('newsImpactContent'); + if (aiData.news_impact_analysis) { + newsImpactContent.innerHTML = renderMarkdown(aiData.news_impact_analysis); + newsImpactSection.classList.remove('hidden'); + } else { + newsImpactSection.classList.add('hidden'); + } + + // Risk Scenarios + const riskSection = document.getElementById('riskScenariosSection'); + const riskContent = document.getElementById('riskScenariosContent'); + if (aiData.risk_scenarios) { + riskContent.innerHTML = renderMarkdown(aiData.risk_scenarios); + riskSection.classList.remove('hidden'); + } else { + riskSection.classList.add('hidden'); + } + + // Charts — support new `charts` array OR legacy `dynamic_ui_config` + const chartsSection = document.getElementById('chartsSection'); + const chartsGrid = document.getElementById('chartsGrid'); + const chartConfigs = aiData.charts || (aiData.dynamic_ui_config ? [aiData.dynamic_ui_config] : []); + + chartsGrid.querySelectorAll('canvas').forEach(c => { const ch = Chart.getChart(c); if (ch) ch.destroy(); }); + chartsGrid.innerHTML = ''; + dynamicChartInstance = null; + + if (chartConfigs.length > 0) { + chartConfigs.forEach((cfg, i) => { + const uid = 'aiChart_' + i; + const wrapper = document.createElement('div'); + wrapper.className = 'bg-[#1a1a1a] border border-[#333] p-4'; + const canvas = document.createElement('canvas'); + canvas.id = uid; + canvas.style.maxHeight = '240px'; + wrapper.appendChild(canvas); + chartsGrid.appendChild(wrapper); + }); + chartConfigs.forEach((cfg, i) => { + const instance = createChart('aiChart_' + i, cfg); + if (i === 0) dynamicChartInstance = instance; + }); + chartsSection.classList.remove('hidden'); + } else { + chartsSection.classList.add('hidden'); + } + + // Show the result panel, hide loading + const aiLoading = document.getElementById('aiLoading'); + aiLoading.classList.add('hidden'); + aiLoading.classList.add('opacity-0'); + aiAnalysisResult.classList.remove('hidden'); + + // Store on raw data for chat context + if (currentRawData) currentRawData.ai_analysis = aiData; +} + +// --- 5. AI GENERATION LOGIC --- + +async function requestAnalysis() { + if (!currentRawData || btnAiAnalyze.disabled) return; + const ticker = currentRawData.ticker; + + btnAiAnalyze.disabled = true; + const orgHtml = btnAiAnalyze.innerHTML; + btnAiAnalyze.innerHTML = '
Standby...'; + + aiAnalysisResult.classList.add('hidden'); + const aiLoading = document.getElementById('aiLoading'); + const aiProgressBar = document.getElementById('aiProgressBar'); + aiLoading.classList.remove('hidden'); + void aiLoading.offsetWidth; // trigger reflow + aiLoading.classList.remove('opacity-0'); + + let width = 0; + const progressInterval = setInterval(() => { + width += (100 - width) * 0.15; + aiProgressBar.style.width = width + '%'; + }, 300); + + try { + const data = await api(`/api/stocks/${encodeURIComponent(ticker)}/analysis`, { method: 'POST' }); + if (currentRawData?.ticker === ticker) renderAiAnalysis(data); + } catch (err) { + if (currentRawData?.ticker === ticker) { + aiLoading.classList.add('hidden'); + aiSummary.innerText = 'Analysis failed: ' + err.message; + aiAction.innerText = ''; + aiAnalysisResult.classList.remove('hidden'); + } + } finally { + clearInterval(progressInterval); + aiProgressBar.style.width = '100%'; + setTimeout(() => { + aiLoading.classList.add('hidden'); + aiLoading.classList.add('opacity-0'); + btnAiAnalyze.disabled = false; + btnAiAnalyze.innerHTML = orgHtml; + }, 400); + } +} + +btnAiAnalyze.addEventListener('click', requestAnalysis); + +// Downloads +function downloadJSON() { + if (!currentRawData) return; + const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(currentRawData, null, 2)); + const anchor = document.createElement('a'); + anchor.href = dataStr; + anchor.download = `Terminal_${currentRawData.ticker || 'Export'}.json`; + anchor.click(); +} diff --git a/static/js/charts.js b/static/js/charts.js new file mode 100644 index 0000000..0830a3a --- /dev/null +++ b/static/js/charts.js @@ -0,0 +1,61 @@ +// Chart.js helpers. Colours come from a fixed palette; LLM-supplied colours are ignored. +// Plain script (not a module): all files share one global scope and load in the +// order listed in index.html. Top-level code may only call functions from earlier files. + +// --- Terminal Chart Color Palette (strict, LLM colors are ignored) --- +const TERMINAL_COLORS = ['#0078D4', '#00CC6A', '#D13438', '#FFB900', '#8A2BE2', '#00BFFF', '#FF8C00']; + +function getChartColors(labels) { + return labels.map((label, i) => { + const l = (label || '').toLowerCase(); + if (l.includes('debt') || l.includes('risk') || l.includes('loss') || l.includes('penalty')) return '#D13438'; + if (l.includes('profit') || l.includes('cash') || l.includes('safety') || l.includes('growth') || l.includes('revenue')) return '#00CC6A'; + return TERMINAL_COLORS[i % TERMINAL_COLORS.length]; + }); +} + +function createChart(canvasId, cfg) { + const canvas = document.getElementById(canvasId); + if (!canvas) return null; + const ctx = canvas.getContext('2d'); + Chart.defaults.color = '#a0a0a0'; + Chart.defaults.borderColor = '#333333'; + const labels = cfg.labels || []; + const colors = getChartColors(labels); + return new Chart(ctx, { + type: cfg.type || cfg.chart_type || 'bar', + data: { + labels: labels, + datasets: [{ + label: cfg.title || 'Metric', + data: cfg.values || [], + backgroundColor: colors.map(c => c + '66'), + borderColor: colors, + borderWidth: 1 + }] + }, + options: { + responsive: true, + plugins: { + title: { display: true, text: cfg.title || '', color: '#e0e0e0', font: { size: 14, family: 'monospace' } }, + legend: { labels: { font: { family: 'monospace' } } } + }, + scales: { + x: { ticks: { font: { family: 'monospace' } } }, + y: { ticks: { font: { family: 'monospace' } } } + } + } + }); +} + +function getExistingChartTitles() { + const titles = []; + document.querySelectorAll('canvas').forEach(c => { + const chart = Chart.getChart(c); + if (chart) { + const t = chart.options?.plugins?.title?.text; + if (t) titles.push(t); + } + }); + return titles; +} diff --git a/static/js/chat.js b/static/js/chat.js new file mode 100644 index 0000000..bec945e --- /dev/null +++ b/static/js/chat.js @@ -0,0 +1,294 @@ +// Chat panel: messages, LLM round-trip, UI actions the model may request, resize. +// Plain script (not a module): all files share one global scope and load in the +// order listed in index.html. Top-level code may only call functions from earlier files. + +// --- 6. CHAT & RESIZE LOGIC --- +const oldChatBar = document.getElementById('oldChatBar'); +const oldChatInput = document.getElementById('oldChatInput'); +const oldChatSendBtn = document.getElementById('oldChatSendBtn'); + +const rightChatPanel = document.getElementById('rightChatPanel'); +const chatResizer = document.getElementById('chatResizer'); +const closeRightChatBtn = document.getElementById('closeRightChatBtn'); +const rightChatInput = document.getElementById('rightChatInput'); +const rightChatSendBtn = document.getElementById('rightChatSendBtn'); +const chatHistory = document.getElementById('chatHistory'); +let conversationMessages = []; // Tracks full chat history for multi-turn LLM context + +// Launch Right Chat Sequence +function triggerChatOpen(initialMsg) { + if (!initialMsg) return; + + oldChatBar.style.display = 'none'; + rightChatPanel.style.display = 'flex'; + chatResizer.style.display = 'block'; + chatResizer.classList.remove('hidden'); + + // Auto-switch to AI Analysis tab + switchToAiTab(); + + rightChatInput.focus(); + appendChatMessage("USER", initialMsg); + sendChatToLLM(initialMsg); +} + +function switchToAiTab() { + document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); + document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); + const aiBtn = document.querySelector('.tab-btn[data-target="tab-ai"]'); + if (aiBtn) aiBtn.classList.add('active'); + const aiTab = document.getElementById('tab-ai'); + if (aiTab) aiTab.classList.add('active'); +} + +function appendChatMessage(role, text, isMarkdown) { + const div = document.createElement('div'); + div.className = 'w-full flex-shrink-0 flex flex-col gap-1'; + + const isUser = role === 'USER'; + + const roleLabel = document.createElement('span'); + roleLabel.className = 'text-[10px] font-bold tracking-wider'; + roleLabel.style.color = isUser ? '#e0e0e0' : 'var(--accent)'; + roleLabel.innerText = role; + + const pBox = document.createElement('div'); + if (isUser) { + pBox.className = 'p-3 text-sm font-light text-[#e0e0e0] bg-[#1a1a1a] border-l-2 border-[#555]'; + pBox.innerText = text; + // Track user message for conversation history + conversationMessages.push({ role: 'user', content: text }); + } else { + pBox.className = 'p-3 text-sm text-[#e0e0e0] bg-[#121212] border border-[#333]'; + if (isMarkdown) { + pBox.innerHTML = renderMarkdown(text); + } else { + pBox.innerText = text; + } + } + + div.appendChild(roleLabel); + div.appendChild(pBox); + chatHistory.appendChild(div); + chatHistory.scrollTop = chatHistory.scrollHeight; + return pBox; +} + +async function sendChatToLLM(question) { + // Show thinking indicator + const thinkingBox = appendChatMessage("SYSTEM", "Analyzing..."); + thinkingBox.innerHTML = '
Processing query...
'; + + try { + const result = await api('/api/chat', { + method: 'POST', + body: { + question: question, + stock: currentRawData, + history: conversationMessages, + existing_chart_titles: getExistingChartTitles(), + }, + }); + + if (!result) { + thinkingBox.innerText = "No response."; + } else { + const replyText = result.reply_text || result.answer || "No response."; + thinkingBox.innerHTML = renderMarkdown(replyText); + conversationMessages.push({ role: 'assistant', content: replyText }); + + // Handle ui_action — could be an object or nested inside reply + let uiAction = result.ui_action; + + // Fallback: if LLM embedded action JSON in reply_text, try to extract it + if (!uiAction && typeof replyText === 'string') { + const actionMatch = replyText.match(/\{"action"\s*:\s*"[^"]+"/); + if (actionMatch) { + try { + const jsonStart = replyText.indexOf(actionMatch[0]); + let depth = 0, end = jsonStart; + for (let i = jsonStart; i < replyText.length; i++) { + if (replyText[i] === '{') depth++; + if (replyText[i] === '}') depth--; + if (depth === 0) { end = i + 1; break; } + } + uiAction = JSON.parse(replyText.substring(jsonStart, end)); + } catch(e) {} + } + } + + if (uiAction) { + handleUiAction(uiAction); + } + // Support array of actions (ui_actions) + if (result.ui_actions && Array.isArray(result.ui_actions)) { + result.ui_actions.forEach(a => handleUiAction(a)); + } + } + } catch(err) { + thinkingBox.innerText = "Error: " + err.message; + thinkingBox.style.color = '#ff6b6b'; + } + chatHistory.scrollTop = chatHistory.scrollHeight; +} + +// Handle dynamic UI actions from chat LLM +function handleUiAction(action) { + if (!action || !action.action) return; + + if (action.action === 'update_chart') { + if (action.labels && action.values) { + // Recreate the canvas if it isn't on the page yet + let canvas = document.getElementById('dynamicChart'); + if (!canvas) { + // Recreate the chart container inside AI analysis result + const aiResult = document.getElementById('aiAnalysisResult'); + if (aiResult) { + const wrapper = document.createElement('div'); + wrapper.className = 'pl-4 border-l-[3px]'; + wrapper.style.borderLeftColor = 'var(--accent)'; + wrapper.innerHTML = ` +

Dynamic Metric Plot

+
+ +
`; + aiResult.appendChild(wrapper); + canvas = document.getElementById('dynamicChart'); + } + } + if (!canvas) return; + + if (dynamicChartInstance) dynamicChartInstance.destroy(); + dynamicChartInstance = createChart('dynamicChart', action); + // Make sure AI result is visible and switch to AI tab + document.getElementById('aiAnalysisResult')?.classList.remove('hidden'); + switchToAiTab(); + } + } else if (action.action === 'switch_tab') { + const targetTab = action.tab || 'tab-ai'; + document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); + document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); + const btn = document.querySelector(`.tab-btn[data-target="${targetTab}"]`); + if (btn) btn.classList.add('active'); + const tab = document.getElementById(targetTab); + if (tab) tab.classList.add('active'); + } else if (action.action === 'search_company') { + // LLM wants to search another company + const newCompany = action.company_name || ''; + const newTicker = action.ticker || ''; + if (newCompany && newTicker) { + appendChatMessage('SYSTEM', `Switching to ${newCompany} (${newTicker})...`); + conversationMessages = []; + companyInput.value = newCompany; + tickerInput.value = newTicker; + executeSearch(newCompany, newTicker); + } + } else if (action.action === 'append_new_chart') { + // Append a brand-new chart to the AI Analysis tab (or specified tab) + const cfg = action.chart_config || action; + if (cfg.labels && cfg.values) { + const tabMap = { 'tab-ai': 'aiAnalysisResult', 'tab-news': 'newsContent', 'ai-analysis': 'aiAnalysisResult' }; + const containerId = tabMap[action.target_tab] || 'aiAnalysisResult'; + const container = document.getElementById(containerId); + if (!container) return; + + const uniqueId = 'dynamicChart_' + Date.now() + '_' + Math.random().toString(36).substr(2, 5); + + const wrapper = document.createElement('div'); + wrapper.className = 'pl-4 border-l-[3px] mt-8'; + wrapper.style.borderLeftColor = 'var(--accent)'; + wrapper.innerHTML = ` +

${cfg.title || 'Chart'}

+
+ +
`; + container.appendChild(wrapper); + container.classList.remove('hidden'); + + createChart(uniqueId, cfg); + switchToAiTab(); + } + } else if (action.action === 'highlight_risk') { + // Flash risk indicators + const circles = [document.getElementById('sbStCircle'), document.getElementById('sbLtCircle')]; + circles.forEach(c => { + if (c) { + c.style.transition = 'transform 0.3s, box-shadow 0.3s'; + c.style.transform = 'scale(1.3)'; + c.style.boxShadow = '0 0 15px rgba(255,100,100,0.6)'; + setTimeout(() => { c.style.transform = 'scale(1)'; c.style.boxShadow = 'none'; }, 2000); + } + }); + } +} + +// Force Update: bypass cache and re-fetch fresh data +oldChatSendBtn.addEventListener('click', () => { + const val = oldChatInput.value.trim(); + if(val) { oldChatInput.value = ''; triggerChatOpen(val); } +}); + +oldChatInput.addEventListener('keypress', (e) => { + if (e.key === 'Enter') { + const val = oldChatInput.value.trim(); + if(val) { oldChatInput.value = ''; triggerChatOpen(val); } + } +}); + +rightChatSendBtn.addEventListener('click', () => { + const val = rightChatInput.value.trim(); + if(val) { + rightChatInput.value = ''; + appendChatMessage("USER", val); + sendChatToLLM(val); + } +}); + +rightChatInput.addEventListener('keypress', (e) => { + if (e.key === 'Enter') { + const val = rightChatInput.value.trim(); + if(val) { + rightChatInput.value = ''; + appendChatMessage("USER", val); + sendChatToLLM(val); + } + } +}); + +closeRightChatBtn.addEventListener('click', () => { + rightChatPanel.style.display = 'none'; + chatResizer.classList.add('hidden'); + oldChatBar.style.display = 'flex'; +}); + +// --- DRAG TO RESIZE LOGIC --- +let isResizing = false; + +chatResizer.addEventListener('mousedown', (e) => { + e.preventDefault(); // Prevents defaults on mousedown + isResizing = true; + document.body.style.userSelect = 'none'; // Prevent text selection during resize + document.body.style.cursor = 'col-resize'; +}); + +document.addEventListener('mousemove', (e) => { + if (!isResizing) return; + + // Right Panel is clamped on the right bounding box + // Distance from Right Edge = Window Width - current MouseX + let newWidth = window.innerWidth - e.clientX; + + // Clamp between 250px and 800px per specifications + if (newWidth < 250) newWidth = 250; + if (newWidth > 800) newWidth = 800; + + rightChatPanel.style.width = newWidth + 'px'; +}); + +document.addEventListener('mouseup', () => { + if (isResizing) { + isResizing = false; + document.body.style.userSelect = ''; + document.body.style.cursor = ''; + } +}); diff --git a/static/js/core.js b/static/js/core.js new file mode 100644 index 0000000..0fbe2ef --- /dev/null +++ b/static/js/core.js @@ -0,0 +1,143 @@ +// Shared helpers and state: API calls, escaping, formatting, DOM handles, toast. +// Plain script (not a module): all files share one global scope and load in the +// order listed in index.html. Top-level code may only call functions from earlier files. + +// Configure marked: all links open in new tab so they never navigate away from the SPA. +// marked >= 13 passes a single token object to renderers (the old (href, title, text) +// signature rendered every link as "undefined"). +marked.use({ + renderer: { + link({ href, title, tokens }) { + const text = this.parser.parseInline(tokens); + return `${text}`; + } + } +}); + +// Constants & State +const companyInput = document.getElementById('companyInput'); +const tickerInput = document.getElementById('tickerInput'); +const dropdown = document.getElementById('dropdown'); +const searchBtn = document.getElementById('searchBtn'); + +// View containers +const initialView = document.getElementById('initialView'); +const dashboardView = document.getElementById('dashboardView'); +const loadingOverlay = document.getElementById('loadingOverlay'); + +// Sidebar +const sidebar = document.getElementById('sidebar'); +const sidebarIcon = document.getElementById('sidebarIcon'); +const sbLogoInitials = document.getElementById('sbLogoInitials'); +const sbTicker = document.getElementById('sbTicker'); +const sbCompanyName = document.getElementById('sbCompanyName'); +const sbMarketCap = document.getElementById('sbMarketCap'); +const sbPrice = document.getElementById('sbPrice'); +const sbCEOList = document.getElementById('sbCEOList'); +const sidebarRiskScores = document.getElementById('sidebarRiskScores'); +const sbStCircle = document.getElementById('sbStCircle'); +const sbLtCircle = document.getElementById('sbLtCircle'); + +// Main Content +const newsContent = document.getElementById('newsContent'); + +// AI +const btnAiAnalyze = document.getElementById('btnAiAnalyze'); +const aiAnalysisResult = document.getElementById('aiAnalysisResult'); +const aiSummary = document.getElementById('aiSummary'); +const aiAction = document.getElementById('aiAction'); + +let currentRawData = null; +let dynamicChartInstance = null; + +// ---- API helper ---- +// All backend calls go through here: JSON in/out, throws Error(detail) on non-2xx. +async function api(path, options = {}) { + const opts = { ...options, headers: { 'Content-Type': 'application/json', ...(options.headers || {}) } }; + if (opts.body && typeof opts.body !== 'string') opts.body = JSON.stringify(opts.body); + const res = await fetch(path, opts); + let data = null; + try { data = await res.json(); } catch (e) {} + if (!res.ok) { + const detail = data?.detail; + throw new Error(typeof detail === 'string' ? detail : `Request failed (${res.status})`); + } + return data; +} + +function esc(value) { + return String(value ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c])); +} + +// Markdown from the LLM -> sanitised HTML. Model output is untrusted (it reads news +// articles), so it never reaches innerHTML without DOMPurify. +function renderMarkdown(text) { + return DOMPurify.sanitize(marked.parse(String(text ?? '')), { + ADD_ATTR: ['target'], + FORBID_TAGS: ['img', 'style', 'form', 'input', 'iframe'], // no remote images/tracking pixels + }); +} + +// ---- Money ---- +// Prices are in `metrics.currency`; statement values (FCF, revenue) in +// `metrics.financialCurrency` (different for e.g. foreign companies listed in the US). +// Yahoo uses minor units for a few markets: GBp = pence, ZAc = cents, ILA = agorot. +const MINOR_UNITS = { GBp: ['GBP', 'p'], GBX: ['GBP', 'p'], ZAc: ['ZAR', 'c'], ILA: ['ILS', 'ag'] }; + +function priceCurrency() { + return currentRawData?.financial_data?.metrics?.currency || 'USD'; +} + +function statementCurrency() { + const m = currentRawData?.financial_data?.metrics || {}; + return m.financialCurrency || m.currency || 'USD'; +} + +function fmtMoney(value, currency = 'USD', digits = 2) { + if (value == null || isNaN(value)) return 'N/A'; + const minor = MINOR_UNITS[currency]; + if (minor) { + return Number(value).toLocaleString('en-US', { minimumFractionDigits: digits, maximumFractionDigits: digits }) + ' ' + minor[1]; + } + try { + return new Intl.NumberFormat('en-US', { + style: 'currency', currency, minimumFractionDigits: digits, maximumFractionDigits: digits, + }).format(value); + } catch (e) { + return `${Number(value).toFixed(digits)} ${currency}`; + } +} + +// Large amounts in compact form: $3.08T, €70.1B, -$512M. +// Assumes Yahoo reports aggregates (market cap, cash flow) in major units even for GBp quotes. +function fmtBig(value, currency = 'USD') { + if (value == null || isNaN(value)) return 'N/A'; + const major = MINOR_UNITS[currency]?.[0] || currency; + try { + return new Intl.NumberFormat('en-US', { + style: 'currency', currency: major, notation: 'compact', maximumFractionDigits: 2, + }).format(value); + } catch (e) { + return `${(value / 1e9).toFixed(2)}B ${currency}`; + } +} + +function timeAgo(iso) { + if (!iso) return ''; + const secs = (Date.now() - new Date(iso).getTime()) / 1000; + if (isNaN(secs)) return ''; + if (secs < 60) return 'just now'; + if (secs < 3600) return `${Math.floor(secs / 60)}m ago`; + if (secs < 86400) return `${Math.floor(secs / 3600)}h ago`; + return `${Math.floor(secs / 86400)}d ago`; +} + + +// ---- Toast ---- +function showToast(msg, duration = 2500) { + const el = document.getElementById('toastMsg'); + el.textContent = msg; + el.style.display = 'block'; + clearTimeout(el._t); + el._t = setTimeout(() => { el.style.display = 'none'; }, duration); +} diff --git a/static/js/dashboard.js b/static/js/dashboard.js new file mode 100644 index 0000000..408a47a --- /dev/null +++ b/static/js/dashboard.js @@ -0,0 +1,494 @@ +// Stock dashboard: sidebar, finance tab sections, metric cards, news tab, nav history. +// Plain script (not a module): all files share one global scope and load in the +// order listed in index.html. Top-level code may only call functions from earlier files. + +// --- Metric Definitions (Fundamentals cards) --- +const fmtPct = v => v != null ? (v * 100).toFixed(1) + '%' : 'N/A'; +const fmtNum = (d=2) => v => v?.toFixed(d) ?? 'N/A'; +const METRIC_DESCRIPTIONS = { + currentRatio: { label: 'Current Ratio', desc: 'Short-term assets vs liabilities. Above 1.0 means more assets than obligations.', format: fmtNum(2) }, + quickRatio: { label: 'Quick Ratio', desc: 'Current ratio excluding inventory — stricter liquidity test.', format: fmtNum(2) }, + profitMargins: { label: 'Profit Margin', desc: 'Net income as % of revenue. The higher, the more efficient the business.', format: fmtPct }, + operatingMargins: { label: 'Operating Margin', desc: 'Profit after operating costs but before interest/taxes.', format: fmtPct }, + revenueGrowth: { label: 'Revenue Growth', desc: 'Year-over-year revenue change.', format: fmtPct }, + earningsGrowth: { label: 'Earnings Growth', desc: 'Year-over-year earnings change.', format: fmtPct }, + trailingEps: { label: 'EPS (Trailing)', desc: 'Earnings per share over the last 12 months.', format: v => fmtMoney(v, priceCurrency()) }, + forwardEps: { label: 'EPS (Forward)', desc: 'Analyst-estimated earnings per share for next 12 months.', format: v => fmtMoney(v, priceCurrency()) }, + debtToEquity: { label: 'Debt / Equity', desc: 'Total debt relative to shareholders equity. Lower = less leverage risk.', format: fmtNum(2) }, + freeCashflow: { label: 'Free Cash Flow', desc: 'Cash generated after capex. Positive = company funds itself without borrowing.', format: v => fmtBig(v, statementCurrency()) }, + dividendYield: { label: 'Dividend Yield', desc: 'Annual dividend as % of current price.', + format: v => v != null ? (v * 100).toFixed(2) + '%' : 'N/A' }, // backend sends a fraction + beta: { label: 'Beta', desc: 'Volatility vs the market. < 1.0 = defensive, > 1.5 = highly volatile.', format: fmtNum(2) }, + marketCap: { label: 'Market Cap', desc: 'Total market value of all outstanding shares.', format: v => fmtBig(v, priceCurrency()) }, +}; + +// Maps each metric key to a health tier: 'good' | 'ok' | 'bad' | 'neutral' +const METRIC_HEALTH = { + currentRatio: v => v >= 2 ? 'good' : v >= 1 ? 'ok' : 'bad', + quickRatio: v => v >= 1 ? 'good' : v >= 0.5 ? 'ok' : 'bad', + profitMargins: v => v >= 0.15 ? 'good' : v >= 0.05 ? 'ok' : v >= 0 ? 'neutral' : 'bad', + operatingMargins: v => v >= 0.15 ? 'good' : v >= 0.05 ? 'ok' : v >= 0 ? 'neutral' : 'bad', + revenueGrowth: v => v >= 0.10 ? 'good' : v >= 0 ? 'ok' : 'bad', + earningsGrowth: v => v >= 0.15 ? 'good' : v >= 0 ? 'ok' : 'bad', + trailingEps: v => v > 0 ? 'good' : 'bad', + forwardEps: v => v > 0 ? 'good' : 'bad', + debtToEquity: v => v < 50 ? 'good' : v < 150 ? 'ok' : 'bad', + freeCashflow: v => v > 0 ? 'good' : 'bad', + dividendYield: () => 'neutral', + beta: v => v < 1 ? 'good' : v < 1.5 ? 'ok' : 'bad', + marketCap: () => 'neutral', +}; +const HEALTH_COLOR = { good: '#4caf50', ok: '#ffc107', bad: '#f44336', neutral: '#a0a0a0' }; + +// --- Finance Tab Rendering Helpers --- + +function scoreColor(s) { + return s >= 70 ? '#4caf50' : s >= 50 ? '#ffc107' : s >= 30 ? '#ff9800' : '#f44336'; +} + +function metricRow(label, value, note) { + return `
+ ${label} + ${value ?? '—'}${note ? `${note}` : ''} +
`; +} + +function renderOpportunityScore(scores) { + if (!scores?.opportunity) return; + const opp = scores.opportunity; + document.getElementById('opportunityBanner').style.display = 'block'; + document.getElementById('oppScoreNum').textContent = opp.score; + document.getElementById('oppScoreNum').style.color = opp.color; + document.getElementById('oppScoreLabel').textContent = opp.label; + document.getElementById('oppScoreLabel').style.color = opp.color; + const bar = document.getElementById('oppScoreBar'); + bar.style.width = opp.score + '%'; + bar.style.background = opp.color; + + document.getElementById('subScoresGrid').innerHTML = (opp.components || []).map(c => ` +
+
${c.score}
+
${esc(c.label)}
+
${esc(c.weight)}
+
click for breakdown
+
`).join(''); +} + +function renderValuationSection(metrics, vScore) { + if (!metrics) return; + const cur = metrics.currentPrice, h52 = metrics.fiftyTwoWeekHigh, l52 = metrics.fiftyTwoWeekLow; + const pos = (cur && h52 && l52 && h52 > l52) ? ((cur - l52) / (h52 - l52) * 100).toFixed(1) : null; + const upside = (metrics.targetMeanPrice && cur) ? (((metrics.targetMeanPrice - cur) / cur) * 100).toFixed(1) : null; + + let rangeBar = ''; + if (pos !== null) { + rangeBar = `
+
+ 52w Low ${fmtMoney(l52, priceCurrency())}52w High ${fmtMoney(h52, priceCurrency())} +
+
+
+
+
${pos}% of 52-week range${vScore?.position_pct != null ? ' · ' + (pos < 30 ? 'near bottom ↓' : pos > 70 ? 'near peak ↑' : 'mid-range') : ''}
+
`; + } + + document.getElementById('valuationData').innerHTML = + metricRow('Trailing P/E', metrics.trailingPE?.toFixed(1)) + + metricRow('Forward P/E', metrics.forwardPE?.toFixed(1), metrics.forwardPE < metrics.trailingPE ? 'earnings growing ↑' : '') + + metricRow('PEG Ratio', metrics.pegRatio?.toFixed(2), metrics.pegRatio < 1 ? '< 1.0 = cheap for growth' : '') + + metricRow('Price / Book', metrics.priceToBook?.toFixed(2)) + + metricRow('Price / Sales', metrics.priceToSalesTrailingTwelveMonths?.toFixed(2)) + + metricRow('EV / EBITDA', metrics.enterpriseToEbitda?.toFixed(1)) + + rangeBar + + (vScore ? `
+
VALUATION SCORE
+
${vScore.score}/100
+
` : ''); +} + +function renderAnalystSection(analystData, aScore, upgrades) { + if (!analystData) return; + const rec = analystData.recommendationKey || ''; + const recLabels = { strongbuy: 'Strong Buy', buy: 'Buy', hold: 'Hold', underperform: 'Underperform', sell: 'Sell' }; + const recColors = { strongbuy: '#4caf50', buy: '#8bc34a', hold: '#ffc107', underperform: '#ff9800', sell: '#f44336' }; + const recKey = rec.replace('_','').toLowerCase(); + const recLabel = recLabels[recKey] || rec; + const recColor = recColors[recKey] || '#888'; + const mean = analystData.recommendationMean; + const tgt = analystData.targetMeanPrice; + const tgtLow = analystData.targetLowPrice; + const tgtHigh = analystData.targetHighPrice; + const n = analystData.numberOfAnalystOpinions; + + // Bull/bear bar (1=all buy, 5=all sell) + const bullPct = mean ? Math.round((5 - mean) / 4 * 100) : 50; + const upside = aScore?.upside_pct; + + let tgtRange = ''; + if (tgtLow && tgtHigh && tgt) { + const span = tgtHigh - tgtLow; + const meanPct = span > 0 ? ((tgt - tgtLow) / span * 100).toFixed(0) : 50; + tgtRange = `
+
+ Low ${fmtMoney(tgtLow, priceCurrency(), 0)}Mean ${fmtMoney(tgt, priceCurrency(), 0)}High ${fmtMoney(tgtHigh, priceCurrency(), 0)} +
+
+
+
+
`; + } + + const ticker = currentRawData?.ticker || ''; + const _ratingRow = u => { + const isUp = (u.action||'').toLowerCase() === 'upgrade' || ['buy','strong buy','outperform','overweight','positive'].includes((u.to_grade||'').toLowerCase()); + const isDown = (u.action||'').toLowerCase() === 'downgrade' || ['sell','underperform','underweight','negative'].includes((u.to_grade||'').toLowerCase()); + const arrow = isUp ? '▲' : isDown ? '▼' : '·'; + const gradeColor = isUp ? '#4caf50' : isDown ? '#f44336' : '#888'; + const searchUrl = `https://www.google.com/search?q=${encodeURIComponent((u.firm||'') + ' ' + ticker + ' ' + (u.to_grade||'') + ' analyst rating')}`; + return `
+ ${arrow} + ${u.date?.slice(0,10) || ''} + ${u.firm || ''} + ${u.to_grade || ''} +
`; + }; + const allUpgrades = (upgrades || []); + const upgradeList = allUpgrades.slice(0, 5).map(_ratingRow).join(''); + const upgradeExtra = allUpgrades.slice(5).map(_ratingRow).join(''); + + document.getElementById('analystData').innerHTML = + `
+ ${recLabel || '—'} + ${n ? n + ' analysts' : ''} +
` + + (mean ? `
+
+
+
+
SellBuy
+
` : '') + + metricRow('Mean Target', tgt ? fmtMoney(tgt, priceCurrency()) : '—', upside != null ? `${upside > 0 ? '+' : ''}${upside}% upside` : '') + + tgtRange + + (upgradeList ? `
+
RECENT RATINGS
+ ${upgradeList} + ${upgradeExtra ? ` + ` : ''} +
` : '') + + (aScore ? `
+
ANALYST SCORE
+
${aScore.score}/100
+
` : ''); +} + +function renderSmartMoneySection(metrics, sScore, insiderTxns) { + if (!metrics) return; + const ins = metrics.heldPercentInsiders; + const inst = metrics.heldPercentInstitutions; + const short = metrics.shortPercentOfFloat; + const shortR = metrics.shortRatio; + + const flags = sScore?.flags || []; + + const _isBuy = tx => /purchase|bought|acqui|open market p|\bp\b/i.test(tx); + const _isSell = tx => /sale|sold|dispos|\bs\b/i.test(tx); + const _txnColor = t => { + const tx = t.transaction || ''; + return _isBuy(tx) ? '#4caf50' : _isSell(tx) ? '#f44336' : '#888'; + }; + const _txnLabel = t => { + const tx = t.transaction || ''; + return _isBuy(tx) ? 'BUY' : _isSell(tx) ? 'SELL' : (tx || '?'); + }; + const _txnRow = t => { + const color = _txnColor(t); + const label = _txnLabel(t); + const val = t.value ? fmtBig(Math.abs(t.value), 'USD') : ''; // SEC filings are in USD + const isUnknown = label === '?' || label === ''; + const safeText = (t.text || '').replace(/"/g, '"').replace(/No description in data — try UPDATE DATA to refresh.'; + const pillStyle = `font-size:0.6rem; font-weight:700; padding:1px 6px; flex-shrink:0; margin-top:1px; cursor:pointer; letter-spacing:0.5px;`; + const pillColor = isUnknown ? '#f5c518' : color; + const pillHtml = `${isUnknown ? '?' : label}`; + return `
+ ${pillHtml} +
+
+ ${t.insider || ''} + ${val} +
+
+ ${t.title ? `${t.title}` : ''} + ${t.date?.slice(0,10) || ''} +
+ +
+
`; + }; + const allTxns = (insiderTxns || []); + const txnList = allTxns.slice(0, 5).map(_txnRow).join(''); + const txnExtra = allTxns.slice(5).map(_txnRow).join(''); + + document.getElementById('smartMoneyData').innerHTML = + metricRow('Insider Ownership', ins != null ? (ins * 100).toFixed(1) + '%' : '—') + + metricRow('Institutional Ownership', inst != null ? (inst * 100).toFixed(1) + '%' : '—') + + metricRow('Short % of Float', short != null ? (short * 100).toFixed(1) + '%' : '—', + short > 0.15 ? '⚠ high' : short > 0.10 ? 'elevated' : '') + + metricRow('Short Ratio (days)', shortR?.toFixed(1)) + + (flags.length ? flags.map(f => `
⚠ ${f}
`).join('') : '') + + (txnList ? `
+
RECENT INSIDER TRANSACTIONS
+ ${txnList} + ${txnExtra ? ` + ` : ''} +
` : '') + + (sScore ? `
+
SMART MONEY SCORE
+
${sScore.score}/100
+
` : ''); +} + +// --- Navigation History --- +function addToNavHistory(company, ticker, safetyScore) { + // Add to front of array, dedupe + searchHistory = searchHistory.filter(h => h.ticker !== ticker); + searchHistory.unshift({ company, ticker, time: new Date(), score: safetyScore || null }); + if (searchHistory.length > 10) searchHistory.pop(); + saveUserHistory(); + renderNavHistory(); +} + +function getScoreDotColor(score) { + if (score === null || score === undefined) return '#555'; + if (score >= 65) return '#22c55e'; // green + if (score >= 40) return '#f59e0b'; // amber + return '#ef4444'; // red +} + +function renderNavHistory() { + const navHistory = document.getElementById('navHistory'); + navHistory.innerHTML = ''; + if (searchHistory.length === 0) { + navHistory.innerHTML = '
No searches yet.
'; + return; + } + searchHistory.forEach(h => { + const item = document.createElement('div'); + item.style.cssText = 'display:flex; justify-content:space-between; align-items:center; padding:6px 8px; cursor:pointer; border-bottom:1px solid #2a2a2a; transition: background 0.15s;'; + item.onmouseenter = () => item.style.background = '#252526'; + item.onmouseleave = () => item.style.background = 'transparent'; + + const timeStr = new Date(h.time).toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'}); + const dotColor = getScoreDotColor(h.score); + item.innerHTML = ` +
+ + ${h.ticker} + ${h.company} +
+ ${timeStr} + `; + item.addEventListener('click', () => { + companyInput.value = h.company; + tickerInput.value = h.ticker; + executeSearch(h.company, h.ticker); + }); + navHistory.appendChild(item); + }); +} + + +// --- 4. POPULATE DASHBOARD --- + +function populateDashboard(data) { + // Destroy all existing Chart.js instances and remove appended chart wrappers + document.querySelectorAll('canvas').forEach(c => { + const chart = Chart.getChart(c); + if (chart) chart.destroy(); + }); + dynamicChartInstance = null; + + // Reset logo glow + document.getElementById('companyLogoBox').style.boxShadow = 'none'; + + // Reset AI Analysis tab to its original structure (remove appended Agent Insight / chart divs) + const aiResult = document.getElementById('aiAnalysisResult'); + aiResult.querySelectorAll('.mt-8').forEach(el => el.remove()); + aiResult.classList.add('hidden'); + + // Reset verdict badge to placeholder state + const verdictBadge = document.getElementById('verdictBadge'); + if (verdictBadge) { verdictBadge.textContent = '—'; verdictBadge.style.borderColor = '#444'; verdictBadge.style.color = '#666'; verdictBadge.style.background = 'transparent'; } + document.getElementById('verdictConfidenceRow')?.classList.add('hidden'); + document.getElementById('verdictHorizonRow')?.classList.add('hidden'); + + // Clear charts grid + const chartsGrid = document.getElementById('chartsGrid'); + if (chartsGrid) { chartsGrid.querySelectorAll('canvas').forEach(c => { const ch = Chart.getChart(c); if (ch) ch.destroy(); }); chartsGrid.innerHTML = ''; } + document.getElementById('chartsSection')?.classList.add('hidden'); + + // Reset text sections + document.getElementById('newsImpactSection')?.classList.add('hidden'); + document.getElementById('financialDeepDiveSection')?.classList.add('hidden'); + document.getElementById('changesSection')?.classList.add('hidden'); + document.getElementById('riskScenariosSection')?.classList.add('hidden'); + + // Build Sidebar + sbTicker.innerText = data.ticker || 'N/A'; + updateWatchlistStar(data.ticker); + sbLogoInitials.innerText = (data.ticker || data.company_name.substring(0,2)).substring(0,2).toUpperCase(); + + const sbLogoImg = document.getElementById('sbLogoImg'); + sbLogoImg.classList.add('hidden'); + sbLogoInitials.style.display = 'block'; + + if (data.company_domain) { + // Try multiple logo sources with fallback chain + const domain = data.company_domain; + const logoSources = [ + `https://img.logo.dev/${domain}?token=pk_anonymous&size=128`, + `https://www.google.com/s2/favicons?domain=${domain}&sz=128`, + `https://logo.clearbit.com/${domain}` + ]; + + let sourceIdx = 0; + function tryNextLogo() { + if (sourceIdx >= logoSources.length) { + sbLogoImg.classList.add('hidden'); + sbLogoInitials.style.display = 'block'; + return; + } + sbLogoImg.src = logoSources[sourceIdx]; + sourceIdx++; + } + + sbLogoImg.onload = () => { + sbLogoImg.classList.remove('hidden'); + sbLogoInitials.style.display = 'none'; + }; + sbLogoImg.onerror = () => tryNextLogo(); + tryNextLogo(); + } + + const metrics = data.financial_data?.metrics || {}; + const cap = fmtBig(metrics.marketCap, metrics.currency || 'USD'); + sbMarketCap.innerText = cap; + const price = metrics.currentPrice; + sbPrice.innerText = fmtMoney(price, metrics.currency || 'USD'); + + // --- TradingView Widget --- + const tvContainer = document.getElementById('tradingViewContainer'); + tvContainer.innerHTML = ''; + if (data.ticker) { + tvContainer.style.display = 'block'; + const tvScript = document.createElement('script'); + tvScript.src = 'https://s3.tradingview.com/external-embedding/embed-widget-advanced-chart.js'; + tvScript.type = 'text/javascript'; + tvScript.async = true; + tvScript.innerHTML = JSON.stringify({ + "autosize": true, "symbol": data.tradingview_symbol || data.ticker, "interval": "D", + "timezone": "Etc/UTC", "theme": "dark", "style": "1", + "locale": "en", "allow_symbol_change": false, + "backgroundColor": "rgba(19, 23, 34, 1)", + "gridColor": "rgba(51, 51, 51, 0.3)", + "hide_top_toolbar": false, "hide_legend": true, + "save_image": false, "height": "100%", "width": "100%" + }); + tvContainer.appendChild(tvScript); + } else { + tvContainer.style.display = 'none'; + } + + // ---- Opportunity Score banner ---- + renderOpportunityScore(data.scores); + + // ---- Three-column deep dive ---- + renderValuationSection(metrics, data.scores?.valuation); + renderAnalystSection(data.financial_data?.analyst_data, data.scores?.analyst, data.financial_data?.upgrades_downgrades); + renderSmartMoneySection(metrics, data.scores?.smart_money, data.financial_data?.insider_transactions); + + // ---- Fundamentals metric cards ---- + const metricCards = document.getElementById('metricCards'); + metricCards.innerHTML = ''; + const cardKeys = [ + 'currentRatio','quickRatio','profitMargins','operatingMargins', + 'revenueGrowth','earningsGrowth','trailingEps','forwardEps', + 'debtToEquity','freeCashflow','dividendYield','beta','marketCap' + ]; + cardKeys.forEach(key => { + const def = METRIC_DESCRIPTIONS[key]; + if (!def) return; + const val = metrics[key]; + if (val == null) return; + const card = document.createElement('div'); + card.style.cssText = 'background:#1a1a1a; border:1px solid #333; padding:14px 16px; transition:border-color 0.2s; cursor:default;'; + card.onmouseenter = () => card.style.borderColor = '#555'; + card.onmouseleave = () => card.style.borderColor = '#333'; + const tier = METRIC_HEALTH[key]?.(val) ?? 'neutral'; + const vColor = HEALTH_COLOR[tier]; + card.innerHTML = ` +
${def.label}
+
${def.format(val)}
+
${def.desc}
+ `; + metricCards.appendChild(card); + }); + + // Officers string (Only CEO) + sbCEOList.innerHTML = ''; + if (data.financial_data?.key_officers) { + data.financial_data.key_officers.slice(0, 1).forEach(o => { + let wpLink = `https://en.wikipedia.org/wiki/Special:Search?search=${encodeURIComponent(o.name)}`; + sbCEOList.innerHTML += `${o.name}${o.title}`; + }); + } + + // Sidebar Risk Badges + if (data.safety) { + sidebarRiskScores.classList.remove('hidden'); + const st = data.safety.short_term.score; + const lt = data.safety.long_term.score; + sbStCircle.innerText = st; + sbStCircle.style.color = `hsl(${st * 1.2}, 100%, 50%)`; + sbStCircle.style.borderColor = `hsl(${st * 1.2}, 100%, 40%)`; + + sbLtCircle.innerText = lt; + sbLtCircle.style.color = `hsl(${lt * 1.2}, 100%, 50%)`; + sbLtCircle.style.borderColor = `hsl(${lt * 1.2}, 100%, 40%)`; + + // Logo glow based on average safety + const avg = (st + lt) / 2; + const glowHue = avg * 1.2; // 0=red, 60=yellow, 120=green + document.getElementById('companyLogoBox').style.boxShadow = `0 0 12px hsla(${glowHue}, 100%, 45%, 0.4)`; + } + + + // News — headlines from Yahoo Finance for this ticker + newsContent.innerHTML = ''; + const news = data.news || []; + if (news.length === 0) { + newsContent.innerHTML = '

No recent news found for this stock.

'; + } + news.forEach(item => { + let domain = ''; + try { domain = new URL(item.url).hostname; } catch (e) {} + const card = document.createElement('div'); + card.style.cssText = 'border:1px solid #333; padding:16px; margin-bottom:12px; background:#1a1a1a; transition: border-color 0.2s;'; + card.onmouseenter = () => card.style.borderColor = '#555'; + card.onmouseleave = () => card.style.borderColor = '#333'; + card.innerHTML = ` +
+ ${domain ? `` : ''} + ${esc(item.title)} +
+ ${item.summary ? `

${esc(item.summary)}

` : ''} +
${esc(item.publisher)}${item.published_at ? ' · ' + timeAgo(item.published_at) : ''}
+ `; + newsContent.appendChild(card); + }); +} diff --git a/static/js/home.js b/static/js/home.js new file mode 100644 index 0000000..1fe5c33 --- /dev/null +++ b/static/js/home.js @@ -0,0 +1,238 @@ +// Home screen: indices, market news, movers, watchlist, search history. +// Plain script (not a module): all files share one global scope and load in the +// order listed in index.html. Top-level code may only call functions from earlier files. + +// ---- Market Indices ---- +async function loadIndices() { + try { + const data = await api('/api/market/indices'); + if (!data.length) return; + document.getElementById('indicesBar').innerHTML = data.map(idx => { + const pos = idx.change_pct >= 0; + const color = pos ? '#4caf50' : '#f44336'; + const arrow = pos ? '▲ ' : '▼ '; + const val = idx.value >= 1000 ? idx.value.toLocaleString('en-US', {minimumFractionDigits:2, maximumFractionDigits:2}) : idx.value.toFixed(2); + return `
+ ${idx.name} + ${val} + ${arrow}${idx.change_pct >= 0 ? '+' : ''}${idx.change_pct}% +
`; + }).join(''); + } catch(e) { + document.getElementById('indicesBar').innerHTML = ''; + } +} + +// ---- Market News ---- +async function loadMarketNews() { + try { + const data = await api('/api/market/news'); + if (!data.length) { document.getElementById('newsList').innerHTML = '
No news available.
'; return; } + document.getElementById('newsList').innerHTML = data.map(n => ` + +
${n.title}
+
${n.publisher} · ${timeAgo(n.published_at)}
+
`).join(''); + } catch(e) {} +} + +// ---- Market Movers ---- +let _moversData = null; +let _moversTab = 'large'; // default to large cap +const LARGE_CAP_THRESHOLD = 10_000_000_000; // >= $10B — large cap +// small cap = anything below large cap (no lower bound) + +async function loadMarketMovers() { + try { + _moversData = await api('/api/market/movers'); + if (!_moversData.gainers?.length && !_moversData.losers?.length) return; + if ([0, 6].includes(new Date().getDay())) document.getElementById('marketStatusBadge').style.display = 'inline'; + renderMovers(); + document.getElementById('marketMovers').style.display = 'block'; + } catch(e) {} +} + +function setMoversTab(tab) { + _moversTab = tab; + document.getElementById('moversTabLarge').style.background = tab === 'large' ? 'var(--accent)' : 'transparent'; + document.getElementById('moversTabLarge').style.color = tab === 'large' ? '#fff' : '#666'; + document.getElementById('moversTabSmall').style.background = tab === 'small' ? 'var(--accent)' : 'transparent'; + document.getElementById('moversTabSmall').style.color = tab === 'small' ? '#fff' : '#666'; + renderMovers(); +} + +function renderMovers() { + if (!_moversData) return; + let gainers = _moversData.gainers || []; + let losers = _moversData.losers || []; + if (_moversTab === 'large') { + gainers = gainers.filter(x => x.market_cap && x.market_cap >= LARGE_CAP_THRESHOLD); + losers = losers.filter(x => x.market_cap && x.market_cap >= LARGE_CAP_THRESHOLD); + } else { + gainers = gainers.filter(x => !x.market_cap || x.market_cap < LARGE_CAP_THRESHOLD); + losers = losers.filter(x => !x.market_cap || x.market_cap < LARGE_CAP_THRESHOLD); + } + renderMoversList(gainers.slice(0,5), 'gainersList', true); + renderMoversList(losers.slice(0,5), 'losersList', false); +} + +function renderMoversList(items, containerId, positive) { + const color = positive ? '#4caf50' : '#f44336'; + document.getElementById(containerId).innerHTML = items.length + ? items.map(item => ` +
+
+ ${item.ticker} + ${item.name} +
+ ${item.change_pct >= 0 ? '+' : ''}${item.change_pct}% +
`).join('') + : `
No ${positive ? 'gainers' : 'losers'} match this filter.
`; +} + +function quickSearch(company, ticker) { + document.getElementById('companyInput').value = company; + document.getElementById('tickerInput').value = ticker; + document.getElementById('searchBtn').click(); +} + + +// ---- Watchlist ---- +let _watchlistData = []; +const wlCacheKey = () => 'wl_local'; + +async function loadWatchlist() { + // Render cached data instantly (synchronous localStorage read) + try { + const raw = localStorage.getItem(wlCacheKey()); + if (raw) { _watchlistData = JSON.parse(raw); renderWatchlist(); } + } catch(e) {} + // Then silently fetch fresh prices in background + _refreshWatchlistPrices(); +} + +async function _refreshWatchlistPrices() { + try { + const fresh = await api('/api/watchlist'); + _watchlistData = fresh; + localStorage.setItem(wlCacheKey(), JSON.stringify(fresh)); + renderWatchlist(); + } catch(e) {} +} + +function renderWatchlist() { + const panel = document.getElementById('watchlistPanel'); + if (!panel) return; + if (!_watchlistData.length) { + panel.innerHTML = '
No stocks yet.
Click ★ on any stock
to add it here.
'; + return; + } + panel.innerHTML = _watchlistData.map(item => { + const pos = (item.change_pct ?? 0) >= 0; + const color = pos ? '#4caf50' : '#f44336'; + const chg = item.change_pct != null ? `${pos ? '+' : ''}${item.change_pct}%` : '--'; + const price = item.price != null ? fmtMoney(item.price, item.currency || 'USD') : '--'; + const name = (item.company_name || '').replace(/'/g, "\\'"); + return `
+
+ ${item.ticker} + ${chg} +
+
${item.company_name || ''}
+
${price}
+
`; + }).join(''); +} + +async function toggleWatchlist() { + if (!currentRawData) return; + const ticker = (currentRawData.ticker || '').toUpperCase(); + const companyName = currentRawData.company_name || ''; + if (!ticker) return; + const inList = _watchlistData.some(x => x.ticker === ticker); + if (inList) { + _watchlistData = _watchlistData.filter(x => x.ticker !== ticker); + } else { + // Seed with cached price if we already have it from a previous analysis load + const cachedPrice = currentRawData?.financial_data?.metrics?.currentPrice ?? null; + _watchlistData.push({ ticker, company_name: companyName, price: cachedPrice, change_pct: null }); + } + // Write to localStorage immediately so the next load is instant + localStorage.setItem(wlCacheKey(), JSON.stringify(_watchlistData)); + updateWatchlistStar(ticker); + renderWatchlist(); + // Fire-and-forget: persist to DB and silently refresh price + if (inList) { + api(`/api/watchlist/${encodeURIComponent(ticker)}`, { method: 'DELETE' }).catch(e => showToast(e.message)); + } else { + api('/api/watchlist', { method: 'POST', body: { ticker, company_name: companyName } }) + .then(() => _refreshWatchlistPrices()) + .catch(e => showToast(e.message)); + } +} + +function updateWatchlistStar(ticker) { + const btn = document.getElementById('btnWatchlist'); + if (!btn) return; + const inList = _watchlistData.some(x => x.ticker === (ticker || '').toUpperCase()); + btn.textContent = inList ? '★' : '☆'; + btn.style.color = inList ? '#f5c518' : '#666'; + btn.title = inList ? 'Remove from watchlist' : 'Add to watchlist'; +} + + +function getUserHistoryKey() { + return 'history_local'; +} + +function loadUserHistory() { + try { + const saved = localStorage.getItem(getUserHistoryKey()); + if (saved) { + searchHistory = JSON.parse(saved).map(h => ({ ...h, time: new Date(h.time) })); + renderNavHistory(); + renderHomeHistory(); + } + } catch(e) {} +} + +function renderHomeHistory() { + const container = document.getElementById('homeHistoryItems'); + const wrapper = document.getElementById('homeHistory'); + if (!container || !wrapper || searchHistory.length === 0) return; + wrapper.style.display = ''; + container.innerHTML = ''; + searchHistory.slice(0, 6).forEach(h => { + const dotColor = getScoreDotColor(h.score); + const chip = document.createElement('button'); + chip.style.cssText = `display:flex; align-items:center; gap:8px; padding:10px 16px; background:#1e1e1e; border:1px solid #333; cursor:pointer; transition:all 0.15s; color:var(--text-main); font-family:'Inter',sans-serif; font-size:0.8rem;`; + chip.onmouseenter = () => { chip.style.borderColor = 'var(--accent)'; chip.style.background = '#252526'; }; + chip.onmouseleave = () => { chip.style.borderColor = '#333'; chip.style.background = '#1e1e1e'; }; + chip.innerHTML = ` + + ${h.ticker} + ${h.company} + `; + chip.addEventListener('click', () => { + companyInput.value = h.company; + tickerInput.value = h.ticker; + executeSearch(h.company, h.ticker); + }); + container.appendChild(chip); + }); +} + +function saveUserHistory() { + try { + localStorage.setItem(getUserHistoryKey(), JSON.stringify(searchHistory)); + } catch(e) {} +} + +let debounceTimer; +let searchHistory = []; diff --git a/static/js/main.js b/static/js/main.js new file mode 100644 index 0000000..7d70e96 --- /dev/null +++ b/static/js/main.js @@ -0,0 +1,10 @@ +// Startup. Runs last, after every other script has defined its functions. +// Plain script (not a module): all files share one global scope and load in the +// order listed in index.html. Top-level code may only call functions from earlier files. + +loadUserHistory(); +loadWatchlist(); +refreshLlmStatus(); +loadIndices(); +loadMarketMovers(); +loadMarketNews(); diff --git a/static/js/scores.js b/static/js/scores.js new file mode 100644 index 0000000..fe07616 --- /dev/null +++ b/static/js/scores.js @@ -0,0 +1,106 @@ +// Score breakdown popover (opportunity pillars) and safety modal. +// Plain script (not a module): all files share one global scope and load in the +// order listed in index.html. Top-level code may only call functions from earlier files. + +// ---- Score breakdowns ---- +// Items with a score get a bar; items without one are explanations (skipped inputs, flags). +function renderBreakdownItems(items) { + return (items || []).map(item => { + if (item.score !== null && item.score !== undefined) { + const c = scoreColor(item.score); + return `
+
+ ${esc(item.item)} + ${item.score}/100 + ${item.weight ? `${esc(item.weight)}` : ''} +
+
+
+
+
`; + } + return `
${esc(item.item)}${item.note ? ` · ${esc(item.note)}` : ''}
`; + }).join(''); +} + +// ---- Score Breakdown Popover ---- +function showScoreBreakdown(key, event) { + event.stopPropagation(); + if (!currentRawData?.scores) return; + const data = currentRawData.scores[key]; + if (!data) return; + const comp = currentRawData.scores.opportunity?.components?.find(c => c.key === key); + document.getElementById('popoverTitle').textContent = (comp?.label || key).toUpperCase() + ' — BREAKDOWN'; + + let html = renderBreakdownItems(data.breakdown); + + if (key === 'smart_money' && data.flags?.length) { + html += `
`; + data.flags.forEach(f => { html += `
⚠ ${f}
`; }); + html += `
`; + } + if (key === 'analyst' && data.upside_pct != null) { + html += `
+ Price-target upside: ${data.upside_pct > 0 ? '+' : ''}${data.upside_pct}% +
`; + } + + document.getElementById('popoverContent').innerHTML = html || '
No breakdown available.
'; + + const popover = document.getElementById('scoreBreakdownPopover'); + popover.style.display = 'block'; + const rect = event.currentTarget.getBoundingClientRect(); + const pw = 290; + let left = rect.left; + let top = rect.bottom + 8; + if (left + pw > window.innerWidth - 12) left = window.innerWidth - pw - 12; + if (top + popover.offsetHeight > window.innerHeight - 12) top = rect.top - popover.offsetHeight - 8; + popover.style.left = left + 'px'; + popover.style.top = top + 'px'; +} + +function hideScoreBreakdown() { + document.getElementById('scoreBreakdownPopover').style.display = 'none'; +} + +function toggleExtra(id, btn) { + const el = document.getElementById(id); + if (!el) return; + const showing = el.style.display !== 'none'; + el.style.display = showing ? 'none' : 'block'; + const n = el.querySelectorAll('[style*="border-bottom"]').length || ''; + btn.textContent = showing ? `SHOW ${n} MORE` : 'SHOW LESS'; +} + +document.addEventListener('click', e => { + const p = document.getElementById('scoreBreakdownPopover'); + if (p && p.style.display !== 'none' && !p.contains(e.target) && !e.target.closest('[data-score-key]')) + hideScoreBreakdown(); +}); + +// ---- Yahoo Finance link ---- +function openYahooFinance() { + const ticker = currentRawData?.ticker; + if (ticker) window.open(`https://finance.yahoo.com/quote/${ticker}`, '_blank', 'noopener'); +} + + +// --- Score Explanation Modal --- +function showScoreExplanation(type) { + const safety = currentRawData?.safety; + if (!safety?.[type]) return; + const data = safety[type]; + const label = type === 'short_term' ? 'Liquidity (short term)' : 'Solvency & Volatility (long term)'; + document.getElementById('scoreModalTitle').innerText = `${label} — ${data.score}/100`; + document.getElementById('scoreModalBody').innerHTML = renderBreakdownItems(data.breakdown) + + `
The score is the weighted average of the items with a bar. Lines without a bar explain what was skipped or flagged.
`; + document.getElementById('scoreModal').style.display = 'flex'; +} + +function closeScoreModal() { + document.getElementById('scoreModal').style.display = 'none'; +} + +document.getElementById('scoreModal').addEventListener('click', function(e) { + if (e.target === this) closeScoreModal(); +}); diff --git a/static/js/search.js b/static/js/search.js new file mode 100644 index 0000000..f41078d --- /dev/null +++ b/static/js/search.js @@ -0,0 +1,245 @@ +// Layout, autocomplete, search flow (executeSearch/loadStock), refresh, search overlay. +// Plain script (not a module): all files share one global scope and load in the +// order listed in index.html. Top-level code may only call functions from earlier files. + +// --- 1. VIEWS & LAYOUT CONTROL --- + +function toggleSidebar() { + const isCollapsed = sidebar.style.marginLeft === '-260px'; + if (isCollapsed) { + sidebar.style.marginLeft = '0px'; + sidebarIcon.innerHTML = ''; + } else { + sidebar.style.marginLeft = '-260px'; + sidebarIcon.innerHTML = ''; + } +} + +// Tabs logic +document.querySelectorAll('.tab-btn').forEach(btn => { + btn.addEventListener('click', () => { + // Remove active from all + document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); + document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active')); + // Add active to current + btn.classList.add('active'); + document.getElementById(btn.getAttribute('data-target')).classList.add('active'); + }); +}); + +// --- 2. AUTOCOMPLETE --- + +// --- Reusable Autocomplete --- +function initAutocomplete(inputEl, dropdownEl, companyTarget, tickerTarget) { + let timer; + inputEl.addEventListener('input', function() { + const query = this.value.trim(); + if (query.length < 3) { + dropdownEl.style.display = 'none'; + clearTimeout(timer); + return; + } + clearTimeout(timer); + timer = setTimeout(async () => { + try { + const data = await api(`/api/search?q=${encodeURIComponent(query)}`); + + if (data.length === 0) { + dropdownEl.innerHTML = '
No results found.
'; + } else { + dropdownEl.innerHTML = ''; + data.forEach(item => { + const div = document.createElement('div'); + div.className = 'dropdown-item flex justify-between items-center'; + div.innerHTML = ` + ${item.name} + ${item.ticker} + `; + div.addEventListener('click', () => { + companyTarget.value = item.name; + tickerTarget.value = item.ticker; + dropdownEl.style.display = 'none'; + }); + dropdownEl.appendChild(div); + }); + } + dropdownEl.style.display = 'block'; + } catch (error) { + console.error(error); + } + }, 150); + }); +} + +// Attach autocomplete to BOTH inputs +initAutocomplete(companyInput, dropdown, companyInput, tickerInput); + +const overlayDropdown = document.getElementById('overlayDropdown'); +const overlayCompanyInputEl = document.getElementById('overlayCompanyInput'); +const overlayTickerInputEl = document.getElementById('overlayTickerInput'); +initAutocomplete(overlayCompanyInputEl, overlayDropdown, overlayCompanyInputEl, overlayTickerInputEl); + +document.addEventListener('click', e => { + if (!companyInput.contains(e.target) && !dropdown.contains(e.target)) { + dropdown.style.display = 'none'; + } + if (overlayDropdown && !overlayCompanyInputEl.contains(e.target) && !overlayDropdown.contains(e.target)) { + overlayDropdown.style.display = 'none'; + } +}); + +// --- 3. MAIN SEARCH TRIGGER --- + +// Core search function — callable from initial search, overlay, and chat actions +async function executeSearch(company, ticker) { + if (!company && !ticker) return; + + // Show dashboard if not already visible + const isInitial = !initialView.classList.contains('hidden'); + if (isInitial) { + initialView.classList.add('opacity-0'); + await new Promise(r => setTimeout(r, 500)); + initialView.classList.add('hidden'); + dashboardView.classList.remove('hidden'); + void dashboardView.offsetWidth; + dashboardView.classList.remove('opacity-0'); + } + + loadingOverlay.classList.remove('hidden'); + try { + if (!ticker) { + const matches = await api(`/api/search?q=${encodeURIComponent(company)}`); + if (!matches.length) throw new Error(`No stock found for "${company}".`); + ticker = matches[0].ticker; + company = matches[0].name; + } + await loadStock(ticker, company, false); + } catch (err) { + console.error(err); + showToast(err.message, 6000); + if (!currentRawData) { // first search failed: go back to the home screen + dashboardView.classList.add('hidden', 'opacity-0'); + initialView.classList.remove('hidden', 'opacity-0'); + } + } finally { + loadingOverlay.classList.add('hidden'); + } +} + +// Fetch one stock snapshot and render it. Throws on failure. +async function loadStock(ticker, company, refresh) { + const params = new URLSearchParams({ name: company || '' }); + if (refresh) params.set('refresh', 'true'); + const data = await api(`/api/stocks/${encodeURIComponent(ticker)}?${params}`); + currentRawData = data; + populateDashboard(data); + updateAsOf(data); + + let avgScore = null; + if (data.safety) { + const st = data.safety.short_term?.score || 0; + const lt = data.safety.long_term?.score || 0; + avgScore = Math.round((st + lt) / 2); + } + addToNavHistory(data.company_name, data.ticker, avgScore); + if (data.warnings?.length) showToast(data.warnings.join(' '), 6000); + + // Show the stored report if there is one; otherwise generate one in the background. + if (data.ai_analysis) renderAiAnalysis(data.ai_analysis); + else if (llmConfigured) requestAnalysis(); + else showNoKeyHint(); +} + +// Whether an OpenRouter key is saved. Without one we don't auto-request reports. +let llmConfigured = true; +async function refreshLlmStatus() { + try { llmConfigured = (await api('/api/settings')).llm_api_key_set; } catch (e) {} +} + +function showNoKeyHint() { + document.getElementById('aiLoading').classList.add('hidden'); + aiSummary.innerText = 'AI analysis is off. Add an OpenRouter API key in Settings (gear icon), then press "New AI report".'; + aiAction.innerText = ''; + aiAnalysisResult.classList.remove('hidden'); +} + +function updateAsOf(data) { + const el = document.getElementById('asOfLabel'); + if (!el) return; + el.textContent = data.as_of ? `data ${timeAgo(data.as_of)}${data.stale ? ' · offline' : ''}` : ''; + el.style.color = data.stale ? '#ff9800' : '#666'; + el.title = data.as_of ? 'Fetched ' + new Date(data.as_of).toLocaleString() : ''; +} + +searchBtn.addEventListener('click', () => { + const company = companyInput.value.trim(); + const ticker = tickerInput.value.trim(); + if (!company) { + alert("Please enter a company name."); + companyInput.focus(); + return; + } + executeSearch(company, ticker); +}); + + +async function forceUpdateSupplier() { + if (!currentRawData) return; + const btn = document.getElementById('btnForceUpdate'); + btn.innerText = 'REFRESHING...'; + btn.style.opacity = '0.5'; + btn.disabled = true; + try { + await loadStock(currentRawData.ticker, currentRawData.company_name, true); + } catch (err) { + showToast(err.message, 6000); + } finally { + btn.innerText = 'REFRESH'; + btn.style.opacity = '1'; + btn.disabled = false; + } +} + +// --- 7. TOPBAR SEARCH OVERLAY --- +const searchOverlay = document.getElementById('searchOverlay'); +const overlayCompanyInput = document.getElementById('overlayCompanyInput'); +const overlayTickerInput = document.getElementById('overlayTickerInput'); +const overlaySearchBtn = document.getElementById('overlaySearchBtn'); +const topbarSearchBtn = document.getElementById('topbarSearchBtn'); + +function openSearchOverlay() { + searchOverlay.classList.add('visible'); + setTimeout(() => overlayCompanyInput.focus(), 50); +} + +function closeSearchOverlay(e) { + // Close only if clicking backdrop (not inner box) + if (e && e.target !== searchOverlay) return; + searchOverlay.classList.remove('visible'); +} + +function triggerOverlaySearch() { + const company = overlayCompanyInput.value.trim(); + const ticker = overlayTickerInput.value.trim(); + if (!company) { overlayCompanyInput.focus(); return; } + searchOverlay.classList.remove('visible'); + companyInput.value = company; + tickerInput.value = ticker; + executeSearch(company, ticker); +} + +topbarSearchBtn.addEventListener('click', openSearchOverlay); +overlaySearchBtn.addEventListener('click', triggerOverlaySearch); + +overlayCompanyInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter') triggerOverlaySearch(); + if (e.key === 'Escape') searchOverlay.classList.remove('visible'); +}); +overlayTickerInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter') triggerOverlaySearch(); + if (e.key === 'Escape') searchOverlay.classList.remove('visible'); +}); + +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') searchOverlay.classList.remove('visible'); +}); diff --git a/static/js/settings.js b/static/js/settings.js new file mode 100644 index 0000000..422a6b7 --- /dev/null +++ b/static/js/settings.js @@ -0,0 +1,44 @@ +// Settings modal (OpenRouter key and model). +// Plain script (not a module): all files share one global scope and load in the +// order listed in index.html. Top-level code may only call functions from earlier files. + +// ---- Settings modal ---- +async function openSettings() { + document.getElementById('settingsModal').style.display = 'flex'; + try { + const data = await api('/api/settings'); + const keyEl = document.getElementById('settingsLlmKey'); + keyEl.value = ''; + keyEl.placeholder = data.llm_api_key_set ? 'Saved. Leave blank to keep it' : 'sk-or-...'; + document.getElementById('settingsLlmModel').value = data.llm_model || data.default_llm_model; + } catch(e) { showToast(e.message); } +} + +function closeSettings() { + document.getElementById('settingsModal').style.display = 'none'; +} + +function toggleVis(inputId, btn) { + const el = document.getElementById(inputId); + const showing = el.type === 'text'; + el.type = showing ? 'password' : 'text'; + btn.textContent = showing ? 'SHOW' : 'HIDE'; +} + +async function saveSettings() { + const llmKey = document.getElementById('settingsLlmKey').value.trim(); + const llmModel = document.getElementById('settingsLlmModel').value.trim(); + const payload = {}; + if (llmKey) payload.llm_api_key = llmKey; + if (llmModel) payload.llm_model = llmModel; + try { + await api('/api/settings', { method: 'PUT', body: payload }); + await refreshLlmStatus(); + closeSettings(); + showToast('Settings saved.'); + } catch(e) { showToast('Could not save settings: ' + e.message); } +} + +document.getElementById('settingsModal').addEventListener('click', function(e) { + if (e.target === this) closeSettings(); +}); diff --git a/static/vendor/chart.umd.min.js b/static/vendor/chart.umd.min.js new file mode 100644 index 0000000..5361469 --- /dev/null +++ b/static/vendor/chart.umd.min.js @@ -0,0 +1,14 @@ +/*! + * Chart.js v4.6.1 + * https://www.chartjs.org + * (c) 2026 Chart.js Contributors + * Released under the MIT License + */ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Chart=e()}(this,(function(){"use strict";var t=Object.freeze({__proto__:null,get Colors(){return Jo},get Decimation(){return ta},get Filler(){return ba},get Legend(){return Ma},get SubTitle(){return Pa},get Title(){return ka},get Tooltip(){return Wa}});function e(){}const i=(()=>{let t=0;return()=>t++})();function s(t){return null==t}function n(t){if(Array.isArray&&Array.isArray(t))return!0;const e=Object.prototype.toString.call(t);return"[object"===e.slice(0,7)&&"Array]"===e.slice(-6)}function o(t){return null!==t&&"[object Object]"===Object.prototype.toString.call(t)}function a(t){return("number"==typeof t||t instanceof Number)&&isFinite(+t)}function r(t,e){return a(t)?t:e}function l(t,e){return void 0===t?e:t}const h=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100:+t/e,c=(t,e)=>"string"==typeof t&&t.endsWith("%")?parseFloat(t)/100*e:+t;function d(t,e,i){if(t&&"function"==typeof t.call)return t.apply(i,e)}function u(t,e,i,s){let a,r,l;if(n(t))if(r=t.length,s)for(a=r-1;a>=0;a--)e.call(i,t[a],a);else for(a=0;at,x:t=>t.x,y:t=>t.y};function v(t){const e=t.split("."),i=[];let s="";for(const t of e)s+=t,s.endsWith("\\")?s=s.slice(0,-1)+".":(i.push(s),s="");return i}function M(t,e){const i=y[e]||(y[e]=function(t){const e=v(t);return t=>{for(const i of e){if(""===i)break;t=t&&t[i]}return t}}(e));return i(t)}function w(t){return t.charAt(0).toUpperCase()+t.slice(1)}const k=t=>void 0!==t,S=t=>"function"==typeof t,P=(t,e)=>{if(t.size!==e.size)return!1;for(const i of t)if(!e.has(i))return!1;return!0};function D(t){return"mouseup"===t.type||"click"===t.type||"contextmenu"===t.type}const C=Math.PI,O=2*C,A=O+C,T=Number.POSITIVE_INFINITY,L=C/180,E=C/2,R=C/4,I=2*C/3,z=Math.log10,F=Math.sign;function V(t,e,i){return Math.abs(t-e)t-e)).pop(),e}function W(t){return!function(t){return"symbol"==typeof t||"object"==typeof t&&null!==t&&!(Symbol.toPrimitive in t||"toString"in t||"valueOf"in t)}(t)&&!isNaN(parseFloat(t))&&isFinite(t)}function H(t,e){const i=Math.round(t);return i-e<=t&&i+e>=t}function j(t,e,i){let s,n,o;for(s=0,n=t.length;sl&&h=Math.min(e,i)-s&&t<=Math.max(e,i)+s}function et(t,e,i){i=i||(i=>t[i]1;)s=o+n>>1,i(s)?o=s:n=s;return{lo:o,hi:n}}const it=(t,e,i,s)=>et(t,i,s?s=>{const n=t[s][e];return nt[s][e]et(t,i,(s=>t[s][e]>=i));function nt(t,e,i){let s=0,n=t.length;for(;ss&&t[n-1]>i;)n--;return s>0||n{const i="_onData"+w(e),s=t[e];Object.defineProperty(t,e,{configurable:!0,enumerable:!1,value(...e){const n=s.apply(this,e);return t._chartjs.listeners.forEach((t=>{"function"==typeof t[i]&&t[i](...e)})),n}})})))}function rt(t,e){const i=t._chartjs;if(!i)return;const s=i.listeners,n=s.indexOf(e);-1!==n&&s.splice(n,1),s.length>0||(ot.forEach((e=>{delete t[e]})),delete t._chartjs)}function lt(t){const e=new Set(t);return e.size===t.length?t:Array.from(e)}const ht="undefined"==typeof window?function(t){return t()}:window.requestAnimationFrame;function ct(t,e){let i=[],s=!1;return function(...n){i=n,s||(s=!0,ht.call(window,(()=>{s=!1,t.apply(e,i)})))}}function dt(t,e){let i;return function(...s){return e?(clearTimeout(i),i=setTimeout(t,e,s)):t.apply(this,s),e}}const ut=t=>"start"===t?"left":"end"===t?"right":"center",ft=(t,e,i)=>"start"===t?e:"end"===t?i:(e+i)/2,gt=(t,e,i,s)=>t===(s?"left":"right")?i:"center"===t?(e+i)/2:e;function pt(t,e,i){const n=e.length;let o=0,a=n;if(t._sorted){const{iScale:r,vScale:l,_parsed:h}=t,c=t.dataset&&t.dataset.options?t.dataset.options.spanGaps:null,d=r.axis,{min:u,max:f,minDefined:g,maxDefined:p}=r.getUserBounds();if(g){if(o=Math.min(it(h,d,u).lo,i?n:it(e,d,r.getPixelForValue(u)).lo),c){const t=h.slice(0,o+1).reverse().findIndex((t=>!s(t[l.axis])));o-=Math.max(0,t)}o=Z(o,0,n-1)}if(p){let t=Math.max(it(h,r.axis,f,!0).hi+1,i?0:it(e,d,r.getPixelForValue(f),!0).hi+1);if(c){const e=h.slice(t-1).findIndex((t=>!s(t[l.axis])));t+=Math.max(0,e)}a=Z(t,o,n)-o}else a=n-o}return{start:o,count:a}}function mt(t){const{xScale:e,yScale:i,_scaleRanges:s}=t,n={xmin:e.min,xmax:e.max,ymin:i.min,ymax:i.max};if(!s)return t._scaleRanges=n,!0;const o=s.xmin!==e.min||s.xmax!==e.max||s.ymin!==i.min||s.ymax!==i.max;return Object.assign(s,n),o}class xt{constructor(){this._request=null,this._charts=new Map,this._running=!1,this._lastDate=void 0}_notify(t,e,i,s){const n=e.listeners[s],o=e.duration;n.forEach((s=>s({chart:t,initial:e.initial,numSteps:o,currentStep:Math.min(i-e.start,o)})))}_refresh(){this._request||(this._running=!0,this._request=ht.call(window,(()=>{this._update(),this._request=null,this._running&&this._refresh()})))}_update(t=Date.now()){let e=0;this._charts.forEach(((i,s)=>{if(!i.running||!i.items.length)return;const n=i.items;let o,a=n.length-1,r=!1;for(;a>=0;--a)o=n[a],o._active?(o._total>i.duration&&(i.duration=o._total),o.tick(t),r=!0):(n[a]=n[n.length-1],n.pop());r&&(s.draw(),this._notify(s,i,t,"progress")),n.length||(i.running=!1,this._notify(s,i,t,"complete"),i.initial=!1),e+=n.length})),this._lastDate=t,0===e&&(this._running=!1)}_getAnims(t){const e=this._charts;let i=e.get(t);return i||(i={running:!1,initial:!0,items:[],listeners:{complete:[],progress:[]}},e.set(t,i)),i}listen(t,e,i){this._getAnims(t).listeners[e].push(i)}add(t,e){e&&e.length&&this._getAnims(t).items.push(...e)}has(t){return this._getAnims(t).items.length>0}start(t){const e=this._charts.get(t);e&&(e.running=!0,e.start=Date.now(),e.duration=e.items.reduce(((t,e)=>Math.max(t,e._duration)),0),this._refresh())}running(t){if(!this._running)return!1;const e=this._charts.get(t);return!!(e&&e.running&&e.items.length)}stop(t){const e=this._charts.get(t);if(!e||!e.items.length)return;const i=e.items;let s=i.length-1;for(;s>=0;--s)i[s].cancel();e.items=[],this._notify(t,e,Date.now(),"complete")}remove(t){return this._charts.delete(t)}}var bt=new xt; +/*! + * @kurkle/color v0.3.2 + * https://github.com/kurkle/color#readme + * (c) 2023 Jukka Kurkela + * Released under the MIT License + */function _t(t){return t+.5|0}const yt=(t,e,i)=>Math.max(Math.min(t,i),e);function vt(t){return yt(_t(2.55*t),0,255)}function Mt(t){return yt(_t(255*t),0,255)}function wt(t){return yt(_t(t/2.55)/100,0,1)}function kt(t){return yt(_t(100*t),0,100)}const St={0:0,1:1,2:2,3:3,4:4,5:5,6:6,7:7,8:8,9:9,A:10,B:11,C:12,D:13,E:14,F:15,a:10,b:11,c:12,d:13,e:14,f:15},Pt=[..."0123456789ABCDEF"],Dt=t=>Pt[15&t],Ct=t=>Pt[(240&t)>>4]+Pt[15&t],Ot=t=>(240&t)>>4==(15&t);function At(t){var e=(t=>Ot(t.r)&&Ot(t.g)&&Ot(t.b)&&Ot(t.a))(t)?Dt:Ct;return t?"#"+e(t.r)+e(t.g)+e(t.b)+((t,e)=>t<255?e(t):"")(t.a,e):void 0}const Tt=/^(hsla?|hwb|hsv)\(\s*([-+.e\d]+)(?:deg)?[\s,]+([-+.e\d]+)%[\s,]+([-+.e\d]+)%(?:[\s,]+([-+.e\d]+)(%)?)?\s*\)$/;function Lt(t,e,i){const s=e*Math.min(i,1-i),n=(e,n=(e+t/30)%12)=>i-s*Math.max(Math.min(n-3,9-n,1),-1);return[n(0),n(8),n(4)]}function Et(t,e,i){const s=(s,n=(s+t/60)%6)=>i-i*e*Math.max(Math.min(n,4-n,1),0);return[s(5),s(3),s(1)]}function Rt(t,e,i){const s=Lt(t,1,.5);let n;for(e+i>1&&(n=1/(e+i),e*=n,i*=n),n=0;n<3;n++)s[n]*=1-e-i,s[n]+=e;return s}function It(t){const e=t.r/255,i=t.g/255,s=t.b/255,n=Math.max(e,i,s),o=Math.min(e,i,s),a=(n+o)/2;let r,l,h;return n!==o&&(h=n-o,l=a>.5?h/(2-n-o):h/(n+o),r=function(t,e,i,s,n){return t===n?(e-i)/s+(e>16&255,o>>8&255,255&o]}return t}(),Ht.transparent=[0,0,0,0]);const e=Ht[t.toLowerCase()];return e&&{r:e[0],g:e[1],b:e[2],a:4===e.length?e[3]:255}}const $t=/^rgba?\(\s*([-+.\d]+)(%)?[\s,]+([-+.e\d]+)(%)?[\s,]+([-+.e\d]+)(%)?(?:[\s,/]+([-+.e\d]+)(%)?)?\s*\)$/;const Yt=t=>t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055,Ut=t=>t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4);function Xt(t,e,i){if(t){let s=It(t);s[e]=Math.max(0,Math.min(s[e]+s[e]*i,0===e?360:1)),s=Ft(s),t.r=s[0],t.g=s[1],t.b=s[2]}}function qt(t,e){return t?Object.assign(e||{},t):t}function Kt(t){var e={r:0,g:0,b:0,a:255};return Array.isArray(t)?t.length>=3&&(e={r:t[0],g:t[1],b:t[2],a:255},t.length>3&&(e.a=Mt(t[3]))):(e=qt(t,{r:0,g:0,b:0,a:1})).a=Mt(e.a),e}function Gt(t){return"r"===t.charAt(0)?function(t){const e=$t.exec(t);let i,s,n,o=255;if(e){if(e[7]!==i){const t=+e[7];o=e[8]?vt(t):yt(255*t,0,255)}return i=+e[1],s=+e[3],n=+e[5],i=255&(e[2]?vt(i):yt(i,0,255)),s=255&(e[4]?vt(s):yt(s,0,255)),n=255&(e[6]?vt(n):yt(n,0,255)),{r:i,g:s,b:n,a:o}}}(t):Bt(t)}class Jt{constructor(t){if(t instanceof Jt)return t;const e=typeof t;let i;var s,n,o;"object"===e?i=Kt(t):"string"===e&&(o=(s=t).length,"#"===s[0]&&(4===o||5===o?n={r:255&17*St[s[1]],g:255&17*St[s[2]],b:255&17*St[s[3]],a:5===o?17*St[s[4]]:255}:7!==o&&9!==o||(n={r:St[s[1]]<<4|St[s[2]],g:St[s[3]]<<4|St[s[4]],b:St[s[5]]<<4|St[s[6]],a:9===o?St[s[7]]<<4|St[s[8]]:255})),i=n||jt(t)||Gt(t)),this._rgb=i,this._valid=!!i}get valid(){return this._valid}get rgb(){var t=qt(this._rgb);return t&&(t.a=wt(t.a)),t}set rgb(t){this._rgb=Kt(t)}rgbString(){return this._valid?(t=this._rgb)&&(t.a<255?`rgba(${t.r}, ${t.g}, ${t.b}, ${wt(t.a)})`:`rgb(${t.r}, ${t.g}, ${t.b})`):void 0;var t}hexString(){return this._valid?At(this._rgb):void 0}hslString(){return this._valid?function(t){if(!t)return;const e=It(t),i=e[0],s=kt(e[1]),n=kt(e[2]);return t.a<255?`hsla(${i}, ${s}%, ${n}%, ${wt(t.a)})`:`hsl(${i}, ${s}%, ${n}%)`}(this._rgb):void 0}mix(t,e){if(t){const i=this.rgb,s=t.rgb;let n;const o=e===n?.5:e,a=2*o-1,r=i.a-s.a,l=((a*r==-1?a:(a+r)/(1+a*r))+1)/2;n=1-l,i.r=255&l*i.r+n*s.r+.5,i.g=255&l*i.g+n*s.g+.5,i.b=255&l*i.b+n*s.b+.5,i.a=o*i.a+(1-o)*s.a,this.rgb=i}return this}interpolate(t,e){return t&&(this._rgb=function(t,e,i){const s=Ut(wt(t.r)),n=Ut(wt(t.g)),o=Ut(wt(t.b));return{r:Mt(Yt(s+i*(Ut(wt(e.r))-s))),g:Mt(Yt(n+i*(Ut(wt(e.g))-n))),b:Mt(Yt(o+i*(Ut(wt(e.b))-o))),a:t.a+i*(e.a-t.a)}}(this._rgb,t._rgb,e)),this}clone(){return new Jt(this.rgb)}alpha(t){return this._rgb.a=Mt(t),this}clearer(t){return this._rgb.a*=1-t,this}greyscale(){const t=this._rgb,e=_t(.3*t.r+.59*t.g+.11*t.b);return t.r=t.g=t.b=e,this}opaquer(t){return this._rgb.a*=1+t,this}negate(){const t=this._rgb;return t.r=255-t.r,t.g=255-t.g,t.b=255-t.b,this}lighten(t){return Xt(this._rgb,2,t),this}darken(t){return Xt(this._rgb,2,-t),this}saturate(t){return Xt(this._rgb,1,t),this}desaturate(t){return Xt(this._rgb,1,-t),this}rotate(t){return function(t,e){var i=It(t);i[0]=Vt(i[0]+e),i=Ft(i),t.r=i[0],t.g=i[1],t.b=i[2]}(this._rgb,t),this}}function Zt(t){if(t&&"object"==typeof t){const e=t.toString();return"[object CanvasPattern]"===e||"[object CanvasGradient]"===e}return!1}function Qt(t){return Zt(t)?t:new Jt(t)}function te(t){return Zt(t)?t:new Jt(t).saturate(.5).darken(.1).hexString()}const ee=["x","y","borderWidth","radius","tension"],ie=["color","borderColor","backgroundColor"];const se=new Map;function ne(t,e,i){return function(t,e){e=e||{};const i=t+JSON.stringify(e);let s=se.get(i);return s||(s=new Intl.NumberFormat(t,e),se.set(i,s)),s}(e,i).format(t)}const oe={values:t=>n(t)?t:""+t,numeric(t,e,i){if(0===t)return"0";const s=this.chart.options.locale;let n,o=t;if(i.length>1){const e=Math.max(Math.abs(i[0].value),Math.abs(i[i.length-1].value));(e<1e-4||e>1e15)&&(n="scientific"),o=function(t,e){let i=e.length>3?e[2].value-e[1].value:e[1].value-e[0].value;Math.abs(i)>=1&&t!==Math.floor(t)&&(i=t-Math.floor(t));return i}(t,i)}const a=z(Math.abs(o)),r=isNaN(a)?1:Math.max(Math.min(-1*Math.floor(a),20),0),l={notation:n,minimumFractionDigits:r,maximumFractionDigits:r};return Object.assign(l,this.options.ticks.format),ne(t,s,l)},logarithmic(t,e,i){if(0===t)return"0";const s=i[e].significand||t/Math.pow(10,Math.floor(z(t)));return[1,2,3,5,10,15].includes(s)||e>.8*i.length?oe.numeric.call(this,t,e,i):""}};var ae={formatters:oe};const re=Object.create(null),le=Object.create(null);function he(t,e){if(!e)return t;const i=e.split(".");for(let e=0,s=i.length;et.chart.platform.getDevicePixelRatio(),this.elements={},this.events=["mousemove","mouseout","click","touchstart","touchmove"],this.font={family:"'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",size:12,style:"normal",lineHeight:1.2,weight:null},this.hover={},this.hoverBackgroundColor=(t,e)=>te(e.backgroundColor),this.hoverBorderColor=(t,e)=>te(e.borderColor),this.hoverColor=(t,e)=>te(e.color),this.indexAxis="x",this.interaction={mode:"nearest",intersect:!0,includeInvisible:!1},this.maintainAspectRatio=!0,this.onHover=null,this.onClick=null,this.parsing=!0,this.plugins={},this.responsive=!0,this.scale=void 0,this.scales={},this.showLine=!0,this.drawActiveElementsOnTop=!0,this.describe(t),this.apply(e)}set(t,e){return ce(this,t,e)}get(t){return he(this,t)}describe(t,e){return ce(le,t,e)}override(t,e){return ce(re,t,e)}route(t,e,i,s){const n=he(this,t),a=he(this,i),r="_"+e;Object.defineProperties(n,{[r]:{value:n[e],writable:!0},[e]:{enumerable:!0,get(){const t=this[r],e=a[s];return o(t)?Object.assign({},e,t):l(t,e)},set(t){this[r]=t}}})}apply(t){t.forEach((t=>t(this)))}}var ue=new de({_scriptable:t=>!t.startsWith("on"),_indexable:t=>"events"!==t,hover:{_fallback:"interaction"},interaction:{_scriptable:!1,_indexable:!1}},[function(t){t.set("animation",{delay:void 0,duration:1e3,easing:"easeOutQuart",fn:void 0,from:void 0,loop:void 0,to:void 0,type:void 0}),t.describe("animation",{_fallback:!1,_indexable:!1,_scriptable:t=>"onProgress"!==t&&"onComplete"!==t&&"fn"!==t}),t.set("animations",{colors:{type:"color",properties:ie},numbers:{type:"number",properties:ee}}),t.describe("animations",{_fallback:"animation"}),t.set("transitions",{active:{animation:{duration:400}},resize:{animation:{duration:0}},show:{animations:{colors:{from:"transparent"},visible:{type:"boolean",duration:0}}},hide:{animations:{colors:{to:"transparent"},visible:{type:"boolean",easing:"linear",fn:t=>0|t}}}})},function(t){t.set("layout",{autoPadding:!0,padding:{top:0,right:0,bottom:0,left:0}})},function(t){t.set("scale",{display:!0,offset:!1,reverse:!1,beginAtZero:!1,bounds:"ticks",clip:!0,grace:0,grid:{display:!0,lineWidth:1,drawOnChartArea:!0,drawTicks:!0,tickLength:8,tickWidth:(t,e)=>e.lineWidth,tickColor:(t,e)=>e.color,offset:!1},border:{display:!0,dash:[],dashOffset:0,width:1},title:{display:!1,text:"",padding:{top:4,bottom:4}},ticks:{minRotation:0,maxRotation:50,mirror:!1,textStrokeWidth:0,textStrokeColor:"",padding:3,display:!0,autoSkip:!0,autoSkipPadding:3,labelOffset:0,callback:ae.formatters.values,minor:{},major:{},align:"center",crossAlign:"near",showLabelBackdrop:!1,backdropColor:"rgba(255, 255, 255, 0.75)",backdropPadding:2}}),t.route("scale.ticks","color","","color"),t.route("scale.grid","color","","borderColor"),t.route("scale.border","color","","borderColor"),t.route("scale.title","color","","color"),t.describe("scale",{_fallback:!1,_scriptable:t=>!t.startsWith("before")&&!t.startsWith("after")&&"callback"!==t&&"parser"!==t,_indexable:t=>"borderDash"!==t&&"tickBorderDash"!==t&&"dash"!==t}),t.describe("scales",{_fallback:"scale"}),t.describe("scale.ticks",{_scriptable:t=>"backdropPadding"!==t&&"callback"!==t,_indexable:t=>"backdropPadding"!==t})}]);function fe(){return"undefined"!=typeof window&&"undefined"!=typeof document}function ge(t){let e=t.parentNode;return e&&"[object ShadowRoot]"===e.toString()&&(e=e.host),e}function pe(t,e,i){let s;return"string"==typeof t?(s=parseInt(t,10),-1!==t.indexOf("%")&&(s=s/100*e.parentNode[i])):s=t,s}const me=t=>t.ownerDocument.defaultView.getComputedStyle(t,null);function xe(t,e){return me(t).getPropertyValue(e)}const be=["top","right","bottom","left"];function _e(t,e,i){const s={};i=i?"-"+i:"";for(let n=0;n<4;n++){const o=be[n];s[o]=parseFloat(t[e+"-"+o+i])||0}return s.width=s.left+s.right,s.height=s.top+s.bottom,s}const ye=(t,e,i)=>(t>0||e>0)&&(!i||!i.shadowRoot);function ve(t,e){if("native"in t)return t;const{canvas:i,currentDevicePixelRatio:s}=e,n=me(i),o="border-box"===n.boxSizing,a=_e(n,"padding"),r=_e(n,"border","width"),{x:l,y:h,box:c}=function(t,e){const i=t.touches,s=i&&i.length?i[0]:t,{offsetX:n,offsetY:o}=s;let a,r,l=!1;if(ye(n,o,t.target))a=n,r=o;else{const t=e.getBoundingClientRect();a=s.clientX-t.left,r=s.clientY-t.top,l=!0}return{x:a,y:r,box:l}}(t,i),d=a.left+(c&&r.left),u=a.top+(c&&r.top);let{width:f,height:g}=e;return o&&(f-=a.width+r.width,g-=a.height+r.height),{x:Math.round((l-d)/f*i.width/s),y:Math.round((h-u)/g*i.height/s)}}const Me=t=>Math.round(10*t)/10;function we(t,e,i,s){const n=me(t),o=_e(n,"margin"),a=pe(n.maxWidth,t,"clientWidth")||T,r=pe(n.maxHeight,t,"clientHeight")||T,l=function(t,e,i){let s,n;if(void 0===e||void 0===i){const o=t&&ge(t);if(o){const t=o.getBoundingClientRect(),a=me(o),r=_e(a,"border","width"),l=_e(a,"padding");e=t.width-l.width-r.width,i=t.height-l.height-r.height,s=pe(a.maxWidth,o,"clientWidth"),n=pe(a.maxHeight,o,"clientHeight")}else e=t.clientWidth,i=t.clientHeight}return{width:e,height:i,maxWidth:s||T,maxHeight:n||T}}(t,e,i);let{width:h,height:c}=l;if("content-box"===n.boxSizing){const t=_e(n,"border","width"),e=_e(n,"padding");h-=e.width+t.width,c-=e.height+t.height}h=Math.max(0,h-o.width),c=Math.max(0,s?h/s:c-o.height),h=Me(Math.min(h,a,l.maxWidth)),c=Me(Math.min(c,r,l.maxHeight)),h&&!c&&(c=Me(h/2));return(void 0!==e||void 0!==i)&&s&&l.height&&c>l.height&&(c=l.height,h=Me(Math.floor(c*s))),{width:h,height:c}}function ke(t,e,i){const s=e||1,n=Me(t.height*s),o=Me(t.width*s);t.height=Me(t.height),t.width=Me(t.width);const a=t.canvas;a.style&&(i||!a.style.height&&!a.style.width)&&(a.style.height=`${t.height}px`,a.style.width=`${t.width}px`);const r=Math.floor(n),l=Math.floor(o);return(t.currentDevicePixelRatio!==s||a.height!==r||a.width!==l)&&(t.currentDevicePixelRatio=s,a.height=r,a.width=l,t.ctx.setTransform(s,0,0,s,0,0),!0)}const Se=function(){let t=!1;try{const e={get passive(){return t=!0,!1}};fe()&&(window.addEventListener("test",null,e),window.removeEventListener("test",null,e))}catch(t){}return t}();function Pe(t,e){const i=xe(t,e),s=i&&i.match(/^(\d+)(\.\d+)?px$/);return s?+s[1]:void 0}function De(t){return!t||s(t.size)||s(t.family)?null:(t.style?t.style+" ":"")+(t.weight?t.weight+" ":"")+t.size+"px "+t.family}function Ce(t,e,i,s,n){let o=e[n];return o||(o=e[n]=t.measureText(n).width,i.push(n)),o>s&&(s=o),s}function Oe(t,e,i,s){let o=(s=s||{}).data=s.data||{},a=s.garbageCollect=s.garbageCollect||[];s.font!==e&&(o=s.data={},a=s.garbageCollect=[],s.font=e),t.save(),t.font=e;let r=0;const l=i.length;let h,c,d,u,f;for(h=0;hi.length){for(h=0;h0&&t.stroke()}}function Re(t,e,i){return i=i||.5,!e||t&&t.x>e.left-i&&t.xe.top-i&&t.y0&&""!==r.strokeColor;let c,d;for(t.save(),t.font=a.string,function(t,e){e.translation&&t.translate(e.translation[0],e.translation[1]),s(e.rotation)||t.rotate(e.rotation),e.color&&(t.fillStyle=e.color),e.textAlign&&(t.textAlign=e.textAlign),e.textBaseline&&(t.textBaseline=e.textBaseline)}(t,r),c=0;ct[0])){const o=i||t;void 0===s&&(s=ti("_fallback",t));const a={[Symbol.toStringTag]:"Object",_cacheable:!0,_scopes:t,_rootScopes:o,_fallback:s,_getTarget:n,override:i=>je([i,...t],e,o,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete e._keys,delete t[0][i],!0),get:(i,s)=>qe(i,s,(()=>function(t,e,i,s){let n;for(const o of e)if(n=ti(Ue(o,t),i),void 0!==n)return Xe(t,n)?Ze(i,s,t,n):n}(s,e,t,i))),getOwnPropertyDescriptor:(t,e)=>Reflect.getOwnPropertyDescriptor(t._scopes[0],e),getPrototypeOf:()=>Reflect.getPrototypeOf(t[0]),has:(t,e)=>ei(t).includes(e),ownKeys:t=>ei(t),set(t,e,i){const s=t._storage||(t._storage=n());return t[e]=s[e]=i,delete t._keys,!0}})}function $e(t,e,i,s){const a={_cacheable:!1,_proxy:t,_context:e,_subProxy:i,_stack:new Set,_descriptors:Ye(t,s),setContext:e=>$e(t,e,i,s),override:n=>$e(t.override(n),e,i,s)};return new Proxy(a,{deleteProperty:(e,i)=>(delete e[i],delete t[i],!0),get:(t,e,i)=>qe(t,e,(()=>function(t,e,i){const{_proxy:s,_context:a,_subProxy:r,_descriptors:l}=t;let h=s[e];S(h)&&l.isScriptable(e)&&(h=function(t,e,i,s){const{_proxy:n,_context:o,_subProxy:a,_stack:r}=i;if(r.has(t))throw new Error("Recursion detected: "+Array.from(r).join("->")+"->"+t);r.add(t);let l=e(o,a||s);r.delete(t),Xe(t,l)&&(l=Ze(n._scopes,n,t,l));return l}(e,h,t,i));n(h)&&h.length&&(h=function(t,e,i,s){const{_proxy:n,_context:a,_subProxy:r,_descriptors:l}=i;if(void 0!==a.index&&s(t))return e[a.index%e.length];if(o(e[0])){const i=e,s=n._scopes.filter((t=>t!==i));e=[];for(const o of i){const i=Ze(s,n,t,o);e.push($e(i,a,r&&r[t],l))}}return e}(e,h,t,l.isIndexable));Xe(e,h)&&(h=$e(h,a,r&&r[e],l));return h}(t,e,i))),getOwnPropertyDescriptor:(e,i)=>e._descriptors.allKeys?Reflect.has(t,i)?{enumerable:!0,configurable:!0}:void 0:Reflect.getOwnPropertyDescriptor(t,i),getPrototypeOf:()=>Reflect.getPrototypeOf(t),has:(e,i)=>Reflect.has(t,i),ownKeys:()=>Reflect.ownKeys(t),set:(e,i,s)=>(t[i]=s,delete e[i],!0)})}function Ye(t,e={scriptable:!0,indexable:!0}){const{_scriptable:i=e.scriptable,_indexable:s=e.indexable,_allKeys:n=e.allKeys}=t;return{allKeys:n,scriptable:i,indexable:s,isScriptable:S(i)?i:()=>i,isIndexable:S(s)?s:()=>s}}const Ue=(t,e)=>t?t+w(e):e,Xe=(t,e)=>o(e)&&"adapters"!==t&&(null===Object.getPrototypeOf(e)||e.constructor===Object);function qe(t,e,i){if(Object.prototype.hasOwnProperty.call(t,e)||"constructor"===e)return t[e];const s=i();return t[e]=s,s}function Ke(t,e,i){return S(t)?t(e,i):t}const Ge=(t,e)=>!0===t?e:"string"==typeof t?M(e,t):void 0;function Je(t,e,i,s,n){for(const o of e){const e=Ge(i,o);if(e){t.add(e);const o=Ke(e._fallback,i,n);if(void 0!==o&&o!==i&&o!==s)return o}else if(!1===e&&void 0!==s&&i!==s)return null}return!1}function Ze(t,e,i,s){const a=e._rootScopes,r=Ke(e._fallback,i,s),l=[...t,...a],h=new Set;h.add(s);let c=Qe(h,l,i,r||i,s);return null!==c&&((void 0===r||r===i||(c=Qe(h,l,r,c,s),null!==c))&&je(Array.from(h),[""],a,r,(()=>function(t,e,i){const s=t._getTarget();e in s||(s[e]={});const a=s[e];if(n(a)&&o(i))return i;return a||{}}(e,i,s))))}function Qe(t,e,i,s,n){for(;i;)i=Je(t,e,i,s,n);return i}function ti(t,e){for(const i of e){if(!i)continue;const e=i[t];if(void 0!==e)return e}}function ei(t){let e=t._keys;return e||(e=t._keys=function(t){const e=new Set;for(const i of t)for(const t of Object.keys(i).filter((t=>!t.startsWith("_"))))e.add(t);return Array.from(e)}(t._scopes)),e}function ii(t,e,i,s){const{iScale:n}=t,{key:o="r"}=this._parsing,a=new Array(s);let r,l,h,c;for(r=0,l=s;re"x"===t?"y":"x";function ai(t,e,i,s){const n=t.skip?e:t,o=e,a=i.skip?e:i,r=q(o,n),l=q(a,o);let h=r/(r+l),c=l/(r+l);h=isNaN(h)?0:h,c=isNaN(c)?0:c;const d=s*h,u=s*c;return{previous:{x:o.x-d*(a.x-n.x),y:o.y-d*(a.y-n.y)},next:{x:o.x+u*(a.x-n.x),y:o.y+u*(a.y-n.y)}}}function ri(t,e="x"){const i=oi(e),s=t.length,n=Array(s).fill(0),o=Array(s);let a,r,l,h=ni(t,0);for(a=0;a!t.skip))),"monotone"===e.cubicInterpolationMode)ri(t,n);else{let i=s?t[t.length-1]:t[0];for(o=0,a=t.length;o0===t||1===t,di=(t,e,i)=>-Math.pow(2,10*(t-=1))*Math.sin((t-e)*O/i),ui=(t,e,i)=>Math.pow(2,-10*t)*Math.sin((t-e)*O/i)+1,fi={linear:t=>t,easeInQuad:t=>t*t,easeOutQuad:t=>-t*(t-2),easeInOutQuad:t=>(t/=.5)<1?.5*t*t:-.5*(--t*(t-2)-1),easeInCubic:t=>t*t*t,easeOutCubic:t=>(t-=1)*t*t+1,easeInOutCubic:t=>(t/=.5)<1?.5*t*t*t:.5*((t-=2)*t*t+2),easeInQuart:t=>t*t*t*t,easeOutQuart:t=>-((t-=1)*t*t*t-1),easeInOutQuart:t=>(t/=.5)<1?.5*t*t*t*t:-.5*((t-=2)*t*t*t-2),easeInQuint:t=>t*t*t*t*t,easeOutQuint:t=>(t-=1)*t*t*t*t+1,easeInOutQuint:t=>(t/=.5)<1?.5*t*t*t*t*t:.5*((t-=2)*t*t*t*t+2),easeInSine:t=>1-Math.cos(t*E),easeOutSine:t=>Math.sin(t*E),easeInOutSine:t=>-.5*(Math.cos(C*t)-1),easeInExpo:t=>0===t?0:Math.pow(2,10*(t-1)),easeOutExpo:t=>1===t?1:1-Math.pow(2,-10*t),easeInOutExpo:t=>ci(t)?t:t<.5?.5*Math.pow(2,10*(2*t-1)):.5*(2-Math.pow(2,-10*(2*t-1))),easeInCirc:t=>t>=1?t:-(Math.sqrt(1-t*t)-1),easeOutCirc:t=>Math.sqrt(1-(t-=1)*t),easeInOutCirc:t=>(t/=.5)<1?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1),easeInElastic:t=>ci(t)?t:di(t,.075,.3),easeOutElastic:t=>ci(t)?t:ui(t,.075,.3),easeInOutElastic(t){const e=.1125;return ci(t)?t:t<.5?.5*di(2*t,e,.45):.5+.5*ui(2*t-1,e,.45)},easeInBack(t){const e=1.70158;return t*t*((e+1)*t-e)},easeOutBack(t){const e=1.70158;return(t-=1)*t*((e+1)*t+e)+1},easeInOutBack(t){let e=1.70158;return(t/=.5)<1?t*t*((1+(e*=1.525))*t-e)*.5:.5*((t-=2)*t*((1+(e*=1.525))*t+e)+2)},easeInBounce:t=>1-fi.easeOutBounce(1-t),easeOutBounce(t){const e=7.5625,i=2.75;return t<1/i?e*t*t:t<2/i?e*(t-=1.5/i)*t+.75:t<2.5/i?e*(t-=2.25/i)*t+.9375:e*(t-=2.625/i)*t+.984375},easeInOutBounce:t=>t<.5?.5*fi.easeInBounce(2*t):.5*fi.easeOutBounce(2*t-1)+.5};function gi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:t.y+i*(e.y-t.y)}}function pi(t,e,i,s){return{x:t.x+i*(e.x-t.x),y:"middle"===s?i<.5?t.y:e.y:"after"===s?i<1?t.y:e.y:i>0?e.y:t.y}}function mi(t,e,i,s){const n={x:t.cp2x,y:t.cp2y},o={x:e.cp1x,y:e.cp1y},a=gi(t,n,i),r=gi(n,o,i),l=gi(o,e,i),h=gi(a,r,i),c=gi(r,l,i);return gi(h,c,i)}const xi=/^(normal|(\d+(?:\.\d+)?)(px|em|%)?)$/,bi=/^(normal|italic|initial|inherit|unset|(oblique( -?[0-9]?[0-9]deg)?))$/;function _i(t,e){const i=(""+t).match(xi);if(!i||"normal"===i[1])return 1.2*e;switch(t=+i[2],i[3]){case"px":return t;case"%":t/=100}return e*t}const yi=t=>+t||0;function vi(t,e){const i={},s=o(e),n=s?Object.keys(e):e,a=o(t)?s?i=>l(t[i],t[e[i]]):e=>t[e]:()=>t;for(const t of n)i[t]=yi(a(t));return i}function Mi(t){return vi(t,{top:"y",right:"x",bottom:"y",left:"x"})}function wi(t){return vi(t,["topLeft","topRight","bottomLeft","bottomRight"])}function ki(t){const e=Mi(t);return e.width=e.left+e.right,e.height=e.top+e.bottom,e}function Si(t,e){t=t||{},e=e||ue.font;let i=l(t.size,e.size);"string"==typeof i&&(i=parseInt(i,10));let s=l(t.style,e.style);s&&!(""+s).match(bi)&&(console.warn('Invalid font style specified: "'+s+'"'),s=void 0);const n={family:l(t.family,e.family),lineHeight:_i(l(t.lineHeight,e.lineHeight),i),size:i,style:s,weight:l(t.weight,e.weight),string:""};return n.string=De(n),n}function Pi(t,e,i,s){let o,a,r,l=!0;for(o=0,a=t.length;oi&&0===t?0:t+e;return{min:a(s,-Math.abs(o)),max:a(n,o)}}function Ci(t,e){return Object.assign(Object.create(t),e)}function Oi(t,e,i){return t?function(t,e){return{x:i=>t+t+e-i,setWidth(t){e=t},textAlign:t=>"center"===t?t:"right"===t?"left":"right",xPlus:(t,e)=>t-e,leftForLtr:(t,e)=>t-e}}(e,i):{x:t=>t,setWidth(t){},textAlign:t=>t,xPlus:(t,e)=>t+e,leftForLtr:(t,e)=>t}}function Ai(t,e){let i,s;"ltr"!==e&&"rtl"!==e||(i=t.canvas.style,s=[i.getPropertyValue("direction"),i.getPropertyPriority("direction")],i.setProperty("direction",e,"important"),t.prevTextDirection=s)}function Ti(t,e){void 0!==e&&(delete t.prevTextDirection,t.canvas.style.setProperty("direction",e[0],e[1]))}function Li(t){return"angle"===t?{between:J,compare:K,normalize:G}:{between:tt,compare:(t,e)=>t-e,normalize:t=>t}}function Ei({start:t,end:e,count:i,loop:s,style:n}){return{start:t%i,end:e%i,loop:s&&(e-t+1)%i==0,style:n}}function Ri(t,e,i){if(!i)return[t];const{property:s,start:n,end:o}=i,a=e.length,{compare:r,between:l,normalize:h}=Li(s),{start:c,end:d,loop:u,style:f}=function(t,e,i){const{property:s,start:n,end:o}=i,{between:a,normalize:r}=Li(s),l=e.length;let h,c,{start:d,end:u,loop:f}=t;if(f){for(d+=l,u+=l,h=0,c=l;hb||l(n,x,p)&&0!==r(n,x),v=()=>!b||0===r(o,p)||l(o,x,p);for(let t=c,i=c;t<=d;++t)m=e[t%a],m.skip||(p=h(m[s]),p!==x&&(b=l(p,n,o),null===_&&y()&&(_=0===r(p,n)?t:i),null!==_&&v()&&(g.push(Ei({start:_,end:t,loop:u,count:a,style:f})),_=null),i=t,x=p));return null!==_&&g.push(Ei({start:_,end:d,loop:u,count:a,style:f})),g}function Ii(t,e){const i=[],s=t.segments;for(let n=0;nn&&t[o%e].skip;)o--;return o%=e,{start:n,end:o}}(i,n,o,s);if(!0===s)return Fi(t,[{start:a,end:r,loop:o}],i,e);return Fi(t,function(t,e,i,s){const n=t.length,o=[];let a,r=e,l=t[e];for(a=e+1;a<=i;++a){const i=t[a%n];i.skip||i.stop?l.skip||(s=!1,o.push({start:e%n,end:(a-1)%n,loop:s}),e=r=i.stop?a:null):(r=a,l.skip&&(e=a)),l=i}return null!==r&&o.push({start:e%n,end:r%n,loop:s}),o}(i,a,r!s(t[e.axis])));n.lo-=Math.max(0,a);const r=i.slice(n.hi).findIndex((t=>!s(t[e.axis])));n.hi+=Math.max(0,r)}return n}if(o._sharedOptions){const t=a[0],s="function"==typeof t.getRange&&t.getRange(e);if(s){const t=r(a,e,i-s),n=r(a,e,i+s);return{lo:t.lo,hi:n.hi}}}}return{lo:0,hi:a.length-1}}function $i(t,e,i,s,n){const o=t.getSortedVisibleDatasetMetas(),a=i[e];for(let t=0,i=o.length;t{t[a]&&t[a](e[i],n)&&(o.push({element:t,datasetIndex:s,index:l}),r=r||t.inRange(e.x,e.y,n))})),s&&!r?[]:o}var Ki={evaluateInteractionItems:$i,modes:{index(t,e,i,s){const n=ve(e,t),o=i.axis||"x",a=i.includeInvisible||!1,r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a),l=[];return r.length?(t.getSortedVisibleDatasetMetas().forEach((t=>{const e=r[0].index,i=t.data[e];i&&!i.skip&&l.push({element:i,datasetIndex:t.index,index:e})})),l):[]},dataset(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;let r=i.intersect?Yi(t,n,o,s,a):Xi(t,n,o,!1,s,a);if(r.length>0){const e=r[0].datasetIndex,i=t.getDatasetMeta(e).data;r=[];for(let t=0;tYi(t,ve(e,t),i.axis||"xy",s,i.includeInvisible||!1),nearest(t,e,i,s){const n=ve(e,t),o=i.axis||"xy",a=i.includeInvisible||!1;return Xi(t,n,o,i.intersect,s,a)},x:(t,e,i,s)=>qi(t,ve(e,t),"x",i.intersect,s),y:(t,e,i,s)=>qi(t,ve(e,t),"y",i.intersect,s)}};const Gi=["left","top","right","bottom"];function Ji(t,e){return t.filter((t=>t.pos===e))}function Zi(t,e){return t.filter((t=>-1===Gi.indexOf(t.pos)&&t.box.axis===e))}function Qi(t,e){return t.sort(((t,i)=>{const s=e?i:t,n=e?t:i;return s.weight===n.weight?s.index-n.index:s.weight-n.weight}))}function ts(t,e){const i=function(t){const e={};for(const i of t){const{stack:t,pos:s,stackWeight:n}=i;if(!t||!Gi.includes(s))continue;const o=e[t]||(e[t]={count:0,placed:0,weight:0,size:0});o.count++,o.weight+=n}return e}(t),{vBoxMaxWidth:s,hBoxMaxHeight:n}=e;let o,a,r;for(o=0,a=t.length;o{s[t]=Math.max(e[t],i[t])})),s}return s(t?["left","right"]:["top","bottom"])}function os(t,e,i,s){const n=[];let o,a,r,l,h,c;for(o=0,a=t.length,h=0;ot.box.fullSize)),!0),s=Qi(Ji(e,"left"),!0),n=Qi(Ji(e,"right")),o=Qi(Ji(e,"top"),!0),a=Qi(Ji(e,"bottom")),r=Zi(e,"x"),l=Zi(e,"y");return{fullSize:i,leftAndTop:s.concat(o),rightAndBottom:n.concat(l).concat(a).concat(r),chartArea:Ji(e,"chartArea"),vertical:s.concat(n).concat(l),horizontal:o.concat(a).concat(r)}}(t.boxes),l=r.vertical,h=r.horizontal;u(t.boxes,(t=>{"function"==typeof t.beforeLayout&&t.beforeLayout()}));const c=l.reduce(((t,e)=>e.box.options&&!1===e.box.options.display?t:t+1),0)||1,d=Object.freeze({outerWidth:e,outerHeight:i,padding:n,availableWidth:o,availableHeight:a,vBoxMaxWidth:o/2/c,hBoxMaxHeight:a/2}),f=Object.assign({},n);is(f,ki(s));const g=Object.assign({maxPadding:f,w:o,h:a,x:n.left,y:n.top},n),p=ts(l.concat(h),d);os(r.fullSize,g,d,p),os(l,g,d,p),os(h,g,d,p)&&os(l,g,d,p),function(t){const e=t.maxPadding;function i(i){const s=Math.max(e[i]-t[i],0);return t[i]+=s,s}t.y+=i("top"),t.x+=i("left"),i("right"),i("bottom")}(g),rs(r.leftAndTop,g,d,p),g.x+=g.w,g.y+=g.h,rs(r.rightAndBottom,g,d,p),t.chartArea={left:g.left,top:g.top,right:g.left+g.w,bottom:g.top+g.h,height:g.h,width:g.w},u(r.chartArea,(e=>{const i=e.box;Object.assign(i,t.chartArea),i.update(g.w,g.h,{left:0,top:0,right:0,bottom:0})}))}};class hs{acquireContext(t,e){}releaseContext(t){return!1}addEventListener(t,e,i){}removeEventListener(t,e,i){}getDevicePixelRatio(){return 1}getMaximumSize(t,e,i,s){return e=Math.max(0,e||t.width),i=i||t.height,{width:e,height:Math.max(0,s?Math.floor(e/s):i)}}isAttached(t){return!0}updateConfig(t){}}class cs extends hs{acquireContext(t){return t&&t.getContext&&t.getContext("2d")||null}updateConfig(t){t.options.animation=!1}}const ds="$chartjs",us={touchstart:"mousedown",touchmove:"mousemove",touchend:"mouseup",pointerenter:"mouseenter",pointerdown:"mousedown",pointermove:"mousemove",pointerup:"mouseup",pointerleave:"mouseout",pointerout:"mouseout"},fs=t=>null===t||""===t;const gs=!!Se&&{passive:!0};function ps(t,e,i){t&&t.canvas&&t.canvas.removeEventListener(e,i,gs)}function ms(t,e){for(const i of t)if(i===e||i.contains(e))return!0}function xs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.addedNodes,s),e=e&&!ms(i.removedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}function bs(t,e,i){const s=t.canvas,n=new MutationObserver((t=>{let e=!1;for(const i of t)e=e||ms(i.removedNodes,s),e=e&&!ms(i.addedNodes,s);e&&i()}));return n.observe(document,{childList:!0,subtree:!0}),n}const _s=new Map;let ys=0;function vs(){const t=window.devicePixelRatio;t!==ys&&(ys=t,_s.forEach(((e,i)=>{i.currentDevicePixelRatio!==t&&e()})))}function Ms(t,e,i){const s=t.canvas,n=s&&ge(s);if(!n)return;const o=ct(((t,e)=>{const s=n.clientWidth;i(t,e),s{const e=t[0],i=e.contentRect.width,s=e.contentRect.height;0===i&&0===s||o(i,s)}));return a.observe(n),function(t,e){_s.size||window.addEventListener("resize",vs),_s.set(t,e)}(t,o),a}function ws(t,e,i){i&&i.disconnect(),"resize"===e&&function(t){_s.delete(t),_s.size||window.removeEventListener("resize",vs)}(t)}function ks(t,e,i){const s=t.canvas,n=ct((e=>{null!==t.ctx&&i(function(t,e){const i=us[t.type]||t.type,{x:s,y:n}=ve(t,e);return{type:i,chart:e,native:t,x:void 0!==s?s:null,y:void 0!==n?n:null}}(e,t))}),t);return function(t,e,i){t&&t.addEventListener(e,i,gs)}(s,e,n),n}class Ss extends hs{acquireContext(t,e){const i=t&&t.getContext&&t.getContext("2d");return i&&i.canvas===t?(function(t,e){const i=t.style,s=t.getAttribute("height"),n=t.getAttribute("width");if(t[ds]={initial:{height:s,width:n,style:{display:i.display,height:i.height,width:i.width}}},i.display=i.display||"block",i.boxSizing=i.boxSizing||"border-box",fs(n)){const e=Pe(t,"width");void 0!==e&&(t.width=e)}if(fs(s))if(""===t.style.height)t.height=t.width/(e||2);else{const e=Pe(t,"height");void 0!==e&&(t.height=e)}}(t,e),i):null}releaseContext(t){const e=t.canvas;if(!e[ds])return!1;const i=e[ds].initial;["height","width"].forEach((t=>{const n=i[t];s(n)?e.removeAttribute(t):e.setAttribute(t,n)}));const n=i.style||{};return Object.keys(n).forEach((t=>{e.style[t]=n[t]})),e.width=e.width,delete e[ds],!0}addEventListener(t,e,i){this.removeEventListener(t,e);const s=t.$proxies||(t.$proxies={}),n={attach:xs,detach:bs,resize:Ms}[e]||ks;s[e]=n(t,e,i)}removeEventListener(t,e){const i=t.$proxies||(t.$proxies={}),s=i[e];if(!s)return;({attach:ws,detach:ws,resize:ws}[e]||ps)(t,e,s),i[e]=void 0}getDevicePixelRatio(){return window.devicePixelRatio}getMaximumSize(t,e,i,s){return we(t,e,i,s)}isAttached(t){const e=t&&ge(t);return!(!e||!e.isConnected)}}function Ps(t){return!fe()||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas?cs:Ss}var Ds=Object.freeze({__proto__:null,BasePlatform:hs,BasicPlatform:cs,DomPlatform:Ss,_detectPlatform:Ps});const Cs="transparent",Os={boolean:(t,e,i)=>i>.5?e:t,color(t,e,i){const s=Qt(t||Cs),n=s.valid&&Qt(e||Cs);return n&&n.valid?n.mix(s,i).hexString():e},number:(t,e,i)=>t+(e-t)*i};class As{constructor(t,e,i,s){const n=e[i];s=Pi([t.to,s,n,t.from]);const o=Pi([t.from,n,s]);this._active=!0,this._fn=t.fn||Os[t.type||typeof o],this._easing=fi[t.easing]||fi.linear,this._start=Math.floor(Date.now()+(t.delay||0)),this._duration=this._total=Math.floor(t.duration),this._loop=!!t.loop,this._target=e,this._prop=i,this._from=o,this._to=s,this._promises=void 0}active(){return this._active}update(t,e,i){if(this._active){this._notify(!1);const s=this._target[this._prop],n=i-this._start,o=this._duration-n;this._start=i,this._duration=Math.floor(Math.max(o,t.duration)),this._total+=n,this._loop=!!t.loop,this._to=Pi([t.to,e,s,t.from]),this._from=Pi([t.from,s,e])}}cancel(){this._active&&(this.tick(Date.now()),this._active=!1,this._notify(!1))}tick(t){const e=t-this._start,i=this._duration,s=this._prop,n=this._from,o=this._loop,a=this._to;let r;if(this._active=n!==a&&(o||e1?2-r:r,r=this._easing(Math.min(1,Math.max(0,r))),this._target[s]=this._fn(n,a,r))}wait(){const t=this._promises||(this._promises=[]);return new Promise(((e,i)=>{t.push({res:e,rej:i})}))}_notify(t){const e=t?"res":"rej",i=this._promises||[];for(let t=0;t{const a=t[s];if(!o(a))return;const r={};for(const t of e)r[t]=a[t];(n(a.properties)&&a.properties||[s]).forEach((t=>{t!==s&&i.has(t)||i.set(t,r)}))}))}_animateOptions(t,e){const i=e.options,s=function(t,e){if(!e)return;let i=t.options;if(!i)return void(t.options=e);i.$shared&&(t.options=i=Object.assign({},i,{$shared:!1,$animations:{}}));return i}(t,i);if(!s)return[];const n=this._createAnimations(s,i);return i.$shared&&function(t,e){const i=[],s=Object.keys(e);for(let e=0;e{t.options=i}),(()=>{})),n}_createAnimations(t,e){const i=this._properties,s=[],n=t.$animations||(t.$animations={}),o=Object.keys(e),a=Date.now();let r;for(r=o.length-1;r>=0;--r){const l=o[r];if("$"===l.charAt(0))continue;if("options"===l){s.push(...this._animateOptions(t,e));continue}const h=e[l];let c=n[l];const d=i.get(l);if(c){if(d&&c.active()){c.update(d,h,a);continue}c.cancel()}d&&d.duration?(n[l]=c=new As(d,t,l,h),s.push(c)):t[l]=h}return s}update(t,e){if(0===this._properties.size)return void Object.assign(t,e);const i=this._createAnimations(t,e);return i.length?(bt.add(this._chart,i),!0):void 0}}function Ls(t,e){const i=t&&t.options||{},s=i.reverse,n=void 0===i.min?e:0,o=void 0===i.max?e:0;return{start:s?o:n,end:s?n:o}}function Es(t,e){const i=[],s=t._getSortedDatasetMetas(e);let n,o;for(n=0,o=s.length;n0||!i&&e<0)return n.index}return null}function Vs(t,e){const{chart:i,_cachedMeta:s}=t,n=i._stacks||(i._stacks={}),{iScale:o,vScale:a,index:r}=s,l=o.axis,h=a.axis,c=function(t,e,i){return`${t.id}.${e.id}.${i.stack||i.type}`}(o,a,s),d=e.length;let u;for(let t=0;ti[t].axis===e)).shift()}function Ns(t,e){const i=t.controller.index,s=t.vScale&&t.vScale.axis;if(s){e=e||t._parsed;for(const t of e){const e=t._stacks;e&&void 0!==e[s]&&void 0!==e[s][i]&&(delete e[s][i],void 0!==e[s]._visualValues&&void 0!==e[s]._visualValues[i]&&delete e[s]._visualValues[i])}}}const Ws=t=>"reset"===t||"none"===t,Hs=(t,e)=>e?t:Object.assign({},t);class js{static defaults={};static datasetElementType=null;static dataElementType=null;constructor(t,e){this.chart=t,this._ctx=t.ctx,this.index=e,this._cachedDataOpts={},this._cachedMeta=this.getMeta(),this._type=this._cachedMeta.type,this.options=void 0,this._parsing=!1,this._data=void 0,this._objectData=void 0,this._sharedOptions=void 0,this._drawStart=void 0,this._drawCount=void 0,this.enableOptionSharing=!1,this.supportsDecimation=!1,this.$context=void 0,this._syncList=[],this.datasetElementType=new.target.datasetElementType,this.dataElementType=new.target.dataElementType,this.initialize()}initialize(){const t=this._cachedMeta;this.configure(),this.linkScales(),t._stacked=Is(t.vScale,t),this.addElements(),this.options.fill&&!this.chart.isPluginEnabled("filler")&&console.warn("Tried to use the 'fill' option without the 'Filler' plugin enabled. Please import and register the 'Filler' plugin and make sure it is not disabled in the options")}updateIndex(t){this.index!==t&&Ns(this._cachedMeta),this.index=t}linkScales(){const t=this.chart,e=this._cachedMeta,i=this.getDataset(),s=(t,e,i,s)=>"x"===t?e:"r"===t?s:i,n=e.xAxisID=l(i.xAxisID,Bs(t,"x")),o=e.yAxisID=l(i.yAxisID,Bs(t,"y")),a=e.rAxisID=l(i.rAxisID,Bs(t,"r")),r=e.indexAxis,h=e.iAxisID=s(r,n,o,a),c=e.vAxisID=s(r,o,n,a);e.xScale=this.getScaleForId(n),e.yScale=this.getScaleForId(o),e.rScale=this.getScaleForId(a),e.iScale=this.getScaleForId(h),e.vScale=this.getScaleForId(c)}getDataset(){return this.chart.data.datasets[this.index]}getMeta(){return this.chart.getDatasetMeta(this.index)}getScaleForId(t){return this.chart.scales[t]}_getOtherScale(t){const e=this._cachedMeta;return t===e.iScale?e.vScale:e.iScale}reset(){this._update("reset")}_destroy(){const t=this._cachedMeta;this._data&&rt(this._data,this),t._stacked&&Ns(t)}_dataCheck(){const t=this.getDataset(),e=t.data||(t.data=[]),i=this._data;if(o(e)){const t=this._cachedMeta;this._data=function(t,e){const{iScale:i,vScale:s}=e,n="x"===i.axis?"x":"y",o="x"===s.axis?"x":"y",a=Object.keys(t),r=new Array(a.length);let l,h,c;for(l=0,h=a.length;l0&&i._parsed[t-1];if(!1===this._parsing)i._parsed=s,i._sorted=!0,d=s;else{d=n(s[t])?this.parseArrayData(i,s,t,e):o(s[t])?this.parseObjectData(i,s,t,e):this.parsePrimitiveData(i,s,t,e);const a=()=>null===c[l]||f&&c[l]t&&!e.hidden&&e._stacked&&{keys:Es(i,!0),values:null})(e,i,this.chart),h={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY},{min:c,max:d}=function(t){const{min:e,max:i,minDefined:s,maxDefined:n}=t.getUserBounds();return{min:s?e:Number.NEGATIVE_INFINITY,max:n?i:Number.POSITIVE_INFINITY}}(r);let u,f;function g(){f=s[u];const e=f[r.axis];return!a(f[t.axis])||c>e||d=0;--u)if(!g()){this.updateRangeFromParsed(h,t,f,l);break}return h}getAllParsedValues(t){const e=this._cachedMeta._parsed,i=[];let s,n,o;for(s=0,n=e.length;s=0&&tthis.getContext(i,s,e)),c);return f.$shared&&(f.$shared=r,n[o]=Object.freeze(Hs(f,r))),f}_resolveAnimations(t,e,i){const s=this.chart,n=this._cachedDataOpts,o=`animation-${e}`,a=n[o];if(a)return a;let r;if(!1!==s.options.animation){const s=this.chart.config,n=s.datasetAnimationScopeKeys(this._type,e),o=s.getOptionScopes(this.getDataset(),n);r=s.createResolver(o,this.getContext(t,i,e))}const l=new Ts(s,r&&r.animations);return r&&r._cacheable&&(n[o]=Object.freeze(l)),l}getSharedOptions(t){if(t.$shared)return this._sharedOptions||(this._sharedOptions=Object.assign({},t))}includeOptions(t,e){return!e||Ws(t)||this.chart._animationsDisabled}_getSharedOptions(t,e){const i=this.resolveDataElementOptions(t,e),s=this._sharedOptions,n=this.getSharedOptions(i),o=this.includeOptions(e,n)||n!==s;return this.updateSharedOptions(n,e,i),{sharedOptions:n,includeOptions:o}}updateElement(t,e,i,s){Ws(s)?Object.assign(t,i):this._resolveAnimations(e,s).update(t,i)}updateSharedOptions(t,e,i){t&&!Ws(e)&&this._resolveAnimations(void 0,e).update(t,i)}_setStyle(t,e,i,s){t.active=s;const n=this.getStyle(e,s);this._resolveAnimations(e,i,s).update(t,{options:!s&&this.getSharedOptions(n)||n})}removeHoverStyle(t,e,i){this._setStyle(t,i,"active",!1)}setHoverStyle(t,e,i){this._setStyle(t,i,"active",!0)}_removeDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!1)}_setDatasetHoverStyle(){const t=this._cachedMeta.dataset;t&&this._setStyle(t,void 0,"active",!0)}_resyncElements(t){const e=this._data,i=this._cachedMeta.data;for(const[t,e,i]of this._syncList)this[t](e,i);this._syncList=[];const s=i.length,n=e.length,o=Math.min(n,s);o&&this.parse(0,o),n>s?this._insertElements(s,n-s,t):n{for(t.length+=e,a=t.length-1;a>=o;a--)t[a]=t[a-e]};for(r(n),a=t;a{s[t]=i[t]&&i[t].active()?i[t]._to:this[t]})),s}}function Ys(t,e){const i=t.options.ticks,n=function(t){const e=t.options.offset,i=t._tickSize(),s=t._length/i+(e?0:1),n=t._maxLength/i;return Math.floor(Math.min(s,n))}(t),o=Math.min(i.maxTicksLimit||n,n),a=i.major.enabled?function(t){const e=[];let i,s;for(i=0,s=t.length;io)return function(t,e,i,s){let n,o=0,a=i[0];for(s=Math.ceil(s),n=0;nn)return e}return Math.max(n,1)}(a,e,o);if(r>0){let t,i;const n=r>1?Math.round((h-l)/(r-1)):null;for(Us(e,c,d,s(n)?0:l-n,l),t=0,i=r-1;t"top"===e||"left"===e?t[e]+i:t[e]-i,qs=(t,e)=>Math.min(e||t,t);function Ks(t,e){const i=[],s=t.length/e,n=t.length;let o=0;for(;oa+r)))return h}function Js(t){return t.drawTicks?t.tickLength:0}function Zs(t,e){if(!t.display)return 0;const i=Si(t.font,e),s=ki(t.padding);return(n(t.text)?t.text.length:1)*i.lineHeight+s.height}function Qs(t,e,i){let s=ut(t);return(i&&"right"!==e||!i&&"right"===e)&&(s=(t=>"left"===t?"right":"right"===t?"left":t)(s)),s}class tn extends $s{constructor(t){super(),this.id=t.id,this.type=t.type,this.options=void 0,this.ctx=t.ctx,this.chart=t.chart,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this._margins={left:0,right:0,top:0,bottom:0},this.maxWidth=void 0,this.maxHeight=void 0,this.paddingTop=void 0,this.paddingBottom=void 0,this.paddingLeft=void 0,this.paddingRight=void 0,this.axis=void 0,this.labelRotation=void 0,this.min=void 0,this.max=void 0,this._range=void 0,this.ticks=[],this._gridLineItems=null,this._labelItems=null,this._labelSizes=null,this._length=0,this._maxLength=0,this._longestTextCache={},this._startPixel=void 0,this._endPixel=void 0,this._reversePixels=!1,this._userMax=void 0,this._userMin=void 0,this._suggestedMax=void 0,this._suggestedMin=void 0,this._ticksLength=0,this._borderValue=0,this._cache={},this._dataLimitsCached=!1,this.$context=void 0}init(t){this.options=t.setContext(this.getContext()),this.axis=t.axis,this._userMin=this.parse(t.min),this._userMax=this.parse(t.max),this._suggestedMin=this.parse(t.suggestedMin),this._suggestedMax=this.parse(t.suggestedMax)}parse(t,e){return t}getUserBounds(){let{_userMin:t,_userMax:e,_suggestedMin:i,_suggestedMax:s}=this;return t=r(t,Number.POSITIVE_INFINITY),e=r(e,Number.NEGATIVE_INFINITY),i=r(i,Number.POSITIVE_INFINITY),s=r(s,Number.NEGATIVE_INFINITY),{min:r(t,i),max:r(e,s),minDefined:a(t),maxDefined:a(e)}}getMinMax(t){let e,{min:i,max:s,minDefined:n,maxDefined:o}=this.getUserBounds();if(n&&o)return{min:i,max:s};const a=this.getMatchingVisibleMetas();for(let r=0,l=a.length;rs?s:i,s=n&&i>s?i:s,{min:r(i,r(s,i)),max:r(s,r(i,s))}}getPadding(){return{left:this.paddingLeft||0,top:this.paddingTop||0,right:this.paddingRight||0,bottom:this.paddingBottom||0}}getTicks(){return this.ticks}getLabels(){const t=this.chart.data;return this.options.labels||(this.isHorizontal()?t.xLabels:t.yLabels)||t.labels||[]}getLabelItems(t=this.chart.chartArea){return this._labelItems||(this._labelItems=this._computeLabelItems(t))}beforeLayout(){this._cache={},this._dataLimitsCached=!1}beforeUpdate(){d(this.options.beforeUpdate,[this])}update(t,e,i){const{beginAtZero:s,grace:n,ticks:o}=this.options,a=o.sampleSize;this.beforeUpdate(),this.maxWidth=t,this.maxHeight=e,this._margins=i=Object.assign({left:0,right:0,top:0,bottom:0},i),this.ticks=null,this._labelSizes=null,this._gridLineItems=null,this._labelItems=null,this.beforeSetDimensions(),this.setDimensions(),this.afterSetDimensions(),this._maxLength=this.isHorizontal()?this.width+i.left+i.right:this.height+i.top+i.bottom,this._dataLimitsCached||(this.beforeDataLimits(),this.determineDataLimits(),this.afterDataLimits(),this._range=Di(this,n,s),this._dataLimitsCached=!0),this.beforeBuildTicks(),this.ticks=this.buildTicks()||[],this.afterBuildTicks();const r=a=n||i<=1||!this.isHorizontal())return void(this.labelRotation=s);const h=this._getLabelSizes(),c=h.widest.width,d=h.highest.height,u=Z(this.chart.width-c,0,this.maxWidth);o=t.offset?this.maxWidth/i:u/(i-1),c+6>o&&(o=u/(i-(t.offset?.5:1)),a=this.maxHeight-Js(t.grid)-e.padding-Zs(t.title,this.chart.options.font),r=Math.sqrt(c*c+d*d),l=Y(Math.min(Math.asin(Z((h.highest.height+6)/o,-1,1)),Math.asin(Z(a/r,-1,1))-Math.asin(Z(d/r,-1,1)))),l=Math.max(s,Math.min(n,l))),this.labelRotation=l}afterCalculateLabelRotation(){d(this.options.afterCalculateLabelRotation,[this])}afterAutoSkip(){}beforeFit(){d(this.options.beforeFit,[this])}fit(){const t={width:0,height:0},{chart:e,options:{ticks:i,title:s,grid:n}}=this,o=this._isVisible(),a=this.isHorizontal();if(o){const o=Zs(s,e.options.font);if(a?(t.width=this.maxWidth,t.height=Js(n)+o):(t.height=this.maxHeight,t.width=Js(n)+o),i.display&&this.ticks.length){const{first:e,last:s,widest:n,highest:o}=this._getLabelSizes(),r=2*i.padding,l=$(this.labelRotation),h=Math.cos(l),c=Math.sin(l);if(a){const e=i.mirror?0:c*n.width+h*o.height;t.height=Math.min(this.maxHeight,t.height+e+r)}else{const e=i.mirror?0:h*n.width+c*o.height;t.width=Math.min(this.maxWidth,t.width+e+r)}this._calculatePadding(e,s,c,h)}}this._handleMargins(),a?(this.width=this._length=e.width-this._margins.left-this._margins.right,this.height=t.height):(this.width=t.width,this.height=this._length=e.height-this._margins.top-this._margins.bottom)}_calculatePadding(t,e,i,s){const{ticks:{align:n,padding:o},position:a}=this.options,r=0!==this.labelRotation,l="top"!==a&&"x"===this.axis;if(this.isHorizontal()){const a=this.getPixelForTick(0)-this.left,h=this.right-this.getPixelForTick(this.ticks.length-1);let c=0,d=0;r?l?(c=s*t.width,d=i*e.height):(c=i*t.height,d=s*e.width):"start"===n?d=e.width:"end"===n?c=t.width:"inner"!==n&&(c=t.width/2,d=e.width/2),this.paddingLeft=Math.max((c-a+o)*this.width/(this.width-a),0),this.paddingRight=Math.max((d-h+o)*this.width/(this.width-h),0)}else{let i=e.height/2,s=t.height/2;"start"===n?(i=0,s=t.height):"end"===n&&(i=e.height,s=0),this.paddingTop=i+o,this.paddingBottom=s+o}}_handleMargins(){this._margins&&(this._margins.left=Math.max(this.paddingLeft,this._margins.left),this._margins.top=Math.max(this.paddingTop,this._margins.top),this._margins.right=Math.max(this.paddingRight,this._margins.right),this._margins.bottom=Math.max(this.paddingBottom,this._margins.bottom))}afterFit(){d(this.options.afterFit,[this])}isHorizontal(){const{axis:t,position:e}=this.options;return"top"===e||"bottom"===e||"x"===t}isFullSize(){return this.options.fullSize}_convertTicksToLabels(t){let e,i;for(this.beforeTickToLabelConversion(),this.generateTickLabels(t),e=0,i=t.length;e{const i=t.gc,s=i.length/2;let n;if(s>e){for(n=0;n({width:r[t]||0,height:l[t]||0});return{first:P(0),last:P(e-1),widest:P(k),highest:P(S),widths:r,heights:l}}getLabelForValue(t){return t}getPixelForValue(t,e){return NaN}getValueForPixel(t){}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getPixelForDecimal(t){this._reversePixels&&(t=1-t);const e=this._startPixel+t*this._length;return Q(this._alignToPixels?Ae(this.chart,e,0):e)}getDecimalForPixel(t){const e=(t-this._startPixel)/this._length;return this._reversePixels?1-e:e}getBasePixel(){return this.getPixelForValue(this.getBaseValue())}getBaseValue(){const{min:t,max:e}=this;return t<0&&e<0?e:t>0&&e>0?t:0}getContext(t){const e=this.ticks||[];if(t>=0&&ta*s?a/i:r/s:r*s0}_computeGridLineItems(t){const e=this.axis,i=this.chart,s=this.options,{grid:n,position:a,border:r}=s,h=n.offset,c=this.isHorizontal(),d=this.ticks.length+(h?1:0),u=Js(n),f=[],g=r.setContext(this.getContext()),p=g.display?g.width:0,m=p/2,x=function(t){return Ae(i,t,p)};let b,_,y,v,M,w,k,S,P,D,C,O;if("top"===a)b=x(this.bottom),w=this.bottom-u,S=b-m,D=x(t.top)+m,O=t.bottom;else if("bottom"===a)b=x(this.top),D=t.top,O=x(t.bottom)-m,w=b+m,S=this.top+u;else if("left"===a)b=x(this.right),M=this.right-u,k=b-m,P=x(t.left)+m,C=t.right;else if("right"===a)b=x(this.left),P=t.left,C=x(t.right)-m,M=b+m,k=this.left+u;else if("x"===e){if("center"===a)b=x((t.top+t.bottom)/2+.5);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}D=t.top,O=t.bottom,w=b+m,S=w+u}else if("y"===e){if("center"===a)b=x((t.left+t.right)/2);else if(o(a)){const t=Object.keys(a)[0],e=a[t];b=x(this.chart.scales[t].getPixelForValue(e))}M=b-m,k=M-u,P=t.left,C=t.right}const A=l(s.ticks.maxTicksLimit,d),T=Math.max(1,Math.ceil(d/A));for(_=0;_0&&(o-=s/2)}d={left:o,top:n,width:s+e.width,height:i+e.height,color:t.backdropColor}}x.push({label:v,font:P,textOffset:O,options:{rotation:m,color:i,strokeColor:o,strokeWidth:h,textAlign:f,textBaseline:A,translation:[M,w],backdrop:d}})}return x}_getXAxisLabelAlignment(){const{position:t,ticks:e}=this.options;if(-$(this.labelRotation))return"top"===t?"left":"right";let i="center";return"start"===e.align?i="left":"end"===e.align?i="right":"inner"===e.align&&(i="inner"),i}_getYAxisLabelAlignment(t){const{position:e,ticks:{crossAlign:i,mirror:s,padding:n}}=this.options,o=t+n,a=this._getLabelSizes().widest.width;let r,l;return"left"===e?s?(l=this.right+n,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l+=a)):(l=this.right-o,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l=this.left)):"right"===e?s?(l=this.left+n,"near"===i?r="right":"center"===i?(r="center",l-=a/2):(r="left",l-=a)):(l=this.left+o,"near"===i?r="left":"center"===i?(r="center",l+=a/2):(r="right",l=this.right)):r="right",{textAlign:r,x:l}}_computeLabelArea(){if(this.options.ticks.mirror)return;const t=this.chart,e=this.options.position;return"left"===e||"right"===e?{top:0,left:this.left,bottom:t.height,right:this.right}:"top"===e||"bottom"===e?{top:this.top,left:0,bottom:this.bottom,right:t.width}:void 0}drawBackground(){const{ctx:t,options:{backgroundColor:e},left:i,top:s,width:n,height:o}=this;e&&(t.save(),t.fillStyle=e,t.fillRect(i,s,n,o),t.restore())}getLineWidthForValue(t){const e=this.options.grid;if(!this._isVisible()||!e.display)return 0;const i=this.ticks.findIndex((e=>e.value===t));if(i>=0){return e.setContext(this.getContext(i)).lineWidth}return 0}drawGrid(t){const e=this.options.grid,i=this.ctx,s=this._gridLineItems||(this._gridLineItems=this._computeGridLineItems(t));let n,o;const a=(t,e,s)=>{s.width&&s.color&&(i.save(),i.lineWidth=s.width,i.strokeStyle=s.color,i.setLineDash(s.borderDash||[]),i.lineDashOffset=s.borderDashOffset,i.beginPath(),i.moveTo(t.x,t.y),i.lineTo(e.x,e.y),i.stroke(),i.restore())};if(e.display)for(n=0,o=s.length;n{this.drawBackground(),this.drawGrid(t),this.drawTitle()}},{z:s,draw:()=>{this.drawBorder()}},{z:e,draw:t=>{this.drawLabels(t)}}]:[{z:e,draw:t=>{this.draw(t)}}]}getMatchingVisibleMetas(t){const e=this.chart.getSortedVisibleDatasetMetas(),i=this.axis+"AxisID",s=[];let n,o;for(n=0,o=e.length;n{const s=i.split("."),n=s.pop(),o=[t].concat(s).join("."),a=e[i].split("."),r=a.pop(),l=a.join(".");ue.route(o,n,l,r)}))}(e,t.defaultRoutes);t.descriptors&&ue.describe(e,t.descriptors)}(t,o,i),this.override&&ue.override(t.id,t.overrides)),o}get(t){return this.items[t]}unregister(t){const e=this.items,i=t.id,s=this.scope;i in e&&delete e[i],s&&i in ue[s]&&(delete ue[s][i],this.override&&delete re[i])}}class sn{constructor(){this.controllers=new en(js,"datasets",!0),this.elements=new en($s,"elements"),this.plugins=new en(Object,"plugins"),this.scales=new en(tn,"scales"),this._typedRegistries=[this.controllers,this.scales,this.elements]}add(...t){this._each("register",t)}remove(...t){this._each("unregister",t)}addControllers(...t){this._each("register",t,this.controllers)}addElements(...t){this._each("register",t,this.elements)}addPlugins(...t){this._each("register",t,this.plugins)}addScales(...t){this._each("register",t,this.scales)}getController(t){return this._get(t,this.controllers,"controller")}getElement(t){return this._get(t,this.elements,"element")}getPlugin(t){return this._get(t,this.plugins,"plugin")}getScale(t){return this._get(t,this.scales,"scale")}removeControllers(...t){this._each("unregister",t,this.controllers)}removeElements(...t){this._each("unregister",t,this.elements)}removePlugins(...t){this._each("unregister",t,this.plugins)}removeScales(...t){this._each("unregister",t,this.scales)}_each(t,e,i){[...e].forEach((e=>{const s=i||this._getRegistryForType(e);i||s.isForType(e)||s===this.plugins&&e.id?this._exec(t,s,e):u(e,(e=>{const s=i||this._getRegistryForType(e);this._exec(t,s,e)}))}))}_exec(t,e,i){const s=w(t);d(i["before"+s],[],i),e[t](i),d(i["after"+s],[],i)}_getRegistryForType(t){for(let e=0;et.filter((t=>!e.some((e=>t.plugin.id===e.plugin.id))));this._notify(s(e,i),t,"stop"),this._notify(s(i,e),t,"start")}}function an(t,e){return e||!1!==t?!0===t?{}:t:null}function rn(t,{plugin:e,local:i},s,n){const o=t.pluginScopeKeys(e),a=t.getOptionScopes(s,o);return i&&e.defaults&&a.push(e.defaults),t.createResolver(a,n,[""],{scriptable:!1,indexable:!1,allKeys:!0})}function ln(t,e){const i=ue.datasets[t]||{};return((e.datasets||{})[t]||{}).indexAxis||e.indexAxis||i.indexAxis||"x"}function hn(t){if("x"===t||"y"===t||"r"===t)return t}function cn(t,...e){if(hn(t))return t;for(const s of e){const e=s.axis||("top"===(i=s.position)||"bottom"===i?"x":"left"===i||"right"===i?"y":void 0)||t.length>1&&hn(t[0].toLowerCase());if(e)return e}var i;throw new Error(`Cannot determine type of '${t}' axis. Please provide 'axis' or 'position' option.`)}function dn(t,e,i){if(i[e+"AxisID"]===t)return{axis:e}}function un(t,e){const i=re[t.type]||{scales:{}},s=e.scales||{},n=ln(t.type,e),a=Object.create(null);return Object.keys(s).forEach((e=>{const r=s[e];if(!o(r))return console.error(`Invalid scale configuration for scale: ${e}`);if(r._proxy)return console.warn(`Ignoring resolver passed as options for scale: ${e}`);const l=cn(e,r,function(t,e){if(e.data&&e.data.datasets){const i=e.data.datasets.filter((e=>e.xAxisID===t||e.yAxisID===t));if(i.length)return dn(t,"x",i[0])||dn(t,"y",i[0])}return{}}(e,t),ue.scales[r.type]),h=function(t,e){return t===e?"_index_":"_value_"}(l,n),c=i.scales||{};a[e]=b(Object.create(null),[{axis:l},r,c[l],c[h]])})),t.data.datasets.forEach((i=>{const n=i.type||t.type,o=i.indexAxis||ln(n,e),r=(re[n]||{}).scales||{};Object.keys(r).forEach((t=>{const e=function(t,e){let i=t;return"_index_"===t?i=e:"_value_"===t&&(i="x"===e?"y":"x"),i}(t,o),n=i[e+"AxisID"]||e;a[n]=a[n]||Object.create(null),b(a[n],[{axis:e},s[n],r[t]])}))})),Object.keys(a).forEach((t=>{const e=a[t];b(e,[ue.scales[e.type],ue.scale])})),a}function fn(t){const e=t.options||(t.options={});e.plugins=l(e.plugins,{}),e.scales=un(t,e)}function gn(t){return(t=t||{}).datasets=t.datasets||[],t.labels=t.labels||[],t}const pn=new Map,mn=new Set;function xn(t,e){let i=pn.get(t);return i||(i=e(),pn.set(t,i),mn.add(i)),i}const bn=(t,e,i)=>{const s=M(e,i);void 0!==s&&t.add(s)};class _n{constructor(t){this._config=function(t){return(t=t||{}).data=gn(t.data),fn(t),t}(t),this._scopeCache=new Map,this._resolverCache=new Map}get platform(){return this._config.platform}get type(){return this._config.type}set type(t){this._config.type=t}get data(){return this._config.data}set data(t){this._config.data=gn(t)}get options(){return this._config.options}set options(t){this._config.options=t}get plugins(){return this._config.plugins}update(){const t=this._config;this.clearCache(),fn(t)}clearCache(){this._scopeCache.clear(),this._resolverCache.clear()}datasetScopeKeys(t){return xn(t,(()=>[[`datasets.${t}`,""]]))}datasetAnimationScopeKeys(t,e){return xn(`${t}.transition.${e}`,(()=>[[`datasets.${t}.transitions.${e}`,`transitions.${e}`],[`datasets.${t}`,""]]))}datasetElementScopeKeys(t,e){return xn(`${t}-${e}`,(()=>[[`datasets.${t}.elements.${e}`,`datasets.${t}`,`elements.${e}`,""]]))}pluginScopeKeys(t){const e=t.id;return xn(`${this.type}-plugin-${e}`,(()=>[[`plugins.${e}`,...t.additionalOptionScopes||[]]]))}_cachedScopes(t,e){const i=this._scopeCache;let s=i.get(t);return s&&!e||(s=new Map,i.set(t,s)),s}getOptionScopes(t,e,i){const{options:s,type:n}=this,o=this._cachedScopes(t,i),a=o.get(e);if(a)return a;const r=new Set;e.forEach((e=>{t&&(r.add(t),e.forEach((e=>bn(r,t,e)))),e.forEach((t=>bn(r,s,t))),e.forEach((t=>bn(r,re[n]||{},t))),e.forEach((t=>bn(r,ue,t))),e.forEach((t=>bn(r,le,t)))}));const l=Array.from(r);return 0===l.length&&l.push(Object.create(null)),mn.has(e)&&o.set(e,l),l}chartOptionScopes(){const{options:t,type:e}=this;return[t,re[e]||{},ue.datasets[e]||{},{type:e},ue,le]}resolveNamedOptions(t,e,i,s=[""]){const o={$shared:!0},{resolver:a,subPrefixes:r}=yn(this._resolverCache,t,s);let l=a;if(function(t,e){const{isScriptable:i,isIndexable:s}=Ye(t);for(const o of e){const e=i(o),a=s(o),r=(a||e)&&t[o];if(e&&(S(r)||vn(r))||a&&n(r))return!0}return!1}(a,e)){o.$shared=!1;l=$e(a,i=S(i)?i():i,this.createResolver(t,i,r))}for(const t of e)o[t]=l[t];return o}createResolver(t,e,i=[""],s){const{resolver:n}=yn(this._resolverCache,t,i);return o(e)?$e(n,e,void 0,s):n}}function yn(t,e,i){let s=t.get(e);s||(s=new Map,t.set(e,s));const n=i.join();let o=s.get(n);if(!o){o={resolver:je(e,i),subPrefixes:i.filter((t=>!t.toLowerCase().includes("hover")))},s.set(n,o)}return o}const vn=t=>o(t)&&Object.getOwnPropertyNames(t).some((e=>S(t[e])));const Mn=["top","bottom","left","right","chartArea"];function wn(t,e){return"top"===t||"bottom"===t||-1===Mn.indexOf(t)&&"x"===e}function kn(t,e){return function(i,s){return i[t]===s[t]?i[e]-s[e]:i[t]-s[t]}}function Sn(t){const e=t.chart,i=e.options.animation;e.notifyPlugins("afterRender"),d(i&&i.onComplete,[t],e)}function Pn(t){const e=t.chart,i=e.options.animation;d(i&&i.onProgress,[t],e)}function Dn(t){return fe()&&"string"==typeof t?t=document.getElementById(t):t&&t.length&&(t=t[0]),t&&t.canvas&&(t=t.canvas),t}const Cn={},On=t=>{const e=Dn(t);return Object.values(Cn).filter((t=>t.canvas===e)).pop()};function An(t,e,i){const s=Object.keys(t);for(const n of s){const s=+n;if(s>=e){const o=t[n];delete t[n],(i>0||s>e)&&(t[s+i]=o)}}}class Tn{static defaults=ue;static instances=Cn;static overrides=re;static registry=nn;static version="4.6.1";static getChart=On;static register(...t){nn.add(...t),Ln()}static unregister(...t){nn.remove(...t),Ln()}constructor(t,e){const s=this.config=new _n(e),n=Dn(t),o=On(n);if(o)throw new Error("Canvas is already in use. Chart with ID '"+o.id+"' must be destroyed before the canvas with ID '"+o.canvas.id+"' can be reused.");const a=s.createResolver(s.chartOptionScopes(),this.getContext());this.platform=new(s.platform||Ps(n)),this.platform.updateConfig(s);const r=this.platform.acquireContext(n,a.aspectRatio),l=r&&r.canvas,h=l&&l.height,c=l&&l.width;this.id=i(),this.ctx=r,this.canvas=l,this.width=c,this.height=h,this._options=a,this._aspectRatio=this.aspectRatio,this._layers=[],this._metasets=[],this._stacks=void 0,this.boxes=[],this.currentDevicePixelRatio=void 0,this.chartArea=void 0,this._active=[],this._lastEvent=void 0,this._listeners={},this._responsiveListeners=void 0,this._sortedMetasets=[],this.scales={},this._plugins=new on,this.$proxies={},this._hiddenIndices={},this.attached=!1,this._animationsDisabled=void 0,this.$context=void 0,this._doResize=dt((t=>this.update(t)),a.resizeDelay||0),this._dataChanges=[],Cn[this.id]=this,r&&l?(bt.listen(this,"complete",Sn),bt.listen(this,"progress",Pn),this._initialize(),this.attached&&this.update()):console.error("Failed to create chart: can't acquire context from the given item")}get aspectRatio(){const{options:{aspectRatio:t,maintainAspectRatio:e},width:i,height:n,_aspectRatio:o}=this;return s(t)?e&&o?o:n?i/n:null:t}get data(){return this.config.data}set data(t){this.config.data=t}get options(){return this._options}set options(t){this.config.options=t}get registry(){return nn}_initialize(){return this.notifyPlugins("beforeInit"),this.options.responsive?this.resize():ke(this,this.options.devicePixelRatio),this.bindEvents(),this.notifyPlugins("afterInit"),this}clear(){return Te(this.canvas,this.ctx),this}stop(){return bt.stop(this),this}resize(t,e){bt.running(this)?this._resizeBeforeDraw={width:t,height:e}:this._resize(t,e)}_resize(t,e){const i=this.options,s=this.canvas,n=i.maintainAspectRatio&&this.aspectRatio,o=this.platform.getMaximumSize(s,t,e,n),a=i.devicePixelRatio||this.platform.getDevicePixelRatio(),r=this.width?"resize":"attach";this.width=o.width,this.height=o.height,this._aspectRatio=this.aspectRatio,ke(this,a,!0)&&(this.notifyPlugins("resize",{size:o}),d(i.onResize,[this,o],this),this.attached&&this._doResize(r)&&this.render())}ensureScalesHaveIDs(){u(this.options.scales||{},((t,e)=>{t.id=e}))}buildOrUpdateScales(){const t=this.options,e=t.scales,i=this.scales,s=Object.keys(i).reduce(((t,e)=>(t[e]=!1,t)),{});let n=[];e&&(n=n.concat(Object.keys(e).map((t=>{const i=e[t],s=cn(t,i),n="r"===s,o="x"===s;return{options:i,dposition:n?"chartArea":o?"bottom":"left",dtype:n?"radialLinear":o?"category":"linear"}})))),u(n,(e=>{const n=e.options,o=n.id,a=cn(o,n),r=l(n.type,e.dtype);void 0!==n.position&&wn(n.position,a)===wn(e.dposition)||(n.position=e.dposition),s[o]=!0;let h=null;if(o in i&&i[o].type===r)h=i[o];else{h=new(nn.getScale(r))({id:o,type:r,ctx:this.ctx,chart:this}),i[h.id]=h}h.init(n,t)})),u(s,((t,e)=>{t||delete i[e]})),u(i,(t=>{ls.configure(this,t,t.options),ls.addBox(this,t)}))}_updateMetasets(){const t=this._metasets,e=this.data.datasets.length,i=t.length;if(t.sort(((t,e)=>t.index-e.index)),i>e){for(let t=e;te.length&&delete this._stacks,t.forEach(((t,i)=>{0===e.filter((e=>e===t._dataset)).length&&this._destroyDatasetMeta(i)}))}buildOrUpdateControllers(){const t=[],e=this.data.datasets;let i,s;for(this._removeUnreferencedMetasets(),i=0,s=e.length;i{this.getDatasetMeta(e).controller.reset()}),this)}reset(){this._resetElements(),this.notifyPlugins("reset")}update(t){const e=this.config;e.update();const i=this._options=e.createResolver(e.chartOptionScopes(),this.getContext()),s=this._animationsDisabled=!i.animation;if(this._updateScales(),this._checkEventBindings(),this._updateHiddenIndices(),this._plugins.invalidate(),!1===this.notifyPlugins("beforeUpdate",{mode:t,cancelable:!0}))return;const n=this.buildOrUpdateControllers();this.notifyPlugins("beforeElementsUpdate");let o=0;for(let t=0,e=this.data.datasets.length;t{t.reset()})),this._updateDatasets(t),this.notifyPlugins("afterUpdate",{mode:t}),this._layers.sort(kn("z","_idx"));const{_active:a,_lastEvent:r}=this;r?this._eventHandler(r,!0):a.length&&this._updateHoverStyles(a,a,!0),this.render()}_updateScales(){u(this.scales,(t=>{ls.removeBox(this,t)})),this.ensureScalesHaveIDs(),this.buildOrUpdateScales()}_checkEventBindings(){const t=this.options,e=new Set(Object.keys(this._listeners)),i=new Set(t.events);P(e,i)&&!!this._responsiveListeners===t.responsive||(this.unbindEvents(),this.bindEvents())}_updateHiddenIndices(){const{_hiddenIndices:t}=this,e=this._getUniformDataChanges()||[];for(const{method:i,start:s,count:n}of e){An(t,s,"_removeElements"===i?-n:n)}}_getUniformDataChanges(){const t=this._dataChanges;if(!t||!t.length)return;this._dataChanges=[];const e=this.data.datasets.length,i=e=>new Set(t.filter((t=>t[0]===e)).map(((t,e)=>e+","+t.splice(1).join(",")))),s=i(0);for(let t=1;tt.split(","))).map((t=>({method:t[1],start:+t[2],count:+t[3]})))}_updateLayout(t){if(!1===this.notifyPlugins("beforeLayout",{cancelable:!0}))return;ls.update(this,this.width,this.height,t);const e=this.chartArea,i=e.width<=0||e.height<=0;this._layers=[],u(this.boxes,(t=>{i&&"chartArea"===t.position||(t.configure&&t.configure(),this._layers.push(...t._layers()))}),this),this._layers.forEach(((t,e)=>{t._idx=e})),this.notifyPlugins("afterLayout")}_updateDatasets(t){if(!1!==this.notifyPlugins("beforeDatasetsUpdate",{mode:t,cancelable:!0})){for(let t=0,e=this.data.datasets.length;t=0;--e)this._drawDataset(t[e]);this.notifyPlugins("afterDatasetsDraw")}_drawDataset(t){const e=this.ctx,i={meta:t,index:t.index,cancelable:!0},s=Wi(this,t);!1!==this.notifyPlugins("beforeDatasetDraw",i)&&(s&&Ie(e,s),t.controller.draw(),s&&ze(e),i.cancelable=!1,this.notifyPlugins("afterDatasetDraw",i))}isPointInArea(t){return Re(t,this.chartArea,this._minPadding)}getElementsAtEventForMode(t,e,i,s){const n=Ki.modes[e];return"function"==typeof n?n(this,t,i,s):[]}getDatasetMeta(t){const e=this.data.datasets[t],i=this._metasets;let s=i.filter((t=>t&&t._dataset===e)).pop();return s||(s={type:null,data:[],dataset:null,controller:null,hidden:null,xAxisID:null,yAxisID:null,order:e&&e.order||0,index:t,_dataset:e,_parsed:[],_sorted:!1},i.push(s)),s}getContext(){return this.$context||(this.$context=Ci(null,{chart:this,type:"chart"}))}getVisibleDatasetCount(){return this.getSortedVisibleDatasetMetas().length}isDatasetVisible(t){const e=this.data.datasets[t];if(!e)return!1;const i=this.getDatasetMeta(t);return"boolean"==typeof i.hidden?!i.hidden:!e.hidden}setDatasetVisibility(t,e){this.getDatasetMeta(t).hidden=!e}toggleDataVisibility(t){this._hiddenIndices[t]=!this._hiddenIndices[t]}getDataVisibility(t){return!this._hiddenIndices[t]}_updateVisibility(t,e,i){const s=i?"show":"hide",n=this.getDatasetMeta(t),o=n.controller._resolveAnimations(void 0,s);k(e)?(n.data[e].hidden=!i,this.update()):(this.setDatasetVisibility(t,i),o.update(n,{visible:i}),this.update((e=>e.datasetIndex===t?s:void 0)))}hide(t,e){this._updateVisibility(t,e,!1)}show(t,e){this._updateVisibility(t,e,!0)}_destroyDatasetMeta(t){const e=this._metasets[t];e&&e.controller&&e.controller._destroy(),delete this._metasets[t]}_stop(){let t,e;for(this.stop(),bt.remove(this),t=0,e=this.data.datasets.length;t{e.addEventListener(this,i,s),t[i]=s},s=(t,e,i)=>{t.offsetX=e,t.offsetY=i,this._eventHandler(t)};u(this.options.events,(t=>i(t,s)))}bindResponsiveEvents(){this._responsiveListeners||(this._responsiveListeners={});const t=this._responsiveListeners,e=this.platform,i=(i,s)=>{e.addEventListener(this,i,s),t[i]=s},s=(i,s)=>{t[i]&&(e.removeEventListener(this,i,s),delete t[i])},n=(t,e)=>{this.canvas&&this.resize(t,e)};let o;const a=()=>{s("attach",a),this.attached=!0,this.resize(),i("resize",n),i("detach",o)};o=()=>{this.attached=!1,s("resize",n),this._stop(),this._resize(0,0),i("attach",a)},e.isAttached(this.canvas)?a():o()}unbindEvents(){u(this._listeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._listeners={},u(this._responsiveListeners,((t,e)=>{this.platform.removeEventListener(this,e,t)})),this._responsiveListeners=void 0}updateHoverStyle(t,e,i){const s=i?"set":"remove";let n,o,a,r;for("dataset"===e&&(n=this.getDatasetMeta(t[0].datasetIndex),n.controller["_"+s+"DatasetHoverStyle"]()),a=0,r=t.length;a{const i=this.getDatasetMeta(t);if(!i)throw new Error("No dataset found at index "+t);return{datasetIndex:t,element:i.data[e],index:e}}));!f(i,e)&&(this._active=i,this._lastEvent=null,this._updateHoverStyles(i,e))}notifyPlugins(t,e,i){return this._plugins.notify(this,t,e,i)}isPluginEnabled(t){return 1===this._plugins._cache.filter((e=>e.plugin.id===t)).length}_updateHoverStyles(t,e,i){const s=this.options.hover,n=(t,e)=>t.filter((t=>!e.some((e=>t.datasetIndex===e.datasetIndex&&t.index===e.index)))),o=n(e,t),a=i?t:n(t,e);o.length&&this.updateHoverStyle(o,s.mode,!1),a.length&&s.mode&&this.updateHoverStyle(a,s.mode,!0)}_eventHandler(t,e){const i={event:t,replay:e,cancelable:!0,inChartArea:this.isPointInArea(t)},s=e=>(e.options.events||this.options.events).includes(t.native.type);if(!1===this.notifyPlugins("beforeEvent",i,s))return;const n=this._handleEvent(t,e,i.inChartArea);return i.cancelable=!1,this.notifyPlugins("afterEvent",i,s),(n||i.changed)&&this.render(),this}_handleEvent(t,e,i){const{_active:s=[],options:n}=this,o=e,a=this._getActiveElements(t,s,i,o),r=D(t),l=function(t,e,i,s){return i&&"mouseout"!==t.type?s?e:t:null}(t,this._lastEvent,i,r);i&&(this._lastEvent=null,d(n.onHover,[t,a,this],this),r&&d(n.onClick,[t,a,this],this));const h=!f(a,s);return(h||e)&&(this._active=a,this._updateHoverStyles(a,s,e)),this._lastEvent=l,h}_getActiveElements(t,e,i,s){if("mouseout"===t.type)return[];if(!i)return e;const n=this.options.hover;return this.getElementsAtEventForMode(t,n.mode,n,s)}}function Ln(){return u(Tn.instances,(t=>t._plugins.invalidate()))}function En(){throw new Error("This method is not implemented: Check that a complete date adapter is provided.")}class Rn{static override(t){Object.assign(Rn.prototype,t)}options;constructor(t){this.options=t||{}}init(){}formats(){return En()}parse(){return En()}format(){return En()}add(){return En()}diff(){return En()}startOf(){return En()}endOf(){return En()}}var In={_date:Rn};function zn(t){const e=t.iScale,i=function(t,e){if(!t._cache.$bar){const i=t.getMatchingVisibleMetas(e);let s=[];for(let e=0,n=i.length;et-e)))}return t._cache.$bar}(e,t.type);let s,n,o,a,r=e._length;const l=()=>{32767!==o&&-32768!==o&&(k(a)&&(r=Math.min(r,Math.abs(o-a)||r)),a=o)};for(s=0,n=i.length;sMath.abs(r)&&(l=r,h=a),e[i.axis]=h,e._custom={barStart:l,barEnd:h,start:n,end:o,min:a,max:r}}(t,e,i,s):e[i.axis]=i.parse(t,s),e}function Vn(t,e,i,s){const n=t.iScale,o=t.vScale,a=n.getLabels(),r=n===o,l=[];let h,c,d,u;for(h=i,c=i+s;ht.x,i="left",s="right"):(e=t.base"spacing"!==t&&"spacingMode"!==t,_indexable:t=>"spacing"!==t&&"spacingMode"!==t&&!t.startsWith("borderDash")&&!t.startsWith("hoverBorderDash")};static overrides={aspectRatio:1,plugins:{legend:{labels:{generateLabels(t){const e=t.data,{labels:{pointStyle:i,textAlign:s,color:n,useBorderRadius:o,borderRadius:a}}=t.legend.options;return e.labels.length&&e.datasets.length?e.labels.map(((e,r)=>{const l=t.getDatasetMeta(0).controller.getStyle(r);return{text:e,fillStyle:l.backgroundColor,fontColor:n,hidden:!t.getDataVisibility(r),lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:l.borderWidth,strokeStyle:l.borderColor,textAlign:s,pointStyle:i,borderRadius:o&&(a||l.borderRadius),index:r}})):[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}}};constructor(t,e){super(t,e),this.enableOptionSharing=!0,this.innerRadius=void 0,this.outerRadius=void 0,this.offsetX=void 0,this.offsetY=void 0}linkScales(){}parse(t,e){const i=this.getDataset().data,s=this._cachedMeta;if(!1===this._parsing)s._parsed=i;else{let n,a,r=t=>+i[t];if(o(i[t])){const{key:t="value"}=this._parsing;r=e=>+M(i[e],t)}for(n=t,a=t+e;nJ(t,r,l,!0)?1:Math.max(e,e*i,s,s*i),g=(t,e,s)=>J(t,r,l,!0)?-1:Math.min(e,e*i,s,s*i),p=f(0,h,d),m=f(E,c,u),x=g(C,h,d),b=g(C+E,c,u);s=(p-x)/2,n=(m-b)/2,o=-(p+x)/2,a=-(m+b)/2}return{ratioX:s,ratioY:n,offsetX:o,offsetY:a}}(u,d,r),x=(i.width-o)/f,b=(i.height-o)/g,_=Math.max(Math.min(x,b)/2,0),y=c(this.options.radius,_),v=(y-Math.max(y*r,0))/this._getVisibleDatasetWeightTotal();this.offsetX=p*y,this.offsetY=m*y,s.total=this.calculateTotal(),this.outerRadius=y-v*this._getRingWeightOffset(this.index),this.innerRadius=Math.max(this.outerRadius-v*l,0),this.updateElements(n,0,n.length,t)}_circumference(t,e){const i=this.options,s=this._cachedMeta,n=this._getCircumference();return e&&i.animation.animateRotate||!this.chart.getDataVisibility(t)||null===s._parsed[t]||s.data[t].hidden?0:this.calculateCircumference(s._parsed[t]*n/O)}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.chartArea,r=o.options.animation,l=(a.left+a.right)/2,h=(a.top+a.bottom)/2,c=n&&r.animateScale,d=c?0:this.innerRadius,u=c?0:this.outerRadius,{sharedOptions:f,includeOptions:g}=this._getSharedOptions(e,s);let p,m=this._getRotation();for(p=0;p0&&!isNaN(t)?O*(Math.abs(t)/e):0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t],i.options.locale);return{label:s[t]||"",value:n}}getMaxBorderWidth(t){let e=0;const i=this.chart;let s,n,o,a,r;if(!t)for(s=0,n=i.data.datasets.length;s{const o=t.getDatasetMeta(0).controller.getStyle(n);return{text:e,fillStyle:o.backgroundColor,strokeStyle:o.borderColor,fontColor:s,lineWidth:o.borderWidth,pointStyle:i,hidden:!t.getDataVisibility(n),index:n}}))}return[]}},onClick(t,e,i){i.chart.toggleDataVisibility(e.index),i.chart.update()}}},scales:{r:{type:"radialLinear",angleLines:{display:!1},beginAtZero:!0,grid:{circular:!0},pointLabels:{display:!1},startAngle:0}}};constructor(t,e){super(t,e),this.innerRadius=void 0,this.outerRadius=void 0}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart,s=i.data.labels||[],n=ne(e._parsed[t].r,i.options.locale);return{label:s[t]||"",value:n}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta.data;this._updateRadius(),this.updateElements(e,0,e.length,t)}getMinMax(){const t=this._cachedMeta,e={min:Number.POSITIVE_INFINITY,max:Number.NEGATIVE_INFINITY};return t.data.forEach(((t,i)=>{const s=this.getParsed(i).r;!isNaN(s)&&this.chart.getDataVisibility(i)&&(se.max&&(e.max=s))})),e}_updateRadius(){const t=this.chart,e=t.chartArea,i=t.options,s=Math.min(e.right-e.left,e.bottom-e.top),n=Math.max(s/2,0),o=(n-Math.max(i.cutoutPercentage?n/100*i.cutoutPercentage:1,0))/t.getVisibleDatasetCount();this.outerRadius=n-o*this.index,this.innerRadius=this.outerRadius-o}updateElements(t,e,i,s){const n="reset"===s,o=this.chart,a=o.options.animation,r=this._cachedMeta.rScale,l=r.xCenter,h=r.yCenter,c=r.getIndexAngle(0)-.5*C;let d,u=c;const f=360/this.countVisibleElements();for(d=0;d{!isNaN(this.getParsed(i).r)&&this.chart.getDataVisibility(i)&&e++})),e}_computeAngle(t,e,i){return this.chart.getDataVisibility(t)?$(this.resolveDataElementOptions(t,e).angle||i):0}}var Un=Object.freeze({__proto__:null,BarController:class extends js{static id="bar";static defaults={datasetElementType:!1,dataElementType:"bar",categoryPercentage:.8,barPercentage:.9,grouped:!0,animations:{numbers:{type:"number",properties:["x","y","base","width","height"]}}};static overrides={scales:{_index_:{type:"category",offset:!0,grid:{offset:!0}},_value_:{type:"linear",beginAtZero:!0}}};parsePrimitiveData(t,e,i,s){return Vn(t,e,i,s)}parseArrayData(t,e,i,s){return Vn(t,e,i,s)}parseObjectData(t,e,i,s){const{iScale:n,vScale:o}=t,{xAxisKey:a="x",yAxisKey:r="y"}=this._parsing,l="x"===n.axis?a:r,h="x"===o.axis?a:r,c=[];let d,u,f,g;for(d=i,u=i+s;dt.controller.options.grouped)),o=i.options.stacked,a=[],r=this._cachedMeta.controller.getParsed(e),l=r&&r[i.axis],h=t=>{const e=t._parsed.find((t=>t[i.axis]===l)),n=e&&e[t.vScale.axis];if(s(n)||isNaN(n))return!0};for(const i of n)if((void 0===e||!h(i))&&((!1===o||-1===a.indexOf(i.stack)||void 0===o&&void 0===i.stack)&&a.push(i.stack),i.index===t))break;return a.length||a.push(void 0),a}_getStackCount(t){return this._getStacks(void 0,t).length}_getAxisCount(){return this._getAxis().length}getFirstScaleIdForIndexAxis(){const t=this.chart.scales,e=this.chart.options.indexAxis;return Object.keys(t).filter((i=>t[i].axis===e)).shift()}_getAxis(){const t={},e=this.getFirstScaleIdForIndexAxis();for(const i of this.chart.data.datasets)t[l("x"===this.chart.options.indexAxis?i.xAxisID:i.yAxisID,e)]=!0;return Object.keys(t)}_getStackIndex(t,e,i){const s=this._getStacks(t,i),n=void 0!==e?s.indexOf(e):-1;return-1===n?s.length-1:n}_getRuler(){const t=this.options,e=this._cachedMeta,i=e.iScale,s=[];let n,o;for(n=0,o=e.data.length;n=i?1:-1)}(u,e,r)*a,f===r&&(x-=u/2);const t=e.getPixelForDecimal(0),s=e.getPixelForDecimal(1),o=Math.min(t,s),h=Math.max(t,s);x=Math.max(Math.min(x,h),o),d=x+u,i&&!c&&(l._stacks[e.axis]._visualValues[n]=e.getValueForPixel(d)-e.getValueForPixel(x))}if(x===e.getPixelForValue(r)){const t=F(u)*e.getLineWidthForValue(r)/2;x+=t,u-=t}return{size:u,base:x,head:d,center:d+u/2}}_calculateBarIndexPixels(t,e){const i=e.scale,n=this.options,o=n.skipNull,a=l(n.maxBarThickness,1/0);let r,h;const c=this._getAxisCount();if(e.grouped){const i=o?this._getStackCount(t):e.stackCount,d="flex"===n.barThickness?function(t,e,i,s){const n=e.pixels,o=n[t];let a=t>0?n[t-1]:null,r=t=0;--i)e=Math.max(e,t[i].size(this.resolveDataElementOptions(i))/2);return e>0&&e}getLabelAndValue(t){const e=this._cachedMeta,i=this.chart.data.labels||[],{xScale:s,yScale:n}=e,o=this.getParsed(t),a=s.getLabelForValue(o.x),r=n.getLabelForValue(o.y),l=o._custom;return{label:i[t]||"",value:"("+a+", "+r+(l?", "+l:"")+")"}}update(t){const e=this._cachedMeta.data;this.updateElements(e,0,e.length,t)}updateElements(t,e,i,s){const n="reset"===s,{iScale:o,vScale:a}=this._cachedMeta,{sharedOptions:r,includeOptions:l}=this._getSharedOptions(e,s),h=o.axis,c=a.axis;for(let d=e;d0&&this.getParsed(e-1);for(let i=0;i<_;++i){const g=t[i],_=x?g:{};if(i=b){_.skip=!0;continue}const v=this.getParsed(i),M=s(v[f]),w=_[u]=a.getPixelForValue(v[u],i),k=_[f]=o||M?r.getBasePixel():r.getPixelForValue(l?this.applyStack(r,v,l):v[f],i);_.skip=isNaN(w)||isNaN(k)||M,_.stop=i>0&&Math.abs(v[u]-y[u])>m,p&&(_.parsed=v,_.raw=h.data[i]),d&&(_.options=c||this.resolveDataElementOptions(i,g.active?"active":n)),x||this.updateElement(g,i,_,n),y=v}}getMaxOverflow(){const t=this._cachedMeta,e=t.dataset,i=e.options&&e.options.borderWidth||0,s=t.data||[];if(!s.length)return i;const n=s[0].size(this.resolveDataElementOptions(0)),o=s[s.length-1].size(this.resolveDataElementOptions(s.length-1));return Math.max(i,n,o)/2}draw(){const t=this._cachedMeta;t.dataset.updateControlPoints(this.chart.chartArea,t.iScale.axis),super.draw()}},PieController:class extends $n{static id="pie";static defaults={cutout:0,rotation:0,circumference:360,radius:"100%"}},PolarAreaController:Yn,RadarController:class extends js{static id="radar";static defaults={datasetElementType:"line",dataElementType:"point",indexAxis:"r",showLine:!0,elements:{line:{fill:"start"}}};static overrides={aspectRatio:1,scales:{r:{type:"radialLinear"}}};getLabelAndValue(t){const e=this._cachedMeta.vScale,i=this.getParsed(t);return{label:e.getLabels()[t],value:""+e.getLabelForValue(i[e.axis])}}parseObjectData(t,e,i,s){return ii.bind(this)(t,e,i,s)}update(t){const e=this._cachedMeta,i=e.dataset,s=e.data||[],n=e.iScale.getLabels();if(i.points=s,"resize"!==t){const e=this.resolveDatasetElementOptions(t);this.options.showLine||(e.borderWidth=0);const o={_loop:!0,_fullLoop:n.length===s.length,options:e};this.updateElement(i,void 0,o,t)}this.updateElements(s,0,s.length,t)}updateElements(t,e,i,s){const n=this._cachedMeta.rScale,o="reset"===s;for(let a=e;a0&&this.getParsed(e-1);for(let c=e;c0&&Math.abs(i[f]-_[f])>x,m&&(p.parsed=i,p.raw=h.data[c]),u&&(p.options=d||this.resolveDataElementOptions(c,e.active?"active":n)),b||this.updateElement(e,c,p,n),_=i}this.updateSharedOptions(d,n,c)}getMaxOverflow(){const t=this._cachedMeta,e=t.data||[];if(!this.options.showLine){let t=0;for(let i=e.length-1;i>=0;--i)t=Math.max(t,e[i].size(this.resolveDataElementOptions(i))/2);return t>0&&t}const i=t.dataset,s=i.options&&i.options.borderWidth||0;if(!e.length)return s;const n=e[0].size(this.resolveDataElementOptions(0)),o=e[e.length-1].size(this.resolveDataElementOptions(e.length-1));return Math.max(s,n,o)/2}}});function Xn(t,e,i,s){const n=vi(t.options.borderRadius,["outerStart","outerEnd","innerStart","innerEnd"]);const o=(i-e)/2,a=Math.min(o,s*e/2),r=t=>{const e=(i-Math.min(o,t))*s/2;return Z(t,0,Math.min(o,e))};return{outerStart:r(n.outerStart),outerEnd:r(n.outerEnd),innerStart:Z(n.innerStart,0,a),innerEnd:Z(n.innerEnd,0,a)}}function qn(t,e,i,s){return{x:i+t*Math.cos(e),y:s+t*Math.sin(e)}}function Kn(t,e,i,s,n,o){const{x:a,y:r,startAngle:l,pixelMargin:h,innerRadius:c}=e,{spacingMode:d="angular"}=e.options,u=n-l;if(o&&e.options.selfJoin&&Math.abs(u)>=O-1e-4)return void function(t,e,i,s){const{x:n,y:o,startAngle:a,pixelMargin:r,innerRadius:l}=e,h=Math.max(e.outerRadius+s+i-r,0),c=l>0?l+s+i+r:0;t.beginPath(),t.arc(n,o,h,a,a+O),c>0&&(t.moveTo(n+Math.cos(a)*c,o+Math.sin(a)*c),t.arc(n,o,c,a+O,a,!0)),t.closePath()}(t,e,i,s);const f=Math.max(e.outerRadius+s+i-h,0);let g=c>0?c+s+i+h:0,p=0,m=0;const x=f>0?Math.max(.001,u*f-i/C)/f:.001,b=(u-x)/2;if(s){const t=((c>0?c-s:0)+(f>0?f-s:0))/2,e=(u-(0!==t?u*t/(t+s):u))/2,i=t>0?Math.asin(Math.min(1,s/t)):0,n=Math.max(0,x/2-.001),o=Math.sin(n);if("parallel"===d){if(0===g&&o>0){const t=s/o,e=Math.max(0,f-.001);g=Math.min(t,e)}const t=Math.min(f>0?f*o:Number.POSITIVE_INFINITY,g>0?g*o:Number.POSITIVE_INFINITY),e=Math.min(s,t);p=f>0?Math.asin(Math.min(1,e/f)):Math.min(n,i),m=g>0?Math.asin(Math.min(1,e/g)):p}else"proportional"===d?(p=Math.min(n,e),m=Math.min(n,e)):(p=Math.min(n,i),m=Math.min(n,i))}const _=l+b+p,y=n-b-p,v=l+b+m,M=n-b-m,w=Math.min(y-_,M-v),{outerStart:k,outerEnd:S,innerStart:P,innerEnd:D}=Xn(e,g,f,w),A=f-k,T=f-S,L=_+k/A,R=y-S/T,I=g+P,z=g+D,F=v+P/I,V=M-D/z;if(t.beginPath(),o){const e=(L+R)/2;if(t.arc(a,r,f,L,e),t.arc(a,r,f,e,R),S>0){const e=qn(T,R,a,r);t.arc(e.x,e.y,S,R,y+E)}const i=qn(z,M,a,r);if(t.lineTo(i.x,i.y),D>0){const e=qn(z,V,a,r);t.arc(e.x,e.y,D,M+E,V+Math.PI)}const s=(M-D/g+(v+P/g))/2;if(t.arc(a,r,g,M-D/g,s,!0),t.arc(a,r,g,s,v+P/g,!0),P>0){const e=qn(I,F,a,r);t.arc(e.x,e.y,P,F+Math.PI,v-E)}const n=qn(A,_,a,r);if(t.lineTo(n.x,n.y),k>0){const e=qn(A,L,a,r);t.arc(e.x,e.y,k,_-E,L)}}else{t.moveTo(a,r);const e=Math.cos(L)*f+a,i=Math.sin(L)*f+r;t.lineTo(e,i);const s=Math.cos(R)*f+a,n=Math.sin(R)*f+r;t.lineTo(s,n)}t.closePath()}function Gn(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r,options:l}=e,{borderWidth:h,borderJoinStyle:c,borderDash:d,borderDashOffset:u,borderRadius:f}=l,g="inner"===l.borderAlign;if(!h)return;t.setLineDash(d||[]),t.lineDashOffset=u,g?(t.lineWidth=2*h,t.lineJoin=c||"round"):(t.lineWidth=h,t.lineJoin=c||"bevel");let p=e.endAngle;const m=Math.abs(p-a)>=O-1e-4;if(o){Kn(t,e,i,s,p,n);for(let e=0;en?(h=n/l,t.arc(o,a,l,i+h,s-h,!0)):t.arc(o,a,n,i+E,s-E),t.closePath(),t.clip()}(t,e,p);!(m&&e.innerRadius>0)&&l.selfJoin&&p-a>=C&&0===f&&"miter"!==c&&function(t,e,i){const{startAngle:s,x:n,y:o,outerRadius:a,innerRadius:r,options:l}=e,{borderWidth:h,borderJoinStyle:c}=l,d=Math.min(h/a,G(s-i));if(t.beginPath(),t.arc(n,o,a-h/2,s+d/2,i-d/2),r>0){const e=Math.min(h/r,G(s-i));t.arc(n,o,r+h/2,i-e/2,s+e/2,!0)}else{const e=Math.min(h/2,a*G(s-i));if("round"===c)t.arc(n,o,e,i-C/2,s+C/2,!0);else if("bevel"===c){const a=2*e*e,r=-a*Math.cos(i+C/2)+n,l=-a*Math.sin(i+C/2)+o,h=a*Math.cos(s+C/2)+n,c=a*Math.sin(s+C/2)+o;t.lineTo(r,l),t.lineTo(h,c)}}t.closePath(),t.moveTo(0,0),t.rect(0,0,t.canvas.width,t.canvas.height),t.clip("evenodd")}(t,e,p),o||(Kn(t,e,i,s,p,n),t.stroke())}function Jn(t,e,i=e){t.lineCap=l(i.borderCapStyle,e.borderCapStyle),t.setLineDash(l(i.borderDash,e.borderDash)),t.lineDashOffset=l(i.borderDashOffset,e.borderDashOffset),t.lineJoin=l(i.borderJoinStyle,e.borderJoinStyle),t.lineWidth=l(i.borderWidth,e.borderWidth),t.strokeStyle=l(i.borderColor,e.borderColor)}function Zn(t,e,i){t.lineTo(i.x,i.y)}function Qn(t,e,i={}){const s=t.length,{start:n=0,end:o=s-1}=i,{start:a,end:r}=e,l=Math.max(n,a),h=Math.min(o,r),c=nr&&o>r;return{count:s,start:l,loop:e.loop,ilen:h(a+(h?r-t:t))%o,_=()=>{f!==g&&(t.lineTo(m,g),t.lineTo(m,f),t.lineTo(m,p))};for(l&&(d=n[b(0)],t.moveTo(d.x,d.y)),c=0;c<=r;++c){if(d=n[b(c)],d.skip)continue;const e=d.x,i=d.y,s=0|e;s===u?(ig&&(g=i),m=(x*m+e)/++x):(_(),t.lineTo(e,i),u=s,x=0,f=g=i),p=i}_()}function io(t){const e=t.options,i=e.borderDash&&e.borderDash.length;return!(t._decimated||t._loop||e.tension||"monotone"===e.cubicInterpolationMode||e.stepped||i)?eo:to}const so="function"==typeof Path2D;function no(t,e,i,s){so&&!e.options.segment?function(t,e,i,s){let n=e._path;n||(n=e._path=new Path2D,e.path(n,i,s)&&n.closePath()),Jn(t,e.options),t.stroke(n)}(t,e,i,s):function(t,e,i,s){const{segments:n,options:o}=e,a=io(e);for(const r of n)Jn(t,o,r.style),t.beginPath(),a(t,e,r,{start:i,end:i+s-1})&&t.closePath(),t.stroke()}(t,e,i,s)}class oo extends $s{static id="line";static defaults={borderCapStyle:"butt",borderDash:[],borderDashOffset:0,borderJoinStyle:"miter",borderWidth:3,capBezierPoints:!0,cubicInterpolationMode:"default",fill:!1,spanGaps:!1,stepped:!1,tension:0};static defaultRoutes={backgroundColor:"backgroundColor",borderColor:"borderColor"};static descriptors={_scriptable:!0,_indexable:t=>"borderDash"!==t&&"fill"!==t};constructor(t){super(),this.animated=!0,this.options=void 0,this._chart=void 0,this._loop=void 0,this._fullLoop=void 0,this._path=void 0,this._points=void 0,this._segments=void 0,this._decimated=!1,this._pointsUpdated=!1,this._datasetIndex=void 0,t&&Object.assign(this,t)}updateControlPoints(t,e){const i=this.options;if((i.tension||"monotone"===i.cubicInterpolationMode)&&!i.stepped&&!this._pointsUpdated){const s=i.spanGaps?this._loop:this._fullLoop;hi(this._points,i,t,s,e),this._pointsUpdated=!0}}set points(t){this._points=t,delete this._segments,delete this._path,this._pointsUpdated=!1}get points(){return this._points}get segments(){return this._segments||(this._segments=zi(this,this.options.segment))}first(){const t=this.segments,e=this.points;return t.length&&e[t[0].start]}last(){const t=this.segments,e=this.points,i=t.length;return i&&e[t[i-1].end]}interpolate(t,e){const i=this.options,s=t[e],n=this.points,o=Ii(this,{property:e,start:s,end:s});if(!o.length)return;const a=[],r=function(t){return t.stepped?pi:t.tension||"monotone"===t.cubicInterpolationMode?mi:gi}(i);let l,h;for(l=0,h=o.length;l"borderDash"!==t};circumference;endAngle;fullCircles;innerRadius;outerRadius;pixelMargin;startAngle;circular;constructor(t){super(),this.options=void 0,this.circumference=void 0,this.startAngle=void 0,this.endAngle=void 0,this.innerRadius=void 0,this.outerRadius=void 0,this.pixelMargin=0,this.fullCircles=0,this.circular=!1,t&&Object.assign(this,t)}inRange(t,e,i){const s=this.getProps(["x","y"],i),{angle:n,distance:o}=X(s,{x:t,y:e}),{startAngle:a,endAngle:r,innerRadius:h,outerRadius:c,circumference:d}=this.getProps(["startAngle","endAngle","innerRadius","outerRadius","circumference"],i),u=(this.options.spacing+this.options.borderWidth)/2,f=l(d,r-a),g=J(n,a,r)&&a!==r,p=f>=O||g,m=tt(o,h+u,c+u);return p&&m}getCenterPoint(t){const{x:e,y:i,startAngle:s,endAngle:n,innerRadius:o,outerRadius:a}=this.getProps(["x","y","startAngle","endAngle","innerRadius","outerRadius"],t),{offset:r,spacing:l}=this.options,h=(s+n)/2,c=(o+a+l+r)/2;return{x:e+Math.cos(h)*c,y:i+Math.sin(h)*c}}tooltipPosition(t){return this.getCenterPoint(t)}draw(t){const{options:e,circumference:i}=this,s=(e.offset||0)/4,n=(e.spacing||0)/2,o=e.circular;if(this.pixelMargin="inner"===e.borderAlign?.33:0,this.fullCircles=i>O?Math.floor(i/O):0,0===i||this.innerRadius<0||this.outerRadius<0)return;t.save();const a=(this.startAngle+this.endAngle)/2;t.translate(Math.cos(a)*s,Math.sin(a)*s);const r=s*(1-Math.sin(Math.min(C,i||0)));t.fillStyle=e.backgroundColor,t.strokeStyle=e.borderColor,function(t,e,i,s,n){const{fullCircles:o,startAngle:a,circumference:r}=e;let l=e.endAngle;if(o){Kn(t,e,i,s,l,n);for(let e=0;e("string"==typeof e?(i=t.push(e)-1,s.unshift({index:i,label:e})):isNaN(e)&&(i=null),i))(t,e,i,s);return n!==t.lastIndexOf(e)?i:n}function mo(t){const e=this.getLabels();return t>=0&&ts=e?s:t,a=t=>n=i?n:t;if(t){const t=F(s),e=F(n);t<0&&e<0?a(0):t>0&&e>0&&o(0)}if(s===n){let e=0===n?1:Math.abs(.05*n);a(n+e),t||o(s-e)}this.min=s,this.max=n}getTickLimit(){const t=this.options.ticks;let e,{maxTicksLimit:i,stepSize:s}=t;return s?(e=Math.ceil(this.max/s)-Math.floor(this.min/s)+1,e>1e3&&(console.warn(`scales.${this.id}.ticks.stepSize: ${s} would result generating up to ${e} ticks. Limiting to 1000.`),e=1e3)):(e=this.computeTickLimit(),i=i||11),i&&(e=Math.min(i,e)),e}computeTickLimit(){return Number.POSITIVE_INFINITY}buildTicks(){const t=this.options,e=t.ticks;let i=this.getTickLimit();i=Math.max(2,i);const n=function(t,e){const i=[],{bounds:n,step:o,min:a,max:r,precision:l,count:h,maxTicks:c,maxDigits:d,includeBounds:u}=t,f=o||1,g=c-1,{min:p,max:m}=e,x=!s(a),b=!s(r),_=!s(h),y=(m-p)/(d+1);let v,M,w,k,S=B((m-p)/g/f)*f;if(S<1e-14&&!x&&!b)return[{value:p},{value:m}];k=Math.ceil(m/S)-Math.floor(p/S),k>g&&(S=B(k*S/g/f)*f),s(l)||(v=Math.pow(10,l),S=Math.ceil(S*v)/v),"ticks"===n?(M=Math.floor(p/S)*S,w=Math.ceil(m/S)*S):(M=p,w=m),x&&b&&o&&H((r-a)/o,S/1e3)?(k=Math.round(Math.min((r-a)/S,c)),S=(r-a)/k,M=a,w=r):_?(M=x?a:M,w=b?r:w,k=h-1,S=(w-M)/k):(k=(w-M)/S,k=V(k,Math.round(k),S/1e3)?Math.round(k):Math.ceil(k));const P=Math.max(U(S),U(M));v=Math.pow(10,s(l)?P:l),M=Math.round(M*v)/v,w=Math.round(w*v)/v;let D=0;for(x&&(u&&M!==a?(i.push({value:a}),Mr)break;i.push({value:t})}return b&&u&&w!==r?i.length&&V(i[i.length-1].value,r,xo(r,y,t))?i[i.length-1].value=r:i.push({value:r}):b&&w!==r||i.push({value:w}),i}({maxTicks:i,bounds:t.bounds,min:t.min,max:t.max,precision:e.precision,step:e.stepSize,count:e.count,maxDigits:this._maxDigits(),horizontal:this.isHorizontal(),minRotation:e.minRotation||0,includeBounds:!1!==e.includeBounds},this._range||this);return"ticks"===t.bounds&&j(n,this,"value"),t.reverse?(n.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),n}configure(){const t=this.ticks;let e=this.min,i=this.max;if(super.configure(),this.options.offset&&t.length){const s=(i-e)/Math.max(t.length-1,1)/2;e-=s,i+=s}this._startValue=e,this._endValue=i,this._valueRange=i-e}getLabelForValue(t){return ne(t,this.chart.options.locale,this.options.ticks.format)}}class _o extends bo{static id="linear";static defaults={ticks:{callback:ae.formatters.numeric}};determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?t:0,this.max=a(e)?e:1,this.handleTickRangeOptions()}computeTickLimit(){const t=this.isHorizontal(),e=t?this.width:this.height,i=$(this.options.ticks.minRotation),s=(t?Math.sin(i):Math.cos(i))||.001,n=this._resolveTickFontOptions(0);return Math.ceil(e/Math.min(40,n.lineHeight/s))}getPixelForValue(t){return null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getValueForPixel(t){return this._startValue+this.getDecimalForPixel(t)*this._valueRange}}const yo=t=>Math.floor(z(t)),vo=(t,e)=>Math.pow(10,yo(t)+e);function Mo(t){return 1===t/Math.pow(10,yo(t))}function wo(t,e,i){const s=Math.pow(10,i),n=Math.floor(t/s);return Math.ceil(e/s)-n}function ko(t,{min:e,max:i}){e=r(t.min,e);const s=[],n=yo(e);let o=function(t,e){let i=yo(e-t);for(;wo(t,e,i)>10;)i++;for(;wo(t,e,i)<10;)i--;return Math.min(i,yo(t))}(e,i),a=o<0?Math.pow(10,Math.abs(o)):1;const l=Math.pow(10,o),h=n>o?Math.pow(10,n):0,c=Math.round((e-h)*a)/a,d=Math.floor((e-h)/l/10)*l*10;let u=Math.floor((c-d)/Math.pow(10,o)),f=r(t.min,Math.round((h+d+u*Math.pow(10,o))*a)/a);for(;f=10?u=u<15?15:20:u++,u>=20&&(o++,u=2,a=o>=0?1:a),f=Math.round((h+d+u*Math.pow(10,o))*a)/a;const g=r(t.max,f);return s.push({value:g,major:Mo(g),significand:u}),s}class So extends tn{static id="logarithmic";static defaults={ticks:{callback:ae.formatters.logarithmic,major:{enabled:!0}}};constructor(t){super(t),this.start=void 0,this.end=void 0,this._startValue=void 0,this._valueRange=0}parse(t,e){const i=bo.prototype.parse.apply(this,[t,e]);if(0!==i)return a(i)&&i>0?i:null;this._zero=!0}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!0);this.min=a(t)?Math.max(0,t):null,this.max=a(e)?Math.max(0,e):null,this.options.beginAtZero&&(this._zero=!0),this._zero&&this.min!==this._suggestedMin&&!a(this._userMin)&&(this.min=t===vo(this.min,0)?vo(this.min,-1):vo(this.min,0)),this.handleTickRangeOptions()}handleTickRangeOptions(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let i=this.min,s=this.max;const n=e=>i=t?i:e,o=t=>s=e?s:t;i===s&&(i<=0?(n(1),o(10)):(n(vo(i,-1)),o(vo(s,1)))),i<=0&&n(vo(s,-1)),s<=0&&o(vo(i,1)),this.min=i,this.max=s}buildTicks(){const t=this.options,e=ko({min:this._userMin,max:this._userMax},this);return"ticks"===t.bounds&&j(e,this,"value"),t.reverse?(e.reverse(),this.start=this.max,this.end=this.min):(this.start=this.min,this.end=this.max),e}getLabelForValue(t){return void 0===t?"0":ne(t,this.chart.options.locale,this.options.ticks.format)}configure(){const t=this.min;super.configure(),this._startValue=z(t),this._valueRange=z(this.max)-z(t)}getPixelForValue(t){return void 0!==t&&0!==t||(t=this.min),null===t||isNaN(t)?NaN:this.getPixelForDecimal(t===this.min?0:(z(t)-this._startValue)/this._valueRange)}getValueForPixel(t){const e=this.getDecimalForPixel(t);return Math.pow(10,this._startValue+e*this._valueRange)}}function Po(t){const e=t.ticks;if(e.display&&t.display){const t=ki(e.backdropPadding);return l(e.font&&e.font.size,ue.font.size)+t.height}return 0}function Do(t,e,i,s,n){return t===s||t===n?{start:e-i/2,end:e+i/2}:tn?{start:e-i,end:e}:{start:e,end:e+i}}function Co(t){const e={l:t.left+t._padding.left,r:t.right-t._padding.right,t:t.top+t._padding.top,b:t.bottom-t._padding.bottom},i=Object.assign({},e),s=[],o=[],a=t._pointLabels.length,r=t.options.pointLabels,l=r.centerPointLabels?C/a:0;for(let u=0;ue.r&&(r=(s.end-e.r)/o,t.r=Math.max(t.r,e.r+r)),n.starte.b&&(l=(n.end-e.b)/a,t.b=Math.max(t.b,e.b+l))}function Ao(t,e,i){const s=t.drawingArea,{extra:n,additionalAngle:o,padding:a,size:r}=i,l=t.getPointPosition(e,s+n+a,o),h=Math.round(Y(G(l.angle+E))),c=function(t,e,i){90===i||270===i?t-=e/2:(i>270||i<90)&&(t-=e);return t}(l.y,r.h,h),d=function(t){if(0===t||180===t)return"center";if(t<180)return"left";return"right"}(h),u=function(t,e,i){"right"===i?t-=e:"center"===i&&(t-=e/2);return t}(l.x,r.w,d);return{visible:!0,x:l.x,y:c,textAlign:d,left:u,top:c,right:u+r.w,bottom:c+r.h}}function To(t,e){if(!e)return!0;const{left:i,top:s,right:n,bottom:o}=t;return!(Re({x:i,y:s},e)||Re({x:i,y:o},e)||Re({x:n,y:s},e)||Re({x:n,y:o},e))}function Lo(t,e,i){const{left:n,top:o,right:a,bottom:r}=i,{backdropColor:l}=e;if(!s(l)){const i=wi(e.borderRadius),s=ki(e.backdropPadding);t.fillStyle=l;const h=n-s.left,c=o-s.top,d=a-n+s.width,u=r-o+s.height;Object.values(i).some((t=>0!==t))?(t.beginPath(),He(t,{x:h,y:c,w:d,h:u,radius:i}),t.fill()):t.fillRect(h,c,d,u)}}function Eo(t,e,i,s){const{ctx:n}=t;if(i)n.arc(t.xCenter,t.yCenter,e,0,O);else{let i=t.getPointPosition(0,e);n.moveTo(i.x,i.y);for(let o=1;ot,padding:5,centerPointLabels:!1}};static defaultRoutes={"angleLines.color":"borderColor","pointLabels.color":"color","ticks.color":"color"};static descriptors={angleLines:{_fallback:"grid"}};constructor(t){super(t),this.xCenter=void 0,this.yCenter=void 0,this.drawingArea=void 0,this._pointLabels=[],this._pointLabelItems=[]}setDimensions(){const t=this._padding=ki(Po(this.options)/2),e=this.width=this.maxWidth-t.width,i=this.height=this.maxHeight-t.height;this.xCenter=Math.floor(this.left+e/2+t.left),this.yCenter=Math.floor(this.top+i/2+t.top),this.drawingArea=Math.floor(Math.min(e,i)/2)}determineDataLimits(){const{min:t,max:e}=this.getMinMax(!1);this.min=a(t)&&!isNaN(t)?t:0,this.max=a(e)&&!isNaN(e)?e:0,this.handleTickRangeOptions()}computeTickLimit(){return Math.ceil(this.drawingArea/Po(this.options))}generateTickLabels(t){bo.prototype.generateTickLabels.call(this,t),this._pointLabels=this.getLabels().map(((t,e)=>{const i=d(this.options.pointLabels.callback,[t,e],this);return i||0===i?i:""})).filter(((t,e)=>this.chart.getDataVisibility(e)))}fit(){const t=this.options;t.display&&t.pointLabels.display?Co(this):this.setCenterPoint(0,0,0,0)}setCenterPoint(t,e,i,s){this.xCenter+=Math.floor((t-e)/2),this.yCenter+=Math.floor((i-s)/2),this.drawingArea-=Math.min(this.drawingArea/2,Math.max(t,e,i,s))}getIndexAngle(t){return G(t*(O/(this._pointLabels.length||1))+$(this.options.startAngle||0))}getDistanceFromCenterForValue(t){if(s(t))return NaN;const e=this.drawingArea/(this.max-this.min);return this.options.reverse?(this.max-t)*e:(t-this.min)*e}getValueForDistanceFromCenter(t){if(s(t))return NaN;const e=t/(this.drawingArea/(this.max-this.min));return this.options.reverse?this.max-e:this.min+e}getPointLabelContext(t){const e=this._pointLabels||[];if(t>=0&&t=0;n--){const e=t._pointLabelItems[n];if(!e.visible)continue;const o=s.setContext(t.getPointLabelContext(n));Lo(i,o,e);const a=Si(o.font),{x:r,y:l,textAlign:h}=e;We(i,t._pointLabels[n],r,l+a.lineHeight/2,a,{color:o.color,textAlign:h,textBaseline:"middle"})}}(this,o),s.display&&this.ticks.forEach(((t,e)=>{if(0!==e||0===e&&this.min<0){r=this.getDistanceFromCenterForValue(t.value);const i=this.getContext(e),a=s.setContext(i),l=n.setContext(i);!function(t,e,i,s,n){const o=t.ctx,a=e.circular,{color:r,lineWidth:l}=e;!a&&!s||!r||!l||i<0||(o.save(),o.strokeStyle=r,o.lineWidth=l,o.setLineDash(n.dash||[]),o.lineDashOffset=n.dashOffset,o.beginPath(),Eo(t,i,a,s),o.closePath(),o.stroke(),o.restore())}(this,a,r,o,l)}})),i.display){for(t.save(),a=o-1;a>=0;a--){const s=i.setContext(this.getPointLabelContext(a)),{color:n,lineWidth:o}=s;o&&n&&(t.lineWidth=o,t.strokeStyle=n,t.setLineDash(s.borderDash),t.lineDashOffset=s.borderDashOffset,r=this.getDistanceFromCenterForValue(e.reverse?this.min:this.max),l=this.getPointPosition(a,r),t.beginPath(),t.moveTo(this.xCenter,this.yCenter),t.lineTo(l.x,l.y),t.stroke())}t.restore()}}drawBorder(){}drawLabels(){const t=this.ctx,e=this.options,i=e.ticks;if(!i.display)return;const s=this.getIndexAngle(0);let n,o;t.save(),t.translate(this.xCenter,this.yCenter),t.rotate(s),t.textAlign="center",t.textBaseline="middle",this.ticks.forEach(((s,a)=>{if(0===a&&this.min>=0&&!e.reverse)return;const r=i.setContext(this.getContext(a)),l=Si(r.font);if(n=this.getDistanceFromCenterForValue(this.ticks[a].value),r.showLabelBackdrop){t.font=l.string,o=t.measureText(s.label).width,t.fillStyle=r.backdropColor;const e=ki(r.backdropPadding);t.fillRect(-o/2-e.left,-n-l.size/2-e.top,o+e.width,l.size+e.height)}We(t,s.label,0,-n,l,{color:r.color,strokeColor:r.textStrokeColor,strokeWidth:r.textStrokeWidth})})),t.restore()}drawTitle(){}}const Io={millisecond:{common:!0,size:1,steps:1e3},second:{common:!0,size:1e3,steps:60},minute:{common:!0,size:6e4,steps:60},hour:{common:!0,size:36e5,steps:24},day:{common:!0,size:864e5,steps:30},week:{common:!1,size:6048e5,steps:4},month:{common:!0,size:2628e6,steps:12},quarter:{common:!1,size:7884e6,steps:4},year:{common:!0,size:3154e7}},zo=Object.keys(Io);function Fo(t,e){return t-e}function Vo(t,e){if(s(e))return null;const i=t._adapter,{parser:n,round:o,isoWeekday:r}=t._parseOpts;let l=e;return"function"==typeof n&&(l=n(l)),a(l)||(l="string"==typeof n?i.parse(l,n):i.parse(l)),null===l?null:(o&&(l="week"!==o||!W(r)&&!0!==r?i.startOf(l,o):i.startOf(l,"isoWeek",r)),+l)}function Bo(t,e,i,s){const n=zo.length;for(let o=zo.indexOf(t);o=e?i[s]:i[n]]=!0}}else t[e]=!0}function Wo(t,e,i){const s=[],n={},o=e.length;let a,r;for(a=0;a=0&&(e[l].major=!0);return e}(t,s,n,i):s}class Ho extends tn{static id="time";static defaults={bounds:"data",adapters:{},time:{parser:!1,unit:!1,round:!1,isoWeekday:!1,minUnit:"millisecond",displayFormats:{}},ticks:{source:"auto",callback:!1,major:{enabled:!1}}};constructor(t){super(t),this._cache={data:[],labels:[],all:[]},this._unit="day",this._majorUnit=void 0,this._offsets={},this._normalized=!1,this._parseOpts=void 0}init(t,e={}){const i=t.time||(t.time={}),s=this._adapter=new In._date(t.adapters.date);s.init(e),b(i.displayFormats,s.formats()),this._parseOpts={parser:i.parser,round:i.round,isoWeekday:i.isoWeekday},super.init(t),this._normalized=e.normalized}parse(t,e){return void 0===t?null:Vo(this,t)}beforeLayout(){super.beforeLayout(),this._cache={data:[],labels:[],all:[]}}determineDataLimits(){const t=this.options,e=this._adapter,i=t.time.unit||"day";let{min:s,max:n,minDefined:o,maxDefined:r}=this.getUserBounds();function l(t){o||isNaN(t.min)||(s=Math.min(s,t.min)),r||isNaN(t.max)||(n=Math.max(n,t.max))}o&&r||(l(this._getLabelBounds()),"ticks"===t.bounds&&"labels"===t.ticks.source||l(this.getMinMax(!1))),s=a(s)&&!isNaN(s)?s:+e.startOf(Date.now(),i),n=a(n)&&!isNaN(n)?n:+e.endOf(Date.now(),i)+1,this.min=Math.min(s,n-1),this.max=Math.max(s+1,n)}_getLabelBounds(){const t=this.getLabelTimestamps();let e=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;return t.length&&(e=t[0],i=t[t.length-1]),{min:e,max:i}}buildTicks(){const t=this.options,e=t.time,i=t.ticks,s="labels"===i.source?this.getLabelTimestamps():this._generate();"ticks"===t.bounds&&s.length&&(this.min=this._userMin||s[0],this.max=this._userMax||s[s.length-1]);const n=this.min,o=nt(s,n,this.max);return this._unit=e.unit||(i.autoSkip?Bo(e.minUnit,this.min,this.max,this._getLabelCapacity(n)):function(t,e,i,s,n){for(let o=zo.length-1;o>=zo.indexOf(i);o--){const i=zo[o];if(Io[i].common&&t._adapter.diff(n,s,i)>=e-1)return i}return zo[i?zo.indexOf(i):0]}(this,o.length,e.minUnit,this.min,this.max)),this._majorUnit=i.major.enabled&&"year"!==this._unit?function(t){for(let e=zo.indexOf(t)+1,i=zo.length;e+t.value)))}initOffsets(t=[]){let e,i,s=0,n=0;this.options.offset&&t.length&&(e=this.getDecimalForValue(t[0]),s=1===t.length?1-e:(this.getDecimalForValue(t[1])-e)/2,i=this.getDecimalForValue(t[t.length-1]),n=1===t.length?i:(i-this.getDecimalForValue(t[t.length-2]))/2);const o=t.length<3?.5:.25;s=Z(s,0,o),n=Z(n,0,o),this._offsets={start:s,end:n,factor:1/(s+1+n)}}_generate(){const t=this._adapter,e=this.min,i=this.max,s=this.options,n=s.time,o=n.unit||Bo(n.minUnit,e,i,this._getLabelCapacity(e)),a=l(s.ticks.stepSize,1),r="week"===o&&n.isoWeekday,h=W(r)||!0===r,c={};let d,u,f=e;if(h&&(f=+t.startOf(f,"isoWeek",r)),f=+t.startOf(f,h?"day":o),t.diff(i,e,o)>1e5*a)throw new Error(e+" and "+i+" are too far apart with stepSize of "+a+" "+o);const g="data"===s.ticks.source&&this.getDataTimestamps();for(d=f,u=0;d+t))}getLabelForValue(t){const e=this._adapter,i=this.options.time;return i.tooltipFormat?e.format(t,i.tooltipFormat):e.format(t,i.displayFormats.datetime)}format(t,e){const i=this.options.time.displayFormats,s=this._unit,n=e||i[s];return this._adapter.format(t,n)}_tickFormatFunction(t,e,i,s){const n=this.options,o=n.ticks.callback;if(o)return d(o,[t,e,i],this);const a=n.time.displayFormats,r=this._unit,l=this._majorUnit,h=r&&a[r],c=l&&a[l],u=i[e],f=l&&c&&u&&u.major;return this._adapter.format(t,s||(f?c:h))}generateTickLabels(t){let e,i,s;for(e=0,i=t.length;e0?a:1}getDataTimestamps(){let t,e,i=this._cache.data||[];if(i.length)return i;const s=this.getMatchingVisibleMetas();if(this._normalized&&s.length)return this._cache.data=s[0].controller.getAllParsedValues(this);for(t=0,e=s.length;t=t[r].pos&&e<=t[l].pos&&({lo:r,hi:l}=it(t,"pos",e)),({pos:s,time:o}=t[r]),({pos:n,time:a}=t[l])):(e>=t[r].time&&e<=t[l].time&&({lo:r,hi:l}=it(t,"time",e)),({time:s,pos:o}=t[r]),({time:n,pos:a}=t[l]));const h=n-s;return h?o+(a-o)*(e-s)/h:o}var $o=Object.freeze({__proto__:null,CategoryScale:class extends tn{static id="category";static defaults={ticks:{callback:mo}};constructor(t){super(t),this._startValue=void 0,this._valueRange=0,this._addedLabels=[]}init(t){const e=this._addedLabels;if(e.length){const t=this.getLabels();for(const{index:i,label:s}of e)t[i]===s&&t.splice(i,1);this._addedLabels=[]}super.init(t)}parse(t,e){if(s(t))return null;const i=this.getLabels();return((t,e)=>null===t?null:Z(Math.round(t),0,e))(e=isFinite(e)&&i[e]===t?e:po(i,t,l(e,t),this._addedLabels),i.length-1)}determineDataLimits(){const{minDefined:t,maxDefined:e}=this.getUserBounds();let{min:i,max:s}=this.getMinMax(!0);"ticks"===this.options.bounds&&(t||(i=0),e||(s=this.getLabels().length-1)),this.min=i,this.max=s}buildTicks(){const t=this.min,e=this.max,i=this.options.offset,s=[];let n=this.getLabels();n=0===t&&e===n.length-1?n:n.slice(t,e+1),this._valueRange=Math.max(n.length-(i?0:1),1),this._startValue=this.min-(i?.5:0);for(let i=t;i<=e;i++)s.push({value:i});return s}getLabelForValue(t){return mo.call(this,t)}configure(){super.configure(),this.isHorizontal()||(this._reversePixels=!this._reversePixels)}getPixelForValue(t){return"number"!=typeof t&&(t=this.parse(t)),null===t?NaN:this.getPixelForDecimal((t-this._startValue)/this._valueRange)}getPixelForTick(t){const e=this.ticks;return t<0||t>e.length-1?null:this.getPixelForValue(e[t].value)}getValueForPixel(t){return Math.round(this._startValue+this.getDecimalForPixel(t)*this._valueRange)}getBasePixel(){return this.bottom}},LinearScale:_o,LogarithmicScale:So,RadialLinearScale:Ro,TimeScale:Ho,TimeSeriesScale:class extends Ho{static id="timeseries";static defaults=Ho.defaults;constructor(t){super(t),this._table=[],this._minPos=void 0,this._tableRange=void 0}initOffsets(){const t=this._getTimestampsForTable(),e=this._table=this.buildLookupTable(t);this._minPos=jo(e,this.min),this._tableRange=jo(e,this.max)-this._minPos,super.initOffsets(t)}buildLookupTable(t){const{min:e,max:i}=this,s=[],n=[];let o,a,r,l,h;for(o=0,a=t.length;o=e&&l<=i&&s.push(l);if(s.length<2)return[{time:e,pos:0},{time:i,pos:1}];for(o=0,a=s.length;ot-e))}_getTimestampsForTable(){let t=this._cache.all||[];if(t.length)return t;const e=this.getDataTimestamps(),i=this.getLabelTimestamps();return t=e.length&&i.length?this.normalize(e.concat(i)):e.length?e:i,t=this._cache.all=t,t}getDecimalForValue(t){return(jo(this._table,t)-this._minPos)/this._tableRange}getValueForPixel(t){const e=this._offsets,i=this.getDecimalForPixel(t)/e.factor-e.end;return jo(this._table,i*this._tableRange+this._minPos,!0)}}});const Yo=["rgb(54, 162, 235)","rgb(255, 99, 132)","rgb(255, 159, 64)","rgb(255, 205, 86)","rgb(75, 192, 192)","rgb(153, 102, 255)","rgb(201, 203, 207)"],Uo=Yo.map((t=>t.replace("rgb(","rgba(").replace(")",", 0.5)")));function Xo(t){return Yo[t%Yo.length]}function qo(t){return Uo[t%Uo.length]}function Ko(t){let e=0;return(i,s)=>{const n=t.getDatasetMeta(s).controller;n instanceof $n?e=function(t,e){return t.backgroundColor=t.data.map((()=>Xo(e++))),e}(i,e):n instanceof Yn?e=function(t,e){return t.backgroundColor=t.data.map((()=>qo(e++))),e}(i,e):n&&(e=function(t,e){return t.borderColor=Xo(e),t.backgroundColor=qo(e),++e}(i,e))}}function Go(t){let e;for(e in t)if(t[e].borderColor||t[e].backgroundColor)return!0;return!1}var Jo={id:"colors",defaults:{enabled:!0,forceOverride:!1},beforeLayout(t,e,i){if(!i.enabled)return;const{data:{datasets:s},options:n}=t.config,{elements:o}=n,a=Go(s)||(r=n)&&(r.borderColor||r.backgroundColor)||o&&Go(o)||"rgba(0,0,0,0.1)"!==ue.borderColor||"rgba(0,0,0,0.1)"!==ue.backgroundColor;var r;if(!i.forceOverride&&a)return;const l=Ko(t);s.forEach(l)}};function Zo(t){if(t._decimated){const e=t._data;delete t._decimated,delete t._data,Object.defineProperty(t,"data",{configurable:!0,enumerable:!0,writable:!0,value:e})}}function Qo(t){t.data.datasets.forEach((t=>{Zo(t)}))}var ta={id:"decimation",defaults:{algorithm:"min-max",enabled:!1},beforeElementsUpdate:(t,e,i)=>{if(!i.enabled)return void Qo(t);const n=t.width;t.data.datasets.forEach(((e,o)=>{const{_data:a,indexAxis:r}=e,l=t.getDatasetMeta(o),h=a||e.data;if("y"===Pi([r,t.options.indexAxis]))return;if(!l.controller.supportsDecimation)return;const c=t.scales[l.xAxisID];if("linear"!==c.type&&"time"!==c.type)return;if(t.options.parsing)return;let{start:d,count:u}=function(t,e){const i=e.length;let s,n=0;const{iScale:o}=t,{min:a,max:r,minDefined:l,maxDefined:h}=o.getUserBounds();return l&&(n=Z(it(e,o.axis,a).lo,0,i-1)),s=h?Z(it(e,o.axis,r).hi+1,n,i)-n:i-n,{start:n,count:s}}(l,h);if(u<=(i.threshold||4*n))return void Zo(e);let f;switch(s(a)&&(e._data=h,delete e.data,Object.defineProperty(e,"data",{configurable:!0,enumerable:!0,get:function(){return this._decimated},set:function(t){this._data=t}})),i.algorithm){case"lttb":f=function(t,e,i,s,n){const o=n.samples||s;if(o>=i)return t.slice(e,e+i);const a=[],r=(i-2)/(o-2);let l=0;const h=e+i-1;let c,d,u,f,g,p=e;for(a[l++]=t[p],c=0;cu&&(u=f,d=t[s],g=s);a[l++]=d,p=g}return a[l++]=t[h],a}(h,d,u,n,i);break;case"min-max":f=function(t,e,i,n){let o,a,r,l,h,c,d,u,f,g,p=0,m=0;const x=[],b=e+i-1,_=t[e].x,y=t[b].x-_;for(o=e;og&&(g=l,d=o),p=(m*p+a.x)/++m;else{const i=o-1;if(!s(c)&&!s(d)){const e=Math.min(c,d),s=Math.max(c,d);e!==u&&e!==i&&x.push({...t[e],x:p}),s!==u&&s!==i&&x.push({...t[s],x:p})}o>0&&i!==u&&x.push(t[i]),x.push(a),h=e,m=0,f=g=l,c=d=u=o}}return x}(h,d,u,n);break;default:throw new Error(`Unsupported decimation algorithm '${i.algorithm}'`)}e._decimated=f}))},destroy(t){Qo(t)}};function ea(t,e,i,s){if(s)return;let n=e[t],o=i[t];return"angle"===t&&(n=G(n),o=G(o)),{property:t,start:n,end:o}}function ia(t,e,i){for(;e>t;e--){const t=i[e];if(!isNaN(t.x)&&!isNaN(t.y))break}return e}function sa(t,e,i,s){return t&&e?s(t[i],e[i]):t?t[i]:e?e[i]:0}function na(t,e){let i=[],s=!1;return n(t)?(s=!0,i=t):i=function(t,e){const{x:i=null,y:s=null}=t||{},n=e.points,o=[];return e.segments.forEach((({start:t,end:e})=>{e=ia(t,e,n);const a=n[t],r=n[e];null!==s?(o.push({x:a.x,y:s}),o.push({x:r.x,y:s})):null!==i&&(o.push({x:i,y:a.y}),o.push({x:i,y:r.y}))})),o}(t,e),i.length?new oo({points:i,options:{tension:0},_loop:s,_fullLoop:s}):null}function oa(t){return t&&!1!==t.fill}function aa(t,e,i){let s=t[e].fill;const n=[e];let o;if(!i)return s;for(;!1!==s&&-1===n.indexOf(s);){if(!a(s))return s;if(o=t[s],!o)return!1;if(o.visible)return s;n.push(s),s=o.fill}return!1}function ra(t,e,i){const s=function(t){const e=t.options,i=e.fill;let s=l(i&&i.target,i);void 0===s&&(s=!!e.backgroundColor);if(!1===s||null===s)return!1;if(!0===s)return"origin";return s}(t);if(o(s))return!isNaN(s.value)&&s;let n=parseFloat(s);return a(n)&&Math.floor(n)===n?function(t,e,i,s){"-"!==t&&"+"!==t||(i=e+i);if(i===e||i<0||i>=s)return!1;return i}(s[0],e,n,i):["origin","start","end","stack","shape"].indexOf(s)>=0&&s}function la(t,e,i){const s=[];for(let n=0;n=0;--e){const i=n[e].$filler;i&&(i.line.updateControlPoints(o,i.axis),s&&i.fill&&ua(t.ctx,i,o))}},beforeDatasetsDraw(t,e,i){if("beforeDatasetsDraw"!==i.drawTime)return;const s=t.getSortedVisibleDatasetMetas();for(let e=s.length-1;e>=0;--e){const i=s[e].$filler;oa(i)&&ua(t.ctx,i,t.chartArea)}},beforeDatasetDraw(t,e,i){const s=e.meta.$filler;oa(s)&&"beforeDatasetDraw"===i.drawTime&&ua(t.ctx,s,t.chartArea)},defaults:{propagate:!0,drawTime:"beforeDatasetDraw"}};const _a=(t,e)=>{let{boxHeight:i=e,boxWidth:s=e}=t;return t.usePointStyle&&(i=Math.min(i,e),s=t.pointStyleWidth||Math.min(s,e)),{boxWidth:s,boxHeight:i,itemHeight:Math.max(e,i)}};class ya extends $s{constructor(t){super(),this._added=!1,this.legendHitBoxes=[],this._hoveredItem=null,this.doughnutMode=!1,this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this.legendItems=void 0,this.columnSizes=void 0,this.lineWidths=void 0,this.maxHeight=void 0,this.maxWidth=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.height=void 0,this.width=void 0,this._margins=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e,i){this.maxWidth=t,this.maxHeight=e,this._margins=i,this.setDimensions(),this.buildLabels(),this.fit()}setDimensions(){this.isHorizontal()?(this.width=this.maxWidth,this.left=this._margins.left,this.right=this.width):(this.height=this.maxHeight,this.top=this._margins.top,this.bottom=this.height)}buildLabels(){const t=this.options.labels||{};let e=d(t.generateLabels,[this.chart],this)||[];t.filter&&(e=e.filter((e=>t.filter(e,this.chart.data)))),t.sort&&(e=e.sort(((e,i)=>t.sort(e,i,this.chart.data)))),this.options.reverse&&e.reverse(),this.legendItems=e}fit(){const{options:t,ctx:e}=this;if(!t.display)return void(this.width=this.height=0);const i=t.labels,s=Si(i.font),n=s.size,o=this._computeTitleHeight(),{boxWidth:a,itemHeight:r}=_a(i,n);let l,h;e.font=s.string,this.isHorizontal()?(l=this.maxWidth,h=this._fitRows(o,n,a,r)+10):(h=this.maxHeight,l=this._fitCols(o,s,a,r)+10),this.width=Math.min(l,t.maxWidth||this.maxWidth),this.height=Math.min(h,t.maxHeight||this.maxHeight)}_fitRows(t,e,i,s){const{ctx:n,maxWidth:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.lineWidths=[0],h=s+a;let c=t;n.textAlign="left",n.textBaseline="middle";let d=-1,u=-h;return this.legendItems.forEach(((t,f)=>{const g=i+e/2+n.measureText(t.text).width;(0===f||l[l.length-1]+g+2*a>o)&&(c+=h,l[l.length-(f>0?0:1)]=0,u+=h,d++),r[f]={left:0,top:u,row:d,width:g,height:s},l[l.length-1]+=g+a})),c}_fitCols(t,e,i,s){const{ctx:n,maxHeight:o,options:{labels:{padding:a}}}=this,r=this.legendHitBoxes=[],l=this.columnSizes=[],h=o-t;let c=a,d=0,u=0,f=0,g=0;return this.legendItems.forEach(((t,o)=>{const{itemWidth:p,itemHeight:m}=function(t,e,i,s,n){const o=function(t,e,i,s){let n=t.text;n&&"string"!=typeof n&&(n=n.reduce(((t,e)=>t.length>e.length?t:e)));return e+i.size/2+s.measureText(n).width}(s,t,e,i),a=function(t,e,i){let s=t;"string"!=typeof e.text&&(s=va(e,i));return s}(n,s,e.lineHeight);return{itemWidth:o,itemHeight:a}}(i,e,n,t,s);o>0&&u+m+2*a>h&&(c+=d+a,l.push({width:d,height:u}),f+=d+a,g++,d=u=0),r[o]={left:f,top:u,col:g,width:p,height:m},d=Math.max(d,p),u+=m+a})),c+=d,l.push({width:d,height:u}),c}adjustHitBoxes(){if(!this.options.display)return;const t=this._computeTitleHeight(),{legendHitBoxes:e,options:{align:i,labels:{padding:s},rtl:n}}=this,o=Oi(n,this.left,this.width);if(this.isHorizontal()){let n=0,a=ft(i,this.left+s,this.right-this.lineWidths[n]);for(const r of e)n!==r.row&&(n=r.row,a=ft(i,this.left+s,this.right-this.lineWidths[n])),r.top+=this.top+t+s,r.left=o.leftForLtr(o.x(a),r.width),a+=r.width+s}else{let n=0,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height);for(const r of e)r.col!==n&&(n=r.col,a=ft(i,this.top+t+s,this.bottom-this.columnSizes[n].height)),r.top=a,r.left+=this.left+s,r.left=o.leftForLtr(o.x(r.left),r.width),a+=r.height+s}}isHorizontal(){return"top"===this.options.position||"bottom"===this.options.position}draw(){if(this.options.display){const t=this.ctx;Ie(t,this),this._draw(),ze(t)}}_draw(){const{options:t,columnSizes:e,lineWidths:i,ctx:s}=this,{align:n,labels:o}=t,a=ue.color,r=Oi(t.rtl,this.left,this.width),h=Si(o.font),{padding:c}=o,d=h.size,u=d/2;let f;this.drawTitle(),s.textAlign=r.textAlign("left"),s.textBaseline="middle",s.lineWidth=.5,s.font=h.string;const{boxWidth:g,boxHeight:p,itemHeight:m}=_a(o,d),x=this.isHorizontal(),b=this._computeTitleHeight();f=x?{x:ft(n,this.left+c,this.right-i[0]),y:this.top+c+b,line:0}:{x:this.left+c,y:ft(n,this.top+b+c,this.bottom-e[0].height),line:0},Ai(this.ctx,t.textDirection);const _=m+c;this.legendItems.forEach(((y,v)=>{s.strokeStyle=y.fontColor,s.fillStyle=y.fontColor;const M=s.measureText(y.text).width,w=r.textAlign(y.textAlign||(y.textAlign=o.textAlign)),k=g+u+M;let S=f.x,P=f.y;r.setWidth(this.width),x?v>0&&S+k+c>this.right&&(P=f.y+=_,f.line++,S=f.x=ft(n,this.left+c,this.right-i[f.line])):v>0&&P+_>this.bottom&&(S=f.x=S+e[f.line].width+c,f.line++,P=f.y=ft(n,this.top+b+c,this.bottom-e[f.line].height));if(function(t,e,i){if(isNaN(g)||g<=0||isNaN(p)||p<0)return;s.save();const n=l(i.lineWidth,1);if(s.fillStyle=l(i.fillStyle,a),s.lineCap=l(i.lineCap,"butt"),s.lineDashOffset=l(i.lineDashOffset,0),s.lineJoin=l(i.lineJoin,"miter"),s.lineWidth=n,s.strokeStyle=l(i.strokeStyle,a),s.setLineDash(l(i.lineDash,[])),o.usePointStyle){const a={radius:p*Math.SQRT2/2,pointStyle:i.pointStyle,rotation:i.rotation,borderWidth:n},l=r.xPlus(t,g/2);Ee(s,a,l,e+u,o.pointStyleWidth&&g)}else{const o=e+Math.max((d-p)/2,0),a=r.leftForLtr(t,g),l=wi(i.borderRadius);s.beginPath(),Object.values(l).some((t=>0!==t))?He(s,{x:a,y:o,w:g,h:p,radius:l}):s.rect(a,o,g,p),s.fill(),0!==n&&s.stroke()}s.restore()}(r.x(S),P,y),S=gt(w,S+g+u,x?S+k:this.right,t.rtl),function(t,e,i){We(s,i.text,t,e+m/2,h,{strikethrough:i.hidden,textAlign:r.textAlign(i.textAlign)})}(r.x(S),P,y),x)f.x+=k+c;else if("string"!=typeof y.text){const t=h.lineHeight;f.y+=va(y,t)+c}else f.y+=_})),Ti(this.ctx,t.textDirection)}drawTitle(){const t=this.options,e=t.title,i=Si(e.font),s=ki(e.padding);if(!e.display)return;const n=Oi(t.rtl,this.left,this.width),o=this.ctx,a=e.position,r=i.size/2,l=s.top+r;let h,c=this.left,d=this.width;if(this.isHorizontal())d=Math.max(...this.lineWidths),h=this.top+l,c=ft(t.align,c,this.right-d);else{const e=this.columnSizes.reduce(((t,e)=>Math.max(t,e.height)),0);h=l+ft(t.align,this.top,this.bottom-e-t.labels.padding-this._computeTitleHeight())}const u=ft(a,c,c+d);o.textAlign=n.textAlign(ut(a)),o.textBaseline="middle",o.strokeStyle=e.color,o.fillStyle=e.color,o.font=i.string,We(o,e.text,u,h,i)}_computeTitleHeight(){const t=this.options.title,e=Si(t.font),i=ki(t.padding);return t.display?e.lineHeight+i.height:0}_getLegendItemAt(t,e){let i,s,n;if(tt(t,this.left,this.right)&&tt(e,this.top,this.bottom))for(n=this.legendHitBoxes,i=0;it.chart.options.color,boxWidth:40,padding:10,generateLabels(t){const e=t.data.datasets,{labels:{usePointStyle:i,pointStyle:s,textAlign:n,color:o,useBorderRadius:a,borderRadius:r}}=t.legend.options;return t._getSortedDatasetMetas().map((t=>{const l=t.controller.getStyle(i?0:void 0),h=ki(l.borderWidth);return{text:e[t.index].label,fillStyle:l.backgroundColor,fontColor:o,hidden:!t.visible,lineCap:l.borderCapStyle,lineDash:l.borderDash,lineDashOffset:l.borderDashOffset,lineJoin:l.borderJoinStyle,lineWidth:(h.width+h.height)/4,strokeStyle:l.borderColor,pointStyle:s||l.pointStyle,rotation:l.rotation,textAlign:n||l.textAlign,borderRadius:a&&(r||l.borderRadius),datasetIndex:t.index}}),this)}},title:{color:t=>t.chart.options.color,display:!1,position:"center",text:""}},descriptors:{_scriptable:t=>!t.startsWith("on"),labels:{_scriptable:t=>!["generateLabels","filter","sort"].includes(t)}}};class wa extends $s{constructor(t){super(),this.chart=t.chart,this.options=t.options,this.ctx=t.ctx,this._padding=void 0,this.top=void 0,this.bottom=void 0,this.left=void 0,this.right=void 0,this.width=void 0,this.height=void 0,this.position=void 0,this.weight=void 0,this.fullSize=void 0}update(t,e){const i=this.options;if(this.left=0,this.top=0,!i.display)return void(this.width=this.height=this.right=this.bottom=0);this.width=this.right=t,this.height=this.bottom=e;const s=n(i.text)?i.text.length:1;this._padding=ki(i.padding);const o=s*Si(i.font).lineHeight+this._padding.height;this.isHorizontal()?this.height=o:this.width=o}isHorizontal(){const t=this.options.position;return"top"===t||"bottom"===t}_drawArgs(t){const{top:e,left:i,bottom:s,right:n,options:o}=this,a=o.align;let r,l,h,c=0;return this.isHorizontal()?(l=ft(a,i,n),h=e+t,r=n-i):("left"===o.position?(l=i+t,h=ft(a,s,e),c=-.5*C):(l=n-t,h=ft(a,e,s),c=.5*C),r=s-e),{titleX:l,titleY:h,maxWidth:r,rotation:c}}draw(){const t=this.ctx,e=this.options;if(!e.display)return;const i=Si(e.font),s=i.lineHeight/2+this._padding.top,{titleX:n,titleY:o,maxWidth:a,rotation:r}=this._drawArgs(s);We(t,e.text,0,0,i,{color:e.color,maxWidth:a,rotation:r,textAlign:ut(e.align),textBaseline:"middle",translation:[n,o]})}}var ka={id:"title",_element:wa,start(t,e,i){!function(t,e){const i=new wa({ctx:t.ctx,options:e,chart:t});ls.configure(t,i,e),ls.addBox(t,i),t.titleBlock=i}(t,i)},stop(t){const e=t.titleBlock;ls.removeBox(t,e),delete t.titleBlock},beforeUpdate(t,e,i){const s=t.titleBlock;ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"bold"},fullSize:!0,padding:10,position:"top",text:"",weight:2e3},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Sa=new WeakMap;var Pa={id:"subtitle",start(t,e,i){const s=new wa({ctx:t.ctx,options:i,chart:t});ls.configure(t,s,i),ls.addBox(t,s),Sa.set(t,s)},stop(t){ls.removeBox(t,Sa.get(t)),Sa.delete(t)},beforeUpdate(t,e,i){const s=Sa.get(t);ls.configure(t,s,i),s.options=i},defaults:{align:"center",display:!1,font:{weight:"normal"},fullSize:!0,padding:0,position:"top",text:"",weight:1500},defaultRoutes:{color:"color"},descriptors:{_scriptable:!0,_indexable:!1}};const Da={average(t){if(!t.length)return!1;let e,i,s=new Set,n=0,o=0;for(e=0,i=t.length;et+e))/s.size,y:n/o}},nearest(t,e){if(!t.length)return!1;let i,s,n,o=e.x,a=e.y,r=Number.POSITIVE_INFINITY;for(i=0,s=t.length;i-1?t.split("\n"):t}function Aa(t,e){const{element:i,datasetIndex:s,index:n}=e,o=t.getDatasetMeta(s).controller,{label:a,value:r}=o.getLabelAndValue(n);return{chart:t,label:a,parsed:o.getParsed(n),raw:t.data.datasets[s].data[n],formattedValue:r,dataset:o.getDataset(),dataIndex:n,datasetIndex:s,element:i}}function Ta(t,e){const i=t.chart.ctx,{body:s,footer:n,title:o}=t,{boxWidth:a,boxHeight:r}=e,l=Si(e.bodyFont),h=Si(e.titleFont),c=Si(e.footerFont),d=o.length,f=n.length,g=s.length,p=ki(e.padding);let m=p.height,x=0,b=s.reduce(((t,e)=>t+e.before.length+e.lines.length+e.after.length),0);if(b+=t.beforeBody.length+t.afterBody.length,d&&(m+=d*h.lineHeight+(d-1)*e.titleSpacing+e.titleMarginBottom),b){m+=g*(e.displayColors?Math.max(r,l.lineHeight):l.lineHeight)+(b-g)*l.lineHeight+(b-1)*e.bodySpacing}f&&(m+=e.footerMarginTop+f*c.lineHeight+(f-1)*e.footerSpacing);let _=0;const y=function(t){x=Math.max(x,i.measureText(t).width+_)};return i.save(),i.font=h.string,u(t.title,y),i.font=l.string,u(t.beforeBody.concat(t.afterBody),y),_=e.displayColors?a+2+e.boxPadding:0,u(s,(t=>{u(t.before,y),u(t.lines,y),u(t.after,y)})),_=0,i.font=c.string,u(t.footer,y),i.restore(),x+=p.width,{width:x,height:m}}function La(t,e,i,s){const{x:n,width:o}=i,{width:a,chartArea:{left:r,right:l}}=t;let h="center";return"center"===s?h=n<=(r+l)/2?"left":"right":n<=o/2?h="left":n>=a-o/2&&(h="right"),function(t,e,i,s){const{x:n,width:o}=s,a=i.caretSize+i.caretPadding;return"left"===t&&n+o+a>e.width||"right"===t&&n-o-a<0||void 0}(h,t,e,i)&&(h="center"),h}function Ea(t,e,i){const s=i.yAlign||e.yAlign||function(t,e){const{y:i,height:s}=e;return it.height-s/2?"bottom":"center"}(t,i);return{xAlign:i.xAlign||e.xAlign||La(t,e,i,s),yAlign:s}}function Ra(t,e,i,s){const{caretSize:n,caretPadding:o,cornerRadius:a}=t,{xAlign:r,yAlign:l}=i,h=n+o,{topLeft:c,topRight:d,bottomLeft:u,bottomRight:f}=wi(a);let g=function(t,e){let{x:i,width:s}=t;return"right"===e?i-=s:"center"===e&&(i-=s/2),i}(e,r);const p=function(t,e,i){let{y:s,height:n}=t;return"top"===e?s+=i:s-="bottom"===e?n+i:n/2,s}(e,l,h);return"center"===l?"left"===r?g+=h:"right"===r&&(g-=h):"left"===r?g-=Math.max(c,u)+n:"right"===r&&(g+=Math.max(d,f)+n),{x:Z(g,0,s.width-e.width),y:Z(p,0,s.height-e.height)}}function Ia(t,e,i){const s=ki(i.padding);return"center"===e?t.x+t.width/2:"right"===e?t.x+t.width-s.right:t.x+s.left}function za(t){return Ca([],Oa(t))}function Fa(t,e){const i=e&&e.dataset&&e.dataset.tooltip&&e.dataset.tooltip.callbacks;return i?t.override(i):t}const Va={beforeTitle:e,title(t){if(t.length>0){const e=t[0],i=e.chart.data.labels,s=i?i.length:0;if(this&&this.options&&"dataset"===this.options.mode)return e.dataset.label||"";if(e.label)return e.label;if(s>0&&e.dataIndex{const e={before:[],lines:[],after:[]},n=Fa(i,t);Ca(e.before,Oa(Ba(n,"beforeLabel",this,t))),Ca(e.lines,Ba(n,"label",this,t)),Ca(e.after,Oa(Ba(n,"afterLabel",this,t))),s.push(e)})),s}getAfterBody(t,e){return za(Ba(e.callbacks,"afterBody",this,t))}getFooter(t,e){const{callbacks:i}=e,s=Ba(i,"beforeFooter",this,t),n=Ba(i,"footer",this,t),o=Ba(i,"afterFooter",this,t);let a=[];return a=Ca(a,Oa(s)),a=Ca(a,Oa(n)),a=Ca(a,Oa(o)),a}_createItems(t){const e=this._active,i=this.chart.data,s=[],n=[],o=[];let a,r,l=[];for(a=0,r=e.length;at.filter(e,s,n,i)))),t.itemSort&&(l=l.sort(((e,s)=>t.itemSort(e,s,i)))),u(l,(e=>{const i=Fa(t.callbacks,e);s.push(Ba(i,"labelColor",this,e)),n.push(Ba(i,"labelPointStyle",this,e)),o.push(Ba(i,"labelTextColor",this,e))})),this.labelColors=s,this.labelPointStyles=n,this.labelTextColors=o,this.dataPoints=l,l}update(t,e){const i=this.options.setContext(this.getContext()),s=this._active;let n,o=[];if(s.length){const t=Da[i.position].call(this,s,this._eventPosition);o=this._createItems(i),this.title=this.getTitle(o,i),this.beforeBody=this.getBeforeBody(o,i),this.body=this.getBody(o,i),this.afterBody=this.getAfterBody(o,i),this.footer=this.getFooter(o,i);const e=this._size=Ta(this,i),a=Object.assign({},t,e),r=Ea(this.chart,i,a),l=Ra(i,a,r,this.chart);this.xAlign=r.xAlign,this.yAlign=r.yAlign,n={opacity:1,x:l.x,y:l.y,width:e.width,height:e.height,caretX:t.x,caretY:t.y}}else 0!==this.opacity&&(n={opacity:0});this._tooltipItems=o,this.$context=void 0,n&&this._resolveAnimations().update(this,n),t&&i.external&&i.external.call(this,{chart:this.chart,tooltip:this,replay:e})}drawCaret(t,e,i,s){const n=this.getCaretPosition(t,i,s);e.lineTo(n.x1,n.y1),e.lineTo(n.x2,n.y2),e.lineTo(n.x3,n.y3)}getCaretPosition(t,e,i){const{xAlign:s,yAlign:n}=this,{caretSize:o,cornerRadius:a}=i,{topLeft:r,topRight:l,bottomLeft:h,bottomRight:c}=wi(a),{x:d,y:u}=t,{width:f,height:g}=e;let p,m,x,b,_,y;return"center"===n?(_=u+g/2,"left"===s?(p=d,m=p-o,b=_+o,y=_-o):(p=d+f,m=p+o,b=_-o,y=_+o),x=p):(m="left"===s?d+Math.max(r,h)+o:"right"===s?d+f-Math.max(l,c)-o:this.caretX,"top"===n?(b=u,_=b-o,p=m-o,x=m+o):(b=u+g,_=b+o,p=m+o,x=m-o),y=b),{x1:p,x2:m,x3:x,y1:b,y2:_,y3:y}}drawTitle(t,e,i){const s=this.title,n=s.length;let o,a,r;if(n){const l=Oi(i.rtl,this.x,this.width);for(t.x=Ia(this,i.titleAlign,i),e.textAlign=l.textAlign(i.titleAlign),e.textBaseline="middle",o=Si(i.titleFont),a=i.titleSpacing,e.fillStyle=i.titleColor,e.font=o.string,r=0;r0!==t))?(t.beginPath(),t.fillStyle=n.multiKeyBackground,He(t,{x:e,y:g,w:h,h:l,radius:r}),t.fill(),t.stroke(),t.fillStyle=a.backgroundColor,t.beginPath(),He(t,{x:i,y:g+1,w:h-2,h:l-2,radius:r}),t.fill()):(t.fillStyle=n.multiKeyBackground,t.fillRect(e,g,h,l),t.strokeRect(e,g,h,l),t.fillStyle=a.backgroundColor,t.fillRect(i,g+1,h-2,l-2))}t.fillStyle=this.labelTextColors[i]}drawBody(t,e,i){const{body:s}=this,{bodySpacing:n,bodyAlign:o,displayColors:a,boxHeight:r,boxWidth:l,boxPadding:h}=i,c=Si(i.bodyFont);let d=c.lineHeight,f=0;const g=Oi(i.rtl,this.x,this.width),p=function(i){e.fillText(i,g.x(t.x+f),t.y+d/2),t.y+=d+n},m=g.textAlign(o);let x,b,_,y,v,M,w;for(e.textAlign=o,e.textBaseline="middle",e.font=c.string,t.x=Ia(this,m,i),e.fillStyle=i.bodyColor,u(this.beforeBody,p),f=a&&"right"!==m?"center"===o?l/2+h:l+2+h:0,y=0,M=s.length;y0&&e.stroke()}_updateAnimationTarget(t){const e=this.chart,i=this.$animations,s=i&&i.x,n=i&&i.y;if(s||n){const i=Da[t.position].call(this,this._active,this._eventPosition);if(!i)return;const o=this._size=Ta(this,t),a=Object.assign({},i,this._size),r=Ea(e,t,a),l=Ra(t,a,r,e);s._to===l.x&&n._to===l.y||(this.xAlign=r.xAlign,this.yAlign=r.yAlign,this.width=o.width,this.height=o.height,this.caretX=i.x,this.caretY=i.y,this._resolveAnimations().update(this,l))}}_willRender(){return!!this.opacity}draw(t){const e=this.options.setContext(this.getContext());let i=this.opacity;if(!i)return;this._updateAnimationTarget(e);const s={width:this.width,height:this.height},n={x:this.x,y:this.y};i=Math.abs(i)<.001?0:i;const o=ki(e.padding),a=this.title.length||this.beforeBody.length||this.body.length||this.afterBody.length||this.footer.length;e.enabled&&a&&(t.save(),t.globalAlpha=i,this.drawBackground(n,t,s,e),Ai(t,e.textDirection),n.y+=o.top,this.drawTitle(n,t,e),this.drawBody(n,t,e),this.drawFooter(n,t,e),Ti(t,e.textDirection),t.restore())}getActiveElements(){return this._active||[]}setActiveElements(t,e){const i=this._active,s=t.map((({datasetIndex:t,index:e})=>{const i=this.chart.getDatasetMeta(t);if(!i)throw new Error("Cannot find a dataset at index "+t);return{datasetIndex:t,element:i.data[e],index:e}})),n=!f(i,s),o=this._positionChanged(s,e);(n||o)&&(this._active=s,this._eventPosition=e,this._ignoreReplayEvents=!0,this.update(!0))}handleEvent(t,e,i=!0){if(e&&this._ignoreReplayEvents)return!1;this._ignoreReplayEvents=!1;const s=this.options,n=this._active||[],o=this._getActiveElements(t,n,e,i),a=this._positionChanged(o,t),r=e||!f(o,n)||a;return r&&(this._active=o,(s.enabled||s.external)&&(this._eventPosition={x:t.x,y:t.y},this.update(!0,e))),r}_getActiveElements(t,e,i,s){const n=this.options;if("mouseout"===t.type)return[];if(!s)return e.filter((t=>this.chart.data.datasets[t.datasetIndex]&&void 0!==this.chart.getDatasetMeta(t.datasetIndex).controller.getParsed(t.index)));const o=this.chart.getElementsAtEventForMode(t,n.mode,n,i);return n.reverse&&o.reverse(),o}_positionChanged(t,e){const{caretX:i,caretY:s,options:n}=this,o=Da[n.position].call(this,t,e);return!1!==o&&(i!==o.x||s!==o.y)}}var Wa={id:"tooltip",_element:Na,positioners:Da,afterInit(t,e,i){i&&(t.tooltip=new Na({chart:t,options:i}))},beforeUpdate(t,e,i){t.tooltip&&t.tooltip.initialize(i)},reset(t,e,i){t.tooltip&&t.tooltip.initialize(i)},afterDraw(t){const e=t.tooltip;if(e&&e._willRender()){const i={tooltip:e};if(!1===t.notifyPlugins("beforeTooltipDraw",{...i,cancelable:!0}))return;e.draw(t.ctx),t.notifyPlugins("afterTooltipDraw",i)}},afterEvent(t,e){if(t.tooltip){const i=e.replay;t.tooltip.handleEvent(e.event,i,e.inChartArea)&&(e.changed=!0)}},defaults:{enabled:!0,external:null,position:"average",backgroundColor:"rgba(0,0,0,0.8)",titleColor:"#fff",titleFont:{weight:"bold"},titleSpacing:2,titleMarginBottom:6,titleAlign:"left",bodyColor:"#fff",bodySpacing:2,bodyFont:{},bodyAlign:"left",footerColor:"#fff",footerSpacing:2,footerMarginTop:6,footerFont:{weight:"bold"},footerAlign:"left",padding:6,caretPadding:2,caretSize:5,cornerRadius:6,boxHeight:(t,e)=>e.bodyFont.size,boxWidth:(t,e)=>e.bodyFont.size,multiKeyBackground:"#fff",displayColors:!0,boxPadding:0,borderColor:"rgba(0,0,0,0)",borderWidth:0,animation:{duration:400,easing:"easeOutQuart"},animations:{numbers:{type:"number",properties:["x","y","width","height","caretX","caretY"]},opacity:{easing:"linear",duration:200}},callbacks:Va},defaultRoutes:{bodyFont:"font",footerFont:"font",titleFont:"font"},descriptors:{_scriptable:t=>"filter"!==t&&"itemSort"!==t&&"external"!==t,_indexable:!1,callbacks:{_scriptable:!1,_indexable:!1},animation:{_fallback:!1},animations:{_fallback:"animation"}},additionalOptionScopes:["interaction"]};return Tn.register(Un,$o,go,t),Tn.helpers={...Hi},Tn._adapters=In,Tn.Animation=As,Tn.Animations=Ts,Tn.animator=bt,Tn.controllers=nn.controllers.items,Tn.DatasetController=js,Tn.Element=$s,Tn.elements=go,Tn.Interaction=Ki,Tn.layouts=ls,Tn.platforms=Ds,Tn.Scale=tn,Tn.Ticks=ae,Object.assign(Tn,Un,$o,go,t,Ds),Tn.Chart=Tn,"undefined"!=typeof window&&(window.Chart=Tn),Tn})); +//# sourceMappingURL=chart.umd.min.js.map diff --git a/static/vendor/fonts/inter-latin-400-normal.woff2 b/static/vendor/fonts/inter-latin-400-normal.woff2 new file mode 100644 index 0000000..f15b025 Binary files /dev/null and b/static/vendor/fonts/inter-latin-400-normal.woff2 differ diff --git a/static/vendor/fonts/inter-latin-500-normal.woff2 b/static/vendor/fonts/inter-latin-500-normal.woff2 new file mode 100644 index 0000000..54f0a59 Binary files /dev/null and b/static/vendor/fonts/inter-latin-500-normal.woff2 differ diff --git a/static/vendor/fonts/inter-latin-600-normal.woff2 b/static/vendor/fonts/inter-latin-600-normal.woff2 new file mode 100644 index 0000000..d189794 Binary files /dev/null and b/static/vendor/fonts/inter-latin-600-normal.woff2 differ diff --git a/static/vendor/fonts/inter-latin-700-normal.woff2 b/static/vendor/fonts/inter-latin-700-normal.woff2 new file mode 100644 index 0000000..a68fb10 Binary files /dev/null and b/static/vendor/fonts/inter-latin-700-normal.woff2 differ diff --git a/static/vendor/fonts/inter-latin-ext-400-normal.woff2 b/static/vendor/fonts/inter-latin-ext-400-normal.woff2 new file mode 100644 index 0000000..5243e4b Binary files /dev/null and b/static/vendor/fonts/inter-latin-ext-400-normal.woff2 differ diff --git a/static/vendor/fonts/inter-latin-ext-500-normal.woff2 b/static/vendor/fonts/inter-latin-ext-500-normal.woff2 new file mode 100644 index 0000000..2ab7ebf Binary files /dev/null and b/static/vendor/fonts/inter-latin-ext-500-normal.woff2 differ diff --git a/static/vendor/fonts/inter-latin-ext-600-normal.woff2 b/static/vendor/fonts/inter-latin-ext-600-normal.woff2 new file mode 100644 index 0000000..bad65d4 Binary files /dev/null and b/static/vendor/fonts/inter-latin-ext-600-normal.woff2 differ diff --git a/static/vendor/fonts/inter-latin-ext-700-normal.woff2 b/static/vendor/fonts/inter-latin-ext-700-normal.woff2 new file mode 100644 index 0000000..c9507e3 Binary files /dev/null and b/static/vendor/fonts/inter-latin-ext-700-normal.woff2 differ diff --git a/static/vendor/licenses/chart.js.LICENSE.md b/static/vendor/licenses/chart.js.LICENSE.md new file mode 100644 index 0000000..f216610 --- /dev/null +++ b/static/vendor/licenses/chart.js.LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2014-2024 Chart.js Contributors + +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. diff --git a/static/vendor/licenses/dompurify.LICENSE b/static/vendor/licenses/dompurify.LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/static/vendor/licenses/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/static/vendor/licenses/inter.LICENSE b/static/vendor/licenses/inter.LICENSE new file mode 100644 index 0000000..40589da --- /dev/null +++ b/static/vendor/licenses/inter.LICENSE @@ -0,0 +1,93 @@ +Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter) Inter-Italic[opsz,wght].ttf: Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/static/vendor/licenses/marked.LICENSE b/static/vendor/licenses/marked.LICENSE new file mode 100644 index 0000000..4bd2d4a --- /dev/null +++ b/static/vendor/licenses/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/static/vendor/marked.umd.js b/static/vendor/marked.umd.js new file mode 100644 index 0000000..636f697 --- /dev/null +++ b/static/vendor/marked.umd.js @@ -0,0 +1,86 @@ +/** + * marked v18.1.3 - 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(g,f){if(typeof exports=="object"&&typeof module<"u"){module.exports=f()}else if("function"==typeof define && define.amd){define("marked",f)}else {g["marked"]=f()}}(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : this,function(){var exports={};var __exports=exports;var module={exports}; +"use strict";var se=Object.defineProperty;var He=Object.getOwnPropertyDescriptor;var je=Object.getOwnPropertyNames;var Ge=Object.prototype.hasOwnProperty;var Ne=(a,e)=>{for(var t in e)se(a,t,{get:e[t],enumerable:!0})},Fe=(a,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of je(e))!Ge.call(a,s)&&s!==t&&se(a,s,{get:()=>e[s],enumerable:!(n=He(e,s))||n.enumerable});return a};var Qe=a=>Fe(se({},"__esModule",{value:!0}),a);var Jt={};Ne(Jt,{Hooks:()=>L,Lexer:()=>O,Marked:()=>Q,Parser:()=>w,Renderer:()=>$,TextRenderer:()=>A,Tokenizer:()=>_,defaults:()=>P,getDefaults:()=>D,lexer:()=>Vt,marked:()=>m,options:()=>Ft,parse:()=>Kt,parseInline:()=>Wt,parser:()=>Xt,setOptions:()=>Qt,use:()=>ve,walkTokens:()=>Ut});module.exports=Qe(Jt);function D(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var P=D();function ie(a){P=a}var q={exec:()=>null};function B(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 Oe=((a="")=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+)[ \t]*)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,blockquoteMarkerWhitespace:/^( {0,3}>)([ \t]+)/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\][ \t]+\S/,listReplaceTask:/^\[[ xX]\][ \t]+/,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:B(a=>new RegExp(`^ {0,${a}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:B(a=>new RegExp(`^ {0,${a}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:B(a=>new RegExp(`^ {0,${a}}(?:\`\`\`|~~~)`)),headingBeginRegex:B(a=>new RegExp(`^ {0,${a}}#{1,6}(?:\\s|$)`)),pedanticHeadingBeginRegex:B(a=>new RegExp(`^ {0,${a}}#`)),htmlBeginRegex:B(a=>new RegExp(`^ {0,${a}}(?:)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|new RegExp(`^ {0,${a}}>`))},Ue=/^(?:[ \t]*(?:\n|$))+/,We=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ke=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}(?:(?=`)\1`*|(?=~)\1~*) *(?=\n|$)|$)/,K=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Xe=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ae=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,we=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+)[ \t]*(?:\n+|$)/,Pe=c(we).replace(/bull/g,ae).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(),Ve=c(we).replace(/bull/g,ae).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(),le=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Je=/^[^\n]+/,ue=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\\n]|\n(?![ \t]*\n))+/,Ye=c(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",ue).replace("title",/(?:"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\\n]|\n(?!\n))*'|\((?:\\[\s\S]|[^()\\])*\))/).getRegex(),et=c(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ae).getRegex(),X="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",pe=/|$))/,tt=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",pe).replace("tag",X).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Se=a=>c(le).replace("hr",K).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",rt).getRegex(),ce={blockquote:st,code:We,def:Ye,fences:Ke,heading:Xe,hr:K,html:tt,lheading:Pe,list:et,newline:Ue,paragraph:nt,table:q,text:Je},be=c("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",K).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",pe).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:q,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:c(le).replace("hr",K).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",Pe).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},at=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,lt=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,ye=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,ut=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Oe?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),$e=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,kt=c($e,"u").replace(/punct/g,C).getRegex(),ft=c($e,"u").replace(/punct/g,_e).getRegex(),mt=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,xt=c(mt,"u").replace(/openQuote/g,ct).replace(/punct/g,C).getRegex(),Le="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",bt=c(Le,"gu").replace(/notPunctSpace/g,V).replace(/punctSpace/g,j).replace(/punct/g,C).getRegex(),Rt=c(Le,"gu").replace(/notPunctSpace/g,dt).replace(/punctSpace/g,ht).replace(/punct/g,_e).getRegex(),Tt="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",Ot=c(Tt,"gu").replace(/notPunctSpace/g,V).replace(/punctSpace/g,j).replace(/punct/g,C).getRegex(),wt=c("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,V).replace(/punctSpace/g,j).replace(/punct/g,C).getRegex(),Pt="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",St=c(Pt,"gu").replace(/notPunctSpace/g,V).replace(/punctSpace/g,j).replace(/punct/g,C).getRegex(),yt=c(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,C).getRegex(),_t="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",$t=c(_t,"gu").replace(/notPunctSpace/g,V).replace(/punctSpace/g,j).replace(/punct/g,C).getRegex(),Lt=c(/\\(punct)/,"gu").replace(/punct/g,C).getRegex(),Ct=c(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,C).getRegex(),It=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(),At=c(pe).replace("(?:-->|$)","-->").getRegex(),Et=c("^comment|^|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",At).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ce=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,re=c(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",Ce).getRegex(),zt=c(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",re).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\((?:\\[\s\S]|[^)\\])*\)/).getRegex(),Mt=c(/^!?\[(label)\]\[(ref)\]/).replace("label",re).replace("ref",ue).getRegex(),Dt=c(/^!?\[(ref)\](?:\[\])?/).replace("ref",ue).getRegex(),Re=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,Bt=c(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).replace("brackets",Ce).getRegex(),qt=c("reflink|nolink(?!\\()","g").replace("reflink",c(/^!?\[(label)\]\[(ref)\]/).replace("label",Bt).replace("ref",Re).getRegex()).replace("nolink",c(/^!?\[(ref)\](?:\[\])?/).replace("ref",Re).getRegex()).getRegex(),Te=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,vt=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,Zt=c(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,vt).getRegex(),he={_backpedal:q,anyPunctuation:Lt,anyPunctuationOutsideCode:Ct,autolink:It,blockSkip:gt,br:ye,code:lt,del:q,delLDelim:q,delRDelim:q,emStrongLDelim:kt,emStrongRDelimAst:bt,emStrongRDelimUnd:wt,escape:at,link:zt,nolink:Dt,punctuation:pt,reflink:Mt,reflinkSearch:qt,tag:Et,text:ut,url:q},Ht={...he,emStrongLDelim:xt,emStrongRDelimAst:Ot,emStrongRDelimUnd:St,link:c(/^!?\[(label)\]\((.*?)\)/).replace("label",re).getRegex(),reflink:c(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",re).getRegex()},oe={...he,emStrongRDelimAst:Rt,emStrongLDelim:ft,delLDelim:yt,delRDelim:$t,url:c(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",Zt).replace("protocol",Te).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]*?(?:(?=[\\":">",'"':""","'":"'"},Ie=a=>Gt[a];function S(a,e){if(e){if(T.escapeTest.test(a))return a.replace(T.escapeReplace,Ie)}else if(T.escapeTestNoEncode.test(a))return a.replace(T.escapeReplaceNoEncode,Ie);return a}function Ae(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 de(a){try{a=encodeURI(a).replace(T.percentDecode,"%")}catch{return null}return a}function ge(a,e){let t=a.replace(T.findPipe,(r,o,i)=>{let l=!1,p=o;for(;--p>=0&&i[p]==="\\";)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 F(a){return a.trim().replace(T.multipleSpaceGlobal," ").toLowerCase().toUpperCase().toLowerCase()}function fe(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}var N=new WeakMap;function me(a){let e={"*":-1,_:-1},t=-1,n=a.length;for(let s=0;s{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 qe(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||P}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]:ke(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=Nt(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=I(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceTabChar.test(s))&&(n=s.trim())}return{type:"heading",raw:I(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:I(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=I(t[0],` +`).split(` +`),s="",r="",o=[];for(;n.length>0;){let i=!1,l=[],p;for(p=0;pb+Y(x,b.length)).replace(this.rules.other.blockquoteSetextReplace,` + $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s} +${h}`:h,r=r?`${r} +${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=d,n.length===0)break;let k=o.at(-1);if(k?.type==="code"||k?.type==="heading"||k?.type==="hr"||k?.type==="html"||k?.type==="table")break;if(k?.type==="blockquote"){let g=k,b=n.join(` +`),x=g.raw+` +`+b.replace(this.rules.other.blockquoteSetextReplace2,""),f=this.blockquote(x);o[o.length-1]=f;let y=x.substring(f.raw.length).replace(/^\n/,""),R=y?y.split(` +`).length:0,E=R?n.slice(0,-R):n;if(E.length>0&&(s=`${s} +${E.join(` +`)}`),r=r.substring(0,r.length-g.text.length)+f.text,n=n.slice(E.length),n.length>0&&this.rules.other.blockquoteStart.test(n[0]))continue;break}else if(k?.type==="list"){let g=k,b=g.raw+` +`+n.join(` +`),x=this.list(b);o[o.length-1]=x;let f=x.raw.length>g.raw.length?b.slice(g.raw.length+1,x.raw.length).split(` +`).length:0;if(f>0){let y=n.slice(0,f).join(` +`);s=`${s} +${y}`,r=`${r} +${y}`}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),p=!1;for(;e;){let u=!1,d="";if(!(t=l.exec(e))||this.rules.block.hr.test(e))break;let k=s();e=e.substring(t[0].length);let g=t[2].split(` +`,1)[0],b=t[1].length,x=this.options.pedantic?Y(g,b):g.replace(this.rules.other.leadingSpaceTab,Z=>Y(Z,b)),f=e.split(` +`,1)[0],y=!x.trim(),R=0;if(this.options.pedantic?(R=2,d=x.trimStart()):y?R=b+1:(R=x.search(this.rules.other.nonSpaceChar),R=R>4?1:R,d=x.slice(R),R+=b),y&&this.rules.other.blankLine.test(f)&&(e=e.substring(f.length+1),u=!0),!u){let Z=this.rules.other.nextBulletRegex(R),U=this.rules.other.hrRegex(R),ee=this.rules.other.fencesBeginRegex(R),te=this.options.pedantic?this.rules.other.pedanticHeadingBeginRegex(R):this.rules.other.headingBeginRegex(R),M=this.rules.other.htmlBeginRegex(R),ne=this.rules.other.blockquoteBeginRegex(R);for(;e;){let W=e.split(` +`,1)[0],H;if(f=W,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),H=f):H=f.replace(this.rules.other.leadingSpaceTab,xe=>Y(xe)),ee.test(f)||te.test(f)||M.test(f)||ne.test(f)||Z.test(f)||U.test(f))break;if(H.search(this.rules.other.nonSpaceChar)>=R||!f.trim())d+=` +`+H.slice(R);else{if(y||x.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ee.test(x)||te.test(x)||M.test(x)||U.test(x))break;let Ze=!this.options.pedantic&&/^ {0,3}(?:=+|-+) *$/.test(f)&&this.rules.block.lheading.test(`${x} +${f}`)?` ${H.replace(/^ {0,3}/,"")}`:f;d+=` +`+Ze}y=!f.trim(),e=e.substring(W.length+1),x=H.slice(R)}}let E=n.slice(k,s());i.loose||(p?i.loose=!0:this.rules.other.doubleBlankLine.test(E)&&(p=!0)),i.items.push({type:"list_item",raw:E,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 u of i.items)if(this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]),!i.loose){let d=u.tokens.filter(g=>g.type==="space"),k=d.length>0&&d.some(g=>this.rules.other.anyLine.test(g.raw));i.loose=k}for(let u of i.items){let d=u.tokens[0];if(u.task&&(d?.type==="text"||d?.type==="paragraph")){u.text=u.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 g=this.lexer.inlineQueue.length-1;g>=0;g--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[g].src)){this.lexer.inlineQueue[g].src=this.lexer.inlineQueue[g].src.replace(this.rules.other.listReplaceTask,"");break}let k=this.rules.other.listTaskCheckbox.exec(u.raw);if(k){let g={type:"checkbox",raw:k[0]+" ",checked:k[0]!=="[ ]"};u.checked=g.checked,i.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=g.raw+u.tokens[0].raw,u.tokens[0].text=g.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(g)):u.tokens.unshift({type:"paragraph",raw:g.raw,text:g.raw,tokens:[g]}):u.tokens.unshift(g)}}else u.task&&(u.task=!1)}if(i.loose)for(let u of i.items){u.loose=!0;for(let d of u.tokens)d.type==="text"&&(d.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=ke(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])&&fe(t[2],"()")!==-1)return;let n=F(t[1]),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:I(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=ge(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:I(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[p]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:I(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&&qe(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 l=I(s.slice(0,-1),"\\");if((s.length-l.length)%2===0)return}else{let l=fe(t[2],"()");if(l===-2)return;if(l>-1){let h=(t[0].indexOf("!")===0?5:4)+t[1].length+l;t[2]=t[2].substring(0,l),t[0]=t[0].substring(0,h).trim(),t[3]=""}}let r=I(t[0].slice(0,-1),"\\");if((t[0].length-r.length)%2===0)return;let o=t[2],i="";if(this.options.pedantic){let l=this.rules.other.pedanticHrefTitle.exec(o);l&&(o=l[1],i=l[3])}else i=t[3]?t[3].slice(1,-1):"";return o=o.trim(),this.rules.other.startAngleBracket.test(o)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?o=o.slice(1):o=o.slice(1,-1)),Be(t,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.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&&qe(e,n[1],s,this.rules))return;let r=t[F(n[2]||n[1])];if(!r){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return Be(n,r,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 p=[...t.slice(Math.max(0,l-2),l)].at(-1)??"",h=p==="*"||p==="_"||!!this.rules.inline.punctuation.exec(p);lee);){if(g=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!g)continue;if(b=[...g].length,s[3]||s[4]){x+=b;continue}else if(s[5]||s[6]||R){if(o&&(s[5]||s[6]))break;if(y%3&&!((y+b)%3)){f+=b;continue}}if(x-=b,x>0)continue;b=Math.min(b,b+x+f);let te=[...s[0]][0].length,M=e.slice(0,k+s.index+te+b);if(Math.min(k,b)%2){let W=M.slice(1,-1);return{type:"em",raw:M,text:W,tokens:this.lexer.inlineTokens(W)}}let ne=M.slice(2,-2);return{type:"strong",raw:M,text:ne,tokens:this.lexer.inlineTokens(ne)}}}}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,p=o,h=this.rules.inline.delRDelim,u=De(this,t),d=t.length-e.length+o;if(uk);){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]){p+=l;continue}if(p-=l,p>0)continue;l=Math.min(l,l+p);let g=[...s[0]][0].length,b=e.slice(0,o+s.index+g+l),x=b.slice(o,-o);return{type:"del",raw:b,text:x,tokens:this.lexer.inlineTokens(x)}}}}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]:Ae(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||P,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:J.normal,inline:G.normal};this.options.pedantic?(t.block=J.pedantic,t.inline=G.pedantic):this.options.gfm&&(t.block=J.gfm,this.options.breaks?t.inline=G.breaks:t.inline=G.gfm),this.tokenizer.rules=t}static get rules(){return{block:J,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),p;this.options.extensions.startBlock.forEach(h=>{p=h.call({lexer:this},l),typeof p=="number"&&p>=0&&(i=Math.min(i,p))}),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,F(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.#n(e):e;Ee(this.tokenizer,n);try{return this.#t(e,n,t)}finally{ze(this.tokenizer)}}#t(e,t,n){let s=!1,r="",o=1/0;for(;e;){if(e.length(i=p.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.escape(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.tag(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.link(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(i.raw.length);let p=n.at(-1);i.type==="text"&&p?.type==="text"?(p.raw+=i.raw,p.text+=i.text):n.push(i);continue}if(i=this.tokenizer.emStrong(e,t,r)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.codespan(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.br(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.del(e,t,r)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.autolink(e)){e=e.substring(i.raw.length),n.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(e))){e=e.substring(i.raw.length),n.push(i);continue}let l=e;if(this.options.extensions?.startInline){let p=1/0,h=e.slice(1),u;this.options.extensions.startInline.forEach(d=>{u=d.call({lexer:this},h),typeof u=="number"&&u>=0&&(p=Math.min(p,u))}),p<1/0&&p>=0&&(l=e.substring(0,p+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 p=n.at(-1);p?.type==="text"?(p.raw+=i.raw,p.text+=i.text):n.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}#n(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,F(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 $=class{options;parser;constructor(e){this.options=e||P}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:S(r,!0))+`
+`:"
"+(n?r:S(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`${S(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?S(n,!0):this.parser.parseInline(s),i=de(e);if(i===null)return o;e=S(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=de(e);if(r===null)return S(n);e=r;let o=`${S(n)}{let i=r[o].flat(1/0);z(n,this.walkTokens(i,t))}):r.tokens&&z(n,this.walkTokens(r.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:Object.create(null),childTokens:Object.create(null)};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 $(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],p=r[i];r[i]=(...h)=>{let u=l.apply(r,h);return u===!1&&(u=p.apply(r,h)),u===!1?"":u??""}}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],p=r[i];r[i]=(...h)=>{let u=l.apply(r,h);return u===!1&&(u=p.apply(r,h)),u}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new L;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],p=r[i];L.passThroughHooks.has(o)?r[i]=h=>{if(r.options.async&&L.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await l.call(r,h);return p.call(r,d)})();let u=l.call(r,h);return p.call(r,u)}:r[i]=(...h)=>{if(r.options.async)return(async()=>{let d=await l.apply(r,h);return d===!1&&(d=await p.apply(r,h)),d})();let u=l.apply(r,h);return u===!1&&(u=p.apply(r,h)),u}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,o=n.walkTokens;s.walkTokens=function(i){let l=[];return z(l,o.call(this,i)),r&&z(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),u=o.hooks?await o.hooks.processAllTokens(h):h;o.walkTokens&&await Promise.all(this.walkTokens(u,o.walkTokens));let k=await(o.hooks?await o.hooks.provideParser(e):e?w.parse:w.parseInline)(u,o);return o.hooks?await o.hooks.postprocess(k):k})().catch(i);try{o.hooks&&(n=o.hooks.preprocess(n));let p=(o.hooks?o.hooks.provideLexer(e):e?O.lex:O.lexInline)(n,o);o.hooks&&(p=o.hooks.processAllTokens(p)),o.walkTokens&&this.walkTokens(p,o.walkTokens);let u=(o.hooks?o.hooks.provideParser(e):e?w.parse:w.parseInline)(p,o);return o.hooks&&(u=o.hooks.postprocess(u)),u}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:

    "+S(n.message+"",!0)+"
    ";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}};var v=new Q;function m(a,e){return v.parse(a,e)}m.options=m.setOptions=function(a){return v.setOptions(a),m.defaults=v.defaults,ie(m.defaults),m};m.getDefaults=D;m.defaults=P;function ve(...a){return v.use(...a),m.defaults=v.defaults,ie(m.defaults),m}m.use=ve;m.walkTokens=function(a,e){return v.walkTokens(a,e)};m.parseInline=v.parseInline;m.Parser=w;m.parser=w.parse;m.Renderer=$;m.TextRenderer=A;m.Lexer=O;m.lexer=O.lex;m.Tokenizer=_;m.Hooks=L;m.parse=m;var Ft=m.options,Qt=m.setOptions,Ut=m.walkTokens,Wt=m.parseInline,Kt=m,Xt=w.parse,Vt=O.lex; + +if(__exports != exports)module.exports = exports;return module.exports})); +//# sourceMappingURL=marked.umd.js.map diff --git a/static/vendor/purify.min.js b/static/vendor/purify.min.js new file mode 100644 index 0000000..54a70fe --- /dev/null +++ b/static/vendor/purify.min.js @@ -0,0 +1,7 @@ +/*! @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(e,t){typeof exports==`object`&&typeof module<`u`?module.exports=t():typeof define==`function`&&define.amd?define([],t):(e=typeof globalThis<`u`?globalThis:e||self,e.DOMPurify=t())})(this,function(){"use strict";function e(e,t){this.v=e,this.k=t}function t(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n`u`?null:E(BigInt.prototype.toString),ge=typeof Symbol>`u`?null:E(Symbol.prototype.toString),S=E(Object.prototype.hasOwnProperty),C=E(Object.prototype.toString),w=E(RegExp.prototype.test),T=D(TypeError);function E(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);var n=[...arguments].slice(1);return g(e,t,n)}}function D(e){return function(){return te(e,[...arguments])}}function O(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:y;if(l&&l(e,null),!v(t))return e;let r=t.length;for(;r--;){let i=t[r];if(typeof i==`string`){let e=n(i);e!==i&&(u(t)||(t[r]=e),i=e)}e[i]=!0}return e}function _e(e){for(let t=0;t/g),Pe=m(/\${[\w\W]*/g),Fe=m(/^data-[\-\w.\u00B7-\uFFFF]+$/),Ie=m(/^aria-[\-\w]+$/),Le=m(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Re=m(/^(?:\w+script|data):/i),ze=m(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Be=m(/^html$/i),Ve=m(/^[a-z][.\w]*(-[.\w]+)+$/i),He=m(/<[/\w!]/g),Ue=m(/<[/\w]/g),We=m(/<\/no(script|embed|frames)/i),Ge=m(/\/>/i),j={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Ke=p(O({},[`style`,`script`,`xmp`,`iframe`,`noembed`,`noframes`,`plaintext`,`noscript`])),qe=function(){return typeof window>`u`?null:window},Je=function(e,t){if(typeof e!=`object`||typeof e.createPolicy!=`function`)return null;let n=null,r=`data-tt-policy-suffix`;t&&t.hasAttribute(r)&&(n=t.getAttribute(r));let i=`dompurify`+(n?`#`+n:``);try{return e.createPolicy(i,{createHTML(e){return e},createScriptURL(e){return e}})}catch(e){return console.warn(`TrustedTypes policy `+i+` could not be created.`),null}},Ye=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},M=function(e,t,n,r){return S(e,t)&&v(e[t])?O(r.base?k(r.base):{},e[t],r.transform):n},Xe=function(e,t,n){let r=S(e,t)?e[t]:void 0;return r&&typeof r==`object`?k(r):n()};function Ze(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:qe(),t=e=>Ze(e);if(t.version=`3.4.17`,t.removed=[],!e||!e.document||e.document.nodeType!==j.document||!e.Element)return t.isSupported=!1,t;let n=e.document,r=n,i=r.currentScript;e.DocumentFragment;let a=e.HTMLTemplateElement,o=e.Node,s=e.Element,l=e.NodeFilter;e.NamedNodeMap===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;let u=e.DOMParser,d=e.trustedTypes,f=s.prototype,ee=A(f,`cloneNode`),g=A(f,`remove`),te=A(f,`removeAttributeNode`),he=A(f,`nextSibling`),b=A(f,`childNodes`),x=A(f,`parentNode`),ge=A(f,`shadowRoot`),C=A(f,`attributes`),E=o&&o.prototype?A(o.prototype,`nodeType`):null,D=o&&o.prototype?A(o.prototype,`nodeName`):null,_e=o&&o.prototype?A(o.prototype,`ownerDocument`):null,N=function(e){return E?E(e):e.nodeType},Qe=function(e){return D?D(e):e.nodeName},$e=ye(f,`namespaceURI`),et=function(e){return $e?$e(e):e.namespaceURI};if(typeof a==`function`){let e=n.createElement(`template`);e.content&&e.content.ownerDocument&&(n=e.content.ownerDocument)}let P,F=``,tt,nt=!1,rt=0,it=function(){if(rt>0)throw T(`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.`)},at=function(e){it(),rt++;try{return P.createHTML(e)}finally{rt--}},ot=function(e){it(),rt++;try{return P.createScriptURL(e)}finally{rt--}},st=function(){return nt||(tt=Je(d,i),nt=!0),tt},ct=n,lt=ct.implementation,ut=ct.createNodeIterator,dt=ct.createDocumentFragment,ft=ct.getElementsByTagName,pt=r.importNode,I=Ye();t.isSupported=typeof c==`function`&&typeof x==`function`&<&<.createHTMLDocument!==void 0;let mt=Me,ht=Ne,gt=Pe,_t=Fe,vt=Ie,yt=Re,bt=ze,xt=Ve,St=Le,L=null,Ct=O({},[...xe,...Se,...Ce,...Te,...De]),R=null,wt=O({},[...Oe,...ke,...Ae,...je]),z=Object.seal(h(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}})),Tt=null,Et=null,B=Object.seal(h(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}})),Dt=!0,Ot=!0,kt=!1,At=!0,V=!1,H=!0,U=!1,jt=!1,Mt=null,Nt=null,Pt=!1,W=!1,Ft=!1,It=!1,Lt=!0,Rt=!1,zt=`user-content-`,Bt=!0,Vt=!1,G=null,K={},q=null,Ht=O({},/* @__PURE__ */ `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`.split(`.`)),Ut=null,Wt=O({},[`audio`,`video`,`img`,`source`,`image`,`track`]),Gt=null,Kt=O({},[`alt`,`class`,`for`,`id`,`label`,`name`,`pattern`,`placeholder`,`role`,`summary`,`title`,`value`,`style`,`xmlns`]),qt=`http://www.w3.org/1998/Math/MathML`,Jt=`http://www.w3.org/2000/svg`,J=`http://www.w3.org/1999/xhtml`,Yt=J,Xt=!1,Zt=null,Qt=O({},[qt,Jt,J],ue),$t=p([`mi`,`mo`,`mn`,`ms`,`mtext`]),en=O({},$t),tn=p([`annotation-xml`]),nn=O({},tn),rn=O({},[`title`,`style`,`font`,`a`,`script`]),an=null,on=[`application/xhtml+xml`,`text/html`],Y=null,sn=null,cn=n.createElement(`form`),ln=function(e){return e instanceof RegExp||e instanceof Function},un=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(sn&&sn===e)return;(!e||typeof e!=`object`)&&(e={}),e=k(e),an=on.indexOf(e.PARSER_MEDIA_TYPE)===-1?`text/html`:e.PARSER_MEDIA_TYPE,Y=an===`application/xhtml+xml`?ue:y,L=M(e,`ALLOWED_TAGS`,Ct,{transform:Y}),R=M(e,`ALLOWED_ATTR`,wt,{transform:Y}),Zt=M(e,`ALLOWED_NAMESPACES`,Qt,{transform:ue}),Gt=M(e,`ADD_URI_SAFE_ATTR`,Kt,{transform:Y,base:Kt}),Ut=M(e,`ADD_DATA_URI_TAGS`,Wt,{transform:Y,base:Wt}),q=M(e,`FORBID_CONTENTS`,Ht,{transform:Y}),Tt=M(e,`FORBID_TAGS`,k({}),{transform:Y}),Et=M(e,`FORBID_ATTR`,k({}),{transform:Y}),K=S(e,`USE_PROFILES`)?e.USE_PROFILES&&typeof e.USE_PROFILES==`object`?k(e.USE_PROFILES):e.USE_PROFILES:!1,Dt=e.ALLOW_ARIA_ATTR!==!1,Ot=e.ALLOW_DATA_ATTR!==!1,kt=e.ALLOW_UNKNOWN_PROTOCOLS||!1,At=e.ALLOW_SELF_CLOSE_IN_ATTR!==!1,V=e.SAFE_FOR_TEMPLATES||!1,H=e.SAFE_FOR_XML!==!1,U=e.WHOLE_DOCUMENT||!1,W=e.RETURN_DOM||!1,Ft=e.RETURN_DOM_FRAGMENT||!1,It=e.RETURN_TRUSTED_TYPE||!1,Pt=e.FORCE_BODY||!1,Lt=e.SANITIZE_DOM!==!1,Rt=e.SANITIZE_NAMED_PROPS||!1,Bt=e.KEEP_CONTENT!==!1,Vt=e.IN_PLACE||!1,St=be(e.ALLOWED_URI_REGEXP)?e.ALLOWED_URI_REGEXP:Le,Yt=typeof e.NAMESPACE==`string`?e.NAMESPACE:J,en=Xe(e,`MATHML_TEXT_INTEGRATION_POINTS`,()=>O({},$t)),nn=Xe(e,`HTML_INTEGRATION_POINTS`,()=>O({},tn));let t=Xe(e,`CUSTOM_ELEMENT_HANDLING`,()=>h(null));if(z=h(null),S(t,`tagNameCheck`)&&ln(t.tagNameCheck)&&(z.tagNameCheck=t.tagNameCheck),S(t,`attributeNameCheck`)&&ln(t.attributeNameCheck)&&(z.attributeNameCheck=t.attributeNameCheck),S(t,`allowCustomizedBuiltInElements`)&&typeof t.allowCustomizedBuiltInElements==`boolean`&&(z.allowCustomizedBuiltInElements=t.allowCustomizedBuiltInElements),m(z),V&&(Ot=!1),Ft&&(W=!0),K&&(L=O({},De),R=h(null),K.html===!0&&(O(L,xe),O(R,Oe)),K.svg===!0&&(O(L,Se),O(R,ke),O(R,je)),K.svgFilters===!0&&(O(L,Ce),O(R,ke),O(R,je)),K.mathMl===!0&&(O(L,Te),O(R,Ae),O(R,je))),B.tagCheck=null,B.attributeCheck=null,S(e,`ADD_TAGS`)&&(typeof e.ADD_TAGS==`function`?B.tagCheck=e.ADD_TAGS:v(e.ADD_TAGS)&&(L===Ct&&(L=k(L)),O(L,e.ADD_TAGS,Y))),S(e,`ADD_ATTR`)&&(typeof e.ADD_ATTR==`function`?B.attributeCheck=e.ADD_ATTR:v(e.ADD_ATTR)&&(R===wt&&(R=k(R)),O(R,e.ADD_ATTR,Y))),S(e,`ADD_FORBID_CONTENTS`)&&v(e.ADD_FORBID_CONTENTS)&&(q===Ht&&(q=k(q)),O(q,e.ADD_FORBID_CONTENTS,Y)),Bt&&(L[`#text`]=!0),U&&O(L,[`html`,`head`,`body`]),L.table&&(O(L,[`tbody`]),delete Tt.tbody),e.TRUSTED_TYPES_POLICY){if(typeof e.TRUSTED_TYPES_POLICY.createHTML!=`function`)throw T(`TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.`);if(typeof e.TRUSTED_TYPES_POLICY.createScriptURL!=`function`)throw T(`TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.`);let t=P;P=e.TRUSTED_TYPES_POLICY;try{F=at(``)}catch(e){throw P=t,e}}else e.TRUSTED_TYPES_POLICY===null?(P=void 0,F=``):(P===void 0&&(P=st()),P&&typeof F==`string`&&(F=at(``)));p&&p(e),sn=e},dn=O({},[...Se,...Ce,...we]),fn=O({},[...Te,...Ee]),pn=function(e,t,n){return t.namespaceURI===J?e===`svg`:t.namespaceURI===qt?e===`svg`&&(n===`annotation-xml`||en[n]):!!dn[e]},mn=function(e,t,n){return t.namespaceURI===J?e===`math`:t.namespaceURI===Jt?e===`math`&&nn[n]:!!fn[e]},hn=function(e,t,n){return t.namespaceURI===Jt&&!nn[n]||t.namespaceURI===qt&&!en[n]?!1:!fn[e]&&(rn[e]||!dn[e])},gn=function(e){let t=et(e),n=y(Qe(e)),r=x(e),i,a;return r&&N(r)===j.element?(i={namespaceURI:et(r)},a=y(Qe(r))):(i={namespaceURI:Yt},a=`template`),Zt[t]?t===Jt?pn(n,i,a):t===qt?mn(n,i,a):t===J?hn(n,i,a):!!(an===`application/xhtml+xml`&&Zt[t]):!1},X=function(e){ie(t.removed,{element:e});try{x(e).removeChild(e)}catch(t){if(g(e),!x(e))throw T(`a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place`)}},_n=function(e,t,n){try{te(e,t)}catch(t){try{e.removeAttribute(n)}catch(e){}}},vn=function(e){Sn(e);let t=b(e);t&&_(ae(t),e=>{try{g(e)}catch(e){}});let n=N(e)===j.element?C(e):null;if(n)for(let t=n.length-1;t>=0;--t){let r=n[t],i=r&&r.name;typeof i==`string`&&_n(e,r,i)}},yn=function(e,n,r){if(!r)try{r=n.getAttributeNode(e)}catch(e){r=null}ie(t.removed,{attribute:r||null,from:n});try{r?te(n,r):n.removeAttribute(e)}catch(t){try{n.removeAttribute(e)}catch(e){}}if(e===`is`){if(W||Ft)try{X(n)}catch(e){}else try{n.setAttribute(e,``)}catch(e){}}},bn=function(e){let t=C(e);if(t)for(let n=t.length-1;n>=0;--n){let r=t[n],i=r&&r.name;typeof i!=`string`||R[Y(i)]||_n(e,r,i)}},xn=function(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=[e];for(;r.length>0;){let e=r.pop();if(t(e)===!1)continue;if(n&&N(e)===j.element){let t=ge(e);Z(t)&&r.push(t)}let i=b(e);if(i)for(let e=i.length-1;e>=0;--e)r.push(i[e])}},Sn=function(e){xn(e,e=>{N(e)===j.element&&bn(e)})},Cn=function(e){let t=[];return xn(e,e=>{t.push(e)},!0),t},wn=function(e,t){let n=se();_(Cn(e),e=>{N(e)===j.element&&ce(n,e)}),_(t,e=>{N(e)===j.element&&!le(n,e)&&bn(e)})},Tn=function(e,n){let r=!1;return _(t.removed,t=>{t.element&&(r=r||t.element===e,Sn(t.element))}),wn(e,n),r},En=function(e,t){let n=G,r=null,i=()=>(r||(r=se(),_(t,e=>{ce(r,e)})),r);for(let t=0;;t++){let r=Cn(e),a=[e],o=!1;if(_(r,e=>{N(e)===j.documentFragment?ie(a,e):!o&&!le(n,e)&&(o=le(i(),e))}),!o)return;if(t>=8)throw T(`the tree kept changing during in-place sanitization; refusing to return it`);_(a,(t,n)=>{Dn(t,n>0,e,i())})}},Dn=function(e,t,n,r){let i=Mn(e),a;for(;a=i.nextNode();)le(r,a)&&!le(G,a)&&(t&&Q(I.uponSanitizeShadowNode,a,null),Hn(a,n),Yn(a,n),Z(a.content)&&Xn(a.content))},On=function(e){G&&ce(G,e)},kn=function(e,t){return H?e===`patchsrc`||e===`for`&&t!==`label`&&t!==`output`:!1},An=function(e){H&&xn(e,e=>{let t=N(e);if(t===j.processingInstruction||t===j.comment&&w(Ue,e.data)){try{g(e)}catch(e){}return!1}if(t===j.element){let t=e,n=Y(Qe(e));try{t.hasAttribute&&t.hasAttribute(`patchsrc`)&&t.removeAttribute(`patchsrc`),t.hasAttribute&&t.hasAttribute(`for`)&&kn(`for`,n)&&t.removeAttribute(`for`)}catch(e){}}return!0})},jn=function(e){let t=null,r=null;if(Pt)e=``+e;else{let t=de(e,/^[\r\n\t ]+/);r=t&&t[0]}an===`application/xhtml+xml`&&Yt===J&&(e=``+e+``);let i=P?at(e):e;if(Yt===J)try{t=new u().parseFromString(i,an)}catch(e){}if(!t||!t.documentElement){t=lt.createDocument(Yt,`template`,null);try{t.documentElement.innerHTML=Xt?F:i}catch(e){}}let a=t.body||t.documentElement;return e&&r&&a.insertBefore(n.createTextNode(r),a.childNodes[0]||null),Yt===J?ft.call(t,U?`html`:`body`)[0]:U?t.documentElement:a},Mn=function(e){let t=_e?_e(e):e.ownerDocument;return ut.call(t||e,e,l.SHOW_ELEMENT|l.SHOW_COMMENT|l.SHOW_TEXT|l.SHOW_PROCESSING_INSTRUCTION|l.SHOW_CDATA_SECTION,null)},Nn=function(e){return e=fe(e,mt,` `),e=fe(e,ht,` `),e=fe(e,gt,` `),e},Pn=function(e){var t;Fn(e);let n=(t=e.querySelectorAll)==null?void 0:t.call(e,`template`);n&&_(n,e=>{Z(e.content)&&Pn(e.content)})},Fn=function(e){e.normalize();let t=_e?_e(e):e.ownerDocument,n=ut.call(t||e,e,l.SHOW_TEXT|l.SHOW_COMMENT|l.SHOW_CDATA_SECTION|l.SHOW_PROCESSING_INSTRUCTION,null),r=n.nextNode();for(;r;)r.data=Nn(r.data),r=n.nextNode()},In=function(e){let t=D?D(e):null;return typeof t!=`string`||Y(t)!==`form`?!1:typeof e.nodeName!=`string`||typeof e.textContent!=`string`||typeof e.removeChild!=`function`||e.attributes!==C(e)||typeof e.removeAttribute!=`function`||typeof e.removeAttributeNode!=`function`||typeof e.getAttributeNode!=`function`||typeof e.setAttribute!=`function`||typeof e.namespaceURI!=`string`||typeof e.insertBefore!=`function`||typeof e.hasChildNodes!=`function`||e.nodeType!==E(e)||e.childNodes!==b(e)},Z=function(e){if(!E||typeof e!=`object`||!e)return!1;try{return E(e)===j.documentFragment}catch(e){return!1}},Ln=function(e){if(!E||typeof e!=`object`||!e)return!1;try{return typeof E(e)==`number`}catch(e){return!1}};function Q(e,n,r){e.length!==0&&_(e,e=>{e.call(t,n,r,sn)})}let Rn=function(e,t){return!!(H&&e.hasChildNodes()&&!Ln(e.firstElementChild)&&w(He,e.textContent)&&w(He,e.innerHTML)||H&&Ke[t]&&N(e)===j.element&&et(e)===J&&(Ln(e.firstElementChild)||typeof e.textContent==`string`&&w(He,e.textContent))||e.nodeType===j.processingInstruction||H&&e.nodeType===j.comment&&w(Ue,e.data))},zn=function(e,t){return e instanceof RegExp?w(e,t):e instanceof Function&&!!e(t,...[...arguments].slice(2))},Bn=function(e,t,n){if(!Tt[t]&&Gn(t)&&zn(z.tagNameCheck,t))return!1;if(Bt&&!q[t]&&!q[y(t)]){let t=x(e),r=b(e);if(r&&t){let i=r.length;for(let a=i-1;a>=0;--a){let i=e===n?ee(r[a],!0):r[a];t.insertBefore(i,he(e))}}}return X(e),!0},Vn=function(e,t,n,r){return e.length===0?t:t===n||t===r?k(t):t},$=function(e,t){return e===t||x(e)!==null?!1:(Vt&&Sn(e),!0)},Hn=function(e,n){if(On(e),Q(I.beforeSanitizeElements,e,null),$(e,n))return!0;if(In(e))return X(e),!0;let r=Y(Qe(e));if(L=Vn(I.uponSanitizeElement,L,Ct,Mt),Q(I.uponSanitizeElement,e,{tagName:r,allowedTags:L}),$(e,n))return!0;if(Rn(e,r))return X(e),!0;if(Tt[r]||!(B.tagCheck instanceof Function&&B.tagCheck(r))&&!L[r]){let t=Bn(e,r,n);return t===!1&&(Q(I.afterSanitizeElements,e,null),$(e,n))?!0:t}if(N(e)===j.element&&!gn(e)||(r===`noscript`||r===`noembed`||r===`noframes`)&&w(We,e.innerHTML))return X(e),!0;if(V&&e.nodeType===j.text){let n=Nn(e.textContent);e.textContent!==n&&(ie(t.removed,{element:e.cloneNode()}),e.textContent=n)}return Q(I.afterSanitizeElements,e,null),$(e,n)},Un=function(e,t,r){if(Et[t]||kn(t,e)||Lt&&(t===`id`||t===`name`)&&(r in n||r in cn))return!1;let i=R[t]||B.attributeCheck instanceof Function&&B.attributeCheck(t,e);return Ot&&w(_t,t)||Dt&&w(vt,t)?!0:i?Gt[t]||w(St,fe(r,bt,``))||(t===`src`||t===`xlink:href`||t===`href`)&&e!==`script`&&pe(r,`data:`)===0&&Ut[e]||kt&&!w(yt,fe(r,bt,``))?!0:!r:Gn(e)&&zn(z.tagNameCheck,e)&&zn(z.attributeNameCheck,t,e)||t===`is`&&z.allowCustomizedBuiltInElements&&zn(z.tagNameCheck,r)},Wn=O({},[`annotation-xml`,`color-profile`,`font-face`,`font-face-format`,`font-face-name`,`font-face-src`,`font-face-uri`,`missing-glyph`]),Gn=function(e){return!Wn[y(e)]&&w(xt,e)},Kn=function(e,t,n,r){if(P&&typeof d==`object`&&typeof d.getAttributeType==`function`&&!n)switch(d.getAttributeType(e,t)){case`TrustedHTML`:return at(r);case`TrustedScriptURL`:return ot(r)}return r},qn=function(e,t,n,r){try{return n?e.setAttributeNS(n,t,r):e.setAttribute(t,r),!In(e)||(X(e),!1)}catch(n){return yn(t,e),!1}},Jn=function(e,t){return H&&w(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,t)?!0:y(e)===`attributename`&&de(t,`href`)!==null},Yn=function(e,n){if(Q(I.beforeSanitizeAttributes,e,null),$(e,n))return;let r=e.attributes;if(!r||In(e))return;R=Vn(I.uponSanitizeAttribute,R,wt,Nt);let i={attrName:``,attrValue:``,keepAttr:!0,allowedAttributes:R,forceKeepAttr:void 0},a=r.length,o=Y(e.nodeName);for(;a--;){let n=r[a],s=n.name,c=n.namespaceURI,l=n.value,u=Y(s),d=l,f=s===`value`?d:me(d),p=!1;i.attrName=u,i.attrValue=f,i.keepAttr=!0,i.forceKeepAttr=void 0,Q(I.uponSanitizeAttribute,e,i),f=i.attrValue,Rt&&(u===`id`||u===`name`)&&pe(f,zt)!==0&&(yn(s,e,n),f=zt+f,p=!0),Jn(s,f)?yn(s,e,n):i.forceKeepAttr||(i.keepAttr?!At&&w(Ge,f)?yn(s,e,n):(V&&(f=Nn(f)),Un(o,u,f)?(f=Kn(o,u,c,f),f!==d&&qn(e,s,c,f)&&p&&re(t.removed)):yn(s,e,n)):yn(s,e,n))}Q(I.afterSanitizeAttributes,e,null),$(e,n)},Xn=function(e){let t=null,n=Mn(e);for(Q(I.beforeSanitizeShadowDOM,e,null);t=n.nextNode();)if(Q(I.uponSanitizeShadowNode,t,null),Hn(t,e),Yn(t,e),Z(t.content)&&Xn(t.content),N(t)===j.element){let e=ge(t);Z(e)&&(Zn(e),Xn(e))}V&&Fn(e),Q(I.afterSanitizeShadowDOM,e,null)},Zn=function(e){let t=[{node:e,shadow:null}];for(;t.length>0;){let e=t.pop();if(e.shadow){Xn(e.shadow);continue}let n=e.node,r=N(n)===j.element,i=b(n);if(i)for(let e=i.length-1;e>=0;--e)t.push({node:i[e],shadow:null});if(r){let e=D?D(n):null;if(typeof e==`string`&&Y(e)===`template`){let e=n.content;Z(e)&&t.push({node:e,shadow:null})}}if(r){let e=ge(n);Z(e)&&t.push({node:null,shadow:e},{node:e,shadow:null})}}};return t.sanitize=function(e){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=null,a=null,o=null,s=null;if(Xt=!e,Xt&&(e=``),typeof e!=`string`&&!Ln(e)&&(e=ve(e),typeof e!=`string`))throw T(`dirty is not a string, aborting`);if(!t.isSupported)return e;jt?(L=Mt,R=Nt):un(n),(I.uponSanitizeElement.length>0||I.uponSanitizeAttribute.length>0)&&(L=k(L)),I.uponSanitizeAttribute.length>0&&(R=k(R)),t.removed=[];let c=Vt&&typeof e!=`string`&&Ln(e),l=[],u=G;if(c){An(e);let t=Qe(e);if(typeof t==`string`){let n=Y(t);if(!L[n]||Tt[n])throw vn(e),T(`root node is forbidden and cannot be sanitized in-place`)}if(In(e))throw vn(e),T(`root node is clobbered and cannot be sanitized in-place`);l=Cn(e),G=se()}else if(Ln(e))i=jn(``),a=i.ownerDocument.importNode(e,!0),a.nodeType===j.element&&a.nodeName===`BODY`||a.nodeName===`HTML`?i=a:i.appendChild(a),Zn(i);else{if(!W&&!V&&!U&&e.indexOf(`<`)===-1)return P&&It?at(e):e;if(i=jn(e),!i)return W?null:It?F:``}i&&Pt&&X(i.firstChild);let d=c?e:i;try{c&&Zn(e);let t=Mn(d);for(;o=t.nextNode();)Hn(o,d),Yn(o,d),Z(o.content)&&Xn(o.content);c&&En(e,l)}catch(t){throw c&&(vn(e),Tn(e,l)),t}finally{G=u}if(c){if(Tn(e,l))throw T(`a node selected for removal could not be safely returned; refusing to sanitize in place`);return V&&Pn(e),e}if(W){if(V&&Pn(i),Ft)for(s=dt.call(i.ownerDocument);i.firstChild;)s.appendChild(i.firstChild);else s=i;return(R.shadowroot||R.shadowrootmode)&&(s=pt.call(r,s,!0)),s}let f=U?i.outerHTML:i.innerHTML;return U&&L[`!doctype`]&&i.ownerDocument&&i.ownerDocument.doctype&&i.ownerDocument.doctype.name&&w(Be,i.ownerDocument.doctype.name)&&(f=` +`+f),V&&(f=Nn(f)),P&&It?at(f):f},t.setConfig=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};un(e),jt=!0,Mt=L,Nt=R},t.clearConfig=function(){sn=null,jt=!1,Mt=null,Nt=null,P=tt,F=``},t.isValidAttribute=function(e,t,n){sn||un({});let r=Y(e),i=Y(t);return typeof n==`string`&&(Jn(t,n)||!At&&w(Ge,n))?!1:Un(r,i,n)},t.addHook=function(e,t){typeof t==`function`&&S(I,e)&&ie(I[e],t)},t.removeHook=function(e,t){if(S(I,e)){if(t!==void 0){let n=ne(I[e],t);return n===-1?void 0:oe(I[e],n,1)[0]}return re(I[e])}},t.removeHooks=function(e){S(I,e)&&(I[e]=[])},t.removeAllHooks=function(){I=Ye()},t}return Ze()}); +//# sourceMappingURL=purify.min.js.map \ No newline at end of file diff --git a/tailwind.config.js b/tailwind.config.js new file mode 100644 index 0000000..857c39a --- /dev/null +++ b/tailwind.config.js @@ -0,0 +1,7 @@ +// Tailwind v3, compiled ahead of time into static/css/tailwind.css (`npm run build:css`). +// Re-run the build after adding Tailwind classes to the HTML or JS. CI fails if you forget. +module.exports = { + content: ["./static/index.html", "./static/js/**/*.js"], + theme: { extend: {} }, + plugins: [], +}; diff --git a/uv.lock b/uv.lock index f812cc8..a38774e 100644 --- a/uv.lock +++ b/uv.lock @@ -1020,7 +1020,7 @@ wheels = [ [[package]] name = "watchstock" -version = "0.3.0" +version = "0.4.0" source = { editable = "." } dependencies = [ { name = "fastapi" }, diff --git a/watchstock/__init__.py b/watchstock/__init__.py index 103e026..623aa25 100644 --- a/watchstock/__init__.py +++ b/watchstock/__init__.py @@ -1,3 +1,3 @@ """WatchStock: personal stock analysis terminal.""" -__version__ = "0.3.0" +__version__ = "0.4.0" diff --git a/watchstock/providers/yahoo.py b/watchstock/providers/yahoo.py index c1e31da..5c88570 100644 --- a/watchstock/providers/yahoo.py +++ b/watchstock/providers/yahoo.py @@ -229,7 +229,11 @@ def fetch_quotes(tickers: list[str]) -> dict[str, dict[str, Any]]: if math.isnan(price): continue change = round((price - prev) / prev * 100, 2) if prev else 0.0 - out[ticker] = {"price": round(price, 2), "change_pct": change} + try: + currency = fi.currency + except Exception: + currency = None + out[ticker] = {"price": round(price, 2), "change_pct": change, "currency": currency} return out diff --git a/watchstock/routes/personal.py b/watchstock/routes/personal.py index 37faf9b..5bd90c2 100644 --- a/watchstock/routes/personal.py +++ b/watchstock/routes/personal.py @@ -30,6 +30,7 @@ async def watchlist() -> list[dict[str, Any]]: quote = quotes.get(item["ticker"], {}) item["price"] = quote.get("price") item["change_pct"] = quote.get("change_pct") + item["currency"] = quote.get("currency") return items