diff --git a/.github/workflows/jevfish-web.yml b/.github/workflows/jevfish-web.yml new file mode 100644 index 0000000000..37a04d9848 --- /dev/null +++ b/.github/workflows/jevfish-web.yml @@ -0,0 +1,25 @@ +name: JevFish web build is committed + +on: + pull_request: + paths: ["jevfish/web/**"] + push: + branches: [main] + paths: ["jevfish/web/**"] + +jobs: + dist: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: npm ci + working-directory: jevfish/web + - run: npm run build + working-directory: jevfish/web + - name: web/dist matches the source + run: | + git status --porcelain jevfish/web/dist + test -z "$(git status --porcelain jevfish/web/dist)" diff --git a/JevFish.app/Contents/Info.plist b/JevFish.app/Contents/Info.plist new file mode 100644 index 0000000000..64c4ecfd4e --- /dev/null +++ b/JevFish.app/Contents/Info.plist @@ -0,0 +1,30 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + JevFish + CFBundleExecutable + JevFish + CFBundleIconFile + AppIcon + CFBundleIdentifier + com.markiewee.jevfish + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + JevFish + CFBundlePackageType + APPL + CFBundleShortVersionString + 0.2.0 + CFBundleVersion + 0.2.0 + LSMinimumSystemVersion + 12.0 + NSHighResolutionCapable + + + diff --git a/JevFish.app/Contents/MacOS/JevFish b/JevFish.app/Contents/MacOS/JevFish new file mode 100755 index 0000000000..ceef9ac846 --- /dev/null +++ b/JevFish.app/Contents/MacOS/JevFish @@ -0,0 +1,33 @@ +#!/bin/bash +# Finder runs this when JevFish.app is opened. The work happens in jevfish/launcher/launch.sh. +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../../.." && pwd)" +state="$HOME/Library/Application Support/JevFish" +has_launcher() { [ -f "$1/jevfish/launcher/launch.sh" ]; } + +# Moved out of its folder: use the folder from the last good start. +if ! has_launcher "$root" && [ -f "$state/repo-path" ]; then + root="$(head -n 1 "$state/repo-path")" +fi +# A downloaded copy can run from a temporary path (App Translocation). Ask Spotlight. +if ! has_launcher "$root"; then + while IFS= read -r marker; do + candidate="$(cd "$(dirname "$marker")/../.." 2>/dev/null && pwd)" + if has_launcher "$candidate"; then + root="$candidate" + break + fi + done < <(mdfind -name jevfish-folder-marker 2>/dev/null) +fi +if ! has_launcher "$root"; then + osascript -e 'display alert "JevFish cannot find its files" message "Keep JevFish.app inside the JevFish folder you downloaded and open it from there." as critical' >/dev/null 2>&1 + exit 1 +fi + +# macOS does not let an app read files in Desktop, Documents or Downloads, and gives no way +# to ask (that needs a paid Apple developer account). Terminal has the permissions the user +# granted it, so hand the same script to Terminal when the folder is out of reach. +if head -c 1 "$root/jevfish/launcher/launch.sh" >/dev/null 2>&1; then + exec /bin/bash "$root/jevfish/launcher/launch.sh" "$root" +fi +exec "${JEVFISH_OPEN_CMD:-open}" -a Terminal "$root/jevfish/launcher/launch.sh" diff --git a/JevFish.app/Contents/Resources/AppIcon.icns b/JevFish.app/Contents/Resources/AppIcon.icns new file mode 100644 index 0000000000..e81ecae0a6 Binary files /dev/null and b/JevFish.app/Contents/Resources/AppIcon.icns differ diff --git a/README.md b/README.md index d05fef685c..aa2579dad7 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ > **This fork adds JevFish.** [`jevfish/`](jevfish/) is our own rebuild of MiroFish's five-stage pipeline. TypeSafe's Jev decides every simulated person's turn; an LLM only writes the text. The graph is local, so no Zep account is needed, and the prediction is calibrated. See [jevfish/README.md](jevfish/README.md). The original MiroFish code below is kept unchanged as reference. +> +> **To run it on a Mac, double-click `JevFish.app` in this folder.** The first start installs everything it needs and opens JevFish in your browser; the app then asks for your Jev and language-model keys on screen. No terminal, no Homebrew, no Node. If macOS blocks the app because you downloaded the ZIP, open System Settings, Privacy & Security, and click Open Anyway. Keep the folder in your home folder rather than Desktop, Documents or Downloads, or JevFish starts in a Terminal window instead. Full instructions: [jevfish/README.md](jevfish/README.md).
diff --git a/jevfish/.gitignore b/jevfish/.gitignore index 4cc7026932..c422343365 100644 --- a/jevfish/.gitignore +++ b/jevfish/.gitignore @@ -4,6 +4,6 @@ data/ __pycache__/ *.pyc web/node_modules/ -web/dist/ +!web/dist/ .cache/ log/ diff --git a/jevfish/README.md b/jevfish/README.md index 5ba1647228..1969e10a13 100644 --- a/jevfish/README.md +++ b/jevfish/README.md @@ -30,18 +30,38 @@ Each simulated turn is a single Jev request containing seven typed questions: ## Run it +Double-click **JevFish.app** in this folder. Nothing else is needed: no terminal, no Homebrew, no Node. + +- The first start installs uv and the Python packages (about 1 GB) with no admin password, then opens JevFish in your browser. It took 30 seconds on a fast connection and can take a few minutes on a slow one. +- Later starts take a few seconds, and reuse a JevFish that is already running. +- It uses the first free port from 5055 to 5064. Logs are in `~/Library/Logs/JevFish/`. +- If something goes wrong, a dialog says what, with a button that opens the log. + +**Where you keep the folder matters.** macOS does not let an app read files in Desktop, Documents or Downloads, and an app can only ask for that with a paid Apple developer account. Keep the JevFish folder in your home folder, in Applications, or on another disk, and the app starts silently. From Desktop, Documents or Downloads it still works: the app hands the same start-up to Terminal, which uses the permissions you have already given it, and a Terminal window shows the progress. + +Then the app asks for two keys on its Setup screen: +- **Jev** from [console.typesafe.ai](https://console.typesafe.ai). A typical run costs about US$0.04. +- **A language model**: a free [Gemini key](https://aistudio.google.com/apikey), or any OpenAI-compatible service (address, model, key). + +"Save and check" stores them in `jevfish/.env` (readable only by you) and checks both with calls that cost nothing. There is also a **test mode** that runs every screen on deterministic fakes, so you can look around without keys. Every number it shows is made up. + +**If macOS blocks the app**, it came from a downloaded ZIP, which macOS quarantines. Open System Settings, Privacy & Security, scroll to the JevFish message and click Open Anyway. A `git clone` has no such block. + +### From the terminal + ```sh cd jevfish uv sync -cd web && npm install && npm run build && cd .. +cd web && npm install && npm run build && cd .. # only if you change the web app; the built one is committed -export TYPESAFE_API_KEY=... # console.typesafe.ai +export TYPESAFE_API_KEY=... # or set the keys in the app export GEMINI_API_KEY=... # or LLM_API_KEY + LLM_BASE_URL + LLM_MODEL for any OpenAI-compatible model uv run jevfish serve # http://127.0.0.1:5055 ``` - **Whole pipeline from the terminal:** `uv run jevfish demo` runs it on `examples/lazybee-cleaning.md`. That file uses example figures, not real Lazybee data. -- **No keys:** `JEVFISH_FAKE_JUDGE=1 JEVFISH_FAKE_LLM=1 uv run jevfish serve` runs everything on deterministic fakes, useful for trying the UI. +- **No keys:** `JEVFISH_FAKE_JUDGE=1 JEVFISH_FAKE_LLM=1 uv run jevfish serve` runs everything on deterministic fakes, the same as test mode. +- The API answers only requests addressed to this computer, and refuses changing requests sent from another website. `serve --host 0.0.0.0` turns that off and warns, which also exposes the key screen to your network. Settings: - `JEVFISH_DATA_DIR` sets where data is stored (default `jevfish/data`). diff --git a/jevfish/docs/api.md b/jevfish/docs/api.md index 0b7de24eec..79846d1451 100644 --- a/jevfish/docs/api.md +++ b/jevfish/docs/api.md @@ -11,9 +11,17 @@ type Task = { id: string; kind: "graph"|"prepare"|"run"|"report"; project_id: st ``` ## Meta -- `GET /api/health` returns `{ok, judge: "jev"|"fake"|"missing TYPESAFE_API_KEY", jev_model, llm: ""|"fake"|"missing LLM_API_KEY", llm_fallbacks: string[], llm_base_url, data_dir}`. +- `GET /api/health` returns `{ok, app: "jevfish", setup_needed, judge: "jev"|"fake"|"missing TYPESAFE_API_KEY", jev_model, llm: ""|"fake"|"missing LLM_API_KEY", llm_fallbacks: string[], llm_base_url, data_dir}`. +- **Local only:** every `/api/` request must be addressed to `127.0.0.1`, `localhost` or `::1`, and requests that change something must not come from another site's `Origin`. Anything else gets 403. `jevfish serve --host` beyond loopback turns the guard off and says so. - `GET /api/tasks/` returns a Task. `POST /api/tasks//cancel` cancels it and returns the Task. +## Setup +- `GET /api/settings` returns `{env_file, test_mode, setup_needed, typesafe_key, llm_provider: "gemini"|"openai", gemini_key, llm_key, llm_base_url, llm_model, active_tasks}`. Saved keys come back as the last four characters (`""` when the key is too short to hint at, `null` when none is saved). Full keys are never sent to the browser. +- `PUT /api/settings` saves keys and returns the same shape. Fields: `typesafe_key`, `llm_provider`, `llm_key`, `llm_base_url`, `llm_model`, `test_mode`. A blank key keeps the saved one. Writes `jevfish/.env` (mode 600) and applies at once, with no restart. Jobs already running keep the keys they started with. +- `POST /api/settings/check` checks the keys in the body, falling back to the saved ones, and returns `{jev: {ok, message}, llm: {ok, message}}`. Both checks are free: listing models for Jev and Gemini, a one-token request for other providers. +- `GET /api/example` returns `{name, requirement, seed_text}` for the example project. +- `POST /api/shutdown` stops the server, right after answering `{ok: true}`. + ## Projects ```ts type Project = { id: string; name: string; requirement: string; created_at: string; updated_at: string; diff --git a/jevfish/docs/superpowers/plans/2026-09-17-one-click-mac-app.md b/jevfish/docs/superpowers/plans/2026-09-17-one-click-mac-app.md new file mode 100644 index 0000000000..988c4cb54d --- /dev/null +++ b/jevfish/docs/superpowers/plans/2026-09-17-one-click-mac-app.md @@ -0,0 +1,1623 @@ +# JevFish One-Click Mac App Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Anyone on a Mac can start JevFish by double-clicking `JevFish.app` and do everything else, keys included, in the web app. No terminal. + +**Architecture:** `JevFish.app` is a tiny shell-script bundle at the repo root. It finds the repo and runs `jevfish/launcher/launch.sh`. That script installs uv and the Python packages if they are missing, reuses or starts the Flask server on a free port, and opens the browser. The web app gains a Setup screen that saves keys to `jevfish/.env`, checks them with free API calls, and hot-reloads the running server. The built web app is committed, so Node is not needed to run it. + +**Tech stack:** bash and osascript for the launcher; Flask blueprint, python-dotenv, typesafe-sdk and openai for setup; Vue 3 and Vite for the screen; pytest. + +**Approval:** On 17 Sep 2026 Mark said "for jev fish make it with jaust a ui and one click setup". He then picked a Mac app with no Terminal window, Macs only, and keeping the upstream code, and set the goal "build jevfish". The first JevFish build used the same pattern: a build goal counted as approval, and the PRD and PR summary went to Mark inline with the result. + +--- + +## PRD + +### Problem +Running JevFish today means opening a terminal and typing eight commands: `uv sync`, `npm install`, `npm run build`, two key exports and `uv run jevfish serve`. Keys only come from environment variables, and without them the app shows a warning with no way to fix it. Kavi and Trisha cannot start it without help, and Mark cannot start it from Finder. + +### Users +Mark, Kavi, Trisha, and anyone else on a Mac who gets the repo, either as a git clone or as the GitHub ZIP. + +### Requirements +1. **One click to start.** Double-clicking `JevFish.app` in the repo folder opens JevFish in the default browser. + - First start: installs uv if missing, into `~/Library/Application Support/JevFish/bin`, with no admin password. Then installs the Python packages, about 1 GB. Needs internet only; no Xcode, no Homebrew, no Node. + - Later starts: a few seconds. If JevFish is already running, it opens the existing server instead of starting another. + - Picks the first free port from 5055 to 5064. + - Failures show a macOS alert in plain words with a "Show log" button. Logs go to `~/Library/Logs/JevFish/`. + - Still works when the app was moved out of the folder (it remembers the repo path) and when macOS runs a downloaded copy from a temporary path (it finds the folder with Spotlight). + - **Folders macOS protects.** An app may not read Desktop, Documents or Downloads, and without a paid Apple developer account it cannot even ask (tested on macOS 26.3.2: silently denied, with an ad-hoc signature and usage strings both present). From those folders the app hands the same script to Terminal, which uses the permissions the user already granted, and the window explains why it is there. Anywhere else it starts silently. +2. **Setup in the app.** Opening the app with keys missing lands on a Setup screen. + - Jev: the TypeSafe API key. + - Language model: Gemini (key only) or any other OpenAI-compatible model (address, model name, key). + - One button, "Save and check". It saves to `jevfish/.env` (mode 600, gitignored), applies at once without a restart, and checks both keys with free calls: listing models for Jev and Gemini, and a one-token request for other providers. + - Saved keys are never sent back to the browser, only their last four characters. + - Test mode on or off (fake Jev and fake model), for trying the UI without keys. + - "Stop JevFish" shuts the server down. + - Settings stay reachable from the header. +3. **Example in the app.** "Fill in the example" on the new-prediction form loads the Lazybee example that `jevfish demo` uses. +4. **Safety.** The API only answers when the Host is the local machine, which blocks DNS rebinding. Changing requests from another website's Origin are refused. `serve --host 0.0.0.0` turns the guard off on purpose and prints a warning. +5. **No regressions.** The CLI (`serve`, `demo`), env-var configuration and all 60 existing tests keep working. + +### Out of scope +- Windows and Linux launchers. +- Code signing and notarisation. These need a paid Apple Developer account. +- Auto-update. +- A native window. It opens in the browser. +- Moving existing project data. + +### Known limits +- A copy downloaded as a ZIP is quarantined by macOS. The first open is blocked with "Apple could not verify". The user goes once to System Settings, Privacy & Security, Open Anyway. The README says so. Git clones are not affected. +- From Desktop, Documents or Downloads the start happens in a Terminal window, as above. Both are the same cause: no paid Apple developer account, and signing is out of scope. + +### Success check +- On this Mac, from a fresh local clone with an empty state folder and uv hidden from PATH, a double-click (`open JevFish.app`) installs uv and the packages, opens the Setup screen, saves real keys, both checks pass, and a test-mode project runs end to end. +- `uv run pytest -q` passes, including the new setup, env-file and launcher tests. +- Headless Chrome QA of the Setup screen at 375, 768 and 1280 wide, in light and dark, shows no console errors and no horizontal scroll. + +--- + +## File structure + +| File | Change | Responsibility | +| --- | --- | --- | +| `jevfish/src/jevfish/config.py` | modify | `env_file_path()`, health gains `app` and `setup_needed` | +| `jevfish/src/jevfish/keys.py` | create | read and write the .env file, turn the setup form into changes, check keys | +| `jevfish/src/jevfish/example.py` | create | the Lazybee example, shared by the CLI and the API | +| `jevfish/src/jevfish/setup_api.py` | create | Flask blueprint for `/api/settings`, `/api/settings/check`, `/api/example`, `/api/shutdown`; the local-only guard | +| `jevfish/src/jevfish/service.py` | modify | `Service.reload()` | +| `jevfish/src/jevfish/api.py` | modify | use `svc.settings`, register the blueprint and guard | +| `jevfish/src/jevfish/cli.py` | modify | use `example.py`, allow remote when host is not loopback | +| `jevfish/tests/test_keys.py` | create | env file and form tests, key checks with fake clients | +| `jevfish/tests/test_setup_api.py` | create | endpoint tests | +| `jevfish/tests/test_launcher.py` | create | launcher and app bundle tests with fake uv and a fake server | +| `jevfish/web/src/lib/api.js` | modify | new calls | +| `jevfish/web/src/lib/health.js` | create | shared health state | +| `jevfish/web/src/views/SetupView.vue` | create | Setup screen | +| `jevfish/web/src/router.js` | modify | `/setup` route, first-load redirect | +| `jevfish/web/src/App.vue` | modify | Settings link, banners link to setup | +| `jevfish/web/src/views/ProjectsView.vue` | modify | "Fill in the example" | +| `jevfish/web/dist/` | commit | built app | +| `jevfish/.gitignore` | modify | stop ignoring `web/dist/` | +| `jevfish/launcher/launch.sh` | create | install, start, open | +| `jevfish/launcher/jevfish-folder-marker` | create | lets Spotlight find the folder | +| `jevfish/launcher/make-icon.sh` | create | rebuilds `AppIcon.icns` from the logo | +| `JevFish.app/Contents/{Info.plist,MacOS/JevFish,Resources/AppIcon.icns}` | create | the double-click app | +| `.github/workflows/jevfish-web.yml` | create | fails when `web/dist` is stale | +| `README.md`, `jevfish/README.md`, `jevfish/docs/api.md` | modify | docs | + +--- + +### Task 1: Config, env file path and health fields + +**Files:** +- Modify: `jevfish/src/jevfish/config.py` +- Test: `jevfish/tests/test_keys.py` + +- [ ] **Step 1: Write the failing test** + +```python +# jevfish/tests/test_keys.py +from jevfish.config import env_file_path, load_settings +from tests.test_pipeline import settings + + +def test_env_file_path_follows_env(tmp_path, monkeypatch): + monkeypatch.setenv("JEVFISH_ENV_FILE", str(tmp_path / "x.env")) + assert env_file_path() == tmp_path / "x.env" + + +def test_health_reports_app_and_setup_needed(tmp_path): + ready = settings(tmp_path).health() + assert ready["app"] == "jevfish" and ready["setup_needed"] is False + missing = settings(tmp_path, fake_judge=False, fake_llm=False).health() + assert missing["setup_needed"] is True +``` + +- [ ] **Step 2: Run it and see it fail** + +Run: `cd jevfish && uv run pytest tests/test_keys.py -q` +Expected: FAIL, `ImportError: cannot import name 'env_file_path'`. + +- [ ] **Step 3: Implement** + +In `config.py`, replace `_load_env_file` with: + +```python +def env_file_path() -> Path: + """Where keys are saved: JEVFISH_ENV_FILE, else jevfish/.env.""" + return Path(os.environ.get("JEVFISH_ENV_FILE") or PACKAGE_ROOT / ".env") + + +def _load_env_file() -> None: + path = env_file_path() + if path.exists(): + from dotenv import load_dotenv + + load_dotenv(path, override=False) +``` + +and make `health()` start with: + +```python + return { + "app": "jevfish", + "setup_needed": not (self.llm_ready and self.judge_ready), + "judge": ... # unchanged from here +``` + +- [ ] **Step 4: Run it and see it pass** + +Run: `uv run pytest tests/test_keys.py -q`. Expected: 2 passed. + +- [ ] **Step 5: Commit** + +`git commit -am "feat(jevfish): env file path and setup_needed in health"` + +### Task 2: keys.py, the env file and key checks + +**Files:** +- Create: `jevfish/src/jevfish/keys.py` +- Test: `jevfish/tests/test_keys.py` (append) + +- [ ] **Step 1: Write the failing tests** + +```python +import os +import stat + +import pytest +from dotenv import dotenv_values + +from jevfish import keys +from jevfish.keys import SetupError, updates_from_form, write_env + + +def test_write_env_keeps_other_lines_and_round_trips(tmp_path): + path = tmp_path / ".env" + path.write_text("# mine\nOTHER=1\nTYPESAFE_API_KEY=old\nTYPESAFE_API_KEY=dupe\nJEVFISH_FAKE_LLM=1\n") + tricky = "k'e\\y$HOME\"x" + write_env(path, {"TYPESAFE_API_KEY": tricky, "JEVFISH_FAKE_LLM": None, "GEMINI_API_KEY": "g123"}) + text = path.read_text() + assert text.startswith("# mine\nOTHER=1\n") + assert text.count("TYPESAFE_API_KEY") == 1 and "JEVFISH_FAKE_LLM" not in text + values = dotenv_values(path) + assert values["TYPESAFE_API_KEY"] == tricky and values["GEMINI_API_KEY"] == "g123" and values["OTHER"] == "1" + assert stat.S_IMODE(os.stat(path).st_mode) == 0o600 + + +def test_write_env_rejects_newlines(tmp_path): + with pytest.raises(SetupError): + write_env(tmp_path / ".env", {"TYPESAFE_API_KEY": "a\nb"}) + + +def test_form_gemini_blank_key_keeps_saved(): + env = {"GEMINI_API_KEY": "saved"} + assert updates_from_form({"llm_provider": "gemini", "llm_key": " "}, env) == { + "LLM_API_KEY": None, "LLM_BASE_URL": None, "LLM_MODEL": None} + with pytest.raises(SetupError): + updates_from_form({"llm_provider": "gemini"}, {}) + + +def test_form_openai_needs_address_model_and_key(): + form = {"llm_provider": "openai", "llm_base_url": "https://api.openai.com/v1", "llm_model": "gpt-4o-mini", "llm_key": "sk-1"} + assert updates_from_form(form, {}) == {"LLM_BASE_URL": "https://api.openai.com/v1", "LLM_MODEL": "gpt-4o-mini", "LLM_API_KEY": "sk-1"} + for bad in ({"llm_base_url": "ftp://x"}, {"llm_model": ""}, {"llm_key": ""}): + with pytest.raises(SetupError): + updates_from_form({**form, **bad}, {}) + + +def test_form_test_mode_and_jev_key(): + assert updates_from_form({"test_mode": True, "typesafe_key": " ts "}, {}) == { + "JEVFISH_FAKE_JUDGE": "1", "JEVFISH_FAKE_LLM": "1", "TYPESAFE_API_KEY": "ts"} + assert updates_from_form({"test_mode": False}, {}) == {"JEVFISH_FAKE_JUDGE": None, "JEVFISH_FAKE_LLM": None} + with pytest.raises(SetupError): + updates_from_form({"llm_provider": "claude"}, {}) + + +def test_hint_shows_only_last_four(): + assert keys.hint(None) is None + assert keys.hint("short") == "" + assert keys.hint("abcdefghijkl1234") == "1234" + + +class _Models: + def __init__(self, result): + self.result = result + + def list(self): + if isinstance(self.result, Exception): + raise self.result + return self.result + + +def test_check_jev_maps_errors(): + from typesafe_sdk import TypeSafeAuthenticationError + + class Model: + def __init__(self, name): + self.name = name + + class Listing: + models = (Model("jev-latest"),) + + def factory(result): + class Client: + def __init__(self, **kw): + self.models = _Models(result) + + def close(self): + pass + return Client + + assert keys.check_jev("k", client_factory=factory(Listing()))["ok"] is True + assert keys.check_jev("k", "jev-9", client_factory=factory(Listing()))["ok"] is False + err = TypeSafeAuthenticationError.__new__(TypeSafeAuthenticationError) + Exception.__init__(err, "401") + bad = keys.check_jev("k", client_factory=factory(err)) + assert bad == {"ok": False, "message": "TypeSafe rejected this key."} + + +def test_check_llm_gemini_and_openai(): + import httpx + from openai import AuthenticationError, BadRequestError + + req = httpx.Request("GET", "https://x") + + def err(cls, code): + return cls("no", response=httpx.Response(code, request=req), body=None) + + class Gemini: + def __init__(self, result): + self.result = result + + def __call__(self, **kw): + self.kw = kw + self.models = _Models(self.result) + return self + + ok = keys.check_llm("gemini", "g", client_factory=Gemini([])) + assert ok["ok"] is True + assert keys.check_llm("gemini", "g", client_factory=Gemini(err(BadRequestError, 400)))["message"] == "Google rejected this key." + + class Chat: + def __init__(self, result): + self.result = result + self.completions = self + + def create(self, **kw): + self.kw = kw + if isinstance(self.result, Exception): + raise self.result + return self.result + + class Other: + def __init__(self, result): + self.chat = Chat(result) + + def __call__(self, **kw): + return self + + good = Other(object()) + assert keys.check_llm("openai", "k", "https://x/v1", "m", client_factory=good)["ok"] is True + assert good.chat.kw["max_tokens"] == 1 and good.chat.kw["model"] == "m" + assert keys.check_llm("openai", "k", "https://x/v1", "m", client_factory=Other(err(AuthenticationError, 401)))["message"] == "The provider rejected this key." +``` + +- [ ] **Step 2: Run them and see them fail** + +Run: `uv run pytest tests/test_keys.py -q`. Expected: FAIL, `ImportError: cannot import name 'keys'`. + +- [ ] **Step 3: Implement `keys.py`** + +```python +"""Keys saved from the Setup screen, and free checks that they work. + +Keys live in the .env file `config` loads (jevfish/.env unless JEVFISH_ENV_FILE says +otherwise). Saving also updates os.environ, so the running server uses them at once. +Checks cost nothing: listing models needs a valid key, and other providers get a +one-token request. +""" + +from __future__ import annotations + +import os +import re +from collections.abc import Mapping +from pathlib import Path + +from .config import GEMINI_BASE_URL + +_LINE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=") +TIMEOUT = 15 + + +class SetupError(ValueError): + pass + + +def _quote(value: str) -> str: + if "\n" in value or "\r" in value: + raise SetupError("Keys cannot contain line breaks.") + # single quotes: python-dotenv reads them literally, so $ in a key is not expanded + return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'" + + +def write_env(path: Path, updates: Mapping[str, str | None]) -> None: + """Set (str) or remove (None) keys in a .env file. Other lines stay as they were.""" + lines = path.read_text().splitlines() if path.exists() else [] + pending = dict(updates) + out: list[str] = [] + for line in lines: + m = _LINE.match(line) + if m and m.group(1) in updates: + value = pending.pop(m.group(1), None) # later duplicates find nothing and drop + if value is not None: + out.append(f"{m.group(1)}={_quote(value)}") + continue + out.append(line) + out += [f"{k}={_quote(v)}" for k, v in pending.items() if v is not None] + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + f.write("\n".join(out) + ("\n" if out else "")) + os.chmod(tmp, 0o600) + os.replace(tmp, path) + + +def apply(updates: Mapping[str, str | None]) -> None: + for key, value in updates.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + + +def hint(value: str | None) -> str | None: + """None when unset; otherwise the last four characters, or "" for short values.""" + if not value: + return None + return value[-4:] if len(value) >= 12 else "" + + +def provider(env: Mapping[str, str]) -> str: + return "openai" if env.get("LLM_API_KEY") or env.get("LLM_BASE_URL") else "gemini" + + +def text(form: Mapping, name: str) -> str: + value = form.get(name) + return value.strip() if isinstance(value, str) else "" + + +def updates_from_form(form: Mapping, env: Mapping[str, str]) -> dict[str, str | None]: + """Turn the Setup form into .env changes. A blank key field keeps the saved key.""" + updates: dict[str, str | None] = {} + if form.get("test_mode") is not None: + on = bool(form["test_mode"]) + updates["JEVFISH_FAKE_JUDGE"] = "1" if on else None + updates["JEVFISH_FAKE_LLM"] = "1" if on else None + if text(form, "typesafe_key"): + updates["TYPESAFE_API_KEY"] = text(form, "typesafe_key") + choice = form.get("llm_provider") + key = text(form, "llm_key") + if choice == "gemini": + if not (key or env.get("GEMINI_API_KEY")): + raise SetupError("Paste your Gemini API key.") + if key: + updates["GEMINI_API_KEY"] = key + updates.update(LLM_API_KEY=None, LLM_BASE_URL=None, LLM_MODEL=None) + elif choice == "openai": + base, model = text(form, "llm_base_url"), text(form, "llm_model") + if not base.startswith(("http://", "https://")): + raise SetupError("The model address must start with http:// or https://.") + if not model: + raise SetupError("Name the model to use, for example gpt-4o-mini.") + if not (key or env.get("LLM_API_KEY")): + raise SetupError("Paste the API key for this model.") + updates.update(LLM_BASE_URL=base, LLM_MODEL=model) + if key: + updates["LLM_API_KEY"] = key + elif choice is not None: + raise SetupError("llm_provider must be gemini or openai.") + return updates + + +def _short(err: Exception) -> str: + return str(err).split(" (request_id")[0][:200] + + +def check_jev(key: str, model: str = "jev-latest", client_factory=None) -> dict: + from typesafe_sdk import TypeSafeAuthenticationError, TypeSafeClient, TypeSafeError, TypeSafePermissionDeniedError + + try: + client = (client_factory or TypeSafeClient)(api_key=key, timeout=TIMEOUT) + try: + names = [m.name for m in client.models.list().models] + finally: + client.close() + except (TypeSafeAuthenticationError, TypeSafePermissionDeniedError): + return {"ok": False, "message": "TypeSafe rejected this key."} + except TypeSafeError as e: + return {"ok": False, "message": f"Could not check the key with TypeSafe: {_short(e)}"} + if model not in names: + return {"ok": False, "message": f"The key works, but {model} is not available to it."} + return {"ok": True, "message": "Jev key works."} + + +def check_llm(choice: str, key: str, base_url: str | None = None, model: str | None = None, client_factory=None) -> dict: + from openai import APIConnectionError, APIStatusError, OpenAI + + make = client_factory or OpenAI + try: + if choice == "gemini": + make(api_key=key, base_url=GEMINI_BASE_URL, timeout=TIMEOUT, max_retries=0).models.list() + else: + make(api_key=key, base_url=base_url, timeout=TIMEOUT, max_retries=0).chat.completions.create( + model=model, messages=[{"role": "user", "content": "Say OK"}], max_tokens=1) + except APIStatusError as e: + who = "Google" if choice == "gemini" else "The provider" + if e.status_code in (401, 403) or (choice == "gemini" and e.status_code == 400): + return {"ok": False, "message": f"{who} rejected this key."} + if e.status_code == 404: + return {"ok": False, "message": f"The provider has no model called {model}."} + return {"ok": False, "message": f"{who} refused the test request (HTTP {e.status_code}): {_short(e)}"} + except APIConnectionError: + return {"ok": False, "message": f"Could not reach {base_url or GEMINI_BASE_URL}."} + return {"ok": True, "message": "Gemini key works." if choice == "gemini" else f"{model} answered."} +``` + +Note: `APITimeoutError` is a subclass of `APIConnectionError`, so one `except` covers both. + +- [ ] **Step 4: Run and pass** + +Run: `uv run pytest tests/test_keys.py -q`. Expected: all pass. + +- [ ] **Step 5: Commit** + +`git add src/jevfish/keys.py tests/test_keys.py && git commit -m "feat(jevfish): save keys to .env and check them for free"` + +### Task 3: The example module and Service.reload + +**Files:** +- Create: `jevfish/src/jevfish/example.py` +- Modify: `jevfish/src/jevfish/cli.py`, `jevfish/src/jevfish/service.py` +- Test: `jevfish/tests/test_setup_api.py` (created in Task 4; the reload test goes there) + +- [ ] **Step 1: Create `example.py`** + +```python +"""The example project: made-up figures for a Singapore co-living brand.""" + +from __future__ import annotations + +from .config import PACKAGE_ROOT + +PATH = PACKAGE_ROOT / "examples" / "lazybee-cleaning.md" +NAME = "Lazybee cleaning upgrade (example)" +QUESTION = ("If Lazybee adds weekly professional cleaning for S$100 more a month (example figure), " + "will more Singapore renters book a viewing?") + + +def example() -> dict: + return {"name": NAME, "requirement": QUESTION, "seed_text": PATH.read_text()} +``` + +- [ ] **Step 2: Point `cli.py` at it** + +Replace `EXAMPLE = PACKAGE_ROOT / "examples" / "lazybee-cleaning.md"` with `from . import example`, and use `example.PATH`, `example.NAME` and `example.QUESTION` as the `demo` defaults. + +- [ ] **Step 3: Add `Service.reload`** + +In `Service.__init__`, add `self._llm_injected = llm is not None`. Then add: + +```python + def reload(self, settings: Settings) -> None: + """Use new keys from now on. Tasks already running keep what they started with. + The data folder never changes while the server runs.""" + self.settings = replace(settings, data_dir=self.settings.data_dir) + if not self._llm_injected: + self._llm = None + + def active_tasks(self) -> int: + return sum(1 for t in self.tasks.list() if t.status in ("queued", "running")) +``` + +with `from dataclasses import replace` at the top. + +- [ ] **Step 4: Run the existing suite** + +Run: `uv run pytest -q`. Expected: all pass (60 plus Task 1 and 2 tests). + +- [ ] **Step 5: Commit** + +`git commit -am "refactor(jevfish): shared example, Service.reload"` + +### Task 4: Setup API and the local-only guard + +**Files:** +- Create: `jevfish/src/jevfish/setup_api.py` +- Modify: `jevfish/src/jevfish/api.py`, `jevfish/src/jevfish/cli.py` +- Test: `jevfish/tests/test_setup_api.py` + +- [ ] **Step 1: Write the failing tests** + +```python +import os + +import pytest + +from jevfish import keys +from jevfish.api import create_app +from jevfish.llm import FakeLLM +from jevfish.service import Service +from tests.test_pipeline import settings + +MANAGED = ("TYPESAFE_API_KEY", "GEMINI_API_KEY", "LLM_API_KEY", "LLM_BASE_URL", "LLM_MODEL", "LLM_MODEL_NAME", + "JEVFISH_FAKE_JUDGE", "JEVFISH_FAKE_LLM", "JEVFISH_DATA_DIR") + + +@pytest.fixture +def env_file(tmp_path): + # saving settings edits os.environ directly, so snapshot and restore all of it + before = dict(os.environ) + for k in MANAGED: + os.environ.pop(k, None) + path = tmp_path / "keys.env" + os.environ["JEVFISH_ENV_FILE"] = str(path) + yield path + os.environ.clear() + os.environ.update(before) + + +@pytest.fixture +def app(tmp_path, env_file): + s = settings(tmp_path, fake_judge=False, fake_llm=False) + stopped = [] + app = create_app(s, Service(s, llm=FakeLLM())) + app.config["JEVFISH_STOP"] = lambda: stopped.append(True) + app.stopped = stopped + return app + + +def test_first_run_needs_setup_then_save_applies_without_restart(app, env_file, tmp_path): + c = app.test_client() + assert c.get("/api/health").get_json()["setup_needed"] is True + got = c.get("/api/settings").get_json() + assert got["typesafe_key"] is None and got["llm_provider"] == "gemini" and got["setup_needed"] is True + r = c.put("/api/settings", json={"typesafe_key": "ts-abcdefgh9999", "llm_provider": "gemini", "llm_key": "gm-abcdefgh7777"}) + assert r.status_code == 200, r.get_json() + body = r.get_json() + assert body["typesafe_key"] == "9999" and body["gemini_key"] == "7777" and body["setup_needed"] is False + assert "ts-abcdefgh9999" not in r.get_data(as_text=True) + assert "TYPESAFE_API_KEY='ts-abcdefgh9999'" in env_file.read_text() + health = c.get("/api/health").get_json() + assert health["judge"] == "jev" and health["setup_needed"] is False + assert health["data_dir"] == str(tmp_path / "data") + + +def test_test_mode_toggle(app): + c = app.test_client() + assert c.put("/api/settings", json={"test_mode": True}).get_json()["test_mode"] is True + assert c.get("/api/health").get_json()["judge"] == "fake" + assert c.put("/api/settings", json={"test_mode": False}).get_json()["test_mode"] is False + assert c.get("/api/health").get_json()["setup_needed"] is True + + +def test_bad_form_is_400(app): + r = app.test_client().put("/api/settings", json={"llm_provider": "openai", "llm_base_url": "nope"}) + assert r.status_code == 400 and "http" in r.get_json()["error"] + + +def test_check_uses_form_keys_then_saved(app, monkeypatch): + calls = [] + monkeypatch.setattr(keys, "check_jev", lambda key, model="jev-latest": calls.append(("jev", key)) or {"ok": True, "message": "j"}) + monkeypatch.setattr(keys, "check_llm", lambda choice, key, base_url=None, model=None: calls.append((choice, key)) or {"ok": False, "message": "l"}) + c = app.test_client() + r = c.post("/api/settings/check", json={"typesafe_key": "typed", "llm_provider": "gemini"}).get_json() + assert r["jev"]["ok"] is True and r["llm"] == {"ok": False, "message": "No Gemini key yet."} + assert calls == [("jev", "typed")] + monkeypatch.setenv("GEMINI_API_KEY", "saved-g") + c.post("/api/settings/check", json={}) + assert calls[-1] == ("gemini", "saved-g") + + +def test_example_and_shutdown(app): + c = app.test_client() + ex = c.get("/api/example").get_json() + assert "Lazybee" in ex["name"] and ex["seed_text"].strip() and ex["requirement"].endswith("?") + assert c.post("/api/shutdown").get_json()["ok"] is True + import time + time.sleep(0.5) + assert app.stopped == [True] + + +def test_guard_blocks_other_hosts_and_origins(app): + c = app.test_client() + assert c.get("/api/health", headers={"Host": "evil.example"}).status_code == 403 + assert c.get("/api/health", headers={"Host": "127.0.0.1:5055"}).status_code == 200 + assert c.put("/api/settings", json={"test_mode": True}, headers={"Origin": "https://evil.example"}).status_code == 403 + assert c.put("/api/settings", json={"test_mode": True}, headers={"Origin": "http://localhost:5173"}).status_code == 200 + assert c.get("/", headers={"Host": "evil.example"}).status_code == 200 # the page itself holds no data + + +def test_guard_can_be_turned_off(tmp_path, env_file): + s = settings(tmp_path) + app = create_app(s, Service(s, llm=FakeLLM()), allow_remote=True) + assert app.test_client().get("/api/health", headers={"Host": "192.168.1.9:5055"}).status_code == 200 +``` + +- [ ] **Step 2: Run and fail** + +Run: `uv run pytest tests/test_setup_api.py -q`. Expected: FAIL (404s and `allow_remote` TypeError). + +- [ ] **Step 3: Implement `setup_api.py`** + +```python +"""Setup endpoints (keys, test mode, the example, stopping) and the local-only guard.""" + +from __future__ import annotations + +import os +import signal +import threading +from urllib.parse import urlsplit + +from flask import Blueprint, current_app, jsonify, request + +from . import example, keys +from .config import env_file_path, load_settings +from .keys import SetupError + +bp = Blueprint("setup", __name__) +LOCAL_NAMES = {"127.0.0.1", "localhost", "::1"} + + +def _svc(): + return current_app.extensions["jevfish"] + + +def _form() -> dict: + data = request.get_json(silent=True) + if not isinstance(data, dict): + raise SetupError("Send the settings as JSON.") + return data + + +def is_local(netloc: str) -> bool: + return (urlsplit("//" + netloc).hostname or "") in LOCAL_NAMES + + +def guard(): + """Only this computer may use the API. Blocks DNS rebinding and other sites' forms.""" + if not request.path.startswith("/api/") or current_app.config.get("JEVFISH_ALLOW_REMOTE"): + return None + if not is_local(request.host): + return jsonify(error="JevFish only answers on this computer. Open http://127.0.0.1 instead."), 403 + origin = request.headers.get("Origin") + if request.method not in ("GET", "HEAD", "OPTIONS") and origin is not None and not is_local(urlsplit(origin).netloc): + return jsonify(error="Requests from other websites are blocked."), 403 + return None + + +@bp.errorhandler(SetupError) +def setup_error(e): + return jsonify(error=str(e)), 400 + + +@bp.get("/api/settings") +def get_settings(): + env, svc = os.environ, _svc() + s = svc.settings + return jsonify( + env_file=str(env_file_path()), + test_mode=s.fake_judge or s.fake_llm, + setup_needed=not (s.llm_ready and s.judge_ready), + typesafe_key=keys.hint(env.get("TYPESAFE_API_KEY")), + llm_provider=keys.provider(env), + gemini_key=keys.hint(env.get("GEMINI_API_KEY")), + llm_key=keys.hint(env.get("LLM_API_KEY")), + llm_base_url=env.get("LLM_BASE_URL", ""), + llm_model=env.get("LLM_MODEL", "") or env.get("LLM_MODEL_NAME", ""), + active_tasks=svc.active_tasks(), + ) + + +@bp.put("/api/settings") +def put_settings(): + updates = keys.updates_from_form(_form(), os.environ) + keys.write_env(env_file_path(), updates) + keys.apply(updates) + _svc().reload(load_settings()) + return get_settings() + + +@bp.post("/api/settings/check") +def check(): + form, env = _form(), os.environ + jev_key = keys.text(form, "typesafe_key") or env.get("TYPESAFE_API_KEY", "") + jev = keys.check_jev(jev_key, _svc().settings.jev_model) if jev_key else {"ok": False, "message": "No Jev key yet."} + choice = form.get("llm_provider") or keys.provider(env) + typed = keys.text(form, "llm_key") + if choice == "gemini": + key = typed or env.get("GEMINI_API_KEY", "") + llm = keys.check_llm("gemini", key) if key else {"ok": False, "message": "No Gemini key yet."} + else: + key = typed or env.get("LLM_API_KEY", "") + base = keys.text(form, "llm_base_url") or env.get("LLM_BASE_URL", "") + model = keys.text(form, "llm_model") or env.get("LLM_MODEL", "") + llm = keys.check_llm("openai", key, base, model) if key and base and model else { + "ok": False, "message": "Fill in the address, model and key first."} + return jsonify(jev=jev, llm=llm) + + +@bp.get("/api/example") +def get_example(): + return jsonify(example.example()) + + +def _stop_process() -> None: + os.kill(os.getpid(), signal.SIGTERM) + + +@bp.post("/api/shutdown") +def shutdown(): + stop = current_app.config.get("JEVFISH_STOP") or _stop_process + threading.Timer(0.3, stop).start() # let the response go out first + return jsonify(ok=True) +``` + +- [ ] **Step 4: Wire it into `api.py`** + +- Signature: `def create_app(settings=None, service=None, allow_remote: bool = False) -> Flask:`. +- After `app.extensions["jevfish"] = svc`, add: + - `app.config["JEVFISH_ALLOW_REMOTE"] = allow_remote` + - `app.before_request(guard)` + - `app.register_blueprint(setup_bp)` +- Import with `from .setup_api import bp as setup_bp, guard`. +- `health()` returns `jsonify(ok=True, **svc.settings.health())`. +- `estimate()` uses `svc.settings.max_requests`. + +The blueprint must be registered before the catch-all `web` route is declared. Flask matches `/api/settings` over `/` either way, because static rules win, but register first for clarity. + +- [ ] **Step 5: `cli.py` serve** + +```python + local = args.host in ("127.0.0.1", "localhost", "::1") + if not local: + print("Warning: listening beyond this computer. Anyone who can reach it can change the keys.") + app = create_app(settings, allow_remote=not local) +``` + +- [ ] **Step 6: Run and pass** + +Run: `uv run pytest -q`. Expected: all pass. + +- [ ] **Step 7: Commit** + +`git add -A src tests && git commit -m "feat(jevfish): setup API (keys, test mode, example, stop) and local-only guard"` + +### Task 5: Web app, Setup screen and example button + +**Files:** +- Create: `jevfish/web/src/lib/health.js`, `jevfish/web/src/views/SetupView.vue` +- Modify: `jevfish/web/src/lib/api.js`, `jevfish/web/src/router.js`, `jevfish/web/src/App.vue`, `jevfish/web/src/views/ProjectsView.vue` + +- [ ] **Step 1: `api.js`** + +Add to the `api` object: + +```js + settings: () => request('GET', '/settings'), + saveSettings: (body) => request('PUT', '/settings', body), + checkKeys: (body) => request('POST', '/settings/check', body), + example: () => request('GET', '/example'), + shutdown: () => request('POST', '/shutdown'), +``` + +- [ ] **Step 2: `lib/health.js`** + +```js +// One shared copy of /api/health, so the banner and the Setup screen agree. +import { ref } from 'vue' +import { api } from './api.js' + +export const health = ref(null) +export const healthError = ref('') + +export async function refreshHealth() { + try { + health.value = await api.health() + healthError.value = '' + } catch (e) { + healthError.value = e.message + } + return health.value +} +``` + +- [ ] **Step 3: `router.js`** + +- Import `SetupView`. +- Add `{ path: '/setup', name: 'setup', component: SetupView }` before the catch-all. +- Export the router, then add: + +```js +// First load only: send people without keys to Setup. +let firstLoad = true +router.beforeEach(async (to) => { + if (!firstLoad) return true + firstLoad = false + const h = await refreshHealth() + if (h && h.setup_needed && to.name !== 'setup') return { name: 'setup' } + return true +}) +``` + +- [ ] **Step 4: `App.vue`** + +- Drop the local `health`/`healthError` refs and the `onMounted` fetch. Import them from `lib/health.js`. +- Import `useRoute`, and hide the banners on the setup route: `const onSetup = computed(() => route.name === 'setup')`. +- The template banners wrapper becomes `v-if="!onSetup && (warnings.length || healthError)"`. +- Each warning gets `Open settings` after the text. +- Add `Settings` before the theme switch. +- Warning wording: "Jev is not set up yet." and "No language model is set up yet." + +- [ ] **Step 5: `SetupView.vue`** + +Complete file: + +```vue + + + + + +``` + +- [ ] **Step 6: `ProjectsView.vue`, fill in the example** + +Script: + +```js +const exampleNote = ref(false) + +async function loadExample() { + createError.value = '' + try { + const ex = await api.example() + name.value = ex.name + question.value = ex.requirement + seedText.value = ex.seed_text + showForm.value = true + exampleNote.value = true + } catch (e) { + createError.value = e.message + } +} +``` + +In the panel head, before the Hide/Show form button, add: + +```html + +``` + +At the top of the form, add: + +```html +

The example is a Singapore co-living brand with made-up figures.

+``` + +- [ ] **Step 7: Build** + +Run: `cd web && npm run build`. Expected: `built in` with no errors. + +- [ ] **Step 8: Commit** + +`git add web/src && git commit -m "feat(jevfish): Setup screen, first-run redirect, fill-in example"` + +### Task 6: Ship the built web app + +**Files:** +- Modify: `jevfish/.gitignore` +- Create: `.github/workflows/jevfish-web.yml` +- Test: `jevfish/tests/test_launcher.py` (web dist check) + +- [ ] **Step 1: `.gitignore`** + +Replace the `web/dist/` line with `!web/dist/`. That line re-includes the folder, which the repo root's `dist/` rule would otherwise ignore. + +- [ ] **Step 2: Workflow** + +```yaml +name: JevFish web build is committed + +on: + pull_request: + paths: ["jevfish/web/**"] + push: + branches: [main] + paths: ["jevfish/web/**"] + +jobs: + dist: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: npm ci + working-directory: jevfish/web + - run: npm run build + working-directory: jevfish/web + - name: web/dist matches the source + run: git status --porcelain jevfish/web/dist && test -z "$(git status --porcelain jevfish/web/dist)" +``` + +- [ ] **Step 3: Test** + +In `tests/test_launcher.py`: + +```python +import re + +from jevfish.config import PACKAGE_ROOT + + +def test_built_web_app_is_present(): + dist = PACKAGE_ROOT / "web" / "dist" + html = (dist / "index.html").read_text() + assets = re.findall(r'(?:src|href)="/(assets/[^"]+)"', html) + assert assets and all((dist / a).is_file() for a in assets) +``` + +- [ ] **Step 4: Commit** + +`git add .gitignore web/dist ../.github/workflows/jevfish-web.yml tests/test_launcher.py && git commit -m "build(jevfish): commit the built web app so no Node is needed"` + +### Task 7: Launcher script + +**Files:** +- Create: `jevfish/launcher/launch.sh` (mode 755), `jevfish/launcher/jevfish-folder-marker` +- Test: `jevfish/tests/test_launcher.py` + +- [ ] **Step 1: Write the failing tests** + +```python +import os +import signal +import socket +import subprocess +import sys +import time + +import pytest + +LAUNCH = PACKAGE_ROOT / "launcher" / "launch.sh" +mac_only = pytest.mark.skipif(sys.platform != "darwin", reason="Mac launcher") + +FAKE_SERVER = """#!{python} +import http.server, json, os, sys +port = int(sys.argv[sys.argv.index("--port") + 1]) +open({pidfile!r}, "a").write(str(os.getpid()) + "\\n") +class H(http.server.BaseHTTPRequestHandler): + def do_GET(self): + body = json.dumps({{"app": "jevfish", "ok": True}}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(body) + def log_message(self, *a): + pass +http.server.HTTPServer(("127.0.0.1", port), H).serve_forever() +""" + +FAKE_UV = """#!/bin/sh +echo "uv $*" >> "{calls}" +mkdir -p .venv/bin +cp "{server}" .venv/bin/jevfish +chmod +x .venv/bin/jevfish +""" + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +@pytest.fixture +def sandbox(tmp_path): + root = tmp_path / "repo" + jf = root / "jevfish" + (jf / "web" / "dist").mkdir(parents=True) + (jf / "web" / "dist" / "index.html").write_text("

app

") + (jf / "pyproject.toml").write_text("") + (jf / "uv.lock").write_text("") + server = tmp_path / "fake-server" + pidfile = tmp_path / "pids" + server.write_text(FAKE_SERVER.format(python=sys.executable, pidfile=str(pidfile))) + server.chmod(0o755) + calls = tmp_path / "uv-calls" + uv = tmp_path / "fake-uv" + uv.write_text(FAKE_UV.format(calls=calls, server=server)) + uv.chmod(0o755) + home = tmp_path / "home" + env = { + "HOME": str(home), "PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "JEVFISH_EXTRA_PATH": "", + "JEVFISH_NO_GUI": "1", "JEVFISH_NO_OPEN": "1", "JEVFISH_PORTS": str(free_port()), + } + box = dict(root=root, jf=jf, uv=uv, calls=calls, env=env, home=home, + state=home / "Library" / "Application Support" / "JevFish", + log=home / "Library" / "Logs" / "JevFish" / "launcher.log") + yield box + if pidfile.exists(): + for pid in pidfile.read_text().split(): + try: + os.kill(int(pid), signal.SIGTERM) + except ProcessLookupError: + pass + + +def launch(box, **extra): + return subprocess.run(["/bin/bash", str(LAUNCH), str(box["root"])], env={**box["env"], **extra}, timeout=90) + + +@mac_only +def test_first_start_installs_then_second_reuses(sandbox): + (sandbox["state"] / "bin").mkdir(parents=True) + (sandbox["state"] / "bin" / "uv").symlink_to(sandbox["uv"]) + assert launch(sandbox).returncode == 0 + log = sandbox["log"].read_text() + port = sandbox["env"]["JEVFISH_PORTS"] + assert f"ready http://127.0.0.1:{port}/" in log + assert sandbox["calls"].read_text().strip() == "uv sync --frozen" + assert (sandbox["jf"] / ".venv" / ".jevfish-synced").exists() + assert (sandbox["state"] / "repo-path").read_text().strip() == str(sandbox["root"]) + assert launch(sandbox).returncode == 0 + assert f"already running on {port}" in sandbox["log"].read_text() + assert sandbox["calls"].read_text().count("sync") == 1 + + +@mac_only +def test_installs_uv_when_missing(sandbox, tmp_path): + installer = tmp_path / "install.sh" + installer.write_text(f'#!/bin/sh\nmkdir -p "$UV_INSTALL_DIR"\ncp "{sandbox["uv"]}" "$UV_INSTALL_DIR/uv"\n') + assert launch(sandbox, JEVFISH_UV_INSTALLER=f"file://{installer}").returncode == 0 + log = sandbox["log"].read_text() + assert "Installing uv" in log and "ready http://" in log + assert (sandbox["state"] / "bin" / "uv").exists() + + +@mac_only +def test_missing_files_fail_cleanly(sandbox): + (sandbox["jf"] / "pyproject.toml").unlink() + assert launch(sandbox).returncode == 1 + assert "error: The JevFish files are missing" in sandbox["log"].read_text() +``` + +- [ ] **Step 2: Run and fail** + +Run: `uv run pytest tests/test_launcher.py -q`. Expected: the launcher tests FAIL (no `launch.sh`). + +- [ ] **Step 3: Write `launch.sh`** + +```bash +#!/bin/bash +# One-click start for JevFish on a Mac. JevFish.app runs this with the repo folder as $1. +# First start: installs uv (into ~/Library/Application Support/JevFish/bin, no admin +# password) and the Python packages. Every start: reuses a running JevFish or starts one +# on a free port, then opens it in the browser. +# +# Test hooks: JEVFISH_NO_GUI=1 logs instead of showing dialogs, JEVFISH_NO_OPEN=1 skips the +# browser, JEVFISH_UV_INSTALLER replaces the uv install script, JEVFISH_PORTS lists ports, +# JEVFISH_EXTRA_PATH replaces the usual tool folders added to PATH, JEVFISH_RETRY_SLEEP sets +# the pause between install attempts. +set -u -o pipefail + +ROOT="${1:-$(cd "$(dirname "$0")/../.." && pwd)}" +JF="$ROOT/jevfish" +STATE="${JEVFISH_HOME:-$HOME/Library/Application Support/JevFish}" +LOGS="$HOME/Library/Logs/JevFish" +LOG="$LOGS/launcher.log" +PORTS="${JEVFISH_PORTS:-5055 5056 5057 5058 5059 5060 5061 5062 5063 5064}" +# Finder starts apps with a bare PATH, so add the usual places uv lives. +export PATH="$STATE/bin:$PATH${JEVFISH_EXTRA_PATH-:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin}" + +mkdir -p "$STATE" "$LOGS" +if [ -t 1 ]; then + # Started in Terminal, because the folder is somewhere apps may not read. Say so, and + # show the progress here as well as in the log. + exec > >(tee -a "$LOG") 2>&1 + echo "JevFish is starting in this window because macOS does not let apps read files in Desktop," + echo "Documents or Downloads. Move the JevFish folder to your home folder for a window-free start." +else + exec >>"$LOG" 2>&1 +fi +echo "== $(date '+%Y-%m-%d %H:%M:%S') start from $ROOT" + +gui() { [ "${JEVFISH_NO_GUI:-}" != "1" ]; } + +tell() { # a dialog that closes itself, so setup carries on behind it + echo "note: $1" + gui && osascript -e "display dialog \"$1\" with title \"JevFish\" buttons {\"OK\"} default button \"OK\" giving up after 30" >/dev/null 2>&1 & +} + +fail() { + echo "error: $1" + if gui; then + choice=$(osascript -e "button returned of (display alert \"JevFish could not start\" message \"$1\" as critical buttons {\"Show log\", \"OK\"} default button \"OK\")" 2>/dev/null) + [ "$choice" = "Show log" ] && open -a Console "$LOG" + fi + exit 1 +} + +running_port() { # prints the port of a JevFish already running here + for p in $PORTS; do + if curl -fsS --max-time 1 "http://127.0.0.1:$p/api/health" 2>/dev/null | grep -q '"app": *"jevfish"'; then + echo "$p" + return 0 + fi + done + return 1 +} + +open_app() { + echo "ready http://127.0.0.1:$1/" + printf '%s\n' "$ROOT" >"$STATE/repo-path" + [ "${JEVFISH_NO_OPEN:-}" = "1" ] || open "http://127.0.0.1:$1/" + exit 0 +} + +[ -f "$JF/pyproject.toml" ] || fail "The JevFish files are missing from $ROOT. Download JevFish again." + +if port=$(running_port); then + echo "already running on $port" + open_app "$port" +fi + +# 1. uv, the tool that installs Python and the packages +UV="$(command -v uv || true)" +if [ -z "$UV" ]; then + tell "Installing uv, a small tool JevFish needs. This happens once." + curl -LsSf "${JEVFISH_UV_INSTALLER:-https://astral.sh/uv/install.sh}" | + env UV_INSTALL_DIR="$STATE/bin" UV_NO_MODIFY_PATH=1 sh || + fail "Could not install uv. Check the internet connection and open JevFish again." + UV="$STATE/bin/uv" + [ -x "$UV" ] || fail "uv did not install. The log has the details." +fi +echo "uv: $UV" + +# 2. Python and the packages, again only when the lock file changed +STAMP="$JF/.venv/.jevfish-synced" +if [ ! -x "$JF/.venv/bin/jevfish" ] || [ ! -f "$STAMP" ] || [ "$JF/uv.lock" -nt "$STAMP" ] || [ "$JF/pyproject.toml" -nt "$STAMP" ]; then + if [ -x "$JF/.venv/bin/jevfish" ]; then + tell "Updating JevFish. Your browser opens when it is ready." + else + tell "Setting up JevFish. The first start downloads about 1 GB and takes around 5 minutes. Your browser opens when it is ready." + fi + # About 150 downloads: retry, since uv keeps whatever finished and a blip should not end setup. + synced="" + for attempt in 1 2 3; do + if (cd "$JF" && UV_HTTP_TIMEOUT="${UV_HTTP_TIMEOUT:-120}" "$UV" sync --frozen); then + synced=1 + break + fi + echo "package install attempt $attempt failed" + sleep "${JEVFISH_RETRY_SLEEP:-5}" + done + [ -n "$synced" ] || fail "Installing the Python packages failed. Check the internet connection and open JevFish again." + touch "$STAMP" +fi + +# 3. The web app ships built. Rebuild only if someone deleted it and Node is around. +if [ ! -f "$JF/web/dist/index.html" ]; then + command -v npm >/dev/null || fail "The web app is missing from jevfish/web/dist. Download JevFish again." + (cd "$JF/web" && npm install && npm run build) || fail "Building the web app failed." +fi + +# 4. Start on the first free port and wait for it +port="" +for p in $PORTS; do + if ! nc -z 127.0.0.1 "$p" >/dev/null 2>&1; then + port="$p" + break + fi +done +[ -n "$port" ] || fail "Ports $PORTS are all in use. Close whatever is using them and open JevFish again." +echo "starting on $port" +(cd "$JF" && nohup "$JF/.venv/bin/jevfish" serve --port "$port" >>"$LOGS/server.log" 2>&1 &) +for _ in $(seq 1 240); do + if curl -fsS --max-time 1 "http://127.0.0.1:$port/api/health" 2>/dev/null | grep -q '"app": *"jevfish"'; then + open_app "$port" + fi + sleep 0.5 +done +fail "JevFish did not start within two minutes. The log has the details." +``` + +`jevfish-folder-marker` contents: `This file lets JevFish.app find this folder when macOS runs the app from a temporary copy. Keep it.` + +- [ ] **Step 4: Run and pass** + +Run: `chmod +x launcher/launch.sh && uv run pytest tests/test_launcher.py -q`. Expected: 4 passed. + +- [ ] **Step 5: Commit** + +`git add launcher tests/test_launcher.py && git commit -m "feat(jevfish): Mac launcher script"` + +### Task 8: JevFish.app bundle and icon + +**Files:** +- Create: `JevFish.app/Contents/Info.plist`, `JevFish.app/Contents/MacOS/JevFish` (755), `JevFish.app/Contents/Resources/AppIcon.icns`, `jevfish/launcher/make-icon.sh` +- Test: `jevfish/tests/test_launcher.py` (append) + +- [ ] **Step 1: Failing test** + +```python +import shutil + +APP = PACKAGE_ROOT.parent / "JevFish.app" + + +@mac_only +def test_app_bundle_is_valid_and_finds_the_repo(tmp_path): + assert subprocess.run(["plutil", "-lint", str(APP / "Contents" / "Info.plist")]).returncode == 0 + exe = APP / "Contents" / "MacOS" / "JevFish" + assert os.access(exe, os.X_OK) + assert (APP / "Contents" / "Resources" / "AppIcon.icns").stat().st_size > 10_000 + repo = tmp_path / "repo" + shutil.copytree(APP, repo / "JevFish.app", symlinks=True) + stub = repo / "jevfish" / "launcher" / "launch.sh" + stub.parent.mkdir(parents=True) + out = tmp_path / "got" + stub.write_text(f'#!/bin/bash\necho "$1" > "{out}"\n') + env = {"HOME": str(tmp_path / "home"), "PATH": "/usr/bin:/bin"} + subprocess.run([str(repo / "JevFish.app" / "Contents" / "MacOS" / "JevFish")], env=env, timeout=30, check=True) + assert out.read_text().strip() == str(repo) + # moved away from the folder: falls back to the remembered path + moved = tmp_path / "Applications" + moved.mkdir() + shutil.move(str(repo / "JevFish.app"), moved / "JevFish.app") + state = tmp_path / "home" / "Library" / "Application Support" / "JevFish" + state.mkdir(parents=True) + (state / "repo-path").write_text(f"{repo}\n") + out.unlink() + subprocess.run([str(moved / "JevFish.app" / "Contents" / "MacOS" / "JevFish")], env=env, timeout=30, check=True) + assert out.read_text().strip() == str(repo) +``` + +- [ ] **Step 2: Run and fail** + +Run: `uv run pytest tests/test_launcher.py -q -k bundle`. Expected: FAIL (no Info.plist). + +- [ ] **Step 3: Info.plist** + +```xml + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + JevFish + CFBundleExecutable + JevFish + CFBundleIconFile + AppIcon + CFBundleIdentifier + com.markiewee.jevfish + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + JevFish + CFBundlePackageType + APPL + CFBundleShortVersionString + 0.2.0 + CFBundleVersion + 0.2.0 + LSMinimumSystemVersion + 12.0 + NSHighResolutionCapable + + + +``` + +- [ ] **Step 4: `MacOS/JevFish`** + +```bash +#!/bin/bash +# Finder runs this when JevFish.app is opened. The work happens in jevfish/launcher/launch.sh. +here="$(cd "$(dirname "$0")" && pwd)" +root="$(cd "$here/../../.." && pwd)" +state="$HOME/Library/Application Support/JevFish" +has_launcher() { [ -f "$1/jevfish/launcher/launch.sh" ]; } + +# Moved out of its folder: use the folder from the last good start. +if ! has_launcher "$root" && [ -f "$state/repo-path" ]; then + root="$(head -n 1 "$state/repo-path")" +fi +# A downloaded copy can run from a temporary path (App Translocation). Ask Spotlight. +if ! has_launcher "$root"; then + while IFS= read -r marker; do + candidate="$(cd "$(dirname "$marker")/../.." 2>/dev/null && pwd)" + if has_launcher "$candidate"; then + root="$candidate" + break + fi + done < <(mdfind -name jevfish-folder-marker 2>/dev/null) +fi +if ! has_launcher "$root"; then + osascript -e 'display alert "JevFish cannot find its files" message "Keep JevFish.app inside the JevFish folder you downloaded and open it from there." as critical' >/dev/null 2>&1 + exit 1 +fi +exec /bin/bash "$root/jevfish/launcher/launch.sh" "$root" +``` + +- [ ] **Step 5: Icon** + +`launcher/make-icon.sh` writes the header logo as a 1024 px SVG (tile `#0e5a6b`, white dots, the same seven circles scaled by 32). It renders the SVG with `qlmanage -t -s 1024`, builds the iconset sizes with `sips -z`, and packs it with `iconutil -c icns` into `JevFish.app/Contents/Resources/AppIcon.icns`. If `qlmanage` output is not square or not transparent, fall back to headless Chrome `--screenshot` with a transparent background. Run it once, eyeball the PNG, commit the `.icns`. + +- [ ] **Step 6: Run and pass, commit** + +Run: `uv run pytest tests/test_launcher.py -q`. Expected: 5 passed. + +`git add ../JevFish.app launcher/make-icon.sh tests/test_launcher.py && git commit -m "feat: JevFish.app, the double-click launcher"` + +### Task 9: Docs + +- [ ] Root `README.md`: under the fork note, add "Start JevFish on a Mac": + - Download the ZIP (or clone) and double-click `JevFish.app`. + - What the first start does. + - The Open Anyway step for ZIP downloads. + - Where the logs are. +- [ ] `jevfish/README.md`: "Run it" leads with the app and the Setup screen. The terminal steps move under "From the terminal". Add a "Setup and safety" section: keys in `.env` mode 600, the local-only guard, and `--host` turning it off. +- [ ] `jevfish/docs/api.md`: + - Document `GET/PUT /api/settings`, `POST /api/settings/check`, `GET /api/example` and `POST /api/shutdown`. + - Health gains `app` and `setup_needed`. + - Add a note on the 403 guard. +- [ ] Commit `docs(jevfish): one-click start`. + +### Task 10: Verify for real + +- [ ] `uv run pytest -q`: everything passes. +- [ ] Fresh-machine run: + - Clone the branch locally into the scratchpad. + - Use a scratch `JEVFISH_HOME`, PATH without uv, and `JEVFISH_EXTRA_PATH=""`. + - Run `launch.sh` with `JEVFISH_NO_GUI=1`. + - Expect uv installed from astral.sh, `uv sync` done, the server up, `ready` in the log. Record the time. +- [ ] Real double-click path: `open JevFish.app` from the working copy. The browser opens on the Setup screen when no keys are saved. Stop the server afterwards via `POST /api/shutdown`. +- [ ] Real keys through the API: + - Save Mark's keys from `~/.chudbrain/secrets.env` into `jevfish/.env` via `PUT /api/settings`, without printing them. + - `POST /api/settings/check` returns both `ok: true`. +- [ ] Browser QA of `/setup`, `/` (with the example filled in) and the banners: + - 375, 768 and 1280 px, light and dark. + - No console errors, no horizontal scroll. + - Test mode on runs a lite project end to end. +- [ ] Open the PR (`feat/jevfish-one-click`) with the PR body below, then merge. + +--- + +## PR draft + +**Title:** JevFish: double-click Mac app and in-app setup + +**Summary** +- `JevFish.app` at the repo root. Double-click it and it installs uv and the Python packages on first start (no admin password, no Xcode, no Node), starts JevFish on a free port or reuses a running one, and opens the browser. Errors come up as a macOS alert with a "Show log" button. The package install is retried three times, because one PyPI timeout should not end setup. +- macOS does not let an app read Desktop, Documents or Downloads. From there the app hands the same script to Terminal, which explains itself in the window. Everywhere else it starts with no window at all. +- Setup screen in the app. It takes the Jev key and a Gemini or any OpenAI-compatible model, then "Save and check" writes `jevfish/.env` (mode 600) and applies it without a restart. It checks both keys with free calls. The screen also has test mode and a Stop button. First load without keys lands there. +- "Fill in the example" on the new-prediction form. +- The API now only answers requests addressed to this computer, and refuses changing requests from other websites. `serve --host` beyond loopback turns this off and warns. +- The built web app is committed, and a workflow fails if it goes stale. + +**Tests** +- `uv run pytest -q`: 84 tests, including new env-file, key-check, setup API, guard, launcher (fake uv, a fake server, a failing first install) and bundle tests. +- Fresh install on this Mac from a blank home folder with uv hidden: uv, Python 3.12 and 1 GB of packages installed and the server was up in 30 seconds. +- Real double-click both ways: silent from an unprotected folder, Terminal handover from the Desktop copy. +- Real keys saved and checked through the new API, wrong keys rejected, `.env` written mode 600. +- A real prediction on the fresh install: 108 Jev requests, US$0.0052, about two minutes on OASIS Reddit. +- Browser QA at 375, 768 and 1280 in light and dark: 19 checks, no console errors, no sideways scroll. + +**Known limit:** ZIP downloads are quarantined by macOS, so the first open needs Privacy & Security, Open Anyway. Signing would need a paid Apple account. diff --git a/jevfish/launcher/jevfish-folder-marker b/jevfish/launcher/jevfish-folder-marker new file mode 100644 index 0000000000..8b12d891e7 --- /dev/null +++ b/jevfish/launcher/jevfish-folder-marker @@ -0,0 +1 @@ +This file lets JevFish.app find this folder when macOS runs the app from a temporary copy. Keep it. diff --git a/jevfish/launcher/launch.sh b/jevfish/launcher/launch.sh new file mode 100755 index 0000000000..2f69f7f828 --- /dev/null +++ b/jevfish/launcher/launch.sh @@ -0,0 +1,131 @@ +#!/bin/bash +# One-click start for JevFish on a Mac. JevFish.app runs this with the repo folder as $1. +# First start: installs uv (into ~/Library/Application Support/JevFish/bin, no admin +# password) and the Python packages. Every start: reuses a running JevFish or starts one +# on a free port, then opens it in the browser. +# +# Test hooks: JEVFISH_NO_GUI=1 logs instead of showing dialogs, JEVFISH_NO_OPEN=1 skips the +# browser, JEVFISH_UV_INSTALLER replaces the uv install script, JEVFISH_PORTS lists ports, +# JEVFISH_EXTRA_PATH replaces the usual tool folders added to PATH, JEVFISH_RETRY_SLEEP sets +# the pause between install attempts. +set -u -o pipefail + +ROOT="${1:-$(cd "$(dirname "$0")/../.." && pwd)}" +JF="$ROOT/jevfish" +STATE="${JEVFISH_HOME:-$HOME/Library/Application Support/JevFish}" +LOGS="$HOME/Library/Logs/JevFish" +LOG="$LOGS/launcher.log" +PORTS="${JEVFISH_PORTS:-5055 5056 5057 5058 5059 5060 5061 5062 5063 5064}" +# Finder starts apps with a bare PATH, so add the usual places uv lives. +export PATH="$STATE/bin:$PATH${JEVFISH_EXTRA_PATH-:$HOME/.local/bin:/opt/homebrew/bin:/usr/local/bin}" + +mkdir -p "$STATE" "$LOGS" +if [ -t 1 ]; then + # Started in Terminal, because the folder is somewhere apps may not read. Say so, and + # show the progress here as well as in the log. + exec > >(tee -a "$LOG") 2>&1 + echo "JevFish is starting in this window because macOS does not let apps read files in Desktop," + echo "Documents or Downloads. Move the JevFish folder to your home folder for a window-free start." +else + exec >>"$LOG" 2>&1 +fi +echo "== $(date '+%Y-%m-%d %H:%M:%S') start from $ROOT" + +gui() { [ "${JEVFISH_NO_GUI:-}" != "1" ]; } + +tell() { # a dialog that closes itself, so setup carries on behind it + echo "note: $1" + gui && osascript -e "display dialog \"$1\" with title \"JevFish\" buttons {\"OK\"} default button \"OK\" giving up after 30" >/dev/null 2>&1 & +} + +fail() { + echo "error: $1" + if gui; then + choice=$(osascript -e "button returned of (display alert \"JevFish could not start\" message \"$1\" as critical buttons {\"Show log\", \"OK\"} default button \"OK\")" 2>/dev/null) + [ "$choice" = "Show log" ] && open -a Console "$LOG" + fi + exit 1 +} + +running_port() { # prints the port of a JevFish already running here + for p in $PORTS; do + if curl -fsS --max-time 1 "http://127.0.0.1:$p/api/health" 2>/dev/null | grep -q '"app": *"jevfish"'; then + echo "$p" + return 0 + fi + done + return 1 +} + +open_app() { + echo "ready http://127.0.0.1:$1/" + printf '%s\n' "$ROOT" >"$STATE/repo-path" + [ "${JEVFISH_NO_OPEN:-}" = "1" ] || open "http://127.0.0.1:$1/" + exit 0 +} + +[ -f "$JF/pyproject.toml" ] || fail "The JevFish files are missing from $ROOT. Download JevFish again." + +if port=$(running_port); then + echo "already running on $port" + open_app "$port" +fi + +# 1. uv, the tool that installs Python and the packages +UV="$(command -v uv || true)" +if [ -z "$UV" ]; then + tell "Installing uv, a small tool JevFish needs. This happens once." + curl -LsSf "${JEVFISH_UV_INSTALLER:-https://astral.sh/uv/install.sh}" | + env UV_INSTALL_DIR="$STATE/bin" UV_NO_MODIFY_PATH=1 sh || + fail "Could not install uv. Check the internet connection and open JevFish again." + UV="$STATE/bin/uv" + [ -x "$UV" ] || fail "uv did not install. The log has the details." +fi +echo "uv: $UV" + +# 2. Python and the packages, again only when the lock file changed +STAMP="$JF/.venv/.jevfish-synced" +if [ ! -x "$JF/.venv/bin/jevfish" ] || [ ! -f "$STAMP" ] || [ "$JF/uv.lock" -nt "$STAMP" ] || [ "$JF/pyproject.toml" -nt "$STAMP" ]; then + if [ -x "$JF/.venv/bin/jevfish" ]; then + tell "Updating JevFish. Your browser opens when it is ready." + else + tell "Setting up JevFish. The first start downloads about 1 GB and takes around 5 minutes. Your browser opens when it is ready." + fi + # About 150 downloads: retry, since uv keeps whatever finished and a blip should not end setup. + synced="" + for attempt in 1 2 3; do + if (cd "$JF" && UV_HTTP_TIMEOUT="${UV_HTTP_TIMEOUT:-120}" "$UV" sync --frozen); then + synced=1 + break + fi + echo "package install attempt $attempt failed" + sleep "${JEVFISH_RETRY_SLEEP:-5}" + done + [ -n "$synced" ] || fail "Installing the Python packages failed. Check the internet connection and open JevFish again." + touch "$STAMP" +fi + +# 3. The web app ships built. Rebuild only if someone deleted it and Node is around. +if [ ! -f "$JF/web/dist/index.html" ]; then + command -v npm >/dev/null || fail "The web app is missing from jevfish/web/dist. Download JevFish again." + (cd "$JF/web" && npm install && npm run build) || fail "Building the web app failed." +fi + +# 4. Start on the first free port and wait for it +port="" +for p in $PORTS; do + if ! nc -z 127.0.0.1 "$p" >/dev/null 2>&1; then + port="$p" + break + fi +done +[ -n "$port" ] || fail "Ports $PORTS are all in use. Close whatever is using them and open JevFish again." +echo "starting on $port" +(cd "$JF" && nohup "$JF/.venv/bin/jevfish" serve --port "$port" >>"$LOGS/server.log" 2>&1 &) +for _ in $(seq 1 240); do + if curl -fsS --max-time 1 "http://127.0.0.1:$port/api/health" 2>/dev/null | grep -q '"app": *"jevfish"'; then + open_app "$port" + fi + sleep 0.5 +done +fail "JevFish did not start within two minutes. The log has the details." diff --git a/jevfish/launcher/make-icon.sh b/jevfish/launcher/make-icon.sh new file mode 100755 index 0000000000..c1b7de1e06 --- /dev/null +++ b/jevfish/launcher/make-icon.sh @@ -0,0 +1,30 @@ +#!/bin/bash +# Rebuilds JevFish.app/Contents/Resources/AppIcon.icns from the header logo. +# Needs only macOS tools: Quick Look renders the SVG, sips resizes, iconutil packs. +set -euo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +out="$here/../../JevFish.app/Contents/Resources/AppIcon.icns" +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +# Apple's grid: an 824 px tile on a 1024 px canvas. Dots shifted 1 unit right to sit centred. +cat >"$work/icon.svg" <<'SVG' + + + + + + + + +SVG +qlmanage -t -s 1024 -o "$work" "$work/icon.svg" >/dev/null +mkdir "$work/AppIcon.iconset" +for size in 16 32 128 256 512; do + sips -z "$size" "$size" "$work/icon.svg.png" --out "$work/AppIcon.iconset/icon_${size}x${size}.png" >/dev/null + double=$((size * 2)) + sips -z "$double" "$double" "$work/icon.svg.png" --out "$work/AppIcon.iconset/icon_${size}x${size}@2x.png" >/dev/null +done +iconutil -c icns "$work/AppIcon.iconset" -o "$out" +cp "$work/icon.svg.png" "${JEVFISH_ICON_PREVIEW:-/dev/null}" 2>/dev/null || true +echo "wrote $out" diff --git a/jevfish/pyproject.toml b/jevfish/pyproject.toml index 220b1cd056..e2b05c7269 100644 --- a/jevfish/pyproject.toml +++ b/jevfish/pyproject.toml @@ -18,7 +18,7 @@ dependencies = [ ] [build-system] -requires = ["uv_build>=0.11.21,<0.12.0"] +requires = ["uv_build>=0.11.21,<0.13.0"] build-backend = "uv_build" [dependency-groups] diff --git a/jevfish/src/jevfish/api.py b/jevfish/src/jevfish/api.py index 8cd605d796..ae00510bf1 100644 --- a/jevfish/src/jevfish/api.py +++ b/jevfish/src/jevfish/api.py @@ -12,6 +12,8 @@ from .judge import JudgeUnavailable from .llm import LLMError from .service import PipelineError, Service +from .setup_api import bp as setup_bp +from .setup_api import guard from .simulate import RunConfig, RunConfigError, planned_requests from .store import NotFound @@ -20,12 +22,16 @@ PRICE_PER_M_INPUT = 0.042 -def create_app(settings: Settings | None = None, service: Service | None = None) -> Flask: +def create_app(settings: Settings | None = None, service: Service | None = None, allow_remote: bool = False) -> Flask: + """allow_remote turns off the local-only guard; only for `serve --host` beyond loopback.""" settings = settings or load_settings() svc = service or Service(settings) app = Flask(__name__, static_folder=None) app.config["MAX_CONTENT_LENGTH"] = 25 * 1024 * 1024 + app.config["JEVFISH_ALLOW_REMOTE"] = allow_remote app.extensions["jevfish"] = svc + app.before_request(guard) + app.register_blueprint(setup_bp) def body() -> dict: data = request.get_json(silent=True) @@ -65,7 +71,7 @@ def http_error(e): # -- meta ------------------------------------------------------------ @app.get("/api/health") def health(): - return jsonify(ok=True, **settings.health()) + return jsonify(ok=True, **svc.settings.health()) @app.get("/api/tasks/") def task(tid): @@ -169,7 +175,7 @@ def estimate(pid): planned = planned_requests(svc.frame(pid), svc.crowd(pid), cfg) return jsonify( planned_requests=planned, - cap=cfg.max_requests or settings.max_requests, + cap=cfg.max_requests or svc.settings.max_requests, est_input_tokens=planned * TOKENS_PER_REQUEST, est_cost_usd=round(planned * TOKENS_PER_REQUEST / 1_000_000 * PRICE_PER_M_INPUT, 4), polls=cfg.polls(), diff --git a/jevfish/src/jevfish/cli.py b/jevfish/src/jevfish/cli.py index dd94ee2281..7654d51451 100644 --- a/jevfish/src/jevfish/cli.py +++ b/jevfish/src/jevfish/cli.py @@ -7,9 +7,8 @@ import time from pathlib import Path -from .config import PACKAGE_ROOT, load_settings - -EXAMPLE = PACKAGE_ROOT / "examples" / "lazybee-cleaning.md" +from . import example +from .config import load_settings def cmd_serve(args) -> int: @@ -17,7 +16,10 @@ def cmd_serve(args) -> int: settings = load_settings() print("JevFish settings:", settings.health()) - app = create_app(settings) + local = args.host in ("127.0.0.1", "localhost", "::1") + if not local: + print("Warning: listening beyond this computer. Anyone who can reach it can change the keys.") + app = create_app(settings, allow_remote=not local) print(f"Open http://{args.host}:{args.port}") app.run(host=args.host, port=args.port, threaded=True, debug=False) return 0 @@ -75,9 +77,9 @@ def main(argv: list[str] | None = None) -> int: serve.add_argument("--port", type=int, default=5055) serve.set_defaults(func=cmd_serve) demo = sub.add_parser("demo", help="run graph, prepare, simulate and report on a seed document") - demo.add_argument("--seed", default=str(EXAMPLE)) - demo.add_argument("--name", default="Lazybee cleaning upgrade (example)") - demo.add_argument("--question", default="If Lazybee adds weekly professional cleaning for S$100 more a month (example figure), will more Singapore renters book a viewing?") + demo.add_argument("--seed", default=str(example.PATH)) + demo.add_argument("--name", default=example.NAME) + demo.add_argument("--question", default=example.QUESTION) demo.add_argument("--platform", default="reddit", choices=["reddit", "twitter", "lite"]) demo.add_argument("--rounds", type=int, default=6) demo.add_argument("--public", type=int, default=40) diff --git a/jevfish/src/jevfish/config.py b/jevfish/src/jevfish/config.py index eb18b9b3d8..f2f4d2c4b0 100644 --- a/jevfish/src/jevfish/config.py +++ b/jevfish/src/jevfish/config.py @@ -23,9 +23,14 @@ def _flag(name: str) -> bool: return os.environ.get(name, "").strip().lower() in {"1", "true", "yes"} +def env_file_path() -> Path: + """Where keys are saved: JEVFISH_ENV_FILE, else jevfish/.env.""" + return Path(os.environ.get("JEVFISH_ENV_FILE") or PACKAGE_ROOT / ".env") + + def _load_env_file() -> None: - path = os.environ.get("JEVFISH_ENV_FILE") or str(PACKAGE_ROOT / ".env") - if Path(path).exists(): + path = env_file_path() + if path.exists(): from dotenv import load_dotenv load_dotenv(path, override=False) @@ -55,6 +60,8 @@ def judge_ready(self) -> bool: def health(self) -> dict: return { + "app": "jevfish", + "setup_needed": not (self.llm_ready and self.judge_ready), "judge": "fake" if self.fake_judge else ("jev" if self.typesafe_key else "missing TYPESAFE_API_KEY"), "jev_model": self.jev_model, "llm": "fake" if self.fake_llm else (self.llm_models[0] if self.llm_api_key else "missing LLM_API_KEY"), diff --git a/jevfish/src/jevfish/example.py b/jevfish/src/jevfish/example.py new file mode 100644 index 0000000000..52444152ac --- /dev/null +++ b/jevfish/src/jevfish/example.py @@ -0,0 +1,14 @@ +"""The example project: made-up figures for a Singapore co-living brand.""" + +from __future__ import annotations + +from .config import PACKAGE_ROOT + +PATH = PACKAGE_ROOT / "examples" / "lazybee-cleaning.md" +NAME = "Lazybee cleaning upgrade (example)" +QUESTION = ("If Lazybee adds weekly professional cleaning for S$100 more a month (example figure), " + "will more Singapore renters book a viewing?") + + +def example() -> dict: + return {"name": NAME, "requirement": QUESTION, "seed_text": PATH.read_text()} diff --git a/jevfish/src/jevfish/keys.py b/jevfish/src/jevfish/keys.py new file mode 100644 index 0000000000..774e9b06fb --- /dev/null +++ b/jevfish/src/jevfish/keys.py @@ -0,0 +1,154 @@ +"""Keys saved from the Setup screen, and free checks that they work. + +Keys live in the .env file `config` loads (jevfish/.env unless JEVFISH_ENV_FILE says +otherwise). Saving also updates os.environ, so the running server uses them at once. +Checks cost nothing: listing models needs a valid key, and other providers get a +one-token request. +""" + +from __future__ import annotations + +import os +import re +from collections.abc import Mapping +from pathlib import Path + +from .config import GEMINI_BASE_URL + +_LINE = re.compile(r"^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=") +TIMEOUT = 15 + + +class SetupError(ValueError): + pass + + +def _quote(value: str) -> str: + if "\n" in value or "\r" in value: + raise SetupError("Keys cannot contain line breaks.") + # single quotes: python-dotenv reads them literally, so $ in a key is not expanded + return "'" + value.replace("\\", "\\\\").replace("'", "\\'") + "'" + + +def write_env(path: Path, updates: Mapping[str, str | None]) -> None: + """Set (str) or remove (None) keys in a .env file. Other lines stay as they were.""" + lines = path.read_text().splitlines() if path.exists() else [] + pending = dict(updates) + out: list[str] = [] + for line in lines: + m = _LINE.match(line) + if m and m.group(1) in updates: + value = pending.pop(m.group(1), None) # later duplicates find nothing and drop + if value is not None: + out.append(f"{m.group(1)}={_quote(value)}") + continue + out.append(line) + out += [f"{k}={_quote(v)}" for k, v in pending.items() if v is not None] + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_name(path.name + ".tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + f.write("\n".join(out) + ("\n" if out else "")) + os.chmod(tmp, 0o600) + os.replace(tmp, path) + + +def apply(updates: Mapping[str, str | None]) -> None: + for key, value in updates.items(): + if value is None: + os.environ.pop(key, None) + else: + os.environ[key] = value + + +def hint(value: str | None) -> str | None: + """None when unset; otherwise the last four characters, or "" for short values.""" + if not value: + return None + return value[-4:] if len(value) >= 12 else "" + + +def provider(env: Mapping[str, str]) -> str: + return "openai" if env.get("LLM_API_KEY") or env.get("LLM_BASE_URL") else "gemini" + + +def text(form: Mapping, name: str) -> str: + value = form.get(name) + return value.strip() if isinstance(value, str) else "" + + +def updates_from_form(form: Mapping, env: Mapping[str, str]) -> dict[str, str | None]: + """Turn the Setup form into .env changes. A blank key field keeps the saved key.""" + updates: dict[str, str | None] = {} + if form.get("test_mode") is not None: + on = bool(form["test_mode"]) + updates["JEVFISH_FAKE_JUDGE"] = "1" if on else None + updates["JEVFISH_FAKE_LLM"] = "1" if on else None + if text(form, "typesafe_key"): + updates["TYPESAFE_API_KEY"] = text(form, "typesafe_key") + choice = form.get("llm_provider") + key = text(form, "llm_key") + if choice == "gemini": + if not (key or env.get("GEMINI_API_KEY")): + raise SetupError("Paste your Gemini API key.") + if key: + updates["GEMINI_API_KEY"] = key + updates.update(LLM_API_KEY=None, LLM_BASE_URL=None, LLM_MODEL=None) + elif choice == "openai": + base, model = text(form, "llm_base_url"), text(form, "llm_model") + if not base.startswith(("http://", "https://")): + raise SetupError("The model address must start with http:// or https://.") + if not model: + raise SetupError("Name the model to use, for example gpt-4o-mini.") + if not (key or env.get("LLM_API_KEY")): + raise SetupError("Paste the API key for this model.") + updates.update(LLM_BASE_URL=base, LLM_MODEL=model) + if key: + updates["LLM_API_KEY"] = key + elif choice is not None: + raise SetupError("llm_provider must be gemini or openai.") + return updates + + +def _short(err: Exception) -> str: + return str(err).split(" (request_id")[0][:200] + + +def check_jev(key: str, model: str = "jev-latest", client_factory=None) -> dict: + from typesafe_sdk import TypeSafeAuthenticationError, TypeSafeClient, TypeSafeError, TypeSafePermissionDeniedError + + try: + client = (client_factory or TypeSafeClient)(api_key=key, timeout=TIMEOUT) + try: + names = [m.name for m in client.models.list().models] + finally: + client.close() + except (TypeSafeAuthenticationError, TypeSafePermissionDeniedError): + return {"ok": False, "message": "TypeSafe rejected this key."} + except TypeSafeError as e: + return {"ok": False, "message": f"Could not check the key with TypeSafe: {_short(e)}"} + if model not in names: + return {"ok": False, "message": f"The key works, but {model} is not available to it."} + return {"ok": True, "message": "Jev key works."} + + +def check_llm(choice: str, key: str, base_url: str | None = None, model: str | None = None, client_factory=None) -> dict: + from openai import APIConnectionError, APIStatusError, OpenAI + + make = client_factory or OpenAI + try: + if choice == "gemini": + make(api_key=key, base_url=GEMINI_BASE_URL, timeout=TIMEOUT, max_retries=0).models.list() + else: + make(api_key=key, base_url=base_url, timeout=TIMEOUT, max_retries=0).chat.completions.create( + model=model, messages=[{"role": "user", "content": "Say OK"}], max_tokens=1) + except APIStatusError as e: + who = "Google" if choice == "gemini" else "The provider" + if e.status_code in (401, 403) or (choice == "gemini" and e.status_code == 400): + return {"ok": False, "message": f"{who} rejected this key."} + if e.status_code == 404: + return {"ok": False, "message": f"The provider has no model called {model}."} + return {"ok": False, "message": f"{who} refused the test request (HTTP {e.status_code}): {_short(e)}"} + except APIConnectionError: # includes timeouts + return {"ok": False, "message": f"Could not reach {base_url or GEMINI_BASE_URL}."} + return {"ok": True, "message": "Gemini key works." if choice == "gemini" else f"{model} answered."} diff --git a/jevfish/src/jevfish/service.py b/jevfish/src/jevfish/service.py index ea3a6dd12d..40238c20b1 100644 --- a/jevfish/src/jevfish/service.py +++ b/jevfish/src/jevfish/service.py @@ -2,6 +2,7 @@ from __future__ import annotations +from dataclasses import replace from pathlib import Path from . import interact @@ -27,8 +28,19 @@ def __init__(self, settings: Settings, store: Store | None = None, llm: LLM | No self.settings = settings self.store = store or Store(settings.data_dir) self._llm = llm + self._llm_injected = llm is not None self.tasks = tasks or TaskManager() + def reload(self, settings: Settings) -> None: + """Use new keys from now on. Tasks already running keep what they started with. + The data folder never changes while the server runs.""" + self.settings = replace(settings, data_dir=self.settings.data_dir) + if not self._llm_injected: + self._llm = None + + def active_tasks(self) -> int: + return sum(1 for t in self.tasks.list() if t.status in ("queued", "running")) + @property def llm(self) -> LLM: if self._llm is None: diff --git a/jevfish/src/jevfish/setup_api.py b/jevfish/src/jevfish/setup_api.py new file mode 100644 index 0000000000..dd8511735b --- /dev/null +++ b/jevfish/src/jevfish/setup_api.py @@ -0,0 +1,121 @@ +"""Setup endpoints (keys, test mode, the example, stopping) and the local-only guard.""" + +from __future__ import annotations + +import os +import signal +import threading +from urllib.parse import urlsplit + +from flask import Blueprint, current_app, jsonify, request + +from . import example, keys +from .config import env_file_path, load_settings +from .keys import SetupError + +bp = Blueprint("setup", __name__) +LOCAL_NAMES = {"127.0.0.1", "localhost", "::1"} + + +def _svc(): + return current_app.extensions["jevfish"] + + +def _form() -> dict: + data = request.get_json(silent=True) + if not isinstance(data, dict): + raise SetupError("Send the settings as JSON.") + return data + + +def is_local(netloc: str) -> bool: + try: + return (urlsplit("//" + netloc).hostname or "") in LOCAL_NAMES + except ValueError: + return False + + +def _origin_is_local(origin: str) -> bool: + try: + return is_local(urlsplit(origin).netloc) + except ValueError: + return False + + +def guard(): + """Only this computer may use the API. Blocks DNS rebinding and other sites' forms.""" + if not request.path.startswith("/api/") or current_app.config.get("JEVFISH_ALLOW_REMOTE"): + return None + if not is_local(request.host): + return jsonify(error="JevFish only answers on this computer. Open http://127.0.0.1 instead."), 403 + origin = request.headers.get("Origin") + if request.method not in ("GET", "HEAD", "OPTIONS") and origin is not None and not _origin_is_local(origin): + return jsonify(error="Requests from other websites are blocked."), 403 + return None + + +@bp.errorhandler(SetupError) +def setup_error(e): + return jsonify(error=str(e)), 400 + + +@bp.get("/api/settings") +def get_settings(): + env, svc = os.environ, _svc() + s = svc.settings + return jsonify( + env_file=str(env_file_path()), + test_mode=s.fake_judge or s.fake_llm, + setup_needed=not (s.llm_ready and s.judge_ready), + typesafe_key=keys.hint(env.get("TYPESAFE_API_KEY")), + llm_provider=keys.provider(env), + gemini_key=keys.hint(env.get("GEMINI_API_KEY")), + llm_key=keys.hint(env.get("LLM_API_KEY")), + llm_base_url=env.get("LLM_BASE_URL", ""), + llm_model=env.get("LLM_MODEL", "") or env.get("LLM_MODEL_NAME", ""), + active_tasks=svc.active_tasks(), + ) + + +@bp.put("/api/settings") +def put_settings(): + updates = keys.updates_from_form(_form(), os.environ) + keys.write_env(env_file_path(), updates) + keys.apply(updates) + _svc().reload(load_settings()) + return get_settings() + + +@bp.post("/api/settings/check") +def check(): + form, env = _form(), os.environ + jev_key = keys.text(form, "typesafe_key") or env.get("TYPESAFE_API_KEY", "") + jev = keys.check_jev(jev_key, _svc().settings.jev_model) if jev_key else {"ok": False, "message": "No Jev key yet."} + choice = form.get("llm_provider") or keys.provider(env) + typed = keys.text(form, "llm_key") + if choice == "gemini": + key = typed or env.get("GEMINI_API_KEY", "") + llm = keys.check_llm("gemini", key) if key else {"ok": False, "message": "No Gemini key yet."} + else: + key = typed or env.get("LLM_API_KEY", "") + base = keys.text(form, "llm_base_url") or env.get("LLM_BASE_URL", "") + model = keys.text(form, "llm_model") or env.get("LLM_MODEL", "") + llm = keys.check_llm("openai", key, base, model) if key and base and model else { + "ok": False, "message": "Fill in the address, model and key first."} + return jsonify(jev=jev, llm=llm) + + +@bp.get("/api/example") +def get_example(): + return jsonify(example.example()) + + +def _stop_process() -> None: + os.kill(os.getpid(), signal.SIGTERM) + + +@bp.post("/api/shutdown") +def shutdown(): + stop = current_app.config.get("JEVFISH_STOP") or _stop_process + threading.Timer(0.3, stop).start() # let the response go out first + return jsonify(ok=True) diff --git a/jevfish/tests/test_keys.py b/jevfish/tests/test_keys.py new file mode 100644 index 0000000000..f927ec0367 --- /dev/null +++ b/jevfish/tests/test_keys.py @@ -0,0 +1,153 @@ +import os +import stat + +import pytest +from dotenv import dotenv_values + +from jevfish import keys +from jevfish.config import env_file_path +from jevfish.keys import SetupError, updates_from_form, write_env +from tests.test_pipeline import settings + + +def test_env_file_path_follows_env(tmp_path, monkeypatch): + monkeypatch.setenv("JEVFISH_ENV_FILE", str(tmp_path / "x.env")) + assert env_file_path() == tmp_path / "x.env" + + +def test_health_reports_app_and_setup_needed(tmp_path): + ready = settings(tmp_path).health() + assert ready["app"] == "jevfish" and ready["setup_needed"] is False + missing = settings(tmp_path, fake_judge=False, fake_llm=False).health() + assert missing["setup_needed"] is True + + +def test_write_env_keeps_other_lines_and_round_trips(tmp_path): + path = tmp_path / ".env" + path.write_text("# mine\nOTHER=1\nTYPESAFE_API_KEY=old\nTYPESAFE_API_KEY=dupe\nJEVFISH_FAKE_LLM=1\n") + tricky = "k'e\\y$HOME\"x" + write_env(path, {"TYPESAFE_API_KEY": tricky, "JEVFISH_FAKE_LLM": None, "GEMINI_API_KEY": "g123"}) + text = path.read_text() + assert text.startswith("# mine\nOTHER=1\n") + assert text.count("TYPESAFE_API_KEY") == 1 and "JEVFISH_FAKE_LLM" not in text + values = dotenv_values(path) + assert values["TYPESAFE_API_KEY"] == tricky and values["GEMINI_API_KEY"] == "g123" and values["OTHER"] == "1" + assert stat.S_IMODE(os.stat(path).st_mode) == 0o600 + + +def test_write_env_rejects_newlines(tmp_path): + with pytest.raises(SetupError): + write_env(tmp_path / ".env", {"TYPESAFE_API_KEY": "a\nb"}) + + +def test_form_gemini_blank_key_keeps_saved(): + env = {"GEMINI_API_KEY": "saved"} + assert updates_from_form({"llm_provider": "gemini", "llm_key": " "}, env) == { + "LLM_API_KEY": None, "LLM_BASE_URL": None, "LLM_MODEL": None} + with pytest.raises(SetupError): + updates_from_form({"llm_provider": "gemini"}, {}) + + +def test_form_openai_needs_address_model_and_key(): + form = {"llm_provider": "openai", "llm_base_url": "https://api.openai.com/v1", "llm_model": "gpt-4o-mini", "llm_key": "sk-1"} + assert updates_from_form(form, {}) == {"LLM_BASE_URL": "https://api.openai.com/v1", "LLM_MODEL": "gpt-4o-mini", "LLM_API_KEY": "sk-1"} + for bad in ({"llm_base_url": "ftp://x"}, {"llm_model": ""}, {"llm_key": ""}): + with pytest.raises(SetupError): + updates_from_form({**form, **bad}, {}) + + +def test_form_test_mode_and_jev_key(): + assert updates_from_form({"test_mode": True, "typesafe_key": " ts "}, {}) == { + "JEVFISH_FAKE_JUDGE": "1", "JEVFISH_FAKE_LLM": "1", "TYPESAFE_API_KEY": "ts"} + assert updates_from_form({"test_mode": False}, {}) == {"JEVFISH_FAKE_JUDGE": None, "JEVFISH_FAKE_LLM": None} + with pytest.raises(SetupError): + updates_from_form({"llm_provider": "claude"}, {}) + + +def test_hint_shows_only_last_four(): + assert keys.hint(None) is None + assert keys.hint("short") == "" + assert keys.hint("abcdefghijkl1234") == "1234" + + +class _Models: + def __init__(self, result): + self.result = result + + def list(self): + if isinstance(self.result, Exception): + raise self.result + return self.result + + +def test_check_jev_maps_errors(): + from typesafe_sdk import TypeSafeAuthenticationError + + class Model: + def __init__(self, name): + self.name = name + + class Listing: + models = (Model("jev-latest"),) + + def factory(result): + class Client: + def __init__(self, **kw): + self.models = _Models(result) + + def close(self): + pass + return Client + + assert keys.check_jev("k", client_factory=factory(Listing()))["ok"] is True + assert keys.check_jev("k", "jev-9", client_factory=factory(Listing()))["ok"] is False + err = TypeSafeAuthenticationError.__new__(TypeSafeAuthenticationError) + Exception.__init__(err, "401") + bad = keys.check_jev("k", client_factory=factory(err)) + assert bad == {"ok": False, "message": "TypeSafe rejected this key."} + + +def test_check_llm_gemini_and_openai(): + import httpx + from openai import AuthenticationError, BadRequestError + + req = httpx.Request("GET", "https://x") + + def err(cls, code): + return cls("no", response=httpx.Response(code, request=req), body=None) + + class Gemini: + def __init__(self, result): + self.result = result + + def __call__(self, **kw): + self.kw = kw + self.models = _Models(self.result) + return self + + assert keys.check_llm("gemini", "g", client_factory=Gemini([]))["ok"] is True + assert keys.check_llm("gemini", "g", client_factory=Gemini(err(BadRequestError, 400)))["message"] == "Google rejected this key." + + class Chat: + def __init__(self, result): + self.result = result + self.completions = self + + def create(self, **kw): + self.kw = kw + if isinstance(self.result, Exception): + raise self.result + return self.result + + class Other: + def __init__(self, result): + self.chat = Chat(result) + + def __call__(self, **kw): + return self + + good = Other(object()) + assert keys.check_llm("openai", "k", "https://x/v1", "m", client_factory=good)["ok"] is True + assert good.chat.kw["max_tokens"] == 1 and good.chat.kw["model"] == "m" + rejected = keys.check_llm("openai", "k", "https://x/v1", "m", client_factory=Other(err(AuthenticationError, 401))) + assert rejected["message"] == "The provider rejected this key." diff --git a/jevfish/tests/test_launcher.py b/jevfish/tests/test_launcher.py new file mode 100644 index 0000000000..ebe4f039db --- /dev/null +++ b/jevfish/tests/test_launcher.py @@ -0,0 +1,184 @@ +import os +import re +import signal +import socket +import subprocess +import sys + +import pytest + +from jevfish.config import PACKAGE_ROOT + +LAUNCH = PACKAGE_ROOT / "launcher" / "launch.sh" +mac_only = pytest.mark.skipif(sys.platform != "darwin", reason="Mac launcher") + +FAKE_SERVER = """#!{python} +import http.server, json, os, sys +port = int(sys.argv[sys.argv.index("--port") + 1]) +open({pidfile!r}, "a").write(str(os.getpid()) + "\\n") +class H(http.server.BaseHTTPRequestHandler): + def do_GET(self): + body = json.dumps({{"app": "jevfish", "ok": True}}).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(body) + def log_message(self, *a): + pass +http.server.HTTPServer(("127.0.0.1", port), H).serve_forever() +""" + +FAKE_UV = """#!/bin/sh +echo "uv $*" >> "{calls}" +mkdir -p .venv/bin +cp "{server}" .venv/bin/jevfish +chmod +x .venv/bin/jevfish +""" + + +def test_built_web_app_is_present(): + dist = PACKAGE_ROOT / "web" / "dist" + html = (dist / "index.html").read_text() + assets = re.findall(r'(?:src|href)="/(assets/[^"]+)"', html) + assert assets and all((dist / a).is_file() for a in assets) + + +def free_port() -> int: + with socket.socket() as s: + s.bind(("127.0.0.1", 0)) + return s.getsockname()[1] + + +@pytest.fixture +def sandbox(tmp_path): + root = tmp_path / "repo" + jf = root / "jevfish" + (jf / "web" / "dist").mkdir(parents=True) + (jf / "web" / "dist" / "index.html").write_text("

app

") + (jf / "pyproject.toml").write_text("") + (jf / "uv.lock").write_text("") + server = tmp_path / "fake-server" + pidfile = tmp_path / "pids" + server.write_text(FAKE_SERVER.format(python=sys.executable, pidfile=str(pidfile))) + server.chmod(0o755) + calls = tmp_path / "uv-calls" + uv = tmp_path / "fake-uv" + uv.write_text(FAKE_UV.format(calls=calls, server=server)) + uv.chmod(0o755) + home = tmp_path / "home" + env = { + "HOME": str(home), "PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "JEVFISH_EXTRA_PATH": "", + "JEVFISH_NO_GUI": "1", "JEVFISH_NO_OPEN": "1", "JEVFISH_PORTS": str(free_port()), + } + box = dict(root=root, jf=jf, uv=uv, calls=calls, env=env, home=home, + state=home / "Library" / "Application Support" / "JevFish", + log=home / "Library" / "Logs" / "JevFish" / "launcher.log") + yield box + if pidfile.exists(): + for pid in pidfile.read_text().split(): + try: + os.kill(int(pid), signal.SIGTERM) + except ProcessLookupError: + pass + + +def launch(box, **extra): + return subprocess.run(["/bin/bash", str(LAUNCH), str(box["root"])], env={**box["env"], **extra}, timeout=90) + + +@mac_only +def test_first_start_installs_then_second_reuses(sandbox): + (sandbox["state"] / "bin").mkdir(parents=True) + (sandbox["state"] / "bin" / "uv").symlink_to(sandbox["uv"]) + assert launch(sandbox).returncode == 0 + log = sandbox["log"].read_text() + port = sandbox["env"]["JEVFISH_PORTS"] + assert f"ready http://127.0.0.1:{port}/" in log + assert sandbox["calls"].read_text().strip() == "uv sync --frozen" + assert (sandbox["jf"] / ".venv" / ".jevfish-synced").exists() + assert (sandbox["state"] / "repo-path").read_text().strip() == str(sandbox["root"]) + assert launch(sandbox).returncode == 0 + assert f"already running on {port}" in sandbox["log"].read_text() + assert sandbox["calls"].read_text().count("sync") == 1 + + +@mac_only +def test_installs_uv_when_missing(sandbox, tmp_path): + installer = tmp_path / "install.sh" + installer.write_text(f'#!/bin/sh\nmkdir -p "$UV_INSTALL_DIR"\ncp "{sandbox["uv"]}" "$UV_INSTALL_DIR/uv"\n') + assert launch(sandbox, JEVFISH_UV_INSTALLER=f"file://{installer}").returncode == 0 + log = sandbox["log"].read_text() + assert "Installing uv" in log and "ready http://" in log + assert (sandbox["state"] / "bin" / "uv").exists() + + +@mac_only +def test_package_install_is_retried(sandbox, tmp_path): + flaky = tmp_path / "flaky-uv" + marker = tmp_path / "failed-once" + flaky.write_text(f'#!/bin/sh\nif [ ! -f "{marker}" ]; then touch "{marker}"; exit 1; fi\nexec "{sandbox["uv"]}" "$@"\n') + flaky.chmod(0o755) + (sandbox["state"] / "bin").mkdir(parents=True) + (sandbox["state"] / "bin" / "uv").symlink_to(flaky) + assert launch(sandbox, JEVFISH_RETRY_SLEEP="0").returncode == 0 + log = sandbox["log"].read_text() + assert "package install attempt 1 failed" in log and "ready http://" in log + + +@mac_only +def test_missing_files_fail_cleanly(sandbox): + (sandbox["jf"] / "pyproject.toml").unlink() + assert launch(sandbox).returncode == 1 + assert "error: The JevFish files are missing" in sandbox["log"].read_text() + + +APP = PACKAGE_ROOT.parent / "JevFish.app" + + +@mac_only +def test_app_bundle_is_valid_and_finds_the_repo(tmp_path): + import shutil + + assert subprocess.run(["plutil", "-lint", str(APP / "Contents" / "Info.plist")]).returncode == 0 + exe = APP / "Contents" / "MacOS" / "JevFish" + assert os.access(exe, os.X_OK) + assert (APP / "Contents" / "Resources" / "AppIcon.icns").stat().st_size > 10_000 + repo = tmp_path / "repo" + shutil.copytree(APP, repo / "JevFish.app", symlinks=True) + stub = repo / "jevfish" / "launcher" / "launch.sh" + stub.parent.mkdir(parents=True) + out = tmp_path / "got" + stub.write_text(f'#!/bin/bash\necho "$1" > "{out}"\n') + env = {"HOME": str(tmp_path / "home"), "PATH": "/usr/bin:/bin"} + subprocess.run([str(repo / "JevFish.app" / "Contents" / "MacOS" / "JevFish")], env=env, timeout=30, check=True) + assert out.read_text().strip() == str(repo) + # moved away from the folder: falls back to the remembered path + moved = tmp_path / "Applications" + moved.mkdir() + shutil.move(str(repo / "JevFish.app"), moved / "JevFish.app") + state = tmp_path / "home" / "Library" / "Application Support" / "JevFish" + state.mkdir(parents=True) + (state / "repo-path").write_text(f"{repo}\n") + out.unlink() + subprocess.run([str(moved / "JevFish.app" / "Contents" / "MacOS" / "JevFish")], env=env, timeout=30, check=True) + assert out.read_text().strip() == str(repo) + + +@mac_only +def test_unreadable_folder_hands_over_to_terminal(tmp_path): + """macOS blocks apps from reading Desktop, Documents and Downloads: Terminal runs it instead.""" + import shutil + + repo = tmp_path / "repo" + shutil.copytree(APP, repo / "JevFish.app", symlinks=True) + script = repo / "jevfish" / "launcher" / "launch.sh" + script.parent.mkdir(parents=True) + script.write_text("#!/bin/bash\necho hi\n") + script.chmod(0o000) # stands in for the privacy block: it exists but cannot be opened + opened = tmp_path / "opened" + fake_open = tmp_path / "fake-open" + fake_open.write_text('#!/bin/bash\necho "$@" > "%s"\n' % opened) + fake_open.chmod(0o755) + env = {"HOME": str(tmp_path / "home"), "PATH": "/usr/bin:/bin", "JEVFISH_OPEN_CMD": str(fake_open)} + subprocess.run([str(repo / "JevFish.app" / "Contents" / "MacOS" / "JevFish")], env=env, timeout=30, check=True) + assert opened.read_text().strip() == f"-a Terminal {script}" diff --git a/jevfish/tests/test_setup_api.py b/jevfish/tests/test_setup_api.py new file mode 100644 index 0000000000..9f0a51b029 --- /dev/null +++ b/jevfish/tests/test_setup_api.py @@ -0,0 +1,105 @@ +import os +import time + +import pytest + +from jevfish import keys +from jevfish.api import create_app +from jevfish.llm import FakeLLM +from jevfish.service import Service +from tests.test_pipeline import settings + +MANAGED = ("TYPESAFE_API_KEY", "GEMINI_API_KEY", "LLM_API_KEY", "LLM_BASE_URL", "LLM_MODEL", "LLM_MODEL_NAME", + "JEVFISH_FAKE_JUDGE", "JEVFISH_FAKE_LLM", "JEVFISH_DATA_DIR") + + +@pytest.fixture +def env_file(tmp_path): + # saving settings edits os.environ directly, so snapshot and restore all of it + before = dict(os.environ) + for k in MANAGED: + os.environ.pop(k, None) + path = tmp_path / "keys.env" + os.environ["JEVFISH_ENV_FILE"] = str(path) + yield path + os.environ.clear() + os.environ.update(before) + + +@pytest.fixture +def app(tmp_path, env_file): + s = settings(tmp_path, fake_judge=False, fake_llm=False) + stopped = [] + app = create_app(s, Service(s, llm=FakeLLM())) + app.config["JEVFISH_STOP"] = lambda: stopped.append(True) + app.stopped = stopped + return app + + +def test_first_run_needs_setup_then_save_applies_without_restart(app, env_file, tmp_path): + c = app.test_client() + assert c.get("/api/health").get_json()["setup_needed"] is True + got = c.get("/api/settings").get_json() + assert got["typesafe_key"] is None and got["llm_provider"] == "gemini" and got["setup_needed"] is True + r = c.put("/api/settings", json={"typesafe_key": "ts-abcdefgh9999", "llm_provider": "gemini", "llm_key": "gm-abcdefgh7777"}) + assert r.status_code == 200, r.get_json() + body = r.get_json() + assert body["typesafe_key"] == "9999" and body["gemini_key"] == "7777" and body["setup_needed"] is False + assert "ts-abcdefgh9999" not in r.get_data(as_text=True) + assert "TYPESAFE_API_KEY='ts-abcdefgh9999'" in env_file.read_text() + health = c.get("/api/health").get_json() + assert health["judge"] == "jev" and health["setup_needed"] is False + assert health["data_dir"] == str(tmp_path / "data") + + +def test_test_mode_toggle(app): + c = app.test_client() + assert c.put("/api/settings", json={"test_mode": True}).get_json()["test_mode"] is True + assert c.get("/api/health").get_json()["judge"] == "fake" + assert c.put("/api/settings", json={"test_mode": False}).get_json()["test_mode"] is False + assert c.get("/api/health").get_json()["setup_needed"] is True + + +def test_bad_form_is_400(app): + r = app.test_client().put("/api/settings", json={"llm_provider": "openai", "llm_base_url": "nope"}) + assert r.status_code == 400 and "http" in r.get_json()["error"] + assert app.test_client().put("/api/settings", data="x").status_code == 400 + + +def test_check_uses_form_keys_then_saved(app, monkeypatch): + calls = [] + monkeypatch.setattr(keys, "check_jev", lambda key, model="jev-latest": calls.append(("jev", key)) or {"ok": True, "message": "j"}) + monkeypatch.setattr(keys, "check_llm", lambda choice, key, base_url=None, model=None: calls.append((choice, key)) or {"ok": False, "message": "l"}) + c = app.test_client() + r = c.post("/api/settings/check", json={"typesafe_key": "typed", "llm_provider": "gemini"}).get_json() + assert r["jev"]["ok"] is True and r["llm"] == {"ok": False, "message": "No Gemini key yet."} + assert calls == [("jev", "typed")] + os.environ["GEMINI_API_KEY"] = "saved-g" + c.post("/api/settings/check", json={}) + assert calls[-1] == ("gemini", "saved-g") + + +def test_example_and_shutdown(app): + c = app.test_client() + ex = c.get("/api/example").get_json() + assert "Lazybee" in ex["name"] and ex["seed_text"].strip() and ex["requirement"].endswith("?") + assert c.post("/api/shutdown").get_json()["ok"] is True + time.sleep(0.5) + assert app.stopped == [True] + + +def test_guard_blocks_other_hosts_and_origins(app): + c = app.test_client() + assert c.get("/api/health", headers={"Host": "evil.example"}).status_code == 403 + assert c.get("/api/health", headers={"Host": "127.0.0.1:5055"}).status_code == 200 + assert c.get("/api/health", headers={"Host": "[::1]:5055"}).status_code == 200 + assert c.put("/api/settings", json={"test_mode": True}, headers={"Origin": "https://evil.example"}).status_code == 403 + assert c.put("/api/settings", json={"test_mode": True}, headers={"Origin": "null"}).status_code == 403 + assert c.put("/api/settings", json={"test_mode": True}, headers={"Origin": "http://localhost:5173"}).status_code == 200 + assert c.get("/", headers={"Host": "evil.example"}).status_code == 200 # the page itself holds no data + + +def test_guard_can_be_turned_off(tmp_path, env_file): + s = settings(tmp_path) + app = create_app(s, Service(s, llm=FakeLLM()), allow_remote=True) + assert app.test_client().get("/api/health", headers={"Host": "192.168.1.9:5055"}).status_code == 200 diff --git a/jevfish/web/dist/assets/index-BHsORouT.css b/jevfish/web/dist/assets/index-BHsORouT.css new file mode 100644 index 0000000000..a276a155b4 --- /dev/null +++ b/jevfish/web/dist/assets/index-BHsORouT.css @@ -0,0 +1 @@ +.topbar[data-v-8c98f59b]{background:var(--panel);border-bottom:1px solid var(--line)}.topbar-inner[data-v-8c98f59b]{display:flex;align-items:center;gap:16px;min-height:56px;flex-wrap:wrap;padding-top:8px;padding-bottom:8px}.brand[data-v-8c98f59b]{display:inline-flex;align-items:center;gap:10px;text-decoration:none;color:var(--ink);font-weight:700;font-size:17px;letter-spacing:-.01em}.brand-tile[data-v-8c98f59b]{fill:var(--accent)}.brand-dots[data-v-8c98f59b]{fill:var(--accent-ink)}.tagline[data-v-8c98f59b]{font-size:13px}@media(max-width:700px){.tagline[data-v-8c98f59b]{display:none}}.banner-wrap[data-v-8c98f59b]{margin-top:16px;display:grid;gap:8px}.main[data-v-8c98f59b]{padding-top:24px;padding-bottom:64px}.intro[data-v-ad940d1f]{max-width:720px}.intro h1[data-v-ad940d1f]{font-size:32px;letter-spacing:-.02em;margin-bottom:8px}.intro p[data-v-ad940d1f]{font-size:16px}@media(max-width:600px){.intro h1[data-v-ad940d1f]{font-size:26px}}.new-form[data-v-ad940d1f]{display:grid;gap:16px;max-width:760px}.file-btn[data-v-ad940d1f]{position:relative}.file-list[data-v-ad940d1f]{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:4px}.file-list li[data-v-ad940d1f]{display:flex;gap:12px;align-items:center;font-size:14px}.project-list[data-v-ad940d1f]{list-style:none;margin:0;padding:0;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius)}.project[data-v-ad940d1f]{display:flex;gap:16px;align-items:center;padding:14px 20px;flex-wrap:wrap}.project+.project[data-v-ad940d1f]{border-top:1px solid var(--line)}.project-link[data-v-ad940d1f]{flex:1 1 360px;min-width:0;text-decoration:none;color:inherit;display:grid;gap:2px}.project-link:hover .project-name[data-v-ad940d1f]{text-decoration:underline}.project-name[data-v-ad940d1f]{font-weight:600;font-size:16px}.project-q[data-v-ad940d1f]{color:var(--muted);font-size:14px}.project-meta[data-v-ad940d1f]{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.back[data-v-9f3ef09d]{color:var(--muted);text-decoration:none;display:inline-block}.back[data-v-9f3ef09d]:before{content:"‹";margin-right:6px}.back[data-v-9f3ef09d]:hover{color:var(--ink)}.ws-head[data-v-9f3ef09d]{max-width:900px}.title-row[data-v-9f3ef09d]{gap:12px}.title-row h1[data-v-9f3ef09d]{font-size:24px}.question[data-v-9f3ef09d]{font-size:20px;line-height:1.4;margin-top:8px;color:var(--ink-2);letter-spacing:-.01em}@media(max-width:600px){.question[data-v-9f3ef09d]{font-size:17px}}.edit-form[data-v-9f3ef09d]{display:grid;gap:12px}.stepbar[data-v-9f3ef09d]{display:flex;gap:16px;align-items:center;flex-wrap:wrap;border-bottom:1px solid var(--line);padding-bottom:12px}.steps[data-v-9f3ef09d]{list-style:none;margin:0;padding:0;display:flex;gap:4px;flex-wrap:wrap;flex:1 1 auto;counter-reset:none}.step[data-v-9f3ef09d]{display:inline-flex;align-items:center;gap:8px;padding:6px 12px 6px 6px;border-radius:999px;text-decoration:none;color:var(--ink-2);font-weight:600;font-size:14px}a.step[data-v-9f3ef09d]:hover{background:var(--panel)}.step-n[data-v-9f3ef09d]{width:24px;height:24px;border-radius:50%;display:inline-grid;place-items:center;font-size:12px;border:1px solid var(--line-strong);color:var(--muted);background:var(--panel);font-variant-numeric:tabular-nums}.step.done .step-n[data-v-9f3ef09d]{border-color:transparent;background:var(--accent-soft);color:var(--accent-text)}.step.current[data-v-9f3ef09d]{background:var(--panel);color:var(--ink);box-shadow:inset 0 0 0 1px var(--line)}.step.current .step-n[data-v-9f3ef09d]{background:var(--accent);border-color:var(--accent);color:var(--accent-ink)}.step.locked[data-v-9f3ef09d]{color:var(--muted);opacity:.6;cursor:not-allowed}.run-pick[data-v-9f3ef09d]{display:flex;align-items:center;gap:8px;min-width:0;flex:0 1 340px}.run-pick select[data-v-9f3ef09d]{min-width:0}@media(max-width:600px){.step[data-v-9f3ef09d]{padding-right:8px;font-size:13px}.run-pick[data-v-9f3ef09d]{flex:1 1 100%}}.fg-box[data-v-be080fe7]{position:relative;border-radius:var(--radius-sm);background:var(--panel-2);border:1px solid var(--line);overflow:hidden;touch-action:none}svg[data-v-be080fe7]{display:block;cursor:grab;-webkit-user-select:none;user-select:none}svg[data-v-be080fe7]:active{cursor:grabbing}.links line[data-v-be080fe7]{stroke:var(--line-strong);stroke-width:1}.links line.hot[data-v-be080fe7]{stroke:var(--ink-2);stroke-width:1.5}.links line.dim[data-v-be080fe7]{opacity:.35}.links line.edgehit[data-v-be080fe7]{stroke:var(--ink);stroke-width:2.5;opacity:1}.node[data-v-be080fe7]{cursor:pointer;outline:none}.node .hit[data-v-be080fe7]{fill:transparent}.node .dot[data-v-be080fe7]{stroke:var(--panel-2);stroke-width:2}.node:hover .dot[data-v-be080fe7],.node:focus-visible .dot[data-v-be080fe7]{stroke:var(--ink);stroke-width:2}.node.sel .dot[data-v-be080fe7]{stroke:var(--ink);stroke-width:3}.node.dim[data-v-be080fe7]{opacity:.3}.node text[data-v-be080fe7]{font-size:11px;fill:var(--ink);paint-order:stroke;stroke:var(--panel-2);stroke-width:3px;stroke-linejoin:round;pointer-events:none}.node.sel text[data-v-be080fe7]{font-weight:700}.fg-tools[data-v-be080fe7]{position:absolute;right:8px;top:8px;display:flex;gap:4px}.hint[data-v-be080fe7]{margin-top:6px}.task[data-v-f35b8610]{display:grid;gap:8px;padding:12px 14px;border:1px solid var(--line);border-radius:var(--radius-sm);background:var(--panel-2)}.task-top[data-v-f35b8610]{display:flex;gap:10px;align-items:center;flex-wrap:wrap}.sources[data-v-b3222292]{list-style:none;margin:0 0 16px;padding:0}.sources li[data-v-b3222292]{display:flex;gap:12px;align-items:baseline;padding:6px 0;border-bottom:1px solid var(--line);flex-wrap:wrap}.sources li[data-v-b3222292]>:first-child{flex:1 1 160px;min-width:0}.add summary[data-v-b3222292]{cursor:pointer;font-weight:600;font-size:14px;color:var(--accent-text);margin-bottom:12px}.add[open] summary[data-v-b3222292]{margin-bottom:12px}label.btn.disabled[data-v-b3222292]{opacity:.5}.stats[data-v-b3222292]{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px;margin:0}@media(max-width:500px){.stats[data-v-b3222292]{grid-template-columns:repeat(2,minmax(0,1fr))}}.stats div[data-v-b3222292]{background:var(--panel-2);border-radius:var(--radius-sm);padding:10px 12px}.stats dt[data-v-b3222292]{font-size:13px;color:var(--muted)}.stats dd[data-v-b3222292]{margin:0;font-size:24px;font-weight:600}.stats dd.bad[data-v-b3222292]{color:var(--bad)}.type-counts[data-v-b3222292]{display:flex;gap:6px;flex-wrap:wrap}.graph-legend[data-v-b3222292]{margin-bottom:12px}.map-grid[data-v-b3222292]{grid-template-columns:minmax(0,1fr) 320px}@media(max-width:900px){.map-grid[data-v-b3222292]{grid-template-columns:minmax(0,1fr)}}.map-main[data-v-b3222292]{min-width:0}.node-table[data-v-b3222292]{max-height:520px;overflow-y:auto;border:1px solid var(--line);border-radius:var(--radius-sm)}.node-table .summary[data-v-b3222292]{min-width:240px;color:var(--ink-2)}tr.picked td[data-v-b3222292]{background:var(--accent-soft)!important}.linkish[data-v-b3222292]{font:inherit;background:none;border:0;padding:0;color:var(--accent-text);cursor:pointer;text-align:left;text-decoration:underline;text-underline-offset:2px}.results[data-v-b3222292]{list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:var(--radius-sm);max-height:260px;overflow-y:auto}.results li+li[data-v-b3222292]{border-top:1px solid var(--line)}.result[data-v-b3222292]{display:grid;gap:2px;width:100%;text-align:left;font:inherit;background:none;border:0;padding:8px 10px;cursor:pointer;color:var(--ink)}.result[data-v-b3222292]:hover{background:var(--panel-2)}.r-title[data-v-b3222292]{display:flex;gap:6px;align-items:center;font-size:14px;font-weight:600}.detail[data-v-b3222292]{border-top:1px solid var(--line);padding-top:12px;display:grid;gap:8px}.facts[data-v-b3222292]{list-style:none;margin:0;padding:0;display:grid;gap:8px;max-height:320px;overflow-y:auto}.facts li[data-v-b3222292]{padding:8px 10px;border-radius:var(--radius-sm);background:var(--panel-2)}.rel[data-v-b3222292]{margin:0 .35em}.facts li.hit[data-v-b3222292]{box-shadow:inset 0 0 0 2px var(--ink-2)}.kv[data-v-eb815f0a]{display:grid;grid-template-columns:max-content minmax(0,1fr);gap:4px 12px;margin:0}.kv dt[data-v-eb815f0a]{color:var(--muted)}.kv dd[data-v-eb815f0a]{margin:0}.levels[data-v-eb815f0a]{margin:0;padding-left:20px}.openings[data-v-eb815f0a]{list-style:none;margin:0;padding:0;display:grid;gap:8px}.openings li[data-v-eb815f0a]{background:var(--panel-2);border-radius:var(--radius-sm);padding:10px 12px}.points td[data-v-eb815f0a]{vertical-align:middle}.pid[data-v-eb815f0a]{max-width:120px;overflow:hidden;text-overflow:ellipsis;display:inline-block;line-height:1.2}.points td.grow[data-v-eb815f0a]{width:100%;min-width:260px}.points select[data-v-eb815f0a]{width:auto}.variants[data-v-eb815f0a]{display:grid;gap:12px}.variant[data-v-eb815f0a]{border:1px solid var(--line);border-radius:var(--radius-sm);padding:14px;display:grid;gap:12px}.v-head[data-v-eb815f0a]{display:flex;gap:12px;align-items:flex-end;flex-wrap:wrap}.v-id[data-v-eb815f0a]{width:110px}.v-label[data-v-eb815f0a]{flex:1 1 220px}.kv-row[data-v-eb815f0a]{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,2fr) auto;gap:8px;align-items:center}@media(max-width:520px){.kv-row[data-v-eb815f0a]{grid-template-columns:minmax(0,1fr) auto}.kv-row input[data-v-eb815f0a]:nth-child(2){grid-column:1;grid-row:2}}.label[data-v-eb815f0a]{font-weight:600;color:var(--ink-2)}.savebar[data-v-eb815f0a]{position:sticky;bottom:0;background:var(--panel);padding:12px 0;border-top:1px solid var(--line)}.seg-list[data-v-1907df61]{list-style:none;margin:0;padding:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:16px}.seg-top[data-v-1907df61]{display:flex;justify-content:space-between;gap:8px}.bar-track[data-v-1907df61]{height:10px;margin:6px 0}.bar[data-v-1907df61]{height:100%;background:var(--s1);border-radius:0 4px 4px 0;min-width:2px}.crowd-table[data-v-1907df61]{margin-top:28px}.kind[data-v-1907df61]{width:auto}.filter[data-v-1907df61]{max-width:280px}@media(max-width:600px){.filter[data-v-1907df61]{max-width:none}}.bordered[data-v-1907df61]{border:1px solid var(--line);border-radius:var(--radius-sm);max-height:560px;overflow-y:auto}.who[data-v-1907df61]{min-width:220px;max-width:380px}.who .name[data-v-1907df61]{display:block;font-weight:600}.bio[data-v-1907df61]{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}.feed[data-v-ced3dc21]{display:grid;gap:10px}.feed-bar[data-v-ced3dc21]{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.vsel[data-v-ced3dc21]{width:auto;max-width:220px}.live[data-v-ced3dc21]{display:inline-flex;gap:6px;align-items:center;font-weight:600;color:var(--good)}.pulse[data-v-ced3dc21]{width:8px;height:8px;border-radius:50%;background:var(--good);animation:pulse-ced3dc21 1.4s ease-in-out infinite}@keyframes pulse-ced3dc21{50%{opacity:.3}}.items[data-v-ced3dc21]{list-style:none;margin:0;padding:0 4px 0 0;display:grid;gap:6px;max-height:640px;overflow-y:auto;overscroll-behavior:contain}.item.post[data-v-ced3dc21],.item.comment[data-v-ced3dc21]{border:1px solid var(--line);border-radius:var(--radius-sm);padding:10px 12px;background:var(--panel);display:grid;gap:6px}.item.comment[data-v-ced3dc21]{margin-left:24px;background:var(--panel-2)}@media(max-width:500px){.item.comment[data-v-ced3dc21]{margin-left:10px}}.item.failed[data-v-ced3dc21]{border-style:dashed}.meta[data-v-ced3dc21]{display:flex;gap:8px;align-items:center;flex-wrap:wrap}.content[data-v-ced3dc21]{white-space:pre-wrap}.reply[data-v-ced3dc21]{border-left:2px solid var(--line-strong);padding-left:8px}.foot[data-v-ced3dc21]{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.foot .pill[data-v-ced3dc21]{max-width:100%;white-space:normal;line-height:1.3}.item.reaction[data-v-ced3dc21]{padding:2px 12px}.line[data-v-ced3dc21]{color:var(--ink-2)}.line .who[data-v-ced3dc21]{font-weight:600;color:var(--ink)}.line .when[data-v-ced3dc21]{margin-left:8px}.empty-feed[data-v-ced3dc21]{padding:16px 0}.lc[data-v-99093c3d]{display:grid;gap:8px}.lc-top[data-v-99093c3d]{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.grid line[data-v-99093c3d]{stroke:var(--grid);stroke-width:1}.grid text[data-v-99093c3d]{font-size:12px;fill:var(--muted);font-variant-numeric:tabular-nums}.axis-title[data-v-99093c3d]{font-size:12px}.line[data-v-99093c3d]{fill:none;stroke-width:2;stroke-linejoin:round;stroke-linecap:round}.pt[data-v-99093c3d]{stroke:var(--panel);stroke-width:2}.cross[data-v-99093c3d]{stroke:var(--line-strong);stroke-width:1}.end[data-v-99093c3d]{font-size:12px;fill:var(--ink-2)}.dots[data-v-9bc118e4]{display:flex;flex-wrap:wrap;gap:3px}.dot[data-v-9bc118e4]{width:9px;height:9px;border-radius:50%;background:var(--dot-empty);display:inline-block;flex:none}.dot.yes[data-v-9bc118e4]{background:var(--c)}.dot.range[data-v-9bc118e4]{background:color-mix(in srgb,var(--c) 38%,var(--panel))}.key[data-v-9bc118e4]{display:flex;flex-wrap:wrap;gap:4px 14px;margin-top:8px}.key>span[data-v-9bc118e4]{display:inline-flex;gap:6px;align-items:center}.tiles[data-v-30b405d5]{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px}.tile[data-v-30b405d5]{border:1px solid var(--line);border-radius:var(--radius);padding:18px;display:grid;gap:14px;align-content:start;background:var(--panel)}.tile-head[data-v-30b405d5]{display:flex;gap:8px;align-items:center}.tile-head h3[data-v-30b405d5]{flex:1;min-width:0}.big[data-v-30b405d5]{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap}.figure[data-v-30b405d5]{font-size:40px;font-weight:650;letter-spacing:-.02em;line-height:1}.of[data-v-30b405d5]{color:var(--ink-2)}.facts[data-v-30b405d5]{margin:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px 16px}.facts dt[data-v-30b405d5]{font-size:13px;color:var(--muted)}.facts dd[data-v-30b405d5]{margin:0;font-weight:600}.compare[data-v-30b405d5]{list-style:none;margin:0;padding:0;display:grid;gap:8px}.compare li[data-v-30b405d5]{display:flex;gap:12px;align-items:center;flex-wrap:wrap;padding:10px 12px;background:var(--panel-2);border-radius:var(--radius-sm)}.c-name[data-v-30b405d5]{font-weight:600;flex:1 1 180px}.usage[data-v-30b405d5]{border-top:1px solid var(--line);padding-top:16px}.usage-grid[data-v-30b405d5]{margin:0 0 8px;display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:12px}.usage-grid dt[data-v-30b405d5]{font-size:13px;color:var(--muted)}.usage-grid dd[data-v-30b405d5]{margin:0;font-size:18px;font-weight:600}.run-grid[data-v-07da18f1]{display:grid;grid-template-columns:minmax(0,1fr) 280px;gap:24px;align-items:start}@media(max-width:900px){.run-grid[data-v-07da18f1]{grid-template-columns:minmax(0,1fr)}}legend.label[data-v-07da18f1],.label[data-v-07da18f1]{font-size:13px;font-weight:600;color:var(--ink-2);padding:0}.checks[data-v-07da18f1]{display:flex;flex-wrap:wrap;gap:8px 20px}.inj[data-v-07da18f1]{display:grid;grid-template-columns:80px minmax(0,1fr) 160px auto;gap:8px;align-items:end}@media(max-width:640px){.inj[data-v-07da18f1]{grid-template-columns:80px minmax(0,1fr)}.inj-text[data-v-07da18f1]{grid-column:1 / -1;grid-row:2}}.estimate[data-v-07da18f1]{position:sticky;top:16px;background:var(--panel-2);border:1px solid var(--line);border-radius:var(--radius);padding:18px;display:grid;gap:8px}.est-big[data-v-07da18f1]{font-size:36px;font-weight:650;line-height:1.1;letter-spacing:-.02em}.est-big.stale[data-v-07da18f1]{opacity:.5}.est[data-v-07da18f1]{margin:4px 0;display:grid;gap:6px}.est div[data-v-07da18f1]{display:flex;justify-content:space-between;gap:12px;font-size:14px}.est dt[data-v-07da18f1]{color:var(--muted)}.est dd[data-v-07da18f1]{margin:0;font-weight:600;text-align:right}.start[data-v-07da18f1]{width:100%;margin-top:4px}.run-head[data-v-07da18f1]{margin-bottom:0}.run-head p[data-v-07da18f1]{flex-basis:100%}.live[data-v-07da18f1]{padding:14px;border-radius:var(--radius-sm);background:var(--accent-soft)}.gb[data-v-5f0a10de]{display:grid;gap:8px}.gb-top[data-v-5f0a10de]{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.grid line[data-v-5f0a10de]{stroke:var(--grid);stroke-width:1}.grid text[data-v-5f0a10de]{font-size:12px;fill:var(--muted);font-variant-numeric:tabular-nums}.base[data-v-5f0a10de]{stroke:var(--line-strong);stroke-width:1}.bar[data-v-5f0a10de]{transition:opacity .15s}.bar.lifted[data-v-5f0a10de]{opacity:.8}rect[data-v-5f0a10de]:focus{outline:none}rect[data-v-5f0a10de]:focus-visible{stroke:var(--focus);stroke-width:2}.report-grid[data-v-dd71796f]{display:grid;grid-template-columns:minmax(0,1.1fr) minmax(0,1fr);gap:20px;align-items:start}@media(max-width:1080px){.report-grid[data-v-dd71796f]{grid-template-columns:minmax(0,1fr)}}.data-col[data-v-dd71796f]{min-width:0}.auto[data-v-dd71796f]{width:auto;max-width:220px}.th-key[data-v-dd71796f]{display:inline-flex;gap:6px;align-items:center}.pt-text[data-v-dd71796f]{min-width:260px}.seg-name[data-v-dd71796f]{min-width:120px;overflow-wrap:break-word}.wrap-th[data-v-dd71796f]{white-space:normal!important;min-width:90px;max-width:180px}.prose[data-v-dd71796f]{max-width:70ch;font-size:15px;line-height:1.65;overflow-wrap:anywhere}.prose[data-v-dd71796f] h1,.prose[data-v-dd71796f] h2,.prose[data-v-dd71796f] h3{margin:1.4em 0 .4em}.prose[data-v-dd71796f] h1{font-size:22px}.prose[data-v-dd71796f] h2{font-size:19px}.prose[data-v-dd71796f] h3{font-size:16px}.prose[data-v-dd71796f]>:first-child{margin-top:0}.prose[data-v-dd71796f] p,.prose[data-v-dd71796f] ul,.prose[data-v-dd71796f] ol,.prose[data-v-dd71796f] blockquote{margin:0 0 .9em}.prose[data-v-dd71796f] ul,.prose[data-v-dd71796f] ol{padding-left:1.3em}.prose[data-v-dd71796f] blockquote{border-left:3px solid var(--line-strong);padding-left:12px;color:var(--ink-2)}.prose[data-v-dd71796f] code{font-size:.9em;background:var(--panel-2);padding:1px 4px;border-radius:4px}.prose[data-v-dd71796f] pre{overflow-x:auto;background:var(--panel-2);padding:10px;border-radius:6px}.prose[data-v-dd71796f] table{border-collapse:collapse;display:block;overflow-x:auto;max-width:100%;margin:0 0 1em;font-size:14px}.prose[data-v-dd71796f] th,.prose[data-v-dd71796f] td{border-bottom:1px solid var(--line);padding:6px 10px;text-align:left}.prose[data-v-dd71796f] img{max-width:100%}.posts-grid[data-v-dd71796f]{grid-template-columns:minmax(0,1fr) 360px}@media(max-width:900px){.posts-grid[data-v-dd71796f]{grid-template-columns:minmax(0,1fr)}}.post[data-v-dd71796f]{border:1px solid var(--line);border-radius:var(--radius-sm);padding:12px 14px;display:grid;gap:6px}.post .content[data-v-dd71796f]{white-space:pre-wrap}.comments[data-v-dd71796f]{list-style:none;margin:4px 0 0;padding:0 0 0 14px;border-left:2px solid var(--line);display:grid;gap:8px}.ask-grid[data-v-69a3ca99]{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:20px;align-items:start}@media(max-width:1000px){.ask-grid[data-v-69a3ca99]{grid-template-columns:minmax(0,1fr)}}.picker-row[data-v-69a3ca99]{display:flex;gap:12px;flex-wrap:wrap;align-items:flex-end}.picker-row .grow[data-v-69a3ca99]{flex:1 1 200px}.label[data-v-69a3ca99]{font-size:13px;font-weight:600;color:var(--ink-2);display:block;margin-bottom:6px}.people[data-v-69a3ca99]{list-style:none;margin:0;padding:4px;max-height:200px;overflow-y:auto;border:1px solid var(--line);border-radius:var(--radius-sm)}.people button[data-v-69a3ca99]{width:100%;font:inherit;text-align:left;background:none;border:0;border-radius:4px;padding:6px 8px;cursor:pointer;display:flex;gap:8px;align-items:baseline;justify-content:space-between;color:var(--ink)}.people button[data-v-69a3ca99]:hover{background:var(--panel-2)}.people button.on[data-v-69a3ca99]{background:var(--accent-soft)}.p-name[data-v-69a3ca99]{font-weight:600;font-size:14px}.pad[data-v-69a3ca99]{padding:8px}.persona[data-v-69a3ca99]{background:var(--panel-2);border-radius:var(--radius-sm);padding:10px 12px}.thread[data-v-69a3ca99]{display:flex;flex-direction:column;gap:8px;max-height:420px;min-height:120px;overflow-y:auto;padding:4px 2px}.msg[data-v-69a3ca99]{max-width:85%;padding:8px 12px;border-radius:14px;font-size:14px;white-space:pre-wrap}.msg.user[data-v-69a3ca99]{align-self:flex-end;background:var(--accent);color:var(--accent-ink);border-bottom-right-radius:4px}.msg.assistant[data-v-69a3ca99]{align-self:flex-start;background:var(--panel-2);border:1px solid var(--line);border-bottom-left-radius:4px}.msg.pending[data-v-69a3ca99]{opacity:.7}.composer[data-v-69a3ca99]{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:8px;align-items:end}.r-q[data-v-69a3ca99]{font-size:17px;font-weight:600}.result[data-v-69a3ca99]{border-top:1px solid var(--line);padding-top:16px}.big[data-v-69a3ca99]{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap;color:var(--ink-2)}.figure[data-v-69a3ca99]{font-size:40px;font-weight:650;letter-spacing:-.02em;line-height:1;color:var(--ink)}.facts[data-v-69a3ca99]{margin:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px 16px}.facts dt[data-v-69a3ca99]{font-size:13px;color:var(--muted)}.facts dd[data-v-69a3ca99]{margin:0;font-weight:600}.names ol[data-v-69a3ca99]{margin:6px 0 0;padding-left:20px;font-size:14px}.asks[data-v-69a3ca99]{list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:var(--radius-sm)}.asks li+li[data-v-69a3ca99]{border-top:1px solid var(--line)}.asks button[data-v-69a3ca99]{width:100%;font:inherit;font-size:14px;text-align:left;background:none;border:0;padding:8px 12px;cursor:pointer;display:flex;gap:12px;justify-content:space-between;align-items:baseline;color:var(--ink);flex-wrap:wrap}.asks button[data-v-69a3ca99]:hover{background:var(--panel-2)}.asks button.on[data-v-69a3ca99]{background:var(--accent-soft)}.setup[data-v-fc354223]{max-width:760px}.intro h1[data-v-fc354223]{font-size:32px;letter-spacing:-.02em;margin-bottom:8px}.intro p[data-v-fc354223]{font-size:16px}@media(max-width:600px){.intro h1[data-v-fc354223]{font-size:26px}}.form-grid.wide[data-v-fc354223]{grid-template-columns:repeat(auto-fill,minmax(240px,1fr))}:root{color-scheme:light;--bg: #f3f5f7;--panel: #ffffff;--panel-2: #f7f9fa;--ink: #17212b;--ink-2: #44505c;--muted: #66727e;--line: #dde3e8;--line-strong: #c3ccd4;--grid: #e9edf0;--accent: #0e5a6b;--accent-hover: #0a4755;--accent-ink: #ffffff;--accent-soft: #e2eff1;--accent-text: #0b5263;--focus: #1c7f94;--good: #13724a;--good-soft: #e3f3ea;--warn: #8a5a00;--warn-soft: #fbf0d9;--bad: #b3261e;--bad-soft: #fbe6e4;--tooltip-bg: #17212b;--tooltip-ink: #f3f5f7;--shadow: 0 1px 2px rgba(23, 33, 43, .05), 0 4px 16px rgba(23, 33, 43, .04);--s1: #2a78d6;--s2: #eb6834;--s3: #1baf7a;--s4: #eda100;--s5: #e87ba4;--s6: #008300;--s7: #4a3aa7;--s8: #e34948;--s-other: #9aa4ad;--dot-empty: #e4e9ed;--radius: 10px;--radius-sm: 6px;--font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif}@media(prefers-color-scheme:dark){:root:not([data-theme=light]){color-scheme:dark;--bg: #111418;--panel: #1b1e23;--panel-2: #20242a;--ink: #e6eaee;--ink-2: #b9c2ca;--muted: #919ca7;--line: #2d333a;--line-strong: #414953;--grid: #272c32;--accent: #6cc3d3;--accent-hover: #8dd3e0;--accent-ink: #08262d;--accent-soft: #173239;--accent-text: #8dd3e0;--focus: #8dd3e0;--good: #5fcf98;--good-soft: #15302a;--warn: #e9b44c;--warn-soft: #33290f;--bad: #f08a82;--bad-soft: #3a1c1b;--tooltip-bg: #e6eaee;--tooltip-ink: #111418;--shadow: 0 1px 2px rgba(0, 0, 0, .3);--s1: #3987e5;--s2: #d95926;--s3: #199e70;--s4: #c98500;--s5: #d55181;--s6: #008300;--s7: #9085e9;--s8: #e66767;--s-other: #6f7a85;--dot-empty: #2b3137}}:root[data-theme=dark]{color-scheme:dark;--bg: #111418;--panel: #1b1e23;--panel-2: #20242a;--ink: #e6eaee;--ink-2: #b9c2ca;--muted: #919ca7;--line: #2d333a;--line-strong: #414953;--grid: #272c32;--accent: #6cc3d3;--accent-hover: #8dd3e0;--accent-ink: #08262d;--accent-soft: #173239;--accent-text: #8dd3e0;--focus: #8dd3e0;--good: #5fcf98;--good-soft: #15302a;--warn: #e9b44c;--warn-soft: #33290f;--bad: #f08a82;--bad-soft: #3a1c1b;--tooltip-bg: #e6eaee;--tooltip-ink: #111418;--shadow: 0 1px 2px rgba(0, 0, 0, .3);--s1: #3987e5;--s2: #d95926;--s3: #199e70;--s4: #c98500;--s5: #d55181;--s6: #008300;--s7: #9085e9;--s8: #e66767;--s-other: #6f7a85;--dot-empty: #2b3137}*,*:before,*:after{box-sizing:border-box}html{-webkit-text-size-adjust:100%}body{margin:0;background:var(--bg);color:var(--ink);font-family:var(--font);font-size:15px;line-height:1.55;overflow-x:hidden}h1,h2,h3,h4{margin:0;line-height:1.25;font-weight:600;letter-spacing:-.01em}h1{font-size:28px}h2{font-size:20px}h3{font-size:16px}h4{font-size:14px}p{margin:0}a{color:var(--accent-text);text-underline-offset:2px}:focus-visible{outline:2px solid var(--focus);outline-offset:2px;border-radius:4px}.wrap{max-width:1200px;margin:0 auto;padding:0 24px}@media(max-width:600px){.wrap{padding:0 16px}}.muted{color:var(--muted)}.small{font-size:13px}.tnum{font-variant-numeric:tabular-nums}.nowrap{white-space:nowrap}.break{overflow-wrap:anywhere}.stack{display:flex;flex-direction:column;gap:12px}.stack-lg{display:flex;flex-direction:column;gap:24px}.stack>*,.stack-lg>*{min-width:0}dl{margin:0}fieldset{border:0;margin:0;padding:0;min-width:0}legend{padding:0;margin-bottom:8px}.row{display:flex;gap:12px;align-items:center;flex-wrap:wrap}.row.end{justify-content:flex-end}.spacer{flex:1}.sr-only{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.panel{background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);padding:24px;min-width:0}.panel.flush{padding:0}.panel-head{display:flex;gap:12px;align-items:baseline;flex-wrap:wrap;margin-bottom:16px}.panel-head p{color:var(--muted);font-size:14px}.panel-head:last-child{margin-bottom:0}.panel.stack>.panel-head,.panel.stack-lg>.panel-head{margin-bottom:0}@media(max-width:600px){.panel{padding:16px}}.grid-2{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:20px}.grid-side{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:20px;align-items:start}@media(max-width:900px){.grid-2,.grid-side{grid-template-columns:minmax(0,1fr)}}label.field{display:block}.field>.label{display:block;font-size:13px;font-weight:600;color:var(--ink-2);margin-bottom:6px}.field>.hint{display:block;font-size:13px;color:var(--muted);margin-top:4px}input[type=text],input[type=number],input[type=search],input[type=password],input[type=url],select,textarea{font:inherit;font-size:14px;color:var(--ink);background:var(--panel);border:1px solid var(--line-strong);border-radius:var(--radius-sm);padding:8px 10px;width:100%;min-width:0}textarea{resize:vertical;line-height:1.5}input:focus,select:focus,textarea:focus{outline:2px solid var(--focus);outline-offset:-1px;border-color:transparent}input[type=number]{font-variant-numeric:tabular-nums}input[type=checkbox],input[type=radio]{accent-color:var(--accent);width:16px;height:16px;margin:0}.check{display:inline-flex;gap:8px;align-items:center;font-size:14px;cursor:pointer}.form-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:16px}.btn{font:inherit;text-decoration:none;font-size:14px;font-weight:600;display:inline-flex;align-items:center;justify-content:center;gap:8px;border-radius:var(--radius-sm);padding:8px 14px;border:1px solid var(--line-strong);background:var(--panel);color:var(--ink);cursor:pointer;white-space:nowrap;min-height:36px}.btn:hover{background:var(--panel-2)}.btn:disabled{opacity:.5;cursor:not-allowed}.btn.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-ink)}.btn.primary:hover:not(:disabled){background:var(--accent-hover);border-color:var(--accent-hover)}.btn.danger{color:var(--bad)}.btn.danger:hover:not(:disabled){background:var(--bad-soft)}.btn.ghost{border-color:transparent;background:transparent;color:var(--ink-2)}.btn.ghost:hover:not(:disabled){background:var(--panel-2)}.btn.small{font-size:13px;padding:4px 10px;min-height:30px}.btn.icon{padding:4px 8px;min-width:32px}.notice{border-radius:var(--radius-sm);padding:10px 14px;font-size:14px;border:1px solid transparent}.notice.error{background:var(--bad-soft);color:var(--bad);border-color:color-mix(in srgb,var(--bad) 30%,transparent)}.notice.warn{background:var(--warn-soft);color:var(--warn);border-color:color-mix(in srgb,var(--warn) 30%,transparent)}.notice.ok{background:var(--good-soft);color:var(--good);border-color:color-mix(in srgb,var(--good) 30%,transparent)}.notice.info{background:var(--accent-soft);color:var(--accent-text)}.notice p+p{margin-top:4px}.empty{text-align:center;padding:40px 16px;color:var(--muted)}.empty h3{color:var(--ink);margin-bottom:6px}.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;font-weight:600;line-height:1;padding:4px 8px;border-radius:999px;background:var(--panel-2);color:var(--ink-2);border:1px solid var(--line);white-space:nowrap}.pill.accent{background:var(--accent-soft);color:var(--accent-text);border-color:transparent}.pill.good{background:var(--good-soft);color:var(--good);border-color:transparent}.pill.warn{background:var(--warn-soft);color:var(--warn);border-color:transparent}.pill.bad{background:var(--bad-soft);color:var(--bad);border-color:transparent}.swatch{display:inline-block;width:10px;height:10px;border-radius:3px;flex:none}.linekey{display:inline-block;width:14px;height:2px;border-radius:2px;flex:none}.table-scroll{overflow-x:auto;-webkit-overflow-scrolling:touch;max-width:100%}table.data{border-collapse:collapse;width:100%;font-size:14px}table.data th,table.data td{padding:8px 12px;text-align:left;border-bottom:1px solid var(--line);vertical-align:top}table.data th{font-size:13px;font-weight:600;color:var(--muted);white-space:nowrap;background:var(--panel);position:sticky;top:0}table.data td.num,table.data th.num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}table.data tbody tr:hover td{background:var(--panel-2)}table.data tr:last-child td{border-bottom:0}.chart-box{overflow-x:auto;max-width:100%}.chart-box svg{display:block}.chart-tooltip{position:fixed;z-index:50;pointer-events:none;background:var(--tooltip-bg);color:var(--tooltip-ink);border-radius:8px;padding:8px 10px;font-size:13px;line-height:1.4;max-width:280px;box-shadow:0 6px 20px #0000002e}.chart-tooltip .tt-title{opacity:.75;margin-bottom:4px}.chart-tooltip .tt-row{display:flex;gap:8px;align-items:center}.chart-tooltip .tt-row strong{font-variant-numeric:tabular-nums}.legend{display:flex;flex-wrap:wrap;gap:6px 16px;font-size:13px;color:var(--ink-2)}.legend span{display:inline-flex;gap:6px;align-items:center}.progress{height:6px;border-radius:999px;background:var(--grid);overflow:hidden}.progress>div{height:100%;background:var(--accent);border-radius:999px;transition:width .4s ease}.seg{display:inline-flex;border:1px solid var(--line-strong);border-radius:var(--radius-sm);overflow:hidden}.seg button{font:inherit;font-size:13px;background:var(--panel);color:var(--ink-2);border:0;padding:5px 10px;cursor:pointer}.seg button+button{border-left:1px solid var(--line-strong)}.seg button[aria-pressed=true]{background:var(--accent-soft);color:var(--accent-text);font-weight:600}.caveat{font-size:13px;color:var(--muted)}@media(prefers-reduced-motion:reduce){*,*:before,*:after{transition:none!important;animation:none!important}} diff --git a/jevfish/web/dist/assets/index-BX2Ou-8v.js b/jevfish/web/dist/assets/index-BX2Ou-8v.js new file mode 100644 index 0000000000..a1eab470cc --- /dev/null +++ b/jevfish/web/dist/assets/index-BX2Ou-8v.js @@ -0,0 +1,63 @@ +(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const l of document.querySelectorAll('link[rel="modulepreload"]'))s(l);new MutationObserver(l=>{for(const r of l)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&s(o)}).observe(document,{childList:!0,subtree:!0});function n(l){const r={};return l.integrity&&(r.integrity=l.integrity),l.referrerPolicy&&(r.referrerPolicy=l.referrerPolicy),l.crossOrigin==="use-credentials"?r.credentials="include":l.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function s(l){if(l.ep)return;l.ep=!0;const r=n(l);fetch(l.href,r)}})();function yo(e){const t=Object.create(null);for(const n of e.split(","))t[n]=1;return n=>n in t}const Ge={},is=[],tn=()=>{},za=()=>!1,Gl=e=>e.charCodeAt(0)===111&&e.charCodeAt(1)===110&&(e.charCodeAt(2)>122||e.charCodeAt(2)<97),Wl=e=>e.startsWith("onUpdate:"),ut=Object.assign,bo=(e,t)=>{const n=e.indexOf(t);n>-1&&e.splice(n,1)},rd=Object.prototype.hasOwnProperty,Ve=(e,t)=>rd.call(e,t),ke=Array.isArray,Pn=e=>ol(e)==="[object Map]",hn=e=>ol(e)==="[object Set]",yi=e=>ol(e)==="[object Date]",Te=e=>typeof e=="function",Qe=e=>typeof e=="string",sn=e=>typeof e=="symbol",ze=e=>e!==null&&typeof e=="object",qa=e=>(ze(e)||Te(e))&&Te(e.then)&&Te(e.catch),Ha=Object.prototype.toString,ol=e=>Ha.call(e),od=e=>ol(e).slice(8,-1),Ga=e=>ol(e)==="[object Object]",_o=e=>Qe(e)&&e!=="NaN"&&e[0]!=="-"&&""+parseInt(e,10)===e,js=yo(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),Kl=e=>{const t=Object.create(null);return(n=>t[n]||(t[n]=e(n)))},id=/-\w/g,Tt=Kl(e=>e.replace(id,t=>t.slice(1).toUpperCase())),ad=/\B([A-Z])/g,Yn=Kl(e=>e.replace(ad,"-$1").toLowerCase()),Yl=Kl(e=>e.charAt(0).toUpperCase()+e.slice(1)),xr=Kl(e=>e?`on${Yl(e)}`:""),Zt=(e,t)=>!Object.is(e,t),Al=(e,...t)=>{for(let n=0;n{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:s,value:n})},Jl=e=>{const t=parseFloat(e);return isNaN(t)?e:t};let bi;const Xl=()=>bi||(bi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{});function We(e){if(ke(e)){const t={};for(let n=0;n{if(n){const s=n.split(cd);s.length>1&&(t[s[0].trim()]=s[1].trim())}}),t}function He(e){let t="";if(Qe(e))t=e;else if(ke(e))for(let n=0;nmn(n,t))}const Ya=e=>!!(e&&e.__v_isRef===!0),y=e=>Qe(e)?e:e==null?"":ke(e)||ze(e)&&(e.toString===Ha||!Te(e.toString))?Ya(e)?y(e.value):JSON.stringify(e,Ja,2):String(e),Ja=(e,t)=>Ya(t)?Ja(e,t.value):Pn(t)?{[`Map(${t.size})`]:[...t.entries()].reduce((n,[s,l],r)=>(n[$r(s,r)+" =>"]=l,n),{})}:hn(t)?{[`Set(${t.size})`]:[...t.values()].map(n=>$r(n))}:sn(t)?$r(t):ze(t)&&!ke(t)&&!Ga(t)?String(t):t,$r=(e,t="")=>{var n;return sn(e)?`Symbol(${(n=e.description)!=null?n:t})`:e};let at;class gd{constructor(t=!1){this.detached=t,this._active=!0,this._on=0,this.effects=[],this.cleanups=[],this._isPaused=!1,this._warnOnRun=!0,this.__v_skip=!0,!t&&at&&(at.active?(this.parent=at,this.index=(at.scopes||(at.scopes=[])).push(this)-1):(this._active=!1,this._warnOnRun=!1))}get active(){return this._active}pause(){if(this._active){this._isPaused=!0;let t,n;if(this.scopes){const s=this.scopes.slice();for(t=0,n=s.length;t0&&--this._on===0){if(at===this)at=this.prevScope;else{let t=at;for(;t;){if(t.prevScope===this){t.prevScope=this.prevScope;break}t=t.prevScope}}this.prevScope=void 0}}stop(t){if(this._active){this._active=!1;let n,s;for(n=0,s=this.effects.length;n0)return;if(Vs){let t=Vs;for(Vs=void 0;t;){const n=t.next;t.next=void 0,t.flags&=-9,t=n}}let e;for(;Us;){let t=Us;for(Us=void 0;t;){const n=t.next;if(t.next=void 0,t.flags&=-9,t.flags&1)try{t.trigger()}catch(s){e||(e=s)}t=n}}if(e)throw e}function eu(e){for(let t=e.deps;t;t=t.nextDep)t.version=-1,t.prevActiveLink=t.dep.activeLink,t.dep.activeLink=t}function tu(e){let t,n=e.depsTail,s=n;for(;s;){const l=s.prevDep;s.version===-1?(s===n&&(n=l),$o(s),yd(s)):t=s,s.dep.activeLink=s.prevActiveLink,s.prevActiveLink=void 0,s=l}e.deps=t,e.depsTail=n}function Hr(e){for(let t=e.deps;t;t=t.nextDep)if(t.dep.version!==t.version||t.dep.computed&&(nu(t.dep.computed)||t.dep.version!==t.version))return!0;return!!e._dirty}function nu(e){if(e.flags&4&&!(e.flags&16)||(e.flags&=-17,e.globalVersion===Ys)||(e.globalVersion=Ys,!e.isSSR&&e.flags&128&&(!e.deps&&!e._dirty||!Hr(e))))return;e.flags|=2;const t=e.dep,n=Ye,s=Ut;Ye=e,Ut=!0;try{eu(e);const l=e.fn(e._value);(t.version===0||Zt(l,e._value))&&(e.flags|=128,e._value=l,t.version++)}catch(l){throw t.version++,l}finally{Ye=n,Ut=s,tu(e),e.flags&=-3}}function $o(e,t=!1){const{dep:n,prevSub:s,nextSub:l}=e;if(s&&(s.nextSub=l,e.prevSub=void 0),l&&(l.prevSub=s,e.nextSub=void 0),n.subs===e&&(n.subs=s,!s&&n.computed)){n.computed.flags&=-5;for(let r=n.computed.deps;r;r=r.nextDep)$o(r,!0)}!t&&!--n.sc&&n.map&&n.map.delete(n.key)}function yd(e){const{prevDep:t,nextDep:n}=e;t&&(t.nextDep=n,e.prevDep=void 0),n&&(n.prevDep=t,e.nextDep=void 0)}let Ut=!0;const su=[];function gn(){su.push(Ut),Ut=!1}function vn(){const e=su.pop();Ut=e===void 0?!0:e}function ki(e){const{cleanup:t}=e;if(e.cleanup=void 0,t){const n=Ye;Ye=void 0;try{t()}finally{Ye=n}}}let Ys=0;class bd{constructor(t,n){this.sub=t,this.dep=n,this.version=n.version,this.nextDep=this.prevDep=this.nextSub=this.prevSub=this.prevActiveLink=void 0}}class So{constructor(t){this.computed=t,this.version=0,this.activeLink=void 0,this.subs=void 0,this.map=void 0,this.key=void 0,this.sc=0,this.__v_skip=!0}track(t){if(!Ye||!Ut||Ye===this.computed)return;let n=this.activeLink;if(n===void 0||n.sub!==Ye)n=this.activeLink=new bd(Ye,this),Ye.deps?(n.prevDep=Ye.depsTail,Ye.depsTail.nextDep=n,Ye.depsTail=n):Ye.deps=Ye.depsTail=n,lu(n);else if(n.version===-1&&(n.version=this.version,n.nextDep)){const s=n.nextDep;s.prevDep=n.prevDep,n.prevDep&&(n.prevDep.nextDep=s),n.prevDep=Ye.depsTail,n.nextDep=void 0,Ye.depsTail.nextDep=n,Ye.depsTail=n,Ye.deps===n&&(Ye.deps=s)}return n}trigger(t){this.version++,Ys++,this.notify(t)}notify(t){wo();try{for(let n=this.subs;n;n=n.prevSub)n.sub.notify()&&n.sub.dep.notify()}finally{xo()}}}function lu(e){if(e.dep.sc++,e.sub.flags&4){const t=e.dep.computed;if(t&&!e.dep.subs){t.flags|=20;for(let s=t.deps;s;s=s.nextDep)lu(s)}const n=e.dep.subs;n!==e&&(e.prevSub=n,n&&(n.nextSub=e)),e.dep.subs=e}}const Gr=new WeakMap,Bn=Symbol(""),Wr=Symbol(""),Js=Symbol("");function ft(e,t,n){if(Ut&&Ye){let s=Gr.get(e);s||Gr.set(e,s=new Map);let l=s.get(n);l||(s.set(n,l=new So),l.map=s,l.key=n),l.track()}}function fn(e,t,n,s,l,r){const o=Gr.get(e);if(!o){Ys++;return}const a=u=>{u&&u.trigger()};if(wo(),t==="clear")o.forEach(a);else{const u=ke(e),d=u&&_o(n);if(u&&n==="length"){const c=Number(s);o.forEach((f,p)=>{(p==="length"||p===Js||!sn(p)&&p>=c)&&a(f)})}else switch((n!==void 0||o.has(void 0))&&a(o.get(n)),d&&a(o.get(Js)),t){case"add":u?d&&a(o.get("length")):(a(o.get(Bn)),Pn(e)&&a(o.get(Wr)));break;case"delete":u||(a(o.get(Bn)),Pn(e)&&a(o.get(Wr)));break;case"set":Pn(e)&&a(o.get(Bn));break}}xo()}function ns(e){const t=Ue(e);return t===e?t:(ft(t,"iterate",Js),Lt(e)?t:t.map(Bt))}function Zl(e){return ft(e=Ue(e),"iterate",Js),e}function Jt(e,t){return yn(e)?ds(zn(e)?Bt(t):t):Bt(t)}const _d={__proto__:null,[Symbol.iterator](){return Tr(this,Symbol.iterator,e=>Jt(this,e))},concat(...e){return ns(this).concat(...e.map(t=>ke(t)?ns(t):t))},entries(){return Tr(this,"entries",e=>(e[1]=Jt(this,e[1]),e))},every(e,t){return an(this,"every",e,t,void 0,arguments)},filter(e,t){return an(this,"filter",e,t,n=>n.map(s=>Jt(this,s)),arguments)},find(e,t){return an(this,"find",e,t,n=>Jt(this,n),arguments)},findIndex(e,t){return an(this,"findIndex",e,t,void 0,arguments)},findLast(e,t){return an(this,"findLast",e,t,n=>Jt(this,n),arguments)},findLastIndex(e,t){return an(this,"findLastIndex",e,t,void 0,arguments)},forEach(e,t){return an(this,"forEach",e,t,void 0,arguments)},includes(...e){return Er(this,"includes",e)},indexOf(...e){return Er(this,"indexOf",e)},join(e){return ns(this).join(e)},lastIndexOf(...e){return Er(this,"lastIndexOf",e)},map(e,t){return an(this,"map",e,t,void 0,arguments)},pop(){return ws(this,"pop")},push(...e){return ws(this,"push",e)},reduce(e,...t){return wi(this,"reduce",e,t)},reduceRight(e,...t){return wi(this,"reduceRight",e,t)},shift(){return ws(this,"shift")},some(e,t){return an(this,"some",e,t,void 0,arguments)},splice(...e){return ws(this,"splice",e)},toReversed(){return ns(this).toReversed()},toSorted(e){return ns(this).toSorted(e)},toSpliced(...e){return ns(this).toSpliced(...e)},unshift(...e){return ws(this,"unshift",e)},values(){return Tr(this,"values",e=>Jt(this,e))}};function Tr(e,t,n){const s=Zl(e),l=s[t]();return s!==e&&!Lt(e)&&(l._next=l.next,l.next=()=>{const r=l._next();return r.done||(r.value=n(r.value)),r}),l}const kd=Array.prototype;function an(e,t,n,s,l,r){const o=Zl(e),a=o!==e&&!Lt(e),u=o[t];if(u!==kd[t]){const f=u.apply(e,r);return a?Bt(f):f}let d=n;o!==e&&(a?d=function(f,p){return n.call(this,Jt(e,f),p,e)}:n.length>2&&(d=function(f,p){return n.call(this,f,p,e)}));const c=u.call(o,d,s);return a&&l?l(c):c}function wi(e,t,n,s){const l=Zl(e),r=l!==e&&!Lt(e);let o=n,a=!1;l!==e&&(r?(a=s.length===0,o=function(d,c,f){return a&&(a=!1,d=Jt(e,d)),n.call(this,d,Jt(e,c),f,e)}):n.length>3&&(o=function(d,c,f){return n.call(this,d,c,f,e)}));const u=l[t](o,...s);return a?Jt(e,u):u}function Er(e,t,n){const s=Ue(e);ft(s,"iterate",Js);const l=s[t](...n);return(l===-1||l===!1)&&Ao(n[0])?(n[0]=Ue(n[0]),s[t](...n)):l}function ws(e,t,n=[]){gn(),wo();const s=Ue(e)[t].apply(e,n);return xo(),vn(),s}const wd=yo("__proto__,__v_isRef,__isVue"),ru=new Set(Object.getOwnPropertyNames(Symbol).filter(e=>e!=="arguments"&&e!=="caller").map(e=>Symbol[e]).filter(sn));function xd(e){sn(e)||(e=String(e));const t=Ue(this);return ft(t,"has",e),t.hasOwnProperty(e)}class ou{constructor(t=!1,n=!1){this._isReadonly=t,this._isShallow=n}get(t,n,s){if(n==="__v_skip")return t.__v_skip;const l=this._isReadonly,r=this._isShallow;if(n==="__v_isReactive")return!l;if(n==="__v_isReadonly")return l;if(n==="__v_isShallow")return r;if(n==="__v_raw")return s===(l?r?Nd:cu:r?uu:au).get(t)||Object.getPrototypeOf(t)===Object.getPrototypeOf(s)?t:void 0;const o=ke(t);if(!l){let u;if(o&&(u=_d[n]))return u;if(n==="hasOwnProperty")return xd}const a=Reflect.get(t,n,ht(t)?t:s);if((sn(n)?ru.has(n):wd(n))||(l||ft(t,"get",n),r))return a;if(ht(a)){const u=o&&_o(n)?a:a.value;return l&&ze(u)?Yr(u):u}return ze(a)?l?Yr(a):Hn(a):a}}class iu extends ou{constructor(t=!1){super(!1,t)}set(t,n,s,l){let r=t[n];const o=ke(t)&&_o(n);if(!this._isShallow){const d=yn(r);if(!Lt(s)&&!yn(s)&&(r=Ue(r),s=Ue(s)),!o&&ht(r)&&!ht(s))return d||(r.value=s),!0}const a=o?Number(n)e,_l=e=>Reflect.getPrototypeOf(e);function Ad(e,t,n){return function(...s){const l=this.__v_raw,r=Ue(l),o=Pn(r),a=e==="entries"||e===Symbol.iterator&&o,u=e==="keys"&&o,d=l[e](...s),c=n?Kr:t?ds:Bt;return!t&&ft(r,"iterate",u?Wr:Bn),ut(Object.create(d),{next(){const{value:f,done:p}=d.next();return p?{value:f,done:p}:{value:a?[c(f[0]),c(f[1])]:c(f),done:p}}})}}function kl(e){return function(...t){return e==="delete"?!1:e==="clear"?void 0:this}}function Rd(e,t){const n={get(l){const r=this.__v_raw,o=Ue(r),a=Ue(l);e||(Zt(l,a)&&ft(o,"get",l),ft(o,"get",a));const{has:u}=_l(o),d=t?Kr:e?ds:Bt;if(u.call(o,l))return d(r.get(l));if(u.call(o,a))return d(r.get(a));r!==o&&r.get(l)},get size(){const l=this.__v_raw;return!e&&ft(Ue(l),"iterate",Bn),l.size},has(l){const r=this.__v_raw,o=Ue(r),a=Ue(l);return e||(Zt(l,a)&&ft(o,"has",l),ft(o,"has",a)),l===a?r.has(l):r.has(l)||r.has(a)},forEach(l,r){const o=this,a=o.__v_raw,u=Ue(a),d=t?Kr:e?ds:Bt;return!e&&ft(u,"iterate",Bn),a.forEach((c,f)=>l.call(r,d(c),d(f),o))}};return ut(n,e?{add:kl("add"),set:kl("set"),delete:kl("delete"),clear:kl("clear")}:{add(l){const r=Ue(this),o=_l(r),a=Ue(l),u=!t&&!Lt(l)&&!yn(l)?a:l;return o.has.call(r,u)||Zt(l,u)&&o.has.call(r,l)||Zt(a,u)&&o.has.call(r,a)||(r.add(u),fn(r,"add",u,u)),this},set(l,r){!t&&!Lt(r)&&!yn(r)&&(r=Ue(r));const o=Ue(this),{has:a,get:u}=_l(o);let d=a.call(o,l);d||(l=Ue(l),d=a.call(o,l));const c=u.call(o,l);return o.set(l,r),d?Zt(r,c)&&fn(o,"set",l,r):fn(o,"add",l,r),this},delete(l){const r=Ue(this),{has:o,get:a}=_l(r);let u=o.call(r,l);u||(l=Ue(l),u=o.call(r,l)),a&&a.call(r,l);const d=r.delete(l);return u&&fn(r,"delete",l,void 0),d},clear(){const l=Ue(this),r=l.size!==0,o=l.clear();return r&&fn(l,"clear",void 0,void 0),o}}),["keys","values","entries",Symbol.iterator].forEach(l=>{n[l]=Ad(l,e,t)}),n}function To(e,t){const n=Rd(e,t);return(s,l,r)=>l==="__v_isReactive"?!e:l==="__v_isReadonly"?e:l==="__v_raw"?s:Reflect.get(Ve(n,l)&&l in s?n:s,l,r)}const Cd={get:To(!1,!1)},Od={get:To(!1,!0)},Pd={get:To(!0,!1)};const au=new WeakMap,uu=new WeakMap,cu=new WeakMap,Nd=new WeakMap;function Id(e){switch(e){case"Object":case"Array":return 1;case"Map":case"Set":case"WeakMap":case"WeakSet":return 2;default:return 0}}function Hn(e){return yn(e)?e:Eo(e,!1,Sd,Cd,au)}function du(e){return Eo(e,!1,Ed,Od,uu)}function Yr(e){return Eo(e,!0,Td,Pd,cu)}function Eo(e,t,n,s,l){if(!ze(e)||e.__v_raw&&!(t&&e.__v_isReactive)||e.__v_skip||!Object.isExtensible(e))return e;const r=l.get(e);if(r)return r;const o=Id(od(e));if(o===0)return e;const a=new Proxy(e,o===2?s:n);return l.set(e,a),a}function zn(e){return yn(e)?zn(e.__v_raw):!!(e&&e.__v_isReactive)}function yn(e){return!!(e&&e.__v_isReadonly)}function Lt(e){return!!(e&&e.__v_isShallow)}function Ao(e){return e?!!e.__v_raw:!1}function Ue(e){const t=e&&e.__v_raw;return t?Ue(t):e}function Md(e){return!Ve(e,"__v_skip")&&Object.isExtensible(e)&&Wa(e,"__v_skip",!0),e}const Bt=e=>ze(e)?Hn(e):e,ds=e=>ze(e)?Yr(e):e;function ht(e){return e?e.__v_isRef===!0:!1}function J(e){return fu(e,!1)}function fs(e){return fu(e,!0)}function fu(e,t){return ht(e)?e:new Ld(e,t)}class Ld{constructor(t,n){this.dep=new So,this.__v_isRef=!0,this.__v_isShallow=!1,this._rawValue=n?t:Ue(t),this._value=n?t:Bt(t),this.__v_isShallow=n}get value(){return this.dep.track(),this._value}set value(t){const n=this._rawValue,s=this.__v_isShallow||Lt(t)||yn(t);t=s?t:Ue(t),Zt(t,n)&&(this._rawValue=t,this._value=s?t:Bt(t),this.dep.trigger())}}function de(e){return ht(e)?e.value:e}const Dd={get:(e,t,n)=>t==="__v_raw"?e:de(Reflect.get(e,t,n)),set:(e,t,n,s)=>{const l=e[t];return ht(l)&&!ht(n)?(l.value=n,!0):Reflect.set(e,t,n,s)}};function pu(e){return zn(e)?e:new Proxy(e,Dd)}class Fd{constructor(t,n,s){this.fn=t,this.setter=n,this._value=void 0,this.dep=new So(this),this.__v_isRef=!0,this.deps=void 0,this.depsTail=void 0,this.flags=16,this.globalVersion=Ys-1,this.next=void 0,this.effect=this,this.__v_isReadonly=!n,this.isSSR=s}notify(){if(this.flags|=16,!(this.flags&8)&&Ye!==this)return Qa(this,!0),!0}get value(){const t=this.dep.track();return nu(this),t&&(t.version=this.dep.version),this._value}set value(t){this.setter&&this.setter(t)}}function jd(e,t,n=!1){let s,l;return Te(e)?s=e:(s=e.get,l=e.set),new Fd(s,l,n)}const wl={},Ol=new WeakMap;let Fn;function Ud(e,t=!1,n=Fn){if(n){let s=Ol.get(n);s||Ol.set(n,s=[]),s.push(e)}}function Vd(e,t,n=Ge){const{immediate:s,deep:l,once:r,scheduler:o,augmentJob:a,call:u}=n,d=O=>l?O:Lt(O)||l===!1||l===0?pn(O,1):pn(O);let c,f,p,g,N=!1,x=!1;if(ht(e)?(f=()=>e.value,N=Lt(e)):zn(e)?(f=()=>d(e),N=!0):ke(e)?(x=!0,N=e.some(O=>zn(O)||Lt(O)),f=()=>e.map(O=>{if(ht(O))return O.value;if(zn(O))return d(O);if(Te(O))return u?u(O,2):O()})):Te(e)?t?f=u?()=>u(e,2):e:f=()=>{if(p){gn();try{p()}finally{vn()}}const O=Fn;Fn=c;try{return u?u(e,3,[g]):e(g)}finally{Fn=O}}:f=tn,t&&l){const O=f,C=l===!0?1/0:l;f=()=>pn(O(),C)}const R=vd(),A=()=>{c.stop(),R&&R.active&&bo(R.effects,c)};if(r&&t){const O=t;t=(...C)=>{const D=O(...C);return A(),D}}let P=x?new Array(e.length).fill(wl):wl;const j=O=>{if(!(!(c.flags&1)||!c.dirty&&!O))if(t){const C=c.run();if(O||l||N||(x?C.some((D,k)=>Zt(D,P[k])):Zt(C,P))){p&&p();const D=Fn;Fn=c;try{const k=[C,P===wl?void 0:x&&P[0]===wl?[]:P,g];P=C,u?u(t,3,k):t(...k)}finally{Fn=D}}}else c.run()};return a&&a(j),c=new Xa(f),c.scheduler=o?()=>o(j,!1):j,g=O=>Ud(O,!1,c),p=c.onStop=()=>{const O=Ol.get(c);if(O){if(u)u(O,4);else for(const C of O)C();Ol.delete(c)}},t?s?j(!0):P=c.run():o?o(j.bind(null,!0),!0):c.run(),A.pause=c.pause.bind(c),A.resume=c.resume.bind(c),A.stop=A,A}function pn(e,t=1/0,n){if(t<=0||!ze(e)||e.__v_skip||(n=n||new Map,(n.get(e)||0)>=t))return e;if(n.set(e,t),t--,ht(e))pn(e.value,t,n);else if(ke(e))for(let s=0;s{pn(s,t,n)});else if(Ga(e)){for(const s in e)pn(e[s],t,n);for(const s of Object.getOwnPropertySymbols(e))Object.prototype.propertyIsEnumerable.call(e,s)&&pn(e[s],t,n)}return e}function il(e,t,n,s){try{return s?e(...s):e()}catch(l){Ql(l,t,n)}}function zt(e,t,n,s){if(Te(e)){const l=il(e,t,n,s);return l&&qa(l)&&l.catch(r=>{Ql(r,t,n)}),l}if(ke(e)){const l=[];for(let r=0;r>>1,l=wt[s],r=Xs(l);r=Xs(n)?wt.push(e):wt.splice(zd(t),0,e),e.flags|=1,mu()}}function mu(){Pl||(Pl=hu.then(vu))}function qd(e){if(!ke(e))En&&e.id===-1?En.splice(ls+1,0,e):e.flags&1||(as.push(e),e.flags|=1);else for(let t=0;tXs(n)-Xs(s));if(as.length=0,En){for(let n=0;ne.id==null?e.flags&2?-1:1/0:e.id;function vu(e){try{for(Yt=0;Yt{s._d&&Ll(-1);const r=Nl(t),o=qn.length;let a;try{a=e(...l)}finally{for(let u=qn.length;u>o;u--)qu();Nl(r),s._d&&Ll(1)}return a};return s._n=!0,s._c=!0,s._d=!0,s}function Se(e,t){if(Nt===null)return e;const n=rr(Nt),s=e.dirs||(e.dirs=[]);for(let l=0;l1)return n&&Te(t)?t.call(s&&s.proxy):t}}const Hd=Symbol.for("v-scx"),Gd=()=>Dt(Hd);function Je(e,t,n){return bu(e,t,n)}function bu(e,t,n=Ge){const{immediate:s,deep:l,flush:r,once:o}=n,a=ut({},n),u=t&&s||!t&&r!=="post";let d;if(el){if(r==="sync"){const g=Gd();d=g.__watcherHandles||(g.__watcherHandles=[])}else if(!u){const g=()=>{};return g.stop=tn,g.resume=tn,g.pause=tn,g}}const c=pt;a.call=(g,N,x)=>zt(g,c,N,x);let f=!1;r==="post"?a.scheduler=g=>{_t(g,c&&c.suspense)}:r!=="sync"&&(f=!0,a.scheduler=(g,N)=>{N?g():Ro(g)}),a.augmentJob=g=>{t&&(g.flags|=4),f&&(g.flags|=2,c&&(g.id=c.uid,g.i=c))};const p=Vd(e,t,a);return el&&(d?d.push(p):u&&p()),p}function Wd(e,t,n){const s=this.proxy,l=Qe(e)?e.includes(".")?_u(s,e):()=>s[e]:e.bind(s,s);let r;Te(t)?r=t:(r=t.handler,n=t);const o=ul(this),a=bu(l,r.bind(s),n);return o(),a}function _u(e,t){const n=t.split(".");return()=>{let s=e;for(let l=0;le.__isTeleport,Un=e=>e&&(e.disabled||e.disabled===""),Kd=e=>e&&(e.defer||e.defer===""),$i=e=>typeof SVGElement<"u"&&e instanceof SVGElement,Si=e=>typeof MathMLElement=="function"&&e instanceof MathMLElement,Jr=(e,t)=>{const n=e&&e.to;return Qe(n)?t?t(n):null:n},Yd={name:"Teleport",__isTeleport:!0,process(e,t,n,s,l,r,o,a,u,d){const{mc:c,pc:f,pbc:p,o:{insert:g,querySelector:N,createText:x,createComment:R,parentNode:A}}=d,P=Un(t.props);let{dynamicChildren:j}=t;const O=(k,_,w)=>{k.shapeFlag&16&&c(k.children,_,w,l,r,o,a,u)},C=(k=t)=>{const _=Un(k.props),w=k.target=Jr(k.props,N),E=Xr(w,k,x,g);w&&(o!=="svg"&&$i(w)?o="svg":o!=="mathml"&&Si(w)&&(o="mathml"),l&&l.isCE&&(l.ce._teleportTargets||(l.ce._teleportTargets=new Set)).add(w),_||(O(k,w,E),Ps(k,!1)))},D=k=>{const _=()=>{if(Tn.get(k)===_){if(Tn.delete(k),Un(k.props)){const w=A(k.el)||n;O(k,w,k.anchor),Ps(k,!0)}C(k)}};Tn.set(k,_),_t(_,r)};if(e==null){const k=t.el=x(""),_=t.anchor=x("");if(g(k,n,s),g(_,n,s),Kd(t.props)||r&&r.pendingBranch){D(t);return}P&&(O(t,n,_),Ps(t,!0)),C()}else{t.el=e.el;const k=t.anchor=e.anchor,_=Tn.get(e);if(_){_.flags|=8,Tn.delete(e),D(t);return}t.targetStart=e.targetStart;const w=t.target=e.target,E=t.targetAnchor=e.targetAnchor,S=Un(e.props),I=S?n:w,V=S?k:E;if(o==="svg"||$i(w)?o="svg":(o==="mathml"||Si(w))&&(o="mathml"),j?(p(e.dynamicChildren,j,I,l,r,o,a),Io(e,t,!0)):u||f(e,t,I,V,l,r,o,a,!1),P)S?t.props&&e.props&&t.props.to!==e.props.to&&(t.props.to=e.props.to):xl(t,n,k,d,1);else if((t.props&&t.props.to)!==(e.props&&e.props.to)){const z=Jr(t.props,N);z&&(t.target=z,xl(t,z,null,d,0))}else S&&xl(t,w,E,d,1);Ps(t,P)}},remove(e,t,n,{um:s,o:{remove:l}},r){const{shapeFlag:o,children:a,anchor:u,targetStart:d,targetAnchor:c,target:f,props:p}=e,g=Un(p),N=r||!g,x=Tn.get(e);if(x&&(x.flags|=8,Tn.delete(e)),f&&(l(d),l(c)),r&&l(u),!x&&(g||f)&&o&16)for(let R=0;R1){for(const n of e)if(n.type!==bn){t=n;break}}return t}function xu(e){if(!Oo(e))return tr(e.type)&&e.children?Xd(e.children):e;if(e.component)return e.component.subTree;const{shapeFlag:t,children:n}=e;if(n){if(t&16)return n[0];if(t&32&&Te(n.default))return n.default()}}function Co(e,t){if(e.shapeFlag&6&&e.component){e.transition=t;const n=e.component.subTree;Co(tr(n.type)&&xu(n)||n,t)}else e.shapeFlag&128?(e.ssContent.transition=t.clone(e.ssContent),e.ssFallback.transition=t.clone(e.ssFallback)):e.transition=t}function $u(e,t){return Te(e)?ut({name:e.name},t,{setup:e}):e}function Su(e){e.ids=[e.ids[0]+e.ids[2]+++"-",0,0]}function Ti(e,t){let n;return!!((n=Object.getOwnPropertyDescriptor(e,t))&&!n.configurable)}const Il=new WeakMap;function zs(e,t,n,s,l=!1){if(ke(e)){e.forEach((x,R)=>zs(x,t&&(ke(t)?t[R]:t),n,s,l));return}if(qs(s)&&!l){s.shapeFlag&512&&s.type.__asyncResolved&&s.component.subTree.component&&zs(e,t,n,s.component.subTree);return}const r=s.shapeFlag&4?rr(s.component):s.el,o=l?null:r,{i:a,r:u}=e,d=t&&t.r,c=a.refs===Ge?a.refs={}:a.refs,f=a.setupState,p=Ue(f),g=f===Ge?za:x=>Ti(c,x)?!1:Ve(p,x),N=(x,R)=>!(R&&Ti(c,R));if(d!=null&&d!==u){if(Ei(t),Qe(d))c[d]=null,g(d)&&(f[d]=null);else if(ht(d)){const x=t;N(d,x.k)&&(d.value=null),x.k&&(c[x.k]=null)}}if(Te(u))il(u,a,12,[o,c]);else{const x=Qe(u),R=ht(u);if(x||R){const A=()=>{if(e.f){const P=x?g(u)?f[u]:c[u]:N()||!e.k?u.value:c[e.k];if(l)ke(P)&&bo(P,r);else if(ke(P))P.includes(r)||P.push(r);else if(x)c[u]=[r],g(u)&&(f[u]=c[u]);else{const j=[r];N(u,e.k)&&(u.value=j),e.k&&(c[e.k]=j)}}else x?(c[u]=o,g(u)&&(f[u]=o)):R&&(N(u,e.k)&&(u.value=o),e.k&&(c[e.k]=o))};if(o){const P=()=>{A(),Il.delete(e)};P.id=-1,Il.set(e,P),_t(P,n)}else Ei(e),A()}}}function Ei(e){const t=Il.get(e);t&&(t.flags|=8,Il.delete(e))}Xl().requestIdleCallback;Xl().cancelIdleCallback;const qs=e=>!!e.type.__asyncLoader,Oo=e=>e.type.__isKeepAlive;function Zd(e,t){Tu(e,"a",t)}function Qd(e,t){Tu(e,"da",t)}function Tu(e,t,n=pt){const s=e.__wdc||(e.__wdc=()=>{let l=n;for(;l;){if(l.isDeactivated)return;l=l.parent}return e()});if(nr(t,s,n),n){let l=n.parent;for(;l&&l.parent;)Oo(l.parent.vnode)&&ef(s,t,n,l),l=l.parent}}function ef(e,t,n,s){const l=nr(t,e,s,!0);Eu(()=>{bo(s[t],l)},n)}function nr(e,t,n=pt,s=!1){if(n){const l=n[e]||(n[e]=[]),r=t.__weh||(t.__weh=(...o)=>{gn();const a=ul(n),u=zt(t,n,e,o);return a(),vn(),u});return s?l.unshift(r):l.push(r),r}}const wn=e=>(t,n=pt)=>{(!el||e==="sp")&&nr(e,(...s)=>t(...s),n)},tf=wn("bm"),al=wn("m"),nf=wn("bu"),sf=wn("u"),Gn=wn("bum"),Eu=wn("um"),lf=wn("sp"),rf=wn("rtg"),of=wn("rtc");function af(e,t=pt){nr("ec",e,t)}const uf="components";function Nn(e,t){return df(uf,e,!0,t)||e}const cf=Symbol.for("v-ndc");function df(e,t,n=!0,s=!1){const l=Nt||pt;if(l){const r=l.type;{const a=Yf(r,!1);if(a&&(a===t||a===Tt(t)||a===Yl(Tt(t))))return r}const o=Ai(l[e]||r[e],t)||Ai(l.appContext[e],t);return!o&&s?r:o}}function Ai(e,t){return e&&(e[t]||e[Tt(t)]||e[Yl(Tt(t))])}function me(e,t,n,s){let l;const r=n,o=ke(e);if(o||Qe(e)){const a=o&&zn(e);let u=!1,d=!1;a&&(u=!Lt(e),d=yn(e),e=Zl(e)),l=new Array(e.length);for(let c=0,f=e.length;ct(a,u,void 0,r));else{const a=Object.keys(e);l=new Array(a.length);for(let u=0,d=a.length;ue?Wu(e)?rr(e):Zr(e.parent):null,Hs=ut(Object.create(null),{$:e=>e,$el:e=>e.vnode.el,$data:e=>e.data,$props:e=>e.props,$attrs:e=>e.attrs,$slots:e=>e.slots,$refs:e=>e.refs,$parent:e=>Zr(e.parent),$root:e=>Zr(e.root),$host:e=>e.ce,$emit:e=>e.emit,$options:e=>Ru(e),$forceUpdate:e=>e.f||(e.f=()=>{Ro(e.update)}),$nextTick:e=>e.n||(e.n=er.bind(e.proxy)),$watch:e=>Wd.bind(e)}),Rr=(e,t)=>e!==Ge&&!e.__isScriptSetup&&Ve(e,t),ff={get({_:e},t){if(t==="__v_skip")return!0;const{ctx:n,setupState:s,data:l,props:r,accessCache:o,type:a,appContext:u}=e;if(t[0]!=="$"){const p=o[t];if(p!==void 0)switch(p){case 1:return s[t];case 2:return l[t];case 4:return n[t];case 3:return r[t]}else{if(Rr(s,t))return o[t]=1,s[t];if(l!==Ge&&Ve(l,t))return o[t]=2,l[t];if(Ve(r,t))return o[t]=3,r[t];if(n!==Ge&&Ve(n,t))return o[t]=4,n[t];Qr&&(o[t]=0)}}const d=Hs[t];let c,f;if(d)return t==="$attrs"&&ft(e.attrs,"get",""),d(e);if((c=a.__cssModules)&&(c=c[t]))return c;if(n!==Ge&&Ve(n,t))return o[t]=4,n[t];if(f=u.config.globalProperties,Ve(f,t))return f[t]},set({_:e},t,n){const{data:s,setupState:l,ctx:r}=e;return Rr(l,t)?(l[t]=n,!0):s!==Ge&&Ve(s,t)?(s[t]=n,!0):Ve(e.props,t)||t[0]==="$"&&t.slice(1)in e?!1:(r[t]=n,!0)},has({_:{data:e,setupState:t,accessCache:n,ctx:s,appContext:l,props:r,type:o}},a){let u;return!!(n[a]||e!==Ge&&a[0]!=="$"&&Ve(e,a)||Rr(t,a)||Ve(r,a)||Ve(s,a)||Ve(Hs,a)||Ve(l.config.globalProperties,a)||(u=o.__cssModules)&&u[a])},defineProperty(e,t,n){return n.get!=null?e._.accessCache[t]=0:Ve(n,"value")&&this.set(e,t,n.value,null),Reflect.defineProperty(e,t,n)}};function Ri(e){return ke(e)?e.reduce((t,n)=>(t[n]=null,t),{}):e}let Qr=!0;function pf(e){const t=Ru(e),n=e.proxy,s=e.ctx;Qr=!1,t.beforeCreate&&Ci(t.beforeCreate,e,"bc");const{data:l,computed:r,methods:o,watch:a,provide:u,inject:d,created:c,beforeMount:f,mounted:p,beforeUpdate:g,updated:N,activated:x,deactivated:R,beforeDestroy:A,beforeUnmount:P,destroyed:j,unmounted:O,render:C,renderTracked:D,renderTriggered:k,errorCaptured:_,serverPrefetch:w,expose:E,inheritAttrs:S,components:I,directives:V,filters:z}=t;if(d&&hf(d,s,null),o)for(const F in o){const $=o[F];Te($)&&(s[F]=$.bind(n))}if(l){const F=l.call(n,n);ze(F)&&(e.data=Hn(F))}if(Qr=!0,r)for(const F in r){const $=r[F],W=Te($)?$.bind(n,n):Te($.get)?$.get.bind(n,n):tn,oe=!Te($)&&Te($.set)?$.set.bind(n):tn,te=K({get:W,set:oe});Object.defineProperty(s,F,{enumerable:!0,configurable:!0,get:()=>te.value,set:ee=>te.value=ee})}if(a)for(const F in a)Au(a[F],s,n,F);if(u){const F=Te(u)?u.call(n):u;Reflect.ownKeys(F).forEach($=>{Bs($,F[$])})}c&&Ci(c,e,"c");function le(F,$){ke($)?$.forEach(W=>F(W.bind(n))):$&&F($.bind(n))}if(le(tf,f),le(al,p),le(nf,g),le(sf,N),le(Zd,x),le(Qd,R),le(af,_),le(of,D),le(rf,k),le(Gn,P),le(Eu,O),le(lf,w),ke(E))if(E.length){const F=e.exposed||(e.exposed={});E.forEach($=>{Object.defineProperty(F,$,{get:()=>n[$],set:W=>n[$]=W,enumerable:!0})})}else e.exposed||(e.exposed={});C&&e.render===tn&&(e.render=C),S!=null&&(e.inheritAttrs=S),I&&(e.components=I),V&&(e.directives=V),w&&Su(e)}function hf(e,t,n=tn){ke(e)&&(e=eo(e));for(const s in e){const l=e[s];let r;ze(l)?"default"in l?r=Dt(l.from||s,l.default,!0):r=Dt(l.from||s):r=Dt(l),ht(r)?Object.defineProperty(t,s,{enumerable:!0,configurable:!0,get:()=>r.value,set:o=>r.value=o}):t[s]=r}}function Ci(e,t,n){zt(ke(e)?e.map(s=>s.bind(t.proxy)):e.bind(t.proxy),t,n)}function Au(e,t,n,s){let l=s.includes(".")?_u(n,s):()=>n[s];if(Qe(e)){const r=t[e];Te(r)&&Je(l,r)}else if(Te(e))Je(l,e.bind(n));else if(ze(e))if(ke(e))e.forEach(r=>Au(r,t,n,s));else{const r=Te(e.handler)?e.handler.bind(n):t[e.handler];Te(r)&&Je(l,r,e)}}function Ru(e){const t=e.type,{mixins:n,extends:s}=t,{mixins:l,optionsCache:r,config:{optionMergeStrategies:o}}=e.appContext,a=r.get(t);let u;return a?u=a:!l.length&&!n&&!s?u=t:(u={},l.length&&l.forEach(d=>Ml(u,d,o,!0)),Ml(u,t,o)),ze(t)&&r.set(t,u),u}function Ml(e,t,n,s=!1){const{mixins:l,extends:r}=t;r&&Ml(e,r,n,!0),l&&l.forEach(o=>Ml(e,o,n,!0));for(const o in t)if(!(s&&o==="expose")){const a=mf[o]||n&&n[o];e[o]=a?a(e[o],t[o]):t[o]}return e}const mf={data:Oi,props:Pi,emits:Pi,methods:Ns,computed:Ns,beforeCreate:bt,created:bt,beforeMount:bt,mounted:bt,beforeUpdate:bt,updated:bt,beforeDestroy:bt,beforeUnmount:bt,destroyed:bt,unmounted:bt,activated:bt,deactivated:bt,errorCaptured:bt,serverPrefetch:bt,components:Ns,directives:Ns,watch:vf,provide:Oi,inject:gf};function Oi(e,t){return t?e?function(){return ut(Te(e)?e.call(this,this):e,Te(t)?t.call(this,this):t)}:t:e}function gf(e,t){return Ns(eo(e),eo(t))}function eo(e){if(ke(e)){const t={};for(let n=0;nt==="modelValue"||t==="model-value"?e.modelModifiers:e[`${t}Modifiers`]||e[`${Tt(t)}Modifiers`]||e[`${Yn(t)}Modifiers`];function kf(e,t,...n){if(e.isUnmounted)return;const s=e.vnode.props||Ge;let l=n;const r=t.startsWith("update:"),o=r&&_f(s,t.slice(7));o&&(o.trim&&(l=n.map(c=>Qe(c)?c.trim():c)),o.number&&(l=l.map(Jl)));let a,u=s[a=xr(t)]||s[a=xr(Tt(t))];!u&&r&&(u=s[a=xr(Yn(t))]),u&&zt(u,e,6,l);const d=s[a+"Once"];if(d){if(!e.emitted)e.emitted={};else if(e.emitted[a])return;e.emitted[a]=!0,zt(d,e,6,l)}}const wf=new WeakMap;function Ou(e,t,n=!1){const s=n?wf:t.emitsCache,l=s.get(e);if(l!==void 0)return l;const r=e.emits;let o={},a=!1;if(!Te(e)){const u=d=>{const c=Ou(d,t,!0);c&&(a=!0,ut(o,c))};!n&&t.mixins.length&&t.mixins.forEach(u),e.extends&&u(e.extends),e.mixins&&e.mixins.forEach(u)}return!r&&!a?(ze(e)&&s.set(e,null),null):(ke(r)?r.forEach(u=>o[u]=null):ut(o,r),ze(e)&&s.set(e,o),o)}function sr(e,t){return!e||!Gl(t)?!1:(t=t.slice(2),t=t==="Once"?t:t.replace(/Once$/,""),Ve(e,t[0].toLowerCase()+t.slice(1))||Ve(e,Yn(t))||Ve(e,t))}function Ni(e){const{type:t,vnode:n,proxy:s,withProxy:l,propsOptions:[r],slots:o,attrs:a,emit:u,render:d,renderCache:c,props:f,data:p,setupState:g,ctx:N,inheritAttrs:x}=e,R=Nl(e);let A,P;try{if(n.shapeFlag&4){const O=l||s,C=O;A=Xt(d.call(C,O,c,f,g,p,N)),P=a}else{const O=t;A=Xt(O.length>1?O(f,{attrs:a,slots:o,emit:u}):O(f,null)),P=t.props?a:xf(a)}}catch(O){qn.length=0,Ql(O,e,1),A=De(bn)}let j=A;if(P&&x!==!1){const O=Object.keys(P),{shapeFlag:C}=j;O.length&&C&7&&(r&&O.some(Wl)&&(P=$f(P,r)),j=ps(j,P,!1,!0))}if(n.dirs&&(j=ps(j,null,!1,!0),j.dirs=j.dirs?j.dirs.concat(n.dirs):n.dirs),n.transition){const O=tr(j.type)&&xu(j)||j;Co(O,n.transition)}return A=j,Nl(R),A}const xf=e=>{let t;for(const n in e)(n==="class"||n==="style"||Gl(n))&&((t||(t={}))[n]=e[n]);return t},$f=(e,t)=>{const n={};for(const s in e)(!Wl(s)||!(s.slice(9)in t))&&(n[s]=e[s]);return n};function Sf(e,t,n){const{props:s,children:l,component:r}=e,{props:o,children:a,patchFlag:u}=t,d=r.emitsOptions;if(t.dirs||t.transition)return!0;if(n&&u>=0){if(u&1024)return!0;if(u&16)return s?Ii(s,o,d):!!o;if(u&8){const c=t.dynamicProps;for(let f=0;fObject.create(Nu),Mu=e=>Object.getPrototypeOf(e)===Nu;function Ef(e,t,n,s=!1){const l={},r=Iu();e.propsDefaults=Object.create(null),Lu(e,t,l,r);for(const o in e.propsOptions[0])o in l||(l[o]=void 0);n?e.props=s?l:du(l):e.type.props?e.props=l:e.props=r,e.attrs=r}function Af(e,t,n,s){const{props:l,attrs:r,vnode:{patchFlag:o}}=e,a=Ue(l),[u]=e.propsOptions;let d=!1;if((s||o>0)&&!(o&16)){if(o&8){const c=e.vnode.dynamicProps;for(let f=0;f{u=!0;const[p,g]=Du(f,t,!0);ut(o,p),g&&a.push(...g)};!n&&t.mixins.length&&t.mixins.forEach(c),e.extends&&c(e.extends),e.mixins&&e.mixins.forEach(c)}if(!r&&!u)return ze(e)&&s.set(e,is),is;if(ke(r))for(let c=0;ce==="_"||e==="_ctx"||e==="$stable",No=e=>ke(e)?e.map(Xt):[Xt(e)],Cf=(e,t,n)=>{if(t._n)return t;const s=Vt((...l)=>No(t(...l)),n);return s._c=!1,s},Fu=(e,t,n)=>{const s=e._ctx;for(const l in e){if(Po(l))continue;const r=e[l];if(Te(r))t[l]=Cf(l,r,s);else if(r!=null){const o=No(r);t[l]=()=>o}}},ju=(e,t)=>{const n=No(t);e.slots.default=()=>n},Uu=(e,t,n)=>{for(const s in t)(n||!Po(s))&&(e[s]=t[s])},Of=(e,t,n)=>{const s=e.slots=Iu();if(e.vnode.shapeFlag&32){const l=t._;l?(Uu(s,t,n),n&&Wa(s,"_",l,!0)):Fu(t,s)}else t&&ju(e,t)},Pf=(e,t,n)=>{const{vnode:s,slots:l}=e;let r=!0,o=Ge;if(s.shapeFlag&32){const a=t._;a?n&&a===1?r=!1:Uu(l,t,n):(r=!t.$stable,Fu(t,l)),o=t}else t&&(ju(e,t),o={default:1});if(r)for(const a in l)!Po(a)&&o[a]==null&&delete l[a]},_t=Df;function Nf(e){return If(e)}function If(e,t){const n=Xl();n.__VUE__=!0;const{insert:s,remove:l,patchProp:r,createElement:o,createText:a,createComment:u,setText:d,setElementText:c,parentNode:f,nextSibling:p,setScopeId:g=tn,insertStaticContent:N}=e,x=(b,T,L,B=null,X=null,U=null,fe=void 0,ie=null,ue=!!T.dynamicChildren)=>{if(b===T)return;b&&!xs(b,T)&&(B=H(b),ee(b,X,U,!0),b=null),T.patchFlag===-2&&(ue=!1,T.dynamicChildren=null);const{type:Q,ref:ve,shapeFlag:pe}=T;switch(Q){case lr:R(b,T,L,B);break;case bn:A(b,T,L,B);break;case Or:b==null&&P(T,L,B,fe);break;case se:I(b,T,L,B,X,U,fe,ie,ue);break;default:pe&1?C(b,T,L,B,X,U,fe,ie,ue):pe&6?V(b,T,L,B,X,U,fe,ie,ue):(pe&64||pe&128)&&Q.process(b,T,L,B,X,U,fe,ie,ue,be)}ve!=null&&X?zs(ve,b&&b.ref,U,T||b,!T):ve==null&&b&&b.ref!=null&&zs(b.ref,null,U,b,!0)},R=(b,T,L,B)=>{if(b==null)s(T.el=a(T.children),L,B);else{const X=T.el=b.el;T.children!==b.children&&d(X,T.children)}},A=(b,T,L,B)=>{b==null?s(T.el=u(T.children||""),L,B):T.el=b.el},P=(b,T,L,B)=>{[b.el,b.anchor]=N(b.children,T,L,B,b.el,b.anchor)},j=({el:b,anchor:T},L,B)=>{let X;for(;b&&b!==T;)X=p(b),s(b,L,B),b=X;s(T,L,B)},O=({el:b,anchor:T})=>{let L;for(;b&&b!==T;)L=p(b),l(b),b=L;l(T)},C=(b,T,L,B,X,U,fe,ie,ue)=>{if(T.type==="svg"?fe="svg":T.type==="math"&&(fe="mathml"),b==null)D(T,L,B,X,U,fe,ie,ue);else{const Q=b.el&&b.el._isVueCE?b.el:null;try{Q&&Q._beginPatch(),w(b,T,X,U,fe,ie,ue)}finally{Q&&Q._endPatch()}}},D=(b,T,L,B,X,U,fe,ie)=>{let ue,Q;const{props:ve,shapeFlag:pe,transition:_e,dirs:we}=b;if(ue=b.el=o(b.type,U,ve&&ve.is,ve),pe&8?c(ue,b.children):pe&16&&_(b.children,ue,null,B,X,Cr(b,U),fe,ie),we&&Mn(b,null,B,"created"),k(ue,b,b.scopeId,fe,B),ve){for(const Oe in ve)Oe!=="value"&&!js(Oe)&&r(ue,Oe,null,ve[Oe],U,B);"value"in ve&&r(ue,"value",null,ve.value,U),(Q=ve.onVnodeBeforeMount)&&Wt(Q,B,b)}we&&Mn(b,null,B,"beforeMount");const Ce=Mf(X,_e);Ce&&_e.beforeEnter(ue),s(ue,T,L),((Q=ve&&ve.onVnodeMounted)||Ce||we)&&_t(()=>{Q&&Wt(Q,B,b),Ce&&_e.enter(ue),we&&Mn(b,null,B,"mounted")},X)},k=(b,T,L,B,X)=>{if(L&&g(b,L),B)for(let U=0;U{for(let Q=ue;Q{const ie=T.el=b.el;let{patchFlag:ue,dynamicChildren:Q,dirs:ve}=T;ue|=b.patchFlag&16;const pe=b.props||Ge,_e=T.props||Ge;let we;if(L&&Ln(L,!1),(we=_e.onVnodeBeforeUpdate)&&Wt(we,L,T,b),ve&&Mn(T,b,L,"beforeUpdate"),L&&Ln(L,!0),Q&&(!b.dynamicChildren||b.dynamicChildren.length!==Q.length)&&(ue=0,fe=!1,Q=null),(pe.innerHTML&&_e.innerHTML==null||pe.textContent&&_e.textContent==null)&&c(ie,""),Q?E(b.dynamicChildren,Q,ie,L,B,Cr(T,X),U):fe||$(b,T,ie,null,L,B,Cr(T,X),U,!1),ue>0){if(ue&16)S(ie,pe,_e,L,X);else if(ue&2&&pe.class!==_e.class&&r(ie,"class",null,_e.class,X),ue&4&&r(ie,"style",pe.style,_e.style,X),ue&8){const Ce=T.dynamicProps;for(let Oe=0;Oe{we&&Wt(we,L,T,b),ve&&Mn(T,b,L,"updated")},B)},E=(b,T,L,B,X,U,fe)=>{for(let ie=0;ie{if(T!==L){if(T!==Ge)for(const U in T)!js(U)&&!(U in L)&&r(b,U,T[U],null,X,B);for(const U in L){if(js(U))continue;const fe=L[U],ie=T[U];fe!==ie&&U!=="value"&&r(b,U,ie,fe,X,B)}"value"in L&&r(b,"value",T.value,L.value,X)}},I=(b,T,L,B,X,U,fe,ie,ue)=>{const Q=T.el=b?b.el:a(""),ve=T.anchor=b?b.anchor:a("");let{patchFlag:pe,dynamicChildren:_e,slotScopeIds:we}=T;we&&(ie=ie?ie.concat(we):we),b==null?(s(Q,L,B),s(ve,L,B),_(T.children||[],L,ve,X,U,fe,ie,ue)):pe>0&&pe&64&&_e&&b.dynamicChildren&&b.dynamicChildren.length===_e.length?(E(b.dynamicChildren,_e,L,X,U,fe,ie),(T.key!=null||X&&T===X.subTree)&&Io(b,T,!0)):$(b,T,L,ve,X,U,fe,ie,ue)},V=(b,T,L,B,X,U,fe,ie,ue)=>{T.slotScopeIds=ie,b==null?T.shapeFlag&512?X.ctx.activate(T,L,B,fe,ue):z(T,L,B,X,U,fe,ue):ge(b,T,ue)},z=(b,T,L,B,X,U,fe)=>{const ie=b.component=zf(b,B,X);if(Oo(b)&&(ie.ctx.renderer=be),Hf(ie,!1,fe),ie.asyncDep){if(X&&X.registerDep(ie,le,fe),!b.el){const ue=ie.subTree=De(bn);A(null,ue,T,L),b.placeholder=ue.el}}else le(ie,b,T,L,X,U,fe)},ge=(b,T,L)=>{const B=T.component=b.component;if(Sf(b,T,L))if(B.asyncDep&&!B.asyncResolved){F(B,T,L);return}else B.next=T,B.update();else T.el=b.el,B.vnode=T},le=(b,T,L,B,X,U,fe)=>{const ie=()=>{if(b.isMounted){let{next:pe,bu:_e,u:we,parent:Ce,vnode:Oe}=b;{const gt=Vu(b);if(gt){pe&&(pe.el=Oe.el,F(b,pe,fe)),gt.asyncDep.then(()=>{_t(()=>{b.isUnmounted||Q()},X)});return}}let Pe=pe,qe;Ln(b,!1),pe?(pe.el=Oe.el,F(b,pe,fe)):pe=Oe,_e&&Al(_e),(qe=pe.props&&pe.props.onVnodeBeforeUpdate)&&Wt(qe,Ce,pe,Oe),Ln(b,!0);const tt=Ni(b),mt=b.subTree;b.subTree=tt,x(mt,tt,f(mt.el),H(mt),b,X,U),pe.el=tt.el,Pe===null&&Tf(b,tt.el),we&&_t(we,X),(qe=pe.props&&pe.props.onVnodeUpdated)&&_t(()=>Wt(qe,Ce,pe,Oe),X)}else{let pe;const{el:_e,props:we}=T,{bm:Ce,m:Oe,parent:Pe,root:qe,type:tt}=b,mt=qs(T);Ln(b,!1),Ce&&Al(Ce),!mt&&(pe=we&&we.onVnodeBeforeMount)&&Wt(pe,Pe,T),Ln(b,!0);{qe.ce&&qe.ce._hasShadowRoot()&&qe.ce._injectChildStyle(tt,b.parent?b.parent.type:void 0);const gt=b.subTree=Ni(b);x(null,gt,L,B,b,X,U),T.el=gt.el}if(Oe&&_t(Oe,X),!mt&&(pe=we&&we.onVnodeMounted)){const gt=T;_t(()=>Wt(pe,Pe,gt),X)}(T.shapeFlag&256||Pe&&qs(Pe.vnode)&&Pe.vnode.shapeFlag&256)&&b.a&&_t(b.a,X),b.isMounted=!0,T=L=B=null}};b.scope.on();const ue=b.effect=new Xa(ie);b.scope.off();const Q=b.update=ue.run.bind(ue),ve=b.job=ue.runIfDirty.bind(ue);ve.i=b,ve.id=b.uid,ue.scheduler=()=>Ro(ve),Ln(b,!0),Q()},F=(b,T,L)=>{T.component=b;const B=b.vnode.props;b.vnode=T,b.next=null,Af(b,T.props,B,L),Pf(b,T.children,L),gn(),xi(b),vn()},$=(b,T,L,B,X,U,fe,ie,ue=!1)=>{const Q=b&&b.children,ve=b?b.shapeFlag:0,pe=T.children,{patchFlag:_e,shapeFlag:we}=T;if(_e>0){if(_e&128){oe(Q,pe,L,B,X,U,fe,ie,ue);return}else if(_e&256){W(Q,pe,L,B,X,U,fe,ie,ue);return}}we&8?(ve&16&&Ee(Q,X,U),pe!==Q&&c(L,pe)):ve&16?we&16?oe(Q,pe,L,B,X,U,fe,ie,ue):Ee(Q,X,U,!0):(ve&8&&c(L,""),we&16&&_(pe,L,B,X,U,fe,ie,ue))},W=(b,T,L,B,X,U,fe,ie,ue)=>{b=b||is,T=T||is;const Q=b.length,ve=T.length,pe=Math.min(Q,ve);let _e;for(_e=0;_eve?Ee(b,X,U,!0,!1,pe):_(T,L,B,X,U,fe,ie,ue,pe)},oe=(b,T,L,B,X,U,fe,ie,ue)=>{let Q=0;const ve=T.length;let pe=b.length-1,_e=ve-1;for(;Q<=pe&&Q<=_e;){const we=b[Q],Ce=T[Q]=ue?dn(T[Q]):Xt(T[Q]);if(xs(we,Ce))x(we,Ce,L,null,X,U,fe,ie,ue);else break;Q++}for(;Q<=pe&&Q<=_e;){const we=b[pe],Ce=T[_e]=ue?dn(T[_e]):Xt(T[_e]);if(xs(we,Ce))x(we,Ce,L,null,X,U,fe,ie,ue);else break;pe--,_e--}if(Q>pe){if(Q<=_e){const we=_e+1,Ce=we_e)for(;Q<=pe;)ee(b[Q],X,U,!0),Q++;else{const we=Q,Ce=Q,Oe=new Map;for(Q=Ce;Q<=_e;Q++){const ot=T[Q]=ue?dn(T[Q]):Xt(T[Q]);ot.key!=null&&Oe.set(ot.key,Q)}let Pe,qe=0;const tt=_e-Ce+1;let mt=!1,gt=0;const rn=new Array(tt);for(Q=0;Q=tt){ee(ot,X,U,!0);continue}let vt;if(ot.key!=null)vt=Oe.get(ot.key);else for(Pe=Ce;Pe<=_e;Pe++)if(rn[Pe-Ce]===0&&xs(ot,T[Pe])){vt=Pe;break}vt===void 0?ee(ot,X,U,!0):(rn[vt-Ce]=Q+1,vt>=gt?gt=vt:mt=!0,x(ot,T[vt],L,null,X,U,fe,ie,ue),qe++)}const on=mt?Lf(rn):is;for(Pe=on.length-1,Q=tt-1;Q>=0;Q--){const ot=Ce+Q,vt=T[ot],ys=T[ot+1],bs=ot+1{const{el:U,type:fe,transition:ie,children:ue,shapeFlag:Q}=b;if(Q&6){te(b.component.subTree,T,L,B);return}if(Q&128){b.suspense.move(T,L,B);return}if(Q&64){fe.move(b,T,L,be);return}if(fe===se){s(U,T,L);for(let pe=0;peie.enter(U),X));else{const{leave:pe,delayLeave:_e,afterLeave:we}=ie,Ce=()=>{b.ctx.isUnmounted?l(U):s(U,T,L)},Oe=()=>{const Pe=U._isLeaving||!!U[Ar];U._isLeaving&&U[Ar](!0),ie.persisted&&!Pe?Ce():pe(U,()=>{Ce(),we&&we()})};_e?_e(U,Ce,Oe):Oe()}else s(U,T,L)},ee=(b,T,L,B=!1,X=!1)=>{const{type:U,props:fe,ref:ie,children:ue,dynamicChildren:Q,shapeFlag:ve,patchFlag:pe,dirs:_e,cacheIndex:we,memo:Ce}=b;if(pe===-2&&(X=!1),ie!=null&&(gn(),zs(ie,null,L,b,!0),vn()),we!=null&&(T.renderCache[we]=void 0),ve&256){T.ctx.deactivate(b);return}const Oe=ve&1&&_e,Pe=!qs(b);let qe;if(Pe&&(qe=fe&&fe.onVnodeBeforeUnmount)&&Wt(qe,T,b),ve&6)ne(b.component,L,B);else{if(ve&128){b.suspense.unmount(L,B);return}Oe&&Mn(b,null,T,"beforeUnmount"),ve&64?b.type.remove(b,T,L,be,B):Q&&!Q.hasOnce&&(U!==se||pe>0&&pe&64)?Ee(Q,T,L,!1,!0):(U===se&&pe&384||!X&&ve&16)&&Ee(ue,T,L),B&&G(b)}const tt=Ce!=null&&we==null;(Pe&&(qe=fe&&fe.onVnodeUnmounted)||Oe||tt)&&_t(()=>{qe&&Wt(qe,T,b),Oe&&Mn(b,null,T,"unmounted"),tt&&(b.el=null)},L)},G=b=>{const{type:T,el:L,anchor:B,transition:X}=b;if(T===se){Y(L,B);return}if(T===Or){O(b);return}const U=()=>{l(L),X&&!X.persisted&&X.afterLeave&&X.afterLeave()};if(b.shapeFlag&1&&X&&!X.persisted){const{leave:fe,delayLeave:ie}=X,ue=()=>fe(L,U);ie?ie(b.el,U,ue):ue()}else U()},Y=(b,T)=>{let L;for(;b!==T;)L=p(b),l(b),b=L;l(T)},ne=(b,T,L)=>{const{bum:B,scope:X,job:U,subTree:fe,um:ie,m:ue,a:Q}=b;Li(ue),Li(Q),B&&Al(B),X.stop(),U&&(U.flags|=8,ee(fe,b,T,L)),ie&&_t(ie,T),_t(()=>{b.isUnmounted=!0},T)},Ee=(b,T,L,B=!1,X=!1,U=0)=>{for(let fe=U;fe{if(b.shapeFlag&6)return H(b.component.subTree);if(b.shapeFlag&128)return b.suspense.next();const T=p(b.anchor||b.el),L=T&&T[ku];return L?p(L):T};let ae=!1;const ce=(b,T,L)=>{let B;b==null?T._vnode&&(ee(T._vnode,null,null,!0),B=T._vnode.component):x(T._vnode||null,b,T,null,null,null,L),T._vnode=b,ae||(ae=!0,xi(B),gu(),ae=!1)},be={p:x,um:ee,m:te,r:G,mt:z,mc:_,pc:$,pbc:E,n:H,o:e};return{render:ce,hydrate:void 0,createApp:bf(ce)}}function Cr({type:e,props:t},n){return n==="svg"&&e==="foreignObject"||n==="mathml"&&e==="annotation-xml"&&t&&t.encoding&&t.encoding.includes("html")?void 0:n}function Ln({effect:e,job:t},n){n?(e.flags|=32,t.flags|=4):(e.flags&=-33,t.flags&=-5)}function Mf(e,t){return(!e||e&&!e.pendingBranch)&&t&&!t.persisted}function Io(e,t,n=!1){const s=e.children,l=t.children;if(ke(s)&&ke(l))for(let r=0;r>1,e[n[a]]0&&(t[s]=n[r-1]),n[r]=s)}}for(r=n.length,o=n[r-1];r-- >0;)n[r]=o,o=t[o];return n}function Vu(e){const t=e.subTree.component;if(t)return t.asyncDep&&!t.asyncResolved?t:Vu(t)}function Li(e){if(e)for(let t=0;te.__isSuspense;function Df(e,t){t&&t.pendingBranch?ke(e)?t.effects.push(...e):t.effects.push(e):qd(e)}const se=Symbol.for("v-fgt"),lr=Symbol.for("v-txt"),bn=Symbol.for("v-cmt"),Or=Symbol.for("v-stc"),qn=[];let It=null;function h(e=!1){qn.push(It=e?null:[])}function qu(){qn.pop(),It=qn[qn.length-1]||null}let Zs=1;function Ll(e,t=!1){Zs+=e,e<0&&It&&t&&(It.hasOnce=!0)}function Hu(e){return e.dynamicChildren=Zs>0?It||is:null,qu(),Zs>0&&It&&It.push(e),e}function m(e,t,n,s,l,r){return Hu(i(e,t,n,s,l,r,!0))}function ln(e,t,n,s,l){return Hu(De(e,t,n,s,l,!0))}function Dl(e){return e?e.__v_isVNode===!0:!1}function xs(e,t){return e.type===t.type&&e.key===t.key}const Gu=({key:e})=>e??null,Rl=({ref:e,ref_key:t,ref_for:n})=>(typeof e=="number"&&(e=""+e),e!=null?Qe(e)||ht(e)||Te(e)?{i:Nt,r:e,k:t,f:!!n}:e:null);function i(e,t=null,n=null,s=0,l=null,r=e===se?0:1,o=!1,a=!1){const u={__v_isVNode:!0,__v_skip:!0,type:e,props:t,key:t&&Gu(t),ref:t&&Rl(t),scopeId:yu,slotScopeIds:null,children:n,component:null,suspense:null,ssContent:null,ssFallback:null,dirs:null,transition:null,el:null,anchor:null,target:null,targetStart:null,targetAnchor:null,staticCount:0,shapeFlag:r,patchFlag:s,dynamicProps:l,dynamicChildren:null,appContext:null,ctx:Nt};return a?(Fl(u,n),r&128&&e.normalize(u)):n&&(u.shapeFlag|=Qe(n)?8:16),Zs>0&&!o&&It&&(u.patchFlag>0||r&6)&&u.patchFlag!==32&&It.push(u),u}const De=Ff;function Ff(e,t=null,n=null,s=0,l=null,r=!1){if((!e||e===cf)&&(e=bn),Dl(e)){const a=ps(e,t,!0);return n&&Fl(a,n),Zs>0&&!r&&It&&(a.shapeFlag&6?It[It.indexOf(e)]=a:It.push(a)),a.patchFlag=-2,a}if(Jf(e)&&(e=e.__vccOpts),t){t=jf(t);let{class:a,style:u}=t;a&&!Qe(a)&&(t.class=He(a)),ze(u)&&(Ao(u)&&!ke(u)&&(u=ut({},u)),t.style=We(u))}const o=Qe(e)?1:zu(e)?128:tr(e)?64:ze(e)?4:Te(e)?2:0;return i(e,t,n,s,l,o,r,!0)}function jf(e){return e?Ao(e)||Mu(e)?ut({},e):e:null}function ps(e,t,n=!1,s=!1){const{props:l,ref:r,patchFlag:o,children:a,transition:u}=e,d=t?Uf(l||{},t):l,c={__v_isVNode:!0,__v_skip:!0,type:e.type,props:d,key:d&&Gu(d),ref:t&&t.ref?n&&r?ke(r)?r.concat(Rl(t)):[r,Rl(t)]:Rl(t):r,scopeId:e.scopeId,slotScopeIds:e.slotScopeIds,children:a,target:e.target,targetStart:e.targetStart,targetAnchor:e.targetAnchor,staticCount:e.staticCount,shapeFlag:e.shapeFlag,patchFlag:t&&e.type!==se?o===-1?16:o|16:o,dynamicProps:e.dynamicProps,dynamicChildren:e.dynamicChildren,appContext:e.appContext,dirs:e.dirs,transition:u,component:e.component,suspense:e.suspense,ssContent:e.ssContent&&ps(e.ssContent),ssFallback:e.ssFallback&&ps(e.ssFallback),placeholder:e.placeholder,el:e.el,anchor:e.anchor,ctx:e.ctx,ce:e.ce};return u&&s&&Co(c,u.clone(c)),c}function xe(e=" ",t=0){return De(lr,null,e,t)}function q(e="",t=!1){return t?(h(),ln(bn,null,e)):De(bn,null,e)}function Xt(e){return e==null||typeof e=="boolean"?De(bn):ke(e)?De(se,null,e.slice()):Dl(e)?dn(e):De(lr,null,String(e))}function dn(e){return e.el===null&&e.patchFlag!==-1||e.memo?e:ps(e)}function Fl(e,t){let n=0;const{shapeFlag:s}=e;if(t==null)t=null;else if(ke(t))n=16;else if(typeof t=="object")if(s&65){const l=t.default;l&&(l._c&&(l._d=!1),Fl(e,l()),l._c&&(l._d=!0));return}else{n=32;const l=t._;!l&&!Mu(t)?t._ctx=Nt:l===3&&Nt&&(Nt.slots._===1?t._=1:(t._=2,e.patchFlag|=1024))}else if(Te(t)){if(s&65){Fl(e,{default:t});return}t={default:t,_ctx:Nt},n=32}else t=String(t),s&64?(n=16,t=[xe(t)]):n=8;e.children=t,e.shapeFlag|=n}function Uf(...e){const t={};for(let n=0;npt||Nt;let jl,Qs;{const e=Xl(),t=(n,s)=>{let l;return(l=e[n])||(l=e[n]=[]),l.push(s),r=>{l.length>1?l.forEach(o=>o(r)):l[0](r)}};jl=t("__VUE_INSTANCE_SETTERS__",n=>pt=n),Qs=t("__VUE_SSR_SETTERS__",n=>el=n)}const ul=e=>{const t=pt;return jl(e),e.scope.on(),()=>{e.scope.off(),jl(t)}},Di=()=>{pt&&pt.scope.off(),jl(null)};function Wu(e){return e.vnode.shapeFlag&4}let el=!1;function Hf(e,t=!1,n=!1){t&&Qs(t);const{props:s,children:l}=e.vnode,r=Wu(e);Ef(e,s,r,t),Of(e,l,n||t);const o=r?Gf(e,t):void 0;return t&&Qs(!1),o}function Gf(e,t){const n=e.type;e.accessCache=Object.create(null),e.proxy=new Proxy(e.ctx,ff);const{setup:s}=n;if(s){gn();const l=e.setupContext=s.length>1?Kf(e):null,r=ul(e),o=il(s,e,0,[e.props,l]),a=qa(o);if(vn(),r(),(a||e.sp)&&!qs(e)&&Su(e),a){if(o.then(Di,Di),t)return o.then(u=>{Qs(!0);try{Fi(e,u,t)}finally{Qs(!1)}}).catch(u=>{Ql(u,e,0)});e.asyncDep=o}else Fi(e,o)}else Ku(e)}function Fi(e,t,n){Te(t)?e.type.__ssrInlineRender?e.ssrRender=t:e.render=t:ze(t)&&(e.setupState=pu(t)),Ku(e)}function Ku(e,t,n){const s=e.type;e.render||(e.render=s.render||tn);{const l=ul(e);gn();try{pf(e)}finally{vn(),l()}}}const Wf={get(e,t){return ft(e,"get",""),e[t]}};function Kf(e){const t=n=>{e.exposed=n||{}};return{attrs:new Proxy(e.attrs,Wf),slots:e.slots,emit:e.emit,expose:t}}function rr(e){return e.exposed?e.exposeProxy||(e.exposeProxy=new Proxy(pu(Md(e.exposed)),{get(t,n){if(n in t)return t[n];if(n in Hs)return Hs[n](e)},has(t,n){return n in t||n in Hs}})):e.proxy}function Yf(e,t=!0){return Te(e)?e.displayName||e.name:e.name||t&&e.__name}function Jf(e){return Te(e)&&"__vccOpts"in e}const K=(e,t)=>jd(e,t,el);function Yu(e,t,n){try{Ll(-1);const s=arguments.length;return s===2?ze(t)&&!ke(t)?Dl(t)?De(e,null,[t]):De(e,t):De(e,null,t):(s>3?n=Array.prototype.slice.call(arguments,2):s===3&&Dl(n)&&(n=[n]),De(e,t,n))}finally{Ll(1)}}const Xf="3.5.42";let no;const ji=typeof window<"u"&&window.trustedTypes;if(ji)try{no=ji.createPolicy("vue",{createHTML:e=>e})}catch{}const Ju=no?e=>no.createHTML(e):e=>e,Zf="http://www.w3.org/2000/svg",Qf="http://www.w3.org/1998/Math/MathML",cn=typeof document<"u"?document:null,Ui=cn&&cn.createElement("template"),ep={insert:(e,t,n)=>{t.insertBefore(e,n||null)},remove:e=>{const t=e.parentNode;t&&t.removeChild(e)},createElement:(e,t,n,s)=>{const l=t==="svg"?cn.createElementNS(Zf,e):t==="mathml"?cn.createElementNS(Qf,e):n?cn.createElement(e,{is:n}):cn.createElement(e);return e==="select"&&s&&s.multiple!=null&&l.setAttribute("multiple",s.multiple),l},createText:e=>cn.createTextNode(e),createComment:e=>cn.createComment(e),setText:(e,t)=>{e.nodeValue=t},setElementText:(e,t)=>{e.textContent=t},parentNode:e=>e.parentNode,nextSibling:e=>e.nextSibling,querySelector:e=>cn.querySelector(e),setScopeId(e,t){e.setAttribute(t,"")},insertStaticContent(e,t,n,s,l,r){const o=n?n.previousSibling:t.lastChild;if(l&&(l===r||l.nextSibling))for(;t.insertBefore(l.cloneNode(!0),n),!(l===r||!(l=l.nextSibling)););else{Ui.innerHTML=Ju(s==="svg"?`${e}`:s==="mathml"?`${e}`:e);const a=Ui.content;if(s==="svg"||s==="mathml"){const u=a.firstChild;for(;u.firstChild;)a.appendChild(u.firstChild);a.removeChild(u)}t.insertBefore(a,n)}return[o?o.nextSibling:t.firstChild,n?n.previousSibling:t.lastChild]}},tp=Symbol("_vtc");function np(e,t,n){const s=e[tp];s&&(t=(t?[t,...s]:[...s]).join(" ")),t==null?e.removeAttribute("class"):n?e.setAttribute("class",t):e.className=t}const Ul=Symbol("_vod"),Xu=Symbol("_vsh"),Zu={name:"show",beforeMount(e,{value:t},{transition:n}){e[Ul]=e.style.display==="none"?"":e.style.display,n&&t?n.beforeEnter(e):$s(e,t)},mounted(e,{value:t},{transition:n}){n&&t&&n.enter(e)},updated(e,{value:t,oldValue:n},{transition:s}){!t!=!n&&(s?t?(s.beforeEnter(e),$s(e,!0),s.enter(e)):s.leave(e,()=>{$s(e,!1)}):$s(e,t))},beforeUnmount(e,{value:t}){$s(e,t)}};function $s(e,t){e.style.display=t?e[Ul]:"none",e[Xu]=!t}const sp=Symbol(""),lp=/(?:^|;)\s*display\s*:/;function rp(e,t,n){const s=e.style,l=Qe(n);let r=!1;if(n&&!l){if(t)if(Qe(t))for(const o of t.split(";")){const a=o.slice(0,o.indexOf(":")).trim();n[a]==null&&Is(s,a,"")}else for(const o in t)n[o]==null&&Is(s,o,"");for(const o in n){o==="display"&&(r=!0);const a=n[o];a!=null?ip(e,o,!Qe(t)&&t?t[o]:void 0,a)||Is(s,o,a):Is(s,o,"")}}else if(l){if(t!==n){const o=s[sp];o&&(n+=";"+o),s.cssText=n,r=lp.test(n)}}else t&&e.removeAttribute("style");Ul in e&&(e[Ul]=r?s.display:"",e[Xu]&&(s.display="none"))}const $l=/\s*!important$/;function Is(e,t,n){if(ke(n))n.forEach(s=>Is(e,t,s));else if(n==null&&(n=""),t.startsWith("--"))$l.test(n)?e.setProperty(t,n.replace($l,""),"important"):e.setProperty(t,n);else{const s=op(e,t);$l.test(n)?e.setProperty(Yn(s),n.replace($l,""),"important"):e[s]=n}}const Vi=["Webkit","Moz","ms"],Pr={};function op(e,t){const n=Pr[t];if(n)return n;let s=Tt(t);if(s!=="filter"&&s in e)return Pr[t]=s;s=Yl(s);for(let l=0;lNr||(pp.then(()=>Nr=0),Nr=Date.now());function mp(e,t){const n=s=>{if(!s._vts)s._vts=Date.now();else if(s._vts<=n.attached)return;const l=n.value;if(ke(l)){const r=s.stopImmediatePropagation;s.stopImmediatePropagation=()=>{r.call(s),s._stopped=!0};const o=l.slice(),a=[s];for(let u=0;ue.charCodeAt(0)===111&&e.charCodeAt(1)===110&&e.charCodeAt(2)>96&&e.charCodeAt(2)<123,gp=(e,t,n,s,l,r)=>{const o=l==="svg";t==="class"?np(e,s,o):t==="style"?rp(e,n,s):Gl(t)?Wl(t)||up(e,t,n,s,r):(t[0]==="."?(t=t.slice(1),!0):t[0]==="^"?(t=t.slice(1),!1):vp(e,t,s,o))?(qi(e,t,s),!e.tagName.includes("-")&&(t==="value"||t==="checked"||t==="selected")&&zi(e,t,s,o,r,t!=="value")):e._isVueCE&&(yp(e,t)||e._def.__asyncLoader&&(/[A-Z]/.test(t)||!Qe(s)))?qi(e,Tt(t),s,r,t):(t==="true-value"?e._trueValue=s:t==="false-value"&&(e._falseValue=s),zi(e,t,s,o))};function vp(e,t,n,s){if(s)return!!(t==="innerHTML"||t==="textContent"||t in e&&Gi(t)&&Te(n));if(t==="spellcheck"||t==="draggable"||t==="translate"||t==="autocorrect"||t==="sandbox"&&e.tagName==="IFRAME"||t==="form"||t==="list"&&e.tagName==="INPUT"||t==="type"&&e.tagName==="TEXTAREA")return!1;if(t==="width"||t==="height"){const l=e.tagName;if(l==="IMG"||l==="VIDEO"||l==="CANVAS"||l==="SOURCE")return!1}return Gi(t)&&Qe(n)?!1:t in e}function yp(e,t){const n=e._def.props;if(!n)return!1;const s=Tt(t);return Array.isArray(n)?n.some(l=>Tt(l)===s):Object.keys(n).some(l=>Tt(l)===s)}const hs=e=>{const t=e.props["onUpdate:modelValue"]||!1;return ke(t)?n=>Al(t,n):t};function bp(e){e.target.composing=!0}function Wi(e){const t=e.target;t.composing&&(t.composing=!1,t.dispatchEvent(new Event("input")))}const en=Symbol("_assign"),Sl=Symbol("_initialValue");function Ir(e,t,n){return t&&(e=e.trim()),n&&(e=Jl(e)),e}const Le={created(e,{modifiers:{lazy:t,trim:n,number:s}},l){e.parentNode&&(e.type==="text"?e[Sl]=e.defaultValue.replace(/[\r\n]/g,""):e.type==="textarea"&&(e[Sl]=e.defaultValue.replace(/\r\n?/g,` +`))),e[en]=hs(l);const r=s||l.props&&l.props.type==="number";Rn(e,t?"change":"input",o=>{o.target.composing||e[en](Ir(e.value,n,r))}),(n||r)&&Rn(e,"change",()=>{e.value=Ir(e.value,n,r)}),t||(Rn(e,"compositionstart",bp),Rn(e,"compositionend",Wi),Rn(e,"change",Wi))},mounted(e,{value:t,modifiers:{trim:n,number:s}}){const l=t??"",r=e[Sl];delete e[Sl],r!==void 0&&(e.type==="text"||e.type==="textarea")&&e.value!==r?e[en](Ir(e.value,n,s)):e.value=l},beforeUpdate(e,{value:t,oldValue:n,modifiers:{lazy:s,trim:l,number:r}},o){if(e[en]=hs(o),e.composing)return;const a=(r||e.type==="number")&&!/^0\d/.test(e.value)?Jl(e.value):e.value,u=t??"";if(a===u)return;const d=e.getRootNode();(d instanceof Document||d instanceof ShadowRoot)&&d.activeElement===e&&e.type!=="range"&&(s&&t===n||l&&e.value.trim()===u)||(e.value=u)}},Qu={deep:!0,created(e,t,n){e[en]=hs(n),Rn(e,"change",()=>{const s=e._modelValue,l=tl(e),r=e.checked,o=e[en];if(ke(s)){const a=ko(s,l),u=a!==-1;if(r&&!u)o(s.concat(l));else if(!r&&u){const d=[...s];d.splice(a,1),o(d)}}else if(hn(s)){const a=new Set(s);r?a.add(l):a.delete(l),o(a)}else o(ec(e,r))})},mounted:Ki,beforeUpdate(e,t,n){e[en]=hs(n),Ki(e,t,n)}};function Ki(e,{value:t,oldValue:n},s){e._modelValue=t;let l;if(ke(t))l=ko(t,s.props.value)>-1;else if(hn(t))l=t.has(s.props.value);else{if(t===n)return;l=mn(t,ec(e,!0))}e.checked!==l&&(e.checked=l)}const _n={deep:!0,created(e,{value:t,modifiers:{number:n}},s){e._modelValue=t,Rn(e,"change",()=>{const l=Array.prototype.filter.call(e.options,u=>u.selected).map(u=>n?Jl(tl(u)):tl(u)),r=e.multiple,o=r?hn(e._modelValue)?new Set(l):l:l[0],a=e._pendingValue=[r,r?ke(o)?l.slice():l:o];try{e[en](o)}finally{er(()=>{e._pendingValue===a&&(e._pendingValue=void 0)})}}),e[en]=hs(s)},mounted(e,{value:t}){Yi(e,t)},beforeUpdate(e,{value:t},n){e._modelValue=t,e[en]=hs(n)},updated(e,{value:t}){const n=e._pendingValue;e._pendingValue=void 0,(!n||n[0]!==e.multiple||!_p(t,n[1],n[0]))&&Yi(e,t)}};function _p(e,t,n){if(!n||ke(e))return mn(e,t);if(hn(e)){if(e.size!==t.length)return!1;for(const s of t)if(!e.has(s))return!1;return!0}return!1}function Yi(e,t){const n=e.multiple,s=ke(t);if(!(n&&!s&&!hn(t))){for(let l=0,r=e.options.length;lString(d)===String(a)):o.selected=ko(t,a)>-1}else o.selected=t.has(a);else if(mn(tl(o),t)){e.selectedIndex!==l&&(e.selectedIndex=l);return}}!n&&e.selectedIndex!==-1&&(e.selectedIndex=-1)}}function tl(e){return"_value"in e?e._value:e.value}function ec(e,t){const n=t?"_trueValue":"_falseValue";return n in e?e[n]:t}const kp=["ctrl","shift","alt","meta"],wp={stop:e=>e.stopPropagation(),prevent:e=>e.preventDefault(),self:e=>e.target!==e.currentTarget,ctrl:e=>!e.ctrlKey,shift:e=>!e.shiftKey,alt:e=>!e.altKey,meta:e=>!e.metaKey,left:e=>"button"in e&&e.button!==0,middle:e=>"button"in e&&e.button!==1,right:e=>"button"in e&&e.button!==2,exact:(e,t)=>kp.some(n=>e[`${n}Key`]&&!t.includes(n))},kn=(e,t)=>{if(!e)return e;const n=e._withMods||(e._withMods={}),s=t.join(".");return n[s]||(n[s]=((l,...r)=>{for(let o=0;o{const t=$p().createApp(...e),{mount:n}=t;return t.mount=s=>{const l=Ep(s);if(!l)return;const r=t._component;!Te(r)&&!r.render&&!r.template&&(r.template=l.innerHTML),l.nodeType===1&&(l.textContent="");const o=n(l,!1,Tp(l));return l instanceof Element&&(l.removeAttribute("v-cloak"),l.setAttribute("data-v-app","")),o},t});function Tp(e){if(e instanceof SVGElement)return"svg";if(typeof MathMLElement=="function"&&e instanceof MathMLElement)return"mathml"}function Ep(e){return Qe(e)?document.querySelector(e):e}const rs=typeof document<"u";function tc(e){return typeof e=="object"||"displayName"in e||"props"in e||"__vccOpts"in e}function Ap(e){return e.__esModule||e[Symbol.toStringTag]==="Module"||e.default&&tc(e.default)}const je=Object.assign;function Mr(e,t){const n={};for(const s in t){const l=t[s];n[s]=qt(l)?l.map(e):e(l)}return n}const Gs=()=>{},qt=Array.isArray;function Xi(e,t){const n={};for(const s in e)n[s]=s in t?t[s]:e[s];return n}const nc=/#/g,Rp=/&/g,Cp=/\//g,Op=/=/g,Pp=/\?/g,sc=/\+/g,Np=/%5B/g,Ip=/%5D/g,lc=/%5E/g,Mp=/%60/g,rc=/%7B/g,Lp=/%7C/g,oc=/%7D/g,Dp=/%20/g;function Mo(e){return e==null?"":encodeURI(""+e).replace(Lp,"|").replace(Np,"[").replace(Ip,"]")}function Fp(e){return Mo(e).replace(rc,"{").replace(oc,"}").replace(lc,"^")}function so(e){return Mo(e).replace(sc,"%2B").replace(Dp,"+").replace(nc,"%23").replace(Rp,"%26").replace(Mp,"`").replace(rc,"{").replace(oc,"}").replace(lc,"^")}function jp(e){return so(e).replace(Op,"%3D")}function Up(e){return Mo(e).replace(nc,"%23").replace(Pp,"%3F")}function Vp(e){return Up(e).replace(Cp,"%2F")}function nl(e){if(e==null)return null;try{return decodeURIComponent(""+e)}catch{}return""+e}const Bp=/\/$/,zp=e=>e.replace(Bp,"");function Lr(e,t,n="/"){let s,l={},r="",o="";const a=t.indexOf("#");let u=t.indexOf("?");return u=a>=0&&u>a?-1:u,u>=0&&(s=t.slice(0,u),r=t.slice(u,a>0?a:t.length),l=e(r.slice(1))),a>=0&&(s=s||t.slice(0,a),o=t.slice(a,t.length)),s=Wp(s??t,n),{fullPath:s+r+o,path:s,query:l,hash:nl(o)}}function qp(e,t){const n=t.query?e(t.query):"";return t.path+(n&&"?")+n+(t.hash||"")}function Zi(e,t){return!t||!e.toLowerCase().startsWith(t.toLowerCase())?e:e.slice(t.length)||"/"}function Hp(e,t,n){const s=t.matched.length-1,l=n.matched.length-1;return s>-1&&s===l&&ms(t.matched[s],n.matched[l])&&ic(t.params,n.params)&&e(t.query)===e(n.query)&&t.hash===n.hash}function ms(e,t){return(e.aliasOf||e)===(t.aliasOf||t)}function ic(e,t){if(Object.keys(e).length!==Object.keys(t).length)return!1;for(var n in e)if(!Gp(e[n],t[n]))return!1;return!0}function Gp(e,t){return qt(e)?Qi(e,t):qt(t)?Qi(t,e):e?.valueOf()===t?.valueOf()}function Qi(e,t){return qt(t)?e.length===t.length&&e.every((n,s)=>n===t[s]):e.length===1&&e[0]===t}function Wp(e,t){if(e.startsWith("/"))return e;if(!e)return t;const n=t.split("/"),s=e.split("/"),l=s[s.length-1];(l===".."||l===".")&&s.push("");let r=n.length-1,o,a;for(o=0;o1&&r--;else break;return n.slice(0,r).join("/")+"/"+s.slice(o).join("/")}const $n={path:"/",name:void 0,params:{},query:{},hash:"",fullPath:"/",matched:[],meta:{},redirectedFrom:void 0};let lo=(function(e){return e.pop="pop",e.push="push",e})({}),Dr=(function(e){return e.back="back",e.forward="forward",e.unknown="",e})({});function Kp(e){if(!e)if(rs){const t=document.querySelector("base");e=t&&t.getAttribute("href")||"/",e=e.replace(/^\w+:\/\/[^\/]+/,"")}else e="/";return e[0]!=="/"&&e[0]!=="#"&&(e="/"+e),zp(e)}const Yp=/^[^#]+#/;function Jp(e,t){return e.replace(Yp,"#")+t}function Xp(e,t){const n=document.documentElement.getBoundingClientRect(),s=e.getBoundingClientRect();return{behavior:t.behavior,left:s.left-n.left-(t.left||0),top:s.top-n.top-(t.top||0)}}const or=()=>({left:window.scrollX,top:window.scrollY});function Zp(e){let t;if("el"in e){const n=e.el,s=typeof n=="string"&&n.startsWith("#"),l=typeof n=="string"?s?document.getElementById(n.slice(1)):document.querySelector(n):n;if(!l)return;t=Xp(l,e)}else t=e;"scrollBehavior"in document.documentElement.style?window.scrollTo(t):window.scrollTo(t.left!=null?t.left:window.scrollX,t.top!=null?t.top:window.scrollY)}function ea(e,t){return(history.state?history.state.position-t:-1)+e}const ro=new Map;function Qp(e,t){ro.set(e,t)}function eh(e){const t=ro.get(e);return ro.delete(e),t}function th(e){return typeof e=="string"||e&&typeof e=="object"}function ac(e){return typeof e=="string"||typeof e=="symbol"}let et=(function(e){return e[e.MATCHER_NOT_FOUND=1]="MATCHER_NOT_FOUND",e[e.NAVIGATION_GUARD_REDIRECT=2]="NAVIGATION_GUARD_REDIRECT",e[e.NAVIGATION_ABORTED=4]="NAVIGATION_ABORTED",e[e.NAVIGATION_CANCELLED=8]="NAVIGATION_CANCELLED",e[e.NAVIGATION_DUPLICATED=16]="NAVIGATION_DUPLICATED",e})({});const uc=Symbol("");et.MATCHER_NOT_FOUND+"",et.NAVIGATION_GUARD_REDIRECT+"",et.NAVIGATION_ABORTED+"",et.NAVIGATION_CANCELLED+"",et.NAVIGATION_DUPLICATED+"";function gs(e,t){return je(new Error,{type:e,[uc]:!0},t)}function un(e,t){return e instanceof Error&&uc in e&&(t==null||!!(e.type&t))}const nh=["params","query","hash"];function sh(e){if(typeof e=="string")return e;if(e.path!=null)return e.path;const t={};for(const n of nh)n in e&&(t[n]=e[n]);return JSON.stringify(t,null,2)}function lh(e){const t={};if(e===""||e==="?")return t;const n=(e[0]==="?"?e.slice(1):e).split("&");for(let s=0;sl&&so(l)):[s&&so(s)]).forEach(l=>{l!==void 0&&(t+=(t.length?"&":"")+n,l!=null&&(t+="="+l))})}return t}function rh(e){const t={};for(const n in e){const s=e[n];s!==void 0&&(t[n]=qt(s)?s.map(l=>l==null?null:""+l):s==null?s:""+s)}return t}const oh=Symbol(""),na=Symbol(""),ir=Symbol(""),Lo=Symbol(""),oo=Symbol("");function Ss(){let e=[];function t(s){return e.push(s),()=>{const l=e.indexOf(s);l>-1&&e.splice(l,1)}}function n(){e=[]}return{add:t,list:()=>e.slice(),reset:n}}function An(e,t,n,s,l,r=o=>o()){const o=s&&(s.enterCallbacks[l]=s.enterCallbacks[l]||[]);return()=>new Promise((a,u)=>{const d=p=>{p===!1?u(gs(et.NAVIGATION_ABORTED,{from:n,to:t})):p instanceof Error?u(p):th(p)?u(gs(et.NAVIGATION_GUARD_REDIRECT,{from:t,to:p})):(o&&s.enterCallbacks[l]===o&&typeof p=="function"&&o.push(p),a())},c=r(()=>e.call(s&&s.instances[l],t,n,d));let f=Promise.resolve(c);e.length<3&&(f=f.then(d)),f.catch(p=>u(p))})}function Fr(e,t,n,s,l=r=>r()){const r=[];for(const o of e)for(const a in o.components){let u=o.components[a];if(!(t!=="beforeRouteEnter"&&!o.instances[a]))if(tc(u)){const d=(u.__vccOpts||u)[t];d&&r.push(An(d,n,s,o,a,l))}else{let d=u();r.push(()=>d.then(c=>{if(!c)throw new Error(`Couldn't resolve component "${a}" at "${o.path}"`);const f=Ap(c)?c.default:c;o.mods[a]=c,o.components[a]=f;const p=(f.__vccOpts||f)[t];return p&&An(p,n,s,o,a,l)()}))}}return r}function ih(e,t){const n=[],s=[],l=[],r=Math.max(t.matched.length,e.matched.length);for(let o=0;oms(d,a))?s.push(a):n.push(a));const u=e.matched[o];u&&(t.matched.find(d=>ms(d,u))||l.push(u))}return[n,s,l]}let ah=()=>location.protocol+"//"+location.host;function cc(e,t){const{pathname:n,search:s,hash:l}=t,r=e.indexOf("#");if(r>-1){let o=l.includes(e.slice(r))?e.slice(r).length:1,a=l.slice(o);return a[0]!=="/"&&(a="/"+a),Zi(a,"")}return Zi(n,e)+s+l}function uh(e,t,n,s){let l=[],r=[],o=null;const a=({state:p})=>{const g=cc(e,location),N=n.value,x=t.value;let R=0;if(p){if(n.value=g,t.value=p,o&&o===N){o=null;return}R=x?p.position-x.position:0}else s(g);l.forEach(A=>{A(n.value,N,{delta:R,type:lo.pop,direction:R?R>0?Dr.forward:Dr.back:Dr.unknown})})};function u(){o=n.value}function d(p){l.push(p);const g=()=>{const N=l.indexOf(p);N>-1&&l.splice(N,1)};return r.push(g),g}function c(){if(document.visibilityState==="hidden"){const{history:p}=window;if(!p.state)return;p.replaceState(je({},p.state,{scroll:or()}),"")}}function f(){for(const p of r)p();r=[],window.removeEventListener("popstate",a),window.removeEventListener("pagehide",c),document.removeEventListener("visibilitychange",c)}return window.addEventListener("popstate",a),window.addEventListener("pagehide",c),document.addEventListener("visibilitychange",c),{pauseListeners:u,listen:d,destroy:f}}function sa(e,t,n,s=!1,l=!1){return{back:e,current:t,forward:n,replaced:s,position:window.history.length,scroll:l?or():null}}function ch(e){const{history:t,location:n}=window,s={value:cc(e,n)},l={value:t.state};l.value||r(s.value,{back:null,current:s.value,forward:null,position:t.length-1,replaced:!0,scroll:null},!0);function r(u,d,c){const f=e.indexOf("#"),p=f>-1?(n.host&&document.querySelector("base")?e:e.slice(f))+u:ah()+e+u;try{t[c?"replaceState":"pushState"](d,"",p),l.value=d}catch(g){console.error(g),n[c?"replace":"assign"](p)}}function o(u,d){r(u,je({},t.state,sa(l.value.back,u,l.value.forward,!0),d,{position:l.value.position}),!0),s.value=u}function a(u,d){const c=je({},l.value,t.state,{forward:u,scroll:or()});r(c.current,c,!0),r(u,je({},sa(s.value,u,null),{position:c.position+1},d),!1),s.value=u}return{location:s,state:l,push:a,replace:o}}function dh(e){e=Kp(e);const t=ch(e),n=uh(e,t.state,t.location,t.replace);function s(r,o=!0){o||n.pauseListeners(),history.go(r)}const l=je({location:"",base:e,go:s,createHref:Jp.bind(null,e)},t,n);return Object.defineProperty(l,"location",{enumerable:!0,get:()=>t.location.value}),Object.defineProperty(l,"state",{enumerable:!0,get:()=>t.state.value}),l}let Vn=(function(e){return e[e.Static=0]="Static",e[e.Param=1]="Param",e[e.Group=2]="Group",e})({});var lt=(function(e){return e[e.Static=0]="Static",e[e.Param=1]="Param",e[e.ParamRegExp=2]="ParamRegExp",e[e.ParamRegExpEnd=3]="ParamRegExpEnd",e[e.EscapeNext=4]="EscapeNext",e})(lt||{});const fh={type:Vn.Static,value:""},ph=/[a-zA-Z0-9_]/;function hh(e){if(!e)return[[]];if(e==="/")return[[fh]];if(!e.startsWith("/"))throw new Error(`Invalid path "${e}"`);function t(g){throw new Error(`ERR (${n})/"${d}": ${g}`)}let n=lt.Static,s=n;const l=[];let r;function o(){r&&l.push(r),r=[]}let a=0,u,d="",c="";function f(){d&&(n===lt.Static?r.push({type:Vn.Static,value:d}):n===lt.Param||n===lt.ParamRegExp||n===lt.ParamRegExpEnd?(r.length>1&&(u==="*"||u==="+")&&t(`A repeatable param (${d}) must be alone in its segment. eg: '/:ids+.`),r.push({type:Vn.Param,value:d,regexp:c,repeatable:u==="*"||u==="+",optional:u==="*"||u==="?"})):t("Invalid state to consume buffer"),d="")}function p(){d+=u}for(;at.length?t.length===1&&t[0]===kt.Static+kt.Segment?1:-1:0}function dc(e,t){let n=0;const s=e.score,l=t.score;for(;n0&&t[t.length-1]<0}const bh={strict:!1,end:!0,sensitive:!1};function _h(e,t,n){const s=vh(hh(e.path),n),l=je(s,{record:e,parent:t,children:[],alias:[]});return t&&!l.record.aliasOf==!t.record.aliasOf&&t.children.push(l),l}function kh(e,t){const n=[],s=new Map;t=Xi(bh,t);function l(f){return s.get(f)}function r(f,p,g){const N=!g,x=ia(f);x.aliasOf=g&&g.record;const R=Xi(t,f),A=[x];if("alias"in f){const O=typeof f.alias=="string"?[f.alias]:f.alias;for(const C of O)A.push(ia(je({},x,{components:g?g.record.components:x.components,path:C,aliasOf:g?g.record:x})))}let P,j;for(const O of A){const{path:C}=O;if(p&&C[0]!=="/"){const D=p.record.path,k=D[D.length-1]==="/"?"":"/";O.path=p.record.path+(C&&k+C)}if(P=_h(O,p,R),g?g.alias.push(P):(j=j||P,j!==P&&j.alias.push(P),N&&f.name&&!aa(P)&&o(f.name)),fc(P)&&u(P),x.children){const D=x.children;for(let k=0;k{o(j)}:Gs}function o(f){if(ac(f)){const p=s.get(f);p&&(s.delete(f),n.splice(n.indexOf(p),1),p.children.forEach(o),p.alias.forEach(o))}else{const p=n.indexOf(f);p>-1&&(n.splice(p,1),f.record.name&&s.delete(f.record.name),f.children.forEach(o),f.alias.forEach(o))}}function a(){return n}function u(f){const p=$h(f,n);n.splice(p,0,f),f.record.name&&!aa(f)&&s.set(f.record.name,f)}function d(f,p){let g,N={},x,R;if("name"in f&&f.name){if(g=s.get(f.name),!g)throw gs(et.MATCHER_NOT_FOUND,{location:f});R=g.record.name,N=je(oa(p.params,g.keys.filter(j=>!j.optional).concat(g.parent?g.parent.keys.filter(j=>j.optional):[]).map(j=>j.name)),f.params&&oa(f.params,g.keys.map(j=>j.name))),x=g.stringify(N)}else if(f.path!=null)x=f.path,g=n.find(j=>j.re.test(x)),g&&(N=g.parse(x),R=g.record.name);else{if(g=p.name?s.get(p.name):n.find(j=>j.re.test(p.path)),!g)throw gs(et.MATCHER_NOT_FOUND,{location:f,currentLocation:p});R=g.record.name,N=je({},p.params,f.params),x=g.stringify(N)}const A=[];let P=g;for(;P;)A.unshift(P.record),P=P.parent;return{name:R,path:x,params:N,matched:A,meta:xh(A)}}e.forEach(f=>r(f));function c(){n.length=0,s.clear()}return{addRoute:r,resolve:d,removeRoute:o,clearRoutes:c,getRoutes:a,getRecordMatcher:l}}function oa(e,t){const n={};for(const s of t)s in e&&(n[s]=e[s]);return n}function ia(e){const t={path:e.path,redirect:e.redirect,name:e.name,meta:e.meta||{},aliasOf:e.aliasOf,beforeEnter:e.beforeEnter,props:wh(e),children:e.children||[],instances:{},leaveGuards:new Set,updateGuards:new Set,enterCallbacks:{},components:"components"in e?e.components||null:e.component&&{default:e.component}};return Object.defineProperty(t,"mods",{value:{}}),t}function wh(e){const t={},n=e.props||!1;if("component"in e)t.default=n;else for(const s in e.components)t[s]=typeof n=="object"?n[s]:n;return t}function aa(e){for(;e;){if(e.record.aliasOf)return!0;e=e.parent}return!1}function xh(e){return e.reduce((t,n)=>je(t,n.meta),{})}function $h(e,t){let n=0,s=t.length;for(;n!==s;){const r=n+s>>1;dc(e,t[r])<0?s=r:n=r+1}const l=Sh(e);return l&&(s=t.lastIndexOf(l,s-1)),s}function Sh(e){let t=e;for(;t=t.parent;)if(fc(t)&&dc(e,t)===0)return t}function fc({record:e}){return!!(e.name||e.components&&Object.keys(e.components).length||e.redirect)}function ua(e){const t=Dt(ir),n=Dt(Lo),s=K(()=>{const u=de(e.to);return t.resolve(u)}),l=K(()=>{const{matched:u}=s.value,{length:d}=u,c=u[d-1],f=n.matched;if(!c||!f.length)return-1;const p=f.findIndex(ms.bind(null,c));if(p>-1)return p;const g=ca(u[d-2]);return d>1&&ca(c)===g&&f[f.length-1].path!==g?f.findIndex(ms.bind(null,u[d-2])):p}),r=K(()=>l.value>-1&&Ch(n.params,s.value.params)),o=K(()=>l.value>-1&&l.value===n.matched.length-1&&ic(n.params,s.value.params));function a(u={}){if(Rh(u)){const d=t[de(e.replace)?"replace":"push"](de(e.to)).catch(Gs);return e.viewTransition&&typeof document<"u"&&"startViewTransition"in document&&document.startViewTransition(()=>d),d}return Promise.resolve()}return{route:s,href:K(()=>s.value.href),isActive:r,isExactActive:o,navigate:a}}function Th(e){return e.length===1?e[0]:e}const Eh=$u({name:"RouterLink",compatConfig:{MODE:3},props:{to:{type:[String,Object],required:!0},replace:Boolean,activeClass:String,exactActiveClass:String,custom:Boolean,ariaCurrentValue:{type:String,default:"page"},viewTransition:Boolean},useLink:ua,setup(e,{slots:t}){const n=Hn(ua(e)),{options:s}=Dt(ir),l=K(()=>({[da(e.activeClass,s.linkActiveClass,"router-link-active")]:n.isActive,[da(e.exactActiveClass,s.linkExactActiveClass,"router-link-exact-active")]:n.isExactActive}));return()=>{const r=t.default&&Th(t.default(n));return e.custom?r:Yu("a",{"aria-current":n.isExactActive?e.ariaCurrentValue:null,href:n.href,onClick:n.navigate,class:l.value},r)}}}),Ah=Eh;function Rh(e){if(!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)&&!e.defaultPrevented&&!(e.button!==void 0&&e.button!==0)){if(e.currentTarget&&e.currentTarget.getAttribute){const t=e.currentTarget.getAttribute("target");if(/\b_blank\b/i.test(t))return}return e.preventDefault&&e.preventDefault(),!0}}function Ch(e,t){for(const n in t){const s=t[n],l=e[n];if(typeof s=="string"){if(s!==l)return!1}else if(!qt(l)||l.length!==s.length||s.some((r,o)=>r.valueOf()!==l[o].valueOf()))return!1}return!0}function ca(e){return e?e.aliasOf?e.aliasOf.path:e.path:""}const da=(e,t,n)=>e??t??n,Oh=$u({name:"RouterView",inheritAttrs:!1,props:{name:{type:String,default:"default"},route:Object},compatConfig:{MODE:3},setup(e,{attrs:t,slots:n}){const s=Dt(oo),l=K(()=>e.route||s.value),r=Dt(na,0),o=K(()=>{let d=de(r);const{matched:c}=l.value;let f;for(;(f=c[d])&&!f.components;)d++;return d}),a=K(()=>l.value.matched[o.value]);Bs(na,K(()=>o.value+1)),Bs(oh,a),Bs(oo,l);const u=J();return Je(()=>[u.value,a.value,e.name],([d,c,f],[p,g,N])=>{c&&(c.instances[f]=d,g&&g!==c&&d&&d===p&&(c.leaveGuards.size||(c.leaveGuards=g.leaveGuards),c.updateGuards.size||(c.updateGuards=g.updateGuards))),d&&c&&(!g||!ms(c,g)||!p)&&(c.enterCallbacks[f]||[]).forEach(x=>x(d))},{flush:"post"}),()=>{const d=l.value,c=e.name,f=a.value,p=f&&f.components[c];if(!p)return fa(n.default,{Component:p,route:d});const g=f.props[c],N=g?g===!0?d.params:typeof g=="function"?g(d):g:null,R=Yu(p,je({},N,t,{onVnodeUnmounted:A=>{A.component.isUnmounted&&(f.instances[c]=null)},ref:u}));return fa(n.default,{Component:R,route:d})||R}}});function fa(e,t){if(!e)return null;const n=e(t);return n.length===1?n[0]:n}const Ph=Oh;function Nh(e){const t=kh(e.routes,e),n=e.parseQuery||lh,s=e.stringifyQuery||ta,l=e.history,r=Ss(),o=Ss(),a=Ss(),u=fs($n);let d=$n;rs&&e.scrollBehavior&&"scrollRestoration"in history&&(history.scrollRestoration="manual");const c=Mr.bind(null,H=>""+H),f=Mr.bind(null,Vp),p=Mr.bind(null,nl);function g(H,ae){let ce,be;return ac(H)?(ce=t.getRecordMatcher(H),be=ae):be=H,t.addRoute(be,ce)}function N(H){const ae=t.getRecordMatcher(H);ae&&t.removeRoute(ae)}function x(){return t.getRoutes().map(H=>H.record)}function R(H){return!!t.getRecordMatcher(H)}function A(H,ae){if(ae=je({},ae||u.value),typeof H=="string"){const L=Lr(n,H,ae.path),B=t.resolve({path:L.path},ae),X=l.createHref(L.fullPath);return je(L,B,{params:p(B.params),hash:nl(L.hash),redirectedFrom:void 0,href:X})}let ce;if(H.path!=null)ce=je({},H,{path:Lr(n,H.path,ae.path).path});else{const L=je({},H.params);for(const B in L)L[B]==null&&delete L[B];ce=je({},H,{params:f(L)}),ae.params=f(ae.params)}const be=t.resolve(ce,ae),Re=H.hash||"";be.params=c(p(be.params));const b=qp(s,je({},H,{hash:Fp(Re),path:be.path})),T=l.createHref(b);return je({fullPath:b,hash:Re,query:s===ta?rh(H.query):H.query||{}},be,{redirectedFrom:void 0,href:T})}function P(H){return typeof H=="string"?Lr(n,H,u.value.path):je({},H)}function j(H,ae){if(d!==H)return gs(et.NAVIGATION_CANCELLED,{from:ae,to:H})}function O(H){return k(H)}function C(H){return O(je(P(H),{replace:!0}))}function D(H,ae){const ce=H.matched[H.matched.length-1];if(ce&&ce.redirect){const{redirect:be}=ce;let Re=typeof be=="function"?be(H,ae):be;return typeof Re=="string"&&(Re=Re.includes("?")||Re.includes("#")?Re=P(Re):{path:Re},Re.params={}),je({query:H.query,hash:H.hash,params:Re.path!=null?{}:H.params},Re)}}function k(H,ae){const ce=d=A(H),be=u.value,Re=H.state,b=H.force,T=H.replace===!0,L=D(ce,be);if(L)return k(je(P(L),{state:typeof L=="object"?je({},Re,L.state):Re,force:b,replace:T}),ae||ce);const B=ce;B.redirectedFrom=ae;let X;return!b&&Hp(s,be,ce)&&(X=gs(et.NAVIGATION_DUPLICATED,{to:B,from:be}),te(be,be,!0,!1)),(X?Promise.resolve(X):E(B,be)).catch(U=>un(U)?un(U,et.NAVIGATION_GUARD_REDIRECT)?U:oe(U):$(U,B,be)).then(U=>{if(U){if(un(U,et.NAVIGATION_GUARD_REDIRECT))return k(je({replace:T},P(U.to),{state:typeof U.to=="object"?je({},Re,U.to.state):Re,force:b}),ae||B)}else U=I(B,be,!0,T,Re);return S(B,be,U),U})}function _(H,ae){const ce=j(H,ae);return ce?Promise.reject(ce):Promise.resolve()}function w(H){const ae=Y.values().next().value;return ae&&typeof ae.runWithContext=="function"?ae.runWithContext(H):H()}function E(H,ae){let ce;const[be,Re,b]=ih(H,ae);ce=Fr(be.reverse(),"beforeRouteLeave",H,ae);for(const L of be)L.leaveGuards.forEach(B=>{ce.push(An(B,H,ae))});const T=_.bind(null,H,ae);return ce.push(T),Ee(ce).then(()=>{ce=[];for(const L of r.list())ce.push(An(L,H,ae));return ce.push(T),Ee(ce)}).then(()=>{ce=Fr(Re,"beforeRouteUpdate",H,ae);for(const L of Re)L.updateGuards.forEach(B=>{ce.push(An(B,H,ae))});return ce.push(T),Ee(ce)}).then(()=>{ce=[];for(const L of b)if(L.beforeEnter)if(qt(L.beforeEnter))for(const B of L.beforeEnter)ce.push(An(B,H,ae));else ce.push(An(L.beforeEnter,H,ae));return ce.push(T),Ee(ce)}).then(()=>(H.matched.forEach(L=>L.enterCallbacks={}),ce=Fr(b,"beforeRouteEnter",H,ae,w),ce.push(T),Ee(ce))).then(()=>{ce=[];for(const L of o.list())ce.push(An(L,H,ae));return ce.push(T),Ee(ce)}).catch(L=>un(L,et.NAVIGATION_CANCELLED)?L:Promise.reject(L))}function S(H,ae,ce){a.list().forEach(be=>w(()=>be(H,ae,ce)))}function I(H,ae,ce,be,Re){const b=j(H,ae);if(b)return b;const T=ae===$n,L=rs?history.state:{};ce&&(be||T?l.replace(H.fullPath,je({scroll:T&&L&&L.scroll},Re)):l.push(H.fullPath,Re)),u.value=H,te(H,ae,ce,T),oe()}let V;function z(){V||(V=l.listen((H,ae,ce)=>{if(!ne.listening)return;const be=A(H),Re=D(be,ne.currentRoute.value);if(Re){k(je(Re,{replace:!0,force:!0}),be).catch(Gs);return}d=be;const b=u.value;rs&&Qp(ea(b.fullPath,ce.delta),or()),E(be,b).catch(T=>un(T,et.NAVIGATION_ABORTED|et.NAVIGATION_CANCELLED)?T:un(T,et.NAVIGATION_GUARD_REDIRECT)?(k(je(P(T.to),{force:!0}),be).then(L=>{un(L,et.NAVIGATION_ABORTED|et.NAVIGATION_DUPLICATED)&&!ce.delta&&ce.type===lo.pop&&l.go(-1,!1)}).catch(Gs),Promise.reject()):(ce.delta&&l.go(-ce.delta,!1),$(T,be,b))).then(T=>{T=T||I(be,b,!1),T&&(ce.delta&&!un(T,et.NAVIGATION_CANCELLED)?l.go(-ce.delta,!1):ce.type===lo.pop&&un(T,et.NAVIGATION_ABORTED|et.NAVIGATION_DUPLICATED)&&l.go(-1,!1)),S(be,b,T)}).catch(Gs)}))}let ge=Ss(),le=Ss(),F;function $(H,ae,ce){oe(H);const be=le.list();return be.length?be.forEach(Re=>Re(H,ae,ce)):console.error(H),Promise.reject(H)}function W(){return F&&u.value!==$n?Promise.resolve():new Promise((H,ae)=>{ge.add([H,ae])})}function oe(H){return F||(F=!H,z(),ge.list().forEach(([ae,ce])=>H?ce(H):ae()),ge.reset()),H}function te(H,ae,ce,be){const{scrollBehavior:Re}=e;if(!rs||!Re)return Promise.resolve();const b=!ce&&eh(ea(H.fullPath,0))||(be||!ce)&&history.state&&history.state.scroll||null;return er().then(()=>Re(H,ae,b)).then(T=>T&&Zp(T)).catch(T=>$(T,H,ae))}const ee=H=>l.go(H);let G;const Y=new Set,ne={currentRoute:u,listening:!0,addRoute:g,removeRoute:N,clearRoutes:t.clearRoutes,hasRoute:R,getRoutes:x,resolve:A,options:e,push:O,replace:C,go:ee,back:()=>ee(-1),forward:()=>ee(1),beforeEach:r.add,beforeResolve:o.add,afterEach:a.add,onError:le.add,isReady:W,install(H){H.component("RouterLink",Ah),H.component("RouterView",Ph),H.config.globalProperties.$router=ne,Object.defineProperty(H.config.globalProperties,"$route",{enumerable:!0,get:()=>de(u)}),rs&&!G&&u.value===$n&&(G=!0,O(l.location).catch(be=>{}));const ae={};for(const be in $n)Object.defineProperty(ae,be,{get:()=>u.value[be],enumerable:!0});H.provide(ir,ne),H.provide(Lo,du(ae)),H.provide(oo,u);const ce=H.unmount;Y.add(H),H.unmount=function(){Y.delete(H),Y.size<1&&(d=$n,V&&V(),V=null,u.value=$n,G=!1,F=!1),ce()}}};function Ee(H){return H.reduce((ae,ce)=>ae.then(()=>w(ce)),Promise.resolve())}return ne}function Do(){return Dt(ir)}function Fo(e){return Dt(Lo)}class io extends Error{constructor(t,n){super(t),this.status=n}}async function Ne(e,t,n,s=!1){const l={method:e,headers:{}};n!==void 0&&(s?l.body=n:(l.headers["Content-Type"]="application/json",l.body=JSON.stringify(n)));let r;try{r=await fetch("/api"+t,l)}catch{throw new io("Cannot reach the JevFish server. Check that it is running.",0)}const o=await r.text();let a=null;try{a=o?JSON.parse(o):null}catch{a=null}if(!r.ok){const u=a&&a.error||`Request failed with status ${r.status}`;throw new io(u,r.status)}return a}const Ae=encodeURIComponent,Ie={health:()=>Ne("GET","/health"),settings:()=>Ne("GET","/settings"),saveSettings:e=>Ne("PUT","/settings",e),checkKeys:e=>Ne("POST","/settings/check",e),example:()=>Ne("GET","/example"),shutdown:()=>Ne("POST","/shutdown"),task:e=>Ne("GET",`/tasks/${Ae(e)}`),cancelTask:e=>Ne("POST",`/tasks/${Ae(e)}/cancel`),projects:()=>Ne("GET","/projects"),createProject:e=>Ne("POST","/projects",e),project:e=>Ne("GET",`/projects/${Ae(e)}`),patchProject:(e,t)=>Ne("PATCH",`/projects/${Ae(e)}`,t),deleteProject:e=>Ne("DELETE",`/projects/${Ae(e)}`),seed:e=>Ne("GET",`/projects/${Ae(e)}/seed`),addSeed:(e,t,n)=>Ne("POST",`/projects/${Ae(e)}/seed`,{text:t,source:n}),uploadFiles:(e,t)=>{const n=new FormData;for(const s of t)n.append("file",s,s.name);return Ne("POST",`/projects/${Ae(e)}/files`,n,!0)},buildGraph:e=>Ne("POST",`/projects/${Ae(e)}/graph`),graph:e=>Ne("GET",`/projects/${Ae(e)}/graph`),searchGraph:(e,t,n=10)=>Ne("GET",`/projects/${Ae(e)}/graph/search?q=${Ae(t)}&limit=${n}`),prepare:(e,t)=>Ne("POST",`/projects/${Ae(e)}/prepare`,t),frame:e=>Ne("GET",`/projects/${Ae(e)}/frame`),saveFrame:(e,t)=>Ne("PUT",`/projects/${Ae(e)}/frame`,t),crowd:e=>Ne("GET",`/projects/${Ae(e)}/crowd`),estimate:(e,t)=>Ne("POST",`/projects/${Ae(e)}/estimate`,t),runs:e=>Ne("GET",`/projects/${Ae(e)}/runs`),startRun:(e,t)=>Ne("POST",`/projects/${Ae(e)}/runs`,t),run:(e,t)=>Ne("GET",`/projects/${Ae(e)}/runs/${Ae(t)}`),cancelRun:(e,t)=>Ne("POST",`/projects/${Ae(e)}/runs/${Ae(t)}/cancel`),actions:(e,t,n=0,s=500)=>Ne("GET",`/projects/${Ae(e)}/runs/${Ae(t)}/actions?since=${n}&limit=${s}`),polls:(e,t)=>Ne("GET",`/projects/${Ae(e)}/runs/${Ae(t)}/polls`),startReport:(e,t)=>Ne("POST",`/projects/${Ae(e)}/runs/${Ae(t)}/report`),report:(e,t)=>Ne("GET",`/projects/${Ae(e)}/runs/${Ae(t)}/report`),chat:(e,t,n)=>Ne("POST",`/projects/${Ae(e)}/runs/${Ae(t)}/chat`,n),chatHistory:(e,t,n,s)=>Ne("GET",`/projects/${Ae(e)}/runs/${Ae(t)}/chat/${Ae(n)}${s?`?variant=${Ae(s)}`:""}`),ask:(e,t,n)=>Ne("POST",`/projects/${Ae(e)}/runs/${Ae(t)}/ask`,n),asked:(e,t)=>Ne("GET",`/projects/${Ae(e)}/runs/${Ae(t)}/ask`)},Ih=new Set(["done","failed","cancelled"]);async function Mh(e,t,n){let s=e;for(t&&t(s);!Ih.has(s.status);){await new Promise(l=>setTimeout(l,1e3));try{s=await Ie.task(s.id)}catch(l){if(l.status===404)throw new io("The server lost track of this task (it may have restarted).",404);continue}t&&t(s)}return s}const sl=J(null),Ws=J("");async function ao(){try{sl.value=await Ie.health(),Ws.value=""}catch(e){Ws.value=e.message}return sl.value}const ct=(e,t)=>{const n=e.__vccOpts||e;for(const[s,l]of t)n[s]=l;return n},Lh={class:"topbar"},Dh={class:"wrap topbar-inner"},Fh={class:"seg",role:"group","aria-label":"Colour theme"},jh=["aria-pressed"],Uh=["aria-pressed"],Vh=["aria-pressed"],Bh={key:0,class:"wrap banner-wrap"},zh={key:0,class:"notice error",role:"alert"},qh={class:"wrap main"},Hh={__name:"App",setup(e){const t=Fo(),n=K(()=>t.name==="setup"),s=J("auto");try{const o=localStorage.getItem("jevfish-theme");(o==="light"||o==="dark")&&(s.value=o)}catch{}function l(o){s.value=o;const a=document.documentElement;o==="auto"?a.removeAttribute("data-theme"):a.setAttribute("data-theme",o);try{o==="auto"?localStorage.removeItem("jevfish-theme"):localStorage.setItem("jevfish-theme",o)}catch{}}const r=K(()=>{const o=sl.value;if(!o)return[];const a=[];return(o.judge==="fake"||o.llm==="fake")&&a.push("Test mode is on, so every number is made up."),o.judge&&o.judge!=="jev"&&o.judge!=="fake"&&a.push("Jev is not set up yet. Runs and crowd questions will fail until it is."),o.llm&&o.llm!=="fake"&&String(o.llm).startsWith("missing")&&a.push("No language model is set up yet. Graphs, crowds, posts and reports need one."),a});return(o,a)=>{const u=Nn("RouterLink"),d=Nn("RouterView");return h(),m(se,null,[i("header",Lh,[i("div",Dh,[De(u,{to:"/",class:"brand","aria-label":"JevFish home"},{default:Vt(()=>[...a[3]||(a[3]=[i("svg",{width:"28",height:"28",viewBox:"0 0 32 32","aria-hidden":"true"},[i("rect",{width:"32",height:"32",rx:"8",class:"brand-tile"}),i("g",{class:"brand-dots"},[i("circle",{cx:"9",cy:"12",r:"2.2"}),i("circle",{cx:"15",cy:"9",r:"2.2"}),i("circle",{cx:"15",cy:"16",r:"2.2"}),i("circle",{cx:"21",cy:"12",r:"2.2"}),i("circle",{cx:"21",cy:"19",r:"2.2"}),i("circle",{cx:"9",cy:"20",r:"2.2"}),i("circle",{cx:"15",cy:"23",r:"2.2"})])],-1),i("span",null,"JevFish",-1)])]),_:1}),a[5]||(a[5]=i("span",{class:"tagline muted"},"Swarm predictions, one Jev decision per person",-1)),a[6]||(a[6]=i("span",{class:"spacer"},null,-1)),De(u,{to:"/setup",class:"btn small ghost"},{default:Vt(()=>[...a[4]||(a[4]=[xe("Settings",-1)])]),_:1}),i("div",Fh,[i("button",{type:"button","aria-pressed":s.value==="auto",onClick:a[0]||(a[0]=c=>l("auto"))},"Auto",8,jh),i("button",{type:"button","aria-pressed":s.value==="light",onClick:a[1]||(a[1]=c=>l("light"))},"Light",8,Uh),i("button",{type:"button","aria-pressed":s.value==="dark",onClick:a[2]||(a[2]=c=>l("dark"))},"Dark",8,Vh)])])]),!n.value&&(r.value.length||de(Ws))?(h(),m("div",Bh,[de(Ws)?(h(),m("div",zh,y(de(Ws)),1)):q("",!0),(h(!0),m(se,null,me(r.value,c=>(h(),m("div",{key:c,class:"notice warn",role:"status"},[xe(y(c)+" ",1),De(u,{to:"/setup"},{default:Vt(()=>[...a[7]||(a[7]=[xe("Open settings",-1)])]),_:1})]))),128))])):q("",!0),i("main",qh,[De(d)])],64)}}},Gh=ct(Hh,[["__scopeId","data-v-8c98f59b"]]);function Qt(e,t=0){return e==null||Number.isNaN(e)?"-":`${(e*100).toFixed(t)}%`}function Cn(e,t=1){return e==null||Number.isNaN(e)?"-":Number(e).toLocaleString("en-US",{minimumFractionDigits:t,maximumFractionDigits:t})}function Xe(e){return e==null||Number.isNaN(e)?"-":Math.round(e).toLocaleString("en-US")}function ss(e,t=1){if(e==null||Number.isNaN(e))return"-";const n=Number(e),s=Math.abs(n).toFixed(t);return Number(s)===0?0 .toFixed(t):(n>0?"+":"−")+s}function pc(e){if(e==null||Number.isNaN(e))return"-";const t=Number(e);return t===0?"$0":t<.01?`$${t.toFixed(4)}`:`$${t.toFixed(2)}`}function ar(e){if(!e)return"";const t=new Date(e);return Number.isNaN(t.getTime())?"":t.toLocaleString("en-GB",{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"})}const hc={new:"Needs seed text",seeded:"Seeded",graph:"Graph built",prepared:"Crowd ready"};function mc(e,t){let n;return(...s)=>{clearTimeout(n),n=setTimeout(()=>e(...s),t)}}const Wh={class:"stack-lg"},Kh={class:"panel","aria-labelledby":"new-head"},Yh={class:"panel-head"},Jh=["aria-expanded"],Xh={key:0,class:"notice info"},Zh={class:"field"},Qh={class:"field"},em={class:"field"},tm={class:"field"},nm={class:"row"},sm={class:"btn small file-btn"},lm={key:0,class:"file-list"},rm={class:"break"},om={class:"muted small"},im=["onClick"],am={key:1,class:"notice error",role:"alert"},um={class:"row"},cm=["disabled"],dm={"aria-labelledby":"list-head",class:"stack"},fm={class:"row"},pm={key:0,class:"muted small"},hm={key:0,class:"notice error",role:"alert"},mm={key:1,class:"muted"},gm={key:2,class:"panel empty"},vm={key:3,class:"project-list"},ym={class:"project-name break"},bm={class:"project-q break"},_m={class:"project-meta"},km={class:"muted small nowrap"},wm={class:"muted small nowrap"},xm=["onClick","aria-label"],$m=".txt,.md,.markdown,.pdf",Sm={__name:"ProjectsView",setup(e){const t=Do(),n=J([]),s=J(!0),l=J(""),r=J(""),o=J(""),a=J(""),u=J([]),d=J(null),c=J(!1),f=J(""),p=J(!1);async function g(){s.value=!0,l.value="";try{n.value=await Ie.projects(),n.value.length||(p.value=!0)}catch(O){l.value=O.message}finally{s.value=!1}}function N(O){const C=Array.from(O.target.files||[]),D=C.filter(k=>!/\.(txt|md|markdown|pdf)$/i.test(k.name));f.value=D.length?`Only .txt, .md and .pdf files work. Skipped: ${D.map(k=>k.name).join(", ")}`:"",u.value=C.filter(k=>/\.(txt|md|markdown|pdf)$/i.test(k.name)&&k.size<=25*1024*1024),C.some(k=>k.size>25*1024*1024)&&(f.value="Files must be 25 MB or smaller.")}function x(O){u.value=u.value.filter((C,D)=>D!==O),!u.value.length&&d.value&&(d.value.value="")}async function R(){if(f.value="",!o.value.trim()){f.value="Write the prediction question first.";return}c.value=!0;let O=null;try{O=await Ie.createProject({name:r.value.trim()||o.value.trim().slice(0,60),requirement:o.value.trim(),seed_text:a.value}),u.value.length&&await Ie.uploadFiles(O.id,u.value),t.push({name:"graph",params:{pid:O.id}})}catch(C){O?t.push({name:"graph",params:{pid:O.id},query:{uploadError:C.message}}):f.value=C.message}finally{c.value=!1}}const A=J(!1);async function P(){f.value="";try{const O=await Ie.example();r.value=O.name,o.value=O.requirement,a.value=O.seed_text,p.value=!0,A.value=!0}catch(O){f.value=O.message}}async function j(O){if(window.confirm(`Delete "${O.name}" and all its runs? This cannot be undone.`))try{await Ie.deleteProject(O.id),n.value=n.value.filter(C=>C.id!==O.id)}catch(C){l.value=C.message}}return al(g),(O,C)=>{const D=Nn("RouterLink");return h(),m("div",Wh,[C[16]||(C[16]=i("section",{class:"intro"},[i("h1",null,"What should the crowd predict?"),i("p",{class:"muted"}," Give JevFish a yes or no question and the documents behind it. It maps the people and facts, builds a synthetic crowd, lets them argue on a simulated social feed, and polls every person with Jev. ")],-1)),i("section",Kh,[i("div",Yh,[C[4]||(C[4]=i("h2",{id:"new-head"},"New prediction",-1)),C[5]||(C[5]=i("span",{class:"spacer"},null,-1)),i("button",{class:"btn small ghost",type:"button",onClick:P},"Fill in the example"),n.value.length?(h(),m("button",{key:0,class:"btn small ghost",type:"button","aria-expanded":p.value,onClick:C[0]||(C[0]=k=>p.value=!p.value)},y(p.value?"Hide form":"Show form"),9,Jh)):q("",!0)]),p.value?(h(),m("form",{key:0,class:"new-form",onSubmit:kn(R,["prevent"])},[A.value?(h(),m("p",Xh,"The example is a Singapore co-living brand with made-up figures.")):q("",!0),i("label",Zh,[C[6]||(C[6]=i("span",{class:"label"},"Prediction question",-1)),Se(i("input",{"onUpdate:modelValue":C[1]||(C[1]=k=>o.value=k),type:"text",placeholder:"Would a weekly cleaning upgrade make more renters book a viewing?",required:""},null,512),[[Le,o.value]]),C[7]||(C[7]=i("span",{class:"hint"},"Phrase it so each simulated person can answer yes or no.",-1))]),i("label",Qh,[C[8]||(C[8]=i("span",{class:"label"},[xe("Project name "),i("span",{class:"muted"},"(optional)")],-1)),Se(i("input",{"onUpdate:modelValue":C[2]||(C[2]=k=>r.value=k),type:"text",placeholder:"Cleaning upgrade"},null,512),[[Le,r.value]])]),i("label",em,[C[9]||(C[9]=i("span",{class:"label"},"Seed text",-1)),Se(i("textarea",{"onUpdate:modelValue":C[3]||(C[3]=k=>a.value=k),rows:"7",placeholder:"Paste the brief, survey notes, articles or anything the crowd should know about."},null,512),[[Le,a.value]])]),i("div",tm,[C[12]||(C[12]=i("span",{class:"label"},"Or add files",-1)),i("div",nm,[i("label",sm,[C[10]||(C[10]=xe(" Choose files ",-1)),i("input",{ref_key:"fileInput",ref:d,class:"sr-only",type:"file",multiple:"",accept:$m,onChange:N},null,544)]),C[11]||(C[11]=i("span",{class:"hint"},".txt, .md or .pdf, up to 25 MB each",-1))]),u.value.length?(h(),m("ul",lm,[(h(!0),m(se,null,me(u.value,(k,_)=>(h(),m("li",{key:k.name+_},[i("span",rm,y(k.name),1),i("span",om,y(Math.max(1,Math.round(k.size/1024)))+" KB",1),i("button",{class:"btn small ghost",type:"button",onClick:w=>x(_)},"Remove",8,im)]))),128))])):q("",!0)]),f.value?(h(),m("div",am,y(f.value),1)):q("",!0),i("div",um,[i("button",{class:"btn primary",type:"submit",disabled:c.value||!o.value.trim()},y(c.value?"Creating project":"Create project"),9,cm),C[13]||(C[13]=i("span",{class:"muted small"},"You can add more sources on the next screen.",-1))])],32)):q("",!0)]),i("section",dm,[i("div",fm,[C[14]||(C[14]=i("h2",{id:"list-head"},"Projects",-1)),n.value.length?(h(),m("span",pm,y(n.value.length)+" total, newest first",1)):q("",!0)]),l.value?(h(),m("div",hm,y(l.value),1)):q("",!0),s.value?(h(),m("p",mm,"Loading projects")):!n.value.length&&!l.value?(h(),m("div",gm,[...C[15]||(C[15]=[i("h3",null,"No projects yet",-1),i("p",null,"Start with a question and some seed text above.",-1)])])):(h(),m("ul",vm,[(h(!0),m(se,null,me(n.value,k=>(h(),m("li",{key:k.id,class:"project"},[De(D,{to:{name:"graph",params:{pid:k.id}},class:"project-link"},{default:Vt(()=>[i("span",ym,y(k.name||"Untitled"),1),i("span",bm,y(k.requirement),1)]),_:2},1032,["to"]),i("div",_m,[i("span",{class:He(["pill",{good:k.stage==="prepared",accent:k.stage==="graph"}])},y(de(hc)[k.stage]||k.stage),3),i("span",km,y(k.sources.length)+" "+y(k.sources.length===1?"source":"sources"),1),i("span",wm,"Updated "+y(de(ar)(k.updated_at)),1),i("button",{class:"btn small ghost danger",type:"button",onClick:_=>j(k),"aria-label":`Delete ${k.name}`},"Delete",8,xm)])]))),128))]))])])}}},Tm=ct(Sm,[["__scopeId","data-v-ad940d1f"]]),gc=Symbol("workspace");function cl(){return Dt(gc)}const ll=new Set(["done","partial"]),uo=new Set(["queued","running"]);function vc(e){if(!e)return"";const t=e.config||{},n=new Date(e.created_at),s=Number.isNaN(n.getTime())?e.id:n.toLocaleString("en-GB",{day:"numeric",month:"short",hour:"2-digit",minute:"2-digit"}),l={queued:"queued",running:"running",done:"finished",partial:"partly finished",failed:"failed",cancelled:"cancelled"}[e.status]||e.status;return`${s}, ${t.platform||"reddit"}, ${t.rounds??"?"} rounds, ${l}`}const Em={class:"stack-lg"},Am={key:0,class:"notice error",role:"alert"},Rm={class:"ws-head"},Cm={class:"row title-row"},Om={class:"break"},Pm={class:"question break"},Nm={class:"field"},Im={class:"field"},Mm={key:0,class:"notice error"},Lm={class:"row"},Dm={class:"stepbar","aria-label":"Prediction steps"},Fm={class:"steps"},jm={class:"step-n","aria-hidden":"true"},Um={key:0,width:"12",height:"12",viewBox:"0 0 12 12"},Vm=["title"],Bm={class:"step-n","aria-hidden":"true"},zm={class:"sr-only"},qm={key:0,class:"run-pick"},Hm=["value"],Gm={key:0,class:"panel empty"},Wm={key:2,class:"muted"},Km={__name:"WorkspaceView",props:{pid:{type:String,required:!0}},setup(e){const t=e,n=Fo(),s=Do(),l=J(null),r=J(""),o=Hn({}),a=new Set,u=fs(null),d=fs(null),c=Hn({});let f=!0;Gn(()=>f=!1);const p=K(()=>["new","seeded","graph","prepared"].indexOf(l.value?.stage??"new")),g=K(()=>[...l.value?.runs||[]].sort((le,F)=>le.created_atg.value.filter(le=>ll.has(le.status))),x=K({get(){const le=n.query.run;return le&&g.value.some(F=>F.id===le)?le:g.value[0]?.id||""},set(le){s.replace({query:{...n.query,run:le||void 0}})}}),R=K(()=>g.value.find(le=>le.id===x.value)||null);async function A(){try{const le=await Ie.project(t.pid);if(!f)return;l.value=le,r.value="",P(le.tasks||[])}catch(le){r.value=le.message}}function P(le){const F=new Set;for(const $ of[...le].sort((W,oe)=>W.created_atnew Date(o[$.kind].created_at))&&(a.has($.id)||(o[$.kind]=$)),($.status==="queued"||$.status==="running")&&!a.has($.id)&&j($))}async function j(le){a.add(le.id),o[le.kind]=le;try{const F=await Mh(le,$=>{f&&(!o[$.kind]||o[$.kind].id===$.id)&&(o[$.kind]=$)});if(le.kind==="prepare"&&F.status==="done"&&(u.value=null,d.value=null),F.kind==="run"||F.kind==="report"){const $=F.result?.run_id||x.value;$&&delete c[$]}return f&&await A(),F}catch(F){const $={...o[le.kind],status:"failed",error:F.message};return o[le.kind]=$,$}finally{a.delete(le.id)}}async function O(le=!1){return(!u.value||le)&&(u.value=await Ie.frame(t.pid)),u.value}async function C(le=!1){return(!d.value||le)&&(d.value=await Ie.crowd(t.pid)),d.value}async function D(le,F=!1){return le?((!c[le]||F)&&(c[le]=await Ie.run(t.pid,le)),c[le]):null}const k=K(()=>{const le=l.value,F=p.value,$=N.value.length>0;return[{name:"graph",n:1,title:"Graph",open:!0,done:!!le?.graph_stats,why:""},{name:"crowd",n:2,title:"Crowd",open:F>=2,done:!!le?.crowd_stats,why:"Build the graph first"},{name:"simulate",n:3,title:"Simulate",open:F>=3,done:$,why:"Prepare the crowd first"},{name:"report",n:4,title:"Report",open:$,done:!!R.value?.report_ready,why:"Finish a run first"},{name:"ask",n:5,title:"Ask",open:$,done:!1,why:"Finish a run first"}]}),_=K(()=>k.value.find(le=>le.name===n.name)||k.value[0]),w=J(!1),E=J(""),S=J(""),I=J("");function V(){E.value=l.value?.name||"",S.value=l.value?.requirement||"",I.value="",w.value=!0}async function z(){try{await Ie.patchProject(t.pid,{name:E.value,requirement:S.value}),w.value=!1,await A()}catch(le){I.value=le.message}}let ge=null;return Je(()=>g.value.some(le=>uo.has(le.status)),le=>{clearInterval(ge),le&&(ge=setInterval(A,2e3))},{immediate:!0}),Gn(()=>clearInterval(ge)),Je(()=>t.pid,()=>{l.value=null,u.value=null,d.value=null,A()},{immediate:!0}),Bs(gc,{pid:K(()=>t.pid),overview:l,refresh:A,tasks:o,track:j,runs:g,finishedRuns:N,selectedRunId:x,selectedRun:R,loadFrame:O,loadCrowd:C,loadRun:D,runDetails:c,frame:u,crowd:d,steps:k}),(le,F)=>{const $=Nn("RouterLink"),W=Nn("RouterView");return h(),m("div",Em,[De($,{to:"/",class:"back small"},{default:Vt(()=>[...F[4]||(F[4]=[xe("All projects",-1)])]),_:1}),r.value?(h(),m("div",Am,y(r.value),1)):q("",!0),l.value?(h(),m(se,{key:1},[i("header",Rm,[w.value?(h(),m("form",{key:1,class:"edit-form",onSubmit:kn(z,["prevent"])},[i("label",Nm,[F[5]||(F[5]=i("span",{class:"label"},"Project name",-1)),Se(i("input",{"onUpdate:modelValue":F[0]||(F[0]=oe=>E.value=oe),type:"text"},null,512),[[Le,E.value]])]),i("label",Im,[F[6]||(F[6]=i("span",{class:"label"},"Prediction question",-1)),Se(i("textarea",{"onUpdate:modelValue":F[1]||(F[1]=oe=>S.value=oe),rows:"2"},null,512),[[Le,S.value]])]),I.value?(h(),m("div",Mm,y(I.value),1)):q("",!0),i("div",Lm,[F[7]||(F[7]=i("button",{class:"btn primary small",type:"submit"},"Save",-1)),i("button",{class:"btn small",type:"button",onClick:F[2]||(F[2]=oe=>w.value=!1)},"Cancel")])],32)):(h(),m(se,{key:0},[i("div",Cm,[i("h1",Om,y(l.value.name||"Untitled"),1),i("span",{class:He(["pill",{good:l.value.stage==="prepared"}])},y(de(hc)[l.value.stage]||l.value.stage),3),i("button",{class:"btn small ghost",type:"button",onClick:V},"Edit")]),i("p",Pm,y(l.value.requirement),1)],64))]),i("nav",Dm,[i("ol",Fm,[(h(!0),m(se,null,me(k.value,oe=>(h(),m("li",{key:oe.name},[oe.open?(h(),ln($,{key:0,to:{name:oe.name,params:{pid:e.pid},query:de(n).query.run?{run:de(n).query.run}:{}},class:He(["step",{current:_.value.name===oe.name,done:oe.done}]),"aria-current":_.value.name===oe.name?"step":void 0},{default:Vt(()=>[i("span",jm,[oe.done&&_.value.name!==oe.name?(h(),m("svg",Um,[...F[8]||(F[8]=[i("path",{d:"M2.5 6.2l2.3 2.3 4.7-5",fill:"none",stroke:"currentColor","stroke-width":"1.8","stroke-linecap":"round","stroke-linejoin":"round"},null,-1)])])):(h(),m(se,{key:1},[xe(y(oe.n),1)],64))]),i("span",null,y(oe.title),1)]),_:2},1032,["to","class","aria-current"])):(h(),m("span",{key:1,class:"step locked",title:oe.why,"aria-disabled":"true"},[i("span",Bm,y(oe.n),1),i("span",null,y(oe.title),1),i("span",zm,"(locked: "+y(oe.why)+")",1)],8,Vm))]))),128))]),g.value.length?(h(),m("label",qm,[F[9]||(F[9]=i("span",{class:"small muted"},"Run",-1)),Se(i("select",{"onUpdate:modelValue":F[3]||(F[3]=oe=>x.value=oe)},[(h(!0),m(se,null,me(g.value,oe=>(h(),m("option",{key:oe.id,value:oe.id},y(de(vc)(oe)),9,Hm))),128))],512),[[_n,x.value]])])):q("",!0)]),_.value.open?(h(),ln(W,{key:e.pid})):(h(),m("div",Gm,[i("h3",null,y(_.value.title)+" is not ready yet",1),i("p",null,y(_.value.why)+".",1)]))],64)):r.value?q("",!0):(h(),m("p",Wm,"Loading project"))])}}},Ym=ct(Km,[["__scopeId","data-v-9f3ef09d"]]),Jm=8;function nn(e){return e=(f=(a+d)/2))?a=f:d=f,(R=n>=(p=(u+c)/2))?u=p:c=p,l=r,!(r=r[A=R<<1|x]))return l[A]=o,e;if(g=+e._x.call(null,r.data),N=+e._y.call(null,r.data),t===g&&n===N)return o.next=r,l?l[A]=o:e._root=o,e;do l=l?l[A]=new Array(4):e._root=new Array(4),(x=t>=(f=(a+d)/2))?a=f:d=f,(R=n>=(p=(u+c)/2))?u=p:c=p;while((A=R<<1|x)===(P=(N>=p)<<1|g>=f));return l[P]=r,l[A]=o,e}function Zm(e){var t,n,s=e.length,l,r,o=new Array(s),a=new Array(s),u=1/0,d=1/0,c=-1/0,f=-1/0;for(n=0;nc&&(c=l),rf&&(f=r));if(u>c||d>f)return this;for(this.cover(u,d).cover(c,f),n=0;ne||e>=l||s>t||t>=r;)switch(d=(tc||(a=N.y0)>f||(u=N.x1)=A)<<1|e>=R)&&(N=p[p.length-1],p[p.length-1]=p[p.length-1-x],p[p.length-1-x]=N)}else{var P=e-+this._x.call(null,g.data),j=t-+this._y.call(null,g.data),O=P*P+j*j;if(O=(p=(o+u)/2))?o=p:u=p,(x=f>=(g=(a+d)/2))?a=g:d=g,t=n,!(n=n[R=x<<1|N]))return this;if(!n.length)break;(t[R+1&3]||t[R+2&3]||t[R+3&3])&&(s=t,A=R)}for(;n.data!==e;)if(l=n,!(n=n.next))return this;return(r=n.next)&&delete n.next,l?(r?l.next=r:delete l.next,this):t?(r?t[R]=r:delete t[R],(n=t[0]||t[1]||t[2]||t[3])&&n===(t[3]||t[2]||t[1]||t[0])&&!n.length&&(s?s[A]=n:this._root=n),this):(this._root=r,this)}function lg(e){for(var t=0,n=e.length;tp.index){var S=g-_.x-_.vx,I=N-_.y-_.vy,V=S*S+I*I;Vg+E||DN+E||kd.r&&(d.r=d[c].r)}function u(){if(t){var d,c=t.length,f;for(n=new Array(c),d=0;d[t(C,D,o),C])),O;for(R=0,a=new Array(A);R{}};function bc(){for(var e=0,t=arguments.length,n={},s;e=0&&(s=n.slice(l+1),n=n.slice(0,l)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:s}})}Cl.prototype=bc.prototype={constructor:Cl,on:function(e,t){var n=this._,s=bg(e+"",n),l,r=-1,o=s.length;if(arguments.length<2){for(;++r0)for(var n=new Array(l),s=0,l,r;s=0&&e._call.call(void 0,t),e=e._next;--vs}function va(){Wn=(Bl=rl.now())+ur,vs=Ms=0;try{wg()}finally{vs=0,$g(),Wn=0}}function xg(){var e=rl.now(),t=e-Bl;t>_c&&(ur-=t,Bl=e)}function $g(){for(var e,t=Vl,n,s=1/0;t;)t._call?(s>t._time&&(s=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:Vl=n);Ls=e,fo(s)}function fo(e){if(!vs){Ms&&(Ms=clearTimeout(Ms));var t=e-Wn;t>24?(e<1/0&&(Ms=setTimeout(va,e-rl.now()-ur)),Ts&&(Ts=clearInterval(Ts))):(Ts||(Bl=rl.now(),Ts=setInterval(xg,_c)),vs=1,kc(va))}}const Sg=1664525,Tg=1013904223,ya=4294967296;function Eg(){let e=1;return()=>(e=(Sg*e+Tg)%ya)/ya}function Ag(e){return e.x}function Rg(e){return e.y}var Cg=10,Og=Math.PI*(3-Math.sqrt(5));function Pg(e){var t,n=1,s=.001,l=1-Math.pow(s,1/300),r=0,o=.6,a=new Map,u=xc(f),d=bc("tick","end"),c=Eg();e==null&&(e=[]);function f(){p(),d.call("tick",t),n1?(R==null?a.delete(x):a.set(x,N(R)),t):a.get(x)},find:function(x,R,A){var P=0,j=e.length,O,C,D,k,_;for(A==null?A=1/0:A*=A,P=0;P1?(d.on(x,R),t):d.on(x)}}}function Ng(){var e,t,n,s,l=$t(-30),r,o=1,a=1/0,u=.81;function d(g){var N,x=e.length,R=jo(e,Ag,Rg).visitAfter(f);for(s=g,N=0;N=a)return;(g.data!==t||g.next)&&(A===0&&(A=On(n),O+=A*A),P===0&&(P=On(n),O+=P*P),OObject.fromEntries(n.types.map((te,ee)=>[te,ee])));function R(te){const ee=x.value[te];return ee==null?"var(--s-other)":nn(ee)}function A(te){return 5+Math.sqrt(te.degree||0)*3.2}const P=K(()=>{a.value;const te=[...u.value].sort((G,Y)=>(Y.degree||0)-(G.degree||0)),ee=new Set(te.slice(0,u.value.length>60?14:30).map(G=>G.id));return n.selectedId&&ee.add(n.selectedId),f.value&&ee.add(f.value.id),ee}),j=K(()=>{const te=new Set;if(!n.selectedId)return te;for(const ee of d.value)ee.source.id===n.selectedId&&te.add(ee.target.id),ee.target.id===n.selectedId&&te.add(ee.source.id);return te});function O(){g&&g.stop();const te=new Map(u.value.map(ae=>[ae.id,ae])),ee=r.value,G=o.value,Y=n.nodes.map(ae=>{const ce=te.get(ae.id);return{...ae,x:ce?.x??ee/2+(Math.random()-.5)*ee*.5,y:ce?.y??G/2+(Math.random()-.5)*G*.5}}),ne=new Set(Y.map(ae=>ae.id)),Ee=n.edges.filter(ae=>ne.has(ae.source)&&ne.has(ae.target)&&ae.source!==ae.target).map(ae=>({...ae}));u.value=Y,d.value=Ee;const H=window.matchMedia&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;if(g=Pg(Y).force("link",vg(Ee).id(ae=>ae.id).distance(70).strength(.4)).force("charge",Ng().strength((Y.length>150?-90:-220)*Math.min(1,Math.max(.45,ee/800)))).force("center",pa(ee/2,G/2)).force("x",ba(ee/2).strength(.04)).force("y",_a(G/2).strength(.06)).force("collide",mg(ae=>A(ae)+6)).on("tick",()=>{C(),a.value++}),H){g.stop();for(let ae=0;ae<300;ae++)g.tick(),C();a.value++}}function C(){const te=r.value,ee=o.value;for(const G of u.value){const Y=A(G)+6;G.x=Math.max(Y+20,Math.min(te-Y-20,G.x)),G.y=Math.max(Y,Math.min(ee-Y-14,G.y))}}function D(){if(!l.value)return;const te=Math.max(240,l.value.clientWidth),ee=te<600?380:520;(Math.abs(te-r.value)>4||ee!==o.value)&&(r.value=te,o.value=ee,g&&(g.force("center",pa(te/2,ee/2)).force("x",ba(te/2).strength(.04)).force("y",_a(ee/2).strength(.06)),g.alpha(.3).restart()))}al(()=>{D(),O(),N=new ResizeObserver(D),N.observe(l.value)}),Gn(()=>{g&&g.stop(),N&&N.disconnect()}),Je(()=>[n.nodes,n.edges],O);const k=J(null);let _=null;function w(te){const ee=k.value.getBoundingClientRect(),G=c.value;return{x:(te.clientX-ee.left-G.x)/G.k,y:(te.clientY-ee.top-G.y)/G.k}}function E(te,ee){te.stopPropagation(),k.value.setPointerCapture(te.pointerId),_={kind:"node",node:ee,moved:!1,sx:te.clientX,sy:te.clientY},ee.fx=ee.x,ee.fy=ee.y}function S(te){k.value.setPointerCapture(te.pointerId),_={kind:"pan",sx:te.clientX,sy:te.clientY,vx:c.value.x,vy:c.value.y,moved:!1}}function I(te){if(!_)return;const ee=te.clientX-_.sx,G=te.clientY-_.sy;if(Math.abs(ee)+Math.abs(G)>3&&(_.moved=!0),_.kind==="pan")c.value={...c.value,x:_.vx+ee,y:_.vy+G};else if(_.moved){const Y=w(te);_.node.fx=Y.x,_.node.fy=Y.y,f.value=null,g.alphaTarget(.2).restart()}}function V(){if(_){if(_.kind==="node"){const te=_.node;te.fx=null,te.fy=null,g.alphaTarget(0),_.moved||s("select",te.id===n.selectedId?"":te.id)}else _.moved||s("select","");_=null}}function z(te,ee=r.value/2,G=o.value/2){const Y=c.value,ne=Math.min(4,Math.max(.3,Y.k*te)),Ee=ne/Y.k;c.value={k:ne,x:ee-(ee-Y.x)*Ee,y:G-(G-Y.y)*Ee}}function ge(te){if(!(te.ctrlKey||te.metaKey))return;te.preventDefault();const ee=k.value.getBoundingClientRect();z(Math.exp(-te.deltaY*.01),te.clientX-ee.left,te.clientY-ee.top)}function le(){c.value={x:0,y:0,k:1},g&&g.alpha(.5).restart()}function F(te,ee){_||(f.value=ee,$(te))}function $(te){const G=Math.min(te.clientX+14,window.innerWidth-300),Y=Math.min(te.clientY+14,window.innerHeight-140);p.value={x:Math.max(8,G),y:Y}}function W(te,ee){(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),s("select",ee.id===n.selectedId?"":ee.id))}Je(()=>n.selectedId,te=>{if(!te)return;const ee=u.value.find(Ee=>Ee.id===te);if(!ee)return;const G=c.value,Y=ee.x*G.k+G.x,ne=ee.y*G.k+G.y;(Y<40||Y>r.value-40||ne<40||ne>o.value-40)&&(c.value={...G,x:r.value/2-ee.x*G.k,y:o.value/2-ee.y*G.k})});function oe(te,ee=22){return te.length>ee?te.slice(0,ee-1)+"…":te}return(te,ee)=>(h(),m("div",Ig,[i("div",{ref_key:"box",ref:l,class:"fg-box",style:We({height:o.value+"px"})},[(h(),m("svg",{ref_key:"svg",ref:k,width:r.value,height:o.value,role:"img","aria-label":`Knowledge graph with ${e.nodes.length} entities and ${e.edges.length} relations`,onPointerdown:S,onPointermove:I,onPointerup:V,onPointercancel:V,onWheel:ge},[i("g",{transform:`translate(${c.value.x},${c.value.y}) scale(${c.value.k})`,"data-tick":a.value},[i("g",Dg,[(h(!0),m(se,null,me(d.value,G=>(h(),m("line",{key:G.id,x1:G.source.x,y1:G.source.y,x2:G.target.x,y2:G.target.y,class:He({hot:e.selectedId&&(G.source.id===e.selectedId||G.target.id===e.selectedId),dim:e.selectedId&&G.source.id!==e.selectedId&&G.target.id!==e.selectedId,edgehit:e.highlightEdge===G.id})},null,10,Fg))),128))]),i("g",jg,[(h(!0),m(se,null,me(u.value,G=>(h(),m("g",{key:G.id,class:He(["node",{sel:G.id===e.selectedId,dim:e.selectedId&&G.id!==e.selectedId&&!j.value.has(G.id)}]),transform:`translate(${G.x},${G.y})`,tabindex:"0",role:"button","aria-label":`${G.name}, ${G.type}, ${G.degree} connections`,onPointerdown:Y=>E(Y,G),onPointerenter:Y=>F(Y,G),onPointermove:$,onPointerleave:ee[0]||(ee[0]=Y=>f.value=null),onKeydown:Y=>W(Y,G),onFocus:ee[1]||(ee[1]=Y=>f.value=null)},[i("circle",{class:"hit",r:Math.max(12,A(G)+4)},null,8,Vg),i("circle",{class:"dot",r:A(G),style:We({fill:R(G.type)})},null,12,Bg),P.value.has(G.id)?(h(),m("text",{key:0,y:A(G)+13,"text-anchor":"middle"},y(oe(G.name)),9,zg)):q("",!0)],42,Ug))),128))])],8,Lg)],40,Mg)),i("div",qg,[i("button",{class:"btn small icon",type:"button","aria-label":"Zoom in",onClick:ee[2]||(ee[2]=G=>z(1.25))},"+"),i("button",{class:"btn small icon",type:"button","aria-label":"Zoom out",onClick:ee[3]||(ee[3]=G=>z(.8))},"−"),i("button",{class:"btn small",type:"button",onClick:le},"Reset")])],4),ee[4]||(ee[4]=i("p",{class:"small muted hint"},"Drag to pan, drag a dot to move it, click a dot for its facts. Hold Ctrl or Cmd and scroll to zoom.",-1)),(h(),ln(wu,{to:"body"},[f.value?(h(),m("div",{key:0,class:"chart-tooltip",style:We({left:p.value.x+"px",top:p.value.y+"px"})},[i("div",Hg,[i("span",{class:"swatch",style:We({background:R(f.value.type)})},null,4),i("strong",null,y(f.value.name),1)]),i("div",Gg,y(f.value.type)+", "+y(f.value.degree)+" "+y(f.value.degree===1?"connection":"connections"),1),f.value.summary?(h(),m("div",Wg,y(f.value.summary.length>180?f.value.summary.slice(0,179)+"…":f.value.summary),1)):q("",!0)],4)):q("",!0)]))]))}},Yg=ct(Kg,[["__scopeId","data-v-be080fe7"]]),Jg={class:"task-top"},Xg={key:0,class:"muted small tnum"},Zg=["aria-valuenow"],Qg={key:1,class:"small muted break"},ev={key:2,class:"notice error break"},tv={__name:"TaskStatus",props:{task:{type:Object,default:null},label:{type:String,default:""},cancellable:{type:Boolean,default:!1},hideDone:{type:Boolean,default:!1}},emits:["cancel"],setup(e){const t=e,n={queued:"Waiting to start",running:"Working",done:"Finished",failed:"Failed",cancelled:"Cancelled"},s=K(()=>t.task&&(t.task.status==="queued"||t.task.status==="running")),l=K(()=>Math.round(Math.max(0,Math.min(1,t.task?.progress||0))*100));return(r,o)=>e.task&&!(e.hideDone&&e.task.status==="done")?(h(),m("div",{key:0,class:He(["task",e.task.status]),role:"status","aria-live":"polite"},[i("div",Jg,[i("strong",null,y(e.label||n[e.task.status]),1),s.value?(h(),m("span",Xg,y(l.value)+"%",1)):(h(),m("span",{key:1,class:He(["pill",{good:e.task.status==="done",bad:e.task.status==="failed",warn:e.task.status==="cancelled"}])},y(n[e.task.status]||e.task.status),3)),o[1]||(o[1]=i("span",{class:"spacer"},null,-1)),e.cancellable&&s.value?(h(),m("button",{key:2,class:"btn small danger",type:"button",onClick:o[0]||(o[0]=a=>r.$emit("cancel"))},"Cancel")):q("",!0)]),s.value?(h(),m("div",{key:0,class:"progress",role:"progressbar","aria-valuenow":l.value,"aria-valuemin":"0","aria-valuemax":"100"},[i("div",{style:We({width:l.value+"%"})},null,4)],8,Zg)):q("",!0),e.task.message?(h(),m("p",Qg,y(e.task.message),1)):q("",!0),e.task.error?(h(),m("p",ev,y(e.task.error),1)):q("",!0)],2)):q("",!0)}},cr=ct(tv,[["__scopeId","data-v-f35b8610"]]),nv={class:"stack-lg"},sv={class:"grid-2"},lv={class:"panel","aria-labelledby":"src-head"},rv={class:"panel-head"},ov={key:0},iv={key:0,class:"sources"},av={class:"break"},uv={class:"muted small tnum nowrap"},cv={class:"muted small nowrap"},dv={key:1,class:"muted"},fv=["open"],pv={class:"field"},hv={class:"field"},mv={class:"row"},gv=["disabled"],vv=["disabled"],yv={key:2,class:"notice error",role:"alert"},bv={class:"panel stack","aria-labelledby":"build-head"},_v={class:"row"},kv=["disabled"],wv={key:0,class:"muted small"},xv={key:1,class:"muted small"},$v={key:0,class:"notice error",role:"alert"},Sv={key:1,class:"stats"},Tv={key:2,class:"type-counts"},Ev={class:"tnum"},Av={key:3,class:"notice warn"},Rv={key:0,class:"notice error",role:"alert"},Cv={key:1,class:"panel","aria-labelledby":"map-head"},Ov={class:"panel-head"},Pv={class:"seg",role:"group","aria-label":"View"},Nv=["aria-pressed"],Iv=["aria-pressed"],Mv={class:"legend graph-legend","aria-label":"Entity types"},Lv={key:0},Dv={class:"grid-side map-grid"},Fv={class:"map-main"},jv={key:0,class:"empty"},Uv={key:2,class:"table-scroll node-table"},Vv={class:"data"},Bv=["onClick"],zv={class:"nowrap"},qv={class:"num"},Hv={class:"num"},Gv={class:"summary"},Wv={class:"side stack"},Kv={class:"field"},Yv={key:0,class:"notice error"},Jv={key:1,class:"results"},Xv=["onClick"],Zv={class:"r-title"},Qv={class:"muted small"},ey={class:"r-title"},ty={class:"muted small break"},ny={key:2,class:"muted small"},sy={key:3,class:"detail"},ly={class:"row"},ry={class:"break"},oy={class:"muted small"},iy={class:"break"},ay={key:0,class:"facts"},uy={class:"small"},cy=["onClick"],dy={key:1},fy={class:"muted rel"},py=["onClick"],hy={key:3},my={class:"small muted break"},gy={key:1,class:"muted small"},vy={key:4,class:"muted small"},yy={__name:"StepGraph",setup(e){const t=cl(),n=Fo(),s=Do(),l=t.pid,r=K(()=>t.overview.value),o=K(()=>t.tasks.graph),a=K(()=>o.value&&(o.value.status==="queued"||o.value.status==="running")),u=J(""),d=J(""),c=J(n.query.uploadError?`The project was created but a file failed: ${n.query.uploadError}`:""),f=J(!1),p=J(null);n.query.uploadError&&s.replace({query:{...n.query,uploadError:void 0}});async function g(){c.value="",f.value=!0;try{await Ie.addSeed(l.value,u.value,d.value.trim()||void 0),u.value="",d.value="",await t.refresh()}catch(G){c.value=G.message}finally{f.value=!1}}async function N(G){const Y=Array.from(G.target.files||[]);if(!Y.length)return;c.value="";const ne=Y.filter(H=>!/\.(txt|md|markdown|pdf)$/i.test(H.name));ne.length&&(c.value=`Only .txt, .md and .pdf files work. Skipped: ${ne.map(H=>H.name).join(", ")}`);const Ee=Y.filter(H=>!ne.includes(H));if(Ee.length){f.value=!0;try{await Ie.uploadFiles(l.value,Ee),await t.refresh()}catch(H){c.value=H.message}finally{f.value=!1}}p.value&&(p.value.value="")}const x=J("");async function R(){x.value="";try{const G=await Ie.buildGraph(l.value);(await t.track(G)).status==="done"&&await j()}catch(G){x.value=G.message}}const A=J(null),P=J("");async function j(){P.value="";try{A.value=await Ie.graph(l.value)}catch(G){G.status!==400&&(P.value=G.message),A.value=null}}Je(()=>r.value?.graph_stats&&r.value.updated_at,(G,Y)=>{r.value?.graph_stats&&(!A.value||G!==Y)&&j()},{immediate:!0});const O=K(()=>{if(!A.value)return[];const G=(A.value.ontology?.entity_types||[]).map(ce=>ce.name),Y=new Set(G),ne=[...new Set(A.value.nodes.map(ce=>ce.type))].filter(ce=>!Y.has(ce)),Ee=[...G,...ne],H=A.value.stats?.types||{};return Ee.filter(ce=>H[ce]||A.value.nodes.some(be=>be.type===ce))}),C=K(()=>O.value.slice(0,8)),D=K(()=>O.value.length-8),k=K(()=>Object.fromEntries((A.value?.nodes||[]).map(G=>[G.id,G]))),_=J(""),w=J(""),E=K(()=>k.value[_.value]||null),S=K(()=>E.value?A.value.edges.filter(G=>G.source===_.value||G.target===_.value):[]);function I(G){_.value=G,G||(w.value="")}const V=J(""),z=J([]),ge=J(!1),le=J(""),F=mc(async G=>{if(!G.trim()){z.value=[];return}ge.value=!0,le.value="";try{z.value=await Ie.searchGraph(l.value,G,10)}catch(Y){le.value=Y.message}finally{ge.value=!1}},300);Je(V,G=>F(G));function $(G){G.kind==="node"?(_.value=G.item.id,w.value=""):(_.value=G.item.source,w.value=G.item.id)}function W(G){const Y=k.value[G.source]?.name||G.source,ne=k.value[G.target]?.name||G.target;return`${Y} ${G.type.toLowerCase().replace(/_/g," ")} ${ne}`}const oe=J("graph"),te=K(()=>[...A.value?.nodes||[]].sort((G,Y)=>Y.degree-G.degree||G.name.localeCompare(Y.name)));function ee(G){const Y=O.value.indexOf(G);return Y>=0&&Y<8?nn(Y):"var(--s-other)"}return(G,Y)=>(h(),m("div",nv,[i("div",sv,[i("section",lv,[i("div",rv,[Y[6]||(Y[6]=i("h2",{id:"src-head"},"Seed sources",-1)),r.value?(h(),m("p",ov,y(de(Xe)(r.value.seed_chars))+" characters in total",1)):q("",!0)]),r.value?.sources.length?(h(),m("ul",iv,[(h(!0),m(se,null,me(r.value.sources,(ne,Ee)=>(h(),m("li",{key:Ee},[i("span",av,y(ne.name),1),i("span",uv,y(de(Xe)(ne.chars))+" chars",1),i("span",cv,y(de(ar)(ne.added_at)),1)]))),128))])):(h(),m("p",dv,"No sources yet. Paste some text or add a file to start.")),i("details",{class:"add",open:!r.value?.sources.length},[Y[11]||(Y[11]=i("summary",null,"Add more sources",-1)),i("form",{class:"stack",onSubmit:kn(g,["prevent"])},[i("label",pv,[Y[7]||(Y[7]=i("span",{class:"label"},"Paste text",-1)),Se(i("textarea",{"onUpdate:modelValue":Y[0]||(Y[0]=ne=>u.value=ne),rows:"5",placeholder:"Articles, notes, survey answers"},null,512),[[Le,u.value]])]),i("label",hv,[Y[8]||(Y[8]=i("span",{class:"label"},[xe("Source name "),i("span",{class:"muted"},"(optional)")],-1)),Se(i("input",{"onUpdate:modelValue":Y[1]||(Y[1]=ne=>d.value=ne),type:"text",placeholder:"Tenant chat notes"},null,512),[[Le,d.value]])]),i("div",mv,[i("button",{class:"btn",type:"submit",disabled:f.value||!u.value.trim()},"Add text",8,gv),i("label",{class:He(["btn",{disabled:f.value}])},[Y[9]||(Y[9]=xe(" Add files ",-1)),i("input",{ref_key:"fileInput",ref:p,class:"sr-only",type:"file",multiple:"",accept:".txt,.md,.markdown,.pdf",disabled:f.value,onChange:N},null,40,vv)],2),Y[10]||(Y[10]=i("span",{class:"muted small"},".txt, .md or .pdf",-1))])],32)],8,fv),c.value?(h(),m("div",yv,y(c.value),1)):q("",!0)]),i("section",bv,[Y[16]||(Y[16]=i("div",{class:"panel-head"},[i("h2",{id:"build-head"},"Knowledge graph"),i("p",null,"The language model reads the sources and maps the people, groups and facts in them.")],-1)),i("div",_v,[i("button",{class:"btn primary",type:"button",disabled:a.value||!r.value?.seed_chars,onClick:R},y(r.value?.graph_stats?"Rebuild graph":"Build graph"),9,kv),r.value?.graph_stats&&r.value?.stage==="prepared"?(h(),m("span",wv,"Rebuilding means you should prepare the crowd again.")):q("",!0),r.value?.seed_chars?q("",!0):(h(),m("span",xv,"Add a source first."))]),x.value?(h(),m("div",$v,y(x.value),1)):q("",!0),De(cr,{task:o.value,label:a.value?"Building the graph":""},null,8,["task","label"]),r.value?.graph_stats?(h(),m("dl",Sv,[i("div",null,[Y[12]||(Y[12]=i("dt",null,"Entities",-1)),i("dd",null,y(de(Xe)(r.value.graph_stats.nodes)),1)]),i("div",null,[Y[13]||(Y[13]=i("dt",null,"Relations",-1)),i("dd",null,y(de(Xe)(r.value.graph_stats.edges)),1)]),i("div",null,[Y[14]||(Y[14]=i("dt",null,"Chunks read",-1)),i("dd",null,y(de(Xe)(r.value.graph_stats.chunks)),1)]),i("div",null,[Y[15]||(Y[15]=i("dt",null,"Chunks failed",-1)),i("dd",{class:He({bad:r.value.graph_stats.failed_chunks})},y(de(Xe)(r.value.graph_stats.failed_chunks)),3)])])):q("",!0),r.value?.graph_stats?(h(),m("div",Tv,[(h(!0),m(se,null,me(r.value.graph_stats.types,(ne,Ee)=>(h(),m("span",{key:Ee,class:"pill"},[i("span",{class:"swatch",style:We({background:ee(Ee)})},null,4),xe(y(Ee)+" ",1),i("span",Ev,y(ne),1)]))),128))])):q("",!0),A.value?.errors?.length?(h(),m("div",Av,[i("p",null,[i("strong",null,y(A.value.errors.length)+" extraction "+y(A.value.errors.length===1?"problem":"problems"),1)]),(h(!0),m(se,null,me(A.value.errors.slice(0,5),(ne,Ee)=>(h(),m("p",{key:Ee,class:"small break"},y(ne),1))),128))])):q("",!0)])]),P.value?(h(),m("div",Rv,y(P.value),1)):q("",!0),A.value?(h(),m("section",Cv,[i("div",Ov,[Y[17]||(Y[17]=i("h2",{id:"map-head"},"Map",-1)),Y[18]||(Y[18]=i("span",{class:"spacer"},null,-1)),i("div",Pv,[i("button",{type:"button","aria-pressed":oe.value==="graph",onClick:Y[2]||(Y[2]=ne=>oe.value="graph")},"Graph",8,Nv),i("button",{type:"button","aria-pressed":oe.value==="table",onClick:Y[3]||(Y[3]=ne=>oe.value="table")},"Table",8,Iv)])]),i("div",Mv,[(h(!0),m(se,null,me(C.value,(ne,Ee)=>(h(),m("span",{key:ne},[i("span",{class:"swatch",style:We({background:de(nn)(Ee),borderRadius:"50%"})},null,4),xe(y(ne),1)]))),128)),D.value>0?(h(),m("span",Lv,[Y[19]||(Y[19]=i("span",{class:"swatch",style:{background:"var(--s-other)","border-radius":"50%"}},null,-1)),xe("Other ("+y(D.value)+" types)",1)])):q("",!0),Y[20]||(Y[20]=i("span",{class:"muted"},"Dot size shows how connected an entity is.",-1))]),i("div",Dv,[i("div",Fv,[A.value.nodes.length?oe.value==="graph"?(h(),ln(Yg,{key:1,nodes:A.value.nodes,edges:A.value.edges,types:O.value,"selected-id":_.value,"highlight-edge":w.value,onSelect:I},null,8,["nodes","edges","types","selected-id","highlight-edge"])):(h(),m("div",Uv,[i("table",Vv,[Y[22]||(Y[22]=i("thead",null,[i("tr",null,[i("th",null,"Entity"),i("th",null,"Type"),i("th",{class:"num"},"Connections"),i("th",{class:"num"},"Mentions"),i("th",null,"Summary")])],-1)),i("tbody",null,[(h(!0),m(se,null,me(te.value,ne=>(h(),m("tr",{key:ne.id,class:He({picked:ne.id===_.value})},[i("td",null,[i("button",{class:"linkish",type:"button",onClick:Ee=>I(ne.id)},y(ne.name),9,Bv)]),i("td",zv,[i("span",{class:"swatch",style:We({background:ee(ne.type)})},null,4),xe(" "+y(ne.type),1)]),i("td",qv,y(ne.degree),1),i("td",Hv,y(ne.mentions),1),i("td",Gv,y(ne.summary),1)],2))),128))])])])):(h(),m("div",jv,[...Y[21]||(Y[21]=[i("h3",null,"The graph is empty",-1),i("p",null,"Add richer sources and rebuild.",-1)])]))]),i("aside",Wv,[i("div",Kv,[Y[23]||(Y[23]=i("label",{class:"label",for:"graph-search"},"Search the graph",-1)),Se(i("input",{id:"graph-search","onUpdate:modelValue":Y[4]||(Y[4]=ne=>V.value=ne),type:"search",placeholder:"cleaning, students, rent",autocomplete:"off"},null,512),[[Le,V.value]])]),le.value?(h(),m("div",Yv,y(le.value),1)):q("",!0),V.value.trim()&&z.value.length?(h(),m("ul",Jv,[(h(!0),m(se,null,me(z.value,(ne,Ee)=>(h(),m("li",{key:Ee},[i("button",{type:"button",class:"result",onClick:H=>$(ne)},[ne.kind==="node"?(h(),m(se,{key:0},[i("span",Zv,[i("span",{class:"swatch",style:We({background:ee(ne.item.type)})},null,4),xe(y(ne.item.name),1)]),i("span",Qv,y(ne.item.type),1)],64)):(h(),m(se,{key:1},[i("span",ey,y(W(ne.item)),1),i("span",ty,y(ne.item.fact),1)],64))],8,Xv)]))),128))])):V.value.trim()&&!ge.value?(h(),m("p",ny,"No matches for that search.")):q("",!0),E.value?(h(),m("div",sy,[i("div",ly,[i("span",{class:"swatch",style:We({background:ee(E.value.type),borderRadius:"50%"})},null,4),i("h3",ry,y(E.value.name),1),Y[24]||(Y[24]=i("span",{class:"spacer"},null,-1)),i("button",{class:"btn small ghost",type:"button",onClick:Y[5]||(Y[5]=ne=>I("")),"aria-label":"Close details"},"Close")]),i("p",oy,y(E.value.type)+", "+y(E.value.degree)+" connections, mentioned "+y(E.value.mentions)+" "+y(E.value.mentions===1?"time":"times"),1),i("p",iy,y(E.value.summary),1),Y[25]||(Y[25]=i("h4",null,"Facts",-1)),S.value.length?(h(),m("ul",ay,[(h(!0),m(se,null,me(S.value,ne=>(h(),m("li",{key:ne.id,class:He({hit:ne.id===w.value})},[i("p",uy,[ne.source!==_.value?(h(),m("button",{key:0,class:"linkish",type:"button",onClick:Ee=>I(ne.source)},y(k.value[ne.source]?.name),9,cy)):(h(),m("strong",dy,y(E.value.name),1)),i("span",fy,y(ne.type.toLowerCase().replace(/_/g," ")),1),ne.target!==_.value?(h(),m("button",{key:2,class:"linkish",type:"button",onClick:Ee=>I(ne.target)},y(k.value[ne.target]?.name),9,py)):(h(),m("strong",hy,y(E.value.name),1))]),i("p",my,y(ne.fact),1)],2))),128))])):(h(),m("p",gy,"No relations recorded."))])):(h(),m("p",vy,"Click a dot or a search result to see its facts."))])])])):q("",!0)]))}},by=ct(yy,[["__scopeId","data-v-b3222292"]]),_y={key:0,class:"fe stack-lg"},ky={class:"read grid-2"},wy={class:"stack"},xy={class:"break"},$y={class:"break"},Sy={key:0,class:"kv small"},Ty={class:"break"},Ey={class:"break"},Ay={class:"stack"},Ry={key:0,class:"kv small"},Cy={class:"break"},Oy={class:"break"},Py={key:1,class:"muted small"},Ny={class:"levels small"},Iy={class:"stack"},My={key:0,class:"openings"},Ly={class:"small"},Dy={key:0,class:"pill"},Fy={class:"break"},jy={key:1,class:"muted small"},Uy={class:"stack"},Vy={class:"table-scroll"},By={class:"data points"},zy={class:"nowrap"},qy=["title"],Hy={class:"grow"},Gy=["onUpdate:modelValue","aria-label"],Wy=["onUpdate:modelValue","aria-label"],Ky=["value"],Yy=["onClick","aria-label"],Jy={class:"stack"},Xy={id:"subject-keys"},Zy=["value"],Qy={class:"variants"},eb={class:"v-head"},tb={class:"field v-id"},nb=["onUpdate:modelValue"],sb={class:"field v-label"},lb=["onUpdate:modelValue"],rb=["disabled","onClick"],ob={class:"stack"},ib={key:0,class:"muted small"},ab=["onUpdate:modelValue","aria-label"],ub=["onUpdate:modelValue","aria-label"],cb=["onClick","aria-label"],db=["onClick"],fb=["disabled"],pb={key:0,class:"notice error",role:"alert"},hb={class:"row savebar"},mb=["disabled"],gb=["disabled"],vb={key:0,class:"muted small"},yb={key:1,class:"pill good",role:"status"},bb={__name:"FrameEditor",props:{frame:{type:Object,required:!0},saving:{type:Boolean,default:!1},error:{type:String,default:""},savedAt:{type:Number,default:0}},emits:["save"],setup(e,{emit:t}){const n=e,s=t;let l=0;const r=J(null),o=J("");function a(k){r.value={points:k.talking_points.map(_=>({key:++l,id:_.id,text:_.text,side:_.side})),variants:k.variants.map(_=>({key:++l,id:_.id,label:_.label,rows:Object.entries(_.subject||{}).map(([w,E])=>({key:++l,k:w,v:String(E)}))}))},o.value=""}Je(()=>n.frame,a,{immediate:!0});const u=K(()=>JSON.stringify(f())),d=J("");Je(()=>n.frame,()=>d.value=u.value,{immediate:!0,flush:"post"});const c=K(()=>d.value&&u.value!==d.value);function f(){return r.value?{...n.frame,talking_points:r.value.points.map(k=>({id:k.id||"",text:k.text,side:k.side})),variants:r.value.variants.map(k=>({id:k.id,label:k.label,subject:Object.fromEntries(k.rows.filter(_=>_.k.trim()).map(_=>[_.k.trim(),_.v]))}))}:n.frame}function p(){r.value.points.push({key:++l,id:"",text:"",side:"neutral"})}function g(k){r.value.points.splice(k,1)}function N(){const k=new Set(r.value.variants.map(E=>E.id));let _=r.value.variants.length+1;for(;k.has(`V${_}`);)_++;const w=Object.keys(n.frame.subject||{})[0]||"";r.value.variants.push({key:++l,id:`V${_}`,label:"",rows:[{key:++l,k:w,v:""}]})}function x(k){r.value.variants.splice(k,1)}function R(k){k.rows.push({key:++l,k:"",v:""})}function A(){if(!r.value.points.filter(w=>w.text.trim()).length)return"Keep at least one talking point with text.";if(!r.value.variants.length)return"Keep at least one variant.";const _=new Set;for(const w of r.value.variants){const E=w.id.replace(/[^A-Za-z0-9_-]/g,"");if(!E)return"Every variant needs a short id made of letters, numbers, _ or -.";if(E.length>12)return`Variant id "${w.id}" is longer than 12 characters.`;if(E!==w.id)return`Variant id "${w.id}" can only use letters, numbers, _ or -.`;if(_.has(E))return`Two variants share the id "${E}".`;if(_.add(E),!w.label.trim())return`Give variant ${E} a label.`}return""}function P(){o.value=A(),!o.value&&s("save",f())}function j(){a(n.frame)}const O=K(()=>Object.keys(n.frame.subject||{})),C=[{v:"pro",t:"For"},{v:"con",t:"Against"},{v:"neutral",t:"Neutral"}],D=K(()=>n.savedAt&&Date.now()-n.savedAt<6e3&&!c.value);return(k,_)=>r.value?(h(),m("div",_y,[i("div",ky,[i("div",wy,[_[2]||(_[2]=i("h3",null,"Question",-1)),i("p",xy,y(e.frame.question),1),_[3]||(_[3]=i("h3",null,"Outcome question",-1)),i("p",$y,y(e.frame.outcome.instructions),1),e.frame.outcome.criteria?(h(),m("dl",Sy,[_[0]||(_[0]=i("dt",null,"Counts as yes",-1)),i("dd",Ty,y(e.frame.outcome.criteria.true),1),_[1]||(_[1]=i("dt",null,"Counts as no",-1)),i("dd",Ey,y(e.frame.outcome.criteria.false),1)])):q("",!0)]),i("div",Ay,[_[4]||(_[4]=i("h3",null,"Subject facts",-1)),O.value.length?(h(),m("dl",Ry,[(h(!0),m(se,null,me(O.value,w=>(h(),m(se,{key:w},[i("dt",Cy,y(w),1),i("dd",Oy,y(e.frame.subject[w]),1)],64))),128))])):(h(),m("p",Py,"None")),_[5]||(_[5]=i("h3",null,"Stance levels",-1)),i("ol",Ny,[(h(!0),m(se,null,me(e.frame.stance.levels,(w,E)=>(h(),m("li",{key:E},y(w),1))),128))])])]),i("div",Iy,[_[7]||(_[7]=i("h3",null,"Opening posts",-1)),e.frame.opening_posts.length?(h(),m("ul",My,[(h(!0),m(se,null,me(e.frame.opening_posts,(w,E)=>(h(),m("li",{key:E},[i("p",Ly,[i("strong",null,y(w.author||"Unnamed"),1),_[6]||(_[6]=xe()),w.talking_point?(h(),m("span",Dy,y(w.talking_point),1)):q("",!0)]),i("p",Fy,y(w.text),1)]))),128))])):(h(),m("p",jy,"None. The feed starts empty."))]),i("form",{class:"stack-lg",onSubmit:kn(P,["prevent"])},[i("fieldset",Uy,[_[9]||(_[9]=i("legend",null,[i("h3",null,"Talking points")],-1)),_[10]||(_[10]=i("p",{class:"muted small"},"The arguments people can pick up. Posts and comments are tagged with the point they make.",-1)),i("div",Vy,[i("table",By,[_[8]||(_[8]=i("thead",null,[i("tr",null,[i("th",null,"Id"),i("th",null,"Point"),i("th",null,"Side"),i("th",null,[i("span",{class:"sr-only"},"Remove")])])],-1)),i("tbody",null,[(h(!0),m(se,null,me(r.value.points,(w,E)=>(h(),m("tr",{key:w.key},[i("td",zy,[i("span",{class:"pill pid",title:w.id},y(w.id||"new"),9,qy)]),i("td",Hy,[Se(i("input",{"onUpdate:modelValue":S=>w.text=S,type:"text","aria-label":`Talking point ${E+1}`},null,8,Gy),[[Le,w.text]])]),i("td",null,[Se(i("select",{"onUpdate:modelValue":S=>w.side=S,"aria-label":`Side of point ${E+1}`},[(h(),m(se,null,me(C,S=>i("option",{key:S.v,value:S.v},y(S.t),9,Ky)),64))],8,Wy),[[_n,w.side]])]),i("td",null,[i("button",{class:"btn small ghost",type:"button",onClick:S=>g(E),"aria-label":`Remove point ${E+1}`},"Remove",8,Yy)])]))),128))])])]),i("div",null,[i("button",{class:"btn small",type:"button",onClick:p},"Add talking point")])]),i("fieldset",Jy,[_[14]||(_[14]=i("legend",null,[i("h3",null,"Variants")],-1)),_[15]||(_[15]=i("p",{class:"muted small"},"Each variant runs against the same crowd with some subject facts changed. Compare an offer against the current one.",-1)),i("datalist",Xy,[(h(!0),m(se,null,me(O.value,w=>(h(),m("option",{key:w,value:w},null,8,Zy))),128))]),i("div",Qy,[(h(!0),m(se,null,me(r.value.variants,(w,E)=>(h(),m("div",{key:w.key,class:"variant"},[i("div",eb,[i("label",tb,[_[11]||(_[11]=i("span",{class:"label"},"Id",-1)),Se(i("input",{"onUpdate:modelValue":S=>w.id=S,type:"text",maxlength:"12"},null,8,nb),[[Le,w.id]])]),i("label",sb,[_[12]||(_[12]=i("span",{class:"label"},"Label",-1)),Se(i("input",{"onUpdate:modelValue":S=>w.label=S,type:"text",placeholder:"Weekly cleaning at S$100 more"},null,8,lb),[[Le,w.label]])]),i("button",{class:"btn small ghost danger",type:"button",disabled:r.value.variants.length<2,onClick:S=>x(E)},"Remove variant",8,rb)]),i("div",ob,[_[13]||(_[13]=i("span",{class:"label small"},"Subject overrides",-1)),w.rows.length?q("",!0):(h(),m("p",ib,"No overrides. This variant uses the subject facts as written.")),(h(!0),m(se,null,me(w.rows,(S,I)=>(h(),m("div",{key:S.key,class:"kv-row"},[Se(i("input",{"onUpdate:modelValue":V=>S.k=V,type:"text",list:"subject-keys",placeholder:"Fact name","aria-label":`Fact name ${I+1}`},null,8,ab),[[Le,S.k]]),Se(i("input",{"onUpdate:modelValue":V=>S.v=V,type:"text",placeholder:"Value for this variant","aria-label":`Fact value ${I+1}`},null,8,ub),[[Le,S.v]]),i("button",{class:"btn small ghost",type:"button",onClick:V=>w.rows.splice(I,1),"aria-label":`Remove override ${I+1}`},"Remove",8,cb)]))),128)),i("div",null,[i("button",{class:"btn small",type:"button",onClick:S=>R(w)},"Add override",8,db)])])]))),128))]),i("div",null,[i("button",{class:"btn small",type:"button",disabled:r.value.variants.length>=8,onClick:N},"Add variant",8,fb)])]),o.value||e.error?(h(),m("div",pb,y(o.value||e.error),1)):q("",!0),i("div",hb,[i("button",{class:"btn primary",type:"submit",disabled:e.saving||!c.value},y(e.saving?"Saving":"Save frame"),9,mb),i("button",{class:"btn",type:"button",disabled:e.saving||!c.value,onClick:j},"Discard changes",8,gb),c.value?(h(),m("span",vb,"Unsaved changes")):D.value?(h(),m("span",yb,"Saved")):q("",!0)])],32)])):q("",!0)}},_b=ct(bb,[["__scopeId","data-v-eb815f0a"]]),kb={class:"stack-lg"},wb={class:"panel","aria-labelledby":"prep-head"},xb={class:"form-grid"},$b={class:"field"},Sb={class:"field"},Tb={class:"field"},Eb={class:"row"},Ab=["disabled"],Rb={key:0,class:"muted small"},Cb={key:0,class:"notice error",role:"alert"},Ob={key:0,class:"notice error",role:"alert"},Pb={key:1,class:"panel","aria-labelledby":"frame-head"},Nb={key:2,class:"panel","aria-labelledby":"crowd-head"},Ib={class:"panel-head"},Mb={key:0,class:"segments stack"},Lb={class:"seg-list"},Db={class:"seg-top"},Fb={class:"break"},jb={class:"tnum"},Ub=["aria-label"],Vb={class:"small muted break"},Bb={key:0,class:"small muted break"},zb={class:"stack crowd-table"},qb={class:"row"},Hb={class:"muted small"},Gb={class:"table-scroll bordered"},Wb={class:"data"},Kb={class:"who"},Yb={class:"name break"},Jb={class:"muted small bio"},Xb={class:"break"},Zb={class:"num"},Qb={class:"num"},e_={class:"num"},t_={key:0},n_={key:0},s_={key:3,class:"row end"},l_={__name:"StepCrowd",setup(e){const t=cl(),n=t.pid,s=K(()=>t.overview.value),l=K(()=>t.tasks.prepare),r=K(()=>l.value&&(l.value.status==="queued"||l.value.status==="running")),o=J(60),a=J(20),u=J(0),d=J("");async function c(){d.value="";const S=Number(o.value),I=Number(a.value);if(!Number.isInteger(S)||S<1||S>2e3)return d.value="Public size must be a whole number from 1 to 2000.";if(!Number.isInteger(I)||I<0||I>200)return d.value="Stakeholders must be a whole number from 0 to 200.";try{const V=await Ie.prepare(n.value,{public_size:S,max_stakeholders:I,seed:Number(u.value)||0});(await t.track(V)).status==="done"&&await N(!0)}catch(V){d.value=V.message}}const f=K(()=>t.frame.value),p=K(()=>t.crowd.value),g=J("");async function N(S=!1){g.value="";try{await Promise.all([t.loadFrame(S),t.loadCrowd(S)])}catch(I){I.status!==400&&(g.value=I.message)}}Je(()=>s.value?.has_frame&&s.value?.crowd_stats,S=>S&&N(),{immediate:!0});const x=J(!1),R=J(""),A=J(0);async function P(S){x.value=!0,R.value="";try{t.frame.value=await Ie.saveFrame(n.value,S),A.value=Date.now()}catch(I){R.value=I.message}finally{x.value=!1}}const j=J(""),O=J("all"),C=J(100),D=K(()=>{const S={};for(const I of p.value?.agents||[])for(const V of I.follows||[])S[V]=(S[V]||0)+1;return S}),k=K(()=>{const S=j.value.trim().toLowerCase();return(p.value?.agents||[]).filter(I=>{if(O.value!=="all"&&I.kind!==O.value)return!1;if(!S)return!0;const V=Object.entries(I.attributes||{}).map(([z,ge])=>`${z} ${ge}`).join(" ");return`${I.name} ${I.username} ${I.segment} ${I.kind} ${I.stance_hint} ${I.bio} ${V}`.toLowerCase().includes(S)})});Je([j,O],()=>C.value=100);const _={for:"For",against:"Against",neutral:"Neutral",mixed:"Mixed"},w=K(()=>Math.max(1e-4,...(p.value?.segments||[]).map(S=>S.share)));function E(S){return Object.entries(S||{}).map(([I,V])=>V&&typeof V=="object"?`${I}: `+Object.entries(V).map(([z,ge])=>`${z} ${Qt(ge)}`).join(", "):`${I}: ${V}`).join("; ")}return(S,I)=>{const V=Nn("RouterLink");return h(),m("div",kb,[i("section",wb,[I[9]||(I[9]=i("div",{class:"panel-head"},[i("h2",{id:"prep-head"},"Prepare the crowd"),i("p",null,"Writes the prediction frame, turns graph entities into stakeholders and samples members of the public.")],-1)),i("form",{class:"stack",onSubmit:kn(c,["prevent"])},[i("div",xb,[i("label",$b,[I[6]||(I[6]=i("span",{class:"label"},"Members of the public",-1)),Se(i("input",{"onUpdate:modelValue":I[0]||(I[0]=z=>o.value=z),type:"number",min:"1",max:"2000",step:"1"},null,512),[[Le,o.value,void 0,{number:!0}]])]),i("label",Sb,[I[7]||(I[7]=i("span",{class:"label"},"Stakeholders, at most",-1)),Se(i("input",{"onUpdate:modelValue":I[1]||(I[1]=z=>a.value=z),type:"number",min:"0",max:"200",step:"1"},null,512),[[Le,a.value,void 0,{number:!0}]])]),i("label",Tb,[I[8]||(I[8]=i("span",{class:"label"},"Random seed",-1)),Se(i("input",{"onUpdate:modelValue":I[2]||(I[2]=z=>u.value=z),type:"number",step:"1"},null,512),[[Le,u.value,void 0,{number:!0}]])])]),i("div",Eb,[i("button",{class:"btn primary",type:"submit",disabled:r.value},y(s.value?.crowd_stats?"Prepare again":"Prepare"),9,Ab),s.value?.crowd_stats?(h(),m("span",Rb,"Preparing again replaces the frame and the crowd, including edits.")):q("",!0)]),d.value?(h(),m("div",Cb,y(d.value),1)):q("",!0),De(cr,{task:l.value,label:r.value?"Preparing the crowd":""},null,8,["task","label"])],32)]),g.value?(h(),m("div",Ob,y(g.value),1)):q("",!0),f.value?(h(),m("section",Pb,[I[10]||(I[10]=i("div",{class:"panel-head"},[i("h2",{id:"frame-head"},"Frame"),i("p",null,"What every person is asked, and the arguments in play.")],-1)),De(_b,{frame:f.value,saving:x.value,error:R.value,"saved-at":A.value,onSave:P},null,8,["frame","saving","error","saved-at"])])):q("",!0),p.value?(h(),m("section",Nb,[i("div",Ib,[I[11]||(I[11]=i("h2",{id:"crowd-head"},"Crowd",-1)),i("p",null,y(de(Xe)(p.value.agents.length))+" people: "+y(de(Xe)(p.value.stats.stakeholders))+" stakeholders and "+y(de(Xe)(p.value.stats.public))+" members of the public.",1)]),p.value.segments.length?(h(),m("div",Mb,[I[12]||(I[12]=i("h3",null,"Public segments",-1)),i("ul",Lb,[(h(!0),m(se,null,me(p.value.segments,z=>(h(),m("li",{key:z.name},[i("div",Db,[i("strong",Fb,y(z.name),1),i("span",jb,y(de(Qt)(z.share)),1)]),i("div",{class:"bar-track",role:"img","aria-label":`${z.name}: ${de(Qt)(z.share)} of the public`},[i("div",{class:"bar",style:We({width:z.share/w.value*100+"%"})},null,4)],8,Ub),i("p",Vb,y(z.description),1),Object.keys(z.attributes||{}).length?(h(),m("p",Bb,y(E(z.attributes)),1)):q("",!0)]))),128))])])):q("",!0),i("div",zb,[i("div",qb,[I[14]||(I[14]=i("h3",null,"People",-1)),I[15]||(I[15]=i("span",{class:"spacer"},null,-1)),Se(i("select",{"onUpdate:modelValue":I[3]||(I[3]=z=>O.value=z),class:"kind","aria-label":"Filter by kind"},[...I[13]||(I[13]=[i("option",{value:"all"},"Everyone",-1),i("option",{value:"stakeholder"},"Stakeholders",-1),i("option",{value:"public"},"Public",-1)])],512),[[_n,O.value]]),Se(i("input",{"onUpdate:modelValue":I[4]||(I[4]=z=>j.value=z),type:"search",class:"filter",placeholder:"Filter by name, group or trait","aria-label":"Filter people"},null,512),[[Le,j.value]])]),i("p",Hb,"Showing "+y(Math.min(C.value,k.value.length))+" of "+y(k.value.length),1),i("div",Gb,[i("table",Wb,[I[17]||(I[17]=i("thead",null,[i("tr",null,[i("th",null,"Name"),i("th",null,"Kind"),i("th",null,"Group"),i("th",null,"Leaning"),i("th",{class:"num"},"Influence"),i("th",{class:"num"},"Activity"),i("th",{class:"num"},"Followers")])],-1)),i("tbody",null,[(h(!0),m(se,null,me(k.value.slice(0,C.value),z=>(h(),m("tr",{key:z.agent_id},[i("td",Kb,[i("span",Yb,y(z.name),1),i("span",Jb,y(z.bio),1)]),i("td",null,y(z.kind==="stakeholder"?"Stakeholder":"Public"),1),i("td",Xb,y(z.segment),1),i("td",null,y(_[z.stance_hint]||z.stance_hint),1),i("td",Zb,y(z.influence.toFixed(2)),1),i("td",Qb,y(z.activity.toFixed(2)),1),i("td",e_,y(D.value[z.agent_id]||0),1)]))),128)),k.value.length?q("",!0):(h(),m("tr",t_,[...I[16]||(I[16]=[i("td",{colspan:"7",class:"muted"},"Nobody matches that filter.",-1)])]))])])]),k.value.length>C.value?(h(),m("div",n_,[i("button",{class:"btn small",type:"button",onClick:I[5]||(I[5]=z=>C.value+=200)},"Show more people")])):q("",!0)])])):q("",!0),p.value&&f.value?(h(),m("div",s_,[De(V,{class:"btn primary",to:{name:"simulate",params:{pid:de(n)}}},{default:Vt(()=>[...I[18]||(I[18]=[xe("Set up a run",-1)])]),_:1},8,["to"])])):q("",!0)])}}},r_=ct(l_,[["__scopeId","data-v-1907df61"]]),o_={class:"feed"},i_={class:"feed-bar"},a_={class:"small muted tnum"},u_=["value"],c_={class:"check small"},d_={key:1,class:"live small"},f_={key:0,class:"notice error"},p_={key:1,class:"muted small empty-feed"},h_={class:"items","aria-live":"off"},m_={class:"meta"},g_={class:"break"},v_={key:0,class:"muted small"},y_={key:1,class:"pill accent"},b_={key:2,class:"pill warn"},__={key:3,class:"pill"},k_={key:4,class:"muted small"},w_={class:"muted small nowrap"},x_={key:0,class:"reply small muted break"},$_={class:"content break"},S_={class:"foot small"},T_=["title"],E_={class:"muted tnum"},A_={key:0,class:"muted tnum"},R_={class:"muted tnum"},C_={class:"muted tnum"},O_={key:2,class:"pill bad"},P_={key:1,class:"line small break"},N_={class:"who"},I_={key:0,class:"muted"},M_={key:1,class:"pill bad"},L_={class:"muted when nowrap"},D_={key:2,class:"row"},F_={__name:"ActionFeed",props:{pid:{type:String,required:!0},runId:{type:String,required:!0},active:{type:Boolean,default:!1},variants:{type:Array,default:()=>[]},points:{type:Object,default:()=>({})}},setup(e){const t=e,n=fs([]),s=J(""),l=J("all"),r=J(!1),o=J(120);let a=0,u=null,d=!1,c=0;async function f(){if(d)return;d=!0;const w=c;try{for(;;){const E=await Ie.actions(t.pid,t.runId,a,500);if(w!==c)return;if(E.length&&(a+=E.length,n.value=n.value.concat(E)),E.length<500)break}s.value=""}catch(E){w===c&&(s.value=E.message)}finally{w===c&&(d=!1)}}function p(){c++,d=!1,a=0,n.value=[],o.value=120,f()}Je(()=>t.runId,p,{immediate:!0}),Je(()=>t.active,(w,E)=>{clearInterval(u),w?u=setInterval(f,1500):E&&setTimeout(f,300)},{immediate:!0}),Gn(()=>{clearInterval(u),c++});const g=(w,E,S)=>`${w}${E}${String(S||"").slice(0,200)}`,N=K(()=>{const w={};for(const E of n.value)E.ok&&(E.action==="create_post"||E.action==="quote_post")&&(w[g(E.variant,E.agent_name,E.content)]||={likes:0,dislikes:0,reshares:0,comments:0});for(const E of n.value){if(!E.ok||!E.target_author)continue;const S=g(E.variant,E.target_author,E.target_excerpt),I=w[S];I&&(E.action==="like_post"?I.likes++:E.action==="dislike_post"?I.dislikes++:E.action==="repost"||E.action==="quote_post"?I.reshares++:E.action==="create_comment"&&I.comments++)}return w}),x=K(()=>{const w={posts:0,comments:0,reactions:0,idle:0};for(const E of n.value)l.value!=="all"&&E.variant!==l.value||(E.action==="create_post"||E.action==="quote_post"?w.posts++:E.action==="create_comment"?w.comments++:E.action==="do_nothing"?w.idle++:w.reactions++);return w}),R=K(()=>{const w=[];for(let E=n.value.length-1;E>=0;E--){const S=n.value[E];l.value!=="all"&&S.variant!==l.value||!r.value&&S.action==="do_nothing"||w.push({a:S,i:E})}return w}),A=K(()=>t.variants.length>1),P=K(()=>Object.fromEntries(t.variants.map(w=>[w.id,w.label])));function j(w){return w.action==="create_post"||w.action==="quote_post"?"post":w.action==="create_comment"?"comment":"reaction"}function O(w){return String(w||"").replace(/\s+\([^)]*\)$/,"")}function C(w){const E=String(w||"").match(/\(([^)]*)\)$/);return E?E[1]:""}function D(w,E=90){return w=String(w||"").replace(/\s+/g," ").trim(),w.length>E?w.slice(0,E-1)+"…":w}function k(w){const E=w.target_author?O(w.target_author):"someone";switch(w.action){case"like_post":return`liked a post by ${E}`;case"dislike_post":return`disliked a post by ${E}`;case"repost":return`reshared a post by ${E}`;case"like_comment":return`liked a comment by ${E}`;case"follow":return`followed ${E}`;case"do_nothing":return"read the feed and moved on";default:return w.action.replace(/_/g," ")}}function _(w){return w.round===0?"Opening":`Round ${w.round}`}return(w,E)=>(h(),m("div",o_,[i("div",i_,[i("p",a_,[xe(y(x.value.posts)+" posts, "+y(x.value.comments)+" comments, "+y(x.value.reactions)+" reactions",1),x.value.idle?(h(),m(se,{key:0},[xe(", "+y(x.value.idle)+" idle turns",1)],64)):q("",!0)]),E[6]||(E[6]=i("span",{class:"spacer"},null,-1)),A.value?Se((h(),m("select",{key:0,"onUpdate:modelValue":E[0]||(E[0]=S=>l.value=S),class:"vsel","aria-label":"Variant shown in the feed"},[E[3]||(E[3]=i("option",{value:"all"},"All variants",-1)),(h(!0),m(se,null,me(e.variants,S=>(h(),m("option",{key:S.id,value:S.id},y(S.label),9,u_))),128))],512)),[[_n,l.value]]):q("",!0),i("label",c_,[Se(i("input",{"onUpdate:modelValue":E[1]||(E[1]=S=>r.value=S),type:"checkbox"},null,512),[[Qu,r.value]]),E[4]||(E[4]=xe(" Show idle turns",-1))]),e.active?(h(),m("span",d_,[...E[5]||(E[5]=[i("span",{class:"pulse","aria-hidden":"true"},null,-1),xe("Live",-1)])])):q("",!0)]),s.value?(h(),m("div",f_,y(s.value),1)):q("",!0),R.value.length?q("",!0):(h(),m("p",p_,y(e.active?"Waiting for the first actions.":"No actions recorded."),1)),i("ol",h_,[(h(!0),m(se,null,me(R.value.slice(0,o.value),({a:S,i:I})=>(h(),m("li",{key:I,class:He(["item",j(S),{failed:!S.ok}])},[j(S)!=="reaction"?(h(),m(se,{key:0},[i("div",m_,[i("strong",g_,y(O(S.agent_name)),1),C(S.agent_name)?(h(),m("span",v_,y(C(S.agent_name)),1)):q("",!0),S.opening?(h(),m("span",y_,"Opening post")):q("",!0),S.injection?(h(),m("span",b_,"News")):q("",!0),S.action==="quote_post"?(h(),m("span",__,"Quote")):q("",!0),E[7]||(E[7]=i("span",{class:"spacer"},null,-1)),A.value?(h(),m("span",k_,y(P.value[S.variant]||S.variant),1)):q("",!0),i("span",w_,y(_(S)),1)]),j(S)==="comment"?(h(),m("p",x_," Replying to "+y(O(S.target_author))+": "+y(D(S.target_excerpt)),1)):q("",!0),i("p",$_,y(S.content),1),i("div",S_,[S.point&&S.point!=="none"?(h(),m("span",{key:0,class:"pill",title:e.points[S.point]||""},[xe(y(S.point),1),e.points[S.point]?(h(),m(se,{key:0},[xe(": "+y(D(e.points[S.point],40)),1)],64)):q("",!0)],8,T_)):q("",!0),j(S)==="post"&&N.value[g(S.variant,S.agent_name,S.content)]?(h(),m(se,{key:1},[i("span",E_,y(N.value[g(S.variant,S.agent_name,S.content)].likes)+" likes",1),N.value[g(S.variant,S.agent_name,S.content)].dislikes?(h(),m("span",A_,y(N.value[g(S.variant,S.agent_name,S.content)].dislikes)+" dislikes",1)):q("",!0),i("span",R_,y(N.value[g(S.variant,S.agent_name,S.content)].reshares)+" reshares",1),i("span",C_,y(N.value[g(S.variant,S.agent_name,S.content)].comments)+" comments",1)],64)):q("",!0),S.ok?q("",!0):(h(),m("span",O_,"Failed: "+y(D(S.error,60)),1))])],64)):(h(),m("p",P_,[i("span",N_,y(O(S.agent_name)),1),xe(" "+y(k(S)),1),S.target_excerpt&&S.action!=="follow"?(h(),m("span",I_,": "+y(D(S.target_excerpt,70)),1)):q("",!0),S.ok?q("",!0):(h(),m("span",M_,"Failed")),i("span",L_,y(A.value?(P.value[S.variant]||S.variant)+", ":"")+y(_(S)),1)]))],2))),128))]),R.value.length>o.value?(h(),m("div",D_,[i("button",{class:"btn small",type:"button",onClick:E[2]||(E[2]=S=>o.value+=200)},"Show older actions")])):q("",!0)]))}},j_=ct(F_,[["__scopeId","data-v-ced3dc21"]]);function $c(e=320,t=640){const n=J(null),s=J(t);let l=null;return al(()=>{const r=()=>{n.value&&(s.value=Math.max(e,Math.floor(n.value.clientWidth)))};r(),l=new ResizeObserver(r),l.observe(n.value)}),Gn(()=>l&&l.disconnect()),{el:n,width:s}}const U_={key:0,class:"tt-title"},Sc={__name:"ChartTooltip",props:{show:Boolean,x:{type:Number,default:0},y:{type:Number,default:0},title:{type:String,default:""},rows:{type:Array,default:()=>[]}},setup(e){function t(n,s){const l=typeof window<"u"?window.innerWidth:1e3;return{left:(n+16+260>l?Math.max(8,n-16-260):n+16)+"px",top:Math.max(8,s-12)+"px"}}return(n,s)=>(h(),ln(wu,{to:"body"},[e.show?(h(),m("div",{key:0,class:"chart-tooltip",style:We(t(e.x,e.y)),role:"presentation"},[e.title?(h(),m("div",U_,y(e.title),1)):q("",!0),(h(!0),m(se,null,me(e.rows,l=>(h(),m("div",{key:l.key,class:"tt-row"},[i("span",{class:He(l.shape==="rect"?"swatch":"linekey"),style:We({background:l.color})},null,6),i("strong",null,y(l.value),1),i("span",null,y(l.label),1)]))),128))],4)):q("",!0)]))}},V_={class:"lc"},B_={class:"lc-top"},z_={key:0,class:"legend"},q_={class:"seg",role:"group","aria-label":"Chart or table"},H_=["aria-pressed"],G_=["aria-pressed"],W_=["width","height","aria-label"],K_={class:"grid"},Y_=["x1","x2","y1","y2"],J_=["x","y"],X_=["x","y"],Z_=["x","y"],Q_=["x1","x2","y1","y2"],e1=["d"],t1=["cx","cy","r"],n1=["x","y"],s1=["x","y","width","height"],l1={key:0,class:"table-scroll"},r1={class:"data"},o1={__name:"LineChart",props:{series:{type:Array,required:!0},xName:{type:String,default:"Round"},xLabel:{type:Function,default:e=>String(e)},yLabel:{type:String,default:"Chance of yes"},height:{type:Number,default:260},describe:{type:String,default:""}},setup(e){const t=e,{el:n,width:s}=$c(320),l=J("chart"),r=K(()=>({l:46,r:t.series.length<=4?64:16,t:14,b:40})),o=K(()=>[...new Set(t.series.flatMap(k=>k.points.map(_=>_.x)))].sort((k,_)=>k-_)),a=K(()=>Math.min(...o.value,0)),u=K(()=>Math.max(...o.value,1)),d=K(()=>s.value-r.value.l-r.value.r),c=K(()=>t.height-r.value.t-r.value.b),f=k=>r.value.l+(k-a.value)/(u.value-a.value||1)*d.value,p=k=>r.value.t+(1-k)*c.value,g=[0,.25,.5,.75,1],N=K(()=>{const k=o.value;if(k.length<=8)return k;const _=Math.ceil(k.length/8);return k.filter((w,E)=>E%_===0||E===k.length-1)});function x(k){return k.map((_,w)=>`${w?"L":"M"}${f(_.x).toFixed(1)},${p(_.y).toFixed(1)}`).join("")}const R=k=>nn(k.index),A=k=>`${Math.round(k*100)}%`,P=K(()=>{if(t.series.length>4||t.series.length<2)return[];const k=t.series.filter(_=>_.points.length).map(_=>({s:_,y:p(_.points[_.points.length-1].y),x:f(_.points[_.points.length-1].x)})).sort((_,w)=>_.y-w.y);for(let _=1;_j.value==null?[]:t.series.map(k=>({s:k,p:k.points.find(_=>_.x===j.value)})).filter(k=>k.p).sort((k,_)=>_.p.y-k.p.y).map(k=>({key:k.s.id,value:A(k.p.y),label:k.s.label,color:R(k.s),shape:"line"})));return(k,_)=>(h(),m("div",V_,[i("div",B_,[e.series.length>1?(h(),m("div",z_,[(h(!0),m(se,null,me(e.series,w=>(h(),m("span",{key:w.id},[i("span",{class:"linekey",style:We({background:R(w)})},null,4),xe(y(w.label),1)]))),128))])):q("",!0),_[3]||(_[3]=i("span",{class:"spacer"},null,-1)),i("div",q_,[i("button",{type:"button","aria-pressed":l.value==="chart",onClick:_[0]||(_[0]=w=>l.value="chart")},"Chart",8,H_),i("button",{type:"button","aria-pressed":l.value==="table",onClick:_[1]||(_[1]=w=>l.value="table")},"Table",8,G_)])]),Se(i("div",{ref_key:"el",ref:n,class:"chart-box"},[(h(),m("svg",{width:de(s),height:e.height,role:"img","aria-label":e.describe||`${e.yLabel} by ${e.xName.toLowerCase()}`},[i("g",K_,[(h(),m(se,null,me(g,w=>i("g",{key:w},[i("line",{x1:r.value.l,x2:de(s)-r.value.r,y1:p(w),y2:p(w)},null,8,Y_),i("text",{x:r.value.l-8,y:p(w),dy:"0.32em","text-anchor":"end"},y(A(w)),9,J_)])),64)),(h(!0),m(se,null,me(N.value,w=>(h(),m("text",{key:w,x:f(w),y:e.height-r.value.b+18,"text-anchor":"middle"},y(e.xLabel(w)),9,X_))),128)),i("text",{x:r.value.l+d.value/2,y:e.height-4,"text-anchor":"middle",class:"axis-title"},y(e.xName),9,Z_)]),j.value!=null?(h(),m("line",{key:0,class:"cross",x1:f(j.value),x2:f(j.value),y1:r.value.t,y2:r.value.t+c.value},null,8,Q_)):q("",!0),(h(!0),m(se,null,me(e.series,w=>(h(),m("g",{key:w.id},[i("path",{d:x(w.points),class:"line",style:We({stroke:R(w)})},null,12,e1),(h(!0),m(se,null,me(w.points,E=>(h(),m("circle",{key:E.x,cx:f(E.x),cy:p(E.y),r:j.value===E.x?5:4,class:"pt",style:We({fill:R(w)})},null,12,t1))),128))]))),128)),(h(!0),m(se,null,me(P.value,w=>(h(),m("g",{key:w.s.id},[i("text",{x:w.x+8,y:w.y,dy:"0.32em",class:"end"},y(w.s.id.length>8?w.s.id.slice(0,7)+"…":w.s.id),9,n1)]))),128)),i("rect",{x:r.value.l-10,y:r.value.t,width:d.value+20,height:c.value,fill:"transparent",onPointermove:C,onPointerleave:_[2]||(_[2]=w=>j.value=null)},null,40,s1)],8,W_))],512),[[Zu,l.value==="chart"]]),l.value==="table"?(h(),m("div",l1,[i("table",r1,[i("thead",null,[i("tr",null,[i("th",null,y(e.xName),1),(h(!0),m(se,null,me(e.series,w=>(h(),m("th",{key:w.id,class:"num"},y(w.label),1))),128))])]),i("tbody",null,[(h(!0),m(se,null,me(o.value,w=>(h(),m("tr",{key:w},[i("td",null,y(e.xLabel(w,!0)),1),(h(!0),m(se,null,me(e.series,E=>(h(),m("td",{key:E.id,class:"num"},y(E.points.find(S=>S.x===w)?A(E.points.find(S=>S.x===w).y):"-"),1))),128))]))),128))])])])):q("",!0),De(Sc,{show:j.value!=null&&l.value==="chart",x:O.value.x,y:O.value.y,title:e.xLabel(j.value,!0),rows:D.value},null,8,["show","x","y","title","rows"])]))}},i1=ct(o1,[["__scopeId","data-v-99093c3d"]]),a1={class:"swarm"},u1=["aria-label"],c1={class:"small muted key"},d1={key:0},f1={__name:"SwarmDots",props:{n:{type:Number,required:!0},expected:{type:Number,required:!0},low:{type:Number,required:!0},high:{type:Number,required:!0},index:{type:Number,default:0},label:{type:String,default:""}},setup(e){const t=e,n=K(()=>t.n>300?Math.ceil(t.n/200):1),s=K(()=>Math.ceil(t.n/n.value)),l=K(()=>Math.max(0,Math.round(t.low/n.value))),r=K(()=>Math.min(s.value,Math.round(t.high/n.value))),o=K(()=>Array.from({length:s.value},(u,d)=>dnn(t.index));return(u,d)=>(h(),m("div",a1,[i("div",{class:"dots",role:"img","aria-label":`${e.label}: about ${e.expected.toFixed(1)} of ${e.n} people say yes, 90% range ${e.low.toFixed(1)} to ${e.high.toFixed(1)}`},[(h(!0),m(se,null,me(o.value,(c,f)=>(h(),m("span",{key:f,class:He(["dot",c]),style:We(c==="no"?null:{"--c":a.value})},null,6))),128))],8,u1),i("p",c1,[i("span",null,[i("span",{class:"dot yes",style:We({"--c":a.value})},null,4),d[0]||(d[0]=xe(" yes at the low end",-1))]),i("span",null,[i("span",{class:"dot range",style:We({"--c":a.value})},null,4),d[1]||(d[1]=xe(" inside the 90% range",-1))]),n.value>1?(h(),m("span",d1,"Each dot is "+y(n.value)+" people.",1)):q("",!0)])]))}},Tc=ct(f1,[["__scopeId","data-v-9bc118e4"]]),p1={class:"results stack-lg"},h1={key:0,class:"notice warn"},m1={class:"tiles"},g1={class:"tile-head"},v1={class:"break"},y1={class:"muted small"},b1={class:"big"},_1={class:"figure"},k1={class:"of"},w1={class:"facts"},x1={class:"tnum"},$1={class:"tnum"},S1={key:0},T1={class:"tnum"},E1={class:"tnum"},A1={key:1,class:"muted"},R1={key:1,class:"stack"},C1={class:"compare"},O1={class:"c-name break"},P1={class:"tnum"},N1={class:"muted small tnum"},I1={class:"stack"},M1={class:"usage"},L1={class:"usage-grid"},D1={class:"tnum"},F1={key:0,class:"muted small"},j1={class:"tnum"},U1={class:"tnum"},V1={class:"tnum"},B1={key:0},z1={class:"tnum"},q1={key:0,class:"muted small"},H1={class:"tnum"},G1={class:"small muted"},W1={__name:"RunResults",props:{summary:{type:Object,required:!0},run:{type:Object,default:null}},setup(e){const t=e,n=K(()=>t.summary.variants.map((c,f)=>({...c,index:f}))),s=K(()=>n.value.map(c=>({id:c.id,label:c.label,index:c.index,points:c.polls.map(f=>({x:f.round,y:f.mean_outcome}))}))),l=K(()=>Object.fromEntries(n.value.map(c=>[c.id,c.label])));function r(c,f){return c==null?"":f?c===0?"Before round 1":`After round ${c}`:String(c)}function o(c){return!c.final||!c.baseline?null:{people:c.final.expected_yes-c.baseline.expected_yes,points:(c.final.mean_outcome-c.baseline.mean_outcome)*100,from:c.baseline.round}}const a={higher:"Higher",lower:"Lower","within noise":"Within noise"},u=K(()=>t.summary.judge||{}),d=K(()=>t.summary.llm);return(c,f)=>(h(),m("div",p1,[e.summary.partial?(h(),m("div",h1,"This run stopped early: "+y(e.summary.partial)+". The numbers cover the rounds that finished.",1)):q("",!0),i("div",m1,[(h(!0),m(se,null,me(n.value,p=>(h(),m("article",{key:p.id,class:"tile"},[i("header",g1,[i("span",{class:"swatch",style:We({background:de(nn)(p.index)})},null,4),i("h3",v1,y(p.label),1),i("span",y1,y(p.id),1)]),p.final?(h(),m(se,{key:0},[i("p",b1,[i("span",_1,y(de(Cn)(p.final.expected_yes)),1),i("span",k1,"of "+y(de(Xe)(p.final.n))+" expected to say yes",1)]),i("dl",w1,[i("div",null,[f[0]||(f[0]=i("dt",null,"90% range",-1)),i("dd",x1,y(de(Cn)(p.final.low))+" to "+y(de(Cn)(p.final.high)),1)]),i("div",null,[f[1]||(f[1]=i("dt",null,"Mean chance of yes",-1)),i("dd",$1,y(de(Qt)(p.final.mean_outcome,1)),1)]),o(p)?(h(),m("div",S1,[f[2]||(f[2]=i("dt",null,"Shift from first poll",-1)),i("dd",T1,y(de(ss)(o(p).people))+" people ("+y(de(ss)(o(p).points))+" points)",1)])):q("",!0),i("div",null,[f[3]||(f[3]=i("dt",null,"Posts written",-1)),i("dd",E1,y(de(Xe)(p.posts_total)),1)])]),De(Tc,{n:p.final.n,expected:p.final.expected_yes,low:p.final.low,high:p.final.high,index:p.index,label:p.label},null,8,["n","expected","low","high","index","label"])],64)):(h(),m("p",A1,"No final poll recorded."))]))),128))]),f[13]||(f[13]=i("p",{class:"caveat"},"Ranges cover chance only, not model error. The crowd is synthetic.",-1)),e.summary.comparisons?.length?(h(),m("section",R1,[i("h3",null,"Compared with "+y(l.value[e.summary.comparisons[0].baseline]||e.summary.comparisons[0].baseline),1),i("ul",C1,[(h(!0),m(se,null,me(e.summary.comparisons,p=>(h(),m("li",{key:p.variant},[i("span",O1,y(l.value[p.variant]||p.variant),1),i("span",P1,y(de(ss)(p.diff_expected_yes))+" expected yes",1),i("span",N1,"90% range "+y(de(ss)(p.low))+" to "+y(de(ss)(p.high))+", chance of yes "+y(de(ss)(p.diff_mean_outcome*100))+" points",1),i("span",{class:He(["pill",{accent:p.verdict!=="within noise"}])},y(a[p.verdict]||p.verdict),3)]))),128))])])):q("",!0),i("section",I1,[f[4]||(f[4]=i("h3",null,"Mean chance of yes at each poll",-1)),De(i1,{series:s.value,"x-name":"Poll round","x-label":r,describe:"Mean chance of yes at each poll round, one line per variant"},null,8,["series"])]),i("section",M1,[f[12]||(f[12]=i("h3",{class:"sr-only"},"Usage",-1)),i("dl",L1,[i("div",null,[f[5]||(f[5]=i("dt",null,"Jev requests",-1)),i("dd",D1,[xe(y(de(Xe)(u.value.requests)),1),e.run?.planned_requests?(h(),m("span",F1," of "+y(de(Xe)(e.run.planned_requests))+" planned",1)):q("",!0)])]),i("div",null,[f[6]||(f[6]=i("dt",null,"Cache hits",-1)),i("dd",j1,y(de(Xe)(u.value.cache_hits)),1)]),i("div",null,[f[7]||(f[7]=i("dt",null,"Estimated Jev cost",-1)),i("dd",U1,y(de(pc)(u.value.est_cost_usd)),1)]),i("div",null,[f[8]||(f[8]=i("dt",null,"Jev input tokens",-1)),i("dd",V1,y(de(Xe)(u.value.input_tokens)),1)]),d.value?(h(),m("div",B1,[f[9]||(f[9]=i("dt",null,"Language model calls",-1)),i("dd",z1,[xe(y(de(Xe)(d.value.calls)),1),d.value.failures?(h(),m("span",q1,", "+y(d.value.failures)+" failed",1)):q("",!0)])])):q("",!0),i("div",null,[f[10]||(f[10]=i("dt",null,"Crowd",-1)),i("dd",H1,y(de(Xe)(e.summary.crowd.size))+" people",1)])]),i("p",G1,[xe("Judge model "+y(u.value.model),1),u.value.fake?(h(),m(se,{key:0},[xe(", a test stand-in, so these numbers are noise")],64)):q("",!0),f[11]||(f[11]=xe(".",-1))])])]))}},K1=ct(W1,[["__scopeId","data-v-30b405d5"]]),Y1={class:"stack-lg"},J1={key:0,class:"notice error",role:"alert"},X1={class:"panel","aria-labelledby":"set-head"},Z1={class:"stack-lg"},Q1={class:"form-grid"},ek={class:"field"},tk={class:"field"},nk={class:"field"},sk={class:"field"},lk={key:0,class:"notice info small"},rk={key:1,class:"stack"},ok={class:"checks"},ik=["value"],ak={class:"break"},uk={class:"muted small"},ck={class:"stack"},dk={key:0,class:"muted small"},fk={class:"field inj-round"},pk=["onUpdate:modelValue","max"],hk={class:"field inj-text"},mk=["onUpdate:modelValue"],gk={class:"field inj-author"},vk=["onUpdate:modelValue"],yk=["onClick","aria-label"],bk={class:"form-grid"},_k={class:"field"},kk=["placeholder"],wk={class:"field"},xk={class:"estimate","aria-live":"polite"},$k={class:"muted small"},Sk={class:"est"},Tk={class:"tnum"},Ek={class:"tnum"},Ak={class:"tnum"},Rk={key:0,class:"notice warn small"},Ck={key:1,class:"muted small"},Ok={key:2,class:"notice error small"},Pk={key:3,class:"notice error small"},Nk=["disabled"],Ik={key:4,class:"muted small"},Mk={key:5,class:"notice error small",role:"alert"},Lk={key:1,class:"panel stack-lg","aria-labelledby":"run-head"},Dk={class:"panel-head run-head"},Fk={class:"break"},jk={key:0,class:"live stack"},Uk={class:"row"},Vk={class:"muted small tnum"},Bk={key:0,class:"muted small tnum"},zk=["disabled"],qk=["aria-valuenow"],Hk={class:"small muted break"},Gk={key:2,class:"notice error break"},Wk={key:3,class:"notice warn"},Kk={key:4,class:"notice error"},Yk={class:"stack"},Jk={key:6,class:"row end"},Xk={__name:"StepSimulate",setup(e){const t=cl(),n=t.pid,s=K(()=>t.frame.value),l=J("");Promise.all([t.loadFrame(),t.loadCrowd()]).catch(F=>l.value=F.message);const r=Hn({platform:"reddit",rounds:12,min:8,max:20,variants:[],injections:[],pollRounds:"",maxRequests:""});Je(()=>s.value?s.value.variants.map(F=>F.id).join(""):null,(F,$)=>{if(F==null)return;const W=F.split(""),oe=$?$.split(""):[];r.variants=W.filter(te=>!oe.includes(te)||r.variants.includes(te))},{immediate:!0});let o=0;function a(){r.injections.push({key:++o,round:Math.max(1,Math.floor(Number(r.rounds)/2)||1),text:"",author:""})}const u=K(()=>{const F=Number(r.rounds);if(!Number.isInteger(F)||F<1||F>500)return"Rounds must be a whole number from 1 to 500.";const $=Number(r.min),W=Number(r.max);if(!Number.isInteger($)||!Number.isInteger(W)||$<1||$>W)return"People per round: the minimum must be at least 1 and no more than the maximum.";if(s.value&&!r.variants.length)return"Pick at least one variant.";for(const[oe,te]of r.injections.entries()){if(!te.text.trim())return`News item ${oe+1} needs text.`;const ee=Number(te.round);if(!Number.isInteger(ee)||ee<1||ee>F)return`News item ${oe+1} needs a round from 1 to ${F}.`}return r.pollRounds.trim()&&r.pollRounds.split(/[\s,]+/).filter(Boolean).some(te=>!/^\d+$/.test(te)||Number(te)>F)?`Poll rounds must be whole numbers from 0 to ${F}, separated by commas.`:String(r.maxRequests).trim()&&(!/^\d+$/.test(String(r.maxRequests).trim())||Number(r.maxRequests)<1)?"Request cap must be a positive whole number, or blank for the server default.":""}),d=K(()=>{const F=s.value?.variants.map(W=>W.id)||[];return{platform:r.platform,rounds:Number(r.rounds),agents_per_round_min:Number(r.min),agents_per_round_max:Number(r.max),variants:r.variants.length===F.length?[]:F.filter(W=>r.variants.includes(W)),injections:r.injections.map(W=>({round:Number(W.round),text:W.text.trim(),...W.author.trim()?{author:W.author.trim()}:{}})),poll_rounds:r.pollRounds.trim()?r.pollRounds.split(/[\s,]+/).filter(Boolean).map(Number):null,max_requests:String(r.maxRequests).trim()?Number(r.maxRequests):null}}),c=J(null),f=J(""),p=J(!1);let g=0;const N=mc(async()=>{if(u.value){c.value=null;return}const F=++g;p.value=!0;try{const $=await Ie.estimate(n.value,d.value);F===g&&(c.value=$,f.value="")}catch($){F===g&&(f.value=$.message,c.value=null)}finally{F===g&&(p.value=!1)}},400);Je(()=>JSON.stringify(d.value)+u.value,N,{immediate:!0});const x=K(()=>c.value&&c.value.planned_requests>c.value.cap),R=K(()=>t.tasks.run),A=K(()=>t.runs.value.some(F=>uo.has(F.status))||R.value&&["queued","running"].includes(R.value.status)),P=J(!1),j=J("");async function O(){if(j.value="",u.value)return j.value=u.value;P.value=!0;try{const{run:F,task:$}=await Ie.startRun(n.value,d.value);await t.refresh(),t.selectedRunId.value=F.id,t.track($)}catch(F){j.value=F.message}finally{P.value=!1}}const C=K(()=>t.selectedRun.value),D=K(()=>!!C.value&&uo.has(C.value.status)),k=K(()=>C.value&&R.value&&R.value.id===C.value.task_id?R.value:null),_=J(null),w=J("");async function E(F){if(w.value="",!C.value)return _.value=null;try{_.value=await t.loadRun(C.value.id,F)}catch($){w.value=$.message}}Je(()=>C.value&&`${C.value.id}:${C.value.status}`,()=>E(!0),{immediate:!0});const S=J(!1);async function I(){if(C.value){S.value=!0;try{await Ie.cancelRun(n.value,C.value.id),await t.refresh()}catch(F){w.value=F.message}finally{S.value=!1}}}const V=K(()=>{const F=C.value?.variants?.length?C.value.variants:s.value?.variants.map(W=>W.id)||[],$=Object.fromEntries((s.value?.variants||[]).map(W=>[W.id,W.label]));for(const W of _.value?.summary?.variants||[])$[W.id]=W.label;return F.map(W=>({id:W,label:$[W]||W}))}),z=K(()=>Object.fromEntries((s.value?.talking_points||[]).map(F=>[F.id,F.text]))),ge=K(()=>Math.round((k.value?.progress??C.value?.progress??0)*100)),le={queued:"Queued",running:"Running",done:"Finished",partial:"Partly finished",failed:"Failed",cancelled:"Cancelled"};return Gn(()=>g++),(F,$)=>{const W=Nn("RouterLink");return h(),m("div",Y1,[l.value?(h(),m("div",J1,y(l.value),1)):q("",!0),i("section",X1,[$[25]||($[25]=i("div",{class:"panel-head"},[i("h2",{id:"set-head"},"New run"),i("p",null,"Each round, some people read their feed and Jev picks what each one does.")],-1)),i("form",{class:"run-grid",onSubmit:kn(O,["prevent"])},[i("div",Z1,[i("div",Q1,[i("label",ek,[$[8]||($[8]=i("span",{class:"label"},"Platform",-1)),Se(i("select",{"onUpdate:modelValue":$[0]||($[0]=oe=>r.platform=oe)},[...$[7]||($[7]=[i("option",{value:"reddit"},"Reddit style",-1),i("option",{value:"lite"},"Lite (fast, in memory)",-1),i("option",{value:"twitter"},"Twitter style",-1)])],512),[[_n,r.platform]])]),i("label",tk,[$[9]||($[9]=i("span",{class:"label"},"Rounds",-1)),Se(i("input",{"onUpdate:modelValue":$[1]||($[1]=oe=>r.rounds=oe),type:"number",min:"1",max:"500",step:"1"},null,512),[[Le,r.rounds,void 0,{number:!0}]])]),i("label",nk,[$[10]||($[10]=i("span",{class:"label"},"People per round, min",-1)),Se(i("input",{"onUpdate:modelValue":$[2]||($[2]=oe=>r.min=oe),type:"number",min:"1",step:"1"},null,512),[[Le,r.min,void 0,{number:!0}]])]),i("label",sk,[$[11]||($[11]=i("span",{class:"label"},"People per round, max",-1)),Se(i("input",{"onUpdate:modelValue":$[3]||($[3]=oe=>r.max=oe),type:"number",min:"1",step:"1"},null,512),[[Le,r.max,void 0,{number:!0}]])])]),r.platform==="twitter"?(h(),m("p",lk," The Twitter style platform downloads a recommendation model of about 500 MB the first time it runs. ")):q("",!0),s.value?(h(),m("fieldset",rk,[$[12]||($[12]=i("legend",{class:"label"},"Variants to run",-1)),i("div",ok,[(h(!0),m(se,null,me(s.value.variants,oe=>(h(),m("label",{key:oe.id,class:"check"},[Se(i("input",{"onUpdate:modelValue":$[4]||($[4]=te=>r.variants=te),type:"checkbox",value:oe.id},null,8,ik),[[Qu,r.variants]]),i("span",ak,[xe(y(oe.label)+" ",1),i("span",uk,y(oe.id),1)])]))),128))])])):q("",!0),i("fieldset",ck,[$[16]||($[16]=i("legend",{class:"label"},"News during the run",-1)),r.injections.length?q("",!0):(h(),m("p",dk,"None. Add a news post to see how the crowd reacts to it.")),(h(!0),m(se,null,me(r.injections,(oe,te)=>(h(),m("div",{key:oe.key,class:"inj"},[i("label",fk,[$[13]||($[13]=i("span",{class:"label small"},"Round",-1)),Se(i("input",{"onUpdate:modelValue":ee=>oe.round=ee,type:"number",min:"1",max:r.rounds,step:"1"},null,8,pk),[[Le,oe.round,void 0,{number:!0}]])]),i("label",hk,[$[14]||($[14]=i("span",{class:"label small"},"Text",-1)),Se(i("input",{"onUpdate:modelValue":ee=>oe.text=ee,type:"text",placeholder:"Coliving Co cuts its rent by 10%"},null,8,mk),[[Le,oe.text]])]),i("label",gk,[$[15]||($[15]=i("span",{class:"label small"},"Posted by",-1)),Se(i("input",{"onUpdate:modelValue":ee=>oe.author=ee,type:"text",placeholder:"News desk"},null,8,vk),[[Le,oe.author]])]),i("button",{class:"btn small ghost",type:"button",onClick:ee=>r.injections.splice(te,1),"aria-label":`Remove news item ${te+1}`},"Remove",8,yk)]))),128)),i("div",null,[i("button",{class:"btn small",type:"button",onClick:a},"Add news")])]),i("div",bk,[i("label",_k,[$[17]||($[17]=i("span",{class:"label"},"Poll after rounds",-1)),Se(i("input",{"onUpdate:modelValue":$[5]||($[5]=oe=>r.pollRounds=oe),type:"text",placeholder:`0, ${Math.floor((Number(r.rounds)||0)/2)}, ${r.rounds}`},null,8,kk),[[Le,r.pollRounds]]),$[18]||($[18]=i("span",{class:"hint"},"0 means before round 1. Blank uses the start, middle and end.",-1))]),i("label",wk,[$[19]||($[19]=i("span",{class:"label"},"Request cap",-1)),Se(i("input",{"onUpdate:modelValue":$[6]||($[6]=oe=>r.maxRequests=oe),type:"text",inputmode:"numeric",placeholder:"Server default"},null,512),[[Le,r.maxRequests]]),$[20]||($[20]=i("span",{class:"hint"},"The run refuses to start above this.",-1))])])]),i("aside",xk,[$[24]||($[24]=i("h3",null,"Estimate",-1)),c.value?(h(),m(se,{key:0},[i("p",{class:He(["est-big tnum",{stale:p.value}])},y(de(Xe)(c.value.planned_requests)),3),i("p",$k,"Jev requests at most, cap "+y(de(Xe)(c.value.cap)),1),i("dl",Sk,[i("div",null,[$[21]||($[21]=i("dt",null,"Estimated cost",-1)),i("dd",Tk,y(de(pc)(c.value.est_cost_usd)),1)]),i("div",null,[$[22]||($[22]=i("dt",null,"Input tokens",-1)),i("dd",Ek,y(de(Xe)(c.value.est_input_tokens)),1)]),i("div",null,[$[23]||($[23]=i("dt",null,"Polls after rounds",-1)),i("dd",Ak,y(c.value.polls.join(", ")),1)])]),x.value?(h(),m("p",Rk,"This is over the cap. Lower the rounds or people per round, or raise the cap.")):q("",!0)],64)):p.value?(h(),m("p",Ck,"Working it out")):q("",!0),u.value?(h(),m("p",Ok,y(u.value),1)):f.value?(h(),m("p",Pk,y(f.value),1)):q("",!0),i("button",{class:"btn primary start",type:"submit",disabled:P.value||A.value||!!u.value||x.value},y(P.value?"Starting":"Start run"),9,Nk),A.value?(h(),m("p",Ik,"A run is already going. Wait for it or cancel it.")):q("",!0),j.value?(h(),m("p",Mk,y(j.value),1)):q("",!0)])],32)]),C.value?(h(),m("section",Lk,[i("div",Dk,[$[26]||($[26]=i("h2",{id:"run-head"},"Run",-1)),i("span",{class:He(["pill",{good:C.value.status==="done",warn:C.value.status==="partial"||C.value.status==="cancelled",bad:C.value.status==="failed",accent:D.value}])},y(le[C.value.status]||C.value.status),3),i("p",Fk,y(de(vc)(C.value)),1)]),D.value?(h(),m("div",jk,[i("div",Uk,[i("strong",null,y(C.value.status==="queued"?"Waiting to start":"Simulating"),1),i("span",Vk,y(ge.value)+"%",1),C.value.requests!=null?(h(),m("span",Bk,y(de(Xe)(C.value.requests))+" of "+y(de(Xe)(C.value.planned_requests))+" requests",1)):q("",!0),$[27]||($[27]=i("span",{class:"spacer"},null,-1)),i("button",{class:"btn small danger",type:"button",disabled:S.value,onClick:I},y(S.value?"Cancelling":"Cancel run"),9,zk)]),i("div",{class:"progress",role:"progressbar","aria-valuenow":ge.value,"aria-valuemin":"0","aria-valuemax":"100"},[i("div",{style:We({width:ge.value+"%"})},null,4)],8,qk),i("p",Hk,y(k.value?.message||C.value.message),1)])):k.value&&k.value.status==="failed"&&!C.value.error?(h(),ln(cr,{key:1,task:k.value},null,8,["task"])):q("",!0),C.value.status==="failed"&&C.value.error?(h(),m("p",Gk,y(C.value.error),1)):q("",!0),C.value.status==="cancelled"?(h(),m("p",Wk,"This run was cancelled before it finished.")):q("",!0),w.value?(h(),m("p",Kk,y(w.value),1)):q("",!0),_.value?.summary&&de(ll).has(C.value.status)?(h(),ln(K1,{key:5,summary:_.value.summary,run:_.value},null,8,["summary","run"])):q("",!0),i("div",Yk,[$[28]||($[28]=i("h3",null,"Activity",-1)),De(j_,{pid:de(n),"run-id":C.value.id,active:D.value,variants:V.value,points:z.value},null,8,["pid","run-id","active","variants","points"])]),de(ll).has(C.value.status)?(h(),m("div",Jk,[De(W,{class:"btn",to:{name:"ask",params:{pid:de(n)},query:{run:C.value.id}}},{default:Vt(()=>[...$[29]||($[29]=[xe("Ask the crowd",-1)])]),_:1},8,["to"]),De(W,{class:"btn primary",to:{name:"report",params:{pid:de(n)},query:{run:C.value.id}}},{default:Vt(()=>[...$[30]||($[30]=[xe("Go to the report",-1)])]),_:1},8,["to"])])):q("",!0)])):q("",!0)])}}},Zk=ct(Xk,[["__scopeId","data-v-07da18f1"]]);function Vo(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var Jn=Vo();function Ec(e){Jn=e}var Ks={exec:()=>null};function Fe(e,t=""){let n=typeof e=="string"?e:e.source,s={replace:(l,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(St.caret,"$1"),n=n.replace(l,o),s},getRegex:()=>new RegExp(n,t)};return s}var Qk=(()=>{try{return!!new RegExp("(?<=1)(?/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceTabs:/^\t+/,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] /,listReplaceTask:/^\[[ 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,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,unescapeTest:/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>new RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`),hrRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`),fencesBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}(?:\`\`\`|~~~)`),headingBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}#`),htmlBeginRegex:e=>new RegExp(`^ {0,${Math.min(3,e-1)}}<(?:[a-z].*>|!--)`,"i")},e0=/^(?:[ \t]*(?:\n|$))+/,t0=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,n0=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,dl=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,s0=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,Bo=/(?:[*+-]|\d{1,9}[.)])/,Ac=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,Rc=Fe(Ac).replace(/bull/g,Bo).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),l0=Fe(Ac).replace(/bull/g,Bo).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}/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),zo=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\n)[^\n]+)*)/,r0=/^[^\n]+/,qo=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,o0=Fe(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("label",qo).replace("title",/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),i0=Fe(/^( {0,3}bull)([ \t][^\n]+?)?(?:\n|$)/).replace(/bull/g,Bo).getRegex(),dr="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",Ho=/|$))/,a0=Fe("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:[^\\n]*\\n+|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>\\n*|$)|\\n*|$)|\\n*|$)|)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",Ho).replace("tag",dr).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Cc=Fe(zo).replace("hr",dl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",dr).getRegex(),u0=Fe(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace("paragraph",Cc).getRegex(),Go={blockquote:u0,code:t0,def:o0,fences:n0,heading:s0,hr:dl,html:a0,lheading:Rc,list:i0,newline:e0,paragraph:Cc,table:Ks,text:r0},ka=Fe("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",dl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",dr).getRegex(),c0={...Go,lheading:l0,table:ka,paragraph:Fe(zo).replace("hr",dl).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",ka).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n").replace("list"," {0,3}(?:[*+-]|1[.)]) ").replace("html",")|<(?:script|pre|style|textarea|!--)").replace("tag",dr).getRegex()},d0={...Go,html:Fe(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+? *(?:\\n{2,}|\\s*$)|\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace("comment",Ho).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:Ks,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:Fe(zo).replace("hr",dl).replace("heading",` *#{1,6} *[^ +]`).replace("lheading",Rc).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},f0=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,p0=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Oc=/^( {2,}|\\)\n(?!\s*$)/,h0=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\`+)[^`]+\k(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Qk?"(?`+)[^`]+\k(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Ic=/^(?:\*+(?:((?!\*)punct)|[^\s*]))|^_+(?:((?!_)punct)|([^\s_]))/,b0=Fe(Ic,"u").replace(/punct/g,fr).getRegex(),_0=Fe(Ic,"u").replace(/punct/g,Nc).getRegex(),Mc="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",k0=Fe(Mc,"gu").replace(/notPunctSpace/g,Pc).replace(/punctSpace/g,Wo).replace(/punct/g,fr).getRegex(),w0=Fe(Mc,"gu").replace(/notPunctSpace/g,v0).replace(/punctSpace/g,g0).replace(/punct/g,Nc).getRegex(),x0=Fe("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Pc).replace(/punctSpace/g,Wo).replace(/punct/g,fr).getRegex(),$0=Fe(/\\(punct)/,"gu").replace(/punct/g,fr).getRegex(),S0=Fe(/^<(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(),T0=Fe(Ho).replace("(?:-->|$)","-->").getRegex(),E0=Fe("^comment|^|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^|^").replace("comment",T0).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),zl=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+[^`]*?`+(?!`)|[^\[\]\\`])*?/,A0=Fe(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]*(?:\n[ \t]*)?)(title))?\s*\)/).replace("label",zl).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]*/).replace("title",/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),Lc=Fe(/^!?\[(label)\]\[(ref)\]/).replace("label",zl).replace("ref",qo).getRegex(),Dc=Fe(/^!?\[(ref)\](?:\[\])?/).replace("ref",qo).getRegex(),R0=Fe("reflink|nolink(?!\\()","g").replace("reflink",Lc).replace("nolink",Dc).getRegex(),wa=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Ko={_backpedal:Ks,anyPunctuation:$0,autolink:S0,blockSkip:y0,br:Oc,code:p0,del:Ks,emStrongLDelim:b0,emStrongRDelimAst:k0,emStrongRDelimUnd:x0,escape:f0,link:A0,nolink:Dc,punctuation:m0,reflink:Lc,reflinkSearch:R0,tag:E0,text:h0,url:Ks},C0={...Ko,link:Fe(/^!?\[(label)\]\((.*?)\)/).replace("label",zl).getRegex(),reflink:Fe(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",zl).getRegex()},po={...Ko,emStrongRDelimAst:w0,emStrongLDelim:_0,url:Fe(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("protocol",wa).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:Fe(/^([`~]+|[^`~])(?:(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\":">",'"':""","'":"'"},xa=e=>P0[e];function Kt(e,t){if(t){if(St.escapeTest.test(e))return e.replace(St.escapeReplace,xa)}else if(St.escapeTestNoEncode.test(e))return e.replace(St.escapeReplaceNoEncode,xa);return e}function $a(e){try{e=encodeURI(e).replace(St.percentDecode,"%")}catch{return null}return e}function Sa(e,t){let n=e.replace(St.findPipe,(r,o,a)=>{let u=!1,d=o;for(;--d>=0&&a[d]==="\\";)u=!u;return u?"|":" |"}),s=n.split(St.splitPipe),l=0;if(s[0].trim()||s.shift(),s.length>0&&!s.at(-1)?.trim()&&s.pop(),t)if(s.length>t)s.splice(t);else for(;s.length0?-2:-1}function Ta(e,t,n,s,l){let r=t.href,o=t.title||null,a=e[1].replace(l.other.outputLinkReplace,"$1");s.state.inLink=!0;let u={type:e[0].charAt(0)==="!"?"image":"link",raw:n,href:r,title:o,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=!1,u}function I0(e,t,n){let s=e.match(n.other.indentCodeCompensation);if(s===null)return t;let l=s[1];return t.split(` +`).map(r=>{let o=r.match(n.other.beginningSpace);if(o===null)return r;let[a]=o;return a.length>=l.length?r.slice(l.length):r}).join(` +`)}var ql=class{options;rules;lexer;constructor(e){this.options=e||Jn}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=t[0].replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:t[0],codeBlockStyle:"indented",text:this.options.pedantic?n:As(n,` +`)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=I0(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=As(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:"heading",raw: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:As(t[0],` +`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=As(t[0],` +`).split(` +`),s="",l="",r=[];for(;n.length>0;){let o=!1,a=[],u;for(u=0;u1,l={type:"list",raw:"",ordered:s,start:s?+n.slice(0,-1):"",loose:!1,items:[]};n=s?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=s?n:"[*+-]");let r=this.rules.other.listItemRegex(n),o=!1;for(;e;){let u=!1,d="",c="";if(!(t=r.exec(e))||this.rules.block.hr.test(e))break;d=t[0],e=e.substring(d.length);let f=t[2].split(` +`,1)[0].replace(this.rules.other.listReplaceTabs,A=>" ".repeat(3*A.length)),p=e.split(` +`,1)[0],g=!f.trim(),N=0;if(this.options.pedantic?(N=2,c=f.trimStart()):g?N=t[1].length+1:(N=t[2].search(this.rules.other.nonSpaceChar),N=N>4?1:N,c=f.slice(N),N+=t[1].length),g&&this.rules.other.blankLine.test(p)&&(d+=p+` +`,e=e.substring(p.length+1),u=!0),!u){let A=this.rules.other.nextBulletRegex(N),P=this.rules.other.hrRegex(N),j=this.rules.other.fencesBeginRegex(N),O=this.rules.other.headingBeginRegex(N),C=this.rules.other.htmlBeginRegex(N);for(;e;){let D=e.split(` +`,1)[0],k;if(p=D,this.options.pedantic?(p=p.replace(this.rules.other.listReplaceNesting," "),k=p):k=p.replace(this.rules.other.tabCharGlobal," "),j.test(p)||O.test(p)||C.test(p)||A.test(p)||P.test(p))break;if(k.search(this.rules.other.nonSpaceChar)>=N||!p.trim())c+=` +`+k.slice(N);else{if(g||f.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||j.test(f)||O.test(f)||P.test(f))break;c+=` +`+p}!g&&!p.trim()&&(g=!0),d+=D+` +`,e=e.substring(D.length+1),f=k.slice(N)}}l.loose||(o?l.loose=!0:this.rules.other.doubleBlankLine.test(d)&&(o=!0));let x=null,R;this.options.gfm&&(x=this.rules.other.listIsTask.exec(c),x&&(R=x[0]!=="[ ] ",c=c.replace(this.rules.other.listReplaceTask,""))),l.items.push({type:"list_item",raw:d,task:!!x,checked:R,loose:!1,text:c,tokens:[]}),l.raw+=d}let a=l.items.at(-1);if(a)a.raw=a.raw.trimEnd(),a.text=a.text.trimEnd();else return;l.raw=l.raw.trimEnd();for(let u=0;uf.type==="space"),c=d.length>0&&d.some(f=>this.rules.other.anyLine.test(f.raw));l.loose=c}if(l.loose)for(let u=0;u({text:a,tokens:this.lexer.inline(a),header:!1,align:r.align[u]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t)return{type:"heading",raw:t[0],depth:t[2].charAt(0)==="="?1:2,text:t[1],tokens:this.lexer.inline(t[1])}}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){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let r=As(n.slice(0,-1),"\\");if((n.length-r.length)%2===0)return}else{let r=N0(t[2],"()");if(r===-2)return;if(r>-1){let o=(t[0].indexOf("!")===0?5:4)+t[1].length+r;t[2]=t[2].substring(0,r),t[0]=t[0].substring(0,o).trim(),t[3]=""}}let s=t[2],l="";if(this.options.pedantic){let r=this.rules.other.pedanticHrefTitle.exec(s);r&&(s=r[1],l=r[3])}else l=t[3]?t[3].slice(1,-1):"";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),Ta(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,"$1"),title:l&&l.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[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal," "),l=t[s.toLowerCase()];if(!l){let r=n[0].charAt(0);return{type:"text",raw:r,text:r}}return Ta(n,l,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!(!s||s[3]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(s[1]||s[2])||!n||this.rules.inline.punctuation.exec(n))){let l=[...s[0]].length-1,r,o,a=l,u=0,d=s[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+l);(s=d.exec(t))!=null;){if(r=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!r)continue;if(o=[...r].length,s[3]||s[4]){a+=o;continue}else if((s[5]||s[6])&&l%3&&!((l+o)%3)){u+=o;continue}if(a-=o,a>0)continue;o=Math.min(o,o+a+u);let c=[...s[0]][0].length,f=e.slice(0,l+s.index+c+o);if(Math.min(l,o)%2){let g=f.slice(1,-1);return{type:"em",raw:f,text:g,tokens:this.lexer.inlineTokens(g)}}let p=f.slice(2,-2);return{type:"strong",raw:f,text:p,tokens:this.lexer.inlineTokens(p)}}}}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),l=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&l&&(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){let t=this.rules.inline.del.exec(e);if(t)return{type:"del",raw:t[0],text:t[2],tokens:this.lexer.inlineTokens(t[2])}}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,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 l;do l=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(l!==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,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:t[0],escaped:n}}}},Ft=class ho{tokens;options;state;tokenizer;inlineQueue;constructor(t){this.tokens=[],this.tokens.links=Object.create(null),this.options=t||Jn,this.options.tokenizer=this.options.tokenizer||new ql,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let n={other:St,block:Tl.normal,inline:Es.normal};this.options.pedantic?(n.block=Tl.pedantic,n.inline=Es.pedantic):this.options.gfm&&(n.block=Tl.gfm,this.options.breaks?n.inline=Es.breaks:n.inline=Es.gfm),this.tokenizer.rules=n}static get rules(){return{block:Tl,inline:Es}}static lex(t,n){return new ho(n).lex(t)}static lexInline(t,n){return new ho(n).inlineTokens(t)}lex(t){t=t.replace(St.carriageReturn,` +`),this.blockTokens(t,this.tokens);for(let n=0;n(l=o.call({lexer:this},t,n))?(t=t.substring(l.raw.length),n.push(l),!0):!1))continue;if(l=this.tokenizer.space(t)){t=t.substring(l.raw.length);let o=n.at(-1);l.raw.length===1&&o!==void 0?o.raw+=` +`:n.push(l);continue}if(l=this.tokenizer.code(t)){t=t.substring(l.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+l.raw,o.text+=` +`+l.text,this.inlineQueue.at(-1).src=o.text):n.push(l);continue}if(l=this.tokenizer.fences(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.heading(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.hr(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.blockquote(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.list(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.html(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.def(t)){t=t.substring(l.raw.length);let o=n.at(-1);o?.type==="paragraph"||o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+l.raw,o.text+=` +`+l.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[l.tag]||(this.tokens.links[l.tag]={href:l.href,title:l.title},n.push(l));continue}if(l=this.tokenizer.table(t)){t=t.substring(l.raw.length),n.push(l);continue}if(l=this.tokenizer.lheading(t)){t=t.substring(l.raw.length),n.push(l);continue}let r=t;if(this.options.extensions?.startBlock){let o=1/0,a=t.slice(1),u;this.options.extensions.startBlock.forEach(d=>{u=d.call({lexer:this},a),typeof u=="number"&&u>=0&&(o=Math.min(o,u))}),o<1/0&&o>=0&&(r=t.substring(0,o+1))}if(this.state.top&&(l=this.tokenizer.paragraph(r))){let o=n.at(-1);s&&o?.type==="paragraph"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+l.raw,o.text+=` +`+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(l),s=r.length!==t.length,t=t.substring(l.raw.length);continue}if(l=this.tokenizer.text(t)){t=t.substring(l.raw.length);let o=n.at(-1);o?.type==="text"?(o.raw+=(o.raw.endsWith(` +`)?"":` +`)+l.raw,o.text+=` +`+l.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):n.push(l);continue}if(t){let o="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(o);break}else throw new Error(o)}}return this.state.top=!0,n}inline(t,n=[]){return this.inlineQueue.push({src:t,tokens:n}),n}inlineTokens(t,n=[]){let s=t,l=null;if(this.tokens.links){let u=Object.keys(this.tokens.links);if(u.length>0)for(;(l=this.tokenizer.rules.inline.reflinkSearch.exec(s))!=null;)u.includes(l[0].slice(l[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,l.index)+"["+"a".repeat(l[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(l=this.tokenizer.rules.inline.anyPunctuation.exec(s))!=null;)s=s.slice(0,l.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(l=this.tokenizer.rules.inline.blockSkip.exec(s))!=null;)r=l[2]?l[2].length:0,s=s.slice(0,l.index+r)+"["+"a".repeat(l[0].length-r-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=this.options.hooks?.emStrongMask?.call({lexer:this},s)??s;let o=!1,a="";for(;t;){o||(a=""),o=!1;let u;if(this.options.extensions?.inline?.some(c=>(u=c.call({lexer:this},t,n))?(t=t.substring(u.raw.length),n.push(u),!0):!1))continue;if(u=this.tokenizer.escape(t)){t=t.substring(u.raw.length),n.push(u);continue}if(u=this.tokenizer.tag(t)){t=t.substring(u.raw.length),n.push(u);continue}if(u=this.tokenizer.link(t)){t=t.substring(u.raw.length),n.push(u);continue}if(u=this.tokenizer.reflink(t,this.tokens.links)){t=t.substring(u.raw.length);let c=n.at(-1);u.type==="text"&&c?.type==="text"?(c.raw+=u.raw,c.text+=u.text):n.push(u);continue}if(u=this.tokenizer.emStrong(t,s,a)){t=t.substring(u.raw.length),n.push(u);continue}if(u=this.tokenizer.codespan(t)){t=t.substring(u.raw.length),n.push(u);continue}if(u=this.tokenizer.br(t)){t=t.substring(u.raw.length),n.push(u);continue}if(u=this.tokenizer.del(t)){t=t.substring(u.raw.length),n.push(u);continue}if(u=this.tokenizer.autolink(t)){t=t.substring(u.raw.length),n.push(u);continue}if(!this.state.inLink&&(u=this.tokenizer.url(t))){t=t.substring(u.raw.length),n.push(u);continue}let d=t;if(this.options.extensions?.startInline){let c=1/0,f=t.slice(1),p;this.options.extensions.startInline.forEach(g=>{p=g.call({lexer:this},f),typeof p=="number"&&p>=0&&(c=Math.min(c,p))}),c<1/0&&c>=0&&(d=t.substring(0,c+1))}if(u=this.tokenizer.inlineText(d)){t=t.substring(u.raw.length),u.raw.slice(-1)!=="_"&&(a=u.raw.slice(-1)),o=!0;let c=n.at(-1);c?.type==="text"?(c.raw+=u.raw,c.text+=u.text):n.push(u);continue}if(t){let c="Infinite loop on byte: "+t.charCodeAt(0);if(this.options.silent){console.error(c);break}else throw new Error(c)}}return n}},Hl=class{options;parser;constructor(e){this.options=e||Jn}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(St.notSpaceStart)?.[0],l=e.replace(St.endingNewline,"")+` +`;return s?'
'+(n?l:Kt(l,!0))+`
+`:"
"+(n?l:Kt(l,!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 o=0;o +`+s+" +`}listitem(e){let t="";if(e.task){let n=this.checkbox({checked:!!e.checked});e.loose?e.tokens[0]?.type==="paragraph"?(e.tokens[0].text=n+" "+e.tokens[0].text,e.tokens[0].tokens&&e.tokens[0].tokens.length>0&&e.tokens[0].tokens[0].type==="text"&&(e.tokens[0].tokens[0].text=n+" "+Kt(e.tokens[0].tokens[0].text),e.tokens[0].tokens[0].escaped=!0)):e.tokens.unshift({type:"text",raw:n+" ",text:n+" ",escaped:!0}):t+=n+" "}return t+=this.parser.parse(e.tokens,!!e.loose),`
  • ${t}
  • +`}checkbox({checked:e}){return"'}paragraph({tokens:e}){return`

    ${this.parser.parseInline(e)}

    +`}table(e){let t="",n="";for(let l=0;l${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`${Kt(e,!0)}`}br(e){return"
    "}del({tokens:e}){return`${this.parser.parseInline(e)}`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),l=$a(e);if(l===null)return s;e=l;let r='
    ",r}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let l=$a(e);if(l===null)return Kt(n);e=l;let r=`${n}{let o=l[r].flat(1/0);n=n.concat(this.walkTokens(o,t))}):l.tokens&&(n=n.concat(this.walkTokens(l.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(l=>{if(!l.name)throw new Error("extension name required");if("renderer"in l){let r=t.renderers[l.name];r?t.renderers[l.name]=function(...o){let a=l.renderer.apply(this,o);return a===!1&&(a=r.apply(this,o)),a}:t.renderers[l.name]=l.renderer}if("tokenizer"in l){if(!l.level||l.level!=="block"&&l.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[l.level];r?r.unshift(l.tokenizer):t[l.level]=[l.tokenizer],l.start&&(l.level==="block"?t.startBlock?t.startBlock.push(l.start):t.startBlock=[l.start]:l.level==="inline"&&(t.startInline?t.startInline.push(l.start):t.startInline=[l.start]))}"childTokens"in l&&l.childTokens&&(t.childTokens[l.name]=l.childTokens)}),s.extensions=t),n.renderer){let l=this.defaults.renderer||new Hl(this.defaults);for(let r in n.renderer){if(!(r in l))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let o=r,a=n.renderer[o],u=l[o];l[o]=(...d)=>{let c=a.apply(l,d);return c===!1&&(c=u.apply(l,d)),c||""}}s.renderer=l}if(n.tokenizer){let l=this.defaults.tokenizer||new ql(this.defaults);for(let r in n.tokenizer){if(!(r in l))throw new Error(`tokenizer '${r}' does not exist`);if(["options","rules","lexer"].includes(r))continue;let o=r,a=n.tokenizer[o],u=l[o];l[o]=(...d)=>{let c=a.apply(l,d);return c===!1&&(c=u.apply(l,d)),c}}s.tokenizer=l}if(n.hooks){let l=this.defaults.hooks||new Ds;for(let r in n.hooks){if(!(r in l))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let o=r,a=n.hooks[o],u=l[o];Ds.passThroughHooks.has(r)?l[o]=d=>{if(this.defaults.async&&Ds.passThroughHooksRespectAsync.has(r))return(async()=>{let f=await a.call(l,d);return u.call(l,f)})();let c=a.call(l,d);return u.call(l,c)}:l[o]=(...d)=>{if(this.defaults.async)return(async()=>{let f=await a.apply(l,d);return f===!1&&(f=await u.apply(l,d)),f})();let c=a.apply(l,d);return c===!1&&(c=u.apply(l,d)),c}}s.hooks=l}if(n.walkTokens){let l=this.defaults.walkTokens,r=n.walkTokens;s.walkTokens=function(o){let a=[];return a.push(r.call(this,o)),l&&(a=a.concat(l.call(this,o))),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Ft.lex(e,t??this.defaults)}parser(e,t){return jt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let s={...n},l={...this.defaults,...s},r=this.onError(!!l.silent,!!l.async);if(this.defaults.async===!0&&s.async===!1)return r(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 t>"u"||t===null)return r(new Error("marked(): input parameter is undefined or null"));if(typeof t!="string")return r(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(t)+", string expected"));if(l.hooks&&(l.hooks.options=l,l.hooks.block=e),l.async)return(async()=>{let o=l.hooks?await l.hooks.preprocess(t):t,a=await(l.hooks?await l.hooks.provideLexer():e?Ft.lex:Ft.lexInline)(o,l),u=l.hooks?await l.hooks.processAllTokens(a):a;l.walkTokens&&await Promise.all(this.walkTokens(u,l.walkTokens));let d=await(l.hooks?await l.hooks.provideParser():e?jt.parse:jt.parseInline)(u,l);return l.hooks?await l.hooks.postprocess(d):d})().catch(r);try{l.hooks&&(t=l.hooks.preprocess(t));let o=(l.hooks?l.hooks.provideLexer():e?Ft.lex:Ft.lexInline)(t,l);l.hooks&&(o=l.hooks.processAllTokens(o)),l.walkTokens&&this.walkTokens(o,l.walkTokens);let a=(l.hooks?l.hooks.provideParser():e?jt.parse:jt.parseInline)(o,l);return l.hooks&&(a=l.hooks.postprocess(a)),a}catch(o){return r(o)}}}onError(e,t){return n=>{if(n.message+=` +Please report this to https://github.com/markedjs/marked.`,e){let s="

    An error occurred:

    "+Kt(n.message+"",!0)+"
    ";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},Kn=new M0;function Be(e,t){return Kn.parse(e,t)}Be.options=Be.setOptions=function(e){return Kn.setOptions(e),Be.defaults=Kn.defaults,Ec(Be.defaults),Be};Be.getDefaults=Vo;Be.defaults=Jn;Be.use=function(...e){return Kn.use(...e),Be.defaults=Kn.defaults,Ec(Be.defaults),Be};Be.walkTokens=function(e,t){return Kn.walkTokens(e,t)};Be.parseInline=Kn.parseInline;Be.Parser=jt;Be.parser=jt.parse;Be.Renderer=Hl;Be.TextRenderer=Yo;Be.Lexer=Ft;Be.lexer=Ft.lex;Be.Tokenizer=ql;Be.Hooks=Ds;Be.parse=Be;Be.options;Be.setOptions;Be.use;Be.walkTokens;Be.parseInline;jt.parse;Ft.lex;function Ea(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,s=Array(t);n2?s-2:0),r=2;r1?n-1:0),l=1;l"u"?null:st(BigInt.prototype.toString),Na=typeof Symbol>"u"?null:st(Symbol.prototype.toString),Ct=st(Object.prototype.hasOwnProperty),Os=st(Object.prototype.toString),dt=st(RegExp.prototype.test),Dn=Y0(TypeError);function st(e){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var n=arguments.length,s=new Array(n>1?n-1:0),l=1;l2&&arguments[2]!==void 0?arguments[2]:Fs;if(Aa&&Aa(e,null),!cs(t))return e;let s=t.length;for(;s--;){let l=t[s];if(typeof l=="string"){const r=n(l);r!==l&&(V0(t)||(t[s]=r),l=r)}e[l]=!0}return e}function J0(e){for(let t=0;t/g),sw=it(/\${[\w\W]*/g),lw=it(/^data-[\-\w.\u00B7-\uFFFF]+$/),rw=it(/^aria-[\-\w]+$/),Fa=it(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),ow=it(/^(?:\w+script|data):/i),iw=it(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),aw=it(/^html$/i),uw=it(/^[a-z][.\w]*(-[.\w]+)+$/i),ja=it(/<[/\w!]/g),Ua=it(/<[/\w]/g),cw=it(/<\/no(script|embed|frames)/i),dw=it(/\/>/i),Ot={element:1,attribute:2,text:3,cdataSection:4,entityReference:5,entityNode:6,processingInstruction:7,comment:8,document:9,documentType:10,documentFragment:11,notation:12},Uc=["style","script","xmp","iframe","noembed","noframes","plaintext","noscript"],fw=rt(Me({},Uc)),pw=(function(){const e={};return jn(Uc,t=>{e[t]=it(new RegExp("])","i"))}),rt(e)})(),hw=function(){return typeof window>"u"?null:window},mw=function(t,n){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let s=null;const l="data-tt-policy-suffix";n&&n.hasAttribute(l)&&(s=n.getAttribute(l));const r="dompurify"+(s?"#"+s:"");try{return t.createPolicy(r,{createHTML(o){return o},createScriptURL(o){return o}})}catch{return console.warn("TrustedTypes policy "+r+" could not be created."),null}},Va=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},Sn=function(t,n,s,l){return Ct(t,n)&&cs(t[n])?Me(l.base?Pt(l.base):{},t[n],l.transform):s},qr=function(t,n,s){const l=Ct(t,n)?t[n]:void 0;return l&&typeof l=="object"?Pt(l):s()};function Vc(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:hw();const t=re=>Vc(re);if(t.version="3.4.15",t.removed=[],!e||!e.document||e.document.nodeType!==Ot.document||!e.Element)return t.isSupported=!1,t;let n=e.document;const s=n,l=s.currentScript;e.DocumentFragment;const r=e.HTMLTemplateElement,o=e.Node,a=e.Element,u=e.NodeFilter,d=e.NamedNodeMap;d===void 0&&(e.NamedNodeMap||e.MozNamedAttrMap),e.HTMLFormElement;const c=e.DOMParser,f=e.trustedTypes,p=a.prototype,g=Mt(p,"cloneNode"),N=Mt(p,"remove"),x=Mt(p,"removeAttributeNode"),R=Mt(p,"nextSibling"),A=Mt(p,"childNodes"),P=Mt(p,"parentNode"),j=Mt(p,"shadowRoot"),O=Mt(p,"attributes"),C=o&&o.prototype?Mt(o.prototype,"nodeType"):null,D=o&&o.prototype?Mt(o.prototype,"nodeName"):null,k=o&&o.prototype?Mt(o.prototype,"ownerDocument"):null,_=function(v){return C?C(v):v.nodeType},w=function(v){return D?D(v):v.nodeName};if(typeof r=="function"){const re=n.createElement("template");re.content&&re.content.ownerDocument&&(n=re.content.ownerDocument)}let E,S="",I,V=!1,z=0;const ge=function(){if(z>0)throw Dn('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.')},le=function(v){ge(),z++;try{return E.createHTML(v)}finally{z--}},F=function(v){ge(),z++;try{return E.createScriptURL(v)}finally{z--}},$=function(){return V||(I=mw(f,l),V=!0),I},W=n,oe=W.implementation,te=W.createNodeIterator,ee=W.createDocumentFragment,G=W.getElementsByTagName,Y=s.importNode;let ne=Va();t.isSupported=typeof Fc=="function"&&typeof P=="function"&&oe&&oe.createHTMLDocument!==void 0;const Ee=tw,H=nw,ae=sw,ce=lw,be=rw,Re=ow,b=iw,T=uw;let L=Fa,B=null;const X=Me({},[...Ia,...Ur,...Vr,...Br,...Ma]);let U=null;const fe=Me({},[...La,...zr,...Da,...El]);let ie=Object.seal(os(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}})),ue=null,Q=null;const ve=Object.seal(os(null,{tagCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeCheck:{writable:!0,configurable:!1,enumerable:!0,value:null}}));let pe=!0,_e=!0,we=!1,Ce=!0,Oe=!1,Pe=!0,qe=!1,tt=!1,mt=null,gt=null,rn=!1,on=!1,ot=!1,vt=!1,ys=!0,bs=!1;const Jo="user-content-";let pr=!0,hr=!1,Xn={},Zn=null;const Xo=Me({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","selectedcontent","style","svg","template","thead","title","video","xmp"]);let Zo=null;const Qo=Me({},["audio","video","img","source","image","track"]);let ei=null;const ti=Me({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),fl="http://www.w3.org/1998/Math/MathML",pl="http://www.w3.org/2000/svg",Ht="http://www.w3.org/1999/xhtml";let Qn=Ht,mr=!1,gr=null;const zc=Me({},[fl,pl,Ht],jr),ni=rt(["mi","mo","mn","ms","mtext"]);let vr=Me({},ni);const si=rt(["annotation-xml"]);let yr=Me({},si);const qc=Me({},["title","style","font","a","script"]);let _s=null;const Hc=["application/xhtml+xml","text/html"],Gc="text/html";let nt=null,es=null;const Wc=n.createElement("form"),li=function(v){return v instanceof RegExp||v instanceof Function},br=function(){let v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(es&&es===v)return;(!v||typeof v!="object")&&(v={}),v=Pt(v),_s=Hc.indexOf(v.PARSER_MEDIA_TYPE)===-1?Gc:v.PARSER_MEDIA_TYPE,nt=_s==="application/xhtml+xml"?jr:Fs,B=Sn(v,"ALLOWED_TAGS",X,{transform:nt}),U=Sn(v,"ALLOWED_ATTR",fe,{transform:nt}),gr=Sn(v,"ALLOWED_NAMESPACES",zc,{transform:jr}),ei=Sn(v,"ADD_URI_SAFE_ATTR",ti,{transform:nt,base:ti}),Zo=Sn(v,"ADD_DATA_URI_TAGS",Qo,{transform:nt,base:Qo}),Zn=Sn(v,"FORBID_CONTENTS",Xo,{transform:nt}),ue=Sn(v,"FORBID_TAGS",Pt({}),{transform:nt}),Q=Sn(v,"FORBID_ATTR",Pt({}),{transform:nt}),Xn=Ct(v,"USE_PROFILES")?v.USE_PROFILES&&typeof v.USE_PROFILES=="object"?Pt(v.USE_PROFILES):v.USE_PROFILES:!1,pe=v.ALLOW_ARIA_ATTR!==!1,_e=v.ALLOW_DATA_ATTR!==!1,we=v.ALLOW_UNKNOWN_PROTOCOLS||!1,Ce=v.ALLOW_SELF_CLOSE_IN_ATTR!==!1,Oe=v.SAFE_FOR_TEMPLATES||!1,Pe=v.SAFE_FOR_XML!==!1,qe=v.WHOLE_DOCUMENT||!1,on=v.RETURN_DOM||!1,ot=v.RETURN_DOM_FRAGMENT||!1,vt=v.RETURN_TRUSTED_TYPE||!1,rn=v.FORCE_BODY||!1,ys=v.SANITIZE_DOM!==!1,bs=v.SANITIZE_NAMED_PROPS||!1,pr=v.KEEP_CONTENT!==!1,hr=v.IN_PLACE||!1,L=Z0(v.ALLOWED_URI_REGEXP)?v.ALLOWED_URI_REGEXP:Fa,Qn=typeof v.NAMESPACE=="string"?v.NAMESPACE:Ht,vr=qr(v,"MATHML_TEXT_INTEGRATION_POINTS",()=>Me({},ni)),yr=qr(v,"HTML_INTEGRATION_POINTS",()=>Me({},si));const M=qr(v,"CUSTOM_ELEMENT_HANDLING",()=>os(null));if(ie=os(null),Ct(M,"tagNameCheck")&&li(M.tagNameCheck)&&(ie.tagNameCheck=M.tagNameCheck),Ct(M,"attributeNameCheck")&&li(M.attributeNameCheck)&&(ie.attributeNameCheck=M.attributeNameCheck),Ct(M,"allowCustomizedBuiltInElements")&&typeof M.allowCustomizedBuiltInElements=="boolean"&&(ie.allowCustomizedBuiltInElements=M.allowCustomizedBuiltInElements),it(ie),Oe&&(_e=!1),ot&&(on=!0),Xn&&(B=Me({},Ma),U=os(null),Xn.html===!0&&(Me(B,Ia),Me(U,La)),Xn.svg===!0&&(Me(B,Ur),Me(U,zr),Me(U,El)),Xn.svgFilters===!0&&(Me(B,Vr),Me(U,zr),Me(U,El)),Xn.mathMl===!0&&(Me(B,Br),Me(U,Da),Me(U,El))),ve.tagCheck=null,ve.attributeCheck=null,Ct(v,"ADD_TAGS")&&(typeof v.ADD_TAGS=="function"?ve.tagCheck=v.ADD_TAGS:cs(v.ADD_TAGS)&&(B===X&&(B=Pt(B)),Me(B,v.ADD_TAGS,nt))),Ct(v,"ADD_ATTR")&&(typeof v.ADD_ATTR=="function"?ve.attributeCheck=v.ADD_ATTR:cs(v.ADD_ATTR)&&(U===fe&&(U=Pt(U)),Me(U,v.ADD_ATTR,nt))),Ct(v,"ADD_FORBID_CONTENTS")&&cs(v.ADD_FORBID_CONTENTS)&&(Zn===Xo&&(Zn=Pt(Zn)),Me(Zn,v.ADD_FORBID_CONTENTS,nt)),pr&&(B["#text"]=!0),qe&&Me(B,["html","head","body"]),B.table&&(Me(B,["tbody"]),delete ue.tbody),v.TRUSTED_TYPES_POLICY){if(typeof v.TRUSTED_TYPES_POLICY.createHTML!="function")throw Dn('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof v.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw Dn('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');const Z=E;E=v.TRUSTED_TYPES_POLICY;try{S=le("")}catch(he){throw E=Z,he}}else v.TRUSTED_TYPES_POLICY===null?(E=void 0,S=""):(E===void 0&&(E=$()),E&&typeof S=="string"&&(S=le("")));rt&&rt(v),es=v},ri=Me({},[...Ur,...Vr,...Q0]),oi=Me({},[...Br,...ew]),Kc=function(v,M,Z){return M.namespaceURI===Ht?v==="svg":M.namespaceURI===fl?v==="svg"&&(Z==="annotation-xml"||vr[Z]):!!ri[v]},Yc=function(v,M,Z){return M.namespaceURI===Ht?v==="math":M.namespaceURI===pl?v==="math"&&yr[Z]:!!oi[v]},Jc=function(v,M,Z){return M.namespaceURI===pl&&!yr[Z]||M.namespaceURI===fl&&!vr[Z]?!1:!oi[v]&&(qc[v]||!ri[v])},Xc=function(v){let M=P(v);(!M||!M.tagName)&&(M={namespaceURI:Qn,tagName:"template"});const Z=Fs(v.tagName),he=Fs(M.tagName);return gr[v.namespaceURI]?v.namespaceURI===pl?Kc(Z,M,he):v.namespaceURI===fl?Yc(Z,M,he):v.namespaceURI===Ht?Jc(Z,M,he):!!(_s==="application/xhtml+xml"&&gr[v.namespaceURI]):!1},xn=function(v){Rs(t.removed,{element:v});try{P(v).removeChild(v)}catch{if(N(v),!P(v))throw Dn("a node selected for removal could not be detached from its tree and cannot be safely returned; refusing to sanitize in place")}},ii=function(v,M,Z){try{x(v,M)}catch{try{v.removeAttribute(Z)}catch{}}},hl=function(v){ml(v);const M=A(v);if(M){const he=[];jn(M,ye=>{Rs(he,ye)}),jn(he,ye=>{try{N(ye)}catch{}})}const Z=O(v);if(Z)for(let he=Z.length-1;he>=0;--he){const ye=Z[he],$e=ye&&ye.name;typeof $e=="string"&&ii(v,ye,$e)}},In=function(v,M,Z){if(!Z)try{Z=M.getAttributeNode(v)}catch{Z=null}Rs(t.removed,{attribute:Z||null,from:M});try{Z?x(M,Z):M.removeAttribute(v)}catch{try{M.removeAttribute(v)}catch{}}if(v==="is")if(on||ot)try{xn(M)}catch{}else try{M.setAttribute(v,"")}catch{}},Zc=function(v){const M=O(v);if(M)for(let Z=M.length-1;Z>=0;--Z){const he=M[Z],ye=he&&he.name;typeof ye!="string"||U[nt(ye)]||ii(v,he,ye)}},ml=function(v){const M=[v];for(;M.length>0;){const Z=M.pop();_(Z)===Ot.element&&Zc(Z);const ye=A(Z);if(ye)for(let $e=ye.length-1;$e>=0;--$e)M.push(ye[$e])}},ai=function(v,M){return Pe?v==="patchsrc"?!0:v==="for"&&M!=="label"&&M!=="output":!1},Qc=function(v){if(!Pe)return;const M=[v];for(;M.length>0;){const Z=M.pop(),he=_(Z);if(he===Ot.processingInstruction||he===Ot.comment&&dt(Ua,Z.data)){try{N(Z)}catch{}continue}if(he===Ot.element){const $e=Z,Ke=nt(w(Z));try{$e.hasAttribute&&$e.hasAttribute("patchsrc")&&$e.removeAttribute("patchsrc"),$e.hasAttribute&&$e.hasAttribute("for")&&ai("for",Ke)&&$e.removeAttribute("for")}catch{}}const ye=A(Z);if(ye)for(let $e=ye.length-1;$e>=0;--$e)M.push(ye[$e])}},ui=function(v){let M=null,Z=null;if(rn)v=""+v;else{const $e=Ca(v,/^[\r\n\t ]+/);Z=$e&&$e[0]}_s==="application/xhtml+xml"&&Qn===Ht&&(v=''+v+"");const he=E?le(v):v;if(Qn===Ht)try{M=new c().parseFromString(he,_s)}catch{}if(!M||!M.documentElement){M=oe.createDocument(Qn,"template",null);try{M.documentElement.innerHTML=mr?S:he}catch{}}const ye=M.body||M.documentElement;return v&&Z&&ye.insertBefore(n.createTextNode(Z),ye.childNodes[0]||null),Qn===Ht?G.call(M,qe?"html":"body")[0]:qe?M.documentElement:ye},ci=function(v){const M=k?k(v):v.ownerDocument;return te.call(M||v,v,u.SHOW_ELEMENT|u.SHOW_COMMENT|u.SHOW_TEXT|u.SHOW_PROCESSING_INSTRUCTION|u.SHOW_CDATA_SECTION,null)},gl=function(v){return v=Cs(v,Ee," "),v=Cs(v,H," "),v=Cs(v,ae," "),v},_r=function(v){var M;v.normalize();const Z=k?k(v):v.ownerDocument,he=te.call(Z||v,v,u.SHOW_TEXT|u.SHOW_COMMENT|u.SHOW_CDATA_SECTION|u.SHOW_PROCESSING_INSTRUCTION,null);let ye=he.nextNode();for(;ye;)ye.data=gl(ye.data),ye=he.nextNode();const $e=(M=v.querySelectorAll)===null||M===void 0?void 0:M.call(v,"template");$e&&jn($e,Ke=>{ts(Ke.content)&&_r(Ke.content)})},vl=function(v){const M=D?D(v):null;return typeof M!="string"||nt(M)!=="form"?!1:typeof v.nodeName!="string"||typeof v.textContent!="string"||typeof v.removeChild!="function"||v.attributes!==O(v)||typeof v.removeAttribute!="function"||typeof v.removeAttributeNode!="function"||typeof v.getAttributeNode!="function"||typeof v.setAttribute!="function"||typeof v.namespaceURI!="string"||typeof v.insertBefore!="function"||typeof v.hasChildNodes!="function"||v.nodeType!==C(v)||v.childNodes!==A(v)},ts=function(v){if(!C||typeof v!="object"||v===null)return!1;try{return C(v)===Ot.documentFragment}catch{return!1}},ks=function(v){if(!C||typeof v!="object"||v===null)return!1;try{return typeof C(v)=="number"}catch{return!1}};function Gt(re,v,M){re.length!==0&&jn(re,Z=>{Z.call(t,v,M,es)})}const ed=function(v,M){return!!(Pe&&v.hasChildNodes()&&!ks(v.firstElementChild)&&dt(ja,v.textContent)&&dt(ja,v.innerHTML)||Pe&&v.namespaceURI===Ht&&fw[M]&&(ks(v.firstElementChild)||typeof v.textContent=="string"&&dt(pw[M],v.textContent))||v.nodeType===Ot.processingInstruction||Pe&&v.nodeType===Ot.comment&&dt(Ua,v.data))},yl=function(v,M){if(v instanceof RegExp)return dt(v,M);if(v instanceof Function){for(var Z=arguments.length,he=new Array(Z>2?Z-2:0),ye=2;ye=0;--Ke){const Ze=v===Z?g(ye[Ke],!0):ye[Ke];he.insertBefore(Ze,R(v))}}}return xn(v),!0},di=function(v,M,Z,he){return v.length===0?M:M===Z||M===he?Pt(M):M},fi=function(v,M){return v===M||P(v)!==null?!1:(hr&&ml(v),!0)},pi=function(v,M){if(Gt(ne.beforeSanitizeElements,v,null),fi(v,M))return!0;if(vl(v))return xn(v),!0;const Z=nt(w(v));if(B=di(ne.uponSanitizeElement,B,X,mt),Gt(ne.uponSanitizeElement,v,{tagName:Z,allowedTags:B}),fi(v,M))return!0;if(ed(v,Z))return xn(v),!0;if(ue[Z]||!(ve.tagCheck instanceof Function&&ve.tagCheck(Z))&&!B[Z]){const ye=td(v,Z,M);return ye===!1&&Gt(ne.afterSanitizeElements,v,null),ye}if(_(v)===Ot.element&&!Xc(v)||(Z==="noscript"||Z==="noembed"||Z==="noframes")&&dt(cw,v.innerHTML))return xn(v),!0;if(Oe&&v.nodeType===Ot.text){const ye=gl(v.textContent);v.textContent!==ye&&(Rs(t.removed,{element:v.cloneNode()}),v.textContent=ye)}return Gt(ne.afterSanitizeElements,v,null),!1},hi=function(v,M,Z){if(Q[M]||ai(M,v)||ys&&(M==="id"||M==="name")&&(Z in n||Z in Wc))return!1;const he=U[M]||ve.attributeCheck instanceof Function&&ve.attributeCheck(M,v);return _e&&dt(ce,M)||pe&&dt(be,M)?!0:he?ei[M]||dt(L,Cs(Z,b,""))||(M==="src"||M==="xlink:href"||M==="href")&&v!=="script"&&Oa(Z,"data:")===0&&Zo[v]||we&&!dt(Re,Cs(Z,b,""))?!0:!Z:mi(v)&&yl(ie.tagNameCheck,v)&&yl(ie.attributeNameCheck,M,v)||M==="is"&&ie.allowCustomizedBuiltInElements&&yl(ie.tagNameCheck,Z)},nd=Me({},["annotation-xml","color-profile","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","missing-glyph"]),mi=function(v){return!nd[Fs(v)]&&dt(T,v)},sd=function(v,M,Z,he){if(E&&typeof f=="object"&&typeof f.getAttributeType=="function"&&!Z)switch(f.getAttributeType(v,M)){case"TrustedHTML":return le(he);case"TrustedScriptURL":return F(he)}return he},ld=function(v,M,Z,he){try{return Z?v.setAttributeNS(Z,M,he):v.setAttribute(M,he),vl(v)?(xn(v),!1):!0}catch{return In(M,v),!1}},gi=function(v){Gt(ne.beforeSanitizeAttributes,v,null);const M=v.attributes;if(!M||vl(v))return;U=di(ne.uponSanitizeAttribute,U,fe,gt);const Z={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:U,forceKeepAttr:void 0};let he=M.length;const ye=nt(v.nodeName);for(;he--;){const $e=M[he],Ke=$e.name,Ze=$e.namespaceURI,At=$e.value,Rt=nt(Ke),wr=At;let yt=Ke==="value"?wr:G0(wr),vi=!1;if(Z.attrName=Rt,Z.attrValue=yt,Z.keepAttr=!0,Z.forceKeepAttr=void 0,Gt(ne.uponSanitizeAttribute,v,Z),yt=Z.attrValue,bs&&(Rt==="id"||Rt==="name")&&Oa(yt,Jo)!==0&&(In(Ke,v,$e),yt=Jo+yt,vi=!0),Pe&&dt(/((--!?|])>)|<\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i,yt)){In(Ke,v,$e);continue}if(Rt==="attributename"&&Ca(yt,"href")){In(Ke,v,$e);continue}if(!Z.forceKeepAttr){if(!Z.keepAttr){In(Ke,v,$e);continue}if(!Ce&&dt(dw,yt)){In(Ke,v,$e);continue}if(Oe&&(yt=gl(yt)),!hi(ye,Rt,yt)){In(Ke,v,$e);continue}yt=sd(ye,Rt,Ze,yt),yt!==wr&&ld(v,Ke,Ze,yt)&&vi&&Ra(t.removed)}}Gt(ne.afterSanitizeAttributes,v,null)},bl=function(v){let M=null;const Z=ci(v);for(Gt(ne.beforeSanitizeShadowDOM,v,null);M=Z.nextNode();)if(Gt(ne.uponSanitizeShadowNode,M,null),pi(M,v),gi(M),ts(M.content)&&bl(M.content),_(M)===Ot.element){const he=j(M);ts(he)&&(kr(he),bl(he))}Gt(ne.afterSanitizeShadowDOM,v,null)},kr=function(v){const M=[{node:v,shadow:null}];for(;M.length>0;){const Z=M.pop();if(Z.shadow){bl(Z.shadow);continue}const he=Z.node,$e=_(he)===Ot.element,Ke=A(he);if(Ke)for(let Ze=Ke.length-1;Ze>=0;--Ze)M.push({node:Ke[Ze],shadow:null});if($e){const Ze=D?D(he):null;if(typeof Ze=="string"&&nt(Ze)==="template"){const At=he.content;ts(At)&&M.push({node:At,shadow:null})}}if($e){const Ze=j(he);ts(Ze)&&M.push({node:null,shadow:Ze},{node:Ze,shadow:null})}}};return t.sanitize=function(re){let v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},M=null,Z=null,he=null,ye=null;if(mr=!re,mr&&(re=""),typeof re!="string"&&!ks(re)&&(re=X0(re),typeof re!="string"))throw Dn("dirty is not a string, aborting");if(!t.isSupported)return re;tt?(B=mt,U=gt):br(v),(ne.uponSanitizeElement.length>0||ne.uponSanitizeAttribute.length>0)&&(B=Pt(B)),ne.uponSanitizeAttribute.length>0&&(U=Pt(U)),t.removed=[];const $e=hr&&typeof re!="string"&&ks(re);if($e){Qc(re);const At=w(re);if(typeof At=="string"){const Rt=nt(At);if(!B[Rt]||ue[Rt])throw hl(re),Dn("root node is forbidden and cannot be sanitized in-place")}if(vl(re))throw hl(re),Dn("root node is clobbered and cannot be sanitized in-place");try{kr(re)}catch(Rt){throw hl(re),Rt}}else if(ks(re))M=ui(""),Z=M.ownerDocument.importNode(re,!0),Z.nodeType===Ot.element&&Z.nodeName==="BODY"||Z.nodeName==="HTML"?M=Z:M.appendChild(Z),kr(M);else{if(!on&&!Oe&&!qe&&re.indexOf("<")===-1)return E&&vt?le(re):re;if(M=ui(re),!M)return on?null:vt?S:""}M&&rn&&xn(M.firstChild);const Ke=$e?re:M;try{const At=ci(Ke);for(;he=At.nextNode();)pi(he,Ke),gi(he),ts(he.content)&&bl(he.content)}catch(At){throw $e&&(hl(re),jn(t.removed,Rt=>{Rt.element&&ml(Rt.element)})),At}if($e)return jn(t.removed,At=>{At.element&&ml(At.element)}),Oe&&_r(re),re;if(on){if(Oe&&_r(M),ot)for(ye=ee.call(M.ownerDocument);M.firstChild;)ye.appendChild(M.firstChild);else ye=M;return(U.shadowroot||U.shadowrootmode)&&(ye=Y.call(s,ye,!0)),ye}let Ze=qe?M.outerHTML:M.innerHTML;return qe&&B["!doctype"]&&M.ownerDocument&&M.ownerDocument.doctype&&M.ownerDocument.doctype.name&&dt(aw,M.ownerDocument.doctype.name)&&(Ze=" +`+Ze),Oe&&(Ze=gl(Ze)),E&&vt?le(Ze):Ze},t.setConfig=function(){let re=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};br(re),tt=!0,mt=B,gt=U},t.clearConfig=function(){es=null,tt=!1,mt=null,gt=null,E=I,S=""},t.isValidAttribute=function(re,v,M){es||br({});const Z=nt(re),he=nt(v);return hi(Z,he,M)},t.addHook=function(re,v){typeof v=="function"&&Ct(ne,re)&&Rs(ne[re],v)},t.removeHook=function(re,v){if(Ct(ne,re)){if(v!==void 0){const M=q0(ne[re],v);return M===-1?void 0:H0(ne[re],M,1)[0]}return Ra(ne[re])}},t.removeHooks=function(re){Ct(ne,re)&&(ne[re]=[])},t.removeAllHooks=function(){ne=Va()},t}var gw=Vc();const vw={class:"gb"},yw={class:"gb-top"},bw={key:0,class:"legend"},_w={class:"seg",role:"group","aria-label":"Chart or table"},kw=["aria-pressed"],ww=["aria-pressed"],xw=["width","height","aria-label"],$w={class:"grid"},Sw=["x1","x2","y1","y2"],Tw=["x","y"],Ew=["x","y"],Aw=["x","dy"],Rw=["d"],Cw=["x","y","width","height","aria-label","onPointerenter","onPointermove","onFocus"],Ow=["x1","x2","y1","y2"],Pw={key:0,class:"table-scroll"},Nw={class:"data"},Iw={key:0,class:"muted"},Mw={__name:"GroupedBars",props:{categories:{type:Array,required:!0},series:{type:Array,required:!0},height:{type:Number,default:280},valueName:{type:String,default:"Share of people"},describe:{type:String,default:""}},setup(e){const t=e,{el:n,width:s}=$c(480),l=J("chart"),r={l:46,r:12,t:14,b:52},o=K(()=>s.value-r.l-r.r),a=K(()=>t.height-r.t-r.b),u=K(()=>{const D=Math.max(.05,...t.series.flatMap(k=>k.values));return Math.min(1,Math.ceil(D*10)/10)}),d=K(()=>{const D=u.value>.5?.25:u.value>.2?.1:.05,k=[];for(let _=0;_<=u.value+1e-9;_+=D)k.push(Math.round(_*100)/100);return k}),c=K(()=>Math.max(u.value,d.value[d.value.length-1])),f=D=>r.t+(1-D/c.value)*a.value,p=K(()=>o.value/Math.max(1,t.categories.length)),g=K(()=>Math.min(24,Math.max(4,(p.value*.7-2*(t.series.length-1))/Math.max(1,t.series.length))));function N(D,k){const _=t.series.length*g.value+(t.series.length-1)*2;return r.l+D*p.value+(p.value-_)/2+k*(g.value+2)}function x(D,k){const _=f(0),w=f(k),E=_-w;if(E<=0)return"";const S=g.value,I=Math.min(4,E,S/2);return`M${D},${_}V${w+I}Q${D},${w} ${D+I},${w}H${D+S-I}Q${D+S},${w} ${D+S},${w+I}V${_}Z`}function R(D,k){const _=String(D).split(/\s+/),w=[""];for(const E of _){const S=w[w.length-1];if((S+" "+E).trim().length>k&&S){if(w.length===2){w[1]=(w[1]+" "+E).trim();continue}w.push(E)}else w[w.length-1]=(S+" "+E).trim()}return w.map(E=>E.length>k+4?E.slice(0,k+3)+"…":E)}const A=D=>`${Math.round(D*100)}%`,P=J(null),j=J({x:0,y:0});function O(D,k,_){P.value={ci:k,si:_},j.value={x:D.clientX,y:D.clientY}}const C=K(()=>{if(!P.value)return[];const D=t.series[P.value.si],k=D.counts?` (${D.counts[P.value.ci]} people)`:"";return[{key:D.id,value:A(D.values[P.value.ci])+k,label:D.label,color:nn(D.index),shape:"rect"}]});return(D,k)=>(h(),m("div",vw,[i("div",yw,[e.series.length>1?(h(),m("div",bw,[(h(!0),m(se,null,me(e.series,_=>(h(),m("span",{key:_.id},[i("span",{class:"swatch",style:We({background:de(nn)(_.index)})},null,4),xe(y(_.label),1)]))),128))])):q("",!0),k[4]||(k[4]=i("span",{class:"spacer"},null,-1)),i("div",_w,[i("button",{type:"button","aria-pressed":l.value==="chart",onClick:k[0]||(k[0]=_=>l.value="chart")},"Chart",8,kw),i("button",{type:"button","aria-pressed":l.value==="table",onClick:k[1]||(k[1]=_=>l.value="table")},"Table",8,ww)])]),Se(i("div",{ref_key:"el",ref:n,class:"chart-box"},[(h(),m("svg",{width:de(s),height:e.height,role:"img","aria-label":e.describe||e.valueName},[i("g",$w,[(h(!0),m(se,null,me(d.value,_=>(h(),m("g",{key:_},[i("line",{x1:r.l,x2:de(s)-r.r,y1:f(_),y2:f(_)},null,8,Sw),i("text",{x:r.l-8,y:f(_),dy:"0.32em","text-anchor":"end"},y(A(_)),9,Tw)]))),128)),(h(!0),m(se,null,me(e.categories,(_,w)=>(h(),m("text",{key:w,x:r.l+w*p.value+p.value/2,y:e.height-r.b+18,"text-anchor":"middle"},[(h(!0),m(se,null,me(R(_,Math.max(8,Math.floor(p.value/7))),(E,S)=>(h(),m("tspan",{key:S,x:r.l+w*p.value+p.value/2,dy:S?14:0},y(E),9,Aw))),128))],8,Ew))),128))]),(h(!0),m(se,null,me(e.series,(_,w)=>(h(),m("g",{key:_.id},[(h(!0),m(se,null,me(_.values,(E,S)=>(h(),m("g",{key:S},[i("path",{d:x(N(S,w),E),class:He(["bar",{lifted:P.value&&P.value.ci===S&&P.value.si===w}]),style:We({fill:de(nn)(_.index)})},null,14,Rw),i("rect",{x:N(S,w)-1,y:r.t,width:g.value+2,height:a.value,fill:"transparent",tabindex:"0","aria-label":`${_.label}, ${e.categories[S]}: ${A(E)}`,onPointerenter:I=>O(I,S,w),onPointermove:I=>O(I,S,w),onPointerleave:k[2]||(k[2]=I=>P.value=null),onFocus:I=>{P.value={ci:S,si:w},j.value={x:I.target.getBoundingClientRect().right,y:I.target.getBoundingClientRect().top+40}},onBlur:k[3]||(k[3]=I=>P.value=null)},null,40,Cw)]))),128))]))),128)),i("line",{class:"base",x1:r.l,x2:de(s)-r.r,y1:f(0),y2:f(0)},null,8,Ow)],8,xw))],512),[[Zu,l.value==="chart"]]),l.value==="table"?(h(),m("div",Pw,[i("table",Nw,[i("thead",null,[i("tr",null,[k[5]||(k[5]=i("th",null,null,-1)),(h(!0),m(se,null,me(e.series,_=>(h(),m("th",{key:_.id,class:"num"},y(_.label),1))),128))])]),i("tbody",null,[(h(!0),m(se,null,me(e.categories,(_,w)=>(h(),m("tr",{key:w},[i("td",null,y(_),1),(h(!0),m(se,null,me(e.series,E=>(h(),m("td",{key:E.id,class:"num"},[xe(y(A(E.values[w])),1),E.counts?(h(),m("span",Iw," ("+y(E.counts[w])+")",1)):q("",!0)]))),128))]))),128))])])])):q("",!0),De(Sc,{show:!!P.value&&l.value==="chart",x:j.value.x,y:j.value.y,title:P.value?e.categories[P.value.ci]:"",rows:C.value},null,8,["show","x","y","title","rows"])]))}},Lw=ct(Mw,[["__scopeId","data-v-5f0a10de"]]),Dw={class:"stack-lg"},Fw={key:0,class:"panel empty"},jw={key:0,class:"notice error",role:"alert"},Uw={class:"report-grid"},Vw={class:"panel stack","aria-labelledby":"rep-head"},Bw={class:"panel-head"},zw={key:0},qw=["disabled"],Hw={key:0,class:"notice error",role:"alert"},Gw=["innerHTML"],Ww={key:2,class:"empty"},Kw={key:0,class:"stack-lg data-col"},Yw={class:"panel stack","aria-labelledby":"stance-head"},Jw={class:"muted small"},Xw={class:"panel stack","aria-labelledby":"seg-head"},Zw={class:"row"},Qw=["value"],ex={class:"table-scroll"},tx={class:"data"},nx={class:"th-key"},sx={class:"seg-name"},lx={class:"num"},rx={key:0,class:"muted small"},ox={key:1,class:"panel stack","aria-labelledby":"pts-head"},ix={class:"table-scroll"},ax={class:"data"},ux={class:"pt-text"},cx={class:"break"},dx={class:"muted small"},fx=["title"],px={key:2,class:"panel stack-lg","aria-labelledby":"posts-head"},hx={class:"row"},mx=["value"],gx={class:"grid-side posts-grid"},vx={class:"stack"},yx={key:0,class:"muted"},bx={class:"small"},_x={class:"break content"},kx={class:"small muted tnum"},wx={key:0,class:"comments"},xx={class:"small"},$x={class:"muted"},Sx={class:"small break"},Tx={class:"stack"},Ex={class:"table-scroll"},Ax={class:"data"},Rx={class:"break"},Cx={class:"num"},Ox={class:"num"},Px={key:0},Nx={__name:"StepReport",setup(e){const t=cl(),n=t.pid,s=K(()=>t.selectedRun.value),l=K(()=>!!s.value&&ll.has(s.value.status)),r=J(null),o=J(null),a=J(""),u=J({});async function d(){if(a.value="",r.value=null,o.value=null,!l.value)return;const I=s.value.id;try{const V=await t.loadRun(I,!0);if(s.value?.id!==I)return;r.value=V,V.report_ready&&(o.value=await Ie.report(n.value,I))}catch(V){a.value=V.message}}Je(()=>s.value?.id+":"+s.value?.status,d,{immediate:!0});const c=K(()=>{const I=t.tasks.report;if(!I)return null;const V=u.value[I.id];return V&&V!==s.value?.id||!V&&!["queued","running"].includes(I.status)?null:I}),f=K(()=>!!t.tasks.report&&["queued","running"].includes(t.tasks.report.status)),p=J("");async function g(){p.value="";const I=s.value.id;try{const V=await Ie.startReport(n.value,I);u.value={...u.value,[V.id]:I},(await t.track(V)).status==="done"&&s.value?.id===I&&(o.value=await Ie.report(n.value,I),r.value=await t.loadRun(I,!0))}catch(V){p.value=V.message}}const N=K(()=>o.value?.markdown?gw.sanitize(Be.parse(o.value.markdown,{gfm:!0,breaks:!1}),{USE_PROFILES:{html:!0}}):""),x=K(()=>r.value?.summary||null),R=K(()=>(x.value?.variants||[]).map((I,V)=>({...I,index:V}))),A=K(()=>R.value.length>1),P=K(()=>x.value?{categories:x.value.stance_levels,series:R.value.filter(I=>I.final).map(I=>{const V=I.final.stance_hist||[],z=V.reduce((ge,le)=>ge+le,0)||1;return{id:I.id,label:I.label,index:I.index,values:V.map(ge=>ge/z),counts:V}})}:null),j=K(()=>{const I=new Set;for(const z of R.value)for(const ge of Object.keys(z.segments||{}))I.add(ge);const V=["kind","group"];return[...V.filter(z=>I.has(z)),...[...I].filter(z=>!V.includes(z)).sort()]}),O=J("group");Je(j,I=>{I.length&&!I.includes(O.value)&&(O.value=I[0])},{immediate:!0});const C={kind:"Kind",group:"Group"},D=K(()=>{const I=new Map;for(const z of R.value)for(const ge of z.segments?.[O.value]||[])I.has(ge.value)||I.set(ge.value,{value:ge.value,n:ge.n,by:{}}),I.get(ge.value).by[z.id]=ge.mean_outcome;const V=R.value[0]?.id;return[...I.values()].sort((z,ge)=>(ge.by[V]??0)-(z.by[V]??0))});function k(I){return O.value==="kind"&&{stakeholder:"Stakeholders",public:"Public"}[I]||I}const _=K(()=>{const I=new Map;for(const z of R.value)for(const ge of z.points||[])I.has(ge.id)||I.set(ge.id,{id:ge.id,text:ge.text,side:ge.side,by:{}}),I.get(ge.id).by[z.id]=ge;const V=R.value[0]?.id;return[...I.values()].sort((z,ge)=>(ge.by[V]?.total??0)-(z.by[V]?.total??0))}),w={pro:"For",con:"Against",neutral:"Neutral"},E=J("");Je(R,I=>{I.length&&!I.some(V=>V.id===E.value)&&(E.value=I[0].id)},{immediate:!0});const S=K(()=>R.value.find(I=>I.id===E.value)||null);return(I,V)=>(h(),m("div",Dw,[l.value?(h(),m(se,{key:1},[a.value?(h(),m("div",jw,y(a.value),1)):q("",!0),i("div",Uw,[i("section",Vw,[i("div",Bw,[V[3]||(V[3]=i("h2",{id:"rep-head"},"Report",-1)),o.value?(h(),m("p",zw,"Written "+y(de(ar)(o.value.created_at)),1)):q("",!0),V[4]||(V[4]=i("span",{class:"spacer"},null,-1)),i("button",{class:He(["btn",{primary:!o.value}]),type:"button",disabled:f.value,onClick:g},y(o.value?"Write again":"Generate report"),11,qw)]),p.value?(h(),m("div",Hw,y(p.value),1)):q("",!0),De(cr,{task:c.value,label:f.value?"Writing the report":"","hide-done":""},null,8,["task","label"]),N.value?(h(),m("article",{key:1,class:"prose",innerHTML:N.value},null,8,Gw)):f.value?q("",!0):(h(),m("div",Ww,[...V[5]||(V[5]=[i("h3",null,"No report yet",-1),i("p",null,"The language model writes it from the run's numbers and sample posts. It can only cite those numbers.",-1)])])),V[6]||(V[6]=i("p",{class:"caveat"},"Ranges cover chance only, not model error. The crowd is synthetic.",-1))]),x.value?(h(),m("div",Kw,[i("section",Yw,[V[7]||(V[7]=i("h3",{id:"stance-head"},"How people feel at the final poll",-1)),i("p",Jw,"Share of the crowd at each stance level"+y(A.value?", by variant":"")+".",1),P.value?.series.length?(h(),ln(Lw,{key:0,categories:P.value.categories,series:P.value.series,describe:"Share of people at each stance level at the final poll"},null,8,["categories","series"])):q("",!0)]),i("section",Xw,[i("div",Zw,[V[8]||(V[8]=i("h3",{id:"seg-head"},"Chance of yes by segment",-1)),V[9]||(V[9]=i("span",{class:"spacer"},null,-1)),Se(i("select",{"onUpdate:modelValue":V[0]||(V[0]=z=>O.value=z),class:"auto","aria-label":"Segment by"},[(h(!0),m(se,null,me(j.value,z=>(h(),m("option",{key:z,value:z},y(C[z]||z),9,Qw))),128))],512),[[_n,O.value]])]),i("div",ex,[i("table",tx,[i("thead",null,[i("tr",null,[i("th",null,y(C[O.value]||O.value),1),V[10]||(V[10]=i("th",{class:"num"},"People",-1)),(h(!0),m(se,null,me(R.value,z=>(h(),m("th",{key:z.id,class:"num wrap-th"},[i("span",nx,[A.value?(h(),m("span",{key:0,class:"swatch",style:We({background:de(nn)(z.index)})},null,4)):q("",!0),xe(y(A.value?z.label:"Mean chance of yes"),1)])]))),128))])]),i("tbody",null,[(h(!0),m(se,null,me(D.value,z=>(h(),m("tr",{key:z.value},[i("td",sx,y(k(z.value)),1),i("td",lx,y(z.n),1),(h(!0),m(se,null,me(R.value,ge=>(h(),m("td",{key:ge.id,class:"num"},y(de(Qt)(z.by[ge.id])),1))),128))]))),128))])])]),A.value?(h(),m("p",rx,"Columns are the mean chance of yes under each variant.")):q("",!0)])])):q("",!0)]),x.value?(h(),m("section",ox,[V[14]||(V[14]=i("h3",{id:"pts-head"},"Which talking points spread",-1)),i("div",ix,[i("table",ax,[i("thead",null,[i("tr",null,[V[11]||(V[11]=i("th",null,"Point",-1)),V[12]||(V[12]=i("th",null,"Side",-1)),(h(!0),m(se,null,me(R.value,z=>(h(),m("th",{key:z.id,class:"num wrap-th"},y(A.value?z.label:"Uses"),1))),128))])]),i("tbody",null,[(h(!0),m(se,null,me(_.value,z=>(h(),m("tr",{key:z.id},[i("td",ux,[i("span",cx,y(z.text),1),V[13]||(V[13]=xe()),i("span",dx,y(z.id),1)]),i("td",null,y(w[z.side]||z.side),1),(h(!0),m(se,null,me(R.value,ge=>(h(),m("td",{key:ge.id,class:"num",title:z.by[ge.id]?`${z.by[ge.id].posts} posts, ${z.by[ge.id].comments} comments, ${z.by[ge.id].quotes} quotes`:""},y(z.by[ge.id]?.total??0),9,fx))),128))]))),128))])])]),V[15]||(V[15]=i("p",{class:"muted small"},"Uses count posts, comments and quotes that make the point.",-1))])):q("",!0),S.value?(h(),m("section",px,[i("div",hx,[V[16]||(V[16]=i("h2",{id:"posts-head"},"Top posts and people",-1)),V[17]||(V[17]=i("span",{class:"spacer"},null,-1)),A.value?Se((h(),m("select",{key:0,"onUpdate:modelValue":V[1]||(V[1]=z=>E.value=z),class:"auto","aria-label":"Variant"},[(h(!0),m(se,null,me(R.value,z=>(h(),m("option",{key:z.id,value:z.id},y(z.label),9,mx))),128))],512)),[[_n,E.value]]):q("",!0)]),i("div",gx,[i("div",vx,[V[19]||(V[19]=i("h3",null,"Most engaging posts",-1)),S.value.top_posts.length?q("",!0):(h(),m("p",yx,"No posts in this variant.")),(h(!0),m(se,null,me(S.value.top_posts,z=>(h(),m("article",{key:z.post_id,class:"post"},[i("p",bx,[i("strong",null,y(z.author),1)]),i("p",_x,y(z.content),1),i("p",kx,y(z.likes)+" likes, "+y(z.dislikes)+" dislikes, "+y(z.shares)+" reshares, "+y(z.comments.length)+" comments",1),z.comments.length?(h(),m("ul",wx,[(h(!0),m(se,null,me(z.comments,(ge,le)=>(h(),m("li",{key:le},[i("p",xx,[i("strong",null,y(ge.author),1),V[18]||(V[18]=xe()),i("span",$x,y(ge.likes)+" likes",1)]),i("p",Sx,y(ge.content),1)]))),128))])):q("",!0)]))),128))]),i("div",Tx,[V[22]||(V[22]=i("h3",null,"Most engaged people",-1)),i("div",Ex,[i("table",Ax,[V[21]||(V[21]=i("thead",null,[i("tr",null,[i("th",null,"Person"),i("th",{class:"num"},"Posts"),i("th",{class:"num"},"Engagement")])],-1)),i("tbody",null,[(h(!0),m(se,null,me(S.value.most_engaged,z=>(h(),m("tr",{key:z.agent_id},[i("td",Rx,y(z.name),1),i("td",Cx,y(de(Xe)(z.posts)),1),i("td",Ox,y(de(Xe)(z.engagement)),1)]))),128)),S.value.most_engaged.length?q("",!0):(h(),m("tr",Px,[...V[20]||(V[20]=[i("td",{colspan:"3",class:"muted"},"Nobody engaged.",-1)])]))])])]),V[23]||(V[23]=i("p",{class:"muted small"},"Engagement counts the likes, reshares and comments a person's posts received.",-1))])])])):q("",!0)],64)):(h(),m("div",Fw,[...V[2]||(V[2]=[i("h3",null,"Pick a finished run",-1),i("p",null,"The selected run has not finished. Choose another one in the run menu above.",-1)])]))]))}},Ix=ct(Nx,[["__scopeId","data-v-dd71796f"]]),Mx={class:"stack-lg"},Lx={key:0,class:"panel empty"},Dx={key:0,class:"notice error",role:"alert"},Fx={class:"ask-grid"},jx={class:"panel stack chat-panel","aria-labelledby":"chat-head"},Ux={class:"picker-row"},Vx={class:"field grow"},Bx={key:0,class:"field"},zx=["value"],qx={class:"people",role:"listbox","aria-label":"People"},Hx=["aria-selected","onClick"],Gx={class:"p-name break"},Wx={class:"muted small"},Kx={key:0,class:"muted small pad"},Yx={key:0,class:"convo stack"},Jx={class:"persona"},Xx={class:"break"},Zx={class:"muted small"},Qx={class:"small muted break"},e$={key:0,class:"muted small"},t$={class:"break"},n$={key:1,class:"msg assistant typing"},s$=["disabled"],l$={key:0,class:"notice error",role:"alert"},r$={key:1,class:"muted small"},o$={class:"panel stack","aria-labelledby":"ask-head"},i$={class:"field"},a$={class:"row"},u$={key:0,class:"field"},c$=["value"],d$=["disabled"],f$={key:0,class:"notice error",role:"alert"},p$={key:1,class:"result stack","aria-live":"polite"},h$={class:"r-q break"},m$={class:"muted small"},g$={class:"big"},v$={class:"figure"},y$={class:"facts"},b$={class:"tnum"},_$={class:"tnum"},k$={key:0,class:"stack"},w$={class:"table-scroll"},x$={class:"data"},$$={class:"break"},S$={class:"num"},T$={class:"num"},E$={class:"num"},A$={class:"grid-2 names"},R$={class:"break"},C$={class:"muted tnum"},O$={class:"break"},P$={class:"muted tnum"},N$={class:"muted small tnum"},I$={key:2,class:"stack"},M$={class:"asks"},L$=["onClick"],D$={class:"break"},F$={class:"muted small tnum nowrap"},j$={__name:"StepAsk",setup(e){const t=cl(),n=t.pid,s=K(()=>t.selectedRun.value),l=K(()=>!!s.value&&ll.has(s.value.status)),r=J("");Promise.all([t.loadFrame(),t.loadCrowd()]).catch(F=>r.value=F.message);const o=K(()=>t.crowd.value?.agents||[]),a=K(()=>{const F=Object.fromEntries((t.frame.value?.variants||[]).map(W=>[W.id,W.label]));return(s.value?.variants?.length?s.value.variants:(t.frame.value?.variants||[]).map(W=>W.id)).map((W,oe)=>({id:W,label:F[W]||W,index:oe}))}),u=J(""),d=J(null),c=J(""),f=J([]),p=J(""),g=J(!1),N=J(""),x=J(null);Je(a,F=>{F.length&&!F.some($=>$.id===c.value)&&(c.value=F[0].id)},{immediate:!0});const R=K(()=>{const F=u.value.trim().toLowerCase();return(F?o.value.filter(W=>`${W.name} ${W.username} ${W.segment} ${W.kind}`.toLowerCase().includes(F)):o.value).slice(0,60)}),A=K(()=>o.value.find(F=>F.agent_id===d.value)||null);async function P(){if(N.value="",f.value=[],d.value==null||!l.value)return;const F=`${s.value.id}:${d.value}:${c.value}`;try{const $=await Ie.chatHistory(n.value,s.value.id,d.value,c.value);F===`${s.value?.id}:${d.value}:${c.value}`&&(f.value=$,j())}catch($){N.value=$.message}}Je(()=>[d.value,c.value,s.value?.id],P);async function j(){await er(),x.value&&(x.value.scrollTop=x.value.scrollHeight)}async function O(){const F=p.value.trim();if(!F||d.value==null)return;g.value=!0,N.value="";const $=[...f.value,{role:"user",content:F,at:new Date().toISOString(),pending:!0}];f.value=$,p.value="",j();try{const W=await Ie.chat(n.value,s.value.id,{agent_id:d.value,message:F,variant:c.value});f.value=W.history,j()}catch(W){N.value=W.message,f.value=$.filter(oe=>!oe.pending),p.value=F}finally{g.value=!1}}function C(F){F.key==="Enter"&&!F.shiftKey&&(F.preventDefault(),O())}const D=J(""),k=J(""),_=J(!1),w=J(""),E=J([]),S=J(null);Je(a,F=>{F.length&&!F.some($=>$.id===k.value)&&(k.value=F[0].id)},{immediate:!0});async function I(){if(E.value=[],S.value=null,!!l.value)try{const F=await Ie.asked(n.value,s.value.id);E.value=[...F].reverse(),S.value=E.value[0]||null}catch(F){w.value=F.message}}Je(()=>s.value?.id+":"+l.value,I,{immediate:!0});async function V(){const F=D.value.trim();if(F){_.value=!0,w.value="";try{const $=await Ie.ask(n.value,s.value.id,{question:F,variant:k.value||void 0});E.value=[$,...E.value],S.value=$,D.value=""}catch($){w.value=$.message}finally{_.value=!1}}}const z=K(()=>Object.fromEntries(a.value.map(F=>[F.id,F.index]))),ge=K(()=>Object.fromEntries(a.value.map(F=>[F.id,F.label]))),le=K(()=>{const F=S.value?.segments||{};return[...F.group||F[Object.keys(F)[0]]||[]].sort((W,oe)=>oe.mean_outcome-W.mean_outcome)});return(F,$)=>(h(),m("div",Mx,[l.value?(h(),m(se,{key:1},[r.value?(h(),m("div",Dx,y(r.value),1)):q("",!0),i("div",Fx,[i("section",jx,[$[11]||($[11]=i("div",{class:"panel-head"},[i("h2",{id:"chat-head"},"Talk to one person"),i("p",null,"They answer in character, from their persona and what they saw in the run.")],-1)),i("div",Ux,[i("label",Vx,[$[6]||($[6]=i("span",{class:"label"},"Find a person",-1)),Se(i("input",{"onUpdate:modelValue":$[0]||($[0]=W=>u.value=W),type:"search",placeholder:"Name or group",autocomplete:"off"},null,512),[[Le,u.value]])]),a.value.length>1?(h(),m("label",Bx,[$[7]||($[7]=i("span",{class:"label"},"Variant",-1)),Se(i("select",{"onUpdate:modelValue":$[1]||($[1]=W=>c.value=W)},[(h(!0),m(se,null,me(a.value,W=>(h(),m("option",{key:W.id,value:W.id},y(W.label),9,zx))),128))],512),[[_n,c.value]])])):q("",!0)]),i("ul",qx,[(h(!0),m(se,null,me(R.value,W=>(h(),m("li",{key:W.agent_id},[i("button",{type:"button",role:"option","aria-selected":W.agent_id===d.value,class:He({on:W.agent_id===d.value}),onClick:oe=>d.value=W.agent_id},[i("span",Gx,y(W.name),1),i("span",Wx,y(W.kind==="stakeholder"?"Stakeholder":W.segment),1)],10,Hx)]))),128)),R.value.length?q("",!0):(h(),m("li",Kx,"Nobody matches."))]),A.value?(h(),m("div",Yx,[i("div",Jx,[i("p",null,[i("strong",Xx,y(A.value.name),1),$[8]||($[8]=xe()),i("span",Zx,y(A.value.segment),1)]),i("p",Qx,y(A.value.bio),1)]),i("div",{ref_key:"thread",ref:x,class:"thread","aria-live":"polite"},[f.value.length?q("",!0):(h(),m("p",e$,"No messages yet. Ask what they think and why.")),(h(!0),m(se,null,me(f.value,(W,oe)=>(h(),m("div",{key:oe,class:He(["msg",[W.role,{pending:W.pending}]])},[i("p",t$,y(W.content),1)],2))),128)),g.value?(h(),m("div",n$,[...$[9]||($[9]=[i("p",{class:"muted"},"Writing a reply",-1)])])):q("",!0)],512),i("form",{class:"composer",onSubmit:kn(O,["prevent"])},[$[10]||($[10]=i("label",{class:"sr-only",for:"chat-input"},"Message",-1)),Se(i("textarea",{id:"chat-input","onUpdate:modelValue":$[2]||($[2]=W=>p.value=W),rows:"2",placeholder:"Would you pay more for weekly cleaning?",onKeydown:C},null,544),[[Le,p.value]]),i("button",{class:"btn primary",type:"submit",disabled:g.value||!p.value.trim()},"Send",8,s$)],32),N.value?(h(),m("div",l$,y(N.value),1)):q("",!0)])):(h(),m("p",r$,"Pick someone from the list to start."))]),i("section",o$,[$[25]||($[25]=i("div",{class:"panel-head"},[i("h2",{id:"ask-head"},"Ask the whole crowd"),i("p",null,"Jev polls every person with a new yes or no question. It takes a few seconds.")],-1)),i("form",{class:"stack",onSubmit:kn(V,["prevent"])},[i("label",i$,[$[12]||($[12]=i("span",{class:"label"},"Question",-1)),Se(i("textarea",{"onUpdate:modelValue":$[3]||($[3]=W=>D.value=W),rows:"2",placeholder:"Would you recommend Lazybee to a friend?"},null,512),[[Le,D.value]])]),i("div",a$,[a.value.length>1?(h(),m("label",u$,[$[13]||($[13]=i("span",{class:"label"},"Variant",-1)),Se(i("select",{"onUpdate:modelValue":$[4]||($[4]=W=>k.value=W)},[(h(!0),m(se,null,me(a.value,W=>(h(),m("option",{key:W.id,value:W.id},y(W.label),9,c$))),128))],512),[[_n,k.value]])])):q("",!0),$[14]||($[14]=i("span",{class:"spacer"},null,-1)),i("button",{class:"btn primary ask-btn",type:"submit",disabled:_.value||!D.value.trim()},y(_.value?`Polling ${o.value.length} people`:"Ask the crowd"),9,d$)])],32),w.value?(h(),m("div",f$,y(w.value),1)):q("",!0),S.value?(h(),m("article",p$,[i("p",h$,y(S.value.question),1),i("p",m$,y(ge.value[S.value.variant]||S.value.variant)+", asked "+y(de(ar)(S.value.at)),1),i("p",g$,[i("span",v$,y(de(Cn)(S.value.summary.expected_yes)),1),i("span",null,"of "+y(S.value.summary.n)+" expected to say yes",1)]),i("dl",y$,[i("div",null,[$[15]||($[15]=i("dt",null,"90% range",-1)),i("dd",b$,y(de(Cn)(S.value.summary.low))+" to "+y(de(Cn)(S.value.summary.high)),1)]),i("div",null,[$[16]||($[16]=i("dt",null,"Mean chance of yes",-1)),i("dd",_$,y(de(Qt)(S.value.summary.mean_outcome,1)),1)])]),De(Tc,{n:S.value.summary.n,expected:S.value.summary.expected_yes,low:S.value.summary.low,high:S.value.summary.high,index:z.value[S.value.variant]??0,label:S.value.question},null,8,["n","expected","low","high","index","label"]),$[23]||($[23]=i("p",{class:"caveat"},"Ranges cover chance only, not model error. The crowd is synthetic.",-1)),le.value.length?(h(),m("div",k$,[$[18]||($[18]=i("h3",null,"By group",-1)),i("div",w$,[i("table",x$,[$[17]||($[17]=i("thead",null,[i("tr",null,[i("th",null,"Group"),i("th",{class:"num"},"People"),i("th",{class:"num"},"Chance of yes"),i("th",{class:"num"},"Expected yes")])],-1)),i("tbody",null,[(h(!0),m(se,null,me(le.value,W=>(h(),m("tr",{key:W.value},[i("td",$$,y(W.value),1),i("td",S$,y(W.n),1),i("td",T$,y(de(Qt)(W.mean_outcome)),1),i("td",E$,y(de(Cn)(W.expected_yes)),1)]))),128))])])])])):q("",!0),i("div",A$,[i("div",null,[$[20]||($[20]=i("h3",null,"Most likely yes",-1)),i("ol",null,[(h(!0),m(se,null,me(S.value.most_yes,W=>(h(),m("li",{key:W.name},[i("span",R$,y(W.name),1),$[19]||($[19]=xe()),i("span",C$,y(de(Qt)(W.p)),1)]))),128))])]),i("div",null,[$[22]||($[22]=i("h3",null,"Most likely no",-1)),i("ol",null,[(h(!0),m(se,null,me(S.value.most_no,W=>(h(),m("li",{key:W.name},[i("span",O$,y(W.name),1),$[21]||($[21]=xe()),i("span",P$,y(de(Qt)(W.p)),1)]))),128))])])]),i("p",N$,y(S.value.requests)+" Jev requests, "+y(S.value.cache_hits)+" from cache",1)])):q("",!0),E.value.length?(h(),m("div",I$,[$[24]||($[24]=i("h3",null,"Earlier questions",-1)),i("ul",M$,[(h(!0),m(se,null,me(E.value,(W,oe)=>(h(),m("li",{key:oe},[i("button",{type:"button",class:He({on:W===S.value}),onClick:te=>S.value=W},[i("span",D$,y(W.question),1),i("span",F$,y(de(Cn)(W.summary.expected_yes))+" of "+y(W.summary.n)+", "+y(de(Qt)(W.summary.mean_outcome)),1)],10,L$)]))),128))])])):q("",!0)])])],64)):(h(),m("div",Lx,[...$[5]||($[5]=[i("h3",null,"Pick a finished run",-1),i("p",null,"People remember what happened in a run, so choose a finished one in the run menu above.",-1)])]))]))}},U$=ct(j$,[["__scopeId","data-v-69a3ca99"]]),V$={key:0,class:"panel empty"},B$={key:1,class:"stack-lg setup"},z$={class:"intro"},q$={key:0,class:"notice error",role:"alert"},H$={class:"panel stack","aria-labelledby":"jev-head"},G$={class:"field"},W$=["placeholder"],K$={class:"hint"},Y$={class:"panel stack","aria-labelledby":"llm-head"},J$={class:"panel-head"},X$={class:"seg",role:"group","aria-label":"Model provider"},Z$=["aria-pressed"],Q$=["aria-pressed"],eS={key:0,class:"muted small"},tS={key:1,class:"muted small"},nS={key:2,class:"form-grid wide"},sS={class:"field"},lS={class:"field"},rS={class:"field"},oS={class:"label"},iS=["placeholder"],aS={class:"hint"},uS={key:0,class:"notice error",role:"alert"},cS={class:"row"},dS=["disabled"],fS={key:2,class:"panel stack","aria-labelledby":"test-head"},pS={class:"row"},hS=["disabled"],mS={key:3,class:"panel stack","aria-labelledby":"stop-head"},gS={class:"caveat break"},vS={__name:"SetupView",setup(e){const t=J(null),n=J(""),s=J(""),l=J("gemini"),r=J(""),o=J(""),a=J(""),u=J(""),d=J(""),c=J(null),f=J(!1);async function p(){try{const C=await Ie.settings();t.value=C,l.value=C.llm_provider,o.value=C.llm_base_url,a.value=C.llm_model}catch(C){n.value=C.message}}al(p);const g=K(()=>t.value&&t.value.setup_needed&&!t.value.test_mode),N=K(()=>t.value?l.value==="gemini"?t.value.gemini_key:t.value.llm_key:null),x=K(()=>!sl.value||sl.value.setup_needed?!1:!c.value||c.value.jev.ok&&c.value.llm.ok);function R(C){return C==null?"":C?`A key ending in ${C} is saved. Leave this blank to keep it.`:"A key is saved. Leave this blank to keep it."}function A(){const C={typesafe_key:s.value,llm_provider:l.value,llm_key:r.value};return l.value==="openai"&&Object.assign(C,{llm_base_url:o.value,llm_model:a.value}),C}async function P(){if(d.value="",c.value=null,!s.value.trim()&&!(t.value&&t.value.typesafe_key!==null)){d.value="Paste your Jev key first.";return}u.value="save";try{t.value=await Ie.saveSettings(A()),s.value="",r.value="",await ao(),u.value="check",c.value=await Ie.checkKeys({llm_provider:l.value})}catch(C){d.value=C.message}finally{u.value=""}}async function j(C){d.value="",u.value="test";try{c.value=null,t.value=await Ie.saveSettings({test_mode:C}),await ao()}catch(D){d.value=D.message}finally{u.value=""}}async function O(){const C=t.value?t.value.active_tasks:0,D=C?` ${C} running ${C===1?"job":"jobs"} will stop too.`:"";if(window.confirm(`Stop JevFish on this computer?${D}`))try{await Ie.shutdown(),f.value=!0}catch(k){d.value=k.message}}return(C,D)=>{const k=Nn("RouterLink");return f.value?(h(),m("div",V$,[...D[7]||(D[7]=[i("h3",null,"JevFish has stopped",-1),i("p",null,"You can close this tab. Open JevFish.app to start it again.",-1)])])):(h(),m("div",B$,[i("section",z$,[i("h1",null,y(g.value?"Set up JevFish":"Settings"),1),D[8]||(D[8]=i("p",{class:"muted"}," JevFish needs two keys. Jev decides what each simulated person does, and a language model writes the graph, the crowd and the posts. Keys stay in a file on this computer. ",-1))]),n.value?(h(),m("div",q$,y(n.value),1)):q("",!0),t.value?(h(),m("form",{key:1,class:"stack-lg",onSubmit:kn(P,["prevent"])},[i("section",H$,[D[10]||(D[10]=i("div",{class:"panel-head"},[i("h2",{id:"jev-head"},"Jev"),i("p",null,[xe("Get a key at "),i("a",{href:"https://console.typesafe.ai",target:"_blank",rel:"noopener"},"console.typesafe.ai"),xe(". A typical run costs about US$0.04.")])],-1)),i("label",G$,[D[9]||(D[9]=i("span",{class:"label"},"TypeSafe API key",-1)),Se(i("input",{"onUpdate:modelValue":D[0]||(D[0]=_=>s.value=_),type:"password",autocomplete:"off",spellcheck:"false",placeholder:t.value.typesafe_key!==null?"Saved":"Paste the key"},null,8,W$),[[Le,s.value]]),i("span",K$,y(R(t.value.typesafe_key)),1)]),c.value?(h(),m("div",{key:0,class:He(["notice",c.value.jev.ok?"ok":"error"]),role:"status"},y(c.value.jev.message),3)):q("",!0)]),i("section",Y$,[i("div",J$,[D[11]||(D[11]=i("h2",{id:"llm-head"},"Language model",-1)),D[12]||(D[12]=i("span",{class:"spacer"},null,-1)),i("div",X$,[i("button",{type:"button","aria-pressed":l.value==="gemini",onClick:D[1]||(D[1]=_=>l.value="gemini")},"Gemini",8,Z$),i("button",{type:"button","aria-pressed":l.value==="openai",onClick:D[2]||(D[2]=_=>l.value="openai")},"Other",8,Q$)])]),l.value==="gemini"?(h(),m("p",eS,[...D[13]||(D[13]=[xe(" Free key at ",-1),i("a",{href:"https://aistudio.google.com/apikey",target:"_blank",rel:"noopener"},"aistudio.google.com/apikey",-1),xe(". The free tier is enough for normal runs. ",-1)])])):(h(),m("p",tS,"Any service that speaks the OpenAI API: OpenAI, OpenRouter, Groq, or a local model.")),l.value==="openai"?(h(),m("div",nS,[i("label",sS,[D[14]||(D[14]=i("span",{class:"label"},"Address",-1)),Se(i("input",{"onUpdate:modelValue":D[3]||(D[3]=_=>o.value=_),type:"url",spellcheck:"false",placeholder:"https://api.openai.com/v1"},null,512),[[Le,o.value]])]),i("label",lS,[D[15]||(D[15]=i("span",{class:"label"},"Model",-1)),Se(i("input",{"onUpdate:modelValue":D[4]||(D[4]=_=>a.value=_),type:"text",spellcheck:"false",placeholder:"gpt-4o-mini"},null,512),[[Le,a.value]])])])):q("",!0),i("label",rS,[i("span",oS,y(l.value==="gemini"?"Gemini API key":"API key"),1),Se(i("input",{"onUpdate:modelValue":D[5]||(D[5]=_=>r.value=_),type:"password",autocomplete:"off",spellcheck:"false",placeholder:N.value!==null?"Saved":"Paste the key"},null,8,iS),[[Le,r.value]]),i("span",aS,y(R(N.value)),1)]),c.value?(h(),m("div",{key:3,class:He(["notice",c.value.llm.ok?"ok":"error"]),role:"status"},y(c.value.llm.message),3)):q("",!0)]),d.value?(h(),m("div",uS,y(d.value),1)):q("",!0),i("div",cS,[i("button",{class:"btn primary",type:"submit",disabled:!!u.value},y(u.value==="save"?"Saving":u.value==="check"?"Checking keys":"Save and check"),9,dS),x.value?(h(),ln(k,{key:0,to:"/",class:"btn"},{default:Vt(()=>[...D[16]||(D[16]=[xe("Start a prediction",-1)])]),_:1})):q("",!0)])],32)):q("",!0),t.value?(h(),m("section",fS,[D[17]||(D[17]=i("div",{class:"panel-head"},[i("h2",{id:"test-head"},"Test mode"),i("p",null,"Try every screen without keys. Every number it shows is made up.")],-1)),i("div",pS,[i("span",{class:He(["pill",t.value.test_mode?"warn":""])},y(t.value.test_mode?"On":"Off"),3),i("button",{class:"btn small",type:"button",disabled:!!u.value,onClick:D[6]||(D[6]=_=>j(!t.value.test_mode))},y(t.value.test_mode?"Turn off test mode":"Turn on test mode"),9,hS)])])):q("",!0),t.value?(h(),m("section",mS,[D[18]||(D[18]=i("div",{class:"panel-head"},[i("h2",{id:"stop-head"},"Stop JevFish"),i("p",null,"Shuts JevFish down on this computer. Open JevFish.app to start it again.")],-1)),i("div",{class:"row"},[i("button",{class:"btn small danger",type:"button",onClick:O},"Stop JevFish")]),i("p",gS,"Keys are saved in "+y(t.value.env_file),1)])):q("",!0)]))}}},yS=ct(vS,[["__scopeId","data-v-fc354223"]]),Bc=Nh({history:dh("/"),routes:[{path:"/",name:"projects",component:Tm},{path:"/p/:pid",component:Ym,props:!0,children:[{path:"",redirect:e=>({name:"graph",params:e.params,query:e.query})},{path:"graph",name:"graph",component:by},{path:"crowd",name:"crowd",component:r_},{path:"simulate",name:"simulate",component:Zk},{path:"report",name:"report",component:Ix},{path:"ask",name:"ask",component:U$}]},{path:"/setup",name:"setup",component:yS},{path:"/:rest(.*)*",redirect:"/"}],scrollBehavior:()=>({top:0})});let Ba=!0;Bc.beforeEach(async e=>{if(!Ba)return!0;Ba=!1;const t=await ao();return t&&t.setup_needed&&e.name!=="setup"?{name:"setup"}:!0});Sp(Gh).use(Bc).mount("#app"); diff --git a/jevfish/web/dist/index.html b/jevfish/web/dist/index.html new file mode 100644 index 0000000000..dc011a10b0 --- /dev/null +++ b/jevfish/web/dist/index.html @@ -0,0 +1,18 @@ + + + + + + + JevFish + + + + + + +
    + + diff --git a/jevfish/web/src/App.vue b/jevfish/web/src/App.vue index c74048c4c6..ca3a45e40e 100644 --- a/jevfish/web/src/App.vue +++ b/jevfish/web/src/App.vue @@ -1,9 +1,10 @@ @@ -62,6 +55,7 @@ const warnings = computed(() => { Swarm predictions, one Jev decision per person + Settings
    @@ -69,9 +63,11 @@ const warnings = computed(() => {
    -