diff --git a/.gitignore b/.gitignore index 8f6198c7..a55ba5a3 100644 --- a/.gitignore +++ b/.gitignore @@ -13,6 +13,12 @@ __pycache__/ # never source). data/ +# Workspace UI build outputs: the frontend's source of truth is ui/; built +# assets are copied into the hflow-ui wheel at packaging time, never committed. +ui/node_modules/ +ui/dist/ +packages/hflow-ui/src/hflow_ui/static/ + # Local maintainer tooling (agent skills, settings); not part of the public repo. .claude/ .agents/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 595adf74..e69ff979 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -113,6 +113,26 @@ repository root, and name the observable result. Keep examples on public APIs; tests belong to business logic and boundary behavior, not to checking that a documentation snippet copied a third-party SDK correctly. +## Changing how episodes are processed + +Identities in HFlow are content hashes, and one of them -- `pipeline_version` +-- is stamped inside the canonical bytes that `episode_id` hashes. A release +number deliberately does **not** feed any of them: a CLI fix or a docs bump +must never invalidate somebody's corpus. What does feed them is +`TRANSFORM_BEHAVIOR_VERSION` in [`src/hflow/behavior.py`](./src/hflow/behavior.py). + +**Bump it in the same commit whenever your change makes the transform write +different bytes for the same input** -- encoder settings or defaults, +chunking and grouping, timestamp handling, the provenance record's shape, or +a bugfix to any of those. Bumping re-versions every existing corpus exactly +once, which is the honest cost; not bumping when behavior changed silently +mixes two behaviors under one version, which is worse. When in doubt, bump, +and say so in the pull request. + +Changes to checks, enrichments, or anything a step merely calls do not need a +bump: a step's own content hash already covers its source and captured +configuration. `tests/test_identity_stability.py` pins these rules. + ## Quality checks Run the Python quality gate and fix every reported issue: diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b943634b..d0d84d41 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -44,7 +44,7 @@ that is actually scheduled. ## Design tenets 1. **Evidence, not verdicts.** Quality checks record measurements, intervals, and tags. Pass/fail policy belongs to the consumer at curation time, never hardcoded into the corpus. -2. **Standard formats at every boundary; no new UIs.** Episodes are standard MCAP (Foxglove/Rerun open them), runs are standard Airflow DAGs (Airflow's UI shows them), the catalog and manifests are Parquet (DuckDB/pandas/anything reads them). We ship no UI and hide nothing; the system is extensible without touching our code. +2. **Standard formats at every boundary; no captive UIs.** Episodes are standard MCAP (Foxglove/Rerun open them), runs are standard Airflow DAGs (Airflow's UI shows them), the catalog and manifests are Parquet (DuckDB/pandas/anything reads them). The optional workspace UI (`hflow serve`, shipped separately as `hflow-server`) is a strict client of these same open surfaces through a documented JSON API -- it hides nothing, gates nothing, and everything it shows stays reachable without it. The system is extensible without touching our code. 3. **Your code stays your code.** Transformations, checks, and enrichments are plain Python functions in the user's own environment. Existing processing code plugs in through small adapters rather than being rebuilt inside a framework. 4. **Ship code only where it earns its place.** Either the canonical format forces bridging (video lives in-band; nothing can read it without our accessors) or the code encodes a painfully-rediscoverable pitfall. We ship no client wrappers around things users already know (`openai`, `subprocess.run(["ffmpeg", ...])`); the examples are the documentation. 5. **Coarse-grained steps.** One task processes one episode or one batch and runs for seconds to minutes. Hot loops live inside a task, never across tasks. diff --git a/docs/FORMAT.md b/docs/FORMAT.md index d0ceb044..787f4100 100644 --- a/docs/FORMAT.md +++ b/docs/FORMAT.md @@ -16,7 +16,7 @@ The single overriding rule: **a canonical episode is spec-conforming MCAP.** Eve - MCAP magic, `Header`, data section, `DataEnd`, summary section, `Footer`, closing magic, per the [MCAP spec](https://mcap.dev/spec). - `Header.profile` is the empty string `""` (the file mixes protobuf video channels with pass-through channels of arbitrary encoding, so no single profile applies). -- `Header.library` is informational only (e.g. `hflow/0.2.0 episode-format/1`). No reader may key behavior off it (see [Identifier rules](#identifier-rules)). +- `Header.library` is informational only (e.g. `hflow episode-format/1 transform-behavior/1`). It deliberately carries no release number: the header is inside the bytes the content episode id hashes, so a release would otherwise give a byte-identical input a new identity. No reader may key behavior off it (see [Identifier rules](#identifier-rules)). - Chunks are compressed with **zstd** by default (`"none"` is permitted). Each `Chunk` record carries `uncompressed_crc`; the `Footer` carries a summary CRC. - The summary section repeats all `Schema` and `Channel` records and contains `Statistics`, all `ChunkIndex` records, `AttachmentIndex`/`MetadataIndex` records, and `SummaryOffset` records. A canonical episode always has a complete summary; unindexed files are not canonical. diff --git a/docs/HOSTING.md b/docs/HOSTING.md index 002a0b90..2f9380e8 100644 --- a/docs/HOSTING.md +++ b/docs/HOSTING.md @@ -154,6 +154,13 @@ deployment against facts: store. - **No tenant-facing log or metrics API.** Observability is Airflow's own UI and task logs on the workspace. +- **The workspace UI (`hflow serve`) authenticates nobody.** It is a local + developer tool bound to `127.0.0.1`, deliberately without a login; it is + not a tenant-facing surface, and serving it to anyone but the workspace's + own operator means putting an authenticating proxy in front of it. Signing + people in and scoping them to a workspace is the control plane's job -- + per-user identity and revocable sessions, which no shared launch secret + could stand in for. - **Task processes share the runtime's environment**, including the workspace's storage credentials, and the venv build runs as root at provision time -- isolation between principals must come from your @@ -161,11 +168,18 @@ deployment against facts: - **A workspace's Airflow stack idles at several GB of RAM** across five long-running services (the compose file defines seven; two are one-shot init containers). -- **Engine upgrades re-version steps.** Step versions content-hash captured - globals, including referenced modules with their versions, so a step that - touches `hflow.*` gets a new version on every hflow release: `hflow - stale` will list its episodes, and curation pins keep working because the - corpus is designed to be permanently mixed-version. +- **Engine upgrades re-version a corpus only when processing changed.** An + hflow release no longer moves any identity by itself: `pipeline_version` + folds in `hflow.behavior.TRANSFORM_BEHAVIOR_VERSION` (bumped deliberately, + only when the transform would write different bytes) instead of the release + number, the canonical file's header carries no release number, and step + versions record the modules they reference by name rather than by version. + A byte-identical input therefore keeps its `episode_id` across upgrades, so + content-addressed dedupe holds. The flip side is a real one: an engine + change that alters processing without a behavior bump is invisible to + `hflow stale`, so operators upgrading across a behavior bump should expect + exactly one corpus-wide re-version and plan reprocessing then. The corpus is + designed to be permanently mixed-version, so curation pins keep working. - **ffmpeg licensing**: the pinned build is BtbN's **GPL** variant (it carries the H.264 encoder the canonical transform needs). GPL source obligations attach to **redistribution** -- shipping worker images or diff --git a/docs/README.md b/docs/README.md index fa0ddfe4..9549b876 100644 --- a/docs/README.md +++ b/docs/README.md @@ -44,6 +44,7 @@ the whole workflow before adapting it. Use these when you already know the outcome you need. - [Port existing processing and quality-check code](./PORTING.md) +- [Browse and curate a workspace in the browser](./UI.md) - [Call an OpenAI vision endpoint from a step](./how-to/call-openai-vision.md) - [Run and operate the local Airflow runtime](./RUNTIME.md) - [Deploy into an existing Airflow environment](./RUNTIME.md#bring-your-own-airflow-hflow-deploy) diff --git a/docs/SERVE.md b/docs/SERVE.md new file mode 100644 index 00000000..d1688265 --- /dev/null +++ b/docs/SERVE.md @@ -0,0 +1,139 @@ +# Serve a workspace over HTTP: `hflow serve` + +`hflow serve` is a local read-mostly server over one data root: it answers +questions about episodes and their quality evidence, compiles curation SQL, +pins manifests, monitors and triggers ingest runs, and describes the +registered pipeline. The server never rewrites or deletes an episode -- the +only files it writes are the manifests you pin and its own small state file. +It can trigger an ingest run, though, which the runtime then writes through +the normal pipeline; `--read-only` refuses that along with the other writes. + +**The JSON API is the product surface, not an implementation detail of some +frontend.** Every fact a browser could show is reachable from `/api/v1`, and +the OpenAPI schema at `/api/openapi.json` describes all of it -- so a +workspace UI is a *client*, and you can build or swap one without touching +this package. The server ships no frontend of its own; point +`HFLOW_UI_ASSETS` at a directory containing an `index.html` to serve one, or +install a wheel that packages assets under `hflow_server/static/`. + +It ships as a separate package, `hflow-server`, on purpose: pipeline workers +install the `hflow` wheel into every task venv, and they should never carry a +web server. **It is not published to PyPI yet** -- until the first release, +run it from a clone: + +```bash +git clone https://github.com/Hebbian-Robotics/hflow.git +cd hflow +uv sync --all-extras # installs hflow and hflow-server +uv run hflow serve # browses $HFLOW_DATA_ROOT, else ./data +uv run hflow serve --data-root ./data --no-browser +``` + +Starting the server prints its URL (`http://127.0.0.1:4356/`) and opens your +browser. With no assets installed, that URL serves a page pointing at the +API. There is no login: see [Trust posture](#trust-posture) for what that +means and when it stops being appropriate. + +## What it shows + +- **Episodes** -- the corpus as a faceted, sortable table over the catalog's + wide `episodes` view (task, operator, status, quality measurements as + columns). Every filter you click compiles to DuckDB SQL server-side, and + the exact SQL is always visible and copyable at the bottom of the screen -- + ready to paste into `hflow curate`. +- **Episode** -- one recording's dossier: status and quarantine tags, contact + sheets, every check run with its content-hash version, measurements with + their producing step, intervals, tags, append history, and a canonical-MCAP + download. +- **Curate** -- a SQL studio over the catalog views: schema sidebar with + per-table profiles, editor with run-selection, result preview with + per-column statistics, and the coverage report (which checks ran over how + much of the corpus) before you pin. **Pin manifest** freezes a query's + result as an immutable Parquet manifest under `/manifests/`, + recorded with its SQL, row count, and coverage in the Manifests registry. +- **Runs** -- the ingest runtime's health, recent runs with their trigger + configuration, per-stage activity, and a trigger form (`hflow ingest`'s + wire shape, as a form). It addresses a rendered local bundle or a remote + runtime (`HFLOW_AIRFLOW_URL` and friends); when neither is reachable the + page says which it looked for and why it failed, rather than disappearing. +- **Pipeline** -- the generated DAG plus the registered steps by stage, with + content-hash versions, critical flags, and endpoint aliases, and the + versions actually observed in the catalog. Each stage's steps are drawn + *inside* its `process_batch` node, which is where they run: they have no + dependency edges on each other, so the graph nests them instead of + inventing a chain between them. Requires `--pipeline path/to/pipeline.py[:app]`, + which imports (executes) the pipeline file exactly like `hflow manifest` does. + +## Flags + +| flag | meaning | +|---|---| +| `--data-root` | workspace to browse (default `$HFLOW_DATA_ROOT`, else `./data`) | +| `--host` | bind address (default `127.0.0.1`; widening past loopback exposes your corpus) | +| `--port` | default `4356`, auto-retries upward when taken | +| `--no-browser` | do not open a browser (headless machines, tunnels) | +| `--read-only` | viewer mode: hides and refuses manifest pinning, saved-query edits, and run triggering | +| `--pipeline` | pipeline file for the Pipeline page (imported once at startup) | + +## Nothing is UI-only + +The UI is a strict client of a documented JSON API (`/api/v1/...`; a running +server publishes its OpenAPI schema at `/api/openapi.json`, ready for a client +generator or any local OpenAPI viewer). Curation, the runs monitor and the +pipeline page are thin calls into the same library functions the CLI uses; the +episode listing, facets, stats and timeline endpoints compile their own +presentation-shaped SQL over the same [catalog views](./CATALOG.md) that +`hflow curate` reads. Either way, everything the UI can show or do is +reachable with `curl`, scriptable, and buildable-upon. If you want a different +frontend over your workspace, the API is the contract; the shipped UI is the +reference client. + +## Trust posture + +**The server is unauthenticated.** There is no login, no token, and no +session: anyone who can reach the bound address can read your whole workspace +and trigger ingest runs. What protects it is the address it binds -- +`127.0.0.1` by default, reachable only from your own machine. This is the +posture of every local developer tool that browses a working directory +(`mlflow ui`, TensorBoard, `dagster dev`, the DuckDB UI): a credential in +front of a single-user machine buys nothing but friction. + +Passing `--host` past loopback is therefore a deliberate exposure, and it is +the only flag that changes who can reach the data. If you need the UI from +another machine, forward the port over SSH (`ssh -L 4356:127.0.0.1:4356 +host`) rather than binding a network interface; if you must bind one, put a +reverse proxy that authenticates in front of it and firewall the port itself. +`--read-only` narrows what a reacher can *do* (no pins, no saved-query edits, +no triggering) but not what they can *read* -- it is a safety catch, not +access control. + +Hosted, multi-user HFlow is a different problem and is solved elsewhere: the +control plane authenticates people and scopes them to workspaces +([HOSTING.md](./HOSTING.md)). That needs per-user identity and revocable +sessions, which one shared launch secret could never provide -- which is why +this server does not pretend to have a piece of it. + +The rest of the posture is real and holds regardless. The UI runs fully +local: all assets ship in the wheel (no CDN, no fonts, no outbound requests), +and your data never leaves your machine. That is why the server publishes the +schema JSON and no interactive Swagger page -- FastAPI's built-in one fetches +its JavaScript and CSS from a public CDN, which would break the promise and +run third-party script same-origin with your workspace's API. The browser +never sees filesystem paths of its choosing (media is addressed by episode and +artifact name, and the server refuses anything outside the data root), Airflow +credentials stay server-side behind a proxy, and curation SQL runs on a +[constrained DuckDB connection](./CATALOG.md) that cannot reach the catalog's +files or the network. What this server writes: `/curation/state.json` +(saved queries and the manifest registry) and your pinned manifests -- nothing +else. Episodes, media and catalog rows are written by the ingest runtime, on +runs you trigger from the Runs page. + +## See also + +- [Catalog tables and curation API](./CATALOG.md) -- the views and SQL idioms + the Episodes and Curate screens are built on +- [Runtime guide](./RUNTIME.md) -- the Airflow runtime the Runs screen fronts +- [Hosting HFlow](./HOSTING.md) -- the data-plane contract for operating + workspaces for other people, whose seams (bucket data roots, scoped + credentials, constrained SQL, remote runtime addressing) are the ones this + UI reads through diff --git a/packages/hflow-server/README.md b/packages/hflow-server/README.md new file mode 100644 index 00000000..3fba1b75 --- /dev/null +++ b/packages/hflow-server/README.md @@ -0,0 +1,41 @@ +# hflow-server + +The HFlow workspace UI: a local web app over one HFlow data root — browse +episodes, quality evidence, and the Parquet catalog in a browser. It writes +nothing but your pinned manifests and its own small state file. + +```bash +hflow serve --data-root ./data +``` + +It binds `127.0.0.1` and authenticates nobody, like other local developer +tools that browse a working directory: anyone who can reach the bound address +can read the workspace and trigger runs, so binding past loopback is a +deliberate exposure. `docs/SERVE.md` ("Trust posture") has the details. + +This package is not on PyPI yet. Until the first release, run it from a clone +of the [repository](https://github.com/Hebbian-Robotics/hflow); `docs/SERVE.md` +there has the exact steps, including the frontend build. + +The UI is a strict client of the same surfaces the `hflow` CLI uses (the +DuckDB-queryable catalog, episode files, and manifests): everything it shows +is reachable with `curl` against its documented JSON API, and nothing is +UI-only. It runs fully offline — all assets ship in this wheel, and your data +never leaves your machine. There is deliberately no Swagger page: FastAPI's +built-in one would load its JavaScript and CSS from a CDN. + +Every endpoint publishes a typed response schema, so `/api/openapi.json` — the +schema the running server serves — is a usable contract to generate a client +from rather than a list of paths returning "object". One module — +`hflow_server/_contract.py` — owns those payload shapes; the routes construct its +models instead of hand-building dicts. + +This package is deliberately separate from the `hflow` SDK wheel so that +pipeline worker environments (which install `hflow` into every task venv) +never carry a web server. + +It ships no frontend. A UI is a client of the schema above: point +`HFLOW_UI_ASSETS` at a directory containing an `index.html` to serve one, or +package assets under `hflow_server/static/` in a wheel and they are picked up +automatically. Nothing here is reachable only from a browser, so more than +one UI can exist against the same server without forking it. diff --git a/packages/hflow-server/pyproject.toml b/packages/hflow-server/pyproject.toml new file mode 100644 index 00000000..41545975 --- /dev/null +++ b/packages/hflow-server/pyproject.toml @@ -0,0 +1,32 @@ +[project] +name = "hflow-server" +version = "0.1.0" +description = "Local web UI for HFlow: browse episodes, quality evidence, and the catalog" +readme = "README.md" +license = "Apache-2.0" +authors = [{ name = "Hebbian Robotics" }] +requires-python = ">=3.11" +dependencies = [ + # The floor is a real one, not a formality: this package imports + # hflow.workspace, hflow.import_pipeline_application, + # hflow.runtime.ingest_dag_topology and hflow.app's artifact-key constant + # at module scope, and none of them exist in hflow 0.2.0. Without the + # floor, `pip install hflow-server` beside an older hflow resolves happily and + # then dies with ImportError on `import hflow_server`. [tool.uv.sources] below + # only steers resolution inside this repo -- it is stripped from the built + # wheel's metadata -- and uv ignores this specifier for the workspace + # member, so in-repo development is unaffected by the number. + "hflow>=0.3.0", + "fastapi>=0.115", + "uvicorn>=0.32", +] + +[project.urls] +Repository = "https://github.com/Hebbian-Robotics/hflow" + +[tool.uv.sources] +hflow = { workspace = true } + +[build-system] +requires = ["uv_build>=0.11.33,<0.12"] +build-backend = "uv_build" diff --git a/packages/hflow-server/src/hflow_server/__init__.py b/packages/hflow-server/src/hflow_server/__init__.py new file mode 100644 index 00000000..62bc2994 --- /dev/null +++ b/packages/hflow-server/src/hflow_server/__init__.py @@ -0,0 +1,13 @@ +"""HFlow workspace server: a read-mostly HTTP API over one data root. + +The public surface is deliberately tiny: :class:`ServerSettings` (parsed launch +configuration) and :func:`serve` (runs the server). The CLI's ``hflow serve`` +subcommand is a thin caller of exactly these two names. +""" + +from hflow_server._settings import ServerSettings +from hflow_server.server import create_app, serve + +__version__ = "0.1.0" + +__all__ = ["ServerSettings", "__version__", "create_app", "serve"] diff --git a/packages/hflow-server/src/hflow_server/_catalog.py b/packages/hflow-server/src/hflow_server/_catalog.py new file mode 100644 index 00000000..14e997c3 --- /dev/null +++ b/packages/hflow-server/src/hflow_server/_catalog.py @@ -0,0 +1,904 @@ +"""The query layer: per-request DuckDB connections over one workspace catalog. + +Every request opens (and closes) a FRESH connection: the wide ``episodes`` +view binds one column per measurement key present at open time (see +``hflow.curation``), so a held connection would never show keys recorded +after startup. Opening is cheap -- the views read local Parquet directly. + +Two boundary rules hold everywhere here: + +- Filter VALUES travel as DuckDB bind parameters, never string-interpolated. + The only identifiers ever interpolated are validated against the live + view's DESCRIBE output (``order_by``) or are literal constants (facet + columns), then double-quoted. +- ``recorded_at`` leaves DuckDB as ISO-8601 TEXT: materializing a + TIMESTAMPTZ into Python requires pytz, which hflow deliberately does not + depend on. The connection is pinned to UTC so the rendering is stable + across host timezones. +""" + +import json +import math +from dataclasses import dataclass +from datetime import date, datetime, time +from decimal import Decimal +from typing import Literal, TypeVar +from urllib.parse import quote + +import duckdb +from pydantic import BaseModel + +from hflow.app import ARTIFACT_MEASUREMENT_KEY_PREFIX, MEDIA_CONTACT_SHEET_STEP_NAME +from hflow.curation import open_catalog_connection +from hflow.workspace import Workspace +from hflow_server._contract import ( + CategoricalColumnStats, + ColumnDescriptor, + DossierEpisode, + EpisodeCheckRunRecord, + EpisodeColumnStats, + EpisodeDossierResponse, + EpisodeFacetsResponse, + EpisodeIntervalRecord, + EpisodeMeasurementRecord, + EpisodeMediaArtifact, + EpisodePageResponse, + EpisodeStatsResponse, + EpisodeStatus, + EpisodeTagRecord, + EpisodeTimelineResponse, + NumericColumnStats, + NumericHistogramBucket, + SuccessFilterValue, + TimelineInterval, + TimelineMeasurement, + ValueCount, +) +from hflow_server._media import is_uri_servable + +# The faceted columns, owned by the response model itself so the served keys +# and the columns actually counted can never diverge. +_FACET_COLUMN_NAMES = tuple(EpisodeFacetsResponse.model_fields) +_SEARCHED_COLUMN_NAMES = ("episode_id", "task", "operator") + +# %z renders the locked-UTC offset as "+00" on DuckDB 1.5.5, which JS +# Date.parse rejects and the frontend's offset-stripping regex misses; the +# connection is pinned to UTC, so render the wall time and append the offset +# literally -- matching _curation._timestamp_replace_clause's "+00:00". +_ISO_TIMESTAMP_FORMAT = "%Y-%m-%dT%H:%M:%S.%f" +_ISO_UTC_OFFSET_SUFFIX = "+00:00" + + +class UnknownOrderColumnError(ValueError): + """``order_by`` named a column the live episodes view does not have.""" + + +def open_workspace_connection(data_root: str) -> duckdb.DuckDBPyConnection: + """One fresh connection over ``/catalog`` (see the module note).""" + connection = open_catalog_connection(Workspace.parse(data_root).catalog_root) + connection.execute("SET TimeZone = 'UTC'") + return connection + + +def utc_iso_text(timestamp_expression: str, alias: str) -> str: + """SQL rendering a (UTC-pinned) timestamp expression as ISO-8601 text. + + ``timestamp_expression`` and ``alias`` are code-owned constants, never + user input. + """ + return ( + f"strftime({timestamp_expression}, '{_ISO_TIMESTAMP_FORMAT}') " + f"|| '{_ISO_UTC_OFFSET_SUFFIX}' AS {alias}" + ) + + +def _recorded_at_as_iso_text(qualified_column: str = "recorded_at") -> str: + return utc_iso_text(qualified_column, "recorded_at") + + +def json_safe_value(value: object) -> object: + """One DuckDB cell as a JSON-legal value. + + Datetimes become ISO-8601 strings (a safety net -- timestamp columns are + already rendered to TEXT in SQL) and NaN/inf doubles become null: both + are illegal in JSON and would otherwise poison the whole payload. The + remaining branches exist for the curation studio, where arbitrary user + SELECTs can materialize types JSON cannot carry (DECIMAL literals, + BLOBs, INTERVALs, nested LISTs/STRUCTs): containers are converted + element-wise and anything else is rendered as text -- a legal query must + never 500 over its result types. + """ + if value is None or isinstance(value, bool | int | str): + return value + if isinstance(value, float): + return value if math.isfinite(value) else None + if isinstance(value, datetime | date | time): + return value.isoformat() + if isinstance(value, Decimal): + return json_safe_value(float(value)) + if isinstance(value, list | tuple): + return [json_safe_value(element) for element in value] + if isinstance(value, dict): + return {str(key): json_safe_value(element) for key, element in value.items()} + if isinstance(value, bytes | bytearray): + return value.decode("utf-8", errors="replace") + return str(value) + + +def fetched_json_safe_rows(executed_query: duckdb.DuckDBPyConnection) -> list[dict[str, object]]: + column_names = [str(column[0]) for column in executed_query.description or []] + return [ + {name: json_safe_value(cell) for name, cell in zip(column_names, row, strict=True)} + for row in executed_query.fetchall() + ] + + +_ContractRecord = TypeVar("_ContractRecord", bound=BaseModel) + + +def _validated_records( + record_model: type[_ContractRecord], executed_query: duckdb.DuckDBPyConnection +) -> list[_ContractRecord]: + """A fixed-column query's rows as contract records. + + Rows pass through :func:`json_safe_value` first, so a NaN double is + already null by the time the model sees it. + """ + return [record_model.model_validate(row) for row in fetched_json_safe_rows(executed_query)] + + +@dataclass(frozen=True) +class EpisodeListFilters: + """Parsed /api/v1/episodes filter params -- values only, never SQL. + + ``status`` and ``success`` keep the refined types the HTTP boundary + already parsed them into: this layer never re-checks them, and a caller + cannot hand it a spelling the SQL below would silently match nothing for. + """ + + tasks: tuple[str, ...] = () + operators: tuple[str, ...] = () + embodiments: tuple[str, ...] = () + status: EpisodeStatus | None = None + success: SuccessFilterValue | None = None + search: str | None = None + + +def episode_status_for_quarantine_flag(quarantined: object) -> EpisodeStatus: + """One episode's status derived from its stored ``quarantined`` flag. + + hflow.curation owns the CANONICAL rule as SQL -- the wide ``episodes`` + view's ``CASE WHEN quarantined THEN 'quarantined' ELSE 'ok' END``. The + dossier reads ``episodes_latest``, which carries the raw flag instead of + that derived column, so this is the server's single Python restatement of the + rule; every path that needs a status from a flag calls here. + """ + return "quarantined" if quarantined else "ok" + + +def quoted_identifier(column_name: str) -> str: + return '"' + column_name.replace('"', '""') + '"' + + +def _escaped_like_fragment(raw_value: str) -> str: + """User text made literal inside a LIKE pattern (backslash-escaped).""" + return raw_value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + + +def _quoted_sql_literal(value: str) -> str: + """One string value as a single-quoted SQL literal (internal quotes doubled).""" + return "'" + value.replace("'", "''") + "'" + + +@dataclass(frozen=True) +class _CompiledFilters: + """The WHERE conditions in two parallel forms plus the bind values. + + ``executed_conditions`` carry ``?`` placeholders bound by ``parameters``; + ``display_conditions`` inline the same values as quoted literals. Building + the display form here (rather than by splitting rendered SQL on '?') means + an order_by identifier that itself contains '?' can never be miscounted as + a placeholder. + """ + + executed_conditions: list[str] + display_conditions: list[str] + parameters: list[str] + + def executed_where(self) -> str: + return ( + (" WHERE " + " AND ".join(self.executed_conditions)) if self.executed_conditions else "" + ) + + def display_where(self) -> str: + return ( + (" WHERE " + " AND ".join(self.display_conditions)) if self.display_conditions else "" + ) + + +def _compiled_conditions(filters: EpisodeListFilters) -> _CompiledFilters: + executed_conditions: list[str] = [] + display_conditions: list[str] = [] + parameters: list[str] = [] + exact_match_columns = ( + ("task", filters.tasks), + ("operator", filters.operators), + ("embodiment", filters.embodiments), + ) + for column_name, values in exact_match_columns: + if values: + quoted_column = quoted_identifier(column_name) + placeholders = ", ".join("?" for _ in values) + executed_conditions.append(f"{quoted_column} IN ({placeholders})") + inlined = ", ".join(_quoted_sql_literal(value) for value in values) + display_conditions.append(f"{quoted_column} IN ({inlined})") + parameters.extend(values) + if filters.status is not None: + executed_conditions.append('"status" = ?') + display_conditions.append(f'"status" = {_quoted_sql_literal(filters.status)}') + parameters.append(filters.status) + if filters.success is not None: + # Stored success is a stringified boolean whose casing varies by the + # recording producer; the filter accepts "true"/"false" regardless. + executed_conditions.append('lower("success") = ?') + display_conditions.append(f'lower("success") = {_quoted_sql_literal(filters.success)}') + parameters.append(filters.success) + if filters.search: + like_pattern = "%" + _escaped_like_fragment(filters.search) + "%" + pattern_literal = _quoted_sql_literal(like_pattern) + executed_disjuncts = " OR ".join( + f"{quoted_identifier(name)} ILIKE ? ESCAPE '\\'" for name in _SEARCHED_COLUMN_NAMES + ) + display_disjuncts = " OR ".join( + f"{quoted_identifier(name)} ILIKE {pattern_literal} ESCAPE '\\'" + for name in _SEARCHED_COLUMN_NAMES + ) + executed_conditions.append("(" + executed_disjuncts + ")") + display_conditions.append("(" + display_disjuncts + ")") + parameters.extend([like_pattern] * len(_SEARCHED_COLUMN_NAMES)) + return _CompiledFilters( + executed_conditions=executed_conditions, + display_conditions=display_conditions, + parameters=parameters, + ) + + +def described_episode_columns(connection: duckdb.DuckDBPyConnection) -> list[ColumnDescriptor]: + """The wide view's live columns.""" + return [ + ColumnDescriptor(name=str(row[0]), type=str(row[1])) + for row in connection.execute("DESCRIBE episodes").fetchall() + ] + + +def query_episode_page( + connection: duckdb.DuckDBPyConnection, + filters: EpisodeListFilters, + *, + order_by: str, + descending: bool, + limit: int, + offset: int, +) -> EpisodePageResponse: + """One filtered, ordered page plus the total over the SAME filters.""" + columns = described_episode_columns(connection) + live_column_names = {column.name for column in columns} + if order_by not in live_column_names: + raise UnknownOrderColumnError( + f"unknown order_by column {order_by!r}; order by one of the episodes view's " + "columns (the 'columns' field of this endpoint lists them)" + ) + compiled = _compiled_conditions(filters) + direction = "DESC" if descending else "ASC" + # episode_id is unique in the wide view, so it is a deterministic + # tiebreaker: without it, ordering by any column with duplicate values + # (task, status, ...) leaves ties unstable across DuckDB's per-query + # parallel sort, so successive OFFSET pages could overlap or drop rows. + order_clause = f'ORDER BY {quoted_identifier(order_by)} {direction}, "episode_id" ASC' + executed_tail = ( + f"FROM episodes{compiled.executed_where()} {order_clause} LIMIT {limit} OFFSET {offset}" + ) + display_tail = ( + f"FROM episodes{compiled.display_where()} {order_clause} LIMIT {limit} OFFSET {offset}" + ) + # The executed form renders recorded_at to ISO text in SQL (see the module + # note); the displayed form stays the logical query a user would write. + executed_sql = f"SELECT * REPLACE ({_recorded_at_as_iso_text()}) {executed_tail}" + display_sql = f"SELECT * {display_tail}" + rows = fetched_json_safe_rows(connection.execute(executed_sql, compiled.parameters)) + count_row = connection.execute( + f"SELECT count(*) FROM episodes{compiled.executed_where()}", compiled.parameters + ).fetchone() + total = int(count_row[0]) if count_row is not None else 0 + return EpisodePageResponse(rows=rows, total=total, columns=columns, sql=display_sql) + + +def query_episode_facets(connection: duckdb.DuckDBPyConnection) -> EpisodeFacetsResponse: + """Facet value counts over the wide episodes view; NULL buckets skipped.""" + facets: dict[str, list[ValueCount]] = {} + for facet_column_name in _FACET_COLUMN_NAMES: + quoted_column = quoted_identifier(facet_column_name) + value_counts = connection.execute( + f"SELECT {quoted_column} AS value, count(*) AS value_count FROM episodes " + f"WHERE {quoted_column} IS NOT NULL " + "GROUP BY 1 ORDER BY value_count DESC, value ASC" + ).fetchall() + facets[facet_column_name] = [ + ValueCount(value=str(value), count=int(count)) for value, count in value_counts + ] + return EpisodeFacetsResponse.model_validate(facets) + + +# /api/v1/episodes/stats shape knobs: ~12 histogram buckets per numeric +# column, top 8 values per categorical column (the remainder is other_count), +# and "low-cardinality" capped so id-like columns never masquerade as facets. +HISTOGRAM_BUCKET_COUNT = 12 +TOP_VALUE_LIMIT = 8 +LOW_CARDINALITY_LIMIT = 32 + +_NUMERIC_STAT_TYPES = frozenset( + { + "TINYINT", + "SMALLINT", + "INTEGER", + "BIGINT", + "HUGEINT", + "UTINYINT", + "USMALLINT", + "UINTEGER", + "UBIGINT", + "FLOAT", + "DOUBLE", + } +) +_CATEGORICAL_STAT_TYPES = frozenset({"VARCHAR", "BOOLEAN"}) + +# Which mini-distribution a column earns: the same two words the served +# models discriminate on (_contract.NumericColumnStats.kind / +# CategoricalColumnStats.kind), so the two dispatches below are checked +# against the closed set rather than against a bare string. +_StatKind = Literal["numeric", "categorical"] + + +def _stat_kind(duckdb_type: str) -> _StatKind | None: + """ "numeric"/"categorical" for distributable column types, else ``None`` + (timestamps, JSON blobs, and nested types have no mini-distribution).""" + normalized_type = duckdb_type.upper() + if normalized_type in _NUMERIC_STAT_TYPES or normalized_type.startswith("DECIMAL"): + return "numeric" + if normalized_type in _CATEGORICAL_STAT_TYPES: + return "categorical" + return None + + +@dataclass(frozen=True) +class _NumericColumnPlan: + """One numeric column that earned a histogram, with its bucket geometry.""" + + name: str + minimum: float + maximum: float + + @property + def bucket_width(self) -> float: + return (self.maximum - self.minimum) / HISTOGRAM_BUCKET_COUNT + + +@dataclass(frozen=True) +class _CategoricalColumnPlan: + """One low-cardinality column that earned a top-values breakdown.""" + + name: str + non_null_count: int + + +def query_episode_stats( + connection: duckdb.DuckDBPyConnection, filters: EpisodeListFilters +) -> EpisodeStatsResponse: + """Per-column mini-distributions over the CURRENT filter set. + + Reuses the episode list's filter compilation (one source of truth), so + the sparkbars always describe exactly the rows the table shows. Two + scans total: one aggregate pass classifying every candidate column + (skipping degenerate ones -- all NULL, a single value, NaN/inf-poisoned + numerics, id-like all-unique or over-the-cap categoricals), then one + UNION ALL query computing every surviving column's histogram buckets or + top values against a shared filtered CTE. + """ + compiled = _compiled_conditions(filters) + parameters = compiled.parameters + where_sql = compiled.executed_where() + candidate_columns = [ + (column.name, kind) + for column in described_episode_columns(connection) + if (kind := _stat_kind(column.type)) is not None + ] + if not candidate_columns: + return EpisodeStatsResponse(columns=[]) + + aggregate_expressions: list[str] = [] + for column_name, kind in candidate_columns: + quoted_column = quoted_identifier(column_name) + if kind == "numeric": + aggregate_expressions.extend( + ( + f"count({quoted_column})", + f"min(CAST({quoted_column} AS DOUBLE))", + f"max(CAST({quoted_column} AS DOUBLE))", + ) + ) + else: + aggregate_expressions.extend( + (f"count({quoted_column})", f"count(DISTINCT {quoted_column})") + ) + aggregate_row = connection.execute( + f"SELECT {', '.join(aggregate_expressions)} FROM episodes{where_sql}", parameters + ).fetchone() + if aggregate_row is None: + return EpisodeStatsResponse(columns=[]) + + plans: list[_NumericColumnPlan | _CategoricalColumnPlan] = [] + value_index = 0 + for column_name, kind in candidate_columns: + if kind == "numeric": + non_null_count, minimum, maximum = aggregate_row[value_index : value_index + 3] + value_index += 3 + if int(non_null_count or 0) == 0 or minimum is None or maximum is None: + continue + minimum, maximum = float(minimum), float(maximum) + # NaN/inf values poison min/max (NaN sorts above everything in + # DuckDB), so a non-finite bound marks the whole column degenerate. + # The span (max - min) can itself overflow to inf even when both + # bounds are finite (e.g. -1.7e308 and 1.7e308); an inf bucket + # width would be interpolated as the bare token "inf" into the + # histogram SQL, so require a finite span too. + if ( + not (math.isfinite(minimum) and math.isfinite(maximum)) + or not math.isfinite(maximum - minimum) + or minimum >= maximum + ): + continue + plans.append(_NumericColumnPlan(name=column_name, minimum=minimum, maximum=maximum)) + else: + non_null_count, distinct_count = aggregate_row[value_index : value_index + 2] + value_index += 2 + non_null_count, distinct_count = int(non_null_count or 0), int(distinct_count or 0) + if distinct_count < 2 or distinct_count > LOW_CARDINALITY_LIMIT: + continue + if distinct_count == non_null_count and distinct_count > 2: + # Every value unique: an identifier, not a distribution. + continue + plans.append(_CategoricalColumnPlan(name=column_name, non_null_count=non_null_count)) + if not plans: + return EpisodeStatsResponse(columns=[]) + + union_branches: list[str] = [] + for plan in plans: + quoted_column = quoted_identifier(plan.name) + name_literal = _quoted_sql_literal(plan.name) + if isinstance(plan, _NumericColumnPlan): + # Bounds are data-derived finite floats (never user input), so + # their repr()s are safe SQL literals. + union_branches.append( + f"SELECT {name_literal} AS column_name, " + f"least(CAST(floor((CAST({quoted_column} AS DOUBLE) - {plan.minimum!r}) " + f"/ {plan.bucket_width!r}) AS BIGINT), {HISTOGRAM_BUCKET_COUNT - 1}) " + "AS bucket_index, " + "CAST(NULL AS VARCHAR) AS value, count(*) AS bucket_count " + f"FROM filtered WHERE {quoted_column} IS NOT NULL GROUP BY 2" + ) + else: + union_branches.append( + "SELECT * FROM (" + f"SELECT {name_literal} AS column_name, CAST(NULL AS BIGINT) AS bucket_index, " + f"CAST({quoted_column} AS VARCHAR) AS value, count(*) AS bucket_count " + f"FROM filtered WHERE {quoted_column} IS NOT NULL " + f"GROUP BY 3 ORDER BY bucket_count DESC, value ASC LIMIT {TOP_VALUE_LIMIT})" + ) + # One query for every column: the shared CTE binds the filter parameters + # exactly once and each branch aggregates the same filtered rows. + distribution_rows = connection.execute( + f"WITH filtered AS (SELECT * FROM episodes{where_sql})\n" + + "\nUNION ALL\n".join(union_branches), + parameters, + ).fetchall() + + bucket_counts_by_column: dict[str, dict[int, int]] = {} + value_counts_by_column: dict[str, list[tuple[str, int]]] = {} + for column_name, bucket_index, value, count in distribution_rows: + if bucket_index is not None: + bucket_counts_by_column.setdefault(str(column_name), {})[int(bucket_index)] = int(count) + else: + value_counts_by_column.setdefault(str(column_name), []).append((str(value), int(count))) + + stat_columns: list[EpisodeColumnStats] = [] + for plan in plans: + if isinstance(plan, _NumericColumnPlan): + bucket_counts = bucket_counts_by_column.get(plan.name, {}) + stat_columns.append( + NumericColumnStats( + name=plan.name, + buckets=[ + NumericHistogramBucket( + lo=plan.minimum + index * plan.bucket_width, + hi=( + plan.maximum + if index == HISTOGRAM_BUCKET_COUNT - 1 + else plan.minimum + (index + 1) * plan.bucket_width + ), + count=bucket_counts.get(index, 0), + ) + for index in range(HISTOGRAM_BUCKET_COUNT) + ], + ) + ) + else: + # UNION ALL guarantees no cross-branch order; re-rank here. + top_values = sorted( + value_counts_by_column.get(plan.name, ()), + key=lambda entry: (-entry[1], entry[0]), + ) + stat_columns.append( + CategoricalColumnStats( + name=plan.name, + values=[ValueCount(value=value, count=count) for value, count in top_values], + other_count=plan.non_null_count - sum(count for _value, count in top_values), + ) + ) + return EpisodeStatsResponse(columns=stat_columns) + + +def find_media_uri( + connection: duckdb.DuckDBPyConnection, episode_id: str, artifact_name: str +) -> str | None: + """The cataloged URI behind one (episode, artifact name), if recorded.""" + row = connection.execute( + "SELECT value_text FROM measurements_latest " + "WHERE episode_id = ? AND check_name = ? AND key = ? AND value_text IS NOT NULL", + [ + episode_id, + MEDIA_CONTACT_SHEET_STEP_NAME, + ARTIFACT_MEASUREMENT_KEY_PREFIX + artifact_name, + ], + ).fetchone() + return str(row[0]) if row is not None and row[0] is not None else None + + +def find_canonical_uri(connection: duckdb.DuckDBPyConnection, episode_id: str) -> str | None: + """The latest cataloged canonical-file URI for one episode, if known.""" + row = connection.execute( + "SELECT uri FROM episodes_latest WHERE episode_id = ?", [episode_id] + ).fetchone() + return str(row[0]) if row is not None and row[0] is not None else None + + +def query_latest_run_intervals( + connection: duckdb.DuckDBPyConnection, episode_id: str +) -> list[EpisodeIntervalRecord]: + """One episode's intervals from its LATEST run -- the current evidence. + + ``check_version`` rides in from that run's ``check_runs`` row because the + intervals table does not carry one itself. One owner for this join: the + dossier and the timeline must never disagree about which run's intervals + an episode "has". + """ + return _validated_records( + EpisodeIntervalRecord, + connection.execute( + """ + SELECT i.label, i.start_ns, i.end_ns, i.check_name, r.check_version + FROM intervals AS i + JOIN episodes_latest AS e + ON i.episode_id = e.episode_id AND i.run_fingerprint = e.run_fingerprint + LEFT JOIN check_runs AS r + ON r.episode_id = i.episode_id AND r.run_fingerprint = i.run_fingerprint + AND r.check_name = i.check_name + WHERE i.episode_id = ? + ORDER BY i.start_ns, i.label + """, + [episode_id], + ), + ) + + +def query_episode_dossier( + connection: duckdb.DuckDBPyConnection, episode_id: str, *, data_root: str +) -> EpisodeDossierResponse | None: + """Everything the episode page shows, or ``None`` when the id is unknown.""" + episode_rows = fetched_json_safe_rows( + connection.execute( + f"SELECT * REPLACE ({_recorded_at_as_iso_text()}) " + "FROM episodes_latest WHERE episode_id = ?", + [episode_id], + ) + ) + if not episode_rows: + return None + episode_row = episode_rows[0] + raw_quarantine_tags = episode_row.get("quarantine_tags_json") + quarantine_tags = ( + [str(tag) for tag in json.loads(str(raw_quarantine_tags))] if raw_quarantine_tags else [] + ) + episode = DossierEpisode.model_validate( + { + **episode_row, + "status": episode_status_for_quarantine_flag(episode_row.get("quarantined")), + "quarantine_tags": quarantine_tags, + } + ) + + measurements = _validated_records( + EpisodeMeasurementRecord, + connection.execute( + "SELECT key, value_double, value_text, value_bool, check_name, check_version, " + f"{_recorded_at_as_iso_text()} " + "FROM measurements_latest WHERE episode_id = ? ORDER BY key", + [episode_id], + ), + ) + check_runs = _validated_records( + EpisodeCheckRunRecord, + connection.execute( + "SELECT check_name, check_version, critical, status, duration_s, error, " + f"{_recorded_at_as_iso_text()}, run_fingerprint " + "FROM check_runs WHERE episode_id = ? ORDER BY recorded_at DESC, check_name ASC", + [episode_id], + ), + ) + # Intervals and tags are the episode's LATEST run only -- the current + # evidence. + intervals = query_latest_run_intervals(connection, episode_id) + tags = _validated_records( + EpisodeTagRecord, + connection.execute( + f"SELECT t.tag, t.check_name, {_recorded_at_as_iso_text('t.recorded_at')} " + "FROM tags AS t " + "JOIN episodes_latest AS e " + " ON t.episode_id = e.episode_id AND t.run_fingerprint = e.run_fingerprint " + "WHERE t.episode_id = ? ORDER BY t.tag", + [episode_id], + ), + ) + history = fetched_json_safe_rows( + connection.execute( + f"SELECT * REPLACE ({_recorded_at_as_iso_text()}) " + "FROM episodes_raw WHERE episode_id = ? " + "ORDER BY recorded_at DESC, run_fingerprint DESC", + [episode_id], + ) + ) + + media_rows = connection.execute( + "SELECT key, value_text FROM measurements_latest " + "WHERE episode_id = ? AND check_name = ? AND key LIKE ? AND value_text IS NOT NULL " + "ORDER BY key", + [episode_id, MEDIA_CONTACT_SHEET_STEP_NAME, ARTIFACT_MEASUREMENT_KEY_PREFIX + "%"], + ).fetchall() + quoted_episode_id = quote(episode_id, safe="") + media: list[EpisodeMediaArtifact] = [] + for key, artifact_uri in media_rows: + artifact_name = str(key).removeprefix(ARTIFACT_MEASUREMENT_KEY_PREFIX) + served_url = ( + f"/api/v1/episodes/{quoted_episode_id}/media/{quote(artifact_name, safe='/')}" + if is_uri_servable(str(artifact_uri), data_root=data_root) + else None + ) + media.append( + EpisodeMediaArtifact(name=artifact_name, uri=str(artifact_uri), url=served_url) + ) + + canonical_uri = episode_row.get("uri") + canonical_url = ( + f"/api/v1/episodes/{quoted_episode_id}/canonical" + if isinstance(canonical_uri, str) and is_uri_servable(canonical_uri, data_root=data_root) + else None + ) + return EpisodeDossierResponse( + episode=episode, + measurements=measurements, + check_runs=check_runs, + intervals=intervals, + tags=tags, + history=history, + media=media, + canonical_url=canonical_url, + ) + + +NANOSECONDS_PER_SECOND = 1_000_000_000 + +# Timeline span derivation. Interval times are nanoseconds of LOG time, so an +# episode with intervals carries its own axis; an episode without them can +# still have a length if some check measured one. A measurement key naming a +# duration supplies that length: the token after the key's last '_' picks the +# unit, and a duration key with NO recognized suffix at all +# (``episode_duration``) is read as SECONDS -- the convention every hflow +# example follows. +# +# The two tables below are one fact split in two, and neither may be read +# alone: _UNIT_BY_KEY_SUFFIX owns which suffixes name a dimension at all (and +# what to call it), _NANOSECONDS_PER_DURATION_UNIT owns which of those +# dimensions are TIMES and how long one is. Every key of the second is a key +# of the first. A suffix the first knows and the second does not is a +# NON-time dimension (hz, pct, count, bytes, deg), so a key like +# ``duty_cycle_duration_pct`` measures no length -- reading it as seconds +# would both contradict the "45 %" its own bar is labelled with and stretch +# the episode's axis by 1e9. +_DURATION_KEY_TOKEN = "duration" +_NANOSECONDS_PER_DURATION_UNIT: dict[str, float] = { + "ns": 1.0, + "us": 1e3, + "ms": 1e6, + "s": 1e9, + "sec": 1e9, + "secs": 1e9, + "second": 1e9, + "seconds": 1e9, + "min": 6e10, + "mins": 6e10, + "minute": 6e10, + "minutes": 6e10, +} +_DEFAULT_DURATION_UNIT_NANOSECONDS = 1e9 + +# Units the measurement bars label themselves with, by the same key suffix. +# Absent from this table means "no unit known" -- the bar shows the bare +# number rather than inventing a dimension. +_UNIT_BY_KEY_SUFFIX: dict[str, str] = { + "ns": "ns", + "us": "us", + "ms": "ms", + "s": "s", + "sec": "s", + "secs": "s", + "second": "s", + "seconds": "s", + "min": "min", + "mins": "min", + "minute": "min", + "minutes": "min", + "hz": "Hz", + "pct": "%", + "percent": "%", + "ratio": "ratio", + "count": "count", + "bytes": "bytes", + "mb": "MB", + "gb": "GB", + "m": "m", + "mm": "mm", + "cm": "cm", + "km": "km", + "deg": "deg", + "rad": "rad", + "kg": "kg", + "n": "N", +} + + +def _measurement_key_suffix(key: str) -> str: + """The unit-bearing tail of a measurement key (``max_gap_ms`` -> ``ms``).""" + return key.rsplit("_", 1)[-1].lower() if "_" in key else "" + + +def _duration_nanoseconds(key: str, value: float) -> float | None: + """A duration-naming measurement converted to nanoseconds, if it is one. + + ``None`` for anything that is not a length, INCLUDING a key that says + "duration" but carries a suffix naming another dimension (see the note + above the tables): a measurement the bars label "45 %" must not also + claim the episode ran for 45 seconds. + """ + if _DURATION_KEY_TOKEN not in key.lower() or not math.isfinite(value) or value <= 0: + return None + key_suffix = _measurement_key_suffix(key) + unit_scale = _NANOSECONDS_PER_DURATION_UNIT.get(key_suffix) + if unit_scale is not None: + return value * unit_scale + if key_suffix in _UNIT_BY_KEY_SUFFIX: + return None + return value * _DEFAULT_DURATION_UNIT_NANOSECONDS + + +def _interval_kind(label: str | None, check_name: str | None) -> str: + """The colour group for one interval label. + + Labels are conventionally ``:`` (``gap:/imu``, + ``joint_discontinuity:/joint_states``), so the prefix is the group. A + label with no prefix groups by itself; an empty label falls back to the + check that produced it, which is the only honest grouping left. + """ + text = label.strip() if label is not None else "" + if not text: + return check_name if check_name else "interval" + prefix = text.split(":", 1)[0].strip() + return prefix or text + + +def _relative_seconds(absolute_ns: int | None, span_start_ns: int | None) -> float | None: + if span_start_ns is None or absolute_ns is None: + return None + return (absolute_ns - span_start_ns) / NANOSECONDS_PER_SECOND + + +def query_episode_timeline( + connection: duckdb.DuckDBPyConnection, episode_id: str +) -> EpisodeTimelineResponse | None: + """One episode's time axis, computed server-side (``None`` when unknown). + + The span comes from the latest run's intervals, extended by any duration + measurement that claims a longer episode; an episode with no intervals but + a duration measurement gets a zero-based axis; an episode with neither + gets nulls, and a client says the span is unknown rather than drawing a + fabricated axis. + """ + if ( + connection.execute( + "SELECT 1 FROM episodes_latest WHERE episode_id = ?", [episode_id] + ).fetchone() + is None + ): + return None + + interval_rows = query_latest_run_intervals(connection, episode_id) + measurement_rows = connection.execute( + "SELECT key, value_double FROM measurements_latest " + "WHERE episode_id = ? AND value_double IS NOT NULL ORDER BY key", + [episode_id], + ).fetchall() + numeric_measurements = [ + (str(key), float(value)) + for key, value in measurement_rows + # NaN/inf poison a bar chart exactly as they poison JSON: drop them. + if isinstance(value, int | float) and math.isfinite(float(value)) + ] + + interval_starts = [row.start_ns for row in interval_rows if row.start_ns is not None] + interval_ends = [row.end_ns for row in interval_rows if row.end_ns is not None] + # Several duration-ish measurements: the largest wins, because the span + # must contain every interval AND every claimed duration. + claimed_durations_ns = [ + duration_ns + for key, value in numeric_measurements + if (duration_ns := _duration_nanoseconds(key, value)) is not None + ] + longest_claimed_duration_ns = max(claimed_durations_ns) if claimed_durations_ns else None + + start_ns: int | None = None + end_ns: int | None = None + if interval_starts: + start_ns = min(interval_starts) + end_ns = max([*interval_ends, start_ns]) + if longest_claimed_duration_ns is not None: + end_ns = max(end_ns, start_ns + int(longest_claimed_duration_ns)) + elif longest_claimed_duration_ns is not None: + start_ns, end_ns = 0, int(longest_claimed_duration_ns) + + duration_s = ( + (end_ns - start_ns) / NANOSECONDS_PER_SECOND + if start_ns is not None and end_ns is not None + else None + ) + return EpisodeTimelineResponse( + start_ns=start_ns, + end_ns=end_ns, + duration_s=duration_s, + intervals=[ + TimelineInterval( + label=row.label, + start_ns=row.start_ns, + end_ns=row.end_ns, + start_s=_relative_seconds(row.start_ns, start_ns), + end_s=_relative_seconds(row.end_ns, start_ns), + check_name=row.check_name, + kind=_interval_kind(row.label, row.check_name), + ) + for row in interval_rows + ], + measurements=[ + TimelineMeasurement( + key=key, value=value, unit=_UNIT_BY_KEY_SUFFIX.get(_measurement_key_suffix(key)) + ) + for key, value in numeric_measurements + ], + ) diff --git a/packages/hflow-server/src/hflow_server/_connections.py b/packages/hflow-server/src/hflow_server/_connections.py new file mode 100644 index 00000000..5a83edab --- /dev/null +++ b/packages/hflow-server/src/hflow_server/_connections.py @@ -0,0 +1,90 @@ +"""Opening a catalog connection for one request -- and refusing as one voice. + +Every request that reads the catalog opens a FRESH connection (see +``_catalog``'s module note for why) and must close it again, and every one of +them owes the caller the same answer when the workspace cannot serve it. Both +facts live here so no route restates either: + +- a data root with no catalog is a MISSING RESOURCE (404); +- a catalog present but written in a format version this build cannot read is + a STATE CONFLICT (409) -- the workspace is there, this build just cannot + speak to it. + +The context managers are the only supported way to open a connection inside a +request: they own the ``open -> use -> close`` shape too, so no endpoint +hand-writes another ``try/finally``. +""" + +from collections.abc import Iterator +from contextlib import contextmanager + +import duckdb +from fastapi import HTTPException + +from hflow.curation import open_catalog_connection +from hflow.workspace import Workspace +from hflow_server import _catalog + + +def catalog_unavailable_refusal(error: FileNotFoundError | ValueError) -> HTTPException: + """The HTTP refusal one unusable catalog maps to (see the module note).""" + if isinstance(error, FileNotFoundError): + return HTTPException(status_code=404, detail=str(error)) + return HTTPException(status_code=409, detail=str(error)) + + +@contextmanager +def opened_workspace_connection_or_refuse(data_root: str) -> Iterator[duckdb.DuckDBPyConnection]: + """A live (UTC-pinned) connection for the server's OWN queries.""" + try: + connection = _catalog.open_workspace_connection(data_root) + except (FileNotFoundError, ValueError) as error: + raise catalog_unavailable_refusal(error) from error + try: + yield connection + finally: + connection.close() + + +@contextmanager +def opened_workspace_connection_or_none( + data_root: str, +) -> Iterator[duckdb.DuckDBPyConnection | None]: + """The same connection, but a workspace with NO catalog yields ``None``. + + For the endpoints where "nothing has been recorded yet" is an answer + rather than a 404. A catalog this build cannot read still refuses: that is + a conflict either way. + """ + try: + connection = _catalog.open_workspace_connection(data_root) + except FileNotFoundError: + yield None + return + except ValueError as error: + raise catalog_unavailable_refusal(error) from error + try: + yield connection + finally: + connection.close() + + +@contextmanager +def opened_constrained_connection_or_refuse(data_root: str) -> Iterator[duckdb.DuckDBPyConnection]: + """The connection USER SQL runs on: catalog materialized in memory, file + access and extension loading locked out. + + Its configuration is locked at open, so the ``SET TimeZone`` pin the live + connection uses cannot apply here; timestamp columns are instead rendered + to UTC ISO text in SQL (``_curation._timestamp_replace_clause``). + """ + try: + connection = open_catalog_connection( + Workspace.parse(data_root).catalog_root, constrained=True + ) + except (FileNotFoundError, ValueError) as error: + raise catalog_unavailable_refusal(error) from error + try: + yield connection + finally: + connection.close() diff --git a/packages/hflow-server/src/hflow_server/_contract.py b/packages/hflow-server/src/hflow_server/_contract.py new file mode 100644 index 00000000..9b719acb --- /dev/null +++ b/packages/hflow-server/src/hflow_server/_contract.py @@ -0,0 +1,769 @@ +"""The published JSON contract: one model per payload this API serves. + +The API is the product surface -- the shipped SPA is only its reference +client, and third parties (increasingly coding agents) build against the +schema at ``/api/openapi.json`` (the schema JSON is the whole published docs +surface -- FastAPI's Swagger page is disabled because it loads from a CDN). +So every route declares a model from this module as its response type instead +of hand-building a dict: the model is the ONE owner of that payload's field +names and types, and the generated OpenAPI describes what actually goes over +the wire. + +Four shapes stay deliberately open, each because another module owns it and +a mirror here could only drift: + +- rows of the wide ``episodes`` view and of a user's own SELECT -- their + columns ARE data, described alongside the rows by :class:`ColumnDescriptor`; +- DuckDB ``SUMMARIZE`` rows, whose key set varies by DuckDB version; +- the pipeline manifest, owned and version-stamped by ``hflow.manifest``; +- a dag run's ``conf`` (:class:`RuntimeRunSummary`), which is whatever the + trigger sent -- ``hflow.runtime.AirflowClient.ingest`` owns the shape of + the ones this API mints, but a run started from Airflow's own UI can carry + anything, so no model here could describe it honestly. + +Nullability follows the catalog's DDL (``hflow.catalog.TABLE_COLUMN_DDL``), +which declares no NOT NULL: a field a stored row could carry as NULL is typed +nullable, so odd data is served honestly instead of turning into a 500 from +response validation. + +Two of these models are also the sidecar's ON-DISK shape +(:class:`SavedQueryEntry`, :class:`PinnedManifestEntry`) -- and so is +everything they nest (:class:`CheckCoverageEntry`): ``_sidecar`` stores +exactly what the API serves, so the registry a user can read with ``jq`` and +the payload the API returns can never disagree. Changing any of them +therefore changes the stored format, which ``_sidecar.STATE_VERSION`` guards. +""" + +from typing import Annotated, Any, Literal + +from pydantic import BaseModel, ConfigDict, Field + +from hflow.manifest import StepKind, StepManifest +from hflow.steps import Stage + +# --- shared vocabularies ----------------------------------------------------- + +# Vocabularies the SDK already owns as closed enums (``hflow.steps.Stage``, +# ``hflow.manifest.StepKind``) are annotated with the enum itself rather than +# restated as a Literal: pydantic serializes a StrEnum to its value, so the +# wire bytes are unchanged while the schema publishes the closed set and the +# adapters below stop unwrapping with ``.value``. The aliases here are for +# vocabularies no module owns as a type. +# +# hflow.curation owns the canonical ok/quarantined rule in SQL (the wide +# ``episodes`` view's ``CASE WHEN quarantined THEN 'quarantined' ELSE 'ok' +# END``). This alias is this API's one restatement of that vocabulary: the +# status filter, the facet values, and the dossier's derived status all use +# it, and _catalog.episode_status_for_quarantine_flag is the one place that +# derives a value of it from a raw flag. +EpisodeStatus = Literal["ok", "quarantined"] + +# Stored ``success`` is a stringified boolean whose casing varies by producer, +# so the filter matches case-insensitively on these two spellings. +SuccessFilterValue = Literal["true", "false"] + +ListingOrder = Literal["asc", "desc"] + +RuntimeSource = Literal["bundle", "remote"] + +# How a stage sub-DAG run was attributed to a master run. "heuristic" is the +# only honest answer available: Airflow stores no parent-run link, so the +# attribution is by time window alone (see _graph._matched_stage_run). +StageRunMatch = Literal["heuristic"] + +# Which cheap-first tier a registered step runs in (hflow.App._ordered_checks). +StepTier = Literal[1, 2] + +# What a browsable catalog relation is, as information_schema reports it. +CatalogTableKind = Literal["view", "table"] + + +class ColumnDescriptor(BaseModel): + """One result column as DuckDB's ``DESCRIBE`` reports it.""" + + name: str + type: str + + +class ValueCount(BaseModel): + """One value and how many episodes carry it.""" + + value: str + count: int + + +# --- /api/v1/health, /api/v1/config ------------------------------------------- + + +class HealthResponse(BaseModel): + """The liveness answer: the cheapest endpoint a probe can poll.""" + + ok: bool + + +class WorkspaceCapabilities(BaseModel): + """What this launch can actually do over this data root. + + ``runtime`` means ADDRESSED (a rendered bundle or an exported remote URL), + not reachable -- /runtime/status owns liveness. + """ + + catalog: bool + media: bool + curation: bool = Field( + description="Whether the curation studio's durable state can be written at " + "all: saved queries, the pinned-manifest registry, and the manifest files " + "need a LOCAL data root, so a bucket-backed workspace answers 501 for every " + "one of them and the frontend should not offer them." + ) + runtime: bool + pipeline: bool + + +class WorkspaceConfigResponse(BaseModel): + """What this server is serving, and what the frontend may offer. + + Deliberately carries no Airflow deep-link base: /runtime/status is the one + owner of the runtime's addressing facts, including its web URL. + """ + + mode: Literal["local"] + read_only: bool + hflow_version: str + hflow_server_version: str + data_root: str + workspace_id: str | None + capabilities: WorkspaceCapabilities + run_profiles: list[str] = Field( + description="Live run-profile names from hflow.steps.RUN_PROFILES, " + "served so the frontend never hardcodes them." + ) + ingest_modes: list[str] = Field( + description="Live ingest modes from hflow.steps.IngestMode; same contract as run_profiles." + ) + + +# --- /api/v1/episodes --------------------------------------------------------- + + +class EpisodePageResponse(BaseModel): + """One filtered, ordered page of the wide ``episodes`` view.""" + + rows: list[dict[str, Any]] = Field( + description="Rows of the wide episodes view. Its columns are data (one per " + "measurement key present at open time), so they are described by " + "'columns' rather than enumerated here." + ) + total: int = Field(description="Rows matching the SAME filters, ignoring limit/offset.") + columns: list[ColumnDescriptor] + sql: str = Field( + description="The SELECT compiled for exactly these filters, with values inlined " + "so it is copy-pastable and runs against the same catalog." + ) + + +class EpisodeFacetsResponse(BaseModel): + """Facet value counts over the wide episodes view; NULL buckets skipped. + + This model is the one owner of WHICH columns are faceted: ``_catalog`` + reads the column list off these fields rather than restating it. + """ + + task: list[ValueCount] + operator: list[ValueCount] + embodiment: list[ValueCount] + status: list[ValueCount] + pipeline_version: list[ValueCount] + + +class NumericHistogramBucket(BaseModel): + """One histogram bucket: ``lo`` inclusive, ``hi`` inclusive on the last.""" + + lo: float + hi: float + count: int + + +class NumericColumnStats(BaseModel): + """A numeric column's mini-distribution under the current filters.""" + + name: str + kind: Literal["numeric"] = "numeric" + buckets: list[NumericHistogramBucket] + + +class CategoricalColumnStats(BaseModel): + """A low-cardinality column's top values under the current filters.""" + + name: str + kind: Literal["categorical"] = "categorical" + values: list[ValueCount] + other_count: int = Field(description="Non-null rows beyond the served top values.") + + +EpisodeColumnStats = Annotated[ + NumericColumnStats | CategoricalColumnStats, Field(discriminator="kind") +] + + +class EpisodeStatsResponse(BaseModel): + """Per-column mini-distributions; degenerate columns are omitted entirely.""" + + columns: list[EpisodeColumnStats] + + +class DossierEpisode(BaseModel): + """The episode's own ``episodes_latest`` row plus the two derived fields. + + ``extra="allow"``: every column of that row rides along unchanged, because + the catalog's columns are data this module cannot enumerate. + """ + + model_config = ConfigDict(extra="allow") + + status: EpisodeStatus + quarantine_tags: list[str] = Field( + description="Parsed out of the row's quarantine_tags_json; empty when not quarantined." + ) + + +class EpisodeMeasurementRecord(BaseModel): + """One measurement, latest per key.""" + + key: str | None + value_double: float | None + value_text: str | None + value_bool: bool | None + check_name: str | None + check_version: str | None + recorded_at: str | None + + +class EpisodeCheckRunRecord(BaseModel): + """One recorded check invocation.""" + + check_name: str | None + check_version: str | None + critical: bool | None + status: str | None + duration_s: float | None + error: str | None + recorded_at: str | None + run_fingerprint: str | None + + +class EpisodeIntervalRecord(BaseModel): + """One interval of the episode's LATEST run. + + ``check_version`` rides in from that run's ``check_runs`` row (a LEFT + JOIN -- the intervals table carries no version of its own). + """ + + label: str | None + start_ns: int | None + end_ns: int | None + check_name: str | None + check_version: str | None + + +class EpisodeTagRecord(BaseModel): + """One tag of the episode's LATEST run.""" + + tag: str | None + check_name: str | None + recorded_at: str | None + + +class EpisodeMediaArtifact(BaseModel): + """One cataloged media artifact and, when servable, its byte URL.""" + + name: str + uri: str + url: str | None = Field( + description="Same-origin byte-serving path, or null when the cataloged file " + "is missing or lands outside the workspace data root." + ) + + +class EpisodeDossierResponse(BaseModel): + """Everything the episode page shows for one episode.""" + + episode: DossierEpisode + measurements: list[EpisodeMeasurementRecord] + check_runs: list[EpisodeCheckRunRecord] + intervals: list[EpisodeIntervalRecord] + tags: list[EpisodeTagRecord] + history: list[dict[str, Any]] = Field( + description="Every append of this episode, newest first: raw episodes_raw rows, " + "whose columns are the catalog's (see EpisodePageResponse.rows)." + ) + media: list[EpisodeMediaArtifact] + canonical_url: str | None + + +class TimelineInterval(BaseModel): + """One interval placed on the episode's axis, in absolute ns and in + seconds RELATIVE to the span start (both computed server-side).""" + + label: str | None + start_ns: int | None + end_ns: int | None + start_s: float | None + end_s: float | None + check_name: str | None + kind: str = Field( + description="Colour group: the label's ':' prefix, else the " + "whole label, else the check that produced it." + ) + + +class TimelineMeasurement(BaseModel): + """One numeric measurement, ready to draw as a bar.""" + + key: str + value: float + unit: str | None = Field( + description="Inferred from the key's unit suffix; null when no dimension is known." + ) + + +class EpisodeTimelineResponse(BaseModel): + """One episode's time axis. All-null bounds mean the span is unknown -- + a client must say so rather than draw a fabricated axis.""" + + start_ns: int | None + end_ns: int | None + duration_s: float | None + intervals: list[TimelineInterval] + measurements: list[TimelineMeasurement] + + +# --- /api/v1/curation, /api/v1/queries, /api/v1/manifests --------------------- + + +class CurationPreviewResponse(BaseModel): + """A user SELECT's first rows, its full count, and optional column stats.""" + + columns: list[ColumnDescriptor] + rows: list[dict[str, Any]] = Field( + description="Rows of the user's own SELECT; its columns are described by 'columns'." + ) + row_count: int = Field(description="Rows the SELECT returns in full, independent of limit.") + truncated: bool + column_stats: list[dict[str, Any]] | None = Field( + description="DuckDB SUMMARIZE rows (column_name, column_type, min, max, " + "null_percentage, ...). DuckDB owns that shape and varies it by version, " + "so it is served as-is. Null unless the request asked for stats." + ) + sql: str = Field( + description="The logical wrapped SELECT, copy-pastable as-is. The executed " + "statement adds a '* REPLACE (...)' projection rendering TIMESTAMPTZ columns " + "as UTC ISO text (the locked connection cannot SET TimeZone), which is a " + "rendering detail of these rows rather than part of the query a user wrote." + ) + + +class CheckCoverageEntry(BaseModel): + """One check's coverage denominator over the WHOLE catalog, not the cut. + + Also the sidecar's stored shape, nested inside every stored manifest + entry's ``coverage`` (see the module note). + """ + + check_name: str + episodes_ran: int + total_episodes: int + fraction: float + + +class CurationReportResponse(BaseModel): + """What a cut would contain, and what evidence backs it -- no files written.""" + + row_count: int + total_episodes: int + coverage: list[CheckCoverageEntry] + + +class SavedQueryEntry(BaseModel): + """One saved studio query. + + Also the sidecar's stored shape for a saved query (see the module note). + """ + + model_config = ConfigDict(populate_by_name=True) + + query_id: str = Field(alias="id") + name: str + sql: str + updated_at: str = Field(description="ISO-8601 UTC.") + + +class SavedQueryListResponse(BaseModel): + queries: list[SavedQueryEntry] + + +class PinnedManifestEntry(BaseModel): + """One registry entry for an immutable pinned manifest file. + + Also the sidecar's stored shape for a manifest (see the module note). + """ + + model_config = ConfigDict(populate_by_name=True) + + manifest_id: str = Field(alias="id") + name: str + description: str + sql: str + manifest_path: str = Field( + description="Data-root-relative, e.g. 'manifests/-.parquet'." + ) + row_count: int + total_episodes: int + coverage: list[CheckCoverageEntry] = Field(description="Frozen at pin time.") + created_at: str = Field(description="ISO-8601 UTC.") + + +class PinnedManifestListResponse(BaseModel): + manifests: list[PinnedManifestEntry] + + +class CatalogTableDescription(BaseModel): + """One browsable catalog relation and its live columns.""" + + name: str + kind: CatalogTableKind + columns: list[ColumnDescriptor] + + +class CatalogTablesResponse(BaseModel): + tables: list[CatalogTableDescription] + + +class CatalogTableSummaryResponse(BaseModel): + """One relation's row count and DuckDB's own column profile.""" + + row_count: int + columns: list[dict[str, Any]] = Field( + description="DuckDB SUMMARIZE rows; see CurationPreviewResponse.column_stats." + ) + + +# --- /api/v1/runtime ---------------------------------------------------------- + + +class RuntimeHealthComponents(BaseModel): + """Airflow's per-component health. + + This model is the one owner of WHICH components /runtime/status reports: + ``_runtime`` reads the names off these fields. A component absent from the + deployment (a minimal stack runs no triggerer) reports null. + """ + + metadatabase: str | None + scheduler: str | None + triggerer: str | None + dag_processor: str | None + + +class RuntimeStatusResponse(BaseModel): + """Whether this workspace's ingest runtime is addressed AND answering. + + Every field except ``available`` defaults to "not known", so an + unavailable answer states only the facts it actually has -- there is no + second hand-written shape for the unavailable case to drift from. + """ + + available: bool + detail: str | None = Field( + default=None, description="Why the runtime is unavailable; null when it is available." + ) + source: RuntimeSource | None = None + airflow_web_url: str | None = Field( + default=None, + description="Deep-link base for the Airflow web UI, AS ADDRESSED FROM THE " + "WORKSPACE HOST. Only a local bundle records its own address; a remote " + "endpoint's is unknown, never guessed.", + ) + airflow_web_url_host_only: bool = Field( + default=False, + description="True when airflow_web_url is a loopback address, so it resolves " + "only on the workspace host: a browser on another machine cannot follow it, " + "and the runtime is reachable there only through a tunnel or a wider " + "`hflow up --api-bind-host`.", + ) + dag_id: str | None = None + registered: bool | None = Field( + default=None, + description="Whether the master DAG is registered. Null means unknown (an auth " + "or transient failure), which is not the same as false.", + ) + health: RuntimeHealthComponents | None = None + + +class RuntimeRunSummary(BaseModel): + """One master DAG run, reduced to what the Runs page shows.""" + + dag_run_id: str | None + state: str | None + logical_date: str | None + start_date: str | None + end_date: str | None + conf: dict[str, Any] = Field(description="The trigger's own input, forwarded verbatim.") + + +class StageRunSummary(BaseModel): + """One stage sub-DAG run in a stage's recent strip.""" + + dag_run_id: str | None + state: str | None + start_date: str | None + end_date: str | None + + +class StageRecentRuns(BaseModel): + """One stage's most recent runs. NOT correlated with any master run.""" + + stage: Stage + dag_id: str + recent: list[StageRunSummary] + + +class RuntimeRunsResponse(BaseModel): + runs: list[RuntimeRunSummary] + stages: list[StageRecentRuns] | None = Field( + description="Per-stage recent runs; null for a remote runtime, whose stage " + "sub-DAG ids only a bundle manifest records." + ) + + +class IngestTriggerResponse(BaseModel): + """What Airflow answered when the run was triggered.""" + + dag_run_id: str | None + state: str | None + + +# --- /api/v1/pipeline --------------------------------------------------------- + + +class PipelineStepManifest(BaseModel): + """One registered step, exactly as ``hflow.manifest.StepManifest`` renders it.""" + + name: str + kind: StepKind + version: str = Field(description="Content hash of the live function.") + critical: bool + requires: list[str] + uses: str | None + + @classmethod + def from_step_manifest(cls, step: StepManifest) -> "PipelineStepManifest": + return cls( + name=step.name, + kind=step.kind, + version=step.version, + critical=step.critical, + requires=list(step.requires), + uses=step.uses, + ) + + +class ObservedCheckVersion(BaseModel): + """What the catalog has SEEN of one (check, version) pair.""" + + check_name: str | None + check_version: str | None + first_seen: str | None + last_seen: str | None + run_count: int + + +class StaleSummary(BaseModel): + """How many recorded episodes are stale against the App's current versions.""" + + pipeline_version: str + count: int + + +class PipelineResponse(BaseModel): + """The startup-imported App, described over this workspace's catalog.""" + + manifest: dict[str, Any] = Field( + description="The pipeline manifest exactly as hflow.manifest.PipelineManifest " + "renders it. hflow.manifest owns that shape and stamps it with " + "'manifest_version', so it is forwarded rather than mirrored here." + ) + observed: list[ObservedCheckVersion] + stale: StaleSummary | None = Field( + description="Null when staleness is unknowable (no catalog yet)." + ) + + +# --- /api/v1/pipeline/graph, /api/v1/runtime/runs/{id}/graph ------------------- + + +class DagTaskNodePayload(BaseModel): + """One task of a generated DAG (mirrors ``hflow.runtime.DagTaskNode``).""" + + task_id: str + summary: str + mapped: bool = Field(description="Dynamically mapped: one instance per planned batch.") + deferred: bool = Field(description="Defers instead of holding a worker slot.") + + +class DagTopologyPayload(BaseModel): + """One DAG's real shape: its tasks and their real dependency edges.""" + + dag_id: str + tasks: list[DagTaskNodePayload] + edges: list[tuple[str, str]] = Field( + description="[upstream, downstream] task-id pairs, in declaration order." + ) + + +class PipelineEngineStep(BaseModel): + """Engine work inside one stage that no manifest lists.""" + + name: str + summary: str + + +class PipelineUserStep(PipelineStepManifest): + """A registered step as the graph endpoint serves it. + + ``tier`` mirrors ``hflow.App._ordered_checks``: tier 2 is exactly the steps + declaring ``requires`` or ``uses``. Steps within a tier have NO ordering. + """ + + tier: StepTier + + @classmethod + def from_step_manifest_in_tier(cls, step: StepManifest, tier: StepTier) -> "PipelineUserStep": + return cls(**PipelineStepManifest.from_step_manifest(step).model_dump(), tier=tier) + + +class QuarantineGate(BaseModel): + """The one real cross-step edge, served as its own object rather than as + an edge in either graph.""" + + from_stage: Stage + to_stages: list[Stage] + critical_step_names: list[str] + explanation: str + + +class PipelineGraphStage(BaseModel): + """One stage lane of the pipeline graph: its DAG plus what runs inside it.""" + + stage: Stage + title: str + description: str + gate_task_id: str + trigger_task_id: str + enabling_profiles: list[str] + dag: DagTopologyPayload + engine_steps: list[PipelineEngineStep] + user_steps: list[PipelineUserStep] + + +class PipelineGraphResponse(BaseModel): + """The ingest DAG's shape merged with the pipeline's own steps.""" + + dag_ids_known: bool = Field( + description="False when no runtime is addressed: the dag ids are display-only." + ) + steps_known: bool = Field( + description="False without --pipeline: what runs inside process_batch is unknown." + ) + master: DagTopologyPayload + stages: list[PipelineGraphStage] + quarantine_gate: QuarantineGate | None = Field( + description="Null exactly when steps_known is false." + ) + + +class RunTaskInstance(BaseModel): + """One Airflow task instance, reduced to what the graph draws.""" + + task_id: str | None + state: str | None + start_date: str | None + end_date: str | None + queued_at: str | None = Field( + description="When the scheduler queued the task, so a replay can tell " + "'waiting for a worker' from 'running'. Airflow may omit it." + ) + try_number: int | None + map_index: int = Field(description="-1 means the task is not mapped.") + duration_s: float | None + + +class MappedFanOutSummary(BaseModel): + """The fan-out's live split, counted server-side over EVERY mapped instance. + + Complete on its own: ``by_state`` partitions all ``total`` instances of + ``task_id`` (an instance Airflow has not scheduled yet counts under + ``no_status``), so ``total == sum(by_state.values())`` always holds and a + client never has to recount the raw instances to size or colour the + fan-out. Only a replay at some earlier instant is a different fact, and + that one the server cannot answer. + """ + + task_id: str + total: int = Field( + description="Instances reported for the mapped task. Before the fan-out expands " + "Airflow reports one unexpanded instance, which is counted -- that is the " + "truth at that moment." + ) + by_state: dict[str, int] + + +class RunGraphMaster(BaseModel): + """The master run's own live state.""" + + dag_run_id: str + state: str | None + tasks: list[RunTaskInstance] + + +class RunGraphStage(BaseModel): + """One stage's live state for this master run, or explicit nulls when the + stage never ran for it.""" + + stage: Stage + dag_id: str + dag_run_id: str | None + state: str | None + match: StageRunMatch | None = Field( + description="How this stage run was attributed to the master run. Airflow " + "stores no parent-run link, so the only honest answer is 'heuristic' -- the " + "earliest stage run started inside this master run's own window -- or null " + "(nothing matched). Two master runs OVERLAPPING in time can still be " + "attributed the same stage run." + ) + tasks: list[RunTaskInstance] + mapped_summary: MappedFanOutSummary | None + + +class RunGraphResponse(BaseModel): + """One master run's live state over the ingest topology.""" + + master: RunGraphMaster + stages: list[RunGraphStage] + + +# --- byte-serving routes ------------------------------------------------------ + +# The three routes that answer with FILE BYTES rather than JSON. Declared so +# the schema says "binary" instead of the empty schema FastAPI publishes for a +# bare Response return type; the routes pair this with +# ``response_class=FileResponse``, which is what drops the phantom +# application/json entry beside it. +BINARY_FILE_RESPONSES: dict[int | str, dict[str, Any]] = { + 200: { + "description": "The file's bytes. An allowlisted inert media type (image, audio, " + "video) is served inline under its own content type; anything else -- and every " + "download -- is opaque application/octet-stream.", + "content": {"application/octet-stream": {"schema": {"type": "string", "format": "binary"}}}, + } +} diff --git a/packages/hflow-server/src/hflow_server/_curation.py b/packages/hflow-server/src/hflow_server/_curation.py new file mode 100644 index 00000000..5f049c5f --- /dev/null +++ b/packages/hflow-server/src/hflow_server/_curation.py @@ -0,0 +1,557 @@ +"""The curation studio API: preview/report/pin, manifests, queries, tables. + +User-supplied SQL only ever runs on a CONSTRAINED connection +(``hflow.open_catalog_connection(..., constrained=True)`` / +``hflow.curate(..., constrained=True)``): the catalog is materialized in +memory at open, file access and extension loading are locked out, so the SQL +can read the data but can never touch the catalog's files -- hosted parity, +and defense in depth even locally. The server wraps that SQL as a subquery +(``SELECT ... FROM ()``) for LIMITing, counting, and SUMMARIZE, so a +smuggled second statement is a parser error, and every DuckDB parser/binder +error travels back as a 400 whose detail is DuckDB's own message -- the +useful part -- never a 500. + +Workspace convention: pinned manifests are immutable files at +``/manifests/-.parquet`` -- never the +engine's default ``/manifest.parquet``, which the CLI's curate +silently overwrites. A pin refuses loudly rather than overwrite anything. +The registry describing them lives in the sidecar (see ``_sidecar``). +""" + +import re +import threading +import uuid +from datetime import UTC, datetime +from pathlib import Path + +import duckdb +from fastapi import APIRouter, HTTPException +from fastapi.responses import FileResponse, Response +from pydantic import BaseModel, Field + +from hflow.curation import CurationReport, curate +from hflow.workspace import Workspace +from hflow_server import _catalog, _connections, _media, _sidecar +from hflow_server._contract import ( + BINARY_FILE_RESPONSES, + CatalogTableDescription, + CatalogTableKind, + CatalogTablesResponse, + CatalogTableSummaryResponse, + CheckCoverageEntry, + ColumnDescriptor, + CurationPreviewResponse, + CurationReportResponse, + PinnedManifestEntry, + PinnedManifestListResponse, + SavedQueryEntry, + SavedQueryListResponse, +) +from hflow_server._settings import ServerSettings, refuse_when_read_only + +MANIFESTS_DIRECTORY_NAME = "manifests" + +# BROWSING ORDER only, never membership: which relations exist is +# hflow.open_catalog_connection's fact, read live off information_schema (see +# _browsable_relations), so a view the SDK adds or renames shows up here +# instead of 404ing from the summary route or 500ing on a DESCRIBE. A +# relation missing from this tuple simply sorts after the familiar ones. +CATALOG_TABLE_BROWSING_ORDER = ( + "episodes", + "episodes_latest", + "episodes_raw", + "check_runs", + "measurements", + "measurements_latest", + "tags", + "intervals", +) + +_TIMESTAMPTZ_TYPE = "TIMESTAMP WITH TIME ZONE" + +# What a read-only launch refuses on this router; the sentence around it (and +# the 403) belongs to _settings.refuse_when_read_only. +_STUDIO_WRITE_ACTIONS = "pinning manifests and editing saved queries are" + +# Upper bounds on everything that can be persisted into the sidecar (which is +# fully re-read and re-serialized on every list request): a name, a +# description, one SQL body, and the number of stored entries. Generous for +# real use, but they make the one file this server writes outside manifests/ +# bounded instead of unbounded. +_MAX_NAME_LENGTH = 200 +_MAX_DESCRIPTION_LENGTH = 2000 +_MAX_SQL_LENGTH = 100_000 +_MAX_SAVED_QUERIES = 1000 +_MAX_PINNED_MANIFESTS = 1000 + + +class PreviewRequest(BaseModel): + sql: str = Field(max_length=_MAX_SQL_LENGTH) + limit: int = Field(default=100, ge=1, le=1000) + stats: bool = False + + +class ReportRequest(BaseModel): + sql: str = Field(max_length=_MAX_SQL_LENGTH) + + +class PinRequest(BaseModel): + sql: str = Field(max_length=_MAX_SQL_LENGTH) + name: str = Field(min_length=1, max_length=_MAX_NAME_LENGTH) + description: str = Field(default="", max_length=_MAX_DESCRIPTION_LENGTH) + + +class SavedQueryCreateRequest(BaseModel): + name: str = Field(min_length=1, max_length=_MAX_NAME_LENGTH) + sql: str = Field(max_length=_MAX_SQL_LENGTH) + + +class SavedQueryUpdateRequest(BaseModel): + name: str | None = Field(default=None, max_length=_MAX_NAME_LENGTH) + sql: str | None = Field(default=None, max_length=_MAX_SQL_LENGTH) + + +# Fallback filename slug when a name has no ASCII alphanumerics (a name in a +# non-Latin script, or symbols only). The full Unicode name is still stored on +# the registry entry; only the on-disk filename uses the slug, and the +# timestamp suffix keeps every filename unique regardless. +_FALLBACK_MANIFEST_SLUG = "manifest" + + +def slugified_manifest_name(raw_name: str) -> str: + """The user-given name as a filename slug: lowercase, [a-z0-9-], dashes + collapsed. Names with no ASCII alphanumerics (e.g. ``数据集``, ``!!!``) + slug to the fallback rather than being refused.""" + slug = re.sub(r"[^a-z0-9]+", "-", raw_name.lower()).strip("-") + return slug or _FALLBACK_MANIFEST_SLUG + + +def _utc_now_iso() -> str: + return datetime.now(UTC).isoformat() + + +def _manifest_timestamp() -> str: + # Microsecond precision: pins of the same name in the same second still + # get distinct files (pins never overwrite; collisions are refused). + return datetime.now(UTC).strftime("%Y%m%dT%H%M%S%fZ") + + +def _stripped_sql_or_refuse(raw_sql: str) -> str: + """The user SQL with trailing semicolons dropped (they break subquerying).""" + stripped_sql = raw_sql.strip().rstrip(";").strip() + if not stripped_sql: + raise HTTPException(status_code=400, detail="sql must be a non-empty SELECT") + return stripped_sql + + +def _bad_sql_refusal(error: duckdb.Error) -> HTTPException: + # DuckDB's parser/binder message IS the useful diagnostic; bad SQL is the + # caller's mistake, never a server fault (so 400, never 500). + return HTTPException(status_code=400, detail=str(error)) + + +def _reject_non_single_select(user_sql: str) -> None: + """Refuse anything that is not exactly one SELECT statement. + + ``execute()`` with no bind parameters runs EVERY statement in the string + and returns only the LAST result, so a smuggled second statement + (``SELECT ...); CREATE TABLE ...; SELECT ... FROM (SELECT ...``) would run + silently -- preview 500s on the resulting shape and report answers over + the wrong statement. ``extract_statements`` parses the text WITHOUT + executing it; require exactly one statement whose type is SELECT. + """ + parser_connection = duckdb.connect() + try: + statements = parser_connection.extract_statements(user_sql) + except duckdb.Error as error: + raise _bad_sql_refusal(error) from error + finally: + parser_connection.close() + if len(statements) != 1 or statements[0].type != duckdb.StatementType.SELECT: + raise HTTPException( + status_code=400, detail="sql must be exactly one read-only SELECT statement" + ) + + +def _sidecar_refusal(error: _sidecar.SidecarError) -> HTTPException: + return HTTPException(status_code=error.status_code, detail=error.detail) + + +def _browsable_relations( + connection: duckdb.DuckDBPyConnection, +) -> dict[str, CatalogTableKind]: + """Every relation this catalog connection registered, in browsing order. + + ``hflow.open_catalog_connection`` owns WHICH relations exist; + ``information_schema`` is that fact as the live connection reports it, so + this endpoint and the summary route below both derive membership from the + connection they already hold rather than from a second list here. + """ + kind_rows = connection.execute( + "SELECT table_name, table_type FROM information_schema.tables" + ).fetchall() + kind_by_name: dict[str, CatalogTableKind] = { + str(table_name): ("view" if str(table_type).upper() == "VIEW" else "table") + for table_name, table_type in kind_rows + } + unfamiliar_position = len(CATALOG_TABLE_BROWSING_ORDER) + return { + name: kind_by_name[name] + for name in sorted( + kind_by_name, + key=lambda name: ( + CATALOG_TABLE_BROWSING_ORDER.index(name) + if name in CATALOG_TABLE_BROWSING_ORDER + else unfamiliar_position, + name, + ), + ) + } + + +def _described_columns( + connection: duckdb.DuckDBPyConnection, user_sql: str +) -> list[ColumnDescriptor]: + described_rows = connection.execute(f"DESCRIBE SELECT * FROM ({user_sql})").fetchall() + return [ColumnDescriptor(name=str(row[0]), type=str(row[1])) for row in described_rows] + + +def _timestamp_replace_clause(columns: list[ColumnDescriptor]) -> str: + """A ``* REPLACE (...)`` clause rendering TIMESTAMPTZ results as ISO UTC text. + + Materializing a TIMESTAMPTZ into Python requires pytz (deliberately not a + dependency), and the locked connection cannot ``SET TimeZone`` -- so the + rendering converts to UTC in SQL (``AT TIME ZONE 'UTC'`` yields the naive + UTC wall time) and appends the offset literally. A TIMESTAMPTZ nested + inside a LIST/STRUCT is rendered whole via CAST to text. + """ + replacements: list[str] = [] + for column in columns: + quoted_name = _catalog.quoted_identifier(column.name) + if column.type == _TIMESTAMPTZ_TYPE: + replacements.append( + f"strftime({quoted_name} AT TIME ZONE 'UTC', '%Y-%m-%dT%H:%M:%S.%f') " + f"|| '+00:00' AS {quoted_name}" + ) + elif _TIMESTAMPTZ_TYPE in column.type: + replacements.append(f"CAST({quoted_name} AS VARCHAR) AS {quoted_name}") + return f"REPLACE ({', '.join(replacements)})" if replacements else "" + + +def run_preview( + connection: duckdb.DuckDBPyConnection, user_sql: str, *, limit: int, include_stats: bool +) -> CurationPreviewResponse: + """Preview rows, the full count, and (optionally) SUMMARIZE column stats.""" + columns = _described_columns(connection, user_sql) + replace_clause = _timestamp_replace_clause(columns) + select_head = f"SELECT * {replace_clause}" if replace_clause else "SELECT *" + rows = _catalog.fetched_json_safe_rows( + connection.execute(f"{select_head} FROM ({user_sql}) LIMIT ?", [limit]) + ) + count_row = connection.execute(f"SELECT count(*) FROM ({user_sql})").fetchone() + row_count = int(count_row[0]) if count_row is not None else 0 + # SUMMARIZE over the SAME timestamp-replaced projection the rows use: the + # constrained connection cannot SET TimeZone (locked at open), so a bare + # SUMMARIZE would stringify TIMESTAMPTZ min/max/quartiles in the host's + # timezone -- inconsistent with (and a different calendar day from) the + # UTC ISO text the preview rows already carry. + column_stats = ( + _catalog.fetched_json_safe_rows( + connection.execute(f"SUMMARIZE {select_head} FROM ({user_sql})") + ) + if include_stats + else None + ) + return CurationPreviewResponse( + columns=columns, + rows=rows, + row_count=row_count, + truncated=row_count > len(rows), + column_stats=column_stats, + # The LOGICAL wrapper, deliberately without select_head's REPLACE: the + # timestamp rendering is how these rows are transported, not part of + # the query a user wrote, so what is served stays copy-pastable -- the + # same split (and the same wording) _catalog's episode listing makes. + sql=f"SELECT * FROM ({user_sql}) LIMIT {limit}", + ) + + +def _curated_or_refused(data_root: str, user_sql: str, *, output: Path | None) -> CurationReport: + try: + return curate( + Workspace.parse(data_root).catalog_root, user_sql, output=output, constrained=True + ) + except (FileNotFoundError, ValueError) as error: + raise _connections.catalog_unavailable_refusal(error) from error + except duckdb.Error as error: + raise _bad_sql_refusal(error) from error + + +def _coverage_entries(report: CurationReport) -> list[CheckCoverageEntry]: + """One curation report's coverage as the served (and pinned) entries.""" + return [ + CheckCoverageEntry( + check_name=entry.check_name, + episodes_ran=entry.episodes_ran, + total_episodes=entry.total_episodes, + fraction=entry.fraction, + ) + for entry in report.coverage + ] + + +def create_curation_router(settings: ServerSettings) -> APIRouter: + """Every curation-studio route, closed over one launch's settings.""" + router = APIRouter(prefix="/api/v1") + # FastAPI runs these sync endpoints on a threadpool, so two overlapping + # writes (double-submit, two tabs) would both read the same base sidecar + # and the later store would silently drop the earlier's entry. One + # process-wide lock serializes the whole load->modify->store of every + # mutating route -- sufficient for the single-server design. + sidecar_write_lock = threading.Lock() + + def loaded_sidecar_state() -> _sidecar.SidecarState: + try: + return _sidecar.load_sidecar_state(settings.data_root) + except _sidecar.SidecarError as error: + raise _sidecar_refusal(error) from error + + def stored_sidecar_state(state: _sidecar.SidecarState) -> None: + try: + _sidecar.store_sidecar_state(settings.data_root, state) + except _sidecar.SidecarError as error: + raise _sidecar_refusal(error) from error + + def local_data_root_or_refuse() -> Path: + try: + return _sidecar.local_data_root(settings.data_root) + except _sidecar.SidecarError as error: + raise _sidecar_refusal(error) from error + + @router.post("/curation/preview") + def run_curation_preview(request: PreviewRequest) -> CurationPreviewResponse: + user_sql = _stripped_sql_or_refuse(request.sql) + _reject_non_single_select(user_sql) + with _connections.opened_constrained_connection_or_refuse(settings.data_root) as connection: + try: + return run_preview( + connection, user_sql, limit=request.limit, include_stats=request.stats + ) + except duckdb.Error as error: + raise _bad_sql_refusal(error) from error + + @router.post("/curation/report") + def run_curation_report(request: ReportRequest) -> CurationReportResponse: + user_sql = _stripped_sql_or_refuse(request.sql) + _reject_non_single_select(user_sql) + report = _curated_or_refused(settings.data_root, user_sql, output=None) + return CurationReportResponse( + row_count=report.row_count, + total_episodes=report.total_episodes, + coverage=_coverage_entries(report), + ) + + @router.post("/curation/pin") + def pin_manifest(request: PinRequest) -> PinnedManifestEntry: + refuse_when_read_only(settings, disabled_actions=_STUDIO_WRITE_ACTIONS) + user_sql = _stripped_sql_or_refuse(request.sql) + _reject_non_single_select(user_sql) + manifest_slug = slugified_manifest_name(request.name) + with sidecar_write_lock: + # Load (and thereby validate) the sidecar BEFORE writing the + # manifest, so a corrupt registry never strands an unregistered + # manifest file. The whole load->curate->store runs under the lock + # so a concurrent write cannot drop this pin's acknowledged entry. + state = loaded_sidecar_state() + if len(state.manifests) >= _MAX_PINNED_MANIFESTS: + raise HTTPException( + status_code=409, + detail=f"this workspace already has {_MAX_PINNED_MANIFESTS} pinned " + "manifests (the registry cap); remove some before pinning more", + ) + manifests_directory = local_data_root_or_refuse() / MANIFESTS_DIRECTORY_NAME + manifest_file = manifests_directory / ( + f"{manifest_slug}-{_manifest_timestamp()}.parquet" + ) + if manifest_file.exists(): + raise HTTPException( + status_code=409, + detail=f"manifest file {manifest_file.name} already exists; " + "pinned manifests are immutable and never overwritten -- retry the pin", + ) + report = _curated_or_refused(settings.data_root, user_sql, output=manifest_file) + entry = PinnedManifestEntry( + manifest_id=uuid.uuid4().hex, + name=request.name, + description=request.description, + sql=user_sql, + manifest_path=f"{MANIFESTS_DIRECTORY_NAME}/{manifest_file.name}", + row_count=report.row_count, + total_episodes=report.total_episodes, + coverage=_coverage_entries(report), + created_at=_utc_now_iso(), + ) + stored_sidecar_state( + _sidecar.SidecarState( + saved_queries=state.saved_queries, manifests=(*state.manifests, entry) + ) + ) + return entry + + @router.get("/manifests") + def list_manifests() -> PinnedManifestListResponse: + state = loaded_sidecar_state() + newest_first = sorted(state.manifests, key=lambda entry: entry.created_at, reverse=True) + return PinnedManifestListResponse(manifests=newest_first) + + @router.get( + "/manifests/{manifest_id}/download", + response_class=FileResponse, + responses=BINARY_FILE_RESPONSES, + ) + def download_manifest(manifest_id: str) -> FileResponse: + state = loaded_sidecar_state() + entry = next( + (manifest for manifest in state.manifests if manifest.manifest_id == manifest_id), + None, + ) + if entry is None: + raise HTTPException( + status_code=404, detail=f"no pinned manifest with id {manifest_id!r}" + ) + manifest_file = local_data_root_or_refuse() / entry.manifest_path + try: + # The same strict-resolve + containment check media serving uses: + # even a hand-edited registry path can only serve workspace files. + resolved_file = _media.resolve_served_file( + str(manifest_file), data_root=settings.data_root + ) + except _media.MediaResolutionError as error: + raise _media.media_refusal(error) from error + return _media.served_file_response( + resolved_file, attachment_filename=Path(entry.manifest_path).name + ) + + @router.get("/queries") + def list_saved_queries() -> SavedQueryListResponse: + state = loaded_sidecar_state() + return SavedQueryListResponse(queries=list(state.saved_queries)) + + @router.post("/queries") + def create_saved_query(request: SavedQueryCreateRequest) -> SavedQueryEntry: + refuse_when_read_only(settings, disabled_actions=_STUDIO_WRITE_ACTIONS) + query_name = request.name.strip() + if not query_name: + raise HTTPException(status_code=400, detail="name must be non-empty") + entry = SavedQueryEntry( + query_id=uuid.uuid4().hex, + name=query_name, + sql=_stripped_sql_or_refuse(request.sql), + updated_at=_utc_now_iso(), + ) + with sidecar_write_lock: + state = loaded_sidecar_state() + if len(state.saved_queries) >= _MAX_SAVED_QUERIES: + raise HTTPException( + status_code=409, + detail=f"this workspace already has {_MAX_SAVED_QUERIES} saved queries " + "(the sidecar cap); remove some before saving more", + ) + stored_sidecar_state( + _sidecar.SidecarState( + saved_queries=(*state.saved_queries, entry), manifests=state.manifests + ) + ) + return entry + + @router.put("/queries/{query_id}") + def update_saved_query(query_id: str, request: SavedQueryUpdateRequest) -> SavedQueryEntry: + refuse_when_read_only(settings, disabled_actions=_STUDIO_WRITE_ACTIONS) + with sidecar_write_lock: + state = loaded_sidecar_state() + existing = next( + (entry for entry in state.saved_queries if entry.query_id == query_id), None + ) + if existing is None: + raise HTTPException(status_code=404, detail=f"no saved query with id {query_id!r}") + updated_name = existing.name + if request.name is not None: + updated_name = request.name.strip() + if not updated_name: + raise HTTPException(status_code=400, detail="name must be non-empty") + updated_sql = ( + _stripped_sql_or_refuse(request.sql) if request.sql is not None else existing.sql + ) + updated_entry = SavedQueryEntry( + query_id=query_id, name=updated_name, sql=updated_sql, updated_at=_utc_now_iso() + ) + stored_sidecar_state( + _sidecar.SidecarState( + saved_queries=tuple( + updated_entry if entry.query_id == query_id else entry + for entry in state.saved_queries + ), + manifests=state.manifests, + ) + ) + return updated_entry + + @router.delete("/queries/{query_id}", status_code=204) + def delete_saved_query(query_id: str) -> Response: + refuse_when_read_only(settings, disabled_actions=_STUDIO_WRITE_ACTIONS) + with sidecar_write_lock: + state = loaded_sidecar_state() + if all(entry.query_id != query_id for entry in state.saved_queries): + raise HTTPException(status_code=404, detail=f"no saved query with id {query_id!r}") + stored_sidecar_state( + _sidecar.SidecarState( + saved_queries=tuple( + entry for entry in state.saved_queries if entry.query_id != query_id + ), + manifests=state.manifests, + ) + ) + return Response(status_code=204) + + @router.get("/catalog/tables") + def list_catalog_tables() -> CatalogTablesResponse: + with _connections.opened_workspace_connection_or_refuse(settings.data_root) as connection: + return CatalogTablesResponse( + tables=[ + CatalogTableDescription( + name=table_name, + kind=kind, + columns=[ + ColumnDescriptor(name=str(row[0]), type=str(row[1])) + for row in connection.execute( + f"DESCRIBE {_catalog.quoted_identifier(table_name)}" + ).fetchall() + ], + ) + for table_name, kind in _browsable_relations(connection).items() + ] + ) + + @router.get("/catalog/tables/{table_name}/summary") + def read_catalog_table_summary(table_name: str) -> CatalogTableSummaryResponse: + with _connections.opened_workspace_connection_or_refuse(settings.data_root) as connection: + # Identifier-validated against the relations this connection + # actually registered: anything else -- including SQL-shaped names + # -- is simply an unknown table, and nothing unvalidated ever + # reaches the interpolations below. + browsable = _browsable_relations(connection) + if table_name not in browsable: + raise HTTPException( + status_code=404, + detail=f"unknown catalog table {table_name!r}; one of: {', '.join(browsable)}", + ) + quoted_table = _catalog.quoted_identifier(table_name) + count_row = connection.execute(f"SELECT count(*) FROM {quoted_table}").fetchone() + return CatalogTableSummaryResponse( + row_count=int(count_row[0]) if count_row is not None else 0, + columns=_catalog.fetched_json_safe_rows( + connection.execute(f"SUMMARIZE SELECT * FROM {quoted_table}") + ), + ) + + return router diff --git a/packages/hflow-server/src/hflow_server/_graph.py b/packages/hflow-server/src/hflow_server/_graph.py new file mode 100644 index 00000000..abf52cb7 --- /dev/null +++ b/packages/hflow-server/src/hflow_server/_graph.py @@ -0,0 +1,564 @@ +"""The visualization API: the ingest DAG's shape, and one run's live state. + +Two nested layers meet on these endpoints, and neither may be drawn as the +other: + +- **Orchestration** -- a real DAG with real edges, served straight from + :func:`hflow.runtime.ingest_dag_topology` (the library's description of the + DAGs ``hflow up`` renders, pinned to the templates by the core suite). The + master resolves the run profile, then walks the stage chain gating and + triggering each sub-DAG; every sub-DAG plans batches, fans ``process_batch`` + out over them, and closes on a budget gate. +- **User steps** -- the registered checks and enrichments of a ``--pipeline`` + App, which have NO dependency edges on each other. They all run INSIDE one + ``process_batch`` task of the stage that owns their kind, ordered only by + the engine's two-tier cheap-first policy (:meth:`hflow.App._ordered_checks`: + a step declaring ``requires`` or ``uses`` runs in the second tier). Drawing + arrows between them would be a lie; the payload states the tiers instead. + +The one real cross-step edge is the quarantine gate, and it is served as its +own object rather than as an edge in either graph. + +Both endpoints degrade instead of failing: the pipeline graph answers with +``dag_ids_known``/``steps_known`` flags when no runtime or no pipeline is +addressed, and the run graph refuses with the runs monitor's 409/502 idiom. +""" + +import re +from collections import Counter +from dataclasses import dataclass +from datetime import UTC, datetime, timedelta +from math import isfinite +from typing import Any + +from fastapi import APIRouter, HTTPException + +from hflow.app import MEDIA_CONTACT_SHEET_STEP_NAME +from hflow.manifest import PipelineManifest +from hflow.runtime import ( + AirflowClient, + AirflowClientError, + DagTaskNode, + DagTopology, + IngestTopology, + StageTopology, + ingest_dag_topology, +) +from hflow.steps import Stage +from hflow_server._contract import ( + DagTaskNodePayload, + DagTopologyPayload, + MappedFanOutSummary, + PipelineEngineStep, + PipelineGraphResponse, + PipelineGraphStage, + PipelineUserStep, + QuarantineGate, + RunGraphMaster, + RunGraphResponse, + RunGraphStage, + RunTaskInstance, + StageRunMatch, +) +from hflow_server._pipeline import PipelineLoaded, PipelineState, registered_steps_by_stage +from hflow_server._runtime import ( + ResolvedRuntime, + RuntimeResolver, + airflow_failure_refusal, + optional_string, + resolved_runtime_or_refuse, +) + +# The display copy for the four stages. Restated here (rather than imported +# from hflow.runtime._bundle's STAGE_TITLES/STAGE_DESCRIPTIONS, which are +# private and worded for Airflow's own UI) so the browser never hardcodes it: +# the thin-client rule applies to prose too. +_STAGE_TITLES: dict[Stage, str] = { + Stage.SYNC: "Transform & sync", + Stage.META: "Metadata", + Stage.LABELS: "Labels & artifacts", + Stage.MEDIA: "Media", +} +_STAGE_DESCRIPTIONS: dict[Stage, str] = { + Stage.SYNC: "canonical transform + derived channels (critical path)", + Stage.META: "checks + catalog registration", + Stage.LABELS: "enrichments (non-critical)", + Stage.MEDIA: "derived media artifacts", +} + +# The master id shown when no runtime is addressed: the DAGs do not exist +# yet, so the graph is drawn under a display-only name (the pipeline's own +# name when one is imported, else this) and ``dag_ids_known`` is false. +DISPLAY_ONLY_MASTER_DAG_ID = "ingest" + +_DAG_ID_UNSAFE_CHARACTERS = re.compile(r"[^A-Za-z0-9_.-]+") + +# How many of a stage sub-DAG's runs the run-graph heuristic looks at. +_STAGE_RUN_SEARCH_LIMIT = 25 + +# How long after a master run ENDED a stage run may still start and count as +# its own. Normally zero is enough (the master defers until each stage run +# finishes), but a master that fails, times out, or is cleared the moment +# after firing a trigger ends before the run it just caused appears -- and the +# two timestamps come from different components' clocks. Generous enough to +# cover that, far short of the gap between two ingests. +_STAGE_RUN_START_GRACE_AFTER_MASTER_END = timedelta(minutes=5) + +# Airflow reports a task instance that has not been scheduled yet with a null +# state; the mapped fan-out summary needs a key for those. +_UNSET_TASK_STATE = "no_status" + + +def _dag_task_node_payload(node: DagTaskNode) -> DagTaskNodePayload: + return DagTaskNodePayload( + task_id=node.task_id, + summary=node.summary, + mapped=node.mapped, + deferred=node.deferred, + ) + + +def _dag_topology_payload(topology: DagTopology) -> DagTopologyPayload: + return DagTopologyPayload( + dag_id=topology.dag_id, + tasks=[_dag_task_node_payload(node) for node in topology.tasks], + edges=[(upstream, downstream) for upstream, downstream in topology.edges], + ) + + +def _display_master_dag_id(pipeline_name: str | None) -> str: + """A stand-in master id for a workspace with no rendered bundle. + + Never presented as real: the response's ``dag_ids_known`` is false, and + the sub-DAG ids derived from it are display-only too. The real id is + ``_ingest``, which only a rendered bundle knows. + """ + if pipeline_name is None: + return DISPLAY_ONLY_MASTER_DAG_ID + sanitized = _DAG_ID_UNSAFE_CHARACTERS.sub("-", pipeline_name).strip("-") + return sanitized or DISPLAY_ONLY_MASTER_DAG_ID + + +def _user_steps(stage: Stage, manifest: PipelineManifest | None) -> list[PipelineUserStep]: + """The registered steps running inside this stage's ``process_batch``. + + Which stage owns which steps, and the order they run in, both come from + :func:`hflow_server._pipeline.registered_steps_by_stage` -- the package's one + owner of that mapping -- so this lane and the pipeline page's lane are + the same steps in the same order, and only ``tier`` is served here. + """ + if manifest is None: + return [] + return [ + PipelineUserStep.from_step_manifest_in_tier(step, tier) + for step, tier in registered_steps_by_stage(manifest)[stage] + ] + + +def _engine_steps(stage: Stage, manifest: PipelineManifest | None) -> list[PipelineEngineStep]: + """The engine's own work inside this stage's ``process_batch``. + + Not registrations -- these are what ``App.process`` does around the user's + steps, and no manifest lists them: the canonical transform (sync), the + catalog append (meta), and the contact-sheet renderer (media). + """ + if stage is Stage.SYNC: + overridden = manifest is not None and manifest.has_transform_override + derived_channel_count = len(manifest.derived_channels) if manifest is not None else 0 + summary = ( + "rewrite the source recording into a canonical MCAP and publish it" + if not overridden + else "rewrite the source recording with this pipeline's transform override " + "and publish it" + ) + if derived_channel_count: + summary += ( + f"; computes {derived_channel_count} registered derived " + f"channel{'s' if derived_channel_count != 1 else ''} over the source" + ) + return [PipelineEngineStep(name="canonical transform", summary=summary)] + if stage is Stage.META: + return [ + PipelineEngineStep( + name="catalog registration", + summary="append this run's episode row and every step's evidence " + "(check runs, measurements, intervals, tags) to the catalog", + ) + ] + if stage is Stage.MEDIA: + return [ + PipelineEngineStep( + name=MEDIA_CONTACT_SHEET_STEP_NAME, + summary="render one contact sheet per camera and record it as a " + "catalog artifact; absent when the episode has no cameras", + ) + ] + return [] + + +# What a failed critical check actually does in App.process: the episode is +# tagged (never deleted), the meta stage skips its REMAINING checks, and every +# enrichment in labels and media is recorded as skipped. +_QUARANTINE_GATE_EXPLANATION = ( + "a False verdict from a critical check quarantines the episode: meta skips its " + "remaining checks, and every enrichment in the labels and media stages is recorded " + "as skipped. Quarantine is a tag, never a deletion." +) +_NO_CRITICAL_CHECKS_EXPLANATION = ( + "this pipeline registers no critical checks, so no check can quarantine an episode. " + "A critical check's False verdict would make meta skip its remaining checks and every " + "enrichment in the labels and media stages." +) + + +def _quarantine_gate(manifest: PipelineManifest | None) -> QuarantineGate | None: + """The one real edge between user steps, or null when no pipeline is known.""" + if manifest is None: + return None + critical_step_names = [step.name for step in manifest.checks if step.critical] + return QuarantineGate( + from_stage=Stage.META, + to_stages=[Stage.LABELS, Stage.MEDIA], + critical_step_names=critical_step_names, + explanation=( + _QUARANTINE_GATE_EXPLANATION if critical_step_names else _NO_CRITICAL_CHECKS_EXPLANATION + ), + ) + + +def _stage_graph( + stage_topology: StageTopology, manifest: PipelineManifest | None +) -> PipelineGraphStage: + stage = stage_topology.stage + return PipelineGraphStage( + stage=stage, + title=_STAGE_TITLES[stage], + description=_STAGE_DESCRIPTIONS[stage], + gate_task_id=stage_topology.gate_task_id, + trigger_task_id=stage_topology.trigger_task_id, + enabling_profiles=list(stage_topology.enabling_profiles), + dag=_dag_topology_payload(stage_topology.dag), + engine_steps=_engine_steps(stage, manifest), + user_steps=_user_steps(stage, manifest), + ) + + +def _parsed_timestamp(value: object) -> datetime | None: + """One Airflow ISO-8601 timestamp as an aware datetime, or None. + + Airflow renders UTC as a trailing ``Z``; it is normalized here rather than + left to ``fromisoformat``'s version-dependent tolerance, and a naive value + is read as UTC so a comparison against another timestamp never raises. + Anything unparseable is None -- a timestamp this build cannot read must + not fail the request. + """ + if not isinstance(value, str) or not value: + return None + try: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + return parsed if parsed.tzinfo is not None else parsed.replace(tzinfo=UTC) + + +def _duration_seconds(instance: dict[str, Any]) -> float | None: + """One task instance's wall duration, computed here rather than trusted. + + Airflow's own ``duration`` field is the fallback for an instance whose + timestamps this build cannot parse. + """ + started_at = _parsed_timestamp(instance.get("start_date")) + ended_at = _parsed_timestamp(instance.get("end_date")) + if started_at is not None and ended_at is not None: + return (ended_at - started_at).total_seconds() + reported_duration = instance.get("duration") + if isinstance(reported_duration, int | float) and not isinstance(reported_duration, bool): + return float(reported_duration) if isfinite(float(reported_duration)) else None + return None + + +def _task_instance(instance: dict[str, Any]) -> RunTaskInstance: + """One Airflow task instance reduced to what the graph draws.""" + try_number = instance.get("try_number") + map_index = instance.get("map_index") + return RunTaskInstance( + task_id=optional_string(instance.get("task_id")), + state=optional_string(instance.get("state")), + start_date=optional_string(instance.get("start_date")), + end_date=optional_string(instance.get("end_date")), + # Airflow has spelled the queued timestamp both ways across versions + # and may omit it; absent is fine. + queued_at=optional_string(instance.get("queued_when") or instance.get("queued_at")), + try_number=int(try_number) if isinstance(try_number, int) else None, + # -1 is Airflow's "not a mapped instance"; an absent value means the + # same thing. + map_index=int(map_index) if isinstance(map_index, int) else -1, + duration_s=_duration_seconds(instance), + ) + + +def _sorted_task_instances( + instances: list[dict[str, Any]], topology: DagTopology +) -> list[RunTaskInstance]: + """Task instances in TOPOLOGY order (then by map index), not API order.""" + topology_positions = {node.task_id: index for index, node in enumerate(topology.tasks)} + unknown_task_position = len(topology_positions) + return sorted( + (_task_instance(instance) for instance in instances), + key=lambda task: ( + topology_positions.get(task.task_id or "", unknown_task_position), + task.task_id or "", + task.map_index, + ), + ) + + +def _mapped_summary( + tasks: list[RunTaskInstance], stage_topology: StageTopology +) -> MappedFanOutSummary | None: + """The fan-out's counts: how many mapped instances are in which state. + + The mapped task id comes from the topology (the node flagged ``mapped``), + so this never restates a task name the library owns. Every instance of + that task lands in exactly one ``by_state`` bucket -- an unscheduled one + under ``no_status`` -- which is what makes the served summary complete + enough that a client never has to recount the raw instances. + """ + mapped_task_ids = [node.task_id for node in stage_topology.dag.tasks if node.mapped] + if not mapped_task_ids: + return None + # Every generated stage sub-DAG has exactly one mapped node + # (``process_batch``); a topology that grows a second one needs a summary + # per mapped task, not a silently truncated one. + mapped_task_id = mapped_task_ids[0] + mapped_instances = [task for task in tasks if task.task_id == mapped_task_id] + if not mapped_instances: + return None + state_counts = Counter(task.state or _UNSET_TASK_STATE for task in mapped_instances) + return MappedFanOutSummary( + task_id=mapped_task_id, + # Before the fan-out expands, Airflow reports ONE instance with + # map_index -1; it is counted, because "1 unexpanded instance" is the + # truth at that moment. + total=len(mapped_instances), + by_state=dict(sorted(state_counts.items())), + ) + + +@dataclass(frozen=True) +class _MatchedStageRun: + """The stage run a master run most plausibly triggered, and how it matched.""" + + run: dict[str, Any] + match: StageRunMatch + + +@dataclass(frozen=True) +class _MasterRunWindow: + """When a master run was live: the interval its stage runs must start in. + + ``ended_at`` is None while the run is still going, which leaves the window + open-ended on the right -- the only case where "no upper bound" is true. + """ + + started_at: datetime + ended_at: datetime | None + + def contains_stage_run_start(self, started_at: datetime) -> bool: + if started_at < self.started_at: + return False + if self.ended_at is None: + return True + return started_at <= self.ended_at + _STAGE_RUN_START_GRACE_AFTER_MASTER_END + + +def _master_run_window(master_run: dict[str, Any]) -> _MasterRunWindow | None: + """One master run's live interval, or None when it has not started yet.""" + started_at = _parsed_timestamp(master_run.get("start_date")) + if started_at is None: + return None + return _MasterRunWindow( + started_at=started_at, ended_at=_parsed_timestamp(master_run.get("end_date")) + ) + + +def _matched_stage_run( + stage_runs: list[dict[str, Any]], window: _MasterRunWindow | None +) -> _MatchedStageRun | None: + """The EARLIEST run of one stage sub-DAG that started inside the master's window. + + The master triggers each stage with a deferring + ``TriggerDagRunOperator(wait_for_completion=True)`` and chains the stages + in order (``hflow.runtime`` renders them that way), so a stage run the + master caused always STARTS while the master run is still live. Bounding + the search by the master's own end is therefore not a guess, and it is + what stops an old master run from adopting an unrelated stage run that + happens to be newer -- the stage lanes only ever look back + ``_STAGE_RUN_SEARCH_LIMIT`` runs, so without the bound every candidate + qualified and the newest won. + + Earliest-in-window, not newest: when two master runs overlap, this + master's own stage run is the first one after its start, while the newest + is biased toward the other master's. The cost is that a stage triggered + twice inside ONE master run (a retried trigger task) shows the first + attempt -- accepted, because preferring the newest is exactly what let an + unrelated run be adopted. + + HONEST LIMITATION, restated in the payload as ``"match": "heuristic"``: + the master lets Airflow mint the sub-DAG's run id and forwards a conf that + carries no back-reference, so the API offers nothing that ties a stage run + to the master run that triggered it. Two master runs whose windows OVERLAP + can still be attributed the same stage run. A master run that has not + started yet (no ``start_date``) matches nothing rather than guessing. + """ + if window is None: + return None + earliest_run: dict[str, Any] | None = None + earliest_started_at: datetime | None = None + for run in stage_runs: + started_at = _parsed_timestamp(run.get("start_date")) + if started_at is None or not window.contains_stage_run_start(started_at): + continue + if earliest_started_at is None or started_at < earliest_started_at: + earliest_run, earliest_started_at = run, started_at + if earliest_run is None: + return None + return _MatchedStageRun(run=earliest_run, match="heuristic") + + +def _empty_stage_graph(stage_topology: StageTopology) -> RunGraphStage: + """A stage that never ran for this master run: explicit nulls, not omissions.""" + return RunGraphStage( + stage=stage_topology.stage, + dag_id=stage_topology.dag.dag_id, + dag_run_id=None, + state=None, + match=None, + tasks=[], + mapped_summary=None, + ) + + +def create_graph_router(pipeline_state: PipelineState, resolver: RuntimeResolver) -> APIRouter: + """The visualization routes, closed over one launch's pipeline and runtime. + + Read-only throughout, so unlike the other routers these need no settings: + the pipeline comes from the one startup import and the runtime from the + shared resolver. + """ + router = APIRouter(prefix="/api/v1") + + def stage_task_instances( + client: AirflowClient, dag_id: str, dag_run_id: str + ) -> list[dict[str, Any]]: + try: + return client.task_instances(dag_id, dag_run_id) + except AirflowClientError: + # A stage sub-DAG that vanished (or a run Airflow expired) leaves + # that lane without task detail; the master's own state -- the + # page's point -- is already in hand, so this is a thinner + # drawing, not a failed request. + return [] + + @router.get("/pipeline/graph") + def read_pipeline_graph() -> PipelineGraphResponse: + """The merged picture: the DAG topology plus the pipeline's user steps. + + Three degraded states, each explicit rather than an error: no runtime + addressed (``dag_ids_known: false``, display-only ids), no + ``--pipeline`` (``steps_known: false``, no user steps and no + quarantine gate), and both at once -- the common first-run case. + """ + resolution = resolver.resolve() + dag_ids_known = isinstance(resolution, ResolvedRuntime) + application = ( + pipeline_state.application if isinstance(pipeline_state, PipelineLoaded) else None + ) + master_dag_id = ( + resolution.dag_id + if isinstance(resolution, ResolvedRuntime) + else _display_master_dag_id(application.name if application is not None else None) + ) + manifest = application.manifest() if application is not None else None + topology: IngestTopology = ingest_dag_topology(master_dag_id) + return PipelineGraphResponse( + dag_ids_known=dag_ids_known, + steps_known=manifest is not None, + master=_dag_topology_payload(topology.master), + stages=[_stage_graph(stage_topology, manifest) for stage_topology in topology.stages], + quarantine_gate=_quarantine_gate(manifest), + ) + + @router.get("/runtime/runs/{dag_run_id}/graph") + def read_run_graph(dag_run_id: str) -> RunGraphResponse: + """One master run's live state over the same topology. + + The master run is addressed directly; each stage's sub-DAG run is + resolved by the documented heuristic in :func:`_matched_stage_run`. + """ + runtime = resolved_runtime_or_refuse(resolver) + topology = ingest_dag_topology(runtime.dag_id) + try: + master_run = runtime.client.dag_run(runtime.dag_id, dag_run_id) + except AirflowClientError as error: + if error.status == 404: + # A definitively unknown run is a missing resource, not an + # upstream failure -- and the detail names only ids the + # caller already sent. + raise HTTPException( + status_code=404, + detail=f"no run {dag_run_id!r} of dag {runtime.dag_id!r}", + ) from error + raise airflow_failure_refusal(error, source=runtime.source) from error + try: + master_instances = runtime.client.task_instances(runtime.dag_id, dag_run_id) + except AirflowClientError as error: + raise airflow_failure_refusal(error, source=runtime.source) from error + master_window = _master_run_window(master_run) + + stages: list[RunGraphStage] = [] + for stage_topology in topology.stages: + stage_dag_id = stage_topology.dag.dag_id + try: + stage_runs = runtime.client.dag_runs( + stage_dag_id, limit=_STAGE_RUN_SEARCH_LIMIT, order_by="-id" + ) + except AirflowClientError: + # An unregistered stage sub-DAG (a partial profile, or a + # bundle mid-render) is a stage that never ran here. + stage_runs = [] + matched = _matched_stage_run(stage_runs, master_window) + if matched is None: + stages.append(_empty_stage_graph(stage_topology)) + continue + stage_run_id = optional_string(matched.run.get("dag_run_id")) + stage_tasks = ( + _sorted_task_instances( + stage_task_instances(runtime.client, stage_dag_id, stage_run_id), + stage_topology.dag, + ) + if stage_run_id is not None + else [] + ) + stages.append( + RunGraphStage( + stage=stage_topology.stage, + dag_id=stage_dag_id, + dag_run_id=stage_run_id, + state=optional_string(matched.run.get("state")), + match=matched.match, + tasks=stage_tasks, + mapped_summary=_mapped_summary(stage_tasks, stage_topology), + ) + ) + + return RunGraphResponse( + master=RunGraphMaster( + dag_run_id=optional_string(master_run.get("dag_run_id")) or dag_run_id, + state=optional_string(master_run.get("state")), + tasks=_sorted_task_instances(master_instances, topology.master), + ), + stages=stages, + ) + + return router diff --git a/packages/hflow-server/src/hflow_server/_media.py b/packages/hflow-server/src/hflow_server/_media.py new file mode 100644 index 00000000..39699389 --- /dev/null +++ b/packages/hflow-server/src/hflow_server/_media.py @@ -0,0 +1,207 @@ +"""Media byte-serving: catalog URIs resolved and contained under the data root. + +The browser never chooses a filesystem path. It addresses bytes as +(episode_id, artifact name); the URI comes out of the catalog, and the +strictly-resolved file must land inside the strictly-resolved local data +root -- anything else is refused, and a refusal never echoes the offending +path (only the containment fact appears in errors). +""" + +import mimetypes +from pathlib import Path + +from fastapi import HTTPException +from starlette.responses import FileResponse + +from hflow.storage import is_bucket_url +from hflow.workspace import ( + CATALOG_DIRECTORY_NAME, + EPISODES_DIRECTORY_NAME, + TEST_RUNS_DIRECTORY_NAME, +) +from hflow_server._settings import local_data_root_or_none + +# The layout directories a workspace's own files live under, owned by +# hflow.workspace. Used to recognise a path recorded from another vantage of +# this workspace (a container mount) and re-anchor it here. +_WORKSPACE_LAYOUT_DIRECTORY_NAMES = frozenset( + {EPISODES_DIRECTORY_NAME, CATALOG_DIRECTORY_NAME, TEST_RUNS_DIRECTORY_NAME} +) + +# Media types inert enough to render inline in the browser: raster images and +# common audio/video containers. Deliberately excludes text/html, +# image/svg+xml, and application/xhtml+xml -- an active document served from +# the UI's own origin runs script same-origin with this workspace's API and +# could drive every endpoint it exposes (read the catalog, pin manifests, +# trigger runs), so anything not on this list is forced to download. +_INLINE_SERVABLE_MEDIA_TYPES = frozenset( + { + "image/png", + "image/jpeg", + "image/gif", + "image/webp", + "image/bmp", + "image/apng", + "image/avif", + "image/x-icon", + "video/mp4", + "video/webm", + "video/ogg", + "video/quicktime", + "audio/mpeg", + "audio/ogg", + "audio/wav", + "audio/x-wav", + "audio/webm", + "audio/aac", + "audio/mp4", + "audio/flac", + } +) + +# Every byte-serving response carries these: no sniffing an octet-stream back +# into an active type, and a policy that denies script/resource loads even if +# a viewer opens the bytes directly. +_HARDENING_HEADERS = { + "X-Content-Type-Options": "nosniff", + "Content-Security-Policy": "default-src 'none'; sandbox", +} + + +class MediaResolutionError(Exception): + """One refusal to serve a catalog URI, carrying its HTTP mapping.""" + + def __init__(self, status_code: int, detail: str) -> None: + super().__init__(detail) + self.status_code = status_code + self.detail = detail + + +def media_refusal(error: MediaResolutionError) -> HTTPException: + """The HTTP refusal one unservable URI maps to. + + Lives beside the error it converts (as ``_connections`` and ``_runtime`` + do for theirs), so the two routes that serve catalog bytes -- episode + media and manifest downloads -- share one mapping instead of each copying + the two field reads. + """ + return HTTPException(status_code=error.status_code, detail=error.detail) + + +def _resolved_local_data_root(data_root: str) -> Path: + local_root = local_data_root_or_none(data_root) + if local_root is None: + raise MediaResolutionError( + 501, + "media serving requires a local data root; bucket-backed workspaces are not served yet", + ) + return local_root.resolve() + + +def _strictly_resolved(candidate: Path) -> Path | None: + """The real file behind a path, or ``None`` when it cannot be reached.""" + try: + return candidate.resolve(strict=True) + except (FileNotFoundError, OSError): + return None + + +def _rebased_onto_this_workspace(recorded_path: Path, resolved_data_root: Path) -> Path | None: + """The same workspace-relative file, as THIS host addresses it. + + One workspace is reachable from several vantages: the Compose runtime + mounts the data root inside its containers, so a run executed there + catalogs ``/opt/airflow/data/episodes//media/x.jpg`` while the very + same bytes sit at ``/episodes//media/x.jpg`` here. A path + recorded from another vantage is not foreign data -- it is this + workspace, named differently -- so it is re-anchored at the first + workspace layout directory in it and re-checked exactly like any other + candidate. Containment is still enforced afterwards, so this only ever + resolves to files already inside the data root; it never widens what may + be served. + """ + for index, component in enumerate(recorded_path.parts): + if component in _WORKSPACE_LAYOUT_DIRECTORY_NAMES: + return resolved_data_root.joinpath(*recorded_path.parts[index:]) + return None + + +def resolve_served_file(uri: str, *, data_root: str) -> Path: + """The real file a catalog URI may be served from, or a typed refusal. + + Resolution is strict (symlinks followed, missing components refused), and + the result must be contained in the resolved data root -- a symlink that + points out of the workspace is refused exactly like a foreign path. A URI + recorded from another vantage of this same workspace (see + :func:`_rebased_onto_this_workspace`) is retried against this host's data + root under the identical containment rule. + """ + if is_bucket_url(uri): + raise MediaResolutionError( + 501, "this file lives in an object store; bucket media serving is not implemented yet" + ) + resolved_data_root = _resolved_local_data_root(data_root) + recorded_path = Path(uri.removeprefix("file://")) + + resolved_file = _strictly_resolved(recorded_path) + escapes_workspace = resolved_file is not None and not resolved_file.is_relative_to( + resolved_data_root + ) + if resolved_file is None or escapes_workspace: + rebased_path = _rebased_onto_this_workspace(recorded_path, resolved_data_root) + rebased_file = None if rebased_path is None else _strictly_resolved(rebased_path) + if rebased_file is not None and rebased_file.is_relative_to(resolved_data_root): + resolved_file = rebased_file + elif escapes_workspace: + raise MediaResolutionError( + 403, "the cataloged URI resolves outside the workspace data root" + ) + else: + raise MediaResolutionError(404, "the cataloged file does not exist on this machine") + + if not resolved_file.is_file(): + raise MediaResolutionError(404, "the cataloged URI does not name a regular file") + return resolved_file + + +def is_uri_servable(uri: str, *, data_root: str) -> bool: + """Whether a GET for this URI would serve bytes (containment + existence).""" + try: + resolve_served_file(uri, data_root=data_root) + except MediaResolutionError: + return False + return True + + +def served_file_response( + resolved_file: Path, *, attachment_filename: str | None = None +) -> FileResponse: + """Bytes served safely: an allowlisted inert media type renders inline; + anything else (or an explicit ``attachment_filename``) is downloaded as + opaque ``application/octet-stream``. Every response carries ``nosniff`` + and a locked-down CSP, so a workspace file whose name ends in .html/.svg + can never execute as an active document on the UI's own origin. + + Starlette's FileResponse handles Range requests where it can, and a plain + GET always works. Passing ``attachment_filename`` names the download + (manifest exports).""" + if attachment_filename is not None: + return FileResponse( + resolved_file, + media_type="application/octet-stream", + filename=attachment_filename, + headers=dict(_HARDENING_HEADERS), + ) + guessed_type, _ = mimetypes.guess_type(resolved_file.name) + if guessed_type in _INLINE_SERVABLE_MEDIA_TYPES: + return FileResponse( + resolved_file, media_type=guessed_type, headers=dict(_HARDENING_HEADERS) + ) + # Not a known-inert type: force a download so an .html/.svg/unknown file + # is never rendered as an active document on this origin. + return FileResponse( + resolved_file, + media_type="application/octet-stream", + filename=resolved_file.name, + headers=dict(_HARDENING_HEADERS), + ) diff --git a/packages/hflow-server/src/hflow_server/_pipeline.py b/packages/hflow-server/src/hflow_server/_pipeline.py new file mode 100644 index 00000000..e8d6f5df --- /dev/null +++ b/packages/hflow-server/src/hflow_server/_pipeline.py @@ -0,0 +1,175 @@ +"""The pipeline page API: the startup-imported App described over the catalog. + +``--pipeline path/to/pipeline.py[:app]`` names a Python file this server +imports -- EXECUTES -- exactly once at startup via the shared +:func:`hflow.import_pipeline_application` seam (the one owner of the "address +a pipeline by file" contract, used by the CLI too; producing a manifest +requires the live functions, because step versions are content hashes of +them). The operator opts into running their own pipeline code by passing the +flag; an import failure never crashes the server -- the error string is +remembered, the config capability reports false, and /api/v1/pipeline answers +409 with the stored reason. +""" + +from dataclasses import dataclass + +from fastapi import APIRouter, HTTPException + +from hflow import App, import_pipeline_application +from hflow.curation import stale_episodes +from hflow.format import EPISODE_FORMAT_VERSION +from hflow.manifest import PipelineManifest, StepManifest +from hflow.steps import Stage +from hflow.workspace import Workspace +from hflow_server import _catalog, _connections +from hflow_server._contract import ( + ObservedCheckVersion, + PipelineResponse, + StaleSummary, + StepTier, +) +from hflow_server._settings import ServerSettings + + +@dataclass(frozen=True) +class PipelineLoaded: + """The one startup import produced a live App.""" + + application: App + + +@dataclass(frozen=True) +class PipelineUnavailable: + """No App for this launch, and exactly why.""" + + detail: str + + +# Two states, never both and never neither -- the same sum ``_runtime`` uses +# for its resolution, so the two capabilities behind the same 409 refusal are +# modelled the same way and the refusal's detail cannot be null. +PipelineState = PipelineLoaded | PipelineUnavailable + + +def load_pipeline_state(pipeline_spec: str | None) -> PipelineState: + """Run the one startup import and remember its outcome, whatever it is.""" + if pipeline_spec is None: + return PipelineUnavailable( + detail=( + "no --pipeline configured: relaunch `hflow serve` with " + "--pipeline path/to/pipeline.py[:app] to serve the pipeline page" + ) + ) + try: + return PipelineLoaded(application=import_pipeline_application(pipeline_spec)) + except ValueError as error: + return PipelineUnavailable(detail=str(error)) + + +def registered_step_tier(step: StepManifest) -> StepTier: + """Which cheap-first tier this step runs in (1 first, 2 second). + + Mirrors :meth:`hflow.App._ordered_checks` and ``_ordered_enrichments`` + EXACTLY: both sort on ``bool(requires) or uses is not None``, so tier 2 is + precisely the steps declaring a required channel or an endpoint alias. + Within a tier there is no ordering at all -- registration order is what + the stable sort preserves, not a dependency. + + The rule ideally belongs in the SDK -- a ``tier`` on + ``hflow.manifest.StepManifest`` that ``App`` sorts on and ``hflow + manifest`` renders, so the CLI could answer "in what order do my steps + run?" too. Until it lives there, this is this package's ONE copy: both + endpoints project from :func:`registered_steps_by_stage` rather than + restating the expression a second time. + """ + return 2 if (bool(step.requires) or step.uses is not None) else 1 + + +def _in_execution_order( + steps: tuple[StepManifest, ...], +) -> tuple[tuple[StepManifest, StepTier], ...]: + # Stable sort on the tier alone: the same sort App._ordered_checks makes, + # so the served order IS the execution order. + return tuple( + (step, registered_step_tier(step)) for step in sorted(steps, key=registered_step_tier) + ) + + +def registered_steps_by_stage( + manifest: PipelineManifest, +) -> dict[Stage, tuple[tuple[StepManifest, StepTier], ...]]: + """Which registered steps run in which stage, in the order they run. + + The ONE owner of that mapping for this package: the pipeline page's lanes + and the graph's per-stage user steps are the same steps in the same order, + differing only in whether the payload carries the tier -- so the two pages + can never show one pipeline as two. + + Stage ownership is the engine's (``hflow.steps``/``App.process``): + registered checks run in META ("checks + catalog registration"), user + enrichments in LABELS ("Labels & artifacts"), while SYNC (the canonical + transform plus derived channels) and MEDIA (the engine's contact-sheet + step) are engine-owned lanes carrying no user-registered steps. + """ + steps_by_stage: dict[Stage, tuple[tuple[StepManifest, StepTier], ...]] = dict.fromkeys( + Stage, () + ) + steps_by_stage[Stage.META] = _in_execution_order(manifest.checks) + steps_by_stage[Stage.LABELS] = _in_execution_order(manifest.enrichments) + return steps_by_stage + + +def _observed_versions_and_stale( + data_root: str, application: App +) -> tuple[list[ObservedCheckVersion], StaleSummary | None]: + """What the catalog has SEEN of this pipeline: per-(check, version) + first/last-seen aggregates, plus the stale count against the App's + current versions. A workspace with no catalog yet has observed nothing + and its staleness is unknowable -- ([], None), not an error.""" + with _connections.opened_workspace_connection_or_none(data_root) as connection: + if connection is None: + return [], None + observed = [ + ObservedCheckVersion.model_validate(row) + for row in _catalog.fetched_json_safe_rows( + connection.execute( + "SELECT check_name, check_version, " + f"{_catalog.utc_iso_text('min(recorded_at)', 'first_seen')}, " + f"{_catalog.utc_iso_text('max(recorded_at)', 'last_seen')}, " + "count(*) AS run_count " + "FROM check_runs GROUP BY check_name, check_version " + "ORDER BY check_name, check_version" + ) + ) + ] + current_pipeline_version = application.pipeline_version + try: + # A pipeline defines the whole current target, format version + # included -- the same pairing the CLI's `hflow stale --pipeline` uses. + stale = stale_episodes( + Workspace.parse(data_root).catalog_root, + pipeline_version=current_pipeline_version, + schema_version=EPISODE_FORMAT_VERSION, + ) + except (FileNotFoundError, ValueError): + return observed, None + return observed, StaleSummary(pipeline_version=current_pipeline_version, count=len(stale)) + + +def create_pipeline_router(settings: ServerSettings, state: PipelineState) -> APIRouter: + """The pipeline route, closed over the one startup import's outcome.""" + router = APIRouter(prefix="/api/v1") + + @router.get("/pipeline") + def read_pipeline() -> PipelineResponse: + if isinstance(state, PipelineUnavailable): + raise HTTPException(status_code=409, detail=state.detail) + manifest = state.application.manifest() + observed, stale = _observed_versions_and_stale(settings.data_root, state.application) + return PipelineResponse( + manifest=manifest.to_json_dict(), + observed=observed, + stale=stale, + ) + + return router diff --git a/packages/hflow-server/src/hflow_server/_runtime.py b/packages/hflow-server/src/hflow_server/_runtime.py new file mode 100644 index 00000000..30bba7a3 --- /dev/null +++ b/packages/hflow-server/src/hflow_server/_runtime.py @@ -0,0 +1,475 @@ +"""The runs monitor API: address the workspace's ingest runtime, proxy Airflow. + +Addressing mirrors the CLI's ``_resolve_bundle_dir``: a local Compose bundle +at ``/runtime`` (skipped for bucket data roots), then the +``./runtime`` fallback, else a remote endpoint resolved from the +``HFLOW_AIRFLOW_*`` environment via :func:`hflow.runtime.resolve_remote_endpoint`. +Resolution happens lazily per request -- the stack may come up (or go away) +after the server started -- and is cached briefly per launch. + +Two rules hold at this boundary: + +- The browser NEVER receives credentials: the bundle's admin password and any + remote token stay inside :class:`hflow.runtime.AirflowClient`; this server + proxies every Airflow call. The only URL it exposes is the deep-link base + the operator already knows (the bundle's own recorded api-server address). +- A missing or unreachable runtime is an ANSWER, never a traceback: + ``/runtime/status`` reports ``available: false`` with the reason, and the + other endpoints refuse with a clear 4xx/502 detail. +""" + +import ipaddress +import logging +import time +import urllib.parse +from dataclasses import dataclass +from pathlib import Path +from posixpath import normpath +from typing import Any + +from fastapi import APIRouter, HTTPException, Query +from pydantic import BaseModel, Field + +from hflow.runtime import ( + AirflowClient, + AirflowClientError, + client_for_bundle, + client_for_endpoint, + load_bundle, + resolve_remote_endpoint, + sub_dag_id_for_stage, +) +from hflow.steps import RUN_PROFILES, IngestMode, Stage +from hflow.storage import is_bucket_url +from hflow.workspace import RUNTIME_BUNDLE_DIRECTORY_NAME +from hflow_server._contract import ( + IngestTriggerResponse, + RuntimeHealthComponents, + RuntimeRunsResponse, + RuntimeRunSummary, + RuntimeSource, + RuntimeStatusResponse, + StageRecentRuns, + StageRunSummary, +) +from hflow_server._settings import ServerSettings, refuse_when_read_only + +# Mirrors hflow.runtime._endpoint's variable name (a documented public +# contract); restated here rather than imported from that private module. +AIRFLOW_URL_ENVIRONMENT_VARIABLE = "HFLOW_AIRFLOW_URL" + +# How long one resolution (bundle files read, client built) is reused before +# the next request re-probes -- long enough to spare a busy Runs page the +# filesystem walk, short enough that `hflow up` shows up within seconds. +RESOLUTION_CACHE_TTL_S = 5.0 + +# The health components /runtime/status reports, owned by the response model +# so the served keys and the components actually read can never diverge. +_HEALTH_COMPONENT_NAMES = tuple(RuntimeHealthComponents.model_fields) + +_RECENT_STAGE_RUN_LIMIT = 5 + +_LOGGER = logging.getLogger("hflow_server.runtime") + + +def _client_error_reason(error: AirflowClientError) -> str: + """A stable machine-readable classification of an Airflow call failure.""" + if error.status in (401, 403): + return "unauthorized" + if error.status is not None: + return "http_error" + return "unreachable" + + +def is_loopback_web_url(web_url: str | None) -> bool: + """Whether this address resolves only on the machine running this server. + + A rendered bundle records ``http://127.0.0.1:`` because that is + where its api-server binds by default. Handed to a browser on another + machine, that URL points at the VIEWER's own loopback -- their laptop, not + the workspace -- so the Runs page must present it as a fact about the host + rather than as a link to follow. + """ + if web_url is None: + return False + host = urllib.parse.urlparse(web_url).hostname + if host is None: + return False + try: + return ipaddress.ip_address(host).is_loopback + except ValueError: + return host == "localhost" + + +def client_error_detail(error: AirflowClientError, *, source: RuntimeSource) -> str: + """A browser-safe detail for an Airflow call failure (shared with _graph). + + A local bundle's api-server address is one the operator already has, so + its verbatim message (which embeds that URL) is fine. A REMOTE runtime's + base URL is deliberately withheld on the success path, and the verbatim + message embeds that URL plus an excerpt of the upstream response body -- + so a remote failure returns only a generic detail with a stable reason + code, and the full error is logged server-side for the operator. + + ``source`` is the refined :data:`RuntimeSource`, not a bare string: this + branch decides what a browser is allowed to see, so the type checker -- + not a test -- is what guarantees a third runtime source would have to + state its own disclosure posture here rather than defaulting into one. + """ + if source == "bundle": + # Say WHOSE loopback this is. The message embeds the bundle's own + # address (typically http://127.0.0.1:8080), and a browser reaching + # this server from another machine reads that as its own laptop -- so the + # sentence has to name the workspace host as the one that called. + return f"the workspace host could not reach its own ingest runtime: {error}" + reason = _client_error_reason(error) + _LOGGER.warning("remote Airflow call failed (reason=%s): %s", reason, error) + if error.status is not None: + return ( + f"the remote ingest runtime returned an error (reason: {reason}, status {error.status})" + ) + return f"the remote ingest runtime is not reachable (reason: {reason})" + + +@dataclass(frozen=True) +class ResolvedRuntime: + """One addressable ingest runtime: the client, its DAG, and its shape.""" + + client: AirflowClient + dag_id: str + source: RuntimeSource + airflow_web_url: str | None + # (stage, sub-DAG id) in stage-graph order; None for remote runtimes + # (only the bundle manifest records the stage sub-DAG ids). + stage_dag_ids: tuple[tuple[Stage, str], ...] | None + + +@dataclass(frozen=True) +class RuntimeUnavailable: + """No usable runtime, and exactly why. + + ``addressed`` separates the two reasons: a bundle or a + ``HFLOW_AIRFLOW_URL`` IS pointed at a runtime but the addressing is + half-formed (a bundle mid-render, a URL with no dag id), versus nothing + pointed anywhere at all. /api/v1/config's ``runtime`` capability is that + flag, so "is a runtime addressed?" has one owner -- :func:`resolve_runtime` + -- rather than a second env-var probe beside it. + """ + + detail: str + addressed: bool + + +RuntimeResolution = ResolvedRuntime | RuntimeUnavailable + + +class IngestRequest(BaseModel): + uris: list[str] = Field(min_length=1) + profile: str = "full" + mode: str = IngestMode.BATCH.value + batch_count: int | None = Field(default=None, ge=1) + + +def find_bundle_directory(data_root: str) -> Path | None: + """The rendered local bundle this workspace addresses, if one exists. + + Mirrors the CLI's ``_resolve_bundle_dir`` probing: ``/runtime`` + first (bucket data roots have no local root, so only the fallback + applies), then ``./runtime``; a candidate counts only when its + ``docker-compose.yaml`` exists. Unlike the CLI there is no primary- + candidate fallback -- "no bundle anywhere" is a real answer here. + + The probe ideally belongs in the SDK, beside the renderer that writes the + marker file: a public ``hflow.runtime.find_bundle_directory(data_root)`` + would leave the CLI and this package as one call plus their differing + fallbacks, the way ``hflow.import_pipeline_application`` already does for + "address a pipeline by file". Until it lands, this is the mirror, and the + only thing that differs is the fallback. + """ + candidates = [Path(RUNTIME_BUNDLE_DIRECTORY_NAME)] + if not is_bucket_url(data_root): + candidates.insert(0, Path(data_root) / RUNTIME_BUNDLE_DIRECTORY_NAME) + for candidate in candidates: + if (candidate / "docker-compose.yaml").is_file(): + return candidate + return None + + +def runtime_addressed(resolution: RuntimeResolution) -> bool: + """Whether a runtime is ADDRESSED -- the /api/v1/config capability. + + Addressed, not reachable and not even fully resolvable: a bundle + mid-render or a URL exported without a dag id still means the operator + pointed this workspace at a runtime, and the Runs screen must stay + reachable so /runtime/status can name the variable to set. Derived from + the shared resolution so the capability and the status endpoint can never + tell two different stories. + """ + return isinstance(resolution, ResolvedRuntime) or resolution.addressed + + +def _stage_dag_ids(master_dag_id: str) -> tuple[tuple[Stage, str], ...]: + """(stage, sub-DAG id) pairs in stage-graph order. + + The sub-DAG ids derive from the master's id the same way the renderer + minted them (:func:`hflow.runtime.sub_dag_id_for_stage`), so there is one + owner of that mapping and no second bundle-manifest parser to drift from + the library's version-guarded :func:`hflow.runtime.load_bundle`. + """ + return tuple((stage, sub_dag_id_for_stage(master_dag_id, stage)) for stage in Stage) + + +def resolve_runtime(data_root: str) -> RuntimeResolution: + """One resolution pass: local bundle first, else the remote environment. + + Every failure mode (no bundle anywhere and no URL exported; a half-formed + bundle; a URL exported without dag id or credentials) becomes a + :class:`RuntimeUnavailable` whose detail names the fix -- never an + exception that would surface as a 500. + """ + bundle_directory = find_bundle_directory(data_root) + if bundle_directory is not None: + try: + bundle_paths = load_bundle(bundle_directory) + except (FileNotFoundError, ValueError) as error: + # A bundle directory IS an address, half-formed or not. + return RuntimeUnavailable(detail=str(error), addressed=True) + return ResolvedRuntime( + client=client_for_bundle(bundle_paths), + dag_id=bundle_paths.dag_id, + source="bundle", + airflow_web_url=bundle_paths.api_base_url, + stage_dag_ids=_stage_dag_ids(bundle_paths.dag_id), + ) + try: + endpoint = resolve_remote_endpoint() + except ValueError as error: + # A URL is exported but the resolution is incomplete; the message + # names exactly which HFLOW_AIRFLOW_* variable to set. + return RuntimeUnavailable(detail=str(error), addressed=True) + if endpoint is None: + return RuntimeUnavailable( + detail=( + "no ingest runtime addressed: no rendered bundle at " + f"{Path(data_root) / RUNTIME_BUNDLE_DIRECTORY_NAME} or ./runtime " + f"(run `hflow up`), and {AIRFLOW_URL_ENVIRONMENT_VARIABLE} is not set" + ), + addressed=False, + ) + return ResolvedRuntime( + client=client_for_endpoint(endpoint), + dag_id=endpoint.dag_id, + source="remote", + # Only a bundle records its own web address; guessing that a remote + # API base URL also serves the web UI would not be honest. + airflow_web_url=None, + stage_dag_ids=None, + ) + + +class RuntimeResolver: + """Per-launch cache around :func:`resolve_runtime` (see the TTL note).""" + + def __init__(self, data_root: str) -> None: + self._data_root = data_root + self._cached_resolution: RuntimeResolution | None = None + self._expires_at_monotonic = 0.0 + + def resolve(self) -> RuntimeResolution: + now_monotonic = time.monotonic() + if self._cached_resolution is None or now_monotonic >= self._expires_at_monotonic: + self._cached_resolution = resolve_runtime(self._data_root) + self._expires_at_monotonic = now_monotonic + RESOLUTION_CACHE_TTL_S + return self._cached_resolution + + +def optional_string(value: object) -> str | None: + """One Airflow JSON field as text, or None for anything else. + + Airflow's payloads are an OPEN contract: a field can be absent, null, or + (across versions) another type entirely. Parsing here means the response + models below never see a shape they would have to 500 over. + """ + return value if isinstance(value, str) else None + + +def _run_summary(run: dict[str, Any]) -> RuntimeRunSummary: + """One master dag run reduced to the fields the Runs page shows. + + The full ``conf`` rides along (it is the trigger's own input); everything + else Airflow returns stays server-side. + """ + conf = run.get("conf") + return RuntimeRunSummary( + dag_run_id=optional_string(run.get("dag_run_id")), + state=optional_string(run.get("state")), + logical_date=optional_string(run.get("logical_date")), + start_date=optional_string(run.get("start_date")), + end_date=optional_string(run.get("end_date")), + conf=conf if isinstance(conf, dict) else {}, + ) + + +def _stage_run_summary(run: dict[str, Any]) -> StageRunSummary: + return StageRunSummary( + dag_run_id=optional_string(run.get("dag_run_id")), + state=optional_string(run.get("state")), + start_date=optional_string(run.get("start_date")), + end_date=optional_string(run.get("end_date")), + ) + + +def resolved_runtime_or_refuse(resolver: RuntimeResolver) -> ResolvedRuntime: + """The addressed runtime, or the refusal every runtime-backed route owes. + + 409, not 404: an unaddressed (or half-formed) runtime conflicts with the + workspace's state, the same mapping an unconfigured pipeline uses. Shared + with the graph routes so both refuse identically, detail included. + """ + resolution = resolver.resolve() + if isinstance(resolution, RuntimeUnavailable): + raise HTTPException(status_code=409, detail=resolution.detail) + return resolution + + +def airflow_failure_refusal(error: AirflowClientError, *, source: RuntimeSource) -> HTTPException: + """One failed Airflow call as the 502 every proxying route answers with. + + 502, not 500: the fault is upstream, and the detail is the browser-safe + one :func:`client_error_detail` decides on. + """ + return HTTPException(status_code=502, detail=client_error_detail(error, source=source)) + + +def create_runtime_router(settings: ServerSettings, resolver: RuntimeResolver) -> APIRouter: + """Every runs-monitor route, closed over one launch's settings. + + The resolver is passed in (rather than built here) so the run-graph routes + in ``_graph`` share one addressing cache with this router. + """ + router = APIRouter(prefix="/api/v1") + + @router.get("/runtime/status") + def read_runtime_status() -> RuntimeStatusResponse: + resolution = resolver.resolve() + if isinstance(resolution, RuntimeUnavailable): + return RuntimeStatusResponse(available=False, detail=resolution.detail) + try: + health = resolution.client.health() + except AirflowClientError as error: + # Addressed but not answering (typical between `hflow up` runs): + # still an available:false ANSWER, with the addressing facts. + return RuntimeStatusResponse( + available=False, + detail=client_error_detail(error, source=resolution.source), + source=resolution.source, + airflow_web_url=resolution.airflow_web_url, + airflow_web_url_host_only=is_loopback_web_url(resolution.airflow_web_url), + dag_id=resolution.dag_id, + ) + registered: bool | None + try: + resolution.client.dag(resolution.dag_id) + registered = True + except AirflowClientError as error: + # 404 is the definitive "not registered (yet)"; anything else + # (auth, transient) leaves registration unknown, not false. + registered = False if error.status == 404 else None + return RuntimeStatusResponse( + available=True, + source=resolution.source, + airflow_web_url=resolution.airflow_web_url, + airflow_web_url_host_only=is_loopback_web_url(resolution.airflow_web_url), + dag_id=resolution.dag_id, + registered=registered, + health=RuntimeHealthComponents.model_validate( + { + component_name: health.components.get(component_name) + for component_name in _HEALTH_COMPONENT_NAMES + } + ), + ) + + @router.get("/runtime/runs") + def list_runtime_runs( + limit: int = Query(default=25, ge=1, le=100), + ) -> RuntimeRunsResponse: + runtime = resolved_runtime_or_refuse(resolver) + try: + # order_by="-id": Airflow truncates to `limit` in id order, so + # newest-first is the only ordering that shows recent activity. + master_runs = runtime.client.dag_runs(runtime.dag_id, limit=limit, order_by="-id") + except AirflowClientError as error: + raise airflow_failure_refusal(error, source=runtime.source) from error + stages: list[StageRecentRuns] | None = None + if runtime.stage_dag_ids is not None: + stages = [] + for stage_name, stage_dag_id in runtime.stage_dag_ids: + try: + recent_runs = runtime.client.dag_runs( + stage_dag_id, limit=_RECENT_STAGE_RUN_LIMIT, order_by="-id" + ) + except AirflowClientError: + # A stage sub-DAG that has not registered (or errored) is + # an empty strip, not a failed page. + recent_runs = [] + stages.append( + StageRecentRuns( + stage=stage_name, + dag_id=stage_dag_id, + recent=[_stage_run_summary(run) for run in recent_runs], + ) + ) + return RuntimeRunsResponse(runs=[_run_summary(run) for run in master_runs], stages=stages) + + @router.post("/runtime/ingest") + def trigger_ingest(request: IngestRequest) -> IngestTriggerResponse: + refuse_when_read_only(settings, disabled_actions="triggering ingest runs is") + uris = [uri.strip() for uri in request.uris] + if any(not uri for uri in uris): + raise HTTPException(status_code=400, detail="every uri must be a non-empty string") + # URIs resolve against the runtime's data root; absolute host paths and + # ../ escapes cannot work there, so refuse them before triggering -- + # the same guard `hflow ingest` enforces (src/hflow/cli.py). + for uri in uris: + if uri.startswith("/") or normpath(uri).startswith(".."): + raise HTTPException( + status_code=400, + detail=f"{uri!r} is not relative to the data root -- URIs are resolved " + "against the runtime's configured data root (e.g. " + "`episodes-in/run_0001.mcap`)", + ) + if request.profile not in RUN_PROFILES: + raise HTTPException( + status_code=400, + detail=f"unknown run profile {request.profile!r}; " + f"valid profiles: {sorted(RUN_PROFILES)}", + ) + try: + mode = IngestMode(request.mode) + except ValueError as error: + raise HTTPException( + status_code=400, + detail=f"unknown ingest mode {request.mode!r}; " + f"valid modes: {[known_mode.value for known_mode in IngestMode]}", + ) from error + runtime = resolved_runtime_or_refuse(resolver) + try: + # AirflowClient.ingest owns the trigger conf's shape (uris/profile/ + # mode/batch_count) for every caller -- CLI, UI, control plane -- + # so a client never rebuilds the dict itself. + trigger_response = runtime.client.ingest( + runtime.dag_id, + uris, + profile=request.profile, + online=mode is IngestMode.ONLINE, + batch_count=request.batch_count, + ) + except AirflowClientError as error: + raise airflow_failure_refusal(error, source=runtime.source) from error + return IngestTriggerResponse( + dag_run_id=optional_string(trigger_response.get("dag_run_id")), + state=optional_string(trigger_response.get("state")), + ) + + return router diff --git a/packages/hflow-server/src/hflow_server/_settings.py b/packages/hflow-server/src/hflow_server/_settings.py new file mode 100644 index 00000000..41bcf714 --- /dev/null +++ b/packages/hflow-server/src/hflow_server/_settings.py @@ -0,0 +1,93 @@ +"""Launch configuration for the workspace server, and what it refuses. + +The settings own the launch-wide facts the routers keep asking about -- +``read_only``, the port a launch may bind, and whether the data root is a +local directory -- so each fact is derived here once, beside the field, and +the refusal it maps to lives next to it rather than being hand-written per +router. +""" + +from dataclasses import dataclass +from pathlib import Path + +from fastapi import HTTPException + +from hflow.storage import LocalStorageRoot, parse_storage_root + +DEFAULT_HOST = "127.0.0.1" +# "HFLO" on a phone keypad; mirrored by the core CLI's DEFAULT_SERVER_PORT. +DEFAULT_PORT = 4356 + +# The TCP ports a launch may ask for, the same range (and the same reason for +# excluding 0) that ``hflow.runtime``'s RuntimeConfig enforces for the +# bundle's api port: 0 means "any free port" to bind(2), but this value is +# interpolated into the URL `serve` prints and hands to the browser, and +# http://127.0.0.1:0 is not dialable. +MIN_PORT = 1 +MAX_PORT = 65535 + + +@dataclass(frozen=True) +class ServerSettings: + """One ``hflow serve`` launch, fully parsed. + + ``data_root`` stays a string: it may be a local path or a bucket URL, and + ``hflow.workspace.Workspace.parse`` owns that distinction. ``assets_dir`` + overrides where the built SPA is served from (tests and frontend dev). + + Nothing here is a credential: the server authenticates nobody, so ``host`` + is the whole access-control story (see docs/SERVE.md, "Trust posture"). + """ + + data_root: str + host: str = DEFAULT_HOST + port: int = DEFAULT_PORT + assets_dir: Path | None = None + open_browser: bool = True + # When true, every mutating endpoint (manifest pinning, saved-query + # writes, ingest triggering) answers 403 and /api/v1/config reports it + # (CLI flag: --read-only). + read_only: bool = False + # ``path/to/pipeline.py[:app]`` (CLI flag: --pipeline). The server + # imports -- EXECUTES -- this file exactly once at startup to serve + # /api/v1/pipeline; ``None`` leaves that capability off. + pipeline: str | None = None + + def __post_init__(self) -> None: + # A range invariant of the field, checked where the field is set, so a + # library caller building ServerSettings directly gets the same answer as + # the command line. Left to bind(2) instead, an out-of-range port + # surfaces as an OverflowError from inside the port probe, and port 0 + # binds fine while printing a URL nobody can open. + if not MIN_PORT <= self.port <= MAX_PORT: + raise ValueError(f"port {self.port!r} is not in {MIN_PORT}-{MAX_PORT}") + + +def local_data_root_or_none(data_root: str) -> Path | None: + """The data root as a local directory, or ``None`` for a bucket URL. + + The ONE derivation of "this workspace's files are reachable as paths" -- + the precondition media serving, the sidecar, and pinned manifest files all + share. Each caller decides what to do without one (``_media`` and + ``_sidecar`` refuse 501 in their own error type; /api/v1/config turns it + into capability flags the frontend can hide affordances behind), but none + of them re-derives the predicate. + """ + parsed_root = parse_storage_root(data_root) + return parsed_root.path if isinstance(parsed_root, LocalStorageRoot) else None + + +def refuse_when_read_only(settings: ServerSettings, *, disabled_actions: str) -> None: + """The 403 every mutating route owes a read-only launch. + + One owner for the status and the sentence, shared by the curation studio + and the runs monitor; only the named actions differ, so a third mutating + router cannot invent a third wording or a different code. + ``disabled_actions`` carries its own agreeing verb ("... is" / "... are") + because the routes name one action or several. + """ + if settings.read_only: + raise HTTPException( + status_code=403, + detail=f"this workspace UI is running read-only; {disabled_actions} disabled", + ) diff --git a/packages/hflow-server/src/hflow_server/_sidecar.py b/packages/hflow-server/src/hflow_server/_sidecar.py new file mode 100644 index 00000000..19c23e2c --- /dev/null +++ b/packages/hflow-server/src/hflow_server/_sidecar.py @@ -0,0 +1,217 @@ +"""Curation sidecar state: ``/curation/state.json``, owned here. + +Workspace convention: curation persists exactly two kinds of durable state -- +saved queries and the pinned-manifest registry -- in ONE JSON sidecar file, +``/curation/state.json``. Together with the manifest files under +``/manifests/``, that sidecar is the ONLY thing this server ever +writes into a workspace. + +It sits under ``curation/`` rather than under any client's name because the +content is the operator's, not a browser's: saved queries and pinned +manifests belong to the workspace, and a second client (another UI, a +script) reads the same file. + +Two rules hold at this boundary: + +- Every write is atomic: the payload lands in a temp file beside the target + and is moved into place with ``os.replace`` (via ``Path.replace``), so a + crash never leaves a torn file. Concurrent writers are last-writer-wins, + which a single-operator local tool accepts. +- Every read parses loudly: a payload that is not JSON, carries a + ``state_version`` this build does not speak, or holds a malformed entry is + refused with an error NAMING THE FILE -- never silently coerced, dropped, + or rewritten (the state is the user's curation record). + +The stored entries ARE the published contract models +(:class:`hflow_server._contract.SavedQueryEntry` and +:class:`~hflow_server._contract.PinnedManifestEntry`): the file a user can read +with ``jq`` and the payload the API serves are one shape with one owner, so +they cannot drift apart. Changing either therefore changes this file's +format, which ``STATE_VERSION`` guards. +""" + +import json +import uuid +from dataclasses import dataclass +from pathlib import Path + +from hflow_server._contract import CheckCoverageEntry, PinnedManifestEntry, SavedQueryEntry +from hflow_server._settings import local_data_root_or_none + +STATE_VERSION = 1 +SIDECAR_DIRECTORY_NAME = "curation" +SIDECAR_FILE_NAME = "state.json" + + +class SidecarError(Exception): + """One refusal to read or write the sidecar, carrying its HTTP mapping.""" + + def __init__(self, status_code: int, detail: str) -> None: + super().__init__(detail) + self.status_code = status_code + self.detail = detail + + +@dataclass(frozen=True) +class SidecarState: + """The whole parsed sidecar; a missing file reads as this default.""" + + saved_queries: tuple[SavedQueryEntry, ...] = () + manifests: tuple[PinnedManifestEntry, ...] = () + + +def local_data_root(data_root: str) -> Path: + """The data root as a local directory; sidecar and manifest writes need one.""" + local_root = local_data_root_or_none(data_root) + if local_root is None: + raise SidecarError( + 501, + "saved queries and pinned manifests need a local data root; " + "bucket-backed workspaces are not supported by the curation studio yet", + ) + return local_root + + +def sidecar_state_file(data_root: str) -> Path: + return local_data_root(data_root) / SIDECAR_DIRECTORY_NAME / SIDECAR_FILE_NAME + + +def load_sidecar_state(data_root: str) -> SidecarState: + """The parsed sidecar; empty when never written, loud on anything corrupt.""" + state_file = sidecar_state_file(data_root) + try: + raw_payload = state_file.read_text(encoding="utf-8") + except FileNotFoundError: + return SidecarState() + except OSError as error: + raise SidecarError(500, f"cannot read curation state file {state_file}: {error}") from error + return _parsed_state(raw_payload, state_file) + + +def store_sidecar_state(data_root: str, state: SidecarState) -> None: + """Atomically replace the sidecar with ``state`` (temp file + os.replace).""" + state_file = sidecar_state_file(data_root) + state_file.parent.mkdir(parents=True, exist_ok=True) + # by_alias: the stored keys are the published ones ("id", not "query_id"). + payload = json.dumps( + { + "state_version": STATE_VERSION, + "saved_queries": [entry.model_dump(by_alias=True) for entry in state.saved_queries], + "manifests": [entry.model_dump(by_alias=True) for entry in state.manifests], + }, + indent=2, + ) + temporary_file = state_file.parent / f".{SIDECAR_FILE_NAME}.{uuid.uuid4().hex}.tmp" + try: + temporary_file.write_text(payload + "\n", encoding="utf-8") + # Path.replace is os.replace: atomic on one filesystem, so a reader + # (or a crash) sees the old complete state or the new one, never a mix. + temporary_file.replace(state_file) + except OSError as error: + temporary_file.unlink(missing_ok=True) + raise SidecarError( + 500, f"cannot write curation state file {state_file}: {error}" + ) from error + + +def _refused(state_file: Path, problem: str) -> SidecarError: + return SidecarError( + 500, f"corrupt curation state file {state_file}: {problem}; fix or remove the file" + ) + + +def _parsed_state(raw_payload: str, state_file: Path) -> SidecarState: + try: + parsed = json.loads(raw_payload) + except json.JSONDecodeError as error: + raise _refused(state_file, f"not valid JSON ({error})") from error + if not isinstance(parsed, dict): + raise _refused(state_file, "expected a JSON object") + found_version = parsed.get("state_version") + if found_version != STATE_VERSION: + # 409, not 500: the same mapping _connections gives a catalog written + # in a format version this build cannot read -- the state is there and + # intact, this build just cannot speak to it, which is a conflict with + # the workspace rather than a fault of this server. A file that is + # corrupt (rather than merely newer) keeps the 500 _refused gives it. + raise SidecarError( + 409, + f"curation state file {state_file} has state_version {found_version!r}; " + f"this build reads version {STATE_VERSION!r}", + ) + saved_queries = tuple( + _parsed_saved_query(entry, state_file) + for entry in _entry_list(parsed, "saved_queries", state_file) + ) + manifests = tuple( + _parsed_manifest(entry, state_file) + for entry in _entry_list(parsed, "manifests", state_file) + ) + return SidecarState(saved_queries=saved_queries, manifests=manifests) + + +def _entry_list(parsed: dict[str, object], key: str, state_file: Path) -> list[dict[str, object]]: + entries = parsed.get(key, []) + if not isinstance(entries, list) or not all(isinstance(entry, dict) for entry in entries): + raise _refused(state_file, f"{key!r} must be a list of objects") + return entries + + +def _string_field(entry: dict[str, object], key: str, state_file: Path) -> str: + value = entry.get(key) + if not isinstance(value, str): + raise _refused(state_file, f"entry field {key!r} must be a string, got {value!r}") + return value + + +def _int_field(entry: dict[str, object], key: str, state_file: Path) -> int: + value = entry.get(key) + if isinstance(value, bool) or not isinstance(value, int): + raise _refused(state_file, f"entry field {key!r} must be an integer, got {value!r}") + return value + + +def _float_field(entry: dict[str, object], key: str, state_file: Path) -> float: + value = entry.get(key) + if isinstance(value, bool) or not isinstance(value, int | float): + raise _refused(state_file, f"entry field {key!r} must be a number, got {value!r}") + return float(value) + + +def _parsed_saved_query(entry: dict[str, object], state_file: Path) -> SavedQueryEntry: + # Field-by-field on purpose: a model_validate refusal would name pydantic's + # own error shape, not this file and the fix for it. + return SavedQueryEntry( + query_id=_string_field(entry, "id", state_file), + name=_string_field(entry, "name", state_file), + sql=_string_field(entry, "sql", state_file), + updated_at=_string_field(entry, "updated_at", state_file), + ) + + +def _parsed_manifest(entry: dict[str, object], state_file: Path) -> PinnedManifestEntry: + raw_coverage = entry.get("coverage", []) + if not isinstance(raw_coverage, list) or not all( + isinstance(coverage_entry, dict) for coverage_entry in raw_coverage + ): + raise _refused(state_file, "'coverage' must be a list of objects") + coverage = [ + CheckCoverageEntry( + check_name=_string_field(coverage_entry, "check_name", state_file), + episodes_ran=_int_field(coverage_entry, "episodes_ran", state_file), + total_episodes=_int_field(coverage_entry, "total_episodes", state_file), + fraction=_float_field(coverage_entry, "fraction", state_file), + ) + for coverage_entry in raw_coverage + ] + return PinnedManifestEntry( + manifest_id=_string_field(entry, "id", state_file), + name=_string_field(entry, "name", state_file), + description=_string_field(entry, "description", state_file), + sql=_string_field(entry, "sql", state_file), + manifest_path=_string_field(entry, "manifest_path", state_file), + row_count=_int_field(entry, "row_count", state_file), + total_episodes=_int_field(entry, "total_episodes", state_file), + coverage=coverage, + created_at=_string_field(entry, "created_at", state_file), + ) diff --git a/packages/hflow-server/src/hflow_server/server.py b/packages/hflow-server/src/hflow_server/server.py new file mode 100644 index 00000000..430e735f --- /dev/null +++ b/packages/hflow-server/src/hflow_server/server.py @@ -0,0 +1,472 @@ +"""The FastAPI app (pure, testable) and the ``hflow serve`` server entry point. + +``create_app`` builds the whole API plus SPA serving from one +:class:`ServerSettings` -- no sockets, no side effects. ``serve`` adds the launch +behavior: pick a free port, print the URL, open the browser, run uvicorn. The +server authenticates nobody: whoever can reach the bound address gets the +whole API (docs/SERVE.md, "Trust posture"). The only workspace files this package +ever writes are the curation studio's: immutable pinned manifests under +``/manifests/`` and the ``/curation/state.json`` sidecar (both +refused when ``settings.read_only``); the server never mints workspace +identity. +""" + +import importlib.resources +import os +import socket +import threading +import webbrowser +from pathlib import Path +from typing import Annotated + +import uvicorn +from fastapi import Depends, FastAPI, HTTPException, Query +from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response +from starlette.datastructures import Headers +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +import hflow +from hflow.format import CATALOG_FORMAT_VERSION +from hflow.steps import RUN_PROFILES, IngestMode +from hflow.workspace import Workspace +from hflow_server import _catalog, _connections, _curation, _graph, _media, _pipeline, _runtime +from hflow_server._contract import ( + BINARY_FILE_RESPONSES, + EpisodeDossierResponse, + EpisodeFacetsResponse, + EpisodePageResponse, + EpisodeStatsResponse, + EpisodeStatus, + EpisodeTimelineResponse, + HealthResponse, + ListingOrder, + SuccessFilterValue, + WorkspaceCapabilities, + WorkspaceConfigResponse, +) +from hflow_server._settings import MAX_PORT, ServerSettings, local_data_root_or_none + +ASSETS_ENVIRONMENT_VARIABLE = "HFLOW_UI_ASSETS" + +_PORT_RETRY_ATTEMPTS = 10 + +# A blanket cap on request-body size: comfortably above the curation studio's +# own per-field limits (a 100k SQL body plus JSON overhead), but a hard stop +# on an unbounded POST -- the sidecar is the one file this server writes outside +# manifests/, so nothing it persists should be able to grow without limit. +_MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024 + + +def _declared_request_body_bytes(scope: Scope) -> int | None: + """The request's Content-Length, or None when it declares none (or lies).""" + declared = Headers(scope=scope).get("content-length") + if declared is None: + return None + try: + return int(declared) + except ValueError: + return None + + +class RequestBodySizeLimitMiddleware: + """Refuses any request body over the size cap with a 413. + + Pure ASGI, and it counts the bytes rather than trusting a header: a + declared ``Content-Length`` is only a claim, and a chunked request makes + none at all, so a header-only check let exactly the thing this middleware + exists to stop -- an unbounded POST buffered whole before any validation + runs -- through by simply omitting the header. A declared length over the + cap is still refused up front, without reading a byte. + + The body is read HERE and replayed downstream rather than counted inside + a wrapped receive channel: an oversized-body error raised from inside the + channel gets rewritten by whatever was reading it (FastAPI's body reader + turns any exception but its own into a generic 400, and an intervening + ``BaseHTTPMiddleware`` collapses even that into an exception group), which + would leave the cap enforced but unsayable. What is buffered is bounded by + the cap itself -- the first chunk that crosses it ends the request -- and + every route on this API reads its whole body anyway, so nothing that would + otherwise have streamed is being held here. + """ + + def __init__(self, app: ASGIApp) -> None: + self._app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if scope["type"] != "http": + await self._app(scope, receive, send) + return + declared_body_bytes = _declared_request_body_bytes(scope) + if declared_body_bytes is not None and declared_body_bytes > _MAX_REQUEST_BODY_BYTES: + await _refuse_oversized_body(scope, receive, send) + return + body_messages = await _capped_body_messages(receive) + if body_messages is None: + await _refuse_oversized_body(scope, receive, send) + return + await self._app(scope, _replaying_receive(body_messages, receive), send) + + +async def _capped_body_messages(receive: Receive) -> list[Message] | None: + """One request's body messages, or ``None`` once they exceed the cap.""" + body_messages: list[Message] = [] + received_body_bytes = 0 + while True: + message = await receive() + body_messages.append(message) + if message["type"] != "http.request": + # http.disconnect: no body is coming, and none ever will. + return body_messages + received_body_bytes += len(message.get("body", b"")) + if received_body_bytes > _MAX_REQUEST_BODY_BYTES: + return None + if not message.get("more_body", False): + return body_messages + + +def _replaying_receive(body_messages: list[Message], receive: Receive) -> Receive: + """A receive channel handing back the read body, then the real channel.""" + unread_messages = iter(body_messages) + + async def replaying_receive() -> Message: + unread = next(unread_messages, None) + # Past the buffered body the real channel takes over, so a downstream + # reader still sees the eventual http.disconnect. + return unread if unread is not None else await receive() + + return replaying_receive + + +async def _refuse_oversized_body(scope: Scope, receive: Receive, send: Send) -> None: + await JSONResponse({"detail": "request body too large"}, status_code=413)(scope, receive, send) + + +_FRONTEND_PLACEHOLDER_PAGE = """ + + HFlow workspace API + +

HFlow workspace API

+

No frontend bundle is installed here. The JSON API is live under + /api/v1, and its OpenAPI schema is at + /api/openapi.json — that schema is the product surface: + everything a UI can show is reachable from it, so any client can be built + against it without touching this package.

+

To serve your own build, point the HFLOW_UI_ASSETS + environment variable at a directory containing an + index.html, or pass assets_dir to + ServerSettings. A bundle packaged inside hflow_server + is picked up automatically.

+ + +""" + + +def parse_episode_list_filters( + task: Annotated[list[str] | None, Query()] = None, + operator: Annotated[list[str] | None, Query()] = None, + embodiment: Annotated[list[str] | None, Query()] = None, + status: Annotated[EpisodeStatus | None, Query()] = None, + success: Annotated[SuccessFilterValue | None, Query()] = None, + search: Annotated[str | None, Query()] = None, +) -> _catalog.EpisodeListFilters: + """The filter params /episodes and /episodes/stats BOTH accept. + + One owner for the pair: the two endpoints must describe the same rows, so + a filter added here reaches the listing and its distributions together -- + they cannot drift into accepting different query strings. + """ + return _catalog.EpisodeListFilters( + tasks=tuple(task or ()), + operators=tuple(operator or ()), + embodiments=tuple(embodiment or ()), + status=status, + success=success, + search=search, + ) + + +EpisodeListFilterParams = Annotated[ + _catalog.EpisodeListFilters, Depends(parse_episode_list_filters) +] + + +def create_app(settings: ServerSettings) -> FastAPI: + """The whole workspace server as a plain ASGI app.""" + # Late import: hflow_server/__init__ imports this module, so the package + # attribute exists only once init finished -- which any create_app call is. + from hflow_server import __version__ as hflow_server_version + + application = FastAPI( + title="HFlow workspace API", + version=hflow_server_version, + # No Swagger or ReDoc HTML page. Both of FastAPI's built-in pages load + # their JS and CSS from cdn.jsdelivr.net, which would break the offline + # promise this UI makes (docs/SERVE.md, "Trust posture": no CDN, no + # outbound requests) and would run third-party script same-origin with + # this workspace's API. The generated schema is served as JSON instead + # -- that IS the contract, and any local OpenAPI viewer or client + # generator reads it. test_ui_offline_posture.py pins this. + docs_url=None, + openapi_url="/api/openapi.json", + redoc_url=None, + ) + # Starlette runs middleware outermost-first in REVERSE registration order, + # so the body-size cap being registered last is what makes it outermost: + # an oversized POST is refused before routing touches it. There is no + # request guard here -- this server authenticates nobody (docs/SERVE.md, + # "Trust posture") -- and if one is ever added, this is where it goes, in + # front of the routes and behind the cap. + application.add_middleware(RequestBodySizeLimitMiddleware) + + # --pipeline is imported -- EXECUTED -- exactly once, here at app + # construction; the outcome (the live App, or the remembered failure) is + # what /api/v1/pipeline and the config capability report for this launch. + pipeline_state = _pipeline.load_pipeline_state(settings.pipeline) + # One runtime resolver per launch, shared by the runs monitor and the + # graph routes so both read the same briefly-cached addressing. + runtime_resolver = _runtime.RuntimeResolver(settings.data_root) + + @application.get("/api/v1/health") + def read_health() -> HealthResponse: + return HealthResponse(ok=True) + + @application.get("/api/v1/config") + def read_config() -> WorkspaceConfigResponse: + workspace = Workspace.parse(settings.data_root) + try: + identity = workspace.identity() + except ValueError: + # A corrupt identity marker must not stop the server from booting: the + # id is informational here, and this surface never mints one. + identity = None + workspace_is_local = local_data_root_or_none(settings.data_root) is not None + return WorkspaceConfigResponse( + mode="local", + read_only=settings.read_only, + hflow_version=hflow.__version__, + hflow_server_version=hflow_server_version, + data_root=settings.data_root, + workspace_id=identity.workspace_id if identity is not None else None, + capabilities=WorkspaceCapabilities( + catalog=_catalog_marker_readable(workspace), + # Media bytes and the studio's writes both need the workspace + # reachable as local paths; they are separate flags because + # bucket support will arrive for them separately. + media=workspace_is_local, + curation=workspace_is_local, + # Addressed (bundle dir or HFLOW_AIRFLOW_URL), not necessarily + # reachable -- /runtime/status owns liveness, and it is also + # the one endpoint that serves the Airflow deep-link base. + runtime=_runtime.runtime_addressed(runtime_resolver.resolve()), + pipeline=isinstance(pipeline_state, _pipeline.PipelineLoaded), + ), + # The trigger form's vocabularies, served so the frontend never + # hardcodes them (hflow.steps stays the one owner). + run_profiles=list(RUN_PROFILES), + ingest_modes=[mode.value for mode in IngestMode], + ) + + @application.get("/api/v1/episodes") + def list_episodes( + filters: EpisodeListFilterParams, + order_by: Annotated[str, Query()] = "recorded_at", + order: Annotated[ListingOrder, Query()] = "desc", + limit: Annotated[int, Query(ge=1, le=500)] = 50, + offset: Annotated[int, Query(ge=0)] = 0, + ) -> EpisodePageResponse: + with _connections.opened_workspace_connection_or_refuse(settings.data_root) as connection: + try: + return _catalog.query_episode_page( + connection, + filters, + order_by=order_by, + descending=order == "desc", + limit=limit, + offset=offset, + ) + except _catalog.UnknownOrderColumnError as error: + raise HTTPException(status_code=400, detail=str(error)) from error + + @application.get("/api/v1/episodes/facets") + def read_episode_facets() -> EpisodeFacetsResponse: + with _connections.opened_workspace_connection_or_refuse(settings.data_root) as connection: + return _catalog.query_episode_facets(connection) + + # Registered before the {episode_id} route below so the literal path + # segment "stats" can never be read as an episode id. + @application.get("/api/v1/episodes/stats") + def read_episode_stats(filters: EpisodeListFilterParams) -> EpisodeStatsResponse: + with _connections.opened_workspace_connection_or_refuse(settings.data_root) as connection: + return _catalog.query_episode_stats(connection, filters) + + @application.get("/api/v1/episodes/{episode_id}") + def read_episode(episode_id: str) -> EpisodeDossierResponse: + with _connections.opened_workspace_connection_or_refuse(settings.data_root) as connection: + dossier = _catalog.query_episode_dossier( + connection, episode_id, data_root=settings.data_root + ) + if dossier is None: + raise HTTPException( + status_code=404, detail=f"no episode {episode_id!r} in this catalog" + ) + return dossier + + @application.get("/api/v1/episodes/{episode_id}/timeline") + def read_episode_timeline(episode_id: str) -> EpisodeTimelineResponse: + with _connections.opened_workspace_connection_or_refuse(settings.data_root) as connection: + timeline = _catalog.query_episode_timeline(connection, episode_id) + if timeline is None: + raise HTTPException( + status_code=404, detail=f"no episode {episode_id!r} in this catalog" + ) + return timeline + + @application.get( + "/api/v1/episodes/{episode_id}/media/{artifact_name:path}", + response_class=FileResponse, + responses=BINARY_FILE_RESPONSES, + ) + def read_episode_media(episode_id: str, artifact_name: str) -> FileResponse: + with _connections.opened_workspace_connection_or_refuse(settings.data_root) as connection: + media_uri = _catalog.find_media_uri(connection, episode_id, artifact_name) + if media_uri is None: + raise HTTPException( + status_code=404, + detail=f"episode {episode_id!r} has no media artifact named {artifact_name!r}", + ) + return _served_file_response_or_refuse(media_uri, settings.data_root) + + @application.get( + "/api/v1/episodes/{episode_id}/canonical", + response_class=FileResponse, + responses=BINARY_FILE_RESPONSES, + ) + def read_episode_canonical(episode_id: str) -> FileResponse: + with _connections.opened_workspace_connection_or_refuse(settings.data_root) as connection: + canonical_uri = _catalog.find_canonical_uri(connection, episode_id) + if canonical_uri is None: + raise HTTPException( + status_code=404, detail=f"no episode {episode_id!r} in this catalog" + ) + return _served_file_response_or_refuse(canonical_uri, settings.data_root) + + # The curation studio, runs monitor, pipeline and visualization routes -- + # included BEFORE the SPA catch-all below so they win route matching. + application.include_router(_curation.create_curation_router(settings)) + application.include_router(_runtime.create_runtime_router(settings, runtime_resolver)) + application.include_router(_pipeline.create_pipeline_router(settings, pipeline_state)) + application.include_router(_graph.create_graph_router(pipeline_state, runtime_resolver)) + + @application.get("/{requested_path:path}", include_in_schema=False) + def serve_spa(requested_path: str) -> Response: + return _spa_response(settings, requested_path) + + return application + + +def _catalog_marker_readable(workspace: Workspace) -> bool: + """Whether the catalog's format marker is present and this build reads it.""" + try: + found_version = workspace.catalog_root.read_bytes("format_version").decode().strip() + except (OSError, UnicodeDecodeError): + return False + return found_version == CATALOG_FORMAT_VERSION + + +def _served_file_response_or_refuse(uri: str, data_root: str) -> FileResponse: + try: + resolved_file = _media.resolve_served_file(uri, data_root=data_root) + except _media.MediaResolutionError as error: + raise _media.media_refusal(error) from error + return _media.served_file_response(resolved_file) + + +def _assets_directory(settings: ServerSettings) -> Path | None: + """Where the built SPA lives: explicit setting, env override, then the wheel.""" + if settings.assets_dir is not None: + return settings.assets_dir + environment_override = os.environ.get(ASSETS_ENVIRONMENT_VARIABLE) + if environment_override: + return Path(environment_override) + # This package ships as a plain directory wheel (uv_build, never zipped), + # so the packaged resource is always a real filesystem path. + packaged_static = Path(str(importlib.resources.files("hflow_server").joinpath("static"))) + return packaged_static if packaged_static.is_dir() else None + + +def _spa_response(settings: ServerSettings, requested_path: str) -> Response: + if requested_path == "api" or requested_path.startswith("api/"): + raise HTTPException(status_code=404, detail="unknown API path") + assets_directory = _assets_directory(settings) + if assets_directory is not None and requested_path: + asset_response = _contained_asset_response(assets_directory, requested_path) + if asset_response is not None: + return asset_response + final_segment = requested_path.rsplit("/", 1)[-1] + if "." in final_segment: + # Looks like a file: a missing asset is a 404, never index.html. + raise HTTPException(status_code=404, detail="no such asset") + if assets_directory is not None: + index_file = assets_directory / "index.html" + if index_file.is_file(): + return FileResponse(index_file) + return HTMLResponse(_FRONTEND_PLACEHOLDER_PAGE) + + +def _contained_asset_response(assets_directory: Path, requested_path: str) -> FileResponse | None: + resolved_assets_directory = assets_directory.resolve() + try: + resolved_candidate = (assets_directory / requested_path).resolve(strict=True) + except (OSError, ValueError): + return None + if not resolved_candidate.is_relative_to(resolved_assets_directory): + # Traversal outside the assets tree is answered as if absent. + return None + if not resolved_candidate.is_file(): + return None + return FileResponse(resolved_candidate) + + +def serve(settings: ServerSettings) -> None: + """Run the workspace server: free port, printed URL, browser, uvicorn.""" + application = create_app(settings) + chosen_port = _first_free_port(settings.host, settings.port) + if chosen_port != settings.port: + # flush=True throughout: the URL must reach a piped stdout (tee, a + # supervisor's log) before the blocking uvicorn.run call. + print( + f"hflow serve: port {settings.port} is taken; serving on port {chosen_port} instead", + flush=True, + ) + url_host = "127.0.0.1" if settings.host == "0.0.0.0" else settings.host + workspace_url = f"http://{url_host}:{chosen_port}/" + print(f"hflow serve: serving {settings.data_root} at {workspace_url}", flush=True) + if settings.open_browser: + # uvicorn.run blocks this thread; a short timer opens the browser + # once the server has had time to bind. + browser_timer = threading.Timer(1.0, webbrowser.open, args=[workspace_url]) + browser_timer.daemon = True + browser_timer.start() + # uvicorn's stock logging config: the access line's query string carries + # episode filters and paging, which are useful when debugging a request + # and are not credentials -- this server has none. + uvicorn.run(application, host=settings.host, port=chosen_port, log_level="info") + + +def _first_free_port(host: str, preferred_port: int) -> int: + """The preferred port, or the first free one in the handful above it. + + ``preferred_port`` is already in ``MIN_PORT..MAX_PORT`` (``ServerSettings`` + parses it there), and the retry window is clipped to MAX_PORT so walking + off the top of the range refuses with the same sentence as an occupied + range rather than with bind(2)'s OverflowError. + """ + last_candidate_port = min(preferred_port + _PORT_RETRY_ATTEMPTS - 1, MAX_PORT) + for candidate_port in range(preferred_port, last_candidate_port + 1): + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe_socket: + try: + probe_socket.bind((host, candidate_port)) + except OSError: + continue + return candidate_port + raise RuntimeError(f"no free port between {preferred_port} and {last_candidate_port} on {host}") diff --git a/packages/hflow-server/src/hflow_server/static/assets/index-3ctZsjaJ.js b/packages/hflow-server/src/hflow_server/static/assets/index-3ctZsjaJ.js new file mode 100644 index 00000000..8294e011 --- /dev/null +++ b/packages/hflow-server/src/hflow_server/static/assets/index-3ctZsjaJ.js @@ -0,0 +1,64 @@ +var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;li[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},u=new class extends l{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},d={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},f=new class{#e=d;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function p(e){setTimeout(e,0)}var m=typeof window>`u`||`Deno`in globalThis;function h(){}function g(e,t){return typeof e==`function`?e(t):e}function _(e){return typeof e==`number`&&e>=0&&e!==1/0}function v(e,t){return Math.max(e+(t||0)-Date.now(),0)}function y(e,t){return typeof e==`function`?e(t):e}function b(e,t){return typeof e==`function`?e(t):e}function x(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==C(o,t.options))return!1}else if(!T(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function S(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(w(t.options.mutationKey)!==w(a))return!1}else if(!T(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function C(e,t){return(t?.queryKeyHashFn||w)(e)}function w(e){return JSON.stringify(e,(e,t)=>A(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function T(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){for(let n=0;n500)return t;let r=k(e)&&k(t);if(!r&&!(A(e)&&A(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l{f.setTimeout(t,e)})}function N(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:D(e,t)}function P(e){return e}function ee(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function te(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ne=Symbol();function re(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===ne?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function ie(e,t){return typeof e==`function`?e(...t):!!e}function F(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var ae=(()=>{let e=()=>m;return{isServer(){return e()},setIsServer(t){e=t}}})();function oe(){let e,t,n=new Promise((n,r)=>{e=n,t=r});n.status=`pending`,n.catch(()=>{});function r(e){Object.assign(n,e),delete n.resolve,delete n.reject}return n.resolve=t=>{r({status:`fulfilled`,value:t}),e(t)},n.reject=e=>{r({status:`rejected`,reason:e}),t(e)},n}var se=p;function ce(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=se,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var le=ce(),ue=new class extends l{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function de(e){return Math.min(1e3*2**e,3e4)}function fe(e){return(e??`online`)!==`online`||ue.isOnline()}var pe=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function me(e){let t=!1,n=0,r,i=oe(),a=()=>i.status!==`pending`,o=t=>{if(!a()){let n=new pe(t);p(n),e.onCancel?.(n)}},s=()=>{t=!0},c=()=>{t=!1},l=()=>u.isFocused()&&(e.networkMode===`always`||ue.isOnline())&&e.canRun(),d=()=>fe(e.networkMode)&&e.canRun(),f=e=>{a()||(r?.(),i.resolve(e))},p=e=>{a()||(r?.(),i.reject(e))},m=()=>new Promise(t=>{r=e=>{(a()||l())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,a()||e.onContinue?.()}),h=()=>{if(a())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(f).catch(r=>{if(a())return;let i=e.retry??(ae.isServer()?0:3),o=e.retryDelay??de,s=typeof o==`function`?o(n,r):o,c=i===!0||typeof i==`number`&&nl()?void 0:m()).then(()=>{t?p(r):h()})})};return{promise:i,status:()=>i.status,cancel:o,continue:()=>(r?.(),i),cancelRetry:s,continueRetry:c,canStart:d,start:()=>(d()?h():m().then(h),i)}}var he=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),_(this.gcTime)&&(this.#e=f.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(ae.isServer()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(f.clearTimeout(this.#e),this.#e=void 0)}};function ge(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{F(e,()=>t.signal,()=>n=!0)},u=re(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?te:ee;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?ve:_e,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:_e(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(ct.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function _e(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function ve(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}var ye=class extends he{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Se(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Se(this.options);e.data!==void 0&&(this.setState(xe(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=N(this.state.data,e,this.options);return this.#l({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#l({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(h).catch(h):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(e=>b(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ne||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>y(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!v(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){this.observers.includes(e)&&(this.observers=this.observers.filter(t=>t!==e),this.observers.length||(this.#a&&(this.#s||this.#c()?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}#c(){return this.state.fetchStatus===`paused`&&this.state.status===`pending`}invalidate(){this.state.isInvalidated||this.#l({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=re(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?ge(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#l({type:`fetch`,meta:a.fetchOptions?.meta}),this.#a=me({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof pe&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#l({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#l({type:`pause`})},onContinue:()=>{this.#l({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await this.#a.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof pe){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#l({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.scheduleGc()}}#l(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...be(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...xe(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),le.batch(()=>{this.observers.forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function be(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:fe(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function xe(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Se(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Ce=class extends l{constructor(e,t){super(),this.options=t,this.#e=e,this.#s=null,this.#o=oe(),this.bindMethods(),this.setOptions(t)}#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Te(this.#t,this.options)?this.#h():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ee(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ee(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof b(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!O(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&De(this.#t,n,this.options,t)&&this.#h(),this.updateResult(),r&&(this.#t!==n||b(this.options.enabled,this.#t)!==b(t.enabled,this.#t)||y(this.options.staleTime,this.#t)!==y(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||b(this.options.enabled,this.#t)!==b(t.enabled,this.#t)||i!==this.#p)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return ke(this,n)&&(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),n===`promise`&&(this.trackProp(`data`),!this.options.experimental_prefetchInRender&&this.#o.status===`pending`&&this.#o.reject(Error(`experimental_prefetchInRender feature flag is not enabled`))),Reflect.get(e,n))})}trackProp(e){this.#m.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t);return n.fetch().then(()=>this.createResult(n,t))}fetch(e){return this.#h({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#h(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(h)),t}#g(){this.#b();let e=y(this.options.staleTime,this.#t);if(ae.isServer()||this.#r.isStale||!_(e))return;let t=v(this.#r.dataUpdatedAt,e)+1;this.#d=f.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return(typeof this.options.refetchInterval==`function`?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(e){this.#x(),this.#p=e,!(ae.isServer()||b(this.options.enabled,this.#t)===!1||!_(this.#p)||this.#p===0)&&(this.#f=f.setInterval(()=>{(this.options.refetchIntervalInBackground||u.isFocused())&&this.#h()},this.#p))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#d!==void 0&&(f.clearTimeout(this.#d),this.#d=void 0)}#x(){this.#f!==void 0&&(f.clearInterval(this.#f),this.#f=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Te(e,t),o=i&&De(e,n,t,r);(a||o)&&(l={...l,...be(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#u?.state.data,this.#u):t.placeholderData,e!==void 0&&(m=`success`,d=N(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#c)d=this.#l;else try{this.#c=t.select,d=t.select(d),d=N(i?.data,d,t),this.#l=d,this.#s=null}catch(e){this.#s=e}}this.#s&&(f=this.#s,d=this.#l,p=Date.now(),m=`error`);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,x=d!==void 0,S={status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!x,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&x,isStale:Oe(e,t),refetch:this.refetch,promise:this.#o,isEnabled:b(t.enabled,e)!==!1};if(this.options.experimental_prefetchInRender){let t=S.data!==void 0,r=S.status===`error`&&!t,i=e=>{r?e.reject(S.error):t&&e.resolve(S.data)},a=()=>{let e=this.#o=S.promise=oe();i(e)},o=this.#o;switch(o.status){case`pending`:e.queryHash===n.queryHash&&i(o);break;case`fulfilled`:(r||S.data!==o.value)&&a();break;case`rejected`:(!r||S.error!==o.reason)&&a()}}return S}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#u=this.#t),!O(t,e)&&(this.#r=t,this.#C({listeners:(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#m.size)return!0;let r=new Set(n??this.#m);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})()}))}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}#C(e){le.batch(()=>{e.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}};function we(e,t){return b(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||b(t.retryOnMount,e)!==!1)}function Te(e,t){return we(e,t)||e.state.data!==void 0&&Ee(e,t,t.refetchOnMount)}function Ee(e,t,n){if(b(t.enabled,e)!==!1&&y(t.staleTime,e)!==`static`){let r=typeof n==`function`?n(e):n;return r===`always`||r!==!1&&Oe(e,t)}return!1}function De(e,t,n,r){return(e!==t||b(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Oe(e,n)}function Oe(e,t){return b(t.enabled,e)!==!1&&e.isStaleByTime(y(t.staleTime,e))}function ke(e,t){return!O(e.getCurrentResult(),t)}var Ae=class extends he{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||je(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=me({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)});let r=this.state.status===`pending`,i=!this.#r.canStart();try{if(r)t();else{this.#i({type:`pending`,variables:e,isPaused:i}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:i})}let a=await this.#r.start();return await this.#n.config.onSuccess?.(a,e,this.state.context,this,n),await this.options.onSuccess?.(a,e,this.state.context,n),await this.#n.config.onSettled?.(a,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(a,null,e,this.state.context,n),this.#i({type:`success`,data:a}),a}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),le.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function je(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Me=class extends l{constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}#e;#t;#n;build(e,t,n){let r=new Ae({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=Ne(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=Ne(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=Ne(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=Ne(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){le.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>S(t,e))}findAll(e={}){return this.getAll().filter(t=>S(e,t))}notify(e){le.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return le.batch(()=>Promise.all(e.map(e=>e.continue().catch(h))))}};function Ne(e){return e.options.scope?.id}var Pe=class extends l{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),O(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&w(t.mutationKey)!==w(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??je();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){le.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},Fe=class extends l{constructor(e={}){super(),this.config=e,this.#e=new Map}#e;build(e,t,n){let r=t.queryKey,i=t.queryHash??C(r,t),a=this.get(i);return a||(a=new ye({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){let t=this.#e.get(e.queryHash);t&&(e.destroy(),t===e&&this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){le.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>x(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>x(e,t)):t}notify(e){le.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){le.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){le.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Ie=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Fe,this.#t=e.mutationCache||new Me,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=u.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=ue.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(y(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=g(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return le.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;le.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return le.batch(()=>(n.findAll(e).forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,...e},t)))}cancelQueries(e,t={}){let n={revert:!0,...t},r=le.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(h).catch(h)}invalidateQueries(e,t={}){return le.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=le.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(h)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(h)}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(y(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(h).catch(h)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(h).catch(h)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return ue.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(w(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{T(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(w(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{T(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=C(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===ne&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},Le=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function E(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function D(e,t){return E(e.type,t,e.props)}function O(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function k(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var A=/\/+/g;function j(e,t){return typeof e==`object`&&e&&e.key!=null?k(``+e.key):t.toString(36)}function M(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function N(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,N(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+j(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(A,`$&/`)+`/`),N(o,r,i,``,function(e){return e})):o!=null&&(O(o)&&(o=D(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(A,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u{t.exports=Le()})),ze=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),Be=o(((e,t)=>{t.exports=ze()})),I=c(Re(),1),L=Be(),Ve=I.createContext(void 0),He=e=>{let t=I.useContext(Ve);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Ue=({client:e,children:t})=>(I.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,L.jsx)(Ve.Provider,{value:e,children:t})),We=I.createContext(!1),Ge=()=>I.useContext(We);We.Provider;function Ke(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var qe=I.createContext(Ke()),Je=()=>I.useContext(qe),Ye=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?ie(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||e.experimental_prefetchInRender||r)&&(t.isReset()||(e.retryOnMount=!1))},Xe=e=>{I.useEffect(()=>{e.clearReset()},[e])},Ze=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||ie(n,[e.error,r])),Qe=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},$e=(e,t)=>e.isLoading&&e.isFetching&&!t,et=(e,t)=>e?.suspense&&t.isPending,tt=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function nt(e,t,n){let r=Ge(),i=Je(),a=He(n),o=a.defaultQueryOptions(e);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Qe(o),Ye(o,i,s),Xe(i);let l=!a.getQueryCache().get(o.queryHash),[u]=I.useState(()=>new t(a,o)),d=u.getOptimisticResult(o),f=!r&&c;if(I.useSyncExternalStore(I.useCallback(e=>{let t=f?u.subscribe(le.batchCalls(e)):h;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),I.useEffect(()=>{u.setOptions(o)},[o,u]),et(o,d))throw tt(o,u,i);if(Ze({result:d,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw d.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,d),o.experimental_prefetchInRender&&!ae.isServer()&&$e(d,r)&&(l?tt(o,u,i):s?.promise)?.catch(h).finally(()=>{u.updateResult()}),o.notifyOnChangeProps?d:u.trackResult(d)}function rt(e,t){return nt(e,Ce,t)}function it(e,t){let n=He(t),[r]=I.useState(()=>new Pe(n,e));I.useEffect(()=>{r.setOptions(e)},[r,e]);let i=I.useSyncExternalStore(I.useCallback(e=>r.subscribe(le.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=I.useCallback((e,t)=>{r.mutate(e,t).catch(h)},[r]);if(i.error&&ie(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var at=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0>>1,a=e[r];if(0>>1;ri(c,n))li(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(li(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,S||(S=!0,O());else{var t=n(l);t!==null&&j(x,t.startTime-e)}}}var S=!1,C=-1,w=5,T=-1;function E(){return g?!0:!(e.unstable_now()-Tt&&E());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&j(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?O():S=!1}}}var O;if(typeof y==`function`)O=function(){y(D)};else if(typeof MessageChannel<`u`){var k=new MessageChannel,A=k.port2;k.port1.onmessage=D,O=function(){A.postMessage(null)}}else O=function(){_(D,0)};function j(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,j(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,O()))),r},e.unstable_shouldYield=E,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),ot=o(((e,t)=>{t.exports=at()})),st=o((e=>{var t=Re();function n(e){var t=`https://react.dev/errors/`+e;if(1{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=st()})),lt=o((e=>{var t=ot(),n=Re(),r=ct();function i(e){var t=`https://react.dev/errors/`+e;if(1ne||(e.current=te[ne],te[ne]=null,ne--)}function F(e,t){ne++,te[ne]=e.current,e.current=t}var ae=re(null),oe=re(null),se=re(null),ce=re(null);function le(e,t){switch(F(se,t),F(oe,e),F(ae,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?Jd(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=Jd(t),e=Yd(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}ie(ae),F(ae,e)}function ue(){ie(ae),ie(oe),ie(se)}function de(e){e.memoizedState!==null&&F(ce,e);var t=ae.current,n=Yd(t,e.type);t!==n&&(F(oe,e),F(ae,n))}function fe(e){oe.current===e&&(ie(ae),ie(oe)),ce.current===e&&(ie(ce),ap._currentValue=ee)}var pe,me;function he(e){if(pe===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);pe=t&&t[1]||``,me=-1)`:-1i||c[r]!==l[i]){var u=` +`+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(``)&&(u=u.replace(``,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{ge=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?he(n):``}function ve(e,t){switch(e.tag){case 26:case 27:case 5:return he(e.type);case 16:return he(`Lazy`);case 13:return e.child!==t&&t!==null?he(`Suspense Fallback`):he(`Suspense`);case 19:return he(`SuspenseList`);case 0:case 15:return _e(e.type,!1);case 11:return _e(e.type.render,!1);case 1:return _e(e.type,!0);case 31:return he(`Activity`);default:return``}}function ye(e){try{var t=``,n=null;do t+=ve(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}var be=Object.prototype.hasOwnProperty,xe=t.unstable_scheduleCallback,Se=t.unstable_cancelCallback,Ce=t.unstable_shouldYield,we=t.unstable_requestPaint,Te=t.unstable_now,Ee=t.unstable_getCurrentPriorityLevel,De=t.unstable_ImmediatePriority,Oe=t.unstable_UserBlockingPriority,ke=t.unstable_NormalPriority,Ae=t.unstable_LowPriority,je=t.unstable_IdlePriority,Me=t.log,Ne=t.unstable_setDisableYieldValue,Pe=null,Fe=null;function Ie(e){if(typeof Me==`function`&&Ne(e),Fe&&typeof Fe.setStrictMode==`function`)try{Fe.setStrictMode(Pe,e)}catch{}}var Le=Math.clz32?Math.clz32:I,ze=Math.log,Be=Math.LN2;function I(e){return e>>>=0,e===0?32:31-(ze(e)/Be|0)|0}var L=256,Ve=262144,He=4194304;function Ue(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function We(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=Ue(n))):i=Ue(o):i=Ue(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=Ue(n))):i=Ue(o)):i=Ue(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function Ge(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function Ke(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function qe(){var e=He;return He<<=1,!(He&62914560)&&(He=4194304),e}function Je(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function Ye(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function Xe(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0`u`||window.document===void 0||window.document.createElement===void 0),un=!1;if(ln)try{var dn={};Object.defineProperty(dn,"passive",{get:function(){un=!0}}),window.addEventListener(`test`,dn,dn),window.removeEventListener(`test`,dn,dn)}catch{un=!1}var fn=null,pn=null,mn=null;function hn(){if(mn)return mn;var e,t=pn,n=t.length,r,i=`value`in fn?fn.value:fn.textContent,a=i.length;for(e=0;e=qn),Xn=` `,Zn=!1;function Qn(e,t){switch(e){case`keyup`:return Gn.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function $n(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var er=!1;function tr(e,t){switch(e){case`compositionend`:return $n(t);case`keypress`:return t.which===32?(Zn=!0,Xn):null;case`textInput`:return e=t.data,e===Xn&&Zn?null:e;default:return null}}function nr(e,t){if(er)return e===`compositionend`||!Kn&&Qn(e,t)?(e=hn(),mn=pn=fn=null,er=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=wr(n)}}function Er(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Er(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Dr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=It(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=It(e.document)}return t}function Or(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var kr=ln&&`documentMode`in document&&11>=document.documentMode,Ar=null,jr=null,Mr=null,Nr=!1;function Pr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Nr||Ar==null||Ar!==It(r)||(r=Ar,`selectionStart`in r&&Or(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Mr&&Cr(Mr,r)||(Mr=r,r=Md(jr,`onSelect`),0>=o,i-=o,Ei=1<<32-Le(t)+i|n<m?(h=d,d=null):h=d.sibling;var g=p(i,d,s[m],c);if(g===null){d===null&&(d=h);break}e&&d&&g.alternate===null&&t(i,d),a=o(g,a,m),u===null?l=g:u.sibling=g,u=g,d=h}if(m===s.length)return n(i,d),z&&Oi(i,m),l;if(d===null){for(;mh?(g=m,m=null):g=m.sibling;var y=p(a,m,v.value,l);if(y===null){m===null&&(m=g);break}e&&m&&y.alternate===null&&t(a,m),s=o(y,s,h),d===null?u=y:d.sibling=y,d=y,m=g}if(v.done)return n(a,m),z&&Oi(a,h),u;if(m===null){for(;!v.done;h++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,h),d===null?u=v:d.sibling=v,d=v);return z&&Oi(a,h),u}for(m=r(m);!v.done;h++,v=c.next())v=_(m,a,h,v.value,l),v!==null&&(e&&v.alternate!==null&&m.delete(v.key===null?h:v.key),s=o(v,s,h),d===null?u=v:d.sibling=v,d=v);return e&&m.forEach(function(e){return t(a,e)}),z&&Oi(a,h),u}function x(e,r,o,c){if(typeof o==`object`&&o&&o.type===g&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case m:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===g){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===T&&Oa(l)===r.type){n(e,r.sibling),c=a(r,o.props),Fa(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===g?(c=pi(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=fi(o.type,o.key,o.props,null,e.mode,c),Fa(c,o),c.return=e,e=c)}return s(e);case h:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=gi(o,e.mode,c),c.return=e,e=c}return s(e);case T:return o=Oa(o),x(e,r,o,c)}if(M(o))return v(e,r,o,c);if(k(o)){if(l=k(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),y(e,r,o,c)}if(typeof o.then==`function`)return x(e,r,Pa(o),c);if(o.$$typeof===b)return x(e,r,na(e,o),c);Ia(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=mi(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Na=0;var i=x(e,t,n,r);return Ma=null,i}catch(t){if(t===Sa||t===wa)throw t;var a=ci(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Ra=La(!0),za=La(!1),Ba=!1;function Va(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Ha(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Ua(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Wa(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,U&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=ai(e),ii(e,null,n),t}return ti(e,r,t,n),ai(e)}function Ga(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qe(e,n)}}function Ka(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var qa=!1;function Ja(){if(qa){var e=pa;if(e!==null)throw e}}function Ya(e,t,n,r){qa=!1;var i=e.updateQueue;Ba=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var p=s.lane&-536870913,m=p!==s.lane;if(m?(G&p)===p:(r&p)===p){p!==0&&p===fa&&(qa=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var h=e,g=s;p=t;var _=n;switch(g.tag){case 1:if(h=g.payload,typeof h==`function`){d=h.call(_,d,p);break a}d=h;break a;case 3:h.flags=h.flags&-65537|128;case 0:if(h=g.payload,p=typeof h==`function`?h.call(_,d,p):h,p==null)break a;d=f({},d,p);break a;case 2:Ba=!0}}p=s.callback,p!==null&&(e.flags|=64,m&&(e.flags|=8192),m=i.callbacks,m===null?i.callbacks=[p]:m.push(p))}else m={lane:p,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=m,c=d):u=u.next=m,o|=p;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;m=s,s=m.next,m.next=null,i.lastBaseUpdate=m,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),Xl|=o,e.lanes=o,e.memoizedState=d}}function Xa(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function Za(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=N.T,s={};N.T=s,Is(e,!1,t,n);try{var c=i(),l=N.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Fs(e,t,ga(c,r),vu(e)):Fs(e,t,r,vu(e))}catch(n){Fs(e,t,{then:function(){},status:`rejected`,reason:n},vu())}finally{P.p=a,o!==null&&s.types!==null&&(o.types=s.types),N.T=o}}function Ts(){}function Es(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Ds(e).queue;ws(e,a,t,ee,n===null?Ts:function(){return Os(e),n(r)})}function Ds(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:ee,baseState:ee,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Lo,lastRenderedState:ee},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Lo,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Os(e){var t=Ds(e);t.next===null&&(t=e.alternate.memoizedState),Fs(e,t.next.queue,{},vu())}function ks(){return ta(ap)}function As(){return No().memoizedState}function js(){return No().memoizedState}function Ms(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=vu();e=Ua(n);var r=Wa(t,e,n);r!==null&&(bu(r,t,n),Ga(r,t,n)),t={cache:ca()},e.payload=t;return}t=t.return}}function Ns(e,t,n){var r=vu();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Ls(e)?Rs(t,n):(n=ni(e,t,n,r),n!==null&&(bu(n,e,r),zs(n,t,r)))}function Ps(e,t,n){Fs(e,t,n,vu())}function Fs(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Ls(e))Rs(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Sr(s,o))return ti(e,t,i,0),Hl===null&&ei(),!1}catch{}if(n=ni(e,t,i,r),n!==null)return bu(n,e,r),zs(n,t,r),!0}return!1}function Is(e,t,n,r){if(r={lane:2,revertLane:_d(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Ls(e)){if(t)throw Error(i(479))}else t=ni(e,n,r,2),t!==null&&bu(t,e,2)}function Ls(e){var t=e.alternate;return e===B||t!==null&&t===B}function Rs(e,t){_o=go=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function zs(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,Qe(e,n)}}var Bs={readContext:ta,use:Fo,useCallback:Co,useContext:Co,useEffect:Co,useImperativeHandle:Co,useLayoutEffect:Co,useInsertionEffect:Co,useMemo:Co,useReducer:Co,useRef:Co,useState:Co,useDebugValue:Co,useDeferredValue:Co,useTransition:Co,useSyncExternalStore:Co,useId:Co,useHostTransitionStatus:Co,useFormState:Co,useActionState:Co,useOptimistic:Co,useMemoCache:Co,useCacheRefresh:Co};Bs.useEffectEvent=Co;var Vs={readContext:ta,use:Fo,useCallback:function(e,t){return Mo().memoizedState=[e,t===void 0?null:t],e},useContext:ta,useEffect:ds,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),ls(4194308,4,_s.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ls(4194308,4,e,t)},useInsertionEffect:function(e,t){ls(4,2,e,t)},useMemo:function(e,t){var n=Mo();t=t===void 0?null:t;var r=e();if(vo){Ie(!0);try{e()}finally{Ie(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=Mo();if(n!==void 0){var i=n(t);if(vo){Ie(!0);try{n(t)}finally{Ie(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Ns.bind(null,B,e),[r.memoizedState,e]},useRef:function(e){var t=Mo();return e={current:e},t.memoizedState=e},useState:function(e){e=qo(e);var t=e.queue,n=Ps.bind(null,B,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:ys,useDeferredValue:function(e,t){return Ss(Mo(),e,t)},useTransition:function(){var e=qo(!1);return e=ws.bind(null,B,e.queue,!0,!1),Mo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=B,a=Mo();if(z){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Hl===null)throw Error(i(349));G&127||Ho(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,ds(Wo.bind(null,r,o,e),[e]),r.flags|=2048,ss(9,{destroy:void 0},Uo.bind(null,r,o,n,t),null),n},useId:function(){var e=Mo(),t=Hl.identifierPrefix;if(z){var n=Di,r=Ei;n=(r&~(1<<32-Le(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=yo++,0<\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[at]=t,o[st]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(Vd(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Pc(t)}}return zc(t),Fc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Pc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=se.current,Vi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Ni,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[at]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Rd(e.nodeValue,n)),e||Ri(t,!0)}else e=qd(e).createTextNode(r),e[at]=t,t.stateNode=e}return zc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Vi(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[at]=t}else Hi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;zc(t),e=!1}else n=Ui(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(lo(t),t):(lo(t),null);if(t.flags&128)throw Error(i(558))}return zc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Vi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[at]=t}else Hi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;zc(t),a=!1}else a=Ui(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(lo(t),t):(lo(t),null)}return lo(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Lc(t,t.updateQueue),zc(t),null);case 4:return ue(),e===null&&Od(t.stateNode.containerInfo),zc(t),null;case 10:return Yi(t.type),zc(t),null;case 19:if(ie(uo),r=t.memoizedState,r===null)return zc(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)Rc(r,!1);else{if(Yl!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=fo(e),o!==null){for(t.flags|=128,Rc(r,!1),e=o.updateQueue,t.updateQueue=e,Lc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)di(n,e),n=n.sibling;return F(uo,uo.current&1|2),z&&Oi(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Te()>ou&&(t.flags|=128,a=!0,Rc(r,!1),t.lanes=4194304)}}else{if(!a){if(e=fo(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Lc(t,e),Rc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!z)return zc(t),null}else 2*Te()-r.renderingStartTime>ou&&n!==536870912&&(t.flags|=128,a=!0,Rc(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(zc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Te(),e.sibling=null,n=uo.current,F(uo,a?n&1|2:n&1),z&&Oi(t,r.treeForkCount),e);case 22:case 23:return lo(t),no(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(zc(t),t.subtreeFlags&6&&(t.flags|=8192)):zc(t),n=t.updateQueue,n!==null&&Lc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&ie(va),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Yi(sa),zc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Vc(e,t){switch(ji(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Yi(sa),ue(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return fe(t),null;case 31:if(t.memoizedState!==null){if(lo(t),t.alternate===null)throw Error(i(340));Hi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(lo(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Hi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return ie(uo),null;case 4:return ue(),null;case 10:return Yi(t.type),null;case 22:case 23:return lo(t),no(),e!==null&&ie(va),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Yi(sa),null;case 25:return null;default:return null}}function Hc(e,t){switch(ji(t),t.tag){case 3:Yi(sa),ue();break;case 26:case 27:case 5:fe(t);break;case 4:ue();break;case 31:t.memoizedState!==null&&lo(t);break;case 13:lo(t);break;case 19:ie(uo);break;case 10:Yi(t.type);break;case 22:case 23:lo(t),no(),e!==null&&ie(va);break;case 24:Yi(sa)}}function Uc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){Xu(t,t.return,e)}}function Wc(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){Xu(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){Xu(t,t.return,e)}}function Gc(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Za(t,n)}catch(t){Xu(e,e.return,t)}}}function Kc(e,t,n){n.props=Js(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){Xu(e,t,n)}}function qc(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){Xu(e,t,n)}}function Jc(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){Xu(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){Xu(e,t,n)}else n.current=null}}function Yc(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){Xu(e,e.return,t)}}function Xc(e,t,n){try{var r=e.stateNode;Hd(r,e.type,n,t),r[st]=t}catch(t){Xu(e,e.return,t)}}function Zc(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&af(e.type)||e.tag===4}function Qc(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||Zc(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&af(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function $c(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=$t));else if(r!==4&&(r===27&&af(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for($c(e,t,n),e=e.sibling;e!==null;)$c(e,t,n),e=e.sibling}function el(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&af(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(el(e,t,n),e=e.sibling;e!==null;)el(e,t,n),e=e.sibling}function tl(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);Vd(t,r,n),t[at]=e,t[st]=n}catch(t){Xu(e,e.return,t)}}var nl=!1,rl=!1,il=!1,al=typeof WeakSet==`function`?WeakSet:Set,ol=null;function sl(e,t){if(e=e.containerInfo,Gd=mp,e=Dr(e),Or(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(Kd={focusedElem:e,selectionRange:n},mp=!1,ol=t;ol!==null;)if(t=ol,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,ol=e;else for(;ol!==null;){switch(t=ol,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n title`))),Vd(o,r,n),o[at]=e,bt(o),r=o;break a;case`link`:var s=Jf(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;cg&&(o=g,g=h,h=o);var _=Tr(s,h),v=Tr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;sn?32:n,N.T=null,n=mu,mu=null;var o=uu,s=fu;if(lu=0,du=uu=null,fu=0,U&6)throw Error(i(331));var c=U;if(U|=4,Ll(o.current),kl(o,o.current,s,n),U=c,ud(0,!1),Fe&&typeof Fe.onPostCommitFiberRoot==`function`)try{Fe.onPostCommitFiberRoot(Pe,o)}catch{}return!0}finally{P.p=a,N.T=r,Ku(e,t)}}function Yu(e,t,n){t=vi(n,t),t=ec(e.stateNode,t,2),e=Wa(e,t,2),e!==null&&(Ye(e,2),ld(e))}function Xu(e,t,n){if(e.tag===3)Yu(e,e,n);else for(;t!==null;){if(t.tag===3){Yu(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(cu===null||!cu.has(r))){e=vi(n,e),n=tc(2),r=Wa(t,n,2),r!==null&&(nc(n,r,t,e),Ye(r,2),ld(r));break}}t=t.return}}function Zu(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Vl;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(ql=!0,i.add(n),e=Qu.bind(null,e,t,n),t.then(e,e))}function Qu(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Hl===e&&(G&n)===n&&(Yl===4||Yl===3&&(G&62914560)===G&&300>Te()-iu?!(U&2)&&Du(e,0):Ql|=n,eu===G&&(eu=0)),ld(e)}function $u(e,t){t===0&&(t=qe()),e=ri(e,t),e!==null&&(Ye(e,t),ld(e))}function ed(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),$u(e,n)}function td(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),$u(e,n)}function nd(e,t){return xe(e,t)}var rd=null,id=null,ad=!1,od=!1,sd=!1,cd=0;function ld(e){e!==id&&e.next===null&&(id===null?rd=id=e:id=id.next=e),od=!0,ad||(ad=!0,gd())}function ud(e,t){if(!sd&&od){sd=!0;do for(var n=!1,r=rd;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-Le(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,hd(r,a))}else a=G,a=We(r,r===Hl?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||Ge(r,a)||(n=!0,hd(r,a))}r=r.next}while(n);sd=!1}}function dd(){fd()}function fd(){od=ad=!1;var e=0;cd!==0&&Qd()&&(e=cd);for(var t=Te(),n=null,r=rd;r!==null;){var i=r.next,a=pd(r,t);a===0?(r.next=null,n===null?rd=i:n.next=i,i===null&&(id=n)):(n=r,(e!==0||a&3)&&(od=!0)),r=i}lu!==0&&lu!==5||ud(e,!1),cd!==0&&(cd=0)}function pd(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0s)break;var u=c.transferSize,d=c.initiatorType;u&&Ud(d)&&(c=c.responseEnd,o+=u*(c`u`?null:document;function Of(e,t,n){var r=Df;if(r&&typeof t==`string`&&t){var i=Rt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),Sf.has(i)||(Sf.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),Vd(t,`link`,e),bt(t),r.head.appendChild(t)))}}function kf(e){wf.D(e),Of(`dns-prefetch`,e,null)}function Af(e,t){wf.C(e,t),Of(`preconnect`,e,t)}function jf(e,t,n){wf.L(e,t,n);var r=Df;if(r&&e&&t){var i=`link[rel="preload"][as="`+Rt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Rt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Rt(n.imageSizes)+`"]`)):i+=`[href="`+Rt(e)+`"]`;var a=i;switch(t){case`style`:a=Lf(e);break;case`script`:a=Vf(e)}xf.has(a)||(e=f({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),xf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Rf(a))||t===`script`&&r.querySelector(Hf(a))||(t=r.createElement(`link`),Vd(t,`link`,e),bt(t),r.head.appendChild(t)))}}function Mf(e,t){wf.m(e,t);var n=Df;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Rt(r)+`"][href="`+Rt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Vf(e)}if(!xf.has(a)&&(e=f({rel:`modulepreload`,href:e},t),xf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Hf(a)))return}r=n.createElement(`link`),Vd(r,`link`,e),bt(r),n.head.appendChild(r)}}}function Nf(e,t,n){wf.S(e,t,n);var r=Df;if(r&&e){var i=yt(r).hoistableStyles,a=Lf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Rf(a)))s.loading=5;else{e=f({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=xf.get(a))&&Gf(e,n);var c=o=r.createElement(`link`);bt(c),Vd(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,Wf(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Pf(e,t){wf.X(e,t);var n=Df;if(n&&e){var r=yt(n).hoistableScripts,i=Vf(e),a=r.get(i);a||(a=n.querySelector(Hf(i)),a||(e=f({src:e,async:!0},t),(t=xf.get(i))&&Kf(e,t),a=n.createElement(`script`),bt(a),Vd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Ff(e,t){wf.M(e,t);var n=Df;if(n&&e){var r=yt(n).hoistableScripts,i=Vf(e),a=r.get(i);a||(a=n.querySelector(Hf(i)),a||(e=f({src:e,async:!0,type:`module`},t),(t=xf.get(i))&&Kf(e,t),a=n.createElement(`script`),bt(a),Vd(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function If(e,t,n,r){var a=(a=se.current)?Cf(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Lf(n.href),n=yt(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Lf(n.href);var o=yt(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(Rf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),xf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},xf.set(e,n),o||Bf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=Vf(n),n=yt(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Lf(e){return`href="`+Rt(e)+`"`}function Rf(e){return`link[rel="stylesheet"][`+e+`]`}function zf(e){return f({},e,{"data-precedence":e.precedence,precedence:null})}function Bf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),Vd(t,`link`,n),bt(t),e.head.appendChild(t))}function Vf(e){return`[src="`+Rt(e)+`"]`}function Hf(e){return`script[async]`+e}function Uf(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Rt(n.href)+`"]`);if(r)return t.instance=r,bt(r),r;var a=f({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),bt(r),Vd(r,`style`,a),Wf(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Lf(n.href);var o=e.querySelector(Rf(a));if(o)return t.state.loading|=4,t.instance=o,bt(o),o;r=zf(n),(a=xf.get(a))&&Gf(r,a),o=(e.ownerDocument||e).createElement(`link`),bt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),Vd(o,`link`,r),t.state.loading|=4,Wf(o,n.precedence,e),t.instance=o;case`script`:return o=Vf(n.src),(a=e.querySelector(Hf(o)))?(t.instance=a,bt(a),a):(r=n,(a=xf.get(o))&&(r=f({},n),Kf(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),bt(a),Vd(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Wf(r,n.precedence,e));return t.instance}function Wf(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o title`):null)}function Xf(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function Zf(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function Qf(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Lf(r.href),a=t.querySelector(Rf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=tp.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,bt(a);return}a=t.ownerDocument||t,r=zf(r),(i=xf.get(i))&&Gf(r,i),a=a.createElement(`link`),bt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),Vd(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=tp.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var $f=0;function ep(e,t){return e.stylesheets&&e.count===0&&rp(e,e.stylesheets),0$f?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function tp(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)rp(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var np=null;function rp(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,np=new Map,t.forEach(ip,e),np=null,tp.call(e))}function ip(e,t){if(!(t.state.loading&4)){var n=np.get(e);if(n)var r=n.get(null);else{n=new Map,np.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=lt()})),dt=`modulepreload`,ft=function(e){return`/`+e},pt={},mt=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=ft(t,n),t=s(t),t in pt)return;pt[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:dt,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},ht=e=>{throw TypeError(e)},gt=(e,t,n)=>t.has(e)||ht(`Cannot `+n),_t=(e,t,n)=>(gt(e,t,`read from private field`),n?n.call(e):t.get(e)),vt=(e,t,n)=>t.has(e)?ht(`Cannot add the same private member more than once`):t instanceof WeakSet?t.add(e):t.set(e,n),yt=(e,t,n,r)=>(gt(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n),bt=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,xt=/^[\\/]{2}/;function St(e,t){return t+e.replace(/\\/g,`/`)}var Ct=`popstate`;function wt(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function Tt(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return kt(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:At(t)}return Mt(t,n,null,e)}function R(e,t){if(e===!1||e==null)throw Error(t)}function Et(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function Dt(){return Math.random().toString(36).substring(2,10)}function Ot(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function kt(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?jt(t):t,state:n,key:t&&t.key||r||Dt(),mask:i}}function At({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function jt(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function Mt(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=wt(e)?e:kt(h.location,e,t);n&&n(r,e),l=u()+1;let d=Ot(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=wt(e)?e:kt(h.location,e,t);n&&n(r,e),l=u();let i=Ot(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return Nt(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(Ct,d),c=e,()=>{i.removeEventListener(Ct,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function Nt(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),R(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:At(t);return i=i.replace(/ $/,`%20`),!n&&xt.test(i)&&(i=r+i),new URL(i,r)}var Pt,Ft=class{constructor(e){if(vt(this,Pt,new Map),e)for(let[t,n]of e)this.set(t,n)}get(e){if(_t(this,Pt).has(e))return _t(this,Pt).get(e);if(e.defaultValue!==void 0)return e.defaultValue;throw Error(`No value found for context`)}set(e,t){_t(this,Pt).set(e,t)}};Pt=new WeakMap;var It=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`children`]);function Lt(e){return It.has(e)}var Rt=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`middleware`,`children`]);function zt(e){return Rt.has(e)}function Bt(e){return e.index===!0}function Vt(e,t,n=[],r={},i=!1){return e.map((e,a)=>{let o=[...n,String(a)],s=typeof e.id==`string`?e.id:o.join(`-`);if(R(e.index!==!0||!e.children,`Cannot specify children on an index route`),R(i||!r[s],`Found a route id collision on id "${s}". Route id's must be globally unique within Data Router usages`),Bt(e)){let n={...e,id:s};return r[s]=Ht(n,t(n)),n}{let n={...e,id:s,children:void 0};return r[s]=Ht(n,t(n)),e.children&&(n.children=Vt(e.children,t,o,r,i)),n}})}function Ht(e,t){return Object.assign(e,{...t,...typeof t.lazy==`object`&&t.lazy!=null?{lazy:{...e.lazy,...t.lazy}}:{}})}function Ut(e,t,n=`/`){return Wt(e,t,n,!1)}function Wt(e,t,n,r,i){let a=dn((typeof t==`string`?jt(t):t).pathname||`/`,n);if(a==null)return null;let o=i??Kt(e),s=null,c=un(a);for(let e=0;s==null&&e{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;R(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=xn([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(R(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),qt(e.children,t,u,l,o)),!(e.path==null&&!e.index)&&t.push({path:l,score:rn(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=ln(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of Jt(e.path))a(e,t,!0,n)}),t}function Jt(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=Jt(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function Yt(e){e.sort((e,t)=>e.score===t.score?an(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var Xt=/^:[\w-]+$/,Zt=3,Qt=2,$t=1,en=10,tn=-2,nn=e=>e===`*`;function rn(e,t){let n=e.split(`/`),r=n.length;return n.some(nn)&&(r+=tn),t&&(r+=Qt),n.filter(e=>!nn(e)).reduce((e,t)=>e+(Xt.test(t)?Zt:t===``?$t:en),r)}function an(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function on(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e{if(t===`*`){let e=s[r]||``;o=a.slice(0,a.length-e.length).replace(/(.)\/+$/,`$1`)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function ln(e,t=!1,n=!0){Et(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(\/|$)/g,`(/$1)?$2`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function un(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return Et(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function dn(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function fn({basename:e,pathname:t}){return t===`/`?e:xn([e,t])}var pn=e=>bt.test(e);function mn(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?jt(e):e,a;return n?(n=bn(n),a=n.startsWith(`/`)?hn(n.substring(1),`/`):hn(n,t)):a=t,{pathname:a,search:wn(r),hash:Tn(i)}}function hn(e,t){let n=Sn(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function gn(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in and the router will parse it for you.`}function _n(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function vn(e){let t=_n(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function yn(e,t,n,r=!1){let i;typeof e==`string`?i=jt(e):(i={...e},R(!i.pathname||!i.pathname.includes(`?`),gn(`?`,`pathname`,`search`,i)),R(!i.pathname||!i.pathname.includes(`#`),gn(`#`,`pathname`,`hash`,i)),R(!i.search||!i.search.includes(`#`),gn(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=mn(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var bn=e=>e.replace(/[\\/]{2,}/g,`/`),xn=e=>bn(e.join(`/`)),Sn=e=>e.replace(/\/+$/,``),Cn=e=>Sn(e).replace(/^\/*/,`/`),wn=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,Tn=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,En=[`EvalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],Dn=class{constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function On(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function kn(e){return xn(e.map(e=>e.route.path).filter(Boolean))||`/`}var An=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function jn(e,t){let n=e;if(typeof n!=`string`||!bt.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(An)try{let e=new URL(window.location.href),r=xt.test(n)?new URL(St(n,e.protocol)):new URL(n),a=dn(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{Et(!1,` contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}var Mn=Symbol(`Uninstrumented`);function Nn(e,t){let n={lazy:[],"lazy.loader":[],"lazy.action":[],"lazy.middleware":[],middleware:[],loader:[],action:[]};e.forEach(e=>e({id:t.id,index:t.index,path:t.path,instrument(e){let t=Object.keys(n);for(let r of t)e[r]&&n[r].push(e[r])}}));let r={};if(typeof t.lazy==`function`&&n.lazy.length>0){let e=Fn(n.lazy,t.lazy,()=>void 0);e&&(r.lazy=e)}if(typeof t.lazy==`object`){let e=t.lazy;[`middleware`,`loader`,`action`].forEach(t=>{let i=e[t],a=n[`lazy.${t}`];if(typeof i==`function`&&a.length>0){let e=Fn(a,i,()=>void 0);e&&(r.lazy=Object.assign(r.lazy||{},{[t]:e}))}})}return[`loader`,`action`].forEach(e=>{let i=t[e];if(typeof i==`function`&&n[e].length>0){let t=i[Mn]??i,a=Fn(n[e],t,(...e)=>Ln(e[0]));a&&(e===`loader`&&t.hydrate===!0&&(a.hydrate=!0),a[Mn]=t,r[e]=a)}}),t.middleware&&t.middleware.length>0&&n.middleware.length>0&&(r.middleware=t.middleware.map(e=>{let t=e[Mn]??e,r=Fn(n.middleware,t,(...e)=>Ln(e[0]));return r?(r[Mn]=t,r):e})),r}function Pn(e,t){let n={navigate:[],fetch:[]};if(t.forEach(e=>e({instrument(e){let t=Object.keys(e);for(let r of t)e[r]&&n[r].push(e[r])}})),n.navigate.length>0){let t=e.navigate[Mn]??e.navigate,r=Fn(n.navigate,t,(...t)=>{let[n,r]=t;return{to:typeof n==`number`||typeof n==`string`?n:n?At(n):`.`,...Rn(e,r??{})}});r&&(r[Mn]=t,e.navigate=r)}if(n.fetch.length>0){let t=e.fetch[Mn]??e.fetch,r=Fn(n.fetch,t,(...t)=>{let[n,,r,i]=t;return{href:r??`.`,fetcherKey:n,...Rn(e,i??{})}});r&&(r[Mn]=t,e.fetch=r)}return e}function Fn(e,t,n){return e.length===0?null:async(...r)=>{let i=await In(e,n(...r),()=>t(...r),e.length-1);if(i.type===`error`)throw i.value;return i.value}}async function In(e,t,n,r){let i=e[r],a;if(i){let o,s=async()=>(o?console.error(`You cannot call instrumented handlers more than once`):o=In(e,t,n,r-1),a=await o,R(a,`Expected a result`),a.type===`error`&&a.value instanceof Error?{status:`error`,error:a.value}:{status:`success`,error:void 0});try{await i(s,t)}catch(e){console.error(`An instrumentation function threw an error:`,e)}o||await s(),await o}else try{a={type:`success`,value:await n()}}catch(e){a={type:`error`,value:e}}return a||{type:`error`,value:Error(`No result assigned in instrumentation chain.`)}}function Ln(e){let{request:t,context:n,params:r,pattern:i}=e;return{request:zn(t),params:{...r},pattern:i,context:Bn(n)}}function Rn(e,t){return{currentUrl:At(e.state.location),...`formMethod`in t?{formMethod:t.formMethod}:{},...`formEncType`in t?{formEncType:t.formEncType}:{},...`formData`in t?{formData:t.formData}:{},...`body`in t?{body:t.body}:{}}}function zn(e){return{method:e.method,url:e.url,headers:{get:(...t)=>e.headers.get(...t)}}}function Bn(e){if(Hn(e)){let t={...e};return Object.freeze(t),t}return{get:t=>e.get(t)}}var Vn=Object.getOwnPropertyNames(Object.prototype).sort().join(`\0`);function Hn(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null||Object.getOwnPropertyNames(t).sort().join(`\0`)===Vn}var Un=[`POST`,`PUT`,`PATCH`,`DELETE`],Wn=new Set(Un),Gn=[`GET`,...Un],Kn=new Set(Gn),qn=new Set([301,302,303,307,308]),Jn=new Set([307,308]),Yn={state:`idle`,location:void 0,matches:void 0,historyAction:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Xn={state:`idle`,data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Zn={state:`unblocked`,proceed:void 0,reset:void 0,location:void 0},Qn=e=>({hasErrorBoundary:!!e.hasErrorBoundary}),$n=`remix-router-transitions`,er=Symbol(`ResetLoaderData`),tr,nr,rr,ir,ar=class{constructor(e){vt(this,tr),vt(this,nr),vt(this,rr),vt(this,ir),yt(this,tr,e),yt(this,nr,Kt(e))}get stableRoutes(){return _t(this,tr)}get activeRoutes(){return _t(this,rr)??_t(this,tr)}get branches(){return _t(this,ir)??_t(this,nr)}get hasHMRRoutes(){return _t(this,rr)!=null}setRoutes(e){yt(this,tr,e),yt(this,nr,Kt(e))}setHmrRoutes(e){yt(this,rr,e),yt(this,ir,Kt(e))}commitHmrRoutes(){_t(this,rr)&&(yt(this,tr,_t(this,rr)),yt(this,nr,_t(this,ir)),yt(this,rr,void 0),yt(this,ir,void 0))}};tr=new WeakMap,nr=new WeakMap,rr=new WeakMap,ir=new WeakMap;function or(e){let t=e.window?e.window:typeof window<`u`?window:void 0,n=t!==void 0&&t.document!==void 0&&t.document.createElement!==void 0;R(e.routes.length>0,`You must provide a non-empty routes array to createRouter`);let r=e.hydrationRouteProperties||[],i=e.mapRouteProperties||Qn,a=i;if(e.instrumentations){let t=e.instrumentations;a=e=>({...i(e),...Nn(t.map(e=>e.route).filter(Boolean),e)})}let o={},s=new ar(Vt(e.routes,a,void 0,o)),c=e.basename||`/`;c.startsWith(`/`)||(c=`/${c}`);let l=e.dataStrategy||Cr,u={...e.future},d=null,f=new Set,p=null,m=null,h=null,g=null,_=e.hydrationData!=null,v=Wt(s.activeRoutes,e.history.location,c,!1,s.branches),y=!1,b=null,x,S;if(v==null&&!e.patchRoutesOnNavigation){let t=Jr(404,{pathname:e.history.location.pathname}),{matches:n,route:r}=qr(s.activeRoutes);x=!0,S=!x,v=n,b={[r.id]:t}}else if(v&&!e.hydrationData&&Ke(v,s.activeRoutes,e.history.location.pathname).active&&(v=null),!v){x=!1,S=!x,v=[];let t=Ke(null,s.activeRoutes,e.history.location.pathname);t.active&&t.matches&&(y=!0,v=t.matches)}else if(v.some(e=>e.route.lazy))x=!1,S=!x;else if(!v.some(e=>dr(e.route)))x=!0,S=!x;else{let t=e.hydrationData?e.hydrationData.loaderData:null,n=e.hydrationData?e.hydrationData.errors:null,r=v;if(n){let e=v.findIndex(e=>n[e.route.id]!==void 0);r=r.slice(0,e+1)}S=!1,x=!0,r.forEach(e=>{let r=fr(e.route,t,n);S||=r.renderFallback,x&&=!r.shouldLoad})}let C,w={historyAction:e.history.action,location:e.history.location,matches:v,initialized:x,renderFallback:S,navigation:Yn,restoreScrollPosition:e.hydrationData==null&&null,preventScrollReset:!1,revalidation:`idle`,loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||b,fetchers:new Map,blockers:new Map},T=`POP`,E=null,D=!1,O,k=!1,A=new Map,j=null,M=!1,N=!1,P=new Set,ee=new Map,te=0,ne=-1,re=new Map,ie=new Set,F=new Map,ae=new Map,oe=new Set,se=new Map,ce,le=null;function ue(){if(d=e.history.listen(({action:t,location:n,delta:r})=>{if(ce){ce(),ce=void 0;return}Et(se.size===0||r!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let i=L({currentLocation:w.location,nextLocation:n,historyAction:t});if(i&&r!=null){let t=new Promise(e=>{ce=e});e.history.go(r*-1),I(i,{state:`blocked`,location:n,proceed(){I(i,{state:`proceeding`,proceed:void 0,reset:void 0,location:n}),t.then(()=>e.history.go(r))},reset(){let e=new Map(w.blockers);e.set(i,Zn),pe({blockers:e})}}),E?.resolve(),E=null;return}return _e(t,n)}),n){vi(t,A);let e=()=>yi(t,A);t.addEventListener(`pagehide`,e),j=()=>t.removeEventListener(`pagehide`,e)}return w.initialized||_e(`POP`,w.location,{initialHydration:!0}),C}function de(){d&&d(),j&&j(),f.clear(),O&&O.abort(),w.fetchers.forEach((e,t)=>Ne(w.fetchers,t)),w.blockers.forEach((e,t)=>Be(t))}function fe(e){if(f.add(e),p){let{newErrors:t}=p;p=null,e(w,{deletedFetchers:[],newErrors:t,viewTransitionOpts:void 0,flushSync:!1})}return()=>f.delete(e)}function pe(e,t={}){e.matches&&=e.matches.map(e=>{let t=o[e.route.id],n=e.route;return n.element!==t.element||n.errorElement!==t.errorElement||n.hydrateFallbackElement!==t.hydrateFallbackElement?{...e,route:t}:e}),w={...w,...e};let n=[],r=[];w.fetchers.forEach((e,t)=>{e.state===`idle`&&(oe.has(t)?n.push(t):r.push(t))}),oe.forEach(e=>{!w.fetchers.has(e)&&!ee.has(e)&&n.push(e)}),f.size===0&&(p={newErrors:e.errors??null}),[...f].forEach(r=>r(w,{deletedFetchers:n,newErrors:e.errors??null,viewTransitionOpts:t.viewTransitionOpts,flushSync:t.flushSync===!0})),n.forEach(e=>Ne(w.fetchers,e)),r.forEach(e=>w.fetchers.delete(e))}function me(t,n,{flushSync:r}={}){let i=w.actionData!=null&&w.navigation.formMethod!=null&&li(w.navigation.formMethod)&&w.navigation.state===`loading`&&t.state?._isRedirect!==!0,a;a=n.actionData?Object.keys(n.actionData).length>0?n.actionData:null:i?w.actionData:null;let o=n.loaderData?Wr(w.loaderData,n.loaderData,n.matches||[],n.errors):w.loaderData,c=w.blockers;c.size>0&&(c=new Map(c),c.forEach((e,t)=>c.set(t,Zn)));let l=!M&&Ge(t,n.matches||w.matches),u=D===!0||w.navigation.formMethod!=null&&li(w.navigation.formMethod)&&t.state?._isRedirect!==!0;s.commitHmrRoutes(),M||T===`POP`||(T===`PUSH`?e.history.push(t,t.state):T===`REPLACE`&&e.history.replace(t,t.state));let d;if(T===`POP`){let e=A.get(w.location.pathname);e&&e.has(t.pathname)?d={currentLocation:w.location,nextLocation:t}:A.has(t.pathname)&&(d={currentLocation:t,nextLocation:w.location})}else if(k){let e=A.get(w.location.pathname);e?e.add(t.pathname):(e=new Set([t.pathname]),A.set(w.location.pathname,e)),d={currentLocation:w.location,nextLocation:t}}pe({...n,actionData:a,loaderData:o,historyAction:T,location:t,initialized:!0,renderFallback:!1,navigation:Yn,revalidation:`idle`,restoreScrollPosition:l,preventScrollReset:u,blockers:c},{viewTransitionOpts:d,flushSync:r===!0}),T=`POP`,D=!1,k=!1,M=!1,N=!1,E?.resolve(),E=null,le?.resolve(),le=null}async function he(t,n){if(E?.resolve(),E=null,typeof t==`number`){E||=bi();let n=E.promise;return e.history.go(t),n}let{path:r,submission:i,error:a}=lr(!1,cr(w.location,w.matches,c,t,n?.fromRouteId,n?.relative),n),o;n?.mask&&(o={pathname:``,search:``,hash:``,...typeof n.mask==`string`?jt(n.mask):{...w.location.mask,...n.mask}});let s=w.location,l=kt(s,r,n&&n.state,void 0,o);l={...l,...e.history.encodeLocation(l)};let u=n&&n.replace!=null?n.replace:void 0,d=`PUSH`;u===!0?d=`REPLACE`:u===!1||i!=null&&li(i.formMethod)&&i.formAction===w.location.pathname+w.location.search&&(d=`REPLACE`);let f=n&&`preventScrollReset`in n?n.preventScrollReset===!0:void 0,p=(n&&n.flushSync)===!0,m=L({currentLocation:s,nextLocation:l,historyAction:d});if(m){I(m,{state:`blocked`,location:l,proceed(){I(m,{state:`proceeding`,proceed:void 0,reset:void 0,location:l}),he(t,n)},reset(){let e=new Map(w.blockers);e.set(m,Zn),pe({blockers:e})}});return}await _e(d,l,{submission:i,pendingError:a,preventScrollReset:f,replace:n&&n.replace,enableViewTransition:n&&n.viewTransition,flushSync:p,callSiteDefaultShouldRevalidate:n&&n.defaultShouldRevalidate})}function ge(){le||=bi(),Oe(),pe({revalidation:`loading`});let e=le.promise;return w.navigation.state===`submitting`?e:w.navigation.state===`idle`?(_e(w.historyAction,w.location,{startUninterruptedRevalidation:!0}),e):(_e(T||w.historyAction,w.navigation.location,{overrideNavigation:w.navigation,enableViewTransition:k===!0}),e)}async function _e(t,n,r){O&&O.abort(),O=null,T=t,M=(r&&r.startUninterruptedRevalidation)===!0,We(w.location,w.matches),D=(r&&r.preventScrollReset)===!0,k=(r&&r.enableViewTransition)===!0;let i=s.activeRoutes,a=r?.initialHydration&&w.matches&&w.matches.length>0&&!y?w.matches:Wt(i,n,c,!1,s.branches),o=(r&&r.flushSync)===!0;if(a&&w.initialized&&!N&&Zr(w.location,n)&&!(r&&r.submission&&li(r.submission.formMethod))){me(n,{matches:a},{flushSync:o});return}let l=Ke(a,i,n.pathname);if(l.active&&l.matches&&(a=l.matches),!a){let{error:e,notFoundMatches:t,route:r}=Ve(n.pathname);me(n,{matches:t,loaderData:{},errors:{[r.id]:e}},{flushSync:o});return}let u=r&&r.overrideNavigation?{...r.overrideNavigation,matches:a,historyAction:t}:void 0;O=new AbortController;let d=Rr(e.history,n,O.signal,r&&r.submission),f=e.getContext?await e.getContext():new Ft,p;if(r&&r.pendingError)p=[Kr(a).route.id,{type:`error`,error:r.pendingError}];else if(r&&r.submission&&li(r.submission.formMethod)){let i=await ve(d,n,r.submission,a,t,f,l.active,r&&r.initialHydration===!0,{replace:r.replace,flushSync:o});if(i.shortCircuited)return;if(i.pendingActionResult){let[e,t]=i.pendingActionResult;if(ni(t)&&On(t.error)&&t.error.status===404){O=null,me(n,{matches:i.matches,loaderData:{},errors:{[e]:t.error}});return}}a=i.matches||a,p=i.pendingActionResult,u=pi(n,a,t,r.submission),o=!1,l.active=!1,d=Rr(e.history,d.url,d.signal)}let{shortCircuited:m,matches:h,loaderData:g,errors:_,workingFetchers:v}=await ye(d,n,a,t,f,l.active,u,r&&r.submission,r&&r.fetcherSubmission,r&&r.replace,r&&r.initialHydration===!0,o,p,r&&r.callSiteDefaultShouldRevalidate);m||(O=null,me(n,{matches:h||a,...Gr(p),loaderData:g,errors:_,...v?{fetchers:v}:{}}))}async function ve(t,n,i,l,u,d,f,p,m={}){if(Oe(),pe({navigation:mi(n,l,u,i)},{flushSync:m.flushSync===!0}),f){let e=await qe(l,n.pathname,t.signal);if(e.type===`aborted`)return{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=qr(s.activeRoutes);return{matches:t,pendingActionResult:[n.id,{type:`error`,error:e.error}]}}let t=Kr(e.partialMatches).route.id;return{matches:e.partialMatches,pendingActionResult:[t,{type:`error`,error:e.error}]}}if(e.matches)l=e.matches;else{let{notFoundMatches:e,error:t,route:r}=Ve(n.pathname);return{matches:e,pendingActionResult:[r.id,{type:`error`,error:t}]}}}let h,g=di(l,n);if(!g.route.action&&!g.route.lazy)h={type:`error`,error:Jr(405,{method:t.method,pathname:n.pathname,routeId:g.route.id})};else{let e=await Ee(t,n,kr(a,o,t,n,l,g,p?[]:r,d),d,null);if(h=e[g.route.id],!h){for(let t of l)if(e[t.route.id]){h=e[t.route.id];break}}if(t.signal.aborted)return{shortCircuited:!0}}if(ri(h)){let n;return n=m&&m.replace!=null?m.replace:Lr(h.response.headers.get(`Location`),new URL(t.url),c,e.history)===w.location.pathname+w.location.search,await Te(t,h,!0,{submission:i,replace:n}),{shortCircuited:!0}}if(ni(h)){let e=Kr(l,g.route.id);return(m&&m.replace)!==!0&&(T=`PUSH`),{matches:l,pendingActionResult:[e.route.id,h,g.route.id]}}return{matches:l,pendingActionResult:[g.route.id,h]}}async function ye(t,n,i,l,u,d,f,p,m,h,g,_,v,y){let b=f||pi(n,i,l,p),x=p||m||fi(b),S=!M&&!g;if(d){if(S){let e=be(v);pe({navigation:b,...e===void 0?{}:{actionData:e}},{flushSync:_})}let e=await qe(i,n.pathname,t.signal);if(e.type===`aborted`)return{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=qr(s.activeRoutes);return{matches:t,loaderData:{},errors:{[n.id]:e.error}}}let t=Kr(e.partialMatches).route.id;return{matches:e.partialMatches,loaderData:{},errors:{[t]:e.error}}}if(e.matches)i=e.matches;else{let{error:e,notFoundMatches:t,route:r}=Ve(n.pathname);return{matches:t,loaderData:{},errors:{[r.id]:e}}}}let C=s.activeRoutes,{dsMatches:T,revalidatingFetchers:E}=ur(t,u,a,o,e.history,w,i,x,n,g?[]:r,g===!0,N,P,oe,F,ie,C,c,e.patchRoutesOnNavigation!=null,s.branches,v,y);if(ne=++te,!e.dataStrategy&&!T.some(e=>e.shouldLoad)&&!T.some(e=>e.route.middleware&&e.route.middleware.length>0)&&E.length===0){let e=new Map(w.fetchers),t=Le(e);return me(n,{matches:i,loaderData:{},errors:v&&ni(v[1])?{[v[0]]:v[1].error}:null,...Gr(v),...t?{fetchers:e}:{}},{flushSync:_}),{shortCircuited:!0}}if(S){let e={};if(!d){e.navigation=b;let t=be(v);t!==void 0&&(e.actionData=t)}E.length>0&&(e.fetchers=xe(E)),pe(e,{flushSync:_})}E.forEach(e=>{Fe(e.key),e.controller&&ee.set(e.key,e.controller)});let D=()=>E.forEach(e=>Fe(e.key));O&&O.signal.addEventListener(`abort`,D);let{loaderResults:k,fetcherResults:A}=await De(T,E,t,n,u);if(t.signal.aborted)return{shortCircuited:!0};O&&O.signal.removeEventListener(`abort`,D),E.forEach(e=>ee.delete(e.key));let j=Yr(k);if(j)return await Te(t,j.result,!0,{replace:h}),{shortCircuited:!0};if(j=Yr(A),j)return ie.add(j.key),await Te(t,j.result,!0,{replace:h}),{shortCircuited:!0};let re=new Map(w.fetchers),{loaderData:ae,errors:se}=Ur(w,i,k,v,E,A,re);g&&w.errors&&(se={...w.errors,...se});let ce=Le(re),le=Re(ne,re),ue=ce||le||E.length>0;return{matches:i,loaderData:ae,errors:se,...ue?{workingFetchers:re}:{}}}function be(e){if(e&&!ni(e[1]))return{[e[0]]:e[1].data};if(w.actionData)return Object.keys(w.actionData).length===0?null:w.actionData}function xe(e){let t=new Map(w.fetchers);return e.forEach(e=>{let n=t.get(e.key),r=hi(void 0,n?n.data:void 0);t.set(e.key,r)}),t}async function Se(t,n,r,i){Fe(t);let a=(i&&i.flushSync)===!0,o=s.activeRoutes,l=cr(w.location,w.matches,c,r,n,i?.relative),u=Wt(o,l,c,!1,s.branches),d=Ke(u,o,l);if(d.active&&d.matches&&(u=d.matches),!u){Ae(t,n,Jr(404,{pathname:l}),{flushSync:a});return}let{path:f,submission:p,error:m}=lr(!0,l,i);if(m){Ae(t,n,m,{flushSync:a});return}let h=e.getContext?await e.getContext():new Ft,g=(i&&i.preventScrollReset)===!0;if(p&&li(p.formMethod)){await Ce(t,n,f,u,h,d.active,a,g,p,i&&i.defaultShouldRevalidate);return}F.set(t,{routeId:n,path:f}),await we(t,n,f,u,h,d.active,a,g,p)}async function Ce(t,n,i,l,u,d,f,p,m,h){Oe(),F.delete(t),ke(t,gi(m,w.fetchers.get(t)),{flushSync:f});let g=new AbortController,_=Rr(e.history,i,g.signal,m);if(d){let e=await qe(l,new URL(_.url).pathname,_.signal,t);if(e.type===`aborted`)return;if(e.type===`error`){Ae(t,n,e.error,{flushSync:f});return}if(e.matches)l=e.matches;else{Ae(t,n,Jr(404,{pathname:i}),{flushSync:f});return}}let v=di(l,i);if(!v.route.action&&!v.route.lazy){Ae(t,n,Jr(405,{method:m.formMethod,pathname:i,routeId:n}),{flushSync:f});return}ee.set(t,g);let y=te,b=kr(a,o,_,i,l,v,r,u),x=await Ee(_,i,b,u,t),S=x[v.route.id];if(!S){for(let e of b)if(x[e.route.id]){S=x[e.route.id];break}}if(_.signal.aborted){ee.get(t)===g&&ee.delete(t);return}if(oe.has(t)){if(ri(S)||ni(S)){ke(t,_i(void 0));return}}else{if(ri(S)){if(ee.delete(t),ne>y){ke(t,_i(void 0));return}return ie.add(t),ke(t,hi(m)),Te(_,S,!1,{fetcherSubmission:m,preventScrollReset:p})}if(ni(S)){Ae(t,n,S.error);return}}let C=w.navigation.location||w.location,E=Rr(e.history,C,g.signal),D=s.activeRoutes,k=w.navigation.state===`idle`?w.matches:Wt(D,w.navigation.location,c,!1,s.branches);R(k,`Didn't find any matches after fetcher action`);let A=++te;re.set(t,A);let{dsMatches:j,revalidatingFetchers:M}=ur(E,u,a,o,e.history,w,k,m,C,r,!1,N,P,oe,F,ie,D,c,e.patchRoutesOnNavigation!=null,s.branches,[v.route.id,S],h),ae=hi(m,S.data),se=new Map(w.fetchers);se.set(t,ae),M.filter(e=>e.key!==t).forEach(e=>{let t=e.key,n=se.get(t),r=hi(void 0,n?n.data:void 0);se.set(t,r),Fe(t),e.controller&&ee.set(t,e.controller)}),pe({fetchers:se});let ce=()=>M.forEach(e=>Fe(e.key));g.signal.addEventListener(`abort`,ce);let{loaderResults:le,fetcherResults:ue}=await De(j,M,E,C,u);if(g.signal.aborted)return;g.signal.removeEventListener(`abort`,ce),re.delete(t),ee.delete(t),M.forEach(e=>ee.delete(e.key));let de=w.fetchers.has(t),fe=e=>{if(!de)return e;let n=new Map(e.fetchers);return n.set(t,_i(S.data)),{...e,fetchers:n}},he=Yr(le);if(he)return w=fe(w),Te(E,he.result,!1,{preventScrollReset:p});if(he=Yr(ue),he)return ie.add(he.key),w=fe(w),Te(E,he.result,!1,{preventScrollReset:p});let ge=new Map(w.fetchers);de&&ge.set(t,_i(S.data));let{loaderData:_e,errors:ve}=Ur(w,k,le,void 0,M,ue,ge);Re(A,ge),w.navigation.state===`loading`&&A>ne?(R(T,`Expected pending action`),O&&O.abort(),me(w.navigation.location,{matches:k,loaderData:_e,errors:ve,fetchers:ge})):(pe({errors:ve,loaderData:Wr(w.loaderData,_e,k,ve),fetchers:ge}),N=!1)}async function we(t,n,i,s,c,l,u,d,f){let p=w.fetchers.get(t);ke(t,hi(f,p?p.data:void 0),{flushSync:u});let m=new AbortController,h=Rr(e.history,i,m.signal);if(l){let e=await qe(s,new URL(h.url).pathname,h.signal,t);if(e.type===`aborted`)return;if(e.type===`error`){Ae(t,n,e.error,{flushSync:u});return}if(e.matches)s=e.matches;else{Ae(t,n,Jr(404,{pathname:i}),{flushSync:u});return}}let g=di(s,i);ee.set(t,m);let _=te,v=await Ee(h,i,kr(a,o,h,i,s,g,r,c),c,t),y=v[g.route.id];if(!y){for(let e of s)if(v[e.route.id]){y=v[e.route.id];break}}if(ee.get(t)===m&&ee.delete(t),!h.signal.aborted){if(oe.has(t)){ke(t,_i(void 0));return}if(ri(y)){if(ne>_){ke(t,_i(void 0));return}ie.add(t),await Te(h,y,!1,{preventScrollReset:d});return}if(ni(y)){Ae(t,n,y.error);return}ke(t,_i(y.data))}}async function Te(r,i,a,{submission:o,fetcherSubmission:s,preventScrollReset:l,replace:u}={}){a||(E?.resolve(),E=null),i.response.headers.has(`X-Remix-Revalidate`)&&(N=!0);let d=i.response.headers.get(`Location`);R(d,`Expected a Location header on the redirect Response`),d=Lr(d,new URL(r.url),c,e.history);let f=kt(w.location,d,{_isRedirect:!0});if(n){let e=!1;if(i.response.headers.has(`X-Remix-Reload-Document`))e=!0;else if(pn(d)){let n=Nt(t,d,!0);e=n.origin!==t.location.origin||dn(n.pathname,c)==null}if(e){u?t.location.replace(d):t.location.assign(d);return}}O=null;let p=u===!0||i.response.headers.has(`X-Remix-Replace`)?`REPLACE`:`PUSH`,{formMethod:m,formAction:h,formEncType:g}=w.navigation;!o&&!s&&m&&h&&g&&(o=fi(w.navigation));let _=o||s;Jn.has(i.response.status)&&_&&li(_.formMethod)?await _e(p,f,{submission:{..._,formAction:d},preventScrollReset:l||D,enableViewTransition:a?k:void 0}):await _e(p,f,{overrideNavigation:pi(f,[],p,o),fetcherSubmission:s,preventScrollReset:l||D,enableViewTransition:a?k:void 0})}async function Ee(e,t,n,r,i){let a,o={};try{a=await Ar(l,e,t,n,i,r,!1)}catch(e){return n.filter(e=>e.shouldLoad).forEach(t=>{o[t.route.id]={type:`error`,error:e}}),o}if(e.signal.aborted)return o;if(!li(e.method))for(let e of n){if(a[e.route.id]?.type===`error`)break;!a.hasOwnProperty(e.route.id)&&!w.loaderData.hasOwnProperty(e.route.id)&&(!w.errors||!w.errors.hasOwnProperty(e.route.id))&&e.shouldCallHandler()&&(a[e.route.id]={type:`error`,result:Error(`No result returned from dataStrategy for route ${e.route.id}`)})}for(let[t,r]of Object.entries(a))if(ti(r)){let i=r.result;o[t]={type:`redirect`,response:Pr(i,e,t,n,c)}}else o[t]=await Nr(r);return o}async function De(e,t,n,r,i){let a=Ee(n,r,e,i,null),o=Promise.all(t.map(async e=>{if(e.matches&&e.match&&e.request&&e.controller){let t=(await Ee(e.request,e.path,e.matches,i,e.key))[e.match.route.id];return{[e.key]:t}}return Promise.resolve({[e.key]:{type:`error`,error:Jr(404,{pathname:e.path})}})}));return{loaderResults:await a,fetcherResults:(await o).reduce((e,t)=>Object.assign(e,t),{})}}function Oe(){N=!0,F.forEach((e,t)=>{ee.has(t)&&P.add(t),Fe(t)})}function ke(e,t,n={}){let r=new Map(w.fetchers);r.set(e,t),pe({fetchers:r},{flushSync:(n&&n.flushSync)===!0})}function Ae(e,t,n,r={}){let i=Kr(w.matches,t),a=new Map(w.fetchers);Ne(a,e),pe({errors:{[i.route.id]:n},fetchers:a},{flushSync:(r&&r.flushSync)===!0})}function je(e){return ae.set(e,(ae.get(e)||0)+1),oe.has(e)&&oe.delete(e),w.fetchers.get(e)||Xn}function Me(e,t){Fe(e,t?.reason),ke(e,_i(null))}function Ne(e,t){let n=w.fetchers.get(t);ee.has(t)&&!(n&&n.state===`loading`&&re.has(t))&&Fe(t),F.delete(t),re.delete(t),ie.delete(t),oe.delete(t),P.delete(t),e.delete(t)}function Pe(e){let t=(ae.get(e)||0)-1;t<=0?(ae.delete(e),oe.add(e)):ae.set(e,t),pe({fetchers:new Map(w.fetchers)})}function Fe(e,t){let n=ee.get(e);n&&(n.abort(t),ee.delete(e))}function Ie(e,t){for(let n of e){let e=t.get(n);R(e,`Expected fetcher: ${n}`);let r=_i(e.data);t.set(n,r)}}function Le(e){let t=[],n=!1;for(let r of ie){let i=e.get(r);R(i,`Expected fetcher: ${r}`),i.state===`loading`&&(ie.delete(r),t.push(r),n=!0)}return Ie(t,e),n}function Re(e,t){let n=[];for(let[r,i]of re)if(i0}function ze(e,t){let n=w.blockers.get(e)||Zn;return se.get(e)!==t&&se.set(e,t),n}function Be(e){w.blockers.delete(e),se.delete(e)}function I(e,t){let n=w.blockers.get(e)||Zn;R(n.state===`unblocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`proceeding`||n.state===`blocked`&&t.state===`unblocked`||n.state===`proceeding`&&t.state===`unblocked`,`Invalid blocker state transition: ${n.state} -> ${t.state}`);let r=new Map(w.blockers);r.set(e,t),pe({blockers:r})}function L({currentLocation:e,nextLocation:t,historyAction:n}){if(se.size===0)return;se.size>1&&Et(!1,`A router only supports one blocker at a time`);let r=Array.from(se.entries()),[i,a]=r[r.length-1],o=w.blockers.get(i);if(!(o&&o.state===`proceeding`)&&a({currentLocation:e,nextLocation:t,historyAction:n}))return i}function Ve(e){let t=Jr(404,{pathname:e}),n=s.activeRoutes,{matches:r,route:i}=qr(n);return{notFoundMatches:r,route:i,error:t}}function He(e,t,n){if(m=e,g=t,h=n||null,!_&&w.navigation===Yn){_=!0;let e=Ge(w.location,w.matches);e!=null&&pe({restoreScrollPosition:e})}return()=>{m=null,g=null,h=null}}function Ue(e,t){return h&&h(e,t.map(e=>Gt(e,w.loaderData)))||e.key}function We(e,t){if(m&&g){let n=Ue(e,t);m[n]=g()}}function Ge(e,t){if(m){let n=Ue(e,t),r=m[n];if(typeof r==`number`)return r}return null}function Ke(t,n,r){if(e.patchRoutesOnNavigation){let e=s.branches;if(!t)return{active:!0,matches:Wt(n,r,c,!0,e)||[]};if(Object.keys(t[0].params).length>0)return{active:!0,matches:Wt(n,r,c,!0,e)}}return{active:!1,matches:null}}async function qe(t,n,r,i){if(!e.patchRoutesOnNavigation)return{type:`success`,matches:t};let l=t;for(;;){let t=o;try{await e.patchRoutesOnNavigation({signal:r,path:n,matches:l,fetcherKey:i,patch:(e,n)=>{r.aborted||gr(e,n,s,t,a,!1)}})}catch(e){return{type:`error`,error:e,partialMatches:l}}if(r.aborted)return{type:`aborted`};let u=s.branches,d=Wt(s.activeRoutes,n,c,!1,u),f=null;if(d&&(Object.keys(d[0].params).length===0||(f=Wt(s.activeRoutes,n,c,!0,u),!(f&&l.lengthe.route.id===t[n].route.id)}function Ye(e){o={},s.setHmrRoutes(Vt(e,a,void 0,o))}function Xe(e,t,n=!1){gr(e,t,s,o,a,n),s.hasHMRRoutes||pe({})}return C={get basename(){return c},get future(){return u},get state(){return w},get routes(){return s.stableRoutes},get branches(){return s.branches},get manifest(){return o},get window(){return t},initialize:ue,subscribe:fe,enableScrollRestoration:He,navigate:he,fetch:Se,revalidate:ge,createHref:t=>e.history.createHref(t),encodeLocation:t=>e.history.encodeLocation(t),getFetcher:je,resetFetcher:Me,deleteFetcher:Pe,dispose:de,getBlocker:ze,deleteBlocker:Be,patchRoutes:Xe,_internalFetchControllers:ee,_internalSetRoutes:Ye,_internalSetStateDoNotUseOrYouWillBreakYourApp(e){pe(e)}},e.instrumentations&&(C=Pn(C,e.instrumentations.map(e=>e.router).filter(Boolean))),C}function sr(e){return e!=null&&(`formData`in e&&e.formData!=null||`body`in e&&e.body!==void 0)}function cr(e,t,n,r,i,a){let o,s;if(i){o=[];for(let e of t)if(o.push(e),e.route.id===i){s=e;break}}else o=t,s=t[t.length-1];let c=yn(r||`.`,vn(o),dn(e.pathname,n)||e.pathname,a===`path`);if(r??(c.search=e.search,c.hash=e.hash),(r==null||r===``||r===`.`)&&s){let e=ui(c.search);if(s.route.index&&!e)c.search=c.search?c.search.replace(/^\?/,`?index&`):`?index`;else if(!s.route.index&&e){let e=new URLSearchParams(c.search),t=e.getAll(`index`);e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();c.search=n?`?${n}`:``}}return n!==`/`&&(c.pathname=fn({basename:n,pathname:c.pathname})),At(c)}function lr(e,t,n){if(!n||!sr(n))return{path:t};if(n.formMethod&&!ci(n.formMethod))return{path:t,error:Jr(405,{method:n.formMethod})};let r=()=>({path:t,error:Jr(400,{type:`invalid-body`})}),i=(n.formMethod||`get`).toUpperCase(),a=Xr(t);if(n.body!==void 0){if(n.formEncType===`text/plain`){if(!li(i))return r();let e=typeof n.body==`string`?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((e,[t,n])=>`${e}${t}=${n} +`,``):String(n.body);return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:void 0,text:e}}}if(n.formEncType===`application/json`){if(!li(i))return r();try{let e=typeof n.body==`string`?JSON.parse(n.body):n.body;return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:e,text:void 0}}}catch{return r()}}}R(typeof FormData==`function`,`FormData is not available in this environment`);let o,s;if(n.formData)o=Br(n.formData),s=n.formData;else if(n.body instanceof FormData)o=Br(n.body),s=n.body;else if(n.body instanceof URLSearchParams)o=n.body,s=Vr(o);else if(n.body==null)o=new URLSearchParams,s=new FormData;else try{o=new URLSearchParams(n.body),s=Vr(o)}catch{return r()}let c={formMethod:i,formAction:a,formEncType:n&&n.formEncType||`application/x-www-form-urlencoded`,formData:s,json:void 0,text:void 0};if(li(c.formMethod))return{path:t,submission:c};let l=jt(t);return e&&l.search&&ui(l.search)&&o.append(`index`,``),l.search=`?${o}`,{path:At(l),submission:c}}function ur(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x){let S=b?ni(b[1])?b[1].error:b[1].data:void 0,C=i.createURL(a.location),w=i.createURL(c),T;if(u&&a.errors){let e=Object.keys(a.errors)[0];T=o.findIndex(t=>t.route.id===e)}else if(b&&ni(b[1])){let e=b[0];T=o.findIndex(t=>t.route.id===e)-1}let E=b?b[1].statusCode:void 0,D=E&&E>=400,O={currentUrl:C,currentParams:a.matches[0]?.params||{},nextUrl:w,nextParams:o[0].params,...s,actionResult:S,actionStatus:E},k=kn(o),A=o.map((i,o)=>{let{route:s}=i,f=null;if(T!=null&&o>T)f=!1;else if(s.lazy)f=!0;else if(!dr(s))f=!1;else if(u){let{shouldLoad:e}=fr(s,a.loaderData,a.errors);f=e}else pr(a.loaderData,a.matches[o],i)&&(f=!0);if(f!==null)return Or(n,r,e,c,k,i,l,t,f);let p=!1;typeof x==`boolean`?p=x:D?p=!1:d||C.pathname+C.search===w.pathname+w.search?p=!0:C.search===w.search?mr(a.matches[o],i)&&(p=!0):p=!0;let m={...O,defaultShouldRevalidate:p},h=hr(i,m);return Or(n,r,e,c,k,i,l,t,h,m,x)}),j=[];return m.forEach((e,s)=>{if(u||!o.some(t=>t.route.id===e.routeId)||p.has(s))return;let c=a.fetchers.get(s),m=c&&c.state!==`idle`&&c.data===void 0,b=Wt(g,e.path,_??`/`,!1,y);if(!b){if(v&&m)return;j.push({key:s,routeId:e.routeId,path:e.path,matches:null,match:null,request:null,controller:null});return}if(h.has(s))return;let S=di(b,e.path),C=new AbortController,w=Rr(i,e.path,C.signal),T=null;if(f.has(s))f.delete(s),T=kr(n,r,w,e.path,b,S,l,t);else if(m)d&&(T=kr(n,r,w,e.path,b,S,l,t));else{let i;i=typeof x==`boolean`?x:!D&&d;let a={...O,defaultShouldRevalidate:i};hr(S,a)&&(T=kr(n,r,w,e.path,b,S,l,t,a))}T&&j.push({key:s,routeId:e.routeId,path:e.path,matches:T,match:S,request:w,controller:C})}),{dsMatches:A,revalidatingFetchers:j}}function dr(e){return e.loader!=null||e.middleware!=null&&e.middleware.length>0}function fr(e,t,n){if(e.lazy)return{shouldLoad:!0,renderFallback:!0};if(!dr(e))return{shouldLoad:!1,renderFallback:!1};let r=t!=null&&e.id in t,i=n!=null&&n[e.id]!==void 0;if(!r&&i)return{shouldLoad:!1,renderFallback:!1};if(typeof e.loader==`function`&&e.loader.hydrate===!0)return{shouldLoad:!0,renderFallback:!r};let a=!r&&!i;return{shouldLoad:a,renderFallback:a}}function pr(e,t,n){let r=!t||n.route.id!==t.route.id,i=!e.hasOwnProperty(n.route.id);return r||i}function mr(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith(`*`)&&e.params[`*`]!==t.params[`*`]}function hr(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n==`boolean`)return n}return t.defaultShouldRevalidate}function gr(e,t,n,r,i,a){let o;if(e){let t=r[e];R(t,`No route found to patch children into: routeId = ${e}`),t.children||=[],o=t.children}else o=n.activeRoutes;let s=[],c=[];if(t.forEach(e=>{let t=o.find(t=>_r(e,t));t?c.push({existingRoute:t,newRoute:e}):s.push(e)}),s.length>0){let t=Vt(s,i,[e||`_`,`patch`,String(o?.length||`0`)],r);o.push(...t)}if(a&&c.length>0)for(let e=0;et.children?.some(t=>_r(e,t)))??!1}var vr=new WeakMap,yr=({key:e,route:t,manifest:n,mapRouteProperties:r})=>{let i=n[t.id];if(R(i,`No route found in manifest`),!i.lazy||typeof i.lazy!=`object`)return;let a=i.lazy[e];if(!a)return;let o=vr.get(i);o||(o={},vr.set(i,o));let s=o[e];if(s)return s;let c=(async()=>{let t=Lt(e),n=i[e]!==void 0&&e!==`hasErrorBoundary`;if(t)Et(!t,`Route property `+e+` is not a supported lazy route property. This property will be ignored.`),o[e]=Promise.resolve();else if(n)Et(!1,`Route "${i.id}" has a static property "${e}" defined. The lazy property will be ignored.`);else{let t=await a();t!=null&&(Object.assign(i,{[e]:t}),Object.assign(i,r(i)))}typeof i.lazy==`object`&&(i.lazy[e]=void 0,Object.values(i.lazy).every(e=>e===void 0)&&(i.lazy=void 0))})();return o[e]=c,c},br=new WeakMap;function xr(e,t,n,r,i){let a=n[e.id];if(R(a,`No route found in manifest`),!e.lazy)return{lazyRoutePromise:void 0,lazyHandlerPromise:void 0};if(typeof e.lazy==`function`){let t=br.get(a);if(t)return{lazyRoutePromise:t,lazyHandlerPromise:t};let n=(async()=>{R(typeof e.lazy==`function`,`No lazy route function found`);let t=await e.lazy(),n={};for(let e in t){let r=t[e];if(r===void 0)continue;let i=zt(e),o=a[e]!==void 0&&e!==`hasErrorBoundary`;i?Et(!i,`Route property `+e+` is not a supported property to be returned from a lazy route function. This property will be ignored.`):o?Et(!o,`Route "${a.id}" has a static property "${e}" defined but its lazy function is also returning a value for this property. The lazy route property "${e}" will be ignored.`):n[e]=r}Object.assign(a,n),Object.assign(a,{...r(a),lazy:void 0})})();return br.set(a,n),n.catch(()=>{}),{lazyRoutePromise:n,lazyHandlerPromise:n}}let o=Object.keys(e.lazy),s=[],c;for(let a of o){if(i&&i.includes(a))continue;let o=yr({key:a,route:e,manifest:n,mapRouteProperties:r});o&&(s.push(o),a===t&&(c=o))}let l=s.length>0?Promise.all(s).then(()=>{}):void 0;return l?.catch(()=>{}),c?.catch(()=>{}),{lazyRoutePromise:l,lazyHandlerPromise:c}}async function Sr(e){let t=e.matches.filter(e=>e.shouldLoad),n={};return(await Promise.all(t.map(e=>e.resolve()))).forEach((e,r)=>{n[t[r].route.id]=e}),n}async function Cr(e){return e.matches.some(e=>e.route.middleware)?wr(e,()=>Sr(e)):Sr(e)}function wr(e,t){return Tr(e,t,e=>{if(si(e))throw e;return e},$r,n);function n(t,n,r){if(r)return Promise.resolve(Object.assign(r.value,{[n]:{type:`error`,result:t}}));{let{matches:r}=e,i=Kr(r,r[Math.min(Math.max(r.findIndex(e=>e.route.id===n),0),Math.max(r.findIndex(e=>e.shouldCallHandler()),0))].route.id).route.id;return Promise.resolve({[i]:{type:`error`,result:t}})}}}async function Tr(e,t,n,r,i){let{matches:a,...o}=e;return await Er(o,a.flatMap(e=>e.route.middleware?e.route.middleware.map(t=>[e.route.id,t]):[]),t,n,r,i)}async function Er(e,t,n,r,i,a,o=0){let{request:s}=e;if(s.signal.aborted)throw s.signal.reason??Error(`Request aborted: ${s.method} ${s.url}`);let c=t[o];if(!c)return await n();let[l,u]=c,d,f=async()=>{if(d)throw Error("You may only call `next()` once per middleware");try{return d={value:await Er(e,t,n,r,i,a,o+1)},d.value}catch(e){return d={value:await a(e,l,d)},d.value}};try{let t=await u(e,f),n=t==null?void 0:r(t);return i(n)?n:d?n??d.value:(d={value:await f()},d.value)}catch(e){return await a(e,l,d)}}function Dr(e,t,n,r,i){let a=yr({key:`middleware`,route:r.route,manifest:t,mapRouteProperties:e}),o=xr(r.route,li(n.method)?`action`:`loader`,t,e,i);return{middleware:a,route:o.lazyRoutePromise,handler:o.lazyHandlerPromise}}function Or(e,t,n,r,i,a,o,s,c,l=null,u){let d=!1,f=Dr(e,t,n,a,o);return{...a,_lazyPromises:f,shouldLoad:c,shouldRevalidateArgs:l,shouldCallHandler(e){return d=!0,l?typeof u==`boolean`?hr(a,{...l,defaultShouldRevalidate:u}):typeof e==`boolean`?hr(a,{...l,defaultShouldRevalidate:e}):hr(a,l):c},resolve(e){let{lazy:t,loader:o,middleware:l}=a.route,u=d||c||e&&!li(n.method)&&(t||o),p=l&&l.length>0&&!o&&!t;return u&&(li(n.method)||!p)?jr({request:n,path:r,pattern:i,match:a,lazyHandlerPromise:f?.handler,lazyRoutePromise:f?.route,handlerOverride:e,scopedContext:s}):Promise.resolve({type:`data`,result:void 0})}}}function kr(e,t,n,r,i,a,o,s,c=null){return i.map(l=>l.route.id===a.route.id?Or(e,t,n,r,kn(i),l,o,s,!0,c):{...l,shouldLoad:!1,shouldRevalidateArgs:c,shouldCallHandler:()=>!1,_lazyPromises:Dr(e,t,n,l,o),resolve:()=>Promise.resolve({type:`data`,result:void 0})})}async function Ar(e,t,n,r,i,a,o){r.some(e=>e._lazyPromises?.middleware)&&await Promise.all(r.map(e=>e._lazyPromises?.middleware));let s={request:t,url:zr(t,n),pattern:kn(r),params:r[0].params,context:a,matches:r},c=o?()=>{throw Error("You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`")}:e=>{let t=s;return wr(t,()=>e({...t,fetcherKey:i,runClientMiddleware:()=>{throw Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler")}}))},l=await e({...s,fetcherKey:i,runClientMiddleware:c});try{await Promise.all(r.flatMap(e=>[e._lazyPromises?.handler,e._lazyPromises?.route]))}catch{}return l}async function jr({request:e,path:t,pattern:n,match:r,lazyHandlerPromise:i,lazyRoutePromise:a,handlerOverride:o,scopedContext:s}){let c,l,u=li(e.method),d=u?`action`:`loader`,f=i=>{let a,c=new Promise((e,t)=>a=t);l=()=>a(),e.signal.addEventListener(`abort`,l);let u=a=>typeof i==`function`?i({request:e,url:zr(e,t),pattern:n,params:r.params,context:s},...a===void 0?[]:[a]):Promise.reject(Error(`You cannot call the handler for a route which defines a boolean "${d}" [routeId: ${r.route.id}]`)),f=(async()=>{try{return{type:`data`,result:await(o?o(e=>u(e)):u())}}catch(e){return{type:`error`,result:e}}})();return Promise.race([f,c])};try{let t=u?r.route.action:r.route.loader;if(i||a){if(t){let e,[n]=await Promise.all([f(t).catch(t=>{e=t}),i,a]);if(e!==void 0)throw e;c=n}else{await i;let t=u?r.route.action:r.route.loader;if(t)[c]=await Promise.all([f(t),a]);else if(d===`action`){let t=new URL(e.url),n=t.pathname+t.search;throw Jr(405,{method:e.method,pathname:n,routeId:r.route.id})}else return{type:`data`,result:void 0}}}else if(t)c=await f(t);else{let t=new URL(e.url);throw Jr(404,{pathname:t.pathname+t.search})}}catch(e){return{type:`error`,result:e}}finally{l&&e.signal.removeEventListener(`abort`,l)}return c}async function Mr(e){let t=e.headers.get(`Content-Type`);return t&&/\bapplication\/json\b/.test(t)?e.body==null?null:e.json():e.text()}async function Nr(e){let{result:t,type:n}=e;if(ai(t)){let e;try{e=await Mr(t)}catch(e){return{type:`error`,error:e}}return n===`error`?{type:`error`,error:new Dn(t.status,t.statusText,e),statusCode:t.status,headers:t.headers}:{type:`data`,data:e,statusCode:t.status,headers:t.headers}}return n===`error`?ii(t)?t.data instanceof Error?{type:`error`,error:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:Qr(t),statusCode:On(t)?t.status:void 0,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:t,statusCode:On(t)?t.status:void 0}:ii(t)?{type:`data`,data:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`data`,data:t}}function Pr(e,t,n,r,i){let a=e.headers.get(`Location`);if(R(a,`Redirects returned/thrown from loaders/actions must have a Location header`),!pn(a)){let o=r.slice(0,r.findIndex(e=>e.route.id===n)+1);a=cr(new URL(t.url),o,i,a),e.headers.set(`Location`,a)}return e}var Fr=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function Ir(e){try{return Fr.includes(new URL(e).protocol)}catch{return!1}}function Lr(e,t,n,r){if(pn(e)){let r=e,i=xt.test(r)?new URL(St(r,t.protocol)):new URL(r);if(Ir(i.toString()))throw Error(`Invalid redirect location`);let a=dn(i.pathname,n)!=null;if(i.origin===t.origin&&a)return bn(i.pathname)+i.search+i.hash}try{if(Ir(r.createURL(e).toString()))throw Error(`Invalid redirect location`)}catch{}return e}function Rr(e,t,n,r){let i=e.createURL(Xr(t)).toString(),a={signal:n};if(r&&li(r.formMethod)){let{formMethod:e,formEncType:t}=r;a.method=e.toUpperCase(),t===`application/json`?(a.headers=new Headers({"Content-Type":t}),a.body=JSON.stringify(r.json)):a.body=t===`text/plain`?r.text:t===`application/x-www-form-urlencoded`&&r.formData?Br(r.formData):r.formData}return new Request(i,a)}function zr(e,t){let n=new URL(e.url),r=typeof t==`string`?jt(t):t;if(n.pathname=r.pathname||`/`,r.search){let e=new URLSearchParams(r.search),t=e.getAll(`index`);e.delete(`index`);for(let n of t.filter(Boolean))e.append(`index`,n);n.search=e.size?`?${e.toString()}`:``}else n.search=``;return n.hash=r.hash||``,n}function Br(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r==`string`?r:r.name);return t}function Vr(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function Hr(e,t,n,r=!1,i=!1){let a={},o=null,s,c=!1,l={},u=n&&ni(n[1])?n[1].error:void 0;return e.forEach(n=>{if(!(n.route.id in t))return;let d=n.route.id,f=t[d];if(R(!ri(f),`Cannot handle redirect results in processLoaderData`),ni(f)){let t=f.error;if(u!==void 0&&(t=u,u=void 0),o||={},i)o[d]=t;else{let n=Kr(e,d);o[n.route.id]??(o[n.route.id]=t)}r||(a[d]=er),c||(c=!0,s=On(f.error)?f.error.status:500),f.headers&&(l[d]=f.headers)}else a[d]=f.data,f.statusCode&&f.statusCode!==200&&!c&&(s=f.statusCode),f.headers&&(l[d]=f.headers)}),u!==void 0&&n&&(o={[n[0]]:u},n[2]&&(a[n[2]]=void 0)),{loaderData:a,errors:o,statusCode:s||200,loaderHeaders:l}}function Ur(e,t,n,r,i,a,o){let{loaderData:s,errors:c}=Hr(t,n,r);return i.filter(e=>!e.matches||e.matches.some(e=>e.shouldLoad)).forEach(t=>{let{key:n,match:r,controller:i}=t;if(i&&i.signal.aborted)return;let s=a[n];if(R(s,`Did not find corresponding fetcher result`),ni(s)){let t=Kr(e.matches,r?.route.id);c&&c[t.route.id]||(c={...c,[t.route.id]:s.error}),o.delete(n)}else if(ri(s))R(!1,`Unhandled fetcher revalidation redirect`);else{let e=_i(s.data);o.set(n,e)}}),{loaderData:s,errors:c}}function Wr(e,t,n,r){let i=Object.entries(t).filter(([,e])=>e!==er).reduce((e,[t,n])=>(e[t]=n,e),{});for(let a of n){let n=a.route.id;if(!t.hasOwnProperty(n)&&e.hasOwnProperty(n)&&a.route.loader&&(i[n]=e[n]),r&&r.hasOwnProperty(n))break}return i}function Gr(e){return e?ni(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function Kr(e,t){return(t?e.slice(0,e.findIndex(e=>e.route.id===t)+1):[...e]).reverse().find(e=>e.route.hasErrorBoundary===!0)||e[0]}function qr(e){let t=e.length===1?e[0]:e.find(e=>e.index||!e.path||e.path===`/`)||{id:`__shim-error-route__`};return{matches:[{params:{},pathname:``,pathnameBase:``,route:t}],route:t}}function Jr(e,{pathname:t,routeId:n,method:r,type:i,message:a}={}){let o=`Unknown Server Error`,s=`Unknown @remix-run/router error`;return e===400?(o=`Bad Request`,r&&t&&n?s=`You made a ${r} request to "${t}" but did not provide a \`loader\` for route "${n}", so there is no way to handle the request.`:i===`invalid-body`&&(s=`Unable to encode submission body`)):e===403?(o=`Forbidden`,s=`Route "${n}" does not match URL "${t}"`):e===404?(o=`Not Found`,s=`No route matches URL "${t}"`):e===405&&(o=`Method Not Allowed`,r&&t&&n?s=`You made a ${r.toUpperCase()} request to "${t}" but did not provide an \`action\` for route "${n}", so there is no way to handle the request.`:r&&(s=`Invalid request method "${r.toUpperCase()}"`)),new Dn(e||500,o,Error(s),!0)}function Yr(e){let t=Object.entries(e);for(let e=t.length-1;e>=0;e--){let[n,r]=t[e];if(ri(r))return{key:n,result:r}}}function Xr(e){return At({...typeof e==`string`?jt(e):e,hash:``})}function Zr(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===``?t.hash!==``:e.hash===t.hash||t.hash!==``}function Qr(e){return new Dn(e.init?.status??500,e.init?.statusText??`Internal Server Error`,e.data)}function $r(e){return typeof e==`object`&&!!e&&Object.entries(e).every(([e,t])=>typeof e==`string`&&ei(t))}function ei(e){return typeof e==`object`&&!!e&&`type`in e&&`result`in e&&(e.type===`data`||e.type===`error`)}function ti(e){return ai(e.result)&&qn.has(e.result.status)}function ni(e){return e.type===`error`}function ri(e){return(e&&e.type)===`redirect`}function ii(e){return typeof e==`object`&&!!e&&`type`in e&&`data`in e&&`init`in e&&e.type===`DataWithResponseInit`}function ai(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function oi(e){return qn.has(e)}function si(e){return ai(e)&&oi(e.status)&&e.headers.has(`Location`)}function ci(e){return Kn.has(e.toUpperCase())}function li(e){return Wn.has(e.toUpperCase())}function ui(e){return new URLSearchParams(e).getAll(`index`).some(e=>e===``)}function di(e,t){let n=typeof t==`string`?jt(t).search:t.search;if(e[e.length-1].route.index&&ui(n||``))return e[e.length-1];let r=_n(e);return r[r.length-1]}function fi(e){let{formMethod:t,formAction:n,formEncType:r,text:i,formData:a,json:o}=e;if(!(!t||!n||!r)){if(i!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:i};if(a!=null)return{formMethod:t,formAction:n,formEncType:r,formData:a,json:void 0,text:void 0};if(o!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:o,text:void 0}}}function pi(e,t,n,r){return r?{state:`loading`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}:{state:`loading`,location:e,matches:t,historyAction:n,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function mi(e,t,n,r){return{state:`submitting`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}}function hi(e,t){return e?{state:`loading`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:`loading`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function gi(e,t){return{state:`submitting`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function _i(e){return{state:`idle`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function vi(e,t){try{let n=e.sessionStorage.getItem($n);if(n){let e=JSON.parse(n);for(let[n,r]of Object.entries(e||{}))r&&Array.isArray(r)&&t.set(n,new Set(r||[]))}}catch{}}function yi(e,t){if(t.size>0){let n={};for(let[e,r]of t)n[e]=[...r];try{e.sessionStorage.setItem($n,JSON.stringify(n))}catch(e){Et(!1,`Failed to save applied view transitions in sessionStorage (${e}).`)}}}function bi(){let e,t,n=new Promise((r,i)=>{e=async e=>{r(e);try{await n}catch{}},t=async e=>{i(e);try{await n}catch{}}});return{promise:n,resolve:e,reject:t}}var xi=I.createContext(null);xi.displayName=`DataRouter`;var Si=I.createContext(null);Si.displayName=`DataRouterState`;var Ci=I.createContext(!1);function wi(){return I.useContext(Ci)}var Ti=I.createContext({isTransitioning:!1});Ti.displayName=`ViewTransition`;var Ei=I.createContext(new Map);Ei.displayName=`Fetchers`;var Di=I.createContext(null);Di.displayName=`Await`;var Oi=I.createContext(null);Oi.displayName=`Navigation`;var ki=I.createContext(null);ki.displayName=`Location`;var Ai=I.createContext({outlet:null,matches:[],isDataRoute:!1});Ai.displayName=`Route`;var ji=I.createContext(null);ji.displayName=`RouteError`;var Mi=`REACT_ROUTER_ERROR`,Ni=`REDIRECT`,Pi=`ROUTE_ERROR_RESPONSE`;function z(e){if(e.startsWith(`${Mi}:${Ni}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function Fi(e){if(e.startsWith(`${Mi}:${Pi}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new Dn(t.status,t.statusText,t.data)}catch{}}function Ii(e,{relative:t}={}){R(Li(),`useHref() may be used only in the context of a component.`);let{basename:n,navigator:r}=I.useContext(Oi),{hash:i,pathname:a,search:o}=Ki(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:xn([n,a])),r.createHref({pathname:s,search:o,hash:i})}function Li(){return I.useContext(ki)!=null}function Ri(){return R(Li(),`useLocation() may be used only in the context of a component.`),I.useContext(ki).location}var zi=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function Bi(e){I.useContext(Oi).static||I.useLayoutEffect(e)}function Vi(){let{isDataRoute:e}=I.useContext(Ai);return e?ca():Hi()}function Hi(){R(Li(),`useNavigate() may be used only in the context of a component.`);let e=I.useContext(xi),{basename:t,navigator:n}=I.useContext(Oi),{matches:r}=I.useContext(Ai),{pathname:i}=Ri(),a=JSON.stringify(vn(r)),o=I.useRef(!1);return Bi(()=>{o.current=!0}),I.useCallback((r,s={})=>{if(Et(o.current,zi),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=yn(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:xn([t,c.pathname])),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var Ui=I.createContext(null);function Wi(e){let t=I.useContext(Ai).outlet;return I.useMemo(()=>t&&I.createElement(Ui.Provider,{value:e},t),[t,e])}function Gi(){let{matches:e}=I.useContext(Ai);return e[e.length-1]?.params??{}}function Ki(e,{relative:t}={}){let{matches:n}=I.useContext(Ai),{pathname:r}=Ri(),i=JSON.stringify(vn(n));return I.useMemo(()=>yn(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function qi(e,t,n){R(Li(),`useRoutes() may be used only in the context of a component.`);let{navigator:r}=I.useContext(Oi),{matches:i}=I.useContext(Ai),a=i[i.length-1],o=a?a.params:{},s=a?a.pathname:`/`,c=a?a.pathnameBase:`/`,l=a&&a.route;{let e=l&&l.path||``;ua(s,!l||e.endsWith(`*`)||e.endsWith(`*?`),`You rendered descendant (or called \`useRoutes()\`) at "${s}" (under ) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render. + +Please change the parent to .`)}let u=Ri(),d;if(t){let e=typeof t==`string`?jt(t):t;R(c===`/`||e.pathname?.startsWith(c),`When overriding the location using \`\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${c}" but pathname "${e.pathname}" was given in the \`location\` prop.`),d=e}else d=u;let f=d.pathname||`/`,p=f;if(c!==`/`){let e=c.replace(/^\//,``).split(`/`);p=`/`+f.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let m=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):Ut(e,{pathname:p});Et(l||m!=null,`No routes matched location "${d.pathname}${d.search}${d.hash}" `),Et(m==null||m[m.length-1].route.element!==void 0||m[m.length-1].route.Component!==void 0||m[m.length-1].route.lazy!==void 0,`Matched leaf route at location "${d.pathname}${d.search}${d.hash}" does not have an element or Component. This means it will render an with a null value by default resulting in an "empty" page.`);let h=ea(m&&m.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:xn([c,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?c:xn([c,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&h?I.createElement(ki.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...d},navigationType:`POP`}},h):h}function Ji(){let e=sa(),t=On(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null,r=`rgba(200,200,200, 0.5)`,i={padding:`0.5rem`,backgroundColor:r},a={padding:`2px 4px`,backgroundColor:r},o=null;return console.error(`Error handled by React Router default ErrorBoundary:`,e),o=I.createElement(I.Fragment,null,I.createElement(`p`,null,`💿 Hey developer 👋`),I.createElement(`p`,null,`You can provide a way better UX than this when your app throws errors by providing your own `,I.createElement(`code`,{style:a},`ErrorBoundary`),` or`,` `,I.createElement(`code`,{style:a},`errorElement`),` prop on your route.`)),I.createElement(I.Fragment,null,I.createElement(`h2`,null,`Unexpected Application Error!`),I.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?I.createElement(`pre`,{style:i},n):null,o)}var Yi=I.createElement(Ji,null),Xi=class extends I.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=Fi(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:I.createElement(Ai.Provider,{value:this.props.routeContext},I.createElement(ji.Provider,{value:e,children:this.props.component}));return this.context?I.createElement(Qi,{error:e},t):t}};Xi.contextType=Ci;var Zi=new WeakMap;function Qi({children:e,error:t}){let{basename:n}=I.useContext(Oi);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=z(t.digest);if(e){let r=Zi.get(t);if(r)throw r;let i=jn(e.location,n),a=i.absoluteURL||i.to;if(Ir(a))throw Error(`Invalid redirect location`);if(An&&!Zi.get(t)){if(i.isExternal||e.reloadDocument)window.location.href=a;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(i.to,{replace:e.replace}));throw Zi.set(t,n),n}}return I.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${a}`})}}return e}function $i({routeContext:e,match:t,children:n}){let r=I.useContext(xi);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),I.createElement(Ai.Provider,{value:e},n)}function ea(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);R(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:kn(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||Yi,o&&(s<0&&c===0?(ua(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?I.createElement(n.route.Component,null):n.route.element?n.route.element:e,I.createElement($i,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?I.createElement(Xi,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function ta(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function na(e){let t=I.useContext(xi);return R(t,ta(e)),t}function ra(e){let t=I.useContext(Si);return R(t,ta(e)),t}function ia(e){let t=I.useContext(Ai);return R(t,ta(e)),t}function aa(e){let t=ia(e),n=t.matches[t.matches.length-1];return R(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function oa(){return aa(`useRouteId`)}function sa(){let e=I.useContext(ji),t=ra(`useRouteError`),n=aa(`useRouteError`);return e===void 0?t.errors?.[n]:e}function ca(){let{router:e}=na(`useNavigate`),t=aa(`useNavigate`),n=I.useRef(!1);return Bi(()=>{n.current=!0}),I.useCallback(async(r,i={})=>{Et(n.current,zi),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var la={};function ua(e,t,n){!t&&!la[e]&&(la[e]=!0,Et(!1,n))}var da={};function fa(e,t){!e&&!da[t]&&(da[t]=!0,console.warn(t))}var pa=I.useOptimistic,ma=()=>void 0;function ha(e){return pa?pa(e):[e,ma]}function ga(e){let t={hasErrorBoundary:e.hasErrorBoundary||e.ErrorBoundary!=null||e.errorElement!=null};return e.Component&&(e.element&&Et(!1,"You should not include both `Component` and `element` on your route - `Component` will be used."),Object.assign(t,{element:I.createElement(e.Component),Component:void 0})),e.HydrateFallback&&(e.hydrateFallbackElement&&Et(!1,"You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used."),Object.assign(t,{hydrateFallbackElement:I.createElement(e.HydrateFallback),HydrateFallback:void 0})),e.ErrorBoundary&&(e.errorElement&&Et(!1,"You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used."),Object.assign(t,{errorElement:I.createElement(e.ErrorBoundary),ErrorBoundary:void 0})),t}var _a=[`HydrateFallback`,`hydrateFallbackElement`],va=class{constructor(){this.status=`pending`,this.promise=new Promise((e,t)=>{this.resolve=t=>{this.status===`pending`&&(this.status=`resolved`,e(t))},this.reject=e=>{this.status===`pending`&&(this.status=`rejected`,t(e))}})}};function ya({router:e,flushSync:t,onError:n,useTransitions:r}){r=wi()||r;let[i,a]=I.useState(e.state),[o,s]=ha(i),[c,l]=I.useState(),[u,d]=I.useState({isTransitioning:!1}),[f,p]=I.useState(),[m,h]=I.useState(),[g,_]=I.useState(),v=I.useRef(new Map),y=I.useCallback((i,{deletedFetchers:o,newErrors:c,flushSync:u,viewTransitionOpts:g})=>{c&&n&&Object.values(c).forEach(e=>n(e,{location:i.location,params:i.matches[0]?.params??{},pattern:kn(i.matches)})),i.fetchers.forEach((e,t)=>{e.data!==void 0&&v.current.set(t,e.data)}),o.forEach(e=>v.current.delete(e)),fa(u===!1||t!=null,'You provided the `flushSync` option to a router update, but you are not using the `` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.');let y=e.window!=null&&e.window.document!=null&&typeof e.window.document.startViewTransition==`function`;if(fa(g==null||y,"You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."),!g||!y){t&&u?t(()=>a(i)):r===!1?a(i):I.startTransition(()=>{r===!0&&s(e=>ba(e,i)),a(i)});return}if(t&&u){t(()=>{m&&(f?.resolve(),m.skipTransition()),d({isTransitioning:!0,flushSync:!0,currentLocation:g.currentLocation,nextLocation:g.nextLocation})});let n=e.window.document.startViewTransition(()=>{t(()=>a(i))});n.finished.finally(()=>{t(()=>{p(void 0),h(void 0),l(void 0),d({isTransitioning:!1})})}),t(()=>h(n));return}m?(f?.resolve(),m.skipTransition(),_({state:i,currentLocation:g.currentLocation,nextLocation:g.nextLocation})):(l(i),d({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}))},[e.window,t,m,f,r,s,n]);I.useLayoutEffect(()=>e.subscribe(y),[e,y]),I.useEffect(()=>{u.isTransitioning&&!u.flushSync&&p(new va)},[u]),I.useEffect(()=>{if(f&&c&&e.window){let t=c,n=f.promise,i=e.window.document.startViewTransition(async()=>{r===!1?a(t):I.startTransition(()=>{r===!0&&s(e=>ba(e,t)),a(t)}),await n});i.finished.finally(()=>{p(void 0),h(void 0),l(void 0),d({isTransitioning:!1})}),h(i)}},[c,f,e.window,r,s]),I.useEffect(()=>{f&&c&&o.location.key===c.location.key&&f.resolve()},[f,m,o.location,c]),I.useEffect(()=>{!u.isTransitioning&&g&&(l(g.state),d({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}),_(void 0))},[u.isTransitioning,g]);let b=I.useMemo(()=>({createHref:e.createHref,encodeLocation:e.encodeLocation,go:t=>e.navigate(t),push:(t,n,r)=>e.navigate(t,{state:n,preventScrollReset:r?.preventScrollReset}),replace:(t,n,r)=>e.navigate(t,{replace:!0,state:n,preventScrollReset:r?.preventScrollReset})}),[e]),x=e.basename||`/`,S=I.useMemo(()=>({router:e,navigator:b,static:!1,basename:x,onError:n}),[e,b,x,n]);return I.createElement(I.Fragment,null,I.createElement(xi.Provider,{value:S},I.createElement(Si.Provider,{value:o},I.createElement(Ei.Provider,{value:v.current},I.createElement(Ti.Provider,{value:u},I.createElement(wa,{basename:x,location:o.location,navigationType:o.historyAction,navigator:b,useTransitions:r},I.createElement(xa,{routes:e.routes,manifest:e.manifest,future:e.future,state:o,isStatic:!1,onError:n})))))),null)}function ba(e,t){return{...e,navigation:t.navigation.state===`idle`?e.navigation:t.navigation,revalidation:t.revalidation===`idle`?e.revalidation:t.revalidation,actionData:t.navigation.state===`submitting`?e.actionData:t.actionData,fetchers:t.fetchers}}var xa=I.memo(Sa);function Sa({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return qi(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function Ca(e){return Wi(e.context)}function wa({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){R(!Li(),`You cannot render a inside another . You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=I.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=jt(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=I.useMemo(()=>{let e=dn(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return Et(h!=null,` is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the won't render anything.`),h==null?null:I.createElement(Oi.Provider,{value:c},I.createElement(ki.Provider,{children:t,value:h}))}I.Component;var Ta=`get`,Ea=`application/x-www-form-urlencoded`;function Da(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function Oa(e){return Da(e)&&e.tagName.toLowerCase()===`button`}function ka(e){return Da(e)&&e.tagName.toLowerCase()===`form`}function Aa(e){return Da(e)&&e.tagName.toLowerCase()===`input`}function ja(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function Ma(e,t){return e.button===0&&(!t||t===`_self`)&&!ja(e)}function Na(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function Pa(e,t){let n=Na(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var Fa=null;function Ia(){if(Fa===null)try{new FormData(document.createElement(`form`),0),Fa=!1}catch{Fa=!0}return Fa}var La=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function Ra(e){return e!=null&&!La.has(e)?(Et(!1,`"${e}" is not a valid \`encType\` for \`
\`/\`\` and will default to "${Ea}"`),null):e}function za(e,t){let n,r,i,a,o;if(ka(e)){let o=e.getAttribute(`action`);r=o?dn(o,t):null,n=e.getAttribute(`method`)||Ta,i=Ra(e.getAttribute(`enctype`))||Ea,a=new FormData(e)}else if(Oa(e)||Aa(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a