From f5dd2fee3139a4192708fbca097aaa885b23d1c2 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 15:27:17 -0700 Subject: [PATCH 01/30] docs: design the full UI without an LLM key and plan FanQL batch 1 --- docs/superpowers/plans/2026-10-29-fanql.md | 1591 +++++++++++++++++ .../specs/2026-10-29-no-llm-ui-design.md | 628 +++++++ 2 files changed, 2219 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-29-fanql.md create mode 100644 docs/superpowers/specs/2026-10-29-no-llm-ui-design.md diff --git a/docs/superpowers/plans/2026-10-29-fanql.md b/docs/superpowers/plans/2026-10-29-fanql.md new file mode 100644 index 00000000..a073f1dd --- /dev/null +++ b/docs/superpowers/plans/2026-10-29-fanql.md @@ -0,0 +1,1591 @@ +# FanQL Batch 1 Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Ship FanQL 1 end to end on the backend: lexer, parser, resolver, lowering, printer and lift, the measure-expression extension in `internal/panel`, completion, the HTTP routes, the MCP input and resource, the generated reference, and the acceptance test suite; then fold in the already-reviewed "hide AI controls when chat is disabled" UI change so one branch carries everything the Explore UI (batch 2) needs. + +**Architecture:** A new package `internal/fanql` owns the language: `Lex` (two contexts) → `Parse` (tree with spans, recovering diagnostics) → `Resolve` (catalog, vocabularies, severity bands, `QueryShape`) → `lower` (pure, to `panel.Query`) → `Print` (canonical text, frozen per version); `Format` lifts a stored `panel.Query` back through an injected `panel.Parser` (DuckDB's parse tree) with an exactness gate and raw fallback. `internal/panel` gains read-only catalog accessors, `QueryShape`, additive `Problem.Span`/`FixIts`, and the measure expression parser that replaces the single-call regex (budgets, `count_if` through `checkFilter`, `nullif` division, unit inference, ranking metadata, `compileItems` and trends integration). `internal/telemetry/severity.go` becomes the one severity table for ingest and FanQL. `internal/api/fanql.go` serves parse/format/complete/reference; `internal/mcp` accepts `text` on `query_telemetry` and serves `fanout://fanql/reference`. + +**Tech Stack:** Go (hand-written lexer, recursive descent, Pratt loops), Echo, the MCP Go SDK already in `internal/mcp`, the pinned DuckDB 2 engine through `scripts/with-duckdb.sh`, `go test -fuzz`, Vitest for the folded UI change. + +**Spec:** `docs/superpowers/specs/2026-10-29-no-llm-ui-design.md`, section 0 (subsections 0.1–0.16). Section references below ("0.7") are to that spec. + +This is batch 1. Batch 2 is the Explore page and its builder, search bars, URL envelope, completion UI and the `editable: false` builder/Save preservation tests (0.11 guarantee 6, UI half). + +## Global Constraints + +- Work on branch `feat/fanql` created from `origin/main` in an in-repo worktree under `.claude/worktrees/` (`git worktree add .claude/worktrees/fanql -b feat/fanql origin/main`); the worktree directory is already git-ignored. +- Conventional commits with scope `fanql`, `panel`, `api`, `mcp` or `ui` (`feat(fanql): …`, `refactor(panel): …`, `test(fanql): …`); one commit per task unless a task lists two. +- NO AI session links or private paths in commits or PR bodies (AGENTS.md public-repository rule); commit messages end with the subject and body only. +- AGENTS.md API and MCP naming: routes `/api/fanql/parse|format|complete|reference`, snake_case JSON, `{code, message}` errors, tool errors `error: {code, message}`, tool annotations reflect behaviour. +- No legacy or fallback paths: `measurePattern` is deleted when the expression parser lands; no second measure parser, no alias routes, no second severity table. +- One renderer: FanQL produces `panel.Query` only; results render through the existing panel engine and `PanelCard`. +- Panels keep storing structured queries; text is derived, never stored (0.13). +- The DuckDB SQL gate is unchanged except the specified measure-expression extension (`count(*) FILTER (WHERE …)` emitted by the compiler for `count_if`; `count_if` filters go through `checkFilter` with no variables); `walkFilter` keeps rejecting `FILTER` inside filters. +- `just check` passes at the end of every task before its commit (where a task notes a long-running DuckDB suite, also run `just test`). + +## Review Focus + +The five most likely user-facing failure modes, each with its test: + +1. **A clause word, operator or pipe inside quotes, a bracket key, a raw entry or parentheses splits or rewrites the query** (`logs where body:"a | b sort c" attributes['x.by']:y`, `` `coalesce(body,'|')=''` ``). Test: `TestLexClauseWordsInsideDelimitersStayTokens` (Task 1) and `TestLowerPositiveFixtures` rows for `http.target:"/a:b"` and `"http://x:8080/y"` (Task 4). +2. **Prefix negation silently drops rows missing the field, or SQL `!=` silently includes them.** `-http.target:/healthz` must count spans without `http.target`; `http.target!=/healthz` must not; `-http_status_code between 400 and 599` must match a present non-numeric value. Test: `TestTruthTable` on DuckDB rows present-equal, present-different, present-uncastable and missing (Task 11). +3. **A variable set to All removes more or less than the user grouped.** `(service:$service status:error)` drops both; `service:$service status:error` keeps the status filter. Test: `TestLowerEntryBoundaries` (Task 4) and `TestVariablesUnderAllPerConstruct` (Task 11). +4. **Opening a stored dashboard changes its query.** Every default-dashboard and eval-fixture query must format and re-lower to itself under the reported tier with identical `Check` results and entry counts; an oversized text must be complete, `editable: false`, and never submitted to `parse`. Test: `TestRoundTripStoredDashboards` and `TestEditableFalsePreservationThroughEnvelope` (Task 11), `TestFormatEditableFalseIsCompleteAndReasoned` (Task 5). +5. **A 1/1 series displaces a 100/1000 series in a ratio chart's top-6.** `count_if(status:error) / count() as r by service` must rank the supported failure first and report the sub-floor series as ranked last. Test: `TestRankingFixtures` sparse-denominator and neutral cases with `Result.Ranking.below_floor` (Task 6). + +--- + +### Task 1: Lexer with filter and measure contexts + +**Files:** +- Create: `internal/fanql/fanql.go` (package doc, `Version`) +- Create: `internal/fanql/lexer.go` +- Test: `internal/fanql/lexer_test.go` + +**Interfaces:** +- Produces: + +```go +package fanql + +const Version = 1 + +type Context uint8 +const ( + FilterContext Context = iota + MeasureContext +) + +type Kind uint8 +const ( + EOF Kind = iota + Word // filter context: any bare run of wordchars (fields, values, keywords, numbers, durations, $vars) + Ident // measure context identifier + Path // measure context dotted identifier run, one token (user.id, resource.k8s.pod.name) + String // quoted literal, either quote; Text is the decoded value + Raw // backtick entry; Text is the decoded body + BracketKey // String immediately after attributes[ or resource[; Text is the key + Number // measure context only: 1.5, 1e3 + Punct // ( ) , : = != <> > >= < <= ~ !~ | [ ] + - * / + Bad // with Message and Hint +) + +type Span struct { + Start, End int // code points, end exclusive +} + +type Token struct { + Kind Kind + Text string // decoded for String/Raw/BracketKey; source text otherwise + Quote byte // '"', '\'' or '`' for String/Raw/BracketKey + Unclosed bool // String/Raw/BracketKey that ran to the end of the text + Ctx Context + Span Span + Message string // Bad only + Hint string // Bad only +} + +type Tokens []Token + +// Lex never fails and always ends with EOF. It switches to MeasureContext after a +// depth-0 "|" and back to FilterContext at a depth-0 by/every/sort/limit/"|" or +// the end (the clause word itself is a FilterContext Word); "count_if(" enters +// FilterContext until its matching ")" (parentheses inside String and Raw do not count). +func Lex(text string) Tokens +``` + +- The filter context has no `Number` token: numbers, durations and booleans are `Word` tokens classified by the parser in value position (0.3 rule 8). A leading `-` or `+` is a `Punct`; the parser applies the sign rule (0.3 rule 7). `$service` is one `Word`; `$` followed by anything else is `Bad` `unexpected $`. +- Wordchar rule from 0.2: any rune except whitespace and `| ( ) , : = ! < > ~ " ' ` [ ]`; `-`/`+` are wordchars except as the first rune; `*` only as the whole token; `# { } @` are never wordchars (`@`, `{` and `!` become `Bad` tokens whose messages the parser completes with the following word: `"@http.target" is not a field name; write the attribute without @: http.target`, `{ selectors are not FanQL; write labels as key:value, e.g. service:api`, `! negation is not FanQL; write -service:api`). +- Operators longest-match first: `>=`, `<=`, `!=`, `<>`, `!~` before `>`, `<`, `=`, `~`; a bare `~~` is `Bad` with hint `~~ is SQL LIKE; use like, ilike or ~`. + +- [ ] **Step 1: Write the failing tests** + +```go +func TestLexFilterContextTokens(t *testing.T) +// `spans where http.target:/a:b duration>=500ms -k:v us-east-1 $svc` -> +// Word(spans) Word(where) Word(http.target) Punct(:) Word(/a) Punct(:) Word(b) Word(duration) Punct(>=) +// Word(500ms) Punct(-) Word(k) Punct(:) Word(v) Word(us-east-1) Word($svc) EOF; every Ctx == FilterContext + +func TestLexLongestMatchOperators(t *testing.T) +// `a>=b a<>b a!~b a!=b a:>b a<=b` -> Punct texts in order: ">=", "<>", "!~", "!=", ":", ">", "<=" + +func TestLexBadTokens(t *testing.T) +// `!service:api` -> tokens[0].Kind == Bad, Text "!", Message "! negation is not FanQL" +// `body ~~ x` -> Bad "~~", Hint "~~ is SQL LIKE; use like, ilike or ~" +// `#tag` -> Bad "#"; `$ x` -> Bad "$" Message "unexpected $" + +func TestLexStringsAndQuoteDoubling(t *testing.T) +// `k:"a ""b"" c"` -> String Text `a "b" c`, Quote '"', Unclosed false +// `k:'it''s'` -> String Text "it's" +// `k:"unclosed` -> String Unclosed true, Span.End == len([]rune(text)) + +func TestLexRawEntries(t *testing.T) +// "`coalesce(body, '``') = ''`" -> Raw Text "coalesce(body, '`') = ''" +// "`coalesce(a" -> Raw Unclosed true + +func TestLexBracketKeys(t *testing.T) +// `attributes['http.target']:x` -> Word(attributes) Punct([) BracketKey(http.target) Punct(]) Punct(:) Word(x) +// `resource["k8s.` -> BracketKey Text "k8s." Unclosed true +// `k:'x'` -> String, not BracketKey (no preceding "[") + +func TestLexMeasureContextSwitching(t *testing.T) +// `spans where a:1 | count_if(status:error -http.target:/healthz) / count() * 1.5 as x by resource.k8s.pod.name every 1m` +// after "|": Ident(count_if) Punct(() [FilterContext: Word(status) Punct(:) Word(error) Punct(-) Word(http.target) Punct(:) Word(/healthz)] +// Punct()) [MeasureContext: Punct(/) Ident(count) Punct(() Punct()) Punct(*) Number(1.5) Ident(as) Ident(x)] +// then Word(by) Word(resource.k8s.pod.name) Word(every) Word(1m) with Ctx FilterContext + +func TestLexPathAndNumberInMeasureContext(t *testing.T) +// `spans | count_distinct(user.id) + avg(attributes.http.response_size) - p95(resource.k) * 1e3 as spread` +// -> Path(user.id), Path(attributes.http.response_size), Path(resource.k), Number(1e3) +// `spans | avg(user.)` -> Ident(user) then Bad(".") Message "unexpected . after user; write the full key, e.g. user.id" +// `spans | count_distinct(x-y)` -> Ident(x) Punct(-) Ident(y) +// `spans | count() * -1 as neg` -> Punct(*) Punct(-) Number(1) + +func TestLexCountIfParenDepthIgnoresStringsAndRaw(t *testing.T) +// "spans | count_if(body:\"a)b\" `x = ')'`) / count() as r" -> the ")" that ends count_if is the one before "/"; "/" is a MeasureContext Punct + +func TestLexSpansAreCodePoints(t *testing.T) +// `logs where body:"héllo ✓" x` -> String Span {16, 25}; Word(x) Span {26, 27} + +func TestLexClauseWordsInsideDelimitersStayTokens(t *testing.T) // Review Focus 1 +// `logs where body:"a | b sort c" attributes['x.by']:y` -> exactly one String token containing "a | b sort c"; +// exactly one BracketKey "x.by"; no Punct "|" and no Word "sort" +// "logs where `coalesce(body,'|')=''` | count()" -> one Raw token; exactly one Punct "|" (the stage pipe) + +func TestLexAlwaysEndsWithEOFAndNeverPanics(t *testing.T) +// inputs: "", "|", "((((", "\"", "`", "attributes[", "$", strings.Repeat("-", 100), "\xff\xfe" -> last token EOF, no panic +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/fanql/...` +Expected: FAIL, package `fanql` has no `Lex`. + +- [ ] **Step 3: Implement `Lex` in `internal/fanql/lexer.go`** + +Scan `[]rune(text)` with an index so spans are code points. State: current `Context`, a `count_if` paren depth stack, the previous significant token (for `BracketKey` detection: a `String` whose previous two tokens are `Word`/`Ident` `attributes`|`resource` and `Punct` `[`). Context switch rules exactly as the `Lex` comment states; the measure-context word rule: a run starting with a letter or `_` is `Ident`, extended greedily to `Path` when a `.` is immediately followed by a letter or `_`; a run starting with a digit is `Number` (digits, optional `.digits`, optional exponent); any other rune is `Punct` when in the punct set, else `Bad`. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test ./internal/fanql/...` +Expected: PASS + +- [ ] **Step 5: Commit** + +```bash +git add internal/fanql +git commit -m "feat(fanql): lex FanQL text in filter and measure contexts" +``` + +### Task 2: Parser, tree and recovering diagnostics + +**Files:** +- Modify: `internal/panel/problems.go` (additive `TextSpan`, `FixIt`, `Problem.Span`, `Problem.FixIts`) +- Test: `internal/panel/problems_test.go` (JSON shape) +- Create: `internal/fanql/ast.go`, `internal/fanql/parser.go`, `internal/fanql/words.go` +- Test: `internal/fanql/parser_test.go` + +**Interfaces:** +- Consumes: `Lex`, `Tokens`, `Token`, `Span` (Task 1). +- Produces in `internal/panel/problems.go` (0.12): + +```go +type TextSpan struct { + Start int `json:"start"` + End int `json:"end"` +} +type FixIt struct { + Label string `json:"label"` + Span TextSpan `json:"span"` + Text string `json:"text"` +} +type Problem struct { + Path string `json:"path"` + Message string `json:"message"` + Hint string `json:"hint,omitempty"` + Span *TextSpan `json:"span,omitempty"` + FixIts []FixIt `json:"fix_its,omitempty"` + productDiagnosis bool +} +``` + +- Produces in `internal/fanql/ast.go`: + +```go +type Query struct { + Source string + SourceSpan Span + Where []Expr // ordered entries (0.6) + WhereWord bool // "where" was present on input + Stage *Stage + Sort *Sort + Limit *Limit + Span Span +} + +type Expr interface{ Span() Span } +type And struct{ Terms []Expr; At Span } +type Or struct{ Terms []Expr; At Span } +type Not struct{ X Expr; At Span } +type Compare struct{ Field Field; Op string; Value Value; At Span } // Op: ":" "=" "!=" "<>" ">" ">=" "<" "<=" "~" "!~" (":>" etc. normalised to the comparison) +type In struct{ Field Field; Values []Value; Variable string; Negated bool; At Span } // Negated: SQL "not in" +type Between struct{ Field Field; Lo, Hi Value; Negated bool; At Span } +type Like struct{ Field Field; Pattern Value; Insensitive bool; Negated bool; At Span } +type IsNull struct{ Field Field; Negated bool; At Span } // is [not] null +type Exists struct{ Field Field; At Span } // k:* (-k:* parses as Not{Exists}) +type Call struct{ Name string; Args []CallArg; Cmp *Comparison; At Span } // predicate_call; Name lowercased +type CallArg struct{ Field *Field; Value *Value; Call *Call } +type Comparison struct{ Op string; Value Value } +type FreeText struct{ Value Value; At Span } +type Raw struct{ Text string; At Span } + +type Field struct { + Scope string // "", "attributes" or "resource" + Key string // dotted path or bracket key as typed; for a single bare segment, that segment + Bracket bool + Single bool // one bare segment: column or attributes['ident'], resolved in Task 3 + Ref *FieldRef // set by Resolve (Task 3) + At Span +} + +type ValueKind uint8 +const (WordValue ValueKind = iota; StringValue; NumberValue; DurationValue; BooleanValue; VariableValue; StarValue) +type Value struct { + Kind ValueKind + Text string // as typed (decoded for strings); numbers keep their sign ("-3"); durations keep the unit ("1.5s") + Stored string // set by Resolve: alias-mapped stored spelling, or Text + At Span +} + +type Stage struct { + Measures []Measure + Histogram *Field + By []Field + Bucket string // "" when absent; lowercased + At Span +} +type Measure struct{ Expr MExpr; Alias string; At Span } +type MExpr interface{ Span() Span } +type MCall struct{ Name string; Args []MArg; At Span } // Name lowercased +type MArg struct{ Field *Field; Number *float64; Star bool; At Span } +type MCountIf struct{ Filter Expr; At Span } // one entry (And, Or or leaf) +type MBinary struct{ Op byte; L, R MExpr; At Span } // '+' '-' '*' '/' +type MNeg struct{ X MExpr; At Span } +type MConst struct{ Value float64; Text string; At Span } + +type Sort struct{ Key string; Ascending bool; At Span } +type Limit struct{ N int; At Span } +``` + +- Produces in `internal/fanql/parser.go`: + +```go +const ( + MaxTextRunes = 4000 + MaxTextBytes = 8192 + MaxTokens = 1024 + MaxNodes = 512 + MaxDepth = 16 + MaxListItems = 100 + MaxProblems = 20 +) + +// Parse enforces the interactive bounds, lexes and parses. It returns a nil +// *Query whenever problems is non-empty (0.12 error model). source is "" for a +// whole query or "spans"|"logs"|"metrics" for search-bar filters only. +func Parse(text string, source string) (*Query, panel.Problems) + +// parseEntry is the unbounded internal entry parser used by the lift gate (Task 5). +func parseEntry(text string) (Expr, panel.Problems) +``` + +- `words.go` holds the tables of 0.3: sources, clause words, expression words, modifiers, bucket names (the twelve plus `auto`), reserved words, foreign-syntax triggers with their messages and hints, the fixed message strings of 0.3 and 0.4. +- Problems from the parser use `Path: "text"`, carry a `Span`, are sorted by `Span.Start`, and are capped at 20 with `more problems follow; fix these first` as the 21st. + +- [ ] **Step 1: Write the failing tests** + +```go +// internal/panel/problems_test.go +func TestProblemJSONCarriesSpanAndFixIts(t *testing.T) +// Problem{Path:"text", Message:"m", Span:&TextSpan{1,4}, FixIts:[]FixIt{{Label:"l", Span:TextSpan{1,4}, Text:"x"}}} marshals to +// {"path":"text","message":"m","span":{"start":1,"end":4},"fix_its":[{"label":"l","span":{"start":1,"end":4},"text":"x"}]} +// and Problem{Path:"p",Message:"m"} marshals without span or fix_its; PresentProblems keeps both fields. + +// internal/fanql/parser_test.go +func TestParseEntriesAndGrouping(t *testing.T) +// `spans where a:1 b:2 (c:3 or d:4) (e:5 f:6)` -> len(Where)==4; types Compare, Compare, *Or (2 terms), *And (2 terms) +// `spans where a:1 or b:2` -> len(Where)==1, *Or +// `spans where (a:1)` -> len(Where)==1, *Compare (parentheses around one term add no node) +// `spans status:error | count()` -> WhereWord false, len(Where)==1 + +func TestParseMixedAndOrIsRejectedWithFixIts(t *testing.T) +// `spans where a:1 b:2 or c:3` -> q == nil; problems[0].Message == "mixed and/or needs parentheses"; +// Hint == "write a:1 (b:2 or c:3) or (a:1 b:2) or c:3"; Span covers "a:1 b:2 or c:3"; +// FixIts == [{"a:1 (b:2 or c:3)"}, {"(a:1 b:2) or c:3"}] (Text fields; both Spans == the problem span) +// `spans where a:1 and b:2 or c:3` -> same message +// `spans where a:1 or b:2 c:3` -> Hint "write a:1 or (b:2 c:3) or (a:1 or b:2) c:3" +// `spans where (a:1 b:2 or c:3)` -> same message, span inside the group +// `spans | count_if(a:1 b:2 or c:3) as x` -> same message, span inside count_if + +func TestParseNegationNesting(t *testing.T) +// `logs where --severity:error` -> Not{Not{Compare}}; `not not a:1` same; `-not a:1` same +// `spans where -(a:1 or b:2)` -> len(Where)==1, Not{Or} +// `spans where not a:1 b:2` -> [Not{Compare}, Compare] + +func TestParseValueClassification(t *testing.T) +// k:500 -> NumberValue "500"; k:1.5s -> DurationValue "1.5s"; k:true -> BooleanValue; k:$v -> VariableValue "$v"; +// k:* -> *Exists; k:"500" -> StringValue "500"; value>-3 -> NumberValue "-3"; k:api -> WordValue; +// start_time>"2026-10-29T10:00:00Z" -> StringValue (timestamps are typed in Task 3); k:-foo -> problem "k: needs a value; e.g. k:api" + +func TestParseColonEndsWord(t *testing.T) +// `spans where http.target:/a:b` -> problem "unexpected : after /a", Hint `quote the value: http.target:"/a:b"`, Span over "http.target:/a:b" +// `logs where http://x:8080/y` -> problem "unexpected : after http", Hint `quote the value: "http://x:8080/y"` + +func TestParseFieldVsFreeText(t *testing.T) +// `logs where service` -> *FreeText "service" (the notice is Task 3's) +// `logs where service:where` -> Compare value WordValue "where" +// `logs where service in (sort, limit)` -> In with 2 values +// `logs where "limit"` -> FreeText StringValue +// `logs where limit 10` -> problem "where needs a filter", Hint `quote "limit" to search for the word, or drop where` +// `logs where in` -> FreeText "in"; `spans where service:join` -> Compare, no problem + +func TestParseOperatorsAfterField(t *testing.T) +// in / not in / between / not between / is null / is not null / like / ilike / not like / not ilike each produce the right node and flags +// `k:>5` -> Compare Op ">" ; `k like a%` -> problem "like needs a quoted pattern" +// `duration between 1s` -> problem "between needs two values" +// `service in $svcs` -> In{Variable:"svcs"} + +func TestParseCalls(t *testing.T) +// `starts_with(http_route, "/api")` -> Call{Name:"starts_with", Args:[Field, Value]} +// `length(body) > 1000` -> Call with Cmp{">", "1000"} +// `starts_with (x, "y")` -> problem "write starts_with(...) without a space" +// `P95(Duration)` -> Call{Name:"p95"} (rejected by Task 3) + +func TestParseStageMeasuresAndArithmetic(t *testing.T) +// `spans | count_if(status:error) / count() * 100 as err_pct by http_route every 1m sort err_pct limit 10` +// -> Measures[0].Expr == MBinary{'*', MBinary{'/', MCountIf{Compare}, MCall{count}}, MConst{100}}; Alias "err_pct"; +// By == [http_route]; Bucket "1m"; Sort{Key:"err_pct", Ascending:false}; Limit{10} +// `spans | p95(duration)-p50(duration) as spread` -> MBinary{'-', MCall, MCall} (no-space arithmetic) +// `spans | count() * -1 as neg` -> MBinary{'*', MCall, MNeg{MConst{1}}} +// `spans | count()*100 as c100`, `count()/count() as one`, `count() * 1e3 as k` (MConst{1000, "1e3"}), `count() * 1.5 as x` +// `spans | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex` -> depth 4, 3 aggregate leaves +// `spans | count() +` -> problem "+ needs a measure or number on both sides" + +func TestParseExpressionRules(t *testing.T) +// `spans | count() / 2` -> "name this expression with as, e.g. count() / 2 as half" +// `spans | share() / 2 as half` -> "share() cannot be combined; it is already a percentage of the scope", Hint "use share() alone, or count_if(...) / count() * 100 for a custom ratio" +// `spans | 1 as one`, `1 / 2 as half`, `-(5) as neg` -> "a measure needs an aggregate; constants can only scale one, e.g. count() * 100" at the expression span +// `spans | count() * 0 as zero` -> no problem +// `spans | histogram(duration), count()` -> "distribution counts require count(); histogram(...) stands alone" +// `spans | histogram(duration) by service` -> Stage.Histogram != nil, By 1 +// `spans | count(*)` -> MCall{count, [Star]} + +func TestParseSortLimitAndSecondPipe(t *testing.T) +// `sort -count` -> Ascending false; `sort +p95` and `sort p95 asc` -> true; `sort p95 desc` -> false +// `spans sort -p95 asc` -> "sort takes one direction" +// `spans | count() by service | sort count | limit 10` -> Sort{count}, Limit{10}, no problem +// `spans | count() by service | top 3 by count` -> "FanQL 1 runs one aggregation stage", Hint "remove the second |; more stages come in a later version" +// `spans limit 10 sort duration` -> "limit comes before sort here; write ... sort duration limit 10" +// `spans | count() limit 0` -> "limit needs a whole number from 1 to 1000; e.g. limit 50" +// `spans where a:1 where b:2` -> "where appears twice; combine the filters into one where" +// `spans | every 1m` -> "every needs measures first; write | count() every 1m" +// `spans | count() every 2m` -> `unknown bucket "2m"; use auto or one of 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h, 1d` +// `spans | count() by a, b, c, d` -> "at most 3 grouping fields" + +func TestParseSourceErrors(t *testing.T) +// `traces where a:1` -> `unknown source "traces"`, Hint "use spans; traces is a viz of spans" +// `from spans` -> `"from" is not FanQL; start with the source: spans where ...` +// `` -> `unknown source ""`, Hint "use spans, logs or metrics"; `logs` alone -> Query{Source:"logs"}, no problem + +func TestParseSearchBarFilters(t *testing.T) +// Parse("service:api timeout", "logs") -> Source "logs", len(Where)==2 +// Parse("where service:api", "logs") -> "the page supplies where" +// Parse("| count()", "logs") -> problem (a stage is not a filter) + +func TestParseReservedAndForeignWords(t *testing.T) +// each reserved word at clause position: `spans where join` -> `"join" is reserved for a future FanQL feature`, Hint "quote it to search for the word" +// `spans | summarize count() by service` -> `"summarize" is not FanQL; write the measures after |, e.g. | count() by service` +// `spans where service == "api"` -> "== is not FanQL; use key:value or =" +// `spans where body =~ "re"` -> "=~ is not FanQL; ~ is contains; use regexp_matches(field, 're') for a regular expression" +// `spans where {service="api"}` -> "{ selectors are not FanQL; write labels as key:value, e.g. service:api" +// `spans where @http.target:x` -> `"@http.target" is not a field name; write the attribute without @: http.target` +// `spans where !service:api` -> "! negation is not FanQL; write -service:api" +// `spans since 1h` -> "the time range is not part of FanQL 1; use the time picker (since is reserved)" +// `spans where service:api*` -> "* wildcards are not in FanQL 1", Hint `use ~ for contains, or quote "api*"` +// `spans where stats` -> FreeText (a bare foreign word in filter position is free text) + +func TestParseUnclosedAndUnmatched(t *testing.T) +// `spans where (a:1` -> "unclosed (; add ) before |, sort, limit or the end", Span == the "(" span +// `spans where a:1)` -> "unmatched ); remove it or add the opening (" +// `spans where "abc` -> `unclosed quote; close the value with "` +// "spans where `coalesce(a" -> "unclosed raw filter; close it with `" +// `spans where a:1 or` -> "or needs a filter on both sides" +// `spans where service:` -> "service: needs a value; e.g. service:api" +// `spans where >500ms` -> "a filter needs a field before >" +// `spans where duration>` -> "duration> needs a value; e.g. duration>500ms" + +func TestParseCollectsAllProblemsInOrderCappedAt20(t *testing.T) +// a text with 25 distinct problems -> len(problems)==21; problems sorted by Span.Start; problems[20].Message == "more problems follow; fix these first" +// `traces | stats x take 5` -> 3 problems + +func TestParseBoundsAreEnforcedIndependently(t *testing.T) +// 4,001 code points (ASCII) -> "a query is at most 4000 characters (8192 bytes)"; 3,000 three-byte runes (9,000 bytes) -> same message +// 1,025 tokens within the text bound -> a tokens problem; 513 nodes -> a nodes problem; 17 nested parentheses -> a depth problem +// `service in (v1, …, v101)` -> a list problem at the 101st value; each case yields exactly that one problem + +func TestParseKeywordCaseFolding(t *testing.T) +// `SPANS WHERE Service:API | COUNT() BY service EVERY 1M SORT COUNT LIMIT 5` -> Source "spans", Field.Key "Service" (kept; resolved case-insensitively in Task 3), +// Value "API" (kept), MCall "count", Bucket "1m", Sort "count" + +func TestParseEntryParserIsUnbounded(t *testing.T) +// parseEntry of a 9,000-byte `body:"…"` entry returns an Expr and no problems +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/panel/ -run TestProblemJSON && bash scripts/with-duckdb.sh go test ./internal/fanql/...` +Expected: FAIL, `TextSpan` undefined; `Parse` undefined. + +- [ ] **Step 3: Implement** + +`problems.go`: add the two types and fields; `PresentProblems` already copies whole structs. + +`parser.go`: recursive descent over `Tokens` with a node counter and depth counter (bounds checked before recursing); `filters` uses a Pratt loop at one level that records the first binary kind (`and`/juxtaposition vs `or`) and reports the grouping problem with both fix-it texts on seeing the other; `term` handles `-`/`not`; `primary` dispatches on the lookahead after a `Word` (0.3 rule 4); the sign rule of 0.3 rule 7 combines `Punct(-)` + number-shaped `Word` in value position; measure parsing is a second Pratt loop (`+ -` below `* /` below unary minus) over `MeasureContext` tokens with `count_if(` delegating to `filters`; recovery after a bad term consumes to the next whitespace at the term's depth and synchronizes at clause words. Every message string lives in `words.go`. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test ./internal/panel/... ./internal/fanql/...` +Expected: PASS + +- [ ] **Step 5: Commit** + +```bash +git add internal/panel/problems.go internal/panel/problems_test.go internal/fanql +git commit -m "feat(fanql): parse FanQL into a tree with recovering diagnostics" +``` + +### Task 3: Resolver against the catalog, vocabularies and severity bands + +**Files:** +- Create: `internal/telemetry/severity.go`, `internal/telemetry/severity_test.go` +- Modify: `internal/ingest/server.go` (delete `normalizeSeverity`/`severityFromText`; call `telemetry.NormalizeSeverity`), `internal/ingest/server_test.go` (point the existing severity tests at the shared package; add the invariant test) +- Create: `internal/panel/export.go` (read-only accessors), `internal/panel/export_test.go` +- Create: `internal/panel/shape.go` (`QueryShape`, `CompatibleVizzes`), `internal/panel/shape_test.go` +- Modify: `internal/panel/validate.go`, `internal/panel/rowpanels.go`, `internal/panel/items.go` (call the extracted shape checks; behaviour preserved) +- Create: `internal/fanql/resolve.go`, `internal/fanql/spellings.go` +- Test: `internal/fanql/resolve_test.go` + +**Interfaces:** +- Consumes: `Query`, `Field`, `Value`, `Stage`, `Measure` (Task 2); `panel.Problems`. +- Produces in `internal/telemetry/severity.go`: + +```go +// SeverityBands in ascending rank: TRACE DEBUG INFO WARN ERROR FATAL. +var SeverityBands = [...]string{"TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"} +func NormalizeSeverity(text string, number int32) string // the ingest function, moved verbatim +func SeverityFromText(text string) string // moved verbatim +func SeverityRank(band string) (int, bool) // false for UNSPECIFIED and unknown words +func SeverityAliases() map[string]string // lowercase synonym -> band, generated from SeverityFromText's table +``` + +- Produces in `internal/panel/export.go`: + +```go +func SignalColumns(signal string) ([]Field, bool) // every column incl. TypeMap, display order +func LowCardinalityColumns(signal string) []string +type MeasureSpec struct { + Name string + Args int + Numeric bool + Additive bool + Unit string + Signals []string // empty: every signal + Quantile float64 +} +func MeasureSpecs() []MeasureSpec // sorted by name +func BucketNames() []string // "auto" then the twelve bucket names from the bucket registry +func FilterFunctionNames() []string // lower upper starts_with contains regexp_matches length (not the ~~ operators) +func Suggest(word string, candidates []string) string // wraps suggest +``` + +- Produces in `internal/panel/shape.go` (0.12): + +```go +type VizRequirement string +const ( + RequiresMinMax VizRequirement = "min_max" + RequiresThresholds VizRequirement = "thresholds" +) +// QueryShape runs the in-memory checks that depend only on the query, the viz +// and the variable declarations, extracted from validateQuery, validateRows and +// the query parts of validateItems; it never normalizes. Paths are query-relative +// ("where[2]", "measures[0]", "by[1]", "bucket", "sort", "limit", "from"). +func QueryShape(q *Query, viz string, vars map[string]Variable) (Problems, []VizRequirement) +type VizCompat struct { + Viz string `json:"viz"` + Requires []VizRequirement `json:"requires"` +} +func CompatibleVizzes(q *Query, vars map[string]Variable) []VizCompat // every viz in vizOrder whose QueryShape passes, in vizOrder +``` + +- Produces in `internal/fanql/resolve.go`: + +```go +type FieldRef struct { + Column string // column name, or "attributes"/"resource" for a lookup + Key string // attribute key when a lookup + Type panel.FieldType + Unit string + CompareAs string // "integer" for http_status_code under < <= > >= between (0.8) +} +type Notice struct { + Path string `json:"path"` + Message string `json:"message"` + Span *panel.TextSpan `json:"span,omitempty"` +} +type ResolveOptions struct { + Viz string + Variables []panel.Variable + Schema *panel.Schema // optional; enables the "stored levels in this window" notice +} +type Resolved struct { + Query *Query + Compatible []panel.VizCompat + Edits []VizEdit + Notices []Notice +} +type VizEdit struct { + Viz string `json:"viz"` + Text string `json:"text"` +} +// Resolve annotates the tree in place (Field.Ref, Value.Stored, Compare bands) and +// reports problems with spans. Shape problems come from panel.QueryShape on the +// lowered query (Task 4 wires the lowering; until then shape checks are skipped +// when the lowering hook is nil). +func Resolve(q *Query, opts ResolveOptions) (*Resolved, panel.Problems) +``` + +- `spellings.go`: status, kind, type alias tables (0.9), durations (`us ms s m h` to milliseconds), timestamp recognition (RFC 3339 and `YYYY-MM-DD HH:MM:SS`, optional fraction and offset), the severity table imported from `internal/telemetry`. +- Severity range annotation: `Compare` on `severity` under `< <= > >=` gets `Bands []string` (add `Bands []string` to `Compare` in `ast.go`); `Between` on `severity` likewise. + +- [ ] **Step 1: Write the failing tests** + +```go +// internal/telemetry/severity_test.go +func TestNormalizeSeverityNumberWins(t *testing.T) +// (…, 14) -> "WARN"; ("ERROR", 9) -> "INFO"; ("FATAL", 0) -> "FATAL"; ("INFO2", 0) -> "INFO"; ("warning", 0) -> "WARN"; +// ("custom", 0) -> "CUSTOM"; ("", 0) -> "UNSPECIFIED"; (…, 21) -> "FATAL"; (…, 1) -> "TRACE" +func TestSeverityRankOrder(t *testing.T) // TRACE +// stored Severity == telemetry.NormalizeSeverity(text, number) for each: INFO, FATAL, WARN, INFO, CUSTOM, UNSPECIFIED + +// internal/panel/export_test.go +func TestExportedRegistriesMatchInternalTables(t *testing.T) +// len(MeasureSpecs()) == len(measureFuncs); BucketNames()[0]=="auto" and the rest equal the bucket registry in order; +// FilterFunctionNames() == [contains length lower regexp_matches starts_with upper]; SignalColumns("spans") includes http_status_code with Type TypeString +func TestColumnNamesContainNoDots(t *testing.T) // registry invariant (0.5) for spans, logs, metrics + +// internal/panel/shape_test.go +func TestQueryShapeMatchesValidateQueryProblems(t *testing.T) +// for 12 panels (one per viz, valid and invalid variants): the query-relative problems of QueryShape, prefixed with "panels[0].query.", +// equal the subset of Validate problems whose path starts with "panels[0].query." (messages and hints identical) +func TestQueryShapeRequires(t *testing.T) // gauge -> [min_max]; state_timeline -> [thresholds]; table -> [] +func TestCompatibleVizzesOnQueryAsWritten(t *testing.T) +// {from:spans, where:[kind = 'SPAN_KIND_SERVER'], measures:[count()], by:[http_route]} -> [bar table]; with bucket auto -> [timeseries state_timeline(requires thresholds)] +// {from:spans, where:[status = 'STATUS_CODE_ERROR']} -> [traces]; {from:logs} -> [logs]; {from:logs, measures:[count()], by:[body_template]} -> [bar table log_patterns] +func TestExistingValidateBehaviourUnchanged(t *testing.T) // the existing validate, rowpanels and items tests pass unchanged (run the package) + +// internal/fanql/resolve_test.go +func TestResolveSingleSegmentFieldIsColumnOrAttribute(t *testing.T) +// `spans where value>-3` -> Field.Ref{Column:"attributes", Key:"value"}; notice `"value" is not a spans column; reading attributes['value']` +// `metrics where value>-3` -> Ref{Column:"value", Type:TypeNumber}; no notice +// `metrics where rate:x` -> attribute; notice `"rate" is a measure, not a metrics column; reading attributes['rate']` +// `spans where Service:api` -> Ref{Column:"service"} (case-folded); `spans where servce:api` -> attribute + notice ending "did you mean service?" + +func TestResolveDottedAndPrefixedKeys(t *testing.T) +// `resource.k8s.pod.name:x` -> Ref{Column:"resource", Key:"k8s.pod.name"}; `attributes.http.target:/h` -> {attributes, http.target}; +// `attributes['resource.k']:x` -> {attributes, resource.k}; `HTTP.Target:x` -> Key "HTTP.Target"; `x-y.z:1` -> problem `"x-y.z" needs brackets` +// `spans | count_distinct(user.id)` -> MArg Field Ref {attributes, user.id}; `| p95(resource.k)` -> {resource, k}; `| last(value) by resource.k8s.pod.name` on metrics -> By[0].Ref {resource, k8s.pod.name} + +func TestResolveVocabularies(t *testing.T) +// status:error -> Value.Stored "STATUS_CODE_ERROR"; status:STATUS_CODE_ERROR -> same; status:"error" -> Stored "error"; status:fail -> `unknown status "fail"; use status:error, status:ok or status:unset` +// kind:server -> SPAN_KIND_SERVER; kind:http -> error with the six kinds; metrics type:counter -> "counter" +// severity:warning -> WARN; severity:Error -> ERROR; severity:custom -> CUSTOM + notice "not a standard level; stored levels in this window: ERROR, INFO" (Schema supplied with those values) +// `severity ~ error` -> literal (no mapping); `status in (error, ok)` -> Stored STATUS_CODE_ERROR, STATUS_CODE_OK + +func TestResolveSeverityRanges(t *testing.T) +// severity>=warn -> Bands [WARN ERROR FATAL]; >warn -> [ERROR FATAL]; [TRACE DEBUG INFO WARN]; <=error -> [TRACE DEBUG INFO WARN ERROR] +// between info and error -> [INFO WARN ERROR]; >fatal -> "severity>fatal matches no level; use severity:fatal"; matches no level +// between error and info -> "between needs the lower level first: severity between info and error" +// >=custom -> `"custom" has no severity rank; use trace, debug, info, warn, error or fatal`; >=unspecified -> same shape +// http_status_code>=warn -> no band mapping (literal "warn" on a text column) + +func TestResolveTypedLiterals(t *testing.T) +// `http_status_code>500ms` -> "units apply to duration only; write http_status_code>500" +// `duration>500` -> "duration needs a unit; e.g. duration>500ms"; `duration_ms>500` -> ok; `duration>-1ms` -> "durations are not negative"; `duration>1h30m` -> problem +// `duration_ms:true` -> "duration_ms needs a number"; `time:x` -> `"time" is a time column; compare it with > or <` +// `start_time>"2026-10-29T10:00:00Z"` -> Value typed timestamp; `start_time>"yesterday"` -> problem naming the accepted forms +// `metrics where timeout` -> "free text needs a field on metrics; use name:http.server.duration" +// `http_status_code>=500` -> Field.Ref.CompareAs "integer"; `http_status_code:500` -> CompareAs "" + +func TestResolveFilterFunctions(t *testing.T) +// `spans where P95(Duration)` -> "function p95 is not allowed in a filter" +// `starts_with(http_route, /api)` -> "starts_with needs a quoted string"; `length(body)` -> "length(...) needs a comparison"; `lower(k)` -> "lower(...) needs a comparison" +// `starts_with(http_route, "/api") > 1` -> problem (predicates are not compared) + +func TestResolveMeasures(t *testing.T) +// `spans | p95(service)` -> "p95 needs a numeric field; service is string"; `| p95()` -> "p95 takes 1 argument(s), got 0; e.g. p95(duration)" +// `| count() as P95` -> `alias "P95" must be lowercase letters, digits and underscores`; `| count(), count()` -> "two measures are named count; add distinct aliases with as" +// `metrics | error_rate()` -> "error_rate is not available for metrics"; `spans | last(value)` -> "last is not available for spans" +// `| count_distinct(flag)` -> attribute + notice; `| count_distinct(x-y)` -> "unexpected - in count_distinct; write attributes['x-y']" +// `| count_if(service:$s) as n` -> "variables are not allowed inside count_if"; `metrics | count_if(name:x) as n` -> "measure arithmetic is not available for metrics" +// `| quantile(duration, 2)` -> "quantile q must be a number between 0 and 1"; `| count() by a, b, c, d` -> "at most 3 grouping fields" + +func TestResolveSortKeys(t *testing.T) +// `spans | count() by service sort p95` -> `sort "p95" must name a measure alias; aliases here: count` +// viz traces: `spans sort +duration` -> "traces sort descending by duration, by errors, or ascending by start only"; `sort duration`, `sort errors`, `sort +start` ok; +// `sort errors` -> notice "sort errors also filters to error spans; new queries: write status:error … sort duration" +// viz logs: `logs sort time` and `sort +time` ok, `sort duration` problem; viz log_patterns: only `sort count` +// viz timeseries: `spans | count() every 1m sort count` -> notice "sort does not apply to bucketed series; series are chosen by top (options)"; no viz -> no notice + +func TestResolveVariables(t *testing.T) +// Variables [{service query}, {svcs query multi}]: `service:$region` -> problem listing "service, svcs"; `service:$svcs` -> "$svcs holds several values; use service in $svcs"; `service in $svcs` ok +// no Variables: `service:$x` -> notice "declared variables are needed to check $x"; `$__window:x` -> problem + +func TestResolveCompatibleVizzesAndEdits(t *testing.T) +// `spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route` -> Compatible contains bar and table; +// Edits == [{timeseries, "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route every auto"}] +// `spans where status:error` -> Compatible [traces]; `spans | count()` -> stat, gauge(requires min_max), table +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/telemetry/ ./internal/ingest/ ./internal/panel/ ./internal/fanql/ -run 'Severity|Normalized|Exported|ColumnNames|QueryShape|Compatible|Resolve'` +Expected: FAIL, undefined symbols. + +- [ ] **Step 3: Implement** + +Move the two ingest functions verbatim into `internal/telemetry/severity.go` (exported names) and derive `SeverityAliases` from the same switch table (one table, two readers). `export.go` wraps the existing maps. `shape.go` moves the query-only checks out of `validateQuery`, `validateRows` and `validateItems` into `QueryShape`, which those functions now call with `path` prefixing; nothing else in `Validate` changes. `resolve.go` walks the tree: fields through `SignalColumns` (case-insensitive match; single-segment fallback to `attributes` with the notice; `Suggest` for the did-you-mean), values through the vocabulary tables under the operators 0.9 lists, severity ranges to `Bands`, literals through the typing table of 0.8, measures through `MeasureSpecs`, sort keys against stage aliases or the viz row keys, variables against declarations; then `Compatible` and `Edits` from `panel.CompatibleVizzes` on the lowered query (the lowering hook is installed by Task 4; `Edits` re-runs `QueryShape` with `Bucket: "auto"` for the bucketed vizzes and prints the text with ` every auto` appended). + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test ./internal/telemetry/... ./internal/ingest/... ./internal/panel/... ./internal/fanql/...` +Expected: PASS (all pre-existing ingest and panel tests included). + +- [ ] **Step 5: Commit (two commits)** + +```bash +git add internal/telemetry/severity.go internal/telemetry/severity_test.go internal/ingest internal/panel/export.go internal/panel/export_test.go internal/panel/shape.go internal/panel/shape_test.go internal/panel/validate.go internal/panel/rowpanels.go internal/panel/items.go +git commit -m "refactor(panel): share the severity table, export catalog accessors and extract QueryShape" +git add internal/fanql +git commit -m "feat(fanql): resolve fields, vocabularies and severity ranges against the catalog" +``` + +### Task 4: Lowering to `panel.Query` + +**Files:** +- Create: `internal/fanql/lower.go` +- Modify: `internal/fanql/fanql.go` (`Options`, `Compiled`, `Compile`), `internal/fanql/resolve.go` (install the lowering hook for shape checks) +- Test: `internal/fanql/lower_test.go` + +**Interfaces:** +- Consumes: `Parse`, `Resolve`, `Resolved`, `FieldRef`, `Value.Stored`, `Compare.Bands` (Tasks 2–3); `panel.Query`, `panel.Histogram`. +- Produces: + +```go +type Options struct { + Source string // "" or spans|logs|metrics (search-bar mode) + Viz string + Variables []panel.Variable + Schema *panel.Schema +} +type Compiled struct { + Query panel.Query + Canonical string // set by Task 5 + Notices []Notice + Compatible []panel.VizCompat + Edits []VizEdit +} +// Compile = Parse -> Resolve -> lower -> QueryShape. nil Compiled whenever problems is non-empty. +func Compile(text string, opts Options) (*Compiled, panel.Problems) + +// lower is pure. Entry problems carry the entry's span: "this filter lowers to N bytes; filters are at most 500" +// at the entry; "at most 16 filters" at the 17th entry. +func lower(r *Resolved) (panel.Query, panel.Problems) +func lowerEntry(e Expr) string // one entry -> SQL text (also used by the lift gate, Task 5) +func lowerMeasure(m Measure) string // -> "count_if() / count() * 100 as err_pct" +func containsSQL(field, value string) string // contains(lower(), lower()) +``` + +- Negation lowering follows 0.7 exactly: NNF first; the `(k IS NULL OR …)` rewrite only when the effective operand is the stored field, `duration_ms`, or the `CAST(attributes[…] AS VARCHAR)` inside `contains`; everything else (cast-backed comparisons and ranges on `http_status_code`, attribute numeric comparisons, calls, raw) lowers to `NOT coalesce((p), FALSE)`. +- Sort lowering: `duration` on traces → `duration_ms`; `+key` keeps the plus; measure aliases as typed. + +- [ ] **Step 1: Write the failing tests** + +```go +func TestLowerPositiveFixtures(t *testing.T) +// Table of every positive fixture in spec 0.7–0.10 and the spec's corpus examples; each row: text, viz (optional), want panel.Query. Minimum rows: +// `spans where duration>500ms` W=[duration_ms > 500] +// `spans where value>-3` W=[attributes['value'] > -3] +// `metrics where value>-3` W=[value > -3] +// `spans where -duration>1s` W=[(duration_ms IS NULL OR duration_ms <= 1000)] +// `logs where --severity:error` W=[severity = 'ERROR'] +// `spans where -(status:error kind:server)` W=[((status IS NULL OR status != 'STATUS_CODE_ERROR') OR (kind IS NULL OR kind != 'SPAN_KIND_SERVER'))] +// `spans where http.target:"/a:b"` W=[attributes['http.target'] = '/a:b'] +// `logs where "http://x:8080/y"` W=[contains(lower(body), lower('http://x:8080/y'))] +// `metrics where name:http.server.duration` W=[name = 'http.server.duration'] +// `spans where resource.k8s.pod.name:x` W=[resource['k8s.pod.name'] = 'x'] +// `spans where attributes['resource.k']:x` W=[attributes['resource.k'] = 'x'] +// `spans where flag:true` W=[attributes['flag'] = true] +// `spans where flag:"true"` W=[attributes['flag'] = 'true'] +// `logs where service` W=[contains(lower(body), lower('service'))] +// `logs where service:where` W=[service = 'where'] +// `logs where body ~ "a_b"` W=[contains(lower(body), lower('a_b'))] +// `logs where body ilike "%a_b%"` W=[body ~~* '%a_b%'] +// `logs where body not like "GET %"` W=[body !~~ 'GET %'] +// `logs where -body like "GET %"` W=[(body IS NULL OR body !~~ 'GET %')] +// `logs where -body ~ "100%"` W=[(body IS NULL OR NOT contains(lower(body), lower('100%')))] +// `spans where service in (a, b)` / `not in` / `-service in` W=[service IN ('a', 'b')] / [service NOT IN ('a', 'b')] / [(service IS NULL OR service NOT IN ('a', 'b'))] +// `spans where service in $svcs` W=[service IN $svcs] +// `spans where duration between 1s and 2s status:error` W=[duration_ms BETWEEN 1000 AND 2000, status = 'STATUS_CODE_ERROR'] +// `spans where a:1 or c:3` W=[(attributes['a'] = 1 OR attributes['c'] = 3)] +// `spans where a:1 (b:2 or c:3)` W=[attributes['a'] = 1, (attributes['b'] = 2 OR attributes['c'] = 3)] +// `spans where (a:1 b:2) or c:3` W=[((attributes['a'] = 1 AND attributes['b'] = 2) OR attributes['c'] = 3)] +// `spans where not a:1 b:2` W=[(attributes['a'] IS NULL OR attributes['a'] != 1), attributes['b'] = 2] +// `spans where (a:1 b:2)` W=[(attributes['a'] = 1 AND attributes['b'] = 2)] +// `spans where service:$service (status:error or status:unset)` W=[service = $service, (status = 'STATUS_CODE_ERROR' OR status = 'STATUS_CODE_UNSET')] +// `spans where -http_status_code>=500` W=[NOT coalesce((TRY_CAST(http_status_code AS INTEGER) >= 500), FALSE)] +// `spans where -starts_with(http_route, "/api")` W=[NOT coalesce((starts_with(http_route, '/api')), FALSE)] +// "logs where -`coalesce(body, '') = ''`" W=[NOT coalesce((coalesce(body, '') = ''), FALSE)] +// "logs where `coalesce(body, '``') = ''`" W=[coalesce(body, '`') = ''] +// `spans where HTTP.Target:x` W=[attributes['HTTP.Target'] = 'x'] +// `logs where length(body) > 1000` W=[length(body) > 1000] +// `spans where k:*` / `-user.id:*` W=[attributes['k'] IS NOT NULL] / [attributes['user.id'] IS NULL] +// `spans where http_status_code>=500` / `:500` W=[TRY_CAST(http_status_code AS INTEGER) >= 500] / [http_status_code = '500'] +// `spans where start_time>"2026-10-29T10:00:00Z"` W=[start_time > '2026-10-29T10:00:00Z'::TIMESTAMPTZ_NS] +// `logs where severity>=warn` / `=14` W=[severity = 'WARN'] / [severity = 'error'] / [severity_number >= 14] +// `spans | histogram(duration) by service` M=[count()], Histogram={duration_ms, log2}, B=[service] +// `metrics where name:x | histogram(value) every 1m` M=[count()], Histogram={value, explicit}, Bucket 1m +// `spans sort errors limit 50` (viz traces) Sort "errors", Limit 50; `spans sort duration` (traces) -> Sort "duration_ms"; `logs sort +time` -> "+time" +// `spans where kind:server | count_if(status:error) / count() * 100 as err_pct` M=[count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as err_pct] +// `spans | count()*100 as c100` / `count()/count() as one` / `p95(duration)-p50(duration) as spread` / `count() * -1 as neg` / `count() * 1e3 as k` +// M=[count() * 100 as c100] / [count() / count() as one] / [p95(duration_ms) - p50(duration_ms) as spread] / [count() * -1 as neg] / [count() * 1000 as k] +// `spans | count_if(status:error -http.target:/healthz) as errs` M=[count_if(status = 'STATUS_CODE_ERROR' AND (attributes['http.target'] IS NULL OR attributes['http.target'] != '/healthz')) as errs] +// `spans | count_if(a:1 or b:2) / count() as r` M=[count_if((attributes['a'] = 1 OR attributes['b'] = 2)) / count() as r] +// `spans | count_distinct(user.id) by service` / `count_distinct(attributes['user.id'])` / `avg(attributes.http.response_size) as sz` / `p95(resource.k) as x` +// M=[count_distinct(attributes['user.id'])] / same / [avg(attributes['http.response_size']) as sz] / [p95(resource['k']) as x] +// `spans where -http_status_code between 400 and 599` W=[NOT coalesce((TRY_CAST(http_status_code AS INTEGER) BETWEEN 400 AND 599), FALSE)] +// `spans where http_status_code not between 400 and 599` W=[TRY_CAST(http_status_code AS INTEGER) NOT BETWEEN 400 AND 599] +// `spans where -http_status_code not between 400 and 599` W=[NOT coalesce((TRY_CAST(http_status_code AS INTEGER) NOT BETWEEN 400 AND 599), FALSE)] +// `spans where -http_status_code:500` W=[(http_status_code IS NULL OR http_status_code != '500')] +// `spans where -service not in (a, b)` / `-service!=api` W=[(service IS NULL OR service IN ('a', 'b'))] / [(service IS NULL OR service = 'api')] +// `logs where -body not like "GET %"` W=[(body IS NULL OR body ~~ 'GET %')] +// `spans where -duration not between 1s and 2s` W=[(duration_ms IS NULL OR duration_ms BETWEEN 1000 AND 2000)] +// `logs where -length(body) > 1000` W=[NOT coalesce((length(body) > 1000), FALSE)] +// `spans where -k ~ v` on an attribute W=[(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('v')))] +// `spans where k ~ v` on an attribute W=[contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('v'))] +// `spans where -k:$v` W=[(attributes['k'] IS NULL OR attributes['k'] != $v)] +// the twelve at-a-glance examples (0.15) -> each lowers without problems + +func TestLowerEntryBoundaries(t *testing.T) // Review Focus 3 +// `spans where a:1 b:2 (c:3 or d:4) (e:5 f:6)` -> exactly 4 entries, in order, strings as in the fixture table +// `spans where service:$service status:error` -> 2 entries; `spans where (service:$service status:error)` -> 1 entry "(service = $service AND status = 'STATUS_CODE_ERROR')" + +func TestLowerStructuredBounds(t *testing.T) +// 17 terms -> problem "at most 16 filters" with Span == the 17th term's span +// one term lowering to 501+ bytes (a 480-byte quoted body value on an attribute) -> `this filter lowers to N bytes; filters are at most 500` (N exact) at that term's span; a 100-value `in` list of short words stays under 500 + +func TestLowerSearchBarMode(t *testing.T) // Compile("service:api timeout", {Source:"logs"}) -> From logs, W=[service = 'api', contains(lower(body), lower('timeout'))] + +func TestLowerCanonicalWhereIsIrrelevantToMeaning(t *testing.T) // `spans status:error` and `spans where status:error` lower identically + +func TestCompileReturnsNoQueryOnProblems(t *testing.T) // `spans where a:1 b:2 or c:3 | p99(duration) by http_route every 1m` -> nil Compiled, exactly 1 problem +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/fanql/ -run 'Lower|Compile'` +Expected: FAIL, `Compile` undefined. + +- [ ] **Step 3: Implement `lower.go` and `Compile`** + +Lowering is a switch over node types producing SQL text with the spellings of 0.7–0.9 (`'` doubled in literals; `attributes['k']` with the key quoted; numbers via `strconv.FormatFloat(v, 'f', -1, 64)`; durations to integer or decimal milliseconds). NNF is a pre-pass. `lowerMeasure` prints the expression with single spaces around binary operators, constants as typed numbers (`1e3` → `1000`), `count_if()`, and ` as alias` when present. `Compile` installs `lower` as the resolver's shape hook so `Resolve` can call `panel.QueryShape` on the lowered query and map query-relative paths back to the node spans (`where[i]` → entry i's span, `measures[j]` → measure j, `by[k]`, `bucket`, `sort`, `limit`). + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test ./internal/fanql/...` +Expected: PASS + +- [ ] **Step 5: Commit** + +```bash +git add internal/fanql +git commit -m "feat(fanql): lower the resolved tree to the structured panel query" +``` + +### Task 5: Printer and lift through the engine parser + +**Files:** +- Create: `internal/fanql/print.go`, `internal/fanql/lift.go` +- Modify: `internal/fanql/fanql.go` (`Compiled.Canonical`), `internal/panel/measure.go` (export `ParseMeasure`) +- Test: `internal/fanql/print_test.go`, `internal/fanql/lift_test.go`, `internal/fanql/testhelpers_test.go` (DuckDB engine helper copied from `internal/panel/testhelpers_test.go`'s `newTestEngine`) + +**Interfaces:** +- Consumes: `Query` tree, `lowerEntry`, `lowerMeasure`, `Lex`, `parseEntry`, `Resolve`; `panel.Parser` (`ParseSQL`, `RenderSQL`); `panel.QueryShape`. +- Produces in `internal/panel/measure.go`: + +```go +// ParseMeasure parses one stored measure string for the signal; Task 6 makes it expression-aware. +func ParseMeasure(signal, text string) (Measure, error) +``` + +- Produces in `internal/fanql`: + +```go +// Print is the canonical printer, frozen within Version (0.13 rule 4). +func Print(q *Query) string + +type FormatOptions struct { + Viz string + Variables []panel.Variable +} +type Formatted struct { + Text string `json:"text"` + Exactness string `json:"exactness"` // "exact" | "normalized" + Editable bool `json:"editable"` + Reason string `json:"reason,omitempty"` + Notices []Notice `json:"notices"` +} +// Format lifts q to a tree through parser, prints it and reports the tier and +// editability. Problems when q fails QueryShape under every viz; error only for +// operational engine failures (never turned into problems). +func Format(ctx context.Context, parser panel.Parser, q panel.Query, opts FormatOptions) (*Formatted, panel.Problems, error) + +type tier uint8 +const (tierExact tier = iota; tierNormalized; tierRaw) +func liftEntry(ctx context.Context, parser panel.Parser, signal, stored string) (Expr, tier, error) +func liftMeasure(ctx context.Context, parser panel.Parser, signal, stored string) (Measure, tier, error) +``` + +- Canonical rules the printer must honour (0.3–0.6): `where` printed whenever filters exist; single spaces; entries parenthesised when their top node is And/Or and there is more than one entry; one `-` for odd negation counts; `k>v` for `k:>v`; alias spellings for vocabularies; bracket form for single-segment attribute keys, bare for dotted; `duration` for `duration_ms`; `sort key` / `sort +key`; no pipe before `sort`/`limit`; clause words as free text quoted; values quoted only when they contain a non-wordchar or start with `-`/`+`/`$`/`*` or are a clause/expression word; `count_if(…)` body printed through the filter printer; constants as shortest round-trip decimals. + +- [ ] **Step 1: Write the failing tests** + +```go +func TestPrintCanonical(t *testing.T) +// text -> Print(Compile(text).tree) (Compiled.Canonical): +// `spans where duration > 500ms` -> `spans where duration>500ms`; `logs where --severity:error` -> `logs where severity:error` +// `spans where flag:true` -> `spans where attributes['flag']:true`; `spans where attributes.http.target:/h` -> `spans where http.target:/h` +// `spans where attributes['resource.k']:x` -> unchanged; `spans status:error | count() by service` -> `spans where status:error | count() by service` +// `spans | count() by service sort -count` -> `… sort count`; `spans | count() by service | sort count | limit 10` -> `… sort count limit 10` +// `spans where k:>5` -> `spans where attributes['k']>5`; `logs where "limit"` -> unchanged; `logs where top:x` -> `logs where attributes['top']:x` +// `spans | count_distinct(attributes['user.id'])` -> `spans | count_distinct(user.id)`; `spans | count_distinct(flag)` -> `spans | count_distinct(attributes['flag'])` +// `spans | P95(Duration)` -> `spans | p95(duration)`; `spans | avg(attributes.http.response_size) as sz` -> `spans | avg(http.response_size) as sz` +// `spans where kind:server | count_if(status:error -http.target:/healthz) / count() * 100 as e` -> unchanged +// `SPANS WHERE Service:API | COUNT() EVERY 1M` -> `spans where service:API | count() every 1m` +// `spans where service:$service (status:error or status:unset)` -> unchanged; `spans where (a:1 b:2)` -> `spans where (attributes['a']:1 attributes['b']:2)` +// `spans where a:1 or b:2` -> `spans where attributes['a']:1 or attributes['b']:2` (single Or entry, no parentheses) + +func TestPrintIsAFixedPoint(t *testing.T) // for every TestPrintCanonical output c: Compile(c).Canonical == c and Compile(c).Query == Compile(text).Query + +func TestFormatOwnLoweringNeedsNoEngine(t *testing.T) +// parser := &countingParser{fail: true}; for each at-a-glance example: f, problems, err := Format(ctx, parser, Compile(text).Query, {}) -> +// err nil, problems empty, f.Exactness "exact", f.Editable true, f.Text == Compile(text).Canonical, parser.calls == 0 + +func TestLiftStoredSQLShapes(t *testing.T) // DuckDB-backed (newTestEngine) +// stored Where entry -> printed entry, tier: +// `service = 'api'` -> `service:api` exact; `service='api'` -> `service:api` normalized (notice `where[0] is shown as service:api; stored text is "service='api'"`) +// `status = 'STATUS_CODE_ERROR'` -> `status:error`; `kind = 'SPAN_KIND_SERVER'` -> `kind:server`; `duration_ms > 500` -> `duration>500ms`; `duration_ms > 1500` -> `duration>1.5s` +// `attributes['http.target'] != '/healthz'` -> `http.target!=/healthz`; `(attributes['k'] IS NULL OR attributes['k'] != 'v')` -> `-attributes['k']:v` exact +// `NOT (attributes['k'] = 'v')` -> raw "`NOT (attributes['k'] = 'v')`"; `NOT (k ~~ 'x%')` on a column -> raw; `body !~~ 'x%'` -> `body not like "x%"` +// `service NOT IN ('a', 'b')` -> `service not in (a, b)`; `NOT coalesce((attributes['k'] = 'v'), FALSE)` -> raw +// `NOT coalesce((TRY_CAST(http_status_code AS INTEGER) BETWEEN 400 AND 599), FALSE)` -> `-http_status_code between 400 and 599` exact +// `(service IS NULL OR service IN ('a', 'b'))` -> `-service not in (a, b)` exact; `TRY_CAST(http_status_code AS INTEGER) >= 500` -> `http_status_code>=500` +// `severity IN ('WARN', 'ERROR', 'FATAL')` -> `severity>=warn`; `severity IN ('INFO', 'ERROR')` -> `severity in (info, error)`; `severity IN ('INFO', 'WARN', 'ERROR')` -> `severity between info and error` +// `contains(lower(body), lower('timeout'))` -> `timeout`; `contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('v'))` -> `attributes['k'] ~ v` +// `start_time > '2026-10-29T10:00:00Z'::TIMESTAMPTZ_NS` -> `start_time>"2026-10-29T10:00:00Z"`; `service IN $svcs` -> `service in $svcs`; `service = $service` -> `service:$service` +// `lower(k) = 'v'` -> raw; `starts_with(http_route, '/api')` -> `starts_with(http_route, "/api")`; `length(body) > 1000` -> `length(body)>1000` +// `service = $service AND status = 'STATUS_CODE_ERROR'` (one entry) -> `(service:$service status:error)`; `a = 1 OR b = 2` -> `(attributes['a']:1 or attributes['b']:2)` when another entry exists +// every row: entry count unchanged; the printed text re-lowers byte-equal (exact) or RenderSQL-equal (normalized); raw rows re-lower byte-equal by construction + +func TestLiftMeasures(t *testing.T) // DuckDB-backed +// `p95( duration_ms )` -> `p95(duration)` normalized; `count() as n` -> `count() as n` exact; `count_distinct(attributes['user.id'])` -> `count_distinct(user.id)` exact +// `quantile(duration_ms, 0.999) as q` -> unchanged; Histogram {duration_ms, log2} + Measures [count()] -> `histogram(duration)`; Histogram with Measures [p95(duration_ms)] -> problems, no text +// Sort "errors" (viz traces) -> `sort errors` + the 0.12 notice; Sort "duration_ms" -> `sort duration`; Sort "+start" -> `sort +start` + +func TestFormatEditableFalseIsCompleteAndReasoned(t *testing.T) // Review Focus 4 +// 16 entries `body = '<480 bytes>'` -> Editable false, Reason == fmt.Sprintf("formatted text is %s bytes; the editor accepts 8,192", ), Text contains all 16 literals, Exactness "exact" +// one raw entry whose 10 backticks double to 20 and push the text over 4,000 code points within 8,192 bytes -> Reason names characters: "formatted text is 4,312 characters; the editor accepts 4,000" +// 1,100 tokens within both text bounds -> Reason names tokens + +func TestFormatOperationalErrorIsReturnedNotAProblem(t *testing.T) // parser.ParseSQL returns context.DeadlineExceeded -> err wraps it, problems nil, f nil +func TestFormatRejectsQueryInvalidUnderEveryViz(t *testing.T) // {from:spans, measures:[count()], by:[a,b,c,d]} -> problems non-empty, f nil, parser never called +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/fanql/ -run 'Print|Format|Lift'` +Expected: FAIL, `Print`/`Format` undefined. + +- [ ] **Step 3: Implement** + +`print.go`: one printer over the resolved tree (the lifted tree is resolved by construction). `lift.go` algorithm (0.11), not determined by tests alone: + +1. Shape gate: `panel.QueryShape` under `opts.Viz`, else under every viz in order; no pass → return problems. +2. Per `Where[i]`: pure pre-pass `recognizeOwnLowering(stored)` over FanQL's own lowering grammar (the exact spellings `lowerEntry` emits); if it yields a tree whose `lowerEntry` is byte-equal to `stored` → exact without the engine. Otherwise `parser.ParseSQL("SELECT 1 FROM "+signal+" WHERE ("+stored+")")`, map `where_clause` per the 0.11 table into candidate trees (shorthand candidates first), re-lower each with `lowerEntry`; byte-equal → exact; else `RenderSQL(ParseSQL(lowered)) == RenderSQL(ParseSQL(stored))` → normalized (notice `where[i] is shown as ; stored text is ""`); no candidate → `Raw{stored}`. +3. Per `Measures[i]`: `liftMeasure` tokenizes in measure context with `count_if(` captured as raw SQL to its matching parenthesis and lifted via `liftEntry`; exact when `lowerMeasure` equals `stored`; normalized when `panel.ParseMeasure(signal, lowered)` equals `panel.ParseMeasure(signal, stored)` on (Func, Field.Text, Q, Alias); otherwise problems (a measure has no raw form; the query is not formatted). +4. `By`, `Histogram.Field` through the catalog spelling; `Bucket`, `Sort`, `Limit`, `From` direct (`duration_ms` → `duration` on traces). +5. `Print`; `Editable` by checking the text against `MaxTextRunes`, `MaxTextBytes`, `MaxTokens` (via `Lex`), `MaxNodes`/`MaxDepth` (via the unbounded parse), with `Reason` naming the first failing bound. + +`Compile` sets `Canonical = Print(tree)`. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test ./internal/fanql/... ./internal/panel/...` +Expected: PASS + +- [ ] **Step 5: Commit** + +```bash +git add internal/fanql internal/panel/measure.go +git commit -m "feat(fanql): print canonical text and lift stored queries through the engine parser" +``` + +### Task 6: Backend measure expressions in `internal/panel` + +**Files:** +- Modify: `internal/panel/measure.go` (expression lexer and Pratt parser replacing `measurePattern`; budgets; `ParseMeasure`), `internal/panel/compile.go` (`measureExprSQL`, ranking rules), `internal/panel/items.go` (`compileItems` → `measureExprSQL`), `internal/panel/table_trends.go` (expressions beside the unchanged `share` branches), `internal/panel/check.go` (`count_if` filters through `checkFilter`), `internal/panel/validate.go` (`inferBetter` recursive; metrics rejection; unit inference), `internal/panel/exec.go` (`Result.Ranking`), `internal/panel/frame.go` (below-floor note), `internal/panel/spec.go` (jsonschema text on `Query.Measures`), `internal/panel/metric_measures.go` (reject expressions) +- Modify: `internal/mcp/panels.go` (`baseSpecGuide` measures sentence), MCP describe/contract snapshots as the tests require +- Test: `internal/panel/measure_expr_test.go`, `internal/panel/compile_expr_test.go`, `internal/panel/ranking_expr_test.go` (DuckDB), `internal/panel/check_test.go` (additions) + +**Interfaces:** +- Consumes: `checkFilter`, `Filter.Expr`, `errorCountFilter`, `wilsonLowerSQL`, `errorCase`, `buildWhere`. +- Produces: + +```go +type MeasureExpr interface{ measureExpr() } +type MeasureCall struct{ Func string; Field *FieldRef; Q float64 } +type MeasureCountIf struct { + Filter string // SQL source inside count_if(…) + Expr string // canonical rendering set by Check; compiled as count(*) FILTER (WHERE (Expr))::DOUBLE +} +type MeasureBinary struct{ Op byte; L, R MeasureExpr } +type MeasureNeg struct{ X MeasureExpr } +type MeasureConst struct{ Value float64; Text string } + +type Measure struct { + Text string + Func string // single call: its name; expression: "expr" + Field *FieldRef // single call only + Q float64 + Alias string + Unit string // 0.10 unit inference for expressions + Additive bool // false for expressions + Expr MeasureExpr // always set (a MeasureCall for a single call) + Leaves int // aggregate leaves + Rank RankRule +} +func (m Measure) IsExpression() bool + +type RankRule struct { + Rule string // "builtin" | "inherit" | "wilson" | "value_floor" + Better string // "lower" | "higher" | "neutral" + Floor int // 20 + SupportColumn string +} +type Ranking struct { + Rule string `json:"rule"` + Better string `json:"better"` + Floor int `json:"floor"` + SupportColumn string `json:"support_column"` + BelowFloor int `json:"below_floor"` + TieBreakers []string `json:"tie_breakers"` // ["n desc", "dimension asc"] +} +// Result gains: Ranking *Ranking `json:"ranking,omitempty"` + +const ( + maxMeasureTokens = 256 + maxMeasureNodes = 64 + maxMeasureDepth = 8 + maxMeasureLeaves = 8 + maxQueryMeasureNodes = 256 + maxQueryMeasureLeaves = 24 +) + +func parseMeasure(sig *signal, text string) (Measure, string, string) // unchanged signature; expression-aware +func parseMeasures(sig *signal, texts []string, path string, problems *Problems) []Measure // adds query-wide budgets +func ParseMeasure(signal, text string) (Measure, error) // from Task 5, now expression-aware +func measureExprSQL(m Measure, sig *signal, seconds float64, partition string) string // recurses; delegates single calls to measureSQL +func rankingOrder(first Measure, sig *signal, better string) (value, samples, extra, order string) // 0.10 ranking table +func inferBetterExpr(e MeasureExpr, p *Panel, sig *signal) string +``` + +- `measureSQL` stays for single calls; `compileQuery`, `compileItems`, `attachTableTrends` and `totals` call `measureExprSQL`. `compileMetricQuery` never sees an expression: `parseMeasure` rejects them for metrics with `measure arithmetic is not available for metrics`. +- `Check`: for each `MeasureCountIf` leaf, `checkFilter(ctx, parser, sig, nil, leaf.Filter)`; `len(f.Params) > 0` → problem `variables are not allowed inside count_if` at `panels[i].query.measures[j]`; `leaf.Expr = f.Expr` on the stored `Checked.Measures`. +- Division: `(L) / nullif((R), 0)`; constants via `strconv.FormatFloat(v, 'f', -1, 64)`; binary operands parenthesised when they are binary. +- Budget messages: `measures[2] has 70 nodes; a measure is at most 64`, `… has 257 tokens; a measure is at most 256`, `… nests 9 deep; a measure nests at most 8`, `… has 9 aggregates; a measure has 1 to 8`, `measures have 257 nodes together; a query has at most 256`, `measures have 25 aggregates together; a query has at most 24`; aggregate-free: the 0.10 message. Depth is checked on descent (fails at 9 before recursing). + +- [ ] **Step 1: Write the failing tests** + +```go +func TestParseMeasureKeepsSingleCalls(t *testing.T) +// for each existing stored spelling: " p95( duration_ms ) ", "COUNT( )", "quantile(duration_ms, 0.999) as q", "count_distinct(attributes['user.id'])", "rate()", "share()", "last(value)" (metrics): +// Func/Field.Text/Q/Alias/Unit/Additive equal the values the regex parser produced (golden list in the test); Text == strings.TrimSpace(input); Leaves == 1; IsExpression() == false + +func TestParseMeasureExpressions(t *testing.T) +// "count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as err_pct" -> Expr == MeasureBinary{'*', MeasureBinary{'/', MeasureCountIf{Filter:"status = 'STATUS_CODE_ERROR'"}, MeasureCall{count}}, MeasureConst{100}}; Unit "percent"; Additive false; Alias "err_pct"; Leaves 2 +// "count_if(status = 'STATUS_CODE_ERROR') / count() as r" -> Unit "ratio"; "p95(duration_ms) - p50(duration_ms) as spread" -> Unit "ms"; "count() * -1 as neg" -> MeasureNeg{MeasureConst{1}}; "sum(duration_ms) / count() as x" -> Unit "none" +// "count_if(a = 1 AND (b IS NULL OR b != 'x)')) as e" -> Filter "a = 1 AND (b IS NULL OR b != 'x)')" (quotes and nested parentheses respected) +// "count() / 2" -> "name this expression with as, e.g. count() / 2 as half"; "share() / 2 as half" -> "share() cannot be combined; it is already a percentage of the scope" +// "1 as one", "1 / 2 as half", "-(5) as neg" -> "a measure needs an aggregate; constants can only scale one, e.g. count() * 100"; "count() * 0 as zero" -> ok +// metrics: "count_if(name = 'x') as n", "count() * 2 as d" -> "measure arithmetic is not available for metrics" +// "count_if() as n" -> problem; "count_if(status = 'x'" -> problem (unclosed) + +func TestMeasureBudgets(t *testing.T) +// generated strings exceeding each per-measure budget by one -> the exact message with figure and limit (65 nodes, 257 tokens, depth 9, 9 leaves); +// two measures of 129 nodes -> "measures have 258 nodes together; a query has at most 256" at the query path; 3 measures of 8 + one of 1 -> "measures have 25 aggregates together; a query has at most 24" +// a 10 KiB whitespace-padded "p95(duration_ms)" parses (tokens, not bytes); depth 8 parses, depth 9 fails before building node 9 (assert via a node counter hook or the message) + +func TestValidateRejectsStructuredBudgetOverrunsAtPath(t *testing.T) +// Validate on a dashboard whose panels[0].query.measures[1] has 65 nodes -> one problem with Path "panels[0].query.measures[1]"; "1 as one" at measures[0] -> rejected; no engine involved (Validate is in-memory) + +func TestCompileExpressionSQL(t *testing.T) +// {from:spans, where:[kind = 'SPAN_KIND_SERVER'], measures:[count_if(TRY_CAST(http_status_code AS INTEGER) >= 500) / count() * 100 as pct_5xx], by:[http_route]} (table, after Check) -> +// SQL contains `count(*) FILTER (WHERE (TRY_CAST(http_status_code AS INTEGER) >= 500))::DOUBLE / nullif(count(*)::DOUBLE, 0) * 100 AS "pct_5xx"` +// the Apdex measure -> SQL contains two FILTER aggregates, "/ 2" and "/ nullif(count(*)::DOUBLE, 0)" +// scatter with measures [count_if(…) as a, p95(duration_ms)] -> compileItems SQL contains the FILTER aggregate; table with a sparkline on an expression -> attachTableTrends SQL contains the FILTER aggregate; share() alone -> unchanged _trend_totals SQL (golden) +// stat totals() for an expression -> interval 0 compiles through the same path (SQL contains FILTER) + +func TestCheckCountIfFilters(t *testing.T) // DuckDB-backed +// count_if(service = $service) -> problem "variables are not allowed inside count_if" at panels[0].query.measures[0] +// count_if(regexp_replace(body, 'a', 'b') = 'x') -> problem at the same path (gate rejection); count_if(status = 'STATUS_CODE_ERROR') -> Checked.Measures[p.ID][0].Expr.(MeasureCountIf).Expr is the canonical rendering +// count_if filter of 501 bytes -> "filters are 1 to 500 characters" + +func TestInferBetterForExpressions(t *testing.T) +// error_rate() * 100 -> lower; 100 - error_rate() -> higher (flipped); -p95(duration_ms) -> higher; count_if(status = 'STATUS_CODE_ERROR') / count() -> lower; count_if(kind = 'SPAN_KIND_SERVER') / count() -> ""; count_if(status = 'STATUS_CODE_ERROR') as e -> lower + +func TestRankingFixtures(t *testing.T) // DuckDB-backed, timeseries by service with options.top 6 (Review Focus 5) +// identity: error_rate(), error_rate() + 0, error_rate() * 100, 100 - error_rate(), -error_rate() select identical series in identical order on seed data that includes a 1/2 series; Ranking.Rule "builtin" for the first, "inherit" for the rest +// sparse denominator: count_if(status = 'STATUS_CODE_ERROR') / count() as r with services A 1/1 and B 100/1000 -> B first; Ranking{Rule:"wilson", Better:"lower", Floor:20, BelowFloor:1}; frame note "1 series had fewer than 20 samples and were ranked last" +// neutral: count_if(kind = 'SPAN_KIND_SERVER') / count() as r with 900/1000, 100/1000, 1/1 -> order 900/1000, 100/1000, 1/1; Better "neutral" +// success rate: 100 - count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as ok with better higher -> same order as error_rate() +// tie: two series with equal score and n -> dimension ascending, identical across 3 runs +// missing numeric sample: avg(attributes['user.score']) / 2 as half where most rows lack the attribute -> Rule "value_floor", support counts present values (SupportColumn names count(TRY_CAST(…))) +// high cardinality: seven services -> Other folds the seventh; Ranking.BelowFloor reports the sub-floor ones +// -p95(duration_ms) as neg with better higher selects what p95(duration_ms) selects with better lower + +func TestApdexFixtures(t *testing.T) // DuckDB-backed: all spans at 500ms -> 1.0; all at 2000ms -> 0.5; all at 100ms -> 1.0; all at 5000ms -> 0.0; zero rows -> NULL (status empty) + +func FuzzParseMeasure(f *testing.F) // seeds: the fixtures above; property: no panic, returns within 50 ms for 64 KiB inputs, depth ≤ 8 on success +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/panel/ -run 'Measure|Budget|Expression|CountIf|InferBetterFor|RankingFixtures|Apdex'` +Expected: FAIL, `MeasureExpr` undefined; expression strings rejected as `is not fn(field) [as alias]`. + +- [ ] **Step 3: Implement** + +`measure.go`: a small lexer (identifiers, numbers, `( ) , + - * /`, `attributes[...]`/`resource[...]` arguments, and a `count_if(` capture that scans to the matching parenthesis honouring single-quoted strings) and a Pratt parser (`+ -` below `* /` below unary minus) building `MeasureExpr` with token, node, depth and leaf counters checked as nodes are built; single-call results fill `Func/Field/Q` exactly as before. Delete `measurePattern`. `compile.go`: `measureExprSQL`; `rankingOrder` implements the 0.10 table (algorithm, not test-determined): classify `first.Expr` as builtin / affine-of-one-call / recognised binomial ratio / other; compute `better` (panel `Better`, else `inferBetterExpr`, else neutral), map it through the coefficient sign for `inherit` and `wilson`; emit `value`, `samples`, `extra` and `order` strings: builtin as today; `inherit` = the inner call's strings verbatim with the mapped direction; `wilson` = `extra` adds `sum(CASE WHEN THEN 1.0 ELSE 0.0 END) AS errors` plus the lower bound (and the upper bound `least(1.0, …)` with `+ 1.96 * sqrt(…)` when `better` is higher), `order` = `(n >= 20) DESC, CASE WHEN n >= 20 THEN END NULLS LAST, n DESC, d`; `value_floor` = `samples` is the denominator's or the minimum leaf support, `order` = `(n >= 20) DESC, CASE WHEN n >= 20 THEN value END NULLS LAST, n DESC, d`. `exec.go` fills `Result.Ranking` from the rule and a `SELECT count(*) FROM candidates WHERE n < 20` executed alongside the rank query when `top > 0`, and adds the frame note. `check.go`, `validate.go`, `items.go`, `table_trends.go`, `spec.go`, `metric_measures.go` as the interfaces state. Update `baseSpecGuide` in `internal/mcp/panels.go` to list `count_if(filter)` and arithmetic. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test ./internal/panel/... ./internal/mcp/... ./internal/fanql/... && just docs-generate && just docs-generate-check` +Expected: PASS; the MCP tools reference regenerates with the new measures sentence. + +- [ ] **Step 5: Commit** + +```bash +git add internal/panel internal/mcp/panels.go internal/mcp site/src/content/docs/reference +git commit -m "feat(panel): conditional aggregates and measure arithmetic with budgets and ranking" +``` + +### Task 7: Completion engine + +**Files:** +- Modify: `internal/fanql/parser.go` (completion mode: expected-set recording) +- Create: `internal/fanql/complete.go` +- Test: `internal/fanql/complete_test.go` + +**Interfaces:** +- Consumes: `Lex`, the parser, `panel.SignalColumns`, `panel.MeasureSpecs`, `panel.BucketNames`, `panel.Schema` (`Signals[name].Columns[i].Values`, `.Attributes` with `Key`, `Type`, `Count`, `Services`, `.Metrics`), `panel.SchemaRequest`. +- Produces: + +```go +type Expect struct { + Class string // source clause field operator value measure marg bucket sort_key integer variable bracket_key free_text + Field *Field // for value + Func string // for marg + Arg int // for marg + Scope string // for bracket_key: attributes|resource +} +// expectAt lexes text, picks the token containing or ending at cursor, and parses +// text[:token.Start] in completion mode, recording what the parser would accept next. +func expectAt(text string, cursor int) (Token, []Expect) + +type SchemaSource interface { + Schema(context.Context, panel.SchemaRequest) (*panel.Schema, error) +} +type Completer struct{ /* source, singleflight map, semaphore(4), negative cache, clock */ } +func NewCompleter(source SchemaSource) *Completer + +type CompleteRequest struct { + Text string + Cursor int // code points + Source string + Viz string + Window string // Explore range (5m … 30d); "" for an absolute window + Namespace string + Variables []panel.Variable +} +type Item struct { + Label string `json:"label"` + Insert string `json:"insert"` + Kind string `json:"kind"` // keyword field attribute value measure bucket variable operator + Detail string `json:"detail"` +} +type SchemaStatus struct { + Window string `json:"window"` + Sampled bool `json:"sampled"` + Warm bool `json:"warm"` + Recent bool `json:"recent"` + Error bool `json:"error,omitempty"` +} +type CompleteResponse struct { + Replace panel.TextSpan `json:"replace"` + Items []Item `json:"items"` + Schema SchemaStatus `json:"schema"` +} +const MaxCompletionItems = 50 +func (c *Completer) Complete(ctx context.Context, req CompleteRequest) CompleteResponse +``` + +- Window clamp: requested schema window is `min(req.Window, 24h)` mapped onto the schema's accepted windows (`5m 15m 1h 3h 6h 12h 24h`); `Recent` is true when `req.Window` is empty (absolute) or longer than 24h. +- Coalescing (0.14 rule 3): one in-flight fetch per `(window, namespace)` key; at most 4 concurrent process-wide; the fetch runs on `context.WithoutCancel(ctx)` with a 20 s timeout; a failure is cached for 10 s and reported as `Warm: false, Error: true`. + +- [ ] **Step 1: Write the failing tests** + +```go +func TestExpectAtRecordsClasses(t *testing.T) +// "" -> [source]; "spans " -> clause, field, free_text, …; "spans where service" (cursor at end) -> replace span == "service", classes include field and free_text +// "spans where service:" -> [value(service)]; "spans | " -> [measure]; "spans | quantile(duration, " -> [marg(quantile, 1)]; "spans | count() every " -> [bucket] +// "spans | count() by service sort " -> [sort_key]; "spans | count() limit " -> [integer]; "spans where attributes['ht" -> token BracketKey, [bracket_key(attributes)] + +func TestCompleteFixtures(t *testing.T) // fake SchemaSource with: logs columns severity values [ERROR INFO WARN], service values [api checkout]; spans attributes http.target (string, 900), http.method (string, 500), user.score (number, 20); resource keys k8s.pod.name; metric names http.server.duration +// `logs where sev|erity:error` -> Replace {11,19}; Items[0].Label "severity" (Kind field) +// `logs where severity:|` -> Items include trace debug info warn error fatal (vocabulary first), then schema values ERROR INFO WARN deduplicated by stored spelling, then "*" +// `logs where severity>=|` -> exactly [trace debug info warn error fatal] +// `spans where http.|` -> Items [http.target, http.method] (Kind attribute, ranked by count), Insert "http.target" +// `spans where attributes['htt|` -> Replace == span of "htt" inside the quotes; Items[0].Insert == "http.target']" +// `spans where resource["k8s.|` -> Items[0].Insert `k8s.pod.name"]` +// `logs where service in (api, |` -> Items [checkout, api] (values), none already present preferred first +// `logs where ser|` -> Items include service (field) and a last item with Detail "free text searches body" +// `spans | p9|` -> [p90 p95 p99]; `metrics | |` -> no error_rate, includes last; `spans | |` -> no last, includes histogram( and count_if( +// `spans | quantile(duration, |` -> [0.5 0.9 0.95 0.99] +// `spans | count() by service, |` with Viz table -> string columns and attribute keys; with Viz timeseries -> no items, one item with Detail "timeseries groups by at most 1 field" +// `spans | count() every |` with Viz bar -> single Detail item "bar panels have no bucket"; without viz -> [auto 10s 30s 1m 5m 10m 15m 30m 1h 3h 6h 12h 1d] +// `spans sort |` with Viz traces -> [duration +start errors] with errors Detail "filters to errors, orders by duration"; `spans | count() by service sort |` -> [count +count] +// `spans where service:$ser|` with Variables [service] -> [$service] +// `logs where "unclosed |` -> no items +// `spans | share() |` -> no + - * / items; `spans | count() |` -> items include + - * / , as by every sort limit +// `spans where duration |` -> operators > >= < <= between and :; `spans where start_time |` -> only comparisons; `logs where severity |` -> comparisons and : +// `spans where service:api |` (after a term) -> field, attribute, -, (, not, $vars items +// every response: len(Items) <= 50; Schema.Window "1h" for req Window "1h" + +func TestCompleteRecentFlag(t *testing.T) // Window "7d" -> schema request Window "24h", Recent true; Window "" -> "24h", Recent true; Window "1h" -> Recent false + +func TestCompleteColdCacheCoalesces(t *testing.T) +// fake source blocks on a gate and counts calls; 50 concurrent Complete calls over 6 distinct (window, namespace) keys on an empty cache -> +// first responses Warm false; after release exactly 6 Schema calls; max concurrent observed <= 4; the request contexts are cancelled before release and the fetches still complete; +// a source that returns an error -> Warm false, Error true; a second request within 10 s makes no call; after 10 s (fake clock) exactly one retry + +func TestCompleteItemsRankByPrefixThenSubstringThenCount(t *testing.T) // `spans where htt|` -> http.target before http.method; `spans where tar|` -> http.target (substring) after any prefix matches +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/fanql/ -run 'Expect|Complete'` +Expected: FAIL, undefined. + +- [ ] **Step 3: Implement** + +Parser completion mode: a flag that makes every `expect`/alternative site append to a recorded `[]Expect` when the token stream is exhausted at the cursor, and suppresses problems. `complete.go`: candidates per class from the 0.14 table; ranking by exact prefix, substring, class order, schema count; `Kind`/`Detail` strings; the coalescing layer as described (map of `chan struct{}` per key, a buffered channel of 4 as the semaphore, a negative-cache map with expiry, an injectable `now`). + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test -race ./internal/fanql/...` +Expected: PASS (race detector clean on the coalescing test). + +- [ ] **Step 5: Commit** + +```bash +git add internal/fanql +git commit -m "feat(fanql): position-aware completion with coalesced schema fetches" +``` + +### Task 8: HTTP API routes + +**Files:** +- Create: `internal/api/fanql.go` +- Modify: `internal/api/auth_middleware.go` (`classifyRoute`), `internal/api/auth_test.go` (`TestRoutePolicyClassification` rows), `internal/api/errors.go` (`apiError.Hint`), `cmd/fanout/main.go` (`api.RegisterFanQLRoutes(e, q, panels)` after `RegisterPanelRoutes`) +- Regenerate: `site/src/content/docs/reference` (`just docs-generate`; the routes reference is collected from source) +- Test: `internal/api/fanql_test.go` + +**Interfaces:** +- Consumes: `fanql.Compile`, `fanql.Format`, `fanql.NewCompleter`, `fanql.Reference` (Task 10; until then the reference route returns `fanql.Reference()` from a stub that Task 10 replaces — do not merge before Task 10), `fanql.Version`, `panel.Parser`, `PanelEngine`, `decodeStrict`, `panelDeadline`, `newAPIError`, `panel.PresentError`, `panel.PresentProblems`. +- Produces: + +```go +type FanQLHandler struct { + parser panel.Parser + engine PanelEngine + completer *fanql.Completer +} +func RegisterFanQLRoutes(e *echo.Echo, parser panel.Parser, engine PanelEngine) +// POST /api/fanql/parse {version?, text, source?, viz?, variables?, preview?} +// POST /api/fanql/format {version?, query, viz?, variables?, panel?} +// POST /api/fanql/complete {version?, text, cursor, source?, viz?, window?, namespace?, variables?} +// GET /api/fanql/reference?version=1 text/markdown; charset=utf-8 + +type apiError struct { + status int + Code string `json:"code"` + Message string `json:"message"` + Hint string `json:"hint,omitempty"` + Problems panel.Problems `json:"problems,omitempty"` + Preview *fanqlPreview `json:"preview,omitempty"` +} +``` + +- Responses exactly as 0.13: parse 200 `{version, query, canonical, viz: {requested?, compatible, edits}, notices}`; 400 `{code: "invalid_fanql", message: "The query has problems.", problems, preview?: {text, note: "not executable"}}`; format 200 `{version, text, exactness, editable, reason?, notices}`, 400 `invalid_spec` with problems, 503 `{code: "unavailable", message}` on operational errors (logged through `panel.PresentError`); complete 200 `{version, replace, items, schema}`; unsupported version 400 `{code: "unsupported_fanql_version", message, hint: "this server reads FanQL 1"}`; a missing version adds the notice `version missing; assuming FanQL 1`. All routes `RequireCapability(ReadTelemetry)`; `decodeStrict` with `512<<10`; `context.WithTimeout(…, panelDeadline)` around `Format` and `Complete`. +- `classifyRoute`: `path == "/api/fanql/parse" || "/api/fanql/format" || "/api/fanql/complete"` → `ReadTelemetry`, `method == POST`; `path == "/api/fanql/reference"` → `ReadTelemetry`, `read`. + +- [ ] **Step 1: Write the failing tests** + +```go +// helpers: serveFanQL(t, parser panel.Parser, engine PanelEngine, method, path, body) like servePanels; fakeParser implementing panel.Parser with scripted ParseSQL/RenderSQL results and an optional error +func TestFanQLParseReturnsQueryCanonicalAndVizzes(t *testing.T) +// POST /api/fanql/parse {"version":1,"text":"spans where status:error | count() by service"} -> 200; +// body.version == 1; body.query == {"from":"spans","where":["status = 'STATUS_CODE_ERROR'"],"measures":["count()"],"by":["service"]}; +// body.canonical == "spans where status:error | count() by service"; body.viz.compatible contains {"viz":"bar","requires":[]} and table; body.viz.edits contains {"viz":"timeseries","text":"spans where status:error | count() by service every auto"}; body.notices == [] + +func TestFanQLParseProblemsHaveNoQuery(t *testing.T) +// {"text":"spans where a:1 b:2 or c:3 | p99(duration) by http_route every 1m"} -> 400; code "invalid_fanql"; message "The query has problems."; +// problems[0].message "mixed and/or needs parentheses"; len(problems[0].fix_its) == 2; problems[0].span present; body has no "query" and no "preview" keys +// same with "preview":true -> body.preview.note == "not executable" + +func TestFanQLParseSearchBarAndViz(t *testing.T) +// {"text":"service:api timeout","source":"logs"} -> 200, 2 where entries, viz.compatible == [{"viz":"logs","requires":[]}] +// {"text":"where service:api","source":"logs"} -> 400 "the page supplies where" +// {"text":"spans | count() every 1m sort count","viz":"timeseries"} -> 200 with the bucketed-sort notice + +func TestFanQLVersionHandling(t *testing.T) +// {"version":2,"text":"spans"} -> 400 code "unsupported_fanql_version", hint "this server reads FanQL 1" +// {"text":"spans"} (no version) -> 200, notices contains "version missing; assuming FanQL 1" +// GET /api/fanql/reference?version=2 -> 400 unsupported_fanql_version + +func TestFanQLFormat(t *testing.T) +// fakeParser scripted for `service='api'` -> {"query":{"from":"spans","where":["service='api'"],"measures":["p95( duration_ms )"]}} -> 200; +// text "spans where service:api | p95(duration)"; exactness "normalized"; editable true; notices contains `where[0] is shown as service:api; stored text is "service='api'"` +// {"query":{"from":"spans","measures":["count()"],"by":["a","b","c","d"]}} -> 400 code "invalid_spec" with problems +// fakeParser{err: context.DeadlineExceeded} with a stored entry FanQL cannot recognise purely -> 503 code "unavailable"; the response carries no problems +// 16 x 480-byte body entries -> 200 editable false, reason starts "formatted text is", text length > 8192 bytes + +func TestFanQLComplete(t *testing.T) +// engine fakePanels with Schema returning logs severity values -> {"text":"logs where sev","cursor":14} -> 200; replace {"start":11,"end":14}; items[0].label "severity"; schema.window "1h"; schema.warm false on the first call + +func TestFanQLReference(t *testing.T) // GET /api/fanql/reference -> 200; Content-Type starts "text/markdown"; body contains "FanQL 1" and "Preview" + +func TestFanQLRoutesAreClassified(t *testing.T) +// classifyRoute(POST, /api/fanql/parse|format|complete) and (GET, /api/fanql/reference) -> routePolicyCapability, ReadTelemetry; (GET, /api/fanql/parse) not ok; (POST, /api/fanql/reference) not ok +// anonymous POST /api/fanql/parse -> 401; viewer -> 200 (through serveFanQL) + +func TestFanQLBodyLimitsAndUnknownFields(t *testing.T) // body of 512 KiB + 1 -> 400; {"text":"spans","unknown":1} -> 400; text of 4,001 characters -> 400 invalid_fanql with the bound message +``` + +Also extend `TestRoutePolicyClassification` in `auth_test.go` with the four routes. + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/api/ -run 'FanQL|RoutePolicyClassification'` +Expected: FAIL, routes 404 / unclassified (the middleware returns 500 for a registered unclassified `/api/` route). + +- [ ] **Step 3: Implement** + +`fanql.go` with request structs (`decodeStrict`), a `version` check shared by the four handlers, `fanql.Compile`/`Format`/`Completer.Complete` calls, the error mapping (`panel.Problems` → `invalid_fanql` for parse, `invalid_spec` for format; `panel.isOperational`-equivalent errors from `Format` → 503 through a new `fanqlError` helper that logs with `panel.PresentError`). Add `Hint` to `apiError`. Register in `cmd/fanout/main.go` with `q` (the `*query.Duck`) as the parser. Add the `classifyRoute` cases. Run `just docs-generate`. + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test ./internal/api/... ./cmd/... && just docs-generate-check` +Expected: PASS; the generated routes reference lists the four routes with `telemetry:read`. + +- [ ] **Step 5: Commit** + +```bash +git add internal/api cmd/fanout/main.go site/src/content/docs/reference +git commit -m "feat(api): FanQL parse, format, complete and reference routes" +``` + +### Task 9: MCP text input and reference resource + +**Files:** +- Modify: `internal/mcp/fragments.go` (`QueryTelemetryInput.Text`, `.FanQLVersion`; `queryTelemetry` parse step), `internal/mcp/panels.go` (tool description sentence) +- Create: `internal/mcp/fanql_resource.go` +- Modify: `internal/mcp/server.go` (`newServer` calls `registerFanQLResource`) +- Test: `internal/mcp/fanql_test.go`; update `describe_test.go` / `fragment_contract_test.go` expectations the new fields change +- Regenerate: the MCP tools reference (`just docs-generate`) + +**Interfaces:** +- Consumes: `fanql.Compile`, `fanql.Options`, `fanql.Version`, `fanql.Reference`, `toolerror.New`. +- Produces: + +```go +type QueryTelemetryInput struct { + Panel panel.Panel `json:"panel" jsonschema:"One v1 panel to display in the answer"` + Text string `json:"text,omitempty" jsonschema:"FanQL text that becomes panel.query; prefer panel.query (structured) or panel.sql; see fanout://fanql/reference"` + FanQLVersion int `json:"fanql_version,omitempty" jsonschema:"FanQL version of text; this server reads 1"` + Variables []panel.Variable `json:"variables,omitempty" …` + Time *panel.Time `json:"time,omitempty" …` + Vars map[string]panel.Value `json:"vars,omitempty" …` +} +const fanqlReferenceURI = "fanout://fanql/reference" +func (s *Server) registerFanQLResource() // Name "FanQL reference", MIME "text/markdown", Text fanql.Reference() +``` + +- Rules: `Text` with `Panel.Query != nil` or `Panel.SQL != ""` → tool error `{code: "invalid_input", message: "text cannot be combined with panel.query or panel.sql"}`; `FanQLVersion` not 0 or 1 → `{code: "unsupported_fanql_version", message: "this server reads FanQL 1"}`; `fanql.Compile(text, {Viz: input.Panel.Viz, Variables: input.Variables})` problems → `{code: "invalid_fanql", message: ""}` and nothing executed; success sets `input.Panel.Query = &compiled.Query` before `runFragment`. Append to the `query_telemetry` description: `Agents: write panel.query (structured JSON) first, or panel.sql for complex work; text accepts the human FanQL form (fanout://fanql/reference) and is never required.` + +- [ ] **Step 1: Write the failing tests** + +```go +func TestQueryTelemetryAcceptsFanQLText(t *testing.T) +// seeded server as fragments_test.go; input {Panel:{ID:"t",Title:"t",Viz:"table"}, Text:"spans where status:error | count() by service"} -> +// fragment Dashboard.Panels[0].Query == &panel.Query{From:"spans", Where:[]string{"status = 'STATUS_CODE_ERROR'"}, Measures:[]string{"count()"}, By:[]string{"service"}}; +// Results equal (same frame) to the structured call with that Query + +func TestQueryTelemetryRejectsTextWithQueryOrSQL(t *testing.T) // Text + Panel.SQL -> error code "invalid_input" message naming text, panel.query and panel.sql; Text + Panel.Query likewise +func TestQueryTelemetryReportsFanQLProblems(t *testing.T) // Text "spans where a:1 b:2 or c:3" -> error code "invalid_fanql", message contains "mixed and/or needs parentheses"; executor Run call count 0 +func TestQueryTelemetryRejectsUnsupportedFanQLVersion(t *testing.T) // FanQLVersion 2 -> code "unsupported_fanql_version" +func TestFanQLReferenceResource(t *testing.T) // ListResources includes fanout://fanql/reference; ReadResource -> MIMEType "text/markdown", Text contains "FanQL 1" and "Preview" +func TestQueryTelemetryDescriptionPrefersStructuredInput(t *testing.T) // the tool description contains "panel.query" before "text" and the resource URI +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/mcp/ -run 'FanQL|QueryTelemetry'` +Expected: FAIL, unknown field `Text`. + +- [ ] **Step 3: Implement the fields, the parse step, the resource and the description** + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test ./internal/mcp/... && just docs-generate && just docs-generate-check` +Expected: PASS; `TestToolsUseVerbFirstSnakeCase` and the describe/contract tests pass with their updated expectations. + +- [ ] **Step 5: Commit** + +```bash +git add internal/mcp site/src/content/docs/reference +git commit -m "feat(mcp): accept FanQL text in query_telemetry and publish the reference resource" +``` + +### Task 10: Generated reference and registry agreement + +**Files:** +- Create: `internal/fanql/reference.go` +- Modify: `cmd/fanout-docgen/main.go` (write `site/src/content/docs/reference/fanql.md` from `fanql.Reference()`), `cmd/fanout-docgen/main_test.go` +- Test: `internal/fanql/reference_test.go` +- Regenerate: `site/src/content/docs/reference/fanql.md` + +**Interfaces:** +- Consumes: `panel.SignalColumns`, `panel.LowCardinalityColumns`, `panel.MeasureSpecs`, `panel.BucketNames`, `panel.FilterFunctionNames`, `telemetry.SeverityBands`, `telemetry.SeverityAliases`, the `words.go` and `spellings.go` tables, `Version`. +- Produces: `func Reference() string` — deterministic Markdown beginning `# FanQL 1` with a `Preview: the syntax may change before GA` line; sections: shape and entry points; sources and clause words; operators with the null notes of 0.7 beside `!=` and beside `not in`/`not like`/`not between`; fields per signal (name, type, unit, description, low-cardinality marker, the `duration` and time-column rules); vocabularies (status, kind, type; severity synonyms, the band rule, the `error_rate()` note); literals and durations; buckets; measures (table of 0.10 plus semantics per signal); expressions (`count_if`, arithmetic, alias rule, `nullif`, `share()` standalone, budgets); filter functions, raw entries and the gate's accept/reject lists; variables and the All rule; traces semantics (root service, root duration) and `sort errors` as legacy; reserved words; bounds; the twelve examples; versioning. + +- [ ] **Step 1: Write the failing tests** + +```go +func TestReferenceCoversEveryRegistryEntry(t *testing.T) +// for every MeasureSpec name, BucketNames entry, FilterFunctionNames entry, column of every signal, status/kind/type alias, severity band and alias, +// operator in [: = != <> > >= < <= ~ !~ in "not in" between "not between" "is null" "is not null" like ilike "not like" "not ilike"], +// reserved word, clause word: strings.Contains(Reference(), "`"+entry+"`") (operators and words) or the name in a table row (fields) + +func TestReferenceIsDeterministicAndMarksPreview(t *testing.T) // Reference() == Reference(); HasPrefix "# FanQL 1"; contains "Preview" +func TestReferenceExamplesCompile(t *testing.T) // every fenced example line in Reference() (the twelve of 0.15 and any others) -> Compile without problems +func TestReferenceStatesTheNullRule(t *testing.T) // contains "rows without `k` are excluded; `-k:v` includes them" and "SQL spelling, SQL meaning" + +// cmd/fanout-docgen/main_test.go +func TestDocgenWritesFanQLReference(t *testing.T) // running the generator into a temp dir writes reference/fanql.md equal to fanql.Reference() with the site front matter +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/fanql/ -run Reference && bash scripts/with-duckdb.sh go test ./cmd/fanout-docgen/` +Expected: FAIL. + +- [ ] **Step 3: Implement `Reference()` and the docgen page; run `just docs-generate`** + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test ./internal/fanql/... ./cmd/fanout-docgen/... && just docs-generate-check` +Expected: PASS + +- [ ] **Step 5: Commit** + +```bash +git add internal/fanql cmd/fanout-docgen site/src/content/docs/reference +git commit -m "feat(fanql): generate the FanQL reference from the registries" +``` + +### Task 11: Corpus, round trip, truth tables, fuzzing, latency + +**Files:** +- Create: `internal/fanql/testdata/corpus.txt` (one fixture per block: text, optional viz, expected lowered JSON or expected problems), `internal/fanql/testdata/canonical.v1.golden` +- Create: `internal/fanql/corpus_test.go`, `roundtrip_test.go`, `semantics_test.go` (DuckDB), `fuzz_test.go`, `bounds_test.go`, `latency_test.go`, `registry_growth_test.go` +- Create: `internal/fanql/testdata/fuzz/` seed corpora + +**Interfaces:** +- Consumes: everything above; `dashboard.DefaultSpec()`, `scripts/dashboard-eval/testdata/server.json` (read as JSON, every `query` object), the MCP panel example fixtures (`internal/mcp/panel_examples_test.go`, exported into a shared `testdata` JSON if needed); `panel.Check`, `panel.NewExecutor`, `query.NewDuck`. +- Produces: tests only. + +- [ ] **Step 1: Write the failing tests** + +```go +func TestCorpus(t *testing.T) +// every fixture in testdata/corpus.txt: positive blocks -> Compile(text, {Viz}).Query equals the expected panel.Query (JSON-equal); negative blocks -> Compile returns nil and problems whose (message, hint, span, fix_its) equal the expected list +// the corpus contains: every positive and negative fixture of spec 0.3–0.10 (the Task 2–4 tables), the twelve at-a-glance examples, the v1 workloads of 0.16, and at least sixty more texts (completion fixtures as texts, each alias, each operator on each literal type, each foreign-word trigger) + +func TestCanonicalFreeze(t *testing.T) +// for every clean corpus text: Compile(text).Canonical equals the line in testdata/canonical.v1.golden (keyed by text); the golden file name embeds Version, so a canonical change fails unless Version changes + +func TestRoundTripCorpusFixedPoint(t *testing.T) // 0.11 guarantee 1: Format(ctx, failingParser, Compile(t).Query) -> exact, editable, Text == Canonical, zero parser calls + +func TestRoundTripStoredDashboards(t *testing.T) // Review Focus 4; 0.11 guarantee 2; DuckDB-backed +// for every panel with Query != nil in dashboard.DefaultSpec(), every dashboard in scripts/dashboard-eval/testdata/server.json and the MCP example panels: +// f := Format(q); when f.Editable: q2 := Compile(f.Text, {Viz: panel.Viz}).Query; q2 equals q byte-exact (tier exact) or RenderSQL/ParseMeasure-equal (tier normalized); +// Check(d) problems identical for q and q2; len(q2.Where) == len(q.Where); when !f.Editable: f.Text contains every stored literal; parser call count on the text == 0 + +func TestRoundTripProperties(t *testing.T) +// generator A (FanQL's own lowering): random trees over the registries, Histogram, variables, raw entries containing backticks, within bounds -> Format exact, editable, Compile fixed point (500 cases, seeded) +// generator B (structured contract): random accepted SQL per entry ≤ 500 bytes (from a grammar of the gate's accepted shapes), random measure whitespace, oversized combinations -> +// tier in {exact, normalized, raw}; Check results equal for q and the re-lowered query when editable; entry counts equal; Editable == false exactly when a bound is exceeded (compute the bound independently in the test) + +func TestEntryBoundaryShapesDiffer(t *testing.T) // {where:[a = 1, b = 2]} and {where:[a = 1 AND b = 2]} -> different texts ("… attributes['a']:1 attributes['b']:2" vs "… (attributes['a']:1 attributes['b']:2)"); each re-lowers to its own shape + +func TestEachInteractiveBoundIndependently(t *testing.T) // text runes, bytes, tokens, nodes, depth (Parse); entries, lowered entry bytes, list length (lower); each case trips exactly its bound + +func TestEditableFalsePreservationThroughEnvelope(t *testing.T) // 0.11 guarantee 6, handler half: an envelope JSON {fanql:1, text:, editable:false, query:q} round-trips through json.Unmarshal/Marshal with q JSON-equal; a parse call counter stays 0 + +func TestTruthTable(t *testing.T) // Review Focus 2; DuckDB-backed: seed 4 spans per case with attributes['k'] = 'v', 'w', uncastable where relevant, and missing; run each FanQL text through Compile -> transient table panel -> Executor.Run; assert row counts: +// k:v 1; -k:v 2; k!=v 1; -k!=v 2; k ~ v 1; -k ~ v 2; k !~ v 2; k in (v, x) 1; -k in (v, x) 2; k not in (v, x) 1; -k not in (v, x) 2; -k:* 1; k:* 2; +// http_status_code rows '404','200','abc',NULL: between 400 and 599 -> 1; -between -> 3 (200, abc, NULL); not between -> 1; -not between -> 3; >=500 -> 0; ->=500 -> 4 +// k like / not like / -like / -not like on 'GET /x', 'POST /x', NULL -> 1, 1, 2, 2 +// -(a:1 b:2) and -(a:1 or b:2) against the four-row matrix; -`attributes['k'] = 'v'` -> 2; -length(body) > 3 with NULL body -> counts the NULL row; -starts_with(http_route, "/api") with NULL route -> counts the NULL row +// stored SQL `NOT (attributes['k'] = 'v')` formatted raw and re-run -> 1 row (meaning preserved) + +func TestVariablesUnderAllPerConstruct(t *testing.T) // Review Focus 3; DuckDB-backed: each 0.6 table row with Vars{service: $__all}: entry counts after dropping and row counts as the table states + +func TestSeverityBandsEndToEnd(t *testing.T) // DuckDB-backed through ingest normalization: rows (text, number) = ("WARN2",14), ("ERROR",9), ("FATAL",0), ("INFO2",0), ("custom",0), ("",0), ("info",9), ("error",17) -> +// stored bands in row order: WARN, INFO, FATAL, INFO, CUSTOM, UNSPECIFIED, INFO, ERROR +// severity>=warn -> 3 (WARN2, FATAL, error); severity 4 (the WARN and the three INFO rows); severity between info and error -> 5; severity>=error -> 2 == rows error_rate() counts; severity:custom -> 1; ranges never match CUSTOM or UNSPECIFIED + +func TestEngineBindingOfEveryLoweredShape(t *testing.T) // DuckDB-backed: every distinct lowered Where string in the corpus, for columns and for attributes[…]/resource[…], passes panel.Check on a transient panel (parse, canonical rendering, bind); plus a 100-value in list under 500 bytes + +func TestNonExecution(t *testing.T) // for every negative corpus text: Compile returns nil; the HTTP parse response (via httptest against FanQLHandler) has no "query" key; preview only with preview:true + +func FuzzLexParsePrint(f *testing.F) // seeds: corpus texts; property: no panic; bounds respected (problems name them); work linear (token count ≤ runes+1); when Parse is clean: Print(Parse(Print(Parse(x)))) == Print(Parse(x)) +func FuzzFormatRoundTrip(f *testing.F) // seeds: stored dashboard queries; random valid panel.Query (generator B) -> Format; Parse when editable (equality under tier) or envelope otherwise + +func TestRegistryGrowth(t *testing.T) // with test hooks that add a synthetic measure "p42", bucket "2m" and filter function "ltrim": no corpus parse changes; adding a synthetic column "value" to spans changes the lowering of `spans where value>-3` and the detector reports it as a version-bump event + +func TestLatencyBudgets(t *testing.T) // skipped with -short; measured over the corpus, reported with t.Logf, asserted: +// Compile p99 < 1 ms (no engine); Format p99 < 20 ms for stored queries with up to 16 entries on the DuckDB engine (count ParseSQL/RenderSQL per call and log the max); Complete p95 < 30 ms warm and expectAt+rank p95 < 5 ms +func BenchmarkCompile(b *testing.B); func BenchmarkFormat(b *testing.B); func BenchmarkComplete(b *testing.B) + +func TestAstralCharactersSpanInCodePoints(t *testing.T) // `logs where body:"𝔘𝔫𝔦" x:1` -> problem spans for a forced error after the string count the astral characters as one each +``` + +- [ ] **Step 2: Run tests to verify they fail** + +Run: `bash scripts/with-duckdb.sh go test ./internal/fanql/ -run 'Corpus|Canonical|RoundTrip|EntryBoundary|Bound|Envelope|TruthTable|UnderAll|SeverityBands|EngineBinding|NonExecution|RegistryGrowth|Latency|Astral'` +Expected: FAIL (missing corpus and golden files; any genuine defects surface here and are fixed in the owning package). + +- [ ] **Step 3: Write the corpus and golden files, the DuckDB helpers (seeded spans and logs through the repository as `internal/panel/testhelpers_test.go` does), the generators and the test hooks; fix defects found** + +- [ ] **Step 4: Run tests to verify they pass** + +Run: `bash scripts/with-duckdb.sh go test -race ./internal/fanql/... && bash scripts/with-duckdb.sh go test -run '^$' -fuzz FuzzLexParsePrint -fuzztime 20s ./internal/fanql/ && bash scripts/with-duckdb.sh go test -run '^$' -fuzz FuzzFormatRoundTrip -fuzztime 20s ./internal/fanql/ && bash scripts/with-duckdb.sh go test -run '^$' -fuzz FuzzParseMeasure -fuzztime 20s ./internal/panel/ && just check` +Expected: PASS; fuzzers find nothing in 20 s; latency figures logged under the thresholds. + +- [ ] **Step 5: Commit** + +```bash +git add internal/fanql internal/panel +git commit -m "test(fanql): corpus, round-trip, truth-table, fuzz and latency acceptance" +``` + +### Task 12: Fold in the chat-disabled UI change (PR #395) + +**Files:** +- Modify (from commit `10253aa4` on `origin/feat/ui-without-ai`): `ui/host/src/rail.tsx`, `ui/host/src/rail.test.tsx`, `ui/host/src/dashboards/grid.tsx`, `ui/host/src/dashboards/grid.test.tsx`, `ui/host/src/settings.tsx`, `ui/host/src/settings.test.tsx`, `ui/host/src/app.test.tsx` +- Regenerate: `internal/ui/dist/**` (built from source on this branch, not copied from the PR) + +**Interfaces:** +- Consumes: `agentAvailable` from `ui/host/src/app-context.ts` (existing). +- Produces: no new interfaces; the rail hides chat, AI create, service investigation and dashboard source-chat links when `agentAvailable` is false; the grid gates Explain and Fix (including fullscreen); home lands on the default dashboard; Settings explains the provider and key variables and the MCP connection. + +- [ ] **Step 1: Cherry-pick the source changes without the committed assets** + +```bash +git fetch origin feat/ui-without-ai +git cherry-pick -n 10253aa4 +git restore --staged --worktree internal/ui/dist +``` + +- [ ] **Step 2: Run the UI tests to verify the folded tests pass on this branch** + +Run: `cd ui/host && bun run test rail grid settings app` +Expected: PASS (the new disabled-state assertions in `rail.test.tsx`, `grid.test.tsx`, `settings.test.tsx`, `app.test.tsx`). + +- [ ] **Step 3: Regenerate the embedded assets and run the gate** + +Run: `just ui-host && just ui-check && just check` +Expected: exit 0 (if `ui-audit` reports only pre-existing advisories, record them in the PR body as #395 did and do not change dependencies). + +- [ ] **Step 4: Commit with a clean message** + +```bash +git add ui/host/src internal/ui/dist +git commit -m "feat(ui): hide AI controls when chat is disabled + +Hide the remaining chat entry points when agent_available is false and +explain how to enable chat or use an MCP client in Settings. + +- Rail: no chat, AI create, service investigation or dashboard source-chat link +- Panels: no Explain or Fix, including fullscreen +- Home: default dashboard +- Settings: provider and key setup and the MCP connection guide + +Folds in #395 unchanged; the embedded host assets are rebuilt on this branch." +``` + +- [ ] **Step 5: Push and open the pull request** + +```bash +git push -u origin feat/fanql +``` + +Open a PR titled `feat(fanql): FanQL 1 parser, measure expressions, API and MCP (batch 1)`. The body lists the tasks above, the spec path (`docs/superpowers/specs/2026-10-29-no-llm-ui-design.md` section 0), the measured latency figures from `TestLatencyBudgets`, the regenerated reference pages, and a note that #395 is folded in and can be closed. No session links. + +--- + +## Self-review against the spec + +- **Coverage.** 0.1 (entry points: Tasks 2, 8); 0.2 (grammar and both lexer contexts: Tasks 1–2); 0.3 (keyword rules 1–17: Task 2, with 9's filter-function check and 15's alias check in Task 3); 0.4 (mandatory grouping: Task 2); 0.5 (field resolution, bracket canonical form, registry invariant: Tasks 3, 5); 0.6 (entries, All table, variables: Tasks 4, 11); 0.7 (truth table and leaf rule: Tasks 4, 11); 0.8 (literals, `http_status_code` cast, contains helper, raw: Tasks 3–4); 0.9 (vocabularies, shared severity table, bands and ranges, invariant test: Tasks 3, 11); 0.10 (measure table, histogram, expressions, budgets, ranking, disclosure: Tasks 2, 4, 6); 0.11 (tiers, lift, gate, `editable`, guarantees 1–6 except the UI half of 6: Tasks 5, 11); 0.12 (`QueryShape`, `viz.compatible`, `viz.edits`, traces semantics, `sort errors`, bucketed-sort notice, error model, `Problem` shape: Tasks 2–4, 8); 0.13 (routes, envelope handling in the handler, versioning, bounds: Tasks 2, 8, 9, 11); 0.14 (completion: Task 7); 0.15 (the twelve examples in the corpus, reference and round trip: Tasks 10–11); 0.16 (acceptance criteria: Task 11; the reference agreement test: Task 10). +- **Type consistency.** `panel.TextSpan`/`FixIt`/`Problem.Span` (Task 2) are what the resolver (Task 3), handler (Task 8) and completion `Replace` (Task 7) use. `fanql.Span` is the internal code-point span; conversion to `panel.TextSpan` happens where problems are built. `Compile`/`Compiled`/`Options` (Task 4) are consumed by Tasks 8, 9, 11; `Formatted`/`FormatOptions` (Task 5) by Task 8; `panel.ParseMeasure` is exported in Task 5 and re-implemented in Task 6 without a signature change; `panel.VizCompat` and `VizEdit` appear in `Compiled` and the parse response unchanged; `Completer`/`CompleteRequest`/`CompleteResponse` (Task 7) are consumed by Task 8; `Reference()` (Task 10) by Tasks 8 and 9 (Task 8 and 9 compile against a stub `Reference()` until Task 10 lands; the branch merges only complete). +- **Review focus.** Each of the five items names its test and task; items 2 and 3 are DuckDB-backed so they test the engine's semantics, not FanQL's assumptions about them. +- **Deliberately left to batch 2.** The Explore page, builder sync through `format`, the `editable: false` read-only text and Save preservation UI tests (0.11 guarantee 6, UI half), the Explore URL envelope and its share fallback, the Logs/Traces search bars, the completion popup and the `recent`/"schema unavailable" UI states, the `Array.from(text)` span conversion in the UI, and the compatible-with-edit viz picker. Everything in 0.16's "later" table is out of scope for both batches. diff --git a/docs/superpowers/specs/2026-10-29-no-llm-ui-design.md b/docs/superpowers/specs/2026-10-29-no-llm-ui-design.md new file mode 100644 index 00000000..8587a7c9 --- /dev/null +++ b/docs/superpowers/specs/2026-10-29-no-llm-ui-design.md @@ -0,0 +1,628 @@ +# Full UI without an LLM key + +Design, 2026-10-29. Status: draft for review; section 0 (FanQL) is owner-approved as of 2026-10-29. + +## Intent + +Fanout must be fully usable when no AI provider is configured (`FANOUT_AI_PROVIDER` empty). Today creating a dashboard, adding a panel, exploring data, searching logs, finding traces and managing alerts all go through chat or MCP. A self-hosted user without a key, or a hosted fanout.run customer who has not entered one, gets read-only dashboards plus SQL edits on existing panels. Chat stays the fastest path when a key exists; it must not be the only path. + +## Goals + +- Every capability chat offers for dashboards, queries, logs, traces and alerts has a direct UI path that works without AI. +- One query model: the existing structured panel query (`from`, `where`, `measures`, `by`, `bucket`, `histogram`, `sort`, `limit`), viewed and edited as FanQL text (section 0) or in a visual builder, plus the existing read-only DuckDB SQL gate for anything the structured query cannot express. +- One renderer: every result renders through the existing `PanelCard` and panel engine. No second chart, table, log or trace path. +- AI affordances (Ask, Explain, Fix, the chat rail) are hidden when chat is disabled, so nothing is a dead button. + +## Non-goals + +- A new query engine. Queries run as SQL or the existing structured query; the text syntax and the builder are two views of the structured query. +- A new execution engine or a weaker SQL gate. The backend changes are the ones section 0 lists: measure expressions (`count_if`, arithmetic) with budgets in `internal/panel`, the extraction of `QueryShape` from panel validation, the shared severity table, and read-only catalog accessors. Every change keeps the existing SQL safety gate. +- Replacing chat or MCP flows. They keep working unchanged when a key exists. + +## Anti-goals + +- A parallel renderer or a second query path for the new pages. +- Weakening the SQL gate (one read-only `SELECT`, approved relations, function blocklist, `$__window`) to make the editor easier. +- UI that shows AI controls which fail when no key is configured. + +## What exists (verified in the current tree) + +- Routes: chat, dashboards list and detail, settings (`ui/host/src/routes/`). +- Dashboards: view, layout, duplicate and remove panels, and "Edit SQL" with a run preview (`ui/host/src/dashboards/panel-sql-editor.tsx`, `grid.tsx`). "Create dashboard" opens chat with `createDashboardPrompt` (`ui/host/src/shell.tsx:54`). +- APIs: `POST /api/panels/query` (runs a dashboard spec, used by the SQL editor preview with a one-panel spec), `GET /api/telemetry/schema`, `POST /api/panels/exemplars`, `POST /api/panels/variables/resolve`, `GET /api/traces/:id`, dashboards CRUD with typed edit operations (`add_panel`, `update_panel`, `remove_panel`, `move_panel` in `internal/dashboard/edit.go`), alerting rules CRUD and alert history (`/api/alerting/rules`, `/api/alerting/alerts`, `/api/alerting/summary`). +- Panel vizzes already include `logs`, `log_patterns`, `traces`, `service_map`, `table`, `timeseries` and others, with drill drawers for logs and traces. +- Alert rules use a CEL `expression` with service, namespace, `for_seconds`, cooldown, repeat interval and webhook fields (`internal/alert/types.go`). + +## Design + +### 0. FanQL, the text query syntax (owner-approved 2026-10-29; preview) + +FanQL is the one-line text form of the structured panel query. Text parses into the same `panel.Query` that panels store and execute, and every valid query formats back to text; panels keep storing the query and the text is derived. One hand-written lexer and recursive-descent parser in Go (`internal/fanql`, with Pratt parsing for the boolean and arithmetic layers) serves the API, MCP and the UI; the UI calls an endpoint and ships no second parser. `fanql.Version` is 1. The syntax is preview: it may change before GA, with a version bump (0.13). + +**Two contracts.** The *interactive language* is the text, bounded for editing (0.13). The *exact interchange form* is the structured `Query` itself: every envelope may carry it, and clients that cannot parse text use it. `Format` is total over valid queries and never truncates; text beyond the interactive bounds is returned complete and marked `editable: false` (0.11). + +Everything below is normative. "Problem" means a diagnostic that blocks execution; "notice" means one that never does (0.12). + +#### 0.1 Shape and entry points + +``` +source [where] filters | measures by fields every bucket sort key limit n +``` + +Explore takes a whole query. The Logs and Traces search bars take `filters` only; the page supplies the source and the viz, and a `where` typed there is the problem `the page supplies where`. The viz is a picker constrained by the query (0.12): an unaggregated span query is valid as `traces`; making it a timeseries by appending `| count() every auto` is a visible edit to the text, never an implicit transformation. + +#### 0.2 Grammar + +Terminals quoted; `[ ]` optional; `{ }` repetition; keywords are case-insensitive and recognised only in the positions 0.3 states. The lexer has two contexts, **filter** and **measure** (0.5, 0.10). + +``` +query = source , [ "where" ] , [ filters ] , [ "|" , stage ] , { "|" , trailer } , [ sort ] , [ limit ] ; +source = "spans" | "logs" | "metrics" ; (* first token only *) +trailer = sort | limit ; (* "| sort x", "| limit n" accepted; canonical drops the pipe *) + +filters = or_chain | conj ; (* an or chain is the whole list, or it is grouped *) +conj = term , { [ "and" ] , term } ; +or_chain = term , "or" , term , { "or" , term } ; +term = ( "-" | "not" ) , term | primary ; (* nested; depth bound *) +primary = "(" , filters , ")" (* one entry; same grouping rule inside *) + | raw + | field , ":" , "*" (* exists *) + | field , ":" , value (* equals, alias-mapped *) + | field , ( "=" | "!=" | "<>" | ">" | ">=" | "<" | "<=" ) , value + | field , ":" , ( ">" | ">=" | "<" | "<=" ) , value (* accepted; canonical k>v *) + | field , ( "~" | "!~" ) , value (* contains, case-insensitive *) + | field , [ "not" ] , "in" , list + | field , [ "not" ] , "between" , value , "and" , value + | field , "is" , [ "not" ] , "null" + | field , [ "not" ] , ( "like" | "ilike" ) , string + | predicate_call + | free_text ; +predicate_call = fname , "(" , [ carg , { "," , carg } ] , ")" , [ ( "=" | "!=" | "<>" | ">" | ">=" | "<" | "<=" ) , value ] ; +carg = field | string | number | predicate_call ; +list = "(" , value , { "," , value } , ")" | variable ; +free_text = word | string ; +field = bracket | "resource" , "." , ident , { "." , ident } + | "attributes" , "." , ident , { "." , ident } + | ident , "." , ident , { "." , ident } (* attributes['a.b.c'] *) + | ident ; (* a column, or attributes['ident'] *) +bracket = ( "attributes" | "resource" ) , "[" , string , "]" ; +value = string | duration | number | boolean | variable | word ; +variable = "$" , ident ; + +stage = measures , [ "by" , field , { "," , field } ] , [ "every" , bucket ] + | "histogram" , "(" , field , ")" , [ "by" , field ] , [ "every" , bucket ] ; +measures = measure , { "," , measure } ; +measure = mexpr , [ "as" , alias ] ; (* alias required unless mexpr is one call; + at least one mcall per measure *) +mexpr = mterm , { ( "+" | "-" ) , mterm } ; +mterm = mfactor , { ( "*" | "/" ) , mfactor } ; +mfactor = [ "-" ] , ( mcall | number | "(" , mexpr , ")" ) ; (* unary minus *) +mcall = mname , "(" , [ marg , { "," , marg } ] , ")" (* mname in the measure registry; count(*) accepted *) + | "count_if" , "(" , filters , ")" ; (* filter context inside; one entry *) +marg = field | number | "*" ; +bucket = "auto" | "10s" | "30s" | "1m" | "5m" | "10m" | "15m" | "30m" | "1h" | "3h" | "6h" | "12h" | "1d" ; + +sort = "sort" , ( ( "+" | "-" ) , sort_key | sort_key , [ "asc" | "desc" ] ) ; +sort_key = ident ; (* measure alias; traces: duration, errors, +start; logs: time, +time; log_patterns: count *) +limit = "limit" , integer ; +``` + +Lexical grammar, filter context: + +``` +ident = ( letter | "_" ) , { letter | digit | "_" } ; +alias = lower , { lower | digit | "_" } ; (* 1..40; aliasPattern in measure.go *) +word = wordchar , { wordchar } ; +wordchar = any rune except whitespace and | ( ) , : = ! < > ~ " ' ` [ ] ; + "-" and "+" are wordchars except as the first rune of a token; + "*" is a wordchar only as the whole token (k:*); + "$" only as the first rune of a variable; "#" "{" "}" "@" are not wordchars ; +string = '"' , { char - '"' | '""' } , '"' | "'" , { char - "'" | "''" } , "'" ; +raw = "`" , { char - "`" | "``" } , "`" ; +number = digit , { digit } , [ "." , { digit } ] , [ ( "e" | "E" ) , [ "+" | "-" ] , digit , { digit } ] ; +duration = number , ( "us" | "ms" | "s" | "m" | "h" ) ; +boolean = "true" | "false" ; +integer = digit , { digit } ; +``` + +Lexical grammar, measure context (after `|` until `by`, `every`, `sort`, `limit`, a second `|` or the end; `count_if(` re-enters filter context until its matching `)`, parentheses inside strings and raw entries not counting): + +``` +ident = as above ; +path = ident , "." , ident , { "." , ident } ; (* no whitespace; one Path token; an attribute path *) +number = as above ; (* a token starting with a digit is a number: 1.5, 1e3 *) +string = as above ; bracket keys as in filter context ; +punct = "(" | ")" | "," | "[" | "]" | "+" | "-" | "*" | "/" ; +``` + +Tokens: `Word`, `Ident`, `Path` (measure context only), `String`, `Raw`, `BracketKey` (a `String` immediately preceded by `attributes[` or `resource[`), `Number`, `Punct`, `Bad`, `EOF`; every token has a code-point span. The lexer never aborts; delimiters are preserved in the stream and matching is the parser's job. In measure context `+ - * /` are always operators regardless of spacing, `*` is legal only as the sole argument of `count(`, `-` at the start of an `mfactor` is unary minus, a `.` not inside a number or between two identifiers is `Bad`, and a trailing `.` (`avg(user.)`) is `unexpected . after user; write the full key, e.g. user.id`. + +#### 0.3 Keywords and contextual rules + +| Group | Words | Recognised | +|---|---|---| +| Sources | `spans logs metrics` | first token only | +| Clause words | `where by every sort limit` and `\|` | depth 0, outside quotes and brackets, at a term boundary | +| Expression words | `and or not in between is null like ilike` | their grammatical positions only | +| Modifiers | `as asc desc` | after a measure; after a sort key | +| Buckets | `auto` and the twelve buckets | after `every` | +| Stage names | `histogram`, `count_if`, the measure functions | after `\|` and `,` | +| Reserved | `let join correlate compare since until top eval extend having fields rename over window` | clause position only; `"join" is reserved for a future FanQL feature`, hint `quote it to search for the word` | +| Foreign | see below | unmistakable syntax only | + +Rules, each with fixtures in the corpus: + +1. **Source.** `spans`, `logs`, `metrics` are recognised only as the first token; elsewhere they are words. Missing or unknown: `unknown source "X"`, hint `use spans, logs or metrics`; `traces` gets `use spans; traces is a viz of spans`; `from spans` gets `"from" is not FanQL; start with the source: spans where ...`. A bare source (`logs`) is valid: all rows under the viz's defaults. +2. **Clause words** are clause words only at depth 0, outside quotes and brackets, at a term boundary. After `:`, a comparison, `in (`, or inside a list they are values (`service:where`, `service in (sort, limit)`). As free text they must be quoted (`logs where "limit"`); canonical quotes them. `logs where limit 10` is `where needs a filter`, hint `quote "limit" to search for the word, or drop where`. `where` twice is `where appears twice; combine the filters into one where`. +3. **Expression words.** `not` at term start; `and`/`or` between terms (0.4); `in between is like ilike` after a field; `null` after `is [not]`; `and` inside `between`, which consumes its own `and` before conjunction parsing. Elsewhere they are ordinary words (`logs where in` searches "in"). A missing upper bound is `between needs two values`. +4. **Field vs free text.** A word is a field only when the next token is `:`, a comparison operator, `~`/`!~`, or one of `in`, `not in`, `between`, `not between`, `is`, `like`, `ilike`, `not like`, `not ilike`. Otherwise it is free text, whether or not it names a column (`logs where service` searches `body` for "service", with the notice `"service" is a field; did you mean service:?`). Meaning never depends on schema discovery. +5. **`:` ends a word.** `http.target:/a:b` tokenises as `http.target` `:` `/a` `:` `b`; the parser reports `unexpected : after /a`, hint `quote the value: http.target:"/a:b"`, over the whole whitespace-delimited run. The same for `http://x:8080/y` typed as free text. +6. **Comparison punctuation** `: = != <> > >= < <= ~ !~` are their own tokens, longest match first; whitespace around them is irrelevant. A bare `!` is `! negation is not FanQL`; `~~` is `~~ is SQL LIKE; use like, ilike or ~`. +7. **Signs.** After a value-expecting operator (`:`, a comparison, `in (`, `,` in a list, `between` bounds) a `-` followed by a digit or `.digit` is a numeric sign (`value>-3`; `duration>-1ms` is then `durations are not negative`). Anywhere else a leading `-` is negation (`-duration>1s` negates the term). `+` at token start is legal only after `sort` and in exponents; elsewhere `unexpected +`. Inside a word both are ordinary (`us-east-1`, `web+api`). Repeated negation parses (`--a`, `not not a`, `-not a`, depth-bounded); canonical prints one `-` for odd, none for even. +8. **Value classification.** In value position the classifier tries duration, then number, then boolean, then word. In field position a number-shaped token is `a filter needs a field before >`. +9. **Calls.** An identifier immediately followed by `(` is a call. In `where` the name must be a filter function (`lower upper starts_with contains regexp_matches length`); `spans where P95(Duration)` is `function p95 is not allowed in a filter`. Arguments are typed by signature: `starts_with(field, string)`, `contains(field, string)`, `regexp_matches(field, string)`, `lower(field)`, `upper(field)`, `length(field)`. A bare word in a `string` slot is `starts_with needs a quoted string`. `length`, `lower`, `upper` must be compared (`length(...) needs a comparison`); `starts_with`, `contains`, `regexp_matches` are predicates alone. A space before `(` is `write starts_with(...) without a space`. +10. **Optional `where`.** `where` may be omitted after the source; canonical prints it whenever a filter is present. Search bars never contain it and reject it. +11. **Foreign syntax** gets a hint, never an alias, and only on unmistakable syntax: a known foreign stage command directly after `|` (`stats summarize select project extend eval fields rename take head top order sort by`), `order by`/`group by`/`facet` at a clause position, a foreign call shape at stage position (`bin( span( percentile( perc95( pct( count_over_time( quantile_over_time( avg( mean( median( dc( distinct_count( cardinality(`), `from`, `index=`, `source=`, `search` as the first token, `ago(`, `now(`, `earliest=`, `_time:`, `since`/`until` at clause position, the operators `== =~ |= |~ ::`, `{` at term start, `@word:`, `!word:`. A bare foreign word in filter position is free text. Messages name the FanQL form: `"summarize" is not FanQL; write the measures after |, e.g. | count() by service`; `== is not FanQL; use key:value or =`; `=~ is not FanQL; ~ is contains; use regexp_matches(field, 're') for a regular expression`; `{ selectors are not FanQL; write labels as key:value, e.g. service:api`; `"@http.target" is not a field name; write the attribute without @: http.target`; `! negation is not FanQL; write -service:api`; `the time range is not part of FanQL 1; use the time picker (since is reserved)`. +12. **Quotes, backticks, brackets.** `"` or `'` with doubling as the only escape (no backslash escapes). Unclosed quote: `unclosed quote; close the value with "`, running to the end of the text. Backticks open a raw entry (0.8); `unclosed raw filter; close it with `` ` ``. Parentheses are preserved in the token stream: `unmatched ); remove it or add the opening (` and `unclosed (; add ) before |, sort, limit or the end` with the opening span. Recovery after a bad term consumes to the next whitespace at the term's depth. +13. **`*` and `$`.** `*` is legal as `k:*`, `-k:*`, `count(*)`; elsewhere in an unquoted value it is `* wildcards are not in FanQL 1`, hint `use ~ for contains, or quote "api*"`. `$ident` is a variable; `$` followed by anything else is `unexpected $`; `$__` names are rejected. +14. **Second `|`.** `| sort x` and `| limit n` after the stage are accepted and canonicalised without the pipe. Any other second stage: `FanQL 1 runs one aggregation stage`, hint `remove the second |; more stages come in a later version`. +15. **Sort.** `sort key`, `sort +key`, `sort -key`, `sort key asc`, `sort key desc`. Two directions is `sort takes one direction`. Canonical: `sort key` (descending) or `sort +key`. `limit` before `sort` is `limit comes before sort here; write ... sort duration limit 10`. The key is checked against the stage's aliases (`sort "p95" must name a measure alias; aliases here: count`) or the viz's row keys (0.12). +16. **Case.** Keywords, function names, column names, units and vocabulary aliases fold case. Values, free text and attribute/resource keys keep case (`HTTP.Target` is the key `HTTP.Target`). +17. **Limits** (0.13) are each reported at a span; `limit 0` is `limit needs a whole number from 1 to 1000; e.g. limit 50`; `every 2m` is `unknown bucket "2m"; use auto or one of 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h, 1d`; `| every 1m` alone is `every needs measures first; write | count() every 1m`; a fourth `by` field is `at most 3 grouping fields`. + +#### 0.4 Mandatory grouping for `and` and `or` + +Highest first: `( )`; `-`/`not`; comparison operators; then one level holding both `or` and `and`/juxtaposition, which **do not mix**. A filter list, the inside of a group, and the inside of `count_if` is either a conjunction or an `or` chain, never both. There is no precedence between `or` and `and`. + +- `a or b` is one entry `(a OR b)`; `a (b or c)` is entries `a`, `(b OR c)`; `(a b) or c` is one entry `((a AND b) OR c)`; `a or (b c)` is one entry; `not a b` is `(NOT a)`, `b`; `-(a or b)` is one entry. +- `a b or c`, `a and b or c`, `a or b c`, `(a b or c)`, `count_if(a b or c)` are the problem `mixed and/or needs parentheses` at the span from the first term to the last, hint `write a (b or c) or (a b) or c`, with a fix-it carrying both texts. Nothing is executed. + +The Pratt loop records the first binary operator kind seen at a level and reports the problem on seeing the other kind. The printer, completion and the fixtures follow this one grammar. Readers arrive with both habits (Splunk search evaluates `OR` before `AND`; Lucene and Kibana KQL the reverse), and the entry boundary that All depends on (0.6) makes a silent choice costly. + +#### 0.5 Fields + +Field position means a `where` term read as a field (0.3 rule 4), a measure argument, `histogram(…)` and the fields after `by`; one resolution rule serves all four: + +- A word of identifier segments is an attribute path: `http.target` is `attributes['http.target']`; `resource.` is `resource['']`; `attributes.` is `attributes['']` (canonical drops the prefix). A bracket key (`attributes['k']`, `resource["k"]`) is literal; the printer never canonicalises a bracket key into a prefix form when the prefix would change the map, so an attribute whose key begins `resource.` is reachable only as `attributes['resource.k']`. +- A **single-segment** identifier is a column when the source has one, else `attributes['ident']`, **never an error**: `spans where value>-3` is `attributes['value'] > -3` and `metrics where rate:x` is `attributes['rate'] = 'x'`. When no column matches, a notice names the reading (`"value" is not a spans column; reading attributes['value']`; for a measure name, `"rate" is a measure, not a metrics column; reading attributes['rate']`) and adds `did you mean service?` when a column is one edit away. Notices never block, so meaning never depends on discovery. +- Canonical prints the **bracket form** for single-segment attribute keys (`attributes['flag']:true`, `count_distinct(attributes['flag'])`) and the bare form for dotted keys (`http.target:/h`, `count_distinct(user.id)`). Adding a column therefore never changes the meaning of canonical or stored text; it changes hand-typed bare text and is a version bump (0.13). +- Registry invariant, tested: column names contain no `.`, so a dotted key is never a column. A segment that is not an identifier (`x-y.z`) is `"x-y.z" needs brackets`; in measure context, where `-` is an operator, `count_distinct(x-y)` is `unexpected - in count_distinct; write attributes['x-y']`. +- `duration` is `duration_ms` in filters, measures and `sort`; `time`, `start_time`, `end_time` are time columns (`"time" is a time column; compare it with > or <`). +- In measure context a dotted word is one `Path` token (`count_distinct(user.id)`, `avg(attributes.http.response_size)`, `p95(resource.k)`); a token starting with a digit is a number (`count() * 1.5`). After `by` the lexer is back in filter context, so `by resource.k8s.pod.name` is a word read as a field. +- In value position a dotted word is a value (`name:http.server.duration`). + +#### 0.6 Entries and variables + +The structured query stores `Where []string`; the compiler ANDs the entries and treats each entry as a unit: an entry referencing a variable set to All is removed whole; an entry whose variable has zero values compiles to `FALSE`; metric aggregates need `name = literal` as a standalone entry; deploy split, rollup scope, annotation scope, empty-panel diagnosis and `inferBetter` all read standalone equalities. FanQL therefore makes entry boundaries part of the meaning: + +- The tree's `Where` is an ordered list of entries. At the top level of `filters`, each whitespace- or `and`-separated term is one entry; a parenthesised group is one entry; a raw entry is one entry; an `or` chain is one entry and must be the entire filter list (otherwise it is the grouping problem of 0.4). +- `where a b (c or d) (e f)` lowers to four entries: `L(a)`, `L(b)`, `(L(c) OR L(d))`, `(L(e) AND L(f))`. `where a or b` is one entry `(L(a) OR L(b))`. +- The printer prints entries in stored order separated by single spaces, parenthesising an entry whose top node is `and` or `or` when there is more than one entry, and never merging or splitting entries. A lifted stored entry `service = $service AND status = 'STATUS_CODE_ERROR'` prints as `(service:$service status:error)`. +- Canonical text echoed after a run shows exactly the boundaries that will execute. + +Variables set to All, per construct (no backend change): + +| FanQL | Entries | Under `$service` = All | +|---|---|---| +| `service:$service status:error` | 2 | status filter kept | +| `(service:$service status:error)` | 1 | both dropped | +| `service:$service or service:worker` | 1 | whole entry dropped | +| `service:$service (status:error or status:unset)` | 2 | status group kept | +| `-service:$service` | 1 | dropped (nothing excluded) | +| `` `service = $service AND x` `` raw | 1 | dropped | +| `count_if(service:$service)` | n/a | rejected: `variables are not allowed inside count_if` | + +The reference states beside `$name`: "a filter that mentions a variable set to All is removed; keep fixed conditions in their own terms". `$service` lowers as `$service`; `k in $multi` lowers to `k IN $multi`; `service:$multi` for a multi variable is `$multi holds several values; use service in $multi`. With `variables` supplied, an undeclared `$x` is a problem with the declared list; without them every `$x` is the notice `declared variables are needed to check $x`, so the search bars can parse, and the run goes through `Check`. + +#### 0.7 Null semantics and negation + +`attributes['k']` is NULL when the key is absent; SQL `k != 'v'` on NULL is NULL and excludes the row. FanQL predicates are two-valued ("matched" or "not matched") and negation is negation of "matched". Negation is pushed to the leaves (negation normal form: `-(a b)` is `(-a) or (-b)`, `-(a or b)` is `(-a) (-b)`, `--a` is `a`); positive leaves are never wrapped, so the standalone-equality shape the panel depends on survives. + +**Rule: prefix negation (`-`, `not`, and FanQL's own `!~`) includes rows missing the field; SQL-spelled infix negation (`!=`, `<>`, `not in`, `not like`, `not between`) keeps SQL three-valued semantics**, so stored SQL negatives lift exactly. + +| Row has `k = v` | `k = w` | `k` missing | FanQL | Lowered | +|---|---|---|---|---| +| T | F | F | `k:v`, `k=v` | `k = 'v'` | +| F | T | **T** | `-k:v`, `not k:v` | `(k IS NULL OR k != 'v')` | +| F | T | F | `k!=v`, `k<>v` | `k != 'v'` (SQL) | +| T | F | **T** | `-k!=v`, `-k<>v` | `(k IS NULL OR k = 'v')` | +| T | F | F | `k ~ v` | `contains(lower(k), lower('v'))` | +| F | T | **T** | `-k ~ v`, `k !~ v` | `(k IS NULL OR NOT contains(lower(k), lower('v')))` | +| T | F | F | `k in (v, x)` | `k IN ('v', 'x')` | +| F | T | **T** | `-k in (v, x)` | `(k IS NULL OR k NOT IN ('v', 'x'))` | +| F | T | F | `k not in (v, x)` | `k NOT IN ('v', 'x')` (SQL) | +| T | F | **T** | `-k not in (v, x)` | `(k IS NULL OR k IN ('v', 'x'))` (a different filter from `-k in`) | +| F | F | T | `-k:*`, `k is null` | `k IS NULL` | +| T | T | F | `k:*`, `k is not null` | `k IS NOT NULL` | +| per bounds | | **T** | `-k between a and b` | `(k IS NULL OR k NOT BETWEEN a AND b)` | +| per bounds | | F | `k not between a and b` | `k NOT BETWEEN a AND b` (SQL) | +| per bounds | | **T** | `-k not between a and b` | `(k IS NULL OR k BETWEEN a AND b)` | +| per cast | | **T** | `-http_status_code between 400 and 599` | `NOT coalesce((TRY_CAST(http_status_code AS INTEGER) BETWEEN 400 AND 599), FALSE)` | +| per pattern | | **T** | `-k like "p"` | `(k IS NULL OR k !~~ 'p')` | +| per pattern | | F | `k not like "p"` | `k !~~ 'p'` (SQL) | +| per pattern | | **T** | `-k not like "p"` | `(k IS NULL OR k ~~ 'p')` | + +**The complete leaf rule.** The authoritative lowering of a negated leaf is `NOT coalesce((p), FALSE)`, where `p` is the leaf's positive lowering including any cast or function it wraps around the field (its effective predicate). The shorter `(k IS NULL OR )` spelling is a permitted rewrite of that form, used only when the effective operand is the stored field itself or a rename or cast that is NULL exactly when the field is NULL (`duration_ms` for `duration`; `CAST(attributes['k'] AS VARCHAR)` inside `contains`). The effective operand decides first; the simple spelling never overrides it. + +| Leaf class | Negated lowering | +|---|---| +| Equality, membership, contains, between, like, comparison whose operand is the stored field | `(k IS NULL OR NOT-form)` as in the table | +| Prefix negation of an SQL-negative leaf on the stored field (`-k!=v`, `-k not in`, `-k not like`, `-k not between`) | `(k IS NULL OR k = 'v')`, `(k IS NULL OR k IN (…))`, `(k IS NULL OR k ~~ 'p')`, `(k IS NULL OR k BETWEEN a AND b)` | +| Existence | `-k:*` is `k IS NULL` | +| Any leaf whose positive lowering wraps the field in `TRY_CAST` or a function: `http_status_code` under `< <= > >=`, `between`, `not between`; attribute `k>5` through a cast; predicate calls and compared calls (`-starts_with(http_route, "/api")`, `-length(body) > 1000`) | `NOT coalesce((p), FALSE)`, the only form; `http_status_code IS NULL` alone would miss a present non-numeric value whose cast is NULL | +| Raw entry `` -`expr` `` | `NOT coalesce((expr), FALSE)` | +| Free text `-word` | `(body IS NULL OR NOT contains(lower(body), lower('word')))` | +| Variable comparison `-k:$v` | `(k IS NULL OR k != $v)`; under All the entry is dropped | + +The reference says beside `!=`: "rows without `k` are excluded; `-k:v` includes them", and beside `not in`/`not like`/`not between`: "SQL spelling, SQL meaning. To exclude these values and include rows missing the field, put `-` before the positive predicate: `-k in (v)`. `-k not in (v)` is a different filter: it negates the SQL-negative predicate and matches rows where `k` is `v` or `k` is missing." Completion offers the `-k in` form after `-`. For columns that are never NULL the forms agree; the `IS NULL` branch is still emitted so the rule has no exceptions. `NOT`, `coalesce`, `IS NULL`, `IN`, `BETWEEN` are all accepted by the filter gate (`filterOperators` in `filter.go`). + +#### 0.8 Literals, contains, raw entries + +| Literal | Form | Typing rule | +|---|---|---| +| String | `"a b"`, `'a b'`, bare `api`, `/healthz`, `us-east-1` | Quote doubling; no backslash escapes. A quoted value is always a string and is never alias-mapped (`status:"STATUS_CODE_ERROR"`, `severity:"error"`). | +| Number | `500`, `1.5`, `2e3`, `-3` | On a number column: number. On a string column: quoted string (`http_status_code:500` is `'500'`). On an attribute: number as typed (`attributes['k'] = 500`); quote to force text. | +| Boolean | `true`, `false` (case-insensitive, bare) | On an attribute: boolean literal; on a string column: `'true'`; on a number column: `duration_ms needs a number`. | +| Duration | `500ms`, `1.5s`, `250us`, `2m`, `1h` | Only on `duration`; converted to milliseconds; no compound `1h30m`; negative rejected. `duration>500` is `duration needs a unit; e.g. duration>500ms` (`duration_ms>500` takes a bare number). On any other field: `units apply to duration only; write http_status_code>500`. | +| Timestamp | `"2026-10-29T10:00:00Z"`, `"2026-10-29 10:00:00"` (quoted; optional fraction and offset; no offset means UTC) | Only on time columns; lowered to `'…'::TIMESTAMPTZ_NS`. Elsewhere a string. | +| Variable | `$service` | 0.6 | +| Existence | `k:*` | `IS NOT NULL`; `-k:*` is `IS NULL`. The only accepted `*` in a value. | +| Free text | `timeout`, `"connection reset"` | `contains(lower(body), lower(text))` on logs, `operation` on spans; metrics: `free text needs a field on metrics; use name:http.server.duration`. | +| Raw | `` `expr` `` | below | + +**`http_status_code`** is a text column. Comparisons `< <= > >=` and `between` on it lower through `TRY_CAST(http_status_code AS INTEGER)` so `>=500` is numeric; equality and `in` stay on the text column (`= '500'`) so the standalone-equality shape survives. One catalog flag (`compareAs: integer`) on one field. + +**Contains.** One helper produces every substring test: `containsSQL(field, value) = contains(lower(), lower())`, where `` is the column or `CAST(attributes['k'] AS VARCHAR)` for attribute and resource lookups (emitted unconditionally), and `` is a string literal with `'` doubled or `$name`. It serves `k ~ v`, `-k ~ v`, `k !~ v`, free text and `-word`; `%` and `_` in the value are ordinary characters. `like`/`ilike` are explicit SQL-pattern operators (`k like "GET %"` is `k ~~ 'GET %'`; `ilike` is `~~*`) so lifted agent filters print without raw; `ESCAPE` is not expressible, and a pattern needing a literal `%` uses `~`. + +**Raw entries.** `` `expr` `` is one entry passed to `checkFilter` verbatim; inside, a doubled backtick is a literal backtick and a single backtick ends the entry, so any string is encodable (`` `coalesce(body, '``') = ''` ``). Raw entries print exactly as stored. The reference lists what the gate accepts: columns, `attributes['k']`/`resource['k']`, comparisons, boolean logic, `IN`, `LIKE`, `IS NULL`, `BETWEEN`, `coalesce`, casts to `VARCHAR BIGINT INTEGER DOUBLE BOOLEAN UBIGINT TIMESTAMPTZ_NS`, `lower upper starts_with contains regexp_matches length`, `$variables`. Not accepted, and so not expressible even raw: `CASE`, `DISTINCT`, `ORDER BY` and `FILTER` inside functions, qualified column names, other functions. + +#### 0.9 Vocabularies and severity + +Aliases apply only under `:`, `=`, `!=`, `<>`, `-`/`not`, `in`, `not in`. Under `~`, `like`, `ilike`, inside function calls, and whenever the value is quoted, the value is literal. The stored spelling is always accepted bare too (`status:STATUS_CODE_ERROR`); canonical prints the alias. Exception, by name: under `<`, `<=`, `>`, `>=` and `between`, a `severity` operand is a level name and is rank-mapped; every other field's range operand is literal. + +| Field | Aliases (input, case-insensitive) | Stored | +|---|---|---| +| `status` (spans) | `error ok unset` | `STATUS_CODE_ERROR` `STATUS_CODE_OK` `STATUS_CODE_UNSET` | +| `kind` (spans) | `server client internal producer consumer unspecified` | `SPAN_KIND_*` | +| `severity` (logs) | canonical `trace debug info warn error fatal unspecified`; ingestion synonyms `warning` (warn), `critical crit emerg emergency alert panic` (fatal), `err severe exception` (error), `information informational notice` (info), `dbg fine` (debug), `verbose finest` (trace); trailing digits dropped (`INFO2`) | the canonical name, uppercase | +| `type` (metrics) | `gauge counter updown histogram summary` | same | +| `duration` | unit suffixes | `duration_ms` | + +Any other word under `severity:` is uppercased, as ingestion does for unknown levels, with the notice `not a standard level; stored levels in this window: …` when schema values are available. `status:fail` is `unknown status "fail"; use status:error, status:ok or status:unset`; `kind:http` likewise. + +The severity alias table is **the same table ingestion uses**: `normalizeSeverity`, `severityFromText` and the rank order move to `internal/telemetry/severity.go` and are imported by `ingest` and `fanql`; no behaviour change in ingestion. + +**Bands and ranges.** Every stored log row's `severity` is `normalizeSeverity(text, number)`: a positive `severity_number` determines the band (≥21 FATAL, ≥17 ERROR, ≥13 WARN, ≥9 INFO, ≥5 DEBUG, ≥1 TRACE); only an absent or nonpositive number falls back to the text mapping, which yields a band, `UNSPECIFIED`, or the emitter's own uppercased word. The stored column is therefore the effective band, computed once with number authority, and ranges compare it: + +| FanQL | Lowered | +|---|---| +| `severity>=warn` | `severity IN ('WARN', 'ERROR', 'FATAL')` | +| `severity>warn` | `severity IN ('ERROR', 'FATAL')` | +| `severityfatal`, `severityfatal matches no level; use severity:fatal` | +| `severity between error and info` | `between needs the lower level first: severity between info and error` | +| `severity>=custom`, `severity>=unspecified` | `"custom" has no severity rank; use trace, debug, info, warn, error or fatal` | + +Consequences: WARN2 (number 14) is stored `WARN` and satisfies `>=warn` and `=warn`; number 0 with text `FATAL` is stored `FATAL` and fails `=14`. The lowering contains no `CASE` (which the filter gate rejects) and lifts back: a stored `severity IN (…)` whose list is exactly a contiguous run of bands in ascending rank order prints as the range form; any other list prints as `severity in (…)`. The rule relies on one invariant, stated in the reference and guarded by a test: no stored log row bypasses `normalizeSeverity` (this product carries no legacy reader). `error_rate()` on logs uses `upper(severity) IN ('ERROR', 'FATAL', 'CRITICAL') OR severity_number >= 17`, which on normalized rows is exactly `severity>=error`; the reference says so beside both. + +#### 0.10 Measures, distributions, expressions + +Measures, as the reference documents them: + +| Measure | Spans and logs | Metrics | +|---|---|---| +| `rate()` | rows per second over the bucket or window | counter increase per second with coverage weighting; counters only | +| `avg(value)` | n/a | gauge/updown point average; histogram `sum/count`; counter: no value, with diagnosis | +| `error_rate()` | percent of rows matching the error definition above | not available | +| `share()` | percent of the scope's rows in this group (window aggregate over the whole scope) | same idea over series | +| `count_distinct(f)` | any field, including string attributes | same | +| `last(f)` | not available | kind-aware last value | +| numeric measures on attributes | through `TRY_CAST(… AS DOUBLE)`; non-numeric values become NULL | same | + +**Distribution form.** `| histogram(duration)` on spans and `| histogram(value)` on metrics lower to `Measures: ["count()"]` and `Histogram: {Field: "duration_ms", Buckets: "log2"}` or `{Field: "value", Buckets: "explicit"}`, the only two shapes validation accepts. `by field` (one; histogram viz) and `every bucket` (heatmap) follow the usual rules; `histogram(…)` cannot be combined with other measures (`distribution counts require count(); histogram(...) stands alone`). Lifting: `Histogram != nil` prints `histogram(f)`; a stored query with `Histogram` and measures other than `["count()"]` fails validation and is not formatted. + +**Conditional aggregates and arithmetic** are in v1 for spans and logs on aggregate vizzes (stat, gauge, timeseries, bar, table, scatter, state_timeline); not for metrics (`measure arithmetic is not available for metrics`), distributions or `log_patterns`. The structured query carries them, so this is a backend change in `internal/panel`: + +- `count_if()` takes one FanQL filter list (same grammar and grouping rule as `where`, one entry); variables inside are rejected in v1; raw entries are allowed. Structured form: the expression with the inner filter in SQL, e.g. `count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as err_pct`; compiled as `count(*) FILTER (WHERE )::DOUBLE`. +- `+ - * /` between measure calls, numeric constants and parenthesised expressions; unary minus. `/` lowers to `a / nullif(b, 0)`; a zero denominator yields NULL. +- An expression that is not a single call needs `as alias` (`name this expression with as, e.g. count() / 2 as half`). A single call keeps the auto-alias rules. +- **Every output expression has at least one aggregate leaf** (a call or `count_if`); numeric constants are operands only. `1 as one`, `1 / 2 as half`, `-(5) as neg` are `a measure needs an aggregate; constants can only scale one, e.g. count() * 100`; `count() * 0 as zero` is valid. The backend enforces the rule on structured `Query.Measures` too. +- **`share()` is a standalone measure only.** Inside an expression it is `share() cannot be combined; it is already a percentage of the scope`, hint `use share() alone, or count_if(...) / count() * 100 for a custom ratio`. Reason: paths that select rows before aggregating (table trends, the metrics trend branch, totals) detect `share` by its top-level function name to restore the whole-scope denominator; a `Binary` root would evade that detection. +- Units: a ratio of two count-family measures is `ratio`; `* 100` on a ratio is `percent`; `+`/`-` of equal units keep the unit; `*`/`/` with a constant keeps the unit; anything else is `none`. Expressions are not additive (no stacking). +- `inferBetter` extends to expressions recursively: a single call is today's rule; an affine `a·x + b` takes `x`'s inference, flipped when `a < 0`; a `ratio`/`percent` whose numerator is a `count_if` over an error filter is `lower`; a `count_if(error filter)` alone is `lower`; otherwise neutral. +- Apdex is written with disjoint predicates: `(count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex`; a span at exactly 500 ms counts once, as satisfied; the population is the rows surviving `where`; a NULL duration counts in `count()` and in neither numerator. + +**Budgets** are enforced in `internal/panel` on every `Query.Measures[i]` string at parse time, whether it arrived from the builder, MCP, a stored dashboard or FanQL. They count tokens and nodes, never raw bytes, so every string accepted today (including whitespace-padded single calls) parses unchanged: + +| Budget | Per measure | Per query | +|---|---|---| +| Tokens (whitespace is not a token) | 256 | — | +| Nodes (`Call`, `CountIf`, `Binary`, `Neg`, `Const`) | 64 | 256 | +| Nesting depth (`Binary`, `Neg`, parentheses together) | 8 (fails at 9 before recursing) | — | +| Aggregate leaves (`Call`, `CountIf`) | 8, and at least 1 | 24 | +| `count_if` filter text | 500 bytes (a `where` entry) | — | +| Measures | — | 6 | + +Problems are reported at `panels[i].query.measures[j]` with the figure and the limit (`measures[2] has 70 nodes; a measure is at most 64`); FanQL maps them to the measure's text span. Raising a budget is additive (a spec note, no FanQL version bump); tightening one so that accepted text would be rejected bumps the FanQL version. + +**Ranking of grouped series.** Grouped timeseries and two-dimension bars select `top` series by ranking the first measure over the whole window; today's rules (`error_rate` by Wilson lower bound behind a 20-sample floor regardless of `better`; numeric measures by value behind the same floor counting actual samples; count-family by value) stay, and every order ends with the compiler's deterministic tie-breakers `n DESC, d` (dimension string ascending). Expressions attach ranking metadata instead of dispatching on the root: + +| Expression shape | Support `n` | Eligibility | Order among eligible | Rule | +|---|---|---|---|---| +| Single registered call | as today | as today | as today | `builtin` | +| Affine of one call `g = a·f + b` (`a*f + b`, `f/c`, `-f`, `b - f`; `a ≠ 0`) | `f`'s | `f`'s | `f`'s own ranking expression, **untransformed**, with `f`'s direction computed from `better_g` mapped through the sign of `a` (flipped when `a < 0`); the coefficients are never applied to the score | `inherit` | +| Recognised binomial ratio `r = count_if(P) / count()`, optionally affine-scaled, same population | `count(*)` | `n >= 20` | by `better_r` on the unscaled proportion: `lower` → Wilson lower bound DESC; `higher` → Wilson upper bound ASC; neutral → Wilson lower bound DESC; `P` matching the error filter makes the default `lower` | `wilson` | +| Ratio with a `count_if` or `count(field)` denominator | the denominator's row count | `n >= 20` | `value NULLS LAST` | `value_floor` | +| Any other expression | `min` over aggregate-leaf supports (`count(field)` for numeric leaves, `count(*)` for count-family and `count_if`) | `n >= 20` | `value NULLS LAST` (`` is DESC unless `better` is `higher`) | `value_floor` | + +Ineligible series (`n < 20`) follow eligible ones by `n DESC, d`; they are ranked last, not removed. Disclosure: `Result.Ranking = {rule, better: "lower" | "higher" | "neutral", floor: 20, support_column, below_floor: k, tie_breakers: ["n desc", "dimension asc"]}` and a frame note when `k > 0` (`k series had fewer than 20 samples and were ranked last`), shown where the UI shows "Other (N)". Consequences that are fixtures: `error_rate() + 0`, `error_rate() * 100`, `100 - error_rate()`, `-error_rate()` and `error_rate()` select identical series in identical order; `-p95(duration)` with `better: higher` selects what `p95(duration)` selects with `better: lower`; `100 - count_if(status:error) / count() * 100` with `better: higher` ranks the Wilson lower bound of the error proportion DESC. + +#### 0.11 Round trip: format, lift, exactness, `editable` + +`Format(q)` lifts a valid `panel.Query` to a FanQL tree and prints it. Definitions, comparing the re-lowered tree with `q` entry by entry using the internal lowering: + +- **Byte-exact**: every `Where[i]` and `Measures[i]` equal as Go strings; `By`, `Bucket`, `Sort`, `Limit`, `Histogram`, `From` equal. +- **AST-exact (normalized)**: some `Where[i]` or `Measures[i]` strings differ while the engine's canonical rendering is equal: `RenderSQL(ParseSQL(lowered)) == RenderSQL(ParseSQL(stored))` for filters, and equality of the parsed measure (function, field, quantile, alias) for measures (so `p95( duration_ms )` formats as `p95(duration)`, normalized). +- **Raw**: a `Where[i]` whose tree contains a node FanQL has no construct for, or whose shorthand candidates all fail the exactness check, prints as a backtick entry; byte-exact by construction. +- **Equivalent** (same results on all data) is not a tier FanQL claims anywhere. + +`Format` returns `exactness: "exact" | "normalized"` (raw entries are exact) and `notices` naming each normalized entry (`where[2] is shown as service:api; stored text is "service='api'"`). Saving from the editor writes the FanQL spelling; the UI shows the notice first. A query that fails shape validation under every viz is not formatted; `Format` returns its problems. + +**Lifting through the engine's parse tree.** Stored strings are arbitrary author text and the engine's parse is the only authority on what they mean, so `Format` runs on the API side with an injected `panel.Parser`. Each `Where[i]` is parsed as `SELECT 1 FROM WHERE ()` (as `checkFilter` does) and the `where_clause` is mapped: `AND`/`OR` conjunctions to entries and groups; `NOT` to a candidate negation; comparisons with a field side and a constant or parameter side; `IN`/`NOT IN`; `BETWEEN`; `IS NULL`/`IS NOT NULL`; `~~ ~~* !~~ !~~*` to `like` forms; `contains(lower(F), lower(C))` to `~`; the engine's parse of `IN $p` to `in $p`; `attributes`/`resource` extracts and the `CAST … AS VARCHAR` inside `contains` to attribute fields; `TRY_CAST(http_status_code AS INTEGER)` under a comparison to `http_status_code`; timestamp casts to timestamps; `severity IN (contiguous bands)` to a range; `NOT coalesce((X), FALSE)` where `X` maps to a leaf to that leaf under prefix negation; the `(k IS NULL OR k = C)` family to `-k!=v`, `-k not in`, `-k not like`, `-k not between`. Anything else (`coalesce`, other casts, field-to-field, `lower(k) = 'v'`, `starts_with`, `regexp_matches`, `length`, `CASE`) is `Raw` for that entry. Measures lift through the backend expression parser; `duration_ms` prints as `duration`, attribute fields in their canonical spelling, `as alias` when stored; `Sort: "errors"` prints `sort errors`. + +**Exactness gate and fallback.** The printer emits candidate text per entry and re-lowers it with the internal entry parser, whose interactive bounds are disabled (the bounded public `Parse` is never part of the gate). Shorthand candidates (`k:v`, `-k:v`, `k!=v`, `duration>500ms`, `k ~ v`, bare word, dotted key, vocabulary alias, severity range) are tried first and kept only if re-lowering is byte-exact or AST-exact. Whenever no candidate passes, **the whole original entry prints raw**, including recognised-but-incompatible trees: stored `NOT (attributes['k'] = 'v')` is raw (FanQL's only negation of `k:v` is null-inclusive); stored `NOT (k ~~ 'x%')` is raw while `k !~~ 'x%'` is `k not like "x%"`; stored `k NOT IN ('a', 'b')` is `k not in (a, b)`; stored `(attributes['k'] IS NULL OR attributes['k'] != 'v')` is `-k:v`; stored `NOT coalesce((attributes['k'] = 'v'), FALSE)` is raw (the permitted rewrite is canonical); stored `NOT coalesce((TRY_CAST(http_status_code AS INTEGER) BETWEEN 400 AND 599), FALSE)` is `-http_status_code between 400 and 599`; stored `(service IS NULL OR service IN ('a', 'b'))` is `-service not in (a, b)`. Format of a query FanQL itself produced never calls the engine: lowering is a pure function and the byte-exact check is a string comparison. + +**`editable`.** `Format` carries `editable: true` when the text is within every interactive bound (0.13), else `editable: false` with `reason` (`formatted text is 15,466 bytes; the editor accepts 8,192`) and the complete text. The UI then shows the text read-only and keeps the builder on the original `Query`; Save writes that `Query` unchanged; the share action falls back to a saved view carrying `query` because a URL cannot carry the text. `Parse` enforces the interactive bounds before tokenising and reports the first one exceeded at a span. The **text-reparse property** `Lower(Parse(Format(q))) == q` under the reported tier is promised and tested only for `editable: true`; `editable: false` text is never submitted to `parse`, and its contract is preservation through the structured envelope (0.13). Oversized valid queries exist (sixteen 480-byte `body` literals; raw entries whose backticks double on escaping; measures padded with whitespace); nothing merges or drops entries to make them fit. + +Guarantees, as tests: (1) every clean corpus text is a fixed point of `Format(Lower(Parse(t)))` with `exact` and `editable`; (2) every valid query in the default dashboards, the dashboard eval fixtures and the MCP tests formats with a tier and `editable`; when editable, `Lower(Parse(Format(q)))` equals `q` under the tier, `Check` results are identical and no entry count changes; when not, the text is complete, the envelope carries `q`, `q` survives JSON round trip, and the parser is never called; (3) property tests from FanQL's own lowering (always `exact`, `editable`, fixed point) and from the structured contract (tier in {exact, normalized, raw}, equal `Check` results and entry counts, `editable == false` exactly when a bound is exceeded); (4) a stored two-entry query and a stored one-entry `AND` query with the same predicates format to different texts and lower back to their own shapes; (5) each interactive bound is tested independently; (6) preservation for `editable: false` through the envelope, the builder and Save. + +#### 0.12 Validation, problems and notices + +**Shape checks.** `parse` and `complete` accept `viz` and `variables` (the dashboard's declarations), both optional; `format` accepts `variables` and an optional `panel`. The resolver lowers to `panel.Query` and calls a new exported `panel.QueryShape(q, viz, vars)`, extracted from the in-memory checks that depend only on the query, the viz and the declarations: from `validateQuery` (entry count and bytes, measure count and the grouped-one-measure rule, `by` bounds, bucket rules, histogram shape, limit, sort alias, unit families, reduce-one-measure), from `validateRows` (row-viz source, sort keys, `log_patterns` shape, no measures/by/bucket, no histogram), from `validateItems` (scatter two measures, `state_timeline` one measure and no sort), and variable references when declarations are supplied. `Requires` lists what full panel validity needs beyond the query: `min_max` for gauge, `thresholds` for `state_timeline`. Stacking additivity, highlight, option maxima and `Check`-only rules (filter binding, metric-name requirement, rollup representability, annotation projection) stay where they are; the FanQL handler maps `panels[0].query.where[i]` paths back to spans when `Check` runs on the transient panel. + +The parse response reports shape problems with spans mapped from the lowered field back to the text (`measures[0]`, `where[2]`, `sort`, `bucket`, `by[1]`), and `viz.compatible: [{viz, requires: []}]` for every viz whose shape check passes **on the query as written**. `QueryShape` never normalizes; a timeseries without a bucket is reported as compatible-with-edit: `viz.edits: [{viz: "timeseries", text: "… every auto"}]`, applied only when the user accepts. Nothing returns a mutated query. + +| Viz | Requires | Forbids | +|---|---|---| +| `logs`, `traces` | `from` logs / spans | measures, `by`, bucket, `histogram` | +| `log_patterns` | `from logs`, `by body_template`, `count()`; bucket auto or listed | a sort other than `count` | +| `timeseries` | 1-6 measures, bucket, `by` ≤ 1; one measure when grouped | | +| `bar` | `by` 1-2; one measure with 2 `by` | bucket | +| `table` | measures; `by` ≤ 3 | bucket | +| `stat`, `gauge` | exactly 1 measure; gauge: `requires min_max` | bucket, `by` | +| `heatmap` | `histogram(…)`, bucket | `by` | +| `histogram` | `histogram(…)` | bucket; `by` ≤ 1 | +| `scatter` | 2 measures, `by` 1-2 | | +| `state_timeline` | 1 measure, `by` 1, bucket; `requires thresholds` | sort | + +**Traces.** The `traces` viz does not list matching spans: candidates are `(namespace, trace_id)` pairs with at least one span matching the filters in the window, ranked by the matching spans' `max(duration_ms)` (or `min(start_time)` for `sort +start`), limited to `limit` (at most 1,001); each candidate returns one row, the trace's root span (or its earliest span in the window when the root is outside it), with `status` set to error if any span in the trace errored. The reference says exactly this; the Explore trace list labels columns "root service" and "root duration". Trace sort keys: `duration` (canonical for `duration_ms`), `errors`, `+start`; `sort +duration` and `sort start` are `traces sort descending by duration, by errors, or ascending by start only`. Logs: `time`, `+time`. `log_patterns`: `count`. + +**`sort errors` stays.** It is valid stored state (appends `status = 'STATUS_CODE_ERROR'` and orders by duration). FanQL accepts and prints it with the notice `sort errors also filters to error spans; new queries: write status:error … sort duration`; completion after `sort` under traces offers `duration`, `+start` and `errors` (detail "filters to errors, orders by duration"); the reference teaches `status:error … sort duration` and lists `errors` as the legacy combined key. + +**Bucketed sort and limit.** For bucketed aggregates the compiler orders by time and selects series by `options.top`, ignoring `Sort`/`Limit`; the panel accepts them, so FanQL must too. With `viz` in a bucketed family, a `sort` or `limit` yields the notice `sort does not apply to bucketed series; series are chosen by top (options)`; the same for `limit` on `stat`/`gauge`. Without a viz, no notice. + +**Error model.** (1) A text with any problem has no executable form: the parse response carries no `query`, Run and Save stay disabled, the user's text is never replaced. (2) All problems in one pass, in source order, capped at 20 (`more problems follow; fix these first` as the 21st); recovery exists to find more problems and to drive completion, never to produce a runnable remainder. (3) A repaired preview is returned only when requested (`preview: true`) and is labelled `not executable`. (4) Notices are a separate list and never block. (5) Fix-its are suggestions attached to a problem; applying one is a user action. + +```go +type Problem struct { + Path string `json:"path"` + Message string `json:"message"` + Hint string `json:"hint,omitempty"` + Span *TextSpan `json:"span,omitempty"` // additive; code-point offsets, end exclusive + FixIts []FixIt `json:"fix_its,omitempty"` // additive; alternatives, never applied automatically +} +type TextSpan struct{ Start, End int } +type FixIt struct { + Label string `json:"label"` + Span TextSpan `json:"span"` + Text string `json:"text"` +} +``` + +`panel.Problem` keeps `Path`, `Message`, `Hint`; `Span` and `FixIts` are additive. There is no severity field: notices (`{path, message, span?}`) use their own list. + +#### 0.13 API, envelope, versioning, bounds + +``` +POST /api/fanql/parse + {version: 1, text, source?, viz?, variables?, preview?: bool} + 200 {version: 1, query, canonical, viz: {requested?, compatible: [{viz, requires: []}], edits: [{viz, text}]}, + notices: [{path, message, span?}]} + 400 {code: "invalid_fanql", message: "The query has problems.", problems: [...], preview?: {text, note: "not executable"}} + +POST /api/fanql/format + {version: 1, query, viz?, variables?, panel?} + 200 {version: 1, text, exactness: "exact" | "normalized", editable: bool, reason?: string, notices: [...]} + 400 {code: "invalid_spec", ... problems} (the query fails QueryShape under every viz) + 503 {code: "unavailable", message} (engine parse failed operationally) + +POST /api/fanql/complete + {version: 1, text, cursor, source?, viz?, window?, namespace?, variables?} + 200 {version: 1, replace: {start, end}, items: [{label, insert, kind, detail}], + schema: {window, sampled: true, warm: bool, recent: bool}} + +GET /api/fanql/reference?version=1 text/markdown +``` + +`format` needs in-memory shape validity under some viz, the supplied `variables` to judge `$x` references (without them, references are notices), and the engine only for `ParseSQL`/`RenderSQL` of stored entries; it never runs `Check`'s bind step or `Normalize`; `panel` is accepted so a builder round trip can report `requires` satisfied or not, and is otherwise ignored. + +**Handler.** `PanelHandler` holds a `PanelEngine` (`Exemplars`, `Run`, `ResolveVariables`, `Schema`) and no parser, so FanQL gets its own handler with an injected `panel.Parser` (`*query.Duck` implements it): + +```go +type FanQLHandler struct { + parser panel.Parser + engine PanelEngine // Schema, for completion +} +func RegisterFanQLRoutes(e *echo.Echo, parser panel.Parser, engine PanelEngine) +``` + +Routes use the 20-second panel deadline; operational errors (`panel.isOperational`) become `503 unavailable` and are logged through `PresentError`, never turned into problems; bodies are decoded with `decodeStrict` and the existing 512 KiB limit; all routes need the `telemetry:read` capability and are classified in `classifyRoute`. Unknown or unsupported `version`: `400 {code: "unsupported_fanql_version", message, hint: "this server reads FanQL 1"}`. A missing `version` means the current one and adds a notice. + +**Envelope.** Panels store `panel.Query` only; the text is derived. Everything else that carries text carries the version and the context the text needs: + +```json +{ + "fanql": 1, + "text": "spans where service:$service | p95(duration) by http_route every 1m", + "editable": true, + "query": { "...": "the lowered Query; required when editable is false, optional otherwise" }, + "viz": "timeseries", + "time": { "range": "1h" }, + "compare": "previous_period", + "variables": [ { "name": "service", "kind": "query", "from": "spans", "field": "service", "include_all": true } ], + "vars": { "service": "checkout" }, + "namespace": "prod", + "options": { "top": 6, "style": "line" } +} +``` + +When `editable` is false the envelope must carry `query`; consumers open the builder on it, show `text` read-only and never submit that text to `parse`. Explore URL: `?v=1&q=&viz=&range=1h|from=..&to=..&compare=&vars=&ns=`; `v` dispatches the parser version, and an unsupported `v` shows the text read-only with the `unsupported_fanql_version` message; an oversized text falls back to a saved view carrying `query`. `time` is `panel.Time`; `compare` is `previous_period` (the only value); `namespace` scopes schema and completion and is not a query filter (`namespace:prod` is). MCP `query_telemetry` gains `text` and `fanql_version` beside `panel`; `panel.query` stays the documented first choice for agents, with SQL for complex work; the text form is accepted and documented for agents but never required. Chat transcripts and documentation carry text without an envelope; they are not machine inputs. + +**Versioning.** (1) `fanql.Version = 1` is accepted on every input and returned on every output. (2) The version changes when a text that parsed under N parses differently or not at all under N+1; reinterpreting a bare word that was already accepted with a meaning is such a change, so a new `severity` alias bumps the version (every bare word is already a stored literal there) while a new `status`/`kind` alias (previously an error), a new stage word after `|` and a new filter function name are additive. (3) Adding a column to a signal changes the meaning of hand-typed single-segment `name:v` text and bumps the version; canonical text is unaffected because single-segment attribute keys print in bracket form; a registry test checks every new column name against the corpus. (4) Canonical output is frozen within a version by a pinned corpus of canonical outputs. (5) Preview status: breaking changes are allowed with a bump and a rewrite path (`Format_2(Lower_1(Parse_1(text)))`), since the lowered `panel.Query` is the shared meaning. (6) The structured `Query` evolves under `panel.SpecVersion` (1); the measure grammar is additive to the spec. + +**Bounds.** Interactive (the text): 4,000 code points **and** 8,192 bytes, whichever fails first (`a query is at most 4000 characters (8192 bytes)`); 1,024 tokens; 512 AST nodes; nesting depth 16 (groups, negation, calls, arithmetic together); `in` lists of 100 values; 20 problems; 50 completion items. Structured (the `Query`), enforced at lowering and reported at the text span: 16 entries (at the 17th entry's span); 500 **bytes** per lowered entry (`this filter lowers to N bytes; filters are at most 500`); 6 measures; 3 `by` fields and the viz's maximum; the expression budgets of 0.10. UI spans are code points; the UI converts once with `Array.from(text)`, and a test covers astral characters in values and keys. + +#### 0.14 Completion + +Inputs: `GET /api/telemetry/schema` returns low-cardinality column values (12 per column, 200 for `service`), attribute keys sampled from 5,000 rows with at most 200 keys per signal (each with type, count and up to three service names), metric names; windows are limited to 24h and relative to now, cached one minute per `(window, namespace)`. Rules that follow: + +1. **Window clamp and recency, disclosed.** Completion requests `window = min(explore range, 24h)`. `schema.recent` is true whenever the Explore window is absolute or longer than 24h, and the popup header then says "keys seen in the last 24h (recent), not in the selected interval". +2. **Sampled metadata ranks; it never hides.** Every key seen is offered; keys not seen are still legal. Service lists only boost keys whose list contains a `service:` literal already in the text. +3. **Cold cache never blocks, and never stampedes.** With no schema for the cache key, completion answers from registries alone with `schema.warm: false` and requests one coalesced background fetch per `(window, namespace)` key, at most 4 concurrent process-wide, on a detached context with the existing 20-second schema deadline. A failed fetch is cached negatively for 10 s and reported as `warm: false, error: true`; the UI re-requests on the next keystroke and shows "schema unavailable" after two failures. +4. **Types rank, not gate.** In a numeric argument slot, number-typed attributes list first, then everything else. `count_distinct` lists every field. `quantile`'s second slot offers `0.5 0.9 0.95 0.99`. Zero-argument functions insert `()` and move on. + +Algorithm: lex the whole text (never fails); the current token is the one containing the cursor or ending at it, and `replace` is its whole span (`sev|erity:error` replaces `severity`). Inside a `String` or `Raw` token: no completion. Inside a `BracketKey` token (`attributes['htt|`): key completion for that scope, the replace span is the key text inside the quotes and the insert closes the bracket (`http.target']`); an unterminated bracket key is still a `BracketKey`. Parse the prefix in completion mode, recording the set of alternatives the parser would accept next (`source`, `clause`, `field`, `operator`, `value(field)`, `measure`, `marg(func, index)`, `bucket`, `sort_key`, `integer`, `variable`, `bracket_key(scope)`; the term-start class is the union of field, free text, `-`, `(`, `$`, `not` and clause words). Map classes to candidates ranked by exact prefix match, substring match, class order and schema count; at most 50 items; the viz and variables shape the sets: + +| Position | Candidates | +|---|---| +| source | `spans logs metrics` | +| after source | `where`, `\|`, `sort`, `limit`; plus fields | +| term start | columns with descriptions; attribute keys (dotted bare; single-segment as `attributes['k']`; `resource.k`); `-`, `(`, `not`; declared `$vars`; a trailing "free text searches body/operation" item | +| after a field | `:`, `>`, `>=`, `<`, `<=`, `!=`, `~`, `in`, `not in`, `between`, `is null`, `like`; after a time field only comparisons; after `duration` comparisons and `between`; after `severity` comparisons (ranges) and `:` | +| after `field:` | the column's values; vocabulary aliases for `status kind severity type`; metric names; `$vars`; `duration`: `500ms 1s 5s`; boolean attributes: `true false`; `*` | +| after `severity>=` etc. | `trace debug info warn error fatal` | +| after `\|` | measures valid for the signal (`error_rate` hidden on metrics, `last` only on metrics), `histogram(` when the viz is heatmap/histogram or unset, `count_if(` | +| inside `fn(` | by signature and argument index | +| after a measure | `,`, `as`, `by`, `every` (only when the viz takes a bucket or is unset), `sort`, `limit`; `+ - * /` (not after `share()`) | +| after `by` | string columns and attribute keys; respects the viz's maximum | +| after `every` | `auto` and the twelve buckets | +| after `sort` | the stage's aliases with `+` forms; without a stage, the viz's row keys | +| after `limit` | `10 50 100 1000`, capped by the viz | + +Latency acceptance: p95 under 30 ms end-to-end with a warm cache and under 5 ms for parse and rank alone; cold bursts measured separately (50 concurrent completions on an empty cache issue exactly one schema query per cache key and at most 4 at once). + +#### 0.15 FanQL at a glance + +One line per query. Prefix `-` excludes and includes rows missing the field; `!=` is SQL. Mix `and` and `or` only with parentheses. `$name` is a dashboard variable; a term mentioning a variable set to All is removed, so keep fixed conditions in their own terms. + +``` + 1 spans where kind:server | error_rate() by service every 1m + 2 spans where service:checkout duration>500ms sort duration limit 50 + 3 spans where service:$service (status:error or status:unset) | count() by http_route + 4 spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route + 5 spans where kind:server | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex + 6 spans | histogram(duration) by service + 7 spans where service:checkout status:error -http.target:/healthz | count() by http_route + 8 spans where user.id:* | count_distinct(user.id) by service + 9 logs where service:api severity:error timeout sort time limit 200 +10 logs where severity>=warn | count() by body_template sort count limit 10 +11 metrics where name:http.server.requests | rate() by service every 1m +12 metrics where name:k8s.container.restarts | last(value) by resource.k8s.pod.name +``` + +| # | Shows | Viz | Notes | +|---|---|---|---| +| 1 | spans, built-in ratio, grouping, bucket | timeseries | percent of server spans in error; top 6 services, rest in Other | +| 2 | spans as traces, duration unit, sort, limit | traces | returns trace roots ranked by the slowest matching span | +| 3 | variable, mandatory `or` grouping | bar/table | two entries; under All the status group stays | +| 4 | conditional aggregate, arithmetic, alias | table/bar | numeric comparison on the text column via TRY_CAST; no bucket as written, so `timeseries` is offered only as an edit that appends `every auto` | +| 5 | Apdex with disjoint predicates | stat | a span at exactly 500 ms counts once | +| 6 | distribution | histogram | `every 1m` instead of `by` makes it a heatmap | +| 7 | null-inclusive exclusion | bar/table | spans without `http.target` are counted | +| 8 | existence, string distinct count | table | `-user.id:*` would find spans missing the key; `count_distinct(user.id)` lexes as one `Path` argument | +| 9 | logs, free text, severity alias | logs | `timeout` is a case-insensitive substring of `body` | +| 10 | severity range, pattern grouping | log_patterns | `>=warn` is WARN, ERROR, FATAL on the stored band | +| 11 | metrics counter rate | timeseries | counter increase per second, not points per second | +| 12 | metrics gauge, resource attribute | table | `last(value)` is kind-aware; `resource.k` is `resource['k']` | + +Comparison claims are descriptive only: over the four reference queries whose output contract is equivalent across FanQL, Fanout SQL, SPL, KQL and Grafana, the FanQL strings total 255 characters against 285 (SPL), 324 (Grafana, with two UI settings), 460 (KQL) and 670 (SQL). These are string sums for typing on a stated dataset, not claims about task completion, learning time or error rates. + +#### 0.16 Scope: version 1 and later + +Version 1 covers, as corpus fixtures that parse, lower, pass `Check` against the pinned engine and run on seed data: error rate by service; p99 by endpoint; top-N slow operations; Apdex; logs for a trace; count distinct users; latency histograms (spans and metrics); 4xx/5xx classes via `count_if`; slow DB statements; queue lag gauges; pod restarts; counter rates; per-route error ratios; errors, total and ratio in one table; absence of a field through `-k:*`; save, share and rerun through the envelope. Partial in v1: comparison with the previous period (envelope `compare`, not text); logs around a trace's time (typed timestamps by hand). + +| Later capability | Why not v1 | Where it goes | +|---|---|---| +| Derived grouping (`4xx`/`5xx` classes in `by`) | needs row expressions in `by`; the engine groups by catalog fields only | `eval` stage in a typed plan lowered to SQL | +| Multi-dimension timeseries | renderer and series selection are one-dimensional | engine and renderer | +| Correlation (`correlate … on trace_id`, a semijoin) and joins | no cross-signal execution path | plan lowered to SQL through the existing gate | +| Top-N per group, per bucket | the compiler folds into Other by one ranking | plan to SQL | +| Arbitrary-lag overlay (`compare 7d`) | `compare` is previous-period only | executor change plus envelope | +| Explicit time in text (`since`/`until`) | time lives in the dashboard/Explore state | envelope first; text later with the reserved words | +| `share()` inside arithmetic | denominator scope through `Binary` nodes in five paths | metadata on the measure expression | +| Absence operators | needs expected-entity inventories | alerts | +| Metrics arithmetic | series alignment across kinds | after the spans/logs expressions land | +| Alias references between measures | not in the structured query | later | + +Extensibility by construction: the parser builds a tree and a separate lowering maps it to the structured query; `|` is a list of stages and any second aggregation stage is `FanQL 1 runs one aggregation stage`, not a syntax error; the reserved words of 0.3 are errors now; functions, field spellings, vocabularies, buckets and foreign-word hints live in registries and the reference is generated from them with a test that every entry appears. Later plans store `Panel.SQL` for execution plus `Panel.Plan` for the round trip; the text round-trips from the plan, never from generated SQL, and editing a plan panel in the SQL tab detaches it. One engine, one gate, one renderer. + +Acceptance replaces size and time estimates: the corpus (every fixture, the twelve examples, the covered workloads, at least sixty more texts); the round-trip guarantees of 0.11; DuckDB-backed truth tables for every negation row and leaf class, variables under All, and severity through ingestion; engine binding of every lowered shape; non-execution of texts with problems; fuzzing over lex, parse, resolve, lower and print in both lexer contexts plus random valid queries through `Format`; completion fixtures and the cold-cache test; ranking fixtures with the `Ranking` disclosure; measured latency (parse, resolve and lower p99 under 1 ms without the engine; `format` p99 under 20 ms for stored queries with up to 16 entries; `complete` p95 under 30 ms warm); every registry entry in the reference and `just docs-generate-check` guarding the site copy; the canonical freeze; registry growth detection; and the structural budgets on structured and text inputs alike. + +### 1. Explore page (`/explore`) + +A single page for ad-hoc questions: + +- Signal picker (spans, logs, metrics), time range (the dashboard time control), and two editors on tabs: + - **Query:** a one-line FanQL box (section 0) with completion from `POST /api/fanql/complete`; the default. Problems render at their spans with fix-its; notices render separately; the canonical text is shown after a run. + - **Builder:** dropdowns for `measures`, `by`, `where` and `bucket`, fed by `GET /api/telemetry/schema` (columns, attribute keys per service, metric names, measure functions). Produces the structured `query`; edits stay in sync with the text box through `POST /api/fanql/format`. When `format` returns `editable: false`, the text is read-only and the builder edits the structured query. + - **SQL:** the existing SQL editor and diagnostics, for advanced use. +- A viz picker limited to `viz.compatible` from the parse response; a compatible-with-edit viz (a timeseries that needs `every auto`, listed under `viz.edits`) is offered as an edit the user accepts. +- Run sends a transient one-panel dashboard spec to `POST /api/panels/query`, as the SQL editor preview already does, and renders the result with `PanelCard`. +- "Open as SQL" converts a builder query to editable SQL when the backend can render it; the reverse direction is not offered. +- "Save to dashboard" picks an existing dashboard or creates a new one, then applies `add_panel`. +- The URL carries the FanQL envelope (section 0.13: `?v=1&q=…&viz=&range=…&vars=…&ns=`) so an Explore view can be shared and bookmarked; an oversized `editable: false` text falls back to a saved view carrying `query`. + +### 2. Logs and Traces as Explore presets + +Rather than separate renderers, the rail gets **Logs** and **Traces** entries that open Explore preset to `viz: logs` (sorted by time) and `viz: traces` (sorted by duration or errors). The search bar accepts FanQL `filters` only (section 0.1); the page supplies the source and viz. Filters (service, severity, status, duration, free-text body search on the redacted body) are also builder fields. Clicking a row uses the existing drill drawers. + +### 3. Dashboards without chat + +- "New dashboard": a name plus a first panel built in the Explore drawer (see Decisions 1), and "Duplicate dashboard" on any dashboard. Uses `POST /api/dashboards`. +- "Add panel" in edit mode opens the Explore editor in a drawer and applies `add_panel`. +- "Edit panel" opens the same editor for builder and SQL panels (the current SQL editor becomes its SQL tab). +- When chat is enabled, "Create with AI" remains next to "New dashboard". + +### 4. Alerts page (`/alerts`) + +- List rules with state and last fired time, and firing history from `/api/alerting/alerts`. +- Create, edit, enable/disable and delete rules on the existing API, with a form for name, service, namespace, `for_seconds`, cooldown, repeat interval and webhook fields. +- The expression field accepts CEL with inline validation from the API's error response and a few starter templates (error rate, p95 latency, throughput, log volume) matching the documented rule kinds. +- Role checks follow the existing capabilities (`read` to view, `manage` to change). + +### 5. AI affordances off when chat is disabled + +`agentAvailable` (already in `app-context.ts`) gates every AI control: chat rail, Ask buttons, Explain, Fix, and "Create with AI". The home route lands on the default dashboard instead of chat when chat is disabled. Settings shows how to enable chat and how to connect an MCP client. + +## Decisions from review (Claude's calls; the owner can overturn them) + +1. **No empty dashboards.** The spec keeps its 1–40 panel invariant (`internal/panel/validate.go`). "New dashboard" asks for a name, then opens the Explore editor in a drawer; the dashboard is created with that first panel. Removing the last panel stays refused. +2. **No template gallery yet.** Only `DefaultSpec()` exists and every owner already has it. Add a "Duplicate dashboard" action instead (new name required); templates become a later content task. +3. **AI keys stay env-only in Fanout.** Self-hosted: Settings explains `FANOUT_AI_PROVIDER` and the key variables, and how to connect an MCP client. Hosted fanout.run: the customer enters a key on the fanout.run account page, and the control plane renders it into the tenant's environment and redeploys (Onebox Cloud design). Fanout gains no secret storage. +4. **UI saves follow the MCP rule that panels must return data,** enforced in the UI: Save and Add panel are enabled only after a run returned rows without error. The HTTP API and the existing SQL editor keep their current behaviour. +5. **Variables.** The Add-panel drawer opened from a dashboard can reference that dashboard's variables (for example `$service`), and the FanQL editor and the builder's where-editor understand `$name` with the All rule of section 0.6. When saving from Explore into a dashboard that has a variable on the same field, the save dialog offers to replace the literal filter with the variable. + +## Constraints + +- Follow `AGENTS.md`: API naming and route conventions for any new endpoint, snake_case JSON, no legacy or fallback paths, one renderer. +- Web conventions in the repository's web style guide and patterns documents; Mantine components already used by the host app. +- Tests for each page (render, empty state, error state, role gating, chat-disabled gating) alongside the existing Vitest suites; Go tests for any backend change. + +## Left to the builder + +- Exact layout and component structure of the builder, within the existing design system. +- Whether "Open as SQL" needs a small backend endpoint that renders a structured query to SQL, or can reuse existing code; add one only if no existing path exists. +- Encoding details of the Explore URL beyond the envelope fields section 0.13 fixes. +- Ordering of the work into pull requests. From 9b2a539f4b95af3669f971becde1a7bb61f4ef91 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 15:35:49 -0700 Subject: [PATCH 02/30] feat(fanql): lex FanQL text in filter and measure contexts --- internal/fanql/fanql.go | 5 + internal/fanql/lexer.go | 231 +++++++++++++++++++++++++++++++++++ internal/fanql/lexer_test.go | 217 ++++++++++++++++++++++++++++++++ 3 files changed, 453 insertions(+) create mode 100644 internal/fanql/fanql.go create mode 100644 internal/fanql/lexer.go create mode 100644 internal/fanql/lexer_test.go diff --git a/internal/fanql/fanql.go b/internal/fanql/fanql.go new file mode 100644 index 00000000..f4570604 --- /dev/null +++ b/internal/fanql/fanql.go @@ -0,0 +1,5 @@ +// Package fanql parses the versioned text form of Fanout's structured telemetry queries. +package fanql + +// Version identifies the interactive language contract. +const Version = 1 diff --git a/internal/fanql/lexer.go b/internal/fanql/lexer.go new file mode 100644 index 00000000..3b2e77f4 --- /dev/null +++ b/internal/fanql/lexer.go @@ -0,0 +1,231 @@ +package fanql + +import ( + "fmt" + "strings" + "unicode" +) + +type Context uint8 + +const ( + FilterContext Context = iota + MeasureContext +) + +type Kind uint8 + +const ( + EOF Kind = iota + Word + Ident + Path + String + Raw + BracketKey + Number + Punct + Bad +) + +// Span uses code-point offsets, with an exclusive end. +type Span struct{ Start, End int } + +type Token struct { + Kind Kind + Text string + Quote byte + Unclosed bool + Ctx Context + Span Span + Message string + Hint string +} + +type Tokens []Token + +func identStart(r rune) bool { return unicode.IsLetter(r) || r == '_' } +func identContinue(r rune) bool { return identStart(r) || unicode.IsDigit(r) } +func digit(r rune) bool { return r >= '0' && r <= '9' } + +// Lex never fails and always ends with EOF. A depth-zero pipe enters measure +// context; by/every/sort/limit or another pipe leaves it. count_if's matching +// parentheses enclose filter context, ignoring delimiters inside quoted tokens. +func Lex(text string) Tokens { + r := []rune(text) + ts := make(Tokens, 0, min(len(r)+1, 1024)) + ctx := FilterContext + depth, brackets := 0, 0 + var conditional []int + for i := 0; i < len(r); { + if unicode.IsSpace(r[i]) { + i++ + continue + } + start := i + tok := Token{Ctx: ctx} + c := r[i] + switch { + case c == '"' || c == '\'' || c == '`': + tok.Kind, tok.Quote = String, byte(c) + if c == '`' { + tok.Kind = Raw + } else if n := len(ts); n >= 2 && ts[n-1].Text == "[" && (strings.EqualFold(ts[n-2].Text, "attributes") || strings.EqualFold(ts[n-2].Text, "resource")) { + tok.Kind = BracketKey + } + i++ + var body strings.Builder + tok.Unclosed = true + for i < len(r) { + if r[i] == c { + i++ + if i < len(r) && r[i] == c { + body.WriteRune(c) + i++ + continue + } + tok.Unclosed = false + break + } + body.WriteRune(r[i]) + i++ + } + tok.Text = body.String() + case ctx == MeasureContext && identStart(c): + tok.Kind = Ident + i++ + for i < len(r) && identContinue(r[i]) { + i++ + } + for i+1 < len(r) && r[i] == '.' && identStart(r[i+1]) { + tok.Kind = Path + i += 2 + for i < len(r) && identContinue(r[i]) { + i++ + } + } + tok.Text = string(r[start:i]) + if depth == 0 && brackets == 0 { + switch strings.ToLower(tok.Text) { + case "by", "every", "sort", "limit": + ctx = FilterContext + tok.Ctx = ctx + tok.Kind = Word + } + } + case ctx == MeasureContext && digit(c): + tok.Kind = Number + i = scanNumber(r, i) + case c == '$': + i++ + if ctx == FilterContext && i < len(r) && identStart(r[i]) { + tok.Kind = Word + for i < len(r) && identContinue(r[i]) { + i++ + } + } else { + tok.Kind = Bad + tok.Message = "unexpected $" + } + case strings.ContainsRune("|(),:=!<>~[]+-*", c) || (ctx == MeasureContext && c == '/'): + tok.Kind = Punct + i++ + if i < len(r) { + pair := string(r[start : i+1]) + switch pair { + case ">=", "<=", "!=", "<>", "!~": + i++ + case "~~": + i++ + tok.Kind = Bad + tok.Hint = "~~ is SQL LIKE; use like, ilike or ~" + tok.Message = tok.Hint + } + } + if c == '!' && i == start+1 { + tok.Kind = Bad + tok.Message = "! negation is not FanQL" + } + case strings.ContainsRune("#{}@", c): + tok.Kind = Bad + i++ + case ctx == FilterContext: + tok.Kind = Word + i++ + for i < len(r) && !unicode.IsSpace(r[i]) && !strings.ContainsRune("|(),:=!<>~\"'`[]*${}#@", r[i]) { + i++ + } + default: + tok.Kind = Bad + i++ + if c == '.' && len(ts) > 0 && ts[len(ts)-1].Kind == Ident { + prev := ts[len(ts)-1].Text + tok.Message = fmt.Sprintf("unexpected . after %s; write the full key, e.g. %s.id", prev, prev) + } + } + if tok.Text == "" && tok.Quote == 0 { + tok.Text = string(r[start:i]) + } + tok.Span = Span{start, i} + if tok.Kind == Bad && tok.Message == "" { + tok.Message = "unexpected " + tok.Text + } + if tok.Kind == Punct { + switch tok.Text { + case "[": + brackets++ + case "]": + brackets = max(0, brackets-1) + case "(": + depth++ + if ctx == MeasureContext && len(ts) > 0 && strings.EqualFold(ts[len(ts)-1].Text, "count_if") { + conditional = append(conditional, depth) + ctx = FilterContext + } + case ")": + if n := len(conditional); n > 0 && depth == conditional[n-1] { + ctx = MeasureContext + tok.Ctx = ctx + conditional = conditional[:n-1] + } + depth = max(0, depth-1) + case "|": + if depth == 0 && brackets == 0 { + if ctx == FilterContext { + ctx = MeasureContext + } else { + ctx = FilterContext + } + } + } + } + ts = append(ts, tok) + } + return append(ts, Token{Kind: EOF, Ctx: FilterContext, Span: Span{len(r), len(r)}}) +} + +func scanNumber(r []rune, i int) int { + for i < len(r) && digit(r[i]) { + i++ + } + if i < len(r) && r[i] == '.' { + i++ + for i < len(r) && digit(r[i]) { + i++ + } + } + if i < len(r) && (r[i] == 'e' || r[i] == 'E') { + end := i + 1 + if end < len(r) && (r[end] == '+' || r[end] == '-') { + end++ + } + start := end + for end < len(r) && digit(r[end]) { + end++ + } + if end > start { + i = end + } + } + return i +} diff --git a/internal/fanql/lexer_test.go b/internal/fanql/lexer_test.go new file mode 100644 index 00000000..8861ace0 --- /dev/null +++ b/internal/fanql/lexer_test.go @@ -0,0 +1,217 @@ +package fanql + +import ( + "reflect" + "strings" + "testing" +) + +func tokenTexts(ts Tokens) []string { + var out []string + for _, t := range ts { + out = append(out, t.Text) + } + return out +} + +func TestLexFilterContextTokens(t *testing.T) { + ts := Lex("spans where http.target:/a:b duration>=500ms -k:v us-east-1 $svc") + want := []string{"spans", "where", "http.target", ":", "/a", ":", "b", "duration", ">=", "500ms", "-", "k", ":", "v", "us-east-1", "$svc", ""} + if !reflect.DeepEqual(tokenTexts(ts), want) { + t.Fatalf("tokens: %#v", ts) + } + for i, tkn := range ts { + kind := Word + if strings.Contains(" : >= - ", " "+tkn.Text+" ") { + kind = Punct + } + if i == len(ts)-1 { + kind = EOF + } + if tkn.Kind != kind || tkn.Ctx != FilterContext { + t.Errorf("token %d: %#v", i, tkn) + } + } +} + +func TestLexLongestMatchOperators(t *testing.T) { + var got []string + for _, tok := range Lex("a>=b a<>b a!~b a!=b a:>b a<=b") { + if tok.Kind == Punct { + got = append(got, tok.Text) + } + } + if !reflect.DeepEqual(got, []string{">=", "<>", "!~", "!=", ":", ">", "<="}) { + t.Fatal(got) + } +} + +func TestLexBadTokens(t *testing.T) { + for _, tc := range []struct{ text, bad, message, hint string }{ + {"!service:api", "!", "! negation is not FanQL", ""}, + {"body ~~ x", "~~", "", "~~ is SQL LIKE; use like, ilike or ~"}, + {"#tag", "#", "", ""}, {"$ x", "$", "unexpected $", ""}, + } { + t.Run(tc.text, func(t *testing.T) { + for _, tok := range Lex(tc.text) { + if tok.Kind == Bad && tok.Text == tc.bad { + if tc.message != "" && tok.Message != tc.message { + t.Fatal(tok) + } + if tc.hint != "" && tok.Hint != tc.hint { + t.Fatal(tok) + } + return + } + } + t.Fatal("missing Bad token") + }) + } +} + +func TestLexStringsAndQuoteDoubling(t *testing.T) { + for _, tc := range []struct { + text, decoded string + quote byte + unclosed bool + }{ + {`k:"a ""b"" c"`, `a "b" c`, '"', false}, {`k:'it''s'`, "it's", '\'', false}, {`k:"unclosed`, "unclosed", '"', true}, + } { + tok := Lex(tc.text)[2] + if tok.Kind != String || tok.Text != tc.decoded || tok.Quote != tc.quote || tok.Unclosed != tc.unclosed { + t.Errorf("%s: %#v", tc.text, tok) + } + if tc.unclosed && tok.Span.End != len([]rune(tc.text)) { + t.Fatal(tok) + } + } +} + +func TestLexRawEntries(t *testing.T) { + for _, tc := range []struct { + text, decoded string + unclosed bool + }{{"`coalesce(body, '``') = ''`", "coalesce(body, '`') = ''", false}, {"`coalesce(a", "coalesce(a", true}} { + tok := Lex(tc.text)[0] + if tok.Kind != Raw || tok.Text != tc.decoded || tok.Unclosed != tc.unclosed || tok.Quote != '`' { + t.Fatal(tok) + } + } +} + +func TestLexBracketKeys(t *testing.T) { + ts := Lex(`attributes['http.target']:x`) + if !reflect.DeepEqual(tokenTexts(ts), []string{"attributes", "[", "http.target", "]", ":", "x", ""}) || ts[2].Kind != BracketKey { + t.Fatal(ts) + } + tok := Lex(`resource["k8s.`)[2] + if tok.Kind != BracketKey || tok.Text != "k8s." || !tok.Unclosed { + t.Fatal(tok) + } + if Lex(`k:'x'`)[2].Kind != String { + t.Fatal("ordinary quote became bracket key") + } +} + +func TestLexMeasureContextSwitching(t *testing.T) { + ts := Lex("spans where a:1 | count_if(status:error -http.target:/healthz) / count() * 1.5 as x by resource.k8s.pod.name every 1m") + want := []string{"spans", "where", "a", ":", "1", "|", "count_if", "(", "status", ":", "error", "-", "http.target", ":", "/healthz", ")", "/", "count", "(", ")", "*", "1.5", "as", "x", "by", "resource.k8s.pod.name", "every", "1m", ""} + if !reflect.DeepEqual(tokenTexts(ts), want) { + t.Fatal(ts) + } + for i, tok := range ts { + ctx := FilterContext + if i >= 6 && i <= 23 && !(i >= 8 && i <= 14) { + ctx = MeasureContext + } + if tok.Ctx != ctx { + t.Errorf("%d: %#v", i, tok) + } + } + if ts[6].Kind != Ident || ts[21].Kind != Number || ts[24].Kind != Word { + t.Fatal(ts) + } +} + +func TestLexPathAndNumberInMeasureContext(t *testing.T) { + ts := Lex("spans | count_distinct(user.id) + avg(attributes.http.response_size) - p95(resource.k) * 1e3 as spread") + var paths []string + for _, tok := range ts { + if tok.Kind == Path { + paths = append(paths, tok.Text) + } + if tok.Text == "1e3" && tok.Kind != Number { + t.Fatal(tok) + } + } + if !reflect.DeepEqual(paths, []string{"user.id", "attributes.http.response_size", "resource.k"}) { + t.Fatal(paths) + } + ts = Lex("spans | avg(user.)") + if ts[4].Kind != Ident || ts[5].Kind != Bad || ts[5].Text != "." || ts[5].Message != "unexpected . after user; write the full key, e.g. user.id" { + t.Fatal(ts) + } + if got := tokenTexts(Lex("spans | count_distinct(x-y)")); !reflect.DeepEqual(got, []string{"spans", "|", "count_distinct", "(", "x", "-", "y", ")", ""}) { + t.Fatal(got) + } + ts = Lex("spans | count() * -1 as neg") + if ts[5].Text != "*" || ts[6].Text != "-" || ts[7].Kind != Number { + t.Fatal(ts) + } +} + +func TestLexCountIfParenDepthIgnoresStringsAndRaw(t *testing.T) { + ts := Lex("spans | count_if(body:\"a)b\" `x = ')'`) / count() as r") + for _, tok := range ts { + if tok.Text == "/" { + if tok.Kind != Punct || tok.Ctx != MeasureContext { + t.Fatal(tok) + } + return + } + } + t.Fatal("missing division") +} + +func TestLexSpansAreCodePoints(t *testing.T) { + ts := Lex(`logs where body:"héllo ✓" x`) + if ts[4].Span != (Span{16, 25}) || ts[5].Span != (Span{26, 27}) { + t.Fatal(ts) + } +} + +func TestLexClauseWordsInsideDelimitersStayTokens(t *testing.T) { + ts := Lex(`logs where body:"a | b sort c" attributes['x.by']:y`) + counts := map[Kind]int{} + for _, tok := range ts { + counts[tok.Kind]++ + if tok.Text == "|" || tok.Text == "sort" { + t.Fatal(tok) + } + } + if counts[String] != 1 || counts[BracketKey] != 1 || ts[4].Text != "a | b sort c" || ts[7].Text != "x.by" { + t.Fatal(ts) + } + ts = Lex("logs where `coalesce(body,'|')=''` | count()") + var raw, pipes int + for _, tok := range ts { + if tok.Kind == Raw { + raw++ + } + if tok.Text == "|" { + pipes++ + } + } + if raw != 1 || pipes != 1 { + t.Fatal(ts) + } +} + +func TestLexAlwaysEndsWithEOFAndNeverPanics(t *testing.T) { + for _, input := range []string{"", "|", "((((", "\"", "`", "attributes[", "$", strings.Repeat("-", 100), "\xff\xfe"} { + ts := Lex(input) + if len(ts) == 0 || ts[len(ts)-1].Kind != EOF { + t.Fatalf("%q: %#v", input, ts) + } + } +} From cc4b00a016ec82da2b64c736e9eba68c00b4005b Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 15:46:35 -0700 Subject: [PATCH 03/30] feat(fanql): parse FanQL into a tree with recovering diagnostics --- internal/fanql/ast.go | 197 ++++ internal/fanql/parser.go | 1298 ++++++++++++++++++++++++++ internal/fanql/parser_test.go | 536 +++++++++++ internal/fanql/words.go | 117 +++ internal/mcp/presentation_test.go | 3 +- internal/panel/deploy_split_test.go | 3 +- internal/panel/distribution_test.go | 2 +- internal/panel/drill_logs_test.go | 5 +- internal/panel/exemplars_test.go | 5 +- internal/panel/items_test.go | 2 +- internal/panel/problems.go | 21 +- internal/panel/problems_test.go | 29 + internal/panel/rollup_panels_test.go | 3 +- 13 files changed, 2205 insertions(+), 16 deletions(-) create mode 100644 internal/fanql/ast.go create mode 100644 internal/fanql/parser.go create mode 100644 internal/fanql/parser_test.go create mode 100644 internal/fanql/words.go create mode 100644 internal/panel/problems_test.go diff --git a/internal/fanql/ast.go b/internal/fanql/ast.go new file mode 100644 index 00000000..f411fd65 --- /dev/null +++ b/internal/fanql/ast.go @@ -0,0 +1,197 @@ +package fanql + +import "github.com/labstack/fanout/internal/panel" + +type Query struct { + Source string + SourceSpan Span + Where []Expr + WhereWord bool + Stage *Stage + Sort *Sort + Limit *Limit + Span Span +} + +type Expr interface{ Span() Span } +type And struct { + Terms []Expr + At Span +} +type Or struct { + Terms []Expr + At Span +} +type Not struct { + X Expr + At Span +} +type Compare struct { + Field Field + Op string + Value Value + At Span +} +type In struct { + Field Field + Values []Value + Variable string + Negated bool + At Span +} +type Between struct { + Field Field + Lo, Hi Value + Negated bool + At Span +} +type Like struct { + Field Field + Pattern Value + Insensitive bool + Negated bool + At Span +} +type IsNull struct { + Field Field + Negated bool + At Span +} +type Exists struct { + Field Field + At Span +} +type Call struct { + Name string + Args []CallArg + Cmp *Comparison + At Span +} +type CallArg struct { + Field *Field + Value *Value + Call *Call +} +type Comparison struct { + Op string + Value Value +} +type FreeText struct { + Value Value + At Span +} + +// RawExpr is a raw SQL filter entry. Raw names its lexical token kind. +type RawExpr struct { + Text string + At Span +} + +func (x And) Span() Span { return x.At } +func (x Or) Span() Span { return x.At } +func (x Not) Span() Span { return x.At } +func (x Compare) Span() Span { return x.At } +func (x In) Span() Span { return x.At } +func (x Between) Span() Span { return x.At } +func (x Like) Span() Span { return x.At } +func (x IsNull) Span() Span { return x.At } +func (x Exists) Span() Span { return x.At } +func (x Call) Span() Span { return x.At } +func (x FreeText) Span() Span { return x.At } +func (x RawExpr) Span() Span { return x.At } + +type Field struct { + Scope string + Key string + Bracket bool + Single bool + Ref *FieldRef + At Span +} + +// FieldRef is populated by resolution; parsing leaves Ref nil. +type FieldRef struct { + Column string + Key string + Type panel.FieldType + Unit string + CompareAs string +} + +type ValueKind uint8 + +const ( + WordValue ValueKind = iota + StringValue + NumberValue + DurationValue + BooleanValue + VariableValue + StarValue +) + +type Value struct { + Kind ValueKind + Text string + Stored string + At Span +} + +type Stage struct { + Measures []Measure + Histogram *Field + By []Field + Bucket string + At Span +} +type Measure struct { + Expr MExpr + Alias string + At Span +} +type MExpr interface{ Span() Span } +type MCall struct { + Name string + Args []MArg + At Span +} +type MArg struct { + Field *Field + Number *float64 + Star bool + At Span +} +type MCountIf struct { + Filter Expr + At Span +} +type MBinary struct { + Op byte + L, R MExpr + At Span +} +type MNeg struct { + X MExpr + At Span +} +type MConst struct { + Value float64 + Text string + At Span +} + +func (x MCall) Span() Span { return x.At } +func (x MCountIf) Span() Span { return x.At } +func (x MBinary) Span() Span { return x.At } +func (x MNeg) Span() Span { return x.At } +func (x MConst) Span() Span { return x.At } + +type Sort struct { + Key string + Ascending bool + At Span +} +type Limit struct { + N int + At Span +} diff --git a/internal/fanql/parser.go b/internal/fanql/parser.go new file mode 100644 index 00000000..092dca6d --- /dev/null +++ b/internal/fanql/parser.go @@ -0,0 +1,1298 @@ +package fanql + +import ( + "regexp" + "sort" + "strconv" + "strings" + "unicode" + + "github.com/labstack/fanout/internal/panel" +) + +const ( + MaxTextRunes = 4000 + MaxTextBytes = 8192 + MaxTokens = 1024 + MaxNodes = 512 + MaxDepth = 16 + MaxListItems = 100 + MaxProblems = 20 +) + +var numberPattern = regexp.MustCompile(`^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?$`) +var durationPattern = regexp.MustCompile(`(?i)^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?(?:us|ms|s|m|h)$`) + +type parser struct { + tokens Tokens + runes []rune + i int + problems panel.Problems + bounded bool + nodes, depth int + heights map[any]int +} + +// A private sentinel unwinds only a bound failure, before further recursion or +// allocation. Other panics remain visible to callers and tests. +type parseBound struct{} + +// Parse returns no query whenever a problem is present. source is empty for a +// whole query, or the page-supplied source for a search-bar filter. +func Parse(text string, source string) (q *Query, problems panel.Problems) { + p := &parser{runes: []rune(text), bounded: true, heights: make(map[any]int)} + defer func() { + if v := recover(); v != nil { + if _, ok := v.(parseBound); !ok { + panic(v) + } + q = nil + } + problems = p.finish() + if len(problems) > 0 { + q = nil + } + }() + if len(p.runes) > MaxTextRunes || len(text) > MaxTextBytes { + p.bound(Span{0, len(p.runes)}, "textBound") + } + p.tokens = Lex(text) + if len(p.tokens)-1 > MaxTokens { + p.bound(p.tokens[MaxTokens].Span, "tokensBound") + } + q = p.query(source) + return q, nil +} + +// parseEntry is the unbounded internal entry parser used by the lift gate. +func parseEntry(text string) (Expr, panel.Problems) { + p := &parser{runes: []rune(text), tokens: Lex(text), heights: make(map[any]int)} + terms := p.filters(false) + for p.peek().Kind != EOF { + p.unexpected() + } + x := p.conjunction(terms) + problems := p.finish() + if len(problems) > 0 { + return nil, problems + } + return x, nil +} + +func (p *parser) peek() Token { return p.tokens[p.i] } +func (p *parser) ahead(n int) Token { return p.tokens[min(p.i+n, len(p.tokens)-1)] } +func (p *parser) take() Token { + t := p.peek() + if t.Kind != EOF { + p.i++ + } + return t +} +func (p *parser) lower() string { return strings.ToLower(p.peek().Text) } +func (p *parser) is(s string) bool { + t := p.peek() + return (t.Kind == Word || t.Kind == Ident || t.Kind == Punct) && strings.EqualFold(t.Text, s) +} +func (p *parser) eat(s string) bool { + if p.is(s) { + p.take() + return true + } + return false +} +func (p *parser) previousEnd() int { + if p.i == 0 { + return 0 + } + return p.tokens[p.i-1].Span.End +} +func (p *parser) text(at Span) string { return string(p.runes[at.Start:at.End]) } +func (p *parser) issue(at Span, message, hint string) { + p.problems = append(p.problems, panel.Problem{Path: "text", Message: message, Hint: hint, Span: &panel.TextSpan{Start: at.Start, End: at.End}}) +} +func (p *parser) report(at Span, code string, args ...any) { + p.issue(at, diagnostic(code, args...), hints[code]) +} +func (p *parser) bound(at Span, code string) { + p.problems = nil + p.report(at, code) + panic(parseBound{}) +} +func (p *parser) enter(at Span) { + if p.bounded && p.depth >= MaxDepth { + p.bound(at, "depthBound") + } + p.depth++ +} +func (p *parser) leave() { p.depth-- } +func (p *parser) node(x any, children ...any) { + p.nodes++ + if p.bounded && p.nodes > MaxNodes { + p.bound(x.(interface{ Span() Span }).Span(), "nodesBound") + } + height := 0 + for _, child := range children { + if child != nil { + height = max(height, p.heights[child]+1) + } + } + p.heights[x] = height + if p.bounded && height+p.depth > MaxDepth { + p.bound(x.(interface{ Span() Span }).Span(), "depthBound") + } +} +func (p *parser) finish() panel.Problems { + sort.SliceStable(p.problems, func(i, j int) bool { return p.problems[i].Span.Start < p.problems[j].Span.Start }) + if len(p.problems) > MaxProblems { + at := *p.problems[MaxProblems].Span + p.problems = p.problems[:MaxProblems] + p.issue(Span{at.Start, at.End}, diagnostic("more"), "") + } + return p.problems +} + +func (p *parser) query(source string) *Query { + q := &Query{Span: Span{0, len(p.runes)}} + if source != "" { + q.Source = strings.ToLower(source) + if !sources[q.Source] { + p.report(Span{}, "source", source) + } + if p.is("where") { + p.report(p.take().Span, "pageWhere") + } + q.Where = p.filters(false) + for p.peek().Kind != EOF { + p.report(p.peek().Span, "pageFilter") + p.skipRun() + } + return q + } + first := p.take() + q.Source = strings.ToLower(first.Text) + q.SourceSpan = first.Span + if first.Kind != Word || !sources[q.Source] { + switch q.Source { + case "from", "index", "source", "search": + p.report(first.Span, "from", q.Source) + default: + hint := hints["source"] + if q.Source == "traces" { + hint = hints["traces"] + } + p.issue(first.Span, diagnostic("source", first.Text), hint) + } + } + q.WhereWord = p.eat("where") + whereAt := p.i - 1 + q.Where = p.filters(false) + if q.WhereWord && len(q.Where) == 0 && len(p.problems) == 0 { + word := p.lower() + hint := "" + if clauses[word] { + hint = whereHint(word) + } + p.issue(p.tokens[whereAt].Span, diagnostic("whereEmpty"), hint) + } + for p.peek().Kind != EOF { + switch { + case p.is("|"): + pipe := p.take() + if p.is("=") || p.is("~") { + op := p.take() + p.report(Span{pipe.Span.Start, op.Span.End}, "pipeOp", "|"+op.Text) + p.skipRun() + continue + } + if p.is("sort") && strings.EqualFold(p.ahead(1).Text, "by") { + p.report(p.take().Span, "foreignStage", "sort") + p.skipStage() + continue + } + if q.Stage != nil { + if !p.is("sort") && !p.is("limit") { + p.report(pipe.Span, "secondStage") + p.skipStage() + continue + } + } else if !p.is("sort") && !p.is("limit") { + q.Stage = p.stage(pipe.Span.Start) + continue + } + case p.is("where"): + p.report(p.take().Span, "whereTwice") + q.Where = append(q.Where, p.filters(false)...) + case p.is("sort"): + if q.Limit != nil { + p.report(p.peek().Span, "limitBeforeSort") + } + if q.Sort != nil { + p.report(p.peek().Span, "duplicate", "sort") + } + q.Sort = p.parseSort() + case p.is("limit"): + if q.Limit != nil { + p.report(p.peek().Span, "duplicate", "limit") + } + q.Limit = p.parseLimit() + case p.is("by"), p.is("every"): + if q.Stage == nil { + code := "byFirst" + if p.is("every") { + code = "everyFirst" + } + p.report(p.take().Span, code) + p.skipRun() + } else { + p.report(p.take().Span, "order", p.tokens[p.i-1].Text) + p.skipRun() + } + default: + p.unexpected() + } + } + return q +} + +func (p *parser) filterStop(nested bool) bool { + t := p.peek() + return t.Kind == EOF || p.is(")") || p.is("|") || (!nested && t.Kind == Word && clauses[p.lower()]) +} + +// filters keeps conjunction entries separate. Only an explicit group or an OR +// chain creates a single entry around multiple terms. +func (p *parser) filters(nested bool) []Expr { + var terms []Expr + var ops []string + mode := "" + mixed := -1 + for !p.filterStop(nested) { + before := p.i + if len(terms) > 0 { + op := "and" + if p.is("and") || p.is("or") { + tok := p.take() + op = strings.ToLower(tok.Text) + if p.filterStop(nested) { + p.report(tok.Span, "sides", op) + break + } + } + if mode == "" { + mode = op + } else if mode != op && mixed < 0 { + mixed = len(ops) + } + ops = append(ops, op) + } else if p.is("and") || p.is("or") { + p.report(p.take().Span, "sides", p.tokens[p.i-1].Text) + continue + } + x := p.term(nested) + if x != nil { + terms = append(terms, x) + } else if len(ops) >= len(terms) && len(ops) > 0 { + ops = ops[:len(ops)-1] + } + if p.i == before { + p.unexpected() + } + } + if mixed >= 0 && len(terms) >= 3 && len(ops) == len(terms)-1 { + at := Span{terms[0].Span().Start, terms[len(terms)-1].Span().End} + first := p.groupingEdit(terms, ops, ops[mixed]) + second := p.groupingEdit(terms, ops, ops[0]) + p.issue(at, diagnostic("mixed"), groupingHint(first, second)) + span := panel.TextSpan{Start: at.Start, End: at.End} + p.problems[len(p.problems)-1].FixIts = []panel.FixIt{{Label: first, Span: span, Text: first}, {Label: second, Span: span, Text: second}} + } + if mode == "or" && len(terms) > 1 { + x := &Or{Terms: terms, At: Span{terms[0].Span().Start, terms[len(terms)-1].Span().End}} + p.node(x) + return []Expr{x} + } + return terms +} + +func (p *parser) conjunction(terms []Expr) Expr { + if len(terms) == 0 { + return nil + } + if len(terms) == 1 { + return terms[0] + } + x := &And{Terms: terms, At: Span{terms[0].Span().Start, terms[len(terms)-1].Span().End}} + p.node(x) + return x +} + +// Each alternative gives one operator kind priority explicitly, grouping every +// run of that kind. Both edits are valid even when a longer list mixes repeatedly. +func (p *parser) groupingEdit(terms []Expr, ops []string, grouped string) string { + var out strings.Builder + for i := 0; i < len(terms); { + j := i + for j < len(ops) && ops[j] == grouped { + j++ + } + if j > i { + out.WriteByte('(') + } + out.WriteString(p.text(Span{terms[i].Span().Start, terms[j].Span().End})) + if j > i { + out.WriteByte(')') + } + if j+1 < len(terms) { + out.WriteString(p.text(Span{terms[j].Span().End, terms[j+1].Span().Start})) + } + i = j + 1 + } + return out.String() +} + +func setExprSpan(x Expr, at Span) { + switch x := x.(type) { + case *And: + x.At = at + case *Or: + x.At = at + case *Not: + x.At = at + case *Compare: + x.At = at + case *In: + x.At = at + case *Between: + x.At = at + case *Like: + x.At = at + case *IsNull: + x.At = at + case *Exists: + x.At = at + case *Call: + x.At = at + case *FreeText: + x.At = at + case *RawExpr: + x.At = at + } +} + +func setMeasureSpan(x MExpr, at Span) { + switch x := x.(type) { + case *MCall: + x.At = at + case *MCountIf: + x.At = at + case *MBinary: + x.At = at + case *MNeg: + x.At = at + case *MConst: + x.At = at + } +} + +func isFieldWordOperator(op string) bool { + switch op { + case "in", "between", "like", "ilike": + return true + } + return false +} + +func (p *parser) term(nested bool) Expr { + if p.is("-") || p.is("not") { + t := p.take() + p.enter(t.Span) + x := p.term(nested) + p.leave() + if x == nil { + return nil + } + n := &Not{X: x, At: Span{t.Span.Start, x.Span().End}} + p.node(n, x) + return n + } + return p.primary(nested) +} + +func (p *parser) primary(nested bool) Expr { + t := p.peek() + if p.eat("(") { + p.enter(t.Span) + terms := p.filters(true) + p.leave() + closed := p.eat(")") + if !closed { + p.report(t.Span, "unclosedGroup") + } + x := p.conjunction(terms) + if x != nil && closed { + setExprSpan(x, Span{t.Span.Start, p.previousEnd()}) + } + return x + } + if t.Kind == Raw { + p.take() + p.checkQuoted(t) + x := &RawExpr{Text: t.Text, At: t.Span} + p.node(x) + return x + } + if t.Kind == String { + p.take() + p.checkQuoted(t) + v := Value{Kind: StringValue, Text: t.Text, At: t.Span} + x := &FreeText{Value: v, At: t.Span} + p.node(x) + return x + } + if t.Kind == Bad { + p.badTerm() + return nil + } + if t.Kind != Word { + if t.Kind != EOF { + p.unexpected() + } else { + p.report(t.Span, "sides", "not") + } + return nil + } + word := strings.ToLower(t.Text) + if p.foreignTerm() { + return nil + } + if reserved[word] { + p.report(t.Span, "reserved", word) + p.take() + return nil + } + if p.ahead(1).Text == "(" { + return p.call() + } + field, ok := p.field() + if !ok { + p.skipRun() + return nil + } + op := p.lower() + if isComparison(op) || op == ":" || op == "~" || op == "!~" { + if numberPattern.MatchString(field.Key) || durationPattern.MatchString(field.Key) { + p.report(field.At, "fieldBefore", op) + p.skipRun() + return nil + } + oper := p.take() + if (op == "=" && (p.is("=") || p.is("~"))) || op == ":" && p.is(":") { + code := "eqeq" + if p.is("~") { + code = "regex" + } + if op == ":" { + code = "cast" + } + end := p.take().Span.End + p.report(Span{oper.Span.Start, end}, code) + p.skipRun() + return nil + } + if op == ":" && isComparison(p.lower()) { + op = p.take().Text + } + v, valid := p.value() + if !valid { + example := "api" + if field.Key == "duration" { + example = "500ms" + } + p.report(Span{field.At.Start, oper.Span.End}, "value", field.Key, op, field.Key, op, example) + p.skipRun() + return nil + } + at := Span{field.At.Start, v.At.End} + if p.is(":") { + p.colonProblem(field, v, at) + return nil + } + if p.peek().Text == "*" && p.peek().Span.Start == v.At.End { + p.wildcard(v) + return nil + } + if op == ":" && v.Kind == StarValue { + x := &Exists{Field: field, At: at} + p.node(x) + return x + } + if v.Kind == StarValue { + p.issue(at, diagnostic("wildcard"), wildcardHint(v.Text)) + return nil + } + x := &Compare{Field: field, Op: op, Value: v, At: at} + p.node(x) + return x + } + neg := false + if expressionWords[op] && op == "not" && isFieldWordOperator(strings.ToLower(p.ahead(1).Text)) { + neg = true + p.take() + op = p.lower() + } + switch op { + case "in": + return p.in(field, neg) + case "between": + p.take() + lo, ok := p.value() + if !ok || !p.eat("and") { + p.report(Span{field.At.Start, p.previousEnd()}, "between") + return nil + } + hi, ok := p.value() + if !ok { + p.report(Span{field.At.Start, p.previousEnd()}, "between") + return nil + } + x := &Between{Field: field, Lo: lo, Hi: hi, Negated: neg, At: Span{field.At.Start, hi.At.End}} + p.node(x) + return x + case "is": + p.take() + neg = p.eat("not") + if !p.eat("null") { + p.report(Span{field.At.Start, p.previousEnd()}, "null") + return nil + } + x := &IsNull{Field: field, Negated: neg, At: Span{field.At.Start, p.previousEnd()}} + p.node(x) + return x + case "like", "ilike": + p.take() + v, ok := p.value() + if !ok || v.Kind != StringValue { + p.report(Span{field.At.Start, p.previousEnd()}, "like") + return nil + } + x := &Like{Field: field, Pattern: v, Insensitive: op == "ilike", Negated: neg, At: Span{field.At.Start, v.At.End}} + p.node(x) + return x + } + if neg { + p.report(p.tokens[p.i-1].Span, "unexpected", "not") + return nil + } + if !nested && clauses[word] { + p.report(t.Span, "unexpected", t.Text) + return nil + } + if p.peek().Text == "*" && p.peek().Span.Start == field.At.End { + p.wildcard(Value{Text: t.Text, At: t.Span}) + return nil + } + x := &FreeText{Value: Value{Kind: WordValue, Text: p.text(field.At), At: field.At}, At: field.At} + p.node(x) + return x +} + +func isComparison(s string) bool { + switch s { + case "=", "!=", "<>", ">", ">=", "<", "<=": + return true + } + return false +} + +func (p *parser) field() (Field, bool) { + t := p.peek() + if t.Kind != Word && t.Kind != Ident && t.Kind != Path { + p.report(t.Span, "field") + return Field{}, false + } + p.take() + f := Field{Key: t.Text, Single: !strings.Contains(t.Text, "."), At: t.Span} + if p.is("[") && (strings.EqualFold(t.Text, "attributes") || strings.EqualFold(t.Text, "resource")) { + p.take() + key := p.peek() + if key.Kind != BracketKey && key.Kind != String { + p.report(key.Span, "bracket") + return f, false + } + p.take() + p.checkQuoted(key) + f.Scope = strings.ToLower(t.Text) + f.Key = key.Text + f.Bracket = true + f.Single = false + f.At.End = key.Span.End + if !p.eat("]") { + p.report(key.Span, "bracket") + return f, false + } + f.At.End = p.previousEnd() + } else if prefix, key, ok := strings.Cut(t.Text, "."); ok && (strings.EqualFold(prefix, "attributes") || strings.EqualFold(prefix, "resource")) { + f.Scope = strings.ToLower(prefix) + f.Key = key + } + return f, true +} + +func classify(t Token) Value { + v := Value{Text: t.Text, At: t.Span} + switch { + case t.Kind == String || t.Kind == BracketKey: + v.Kind = StringValue + case strings.HasPrefix(t.Text, "$"): + v.Kind = VariableValue + case t.Text == "*": + v.Kind = StarValue + case durationPattern.MatchString(t.Text): + v.Kind = DurationValue + case numberPattern.MatchString(t.Text): + v.Kind = NumberValue + case strings.EqualFold(t.Text, "true") || strings.EqualFold(t.Text, "false"): + v.Kind = BooleanValue + default: + v.Kind = WordValue + } + return v +} + +func (p *parser) value() (Value, bool) { + for p.is("+") { + p.report(p.take().Span, "plus") + } + t := p.peek() + if p.is("-") { + next := p.ahead(1) + v := classify(next) + if (next.Kind == Word || next.Kind == Number) && (v.Kind == NumberValue || v.Kind == DurationValue) && !strings.HasPrefix(next.Text, "-") { + p.take() + p.take() + v.Text = "-" + v.Text + v.At.Start = t.Span.Start + return v, true + } + return Value{}, false + } + if t.Kind != Word && t.Kind != String && t.Kind != Number && !(t.Kind == Punct && t.Text == "*") { + return Value{}, false + } + p.take() + p.checkQuoted(t) + v := classify(t) + if v.Kind == VariableValue && strings.HasPrefix(v.Text, "$__") { + p.report(v.At, "variable") + } + return v, true +} + +func (p *parser) in(f Field, neg bool) Expr { + p.take() + x := &In{Field: f, Negated: neg, At: Span{f.At.Start, p.previousEnd()}} + if p.peek().Kind == Word && strings.HasPrefix(p.peek().Text, "$") { + v, _ := p.value() + x.Variable = strings.TrimPrefix(v.Text, "$") + x.At.End = v.At.End + p.node(x) + return x + } + if !p.eat("(") { + p.report(p.peek().Span, "list") + return nil + } + for p.peek().Kind != EOF && !p.is(")") { + v, ok := p.value() + if !ok { + p.report(p.peek().Span, "listValue") + p.skipRun() + break + } + if p.bounded && len(x.Values) >= MaxListItems { + p.bound(v.At, "listBound") + } + x.Values = append(x.Values, v) + if v.Kind == StarValue { + p.issue(v.At, diagnostic("wildcard"), wildcardHint(v.Text)) + } + if !p.eat(",") { + break + } + if p.is(")") { + p.report(p.peek().Span, "listValue") + } + } + if len(x.Values) == 0 { + p.report(p.peek().Span, "listValue") + } + if !p.eat(")") { + p.report(p.peek().Span, "list") + } + x.At.End = p.previousEnd() + p.node(x) + return x +} + +func (p *parser) call() *Call { + t := p.take() + x := &Call{Name: strings.ToLower(t.Text), At: t.Span} + open := p.take() + if open.Span.Start != t.Span.End { + p.report(Span{t.Span.Start, open.Span.End}, "callSpace", x.Name) + } + p.enter(open.Span) + for p.peek().Kind != EOF && !p.is(")") && !p.is("|") { + before := p.i + arg := CallArg{} + switch t := p.peek(); { + case t.Kind == Word && p.ahead(1).Text == "(": + arg.Call = p.call() + case t.Kind == String || t.Kind == Number || t.Kind == Word && numberPattern.MatchString(t.Text) || p.is("-"): + v, ok := p.value() + if ok { + arg.Value = &v + } else { + p.report(t.Span, "callArg", x.Name) + p.take() + } + case t.Kind == Word: + f, ok := p.field() + if ok { + arg.Field = &f + } + default: + p.report(t.Span, "callArg", x.Name) + p.take() + } + x.Args = append(x.Args, arg) + if p.i == before { + p.take() + } + if !p.eat(",") { + break + } + } + if !p.eat(")") { + p.report(open.Span, "callClose") + } + p.leave() + if isComparison(p.lower()) { + op := p.take() + v, ok := p.value() + if ok { + x.Cmp = &Comparison{Op: op.Text, Value: v} + } else { + p.report(op.Span, "value", x.Name, op.Text, x.Name, op.Text, "1000") + } + } + x.At.End = p.previousEnd() + var children []any + for _, a := range x.Args { + if a.Call != nil { + children = append(children, a.Call) + } + } + p.node(x, children...) + return x +} + +func (p *parser) checkQuoted(t Token) { + if !t.Unclosed { + return + } + if t.Kind == Raw { + p.report(t.Span, "raw") + } else { + p.report(t.Span, "quote", t.Quote) + } +} + +func (p *parser) colonProblem(f Field, v Value, at Span) { + run := p.runSpan(at.Start) + value := p.text(Span{v.At.Start, run.End}) + prefix := p.text(Span{f.At.Start, v.At.Start}) + after := v.Text + if strings.HasPrefix(value, "//") { + value = p.text(run) + prefix = "" + after = f.Key + } + p.issue(run, diagnostic("colon", after), quoteValueHint(prefix, value)) + p.skipRun() +} + +func (p *parser) wildcard(v Value) { + at := p.runSpan(v.At.Start) + p.issue(at, diagnostic("wildcard"), wildcardHint(p.text(at))) + p.skipRun() +} + +func (p *parser) runSpan(start int) Span { + end := start + for end < len(p.runes) && !unicode.IsSpace(p.runes[end]) { + end++ + } + return Span{start, end} +} + +// Recovery skips a malformed run, respecting delimiters and whitespace at the +// term's depth. Clause words and pipes remain available to the outer parser. +func (p *parser) skipRun() { + if p.peek().Kind == EOF { + return + } + first := p.take() + end := first.Span.End + depth := 0 + if first.Kind == Punct && first.Text == "(" { + depth = 1 + } + for p.peek().Kind != EOF { + t := p.peek() + if depth == 0 && (t.Span.Start > end || p.is("|") || p.is(")")) { + break + } + if p.is("(") { + depth++ + } + if p.is(")") { + depth-- + } + end = p.take().Span.End + } +} + +func (p *parser) badTerm() { + t := p.take() + switch t.Text { + case "{": + p.report(t.Span, "selector") + case "@": + word := p.peek() + p.report(Span{t.Span.Start, word.Span.End}, "at", "@"+word.Text, word.Text) + case "!": + at := p.runSpan(t.Span.Start) + p.report(at, "bang", strings.TrimPrefix(p.text(at), "!")) + default: + p.issue(t.Span, t.Message, t.Hint) + } + if p.peek().Span.Start == t.Span.End { + p.skipRun() + } +} + +func (p *parser) foreignTerm() bool { + t := p.peek() + word := p.lower() + if word == "since" || word == "until" { + p.report(t.Span, "time", word) + p.take() + if p.peek().Kind == Word { + p.take() + } + return true + } + if (word == "ago" || word == "now") && p.ahead(1).Text == "(" { + p.report(t.Span, "timeCall", word) + p.skipRun() + return true + } + if word == "earliest" && p.ahead(1).Text == "=" || word == "_time" && p.ahead(1).Text == ":" { + p.report(t.Span, "time", word) + p.skipRun() + return true + } + if word == "facet" || (word == "order" || word == "group") && strings.EqualFold(p.ahead(1).Text, "by") { + p.report(t.Span, "foreignClause", word) + p.skipRun() + if p.is("by") { + p.take() + } + return true + } + return false +} + +func (p *parser) unexpected() { + t := p.peek() + if t.Kind == Bad { + p.badTerm() + return + } + if p.eat(")") { + p.report(t.Span, "unmatched") + return + } + if isComparison(t.Text) || t.Text == ":" || t.Text == "~" || t.Text == "!~" { + p.report(t.Span, "fieldBefore", t.Text) + p.skipRun() + return + } + if p.eat("+") { + p.report(t.Span, "plus") + return + } + if p.is("*") { + p.wildcard(Value{Text: t.Text, At: t.Span}) + return + } + if !p.foreignTerm() { + p.report(t.Span, "unexpected", t.Text) + p.take() + } +} + +func (p *parser) skipStage() { + for p.peek().Kind != EOF && !p.is("sort") && !p.is("limit") && !p.is("|") { + p.take() + } +} + +func (p *parser) parseSort() *Sort { + start := p.take() + x := &Sort{At: start.Span} + signed := p.is("+") || p.is("-") + if signed { + x.Ascending = p.take().Text == "+" + } + t := p.peek() + if t.Kind != Word && t.Kind != Ident { + p.report(t.Span, "sortKey") + return x + } + x.Key = strings.ToLower(p.take().Text) + if p.is("asc") || p.is("desc") { + if signed { + p.report(p.peek().Span, "direction") + } + x.Ascending = !strings.EqualFold(p.take().Text, "desc") + } + x.At.End = p.previousEnd() + return x +} + +func (p *parser) parseLimit() *Limit { + start := p.take() + t := p.peek() + x := &Limit{At: start.Span} + n, err := strconv.Atoi(t.Text) + if t.Kind != Word || err != nil || n < 1 || n > 1000 || strings.IndexFunc(t.Text, func(r rune) bool { return !digit(r) }) >= 0 { + p.report(t.Span, "limit") + if t.Kind != EOF { + p.take() + } + } else { + x.N = n + p.take() + } + x.At.End = p.previousEnd() + return x +} + +func (p *parser) stage(start int) *Stage { + s := &Stage{At: Span{Start: start}} + for p.peek().Kind != EOF && !p.is("|") && !clauses[p.lower()] { + before := p.i + if p.peek().Kind == Ident && foreignStages[p.lower()] { + t := p.take() + p.report(t.Span, "foreignStage", strings.ToLower(t.Text)) + for p.peek().Kind != EOF && !p.is("|") && !p.is(",") && !clauses[p.lower()] && !foreignStages[p.lower()] && p.ahead(1).Text != "(" { + p.take() + } + continue + } + if p.peek().Kind == Ident && foreignCalls[p.lower()] && p.ahead(1).Text == "(" { + p.report(p.peek().Span, "foreignCall", p.lower()) + p.skipRun() + continue + } + expr := p.mexpr(0) + if expr != nil { + m := Measure{Expr: expr, At: expr.Span()} + if modifiers[p.lower()] && p.eat("as") { + t := p.peek() + if t.Kind == Ident { + m.Alias = p.take().Text + m.At.End = t.Span.End + } else { + p.report(t.Span, "alias") + } + } + leaves, share, distribution := measureLeaves(expr) + if leaves == 0 { + p.report(expr.Span(), "aggregate") + } + _, call := expr.(*MCall) + _, countIf := expr.(*MCountIf) + if distribution && !call { + p.report(expr.Span(), "histogram") + } + if !call && !countIf { + if m.Alias == "" { + p.report(expr.Span(), "measureName") + } + if share { + p.report(expr.Span(), "share") + } + } + if call, ok := expr.(*MCall); ok && call.Name == "histogram" { + if s.Histogram != nil || len(s.Measures) > 0 { + p.report(call.At, "histogram") + } + if m.Alias != "" { + p.report(m.At, "histogramAlias") + } + if len(call.Args) != 1 || call.Args[0].Field == nil { + p.report(call.At, "histogramField") + } else { + s.Histogram = call.Args[0].Field + } + } else { + if s.Histogram != nil { + p.report(m.At, "histogram") + } + s.Measures = append(s.Measures, m) + } + } + if p.eat(",") { + if p.peek().Kind == EOF || clauses[p.lower()] { + p.report(p.peek().Span, "measure") + } + continue + } + if expr != nil && p.peek().Kind != EOF && !p.is("|") && !clauses[p.lower()] { + p.report(p.peek().Span, "measureComma") + } + if p.i == before { + p.unexpected() + } + } + for p.is("by") || p.is("every") { + if p.eat("by") { + if len(s.By) > 0 { + p.report(p.tokens[p.i-1].Span, "duplicate", "by") + } + if s.Bucket != "" { + p.report(p.tokens[p.i-1].Span, "order", "by") + } + if len(s.Measures) == 0 && s.Histogram == nil { + p.report(p.tokens[p.i-1].Span, "byFirst") + } + for { + f, ok := p.field() + if !ok { + if p.peek().Kind != EOF && !clauses[p.lower()] { + p.take() + } + break + } + s.By = append(s.By, f) + if len(s.By) == 4 { + p.report(f.At, "byMax") + } + if s.Histogram != nil && len(s.By) == 2 { + p.report(f.At, "histogramBy") + } + if !p.eat(",") { + break + } + } + } else { + at := p.take().Span + if len(s.Measures) == 0 && s.Histogram == nil { + p.report(at, "everyFirst") + } + if s.Bucket != "" { + p.report(at, "duplicate", "every") + } + t := p.peek() + s.Bucket = strings.ToLower(t.Text) + if !buckets[s.Bucket] { + p.report(t.Span, "bucket", t.Text) + } + if t.Kind != EOF { + p.take() + } + } + } + if len(s.Measures) == 0 && s.Histogram == nil && len(p.problems) == 0 { + p.report(p.peek().Span, "measure") + } + s.At.End = p.previousEnd() + return s +} + +func measurePrecedence(t Token) int { + if t.Kind != Punct { + return -1 + } + switch t.Text { + case "+", "-": + return 1 + case "*", "/": + return 2 + } + return -1 +} + +func (p *parser) canMFactor() bool { + t := p.peek() + return t.Kind == Number || t.Kind == Ident && t.Text != "as" || p.is("(") || p.is("-") +} + +func (p *parser) mexpr(minPrec int) MExpr { + left := p.mfactor() + if left == nil { + return nil + } + for prec := measurePrecedence(p.peek()); prec >= minPrec; prec = measurePrecedence(p.peek()) { + op := p.take() + if !p.canMFactor() { + p.report(op.Span, "measureSides", op.Text) + return left + } + right := p.mexpr(prec + 1) + if right == nil { + return left + } + x := &MBinary{Op: op.Text[0], L: left, R: right, At: Span{left.Span().Start, right.Span().End}} + p.node(x, left, right) + left = x + } + return left +} + +func (p *parser) mfactor() MExpr { + t := p.peek() + if p.eat("-") { + p.enter(t.Span) + x := p.mfactor() + p.leave() + if x == nil { + return nil + } + n := &MNeg{X: x, At: Span{t.Span.Start, x.Span().End}} + p.node(n, x) + return n + } + if p.eat("(") { + p.enter(t.Span) + x := p.mexpr(0) + p.leave() + if !p.eat(")") { + p.report(t.Span, "unclosedGroup") + } else if x != nil { + setMeasureSpan(x, Span{t.Span.Start, p.previousEnd()}) + } + return x + } + if t.Kind == Number { + p.take() + v, err := strconv.ParseFloat(t.Text, 64) + if err != nil { + p.report(t.Span, "measure") + return nil + } + x := &MConst{Value: v, Text: t.Text, At: t.Span} + p.node(x) + return x + } + if t.Kind == Ident && p.ahead(1).Text == "(" { + return p.mcall() + } + if t.Kind == Bad { + p.badTerm() + return nil + } + p.report(t.Span, "measure") + if t.Kind != EOF { + p.take() + } + return nil +} + +func (p *parser) mcall() MExpr { + name := p.take() + open := p.take() + at := Span{Start: name.Span.Start} + p.enter(open.Span) + if strings.EqualFold(name.Text, "count_if") { + filter := p.conjunction(p.filters(true)) + if filter == nil { + p.report(open.Span, "sides", "count_if") + } + if !p.eat(")") { + p.report(open.Span, "callClose") + } + p.leave() + at.End = p.previousEnd() + x := &MCountIf{Filter: filter, At: at} + p.node(x, filter) + return x + } + x := &MCall{Name: strings.ToLower(name.Text), At: at} + for p.peek().Kind != EOF && !p.is(")") && !p.is("|") { + t := p.peek() + arg := MArg{At: t.Span} + switch { + case p.eat("*"): + arg.Star = true + case t.Kind == Number || p.is("-"): + v, ok := p.value() + if !ok || v.Kind != NumberValue { + p.report(t.Span, "measureArg") + p.take() + } else { + n, err := strconv.ParseFloat(v.Text, 64) + if err != nil { + p.report(v.At, "measureArg") + } else { + arg.Number = &n + } + arg.At = v.At + } + case t.Kind == Ident || t.Kind == Path: + f, ok := p.field() + if ok { + arg.Field = &f + arg.At = f.At + } + default: + p.report(t.Span, "measureArg") + p.take() + } + x.Args = append(x.Args, arg) + if !p.eat(",") { + break + } + } + if !p.eat(")") { + p.report(open.Span, "callClose") + } + p.leave() + x.At.End = p.previousEnd() + for _, arg := range x.Args { + if arg.Star && (x.Name != "count" || len(x.Args) != 1) { + p.report(arg.At, "starArg") + } + } + p.node(x) + return x +} + +func measureLeaves(x MExpr) (int, bool, bool) { + switch x := x.(type) { + case *MCall: + return 1, x.Name == "share", x.Name == "histogram" + case *MCountIf: + return 1, false, false + case *MBinary: + l, ls, lh := measureLeaves(x.L) + r, rs, rh := measureLeaves(x.R) + return l + r, ls || rs, lh || rh + case *MNeg: + return measureLeaves(x.X) + } + return 0, false, false +} diff --git a/internal/fanql/parser_test.go b/internal/fanql/parser_test.go new file mode 100644 index 00000000..8965249b --- /dev/null +++ b/internal/fanql/parser_test.go @@ -0,0 +1,536 @@ +package fanql + +import ( + "fmt" + "reflect" + "strings" + "testing" + + "github.com/labstack/fanout/internal/panel" +) + +func mustParse(t *testing.T, text string) *Query { + t.Helper() + q, ps := Parse(text, "") + if len(ps) != 0 || q == nil { + t.Fatalf("Parse(%q): %#v", text, ps) + } + return q +} + +func wantProblem(t *testing.T, text, source, message, hint string) panel.Problems { + t.Helper() + q, ps := Parse(text, source) + if q != nil || len(ps) == 0 { + t.Fatalf("Parse(%q) = %#v, %#v; want problem %q", text, q, ps, message) + } + for _, p := range ps { + if p.Message == message { + if p.Path != "text" || p.Span == nil || (hint != "" && p.Hint != hint) { + t.Fatalf("Parse(%q): %#v", text, p) + } + return ps + } + } + t.Fatalf("Parse(%q): %#v; want %q", text, ps, message) + return nil +} + +func TestParseEntriesAndGrouping(t *testing.T) { + q := mustParse(t, "spans where a:1 b:2 (c:3 or d:4) (e:5 f:6)") + if len(q.Where) != 4 { + t.Fatal(q) + } + if _, ok := q.Where[0].(*Compare); !ok { + t.Fatal(q.Where) + } + if _, ok := q.Where[1].(*Compare); !ok { + t.Fatal(q.Where) + } + if x, ok := q.Where[2].(*Or); !ok || len(x.Terms) != 2 { + t.Fatal(q.Where) + } + if x, ok := q.Where[3].(*And); !ok || len(x.Terms) != 2 { + t.Fatal(q.Where) + } + q = mustParse(t, "spans where a:1 or b:2") + if len(q.Where) != 1 { + t.Fatal(q) + } + if _, ok := q.Where[0].(*Or); !ok { + t.Fatal(q) + } + q = mustParse(t, "spans where (a:1)") + if len(q.Where) != 1 { + t.Fatal(q) + } + if _, ok := q.Where[0].(*Compare); !ok { + t.Fatal(q) + } + q = mustParse(t, "spans status:error | count()") + if q.WhereWord || len(q.Where) != 1 { + t.Fatal(q) + } +} + +func TestParseMixedAndOrIsRejectedWithFixIts(t *testing.T) { + for _, tc := range []struct{ text, body, a, b string }{ + {"spans where a:1 b:2 or c:3", "a:1 b:2 or c:3", "a:1 (b:2 or c:3)", "(a:1 b:2) or c:3"}, + {"spans where a:1 and b:2 or c:3", "a:1 and b:2 or c:3", "a:1 and (b:2 or c:3)", "(a:1 and b:2) or c:3"}, + {"spans where a:1 or b:2 c:3", "a:1 or b:2 c:3", "a:1 or (b:2 c:3)", "(a:1 or b:2) c:3"}, + {"spans where (a:1 b:2 or c:3)", "a:1 b:2 or c:3", "a:1 (b:2 or c:3)", "(a:1 b:2) or c:3"}, + {"spans | count_if(a:1 b:2 or c:3) as x", "a:1 b:2 or c:3", "a:1 (b:2 or c:3)", "(a:1 b:2) or c:3"}, + } { + t.Run(tc.text, func(t *testing.T) { + ps := wantProblem(t, tc.text, "", "mixed and/or needs parentheses", "write "+tc.a+" or "+tc.b) + p := ps[0] + start := strings.Index(tc.text, tc.body) + span := panel.TextSpan{Start: start, End: start + len(tc.body)} + if *p.Span != span || len(p.FixIts) != 2 || p.FixIts[0].Span != span || p.FixIts[1].Span != span || p.FixIts[0].Text != tc.a || p.FixIts[1].Text != tc.b { + t.Fatal(p) + } + }) + } +} + +func TestParseNegationNesting(t *testing.T) { + for _, input := range []string{"logs where --severity:error", "logs where not not a:1", "logs where -not a:1"} { + q := mustParse(t, input) + outer, ok := q.Where[0].(*Not) + if !ok { + t.Fatal(q) + } + inner, ok := outer.X.(*Not) + if !ok { + t.Fatal(outer) + } + if _, ok := inner.X.(*Compare); !ok { + t.Fatal(inner) + } + } + q := mustParse(t, "spans where -(a:1 or b:2)") + n, ok := q.Where[0].(*Not) + if !ok || len(q.Where) != 1 { + t.Fatal(q) + } + if _, ok := n.X.(*Or); !ok { + t.Fatal(n) + } + q = mustParse(t, "spans where not a:1 b:2") + if len(q.Where) != 2 { + t.Fatal(q) + } + if _, ok := q.Where[0].(*Not); !ok { + t.Fatal(q) + } +} + +func TestParseValueClassification(t *testing.T) { + for _, tc := range []struct { + input, text string + kind ValueKind + }{{"k:500", "500", NumberValue}, {"k:1.5s", "1.5s", DurationValue}, {"k:true", "true", BooleanValue}, {"k:$v", "$v", VariableValue}, {`k:"500"`, "500", StringValue}, {"value>-3", "-3", NumberValue}, {"k:api", "api", WordValue}, {`start_time>"2026-10-29T10:00:00Z"`, "2026-10-29T10:00:00Z", StringValue}} { + x := mustParse(t, "spans where "+tc.input).Where[0].(*Compare) + if x.Value.Kind != tc.kind || x.Value.Text != tc.text { + t.Fatal(x) + } + } + if _, ok := mustParse(t, "spans where k:*").Where[0].(*Exists); !ok { + t.Fatal("expected exists") + } + wantProblem(t, "spans where k:-foo", "", "k: needs a value; e.g. k:api", "") +} + +func TestParseColonEndsWord(t *testing.T) { + ps := wantProblem(t, "spans where http.target:/a:b", "", "unexpected : after /a", `quote the value: http.target:"/a:b"`) + if *ps[0].Span != (panel.TextSpan{Start: 12, End: 28}) { + t.Fatal(ps) + } + wantProblem(t, "logs where http://x:8080/y", "", "unexpected : after http", `quote the value: "http://x:8080/y"`) +} + +func TestParseFieldVsFreeText(t *testing.T) { + for _, s := range []string{"service", "in", `"limit"`, "stats"} { + if _, ok := mustParse(t, "logs where "+s).Where[0].(*FreeText); !ok { + t.Fatal(s) + } + } + for _, s := range []string{"where", "join"} { + x := mustParse(t, "logs where service:"+s).Where[0].(*Compare) + if x.Value.Kind != WordValue || x.Value.Text != s { + t.Fatal(x) + } + } + x := mustParse(t, "logs where service in (sort, limit)").Where[0].(*In) + if len(x.Values) != 2 || x.Values[0].Text != "sort" || x.Values[1].Text != "limit" { + t.Fatal(x) + } + wantProblem(t, "logs where limit 10", "", "where needs a filter", `quote "limit" to search for the word, or drop where`) +} + +func TestParseOperatorsAfterField(t *testing.T) { + for _, op := range []string{"in", "not in", "between", "not between", "is null", "is not null", "like", "ilike", "not like", "not ilike"} { + input := "k " + op + switch { + case strings.HasSuffix(op, "in"): + input += " (a, b)" + case strings.HasSuffix(op, "between"): + input += " 1 and 2" + case strings.Contains(op, "like"): + input += ` "a%"` + } + x := mustParse(t, "spans where "+input).Where[0] + neg := strings.Contains(op, "not") + switch x := x.(type) { + case *In: + if x.Negated != neg || len(x.Values) != 2 { + t.Fatal(x) + } + case *Between: + if x.Negated != neg || x.Lo.Text != "1" || x.Hi.Text != "2" { + t.Fatal(x) + } + case *IsNull: + if x.Negated != neg { + t.Fatal(x) + } + case *Like: + if x.Negated != neg || x.Insensitive != strings.Contains(op, "ilike") || x.Pattern.Text != "a%" { + t.Fatal(x) + } + default: + t.Fatalf("%s: %T", op, x) + } + } + if mustParse(t, "spans where k:>5").Where[0].(*Compare).Op != ">" { + t.Fatal("colon comparison") + } + wantProblem(t, "spans where k like a%", "", "like needs a quoted pattern", "") + wantProblem(t, "spans where duration between 1s", "", "between needs two values", "") + x := mustParse(t, "spans where service in $svcs").Where[0].(*In) + if x.Variable != "svcs" { + t.Fatal(x) + } +} + +func TestParseCalls(t *testing.T) { + x := mustParse(t, `spans where starts_with(http_route, "/api")`).Where[0].(*Call) + if x.Name != "starts_with" || len(x.Args) != 2 || x.Args[0].Field == nil || x.Args[0].Field.Key != "http_route" || x.Args[1].Value == nil || x.Args[1].Value.Text != "/api" { + t.Fatal(x) + } + x = mustParse(t, "logs where length(body) > 1000").Where[0].(*Call) + if x.Cmp == nil || x.Cmp.Op != ">" || x.Cmp.Value.Text != "1000" { + t.Fatal(x) + } + wantProblem(t, `logs where starts_with (x, "y")`, "", "write starts_with(...) without a space", "") + x = mustParse(t, "spans where P95(Duration)").Where[0].(*Call) + if x.Name != "p95" { + t.Fatal(x) + } +} + +func TestParseStageMeasuresAndArithmetic(t *testing.T) { + q := mustParse(t, "spans | count_if(status:error) / count() * 100 as err_pct by http_route every 1m sort err_pct limit 10") + m := q.Stage.Measures[0] + mul, ok := m.Expr.(*MBinary) + if !ok || mul.Op != '*' || m.Alias != "err_pct" { + t.Fatal(m) + } + div, ok := mul.L.(*MBinary) + if !ok || div.Op != '/' { + t.Fatal(mul) + } + if _, ok := div.L.(*MCountIf); !ok { + t.Fatal(div) + } + if div.R.(*MCall).Name != "count" || mul.R.(*MConst).Value != 100 { + t.Fatal(mul) + } + if q.Stage.By[0].Key != "http_route" || q.Stage.Bucket != "1m" || q.Sort.Key != "err_pct" || q.Sort.Ascending || q.Limit.N != 10 { + t.Fatal(q) + } + x := mustParse(t, "spans | p95(duration)-p50(duration) as spread").Stage.Measures[0].Expr.(*MBinary) + if x.Op != '-' || x.L.(*MCall).Name != "p95" || x.R.(*MCall).Name != "p50" { + t.Fatal(x) + } + x = mustParse(t, "spans | count() * -1 as neg").Stage.Measures[0].Expr.(*MBinary) + if x.R.(*MNeg).X.(*MConst).Value != 1 { + t.Fatal(x) + } + for _, s := range []string{"count()*100 as c100", "count()/count() as one", "count() * 1e3 as k", "count() * 1.5 as x", "(count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex"} { + mustParse(t, "spans | "+s) + } + c := mustParse(t, "spans | count() * 1e3 as k").Stage.Measures[0].Expr.(*MBinary).R.(*MConst) + if c.Value != 1000 || c.Text != "1e3" { + t.Fatal(c) + } + wantProblem(t, "spans | count() +", "", "+ needs a measure or number on both sides", "") +} + +func TestParseExpressionRules(t *testing.T) { + wantProblem(t, "spans | count() / 2", "", "name this expression with as, e.g. count() / 2 as half", "") + wantProblem(t, "spans | share() / 2 as half", "", "share() cannot be combined; it is already a percentage of the scope", "use share() alone, or count_if(...) / count() * 100 for a custom ratio") + for _, s := range []string{"1 as one", "1 / 2 as half", "-(5) as neg"} { + ps := wantProblem(t, "spans | "+s, "", "a measure needs an aggregate; constants can only scale one, e.g. count() * 100", "") + if ps[0].Span.Start != 8 { + t.Fatal(ps) + } + } + mustParse(t, "spans | count() * 0 as zero") + wantProblem(t, "spans | histogram(duration), count()", "", "distribution counts require count(); histogram(...) stands alone", "") + q := mustParse(t, "spans | histogram(duration) by service") + if q.Stage.Histogram == nil || q.Stage.Histogram.Key != "duration" || len(q.Stage.By) != 1 { + t.Fatal(q) + } + x := mustParse(t, "spans | count(*)").Stage.Measures[0].Expr.(*MCall) + if x.Name != "count" || len(x.Args) != 1 || !x.Args[0].Star { + t.Fatal(x) + } +} + +func TestParseSortLimitAndSecondPipe(t *testing.T) { + for _, tc := range []struct { + sort string + asc bool + }{{"-count", false}, {"+p95", true}, {"p95 asc", true}, {"p95 desc", false}} { + q := mustParse(t, "spans sort "+tc.sort) + if q.Sort.Ascending != tc.asc { + t.Fatal(q.Sort) + } + } + wantProblem(t, "spans sort -p95 asc", "", "sort takes one direction", "") + q := mustParse(t, "spans | count() by service | sort count | limit 10") + if q.Sort.Key != "count" || q.Limit.N != 10 { + t.Fatal(q) + } + for _, tc := range []struct{ text, message, hint string }{ + {"spans | count() by service | top 3 by count", "FanQL 1 runs one aggregation stage", "remove the second |; more stages come in a later version"}, + {"spans limit 10 sort duration", "limit comes before sort here; write ... sort duration limit 10", ""}, + {"spans | count() limit 0", "limit needs a whole number from 1 to 1000; e.g. limit 50", ""}, + {"spans where a:1 where b:2", "where appears twice; combine the filters into one where", ""}, + {"spans | every 1m", "every needs measures first; write | count() every 1m", ""}, + {"spans | count() every 2m", `unknown bucket "2m"; use auto or one of 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h, 1d`, ""}, + {"spans | count() by a, b, c, d", "at most 3 grouping fields", ""}, + } { + wantProblem(t, tc.text, "", tc.message, tc.hint) + } +} + +func TestParseSourceErrors(t *testing.T) { + wantProblem(t, "traces where a:1", "", `unknown source "traces"`, "use spans; traces is a viz of spans") + wantProblem(t, "from spans", "", `"from" is not FanQL; start with the source: spans where ...`, "") + wantProblem(t, "", "", `unknown source ""`, "use spans, logs or metrics") + q := mustParse(t, "logs") + if q.Source != "logs" || len(q.Where) != 0 { + t.Fatal(q) + } +} + +func TestParseSearchBarFilters(t *testing.T) { + q, ps := Parse("service:api timeout", "logs") + if len(ps) != 0 || q == nil || q.Source != "logs" || len(q.Where) != 2 { + t.Fatalf("%#v %#v", q, ps) + } + wantProblem(t, "where service:api", "logs", "the page supplies where", "") + if q, ps := Parse("| count()", "logs"); q != nil || len(ps) == 0 { + t.Fatal(q, ps) + } +} + +func TestParseReservedAndForeignWords(t *testing.T) { + for _, w := range strings.Fields("let join correlate compare top eval extend having fields rename over window") { + wantProblem(t, "spans where "+w, "", fmt.Sprintf("%q is reserved for a future FanQL feature", w), "quote it to search for the word") + } + for _, tc := range []struct{ text, message, hint string }{ + {"spans | summarize count() by service", `"summarize" is not FanQL; write the measures after |, e.g. | count() by service`, ""}, + {`spans where service == "api"`, "== is not FanQL; use key:value or =", ""}, + {`spans where body =~ "re"`, "=~ is not FanQL; ~ is contains; use regexp_matches(field, 're') for a regular expression", ""}, + {`spans where {service="api"}`, "{ selectors are not FanQL; write labels as key:value, e.g. service:api", ""}, + {"spans where @http.target:x", `"@http.target" is not a field name; write the attribute without @: http.target`, ""}, + {"spans where !service:api", "! negation is not FanQL; write -service:api", ""}, + {"spans since 1h", "the time range is not part of FanQL 1; use the time picker (since is reserved)", ""}, + {"spans until 1h", "the time range is not part of FanQL 1; use the time picker (until is reserved)", ""}, + {"spans where service:api*", "* wildcards are not in FanQL 1", `use ~ for contains, or quote "api*"`}, + } { + wantProblem(t, tc.text, "", tc.message, tc.hint) + } + if _, ok := mustParse(t, "spans where stats").Where[0].(*FreeText); !ok { + t.Fatal("foreign free text") + } +} + +func TestParseUnclosedAndUnmatched(t *testing.T) { + for _, tc := range []struct{ text, message string }{ + {"spans where (a:1", "unclosed (; add ) before |, sort, limit or the end"}, + {"spans where a:1)", "unmatched ); remove it or add the opening ("}, + {"spans where \"abc", `unclosed quote; close the value with "`}, + {"spans where `coalesce(a", "unclosed raw filter; close it with `"}, + {"spans where a:1 or", "or needs a filter on both sides"}, + {"spans where service:", "service: needs a value; e.g. service:api"}, + {"spans where >500ms", "a filter needs a field before >"}, + {"spans where duration>", "duration> needs a value; e.g. duration>500ms"}, + } { + ps := wantProblem(t, tc.text, "", tc.message, "") + if strings.Contains(tc.text, "(a:1") && *ps[0].Span != (panel.TextSpan{Start: 12, End: 13}) { + t.Fatal(ps) + } + } +} + +func TestParseCollectsAllProblemsInOrderCappedAt20(t *testing.T) { + q, ps := Parse("spans where "+strings.Repeat("!k:v ", 25), "") + if q != nil || len(ps) != 21 || ps[20].Message != "more problems follow; fix these first" { + t.Fatal(q, ps) + } + for i, p := range ps { + if p.Span == nil || p.Path != "text" || (i > 0 && p.Span.Start < ps[i-1].Span.Start) { + t.Fatal(ps) + } + } + q, ps = Parse("traces | stats x take 5", "") + if q != nil || len(ps) != 3 { + t.Fatal(q, ps) + } +} + +func TestParseBoundsAreEnforcedIndependently(t *testing.T) { + values := make([]string, 101) + for i := range values { + values[i] = fmt.Sprintf("v%d", i+1) + } + for _, tc := range []struct{ text, fragment string }{ + {strings.Repeat("a", 4001), "a query is at most 4000 characters (8192 bytes)"}, + {strings.Repeat("界", 3000), "a query is at most 4000 characters (8192 bytes)"}, + {"spans " + strings.Repeat("a ", 1024), "tokens"}, + {"spans " + strings.Repeat("a ", 513), "nodes"}, + {"spans " + strings.Repeat("(", 17) + "a:1" + strings.Repeat(")", 17), "depth"}, + {"spans service in (" + strings.Join(values, ",") + ")", "list"}, + } { + q, ps := Parse(tc.text, "") + if q != nil || len(ps) != 1 || !strings.Contains(ps[0].Message, tc.fragment) || ps[0].Span == nil { + t.Fatalf("%s: %#v %#v", tc.fragment, q, ps) + } + if tc.fragment == "list" && string([]rune(tc.text)[ps[0].Span.Start:ps[0].Span.End]) != "v101" { + t.Fatal(ps) + } + } +} + +func TestParseKeywordCaseFolding(t *testing.T) { + q := mustParse(t, "SPANS WHERE Service:API | COUNT() BY service EVERY 1M SORT COUNT LIMIT 5") + x := q.Where[0].(*Compare) + if q.Source != "spans" || x.Field.Key != "Service" || x.Value.Text != "API" || q.Stage.Measures[0].Expr.(*MCall).Name != "count" || q.Stage.Bucket != "1m" || q.Sort.Key != "count" { + t.Fatal(q, x) + } +} + +func TestParseEntryParserIsUnbounded(t *testing.T) { + x, ps := parseEntry(`body:"` + strings.Repeat("x", 9000) + `"`) + if len(ps) != 0 || x == nil { + t.Fatal(x, ps) + } +} + +func TestParseFieldsAndLiteralSpans(t *testing.T) { + q := mustParse(t, `logs where attributes['𝔘.key']:"✓" resource.k8s.pod.name:x a.b:y`) + fields := []Field{q.Where[0].(*Compare).Field, q.Where[1].(*Compare).Field, q.Where[2].(*Compare).Field} + if fields[0].Scope != "attributes" || fields[0].Key != "𝔘.key" || !fields[0].Bracket || fields[0].Single || fields[1].Scope != "resource" || fields[1].Key != "k8s.pod.name" || fields[2].Scope != "" || fields[2].Key != "a.b" { + t.Fatal(fields) + } + if !reflect.DeepEqual(q.SourceSpan, Span{0, 4}) { + t.Fatal(q) + } +} + +func TestParseRejectsMissingMeasureCommas(t *testing.T) { + wantProblem(t, "spans | count() rate()", "", "separate measures with a comma", "") +} + +func TestParseGroupingFixItsRepairLongerChains(t *testing.T) { + for _, s := range []string{"a:1 b:2 or c:3 d:4", "a:1 or b:2 c:3 or d:4", "(a:1 b:2) c:3 or d:4"} { + text := "spans where " + s + ps := wantProblem(t, text, "", "mixed and/or needs parentheses", "") + for _, fix := range ps[0].FixIts { + r := []rune(text) + repaired := string(r[:fix.Span.Start]) + fix.Text + string(r[fix.Span.End:]) + mustParse(t, repaired) + } + } +} + +func TestParseApdexTree(t *testing.T) { + q := mustParse(t, "spans | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex") + var walk func(MExpr) (int, int) + walk = func(x MExpr) (int, int) { + switch x := x.(type) { + case *MBinary: + ld, ln := walk(x.L) + rd, rn := walk(x.R) + return max(ld, rd) + 1, ln + rn + case *MNeg: + d, n := walk(x.X) + return d + 1, n + case *MCall, *MCountIf: + return 1, 1 + default: + return 1, 0 + } + } + depth, leaves := walk(q.Stage.Measures[0].Expr) + if depth != 4 || leaves != 3 { + t.Fatalf("depth %d, aggregates %d", depth, leaves) + } +} + +func TestParseFilterSignsAndFieldShapes(t *testing.T) { + for _, tc := range []struct{ text, message string }{ + {"spans where k:+3", "unexpected +"}, + {"spans where 500>3", "a filter needs a field before >"}, + {"spans where *foo", "* wildcards are not in FanQL 1"}, + {"spans | avg(*)", "* is only allowed as the sole argument of count(*)"}, + } { + wantProblem(t, tc.text, "", tc.message, "") + } + q := mustParse(t, "spans where k not a:1") + if len(q.Where) != 2 { + t.Fatal(q) + } + if _, ok := q.Where[1].(*Not); !ok { + t.Fatal(q.Where) + } +} + +func TestParseForeignSyntaxInEachPosition(t *testing.T) { + for _, s := range []string{"spans | sort by service", "spans where body::text", "spans |= err", "spans |~ err", "spans group by service", "spans facet service", "spans where ago(1h)", "spans where now()", "spans where earliest=1h", "spans where _time:x"} { + if q, ps := Parse(s, ""); q != nil || len(ps) == 0 { + t.Fatalf("accepted %s: %#v", s, q) + } + } + mustParse(t, "metrics | avg(value)") +} + +func TestParseCombinedNestingBounds(t *testing.T) { + for _, text := range []string{ + "spans where " + strings.Repeat("not ", 17) + "a:1", + "spans where " + strings.Repeat("lower(", 17) + "body" + strings.Repeat(")", 17) + " = 'x'", + "spans where " + strings.Repeat("(", 9) + strings.Repeat("not ", 8) + "a:1" + strings.Repeat(")", 9), + "spans | count()" + strings.Repeat(" + 1", 17) + " as x", + } { + _, ps := Parse(text, "") + if len(ps) != 1 || !strings.Contains(ps[0].Message, "depth") { + t.Fatalf("%q: %#v", text, ps) + } + } + mustParse(t, "spans where "+strings.Repeat("not ", 16)+"a:1") +} + +func TestParseDistributionStandsAlone(t *testing.T) { + for _, text := range []string{"spans | histogram(duration) + count() as x", "spans | count() + histogram(duration) as x", "spans | histogram(duration), histogram(value)"} { + wantProblem(t, text, "", "distribution counts require count(); histogram(...) stands alone", "") + } + wantProblem(t, "spans | histogram(duration) as x", "", "histogram(...) does not take an alias", "") +} + +func TestParseListsRejectWildcards(t *testing.T) { + wantProblem(t, "spans where service in (*)", "", "* wildcards are not in FanQL 1", "") +} diff --git a/internal/fanql/words.go b/internal/fanql/words.go new file mode 100644 index 00000000..f961726e --- /dev/null +++ b/internal/fanql/words.go @@ -0,0 +1,117 @@ +package fanql + +import ( + "fmt" + "strings" +) + +var sources = wordSet("spans logs metrics") +var clauses = wordSet("where by every sort limit") +var expressionWords = wordSet("and or not in between is null like ilike") +var modifiers = wordSet("as asc desc") +var buckets = wordSet("auto 10s 30s 1m 5m 10m 15m 30m 1h 3h 6h 12h 1d") +var reserved = wordSet("let join correlate compare since until top eval extend having fields rename over window") +var foreignStages = wordSet("stats summarize select project extend eval fields rename take head top order sort") +var foreignCalls = wordSet("bin span percentile perc95 pct count_over_time quantile_over_time mean median dc distinct_count cardinality") + +func wordSet(s string) map[string]bool { + set := make(map[string]bool) + for _, word := range strings.Fields(s) { + set[word] = true + } + return set +} + +// Centralize diagnostic wording so the parser and future completion share it. +var messages = map[string]string{ + "textBound": "a query is at most 4000 characters (8192 bytes)", + "tokensBound": "a query is at most 1024 tokens", + "nodesBound": "a query is at most 512 nodes", + "depthBound": "a query has at most 16 levels of nesting depth", + "listBound": "an in list is at most 100 values", + "more": "more problems follow; fix these first", + "source": "unknown source %q", + "from": "%q is not FanQL; start with the source: spans where ...", + "pageWhere": "the page supplies where", + "pageFilter": "the page accepts filters only; measures, sort and limit belong in Explore", + "whereEmpty": "where needs a filter", + "whereTwice": "where appears twice; combine the filters into one where", + "mixed": "mixed and/or needs parentheses", + "sides": "%s needs a filter on both sides", + "value": "%s%s needs a value; e.g. %s%s%s", + "colon": "unexpected : after %s", + "fieldBefore": "a filter needs a field before %s", + "field": "a field needs a name, e.g. service or attributes['key']", + "bracket": "a bracket field needs a quoted key and ]", + "between": "between needs two values", + "like": "like needs a quoted pattern", + "null": "is needs null or not null", + "list": "in needs a list or variable, e.g. in (api, web)", + "listValue": "a list needs a value after each comma", + "callSpace": "write %s(...) without a space", + "callArg": "%s needs a field, quoted string, number or nested call", + "callClose": "unclosed call; add )", + "unclosedGroup": "unclosed (; add ) before |, sort, limit or the end", + "unmatched": "unmatched ); remove it or add the opening (", + "quote": "unclosed quote; close the value with %c", + "raw": "unclosed raw filter; close it with `", + "unexpected": "unexpected %s", + "plus": "unexpected +", + "wildcard": "* wildcards are not in FanQL 1", + "variable": "$__ names are reserved; use a dashboard variable name", + "reserved": "%q is reserved for a future FanQL feature", + "foreignStage": "%q is not FanQL; write the measures after |, e.g. | count() by service", + "foreignCall": "%s(...) is not FanQL; use the FanQL measure functions", + "foreignClause": "%s is not FanQL; use by after measures, e.g. | count() by service", + "time": "the time range is not part of FanQL 1; use the time picker (%s is reserved)", + "timeCall": "%s(...) is not FanQL; use the time picker", + "eqeq": "== is not FanQL; use key:value or =", + "regex": "=~ is not FanQL; ~ is contains; use regexp_matches(field, 're') for a regular expression", + "pipeOp": "%s is not FanQL; use body ~ \"text\" for contains", + "cast": ":: is not FanQL; use field comparisons or a backtick raw filter", + "selector": "{ selectors are not FanQL; write labels as key:value, e.g. service:api", + "at": "%q is not a field name; write the attribute without @: %s", + "bang": "! negation is not FanQL; write -%s", + "measure": "a measure needs a call, number or parenthesised expression", + "measureSides": "%s needs a measure or number on both sides", + "measureName": "name this expression with as, e.g. count() / 2 as half", + "aggregate": "a measure needs an aggregate; constants can only scale one, e.g. count() * 100", + "share": "share() cannot be combined; it is already a percentage of the scope", + "histogram": "distribution counts require count(); histogram(...) stands alone", + "histogramField": "histogram needs one field, e.g. histogram(duration)", + "histogramAlias": "histogram(...) does not take an alias", + "measureArg": "a measure argument needs a field, number or *", + "measureComma": "separate measures with a comma", + "starArg": "* is only allowed as the sole argument of count(*)", + "alias": "as needs a measure alias", + "secondStage": "FanQL 1 runs one aggregation stage", + "everyFirst": "every needs measures first; write | count() every 1m", + "byFirst": "by needs measures first; write | count() by service", + "bucket": "unknown bucket %q; use auto or one of 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h, 1d", + "byMax": "at most 3 grouping fields", + "histogramBy": "histogram accepts at most one grouping field", + "direction": "sort takes one direction", + "sortKey": "sort needs a key, e.g. sort duration", + "limitBeforeSort": "limit comes before sort here; write ... sort duration limit 10", + "limit": "limit needs a whole number from 1 to 1000; e.g. limit 50", + "duplicate": "%s appears twice", + "order": "%s must follow measures and come before sort and limit", +} + +var hints = map[string]string{ + "source": "use spans, logs or metrics", + "traces": "use spans; traces is a viz of spans", + "reserved": "quote it to search for the word", + "share": "use share() alone, or count_if(...) / count() * 100 for a custom ratio", + "secondStage": "remove the second |; more stages come in a later version", +} + +func diagnostic(code string, args ...any) string { return fmt.Sprintf(messages[code], args...) } +func whereHint(word string) string { + return fmt.Sprintf("quote %q to search for the word, or drop where", word) +} +func wildcardHint(word string) string { return fmt.Sprintf("use ~ for contains, or quote %q", word) } +func quoteValueHint(field, value string) string { + return fmt.Sprintf("quote the value: %s%q", field, value) +} +func groupingHint(a, b string) string { return "write " + a + " or " + b } diff --git a/internal/mcp/presentation_test.go b/internal/mcp/presentation_test.go index 1217735f..48ff6cfb 100644 --- a/internal/mcp/presentation_test.go +++ b/internal/mcp/presentation_test.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "errors" + "reflect" "regexp" "strings" "testing" @@ -276,7 +277,7 @@ func TestDashboardRejectionsPreserveRouteDiagnosesThroughMiddleware(t *testing.T if err != nil || json.Unmarshal(raw, &structured) != nil || structured.Error == nil || *structured.Error != *failure.Error { t.Fatalf("structured=%s err=%v", raw, err) } - if len(structured.Problems) != 1 || structured.Problems[0] != failure.Problems[0] { + if len(structured.Problems) != 1 || !reflect.DeepEqual(structured.Problems[0], failure.Problems[0]) { t.Fatalf("structured problems=%+v", structured.Problems) } }) diff --git a/internal/panel/deploy_split_test.go b/internal/panel/deploy_split_test.go index 001deb37..9a63fec5 100644 --- a/internal/panel/deploy_split_test.go +++ b/internal/panel/deploy_split_test.go @@ -3,7 +3,6 @@ package panel import ( "encoding/json" "errors" - "slices" "strings" "testing" "time" @@ -80,7 +79,7 @@ func TestDeploySplitAllFallsBackAndRequiresEquality(t *testing.T) { err = e.Validate(t.Context(), &d) var problems Problems want := Problem{Path: "panels[0].options.split", Message: "deploy split requires a service equality filter", Hint: "add service = 'name' or service = $service"} - if !errors.As(err, &problems) || !slices.Contains(problems, want) { + if !errors.As(err, &problems) || !containsProblem(problems, want) { t.Fatalf("got %v want %+v", err, want) } } diff --git a/internal/panel/distribution_test.go b/internal/panel/distribution_test.go index 3e01dac7..c8010c2b 100644 --- a/internal/panel/distribution_test.go +++ b/internal/panel/distribution_test.go @@ -189,7 +189,7 @@ func TestDistributionValidation(t *testing.T) { d := Dashboard{Name: "Rule", Panels: []Panel{tc.p}} Normalize(&d) got := Validate(&d) - if !slices.Contains(got, tc.want) { + if !containsProblem(got, tc.want) { t.Fatalf("got %+v want %+v", got, tc.want) } } diff --git a/internal/panel/drill_logs_test.go b/internal/panel/drill_logs_test.go index fb9dcc9d..b56b1077 100644 --- a/internal/panel/drill_logs_test.go +++ b/internal/panel/drill_logs_test.go @@ -2,7 +2,6 @@ package panel import ( "errors" - "slices" "testing" "time" @@ -37,7 +36,7 @@ func TestExemplarKindValidation(t *testing.T) { _, err := e.Exemplars(t.Context(), req) var got Problems want := Problem{Path: "kind", Message: "kind must be traces or logs", Hint: "choose traces or logs"} - if !errors.As(err, &got) || !slices.Contains(got, want) { + if !errors.As(err, &got) || !containsProblem(got, want) { t.Fatalf("got %v want %+v", err, want) } } @@ -75,7 +74,7 @@ func TestDrillLogsCapAndSource(t *testing.T) { req.Dimensions = nil _, err = e.Exemplars(t.Context(), req) var problems Problems - if !errors.As(err, &problems) || !slices.Contains(problems, Problem{Path: "kind", Message: "log selections need a logs-source panel"}) { + if !errors.As(err, &problems) || !containsProblem(problems, Problem{Path: "kind", Message: "log selections need a logs-source panel"}) { t.Fatalf("source accepted: %v", err) } } diff --git a/internal/panel/exemplars_test.go b/internal/panel/exemplars_test.go index 42786539..e9ad38b6 100644 --- a/internal/panel/exemplars_test.go +++ b/internal/panel/exemplars_test.go @@ -4,7 +4,6 @@ import ( "errors" "github.com/labstack/fanout/internal/telemetry" "math" - "slices" "testing" "time" ) @@ -39,7 +38,7 @@ func TestExemplarsRejectForgedDimensions(t *testing.T) { _, err := e.Exemplars(t.Context(), req) var problems Problems want := Problem{Path: "dimensions", Message: "dimensions must name query.by fields and values at most 500 characters", Hint: "select one of the panel grouping fields"} - if !errors.As(err, &problems) || !slices.Contains(problems, want) { + if !errors.As(err, &problems) || !containsProblem(problems, want) { t.Fatalf("got %v want %+v", err, want) } req.Dimensions = map[string]string{"http_route": "x'); DROP TABLE spans; --"} @@ -67,7 +66,7 @@ func TestExemplarBucketValidation(t *testing.T) { for _, tc := range cases { _, _, err := selectionWhere(p, nil, scope, nil, tc.bucket) var got Problems - if !errors.As(err, &got) || !slices.Contains(got, tc.want) { + if !errors.As(err, &got) || !containsProblem(got, tc.want) { t.Fatalf("got %v want %+v", err, tc.want) } } diff --git a/internal/panel/items_test.go b/internal/panel/items_test.go index 1619420d..a66d17f5 100644 --- a/internal/panel/items_test.go +++ b/internal/panel/items_test.go @@ -103,7 +103,7 @@ func TestItemsValidation(t *testing.T) { d := Dashboard{Name: "Rule", Panels: []Panel{tc.panel}} Normalize(&d) got := Validate(&d) - if !slices.Contains(got, tc.want) { + if !containsProblem(got, tc.want) { t.Fatalf("got %+v want %+v", got, tc.want) } } diff --git a/internal/panel/problems.go b/internal/panel/problems.go index af3dd696..07f944a9 100644 --- a/internal/panel/problems.go +++ b/internal/panel/problems.go @@ -5,12 +5,27 @@ import ( "strings" ) +// TextSpan uses code-point offsets, with an exclusive end. +type TextSpan struct { + Start int `json:"start"` + End int `json:"end"` +} + +// FixIt is an alternative text replacement the author may choose to apply. +type FixIt struct { + Label string `json:"label"` + Span TextSpan `json:"span"` + Text string `json:"text"` +} + // Problem is one reason a spec cannot be saved or run, addressed by a JSON // path so the author can fix exactly that field. type Problem struct { - Path string `json:"path"` - Message string `json:"message"` - Hint string `json:"hint,omitempty"` + Path string `json:"path"` + Message string `json:"message"` + Hint string `json:"hint,omitempty"` + Span *TextSpan `json:"span,omitempty"` + FixIts []FixIt `json:"fix_its,omitempty"` productDiagnosis bool } diff --git a/internal/panel/problems_test.go b/internal/panel/problems_test.go new file mode 100644 index 00000000..0583ec17 --- /dev/null +++ b/internal/panel/problems_test.go @@ -0,0 +1,29 @@ +package panel + +import ( + "encoding/json" + "reflect" + "slices" + "testing" +) + +// Problem includes optional slices; compare complete diagnostics by value. +func containsProblem(problems Problems, want Problem) bool { + return slices.ContainsFunc(problems, func(got Problem) bool { return reflect.DeepEqual(got, want) }) +} + +func TestProblemJSONCarriesSpanAndFixIts(t *testing.T) { + p := Problem{Path: "text", Message: "m", Span: &TextSpan{Start: 1, End: 4}, FixIts: []FixIt{{Label: "l", Span: TextSpan{Start: 1, End: 4}, Text: "x"}}} + data, err := json.Marshal(p) + if err != nil || string(data) != `{"path":"text","message":"m","span":{"start":1,"end":4},"fix_its":[{"label":"l","span":{"start":1,"end":4},"text":"x"}]}` { + t.Fatalf("%s %v", data, err) + } + data, err = json.Marshal(Problem{Path: "p", Message: "m"}) + if err != nil || string(data) != `{"path":"p","message":"m"}` { + t.Fatalf("%s %v", data, err) + } + shown := PresentProblems(Problems{p}) + if len(shown) != 1 || !reflect.DeepEqual(shown[0].Span, p.Span) || !reflect.DeepEqual(shown[0].FixIts, p.FixIts) { + t.Fatal(shown) + } +} diff --git a/internal/panel/rollup_panels_test.go b/internal/panel/rollup_panels_test.go index 10f500fe..856fc347 100644 --- a/internal/panel/rollup_panels_test.go +++ b/internal/panel/rollup_panels_test.go @@ -4,7 +4,6 @@ import ( "context" "errors" "reflect" - "slices" "strings" "testing" "time" @@ -198,7 +197,7 @@ func TestRollupPanelsRejectUnrepresentableFilters(t *testing.T) { err := e.Validate(t.Context(), &d) var got Problems want := Problem{Path: "panels[0].query.where[0]", Message: tc.message, Hint: "use namespace or service equality with a literal or single-value variable"} - if !errors.As(err, &got) || !slices.Contains(got, want) { + if !errors.As(err, &got) || !containsProblem(got, want) { t.Fatalf("%s: got %v want %+v", tc.where, err, want) } } From 63704263a6d1a38d41487de3f17e0002dd82553b Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 16:00:58 -0700 Subject: [PATCH 04/30] refactor(panel): share the severity table, export catalog accessors and extract QueryShape --- internal/ingest/server.go | 58 +---- internal/ingest/server_test.go | 30 ++- internal/panel/export.go | 78 +++++++ internal/panel/export_test.go | 67 ++++++ internal/panel/items.go | 16 +- internal/panel/rowpanels.go | 50 +---- internal/panel/shape.go | 319 ++++++++++++++++++++++++++++ internal/panel/shape_test.go | 105 +++++++++ internal/panel/validate.go | 117 +--------- internal/telemetry/severity.go | 74 +++++++ internal/telemetry/severity_test.go | 50 +++++ scripts/go-deadcode.allowlist | 10 + 12 files changed, 744 insertions(+), 230 deletions(-) create mode 100644 internal/panel/export.go create mode 100644 internal/panel/export_test.go create mode 100644 internal/panel/shape.go create mode 100644 internal/panel/shape_test.go create mode 100644 internal/telemetry/severity.go create mode 100644 internal/telemetry/severity_test.go diff --git a/internal/ingest/server.go b/internal/ingest/server.go index 26ba46dd..cff3d000 100644 --- a/internal/ingest/server.go +++ b/internal/ingest/server.go @@ -209,7 +209,7 @@ func (s *Server) exportLogs(ctx context.Context, req *collectorlogs.ExportLogsSe Namespace: namespace, TimeUnixNanos: int64(lr.TimeUnixNano), ObservedTimeNanos: int64(lr.ObservedTimeUnixNano), - Severity: normalizeSeverity(lr.SeverityText, int32(lr.SeverityNumber)), + Severity: telemetry.NormalizeSeverity(lr.SeverityText, int32(lr.SeverityNumber)), SeverityNumber: int32(lr.SeverityNumber), Body: body, BodyTemplate: tmpl, @@ -667,62 +667,6 @@ func anyValueString(v *common.AnyValue) string { } } -// normalizeSeverity maps a record onto the six OTel severity names, so that a -// search for ERROR finds every error however its emitter spelled it. -// -// Passing SeverityText through unchanged is what produced a store holding -// INFO, INFORMATION and "" for the same level: .NET writes "Information", -// Envoy's access logs carry no severity at all, and each spelling then answered -// a different query. severity_number is preferred because the specification -// makes it the authoritative field and the text the display form, and a record -// that carries neither is stored as UNSPECIFIED rather than as an empty string -// — the log-bucket query already labels that case UNSPECIFIED, and a level you -// can see in the chart should be one you can filter on. -func normalizeSeverity(text string, number int32) string { - switch { - case number >= 21: - return "FATAL" - case number >= 17: - return "ERROR" - case number >= 13: - return "WARN" - case number >= 9: - return "INFO" - case number >= 5: - return "DEBUG" - case number >= 1: - return "TRACE" - } - return severityFromText(text) -} - -// severityFromText canonicalizes the spellings emitters use when they send no -// severity_number: OTel's own numbered short names (INFO2, WARN3), the syslog -// names, and the long forms favoured by .NET and Python. -func severityFromText(text string) string { - name := strings.ToUpper(strings.TrimSpace(text)) - name = strings.TrimRight(name, "0123456789") - switch name { - case "FATAL", "CRIT", "CRITICAL", "EMERG", "EMERGENCY", "ALERT", "PANIC": - return "FATAL" - case "ERROR", "ERR", "SEVERE", "EXCEPTION": - return "ERROR" - case "WARN", "WARNING": - return "WARN" - case "INFO", "INFORMATION", "INFORMATIONAL", "NOTICE": - return "INFO" - case "DEBUG", "DBG", "FINE": - return "DEBUG" - case "TRACE", "VERBOSE", "FINEST": - return "TRACE" - case "": - return "UNSPECIFIED" - } - // An unrecognised level is still the emitter's own word for it, and - // discarding it would lose the only grading the record carries. - return name -} - func getServiceName(r *resourcepb.Resource) string { return getResourceAttr(r, "service.name") } diff --git a/internal/ingest/server_test.go b/internal/ingest/server_test.go index 604fe563..b54c59fc 100644 --- a/internal/ingest/server_test.go +++ b/internal/ingest/server_test.go @@ -5,8 +5,10 @@ import ( "errors" "testing" + collectorlogs "go.opentelemetry.io/proto/otlp/collector/logs/v1" collectortrace "go.opentelemetry.io/proto/otlp/collector/trace/v1" common "go.opentelemetry.io/proto/otlp/common/v1" + logspb "go.opentelemetry.io/proto/otlp/logs/v1" metricspb "go.opentelemetry.io/proto/otlp/metrics/v1" resourcepb "go.opentelemetry.io/proto/otlp/resource/v1" tracepb "go.opentelemetry.io/proto/otlp/trace/v1" @@ -515,13 +517,39 @@ func TestNormalizeSeverityCanonicalizesEmitterSpellings(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if got := normalizeSeverity(tt.text, tt.number); got != tt.want { + if got := telemetry.NormalizeSeverity(tt.text, tt.number); got != tt.want { t.Errorf("normalizeSeverity(%q, %d) = %q, want %q", tt.text, tt.number, got, tt.want) } }) } } +func TestExportedLogsCarryNormalizedBands(t *testing.T) { + spans := make(chan telemetry.Span, 1) + logs := make(chan telemetry.Log, 6) + metrics := make(chan telemetry.Metric, 1) + srv := NewServer(config.Config{}, newTestSubmitter(spans, logs, metrics)) + pairs := []struct { + text string + number int32 + want string + }{{"ERROR", 9, "INFO"}, {"FATAL", 0, "FATAL"}, {"WARN2", 14, "WARN"}, {"info", 0, "INFO"}, {"custom", 0, "CUSTOM"}, {"", 0, "UNSPECIFIED"}} + var records []*logspb.LogRecord + for _, p := range pairs { + records = append(records, &logspb.LogRecord{SeverityText: p.text, SeverityNumber: logspb.SeverityNumber(p.number), TimeUnixNano: 1}) + } + _, err := srv.exportLogs(context.Background(), &collectorlogs.ExportLogsServiceRequest{ResourceLogs: []*logspb.ResourceLogs{{ScopeLogs: []*logspb.ScopeLogs{{LogRecords: records}}}}}) + if err != nil { + t.Fatal(err) + } + for _, p := range pairs { + got := <-logs + if got.Severity != p.want || got.Severity != telemetry.NormalizeSeverity(p.text, p.number) { + t.Errorf("stored severity = %q, want %q", got.Severity, p.want) + } + } +} + func TestTraceExportAcceptsSpanWithoutStatus(t *testing.T) { // status is optional in OTLP and most SDKs omit it for an unset status. // Reading it through the struct field panicked the handler, so a single diff --git a/internal/panel/export.go b/internal/panel/export.go new file mode 100644 index 00000000..0931b869 --- /dev/null +++ b/internal/panel/export.go @@ -0,0 +1,78 @@ +package panel + +import ( + "slices" + "strings" +) + +// SignalColumns returns a copy of every catalog column in display order. +func SignalColumns(signal string) ([]Field, bool) { + s, ok := lookupSignal(signal) + if !ok { + return nil, false + } + return slices.Clone(s.fields), true +} + +// LowCardinalityColumns returns columns whose common values the schema lists. +func LowCardinalityColumns(signal string) []string { + s, ok := lookupSignal(signal) + if !ok { + return nil + } + return slices.Clone(s.lowCard) +} + +// MeasureSpec describes a registered aggregate without exposing mutable tables. +type MeasureSpec struct { + Name string + Args int + Numeric bool + Additive bool + Unit string + Signals []string + Quantile float64 +} + +// MeasureSpecs lists registered measures, sorted by name. +func MeasureSpecs() []MeasureSpec { + out := make([]MeasureSpec, 0, len(measureFuncs)) + for _, name := range measureNames() { + s := measureFuncs[name] + out = append(out, MeasureSpec{Name: name, Args: s.args, Numeric: s.numeric, Additive: s.additive, Unit: s.unit, Signals: slices.Clone(s.signals), Quantile: s.quantile}) + } + return out +} + +// BucketNames lists auto followed by the registered intervals in duration order. +func BucketNames() []string { + out := make([]string, 0, len(buckets)+1) + for name := range buckets { + out = append(out, name) + } + slices.SortFunc(out, func(a, b string) int { + if buckets[a] < buckets[b] { + return -1 + } + if buckets[a] > buckets[b] { + return 1 + } + return 0 + }) + return append([]string{"auto"}, out...) +} + +// FilterFunctionNames lists named filter functions, excluding SQL operators. +func FilterFunctionNames() []string { + out := make([]string, 0, len(filterFunctions)) + for name := range filterFunctions { + if !strings.Contains(name, "~") { + out = append(out, name) + } + } + slices.Sort(out) + return out +} + +// Suggest returns the catalog's spelling suggestion, if any. +func Suggest(word string, candidates []string) string { return suggest(word, candidates) } diff --git a/internal/panel/export_test.go b/internal/panel/export_test.go new file mode 100644 index 00000000..3e2a6c73 --- /dev/null +++ b/internal/panel/export_test.go @@ -0,0 +1,67 @@ +package panel + +import ( + "reflect" + "slices" + "strings" + "testing" +) + +func TestExportedRegistriesMatchInternalTables(t *testing.T) { + specs := MeasureSpecs() + if len(specs) != len(measureFuncs) { + t.Fatalf("measure specs: %d, want %d", len(specs), len(measureFuncs)) + } + for i, m := range specs { + if i > 0 && specs[i-1].Name >= m.Name { + t.Fatal("measure specs not sorted") + } + s := measureFuncs[m.Name] + if m.Args != s.args || m.Numeric != s.numeric || m.Additive != s.additive || m.Unit != s.unit || m.Quantile != s.quantile || !reflect.DeepEqual(m.Signals, s.signals) { + t.Errorf("spec mismatch: %+v", m) + } + } + wantBuckets := []string{"auto", "10s", "30s", "1m", "5m", "10m", "15m", "30m", "1h", "3h", "6h", "12h", "1d"} + if got := BucketNames(); !slices.Equal(got, wantBuckets) { + t.Errorf("buckets = %v", got) + } + for _, name := range wantBuckets[1:] { + if _, ok := buckets[name]; !ok { + t.Errorf("unknown bucket %s", name) + } + } + if got := FilterFunctionNames(); !slices.Equal(got, []string{"contains", "length", "lower", "regexp_matches", "starts_with", "upper"}) { + t.Errorf("filter functions = %v", got) + } + cols, ok := SignalColumns("spans") + if !ok || !slices.ContainsFunc(cols, func(f Field) bool { return f.Name == "http_status_code" && f.Type == TypeString }) { + t.Fatal("missing string http_status_code") + } + if !slices.ContainsFunc(cols, func(f Field) bool { return f.Name == "attributes" && f.Type == TypeMap }) { + t.Fatal("missing attributes map") + } + if !reflect.DeepEqual(cols, signals["spans"].fields) { + t.Fatal("columns differ from display order") + } + cols[0].Name = "BROKEN" + if again, _ := SignalColumns("spans"); again[0].Name == "BROKEN" { + t.Fatal("columns are mutable") + } + if got := LowCardinalityColumns("spans"); !slices.Equal(got, signals["spans"].lowCard) { + t.Errorf("low cardinality = %v", got) + } + if cols, ok := SignalColumns("invalid"); ok || cols != nil { + t.Fatal("invalid signal accepted") + } +} + +func TestColumnNamesContainNoDots(t *testing.T) { + for _, signal := range SignalNames() { + cols, _ := SignalColumns(signal) + for _, col := range cols { + if strings.Contains(col.Name, ".") { + t.Errorf("%s column %q contains a dot", signal, col.Name) + } + } + } +} diff --git a/internal/panel/items.go b/internal/panel/items.go index 68c0052c..c4d981f3 100644 --- a/internal/panel/items.go +++ b/internal/panel/items.go @@ -114,19 +114,9 @@ func validateItems(p *Panel, path string, problems *Problems) { problems.add(path+".query", "item panels require structured queries") return } - if p.Viz == "scatter" && len(p.Query.Measures) != 2 { - problems.addHint(path+".query.measures", "scatter requires exactly two measures", "select x and y measures in that order") - } - if p.Viz == "state_timeline" { - if p.Query != nil && p.Query.Sort != "" { - problems.add(path+".query.sort", "state_timeline has fixed chronological ordering") - } - if p.Query != nil && len(p.Query.Measures) != 1 { - problems.add(path+".query.measures", "state_timeline requires one measure") - } - if len(p.Thresholds) == 0 { - problems.addHint(path+".thresholds", "state_timeline requires thresholds", "set a warn or bad boundary for the selected measure") - } + queryShapeItems(p.Query, p.Viz, path+".query", problems) + if p.Viz == "state_timeline" && len(p.Thresholds) == 0 { + problems.addHint(path+".thresholds", "state_timeline requires thresholds", "set a warn or bad boundary for the selected measure") } if p.Options != nil && p.Options.Style != "" { problems.add(path+".options.style", "item panels cannot stack or set line styles") diff --git a/internal/panel/rowpanels.go b/internal/panel/rowpanels.go index faf945c0..50e69d62 100644 --- a/internal/panel/rowpanels.go +++ b/internal/panel/rowpanels.go @@ -134,53 +134,5 @@ func validateRows(p *Panel, path string, problems *Problems) { } return } - q := p.Query - if q.Limit < 0 || q.Limit > 1000 { - problems.addHint(path+".query.limit", "limit must be 0 to 1000", "use a limit from 1 to 1000 or omit it for the default") - } - if q.Histogram != nil { - problems.addHint(path+".query.histogram", "histogram applies only to heatmap and histogram", "remove histogram or use a heatmap or histogram panel") - } - if p.Viz == "traces" { - if q.From != "spans" { - problems.addHint(path+".query.from", "traces reads spans", "use query {from: spans}") - } - if q.Sort != "" && q.Sort != "duration_ms" && q.Sort != "errors" && q.Sort != "+start" { - problems.addHint(path+".query.sort", "traces sort is duration_ms, errors or +start", "use sort duration_ms, errors, +start or omit sort") - } - } else { - if q.From != "logs" { - problems.addHint(path+".query.from", "logs and log_patterns read logs", "use query {from: logs}") - } - } - if p.Viz == "logs" && q.Sort != "" && q.Sort != "time" && q.Sort != "+time" { - problems.addHint(path+".query.sort", "logs sort is time or +time", "use sort time, +time or omit sort") - } - if p.Viz == "log_patterns" { - if len(q.By) != 1 || q.By[0] != "body_template" { - problems.addHint(path+".query.by", "log_patterns groups by body_template", "use by [body_template]") - } - if len(q.Measures) != 1 || q.Measures[0] != "count()" { - problems.addHint(path+".query.measures", "log_patterns requires count()", "use measures [count()]") - } - if q.Sort != "" && q.Sort != "count" { - problems.addHint(path+".query.sort", "log_patterns sort is count", "use sort count or omit sort") - } - if q.Bucket != "" && q.Bucket != "auto" { - if _, ok := buckets[q.Bucket]; !ok { - problems.addHint(path+".query.bucket", "bucket must be auto or a supported interval", "use auto, 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h or 1d") - } - } - } - if p.Viz == "logs" || p.Viz == "traces" { - if len(q.Measures) > 0 { - problems.addHint(path+".query.measures", "fixed row projections do not take aggregate measures", "remove measures; use log_patterns for counts or a table for aggregates") - } - if len(q.By) > 0 { - problems.addHint(path+".query.by", "logs and traces panels do not group; use log_patterns or a table", "remove by or use log_patterns or a table") - } - if q.Bucket != "" { - problems.addHint(path+".query.bucket", "logs and traces panels do not take a bucket", "remove bucket") - } - } + queryShapeRows(p.Query, p.Viz, path+".query", problems) } diff --git a/internal/panel/shape.go b/internal/panel/shape.go new file mode 100644 index 00000000..10722de3 --- /dev/null +++ b/internal/panel/shape.go @@ -0,0 +1,319 @@ +package panel + +import ( + "fmt" + "slices" + "strings" +) + +// VizRequirement identifies panel configuration required beyond the query. +type VizRequirement string + +const ( + RequiresMinMax VizRequirement = "min_max" + RequiresThresholds VizRequirement = "thresholds" +) + +// VizCompat identifies a visualization accepting the query as written. +type VizCompat struct { + Viz string `json:"viz"` + Requires []VizRequirement `json:"requires"` +} + +// QueryShape checks query-only structure without normalizing or using an engine. +// A nil vars map omits declaration checks. All problem paths are query-relative. +func QueryShape(q *Query, viz string, vars map[string]Variable) (Problems, []VizRequirement) { + requirements := []VizRequirement{} + if viz == "gauge" { + requirements = append(requirements, RequiresMinMax) + } + if viz == "state_timeline" { + requirements = append(requirements, RequiresThresholds) + } + var problems Problems + spec, ok := vizSpecs[viz] + if !ok { + problems.addHint("", fmt.Sprintf("unsupported viz %q", viz), "use one of "+strings.Join(vizOrder, ", ")) + return problems, requirements + } + if q == nil { + problems.add("", "a structured query is required") + return problems, requirements + } + if !spec.query { + problems.add("", "text panels have content, not a query") + return problems, requirements + } + p := &Panel{Viz: viz, Query: q} + queryShapeRows(q, viz, "", &problems) + queryShapeItems(q, viz, "", &problems) + if measures, ok := queryShapeAggregate(p, spec, "", &problems, true); ok { + queryShapeAggregateTail(q, viz, "", measures, &problems) + queryShapeReduce(q, spec, viz, "", &problems) + } + if vars != nil { + queryShapeVariables(q, vars, "", &problems) + } + for i := range problems { + problems[i].Path = strings.TrimPrefix(problems[i].Path, ".") + } + return problems, requirements +} + +// CompatibleVizzes lists the query visualizations accepting the query unchanged. +func CompatibleVizzes(q *Query, vars map[string]Variable) []VizCompat { + out := []VizCompat{} + for _, viz := range vizOrder { + // Text and fixed rollup scopes are not FanQL query visualization targets. + if viz == "text" || viz == "health" || viz == "service_map" { + continue + } + problems, requires := QueryShape(q, viz, vars) + if len(problems) == 0 { + out = append(out, VizCompat{Viz: viz, Requires: requires}) + } + } + return out +} + +func queryShapeVariables(q *Query, vars map[string]Variable, path string, problems *Problems) { + for _, ref := range varRefs(strings.Join(q.Where, " ")) { + if _, ok := vars[ref]; !ok { + problems.addHint(path+".where", fmt.Sprintf("$%s is not a dashboard variable", ref), suggest(ref, mapKeys(vars))) + } + } +} + +// Measures with arithmetic are structurally known before their engine compiler +// is installed. Binding and measure-expression semantics remain Check's job. +func shapeMeasures(sig *signal, texts []string, path string, problems *Problems) []Measure { + out := make([]Measure, 0, len(texts)) + for i, text := range texts { + m, message, hint := parseMeasure(sig, text) + if message != "" && (strings.Contains(text, "count_if(") || strings.ContainsAny(stripQuoted(text), "+-*/")) { + alias := "" + if at := strings.LastIndex(text, " as "); at >= 0 { + alias = strings.TrimSpace(text[at+4:]) + } else if strings.HasPrefix(text, "count_if(") && strings.HasSuffix(text, ")") { + alias = "count_if" + } + if aliasPattern.MatchString(alias) { + m = Measure{Text: text, Func: "expr", Alias: alias, Unit: "none"} + message = "" + } + } + if message != "" { + problems.addHint(fmt.Sprintf("%s[%d]", path, i), fmt.Sprintf("%q %s", text, message), hint) + continue + } + out = append(out, m) + } + uses := map[string]int{} + for _, m := range out { + if m.Alias == "" { + uses[m.Func]++ + } + } + seen := map[string]bool{} + for i := range out { + if out[i].Alias == "" { + out[i].Alias = out[i].Func + if uses[out[i].Func] > 1 && out[i].Field != nil { + out[i].Alias = out[i].Func + "_" + sanitize(out[i].Field.alias()) + } + } + if seen[out[i].Alias] { + problems.add(path, fmt.Sprintf("two measures are named %s; add distinct aliases with as", out[i].Alias)) + } + seen[out[i].Alias] = true + } + return out +} + +func queryShapeAggregate(p *Panel, spec vizSpec, path string, problems *Problems, shapeOnly bool) ([]Measure, bool) { + q := p.Query + if p.Viz == "logs" || p.Viz == "traces" || p.Viz == "log_patterns" { + // Fixed projections are checked field by field in validateRows; avoid + // duplicate aggregate-query Problems for the same rejected field. + if len(q.Where) > 16 { + problems.addHint(path+".where", "at most 16 filters per query", "remove filters until at most 16 remain") + } + for i, w := range q.Where { + if strings.TrimSpace(w) == "" || len(w) > 500 { + problems.addHint(fmt.Sprintf("%s.where[%d]", path, i), "filters are 1 to 500 characters", "use a nonempty filter of at most 500 characters") + } + } + return nil, false + } + if len(q.Where) > 16 { + problems.add(path+".where", "at most 16 filters per query") + } + sig, ok := lookupSignal(q.From) + if !ok { + problems.addHint(path+".from", fmt.Sprintf("unknown signal %q", q.From), "use spans, logs or metrics") + return nil, false + } + for i, w := range q.Where { + if strings.TrimSpace(w) == "" || len(w) > 500 { + problems.add(fmt.Sprintf("%s.where[%d]", path, i), "filters are 1 to 500 characters") + } + } + if (len(q.Measures) == 0 && p.Viz != "logs" && p.Viz != "traces" && p.Viz != "health" && p.Viz != "service_map") || len(q.Measures) > 6 { + problems.add(path+".measures", "a query has 1 to 6 measures; fixed logs and traces take none") + } + if len(q.Measures) > 1 && ((p.Viz == "timeseries" && len(q.By) > 0) || (p.Viz == "bar" && len(q.By) == 2)) { + problems.addHint(path+".measures", "grouped panels show one measure", "use one panel per measure, or remove by") + } + var measures []Measure + if shapeOnly { + measures = shapeMeasures(sig, q.Measures, path+".measures", problems) + } else { + measures = parseMeasures(sig, q.Measures, path+".measures", problems) + } + if len(q.By) < spec.minBy { + problems.add(path+".by", fmt.Sprintf("%s panels group by at least %d field", p.Viz, spec.minBy)) + } + if len(q.By) > spec.maxBy { + problems.add(path+".by", fmt.Sprintf("%s panels group by at most %d field(s)", p.Viz, spec.maxBy)) + } + byAliases := map[string]bool{} + for i, by := range q.By { + ref, err := sig.field(by) + if err != nil { + problems.add(fmt.Sprintf("%s.by[%d]", path, i), err.Error()) + continue + } + if byAliases[ref.alias()] { + problems.addHint(fmt.Sprintf("%s.by[%d]", path, i), fmt.Sprintf("two grouping fields produce the column %s", ref.alias()), "group by one of them") + } + byAliases[ref.alias()] = true + } + for _, m := range measures { + if byAliases[m.Alias] { + problems.addHint(path+".measures", fmt.Sprintf("measure %s has the same column name as a grouping field", m.Alias), "rename with as") + } + } + switch { + case spec.bucket && q.Bucket == "": + problems.add(path+".bucket", "timeseries panels need a bucket; use auto") + case !spec.bucket && q.Bucket != "": + problems.add(path+".bucket", fmt.Sprintf("%s panels do not take a bucket", p.Viz)) + case q.Bucket != "" && q.Bucket != "auto": + if _, ok := buckets[q.Bucket]; !ok { + problems.add(path+".bucket", "bucket must be auto or one of 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h, 1d") + } + } + if p.Viz == "heatmap" || p.Viz == "histogram" { + if q.Histogram == nil { + problems.addHint(path+".histogram", "distribution panels require a histogram", "spans: duration_ms/log2; metrics: value/explicit") + } else if (q.From != "spans" || q.Histogram.Field != "duration_ms" || q.Histogram.Buckets != "log2") && + (q.From != "metrics" || q.Histogram.Field != "value" || q.Histogram.Buckets != "explicit") { + problems.add(path+".histogram", "use spans duration_ms/log2 or metrics value/explicit") + } + if len(q.Measures) != 1 || q.Measures[0] != "count()" { + problems.addHint(path+".measures", "distribution counts require count()", "use count() as the observation weight") + } + + } else if q.Histogram != nil { + problems.add(path+".histogram", "histogram applies only to heatmap and histogram") + } + return measures, true +} + +func queryShapeAggregateTail(q *Query, viz, path string, measures []Measure, problems *Problems) { + if q.Limit < 0 || q.Limit > 1000 { + problems.add(path+".limit", "limit must be 0 to 1000") + } + if q.Sort != "" && viz != "logs" && viz != "traces" { + alias := strings.TrimPrefix(q.Sort, "+") + if !slices.ContainsFunc(measures, func(m Measure) bool { return m.Alias == alias }) { + problems.add(path+".sort", fmt.Sprintf("sort %q must name a measure alias", q.Sort)) + } + } + families := map[string]bool{} + for _, m := range measures { + families[unitFamilies[m.Unit]] = true + } + delete(families, "none") + if len(families) > 1 && viz != "table" && viz != "scatter" { + problems.add(path+".measures", "these measures have different units and would share one axis; split them into separate panels") + } + +} + +func queryShapeReduce(q *Query, spec vizSpec, viz, path string, problems *Problems) { + if spec.reduces && len(q.Measures) != 1 { + problems.add(path+".measures", fmt.Sprintf("%s panels show one measure", viz)) + } +} + +func queryShapeRows(q *Query, viz, path string, problems *Problems) { + if viz != "logs" && viz != "traces" && viz != "log_patterns" { + return + } + if q.Limit < 0 || q.Limit > 1000 { + problems.addHint(path+".limit", "limit must be 0 to 1000", "use a limit from 1 to 1000 or omit it for the default") + } + if q.Histogram != nil { + problems.addHint(path+".histogram", "histogram applies only to heatmap and histogram", "remove histogram or use a heatmap or histogram panel") + } + if viz == "traces" { + if q.From != "spans" { + problems.addHint(path+".from", "traces reads spans", "use query {from: spans}") + } + if q.Sort != "" && q.Sort != "duration_ms" && q.Sort != "errors" && q.Sort != "+start" { + problems.addHint(path+".sort", "traces sort is duration_ms, errors or +start", "use sort duration_ms, errors, +start or omit sort") + } + } else { + if q.From != "logs" { + problems.addHint(path+".from", "logs and log_patterns read logs", "use query {from: logs}") + } + } + if viz == "logs" && q.Sort != "" && q.Sort != "time" && q.Sort != "+time" { + problems.addHint(path+".sort", "logs sort is time or +time", "use sort time, +time or omit sort") + } + if viz == "log_patterns" { + if len(q.By) != 1 || q.By[0] != "body_template" { + problems.addHint(path+".by", "log_patterns groups by body_template", "use by [body_template]") + } + if len(q.Measures) != 1 || q.Measures[0] != "count()" { + problems.addHint(path+".measures", "log_patterns requires count()", "use measures [count()]") + } + if q.Sort != "" && q.Sort != "count" { + problems.addHint(path+".sort", "log_patterns sort is count", "use sort count or omit sort") + } + if q.Bucket != "" && q.Bucket != "auto" { + if _, ok := buckets[q.Bucket]; !ok { + problems.addHint(path+".bucket", "bucket must be auto or a supported interval", "use auto, 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h or 1d") + } + } + } + if viz == "logs" || viz == "traces" { + if len(q.Measures) > 0 { + problems.addHint(path+".measures", "fixed row projections do not take aggregate measures", "remove measures; use log_patterns for counts or a table for aggregates") + } + if len(q.By) > 0 { + problems.addHint(path+".by", "logs and traces panels do not group; use log_patterns or a table", "remove by or use log_patterns or a table") + } + if q.Bucket != "" { + problems.addHint(path+".bucket", "logs and traces panels do not take a bucket", "remove bucket") + } + } +} + +func queryShapeItems(q *Query, viz, path string, problems *Problems) { + if q == nil { + return + } + if viz == "scatter" && len(q.Measures) != 2 { + problems.addHint(path+".measures", "scatter requires exactly two measures", "select x and y measures in that order") + } + if viz == "state_timeline" { + if q != nil && q.Sort != "" { + problems.add(path+".sort", "state_timeline has fixed chronological ordering") + } + if q != nil && len(q.Measures) != 1 { + problems.add(path+".measures", "state_timeline requires one measure") + } + } +} diff --git a/internal/panel/shape_test.go b/internal/panel/shape_test.go new file mode 100644 index 00000000..b2c1e8d0 --- /dev/null +++ b/internal/panel/shape_test.go @@ -0,0 +1,105 @@ +package panel + +import ( + "reflect" + "slices" + "strings" + "testing" +) + +func TestQueryShapeMatchesValidateQueryProblems(t *testing.T) { + queries := []struct { + viz string + q Query + }{ + {"stat", Query{From: "spans", Measures: []string{"count()"}}}, + {"gauge", Query{From: "spans", Measures: []string{"count()", "rate()"}}}, + {"timeseries", Query{From: "spans", Measures: []string{"count()"}, By: []string{"service"}}}, + {"bar", Query{From: "spans", Measures: []string{"count()"}}}, + {"table", Query{From: "spans", Measures: []string{"count()"}, Sort: "wrong"}}, + {"heatmap", Query{From: "spans", Measures: []string{"count()"}, Bucket: "auto"}}, + {"histogram", Query{From: "spans", Measures: []string{"count()"}, Histogram: &Histogram{Field: "duration_ms", Buckets: "log2"}}}, + {"scatter", Query{From: "spans", Measures: []string{"count()"}, By: []string{"service"}}}, + {"state_timeline", Query{From: "spans", Measures: []string{"count()"}, By: []string{"service"}, Bucket: "auto", Sort: "count"}}, + {"logs", Query{From: "spans", Measures: []string{"count()"}, Sort: "wrong"}}, + {"log_patterns", Query{From: "logs", Measures: []string{"count()"}, By: []string{"service"}}}, + {"traces", Query{From: "spans", Sort: "+start", Where: []string{"service = 'api'"}}}, + } + for _, tc := range queries { + t.Run(tc.viz, func(t *testing.T) { + p := Panel{ID: "test", Title: "test", Viz: tc.viz, Query: &tc.q} + d := Dashboard{Name: "test", Panels: []Panel{p}} + original := tc.q + Normalize(&d) + // Shape never supplies defaults; compare against the original query. + tc.q = original + d.Panels[0].Query = &tc.q + var want Problems + for _, p := range Validate(&d) { + if strings.HasPrefix(p.Path, "panels[0].query.") { + p.Path = strings.TrimPrefix(p.Path, "panels[0].query.") + want = append(want, p) + } + } + got, _ := QueryShape(&tc.q, tc.viz, nil) + if !reflect.DeepEqual(got, want) { + t.Errorf("shape = %#v; validate = %#v", got, want) + } + }) + } +} + +func TestQueryShapeRequires(t *testing.T) { + q := &Query{From: "spans", Measures: []string{"count()"}} + for _, tc := range []struct { + viz string + want []VizRequirement + }{{"gauge", []VizRequirement{RequiresMinMax}}, {"state_timeline", []VizRequirement{RequiresThresholds}}, {"table", []VizRequirement{}}} { + _, got := QueryShape(q, tc.viz, nil) + if !slices.Equal(got, tc.want) { + t.Errorf("%s requires %v, want %v", tc.viz, got, tc.want) + } + } +} + +func TestQueryShapeCountIfDefaultAlias(t *testing.T) { + q := &Query{From: "spans", Measures: []string{"count_if(status = 'STATUS_CODE_ERROR')"}, Sort: "count_if"} + if problems, _ := QueryShape(q, "table", nil); len(problems) != 0 { + t.Fatalf("count_if shape: %v", problems) + } +} + +func TestCompatibleVizzesOnQueryAsWritten(t *testing.T) { + for _, tc := range []struct { + q Query + want []string + }{ + {Query{From: "spans", Where: []string{"kind = 'SPAN_KIND_SERVER'"}, Measures: []string{"count()"}, By: []string{"http_route"}}, []string{"bar", "table"}}, + {Query{From: "spans", Where: []string{"kind = 'SPAN_KIND_SERVER'"}, Measures: []string{"count()"}, By: []string{"http_route"}, Bucket: "auto"}, []string{"timeseries", "state_timeline"}}, + {Query{From: "spans", Where: []string{"status = 'STATUS_CODE_ERROR'"}}, []string{"traces"}}, + {Query{From: "logs"}, []string{"logs"}}, + {Query{From: "logs", Measures: []string{"count()"}, By: []string{"body_template"}}, []string{"bar", "table", "log_patterns"}}, + } { + var got []string + for _, c := range CompatibleVizzes(&tc.q, nil) { + got = append(got, c.Viz) + if c.Requires == nil { + t.Errorf("%s has null requirements", c.Viz) + } + } + if !slices.Equal(got, tc.want) { + t.Errorf("%+v compatible = %v, want %v", tc.q, got, tc.want) + } + } +} + +func TestExistingValidateBehaviourUnchanged(t *testing.T) { + q := &Query{From: "spans", Measures: []string{"count()"}, Where: []string{"service = $missing"}} + got, _ := QueryShape(q, "table", map[string]Variable{}) + if len(got) != 1 || got[0].Path != "where" || !strings.Contains(got[0].Message, "$missing is not a dashboard variable") { + t.Fatalf("variables = %#v", got) + } + if got, _ := QueryShape(q, "table", nil); len(got) != 0 { + t.Fatalf("nil declarations: %v", got) + } +} diff --git a/internal/panel/validate.go b/internal/panel/validate.go index f5380895..42363b7a 100644 --- a/internal/panel/validate.go +++ b/internal/panel/validate.go @@ -384,18 +384,9 @@ func validatePanel(p *Panel, path string, vars map[string]Variable, problems *Pr } } } - for _, ref := range varRefs(strings.Join(queryWhere(p), " ")) { - if _, ok := vars[ref]; !ok { - problems.addHint(path+".query.where", fmt.Sprintf("$%s is not a dashboard variable", ref), suggest(ref, mapKeys(vars))) - } - } -} - -func queryWhere(p *Panel) []string { - if p.Query == nil { - return nil + if p.Query != nil { + queryShapeVariables(p.Query, vars, path+".query", problems) } - return p.Query.Where } func mapKeys(vars map[string]Variable) []string { @@ -407,106 +398,14 @@ func mapKeys(vars map[string]Variable) []string { } func validateQuery(p *Panel, spec vizSpec, path string, problems *Problems) { - q := p.Query - if p.Viz == "logs" || p.Viz == "traces" || p.Viz == "log_patterns" { - // Fixed projections are checked field by field in validateRows; avoid - // duplicate aggregate-query Problems for the same rejected field. - if len(q.Where) > 16 { - problems.addHint(path+".where", "at most 16 filters per query", "remove filters until at most 16 remain") - } - for i, w := range q.Where { - if strings.TrimSpace(w) == "" || len(w) > 500 { - problems.addHint(fmt.Sprintf("%s.where[%d]", path, i), "filters are 1 to 500 characters", "use a nonempty filter of at most 500 characters") - } - } - return - } - if len(q.Where) > 16 { - problems.add(path+".where", "at most 16 filters per query") - } - sig, ok := lookupSignal(q.From) + measures, ok := queryShapeAggregate(p, spec, path, problems, false) if !ok { - problems.addHint(path+".from", fmt.Sprintf("unknown signal %q", q.From), "use spans, logs or metrics") return } - for i, w := range q.Where { - if strings.TrimSpace(w) == "" || len(w) > 500 { - problems.add(fmt.Sprintf("%s.where[%d]", path, i), "filters are 1 to 500 characters") - } - } - if (len(q.Measures) == 0 && p.Viz != "logs" && p.Viz != "traces" && p.Viz != "health" && p.Viz != "service_map") || len(q.Measures) > 6 { - problems.add(path+".measures", "a query has 1 to 6 measures; fixed logs and traces take none") - } - if len(q.Measures) > 1 && ((p.Viz == "timeseries" && len(q.By) > 0) || (p.Viz == "bar" && len(q.By) == 2)) { - problems.addHint(path+".measures", "grouped panels show one measure", "use one panel per measure, or remove by") - } - measures := parseMeasures(sig, q.Measures, path+".measures", problems) - if len(q.By) < spec.minBy { - problems.add(path+".by", fmt.Sprintf("%s panels group by at least %d field", p.Viz, spec.minBy)) - } - if len(q.By) > spec.maxBy { - problems.add(path+".by", fmt.Sprintf("%s panels group by at most %d field(s)", p.Viz, spec.maxBy)) - } - byAliases := map[string]bool{} - for i, by := range q.By { - ref, err := sig.field(by) - if err != nil { - problems.add(fmt.Sprintf("%s.by[%d]", path, i), err.Error()) - continue - } - if byAliases[ref.alias()] { - problems.addHint(fmt.Sprintf("%s.by[%d]", path, i), fmt.Sprintf("two grouping fields produce the column %s", ref.alias()), "group by one of them") - } - byAliases[ref.alias()] = true - } - for _, m := range measures { - if byAliases[m.Alias] { - problems.addHint(path+".measures", fmt.Sprintf("measure %s has the same column name as a grouping field", m.Alias), "rename with as") - } - } - switch { - case spec.bucket && q.Bucket == "": - problems.add(path+".bucket", "timeseries panels need a bucket; use auto") - case !spec.bucket && q.Bucket != "": - problems.add(path+".bucket", fmt.Sprintf("%s panels do not take a bucket", p.Viz)) - case q.Bucket != "" && q.Bucket != "auto": - if _, ok := buckets[q.Bucket]; !ok { - problems.add(path+".bucket", "bucket must be auto or one of 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h, 1d") - } - } - if p.Viz == "heatmap" || p.Viz == "histogram" { - if q.Histogram == nil { - problems.addHint(path+".histogram", "distribution panels require a histogram", "spans: duration_ms/log2; metrics: value/explicit") - } else if (q.From != "spans" || q.Histogram.Field != "duration_ms" || q.Histogram.Buckets != "log2") && - (q.From != "metrics" || q.Histogram.Field != "value" || q.Histogram.Buckets != "explicit") { - problems.add(path+".histogram", "use spans duration_ms/log2 or metrics value/explicit") - } - if len(q.Measures) != 1 || q.Measures[0] != "count()" { - problems.addHint(path+".measures", "distribution counts require count()", "use count() as the observation weight") - } - if p.SQL != "" { - problems.add(path+".sql", "distribution panels use a structured histogram") - } - } else if q.Histogram != nil { - problems.add(path+".histogram", "histogram applies only to heatmap and histogram") - } - if q.Limit < 0 || q.Limit > 1000 { - problems.add(path+".limit", "limit must be 0 to 1000") - } - if q.Sort != "" && p.Viz != "logs" && p.Viz != "traces" { - alias := strings.TrimPrefix(q.Sort, "+") - if !slices.ContainsFunc(measures, func(m Measure) bool { return m.Alias == alias }) { - problems.add(path+".sort", fmt.Sprintf("sort %q must name a measure alias", q.Sort)) - } - } - families := map[string]bool{} - for _, m := range measures { - families[unitFamilies[m.Unit]] = true - } - delete(families, "none") - if len(families) > 1 && p.Viz != "table" && p.Viz != "scatter" { - problems.add(path+".measures", "these measures have different units and would share one axis; split them into separate panels") + if (p.Viz == "heatmap" || p.Viz == "histogram") && p.SQL != "" { + problems.add(path+".sql", "distribution panels use a structured histogram") } + queryShapeAggregateTail(p.Query, p.Viz, path, measures, problems) if p.Options != nil && p.Options.Style == "stacked" { for _, m := range measures { if !m.Additive { @@ -515,9 +414,7 @@ func validateQuery(p *Panel, spec vizSpec, path string, problems *Problems) { } } } - if spec.reduces && len(q.Measures) != 1 { - problems.add(path+".measures", fmt.Sprintf("%s panels show one measure", p.Viz)) - } + queryShapeReduce(p.Query, spec, p.Viz, path, problems) } // Infer only recognizable semantics; ambiguous measures remain neutral. diff --git a/internal/telemetry/severity.go b/internal/telemetry/severity.go new file mode 100644 index 00000000..b75b41f9 --- /dev/null +++ b/internal/telemetry/severity.go @@ -0,0 +1,74 @@ +package telemetry + +import ( + "maps" + "slices" + "strings" +) + +// SeverityBands lists the six standard severity bands in ascending rank. +var SeverityBands = [...]string{"TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"} + +var severityAliases = map[string]string{ + "fatal": "FATAL", "crit": "FATAL", "critical": "FATAL", "emerg": "FATAL", "emergency": "FATAL", "alert": "FATAL", "panic": "FATAL", + "error": "ERROR", "err": "ERROR", "severe": "ERROR", "exception": "ERROR", + "warn": "WARN", "warning": "WARN", + "info": "INFO", "information": "INFO", "informational": "INFO", "notice": "INFO", + "debug": "DEBUG", "dbg": "DEBUG", "fine": "DEBUG", + "trace": "TRACE", "verbose": "TRACE", "finest": "TRACE", +} + +// SeverityAliases returns a copy of the lowercase synonym-to-band table. +func SeverityAliases() map[string]string { return maps.Clone(severityAliases) } + +// SeverityRank returns a standard band's ascending rank; unknown bands have none. +func SeverityRank(band string) (int, bool) { + rank := slices.Index(SeverityBands[:], band) + return rank, rank >= 0 +} + +// NormalizeSeverity maps a record onto the six OTel severity names, so that a +// search for ERROR finds every error however its emitter spelled it. +// +// Passing SeverityText through unchanged is what produced a store holding +// INFO, INFORMATION and "" for the same level: .NET writes "Information", +// Envoy's access logs carry no severity at all, and each spelling then answered +// a different query. severity_number is preferred because the specification +// makes it the authoritative field and the text the display form, and a record +// that carries neither is stored as UNSPECIFIED rather than as an empty string +// — the log-bucket query already labels that case UNSPECIFIED, and a level you +// can see in the chart should be one you can filter on. +func NormalizeSeverity(text string, number int32) string { + switch { + case number >= 21: + return "FATAL" + case number >= 17: + return "ERROR" + case number >= 13: + return "WARN" + case number >= 9: + return "INFO" + case number >= 5: + return "DEBUG" + case number >= 1: + return "TRACE" + } + return SeverityFromText(text) +} + +// SeverityFromText canonicalizes the spellings emitters use when they send no +// severity_number: OTel's own numbered short names (INFO2, WARN3), the syslog +// names, and the long forms favoured by .NET and Python. +func SeverityFromText(text string) string { + name := strings.ToUpper(strings.TrimSpace(text)) + name = strings.TrimRight(name, "0123456789") + if band, ok := severityAliases[strings.ToLower(name)]; ok { + return band + } + if name == "" { + return "UNSPECIFIED" + } + // An unrecognised level is still the emitter's own word for it, and + // discarding it would lose the only grading the record carries. + return name +} diff --git a/internal/telemetry/severity_test.go b/internal/telemetry/severity_test.go new file mode 100644 index 00000000..8b6712ac --- /dev/null +++ b/internal/telemetry/severity_test.go @@ -0,0 +1,50 @@ +package telemetry + +import "testing" + +func TestNormalizeSeverityNumberWins(t *testing.T) { + for _, tc := range []struct { + text string + number int32 + want string + }{ + {"WARN2", 14, "WARN"}, {"ERROR", 9, "INFO"}, {"FATAL", 0, "FATAL"}, + {"INFO2", 0, "INFO"}, {"warning", 0, "WARN"}, {"custom", 0, "CUSTOM"}, + {"", 0, "UNSPECIFIED"}, {"anything", 21, "FATAL"}, {"anything", 1, "TRACE"}, + } { + if got := NormalizeSeverity(tc.text, tc.number); got != tc.want { + t.Errorf("NormalizeSeverity(%q, %d) = %q, want %q", tc.text, tc.number, got, tc.want) + } + } +} + +func TestSeverityRankOrder(t *testing.T) { + for i, band := range []string{"TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"} { + if rank, ok := SeverityRank(band); !ok || rank != i { + t.Errorf("SeverityRank(%q) = %d, %v", band, rank, ok) + } + } + for _, band := range []string{"UNSPECIFIED", "CUSTOM"} { + if _, ok := SeverityRank(band); ok { + t.Errorf("SeverityRank(%q) succeeded", band) + } + } +} + +func TestSeverityAliasesMatchSeverityFromText(t *testing.T) { + aliases := SeverityAliases() + for _, a := range []string{"warning", "critical", "crit", "emerg", "emergency", "alert", "panic", "err", "severe", "exception", "information", "informational", "notice", "dbg", "fine", "verbose", "finest"} { + if _, ok := aliases[a]; !ok { + t.Errorf("missing alias %s", a) + } + } + for alias, band := range aliases { + if got := SeverityFromText(alias); got != band { + t.Errorf("SeverityFromText(%q) = %q, want %q", alias, got, band) + } + } + aliases["warning"] = "BROKEN" + if SeverityAliases()["warning"] != "WARN" { + t.Fatal("accessor exposes mutable table") + } +} diff --git a/scripts/go-deadcode.allowlist b/scripts/go-deadcode.allowlist index 9aa78301..ca01e549 100644 --- a/scripts/go-deadcode.allowlist +++ b/scripts/go-deadcode.allowlist @@ -1,2 +1,12 @@ # Exact symbolreviewed reason for genuine non-main entry points only. github.com/labstack/fanout/internal/auth.OAuthTokenPair.String fmt.Stringer security boundary: formatting token pairs must redact both credentials; not a callable product action. +github.com/labstack/fanout/internal/panel.SignalColumns FanQL catalog library entry point; production HTTP/MCP/reference consumers land in batch 1 Tasks 8–10. +github.com/labstack/fanout/internal/panel.LowCardinalityColumns FanQL completion/reference library entry point; production consumers land in batch 1 Tasks 7–10. +github.com/labstack/fanout/internal/panel.MeasureSpecs FanQL resolver/reference library entry point; production consumers land in batch 1 Tasks 8–10. +github.com/labstack/fanout/internal/panel.BucketNames FanQL completion/reference library entry point; production consumers land in batch 1 Tasks 7–10. +github.com/labstack/fanout/internal/panel.FilterFunctionNames FanQL resolver/reference library entry point; production consumers land in batch 1 Tasks 8–10. +github.com/labstack/fanout/internal/panel.Suggest FanQL resolver library entry point; production HTTP/MCP consumers land in batch 1 Tasks 8–9. +github.com/labstack/fanout/internal/panel.QueryShape FanQL shape-check library entry point; production HTTP/MCP consumers land in batch 1 Tasks 8–9. +github.com/labstack/fanout/internal/panel.CompatibleVizzes FanQL visualization compatibility library entry point; production HTTP consumers land in batch 1 Task 8. +github.com/labstack/fanout/internal/telemetry.SeverityAliases Shared FanQL vocabulary/reference library entry point; production consumers land in batch 1 Tasks 8–10. +github.com/labstack/fanout/internal/telemetry.SeverityRank FanQL severity range library entry point; production HTTP/MCP consumers land in batch 1 Tasks 8–9. From 9fdd4477e19df31dfc89b585a0416c6515df817c Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 16:01:03 -0700 Subject: [PATCH 05/30] feat(fanql): resolve fields, vocabularies and severity ranges against the catalog --- internal/fanql/ast.go | 7 +- internal/fanql/resolve.go | 620 +++++++++++++++++++++++++++++++++ internal/fanql/resolve_test.go | 306 ++++++++++++++++ internal/fanql/spellings.go | 37 ++ 4 files changed, 968 insertions(+), 2 deletions(-) create mode 100644 internal/fanql/resolve.go create mode 100644 internal/fanql/resolve_test.go create mode 100644 internal/fanql/spellings.go diff --git a/internal/fanql/ast.go b/internal/fanql/ast.go index f411fd65..ae005ab3 100644 --- a/internal/fanql/ast.go +++ b/internal/fanql/ast.go @@ -30,6 +30,7 @@ type Compare struct { Field Field Op string Value Value + Bands []string At Span } type In struct { @@ -43,6 +44,7 @@ type Between struct { Field Field Lo, Hi Value Negated bool + Bands []string At Span } type Like struct { @@ -77,8 +79,9 @@ type Comparison struct { Value Value } type FreeText struct { - Value Value - At Span + Value Value + At Span + column string // resolved search column: body on logs, operation on spans } // RawExpr is a raw SQL filter entry. Raw names its lexical token kind. diff --git a/internal/fanql/resolve.go b/internal/fanql/resolve.go new file mode 100644 index 00000000..8d7912f8 --- /dev/null +++ b/internal/fanql/resolve.go @@ -0,0 +1,620 @@ +package fanql + +import ( + "fmt" + "slices" + "sort" + "strings" + + "github.com/labstack/fanout/internal/panel" + "github.com/labstack/fanout/internal/telemetry" +) + +type Notice struct { + Path string `json:"path"` + Message string `json:"message"` + Span *panel.TextSpan `json:"span,omitempty"` +} +type ResolveOptions struct { + Viz string + Variables []panel.Variable + Schema *panel.Schema +} +type Resolved struct { + Query *Query + Compatible []panel.VizCompat + Edits []VizEdit + Notices []Notice +} +type VizEdit struct { + Viz string `json:"viz"` + Text string `json:"text"` +} + +// Installed by the lowering layer. Resolution itself never executes SQL. +var resolveLower func(*Resolved) (panel.Query, panel.Problems) +var resolvePrint func(*Query) string + +type resolver struct { + opts ResolveOptions + out *Resolved + problems panel.Problems + countIf bool + path string +} + +// Resolve annotates fields and values in place, retaining entry boundaries. +func Resolve(q *Query, opts ResolveOptions) (*Resolved, panel.Problems) { + r := &resolver{opts: opts, out: &Resolved{Query: q, Notices: []Notice{}, Compatible: []panel.VizCompat{}, Edits: []VizEdit{}}} + if q == nil { + return nil, panel.Problems{{Path: "text", Message: "a query is required"}} + } + for i, e := range q.Where { + r.path = fmt.Sprintf("where[%d]", i) + r.expr(e) + } + if s := q.Stage; s != nil { + if s.Histogram != nil { + r.path = "histogram.field" + r.field(s.Histogram) + } + for i := range s.By { + r.path = fmt.Sprintf("by[%d]", i) + r.field(&s.By[i]) + } + aliases := map[string]bool{} + for i := range s.Measures { + m := &s.Measures[i] + r.path = fmt.Sprintf("measures[%d]", i) + r.measure(m.Expr) + if m.Alias != "" && !aliasName.MatchString(m.Alias) { + r.issue(m.At, fmt.Sprintf("alias %q must be lowercase letters, digits and underscores", m.Alias)) + } + name := measureAlias(*m, s.Measures) + if aliases[name] { + r.issue(m.At, "two measures are named "+name+"; add distinct aliases with as") + } + aliases[name] = true + } + } + r.sort() + if len(r.problems) == 0 && resolveLower != nil { + pq, ps := resolveLower(r.out) + r.problems = append(r.problems, ps...) + vars := map[string]panel.Variable(nil) + if opts.Variables != nil { + vars = map[string]panel.Variable{} + for _, v := range opts.Variables { + vars[v.Name] = v + } + } + if opts.Viz != "" { + ps, _ = panel.QueryShape(&pq, opts.Viz, vars) + for _, p := range ps { + p.Span = textSpan(queryPathSpan(q, p.Path)) + r.problems = append(r.problems, p) + } + } + r.out.Compatible = panel.CompatibleVizzes(&pq, vars) + if pq.Bucket == "" && q.Stage != nil && q.Stage.Histogram == nil { + pq.Bucket = "auto" + if ps, _ := panel.QueryShape(&pq, "timeseries", vars); len(ps) == 0 && resolvePrint != nil { + r.out.Edits = append(r.out.Edits, VizEdit{Viz: "timeseries", Text: resolvePrint(q) + " every auto"}) + } + } + } + sort.SliceStable(r.problems, func(i, j int) bool { + return r.problems[i].Span != nil && r.problems[j].Span != nil && r.problems[i].Span.Start < r.problems[j].Span.Start + }) + if len(r.problems) > MaxProblems { + r.problems = append(r.problems[:MaxProblems], panel.Problem{Path: "text", Message: messages["more"], Span: r.problems[MaxProblems].Span}) + } + if len(r.problems) > 0 { + return nil, r.problems + } + return r.out, nil +} + +func textSpan(s Span) *panel.TextSpan { return &panel.TextSpan{Start: s.Start, End: s.End} } +func (r *resolver) issue(at Span, message string) { + r.problems = append(r.problems, panel.Problem{Path: r.path, Message: message, Span: textSpan(at)}) +} +func (r *resolver) notice(at Span, message string) { + r.out.Notices = append(r.out.Notices, Notice{Path: r.path, Message: message, Span: textSpan(at)}) +} + +func (r *resolver) field(f *Field) { + if f.Ref != nil { + return + } + key := f.Key + scope := f.Scope + if strings.HasPrefix(key, "$__") { + r.issue(f.At, messages["variable"]) + } + if scope == "" && !f.Bracket && strings.EqualFold(key, "duration") { + key = "duration_ms" + } + columns, _ := panel.SignalColumns(r.out.Query.Source) + if scope == "" && !f.Bracket && !strings.Contains(key, ".") { + for _, c := range columns { + if strings.EqualFold(key, c.Name) { + if c.Type == panel.TypeMap { + r.issue(f.At, c.Name+" is a map; use "+c.Name+"['key']") + } + f.Ref = &FieldRef{Column: c.Name, Type: c.Type, Unit: c.Unit} + return + } + } + } + if scope == "" { + scope = "attributes" + } + if !f.Bracket && !identifierPath.MatchString(key) { + r.issue(f.At, fmt.Sprintf("%q needs brackets", key)) + } + f.Ref = &FieldRef{Column: scope, Key: key, Type: panel.TypeString, Unit: "none"} + if f.Scope == "" && !f.Bracket && !strings.Contains(key, ".") { + message := fmt.Sprintf("%q is not a %s column; reading attributes['%s']", key, r.out.Query.Source, key) + for _, m := range panel.MeasureSpecs() { + if strings.EqualFold(m.Name, key) { + message = fmt.Sprintf("%q is a measure, not a %s column; reading attributes['%s']", key, r.out.Query.Source, key) + break + } + } + var names []string + for _, c := range columns { + names = append(names, c.Name) + } + if hint := panel.Suggest(strings.ToLower(key), names); hint != "" { + message += "; " + hint + } + r.notice(f.At, message) + } +} + +func (r *resolver) expr(e Expr) { + switch x := e.(type) { + case *And: + for _, v := range x.Terms { + r.expr(v) + } + case *Or: + for _, v := range x.Terms { + r.expr(v) + } + case *Not: + r.expr(x.X) + case *Compare: + r.field(&x.Field) + r.value(&x.Field, &x.Value, x.Op, false) + if x.Field.Ref.Column == "severity" && x.Field.Ref.Key == "" && isRange(x.Op) { + x.Bands = r.bands(x.Field, x.Op, x.Value, nil) + } + case *In: + r.field(&x.Field) + if x.Variable != "" { + r.variable("$"+x.Variable, x.Field.Key, x.At, true) + } + for i := range x.Values { + r.value(&x.Field, &x.Values[i], "in", true) + } + case *Between: + r.field(&x.Field) + r.value(&x.Field, &x.Lo, "between", false) + r.value(&x.Field, &x.Hi, "between", false) + if x.Field.Ref.Column == "severity" && x.Field.Ref.Key == "" { + x.Bands = r.bands(x.Field, "between", x.Lo, &x.Hi) + } + case *Like: + r.field(&x.Field) + x.Pattern.Stored = x.Pattern.Text + case *Exists: + r.field(&x.Field) + case *IsNull: + r.field(&x.Field) + case *Call: + r.call(x) + case *FreeText: + x.Value.Stored = x.Value.Text + x.column = "body" + if r.out.Query.Source == "spans" { + x.column = "operation" + } + if r.out.Query.Source == "metrics" { + r.issue(x.At, "free text needs a field on metrics; use name:http.server.duration") + } + cols, _ := panel.SignalColumns(r.out.Query.Source) + for _, c := range cols { + if strings.EqualFold(c.Name, x.Value.Text) { + r.notice(x.At, fmt.Sprintf("%q is a field; did you mean %s:?", x.Value.Text, c.Name)) + break + } + } + case *RawExpr: + // SQL is retained verbatim; the panel gate checks its syntax at execution. + for _, tok := range Lex(x.Text) { + if tok.Kind == Word && strings.HasPrefix(tok.Text, "$") { + r.variable(tok.Text, "", x.At, false) + } + } + } +} + +func isRange(op string) bool { + return op == ">" || op == ">=" || op == "<" || op == "<=" || op == "between" +} +func (r *resolver) value(f *Field, v *Value, op string, multi bool) { + v.Stored = v.Text + if v.Kind == VariableValue { + r.variable(v.Text, f.Key, v.At, multi) + return + } + ref := f.Ref + if ref.Column == "http_status_code" && ref.Key == "" && isRange(op) { + ref.CompareAs = "integer" + } + if v.Kind == DurationValue { + if !strings.EqualFold(f.Key, "duration") || f.Scope != "" { + text := v.Text + for _, u := range []string{"us", "ms", "s", "m", "h"} { + if strings.HasSuffix(strings.ToLower(text), u) { + text = text[:len(text)-len(u)] + break + } + } + r.issue(v.At, "units apply to duration only; write "+f.Key+op+text) + return + } + n, ok := durationMS(v.Text) + if !ok { + r.issue(v.At, "duration needs a unit; e.g. duration>500ms") + } else if n < 0 { + r.issue(v.At, "durations are not negative") + } + return + } + if strings.EqualFold(f.Key, "duration") && f.Scope == "" { + r.issue(v.At, "duration needs a unit; e.g. duration>500ms") + return + } + if ref.Type == panel.TypeTime && ref.Key == "" { + if !isRange(op) { + r.issue(f.At, fmt.Sprintf("%q is a time column; compare it with > or <", ref.Column)) + } else if v.Kind != StringValue || !timestamp(v.Text) { + r.issue(v.At, "time needs a quoted timestamp in RFC 3339 or YYYY-MM-DD HH:MM:SS form (optional fraction and offset)") + } + return + } + if ref.Type == panel.TypeNumber && ref.Key == "" && v.Kind != NumberValue { + r.issue(v.At, ref.Column+" needs a number") + return + } + if v.Kind == BooleanValue { + v.Stored = strings.ToLower(v.Text) + } + if v.Kind == StringValue || !(op == ":" || op == "=" || op == "!=" || op == "<>" || op == "in") || ref.Key != "" { + return + } + var table map[string]string + var choices string + switch ref.Column { + case "status": + if r.out.Query.Source == "spans" { + table = statusAliases + choices = "status:error, status:ok or status:unset" + } + case "kind": + if r.out.Query.Source == "spans" { + table = kindAliases + choices = "kind:server, kind:client, kind:internal, kind:producer, kind:consumer or kind:unspecified" + } + case "type": + if r.out.Query.Source == "metrics" { + table = typeAliases + choices = "type:gauge, type:counter, type:updown, type:histogram or type:summary" + } + case "severity": + v.Stored = telemetry.SeverityFromText(v.Text) + if _, ok := telemetry.SeverityRank(v.Stored); !ok && v.Stored != "UNSPECIFIED" && r.opts.Schema != nil { + for _, c := range r.opts.Schema.Signals["logs"].Columns { + if c.Name == "severity" { + var vals []string + for _, v := range c.Values { + vals = append(vals, v.Value) + } + if len(vals) > 0 { + r.notice(v.At, "not a standard level; stored levels in this window: "+strings.Join(vals, ", ")) + } + } + } + } + return + } + if table != nil { + for a, s := range table { + if strings.EqualFold(v.Text, a) || strings.EqualFold(v.Text, s) { + v.Stored = s + return + } + } + r.issue(v.At, fmt.Sprintf("unknown %s %q; use %s", ref.Column, v.Text, choices)) + } +} + +func (r *resolver) bands(f Field, op string, lo Value, hi *Value) []string { + level := telemetry.SeverityFromText(lo.Text) + rank, ok := telemetry.SeverityRank(level) + if !ok { + r.issue(lo.At, fmt.Sprintf("%q has no severity rank; use trace, debug, info, warn, error or fatal", lo.Text)) + return nil + } + start, end := 0, len(telemetry.SeverityBands)-1 + switch op { + case ">": + start = rank + 1 + case ">=": + start = rank + case "<": + end = rank - 1 + case "<=": + end = rank + case "between": + start = rank + var good bool + end, good = telemetry.SeverityRank(telemetry.SeverityFromText(hi.Text)) + if !good { + r.issue(hi.At, fmt.Sprintf("%q has no severity rank; use trace, debug, info, warn, error or fatal", hi.Text)) + return nil + } + if start > end { + r.issue(lo.At, "between needs the lower level first: severity between "+strings.ToLower(hi.Text)+" and "+strings.ToLower(lo.Text)) + return nil + } + } + if start > end { + r.issue(lo.At, fmt.Sprintf("severity%s%s matches no level; use severity:%s", op, lo.Text, strings.ToLower(level))) + return nil + } + return slices.Clone(telemetry.SeverityBands[start : end+1]) +} + +func (r *resolver) variable(name, field string, at Span, multi bool) { + if r.countIf { + r.issue(at, "variables are not allowed inside count_if") + return + } + if strings.HasPrefix(name, "$__") { + r.issue(at, messages["variable"]) + return + } + if r.opts.Variables == nil { + r.notice(at, "declared variables are needed to check "+name) + return + } + var names []string + for _, v := range r.opts.Variables { + names = append(names, v.Name) + if "$"+v.Name == name { + if v.Multi && !multi { + r.issue(at, name+" holds several values; use "+field+" in "+name) + } + return + } + } + r.issue(at, "undeclared variable "+name+"; declared variables: "+strings.Join(names, ", ")) +} + +func (r *resolver) call(c *Call) { + if !slices.Contains(panel.FilterFunctionNames(), c.Name) { + r.issue(c.At, "function "+c.Name+" is not allowed in a filter") + return + } + predicate := c.Name == "starts_with" || c.Name == "contains" || c.Name == "regexp_matches" + want := 1 + if predicate { + want = 2 + } + if len(c.Args) != want { + r.issue(c.At, fmt.Sprintf("%s takes %d argument(s), got %d", c.Name, want, len(c.Args))) + } + for i := range c.Args { + a := &c.Args[i] + if i == 0 { + if a.Field != nil { + r.field(a.Field) + } else if a.Call != nil { + r.call(a.Call) + } else { + r.issue(c.At, c.Name+" needs a field") + } + } else if a.Value == nil || a.Value.Kind != StringValue { + r.issue(c.At, c.Name+" needs a quoted string") + } else { + a.Value.Stored = a.Value.Text + } + } + if predicate && c.Cmp != nil { + r.issue(c.At, "predicates are not compared; use "+c.Name+"(...) alone") + } + if !predicate && c.Cmp == nil { + r.issue(c.At, c.Name+"(...) needs a comparison") + } + if c.Cmp != nil { + c.Cmp.Value.Stored = c.Cmp.Value.Text + } +} + +func (r *resolver) measure(e MExpr) { + switch x := e.(type) { + case *MCall: + var spec *panel.MeasureSpec + for _, s := range panel.MeasureSpecs() { + if s.Name == x.Name { + s := s + spec = &s + break + } + } + if spec == nil { + r.issue(x.At, "unknown function "+x.Name) + return + } + if len(spec.Signals) > 0 && !slices.Contains(spec.Signals, r.out.Query.Source) { + r.issue(x.At, x.Name+" is not available for "+r.out.Query.Source) + return + } + args := len(x.Args) + if x.Name == "count" && args == 1 && x.Args[0].Star { + args = 0 + } + if args != spec.Args { + r.issue(x.At, fmt.Sprintf("%s takes %d argument(s), got %d; e.g. %s(duration)", x.Name, spec.Args, args, x.Name)) + return + } + for i := range x.Args { + a := &x.Args[i] + if a.Field != nil { + r.field(a.Field) + if spec.Numeric && a.Field.Ref.Key == "" && a.Field.Ref.Type != panel.TypeNumber { + r.issue(a.At, fmt.Sprintf("%s needs a numeric field; %s is %s", x.Name, a.Field.Key, a.Field.Ref.Type)) + } + } + } + if x.Name == "quantile" && (len(x.Args) < 2 || x.Args[1].Number == nil || *x.Args[1].Number <= 0 || *x.Args[1].Number >= 1) { + r.issue(x.At, "quantile q must be a number between 0 and 1") + } + case *MCountIf: + if r.out.Query.Source == "metrics" { + r.issue(x.At, "measure arithmetic is not available for metrics") + return + } + r.countIf = true + r.expr(x.Filter) + r.countIf = false + case *MBinary: + if r.out.Query.Source == "metrics" { + r.issue(x.At, "measure arithmetic is not available for metrics") + return + } + r.measure(x.L) + r.measure(x.R) + case *MNeg: + if r.out.Query.Source == "metrics" { + r.issue(x.At, "measure arithmetic is not available for metrics") + return + } + r.measure(x.X) + } +} + +func measureAlias(m Measure, all []Measure) string { + if m.Alias != "" { + return m.Alias + } + if _, ok := m.Expr.(*MCountIf); ok { + return "count_if" + } + c, ok := m.Expr.(*MCall) + if !ok { + return "" + } + n := 0 + for _, v := range all { + if x, ok := v.Expr.(*MCall); ok && x.Name == c.Name && v.Alias == "" { + n++ + } + } + if n > 1 && len(c.Args) > 0 && c.Args[0].Field != nil { + f := c.Args[0].Field + key := f.Key + if f.Ref != nil { + key = f.Ref.Column + if f.Ref.Key != "" { + key = f.Ref.Key + } + } + var b strings.Builder + for _, ch := range strings.ToLower(key) { + if ch >= 'a' && ch <= 'z' || ch >= '0' && ch <= '9' { + b.WriteRune(ch) + } else { + b.WriteByte('_') + } + } + return c.Name + "_" + strings.Trim(b.String(), "_") + } + return c.Name +} + +func (r *resolver) sort() { + q := r.out.Query + r.path = "sort" + if q.Sort != nil { + s := q.Sort + switch r.opts.Viz { + case "traces": + if !(s.Key == "duration" && !s.Ascending || s.Key == "duration_ms" && !s.Ascending || s.Key == "errors" && !s.Ascending || s.Key == "start" && s.Ascending) { + r.issue(s.At, "traces sort descending by duration, by errors, or ascending by start only") + } + case "logs": + if s.Key != "time" { + r.issue(s.At, "logs sort by time or +time only") + } + case "log_patterns": + if s.Key != "count" || s.Ascending { + r.issue(s.At, "log_patterns sort by count only") + } + default: + if q.Stage != nil && q.Stage.Histogram == nil { + var aliases []string + for _, m := range q.Stage.Measures { + aliases = append(aliases, measureAlias(m, q.Stage.Measures)) + } + if !slices.Contains(aliases, s.Key) { + r.issue(s.At, fmt.Sprintf("sort %q must name a measure alias; aliases here: %s", s.Key, strings.Join(aliases, ", "))) + } + } + } + if s.Key == "errors" && q.Source == "spans" { + r.notice(s.At, "sort errors also filters to error spans; new queries: write status:error … sort duration") + } + } + if (q.Sort != nil || q.Limit != nil) && slices.Contains([]string{"timeseries", "heatmap", "state_timeline"}, r.opts.Viz) || q.Limit != nil && slices.Contains([]string{"stat", "gauge"}, r.opts.Viz) { + at := q.Span + if q.Sort != nil { + at = q.Sort.At + } else if q.Limit != nil { + at = q.Limit.At + } + r.notice(at, "sort does not apply to bucketed series; series are chosen by top (options)") + } +} + +func queryPathSpan(q *Query, path string) Span { + var i int + if _, err := fmt.Sscanf(path, "where[%d]", &i); err == nil && i >= 0 && i < len(q.Where) { + return q.Where[i].Span() + } + if q.Stage != nil { + if _, err := fmt.Sscanf(path, "measures[%d]", &i); err == nil && i >= 0 && i < len(q.Stage.Measures) { + return q.Stage.Measures[i].At + } + if _, err := fmt.Sscanf(path, "by[%d]", &i); err == nil && i >= 0 && i < len(q.Stage.By) { + return q.Stage.By[i].At + } + if path == "bucket" { + return q.Stage.At + } + } + if path == "sort" && q.Sort != nil { + return q.Sort.At + } + if path == "limit" && q.Limit != nil { + return q.Limit.At + } + if path == "from" { + return q.SourceSpan + } + return q.Span +} diff --git a/internal/fanql/resolve_test.go b/internal/fanql/resolve_test.go new file mode 100644 index 00000000..6bc9dcbf --- /dev/null +++ b/internal/fanql/resolve_test.go @@ -0,0 +1,306 @@ +package fanql + +import ( + "reflect" + "strings" + "testing" + + "github.com/labstack/fanout/internal/panel" +) + +func resolvedText(t *testing.T, text string, opts ResolveOptions) (*Resolved, panel.Problems) { + t.Helper() + q, ps := Parse(text, "") + if len(ps) != 0 { + t.Fatalf("parse %q: %v", text, ps) + } + return Resolve(q, opts) +} + +func TestResolveSingleSegmentFieldIsColumnOrAttribute(t *testing.T) { + for _, tt := range []struct { + text, column, key string + typ panel.FieldType + notice string + }{ + {"spans where value>-3", "attributes", "value", panel.TypeString, `"value" is not a spans column; reading attributes['value']`}, + {"metrics where value>-3", "value", "", panel.TypeNumber, ""}, + {"metrics where rate:x", "attributes", "rate", panel.TypeString, `"rate" is a measure, not a metrics column; reading attributes['rate']`}, + {"spans where Service:api", "service", "", panel.TypeString, ""}, + {"spans where servce:api", "attributes", "servce", panel.TypeString, "did you mean service?"}, + } { + t.Run(tt.text, func(t *testing.T) { + r, ps := resolvedText(t, tt.text, ResolveOptions{}) + if len(ps) > 0 { + t.Fatal(ps) + } + f := r.Query.Where[0].(*Compare).Field.Ref + if f.Column != tt.column || f.Key != tt.key || f.Type != tt.typ { + t.Fatalf("ref %#v", f) + } + if tt.notice == "" { + if len(r.Notices) != 0 { + t.Fatal(r.Notices) + } + } else if len(r.Notices) == 0 || !strings.Contains(r.Notices[0].Message, tt.notice) { + t.Fatal(r.Notices) + } + }) + } +} + +func TestResolveDottedAndPrefixedKeys(t *testing.T) { + for _, tt := range []struct{ field, column, key string }{ + {"resource.k8s.pod.name", "resource", "k8s.pod.name"}, {"attributes.http.target", "attributes", "http.target"}, + {"attributes['resource.k']", "attributes", "resource.k"}, {"HTTP.Target", "attributes", "HTTP.Target"}, + } { + r, ps := resolvedText(t, "spans where "+tt.field+":x", ResolveOptions{}) + if len(ps) > 0 { + t.Fatal(ps) + } + f := r.Query.Where[0].(*Compare).Field.Ref + if f.Column != tt.column || f.Key != tt.key { + t.Fatal(f) + } + } + r, ps := resolvedText(t, "spans | count_distinct(user.id), p95(resource.k)", ResolveOptions{}) + if len(ps) > 0 { + t.Fatal(ps) + } + if r.Query.Stage.Measures[0].Expr.(*MCall).Args[0].Field.Ref.Key != "user.id" || r.Query.Stage.Measures[1].Expr.(*MCall).Args[0].Field.Ref.Column != "resource" { + t.Fatal(r.Query.Stage) + } + r, ps = resolvedText(t, "metrics | last(value) by resource.k8s.pod.name", ResolveOptions{}) + if len(ps) > 0 || r.Query.Stage.By[0].Ref.Key != "k8s.pod.name" { + t.Fatal(r, ps) + } + _, ps = resolvedText(t, "spans where x-y.z:1", ResolveOptions{}) + if len(ps) == 0 || ps[0].Message != `"x-y.z" needs brackets` { + t.Fatal(ps) + } +} + +func TestResolveVocabularies(t *testing.T) { + for _, tt := range []struct{ text, want string }{ + {"spans where status:error", "STATUS_CODE_ERROR"}, {"spans where status:STATUS_CODE_ERROR", "STATUS_CODE_ERROR"}, {`spans where status:"error"`, "error"}, + {"spans where kind:server", "SPAN_KIND_SERVER"}, {"metrics where type:counter", "counter"}, {"logs where severity:warning", "WARN"}, {"logs where severity:Error", "ERROR"}, {"logs where severity ~ error", "error"}, + } { + r, ps := resolvedText(t, tt.text, ResolveOptions{}) + if len(ps) > 0 { + t.Fatal(ps) + } + if v := r.Query.Where[0].(*Compare).Value.Stored; v != tt.want { + t.Fatalf("%s: %s", tt.text, v) + } + } + r, ps := resolvedText(t, "spans where status in (error, ok)", ResolveOptions{}) + if len(ps) > 0 { + t.Fatal(ps) + } + if got := r.Query.Where[0].(*In).Values; got[0].Stored != "STATUS_CODE_ERROR" || got[1].Stored != "STATUS_CODE_OK" { + t.Fatal(got) + } + schema := &panel.Schema{Signals: map[string]panel.SignalSchema{"logs": {Columns: []panel.ColumnSchema{{Field: panel.Field{Name: "severity"}, Values: []panel.Option{{Value: "ERROR"}, {Value: "INFO"}}}}}}} + r, ps = resolvedText(t, "logs where severity:custom", ResolveOptions{Schema: schema}) + if len(ps) > 0 || r.Query.Where[0].(*Compare).Value.Stored != "CUSTOM" || len(r.Notices) != 1 || r.Notices[0].Message != "not a standard level; stored levels in this window: ERROR, INFO" { + t.Fatal(r, ps) + } +} + +func TestResolveSeverityRanges(t *testing.T) { + for _, tt := range []struct { + text string + want []string + }{ + {"severity>=warn", []string{"WARN", "ERROR", "FATAL"}}, {"severity>warn", []string{"ERROR", "FATAL"}}, + {"severity 0 { + t.Fatal(ps) + } + var bands []string + switch x := r.Query.Where[0].(type) { + case *Compare: + bands = x.Bands + case *Between: + bands = x.Bands + } + if !reflect.DeepEqual(bands, tt.want) { + t.Fatal(bands, tt.want) + } + } + r, ps := resolvedText(t, "spans where http_status_code>=warn", ResolveOptions{}) + if len(ps) > 0 || r.Query.Where[0].(*Compare).Bands != nil { + t.Fatal(r, ps) + } +} + +func TestResolveTypedLiterals(t *testing.T) { + for _, text := range []string{"spans where duration_ms>500", `spans where start_time>"2026-10-29T10:00:00Z"`, `spans where start_time>"2026-10-29 10:00:00"`} { + _, ps := resolvedText(t, text, ResolveOptions{}) + if len(ps) > 0 { + t.Fatal(ps) + } + } + for _, tt := range []struct{ text, want string }{{"spans where http_status_code>=500", "integer"}, {"spans where http_status_code:500", ""}} { + r, ps := resolvedText(t, tt.text, ResolveOptions{}) + if len(ps) > 0 || r.Query.Where[0].(*Compare).Field.Ref.CompareAs != tt.want { + t.Fatal(r, ps) + } + } +} + +func TestResolveFilterFunctions(t *testing.T) { + for _, text := range []string{`logs where length(body)>1000`, `spans where lower(service) = "api"`, `spans where starts_with(http_route, "/api")`, `logs where regexp_matches(body, "error.*")`} { + if _, ps := resolvedText(t, text, ResolveOptions{}); len(ps) != 0 { + t.Fatal(text, ps) + } + } +} + +func TestResolveMeasures(t *testing.T) { + r, ps := resolvedText(t, `spans | count_distinct(flag)`, ResolveOptions{}) + if len(ps) != 0 || len(r.Notices) != 1 || r.Query.Stage.Measures[0].Expr.(*MCall).Args[0].Field.Ref.Key != "flag" { + t.Fatal(r, ps) + } + for _, text := range []string{`spans | count(*)`, `spans | quantile(duration, 0.999) as q`, `spans | count_if(status:error)`} { + if _, ps := resolvedText(t, text, ResolveOptions{}); len(ps) != 0 { + t.Fatal(text, ps) + } + } +} + +func TestResolveDiagnostics(t *testing.T) { + for _, tt := range []struct{ text, want string }{ + {"spans where status:fail", `unknown status "fail"; use status:error, status:ok or status:unset`}, + {"spans where kind:http", "use kind:server"}, + {"logs where severity>fatal", "severity>fatal matches no level; use severity:fatal"}, + {"logs where severity=custom", `"custom" has no severity rank; use trace, debug, info, warn, error or fatal`}, + {"logs where severity>=unspecified", `"unspecified" has no severity rank`}, + {"spans where http_status_code>500ms", "units apply to duration only; write http_status_code>500"}, + {"spans where duration>500", "duration needs a unit; e.g. duration>500ms"}, + {"spans where duration>-1ms", "durations are not negative"}, + {"spans where duration>1h30m", "duration needs a unit"}, + {"spans where duration_ms:true", "duration_ms needs a number"}, + {"logs where time:x", `"time" is a time column; compare it with > or <`}, + {`spans where start_time>"yesterday"`, "RFC 3339"}, + {"metrics where timeout", "free text needs a field on metrics; use name:http.server.duration"}, + {"spans where P95(Duration)", "function p95 is not allowed in a filter"}, + {"spans where starts_with(http_route, /api)", "starts_with needs a quoted string"}, + {"logs where length(body)", "length(...) needs a comparison"}, + {"spans where lower(k)", "lower(...) needs a comparison"}, + {`spans where starts_with(http_route, "/api") > 1`, "predicates are not compared"}, + {"spans | p95(service)", "p95 needs a numeric field; service is string"}, + {"spans | p95()", "p95 takes 1 argument(s), got 0; e.g. p95(duration)"}, + {"spans | count() as P95", `alias "P95" must be lowercase letters, digits and underscores`}, + {"spans | count(), count()", "two measures are named count; add distinct aliases with as"}, + {"metrics | error_rate()", "error_rate is not available for metrics"}, + {"spans | last(value)", "last is not available for spans"}, + {"spans | count_if(service:$s) as n", "variables are not allowed inside count_if"}, + {"metrics | count_if(name:x) as n", "measure arithmetic is not available for metrics"}, + {"metrics | -avg(value) as neg", "measure arithmetic is not available for metrics"}, + {"spans | quantile(duration, 2)", "quantile q must be a number between 0 and 1"}, + {"spans | count() by service sort p95", `sort "p95" must name a measure alias; aliases here: count`}, + {"spans where $__window:x", "$__ names are reserved"}, + } { + t.Run(tt.text, func(t *testing.T) { + _, ps := resolvedText(t, tt.text, ResolveOptions{}) + if len(ps) == 0 || !strings.Contains(ps[0].Message, tt.want) || ps[0].Span == nil { + t.Fatalf("want %q: %v", tt.want, ps) + } + }) + } + // These syntax diagnostics belong to the existing parser, before resolution. + for _, text := range []string{"spans | count_distinct(x-y)", "spans | count() by a, b, c, d"} { + if _, ps := Parse(text, ""); len(ps) == 0 { + t.Fatal(text) + } + } +} + +func TestResolveSortKeys(t *testing.T) { + for _, tt := range []struct { + text, viz string + bad bool + notice string + }{ + {"spans sort +duration", "traces", true, ""}, {"spans sort duration", "traces", false, ""}, {"spans sort errors", "traces", false, "sort errors also filters to error spans; new queries: write status:error … sort duration"}, + {"spans sort +start", "traces", false, ""}, {"logs sort time", "logs", false, ""}, {"logs sort +time", "logs", false, ""}, {"logs sort duration", "logs", true, ""}, + {"logs | count() by body_template sort count", "log_patterns", false, ""}, {"logs | count() by body_template sort rate", "log_patterns", true, ""}, + {"spans | count() every 1m sort count", "timeseries", false, "sort does not apply to bucketed series; series are chosen by top (options)"}, {"spans | count() every 1m sort count", "", false, ""}, + } { + r, ps := resolvedText(t, tt.text, ResolveOptions{Viz: tt.viz}) + if tt.bad { + if len(ps) == 0 { + t.Fatal(tt.text) + } + continue + } + if len(ps) > 0 { + t.Fatal(ps) + } + if tt.notice != "" && (len(r.Notices) == 0 || r.Notices[len(r.Notices)-1].Message != tt.notice) { + t.Fatal(r.Notices) + } + if tt.notice == "" && len(r.Notices) > 0 { + t.Fatal(r.Notices) + } + } +} + +func TestResolveVariables(t *testing.T) { + opts := ResolveOptions{Variables: []panel.Variable{{Name: "service", Kind: "query"}, {Name: "svcs", Kind: "query", Multi: true}}} + for _, tt := range []struct{ text, want string }{{"service:$region", "service, svcs"}, {"service:$svcs", "$svcs holds several values; use service in $svcs"}} { + _, ps := resolvedText(t, "spans where "+tt.text, opts) + if len(ps) == 0 || !strings.Contains(ps[0].Message, tt.want) { + t.Fatal(ps) + } + } + _, ps := resolvedText(t, "spans where service in $svcs", opts) + if len(ps) > 0 { + t.Fatal(ps) + } + r, ps := resolvedText(t, "spans where service:$x", ResolveOptions{}) + if len(ps) > 0 || len(r.Notices) != 1 || r.Notices[0].Message != "declared variables are needed to check $x" { + t.Fatal(r, ps) + } +} + +func TestResolveCompatibleVizzesAndEdits(t *testing.T) { + if resolveLower == nil { + t.Skip("Task 4 installs the lowering hook") + } + r, ps := resolvedText(t, "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route", ResolveOptions{}) + if len(ps) > 0 { + t.Fatal(ps) + } + var names []string + for _, v := range r.Compatible { + names = append(names, v.Viz) + } + if !reflect.DeepEqual(names, []string{"bar", "table"}) { + t.Fatal(r.Compatible) + } + if len(r.Edits) != 1 || r.Edits[0].Viz != "timeseries" || r.Edits[0].Text != "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route every auto" { + t.Fatal(r.Edits) + } + r, ps = resolvedText(t, "spans where status:error", ResolveOptions{}) + if len(ps) > 0 || len(r.Compatible) != 1 || r.Compatible[0].Viz != "traces" { + t.Fatal(r, ps) + } + r, ps = resolvedText(t, "spans | count()", ResolveOptions{}) + if len(ps) > 0 { + t.Fatal(ps) + } + names = nil + for _, v := range r.Compatible { + names = append(names, v.Viz) + } + if !reflect.DeepEqual(names, []string{"stat", "gauge", "table"}) { + t.Fatal(names) + } +} diff --git a/internal/fanql/spellings.go b/internal/fanql/spellings.go new file mode 100644 index 00000000..02a8be1e --- /dev/null +++ b/internal/fanql/spellings.go @@ -0,0 +1,37 @@ +package fanql + +import ( + "regexp" + "strconv" + "strings" + "time" +) + +var statusAliases = map[string]string{"error": "STATUS_CODE_ERROR", "ok": "STATUS_CODE_OK", "unset": "STATUS_CODE_UNSET"} +var kindAliases = map[string]string{"server": "SPAN_KIND_SERVER", "client": "SPAN_KIND_CLIENT", "internal": "SPAN_KIND_INTERNAL", "producer": "SPAN_KIND_PRODUCER", "consumer": "SPAN_KIND_CONSUMER", "unspecified": "SPAN_KIND_UNSPECIFIED"} +var typeAliases = map[string]string{"gauge": "gauge", "counter": "counter", "updown": "updown", "histogram": "histogram", "summary": "summary"} +var identifierPath = regexp.MustCompile(`^[A-Za-z_][A-Za-z_0-9]*(\.[A-Za-z_][A-Za-z_0-9]*)*$`) +var aliasName = regexp.MustCompile(`^[a-z][a-z0-9_]{0,39}$`) + +func durationMS(text string) (float64, bool) { + text = strings.ToLower(text) + for _, u := range []struct { + name string + scale float64 + }{{"us", .001}, {"ms", 1}, {"s", 1000}, {"m", 60000}, {"h", 3600000}} { + if strings.HasSuffix(text, u.name) { + n, err := strconv.ParseFloat(strings.TrimSuffix(text, u.name), 64) + return n * u.scale, err == nil + } + } + return 0, false +} + +func timestamp(text string) bool { + for _, layout := range []string{time.RFC3339Nano, "2006-01-02 15:04:05Z07:00", "2006-01-02 15:04:05Z0700", "2006-01-02 15:04:05"} { + if _, err := time.Parse(layout, text); err == nil { + return true + } + } + return false +} From 4dfb4042dc66702b7cdd09a1c55f46becac3970e Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 16:03:14 -0700 Subject: [PATCH 06/30] feat(fanql): lower the resolved tree to the structured panel query --- internal/fanql/fanql.go | 35 ++++ internal/fanql/lower.go | 350 +++++++++++++++++++++++++++++++++ internal/fanql/lower_test.go | 209 ++++++++++++++++++++ internal/fanql/resolve.go | 2 +- internal/fanql/resolve_test.go | 3 +- 5 files changed, 597 insertions(+), 2 deletions(-) create mode 100644 internal/fanql/lower.go create mode 100644 internal/fanql/lower_test.go diff --git a/internal/fanql/fanql.go b/internal/fanql/fanql.go index f4570604..b838de48 100644 --- a/internal/fanql/fanql.go +++ b/internal/fanql/fanql.go @@ -1,5 +1,40 @@ // Package fanql parses the versioned text form of Fanout's structured telemetry queries. package fanql +import "github.com/labstack/fanout/internal/panel" + // Version identifies the interactive language contract. const Version = 1 + +type Options struct { + Source string + Viz string + Variables []panel.Variable + Schema *panel.Schema +} + +type Compiled struct { + Query panel.Query + Canonical string + Notices []Notice + Compatible []panel.VizCompat + Edits []VizEdit +} + +// Compile parses, resolves and lowers text without executing SQL. A problem +// always prevents an executable query from being returned. +func Compile(text string, opts Options) (*Compiled, panel.Problems) { + q, problems := Parse(text, opts.Source) + if len(problems) != 0 { + return nil, problems + } + r, problems := Resolve(q, ResolveOptions{Viz: opts.Viz, Variables: opts.Variables, Schema: opts.Schema}) + if len(problems) != 0 { + return nil, problems + } + pq, problems := lower(r) + if len(problems) != 0 { + return nil, problems + } + return &Compiled{Query: pq, Notices: r.Notices, Compatible: r.Compatible, Edits: r.Edits}, nil +} diff --git a/internal/fanql/lower.go b/internal/fanql/lower.go new file mode 100644 index 00000000..636906bb --- /dev/null +++ b/internal/fanql/lower.go @@ -0,0 +1,350 @@ +package fanql + +import ( + "fmt" + "strconv" + "strings" + + "github.com/labstack/fanout/internal/panel" +) + +func init() { resolveLower = lower } + +// lower is pure: it emits one SQL string per entry and keeps all stored order. +func lower(r *Resolved) (panel.Query, panel.Problems) { + q := r.Query + out := panel.Query{From: q.Source} + var problems panel.Problems + for i, e := range q.Where { + if i == 16 { + problems = append(problems, panel.Problem{Path: fmt.Sprintf("where[%d]", i), Message: "at most 16 filters", Span: textSpan(e.Span())}) + break + } + sql := lowerEntry(e) + if len(sql) > 500 { + problems = append(problems, panel.Problem{Path: fmt.Sprintf("where[%d]", i), Message: fmt.Sprintf("this filter lowers to %d bytes; filters are at most 500", len(sql)), Span: textSpan(e.Span())}) + } + out.Where = append(out.Where, sql) + } + if s := q.Stage; s != nil { + out.Bucket = s.Bucket + for _, f := range s.By { + out.By = append(out.By, lowerField(f)) + } + if s.Histogram != nil { + buckets := "log2" + if q.Source == "metrics" { + buckets = "explicit" + } + out.Measures = []string{"count()"} + out.Histogram = &panel.Histogram{Field: lowerField(*s.Histogram), Buckets: buckets} + } else { + for _, m := range s.Measures { + out.Measures = append(out.Measures, lowerMeasure(m)) + } + } + } + if q.Sort != nil { + key := q.Sort.Key + if key == "duration" { + key = "duration_ms" + } + out.Sort = key + if q.Sort.Ascending { + out.Sort = "+" + key + } + } + if q.Limit != nil { + out.Limit = q.Limit.N + } + return out, problems +} + +func lowerField(f Field) string { + if f.Ref == nil { + return f.Key + } + if f.Ref.Key != "" { + return f.Ref.Column + "[" + sqlString(f.Ref.Key) + "]" + } + return f.Ref.Column +} +func compareField(f Field) string { + s := lowerField(f) + if f.Ref != nil && f.Ref.CompareAs == "integer" { + return "TRY_CAST(" + s + " AS INTEGER)" + } + return s +} +func sqlString(text string) string { return "'" + strings.ReplaceAll(text, "'", "''") + "'" } +func decimal(n float64) string { return strconv.FormatFloat(n, 'f', -1, 64) } +func lowerValue(f Field, v Value) string { + text := v.Stored + if text == "" { + text = v.Text + } + if v.Kind == VariableValue { + return v.Text + } + if v.Kind == DurationValue { + n, _ := durationMS(v.Text) + return decimal(n) + } + if f.Ref != nil && f.Ref.Type == panel.TypeTime && f.Ref.Key == "" { + return sqlString(text) + "::TIMESTAMPTZ_NS" + } + if v.Kind == StringValue { + return sqlString(text) + } + if f.Ref != nil && f.Ref.Key == "" && f.Ref.Type == panel.TypeString && f.Ref.CompareAs == "" { + return sqlString(text) + } + if v.Kind == NumberValue { + n, _ := strconv.ParseFloat(text, 64) + return decimal(n) + } + if v.Kind == BooleanValue { + return strings.ToLower(text) + } + return sqlString(text) +} + +func lowerEntry(e Expr) string { return lowerNegated(e, false) } +func lowerNegated(e Expr, neg bool) string { + switch x := e.(type) { + case *Not: + return lowerNegated(x.X, !neg) + case *And: + return lowerTerms(x.Terms, false, neg) + case *Or: + return lowerTerms(x.Terms, true, neg) + case *Compare: + if x.Op == "!~" { + copy := *x + copy.Op = "~" + return lowerNegated(©, !neg) + } + f := compareField(x.Field) + op := x.Op + if op == ":" { + op = "=" + } + if op == "<>" { + op = "!=" + } + if x.Bands != nil { + return lowerBands(x.Field, x.Bands, false, neg) + } + v := lowerValue(x.Field, x.Value) + if op == "~" { + field := lowerField(x.Field) + if x.Field.Ref != nil && x.Field.Ref.Key != "" { + field = "CAST(" + field + " AS VARCHAR)" + } + v = sqlString(x.Value.Stored) + if x.Value.Kind == VariableValue { + v = x.Value.Text + } + p := containsSQL(field, v) + if neg { + return "(" + lowerField(x.Field) + " IS NULL OR NOT " + p + ")" + } + return p + } + p := f + " " + op + " " + v + if neg { + if simpleOperand(x.Field, op) { + inverse := map[string]string{"=": "!=", "!=": "=", ">": "<=", ">=": "<", "<": ">=", "<=": ">"}[op] + return "(" + lowerField(x.Field) + " IS NULL OR " + f + " " + inverse + " " + v + ")" + } + return nullNegation(p) + } + return p + case *In: + var vals []string + for _, v := range x.Values { + vals = append(vals, lowerValue(x.Field, v)) + } + list := "(" + strings.Join(vals, ", ") + ")" + if x.Variable != "" { + list = "$" + x.Variable + } + op := "IN" + if x.Negated != neg { + op = "NOT IN" + } + p := lowerField(x.Field) + " " + op + " " + list + if neg { + return "(" + lowerField(x.Field) + " IS NULL OR " + p + ")" + } + return p + case *Between: + if x.Bands != nil { + return lowerBands(x.Field, x.Bands, x.Negated, neg) + } + op := "BETWEEN" + if x.Negated { + op = "NOT BETWEEN" + } + p := compareField(x.Field) + " " + op + " " + lowerValue(x.Field, x.Lo) + " AND " + lowerValue(x.Field, x.Hi) + if neg { + if simpleOperand(x.Field, "between") { + op = "NOT BETWEEN" + if x.Negated { + op = "BETWEEN" + } + return "(" + lowerField(x.Field) + " IS NULL OR " + lowerField(x.Field) + " " + op + " " + lowerValue(x.Field, x.Lo) + " AND " + lowerValue(x.Field, x.Hi) + ")" + } + return nullNegation(p) + } + return p + case *Like: + op := "~~" + if x.Insensitive { + op += "*" + } + if x.Negated != neg { + op = "!" + op + } + p := lowerField(x.Field) + " " + op + " " + sqlString(x.Pattern.Text) + if neg { + return "(" + lowerField(x.Field) + " IS NULL OR " + p + ")" + } + return p + case *Exists: + if neg { + return lowerField(x.Field) + " IS NULL" + } + return lowerField(x.Field) + " IS NOT NULL" + case *IsNull: + if x.Negated != neg { + return lowerField(x.Field) + " IS NOT NULL" + } + return lowerField(x.Field) + " IS NULL" + case *FreeText: + field := "body" + if x.column != "" { + field = x.column + } + p := containsSQL(field, sqlString(x.Value.Text)) + if neg { + return "(" + field + " IS NULL OR NOT " + p + ")" + } + return p + case *Call: + p := lowerCall(x) + if neg { + return nullNegation(p) + } + return p + case *RawExpr: + if neg { + return nullNegation(x.Text) + } + return x.Text + } + return "" +} + +func lowerTerms(terms []Expr, or, neg bool) string { + var out []string + for _, e := range terms { + out = append(out, lowerNegated(e, neg)) + } + sep := " AND " + if or != neg { + sep = " OR " + } + return "(" + strings.Join(out, sep) + ")" +} +func nullNegation(p string) string { return "NOT coalesce((" + p + "), FALSE)" } +func simpleOperand(f Field, op string) bool { + return f.Ref != nil && f.Ref.CompareAs == "" && !(f.Ref.Key != "" && isRange(op)) +} +func lowerBands(f Field, bands []string, sqlNeg, neg bool) string { + var out []string + for _, b := range bands { + out = append(out, sqlString(b)) + } + op := "IN" + if sqlNeg != neg { + op = "NOT IN" + } + p := lowerField(f) + " " + op + " (" + strings.Join(out, ", ") + ")" + if neg { + return "(" + lowerField(f) + " IS NULL OR " + p + ")" + } + return p +} +func containsSQL(field, value string) string { + return "contains(lower(" + field + "), lower(" + value + "))" +} +func lowerCall(c *Call) string { + var args []string + for _, a := range c.Args { + if a.Field != nil { + args = append(args, lowerField(*a.Field)) + } else if a.Call != nil { + args = append(args, lowerCall(a.Call)) + } else if a.Value != nil { + v := a.Value + if v.Kind == NumberValue || v.Kind == BooleanValue { + args = append(args, v.Text) + } else { + args = append(args, sqlString(v.Text)) + } + } + } + p := c.Name + "(" + strings.Join(args, ", ") + ")" + if c.Cmp != nil { + v := c.Cmp.Value.Text + if c.Cmp.Value.Kind != NumberValue && c.Cmp.Value.Kind != BooleanValue { + v = sqlString(v) + } + p += " " + c.Cmp.Op + " " + v + } + return p +} + +func lowerMeasure(m Measure) string { + text := lowerMExpr(m.Expr, 0) + if m.Alias != "" { + text += " as " + m.Alias + } + return text +} +func lowerMExpr(e MExpr, parent int) string { + switch x := e.(type) { + case *MCall: + var args []string + for _, a := range x.Args { + if a.Field != nil { + args = append(args, lowerField(*a.Field)) + } else if a.Number != nil { + args = append(args, decimal(*a.Number)) + } + } + return x.Name + "(" + strings.Join(args, ", ") + ")" + case *MCountIf: + sql := lowerEntry(x.Filter) + if _, ok := x.Filter.(*And); ok { + sql = strings.TrimSuffix(strings.TrimPrefix(sql, "("), ")") + } + return "count_if(" + sql + ")" + case *MConst: + return decimal(x.Value) + case *MNeg: + return "-" + lowerMExpr(x.X, 3) + case *MBinary: + prec := 1 + if x.Op == '*' || x.Op == '/' { + prec = 2 + } + text := lowerMExpr(x.L, prec) + " " + string(x.Op) + " " + lowerMExpr(x.R, prec+1) + if prec < parent { + return "(" + text + ")" + } + return text + } + return "" +} diff --git a/internal/fanql/lower_test.go b/internal/fanql/lower_test.go new file mode 100644 index 00000000..f1b5adc3 --- /dev/null +++ b/internal/fanql/lower_test.go @@ -0,0 +1,209 @@ +package fanql + +import ( + "fmt" + "reflect" + "strings" + "testing" + + "github.com/labstack/fanout/internal/panel" +) + +var lowerFixtures = []struct{ text, sql string }{ + {`spans where duration>500ms`, `duration_ms > 500`}, + {`spans where value>-3`, `attributes['value'] > -3`}, + {`metrics where value>-3`, `value > -3`}, + {`spans where -duration>1s`, `(duration_ms IS NULL OR duration_ms <= 1000)`}, + {`logs where --severity:error`, `severity = 'ERROR'`}, + {`spans where -(status:error kind:server)`, `((status IS NULL OR status != 'STATUS_CODE_ERROR') OR (kind IS NULL OR kind != 'SPAN_KIND_SERVER'))`}, + {`spans where http.target:"/a:b"`, `attributes['http.target'] = '/a:b'`}, + {`logs where "http://x:8080/y"`, `contains(lower(body), lower('http://x:8080/y'))`}, + {`metrics where name:http.server.duration`, `name = 'http.server.duration'`}, + {`spans where resource.k8s.pod.name:x`, `resource['k8s.pod.name'] = 'x'`}, + {`spans where attributes['resource.k']:x`, `attributes['resource.k'] = 'x'`}, + {`spans where flag:true`, `attributes['flag'] = true`}, + {`spans where flag:"true"`, `attributes['flag'] = 'true'`}, + {`logs where service`, `contains(lower(body), lower('service'))`}, + {`logs where service:where`, `service = 'where'`}, + {`logs where body ~ "a_b"`, `contains(lower(body), lower('a_b'))`}, + {`logs where body ilike "%a_b%"`, `body ~~* '%a_b%'`}, + {`logs where body not like "GET %"`, `body !~~ 'GET %'`}, + {`logs where -body like "GET %"`, `(body IS NULL OR body !~~ 'GET %')`}, + {`logs where -body ~ "100%"`, `(body IS NULL OR NOT contains(lower(body), lower('100%')))`}, + {`spans where service in (a, b)`, `service IN ('a', 'b')`}, + {`spans where service not in (a, b)`, `service NOT IN ('a', 'b')`}, + {`spans where -service in (a, b)`, `(service IS NULL OR service NOT IN ('a', 'b'))`}, + {`spans where service in $svcs`, `service IN $svcs`}, + {`spans where a:1 or c:3`, `(attributes['a'] = 1 OR attributes['c'] = 3)`}, + {`spans where (a:1 b:2) or c:3`, `((attributes['a'] = 1 AND attributes['b'] = 2) OR attributes['c'] = 3)`}, + {`spans where (a:1 b:2)`, `(attributes['a'] = 1 AND attributes['b'] = 2)`}, + {`spans where -http_status_code>=500`, `NOT coalesce((TRY_CAST(http_status_code AS INTEGER) >= 500), FALSE)`}, + {`spans where -starts_with(http_route, "/api")`, `NOT coalesce((starts_with(http_route, '/api')), FALSE)`}, + {"logs where -`coalesce(body, '') = ''`", `NOT coalesce((coalesce(body, '') = ''), FALSE)`}, + {"logs where `coalesce(body, '``') = ''`", "coalesce(body, '`') = ''"}, + {`spans where HTTP.Target:x`, `attributes['HTTP.Target'] = 'x'`}, + {`logs where length(body) > 1000`, `length(body) > 1000`}, + {`spans where k:*`, `attributes['k'] IS NOT NULL`}, + {`spans where -user.id:*`, `attributes['user.id'] IS NULL`}, + {`spans where http_status_code>=500`, `TRY_CAST(http_status_code AS INTEGER) >= 500`}, + {`spans where http_status_code:500`, `http_status_code = '500'`}, + {`spans where start_time>"2026-10-29T10:00:00Z"`, `start_time > '2026-10-29T10:00:00Z'::TIMESTAMPTZ_NS`}, + {`logs where severity>=warn`, `severity IN ('WARN', 'ERROR', 'FATAL')`}, + {`logs where severity=14`, `severity_number >= 14`}, + {`spans where -http_status_code between 400 and 599`, `NOT coalesce((TRY_CAST(http_status_code AS INTEGER) BETWEEN 400 AND 599), FALSE)`}, + {`spans where http_status_code not between 400 and 599`, `TRY_CAST(http_status_code AS INTEGER) NOT BETWEEN 400 AND 599`}, + {`spans where -http_status_code not between 400 and 599`, `NOT coalesce((TRY_CAST(http_status_code AS INTEGER) NOT BETWEEN 400 AND 599), FALSE)`}, + {`spans where -http_status_code:500`, `(http_status_code IS NULL OR http_status_code != '500')`}, + {`spans where -service not in (a, b)`, `(service IS NULL OR service IN ('a', 'b'))`}, + {`spans where -service!=api`, `(service IS NULL OR service = 'api')`}, + {`logs where -body not like "GET %"`, `(body IS NULL OR body ~~ 'GET %')`}, + {`spans where -duration not between 1s and 2s`, `(duration_ms IS NULL OR duration_ms BETWEEN 1000 AND 2000)`}, + {`logs where -length(body) > 1000`, `NOT coalesce((length(body) > 1000), FALSE)`}, + {`spans where -k ~ v`, `(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('v')))`}, + {`spans where k ~ v`, `contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('v'))`}, + {`spans where -k:$v`, `(attributes['k'] IS NULL OR attributes['k'] != $v)`}, +} + +func TestLowerPositiveFixtures(t *testing.T) { + for _, tt := range lowerFixtures { + t.Run(tt.text, func(t *testing.T) { + c, ps := Compile(tt.text, Options{}) + if len(ps) > 0 { + t.Fatal(ps) + } + want := panel.Query{From: strings.Fields(tt.text)[0], Where: []string{tt.sql}} + if !reflect.DeepEqual(c.Query, want) { + t.Fatalf("got %#v; want %#v", c.Query, want) + } + }) + } + for _, tt := range []struct { + text string + want panel.Query + }{ + {`spans | histogram(duration) by service`, panel.Query{From: "spans", Measures: []string{"count()"}, Histogram: &panel.Histogram{Field: "duration_ms", Buckets: "log2"}, By: []string{"service"}}}, + {`metrics where name:x | histogram(value) every 1m`, panel.Query{From: "metrics", Where: []string{"name = 'x'"}, Measures: []string{"count()"}, Histogram: &panel.Histogram{Field: "value", Buckets: "explicit"}, Bucket: "1m"}}, + {`spans sort errors limit 50`, panel.Query{From: "spans", Sort: "errors", Limit: 50}}, + {`spans sort duration`, panel.Query{From: "spans", Sort: "duration_ms"}}, + {`logs sort +time`, panel.Query{From: "logs", Sort: "+time"}}, + } { + c, ps := Compile(tt.text, Options{}) + if len(ps) > 0 || !reflect.DeepEqual(c.Query, tt.want) { + t.Fatal(tt.text, c, ps) + } + } + for _, tt := range []struct{ text, measure string }{ + {`spans where kind:server | count_if(status:error) / count() * 100 as err_pct`, `count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as err_pct`}, + {`spans | count()*100 as c100`, `count() * 100 as c100`}, + {`spans | count()/count() as one`, `count() / count() as one`}, + {`spans | p95(duration)-p50(duration) as spread`, `p95(duration_ms) - p50(duration_ms) as spread`}, + {`spans | count() * -1 as neg`, `count() * -1 as neg`}, + {`spans | count() * 1e3 as k`, `count() * 1000 as k`}, + {`spans | count_if(status:error -http.target:/healthz) as errs`, `count_if(status = 'STATUS_CODE_ERROR' AND (attributes['http.target'] IS NULL OR attributes['http.target'] != '/healthz')) as errs`}, + {`spans | count_if(a:1 or b:2) / count() as r`, `count_if((attributes['a'] = 1 OR attributes['b'] = 2)) / count() as r`}, + {`spans | count_distinct(user.id) by service`, `count_distinct(attributes['user.id'])`}, + {`spans | count_distinct(attributes['user.id'])`, `count_distinct(attributes['user.id'])`}, + {`spans | avg(attributes.http.response_size) as sz`, `avg(attributes['http.response_size']) as sz`}, + {`spans | p95(resource.k) as x`, `p95(resource['k']) as x`}, + } { + c, ps := Compile(tt.text, Options{}) + if len(ps) > 0 || len(c.Query.Measures) != 1 || c.Query.Measures[0] != tt.measure { + t.Fatal(tt.text, c, ps) + } + } + for _, text := range glanceExamples { + if _, ps := Compile(text, Options{}); len(ps) > 0 { + t.Fatal(text, ps) + } + } +} + +var glanceExamples = []string{ + `spans where kind:server | error_rate() by service every 1m`, + `spans where service:checkout duration>500ms sort duration limit 50`, + `spans where service:$service (status:error or status:unset) | count() by http_route`, + `spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route`, + `spans where kind:server | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex`, + `spans | histogram(duration) by service`, + `spans where service:checkout status:error -http.target:/healthz | count() by http_route`, + `spans where user.id:* | count_distinct(user.id) by service`, + `logs where service:api severity:error timeout sort time limit 200`, + `logs where severity>=warn | count() by body_template sort count limit 10`, + `metrics where name:http.server.requests | rate() by service every 1m`, + `metrics where name:k8s.container.restarts | last(value) by resource.k8s.pod.name`, +} + +func TestLowerEntryBoundaries(t *testing.T) { + for _, tt := range []struct { + text string + want []string + }{ + {`spans where a:1 b:2 (c:3 or d:4) (e:5 f:6)`, []string{`attributes['a'] = 1`, `attributes['b'] = 2`, `(attributes['c'] = 3 OR attributes['d'] = 4)`, `(attributes['e'] = 5 AND attributes['f'] = 6)`}}, + {`spans where service:$service status:error`, []string{`service = $service`, `status = 'STATUS_CODE_ERROR'`}}, + {`spans where (service:$service status:error)`, []string{`(service = $service AND status = 'STATUS_CODE_ERROR')`}}, + {`spans where a:1 (b:2 or c:3)`, []string{`attributes['a'] = 1`, `(attributes['b'] = 2 OR attributes['c'] = 3)`}}, + {`spans where not a:1 b:2`, []string{`(attributes['a'] IS NULL OR attributes['a'] != 1)`, `attributes['b'] = 2`}}, + {`spans where duration between 1s and 2s status:error`, []string{`duration_ms BETWEEN 1000 AND 2000`, `status = 'STATUS_CODE_ERROR'`}}, + {`spans where service:$service (status:error or status:unset)`, []string{`service = $service`, `(status = 'STATUS_CODE_ERROR' OR status = 'STATUS_CODE_UNSET')`}}, + } { + c, ps := Compile(tt.text, Options{}) + if len(ps) > 0 || !reflect.DeepEqual(c.Query.Where, tt.want) { + t.Fatal(tt.text, c, ps) + } + } +} + +func TestLowerStructuredBounds(t *testing.T) { + text := "spans where " + strings.Repeat("a:1 ", 16) + "z:2" + q, ps := Parse(text, "") + if len(ps) > 0 { + t.Fatal(ps) + } + c, ps := Compile(text, Options{}) + if c != nil || len(ps) != 1 || ps[0].Message != "at most 16 filters" || *ps[0].Span != *textSpan(q.Where[16].Span()) { + t.Fatal(c, ps) + } + text = `logs where attributes['long']:"` + strings.Repeat("x", 480) + `"` + c, ps = Compile(text, Options{}) + want := fmt.Sprintf("this filter lowers to %d bytes; filters are at most 500", len(`attributes['long'] = '`+strings.Repeat("x", 480)+`'`)) + if c != nil || len(ps) != 1 || ps[0].Message != want { + t.Fatal(c, ps, want) + } + if c, ps := Compile(text, Options{Viz: "logs"}); c != nil || len(ps) != 1 || ps[0].Message != want { + t.Fatal("the selected viz must not duplicate the lowering bound", c, ps) + } + // One hundred quoted one-letter strings require 519 SQL bytes, so use + // short numbers to exercise the 100-value limit independently of bytes. + text = "spans where k in (" + strings.TrimSuffix(strings.Repeat("0,", 100), ",") + ")" + if _, ps = Compile(text, Options{}); len(ps) > 0 { + t.Fatal(ps) + } +} + +func TestLowerSearchBarMode(t *testing.T) { + c, ps := Compile("service:api timeout", Options{Source: "logs"}) + want := panel.Query{From: "logs", Where: []string{`service = 'api'`, `contains(lower(body), lower('timeout'))`}} + if len(ps) > 0 || !reflect.DeepEqual(c.Query, want) { + t.Fatal(c, ps) + } +} +func TestLowerCanonicalWhereIsIrrelevantToMeaning(t *testing.T) { + a, ps := Compile("spans status:error", Options{}) + if len(ps) > 0 { + t.Fatal(ps) + } + b, ps := Compile("spans where status:error", Options{}) + if len(ps) > 0 || !reflect.DeepEqual(a.Query, b.Query) { + t.Fatal(a, b, ps) + } +} +func TestCompileReturnsNoQueryOnProblems(t *testing.T) { + c, ps := Compile("spans where a:1 b:2 or c:3 | p99(duration) by http_route every 1m", Options{}) + if c != nil || len(ps) != 1 { + t.Fatal(c, ps) + } +} diff --git a/internal/fanql/resolve.go b/internal/fanql/resolve.go index 8d7912f8..d9c04594 100644 --- a/internal/fanql/resolve.go +++ b/internal/fanql/resolve.go @@ -88,7 +88,7 @@ func Resolve(q *Query, opts ResolveOptions) (*Resolved, panel.Problems) { vars[v.Name] = v } } - if opts.Viz != "" { + if opts.Viz != "" && len(ps) == 0 { ps, _ = panel.QueryShape(&pq, opts.Viz, vars) for _, p := range ps { p.Span = textSpan(queryPathSpan(q, p.Path)) diff --git a/internal/fanql/resolve_test.go b/internal/fanql/resolve_test.go index 6bc9dcbf..8aa70f9f 100644 --- a/internal/fanql/resolve_test.go +++ b/internal/fanql/resolve_test.go @@ -285,7 +285,8 @@ func TestResolveCompatibleVizzesAndEdits(t *testing.T) { if !reflect.DeepEqual(names, []string{"bar", "table"}) { t.Fatal(r.Compatible) } - if len(r.Edits) != 1 || r.Edits[0].Viz != "timeseries" || r.Edits[0].Text != "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route every auto" { + // Task 5 supplies the canonical printer used for edit text. + if resolvePrint != nil && (len(r.Edits) != 1 || r.Edits[0].Viz != "timeseries" || r.Edits[0].Text != "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route every auto") { t.Fatal(r.Edits) } r, ps = resolvedText(t, "spans where status:error", ResolveOptions{}) From 695aeb31cbf0700024fc910806cca8fbebd10615 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 16:09:23 -0700 Subject: [PATCH 07/30] feat(fanql): print canonical text and lift stored queries through the engine parser --- internal/fanql/fanql.go | 2 +- internal/fanql/lift.go | 1084 ++++++++++++++++++++++++++++ internal/fanql/lift_test.go | 352 +++++++++ internal/fanql/lower.go | 7 + internal/fanql/parser.go | 4 +- internal/fanql/print.go | 444 ++++++++++++ internal/fanql/print_test.go | 84 +++ internal/fanql/resolve.go | 8 +- internal/fanql/resolve_test.go | 16 +- internal/fanql/testhelpers_test.go | 25 + internal/panel/measure.go | 16 + scripts/go-deadcode.allowlist | 1 + 12 files changed, 2034 insertions(+), 9 deletions(-) create mode 100644 internal/fanql/lift.go create mode 100644 internal/fanql/lift_test.go create mode 100644 internal/fanql/print.go create mode 100644 internal/fanql/print_test.go create mode 100644 internal/fanql/testhelpers_test.go diff --git a/internal/fanql/fanql.go b/internal/fanql/fanql.go index b838de48..fecc6953 100644 --- a/internal/fanql/fanql.go +++ b/internal/fanql/fanql.go @@ -36,5 +36,5 @@ func Compile(text string, opts Options) (*Compiled, panel.Problems) { if len(problems) != 0 { return nil, problems } - return &Compiled{Query: pq, Notices: r.Notices, Compatible: r.Compatible, Edits: r.Edits}, nil + return &Compiled{Query: pq, Canonical: Print(q), Notices: r.Notices, Compatible: r.Compatible, Edits: r.Edits}, nil } diff --git a/internal/fanql/lift.go b/internal/fanql/lift.go new file mode 100644 index 00000000..538b1763 --- /dev/null +++ b/internal/fanql/lift.go @@ -0,0 +1,1084 @@ +package fanql + +import ( + "context" + "database/sql" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "unicode/utf8" + + "github.com/labstack/fanout/internal/panel" + "github.com/labstack/fanout/internal/telemetry" +) + +type FormatOptions struct { + Viz string + Variables []panel.Variable +} +type Formatted struct { + Text string `json:"text"` + Exactness string `json:"exactness"` + Editable bool `json:"editable"` + Reason string `json:"reason,omitempty"` + Notices []Notice `json:"notices"` +} +type tier uint8 + +const ( + tierExact tier = iota + tierNormalized + tierRaw +) + +// Format preserves each stored filter as one entry. Candidates are kept only +// after a byte or engine-AST exactness check; all other filters remain raw. +func Format(ctx context.Context, p panel.Parser, stored panel.Query, opts FormatOptions) (*Formatted, panel.Problems, error) { + vars := map[string]panel.Variable(nil) + if opts.Variables != nil { + vars = make(map[string]panel.Variable, len(opts.Variables)) + for _, v := range opts.Variables { + vars[v.Name] = v + } + } + var problems panel.Problems + if opts.Viz != "" { + problems, _ = panel.QueryShape(&stored, opts.Viz, vars) + } else if len(panel.CompatibleVizzes(&stored, vars)) == 0 { + problems, _ = panel.QueryShape(&stored, "table", vars) + } + if len(problems) > 0 { + return nil, problems, nil + } + q := &Query{Source: stored.From} + f := &Formatted{Exactness: "exact", Notices: []Notice{}} + for i, text := range stored.Where { + e, t, err := liftEntry(ctx, p, stored.From, text) + if err != nil { + if operationalFormatError(err) { + return nil, nil, fmt.Errorf("format where[%d]: %w", i, err) + } + return nil, panel.Problems{{Path: fmt.Sprintf("where[%d]", i), Message: err.Error()}}, nil + } + q.Where = append(q.Where, e) + if t == tierNormalized { + f.Exactness = "normalized" + f.Notices = append(f.Notices, Notice{Path: fmt.Sprintf("where[%d]", i), Message: fmt.Sprintf("where[%d] is shown as %s; stored text is %q", i, printEntry(e, false), text)}) + } + } + if len(stored.Measures) > 0 || stored.Histogram != nil || len(stored.By) > 0 || stored.Bucket != "" { + q.Stage = &Stage{Bucket: stored.Bucket} + if stored.Histogram != nil { + field, ok := liftFieldText(stored.From, stored.Histogram.Field) + if !ok { + return nil, panel.Problems{{Path: "histogram.field", Message: "histogram field cannot be expressed in FanQL"}}, nil + } + q.Stage.Histogram = &field + } else { + for i, text := range stored.Measures { + m, t, err := liftMeasure(ctx, p, stored.From, text) + if err != nil { + if operationalFormatError(err) { + return nil, nil, fmt.Errorf("format measures[%d]: %w", i, err) + } + return nil, panel.Problems{{Path: fmt.Sprintf("measures[%d]", i), Message: err.Error()}}, nil + } + q.Stage.Measures = append(q.Stage.Measures, m) + if t == tierNormalized { + f.Exactness = "normalized" + f.Notices = append(f.Notices, Notice{Path: fmt.Sprintf("measures[%d]", i), Message: fmt.Sprintf("measures[%d] is shown as %s; stored text is %q", i, printMeasure(m), text)}) + } + } + } + for _, text := range stored.By { + field, ok := liftFieldText(stored.From, text) + if !ok { + return nil, panel.Problems{{Path: "by", Message: "grouping field cannot be expressed in FanQL"}}, nil + } + q.Stage.By = append(q.Stage.By, field) + } + } + if stored.Sort != "" { + q.Sort = &Sort{Key: strings.TrimPrefix(stored.Sort, "+"), Ascending: strings.HasPrefix(stored.Sort, "+")} + } + if stored.Limit != 0 { + q.Limit = &Limit{N: stored.Limit} + } + if opts.Viz == "traces" && stored.Sort == "errors" { + f.Notices = append(f.Notices, Notice{Path: "sort", Message: "sort errors also filters to error spans; new queries: write status:error … sort duration"}) + } + if opts.Viz != "" && (stored.Sort != "" || stored.Limit != 0) && stored.Bucket != "" || stored.Limit != 0 && (opts.Viz == "stat" || opts.Viz == "gauge") { + f.Notices = append(f.Notices, Notice{Path: "sort", Message: "sort does not apply to bucketed series; series are chosen by top (options)"}) + } + f.Text = Print(q) + f.Reason = editableReason(f.Text) + f.Editable = f.Reason == "" + return f, nil, nil +} + +// formatInputError denotes a stored query that cannot be expressed without +// changing meaning. Every other non-syntax failure belongs to the engine. +type formatInputError struct{ message string } + +func (e formatInputError) Error() string { return e.message } +func formatInput(message string, args ...any) error { + return formatInputError{message: fmt.Sprintf(message, args...)} +} +func operationalFormatError(err error) bool { + if err == nil { + return false + } + if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) || errors.Is(err, sql.ErrConnDone) { + return true + } + var input formatInputError + return !errors.As(err, &input) && !strings.HasPrefix(err.Error(), "SQL parsing failed:") +} + +func groupedNumber(n int) string { + s := strconv.Itoa(n) + for i := len(s) - 3; i > 0; i -= 3 { + s = s[:i] + "," + s[i:] + } + return s +} +func editableReason(text string) string { + bound := func(n, max int, unit string) string { + return fmt.Sprintf("formatted text is %s %s; the editor accepts %s", groupedNumber(n), unit, groupedNumber(max)) + } + if n := utf8.RuneCountInString(text); n > MaxTextRunes { + return bound(n, MaxTextRunes, "characters") + } + if len(text) > MaxTextBytes { + return bound(len(text), MaxTextBytes, "bytes") + } + tokens := Lex(text) + if n := len(tokens) - 1; n > MaxTokens { + return bound(n, MaxTokens, "tokens") + } + // The internal parser is unbounded; its counters still record the complete + // tree, so oversized stored text is never truncated by interactive parsing. + p := &parser{runes: []rune(text), tokens: tokens, heights: make(map[any]int)} + p.query("") + if p.nodes > MaxNodes { + return bound(p.nodes, MaxNodes, "nodes") + } + maxDepth, lexicalDepth := 0, 0 + for _, token := range tokens { + if token.Kind == Punct && token.Text == "(" { + lexicalDepth++ + maxDepth = max(maxDepth, lexicalDepth) + } + if token.Kind == Punct && token.Text == ")" { + lexicalDepth-- + } + } + for _, height := range p.heights { + maxDepth = max(maxDepth, height) + } + if maxDepth > MaxDepth { + return bound(maxDepth, MaxDepth, "levels of nesting depth") + } + return "" +} + +func liftEntry(ctx context.Context, p panel.Parser, signal, stored string) (Expr, tier, error) { + if e := recognizeOwnLowering(signal, stored); e != nil { + return e, tierExact, nil + } + node, err := p.ParseSQL(ctx, "SELECT 1 FROM "+signal+" WHERE ("+stored+")") + if err != nil { + return nil, tierRaw, err + } + e := liftSQLNode(signal, node["where_clause"]) + e = reparseLiftedEntry(signal, e) + if e == nil { + return &RawExpr{Text: stored}, tierRaw, nil + } + lowered := lowerEntry(e) + if lowered == stored { + return e, tierExact, nil + } + candidate, err := p.ParseSQL(ctx, "SELECT 1 FROM "+signal+" WHERE ("+lowered+")") + if err != nil { + if operationalFormatError(err) { + return nil, tierRaw, err + } + return &RawExpr{Text: stored}, tierRaw, nil + } + a, err := p.RenderSQL(ctx, node) + if err != nil { + return nil, tierRaw, err + } + b, err := p.RenderSQL(ctx, candidate) + if err != nil { + return nil, tierRaw, err + } + if a == b { + return e, tierNormalized, nil + } + return &RawExpr{Text: stored}, tierRaw, nil +} + +// recognizeOwnLowering parses only the grammar our lowerer emits. It is not a +// SQL authority: the result is discarded unless lowering recreates every byte. +func recognizeOwnLowering(signal, stored string) Expr { + r := &ownSQLReader{tokens: ownSQLTokens(stored)} + n := r.expression(0) + if r.failed || r.pos != len(r.tokens) { + return nil + } + e := reparseLiftedEntry(signal, liftSQLNode(signal, n)) + if e != nil && lowerEntry(e) == stored { + return e + } + return nil +} + +// The gate uses the complete unbounded entry parser, then the resolver's +// semantic walk, so a short spelling is accepted only with the meaning that a +// user editing that spelling will actually obtain. +func reparseLiftedEntry(signal string, e Expr) Expr { + if e == nil { + return nil + } + parsed, ps := parseEntry(printEntry(e, false)) + if len(ps) > 0 { + return nil + } + q := &Query{Source: signal, Where: []Expr{parsed}} + r := &resolver{out: &Resolved{Query: q, Notices: []Notice{}}} + r.expr(parsed) + if len(r.problems) > 0 { + return nil + } + return parsed +} + +func liftFieldText(signal, text string) (Field, bool) { + r := &ownSQLReader{tokens: ownSQLTokens(text)} + node := r.atom() + if r.failed || r.pos != len(r.tokens) { + return Field{}, false + } + return liftSQLField(signal, node, false) +} + +func liftSQLField(signal string, n any, contains bool) (Field, bool) { + node, _ := n.(map[string]any) + if node == nil { + return Field{}, false + } + switch node["class"] { + case "CAST": + typ, _ := node["type_expr"].(map[string]any) + name, _ := typ["type_name"].(string) + f, ok := liftSQLField(signal, node["child"], false) + if !ok { + return Field{}, false + } + if contains && name == "VARCHAR" && f.Ref.Key != "" { + return f, true + } + tr, _ := node["try_cast"].(bool) + if tr && name == "INTEGER" && f.Ref.Column == "http_status_code" && f.Ref.Key == "" { + f.Ref.CompareAs = "integer" + return f, true + } + return Field{}, false + case "COLUMN_REF": + names, _ := node["column_names"].([]any) + if len(names) != 1 { + return Field{}, false + } + name, _ := names[0].(string) + cols, _ := panel.SignalColumns(signal) + for _, col := range cols { + if col.Name == name && col.Type != panel.TypeMap { + return Field{Key: name, Single: true, Ref: &FieldRef{Column: name, Type: col.Type, Unit: col.Unit}}, true + } + } + case "OPERATOR": + if node["type"] != "ARRAY_EXTRACT" { + return Field{}, false + } + children, _ := node["children"].([]any) + if len(children) != 2 { + return Field{}, false + } + col, _ := children[0].(map[string]any) + names, _ := col["column_names"].([]any) + if col["class"] != "COLUMN_REF" || len(names) != 1 || (names[0] != "attributes" && names[0] != "resource") { + return Field{}, false + } + v, ok := liftSQLValue(children[1]) + if !ok || v.Kind != StringValue { + return Field{}, false + } + column, _ := names[0].(string) + return Field{Scope: column, Key: v.Text, Bracket: true, Ref: &FieldRef{Column: column, Key: v.Text, Type: panel.TypeString, Unit: "none"}}, true + } + return Field{}, false +} + +func liftSQLValue(n any) (Value, bool) { + node, _ := n.(map[string]any) + if node == nil { + return Value{}, false + } + if node["class"] == "CAST" { + typ, _ := node["type_expr"].(map[string]any) + if typ["type_name"] == "TIMESTAMPTZ_NS" { + return liftSQLValue(node["child"]) + } + return Value{}, false + } + if node["class"] == "PARAMETER" { + id, _ := node["identifier"].(string) + if id != "" { + return Value{Kind: VariableValue, Text: "$" + id, Stored: "$" + id}, true + } + return Value{}, false + } + if node["class"] != "CONSTANT" { + return Value{}, false + } + literal, _ := node["literal"].(map[string]any) + kind, _ := literal["kind"].(string) + text, _ := literal["text"].(string) + if text == "" { + if v, ok := literal["value"]; ok { + text = fmt.Sprint(v) + } + } + switch kind { + case "STRING": + return Value{Kind: StringValue, Text: text, Stored: text}, true + case "INTEGER", "NUMERIC", "DECIMAL", "FLOAT", "DOUBLE": + return Value{Kind: NumberValue, Text: text, Stored: text}, true + case "BOOLEAN": + return Value{Kind: BooleanValue, Text: strings.ToLower(text), Stored: strings.ToLower(text)}, true + } + return Value{}, false +} + +func spellingValue(f Field, v Value) Value { + if v.Kind == VariableValue { + return v + } + if f.Ref.Column == "duration_ms" && f.Ref.Key == "" && v.Kind == NumberValue { + if n, err := strconv.ParseFloat(v.Text, 64); err == nil { + v.Kind = DurationValue + v.Text = durationText(n) + } + return v + } + if v.Kind == StringValue && f.Ref.Key == "" && f.Ref.Type == panel.TypeString { + switch f.Ref.Column { + case "status": + if strings.HasPrefix(v.Text, "STATUS_CODE_") { + v.Kind = WordValue + v.Text = strings.ToLower(strings.TrimPrefix(v.Text, "STATUS_CODE_")) + return v + } + case "kind": + if strings.HasPrefix(v.Text, "SPAN_KIND_") { + v.Kind = WordValue + v.Text = strings.ToLower(strings.TrimPrefix(v.Text, "SPAN_KIND_")) + return v + } + case "severity": + if v.Text == strings.ToUpper(v.Text) && classify(Token{Kind: Word, Text: strings.ToLower(v.Text)}).Kind == WordValue { + v.Kind = WordValue + v.Text = strings.ToLower(v.Text) + return v + } + } + if f.Ref.Column != "status" && f.Ref.Column != "kind" && f.Ref.Column != "severity" && f.Ref.Column != "type" && f.Ref.CompareAs == "" { + if numberPattern.MatchString(v.Text) { + v.Kind = NumberValue + return v + } + if v.Text == "true" || v.Text == "false" { + v.Kind = BooleanValue + return v + } + } + if f.Ref.Column == "status" || f.Ref.Column == "kind" || f.Ref.Column == "severity" { + return v + } + if f.Ref.Column == "type" { + if _, ok := typeAliases[v.Text]; !ok { + return v + } + } + if bareValue(v.Text) && !numberPattern.MatchString(v.Text) && !durationPattern.MatchString(v.Text) && !strings.EqualFold(v.Text, "true") && !strings.EqualFold(v.Text, "false") { + v.Kind = WordValue + } + } + return v +} +func durationText(ms float64) string { + units := []struct { + value float64 + name string + }{{3600000, "h"}, {60000, "m"}, {1000, "s"}, {1, "ms"}, {0.001, "us"}} + for _, u := range units { + if ms >= u.value { + return strconv.FormatFloat(ms/u.value, 'f', -1, 64) + u.name + } + } + return strconv.FormatFloat(ms, 'f', -1, 64) + "ms" +} + +func liftSQLNode(signal string, n any) Expr { + node, _ := n.(map[string]any) + if node == nil { + return nil + } + children, _ := node["children"].([]any) + switch node["class"] { + case "CONJUNCTION": + terms := make([]Expr, len(children)) + for i, c := range children { + terms[i] = liftSQLNode(signal, c) + if terms[i] == nil { + return nil + } + } + if node["type"] == "CONJUNCTION_OR" { + if len(terms) == 2 { + if x := liftNullInclusive(terms[0], terms[1]); x != nil { + return x + } + if x := liftNullInclusive(terms[1], terms[0]); x != nil { + return x + } + } + return &Or{Terms: terms} + } + return &And{Terms: terms} + case "COMPARISON": + f, ok := liftSQLField(signal, node["left"], false) + v, valid := liftSQLValue(node["right"]) + if ok && valid { + op := map[string]string{"COMPARE_EQUAL": ":", "COMPARE_NOTEQUAL": "!=", "COMPARE_LESSTHAN": "<", "COMPARE_GREATERTHAN": ">", "COMPARE_LESSTHANOREQUALTO": "<=", "COMPARE_GREATERTHANOREQUALTO": ">="}[fmt.Sprint(node["type"])] + if op != "" { + return &Compare{Field: f, Op: op, Value: spellingValue(f, v)} + } + } + if call := liftSQLCall(signal, node["left"]); call != nil && valid { + op := map[string]string{"COMPARE_EQUAL": "=", "COMPARE_NOTEQUAL": "!=", "COMPARE_LESSTHAN": "<", "COMPARE_GREATERTHAN": ">", "COMPARE_LESSTHANOREQUALTO": "<=", "COMPARE_GREATERTHANOREQUALTO": ">="}[fmt.Sprint(node["type"])] + if op != "" { + call.Cmp = &Comparison{Op: op, Value: v} + return call + } + } + case "BETWEEN": + f, ok := liftSQLField(signal, node["input"], false) + lo, a := liftSQLValue(node["lower"]) + hi, b := liftSQLValue(node["upper"]) + if ok && a && b { + neg, _ := node["negated"].(bool) + return &Between{Field: f, Lo: spellingValue(f, lo), Hi: spellingValue(f, hi), Negated: neg} + } + case "OPERATOR": + switch node["type"] { + case "OPERATOR_IS_NULL", "OPERATOR_IS_NOT_NULL": + if len(children) == 1 { + if f, ok := liftSQLField(signal, children[0], false); ok { + return &IsNull{Field: f, Negated: node["type"] == "OPERATOR_IS_NOT_NULL"} + } + } + case "COMPARE_IN", "COMPARE_NOT_IN": + if len(children) < 2 { + return nil + } + f, ok := liftSQLField(signal, children[0], false) + if !ok { + return nil + } + in := &In{Field: f, Negated: node["type"] == "COMPARE_NOT_IN"} + for _, c := range children[1:] { + v, ok := liftSQLValue(c) + if !ok { + return nil + } + in.Values = append(in.Values, spellingValue(f, v)) + } + if len(in.Values) == 1 && in.Values[0].Kind == VariableValue { + in.Variable = strings.TrimPrefix(in.Values[0].Text, "$") + in.Values = nil + return in + } + if !in.Negated && f.Ref.Column == "severity" && f.Ref.Key == "" { + return liftSeverityRange(in) + } + return in + case "OPERATOR_NOT": + if len(children) != 1 { + return nil + } + inner, _ := children[0].(map[string]any) + if inner["class"] == "OPERATOR" && inner["type"] == "OPERATOR_COALESCE" { + parts, _ := inner["children"].([]any) + if len(parts) == 2 { + v, ok := liftSQLValue(parts[1]) + if ok && v.Kind == BooleanValue && v.Text == "false" { + if e := liftSQLNode(signal, parts[0]); e != nil { + return &Not{X: e} + } + } + } + } + if inner["class"] == "BETWEEN" { + if e, ok := liftSQLNode(signal, children[0]).(*Between); ok { + e.Negated = !e.Negated + return e + } + } + if e := liftSQLNode(signal, children[0]); e != nil { + return &Not{X: e} + } + } + case "FUNCTION": + name, _ := node["function_name"].(string) + args := sqlFunctionArgs(node) + if name == "contains" && len(args) == 2 { + if v, ok := liftSQLValue(args[0]); ok && v.Kind == VariableValue { + if f, ok := liftSQLField(signal, args[1], false); ok { + return &In{Field: f, Variable: strings.TrimPrefix(v.Text, "$")} + } + } + left, lok := unwrapFunction(args[0], "lower") + right, rok := unwrapFunction(args[1], "lower") + if lok && rok { + if f, ok := liftSQLField(signal, left, true); ok { + if v, ok := liftSQLValue(right); ok { + if v.Kind != VariableValue && f.Ref.Key == "" && (signal == "logs" && f.Ref.Column == "body" || signal == "spans" && f.Ref.Column == "operation") { + if v.Kind == StringValue && bareValue(v.Text) { + v.Kind = WordValue + } + return &FreeText{Value: v, column: f.Ref.Column} + } + if v.Kind == StringValue && bareValue(v.Text) { + v.Kind = WordValue + } + return &Compare{Field: f, Op: "~", Value: v} + } + } + } + } + if (name == "~~" || name == "!~~" || name == "~~*" || name == "!~~*") && len(args) == 2 { + f, ok := liftSQLField(signal, args[0], false) + v, valid := liftSQLValue(args[1]) + if ok && valid { + return &Like{Field: f, Pattern: v, Negated: strings.HasPrefix(name, "!"), Insensitive: strings.HasSuffix(name, "*")} + } + } + if call := liftSQLCall(signal, n); call != nil { + return call + } + } + return nil +} + +func liftSQLCall(signal string, n any) *Call { + node, _ := n.(map[string]any) + if node["class"] != "FUNCTION" { + return nil + } + name, _ := node["function_name"].(string) + // String transforms used as operands deliberately stay raw. Predicate calls + // and length comparisons are precisely representable and pass the gate. + if name != "starts_with" && name != "contains" && name != "regexp_matches" && name != "length" { + return nil + } + args := sqlFunctionArgs(node) + out := &Call{Name: name} + for _, a := range args { + if f, ok := liftSQLField(signal, a, false); ok { + out.Args = append(out.Args, CallArg{Field: &f}) + } else if v, ok := liftSQLValue(a); ok { + out.Args = append(out.Args, CallArg{Value: &v}) + } else { + return nil + } + } + return out +} +func sqlFunctionArgs(n map[string]any) []any { + entries, _ := n["arguments"].([]any) + out := make([]any, 0, len(entries)) + for _, entry := range entries { + m, _ := entry.(map[string]any) + out = append(out, m["expression"]) + } + return out +} +func unwrapFunction(n any, name string) (any, bool) { + node, _ := n.(map[string]any) + if node["class"] != "FUNCTION" || node["function_name"] != name { + return nil, false + } + args := sqlFunctionArgs(node) + if len(args) != 1 { + return nil, false + } + return args[0], true +} +func sameLiftedField(a, b Field) bool { + return a.Ref != nil && b.Ref != nil && a.Ref.Column == b.Ref.Column && a.Ref.Key == b.Ref.Key +} +func liftNullInclusive(null, other Expr) Expr { + is, ok := null.(*IsNull) + if !ok || is.Negated { + return nil + } + switch x := other.(type) { + case *Compare: + if len(x.Bands) > 0 && sameLiftedField(is.Field, x.Field) { + return &Not{X: bandMembership(x.Field, x.Bands, true)} + } + if !sameLiftedField(is.Field, x.Field) { + return nil + } + c := *x + switch c.Op { + case ":", "=": + c.Op = "!=" + case "!=", "<>": + c.Op = ":" + case ">": + c.Op = "<=" + case ">=": + c.Op = "<" + case "<": + c.Op = ">=" + case "<=": + c.Op = ">" + default: + return nil + } + return &Not{X: &c} + case *In: + if sameLiftedField(is.Field, x.Field) { + c := *x + c.Negated = !c.Negated + return &Not{X: &c} + } + case *Between: + if len(x.Bands) > 0 && sameLiftedField(is.Field, x.Field) { + return &Not{X: bandMembership(x.Field, x.Bands, !x.Negated)} + } + if sameLiftedField(is.Field, x.Field) { + c := *x + c.Negated = !c.Negated + return &Not{X: &c} + } + case *Like: + if sameLiftedField(is.Field, x.Field) { + c := *x + c.Negated = !c.Negated + return &Not{X: &c} + } + case *Not: + switch c := x.X.(type) { + case *Compare: + if c.Op == "~" && sameLiftedField(is.Field, c.Field) { + return &Not{X: c} + } + case *FreeText: + if is.Field.Ref.Key == "" && (is.Field.Ref.Column == "body" || is.Field.Ref.Column == "operation") { + return &Not{X: c} + } + } + } + return nil +} +func bandMembership(f Field, bands []string, negated bool) *In { + in := &In{Field: f, Negated: negated} + for _, band := range bands { + in.Values = append(in.Values, Value{Kind: WordValue, Text: strings.ToLower(band), Stored: band}) + } + return in +} + +func liftSeverityRange(in *In) Expr { + if len(in.Values) < 1 { + return in + } + ranks := make([]int, len(in.Values)) + for i, v := range in.Values { + rank, ok := telemetry.SeverityRank(v.Stored) + if !ok { + return in + } + ranks[i] = rank + if i > 0 && rank != ranks[i-1]+1 { + return in + } + } + // The order and spelling must be exactly the shared canonical band table. + first, last := ranks[0], ranks[len(ranks)-1] + if first < 0 || last >= len(telemetry.SeverityBands) { + return in + } + value := func(rank int) Value { + band := telemetry.SeverityBands[rank] + return Value{Kind: WordValue, Text: strings.ToLower(band), Stored: band} + } + bands := make([]string, len(ranks)) + for i, r := range ranks { + bands[i] = telemetry.SeverityBands[r] + } + if last == len(telemetry.SeverityBands)-1 { + return &Compare{Field: in.Field, Op: ">=", Value: value(first), Bands: bands} + } + if first == 0 { + return &Compare{Field: in.Field, Op: "<=", Value: value(last), Bands: bands} + } + return &Between{Field: in.Field, Lo: value(first), Hi: value(last), Bands: bands} +} + +func liftMeasure(ctx context.Context, p panel.Parser, signal, stored string) (Measure, tier, error) { + // Count-if bodies are stored SQL, while the surrounding expression already + // uses FanQL's measure grammar. Lift the bodies before invoking that parser. + converted, err := liftCountIfBodies(ctx, p, signal, stored) + if err != nil { + return Measure{}, tierRaw, err + } + text := signal + " | " + converted + parser := &parser{runes: []rune(text), tokens: Lex(text), heights: make(map[any]int)} + q := parser.query("") + if ps := parser.finish(); len(ps) > 0 || q.Stage == nil || len(q.Stage.Measures) != 1 { + return Measure{}, tierRaw, formatInput("measure %q cannot be expressed in FanQL", stored) + } + if _, ps := Resolve(q, ResolveOptions{}); len(ps) > 0 { + return Measure{}, tierRaw, formatInput("measure %q cannot be expressed in FanQL: %s", stored, ps[0].Message) + } + m := q.Stage.Measures[0] + lowered := lowerMeasure(m) + if lowered == stored { + return m, tierExact, nil + } + a, errA := panel.ParseMeasure(signal, lowered) + b, errB := panel.ParseMeasure(signal, stored) + if errA == nil && errB == nil && a.Func == b.Func && reflect.DeepEqual(a.Field, b.Field) && a.Q == b.Q && a.Alias == b.Alias { + return m, tierNormalized, nil + } + return Measure{}, tierRaw, formatInput("measure %q cannot be formatted without changing its parsed meaning", stored) +} +func liftCountIfBodies(ctx context.Context, p panel.Parser, signal, text string) (string, error) { + tokens := ownSQLTokens(text) + var b strings.Builder + end := 0 + for i := 0; i+1 < len(tokens); i++ { + if !strings.EqualFold(tokens[i].text, "count_if") || tokens[i+1].text != "(" { + continue + } + depth := 1 + j := i + 2 + for ; j < len(tokens); j++ { + if tokens[j].text == "(" { + depth++ + } + if tokens[j].text == ")" { + depth-- + if depth == 0 { + break + } + } + } + if j == len(tokens) { + return "", formatInput("unclosed count_if") + } + body := text[tokens[i+1].end:tokens[j].start] + // A count_if conjunction has no entry-level outer parentheses. + // Recognize that exact emitted production without consulting the engine. + reader := &ownSQLReader{tokens: ownSQLTokens(body)} + node := reader.expression(0) + var e Expr + if !reader.failed && reader.pos == len(reader.tokens) { + candidate := liftSQLNode(signal, node) + if candidate != nil && lowerMExpr(&MCountIf{Filter: candidate}, 0) == "count_if("+body+")" { + e = candidate + } + } + if e == nil { + var err error + e, _, err = liftEntry(ctx, p, signal, body) + if err != nil { + return "", err + } + } + b.WriteString(text[end:tokens[i+1].end]) + b.WriteString(printEntry(e, false)) + end = tokens[j].start + i = j + } + b.WriteString(text[end:]) + return b.String(), nil +} + +// ownSQLReader recognizes only the expression productions emitted by lowerEntry. +// Quoting is scanned rather than split, so clause words and delimiters inside a +// SQL literal cannot affect the tree. +type ownSQLToken struct { + text string + quote byte + start, end int +} + +func ownSQLTokens(text string) []ownSQLToken { + var out []ownSQLToken + for i := 0; i < len(text); { + if strings.ContainsRune(" \t\r\n", rune(text[i])) { + i++ + continue + } + start := i + c := text[i] + if c == '\'' || c == '"' { + quote := c + i++ + var b strings.Builder + for i < len(text) { + if text[i] == quote { + if i+1 < len(text) && text[i+1] == quote { + b.WriteByte(quote) + i += 2 + continue + } + i++ + break + } + b.WriteByte(text[i]) + i++ + } + out = append(out, ownSQLToken{text: b.String(), quote: quote, start: start, end: i}) + continue + } + if strings.ContainsRune("(),[]", rune(c)) { + i++ + out = append(out, ownSQLToken{text: string(c), start: start, end: i}) + continue + } + if strings.ContainsRune("=<>!~:", rune(c)) { + i++ + for i < len(text) && strings.ContainsRune("=<>!~:*", rune(text[i])) { + i++ + } + out = append(out, ownSQLToken{text: text[start:i], start: start, end: i}) + continue + } + for i < len(text) && !strings.ContainsRune(" \t\r\n(),[]=<>!~:'\"", rune(text[i])) { + i++ + } + if i == start { + i++ + } + out = append(out, ownSQLToken{text: text[start:i], start: start, end: i}) + } + return out +} + +type ownSQLReader struct { + tokens []ownSQLToken + pos int + failed bool +} + +func (r *ownSQLReader) peek() string { + if r.pos == len(r.tokens) { + return "" + } + if r.tokens[r.pos].quote != 0 { + return "#quoted" + } + return strings.ToUpper(r.tokens[r.pos].text) +} +func (r *ownSQLReader) eat(s string) bool { + if r.peek() == s { + r.pos++ + return true + } + return false +} +func (r *ownSQLReader) need(s string) { + if !r.eat(s) { + r.failed = true + } +} +func (r *ownSQLReader) expression(min int) map[string]any { + left := r.predicate() + for { + op := r.peek() + prec := 0 + if op == "OR" { + prec = 1 + } + if op == "AND" { + prec = 2 + } + if prec == 0 || prec < min { + break + } + r.pos++ + right := r.expression(prec + 1) + kind := "CONJUNCTION_" + op + if left["class"] == "CONJUNCTION" && left["type"] == kind && left["own_group"] != true { + children, _ := left["children"].([]any) + left["children"] = append(children, right) + } else { + left = map[string]any{"class": "CONJUNCTION", "type": kind, "children": []any{left, right}} + } + } + return left +} +func (r *ownSQLReader) predicate() map[string]any { + if r.eat("NOT") { + return ownOperator("OPERATOR_NOT", r.predicate()) + } + left := r.atom() + op := r.peek() + if kind := map[string]string{"=": "COMPARE_EQUAL", "!=": "COMPARE_NOTEQUAL", "<>": "COMPARE_NOTEQUAL", "<": "COMPARE_LESSTHAN", ">": "COMPARE_GREATERTHAN", "<=": "COMPARE_LESSTHANOREQUALTO", ">=": "COMPARE_GREATERTHANOREQUALTO"}[op]; kind != "" { + r.pos++ + return map[string]any{"class": "COMPARISON", "type": kind, "left": left, "right": r.atom()} + } + if r.eat("IS") { + neg := r.eat("NOT") + r.need("NULL") + kind := "OPERATOR_IS_NULL" + if neg { + kind = "OPERATOR_IS_NOT_NULL" + } + return ownOperator(kind, left) + } + neg := r.eat("NOT") + if r.eat("IN") { + children := []any{left} + if r.eat("(") { + for { + children = append(children, r.atom()) + if !r.eat(",") { + break + } + } + r.need(")") + } else { + children = append(children, r.atom()) + } + kind := "COMPARE_IN" + if neg { + kind = "COMPARE_NOT_IN" + } + return ownOperator(kind, children...) + } + if r.eat("BETWEEN") { + lo := r.atom() + r.need("AND") + hi := r.atom() + return map[string]any{"class": "BETWEEN", "type": "COMPARE_BETWEEN", "input": left, "lower": lo, "upper": hi, "negated": neg} + } + op = r.peek() + if op == "~~" || op == "!~~" || op == "~~*" || op == "!~~*" { + r.pos++ + return ownFunction(strings.ToLower(op), []any{left, r.atom()}) + } + if neg { + r.failed = true + } + return left +} +func (r *ownSQLReader) atom() map[string]any { + if r.pos >= len(r.tokens) { + r.failed = true + return nil + } + if r.eat("(") { + node := r.expression(0) + r.need(")") + if node != nil { + node["own_group"] = true + } + return node + } + token := r.tokens[r.pos] + r.pos++ + var node map[string]any + switch { + case token.quote == '\'': + node = ownConstant("STRING", token.text) + case token.quote == '"': + node = map[string]any{"class": "COLUMN_REF", "column_names": []any{token.text}} + case strings.EqualFold(token.text, "true") || strings.EqualFold(token.text, "false"): + node = ownConstant("BOOLEAN", strings.ToLower(token.text)) + case numberPattern.MatchString(token.text): + node = ownConstant("NUMERIC", token.text) + case strings.HasPrefix(token.text, "$"): + node = map[string]any{"class": "PARAMETER", "identifier": strings.TrimPrefix(token.text, "$")} + case r.eat("("): + name := strings.ToLower(token.text) + if name == "cast" || name == "try_cast" { + child := r.expression(0) + r.need("AS") + if r.pos == len(r.tokens) { + r.failed = true + return nil + } + typ := strings.ToUpper(r.tokens[r.pos].text) + r.pos++ + r.need(")") + node = map[string]any{"class": "CAST", "type": "OPERATOR_CAST", "child": child, "try_cast": name == "try_cast", "type_expr": map[string]any{"type_name": typ}} + } else { + var args []any + if !r.eat(")") { + for { + args = append(args, r.expression(0)) + if !r.eat(",") { + break + } + } + r.need(")") + } + if name == "coalesce" { + node = ownOperator("OPERATOR_COALESCE", args...) + } else { + node = ownFunction(name, args) + } + } + default: + node = map[string]any{"class": "COLUMN_REF", "column_names": []any{token.text}} + } + if r.eat("[") { + key := r.atom() + r.need("]") + node = ownOperator("ARRAY_EXTRACT", node, key) + } + if r.eat("::") { + if r.pos == len(r.tokens) { + r.failed = true + return nil + } + typ := strings.ToUpper(r.tokens[r.pos].text) + r.pos++ + node = map[string]any{"class": "CAST", "child": node, "type_expr": map[string]any{"type_name": typ}} + } + return node +} +func ownConstant(kind, text string) map[string]any { + return map[string]any{"class": "CONSTANT", "literal": map[string]any{"kind": kind, "text": text}} +} +func ownOperator(kind string, children ...any) map[string]any { + return map[string]any{"class": "OPERATOR", "type": kind, "children": children} +} +func ownFunction(name string, args []any) map[string]any { + entries := make([]any, len(args)) + for i, a := range args { + entries[i] = map[string]any{"expression": a} + } + return map[string]any{"class": "FUNCTION", "function_name": name, "arguments": entries} +} diff --git a/internal/fanql/lift_test.go b/internal/fanql/lift_test.go new file mode 100644 index 00000000..eddb9aac --- /dev/null +++ b/internal/fanql/lift_test.go @@ -0,0 +1,352 @@ +package fanql + +import ( + "context" + "errors" + "fmt" + "reflect" + "strings" + "testing" + + "github.com/labstack/fanout/internal/panel" +) + +type countingParser struct { + panel.Parser + calls int + fail bool + failErr error +} + +func (p *countingParser) ParseSQL(ctx context.Context, text string) (map[string]any, error) { + p.calls++ + if p.failErr != nil { + return nil, p.failErr + } + if p.fail { + return nil, context.DeadlineExceeded + } + return p.Parser.ParseSQL(ctx, text) +} + +func TestFormatOwnLoweringNeedsNoEngine(t *testing.T) { + for _, text := range glanceExamples { + t.Run(text, func(t *testing.T) { + c, problems := Compile(text, Options{}) + if len(problems) != 0 { + t.Fatalf("compile: %+v", problems) + } + p := &countingParser{fail: true} + f, problems, err := Format(t.Context(), p, c.Query, FormatOptions{}) + if err != nil || len(problems) != 0 { + t.Fatalf("format: %+v %v", problems, err) + } + if f.Exactness != "exact" || !f.Editable || f.Text != c.Canonical || p.calls != 0 { + t.Fatalf("format: %+v, calls %d; want %q", f, p.calls, c.Canonical) + } + }) + } +} + +func TestLiftStoredSQLShapes(t *testing.T) { + d, _ := newTestEngine(t) + for _, tt := range []struct{ signal, sql, text, tier string }{ + {"spans", `service = 'api'`, `service:api`, "exact"}, + {"spans", `service='api'`, `service:api`, "normalized"}, + {"spans", `status = 'STATUS_CODE_ERROR'`, `status:error`, "exact"}, + {"spans", `kind = 'SPAN_KIND_SERVER'`, `kind:server`, "exact"}, + {"spans", `duration_ms > 500`, `duration>500ms`, "exact"}, + {"spans", `duration_ms > 1500`, `duration>1.5s`, "exact"}, + {"spans", `attributes['http.target'] != '/healthz'`, `http.target!=/healthz`, "exact"}, + {"spans", `(attributes['k'] IS NULL OR attributes['k'] != 'v')`, `-attributes['k']:v`, "exact"}, + {"spans", `NOT (attributes['k'] = 'v')`, "`NOT (attributes['k'] = 'v')`", "exact"}, + {"logs", `NOT (body ~~ 'x%')`, "`NOT (body ~~ 'x%')`", "exact"}, + {"logs", `body !~~ 'x%'`, `body not like "x%"`, "exact"}, + {"spans", `service NOT IN ('a', 'b')`, `service not in (a, b)`, "exact"}, + {"spans", `NOT coalesce((attributes['k'] = 'v'), FALSE)`, "`NOT coalesce((attributes['k'] = 'v'), FALSE)`", "exact"}, + {"spans", `NOT coalesce((TRY_CAST(http_status_code AS INTEGER) BETWEEN 400 AND 599), FALSE)`, `-http_status_code between 400 and 599`, "exact"}, + {"spans", `(service IS NULL OR service IN ('a', 'b'))`, `-service not in (a, b)`, "exact"}, + {"spans", `TRY_CAST(http_status_code AS INTEGER) >= 500`, `http_status_code>=500`, "exact"}, + {"logs", `severity IN ('WARN', 'ERROR', 'FATAL')`, `severity>=warn`, "exact"}, + {"logs", `severity IN ('INFO', 'ERROR')`, `severity in (info, error)`, "exact"}, + {"logs", `severity IN ('INFO', 'WARN', 'ERROR')`, `severity between info and error`, "exact"}, + {"logs", `contains(lower(body), lower('timeout'))`, `timeout`, "exact"}, + {"spans", `contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('v'))`, `attributes['k'] ~ v`, "exact"}, + {"spans", `start_time > '2026-10-29T10:00:00Z'::TIMESTAMPTZ_NS`, `start_time>"2026-10-29T10:00:00Z"`, "exact"}, + {"spans", `service IN $svcs`, `service in $svcs`, "exact"}, + {"spans", `service = $service`, `service:$service`, "exact"}, + {"spans", `lower(operation) = 'v'`, "`lower(operation) = 'v'`", "exact"}, + {"spans", `starts_with(http_route, '/api')`, `starts_with(http_route, "/api")`, "exact"}, + {"logs", `length(body) > 1000`, `length(body)>1000`, "exact"}, + {"spans", `service = $service AND status = 'STATUS_CODE_ERROR'`, `(service:$service status:error)`, "normalized"}, + } { + t.Run(tt.sql, func(t *testing.T) { + q := panel.Query{From: tt.signal, Where: []string{tt.sql}} + f, problems, err := Format(t.Context(), d, q, FormatOptions{}) + if err != nil || len(problems) != 0 { + t.Fatalf("format: %+v %v", problems, err) + } + if f.Text != tt.signal+" where "+tt.text || f.Exactness != tt.tier { + t.Fatalf("got %+v, want %q %s", f, tt.text, tt.tier) + } + c, ps := Compile(f.Text, Options{}) + if len(ps) != 0 || len(c.Query.Where) != 1 { + t.Fatalf("recompile: %+v %+v", c, ps) + } + if f.Exactness == "exact" { + if !reflect.DeepEqual(c.Query, q) { + t.Fatalf("not exact: %#v != %#v", c.Query, q) + } + } else { + a, _ := d.ParseSQL(t.Context(), "SELECT 1 FROM "+tt.signal+" WHERE ("+tt.sql+")") + b, _ := d.ParseSQL(t.Context(), "SELECT 1 FROM "+tt.signal+" WHERE ("+c.Query.Where[0]+")") + x, _ := d.RenderSQL(t.Context(), a) + y, _ := d.RenderSQL(t.Context(), b) + if x != y { + t.Fatalf("not normalized: %q != %q", x, y) + } + if tt.sql == `service='api'` && (len(f.Notices) == 0 || f.Notices[0].Message != `where[0] is shown as service:api; stored text is "service='api'"`) { + t.Fatalf("notice: %+v", f.Notices) + } + } + }) + } + q := panel.Query{From: "spans", Where: []string{`attributes['a'] = 1 OR attributes['b'] = 2`, `service = 'api'`}} + f, ps, err := Format(t.Context(), d, q, FormatOptions{}) + if err != nil || len(ps) > 0 || f.Text != `spans where (attributes['a']:1 or attributes['b']:2) service:api` { + t.Fatalf("entry grouping: %+v %+v %v", f, ps, err) + } +} + +func TestLiftMeasures(t *testing.T) { + d, _ := newTestEngine(t) + for _, tt := range []struct{ stored, want, tier string }{ + {`p95( duration_ms )`, `p95(duration)`, "normalized"}, + {`count() as n`, `count() as n`, "exact"}, + {`count_distinct(attributes['user.id'])`, `count_distinct(user.id)`, "exact"}, + {`quantile(duration_ms, 0.999) as q`, `quantile(duration, 0.999) as q`, "exact"}, + } { + f, ps, err := Format(t.Context(), d, panel.Query{From: "spans", Measures: []string{tt.stored}}, FormatOptions{}) + if err != nil || len(ps) > 0 || f.Text != "spans | "+tt.want || f.Exactness != tt.tier { + t.Fatalf("%s: %+v %+v %v", tt.stored, f, ps, err) + } + } + q := panel.Query{From: "spans", Measures: []string{"count()"}, Histogram: &panel.Histogram{Field: "duration_ms", Buckets: "log2"}} + f, ps, err := Format(t.Context(), d, q, FormatOptions{}) + if err != nil || len(ps) > 0 || f.Text != "spans | histogram(duration)" { + t.Fatalf("histogram: %+v %+v %v", f, ps, err) + } + q.Measures = []string{"p95(duration_ms)"} + f, ps, err = Format(t.Context(), d, q, FormatOptions{}) + if err != nil || len(ps) == 0 || f != nil { + t.Fatalf("invalid histogram: %+v %+v %v", f, ps, err) + } + for _, sort := range []string{"errors", "duration_ms", "+start"} { + f, ps, err = Format(t.Context(), d, panel.Query{From: "spans", Sort: sort}, FormatOptions{Viz: "traces"}) + want := sort + if sort == "duration_ms" { + want = "duration" + } + if err != nil || len(ps) > 0 || f.Text != "spans sort "+want { + t.Fatalf("sort: %+v %+v %v", f, ps, err) + } + if sort == "errors" && (len(f.Notices) == 0 || !strings.Contains(f.Notices[0].Message, "sort errors also filters")) { + t.Fatalf("notice: %+v", f.Notices) + } + } +} + +func TestFormatEditableFalseIsCompleteAndReasoned(t *testing.T) { + d, _ := newTestEngine(t) + q := panel.Query{From: "logs"} + for i := range 16 { + q.Where = append(q.Where, "body = '"+strings.Repeat("x", 480)+fmt.Sprint(i)+"'") + } + f, ps, err := Format(t.Context(), d, q, FormatOptions{}) + if err != nil || len(ps) > 0 { + t.Fatalf("format: %+v %v", ps, err) + } + if f.Editable || f.Exactness != "exact" || f.Reason != "formatted text is 7,808 characters; the editor accepts 4,000" { + t.Fatalf("oversized: %+v", f) + } + for i := range 16 { + if !strings.Contains(f.Text, strings.Repeat("x", 480)+fmt.Sprint(i)) { + t.Fatalf("lost literal %d", i) + } + } + rawQuery := panel.Query{From: "logs"} + for i := range 16 { + rawQuery.Where = append(rawQuery.Where, "coalesce(body, '"+strings.Repeat("𝔘", 110)+strings.Repeat("`", 30)+fmt.Sprint(i)+"') = ''") + } + rawFormat, ps, err := Format(t.Context(), d, rawQuery, FormatOptions{}) + if err != nil || len(ps) > 0 { + t.Fatalf("raw format: %+v %v", ps, err) + } + if rawFormat.Editable || rawFormat.Exactness != "exact" || rawFormat.Reason != "formatted text is 8,448 bytes; the editor accepts 8,192" { + t.Fatalf("raw byte bound: %+v", rawFormat) + } + for _, entry := range rawQuery.Where { + if !strings.Contains(rawFormat.Text, strings.ReplaceAll(entry, "`", "``")) { + t.Fatal("lost raw literal") + } + } + // Bounds are independent even when no stored, shape-valid query can generate + // a single 4K raw entry (the filter contract caps each entry at 500 bytes). + if reason := editableReason("logs where `" + strings.Repeat("x", 4279) + strings.Repeat("``", 10) + "`"); reason != "formatted text is 4,312 characters; the editor accepts 4,000" { + t.Fatalf("characters: %q", reason) + } + if reason := editableReason("logs where " + strings.Repeat("a ", 1100)); reason != "formatted text is 1,102 tokens; the editor accepts 1,024" { + t.Fatalf("tokens: %q", reason) + } + if reason := editableReason("logs where \"" + strings.Repeat("𝔘", 2100) + "\""); reason != "formatted text is 8,413 bytes; the editor accepts 8,192" { + t.Fatalf("bytes: %q", reason) + } +} + +func TestFormatOperationalErrorIsReturnedNotAProblem(t *testing.T) { + for _, wantErr := range []error{context.DeadlineExceeded, errors.New("disk failure")} { + f, ps, err := Format(t.Context(), &countingParser{failErr: wantErr}, panel.Query{From: "logs", Where: []string{`coalesce(body, '') = ''`}}, FormatOptions{}) + if f != nil || len(ps) > 0 || !errors.Is(err, wantErr) { + t.Fatalf("got %+v %+v %v", f, ps, err) + } + } +} + +type failingRenderParser struct { + panel.Parser + err error +} + +func (p failingRenderParser) RenderSQL(context.Context, map[string]any) (string, error) { + return "", p.err +} + +func TestFormatRenderOperationalErrorIsReturnedNotAProblem(t *testing.T) { + d, _ := newTestEngine(t) + wantErr := errors.New("engine serialization failed") + f, ps, err := Format(t.Context(), failingRenderParser{Parser: d, err: wantErr}, panel.Query{From: "spans", Where: []string{`service='api'`}}, FormatOptions{}) + if f != nil || len(ps) > 0 || !errors.Is(err, wantErr) { + t.Fatalf("got %+v %+v %v", f, ps, err) + } +} + +func TestFormatRejectsQueryInvalidUnderEveryViz(t *testing.T) { + p := &countingParser{fail: true} + f, ps, err := Format(t.Context(), p, panel.Query{From: "spans", Measures: []string{"count()"}, By: []string{"a", "b", "c", "d"}}, FormatOptions{}) + if f != nil || len(ps) == 0 || err != nil || p.calls != 0 { + t.Fatalf("got %+v %+v %v calls %d", f, ps, err, p.calls) + } +} + +func TestFormatOwnLoweringFilterFixturesNeedNoEngine(t *testing.T) { + for _, fixture := range lowerFixtures { + if strings.ContainsRune(fixture.text, '`') { + continue + } // Arbitrary raw SQL needs the engine's authority. + text := fixture.text + if strings.HasPrefix(text, "metrics ") { + text += " | count()" + } // Metrics has no fixed row visualization. + t.Run(text, func(t *testing.T) { + c, ps := Compile(text, Options{}) + if len(ps) > 0 { + t.Fatal(ps) + } + p := &countingParser{fail: true} + f, ps, err := Format(t.Context(), p, c.Query, FormatOptions{}) + if err != nil || len(ps) > 0 { + t.Fatalf("format %+v %v; canonical %q", ps, err, c.Canonical) + } + if f.Exactness != "exact" || f.Text != c.Canonical || p.calls != 0 { + t.Fatalf("got %+v calls %d, want %q", f, p.calls, c.Canonical) + } + c2, ps := Compile(f.Text, Options{}) + if len(ps) > 0 || !reflect.DeepEqual(c.Query, c2.Query) || c2.Canonical != c.Canonical { + t.Fatalf("fixed point: %+v %+v", c2, ps) + } + }) + } +} + +func TestFormatReportsIgnoredSortAndLimit(t *testing.T) { + for _, tt := range []struct { + viz string + q panel.Query + }{ + {"timeseries", panel.Query{From: "spans", Measures: []string{"count()"}, Bucket: "auto", Sort: "count", Limit: 10}}, + {"stat", panel.Query{From: "spans", Measures: []string{"count()"}, Limit: 10}}, + {"gauge", panel.Query{From: "spans", Measures: []string{"count()"}, Limit: 10}}, + } { + f, ps, err := Format(t.Context(), &countingParser{fail: true}, tt.q, FormatOptions{Viz: tt.viz}) + if err != nil || len(ps) > 0 || len(f.Notices) != 1 || f.Notices[0].Message != "sort does not apply to bucketed series; series are chosen by top (options)" { + t.Fatalf("%s: %+v %+v %v", tt.viz, f, ps, err) + } + } +} + +func TestFormatOwnSeverityBandsAreFixedPoints(t *testing.T) { + for _, text := range []string{ + `logs where severity not between info and error`, + `logs where -severity>=warn`, + `logs where severity in (info, warn, error)`, + `logs where -severity not between info and error`, + `logs where severity>error`, + `logs where severity 0 { + t.Fatal(ps) + } + p := &countingParser{fail: true} + f, ps, err := Format(t.Context(), p, c.Query, FormatOptions{}) + if err != nil || len(ps) > 0 || f.Exactness != "exact" || f.Text != c.Canonical || p.calls != 0 { + t.Fatalf("format %+v %+v %v calls %d, want %q", f, ps, err, p.calls, c.Canonical) + } + again, ps := Compile(f.Text, Options{}) + if len(ps) > 0 || !reflect.DeepEqual(again.Query, c.Query) { + t.Fatalf("fixed point: %+v %+v", again, ps) + } + }) + } +} + +func TestFormatOwnLiteralSpellingsAreFixedPoints(t *testing.T) { + for _, text := range []string{ + `spans where status:"STATUS_CODE_ERROR"`, + `spans where kind:"SPAN_KIND_SERVER"`, + `spans where status:"error"`, + `logs where severity:"ERROR"`, + `logs where severity:"error"`, + `metrics where type:COUNTER | count()`, + `metrics where type:"counter" | count()`, + `spans where http_status_code:2e3`, + `logs where service:"TRUE"`, + `spans | count(*)`, + `logs where severity:14`, + `logs where severity:true`, + `logs where severity:"TRUE"`, + `logs where severity:"1H"`, + `logs where severity:where`, + `spans where status:500`, + `metrics where type:false | count()`, + } { + t.Run(text, func(t *testing.T) { + c, ps := Compile(text, Options{}) + if len(ps) > 0 { + t.Fatal(ps) + } + p := &countingParser{fail: true} + f, ps, err := Format(t.Context(), p, c.Query, FormatOptions{}) + if err != nil || len(ps) > 0 || f.Exactness != "exact" || f.Text != c.Canonical || p.calls != 0 { + t.Fatalf("format %+v %+v %v calls %d, want %q", f, ps, err, p.calls, c.Canonical) + } + again, ps := Compile(f.Text, Options{}) + if len(ps) > 0 || !reflect.DeepEqual(again.Query, c.Query) { + t.Fatalf("fixed point: %+v %+v", again, ps) + } + }) + } +} diff --git a/internal/fanql/lower.go b/internal/fanql/lower.go index 636906bb..963af36d 100644 --- a/internal/fanql/lower.go +++ b/internal/fanql/lower.go @@ -298,6 +298,13 @@ func lowerCall(c *Call) string { p := c.Name + "(" + strings.Join(args, ", ") + ")" if c.Cmp != nil { v := c.Cmp.Value.Text + if c.Cmp.Value.Kind == NumberValue { + n, _ := strconv.ParseFloat(v, 64) + v = decimal(n) + } + if c.Cmp.Value.Kind == BooleanValue { + v = strings.ToLower(v) + } if c.Cmp.Value.Kind != NumberValue && c.Cmp.Value.Kind != BooleanValue { v = sqlString(v) } diff --git a/internal/fanql/parser.go b/internal/fanql/parser.go index 092dca6d..65460768 100644 --- a/internal/fanql/parser.go +++ b/internal/fanql/parser.go @@ -465,7 +465,9 @@ func (p *parser) primary(nested bool) Expr { if p.foreignTerm() { return nil } - if reserved[word] { + next := strings.ToLower(p.ahead(1).Text) + fieldOperator := isComparison(next) || next == ":" || next == "~" || next == "!~" || next == "is" || isFieldWordOperator(next) || next == "not" && isFieldWordOperator(strings.ToLower(p.ahead(2).Text)) + if reserved[word] && !fieldOperator { p.report(t.Span, "reserved", word) p.take() return nil diff --git a/internal/fanql/print.go b/internal/fanql/print.go new file mode 100644 index 00000000..7fbef331 --- /dev/null +++ b/internal/fanql/print.go @@ -0,0 +1,444 @@ +package fanql + +import ( + "strconv" + "strings" + "unicode" + + "github.com/labstack/fanout/internal/telemetry" +) + +func init() { resolvePrint = Print } + +// Print prints the canonical spelling of a resolved tree. This spelling is +// frozen for Version; in particular, filter entry boundaries are preserved. +func Print(q *Query) string { + if q == nil { + return "" + } + text := q.Source + if len(q.Where) > 0 { + entries := make([]string, len(q.Where)) + for i, e := range q.Where { + entries[i] = printEntry(e, len(q.Where) > 1) + } + text += " where " + strings.Join(entries, " ") + } + if s := q.Stage; s != nil { + text += " | " + if s.Histogram != nil { + text += "histogram(" + printField(*s.Histogram) + ")" + } else { + ms := make([]string, len(s.Measures)) + for i, m := range s.Measures { + ms[i] = printMeasure(m) + } + text += strings.Join(ms, ", ") + } + if len(s.By) > 0 { + by := make([]string, len(s.By)) + for i, f := range s.By { + by[i] = printField(f) + } + text += " by " + strings.Join(by, ", ") + } + if s.Bucket != "" { + text += " every " + s.Bucket + } + } + if q.Sort != nil { + text += " sort " + if q.Sort.Ascending { + text += "+" + } + key := q.Sort.Key + if key == "duration_ms" { + key = "duration" + } + text += key + } + if q.Limit != nil { + text += " limit " + strconv.Itoa(q.Limit.N) + } + return text +} + +func printEntry(e Expr, grouped bool) string { return printExpr(canonicalExpr(e, false), grouped) } + +// Canonical negation follows the lowerer's NNF so text with the same lowered +// form has a single spelling and can be lifted without origin metadata. +func canonicalExpr(e Expr, neg bool) Expr { + switch x := e.(type) { + case *Not: + return canonicalExpr(x.X, !neg) + case *And: + terms := make([]Expr, len(x.Terms)) + for i, t := range x.Terms { + terms[i] = canonicalExpr(t, neg) + } + if neg { + return &Or{Terms: terms, At: x.At} + } + return &And{Terms: terms, At: x.At} + case *Or: + terms := make([]Expr, len(x.Terms)) + for i, t := range x.Terms { + terms[i] = canonicalExpr(t, neg) + } + if neg { + return &And{Terms: terms, At: x.At} + } + return &Or{Terms: terms, At: x.At} + case *In: + if !x.Negated && x.Variable == "" && x.Field.Ref != nil && x.Field.Ref.Column == "severity" && x.Field.Ref.Key == "" { + if candidate := liftSeverityRange(x); candidate != x { + return canonicalExpr(candidate, neg) + } + } + case *Between: + if x.Negated && len(x.Bands) > 0 { + return canonicalExpr(bandMembership(x.Field, x.Bands, true), neg) + } + case *Compare: + if x.Op == "~" && x.Value.Kind != VariableValue && x.Field.Ref != nil && x.Field.Ref.Key == "" && (x.Field.Ref.Column == "body" || x.Field.Ref.Column == "operation") { + v := x.Value + v.Kind = WordValue + if v.Stored != "" { + v.Text = v.Stored + } + return canonicalExpr(&FreeText{Value: v, column: x.Field.Ref.Column, At: x.At}, neg) + } + if x.Op == "!~" { + copy := *x + copy.Op = "~" + return canonicalExpr(©, !neg) + } + } + if neg { + return &Not{X: e, At: e.Span()} + } + return e +} + +func printExpr(e Expr, grouped bool) string { + switch x := e.(type) { + case *And: + terms := make([]string, len(x.Terms)) + for i, t := range x.Terms { + terms[i] = printExpr(t, true) + } + return "(" + strings.Join(terms, " ") + ")" + case *Or: + terms := make([]string, len(x.Terms)) + for i, t := range x.Terms { + terms[i] = printExpr(t, true) + } + text := strings.Join(terms, " or ") + if grouped { + text = "(" + text + ")" + } + return text + case *Not: + odd := true + inner := x.X + for { + n, ok := inner.(*Not) + if !ok { + break + } + odd = !odd + inner = n.X + } + if !odd { + return printExpr(inner, grouped) + } + return "-" + printExpr(inner, true) + case *Compare: + if len(x.Bands) > 0 { + return printBandRange(x.Field, x.Bands) + } + op := x.Op + if op == "=" { + op = ":" + } + if op == "<>" { + op = "!=" + } + if op == "~" || op == "!~" { + return printField(x.Field) + " " + op + " " + printValue(x.Value, x.Field, false) + } + return printField(x.Field) + op + printValue(x.Value, x.Field, op == ":" || op == "=" || op == "!=" || op == "<>") + case *In: + op := " in " + if x.Negated { + op = " not in " + } + if x.Variable != "" { + return printField(x.Field) + op + "$" + x.Variable + } + vs := make([]string, len(x.Values)) + for i, v := range x.Values { + vs[i] = printValue(v, x.Field, true) + } + return printField(x.Field) + op + "(" + strings.Join(vs, ", ") + ")" + case *Between: + if len(x.Bands) > 0 && !x.Negated { + return printBandRange(x.Field, x.Bands) + } + op := " between " + if x.Negated { + op = " not between " + } + return printField(x.Field) + op + printValue(x.Lo, x.Field, false) + " and " + printValue(x.Hi, x.Field, false) + case *Like: + op := "like" + if x.Insensitive { + op = "ilike" + } + if x.Negated { + op = "not " + op + } + return printField(x.Field) + " " + op + " " + quoteText(x.Pattern.Text) + case *Exists: + return printField(x.Field) + ":*" + case *IsNull: + if x.Negated { + return printField(x.Field) + ":*" + } + return "-" + printField(x.Field) + ":*" + case *Call: + return printCall(x) + case *FreeText: + return printLiteral(x.Value, false) + case *RawExpr: + return "`" + strings.ReplaceAll(x.Text, "`", "``") + "`" + } + return "" +} + +func printField(f Field) string { + column, key := f.Key, "" + if f.Ref != nil { + column, key = f.Ref.Column, f.Ref.Key + } else if f.Scope != "" { + column, key = f.Scope, f.Key + } else if !f.Single { + column, key = "attributes", f.Key + } + if key == "" { + if column == "duration_ms" { + return "duration" + } + return column + } + if column == "attributes" && strings.Contains(key, ".") && !strings.HasPrefix(strings.ToLower(key), "resource.") && !strings.HasPrefix(strings.ToLower(key), "attributes.") && validPath(key) { + return key + } + if column == "resource" && validPath(key) { + return "resource." + key + } + return column + "['" + strings.ReplaceAll(key, "'", "''") + "']" +} + +func validPath(s string) bool { return identifierPath.MatchString(s) } + +func quoteText(s string) string { return `"` + strings.ReplaceAll(s, `"`, `""`) + `"` } + +func printValue(v Value, f Field, aliases bool) string { + if aliases && v.Kind != VariableValue { + stored := v.Stored + if stored == "" { + stored = v.Text + } + column := f.Key + if f.Ref != nil { + column = f.Ref.Column + if f.Ref.Key != "" { + column = "" + } + } + switch column { + case "status": + for alias, value := range statusAliases { + if stored == value { + return alias + } + } + case "kind": + for alias, value := range kindAliases { + if stored == value { + return alias + } + } + case "severity": + if v.Kind != StringValue || telemetry.SeverityFromText(stored) == stored { + alias := strings.ToLower(stored) + // Numeric, boolean and duration-shaped tokens are literals, not + // vocabulary words. Keep quoted strings' spelling in those cases. + if classify(Token{Kind: Word, Text: alias}).Kind == WordValue { + if bareValue(alias) { + return alias + } + return quoteText(stored) + } + } + case "type": + for alias, value := range typeAliases { + if stored == value { + return alias + } + } + } + } + if v.Kind == NumberValue && f.Ref != nil && f.Ref.Type == "string" && f.Ref.Key == "" && f.Ref.CompareAs == "" { + return v.Text + } + if v.Kind == StringValue { + if f.Ref != nil && f.Ref.Key == "" && f.Ref.Type == "string" && f.Ref.CompareAs == "" { + if numberPattern.MatchString(v.Text) { + return v.Text + } + if v.Text == "true" || v.Text == "false" { + return strings.ToLower(v.Text) + } + } + // A quoted value can deliberately bypass vocabulary mapping or force a + // string rather than a numeric/boolean attribute literal. + column := "" + if f.Ref != nil && f.Ref.Key == "" { + column = f.Ref.Column + } + if (!aliases || column != "status" && column != "kind" && column != "severity" && column != "type") && (f.Ref == nil || f.Ref.Type != "time") && bareValue(v.Text) && !numberPattern.MatchString(v.Text) && !durationPattern.MatchString(v.Text) && !strings.EqualFold(v.Text, "true") && !strings.EqualFold(v.Text, "false") { + return v.Text + } + return quoteText(v.Text) + } + return printLiteral(v, false) +} + +func printLiteral(v Value, forceQuote bool) string { + if v.Kind == VariableValue { + return v.Text + } + if v.Kind == NumberValue { + if n, err := strconv.ParseFloat(v.Text, 64); err == nil { + return strconv.FormatFloat(n, 'f', -1, 64) + } + } + if v.Kind == BooleanValue { + return strings.ToLower(v.Text) + } + if v.Kind == DurationValue { + if ms, ok := durationMS(v.Text); ok { + return durationText(ms) + } + return strings.ToLower(v.Text) + } + if forceQuote || !bareValue(v.Text) { + return quoteText(v.Text) + } + return v.Text +} + +func bareValue(s string) bool { + if s == "" || strings.ContainsRune("-+$*", rune(s[0])) { + return false + } + if clauses[strings.ToLower(s)] || expressionWords[strings.ToLower(s)] || modifiers[strings.ToLower(s)] || reserved[strings.ToLower(s)] { + return false + } + for _, r := range s { + if unicode.IsSpace(r) || strings.ContainsRune("|(),:=!<>~\"'`[]#{}@", r) { + return false + } + } + return true +} + +func printCall(x *Call) string { + args := make([]string, len(x.Args)) + for i, a := range x.Args { + switch { + case a.Field != nil: + args[i] = printField(*a.Field) + case a.Value != nil: + args[i] = quoteText(a.Value.Text) + if a.Value.Kind == NumberValue { + args[i] = printLiteral(*a.Value, false) + } + case a.Call != nil: + args[i] = printCall(a.Call) + } + } + text := x.Name + "(" + strings.Join(args, ", ") + ")" + if x.Cmp != nil { + value := printLiteral(x.Cmp.Value, false) + if x.Cmp.Value.Kind == StringValue { + value = quoteText(x.Cmp.Value.Text) + } + text += x.Cmp.Op + value + } + return text +} + +func printMeasure(m Measure) string { + text := printMExpr(m.Expr, 0) + if m.Alias != "" { + text += " as " + m.Alias + } + return text +} + +func printMExpr(e MExpr, parent int) string { + switch x := e.(type) { + case *MCall: + if x.Name == "count" && len(x.Args) == 1 && x.Args[0].Star { + return "count()" + } + args := make([]string, len(x.Args)) + for i, a := range x.Args { + switch { + case a.Field != nil: + args[i] = printField(*a.Field) + case a.Number != nil: + args[i] = strconv.FormatFloat(*a.Number, 'f', -1, 64) + case a.Star: + args[i] = "*" + } + } + return x.Name + "(" + strings.Join(args, ", ") + ")" + case *MCountIf: + body := printEntry(x.Filter, false) + if _, ok := x.Filter.(*And); ok { + body = strings.TrimSuffix(strings.TrimPrefix(body, "("), ")") + } + return "count_if(" + body + ")" + case *MBinary: + prec := 1 + if x.Op == '*' || x.Op == '/' { + prec = 2 + } + text := printMExpr(x.L, prec) + " " + string(x.Op) + " " + printMExpr(x.R, prec+1) + if prec < parent { + text = "(" + text + ")" + } + return text + case *MNeg: + return "-" + printMExpr(x.X, 3) + case *MConst: + return strconv.FormatFloat(x.Value, 'f', -1, 64) + } + return "" +} + +func printBandRange(f Field, bands []string) string { + first, last := strings.ToLower(bands[0]), strings.ToLower(bands[len(bands)-1]) + field := printField(f) + if last == "fatal" { + return field + ">=" + first + } + if first == "trace" { + return field + "<=" + last + } + return field + " between " + first + " and " + last +} diff --git a/internal/fanql/print_test.go b/internal/fanql/print_test.go new file mode 100644 index 00000000..6855fffb --- /dev/null +++ b/internal/fanql/print_test.go @@ -0,0 +1,84 @@ +package fanql + +import ( + "reflect" + "testing" +) + +var canonicalCases = [][2]string{ + {`spans where attributes['attributes.k']:x`, `spans where attributes['attributes.k']:x`}, + {`spans where attributes['Resource.k']:x`, `spans where attributes['Resource.k']:x`}, + {`logs where length(body)>1e3`, `logs where length(body)>1000`}, + {`spans where status ~ STATUS_CODE_ERROR`, `spans where status ~ STATUS_CODE_ERROR`}, + {`spans where status>STATUS_CODE_ERROR`, `spans where status>STATUS_CODE_ERROR`}, + {`logs where severity ~ "ERROR"`, `logs where severity ~ ERROR`}, + {`logs where body ~ 2e3`, `logs where 2e3`}, + {`logs where body ~ $term`, `logs where body ~ $term`}, + {`spans where http_status_code:2e3`, `spans where http_status_code:2e3`}, + {`logs where service:"TRUE"`, `logs where service:"TRUE"`}, + {`spans where attributes['é.x']:api`, `spans where attributes['é.x']:api`}, + {`spans where duration > 500ms`, `spans where duration>500ms`}, + {`logs where --severity:error`, `logs where severity:error`}, + {`spans where flag:true`, `spans where attributes['flag']:true`}, + {`spans where attributes.http.target:/h`, `spans where http.target:/h`}, + {`spans where attributes['resource.k']:x`, `spans where attributes['resource.k']:x`}, + {`spans status:error | count() by service`, `spans where status:error | count() by service`}, + {`spans | count() by service sort -count`, `spans | count() by service sort count`}, + {`spans | count() by service | sort count | limit 10`, `spans | count() by service sort count limit 10`}, + {`spans where k:>5`, `spans where attributes['k']>5`}, + {`logs where "limit"`, `logs where "limit"`}, + {`logs where top:x`, `logs where attributes['top']:x`}, + {`spans | count_distinct(attributes['user.id'])`, `spans | count_distinct(user.id)`}, + {`spans | count_distinct(flag)`, `spans | count_distinct(attributes['flag'])`}, + {`spans | P95(Duration)`, `spans | p95(duration)`}, + {`spans | avg(attributes.http.response_size) as sz`, `spans | avg(http.response_size) as sz`}, + {`spans where kind:server | count_if(status:error -http.target:/healthz) / count() * 100 as e`, `spans where kind:server | count_if(status:error -http.target:/healthz) / count() * 100 as e`}, + {`SPANS WHERE Service:API | COUNT() EVERY 1M`, `spans where service:API | count() every 1m`}, + {`spans where service:$service (status:error or status:unset)`, `spans where service:$service (status:error or status:unset)`}, + {`spans where (a:1 b:2)`, `spans where (attributes['a']:1 attributes['b']:2)`}, + {`spans where a:1 or b:2`, `spans where attributes['a']:1 or attributes['b']:2`}, +} + +func TestPrintCanonical(t *testing.T) { + for _, tt := range canonicalCases { + t.Run(tt[0], func(t *testing.T) { + c, problems := Compile(tt[0], Options{}) + if len(problems) != 0 { + t.Fatalf("compile: %+v", problems) + } + if c.Canonical != tt[1] { + t.Fatalf("got %q, want %q", c.Canonical, tt[1]) + } + }) + } +} + +func TestPrintIsAFixedPoint(t *testing.T) { + for _, tt := range canonicalCases { + a, problems := Compile(tt[0], Options{}) + if len(problems) != 0 { + t.Fatalf("%s: %+v", tt[0], problems) + } + b, problems := Compile(a.Canonical, Options{}) + if len(problems) != 0 { + t.Fatalf("%s: %+v", a.Canonical, problems) + } + if b.Canonical != a.Canonical || !reflect.DeepEqual(a.Query, b.Query) { + t.Fatalf("not a fixed point: %q -> %q; %#v != %#v", tt[0], b.Canonical, a.Query, b.Query) + } + } +} + +func TestPrintCompatibleEditPlacesBucketBeforeSortAndLimit(t *testing.T) { + c, ps := Compile(`spans | count() by service sort count limit 10`, Options{}) + if len(ps) > 0 { + t.Fatal(ps) + } + if len(c.Edits) != 1 || c.Edits[0].Text != `spans | count() by service every auto sort count limit 10` { + t.Fatalf("edits: %+v", c.Edits) + } + edited, ps := Compile(c.Edits[0].Text, Options{Viz: "timeseries"}) + if len(ps) > 0 || edited.Query.Bucket != "auto" || edited.Query.Sort != "count" || edited.Query.Limit != 10 { + t.Fatalf("applied edit: %+v %+v", edited, ps) + } +} diff --git a/internal/fanql/resolve.go b/internal/fanql/resolve.go index d9c04594..7f872d81 100644 --- a/internal/fanql/resolve.go +++ b/internal/fanql/resolve.go @@ -99,7 +99,11 @@ func Resolve(q *Query, opts ResolveOptions) (*Resolved, panel.Problems) { if pq.Bucket == "" && q.Stage != nil && q.Stage.Histogram == nil { pq.Bucket = "auto" if ps, _ := panel.QueryShape(&pq, "timeseries", vars); len(ps) == 0 && resolvePrint != nil { - r.out.Edits = append(r.out.Edits, VizEdit{Viz: "timeseries", Text: resolvePrint(q) + " every auto"}) + edit := *q + stage := *q.Stage + stage.Bucket = "auto" + edit.Stage = &stage + r.out.Edits = append(r.out.Edits, VizEdit{Viz: "timeseries", Text: resolvePrint(&edit)}) } } } @@ -293,7 +297,7 @@ func (r *resolver) value(f *Field, v *Value, op string, multi bool) { if v.Kind == BooleanValue { v.Stored = strings.ToLower(v.Text) } - if v.Kind == StringValue || !(op == ":" || op == "=" || op == "!=" || op == "<>" || op == "in") || ref.Key != "" { + if v.Kind != WordValue || !(op == ":" || op == "=" || op == "!=" || op == "<>" || op == "in") || ref.Key != "" { return } var table map[string]string diff --git a/internal/fanql/resolve_test.go b/internal/fanql/resolve_test.go index 8aa70f9f..8fe73ec0 100644 --- a/internal/fanql/resolve_test.go +++ b/internal/fanql/resolve_test.go @@ -138,6 +138,16 @@ func TestResolveSeverityRanges(t *testing.T) { } func TestResolveTypedLiterals(t *testing.T) { + for _, text := range []string{"logs where severity:14", "logs where severity:true", "spans where status:500", "metrics where type:false"} { + r, ps := resolvedText(t, text, ResolveOptions{}) + if len(ps) != 0 { + t.Fatal(text, ps) + } + v := r.Query.Where[0].(*Compare).Value + if v.Stored != v.Text { + t.Fatalf("typed literals must not be vocabulary words: %#v", v) + } + } for _, text := range []string{"spans where duration_ms>500", `spans where start_time>"2026-10-29T10:00:00Z"`, `spans where start_time>"2026-10-29 10:00:00"`} { _, ps := resolvedText(t, text, ResolveOptions{}) if len(ps) > 0 { @@ -271,9 +281,6 @@ func TestResolveVariables(t *testing.T) { } func TestResolveCompatibleVizzesAndEdits(t *testing.T) { - if resolveLower == nil { - t.Skip("Task 4 installs the lowering hook") - } r, ps := resolvedText(t, "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route", ResolveOptions{}) if len(ps) > 0 { t.Fatal(ps) @@ -285,8 +292,7 @@ func TestResolveCompatibleVizzesAndEdits(t *testing.T) { if !reflect.DeepEqual(names, []string{"bar", "table"}) { t.Fatal(r.Compatible) } - // Task 5 supplies the canonical printer used for edit text. - if resolvePrint != nil && (len(r.Edits) != 1 || r.Edits[0].Viz != "timeseries" || r.Edits[0].Text != "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route every auto") { + if len(r.Edits) != 1 || r.Edits[0].Viz != "timeseries" || r.Edits[0].Text != "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route every auto" { t.Fatal(r.Edits) } r, ps = resolvedText(t, "spans where status:error", ResolveOptions{}) diff --git a/internal/fanql/testhelpers_test.go b/internal/fanql/testhelpers_test.go new file mode 100644 index 00000000..eff2183f --- /dev/null +++ b/internal/fanql/testhelpers_test.go @@ -0,0 +1,25 @@ +package fanql + +import ( + "testing" + "time" + + "github.com/labstack/fanout/internal/config" + "github.com/labstack/fanout/internal/query" + telemetrystore "github.com/labstack/fanout/internal/telemetry/store" +) + +func newTestEngine(t *testing.T) (*query.Duck, *telemetrystore.Repository) { + t.Helper() + cfg := config.Config{DataDir: t.TempDir(), DuckDBMemory: "256MB", DuckDBThreads: 2, DuckDBMaxConns: 4, RollupInterval: time.Hour} + repo, err := telemetrystore.Open(cfg.TelemetryDir()) + if err != nil { + t.Fatal(err) + } + d, err := query.NewDuck(t.Context(), cfg, repo) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = d.Close(); _ = repo.Close() }) + return d, repo +} diff --git a/internal/panel/measure.go b/internal/panel/measure.go index 48cb3217..95dbe2f8 100644 --- a/internal/panel/measure.go +++ b/internal/panel/measure.go @@ -165,3 +165,19 @@ func sanitize(value string) string { } return strings.Trim(b.String(), "_") } + +// ParseMeasure parses one stored aggregate measure for the named signal. +func ParseMeasure(signal, text string) (Measure, error) { + sig, ok := lookupSignal(signal) + if !ok { + return Measure{}, fmt.Errorf("unknown signal %q", signal) + } + m, message, hint := parseMeasure(sig, text) + if message != "" { + if hint != "" { + message += "; " + hint + } + return Measure{}, fmt.Errorf("%s", message) + } + return m, nil +} diff --git a/scripts/go-deadcode.allowlist b/scripts/go-deadcode.allowlist index ca01e549..c87824ff 100644 --- a/scripts/go-deadcode.allowlist +++ b/scripts/go-deadcode.allowlist @@ -10,3 +10,4 @@ github.com/labstack/fanout/internal/panel.QueryShape FanQL shape-check library e github.com/labstack/fanout/internal/panel.CompatibleVizzes FanQL visualization compatibility library entry point; production HTTP consumers land in batch 1 Task 8. github.com/labstack/fanout/internal/telemetry.SeverityAliases Shared FanQL vocabulary/reference library entry point; production consumers land in batch 1 Tasks 8–10. github.com/labstack/fanout/internal/telemetry.SeverityRank FanQL severity range library entry point; production HTTP/MCP consumers land in batch 1 Tasks 8–9. +github.com/labstack/fanout/internal/panel.ParseMeasure FanQL stored-query formatting library entry point; production HTTP consumer lands in batch 1 Task 8. From e6fef6d0cb7b2209b60f40096e19d0f851078327 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 16:29:58 -0700 Subject: [PATCH 08/30] feat(panel): conditional aggregates and measure arithmetic with budgets and ranking --- internal/mcp/panels.go | 2 +- internal/panel/check.go | 54 ++ internal/panel/compile.go | 43 +- internal/panel/compile_expr_test.go | 136 +++++ internal/panel/exec.go | 44 +- internal/panel/frame.go | 1 + internal/panel/items.go | 2 +- internal/panel/measure.go | 478 ++++++++++++++++-- internal/panel/measure_compile.go | 235 +++++++++ internal/panel/measure_expr_test.go | 220 ++++++++ internal/panel/metric_measures.go | 6 + internal/panel/ranking_expr_test.go | 264 ++++++++++ internal/panel/shape.go | 45 +- internal/panel/spec.go | 2 +- internal/panel/table_trends.go | 2 +- internal/panel/validate.go | 41 ++ site/src/content/docs/reference/mcp-tools.mdx | 2 +- ui/host/tests/go-fragments/logs.json | 11 + 18 files changed, 1483 insertions(+), 105 deletions(-) create mode 100644 internal/panel/compile_expr_test.go create mode 100644 internal/panel/measure_compile.go create mode 100644 internal/panel/measure_expr_test.go create mode 100644 internal/panel/ranking_expr_test.go diff --git a/internal/mcp/panels.go b/internal/mcp/panels.go index ae72f565..a938d29e 100644 --- a/internal/mcp/panels.go +++ b/internal/mcp/panels.go @@ -44,7 +44,7 @@ type PreviewOutput struct { Problems []panel.Problem `json:"problems,omitempty"` } -const baseSpecGuide = `A dashboard is {name, description, time:{range}, variables, panels}. Each panel: {id (lowercase), title, viz, width 1-12, query or sql}. viz: stat or gauge (one measure; gauge needs min and max), timeseries (bucket auto, at most one by), bar (one or two by), table (up to three by), text (content in Markdown), heatmap (bucket auto, no by), histogram (at most one by), scatter (exactly two measures in x then y order, one item dimension and an optional colour dimension), state_timeline (one measure, one item dimension, bucket auto and thresholds required). Rollup panel types are service_map (dependency graph) and health (overview metrics, error trend and health distribution). They require query.from=spans, no measures, by, bucket or sort, and only namespace/service equality filters with a literal or single-value variable; explicit casts and values with surrounding whitespace are rejected. Reads default to 400 services/edges and are capped at 400 even when query.limit is larger. Service scope applies before the limit; map nodes carry p95_ms and edges carry average_ms; error_rate is percent. Row panel types are logs, log_patterns and traces. Logs and traces take no measures, by or bucket. Patterns use count() by body_template. Patterns group only by body_template. Severity is the most frequent severity, ties choose the higher severity. Service is the most frequent service, ties choose ascending service name. Both describe the scoped, redacted events, not extra grouping dimensions. Each pattern returns dominant severity, top service, count and a dense trend, computed in the same bounded query after redaction and scoped filters. Redaction applies before filtering, grouping, display and drill-down. Row panels cannot use SQL. "erroring" means slowest erroring traces: filter to erroring traces, then rank by root duration. Trace candidate ranking is approximate when filters exclude the root span, as with exemplars. Categorical charts use fixed-order colour slots. Categorical options.top defaults to 6, maximum 6. Structured panels: the server computes Other; series are chosen worst-first by confidence (Wilson lower bound for error rates; at least 20 samples for latency); the rest fold into Other (N). Count, rate, sum and share rank largest first. Error rates require at least 20 requests for eligible Wilson ranking (z=1.96). Percentiles, quantile, avg, max and min require at least 20 non-null numeric samples for eligible value ranking and use better (explicit or inferred). Ineligible series follow eligible ones by sample count descending. Ties use sample count descending, then name ascending. SQL panels: series past six are left out, with a note. state_timeline defaults to 8 rows, maximum 20; other noncategorical panels use the same limits. Scatter supports options.x_scale and options.y_scale (log or linear), with distinct x_unit for x and unit for y, each inferred independently when omitted. Rows returned use the count unit. State timelines preserve null and absent buckets as unknown and keep the top items without merging them into Other. Scatter requires a structured query. SQL state_timeline requires timestamp time, a string item, one numeric measure and optional string state; its interval is one minute and thresholds are required. Items rank by volume (row count) for top N. Previous-period comparison is not drawn for scatter or state_timeline. Distribution panels use a structured query with one count() measure and histogram: {field: duration_ms, buckets: log2} for spans or {field: value, buckets: explicit} for metrics. Negative span durations clamp to [0,1); +Inf goes to overflow; NaN is excluded because it is not a measurement. Metric histograms use stored temporality and shared per-series increases; resets contribute current counts. Delta histograms sum observation weights. query: {from: spans|logs|metrics, where: [filter expressions], measures: [fn(field) as alias], by: [fields], bucket, sort, limit}. Measures: count(), rate() per second, error_rate() percent, share() percent, avg/min/max/sum(field), last(value) for metrics, p50/p75/p90/p95/p99(field), quantile(field, 0.999), count_distinct(field). Fields are columns from get_telemetry_schema or attributes['key'] / resource['key'] with the key written literally. Filters are SQL boolean expressions: service = $service, kind = 'SPAN_KIND_SERVER', status = 'STATUS_CODE_ERROR', http_route IN $routes, attributes['http.response.status_code']::INTEGER >= 500. Variables: {name, kind: query|custom|constant|text, from, field, default, include_all}; $__all selects All and removes filters that use the variable. sql: one SELECT over spans, logs, metrics, service_rollup, edge_rollup or resource_inventory that filters time with $__window(column).` + " " + panel.SQLTimestampGuide + ` Use values exactly as get_telemetry_schema lists them. Example panel: {"id":"latency","title":"Checkout latency","viz":"timeseries","width":8,"query":{"from":"spans","where":["service = 'checkout'","kind = 'SPAN_KIND_SERVER'"],"measures":["p50(duration_ms)","p95(duration_ms)","p99(duration_ms)"],"bucket":"auto"},"unit":"ms","thresholds":[{"value":1500,"status":"bad"}]}.` + " " + metricMeasureGuide + " " + resourceInventoryGuide +const baseSpecGuide = `A dashboard is {name, description, time:{range}, variables, panels}. Each panel: {id (lowercase), title, viz, width 1-12, query or sql}. viz: stat or gauge (one measure; gauge needs min and max), timeseries (bucket auto, at most one by), bar (one or two by), table (up to three by), text (content in Markdown), heatmap (bucket auto, no by), histogram (at most one by), scatter (exactly two measures in x then y order, one item dimension and an optional colour dimension), state_timeline (one measure, one item dimension, bucket auto and thresholds required). Rollup panel types are service_map (dependency graph) and health (overview metrics, error trend and health distribution). They require query.from=spans, no measures, by, bucket or sort, and only namespace/service equality filters with a literal or single-value variable; explicit casts and values with surrounding whitespace are rejected. Reads default to 400 services/edges and are capped at 400 even when query.limit is larger. Service scope applies before the limit; map nodes carry p95_ms and edges carry average_ms; error_rate is percent. Row panel types are logs, log_patterns and traces. Logs and traces take no measures, by or bucket. Patterns use count() by body_template. Patterns group only by body_template. Severity is the most frequent severity, ties choose the higher severity. Service is the most frequent service, ties choose ascending service name. Both describe the scoped, redacted events, not extra grouping dimensions. Each pattern returns dominant severity, top service, count and a dense trend, computed in the same bounded query after redaction and scoped filters. Redaction applies before filtering, grouping, display and drill-down. Row panels cannot use SQL. "erroring" means slowest erroring traces: filter to erroring traces, then rank by root duration. Trace candidate ranking is approximate when filters exclude the root span, as with exemplars. Categorical charts use fixed-order colour slots. Categorical options.top defaults to 6, maximum 6. Structured panels: the server computes Other; series are chosen worst-first by confidence (Wilson lower bound for error rates; at least 20 samples for latency); the rest fold into Other (N). Count, rate, sum and share rank largest first. Error rates require at least 20 requests for eligible Wilson ranking (z=1.96). Percentiles, quantile, avg, max and min require at least 20 non-null numeric samples for eligible value ranking and use better (explicit or inferred). Ineligible series follow eligible ones by sample count descending. Ties use sample count descending, then name ascending. SQL panels: series past six are left out, with a note. state_timeline defaults to 8 rows, maximum 20; other noncategorical panels use the same limits. Scatter supports options.x_scale and options.y_scale (log or linear), with distinct x_unit for x and unit for y, each inferred independently when omitted. Rows returned use the count unit. State timelines preserve null and absent buckets as unknown and keep the top items without merging them into Other. Scatter requires a structured query. SQL state_timeline requires timestamp time, a string item, one numeric measure and optional string state; its interval is one minute and thresholds are required. Items rank by volume (row count) for top N. Previous-period comparison is not drawn for scatter or state_timeline. Distribution panels use a structured query with one count() measure and histogram: {field: duration_ms, buckets: log2} for spans or {field: value, buckets: explicit} for metrics. Negative span durations clamp to [0,1); +Inf goes to overflow; NaN is excluded because it is not a measurement. Metric histograms use stored temporality and shared per-series increases; resets contribute current counts. Delta histograms sum observation weights. query: {from: spans|logs|metrics, where: [filter expressions], measures: [fn(field) as alias], by: [fields], bucket, sort, limit}. Measures: count(), rate() per second, error_rate() percent, share() percent, avg/min/max/sum(field), last(value) for metrics, p50/p75/p90/p95/p99(field), quantile(field, 0.999), count_distinct(field). Spans and logs aggregate panels also support count_if(SQL filter) and + - * / with constants and parentheses; arithmetic requires as alias and at least one aggregate, variables are not allowed inside count_if, share() stands alone, and division by zero returns null. Measures are bounded to 256 tokens, 64 nodes, depth 8 and 8 aggregates each, and 256 nodes and 24 aggregates together. Metrics do not support arithmetic. Fields are columns from get_telemetry_schema or attributes['key'] / resource['key'] with the key written literally. Filters are SQL boolean expressions: service = $service, kind = 'SPAN_KIND_SERVER', status = 'STATUS_CODE_ERROR', http_route IN $routes, attributes['http.response.status_code']::INTEGER >= 500. Variables: {name, kind: query|custom|constant|text, from, field, default, include_all}; $__all selects All and removes filters that use the variable. sql: one SELECT over spans, logs, metrics, service_rollup, edge_rollup or resource_inventory that filters time with $__window(column).` + " " + panel.SQLTimestampGuide + ` Use values exactly as get_telemetry_schema lists them. Example panel: {"id":"latency","title":"Checkout latency","viz":"timeseries","width":8,"query":{"from":"spans","where":["service = 'checkout'","kind = 'SPAN_KIND_SERVER'"],"measures":["p50(duration_ms)","p95(duration_ms)","p99(duration_ms)"],"bucket":"auto"},"unit":"ms","thresholds":[{"value":1500,"status":"bad"}]}.` + " " + metricMeasureGuide + " " + resourceInventoryGuide func (s *Server) registerPanelTools() { readOnly := &mcp.ToolAnnotations{ReadOnlyHint: true, OpenWorldHint: boolPtr(false)} diff --git a/internal/panel/check.go b/internal/panel/check.go index e0ca3fe6..39a52bc5 100644 --- a/internal/panel/check.go +++ b/internal/panel/check.go @@ -89,6 +89,24 @@ func Check(ctx context.Context, parser Parser, d *Dashboard) (*Checked, Problems } var ignored Problems checked.Measures[p.ID] = parseMeasures(sig, p.Query.Measures, "", &ignored) + for j := range checked.Measures[p.ID] { + m := &checked.Measures[p.ID][j] + expr, err := checkMeasureExpr(ctx, parser, sig, m.Expr) + if err != nil { + if isOperational(err) { + return nil, nil, err + } + problems.add(fmt.Sprintf("%s.query.measures[%d]", path, j), PresentError(err, SQLError)) + continue + } + m.Expr = expr + better := p.Better + if better == "" { + better = inferBetterExpr(m.Expr, p, sig) + } + m.Rank = rankRule(*m, sig, better) + } + for j, expr := range p.Query.Where { f, err := checkFilter(ctx, parser, sig, earlier, expr) if err != nil { @@ -236,3 +254,39 @@ func validateTimelineColumns(columns []Column) error { } return nil } + +// checkMeasureExpr sends each conditional aggregate through the same WHERE +// allowlist as panel filters, with no dashboard variables in its population. +func checkMeasureExpr(ctx context.Context, parser Parser, sig *signal, e MeasureExpr) (MeasureExpr, error) { + switch leaf := e.(type) { + case MeasureCountIf: + if varRefPattern.MatchString(stripQuoted(leaf.Filter)) { + return nil, errors.New("variables are not allowed inside count_if") + } + f, err := checkFilter(ctx, parser, sig, nil, leaf.Filter) + if err != nil { + return nil, err + } + if len(f.Params) > 0 { + return nil, errors.New("variables are not allowed inside count_if") + } + leaf.Expr = f.Expr + return leaf, nil + case MeasureBinary: + l, err := checkMeasureExpr(ctx, parser, sig, leaf.L) + if err != nil { + return nil, err + } + r, err := checkMeasureExpr(ctx, parser, sig, leaf.R) + if err != nil { + return nil, err + } + leaf.L, leaf.R = l, r + return leaf, nil + case MeasureNeg: + x, err := checkMeasureExpr(ctx, parser, sig, leaf.X) + leaf.X = x + return leaf, err + } + return e, nil +} diff --git a/internal/panel/compile.go b/internal/panel/compile.go index bd550ef8..2bf13e6e 100644 --- a/internal/panel/compile.go +++ b/internal/panel/compile.go @@ -71,6 +71,9 @@ type Column struct { // Compiled is one statement ready to run. type Compiled struct { + ranking *Ranking + rankingFloor bool + rankOffset int SQL string Args []any Columns []Column @@ -210,7 +213,7 @@ func compileQuery(p *Panel, measures []Measure, filters []Filter, scope Scope) ( partition = "PARTITION BY " + bucket } for _, m := range measures { - selects = append(selects, measureSQL(m, sig, seconds, partition)+" AS "+quoteIdent(m.Alias)) + selects = append(selects, measureExprSQL(m, sig, seconds, partition)+" AS "+quoteIdent(m.Alias)) unit := m.Unit if unit == "none" { unit = "" // The catalog cannot infer a physical unit for this field. @@ -218,44 +221,36 @@ func compileQuery(p *Panel, measures []Measure, filters []Filter, scope Scope) ( columns = append(columns, Column{Name: m.Alias, Type: "number", Role: "measure", Unit: unit}) } var b strings.Builder + var ranking *Ranking + rankingFloor := false b.WriteString("WITH base AS (SELECT * FROM " + structuredSource(sig.name) + " WHERE " + where + ")") if top > 0 { - // Rank over the complete panel window, before bucket aggregation. Volume - // measures retain largest-first semantics even when higher is better. - direction := "DESC" first := measures[0] - rankPanel, rankQuery := *p, *p.Query - rankQuery.Measures = []string{first.Text} - rankPanel.Query = &rankQuery better := p.Better if better == "" { - better = inferBetter(&rankPanel) + better = inferBetterExpr(first.Expr, p, sig) } - if !first.Additive && first.Func != "share" && better == "higher" { - direction = "ASC" + value, samples, extra, order := rankingOrder(first, sig, better) + base, _, _, _ := affineBase(first.Expr) + if call, ok := base.(MeasureCall); ok && call.Func == "rate" { + value = measureSQL(Measure{Func: call.Func}, sig, scope.End.Sub(scope.Start).Seconds(), "") } - value := measureSQL(first, sig, scope.End.Sub(scope.Start).Seconds(), "") - samples, extra := "count(*)", "" - order := "value " + direction + " NULLS LAST, n DESC, d" - switch first.Func { - case "error_rate": - // The common 20-sample floor prevents tiny request series from - // displacing supported failures (even 1/2 has a 9.45% bound). - extra = ", sum(" + errorCase(sig) + ") AS errors, " + wilsonLowerSQL() + " AS confidence" - order = "(n >= 20) DESC, CASE WHEN n >= 20 THEN confidence END DESC NULLS LAST, n DESC, d" - case "p50", "p75", "p90", "p95", "p99", "quantile", "avg", "max", "min": - // Count actual numeric samples, not rows with missing values. - samples = "count(" + first.Field.numberSQL() + ")" - order = "(n >= 20) DESC, CASE WHEN n >= 20 THEN value END " + direction + " NULLS LAST, n DESC, d" + rankingFloor = strings.HasPrefix(order, "(n >= 20)") + rule := rankRule(first, sig, better) + if rule.Rule == "value_floor" { + value = measureExprSQL(first, sig, scope.End.Sub(scope.Start).Seconds(), "") } + ranking = &Ranking{Rule: rule.Rule, Better: rule.Better, Floor: rule.Floor, SupportColumn: samples, TieBreakers: []string{"n desc", "dimension asc"}} + fmt.Fprintf(&b, ", candidates AS (SELECT coalesce(%s, '') AS d, %s AS value, %s AS n%s FROM base GROUP BY 1), top AS (SELECT d FROM candidates ORDER BY %s LIMIT %d)", dims[foldDimension].stringSQL(), value, samples, extra, order, top) } + rankOffset := b.Len() + len(" SELECT ") + len(strings.Join(selects, ", ")) b.WriteString(" SELECT " + strings.Join(selects, ", ") + " FROM base") if len(groups) > 0 { b.WriteString(" GROUP BY " + strings.Join(groups, ", ")) } b.WriteString(orderAndLimit(p, measures, bucket != "", len(dims))) - return Compiled{SQL: b.String(), Args: args, Columns: columns}, nil + return Compiled{SQL: b.String(), Args: args, Columns: columns, ranking: ranking, rankOffset: rankOffset, rankingFloor: rankingFloor}, nil } func measureSQL(m Measure, sig *signal, seconds float64, partition string) string { diff --git a/internal/panel/compile_expr_test.go b/internal/panel/compile_expr_test.go new file mode 100644 index 00000000..8d005f59 --- /dev/null +++ b/internal/panel/compile_expr_test.go @@ -0,0 +1,136 @@ +package panel + +import ( + "context" + "github.com/labstack/fanout/internal/queryrows" + "strings" + "testing" + "time" +) + +func TestCheckCountIfFilters(t *testing.T) { + duck, _ := newTestEngine(t) + for _, tc := range []struct{ text, want string }{ + {"count_if(service = $service) as e", "variables are not allowed inside count_if"}, + {"count_if(regexp_replace(service, 'a', 'b') = 'x') as e", "not allowed"}, + {"count_if(" + strings.Repeat(" ", 480) + "status = 'STATUS_CODE_ERROR') as e", "filters are 1 to 500 characters"}, + } { + d := exprDashboard(tc.text) + _, problems, err := Check(t.Context(), duck, &d) + if err != nil || len(problems) != 1 || problems[0].Path != "panels[0].query.measures[0]" || !strings.Contains(problems[0].Message, tc.want) { + t.Errorf("%s: %+v %v", tc.text, problems, err) + } + } + d := exprDashboard("count_if(status = 'STATUS_CODE_ERROR') as e") + checked, problems, err := Check(t.Context(), duck, &d) + if err != nil || len(problems) != 0 { + t.Fatalf("%+v %v", problems, err) + } + leaf := checked.Measures["e"][0].Expr.(MeasureCountIf) + filter, err := checkFilter(t.Context(), duck, signals["spans"], nil, "status = 'STATUS_CODE_ERROR'") + if err != nil || leaf.Expr != filter.Expr || leaf.Expr == "" { + t.Fatalf("%+v %+v %v", leaf, filter, err) + } +} +func TestCompileExpressionSQL(t *testing.T) { + duck, _ := newTestEngine(t) + text := "count_if(TRY_CAST(http_status_code AS INTEGER) >= 500) / count() * 100 as pct_5xx" + d := exprDashboard(text) + d.Panels[0].Query.By = []string{"http_route"} + d.Panels[0].Query.Where = []string{"kind = 'SPAN_KIND_SERVER'"} + checked, problems, err := Check(t.Context(), duck, &d) + if err != nil || len(problems) != 0 { + t.Fatalf("%+v %v", problems, err) + } + scope := Scope{Start: fixtureStart, End: fixtureStart.Add(time.Hour)} + compiled, err := compileQuery(&d.Panels[0], checked.Measures["e"], checked.Filters["e"], scope) + if err != nil { + t.Fatal(err) + } + for _, part := range []string{"count(*) FILTER (WHERE (", "TRY_CAST(http_status_code AS INTEGER)", " / nullif(count(*)::DOUBLE, 0) * 100 AS \"pct_5xx\""} { + if !strings.Contains(compiled.SQL, part) { + t.Fatalf("missing %s: %s", part, compiled.SQL) + } + } + d = exprDashboard("(count_if(duration_ms <= 500) + count_if(duration_ms > 500 AND duration_ms <= 2000) / 2) / count() as apdex") + checked, problems, err = Check(t.Context(), duck, &d) + if err != nil || len(problems) != 0 { + t.Fatalf("%+v %v", problems, err) + } + compiled, err = compileQuery(&d.Panels[0], checked.Measures["e"], nil, scope) + if err != nil || strings.Count(compiled.SQL, "FILTER (WHERE") != 2 || !strings.Contains(compiled.SQL, " / nullif(2, 0)") || !strings.Contains(compiled.SQL, " / nullif(count(*)::DOUBLE, 0)") { + t.Fatalf("%s %v", compiled.SQL, err) + } + d = exprDashboard("count_if(status = 'STATUS_CODE_ERROR') as a", "p95(duration_ms)") + d.Panels[0].Viz = "scatter" + d.Panels[0].Query.By = []string{"service"} + checked, problems, err = Check(t.Context(), duck, &d) + if err != nil || len(problems) != 0 { + t.Fatalf("%+v %v", problems, err) + } + compiled, err = compileItems(&d.Panels[0], checked.Measures["e"], nil, scope) + if err != nil || !strings.Contains(compiled.SQL, "FILTER (WHERE") { + t.Fatalf("%s %v", compiled.SQL, err) + } +} + +type expressionSQLCapture struct { + Engine + queries []string +} + +func (e *expressionSQLCapture) QueryContext(ctx context.Context, text string, args ...any) (queryrows.Rows, error) { + e.queries = append(e.queries, text) + return e.Engine.QueryContext(ctx, text, args...) +} +func TestCompileExpressionTrendsAndTotals(t *testing.T) { + duck, repo := newTestEngine(t) + commit(t, repo, shopSpans(), nil) + capture := &expressionSQLCapture{Engine: duck} + e := NewExecutor(capture, 30) + e.now = func() time.Time { return fixtureStart.Add(time.Hour) } + for _, tc := range []struct{ measure, alias, fragment string }{{"count_if(status = 'STATUS_CODE_ERROR') / count() as e", "e", "FILTER (WHERE"}, {"share()", "share", "_trend_totals AS"}} { + capture.queries = nil + d := exprDashboard(tc.measure) + p := &d.Panels[0] + p.Query.By = []string{"service"} + p.Query.Limit = 1 + p.Options = &Options{Columns: []ColumnFormat{{Field: tc.alias, Format: "sparkline"}}} + got, err := e.Run(t.Context(), RunRequest{Dashboard: d}) + if err != nil || len(got) != 1 || got[0].Status != StatusOK || got[0].Frame.Trends == nil { + t.Fatalf("%+v %v", got, err) + } + found := false + for _, sql := range capture.queries { + if strings.Contains(sql, "ORDER BY _t DESC") { + found = true + if !strings.Contains(sql, tc.fragment) { + t.Fatalf("trend: %s", sql) + } + if tc.alias == "share" && (!strings.Contains(sql, "100.0*count(*)/nullif(max(_trend_total),0)") || !strings.Contains(sql, "FROM _trend_scope JOIN _trend_totals")) { + t.Fatalf("share scope changed: %s", sql) + } + } + } + if !found { + t.Fatal("no trend query") + } + } + capture.queries = nil + d := exprDashboard("count_if(status = 'STATUS_CODE_ERROR') as e") + d.Panels[0].Viz = "stat" + d.Panels[0].Reduce = "window" + got, err := e.Run(t.Context(), RunRequest{Dashboard: d}) + if err != nil || len(got) != 1 || got[0].Status != StatusOK || got[0].Frame.Totals[1] != float64(6) { + t.Fatalf("%+v %v", got, err) + } + found := false + for _, sql := range capture.queries { + if strings.Contains(sql, "FILTER (WHERE") && !strings.Contains(sql, "time_bucket(") { + found = true + } + } + if !found { + t.Fatal("totals did not use expression compiler") + } +} diff --git a/internal/panel/exec.go b/internal/panel/exec.go index 308a4eaa..2b7b6389 100644 --- a/internal/panel/exec.go +++ b/internal/panel/exec.go @@ -39,6 +39,7 @@ type RunRequest struct { } type Result struct { + Ranking *Ranking `json:"ranking,omitempty"` AnnotationScope *AnnotationMatch `json:"annotation_scope,omitempty"` AnnotationError string `json:"annotation_error,omitempty"` ID string `json:"id"` @@ -364,6 +365,7 @@ func (e *Executor) runPanel(ctx context.Context, p *Panel, checked *Checked, t T return failed(res, err, parent.Err()) } res.Frame, res.SQL = frame, sqlText + res.Ranking = frame.ranking // Trend failures are recorded on the frame and preserve the main table. _ = e.attachTableTrends(ctx, p, checked, scope, frame) if p.Query != nil && (p.Viz == "timeseries" || p.Viz == "heatmap" || p.Viz == "state_timeline" || p.Viz == "health") { @@ -398,7 +400,7 @@ func (e *Executor) runPanel(ctx context.Context, p *Panel, checked *Checked, t T res.ShiftMS = shift.Milliseconds() } } - if frame.Rows == 0 || (p.Query != nil && p.Query.From == "metrics" && p.Viz != "histogram" && p.Viz != "heatmap" && !metricFrameHasValue(frame)) { + if frame.Rows == 0 || emptyExpressionTotal(p, checked.Measures[p.ID], frame) || (p.Query != nil && p.Query.From == "metrics" && p.Viz != "histogram" && p.Viz != "heatmap" && !metricFrameHasValue(frame)) { res.Status = StatusEmpty res.Diagnosis = e.diagnose(ctx, p, checked.Filters[p.ID], scope) } @@ -447,7 +449,15 @@ func (e *Executor) runScope(ctx context.Context, p *Panel, checked *Checked, sco if err != nil { return nil, "", err } - rows, err := e.engine.QueryContext(ctx, compiled.SQL, compiled.Args...) + // The disclosure is a scalar read of the same candidates CTE, so it + // shares the ranking request and its pinned file snapshot. + executionSQL := compiled.SQL + scanColumns := compiled.Columns + if compiled.ranking != nil { + executionSQL = executionSQL[:compiled.rankOffset] + `, (SELECT count(*) FROM candidates WHERE n < 20)::DOUBLE AS "_fanql_below_floor"` + executionSQL[compiled.rankOffset:] + scanColumns = append(append([]Column(nil), scanColumns...), Column{Name: "_fanql_below_floor", Type: "number"}) + } + rows, err := e.engine.QueryContext(ctx, executionSQL, compiled.Args...) if err != nil { return nil, compiled.SQL, err } @@ -467,7 +477,23 @@ func (e *Executor) runScope(ctx context.Context, p *Panel, checked *Checked, sco if p.Viz == "log_patterns" { rowLimit = patternLimit(p) } - frame, err := scanFrame(rows, compiled.Columns, rowLimit) + frame, err := scanFrame(rows, scanColumns, rowLimit) + if frame != nil && compiled.ranking != nil { + frame.ranking = compiled.ranking + if frame.Rows > 0 { + if n, ok := frame.Values[len(frame.Values)-1][0].(float64); ok { + frame.ranking.BelowFloor = int(n) + } + } + frame.Columns, frame.Values = frame.Columns[:len(frame.Columns)-1], frame.Values[:len(frame.Values)-1] + if frame.ranking.BelowFloor > 0 { + note := fmt.Sprintf("%d series had fewer than 20 samples", frame.ranking.BelowFloor) + if compiled.rankingFloor { + note += " and were ranked last" + } + frame.addNote(note) + } + } if frame != nil { frame.bucketed = scope.Interval > 0 && len(compiled.Columns) > 0 && compiled.Columns[0].Role == "time" if compiled.TrendInterval > 0 { @@ -570,3 +596,15 @@ func metricFrameHasValue(f *Frame) bool { } return false } + +func emptyExpressionTotal(p *Panel, measures []Measure, frame *Frame) bool { + if p.Query == nil || (p.Viz != "stat" && p.Viz != "gauge") || len(measures) != 1 || !measures[0].IsExpression() { + return false + } + for i, column := range frame.Columns { + if column.Role == "measure" && i < len(frame.Totals) && frame.Totals[i] != nil { + return false + } + } + return true +} diff --git a/internal/panel/frame.go b/internal/panel/frame.go index c614fe4d..55d30c59 100644 --- a/internal/panel/frame.go +++ b/internal/panel/frame.go @@ -14,6 +14,7 @@ import ( // Frame is a columnar query result: one array of values per column. type Frame struct { + ranking *Ranking Periods map[string]Time `json:"periods,omitempty"` Trends map[string][][]any `json:"trends,omitempty"` Note string `json:"note,omitempty"` diff --git a/internal/panel/items.go b/internal/panel/items.go index c4d981f3..0e611d59 100644 --- a/internal/panel/items.go +++ b/internal/panel/items.go @@ -59,7 +59,7 @@ func compileItems(p *Panel, measures []Measure, filters []Filter, scope Scope) ( if p.Unit != "" && (p.Viz != "scatter" || i == 1) { unit = p.Unit } - selects = append(selects, measureSQL(m, sig, seconds, partition)+" AS "+quoteIdent(m.Alias)) + selects = append(selects, measureExprSQL(m, sig, seconds, partition)+" AS "+quoteIdent(m.Alias)) columns = append(columns, Column{Name: m.Alias, Type: "number", Role: "measure", Unit: unit}) } text := "WITH base AS (SELECT * FROM " + structuredSource(sig.name) + " WHERE " + where + ")" diff --git a/internal/panel/measure.go b/internal/panel/measure.go index 95dbe2f8..0592e5a3 100644 --- a/internal/panel/measure.go +++ b/internal/panel/measure.go @@ -2,6 +2,7 @@ package panel import ( "fmt" + "math" "regexp" "slices" "strconv" @@ -17,6 +18,10 @@ type Measure struct { Alias string Unit string Additive bool + Expr MeasureExpr + Leaves int + Rank RankRule + nodes int } type measureFunc struct { @@ -56,61 +61,465 @@ func measureNames() []string { return out } -var ( - measurePattern = regexp.MustCompile(`^\s*([A-Za-z_0-9]+)\s*\((.*)\)\s*(?:(?i:as)\s+(\S+))?\s*$`) - aliasPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,39}$`) +var aliasPattern = regexp.MustCompile(`^[a-z][a-z0-9_]{0,39}$`) + +// MeasureExpr is a bounded aggregate expression. Only checked CountIf.Expr is +// compiled; its source is retained for diagnostics and direction inference. +type MeasureExpr interface{ measureExpr() } +type MeasureCall struct { + Func string + Field *FieldRef + Q float64 +} +type MeasureCountIf struct { + Filter string + Expr string +} +type MeasureBinary struct { + Op byte + L, R MeasureExpr +} +type MeasureNeg struct{ X MeasureExpr } +type MeasureConst struct { + Value float64 + Text string +} + +func (MeasureCall) measureExpr() {} +func (MeasureCountIf) measureExpr() {} +func (MeasureBinary) measureExpr() {} +func (MeasureNeg) measureExpr() {} +func (MeasureConst) measureExpr() {} +func (m Measure) IsExpression() bool { return m.Func == "expr" } + +type RankRule struct { + Rule, Better string + Floor int + SupportColumn string +} +type Ranking struct { + Rule string `json:"rule"` + Better string `json:"better"` + Floor int `json:"floor"` + SupportColumn string `json:"support_column"` + BelowFloor int `json:"below_floor"` + TieBreakers []string `json:"tie_breakers"` +} + +const ( + maxMeasureTokens = 256 + maxMeasureNodes = 64 + maxMeasureDepth = 8 + maxMeasureLeaves = 8 + maxQueryMeasureNodes = 256 + maxQueryMeasureLeaves = 24 ) -func parseMeasure(sig *signal, text string) (Measure, string, string) { - m := measurePattern.FindStringSubmatch(text) - if m == nil { - return Measure{}, "is not fn(field) [as alias]", "e.g. p95(duration_ms) or count()" +type measureToken struct { + text string + start, end int +} +type measureParser struct { + sig *signal + text string + tokens []measureToken + at, nodes, leaves int + parsedDepth int + message, hint string +} + +// Strings (including escaped SQL quotes) remain one token. The scanner counts +// SQL tokens inside count_if too, without interpreting or trusting that SQL. +func measureTokens(text string) ([]measureToken, string) { + var tokens []measureToken + for i := 0; i < len(text); { + if text[i] == ' ' || text[i] == '\t' || text[i] == '\r' || text[i] == '\n' { + i++ + continue + } + start := i + c := text[i] + i++ + switch { + case c == '\'' || c == '"': + closed := false + for i < len(text) { + if text[i] == c { + i++ + if i < len(text) && text[i] == c { + i++ + continue + } + closed = true + break + } + i++ + } + if !closed { + return nil, "unterminated quoted literal" + } + case c >= '0' && c <= '9' || c == '.' && i < len(text) && text[i] >= '0' && text[i] <= '9': + for i < len(text) && ((text[i] >= '0' && text[i] <= '9') || text[i] == '.') { + i++ + } + if i < len(text) && (text[i] == 'e' || text[i] == 'E') { + i++ + if i < len(text) && (text[i] == '+' || text[i] == '-') { + i++ + } + for i < len(text) && text[i] >= '0' && text[i] <= '9' { + i++ + } + } + case c == '_' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= 128: + for i < len(text) { + c := text[i] + if !(c == '_' || c == '.' || c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c >= 128) { + break + } + i++ + } + } + tokens = append(tokens, measureToken{text[start:i], start, i}) + if len(tokens) > maxMeasureTokens { + return nil, fmt.Sprintf("has %d tokens; a measure is at most %d", len(tokens), maxMeasureTokens) + } + } + return tokens, "" +} +func (p *measureParser) peek() string { + if p.at >= len(p.tokens) { + return "" + } + return p.tokens[p.at].text +} +func (p *measureParser) take(text string) bool { + if strings.EqualFold(p.peek(), text) { + p.at++ + return true + } + return false +} +func (p *measureParser) fail(message string) { + if p.message == "" { + p.message = message + } +} +func (p *measureParser) node(e MeasureExpr) MeasureExpr { + p.nodes++ + if p.nodes > maxMeasureNodes { + p.fail(fmt.Sprintf("has %d nodes; a measure is at most %d", p.nodes, maxMeasureNodes)) + } + switch e.(type) { + case MeasureCall, MeasureCountIf: + p.leaves++ + if p.leaves > maxMeasureLeaves { + p.fail(fmt.Sprintf("has %d aggregates; a measure has 1 to %d", p.leaves, maxMeasureLeaves)) + } + } + return e +} +func (p *measureParser) expr(minPrecedence, depth int) MeasureExpr { + if depth > maxMeasureDepth { + p.fail(fmt.Sprintf("nests %d deep; a measure nests at most %d", depth, maxMeasureDepth)) + return nil + } + if p.message != "" { + return nil + } + var left MeasureExpr + leftDepth := 0 + switch { + case p.take("-"): + x := p.expr(3, depth+1) + leftDepth = p.parsedDepth + 1 + left = p.node(MeasureNeg{x}) + case p.take("("): + left = p.expr(0, depth+1) + leftDepth = p.parsedDepth + 1 + if !p.take(")") { + p.fail("expected )") + } + case p.peek() == "": + p.fail("expected a measure or number") + return nil + default: + tok := p.tokens[p.at] + p.at++ + if n, err := strconv.ParseFloat(tok.text, 64); err == nil && !math.IsNaN(n) && !math.IsInf(n, 0) { + left = p.node(MeasureConst{n, tok.text}) + } else { + left = p.call(tok) + } + } + for p.message == "" { + op := p.peek() + precedence := 0 + if op == "+" || op == "-" { + precedence = 1 + } + if op == "*" || op == "/" { + precedence = 2 + } + if precedence == 0 || precedence < minPrecedence { + break + } + p.at++ + right := p.expr(precedence+1, depth+1) + leftDepth = 1 + max(leftDepth, p.parsedDepth) + if d := leftDepth + depth; d > maxMeasureDepth { + p.fail(fmt.Sprintf("nests %d deep; a measure nests at most %d", d, maxMeasureDepth)) + break + } + left = p.node(MeasureBinary{op[0], left, right}) + } + p.parsedDepth = leftDepth + return left +} +func (p *measureParser) call(tok measureToken) MeasureExpr { + name := strings.ToLower(tok.text) + if !p.take("(") { + p.fail("is not fn(field) [as alias]") + return nil + } + opening := p.tokens[p.at-1] + start := opening.end + nest := 1 + end := start + for p.at < len(p.tokens) { + t := p.tokens[p.at] + p.at++ + if t.text == "(" { + nest++ + } + if t.text == ")" { + nest-- + if nest == 0 { + end = t.start + break + } + } + } + if nest != 0 { + if name == "count_if" { + p.fail("unclosed count_if") + } else { + p.fail("unclosed measure call") + } + return nil + } + inner := p.text[start:end] + if name == "count_if" { + if strings.TrimSpace(inner) == "" { + p.fail("count_if needs a filter") + } + if len(inner) > 500 { + p.fail("filters are 1 to 500 characters") + } + return p.node(MeasureCountIf{Filter: inner}) } - name := strings.ToLower(m[1]) spec, ok := measureFuncs[name] if !ok { - return Measure{}, fmt.Sprintf("unknown function %s", name), suggestOr(name, measureNames(), "functions: "+strings.Join(measureNames(), ", ")) + p.fail(fmt.Sprintf("unknown function %s", name)) + p.hint = suggestOr(name, measureNames(), "functions: "+strings.Join(measureNames(), ", ")) + return nil } - if len(spec.signals) > 0 && !slices.Contains(spec.signals, sig.name) { - return Measure{}, fmt.Sprintf("%s is not available for %s", name, sig.name), "available for " + strings.Join(spec.signals, ", ") + if len(spec.signals) > 0 && !slices.Contains(spec.signals, p.sig.name) { + p.fail(fmt.Sprintf("%s is not available for %s", name, p.sig.name)) + p.hint = "available for " + strings.Join(spec.signals, ", ") + return nil } var args []string - if inner := strings.TrimSpace(m[2]); inner != "" { - for _, part := range strings.Split(inner, ",") { - args = append(args, strings.TrimSpace(part)) + // Commas in literal attribute keys belong to the field, not the signature. + argStart := start + quoted := byte(0) + for i := start; i < end; i++ { + c := p.text[i] + if quoted != 0 { + if c == quoted { + if i+1 < end && p.text[i+1] == quoted { + i++ + continue + } + quoted = 0 + } + continue + } + if c == '\'' || c == '"' { + quoted = c + } + if c == ',' { + args = append(args, strings.TrimSpace(p.text[argStart:i])) + argStart = i + 1 } } + if strings.TrimSpace(inner) != "" { + args = append(args, strings.TrimSpace(p.text[argStart:end])) + } + // SQL's conventional count(*) spelling is equivalent to count(). + if name == "count" && len(args) == 1 && args[0] == "*" { + args = nil + } if len(args) != spec.args { - return Measure{}, fmt.Sprintf("%s takes %d argument(s), got %d", name, spec.args, len(args)), "" + p.fail(fmt.Sprintf("%s takes %d argument(s), got %d", name, spec.args, len(args))) + return nil } - out := Measure{Text: strings.TrimSpace(text), Func: name, Additive: spec.additive, Unit: spec.unit, Q: spec.quantile} + call := MeasureCall{Func: name, Q: spec.quantile} if spec.args >= 1 { - ref, err := sig.field(args[0]) + ref, err := p.sig.field(args[0]) if err != nil { - return Measure{}, err.Error(), "" + p.fail(err.Error()) + return nil } if spec.numeric && ref.Type != TypeNumber && ref.Key == "" { - return Measure{}, fmt.Sprintf("%s needs a numeric field; %s is %s", name, ref.Text, ref.Type), "" - } - out.Field = &ref - if out.Unit == "" { - out.Unit = ref.Unit + p.fail(fmt.Sprintf("%s needs a numeric field; %s is %s", name, ref.Text, ref.Type)) + return nil } + call.Field = &ref } if name == "quantile" { q, err := strconv.ParseFloat(args[1], 64) if err != nil || q <= 0 || q >= 1 { - return Measure{}, "quantile q must be a number between 0 and 1", "e.g. quantile(duration_ms, 0.999)" + p.fail("quantile q must be a number between 0 and 1") + p.hint = "e.g. quantile(duration_ms, 0.999)" + return nil } - out.Q = q + call.Q = q + } + return p.node(call) +} +func parseMeasure(sig *signal, text string) (Measure, string, string) { + tokens, message := measureTokens(text) + if message != "" { + return Measure{}, message, "" } - if alias := m[3]; alias != "" { + p := measureParser{sig: sig, text: text, tokens: tokens} + e := p.expr(0, 0) + alias := "" + if p.take("as") { + if p.at < len(tokens) { + alias = p.peek() + p.at++ + } if !aliasPattern.MatchString(alias) { - return Measure{}, fmt.Sprintf("alias %q must be lowercase letters, digits and underscores", alias), "" + p.fail(fmt.Sprintf("alias %q must be lowercase letters, digits and underscores", alias)) + } + } + if p.at < len(tokens) { + p.fail("unexpected token " + p.peek()) + } + if p.message != "" { + return Measure{}, p.message, p.hint + } + if p.leaves == 0 { + return Measure{}, "a measure needs an aggregate; constants can only scale one, e.g. count() * 100", "" + } + m := Measure{Text: strings.TrimSpace(text), Func: "expr", Alias: alias, Expr: e, Leaves: p.leaves, nodes: p.nodes, Unit: measureUnit(e)} + switch call := e.(type) { + case MeasureCall: + m.Func = call.Func + m.Field = call.Field + m.Q = call.Q + m.Additive = measureFuncs[call.Func].additive + case MeasureCountIf: + m.Func = "count_if" + } + if sig.name == "metrics" && (m.IsExpression() || m.Func == "count_if") { + return Measure{}, "measure arithmetic is not available for metrics", "" + } + if m.IsExpression() { + if hasShare(e) { + return Measure{}, "share() cannot be combined; it is already a percentage of the scope", "use share() alone, or count_if(...) / count() * 100 for a custom ratio" + } + if alias == "" { + return Measure{}, "name this expression with as, e.g. count() / 2 as half", "" + } + } + m.Rank = rankRule(m, sig, "") + return m, "", "" +} +func hasShare(e MeasureExpr) bool { + switch e := e.(type) { + case MeasureCall: + return e.Func == "share" + case MeasureBinary: + return hasShare(e.L) || hasShare(e.R) + case MeasureNeg: + return hasShare(e.X) + } + return false +} +func measureUnit(e MeasureExpr) string { + switch e := e.(type) { + case MeasureCall: + spec := measureFuncs[e.Func] + if spec.unit != "" { + return spec.unit + } + if e.Field != nil { + return e.Field.Unit + } + case MeasureCountIf: + return "count" + case MeasureNeg: + return measureUnit(e.X) + case MeasureBinary: + l, r := measureUnit(e.L), measureUnit(e.R) + if (e.Op == '+' || e.Op == '-') && l == r { + return l + } + if e.Op == '/' && l == "count" && r == "count" { + return "ratio" + } + if e.Op == '*' { + if n, ok := constantValue(e.R); ok { + if l == "ratio" && n == 100 { + return "percent" + } + return l + } + if n, ok := constantValue(e.L); ok { + if r == "ratio" && n == 100 { + return "percent" + } + return r + } + } + if e.Op == '/' { + if _, ok := constantValue(e.R); ok { + return l + } + } + } + return "none" +} + +func constantValue(e MeasureExpr) (float64, bool) { + switch e := e.(type) { + case MeasureConst: + return e.Value, true + case MeasureNeg: + v, ok := constantValue(e.X) + return -v, ok + case MeasureBinary: + l, ok := constantValue(e.L) + r, ok2 := constantValue(e.R) + if ok && ok2 { + switch e.Op { + case '+': + return l + r, true + case '-': + return l - r, true + case '*': + return l * r, true + case '/': + if r != 0 { + return l / r, true + } + } } - out.Alias = alias } - return out, "", "" + return 0, false } func suggestOr(word string, candidates []string, fallback string) string { @@ -124,13 +533,22 @@ func suggestOr(word string, candidates []string, fallback string) string { // function name, or function_field when two measures share a function. func parseMeasures(sig *signal, texts []string, path string, problems *Problems) []Measure { out := make([]Measure, 0, len(texts)) + nodes, leaves := 0, 0 for i, text := range texts { m, message, hint := parseMeasure(sig, text) if message != "" { - problems.addHint(fmt.Sprintf("%s[%d]", path, i), fmt.Sprintf("%q %s", text, message), hint) + problems.addHint(fmt.Sprintf("%s[%d]", path, i), fmt.Sprintf("measures[%d] %s", i, message), hint) continue } out = append(out, m) + nodes += m.nodes + leaves += m.Leaves + } + if nodes > maxQueryMeasureNodes { + problems.add(path, fmt.Sprintf("measures have %d nodes together; a query has at most %d", nodes, maxQueryMeasureNodes)) + } + if leaves > maxQueryMeasureLeaves { + problems.add(path, fmt.Sprintf("measures have %d aggregates together; a query has at most %d", leaves, maxQueryMeasureLeaves)) } uses := map[string]int{} for _, m := range out { diff --git a/internal/panel/measure_compile.go b/internal/panel/measure_compile.go new file mode 100644 index 00000000..1650cfdc --- /dev/null +++ b/internal/panel/measure_compile.go @@ -0,0 +1,235 @@ +package panel + +import ( + "strconv" + "strings" +) + +// measureExprSQL renders only the bounded tree. SQL filter source never enters +// this path: Check installs the validated canonical rendering in each leaf. +func measureExprSQL(m Measure, sig *signal, seconds float64, partition string) string { + if m.Expr == nil { + return measureSQL(m, sig, seconds, partition) + } + return renderMeasureExpr(m.Expr, sig, seconds, partition, 0) +} +func renderMeasureExpr(e MeasureExpr, sig *signal, seconds float64, partition string, parent int) string { + switch e := e.(type) { + case MeasureCall: + return measureSQL(Measure{Func: e.Func, Field: e.Field, Q: e.Q}, sig, seconds, partition) + case MeasureCountIf: + return "count(*) FILTER (WHERE (" + e.Expr + "))::DOUBLE" + case MeasureConst: + return strconv.FormatFloat(e.Value, 'f', -1, 64) + case MeasureNeg: + return "-(" + renderMeasureExpr(e.X, sig, seconds, partition, 0) + ")" + case MeasureBinary: + precedence := 1 + if e.Op == '*' || e.Op == '/' { + precedence = 2 + } + left := renderMeasureExpr(e.L, sig, seconds, partition, precedence) + right := renderMeasureExpr(e.R, sig, seconds, partition, precedence+1) + if e.Op == '/' { + right = "nullif(" + renderMeasureExpr(e.R, sig, seconds, partition, 0) + ", 0)" + } + sql := left + " " + string(e.Op) + " " + right + if precedence < parent { + return "(" + sql + ")" + } + return sql + } + panic("unknown measure expression") +} + +// affineBase decomposes a*x+b while preserving x's untransformed ranking score. +// It intentionally declines expressions with multiple nonconstant operands. +func affineBase(e MeasureExpr) (base MeasureExpr, a, b float64, ok bool) { + switch e := e.(type) { + case MeasureNeg: + x, a, b, ok := affineBase(e.X) + return x, -a, -b, ok + case MeasureBinary: + if c, constant := constantValue(e.R); constant { + x, a, b, ok := affineBase(e.L) + switch e.Op { + case '+': + return x, a, b + c, ok + case '-': + return x, a, b - c, ok + case '*': + return x, a * c, b * c, ok + case '/': + if c != 0 { + return x, a / c, b / c, ok + } + } + } + if c, constant := constantValue(e.L); constant { + x, a, b, ok := affineBase(e.R) + switch e.Op { + case '+': + return x, a, b + c, ok + case '-': + return x, -a, c - b, ok + case '*': + return x, a * c, b * c, ok + } + } + case MeasureConst: + return nil, 0, 0, false + } + return e, 1, 0, true +} +func binomial(e MeasureExpr) (MeasureCountIf, bool) { + if e, ok := e.(MeasureBinary); ok && e.Op == '/' { + n, ok := e.L.(MeasureCountIf) + d, ok2 := e.R.(MeasureCall) + if ok && ok2 && d.Func == "count" { + return n, true + } + } + return MeasureCountIf{}, false +} +func flipBetter(better string) string { + if better == "lower" { + return "higher" + } + if better == "higher" { + return "lower" + } + return better +} +func neutralBetter(better string) string { + if better == "" { + return "neutral" + } + return better +} +func rankRule(m Measure, sig *signal, better string) RankRule { + rule := RankRule{Rule: "builtin", Better: neutralBetter(better), Floor: 20, SupportColumn: "count(*)"} + base, a, _, ok := affineBase(m.Expr) + if _, singleCall := m.Expr.(MeasureCall); !singleCall { + rule.Rule = "value_floor" + } + if ok && a != 0 { + if call, yes := base.(MeasureCall); yes { + if m.IsExpression() { + rule.Rule = "inherit" + } + rule.SupportColumn = builtinSupport(call) + } else if _, yes := binomial(base); yes { + rule.Rule = "wilson" + } + } + if rule.Rule == "value_floor" { + rule.SupportColumn = expressionSupport(m.Expr) + } + return rule +} + +// Builtin and inherited calls retain their original support and tie semantics. +func builtinSupport(call MeasureCall) string { + switch call.Func { + case "p50", "p75", "p90", "p95", "p99", "quantile", "avg", "max", "min": + return "count(" + call.Field.numberSQL() + ")" + } + return "count(*)" +} +func leafSupport(e MeasureExpr) string { + switch e := e.(type) { + case MeasureCall: + if e.Field != nil && measureFuncs[e.Func].numeric { + return "count(" + e.Field.numberSQL() + ")" + } + } + return "count(*)" +} +func expressionSupport(e MeasureExpr) string { + // Ratios with a conditional-count denominator use that population directly. + base, _, _, ok := affineBase(e) + if ratio, yes := base.(MeasureBinary); ok && yes && ratio.Op == '/' { + if denom, yes := ratio.R.(MeasureCountIf); yes { + return "count(*) FILTER (WHERE (" + denom.Expr + "))" + } + } + var supports []string + var walk func(MeasureExpr) + walk = func(e MeasureExpr) { + switch e := e.(type) { + case MeasureCall, MeasureCountIf: + s := leafSupport(e) + for _, v := range supports { + if v == s { + return + } + } + supports = append(supports, s) + case MeasureBinary: + walk(e.L) + walk(e.R) + case MeasureNeg: + walk(e.X) + } + } + walk(e) + if len(supports) == 1 { + return supports[0] + } + return "least(" + strings.Join(supports, ", ") + ")" +} +func rankingOrder(first Measure, sig *signal, better string) (value, samples, extra, order string) { + // Ranking comparisons use totals; rate's fixed positive seconds scale cannot + // affect order, so one second is sufficient for its score. + value = measureExprSQL(first, sig, 1, "") + rule := rankRule(first, sig, better) + samples = rule.SupportColumn + base, a, _, _ := affineBase(first.Expr) + if a < 0 && (rule.Rule == "inherit" || rule.Rule == "wilson") { + better = flipBetter(better) + } + direction := "DESC" + if better == "higher" { + direction = "ASC" + } + if rule.Rule == "builtin" || rule.Rule == "inherit" { + call, _ := base.(MeasureCall) + m := Measure{Func: call.Func, Field: call.Field, Q: call.Q, Additive: measureFuncs[call.Func].additive} + // count_if alone uses its value and row support like the count family. + if call.Func == "" { + return value, samples, "", "value DESC NULLS LAST, n DESC, d" + } + value = measureSQL(m, sig, 1, "") + if m.Additive || m.Func == "share" { + direction = "DESC" + } + order = "value " + direction + " NULLS LAST, n DESC, d" + switch m.Func { + case "error_rate": + extra = ", sum(" + errorCase(sig) + ") AS errors, " + wilsonLowerSQL() + " AS confidence" + order = floorOrder("confidence", "DESC") + case "p50", "p75", "p90", "p95", "p99", "quantile", "avg", "max", "min": + order = floorOrder("value", direction) + } + return + } + if rule.Rule == "wilson" { + leaf, _ := binomial(base) + extra = ", sum(CASE WHEN " + leaf.Expr + " THEN 1.0 ELSE 0.0 END) AS errors, " + wilsonLowerSQL() + " AS confidence" + if better == "higher" { + extra = ", sum(CASE WHEN " + leaf.Expr + " THEN 1.0 ELSE 0.0 END) AS errors, " + wilsonUpperSQL() + " AS confidence" + order = floorOrder("confidence", "ASC") + } else { + order = floorOrder("confidence", "DESC") + } + } else { + order = floorOrder("value", direction) + } + return +} +func floorOrder(score, direction string) string { + return "(n >= 20) DESC, CASE WHEN n >= 20 THEN " + score + " END " + direction + " NULLS LAST, n DESC, d" +} +func wilsonUpperSQL() string { + return strings.Replace(strings.Replace(wilsonLowerSQL(), "greatest(0.0,", "least(1.0,", 1), "- 1.96 * sqrt", "+ 1.96 * sqrt", 1) +} diff --git a/internal/panel/measure_expr_test.go b/internal/panel/measure_expr_test.go new file mode 100644 index 00000000..3dd4bf7d --- /dev/null +++ b/internal/panel/measure_expr_test.go @@ -0,0 +1,220 @@ +package panel + +import ( + "fmt" + "strings" + "testing" + "time" +) + +func TestParseMeasureKeepsSingleCalls(t *testing.T) { + for _, tc := range []struct { + sig, text, fn, field, alias, unit string + q float64 + additive bool + }{ + {"spans", " p95( duration_ms ) ", "p95", "duration_ms", "", "ms", .95, false}, + {"spans", "COUNT( )", "count", "", "", "count", 0, true}, + {"spans", "quantile(duration_ms, 0.999) as q", "quantile", "duration_ms", "q", "ms", .999, false}, + {"spans", "count_distinct(attributes['user.id'])", "count_distinct", "attributes['user.id']", "", "count", 0, false}, + {"spans", "rate()", "rate", "", "", "per_second", 0, true}, + {"spans", "share()", "share", "", "", "percent", 0, false}, + {"metrics", "last(value)", "last", "value", "", "none", 0, false}, + } { + t.Run(tc.text, func(t *testing.T) { + m, err := ParseMeasure(tc.sig, tc.text) + if err != nil { + t.Fatal(err) + } + field := "" + if m.Field != nil { + field = m.Field.Text + } + if m.Func != tc.fn || field != tc.field || m.Q != tc.q || m.Alias != tc.alias || m.Unit != tc.unit || m.Additive != tc.additive || m.Text != strings.TrimSpace(tc.text) || m.Leaves != 1 || m.IsExpression() { + t.Fatalf("got %+v field=%s", m, field) + } + if _, ok := m.Expr.(MeasureCall); !ok { + t.Fatalf("call tree: %#v", m.Expr) + } + }) + } +} +func TestParseMeasureExpressions(t *testing.T) { + for _, tc := range []struct { + text, unit string + leaves int + }{ + {"count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as err_pct", "percent", 2}, + {"count_if(status = 'STATUS_CODE_ERROR') / count() as r", "ratio", 2}, + {"p95(duration_ms) - p50(duration_ms) as spread", "ms", 2}, + {"count() * -1 as neg", "count", 1}, + {"sum(duration_ms) / count() as x", "none", 2}, + {"count() * 0 as zero", "count", 1}, + {"count_if(a = 1 AND (b IS NULL OR b != 'x)')) as e", "count", 1}, + } { + t.Run(tc.text, func(t *testing.T) { + m, err := ParseMeasure("spans", tc.text) + if err != nil { + t.Fatal(err) + } + if m.Unit != tc.unit || m.Leaves != tc.leaves || m.Additive { + t.Fatalf("got %+v", m) + } + }) + } + m, _ := ParseMeasure("spans", "count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as err_pct") + root, ok := m.Expr.(MeasureBinary) + if !ok || root.Op != '*' || m.Alias != "err_pct" { + t.Fatalf("%#v", m) + } + ratio := root.L.(MeasureBinary) + if ratio.Op != '/' || ratio.L.(MeasureCountIf).Filter != "status = 'STATUS_CODE_ERROR'" || ratio.R.(MeasureCall).Func != "count" || root.R.(MeasureConst).Value != 100 { + t.Fatalf("%#v", root) + } + neg, _ := ParseMeasure("spans", "count() * -1 as neg") + if neg.Expr.(MeasureBinary).R.(MeasureNeg).X.(MeasureConst).Value != 1 { + t.Fatal(neg) + } + quoted, _ := ParseMeasure("spans", "count_if(a = 1 AND (b IS NULL OR b != 'x)')) as e") + if quoted.Expr.(MeasureCountIf).Filter != "a = 1 AND (b IS NULL OR b != 'x)')" { + t.Fatal(quoted) + } + for _, tc := range []struct{ sig, text, want string }{ + {"spans", "count() / 2", "name this expression with as, e.g. count() / 2 as half"}, + {"spans", "share() / 2 as half", "share() cannot be combined; it is already a percentage of the scope"}, + {"spans", "1 as one", "a measure needs an aggregate; constants can only scale one, e.g. count() * 100"}, + {"spans", "1 / 2 as half", "a measure needs an aggregate; constants can only scale one, e.g. count() * 100"}, + {"spans", "-(5) as neg", "a measure needs an aggregate; constants can only scale one, e.g. count() * 100"}, + {"metrics", "count_if(name = 'x') as n", "measure arithmetic is not available for metrics"}, + {"metrics", "count() * 2 as d", "measure arithmetic is not available for metrics"}, + {"spans", "count_if() as n", "count_if needs a filter"}, + {"spans", "count_if(status = 'x'", "unclosed count_if"}, + } { + t.Run(tc.text, func(t *testing.T) { + _, err := ParseMeasure(tc.sig, tc.text) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("got %v want %s", err, tc.want) + } + }) + } +} + +// A balanced expression isolates node budgets from the independent depth cap. +func balancedMeasureNodes(n int) string { return balancedMeasureTree(n, 0) } +func balancedMeasureTree(n, level int) string { + if n == 1 { + return "1" + } + left := (n - 1) / 2 + if left%2 == 0 { + left-- + } + op := "+" + if level%2 != 0 { + op = "*" + } + l, r := balancedMeasureTree(left, level+1), balancedMeasureTree(n-1-left, level+1) + if op == "*" { + if left > 1 { + l = "(" + l + ")" + } + if n-1-left > 1 { + r = "(" + r + ")" + } + } + return l + op + r +} +func aggregateInBalanced(n int) string { + return strings.Replace(balancedMeasureNodes(n), "1", "count()", 1) +} +func TestMeasureBudgets(t *testing.T) { + for _, tc := range []struct{ text, want string }{ + {aggregateInBalanced(65) + " as n", "has 65 nodes; a measure is at most 64"}, + {"count_if(" + strings.Repeat("x ", 252) + ") as n", "has 257 tokens; a measure is at most 256"}, + {strings.Repeat("(", 9) + "count()" + strings.Repeat(")", 9) + " as n", "nests 9 deep; a measure nests at most 8"}, + {"count() + ((((((((1)))))))) as n", "nests 9 deep; a measure nests at most 8"}, + {"(count()+count()+count())+(count()+count()+count())+(count()+count()+count()) as n", "has 9 aggregates; a measure has 1 to 8"}, + } { + _, err := ParseMeasure("spans", tc.text) + if err == nil || !strings.Contains(err.Error(), tc.want) { + t.Errorf("got %v want %s", err, tc.want) + } + } + for _, text := range []string{strings.Repeat(" ", 10*1024) + "p95(duration_ms)", strings.Repeat("(", 8) + "count()" + strings.Repeat(")", 8)} { + if _, err := ParseMeasure("spans", text); err != nil { + t.Fatal(err) + } + } + sig, _ := lookupSignal("spans") + var problems Problems + texts := []string{} + for i, size := range []int{63, 63, 63, 63, 5} { + texts = append(texts, fmt.Sprintf("%s as n%d", aggregateInBalanced(size), i)) + } + parseMeasures(sig, texts, "panels[0].query.measures", &problems) + if len(problems) != 1 || problems[0].Path != "panels[0].query.measures" || problems[0].Message != "measures have 257 nodes together; a query has at most 256" { + t.Fatalf("%+v", problems) + } + problems = nil + eight := "(count()+count())+(count()+count())+(count()+count())+(count()+count())" + parseMeasures(sig, []string{eight + " as a", eight + " as b", eight + " as c", "count() as d"}, "m", &problems) + if len(problems) != 1 || problems[0].Message != "measures have 25 aggregates together; a query has at most 24" { + t.Fatalf("%+v", problems) + } +} +func exprDashboard(measures ...string) Dashboard { + d := Dashboard{Name: "Expressions", Time: Time{Range: "1h"}, Panels: []Panel{{ID: "e", Title: "E", Viz: "table", Query: &Query{From: "spans", Measures: measures}}}} + Normalize(&d) + return d +} +func TestValidateRejectsStructuredBudgetOverrunsAtPath(t *testing.T) { + d := exprDashboard("count()", aggregateInBalanced(65)+" as n") + p := Validate(&d) + if len(p) != 1 || p[0].Path != "panels[0].query.measures[1]" { + t.Fatalf("%+v", p) + } + d = exprDashboard("1 as one") + p = Validate(&d) + if len(p) != 1 || p[0].Path != "panels[0].query.measures[0]" { + t.Fatalf("%+v", p) + } +} +func TestInferBetterForExpressions(t *testing.T) { + for _, tc := range []struct{ text, want string }{ + {"error_rate() * 100 as e", "lower"}, {"100 - error_rate() as e", "higher"}, {"-p95(duration_ms) as e", "higher"}, + {"count_if(status = 'STATUS_CODE_ERROR') / count() as r", "lower"}, {"count_if(kind = 'SPAN_KIND_SERVER') / count() as r", ""}, {"count_if(status = 'STATUS_CODE_ERROR') as e", "lower"}, + } { + d := exprDashboard(tc.text) + if got := inferBetter(&d.Panels[0]); got != tc.want { + t.Errorf("%s: %s want %s", tc.text, got, tc.want) + } + } +} +func FuzzParseMeasure(f *testing.F) { + for _, s := range []string{"count()", "count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as r", "-p95(duration_ms) as n", "share() / 2 as x", strings.Repeat("(", 1000)} { + f.Add(s) + } + f.Fuzz(func(t *testing.T, text string) { + if len(text) > 65536 { + return + } + started := time.Now() + m, err := ParseMeasure("spans", text) + if time.Since(started) > 50*time.Millisecond { + t.Errorf("parse exceeded 50ms") + } + if err == nil && measureDepth(m.Expr) > 8 { + t.Errorf("depth exceeds 8: %+v", m) + } + }) +} + +func measureDepth(e MeasureExpr) int { + switch e := e.(type) { + case MeasureBinary: + return 1 + max(measureDepth(e.L), measureDepth(e.R)) + case MeasureNeg: + return 1 + measureDepth(e.X) + } + return 0 +} diff --git a/internal/panel/metric_measures.go b/internal/panel/metric_measures.go index 2e1c7d33..dc506270 100644 --- a/internal/panel/metric_measures.go +++ b/internal/panel/metric_measures.go @@ -69,6 +69,12 @@ func metricMeasureKinds(m Measure) []string { } func compileMetricQuery(p *Panel, measures []Measure, filters []Filter, scope Scope) (Compiled, error) { + for _, m := range measures { + if m.IsExpression() || m.Func == "count_if" { + return Compiled{}, fmt.Errorf("measure arithmetic is not available for metrics") + } + } + sig := signals["metrics"] where, args, err := buildWhere(sig, filters, scope) if err != nil { diff --git a/internal/panel/ranking_expr_test.go b/internal/panel/ranking_expr_test.go new file mode 100644 index 00000000..13a5247a --- /dev/null +++ b/internal/panel/ranking_expr_test.go @@ -0,0 +1,264 @@ +package panel + +import ( + "fmt" + "reflect" + "strings" + "testing" + "time" + + "github.com/labstack/fanout/internal/telemetry" +) + +func TestRankingFixtures(t *testing.T) { + duck, repo := newTestEngine(t) + var spans []telemetry.Span + add := func(service string, n, errors, servers int, latency float64) { + for i := range n { + status := "STATUS_CODE_OK" + if i < errors { + status = "STATUS_CODE_ERROR" + } + kind := "SPAN_KIND_CLIENT" + if i < servers { + kind = "SPAN_KIND_SERVER" + } + id := fmt.Sprintf("%s-%d", service, i) + attrs := map[string]any{} + if service != "B" || i < 1 { + attrs["user.score"] = latency + } + spans = append(spans, telemetry.Span{Namespace: "test", ServiceName: service, TraceID: id, SpanID: id, StatusCode: status, Kind: kind, DurationMS: latency, StartUnixNanos: fixtureStart.UnixNano(), EndUnixNanos: fixtureStart.UnixNano() + int64(latency*1e6), Attributes: attrs}) + } + } + add("A", 1, 1, 1, 10000) + add("B", 1000, 100, 900, 100) + add("C", 1000, 10, 100, 50) + add("D", 40, 0, 0, 20) + add("E", 40, 0, 0, 10) + add("F", 40, 0, 0, 10) + add("G", 2, 1, 0, 5000) + commit(t, repo, spans, nil) + e := NewExecutor(duck, 30) + e.now = func() time.Time { return fixtureStart.Add(time.Hour) } + run := func(text, better string, top int) Result { + t.Helper() + d := exprDashboard(text) + p := &d.Panels[0] + p.Viz = "timeseries" + p.Better = better + p.Query.By = []string{"service"} + p.Query.Bucket = "1m" + p.Options = &Options{Top: top} + r, err := e.Run(t.Context(), RunRequest{Dashboard: d}) + if err != nil || len(r) != 1 || r[0].Status != StatusOK { + t.Fatalf("%s: %+v %v", text, r, err) + } + return r[0] + } + names := func(r Result) []string { + out := []string{} + for _, v := range r.Frame.Values[1] { + if !strings.HasPrefix(v.(string), "Other (") { + out = append(out, v.(string)) + } + } + return out + } + baseline := names(run("error_rate()", "", 3)) + for _, text := range []string{"error_rate() + 0 as e", "error_rate() * 100 as e", "100 - error_rate() as e", "-error_rate() as e"} { + r := run(text, "", 3) + if !reflect.DeepEqual(names(r), baseline) || r.Ranking == nil || r.Ranking.Rule != "inherit" { + t.Fatalf("%s: %v baseline %v ranking %+v", text, names(r), baseline, r.Ranking) + } + } + if run("error_rate()", "", 3).Ranking.Rule != "builtin" { + t.Fatal("builtin metadata") + } + sparse := run("count_if(status = 'STATUS_CODE_ERROR') / count() as r", "", 1) + if !reflect.DeepEqual(names(sparse), []string{"B"}) { + t.Fatalf("sparse ratio displaced supported B: %v", names(sparse)) + } + r := run("count_if(status = 'STATUS_CODE_ERROR') / count() as r", "", 6) + if r.Ranking == nil || r.Ranking.Rule != "wilson" || r.Ranking.Better != "lower" || r.Ranking.Floor != 20 || r.Ranking.BelowFloor != 2 || !strings.Contains(r.Frame.Note, "2 series had fewer than 20 samples and were ranked last") || !reflect.DeepEqual(r.Ranking.TieBreakers, []string{"n desc", "dimension asc"}) { + t.Fatalf("%+v %+v", r.Ranking, r.Frame) + } + if !reflect.DeepEqual(names(run("100 - count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as ok", "higher", 3)), baseline) { + t.Fatal("success ratio changed ranking") + } + standalone := run("count_if(status = 'STATUS_CODE_ERROR') as errors", "", 2) + if standalone.Ranking.Rule != "value_floor" || !reflect.DeepEqual(names(standalone), []string{"B", "C"}) { + t.Fatalf("standalone conditional: %+v %v", standalone.Ranking, names(standalone)) + } + neutral := run("count_if(kind = 'SPAN_KIND_SERVER') / count() as r", "", 2) + if neutral.Ranking.Better != "neutral" || !reflect.DeepEqual(names(neutral), []string{"B", "C"}) { + t.Fatalf("%+v %v", neutral.Ranking, names(neutral)) + } + for range 3 { + if !reflect.DeepEqual(names(run("count_if(kind = 'SPAN_KIND_SERVER') / count() as r", "", 4)), []string{"B", "C", "D", "E"}) { + t.Fatal("non-deterministic tie") + } + } + numeric := run("avg(attributes['user.score']) / 2 as half", "", 2) + if numeric.Ranking.Rule != "inherit" || numeric.Ranking.BelowFloor != 3 || !strings.Contains(numeric.Ranking.SupportColumn, "count(TRY_CAST(") || reflect.DeepEqual(names(numeric), []string{"A", "B"}) { + t.Fatalf("%+v", numeric.Ranking) + } + generic := run("avg(attributes['user.score']) / (count()+1) as half", "", 2) + if generic.Ranking.Rule != "value_floor" || !strings.Contains(generic.Ranking.SupportColumn, "count(TRY_CAST(") { + t.Fatalf("%+v", generic.Ranking) + } + if !reflect.DeepEqual(names(run("-p95(duration_ms) as neg", "higher", 3)), names(run("p95(duration_ms)", "lower", 3))) { + t.Fatal("negative latency ranking") + } +} +func TestApdexFixtures(t *testing.T) { + duck, repo := newTestEngine(t) + var spans []telemetry.Span + for _, ms := range []int{100, 500, 2000, 5000} { + for i := range 20 { + id := fmt.Sprintf("%d-%d", ms, i) + spans = append(spans, telemetry.Span{Namespace: "test", ServiceName: fmt.Sprint(ms), TraceID: id, SpanID: id, DurationMS: float64(ms), StartUnixNanos: fixtureStart.UnixNano(), EndUnixNanos: fixtureStart.UnixNano() + int64(ms)*1e6}) + } + } + commit(t, repo, spans, nil) + e := NewExecutor(duck, 30) + e.now = func() time.Time { return fixtureStart.Add(time.Hour) } + for _, tc := range []struct { + service string + want any + }{{"100", 1.0}, {"500", 1.0}, {"2000", .5}, {"5000", 0.0}, {"absent", nil}} { + d := exprDashboard("(count_if(duration_ms <= 500) + count_if(duration_ms > 500 AND duration_ms <= 2000) / 2) / count() as apdex") + p := &d.Panels[0] + p.Viz = "stat" + p.Reduce = "window" + p.Query.Where = []string{"service = '" + tc.service + "'"} + r, err := e.Run(t.Context(), RunRequest{Dashboard: d}) + if err != nil || len(r) != 1 || r[0].Status == StatusError || r[0].Frame.Totals[1] != tc.want || (tc.want == nil && r[0].Status != StatusEmpty) { + t.Fatalf("%s: %+v %v", tc.service, r, err) + } + } +} + +func TestRankingExpressionUsesWindowSeconds(t *testing.T) { + duck, repo := newTestEngine(t) + var spans []telemetry.Span + for _, tc := range []struct { + service string + n, errors int + }{{"A", 1000, 0}, {"B", 100, 10}} { + for i := range tc.n { + status := "STATUS_CODE_OK" + if i < tc.errors { + status = "STATUS_CODE_ERROR" + } + id := fmt.Sprintf("%s-%d", tc.service, i) + spans = append(spans, telemetry.Span{Namespace: "test", ServiceName: tc.service, TraceID: id, SpanID: id, StatusCode: status, StartUnixNanos: fixtureStart.UnixNano(), EndUnixNanos: fixtureStart.UnixNano() + 1e6, DurationMS: 1}) + } + } + commit(t, repo, spans, nil) + e := NewExecutor(duck, 30) + e.now = func() time.Time { return fixtureStart.Add(time.Hour) } + d := exprDashboard("rate() + count_if(status = 'STATUS_CODE_ERROR') as score") + p := &d.Panels[0] + p.Viz = "timeseries" + p.Query.By = []string{"service"} + p.Query.Bucket = "1m" + p.Options = &Options{Top: 1} + got, err := e.Run(t.Context(), RunRequest{Dashboard: d}) + if err != nil || len(got) != 1 || got[0].Status != StatusOK { + t.Fatalf("%+v %v", got, err) + } + names := got[0].Frame.Values[1] + if !reflect.DeepEqual(names, []any{"B", "Other (1)"}) { + t.Fatalf("ranked %v: expected B's 10+100/3600 to outrank A's 1000/3600", names) + } +} + +func TestRankingBuiltinSumKeepsRowSupport(t *testing.T) { + duck, repo := newTestEngine(t) + var spans []telemetry.Span + for _, tc := range []struct { + service string + rows, present int + value float64 + }{{"A", 50, 1, 100}, {"B", 20, 20, 5}, {"C", 1, 1, 1000}} { + for i := range tc.rows { + id := fmt.Sprintf("%s-%d", tc.service, i) + attrs := map[string]any{} + if i < tc.present { + attrs["score"] = tc.value + } + spans = append(spans, telemetry.Span{Namespace: "test", ServiceName: tc.service, TraceID: id, SpanID: id, StartUnixNanos: fixtureStart.UnixNano(), EndUnixNanos: fixtureStart.UnixNano() + 1e6, DurationMS: 1, Attributes: attrs}) + } + } + commit(t, repo, spans, nil) + e := NewExecutor(duck, 30) + e.now = func() time.Time { return fixtureStart.Add(time.Hour) } + run := func(measure, where string) Result { + t.Helper() + d := exprDashboard(measure) + p := &d.Panels[0] + p.Viz = "timeseries" + p.Query.By = []string{"service"} + p.Query.Bucket = "1m" + p.Options = &Options{Top: 1} + if where != "" { + p.Query.Where = []string{where} + } + got, err := e.Run(t.Context(), RunRequest{Dashboard: d}) + if err != nil || len(got) != 1 || got[0].Status != StatusOK { + t.Fatalf("%+v %v", got, err) + } + return got[0] + } + for _, measure := range []string{"sum(attributes['score'])", "sum(attributes['score']) * 2 as s"} { + r := run(measure, "service != 'C'") + if r.Ranking.SupportColumn != "count(*)" || !reflect.DeepEqual(r.Frame.Values[1], []any{"A", "Other (1)"}) { + t.Fatalf("sum row support changed: %+v %+v", r.Ranking, r.Frame) + } + } + r := run("sum(attributes['score'])", "") + if r.Ranking.BelowFloor != 1 || !reflect.DeepEqual(r.Frame.Values[1], []any{"C", "Other (2)"}) || strings.Contains(r.Frame.Note, "ranked last") { + t.Fatalf("no-floor sum disclosure: %+v %+v", r.Ranking, r.Frame) + } + generic := run("sum(attributes['score']) + count_if(status = 'STATUS_CODE_ERROR') as s", "service != 'C'") + if generic.Ranking.Rule != "value_floor" || !strings.Contains(generic.Ranking.SupportColumn, "count(TRY_CAST(") || !reflect.DeepEqual(generic.Frame.Values[1], []any{"B", "Other (1)"}) { + t.Fatalf("generic support: %+v %+v", generic.Ranking, generic.Frame) + } +} + +func TestRankingWilsonHigherUsesUpperBound(t *testing.T) { + duck, repo := newTestEngine(t) + var spans []telemetry.Span + for _, tc := range []struct { + service string + rows, servers int + }{{"A", 20, 0}, {"B", 1000, 10}, {"C", 1000, 900}} { + for i := range tc.rows { + id := fmt.Sprintf("%s-%d", tc.service, i) + kind := "SPAN_KIND_CLIENT" + if i < tc.servers { + kind = "SPAN_KIND_SERVER" + } + spans = append(spans, telemetry.Span{Namespace: "test", ServiceName: tc.service, TraceID: id, SpanID: id, Kind: kind, StartUnixNanos: fixtureStart.UnixNano(), EndUnixNanos: fixtureStart.UnixNano() + 1e6, DurationMS: 1}) + } + } + commit(t, repo, spans, nil) + e := NewExecutor(duck, 30) + e.now = func() time.Time { return fixtureStart.Add(time.Hour) } + d := exprDashboard("count_if(kind = 'SPAN_KIND_SERVER') / count() as r") + p := &d.Panels[0] + p.Viz = "timeseries" + p.Better = "higher" + p.Query.By = []string{"service"} + p.Query.Bucket = "1m" + p.Options = &Options{Top: 1} + got, err := e.Run(t.Context(), RunRequest{Dashboard: d}) + if err != nil || len(got) != 1 || got[0].Status != StatusOK { + t.Fatalf("%+v %v", got, err) + } + r := got[0] + if !reflect.DeepEqual(r.Frame.Values[1], []any{"B", "Other (2)"}) || r.Ranking.Rule != "wilson" || r.Ranking.Better != "higher" || !strings.Contains(r.SQL, "least(1.0,") || !strings.Contains(r.SQL, "confidence END ASC NULLS LAST") { + t.Fatalf("upper-bound ranking: %+v %+v %s", r.Ranking, r.Frame, r.SQL) + } +} diff --git a/internal/panel/shape.go b/internal/panel/shape.go index 10722de3..e5bf5f8c 100644 --- a/internal/panel/shape.go +++ b/internal/panel/shape.go @@ -84,50 +84,9 @@ func queryShapeVariables(q *Query, vars map[string]Variable, path string, proble } } -// Measures with arithmetic are structurally known before their engine compiler -// is installed. Binding and measure-expression semantics remain Check's job. +// Query shape and validation share the bounded measure parser. func shapeMeasures(sig *signal, texts []string, path string, problems *Problems) []Measure { - out := make([]Measure, 0, len(texts)) - for i, text := range texts { - m, message, hint := parseMeasure(sig, text) - if message != "" && (strings.Contains(text, "count_if(") || strings.ContainsAny(stripQuoted(text), "+-*/")) { - alias := "" - if at := strings.LastIndex(text, " as "); at >= 0 { - alias = strings.TrimSpace(text[at+4:]) - } else if strings.HasPrefix(text, "count_if(") && strings.HasSuffix(text, ")") { - alias = "count_if" - } - if aliasPattern.MatchString(alias) { - m = Measure{Text: text, Func: "expr", Alias: alias, Unit: "none"} - message = "" - } - } - if message != "" { - problems.addHint(fmt.Sprintf("%s[%d]", path, i), fmt.Sprintf("%q %s", text, message), hint) - continue - } - out = append(out, m) - } - uses := map[string]int{} - for _, m := range out { - if m.Alias == "" { - uses[m.Func]++ - } - } - seen := map[string]bool{} - for i := range out { - if out[i].Alias == "" { - out[i].Alias = out[i].Func - if uses[out[i].Func] > 1 && out[i].Field != nil { - out[i].Alias = out[i].Func + "_" + sanitize(out[i].Field.alias()) - } - } - if seen[out[i].Alias] { - problems.add(path, fmt.Sprintf("two measures are named %s; add distinct aliases with as", out[i].Alias)) - } - seen[out[i].Alias] = true - } - return out + return parseMeasures(sig, texts, path, problems) } func queryShapeAggregate(p *Panel, spec vizSpec, path string, problems *Problems, shapeOnly bool) ([]Measure, bool) { diff --git a/internal/panel/spec.go b/internal/panel/spec.go index 38dee827..98eaace9 100644 --- a/internal/panel/spec.go +++ b/internal/panel/spec.go @@ -77,7 +77,7 @@ type Panel struct { type Query struct { From string `json:"from" jsonschema:"spans, logs or metrics"` Where []string `json:"where,omitempty" jsonschema:"Filter expressions joined by AND, e.g. service = $service or attributes['http.route'] = '/cart'"` - Measures []string `json:"measures,omitempty" jsonschema:"Fixed logs, traces, service_map and health take no measures; other queries take 1 to 6 of fn(field) [as alias]: count(), rate(), error_rate(), share(), avg, min, max, sum, last, p50, p75, p90, p95, p99, quantile(field, q), count_distinct(field)"` + Measures []string `json:"measures,omitempty" jsonschema:"For spans and logs aggregate panels: count_if(SQL filter) and + - * / expressions with constants; expressions require as alias and an aggregate, share() stands alone, division by zero returns null. Metrics do not support arithmetic. At most 256 tokens, 64 nodes, depth 8 and 8 aggregates per measure; 256 nodes and 24 aggregates per query. Fixed logs, traces, service_map and health take no measures; other queries take 1 to 6 of fn(field) [as alias]: count(), rate(), error_rate(), share(), avg, min, max, sum, last, p50, p75, p90, p95, p99, quantile(field, q), count_distinct(field)"` By []string `json:"by,omitempty" jsonschema:"Up to 3 grouping fields: columns or attributes['key']"` Bucket string `json:"bucket,omitempty" jsonschema:"auto or 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h, 1d; required for timeseries"` Histogram *Histogram `json:"histogram,omitempty" jsonschema:"heatmap and histogram panels (milestone 2)"` diff --git a/internal/panel/table_trends.go b/internal/panel/table_trends.go index 04a7107a..08978e85 100644 --- a/internal/panel/table_trends.go +++ b/internal/panel/table_trends.go @@ -97,7 +97,7 @@ func (e *Executor) attachTableTrends(ctx context.Context, p *Panel, checked *Che if wanted[m.Alias] { expression := "NULL::DOUBLE" if sig.name != "metrics" { - expression = measureSQL(m, sig, interval.Seconds(), "PARTITION BY "+bucket) + expression = measureExprSQL(m, sig, interval.Seconds(), "PARTITION BY "+bucket) } if m.Func == "share" { share = true diff --git a/internal/panel/validate.go b/internal/panel/validate.go index 42363b7a..98b1c733 100644 --- a/internal/panel/validate.go +++ b/internal/panel/validate.go @@ -430,9 +430,50 @@ func inferBetter(p *Panel) string { if message != "" { return "" } + return inferBetterExpr(m.Expr, p, sig) +} + +func inferBetterExpr(e MeasureExpr, p *Panel, sig *signal) string { + base, a, _, ok := affineBase(e) + if ok && a != 0 { + if _, call := base.(MeasureCall); !call { + if leaf, binomial := binomial(base); binomial { + better := "" + if errorCountFilter.MatchString(leaf.Filter) { + better = "lower" + } + if a < 0 { + better = flipBetter(better) + } + return better + } + if leaf, conditional := base.(MeasureCountIf); conditional { + better := "" + if errorCountFilter.MatchString(leaf.Filter) { + better = "lower" + } + if a < 0 { + better = flipBetter(better) + } + return better + } + return "" + } + call := base.(MeasureCall) + better := inferBetterCall(call, p, sig) + if a < 0 { + better = flipBetter(better) + } + return better + } + return "" +} + +func inferBetterCall(m MeasureCall, p *Panel, sig *signal) string { if unitFamilies[p.Unit] == "duration" || m.Func == "error_rate" || (m.Field != nil && unitFamilies[m.Field.Unit] == "duration") { return "lower" } + errorFiltered := false for _, filter := range p.Query.Where { if errorCountFilter.MatchString(filter) { diff --git a/site/src/content/docs/reference/mcp-tools.mdx b/site/src/content/docs/reference/mcp-tools.mdx index 9a41c7d6..7a848437 100644 --- a/site/src/content/docs/reference/mcp-tools.mdx +++ b/site/src/content/docs/reference/mcp-tools.mdx @@ -65,7 +65,7 @@ AG-UI `mcp-app` activity content uses exactly `resource_uri`, `tool_name`, ## create_dashboard -**Create dashboard** — Create a dashboard for the authenticated user from a complete spec. Read get_telemetry_schema first and preview_panels until every non-text panel returns data. Empty or failing panels return error.code invalid_spec with their path, title and diagnosis, plus structured problems. Successful saves return a receipt for that committed version: base_version, version, changes, layout_changed, dashboard_fields and save_check. Changes describe authored panel fields and position_changed; physical packing is only layout_changed. Order chips mark the minimal moved set. save_check reports checked, reason when unchecked, total elapsed_ms and one status/rows result per saved panel with elapsed_ms when executed. checked means every panel was executed, not that error or empty panels are healthy. Text rows identify nonempty content, not telemetry. Use the structured receipt rather than prose warnings as check evidence. Create receipts list added panels without layout or dashboard edit chips. No-op saves still create a new version with no change chips. Per-panel elapsed_ms is omitted when the panel did not run. A dashboard is \{name, description, time:\{range}, variables, panels}. Each panel: \{id (lowercase), title, viz, width 1-12, query or sql}. viz: stat or gauge (one measure; gauge needs min and max), timeseries (bucket auto, at most one by), bar (one or two by), table (up to three by), text (content in Markdown), heatmap (bucket auto, no by), histogram (at most one by), scatter (exactly two measures in x then y order, one item dimension and an optional colour dimension), state_timeline (one measure, one item dimension, bucket auto and thresholds required). Rollup panel types are service_map (dependency graph) and health (overview metrics, error trend and health distribution). They require query.from=spans, no measures, by, bucket or sort, and only namespace/service equality filters with a literal or single-value variable; explicit casts and values with surrounding whitespace are rejected. Reads default to 400 services/edges and are capped at 400 even when query.limit is larger. Service scope applies before the limit; map nodes carry p95_ms and edges carry average_ms; error_rate is percent. Row panel types are logs, log_patterns and traces. Logs and traces take no measures, by or bucket. Patterns use count() by body_template. Patterns group only by body_template. Severity is the most frequent severity, ties choose the higher severity. Service is the most frequent service, ties choose ascending service name. Both describe the scoped, redacted events, not extra grouping dimensions. Each pattern returns dominant severity, top service, count and a dense trend, computed in the same bounded query after redaction and scoped filters. Redaction applies before filtering, grouping, display and drill-down. Row panels cannot use SQL. "erroring" means slowest erroring traces: filter to erroring traces, then rank by root duration. Trace candidate ranking is approximate when filters exclude the root span, as with exemplars. Categorical charts use fixed-order colour slots. Categorical options.top defaults to 6, maximum 6. Structured panels: the server computes Other; series are chosen worst-first by confidence (Wilson lower bound for error rates; at least 20 samples for latency); the rest fold into Other (N). Count, rate, sum and share rank largest first. Error rates require at least 20 requests for eligible Wilson ranking (z=1.96). Percentiles, quantile, avg, max and min require at least 20 non-null numeric samples for eligible value ranking and use better (explicit or inferred). Ineligible series follow eligible ones by sample count descending. Ties use sample count descending, then name ascending. SQL panels: series past six are left out, with a note. state_timeline defaults to 8 rows, maximum 20; other noncategorical panels use the same limits. Scatter supports options.x_scale and options.y_scale (log or linear), with distinct x_unit for x and unit for y, each inferred independently when omitted. Rows returned use the count unit. State timelines preserve null and absent buckets as unknown and keep the top items without merging them into Other. Scatter requires a structured query. SQL state_timeline requires timestamp time, a string item, one numeric measure and optional string state; its interval is one minute and thresholds are required. Items rank by volume (row count) for top N. Previous-period comparison is not drawn for scatter or state_timeline. Distribution panels use a structured query with one count() measure and histogram: \{field: duration_ms, buckets: log2} for spans or \{field: value, buckets: explicit} for metrics. Negative span durations clamp to [0,1); +Inf goes to overflow; NaN is excluded because it is not a measurement. Metric histograms use stored temporality and shared per-series increases; resets contribute current counts. Delta histograms sum observation weights. query: \{from: spans|logs|metrics, where: [filter expressions], measures: [fn(field) as alias], by: [fields], bucket, sort, limit}. Measures: count(), rate() per second, error_rate() percent, share() percent, avg/min/max/sum(field), last(value) for metrics, p50/p75/p90/p95/p99(field), quantile(field, 0.999), count_distinct(field). Fields are columns from get_telemetry_schema or attributes['key'] / resource['key'] with the key written literally. Filters are SQL boolean expressions: service = $service, kind = 'SPAN_KIND_SERVER', status = 'STATUS_CODE_ERROR', http_route IN $routes, attributes['http.response.status_code']::INTEGER >= 500. Variables: \{name, kind: query|custom|constant|text, from, field, default, include_all}; $__all selects All and removes filters that use the variable. sql: one SELECT over spans, logs, metrics, service_rollup, edge_rollup or resource_inventory that filters time with $__window(column). Compare time columns with TIMESTAMP 'YYYY-MM-DD HH:MM:SS' (UTC), or cast TIMESTAMPTZ literals with ::TIMESTAMPTZ_NS. Use values exactly as get_telemetry_schema lists them. Example panel: \{"id":"latency","title":"Checkout latency","viz":"timeseries","width":8,"query":\{"from":"spans","where":["service = 'checkout'","kind = 'SPAN_KIND_SERVER'"],"measures":["p50(duration_ms)","p95(duration_ms)","p99(duration_ms)"],"bucket":"auto"},"unit":"ms","thresholds":[\{"value":1500,"status":"bad"}]}. Metrics: gauge/updown | counter | histogram. count(): points; count_distinct(): distinct. rate(): undefined | series increase/elapsed summed | count rate summed. sum(value): series means summed | increases | sum increases. avg(value): mean series means | undefined | sum/count increases. Gauge/updown sum/avg carry earlier points within 5m. Deltas spread across covered buckets; rate alone carries within 5m. rate() is per-second increase over covered elapsed time; auto >=1m. min/max: points | points | undefined. last(value): latest strictly before bucket/window end, reported within 5m, summed | same | undefined. pNN/quantile: points | undefined | interpolated bucket increases. summary: no value aggregates. Undefined: NULL. Fix name in its own where entry: one literal or single-value variable without All or multi-value; or name in by. Read type/temporality from get_telemetry_schema. Panel SQL also supports resource_inventory: signal, namespace, service, full typed resource, first_seen and last_seen. One row per distinct full resource per signal/namespace/service observed inside the logical panel window; first_seen/last_seen are actual in-window event times. Select signal='spans', 'logs' or 'metrics' and use resource['key'] with literal dotted keys. count(*) counts resource identities per signal, not events or instances. Declare $__window(first_seen). This relation is SQL-only: query.from and variables remain spans|logs|metrics; unscoped SQL cannot read it. state_timeline needs at least one threshold marked warn or bad, rather than only ok. Annotations attach only to timeseries, heatmap and state_timeline panels, scoped by service and namespace filters. drill: logs needs query.from=logs. Drill is not available on metrics. Every table format's field must exist in the returned frame; formatting cannot reference an absent column. A structured-table sparkline field must be a measure alias from that table's query. service_link needs variable to name the query or custom variable selected by the link. highlight applies to logs and log_patterns, at most 200 characters. split: deploy needs a service equality filter, as a literal or a single-value variable; other filters are allowed. When the service is All, a split: deploy panel shows the plain bar with a note explaining the missing service scope. Use service_map for dependency context, health for service health; neither proves causality. Example 1: Reference shapes; use only the types the question needs. \{"name":"Investigation shapes","annotations":\{"deploys":true,"anomalies":true},"variables":[\{"name":"service","kind":"query","from":"spans","field":"service"}],"panels":[\{"id":"latency_heat","title":"Latency over time","viz":"heatmap","query":\{"from":"spans","where":["service = $service"],"measures":["count()"],"bucket":"auto","histogram":\{"field":"duration_ms","buckets":"log2"}},"drill":"traces"},\{"id":"latency_hist","title":"Latency by operation","viz":"histogram","query":\{"from":"spans","where":["service = $service"],"measures":["count()"],"by":["operation"],"histogram":\{"field":"duration_ms","buckets":"log2"}},"drill":"traces"},\{"id":"items","title":"Calls versus tail latency","viz":"scatter","query":\{"from":"spans","where":["service = $service"],"measures":["count() as rows","p95(duration_ms) as tail_latency"],"by":["operation"]},"drill":"traces"},\{"id":"states","title":"Error states","viz":"state_timeline","query":\{"from":"spans","where":["service = $service"],"measures":["error_rate()"],"by":["operation"],"bucket":"auto"},"thresholds":[\{"value":5,"status":"bad"}],"drill":"traces"},\{"id":"log_rows","title":"Recent logs","viz":"logs","query":\{"from":"logs","where":["service = $service"],"sort":"time","limit":100},"drill":"logs"},\{"id":"patterns","title":"Repeated log patterns","viz":"log_patterns","query":\{"from":"logs","where":["service = $service"],"measures":["count()"],"by":["body_template"],"bucket":"auto","limit":50},"drill":"logs"},\{"id":"trace_rows","title":"Slow traces","viz":"traces","query":\{"from":"spans","where":["service = $service"],"sort":"duration_ms","limit":20},"drill":"traces"},\{"id":"map","title":"Service calls","viz":"service_map","query":\{"from":"spans"}},\{"id":"health","title":"Service health","viz":"health","query":\{"from":"spans"}}]} Example 2: Reference shapes; use only the types the question needs. \{"name":"Interaction shapes","variables":[\{"name":"service","kind":"query","from":"spans","field":"service"}],"panels":[\{"id":"hist","title":"Metric distribution","viz":"histogram","query":\{"from":"metrics","where":["service = $service"],"measures":["count()"],"histogram":\{"field":"value","buckets":"explicit"}}},\{"id":"table","title":"Service calls and trends","viz":"table","query":\{"from":"spans","measures":["count() as calls"],"by":["service"]},"options":\{"columns":[\{"field":"service","format":"service_link","variable":"service"},\{"field":"calls","format":"sparkline"}]}},\{"id":"prior","title":"Service calls one day earlier","viz":"bar","query":\{"from":"spans","measures":["count()"],"by":["service"]},"click":\{"set_variable":"service"},"time":\{"shift":"1d"}}]} Metric examples; use when the discovered type fits. \{"name":"Metric measures","panels":[\{"id":"network","title":"Network bytes per second","viz":"timeseries","query":\{"from":"metrics","where":["name = 'system.network.io'"],"measures":["rate()"],"by":["attributes['direction']"],"bucket":"auto"}},\{"id":"duration","title":"Request duration p95","viz":"timeseries","query":\{"from":"metrics","where":["name = 'http.server.request.duration'"],"measures":["p95(value)"],"bucket":"auto"},"unit":"s"}]} Observed-resource SQL example. \{"name":"Observed resources","panels":[\{"id":"resources","title":"Span resources observed in this window","viz":"table","sql":"SELECT namespace,service,resource['service.version']::VARCHAR AS version,first_seen,last_seen FROM resource_inventory WHERE signal='spans' AND $__window(first_seen) ORDER BY namespace,service,version,first_seen,last_seen"}]} +**Create dashboard** — Create a dashboard for the authenticated user from a complete spec. Read get_telemetry_schema first and preview_panels until every non-text panel returns data. Empty or failing panels return error.code invalid_spec with their path, title and diagnosis, plus structured problems. Successful saves return a receipt for that committed version: base_version, version, changes, layout_changed, dashboard_fields and save_check. Changes describe authored panel fields and position_changed; physical packing is only layout_changed. Order chips mark the minimal moved set. save_check reports checked, reason when unchecked, total elapsed_ms and one status/rows result per saved panel with elapsed_ms when executed. checked means every panel was executed, not that error or empty panels are healthy. Text rows identify nonempty content, not telemetry. Use the structured receipt rather than prose warnings as check evidence. Create receipts list added panels without layout or dashboard edit chips. No-op saves still create a new version with no change chips. Per-panel elapsed_ms is omitted when the panel did not run. A dashboard is \{name, description, time:\{range}, variables, panels}. Each panel: \{id (lowercase), title, viz, width 1-12, query or sql}. viz: stat or gauge (one measure; gauge needs min and max), timeseries (bucket auto, at most one by), bar (one or two by), table (up to three by), text (content in Markdown), heatmap (bucket auto, no by), histogram (at most one by), scatter (exactly two measures in x then y order, one item dimension and an optional colour dimension), state_timeline (one measure, one item dimension, bucket auto and thresholds required). Rollup panel types are service_map (dependency graph) and health (overview metrics, error trend and health distribution). They require query.from=spans, no measures, by, bucket or sort, and only namespace/service equality filters with a literal or single-value variable; explicit casts and values with surrounding whitespace are rejected. Reads default to 400 services/edges and are capped at 400 even when query.limit is larger. Service scope applies before the limit; map nodes carry p95_ms and edges carry average_ms; error_rate is percent. Row panel types are logs, log_patterns and traces. Logs and traces take no measures, by or bucket. Patterns use count() by body_template. Patterns group only by body_template. Severity is the most frequent severity, ties choose the higher severity. Service is the most frequent service, ties choose ascending service name. Both describe the scoped, redacted events, not extra grouping dimensions. Each pattern returns dominant severity, top service, count and a dense trend, computed in the same bounded query after redaction and scoped filters. Redaction applies before filtering, grouping, display and drill-down. Row panels cannot use SQL. "erroring" means slowest erroring traces: filter to erroring traces, then rank by root duration. Trace candidate ranking is approximate when filters exclude the root span, as with exemplars. Categorical charts use fixed-order colour slots. Categorical options.top defaults to 6, maximum 6. Structured panels: the server computes Other; series are chosen worst-first by confidence (Wilson lower bound for error rates; at least 20 samples for latency); the rest fold into Other (N). Count, rate, sum and share rank largest first. Error rates require at least 20 requests for eligible Wilson ranking (z=1.96). Percentiles, quantile, avg, max and min require at least 20 non-null numeric samples for eligible value ranking and use better (explicit or inferred). Ineligible series follow eligible ones by sample count descending. Ties use sample count descending, then name ascending. SQL panels: series past six are left out, with a note. state_timeline defaults to 8 rows, maximum 20; other noncategorical panels use the same limits. Scatter supports options.x_scale and options.y_scale (log or linear), with distinct x_unit for x and unit for y, each inferred independently when omitted. Rows returned use the count unit. State timelines preserve null and absent buckets as unknown and keep the top items without merging them into Other. Scatter requires a structured query. SQL state_timeline requires timestamp time, a string item, one numeric measure and optional string state; its interval is one minute and thresholds are required. Items rank by volume (row count) for top N. Previous-period comparison is not drawn for scatter or state_timeline. Distribution panels use a structured query with one count() measure and histogram: \{field: duration_ms, buckets: log2} for spans or \{field: value, buckets: explicit} for metrics. Negative span durations clamp to [0,1); +Inf goes to overflow; NaN is excluded because it is not a measurement. Metric histograms use stored temporality and shared per-series increases; resets contribute current counts. Delta histograms sum observation weights. query: \{from: spans|logs|metrics, where: [filter expressions], measures: [fn(field) as alias], by: [fields], bucket, sort, limit}. Measures: count(), rate() per second, error_rate() percent, share() percent, avg/min/max/sum(field), last(value) for metrics, p50/p75/p90/p95/p99(field), quantile(field, 0.999), count_distinct(field). Spans and logs aggregate panels also support count_if(SQL filter) and + - * / with constants and parentheses; arithmetic requires as alias and at least one aggregate, variables are not allowed inside count_if, share() stands alone, and division by zero returns null. Measures are bounded to 256 tokens, 64 nodes, depth 8 and 8 aggregates each, and 256 nodes and 24 aggregates together. Metrics do not support arithmetic. Fields are columns from get_telemetry_schema or attributes['key'] / resource['key'] with the key written literally. Filters are SQL boolean expressions: service = $service, kind = 'SPAN_KIND_SERVER', status = 'STATUS_CODE_ERROR', http_route IN $routes, attributes['http.response.status_code']::INTEGER >= 500. Variables: \{name, kind: query|custom|constant|text, from, field, default, include_all}; $__all selects All and removes filters that use the variable. sql: one SELECT over spans, logs, metrics, service_rollup, edge_rollup or resource_inventory that filters time with $__window(column). Compare time columns with TIMESTAMP 'YYYY-MM-DD HH:MM:SS' (UTC), or cast TIMESTAMPTZ literals with ::TIMESTAMPTZ_NS. Use values exactly as get_telemetry_schema lists them. Example panel: \{"id":"latency","title":"Checkout latency","viz":"timeseries","width":8,"query":\{"from":"spans","where":["service = 'checkout'","kind = 'SPAN_KIND_SERVER'"],"measures":["p50(duration_ms)","p95(duration_ms)","p99(duration_ms)"],"bucket":"auto"},"unit":"ms","thresholds":[\{"value":1500,"status":"bad"}]}. Metrics: gauge/updown | counter | histogram. count(): points; count_distinct(): distinct. rate(): undefined | series increase/elapsed summed | count rate summed. sum(value): series means summed | increases | sum increases. avg(value): mean series means | undefined | sum/count increases. Gauge/updown sum/avg carry earlier points within 5m. Deltas spread across covered buckets; rate alone carries within 5m. rate() is per-second increase over covered elapsed time; auto >=1m. min/max: points | points | undefined. last(value): latest strictly before bucket/window end, reported within 5m, summed | same | undefined. pNN/quantile: points | undefined | interpolated bucket increases. summary: no value aggregates. Undefined: NULL. Fix name in its own where entry: one literal or single-value variable without All or multi-value; or name in by. Read type/temporality from get_telemetry_schema. Panel SQL also supports resource_inventory: signal, namespace, service, full typed resource, first_seen and last_seen. One row per distinct full resource per signal/namespace/service observed inside the logical panel window; first_seen/last_seen are actual in-window event times. Select signal='spans', 'logs' or 'metrics' and use resource['key'] with literal dotted keys. count(*) counts resource identities per signal, not events or instances. Declare $__window(first_seen). This relation is SQL-only: query.from and variables remain spans|logs|metrics; unscoped SQL cannot read it. state_timeline needs at least one threshold marked warn or bad, rather than only ok. Annotations attach only to timeseries, heatmap and state_timeline panels, scoped by service and namespace filters. drill: logs needs query.from=logs. Drill is not available on metrics. Every table format's field must exist in the returned frame; formatting cannot reference an absent column. A structured-table sparkline field must be a measure alias from that table's query. service_link needs variable to name the query or custom variable selected by the link. highlight applies to logs and log_patterns, at most 200 characters. split: deploy needs a service equality filter, as a literal or a single-value variable; other filters are allowed. When the service is All, a split: deploy panel shows the plain bar with a note explaining the missing service scope. Use service_map for dependency context, health for service health; neither proves causality. Example 1: Reference shapes; use only the types the question needs. \{"name":"Investigation shapes","annotations":\{"deploys":true,"anomalies":true},"variables":[\{"name":"service","kind":"query","from":"spans","field":"service"}],"panels":[\{"id":"latency_heat","title":"Latency over time","viz":"heatmap","query":\{"from":"spans","where":["service = $service"],"measures":["count()"],"bucket":"auto","histogram":\{"field":"duration_ms","buckets":"log2"}},"drill":"traces"},\{"id":"latency_hist","title":"Latency by operation","viz":"histogram","query":\{"from":"spans","where":["service = $service"],"measures":["count()"],"by":["operation"],"histogram":\{"field":"duration_ms","buckets":"log2"}},"drill":"traces"},\{"id":"items","title":"Calls versus tail latency","viz":"scatter","query":\{"from":"spans","where":["service = $service"],"measures":["count() as rows","p95(duration_ms) as tail_latency"],"by":["operation"]},"drill":"traces"},\{"id":"states","title":"Error states","viz":"state_timeline","query":\{"from":"spans","where":["service = $service"],"measures":["error_rate()"],"by":["operation"],"bucket":"auto"},"thresholds":[\{"value":5,"status":"bad"}],"drill":"traces"},\{"id":"log_rows","title":"Recent logs","viz":"logs","query":\{"from":"logs","where":["service = $service"],"sort":"time","limit":100},"drill":"logs"},\{"id":"patterns","title":"Repeated log patterns","viz":"log_patterns","query":\{"from":"logs","where":["service = $service"],"measures":["count()"],"by":["body_template"],"bucket":"auto","limit":50},"drill":"logs"},\{"id":"trace_rows","title":"Slow traces","viz":"traces","query":\{"from":"spans","where":["service = $service"],"sort":"duration_ms","limit":20},"drill":"traces"},\{"id":"map","title":"Service calls","viz":"service_map","query":\{"from":"spans"}},\{"id":"health","title":"Service health","viz":"health","query":\{"from":"spans"}}]} Example 2: Reference shapes; use only the types the question needs. \{"name":"Interaction shapes","variables":[\{"name":"service","kind":"query","from":"spans","field":"service"}],"panels":[\{"id":"hist","title":"Metric distribution","viz":"histogram","query":\{"from":"metrics","where":["service = $service"],"measures":["count()"],"histogram":\{"field":"value","buckets":"explicit"}}},\{"id":"table","title":"Service calls and trends","viz":"table","query":\{"from":"spans","measures":["count() as calls"],"by":["service"]},"options":\{"columns":[\{"field":"service","format":"service_link","variable":"service"},\{"field":"calls","format":"sparkline"}]}},\{"id":"prior","title":"Service calls one day earlier","viz":"bar","query":\{"from":"spans","measures":["count()"],"by":["service"]},"click":\{"set_variable":"service"},"time":\{"shift":"1d"}}]} Metric examples; use when the discovered type fits. \{"name":"Metric measures","panels":[\{"id":"network","title":"Network bytes per second","viz":"timeseries","query":\{"from":"metrics","where":["name = 'system.network.io'"],"measures":["rate()"],"by":["attributes['direction']"],"bucket":"auto"}},\{"id":"duration","title":"Request duration p95","viz":"timeseries","query":\{"from":"metrics","where":["name = 'http.server.request.duration'"],"measures":["p95(value)"],"bucket":"auto"},"unit":"s"}]} Observed-resource SQL example. \{"name":"Observed resources","panels":[\{"id":"resources","title":"Span resources observed in this window","viz":"table","sql":"SELECT namespace,service,resource['service.version']::VARCHAR AS version,first_seen,last_seen FROM resource_inventory WHERE signal='spans' AND $__window(first_seen) ORDER BY namespace,service,version,first_seen,last_seen"}]} **Additive.** It creates something new and alters nothing that exists. diff --git a/ui/host/tests/go-fragments/logs.json b/ui/host/tests/go-fragments/logs.json index 5a85ef34..3ecab170 100644 --- a/ui/host/tests/go-fragments/logs.json +++ b/ui/host/tests/go-fragments/logs.json @@ -52,6 +52,17 @@ }, "results": [ { + "ranking": { + "rule": "builtin", + "better": "higher", + "floor": 20, + "support_column": "count(*)", + "below_floor": 0, + "tie_breakers": [ + "n desc", + "dimension asc" + ] + }, "annotation_scope": { "services": [ { From 6d18a5a8fedb8de5eb302f3fdc8024e7cb229cd3 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 16:30:08 -0700 Subject: [PATCH 09/30] feat(fanql): position-aware completion with coalesced schema fetches --- internal/fanql/complete.go | 664 ++++++++++++++++++++++++++++++++ internal/fanql/complete_test.go | 519 +++++++++++++++++++++++++ internal/fanql/parser.go | 79 +++- 3 files changed, 1254 insertions(+), 8 deletions(-) create mode 100644 internal/fanql/complete.go create mode 100644 internal/fanql/complete_test.go diff --git a/internal/fanql/complete.go b/internal/fanql/complete.go new file mode 100644 index 00000000..9a4b3597 --- /dev/null +++ b/internal/fanql/complete.go @@ -0,0 +1,664 @@ +package fanql + +import ( + "context" + "fmt" + "slices" + "sort" + "strconv" + "strings" + "sync" + "time" + + "github.com/labstack/fanout/internal/panel" + "github.com/labstack/fanout/internal/telemetry" +) + +type Expect struct { + Class string + Field *Field + Func string + Arg int + Scope string +} + +// expectAt replaces a whole lexical token even when the cursor is in its middle. +// Punctuation is consumed by the grammar: a cursor after ':' expects a value. +func expectAt(text string, cursor int) (Token, []Expect) { + token, p := completionPrefix(text, cursor, "") + return token, p.expected +} + +func completionPrefix(text string, cursor int, source string) (token Token, p *parser) { + runes := []rune(text) + cursor = max(0, min(cursor, len(runes))) + token = Token{Kind: EOF, Span: Span{cursor, cursor}} + for _, candidate := range Lex(text) { + if candidate.Kind == EOF { + break + } + if candidate.Span.Start <= cursor && cursor <= candidate.Span.End { + switch candidate.Kind { + case Word, Ident, Path, String, Raw, BracketKey, Number: + token = candidate + } + } + } + start := token.Span.Start + prefix := string(runes[:start]) + p = &parser{runes: []rune(prefix), tokens: Lex(prefix), bounded: true, heights: make(map[any]int), completion: true, completionUsed: make(map[string]bool)} + defer func() { + if v := recover(); v != nil { + switch v.(type) { + case completionEnd, parseBound: + default: + panic(v) + } + } + }() + if len(p.runes) > MaxTextRunes || len(prefix) > MaxTextBytes || len(p.tokens) > MaxTokens+1 { + return token, p + } + p.query(source) + return token, p +} + +type SchemaSource interface { + Schema(context.Context, panel.SchemaRequest) (*panel.Schema, error) +} + +type CompleteRequest struct { + Text string + Cursor int + Source string + Viz string + Window string + Namespace string + Variables []panel.Variable +} + +type Item struct { + Label string `json:"label"` + Insert string `json:"insert"` + Kind string `json:"kind"` + Detail string `json:"detail"` +} + +type SchemaStatus struct { + Window string `json:"window"` + Sampled bool `json:"sampled"` + Warm bool `json:"warm"` + Recent bool `json:"recent"` + Error bool `json:"error,omitempty"` +} + +type CompleteResponse struct { + Replace panel.TextSpan `json:"replace"` + Items []Item `json:"items"` + Schema SchemaStatus `json:"schema"` +} + +const MaxCompletionItems = 50 + +type completionKey struct{ window, namespace string } +type completionSchemaEntry struct { + schema *panel.Schema + expires time.Time + failed bool +} + +// Schema work is limited across all Completers, including requests queued after +// their HTTP contexts have gone away. No request waits for this semaphore. +var completionSchemaSlots = make(chan struct{}, 4) + +type Completer struct { + source SchemaSource + mu sync.Mutex + inflight map[completionKey]chan struct{} + cache map[completionKey]completionSchemaEntry + now func() time.Time +} + +func NewCompleter(source SchemaSource) *Completer { + return &Completer{source: source, inflight: make(map[completionKey]chan struct{}), cache: make(map[completionKey]completionSchemaEntry), now: time.Now} +} + +func completionWindow(window string) (string, bool) { + if window == "" { + return "24h", true + } + d, err := time.ParseDuration(window) + if strings.HasSuffix(window, "d") { + var days float64 + days, err = strconv.ParseFloat(strings.TrimSuffix(window, "d"), 64) + d = time.Duration(days * float64(24*time.Hour)) + } + if err != nil || d <= 0 { + return "24h", true + } + if d > 24*time.Hour { + return "24h", true + } + for _, name := range []string{"5m", "15m", "1h", "3h", "6h", "12h", "24h"} { + n, _ := time.ParseDuration(name) + if d <= n { + return name, false + } + } + return "24h", false +} + +func (c *Completer) schema(ctx context.Context, key completionKey) (*panel.Schema, bool, bool) { + c.mu.Lock() + defer c.mu.Unlock() + now := c.now() + if entry, ok := c.cache[key]; ok && now.Before(entry.expires) { + return entry.schema, entry.schema != nil, entry.failed + } + if c.source == nil { + return nil, false, false + } + if _, ok := c.inflight[key]; !ok { + done := make(chan struct{}) + c.inflight[key] = done + go c.fetch(context.WithoutCancel(ctx), key, done) + } + return nil, false, false +} + +func (c *Completer) fetch(parent context.Context, key completionKey, done chan struct{}) { + ctx, cancel := context.WithTimeout(parent, 20*time.Second) + defer cancel() + var schema *panel.Schema + var err error + select { + case completionSchemaSlots <- struct{}{}: + schema, err = c.source.Schema(ctx, panel.SchemaRequest{Window: key.window, Namespace: key.namespace}) + <-completionSchemaSlots + case <-ctx.Done(): + err = ctx.Err() + } + c.mu.Lock() + defer c.mu.Unlock() + now := c.now() + ttl := time.Minute + failed := err != nil || schema == nil + if failed { + ttl = 10 * time.Second + schema = nil + } + for k, entry := range c.cache { + if !now.Before(entry.expires) { + delete(c.cache, k) + } + } + if len(c.cache) >= 64 { + clear(c.cache) + } + c.cache[key] = completionSchemaEntry{schema: schema, expires: now.Add(ttl), failed: failed} + delete(c.inflight, key) + close(done) +} + +type completionCandidate struct { + item Item + class, match, boost int + count int64 + used bool +} + +type completionCandidates struct { + req CompleteRequest + token Token + p *parser + signal panel.SignalSchema + source, prefix string + items []completionCandidate + class int +} + +func (c *Completer) Complete(ctx context.Context, req CompleteRequest) CompleteResponse { + window, recent := completionWindow(req.Window) + schema, warm, failed := c.schema(ctx, completionKey{window, req.Namespace}) + token, p := completionPrefix(req.Text, req.Cursor, req.Source) + r := CompleteResponse{Replace: panel.TextSpan{Start: token.Span.Start, End: token.Span.End}, Items: []Item{}, Schema: SchemaStatus{Window: window, Sampled: true, Warm: warm, Recent: recent, Error: failed}} + if token.Kind == String || token.Kind == Raw { + return r + } + source := req.Source + if p.completionQuery != nil { + source = p.completionQuery.Source + } + state := completionCandidates{req: req, token: token, p: p, source: source} + if schema != nil { + state.signal = schema.Signals[source] + } + cursor := max(token.Span.Start, min(req.Cursor, token.Span.End)) + if token.Kind != EOF { + state.prefix = string([]rune(req.Text)[token.Span.Start:cursor]) + } + if token.Kind == BracketKey { + r.Replace.Start++ + if !token.Unclosed { + r.Replace.End-- + } + state.prefix = strings.TrimPrefix(state.prefix, string(token.Quote)) + quote := string(token.Quote) + state.prefix = strings.ReplaceAll(state.prefix, quote+quote, quote) + } + for i, e := range p.expected { + state.class = i + state.candidates(e) + } + sort.SliceStable(state.items, func(i, j int) bool { + a, b := state.items[i], state.items[j] + if a.match != b.match { + return a.match < b.match + } + if a.used != b.used { + return !a.used + } + if a.boost != b.boost { + return a.boost > b.boost + } + if a.class != b.class { + return a.class < b.class + } + return a.count > b.count + }) + seen := map[string]bool{} + for _, candidate := range state.items { + if seen[candidate.item.Label] { + continue + } + seen[candidate.item.Label] = true + r.Items = append(r.Items, candidate.item) + if len(r.Items) == MaxCompletionItems { + break + } + } + return r +} + +func (s *completionCandidates) add(label, insert, kind, detail string, count int64, boost int) { + match := 0 + prefix := strings.ToLower(s.prefix) + lower := strings.ToLower(label) + if prefix != "" && !strings.HasPrefix(lower, prefix) { + if !strings.Contains(lower, prefix) { + return + } + match = 1 + } + if insert == "" { + insert = label + } + class := s.class * 2 + if kind == "attribute" { + class++ + } + s.items = append(s.items, completionCandidate{item: Item{Label: label, Insert: insert, Kind: kind, Detail: detail}, class: class, match: match, count: count, boost: boost, used: s.p.completionUsed[lower]}) +} + +func (s *completionCandidates) words(kind string, words ...string) { + for _, word := range words { + s.add(word, word, kind, "", 0, 0) + } +} + +func (s *completionCandidates) candidates(e Expect) { + switch e.Class { + case "source": + s.words("keyword", panel.SignalNames()...) + case "field": + s.fields(e, false, "") + case "bracket_key": + s.fields(e, false, e.Scope) + case "variable": + for _, v := range s.req.Variables { + s.add("$"+v.Name, "", "variable", "", 0, 0) + } + case "free_text": + if strings.ContainsAny(s.prefix, ".$[") { + return + } + column := "operation" + if s.source == "logs" { + column = "body" + } + // This hint follows real suggestions even when the prefix matches no field. + s.items = append(s.items, completionCandidate{item: Item{Label: s.prefix, Insert: s.prefix, Kind: "value", Detail: "free text searches " + column}, match: 3, class: s.class}) + case "operator": + if e.Scope == "term" { + s.words("operator", "-", "(", "not") + return + } + s.operators(e.Field) + case "value": + s.values(e) + case "measure": + s.measures() + case "marg": + if e.Func == "quantile" && e.Arg == 1 { + s.words("value", "0.5", "0.9", "0.95", "0.99") + return + } + if e.Func == "histogram" { + s.fields(e, true, "") + return + } + for _, spec := range panel.MeasureSpecs() { + if spec.Name == e.Func && e.Arg < spec.Args { + s.fields(e, spec.Numeric, "") + return + } + } + case "bucket": + if s.req.Viz != "" && !slices.Contains([]string{"timeseries", "heatmap", "state_timeline", "log_patterns"}, s.req.Viz) { + s.add("", "", "keyword", s.req.Viz+" panels have no bucket", 0, 0) + return + } + s.words("bucket", panel.BucketNames()...) + case "sort_key": + s.sortKeys() + case "integer": + limit := 1000 + if s.req.Viz == "log_patterns" { + limit = 50 + } + if s.req.Viz == "health" || s.req.Viz == "service_map" { + limit = 400 + } + for _, n := range []int{10, 50, 100, 1000} { + if n <= limit { + s.words("value", fmt.Sprint(n)) + } + } + case "clause": + switch e.Scope { + case "measure": + s.words("keyword", ",", "as", "by") + if s.bucketAllowed() { + s.words("keyword", "every") + } + s.words("keyword", "sort", "limit") + if stage := s.p.completionQuery.Stage; stage != nil && len(stage.Measures) > 0 { + _, share, _ := measureLeaves(stage.Measures[len(stage.Measures)-1].Expr) + if !share { + s.words("operator", "+", "-", "*", "/") + } + } + case "stage": + if s.p.completionQuery.Stage.Bucket == "" && s.bucketAllowed() { + s.words("keyword", "every") + } + s.words("keyword", "sort", "limit") + default: + if s.req.Source == "" { + s.words("keyword", "where", "|", "sort", "limit") + } + } + } +} + +func (s *completionCandidates) bucketAllowed() bool { + return s.req.Viz == "" || slices.Contains([]string{"timeseries", "heatmap", "state_timeline", "log_patterns"}, s.req.Viz) +} + +func (s *completionCandidates) fields(e Expect, numeric bool, scope string) { + if e.Func == "by" { + maximum := 3 + switch s.req.Viz { + case "timeseries", "state_timeline", "histogram", "log_patterns": + maximum = 1 + case "bar", "scatter": + maximum = 2 + case "stat", "gauge", "heatmap", "logs", "traces", "health", "service_map": + maximum = 0 + } + if e.Arg >= maximum { + s.add("", "", "keyword", fmt.Sprintf("%s groups by at most %d field", s.req.Viz, maximum), 0, 0) + return + } + } + if scope == "" { + fields, _ := panel.SignalColumns(s.source) + for _, field := range fields { + if field.Type == panel.TypeMap || e.Func == "by" && field.Type != panel.TypeString { + continue + } + name := field.Name + if name == "duration_ms" { + name = "duration" + } + boost := 0 + if numeric && field.Type == panel.TypeNumber { + boost = 2 + } + s.add(name, name, "field", field.Description, 0, boost) + } + } + for _, attribute := range s.signal.Attributes { + attributeScope := attribute.Scope + if attributeScope == "" { + attributeScope = "attributes" + } + if scope != "" && attributeScope != scope { + continue + } + label := attribute.Key + var insert string + if scope != "" { + quote := string(s.token.Quote) + insert = strings.ReplaceAll(attribute.Key, quote, quote+quote) + if s.token.Unclosed { + insert += quote + "]" + } + } else { + label = printField(Field{Scope: attributeScope, Key: attribute.Key}) + insert = label + } + boost := 0 + if numeric && attribute.Type == "number" { + boost = 2 + } + if s.serviceBoost(attribute.Services) { + boost++ + } + s.add(label, insert, "attribute", attribute.Type, attribute.Count, boost) + } +} + +func (s *completionCandidates) serviceBoost(services string) bool { + if services == "" || s.p.completionQuery == nil { + return false + } + var has func(Expr) bool + has = func(x Expr) bool { + switch x := x.(type) { + case *Compare: + if x.Field.Key == "service" && x.Field.Scope == "" && (x.Op == ":" || x.Op == "=") && x.Value.Kind != VariableValue { + return slices.Contains(strings.Split(services, ", "), x.Value.Text) + } + case *And: + for _, term := range x.Terms { + if has(term) { + return true + } + } + } + return false + } + for _, x := range s.p.completionQuery.Where { + if has(x) { + return true + } + } + return false +} + +func (s *completionCandidates) operators(field *Field) { + if field == nil { + return + } + if field.Scope == "" { + switch strings.ToLower(field.Key) { + case "duration": + s.words("operator", ">", ">=", "<", "<=", "between", ":") + return + case "severity": + s.words("operator", ">", ">=", "<", "<=", ":") + return + } + fields, _ := panel.SignalColumns(s.source) + for _, f := range fields { + if f.Name == field.Key && f.Type == panel.TypeTime { + s.words("operator", "=", "!=", ">", ">=", "<", "<=") + return + } + } + } + s.words("operator", ":", ">", ">=", "<", "<=", "!=", "~", "in", "not in", "between", "is null", "like") +} + +func (s *completionCandidates) values(e Expect) { + if e.Field == nil { + return + } + f := e.Field + seen := map[string]bool{} + vocabulary := true + addValue := func(label, stored, insert string, count int64) { + if seen[stored] { + return + } + seen[stored] = true + boost := 0 + if vocabulary { + boost = 1 + } + s.add(label, insert, "value", "", count, boost) + } + value := func(label, stored string, count int64) { addValue(label, stored, label, count) } + sampledValue := func(label string, count int64) { + addValue(label, label, printValue(Value{Kind: StringValue, Text: label}, *f, false), count) + } + if f.Scope == "" { + if f.Key == "severity" { + for _, band := range telemetry.SeverityBands { + value(strings.ToLower(band), band, 0) + } + if isRange(e.Scope) || e.Scope == "between" { + return + } + } else { + var aliases map[string]string + switch f.Key { + case "status": + aliases = statusAliases + case "kind": + aliases = kindAliases + case "type": + aliases = typeAliases + } + for _, label := range sortedCompletionKeys(aliases) { + value(label, aliases[label], 0) + } + } + vocabulary = false + if f.Key == "duration" { + for _, v := range []string{"500ms", "1s", "5s"} { + value(v, v, 0) + } + } + for _, column := range s.signal.Columns { + if column.Name == f.Key { + for _, v := range column.Values { + sampledValue(v.Value, v.Count) + } + } + } + if f.Key == "name" { + for _, metric := range s.signal.Metrics { + sampledValue(metric.Name, metric.Count) + } + } + } + vocabulary = false + for _, attribute := range s.signal.Attributes { + scope := f.Scope + if scope == "" { + scope = "attributes" + } + if attribute.Key == f.Key && (attribute.Scope == scope || attribute.Scope == "" && scope == "attributes") && attribute.Type == "boolean" { + value("true", "true", 0) + value("false", "false", 0) + } + } + if e.Scope != "in" { + for _, v := range s.req.Variables { + s.add("$"+v.Name, "", "variable", "", 0, 0) + } + value("*", "*", 0) + } +} + +func sortedCompletionKeys(m map[string]string) []string { + keys := make([]string, 0, len(m)) + for key := range m { + keys = append(keys, key) + } + slices.Sort(keys) + return keys +} + +func (s *completionCandidates) measures() { + for _, spec := range panel.MeasureSpecs() { + if len(spec.Signals) > 0 && !slices.Contains(spec.Signals, s.source) { + continue + } + insert := spec.Name + "(" + if spec.Args == 0 { + insert += ")" + } + s.add(spec.Name, insert, "measure", "", 0, 0) + } + if s.source != "metrics" { + s.add("count_if", "count_if(", "measure", "", 0, 0) + } + if (s.req.Viz == "" || s.req.Viz == "heatmap" || s.req.Viz == "histogram") && (s.source == "spans" || s.source == "metrics") { + s.add("histogram", "histogram(", "measure", "", 0, 0) + } +} + +func (s *completionCandidates) sortKeys() { + if q := s.p.completionQuery; q != nil && q.Stage != nil { + // The resolver owns aliases, including repeated calls whose argument's + // resolved spelling forms part of the alias (duration -> duration_ms). + r := resolver{out: &Resolved{Query: q}} + for _, measure := range q.Stage.Measures { + r.measure(measure.Expr) + } + for _, measure := range q.Stage.Measures { + alias := measureAlias(measure, q.Stage.Measures) + if alias != "" { + s.words("field", alias, "+"+alias) + } + } + return + } + switch s.req.Viz { + case "traces": + s.words("field", "duration", "+start") + s.add("errors", "errors", "field", "filters to errors, orders by duration", 0, 0) + case "log_patterns": + s.words("field", "count") + default: + if s.source == "logs" { + s.words("field", "time", "+time") + } else if s.source == "spans" { + s.words("field", "duration", "+start") + s.add("errors", "errors", "field", "filters to errors, orders by duration", 0, 0) + } + } +} diff --git a/internal/fanql/complete_test.go b/internal/fanql/complete_test.go new file mode 100644 index 00000000..396577fa --- /dev/null +++ b/internal/fanql/complete_test.go @@ -0,0 +1,519 @@ +package fanql + +import ( + "context" + "errors" + "reflect" + "slices" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/labstack/fanout/internal/panel" +) + +type completionSchemaFunc func(context.Context, panel.SchemaRequest) (*panel.Schema, error) + +func (f completionSchemaFunc) Schema(ctx context.Context, req panel.SchemaRequest) (*panel.Schema, error) { + return f(ctx, req) +} + +func completionFixtureSchema() *panel.Schema { + return &panel.Schema{Signals: map[string]panel.SignalSchema{ + "logs": {Columns: []panel.ColumnSchema{ + {Field: panel.Field{Name: "severity"}, Values: []panel.Option{{Value: "ERROR"}, {Value: "INFO"}, {Value: "WARN"}}}, + {Field: panel.Field{Name: "service"}, Values: []panel.Option{{Value: "api"}, {Value: "checkout"}}}, + }}, + "spans": {Attributes: []panel.AttributeSchema{ + {Key: "http.target", Scope: "attributes", Type: "string", Count: 900}, + {Key: "http.method", Scope: "attributes", Type: "string", Count: 500}, + {Key: "user.score", Scope: "attributes", Type: "number", Count: 20}, + {Key: "k8s.pod.name", Scope: "resource", Type: "string", Count: 10}, + {Key: "enabled", Scope: "attributes", Type: "boolean", Count: 5}, + }}, + "metrics": {Metrics: []panel.MetricSchema{{Name: "http.server.duration", Count: 100}}}, + }} +} + +func completionRequest(marked string) CompleteRequest { + at := strings.Index(marked, "¦") + if at < 0 { + return CompleteRequest{Text: marked, Cursor: len([]rune(marked)), Window: "1h"} + } + return CompleteRequest{Text: strings.Replace(marked, "¦", "", 1), Cursor: len([]rune(marked[:at])), Window: "1h"} +} + +func completionLabels(r CompleteResponse) []string { + out := make([]string, len(r.Items)) + for i, item := range r.Items { + out[i] = item.Label + } + return out +} + +func waitCompletion(t *testing.T, c *Completer, req CompleteRequest, ready func(CompleteResponse) bool) CompleteResponse { + t.Helper() + deadline := time.Now().Add(3 * time.Second) + for time.Now().Before(deadline) { + r := c.Complete(context.Background(), req) + if ready(r) { + return r + } + time.Sleep(time.Millisecond) + } + t.Fatal("background schema fetch did not finish") + return CompleteResponse{} +} + +func warmCompleter(t *testing.T) *Completer { + t.Helper() + c := NewCompleter(completionSchemaFunc(func(context.Context, panel.SchemaRequest) (*panel.Schema, error) { + return completionFixtureSchema(), nil + })) + waitCompletion(t, c, completionRequest("spans "), func(r CompleteResponse) bool { return r.Schema.Warm }) + return c +} + +func TestExpectAtRecordsClasses(t *testing.T) { + tests := []struct { + text string + classes []string + field, function string + arg int + }{ + {"", []string{"source"}, "", "", 0}, + {"spans ", []string{"clause", "field", "free_text"}, "", "", 0}, + {"spans where service", []string{"field", "free_text"}, "", "", 0}, + {"spans where service:", []string{"value"}, "service", "", 0}, + {"spans | ", []string{"measure"}, "", "", 0}, + {"spans | quantile(duration, ", []string{"marg"}, "", "quantile", 1}, + {"spans | count() every ", []string{"bucket"}, "", "", 0}, + {"spans | count() by service sort ", []string{"sort_key"}, "", "", 0}, + {"spans | count() limit ", []string{"integer"}, "", "", 0}, + {"spans where attributes['ht", []string{"bracket_key"}, "", "", 0}, + } + for _, tt := range tests { + t.Run(tt.text, func(t *testing.T) { + token, got := expectAt(tt.text, len([]rune(tt.text))) + var classes []string + for _, e := range got { + classes = append(classes, e.Class) + } + for _, class := range tt.classes { + if !slices.Contains(classes, class) { + t.Fatalf("classes %v, want %s", classes, class) + } + } + if tt.field != "" && (got[0].Field == nil || got[0].Field.Key != tt.field) { + t.Fatalf("field = %+v", got) + } + if tt.function != "" && (got[0].Func != tt.function || got[0].Arg != tt.arg) { + t.Fatalf("argument = %+v", got) + } + if strings.HasSuffix(tt.text, "service") && token.Span != (Span{12, 19}) { + t.Fatalf("replace token = %+v", token) + } + if strings.Contains(tt.text, "['ht") && (token.Kind != BracketKey || got[0].Scope != "attributes") { + t.Fatalf("bracket = %+v %+v", token, got) + } + }) + } +} + +func TestCompleteFixtures(t *testing.T) { + c := warmCompleter(t) + tests := []struct { + text, viz string + exact, includes, excludes []string + first, insert, detail string + replace *panel.TextSpan + }{ + {text: "logs where sev¦erity:error", first: "severity", replace: &panel.TextSpan{Start: 11, End: 19}}, + {text: "logs where severity:¦", includes: []string{"trace", "debug", "info", "warn", "error", "fatal", "*"}, excludes: []string{"ERROR", "INFO", "WARN"}}, + {text: "logs where severity>=¦", exact: []string{"trace", "debug", "info", "warn", "error", "fatal"}}, + {text: "spans where http.¦", exact: []string{"http.target", "http.method"}, insert: "http.target"}, + {text: "spans where attributes['htt¦", first: "http.target", insert: "http.target']", replace: &panel.TextSpan{Start: 24, End: 27}}, + {text: "spans where resource[\"k8s.¦", first: "k8s.pod.name", insert: "k8s.pod.name\"]"}, + {text: "logs where service in (api, ¦", exact: []string{"checkout", "api"}}, + {text: "logs where ser¦", includes: []string{"service"}, detail: "free text searches body"}, + {text: "spans | p9¦", exact: []string{"p90", "p95", "p99"}}, + {text: "metrics | ¦", includes: []string{"last"}, excludes: []string{"error_rate"}}, + {text: "spans | ¦", includes: []string{"histogram", "count_if"}, excludes: []string{"last"}}, + {text: "spans | quantile(duration, ¦", exact: []string{"0.5", "0.9", "0.95", "0.99"}}, + {text: "spans | count() by service, ¦", viz: "table", includes: []string{"operation", "http.target", "user.score"}, excludes: []string{"duration", "start_time"}}, + {text: "spans | count() by service, ¦", viz: "timeseries", detail: "timeseries groups by at most 1 field"}, + {text: "spans | count() every ¦", viz: "bar", detail: "bar panels have no bucket"}, + {text: "spans | count() every ¦", exact: []string{"auto", "10s", "30s", "1m", "5m", "10m", "15m", "30m", "1h", "3h", "6h", "12h", "1d"}}, + {text: "spans sort ¦", viz: "traces", exact: []string{"duration", "+start", "errors"}, detail: "filters to errors, orders by duration"}, + {text: "spans | count() by service sort ¦", exact: []string{"count", "+count"}}, + {text: "spans where service:$ser¦", exact: []string{"$service"}}, + {text: "logs where \"unclosed ¦", exact: []string{}}, + {text: "spans | share() ¦", excludes: []string{"+", "-", "*", "/"}}, + {text: "spans | count() ¦", includes: []string{"+", "-", "*", "/", ",", "as", "by", "every", "sort", "limit"}}, + {text: "spans where duration ¦", exact: []string{">", ">=", "<", "<=", "between", ":"}}, + {text: "spans where start_time ¦", exact: []string{"=", "!=", ">", ">=", "<", "<="}}, + {text: "logs where severity ¦", exact: []string{">", ">=", "<", "<=", ":"}}, + {text: "spans where service:api ¦", includes: []string{"service", "http.target", "-", "(", "not", "$service"}}, + {text: "spans | sum(¦", first: "duration", includes: []string{"user.score", "http.target"}}, + {text: "spans | count_distinct(¦", includes: []string{"service", "duration", "http.target"}}, + {text: "metrics where name:¦", includes: []string{"http.server.duration", "*"}}, + {text: "spans where enabled:¦", includes: []string{"true", "false", "*"}}, + {text: "spans where duration:¦", includes: []string{"500ms", "1s", "5s", "*"}}, + {text: "spans | count() limit ¦", exact: []string{"10", "50", "100", "1000"}}, + {text: "logs limit ¦", viz: "log_patterns", exact: []string{"10", "50"}}, + {text: "logs where `coalesce(body,'|') ¦", exact: []string{}}, + } + for _, tt := range tests { + t.Run(tt.text+tt.viz, func(t *testing.T) { + req := completionRequest(tt.text) + req.Viz = tt.viz + req.Variables = []panel.Variable{{Name: "service"}} + r := c.Complete(context.Background(), req) + labels := completionLabels(r) + if len(r.Items) > 50 || r.Schema.Window != "1h" || !r.Schema.Warm { + t.Fatalf("response bounds/status: %+v", r) + } + if tt.exact != nil && !reflect.DeepEqual(labels, tt.exact) { + t.Errorf("labels %v, want %v", labels, tt.exact) + } + for _, s := range tt.includes { + if !slices.Contains(labels, s) { + t.Errorf("%v missing %q", labels, s) + } + } + for _, s := range tt.excludes { + if slices.Contains(labels, s) { + t.Errorf("%v includes %q", labels, s) + } + } + if tt.first != "" && (len(labels) == 0 || labels[0] != tt.first) { + t.Errorf("first = %v, want %s", labels, tt.first) + } + if tt.insert != "" && (len(r.Items) == 0 || r.Items[0].Insert != tt.insert) { + t.Errorf("insert = %+v, want %q", r.Items, tt.insert) + } + if tt.detail != "" && !slices.ContainsFunc(r.Items, func(i Item) bool { return i.Detail == tt.detail }) { + t.Errorf("missing detail %q: %+v", tt.detail, r.Items) + } + if tt.replace != nil && r.Replace != *tt.replace { + t.Errorf("replace = %+v, want %+v", r.Replace, tt.replace) + } + if strings.Contains(tt.text, "sev¦erity") && (len(r.Items) == 0 || r.Items[0].Kind != "field") { + t.Error("severity must be a field") + } + if strings.Contains(tt.text, "http.¦") && slices.ContainsFunc(r.Items, func(i Item) bool { return i.Kind != "attribute" }) { + t.Error("expected attribute kinds") + } + if tt.text == "logs where ser¦" && r.Items[len(r.Items)-1].Detail != "free text searches body" { + t.Error("free text hint must be last") + } + }) + } + for _, marked := range []string{"spans | count(¦", "spans | rate(¦"} { + r := c.Complete(context.Background(), completionRequest(marked)) + if len(r.Items) != 0 { + t.Errorf("zero argument function: %+v", r.Items) + } + } + r := c.Complete(context.Background(), completionRequest("spans where attributes['😀¦")) + if r.Replace != (panel.TextSpan{Start: 24, End: 25}) { + t.Errorf("code point replace %+v", r.Replace) + } + page := completionRequest("ser¦") + page.Source = "logs" + if !slices.Contains(completionLabels(c.Complete(context.Background(), page)), "service") { + t.Error("page-supplied source completion") + } +} + +func TestCompleteRecentFlag(t *testing.T) { + for _, tt := range []struct { + window, want string + recent bool + }{{"7d", "24h", true}, {"", "24h", true}, {"1d", "24h", false}, {"1h", "1h", false}, {"30m", "1h", false}} { + t.Run(tt.window, func(t *testing.T) { + requests := make(chan panel.SchemaRequest, 1) + c := NewCompleter(completionSchemaFunc(func(_ context.Context, r panel.SchemaRequest) (*panel.Schema, error) { + requests <- r + return completionFixtureSchema(), nil + })) + r := c.Complete(context.Background(), CompleteRequest{Window: tt.window, Namespace: "prod"}) + if r.Schema.Window != tt.want || r.Schema.Recent != tt.recent { + t.Errorf("status %+v", r.Schema) + } + select { + case req := <-requests: + if req.Window != tt.want || req.Namespace != "prod" { + t.Errorf("schema request %+v", req) + } + case <-time.After(time.Second): + t.Fatal("no schema fetch") + } + }) + } +} + +func TestCompleteColdCacheCoalesces(t *testing.T) { + gate := make(chan struct{}) + var calls, active, maximum atomic.Int32 + c := NewCompleter(completionSchemaFunc(func(ctx context.Context, _ panel.SchemaRequest) (*panel.Schema, error) { + calls.Add(1) + n := active.Add(1) + defer active.Add(-1) + for old := maximum.Load(); n > old && !maximum.CompareAndSwap(old, n); old = maximum.Load() { + } + deadline, ok := ctx.Deadline() + if !ok || time.Until(deadline) > 20*time.Second { + t.Error("missing 20s detached deadline") + } + <-gate + if ctx.Err() != nil { + t.Errorf("fetch inherited request cancellation: %v", ctx.Err()) + } + return completionFixtureSchema(), nil + })) + ctx, cancel := context.WithCancel(context.Background()) + var wg sync.WaitGroup + for i := 0; i < 50; i++ { + wg.Go(func() { + r := c.Complete(ctx, CompleteRequest{Window: "1h", Namespace: string(rune('a' + i%6))}) + if r.Schema.Warm { + t.Error("cold cache returned warm") + } + }) + } + done := make(chan struct{}) + go func() { wg.Wait(); close(done) }() + select { + case <-done: + case <-time.After(time.Second): + close(gate) + t.Fatal("cold completion blocked") + } + cancel() + close(gate) + for i := 0; i < 6; i++ { + waitCompletion(t, c, CompleteRequest{Window: "1h", Namespace: string(rune('a' + i))}, func(r CompleteResponse) bool { return r.Schema.Warm }) + } + if calls.Load() != 6 || maximum.Load() > 4 { + t.Fatalf("calls %d, max active %d", calls.Load(), maximum.Load()) + } + var failed atomic.Int32 + bad := NewCompleter(completionSchemaFunc(func(context.Context, panel.SchemaRequest) (*panel.Schema, error) { + failed.Add(1) + return nil, errors.New("unavailable") + })) + now := time.Date(2026, 10, 29, 0, 0, 0, 0, time.UTC) + bad.now = func() time.Time { return now } + waitCompletion(t, bad, CompleteRequest{Window: "1h"}, func(r CompleteResponse) bool { return r.Schema.Error }) + r := bad.Complete(context.Background(), CompleteRequest{Window: "1h"}) + if r.Schema.Warm || !r.Schema.Error || failed.Load() != 1 { + t.Fatalf("negative cache %+v calls %d", r.Schema, failed.Load()) + } + now = now.Add(10 * time.Second) + waitCompletion(t, bad, CompleteRequest{Window: "1h"}, func(r CompleteResponse) bool { return r.Schema.Error }) + if failed.Load() != 2 { + t.Fatalf("negative expiry calls %d", failed.Load()) + } +} + +func TestCompleteItemsRankByPrefixThenSubstringThenCount(t *testing.T) { + c := warmCompleter(t) + for _, tt := range []struct { + text string + want []string + }{{"spans where htt¦", []string{"http.target", "http.method"}}, {"spans where tar¦", []string{"start_time", "http.target"}}} { + labels := completionLabels(c.Complete(context.Background(), completionRequest(tt.text))) + var attrs []string + for _, s := range labels { + if slices.Contains(tt.want, s) { + attrs = append(attrs, s) + } + } + if !reflect.DeepEqual(attrs, tt.want) { + t.Errorf("%s = %v, want %v", tt.text, attrs, tt.want) + } + } +} + +func TestCompleteVocabularyPrecedesSampledValues(t *testing.T) { + schema := completionFixtureSchema() + logs := schema.Signals["logs"] + logs.Columns[0].Values = append(logs.Columns[0].Values, panel.Option{Value: "CUSTOM", Count: 999}) + schema.Signals["logs"] = logs + c := NewCompleter(completionSchemaFunc(func(context.Context, panel.SchemaRequest) (*panel.Schema, error) { return schema, nil })) + r := waitCompletion(t, c, completionRequest("logs where severity:¦"), func(r CompleteResponse) bool { return r.Schema.Warm }) + if got := completionLabels(r); len(got) < 7 || !slices.Equal(got[:7], []string{"trace", "debug", "info", "warn", "error", "fatal", "CUSTOM"}) { + t.Fatalf("vocabulary before samples: %v", got) + } +} + +func TestCompleteSortAliasesLower(t *testing.T) { + c := warmCompleter(t) + req := completionRequest("spans | avg(duration), avg(user.score) sort ¦") + r := c.Complete(context.Background(), req) + if got := completionLabels(r); !slices.Equal(got, []string{"avg_duration_ms", "+avg_duration_ms", "avg_user_score", "+avg_user_score"}) { + t.Fatalf("sort aliases %v", got) + } + for _, item := range r.Items { + q, problems := Parse(req.Text+item.Insert, "") + if len(problems) > 0 { + t.Fatal(problems) + } + resolved, problems := Resolve(q, ResolveOptions{Viz: "table"}) + if len(problems) > 0 { + t.Fatal(problems) + } + if _, problems := lower(resolved); len(problems) > 0 { + t.Fatal(problems) + } + } +} + +func TestCompleteServiceMetadataBoostsWithoutHiding(t *testing.T) { + schema := completionFixtureSchema() + spans := schema.Signals["spans"] + spans.Attributes[1].Services = "checkout, api" + schema.Signals["spans"] = spans + c := NewCompleter(completionSchemaFunc(func(context.Context, panel.SchemaRequest) (*panel.Schema, error) { return schema, nil })) + r := waitCompletion(t, c, completionRequest("spans where service:checkout http.¦"), func(r CompleteResponse) bool { return r.Schema.Warm }) + if !slices.Equal(completionLabels(r), []string{"http.method", "http.target"}) { + t.Fatalf("service boost: %v", completionLabels(r)) + } + plain := c.Complete(context.Background(), completionRequest("spans where http.¦")) + if !slices.Equal(completionLabels(plain), []string{"http.target", "http.method"}) { + t.Fatalf("unscoped counts: %v", completionLabels(plain)) + } +} + +func TestCompleteSchemaConcurrencyIsProcessWide(t *testing.T) { + gate := make(chan struct{}) + started := make(chan struct{}, 12) + var active, maximum, calls atomic.Int32 + source := completionSchemaFunc(func(context.Context, panel.SchemaRequest) (*panel.Schema, error) { + calls.Add(1) + n := active.Add(1) + defer active.Add(-1) + for old := maximum.Load(); n > old && !maximum.CompareAndSwap(old, n); old = maximum.Load() { + } + started <- struct{}{} + <-gate + return completionFixtureSchema(), nil + }) + a, b := NewCompleter(source), NewCompleter(source) + for i := 0; i < 6; i++ { + a.Complete(context.Background(), CompleteRequest{Window: "1h", Namespace: string(rune('a' + i))}) + b.Complete(context.Background(), CompleteRequest{Window: "1h", Namespace: string(rune('a' + i))}) + } + for i := 0; i < 4; i++ { + select { + case <-started: + case <-time.After(time.Second): + close(gate) + t.Fatal("schema workers did not start") + } + } + select { + case <-started: + close(gate) + t.Fatal("more than four schema workers started across completers") + case <-time.After(20 * time.Millisecond): + } + close(gate) + for _, c := range []*Completer{a, b} { + for i := 0; i < 6; i++ { + waitCompletion(t, c, CompleteRequest{Window: "1h", Namespace: string(rune('a' + i))}, func(r CompleteResponse) bool { return r.Schema.Warm }) + } + } + if calls.Load() != 12 || maximum.Load() > 4 { + t.Fatalf("process-wide calls %d max %d", calls.Load(), maximum.Load()) + } +} + +func TestCompleteRecoversInvalidFiltersBeforeStage(t *testing.T) { + c := NewCompleter(nil) + r := c.Complete(context.Background(), completionRequest("logs where service:api and severity:error or body:timeout | count() by ¦")) + if !slices.Contains(completionLabels(r), "service") { + t.Fatalf("completion after invalid filter: %v", completionLabels(r)) + } +} + +func TestCompleteInsertedValuesPreserveLiteralMeaning(t *testing.T) { + schema := completionFixtureSchema() + logs := schema.Signals["logs"] + logs.Columns[1].Values = []panel.Option{{Value: "checkout api"}, {Value: "checkout:api"}, {Value: "count | limit 1"}, {Value: `say "hello"`}, {Value: "$service"}, {Value: "*"}, {Value: "500ms"}, {Value: "true"}, {Value: "api"}} + schema.Signals["logs"] = logs + c := NewCompleter(completionSchemaFunc(func(context.Context, panel.SchemaRequest) (*panel.Schema, error) { return schema, nil })) + req := completionRequest("logs where service:¦") + r := waitCompletion(t, c, req, func(r CompleteResponse) bool { return r.Schema.Warm }) + for _, tt := range []struct{ label, sql string }{{"checkout api", `service = 'checkout api'`}, {"checkout:api", `service = 'checkout:api'`}, {"count | limit 1", `service = 'count | limit 1'`}, {`say "hello"`, `service = 'say "hello"'`}, {"$service", `service = '$service'`}, {"*", `service = '*'`}, {"500ms", `service = '500ms'`}, {"true", `service = 'true'`}, {"api", `service = 'api'`}} { + t.Run(tt.label, func(t *testing.T) { + at := slices.IndexFunc(r.Items, func(item Item) bool { return item.Label == tt.label }) + if at < 0 { + t.Fatalf("missing readable value %q", tt.label) + } + text := applyCompletion(req.Text, r.Replace, r.Items[at].Insert) + if tt.label == "api" && r.Items[at].Insert != "api" { + t.Errorf("safe value insert %q", r.Items[at].Insert) + } + compiled, problems := Compile(text, Options{}) + if len(problems) > 0 { + t.Fatalf("inserted %q: %v", text, problems) + } + if !slices.Equal(compiled.Query.Where, []string{tt.sql}) { + t.Fatalf("inserted %q lowers to %v, want %s", text, compiled.Query.Where, tt.sql) + } + }) + } +} + +func TestCompleteInsertedAttributeFieldsPreserveScope(t *testing.T) { + schema := completionFixtureSchema() + spans := schema.Signals["spans"] + spans.Attributes = []panel.AttributeSchema{{Key: "resource.foo", Scope: "attributes"}, {Key: "attributes.foo", Scope: "attributes"}, {Key: "service-name", Scope: "resource"}, {Key: "owner's.name", Scope: "attributes"}, {Key: `owner"s.name`, Scope: "resource"}, {Key: "where", Scope: "resource"}, {Key: "service", Scope: "resource"}} + schema.Signals["spans"] = spans + c := NewCompleter(completionSchemaFunc(func(context.Context, panel.SchemaRequest) (*panel.Schema, error) { return schema, nil })) + for _, tt := range []struct{ text, key, scope, label string }{ + {"spans where res¦", "resource.foo", "attributes", "attributes['resource.foo']"}, + {"spans where attr¦", "attributes.foo", "attributes", "attributes['attributes.foo']"}, + {"spans where service-¦", "service-name", "resource", "resource['service-name']"}, + {"spans where resource.wh¦", "where", "resource", "resource.where"}, + {"spans where resource.serv¦", "service", "resource", "resource.service"}, + {"spans where attributes['own¦", "owner's.name", "attributes", "owner's.name"}, + {"spans where attributes['own¦']:api", "owner's.name", "attributes", "owner's.name"}, + {"spans where attributes['owner''¦", "owner's.name", "attributes", "owner's.name"}, + {`spans where resource["own¦`, `owner"s.name`, "resource", `owner"s.name`}, + {`spans where resource["own¦"]:api`, `owner"s.name`, "resource", `owner"s.name`}, + {`spans where resource["owner""¦`, `owner"s.name`, "resource", `owner"s.name`}, + } { + t.Run(tt.text, func(t *testing.T) { + req := completionRequest(tt.text) + r := waitCompletion(t, c, req, func(r CompleteResponse) bool { return r.Schema.Warm }) + at := slices.IndexFunc(r.Items, func(item Item) bool { + return item.Kind == "attribute" && item.Label == tt.label + }) + if at < 0 { + t.Fatalf("no completion for %q: %+v", tt.key, r.Items) + } + text := applyCompletion(req.Text, r.Replace, r.Items[at].Insert) + if !strings.HasSuffix(text, ":api") { + text += ":api" + } + compiled, problems := Compile(text, Options{}) + if len(problems) > 0 { + t.Fatalf("inserted %q: %v", text, problems) + } + want := tt.scope + "['" + strings.ReplaceAll(tt.key, "'", "''") + "'] = 'api'" + if !slices.Equal(compiled.Query.Where, []string{want}) { + t.Fatalf("inserted %q lowers to %v, want %s", text, compiled.Query.Where, want) + } + }) + } +} + +func applyCompletion(text string, replace panel.TextSpan, insert string) string { + runes := []rune(text) + return string(runes[:replace.Start]) + insert + string(runes[replace.End:]) +} diff --git a/internal/fanql/parser.go b/internal/fanql/parser.go index 65460768..30fe1258 100644 --- a/internal/fanql/parser.go +++ b/internal/fanql/parser.go @@ -24,13 +24,37 @@ var numberPattern = regexp.MustCompile(`^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[e var durationPattern = regexp.MustCompile(`(?i)^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?(?:us|ms|s|m|h)$`) type parser struct { - tokens Tokens - runes []rune - i int - problems panel.Problems - bounded bool - nodes, depth int - heights map[any]int + tokens Tokens + runes []rune + i int + problems panel.Problems + bounded bool + nodes, depth int + heights map[any]int + completion bool + expected []Expect + completionQuery *Query + completionUsed map[string]bool +} + +// Completion uses the same productions and alternatives as Parse. Unwinding at +// the first unfinished production preserves its context without error recovery +// inventing a different position for the cursor. +type completionEnd struct{} + +func (p *parser) expectNext(alternatives ...Expect) { + if p.completion && p.peek().Kind == EOF { + p.expected = append(p.expected, alternatives...) + panic(completionEnd{}) + } +} + +func (p *parser) expectTerm(nested bool) { + alternatives := []Expect{{Class: "field"}, {Class: "free_text"}, {Class: "operator", Scope: "term"}, {Class: "variable"}} + if !nested { + alternatives = append([]Expect{{Class: "clause"}}, alternatives...) + } + p.expectNext(alternatives...) } // A private sentinel unwinds only a bound failure, before further recursion or @@ -108,6 +132,9 @@ func (p *parser) previousEnd() int { } func (p *parser) text(at Span) string { return string(p.runes[at.Start:at.End]) } func (p *parser) issue(at Span, message, hint string) { + if p.completion { + return + } p.problems = append(p.problems, panel.Problem{Path: "text", Message: message, Hint: hint, Span: &panel.TextSpan{Start: at.Start, End: at.End}}) } func (p *parser) report(at Span, code string, args ...any) { @@ -153,6 +180,7 @@ func (p *parser) finish() panel.Problems { func (p *parser) query(source string) *Query { q := &Query{Span: Span{0, len(p.runes)}} + p.completionQuery = q if source != "" { q.Source = strings.ToLower(source) if !sources[q.Source] { @@ -168,6 +196,7 @@ func (p *parser) query(source string) *Query { } return q } + p.expectNext(Expect{Class: "source"}) first := p.take() q.Source = strings.ToLower(first.Text) q.SourceSpan = first.Span @@ -266,6 +295,7 @@ func (p *parser) filters(nested bool) []Expr { var ops []string mode := "" mixed := -1 + p.expectTerm(nested) for !p.filterStop(nested) { before := p.i if len(terms) > 0 { @@ -274,6 +304,7 @@ func (p *parser) filters(nested bool) []Expr { tok := p.take() op = strings.ToLower(tok.Text) if p.filterStop(nested) { + p.expectTerm(nested) p.report(tok.Span, "sides", op) break } @@ -298,7 +329,11 @@ func (p *parser) filters(nested bool) []Expr { p.unexpected() } } - if mixed >= 0 && len(terms) >= 3 && len(ops) == len(terms)-1 { + if p.completion && !nested { + p.completionQuery.Where = terms + } + p.expectTerm(nested) + if !p.completion && mixed >= 0 && len(terms) >= 3 && len(ops) == len(terms)-1 { at := Span{terms[0].Span().Start, terms[len(terms)-1].Span().End} first := p.groupingEdit(terms, ops, ops[mixed]) second := p.groupingEdit(terms, ops, ops[0]) @@ -403,6 +438,7 @@ func isFieldWordOperator(op string) bool { } func (p *parser) term(nested bool) Expr { + p.expectTerm(nested) if p.is("-") || p.is("not") { t := p.take() p.enter(t.Span) @@ -481,6 +517,7 @@ func (p *parser) primary(nested bool) Expr { return nil } op := p.lower() + p.expectNext(Expect{Class: "operator", Field: &field}) if isComparison(op) || op == ":" || op == "~" || op == "!~" { if numberPattern.MatchString(field.Key) || durationPattern.MatchString(field.Key) { p.report(field.At, "fieldBefore", op) @@ -504,6 +541,7 @@ func (p *parser) primary(nested bool) Expr { if op == ":" && isComparison(p.lower()) { op = p.take().Text } + p.expectNext(Expect{Class: "value", Field: &field, Scope: op}) v, valid := p.value() if !valid { example := "api" @@ -547,11 +585,13 @@ func (p *parser) primary(nested bool) Expr { return p.in(field, neg) case "between": p.take() + p.expectNext(Expect{Class: "value", Field: &field, Scope: "between"}) lo, ok := p.value() if !ok || !p.eat("and") { p.report(Span{field.At.Start, p.previousEnd()}, "between") return nil } + p.expectNext(Expect{Class: "value", Field: &field, Scope: "between"}) hi, ok := p.value() if !ok { p.report(Span{field.At.Start, p.previousEnd()}, "between") @@ -572,6 +612,7 @@ func (p *parser) primary(nested bool) Expr { return x case "like", "ilike": p.take() + p.expectNext(Expect{Class: "value", Field: &field}) v, ok := p.value() if !ok || v.Kind != StringValue { p.report(Span{field.At.Start, p.previousEnd()}, "like") @@ -616,6 +657,7 @@ func (p *parser) field() (Field, bool) { f := Field{Key: t.Text, Single: !strings.Contains(t.Text, "."), At: t.Span} if p.is("[") && (strings.EqualFold(t.Text, "attributes") || strings.EqualFold(t.Text, "resource")) { p.take() + p.expectNext(Expect{Class: "bracket_key", Scope: strings.ToLower(t.Text)}) key := p.peek() if key.Kind != BracketKey && key.Kind != String { p.report(key.Span, "bracket") @@ -692,6 +734,7 @@ func (p *parser) value() (Value, bool) { func (p *parser) in(f Field, neg bool) Expr { p.take() + p.expectNext(Expect{Class: "value", Field: &f, Scope: "in"}) x := &In{Field: f, Negated: neg, At: Span{f.At.Start, p.previousEnd()}} if p.peek().Kind == Word && strings.HasPrefix(p.peek().Text, "$") { v, _ := p.value() @@ -704,6 +747,7 @@ func (p *parser) in(f Field, neg bool) Expr { p.report(p.peek().Span, "list") return nil } + p.expectNext(Expect{Class: "value", Field: &f, Scope: "in"}) for p.peek().Kind != EOF && !p.is(")") { v, ok := p.value() if !ok { @@ -715,12 +759,16 @@ func (p *parser) in(f Field, neg bool) Expr { p.bound(v.At, "listBound") } x.Values = append(x.Values, v) + if p.completion { + p.completionUsed[strings.ToLower(v.Text)] = true + } if v.Kind == StarValue { p.issue(v.At, diagnostic("wildcard"), wildcardHint(v.Text)) } if !p.eat(",") { break } + p.expectNext(Expect{Class: "value", Field: &f, Scope: "in"}) if p.is(")") { p.report(p.peek().Span, "listValue") } @@ -953,11 +1001,13 @@ func (p *parser) skipStage() { func (p *parser) parseSort() *Sort { start := p.take() + p.expectNext(Expect{Class: "sort_key"}) x := &Sort{At: start.Span} signed := p.is("+") || p.is("-") if signed { x.Ascending = p.take().Text == "+" } + p.expectNext(Expect{Class: "sort_key"}) t := p.peek() if t.Kind != Word && t.Kind != Ident { p.report(t.Span, "sortKey") @@ -976,6 +1026,7 @@ func (p *parser) parseSort() *Sort { func (p *parser) parseLimit() *Limit { start := p.take() + p.expectNext(Expect{Class: "integer"}) t := p.peek() x := &Limit{At: start.Span} n, err := strconv.Atoi(t.Text) @@ -994,6 +1045,10 @@ func (p *parser) parseLimit() *Limit { func (p *parser) stage(start int) *Stage { s := &Stage{At: Span{Start: start}} + if p.completion { + p.completionQuery.Stage = s + } + p.expectNext(Expect{Class: "measure"}) for p.peek().Kind != EOF && !p.is("|") && !clauses[p.lower()] { before := p.i if p.peek().Kind == Ident && foreignStages[p.lower()] { @@ -1058,6 +1113,7 @@ func (p *parser) stage(start int) *Stage { } } if p.eat(",") { + p.expectNext(Expect{Class: "measure"}) if p.peek().Kind == EOF || clauses[p.lower()] { p.report(p.peek().Span, "measure") } @@ -1070,6 +1126,7 @@ func (p *parser) stage(start int) *Stage { p.unexpected() } } + p.expectNext(Expect{Class: "clause", Scope: "measure"}) for p.is("by") || p.is("every") { if p.eat("by") { if len(s.By) > 0 { @@ -1082,6 +1139,7 @@ func (p *parser) stage(start int) *Stage { p.report(p.tokens[p.i-1].Span, "byFirst") } for { + p.expectNext(Expect{Class: "field", Func: "by", Arg: len(s.By)}) f, ok := p.field() if !ok { if p.peek().Kind != EOF && !clauses[p.lower()] { @@ -1102,6 +1160,7 @@ func (p *parser) stage(start int) *Stage { } } else { at := p.take().Span + p.expectNext(Expect{Class: "bucket"}) if len(s.Measures) == 0 && s.Histogram == nil { p.report(at, "everyFirst") } @@ -1118,6 +1177,7 @@ func (p *parser) stage(start int) *Stage { } } } + p.expectNext(Expect{Class: "clause", Scope: "stage"}) if len(s.Measures) == 0 && s.Histogram == nil && len(p.problems) == 0 { p.report(p.peek().Span, "measure") } @@ -1166,6 +1226,7 @@ func (p *parser) mexpr(minPrec int) MExpr { } func (p *parser) mfactor() MExpr { + p.expectNext(Expect{Class: "measure"}) t := p.peek() if p.eat("-") { p.enter(t.Span) @@ -1234,6 +1295,7 @@ func (p *parser) mcall() MExpr { return x } x := &MCall{Name: strings.ToLower(name.Text), At: at} + p.expectNext(Expect{Class: "marg", Func: x.Name, Arg: 0}) for p.peek().Kind != EOF && !p.is(")") && !p.is("|") { t := p.peek() arg := MArg{At: t.Span} @@ -1268,6 +1330,7 @@ func (p *parser) mcall() MExpr { if !p.eat(",") { break } + p.expectNext(Expect{Class: "marg", Func: x.Name, Arg: len(x.Args)}) } if !p.eat(")") { p.report(open.Span, "callClose") From 7369e54e02bcbc3ed3c2343ae88b1a6bedeb7a8c Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 16:30:19 -0700 Subject: [PATCH 10/30] feat(api): FanQL parse, format, complete and reference routes --- cmd/fanout/main.go | 1 + internal/api/auth_middleware.go | 4 +- internal/api/auth_test.go | 4 + internal/api/errors.go | 3 + internal/api/fanql.go | 202 ++++++++++ internal/api/fanql_test.go | 361 ++++++++++++++++++ internal/fanql/reference.go | 6 + scripts/go-deadcode.allowlist | 10 +- .../content/docs/reference/http-routes.mdx | 4 + 9 files changed, 585 insertions(+), 10 deletions(-) create mode 100644 internal/api/fanql.go create mode 100644 internal/api/fanql_test.go create mode 100644 internal/fanql/reference.go diff --git a/cmd/fanout/main.go b/cmd/fanout/main.go index e78ba34d..32c9b5a0 100644 --- a/cmd/fanout/main.go +++ b/cmd/fanout/main.go @@ -278,6 +278,7 @@ func main() { panels := panel.NewExecutor(q, cfg.RetentionDays) panels.SetRollupReader(queries) api.RegisterPanelRoutes(e, panels) + api.RegisterFanQLRoutes(e, q, panels) api.RegisterAnnotationRoutes(e, annotations.New(q)) api.RegisterTraceRoutes(e, queries, cfg.RetentionDays) api.RegisterIntelligenceRoutes(e, detector) diff --git a/internal/api/auth_middleware.go b/internal/api/auth_middleware.go index a91e3b65..f58e917f 100644 --- a/internal/api/auth_middleware.go +++ b/internal/api/auth_middleware.go @@ -310,7 +310,9 @@ func classifyRoute(method, path string) (routePolicy, bool) { return routePolicy{kind: routePolicyCapability, capability: ManageAlerts}, unsafe case path == "/api/panels/query" || path == "/api/panels/exemplars" || path == "/api/panels/variables/resolve" || path == "/api/annotations": return routePolicy{kind: routePolicyCapability, capability: ReadTelemetry}, method == http.MethodPost - case path == "/api/telemetry/schema": + case path == "/api/fanql/parse" || path == "/api/fanql/format" || path == "/api/fanql/complete": + return routePolicy{kind: routePolicyCapability, capability: ReadTelemetry}, method == http.MethodPost + case path == "/api/fanql/reference" || path == "/api/telemetry/schema": return routePolicy{kind: routePolicyCapability, capability: ReadTelemetry}, read case path == "/api/dashboards" || strings.HasPrefix(path, "/api/dashboards/"): return routePolicy{kind: routePolicyCapability, capability: ManageOwnDashboards}, read || unsafe diff --git a/internal/api/auth_test.go b/internal/api/auth_test.go index 00627d73..6cecd594 100644 --- a/internal/api/auth_test.go +++ b/internal/api/auth_test.go @@ -182,6 +182,10 @@ func TestRoutePolicyClassification(t *testing.T) { {http.MethodPost, "/api/dashboards/dashboard-1/versions/1/restore", routePolicyCapability, ManageOwnDashboards}, {http.MethodPost, "/api/agent/runs", routePolicyCapability, RunAgent}, {http.MethodPost, "/api/panels/variables/resolve", routePolicyCapability, ReadTelemetry}, + {http.MethodPost, "/api/fanql/parse", routePolicyCapability, ReadTelemetry}, + {http.MethodPost, "/api/fanql/format", routePolicyCapability, ReadTelemetry}, + {http.MethodPost, "/api/fanql/complete", routePolicyCapability, ReadTelemetry}, + {http.MethodGet, "/api/fanql/reference", routePolicyCapability, ReadTelemetry}, {http.MethodGet, "/api/settings/ingest", routePolicyCapability, ReadIngestMetadata}, {http.MethodPost, "/api/settings/ingest/token/rotate", routePolicyCapability, ManageIngest}, {http.MethodPost, "/api/users/user-1/access/revoke", routePolicyCapability, ManageUsers}, diff --git a/internal/api/errors.go b/internal/api/errors.go index fe8ff191..30417c0c 100644 --- a/internal/api/errors.go +++ b/internal/api/errors.go @@ -13,7 +13,9 @@ type apiError struct { status int Code string `json:"code"` Message string `json:"message"` + Hint string `json:"hint,omitempty"` Problems panel.Problems `json:"problems,omitempty"` + Preview *fanqlPreview `json:"preview,omitempty"` } func (e *apiError) Error() string { return e.Message } @@ -83,6 +85,7 @@ func HTTPErrorHandler(c *echo.Context, err error) { var httpError *echo.HTTPError if errors.As(err, &specific) { body.Code, body.Message, body.Problems = specific.Code, specific.Message, specific.Problems + body.Hint, body.Preview = specific.Hint, specific.Preview } else if errors.As(err, &httpError) && httpError.Message != "" { body.Message = httpError.Message } else if status < 500 { diff --git a/internal/api/fanql.go b/internal/api/fanql.go new file mode 100644 index 00000000..01095819 --- /dev/null +++ b/internal/api/fanql.go @@ -0,0 +1,202 @@ +package api + +import ( + "context" + "encoding/json" + "net/http" + "strconv" + + "github.com/labstack/echo/v5" + "github.com/labstack/fanout/internal/fanql" + "github.com/labstack/fanout/internal/panel" +) + +type FanQLHandler struct { + parser panel.Parser + engine PanelEngine + completer *fanql.Completer +} + +func RegisterFanQLRoutes(e *echo.Echo, parser panel.Parser, engine PanelEngine) { + h := &FanQLHandler{parser: parser, engine: engine, completer: fanql.NewCompleter(engine)} + read := RequireCapability(ReadTelemetry) + e.POST("/api/fanql/parse", h.parse, read) + e.POST("/api/fanql/format", h.format, read) + e.POST("/api/fanql/complete", h.complete, read) + e.GET("/api/fanql/reference", h.reference, read) +} + +type fanqlPreview struct { + Text string `json:"text"` + Note string `json:"note"` +} + +// RawMessage distinguishes an omitted version from every explicitly supplied +// value, including null and values of the wrong JSON type. +func checkFanQLVersion(version json.RawMessage) (bool, error) { + if len(version) == 0 { + return true, nil + } + var n int + if err := json.Unmarshal(version, &n); err == nil && n == fanql.Version { + return false, nil + } + failure := newAPIError(http.StatusBadRequest, "unsupported_fanql_version", "This server cannot read the requested FanQL version.") + failure.Hint = "this server reads FanQL " + strconv.Itoa(fanql.Version) + return false, failure +} + +func fanqlNotices(notices []fanql.Notice, missing bool) []fanql.Notice { + if notices == nil { + notices = []fanql.Notice{} + } + if missing { + notices = append(notices, fanql.Notice{Path: "version", Message: "version missing; assuming FanQL " + strconv.Itoa(fanql.Version)}) + } + return notices +} + +func (h *FanQLHandler) parse(c *echo.Context) error { + var req struct { + Version json.RawMessage `json:"version"` + Text string `json:"text"` + Source string `json:"source,omitempty"` + Viz string `json:"viz,omitempty"` + Variables []panel.Variable `json:"variables,omitempty"` + Preview bool `json:"preview,omitempty"` + } + if err := decodeStrict(c, &req, 512<<10); err != nil { + return err + } + missing, err := checkFanQLVersion(req.Version) + if err != nil { + return err + } + compiled, problems := fanql.Compile(req.Text, fanql.Options{Source: req.Source, Viz: req.Viz, Variables: req.Variables}) + if len(problems) != 0 { + failure := newAPIError(http.StatusBadRequest, "invalid_fanql", "The query has problems.") + failure.Problems = panel.PresentProblems(problems) + if req.Preview { + failure.Preview = &fanqlPreview{Text: req.Text, Note: "not executable"} + } + return failure + } + return c.JSON(http.StatusOK, struct { + Version int `json:"version"` + Query panel.Query `json:"query"` + Canonical string `json:"canonical"` + Viz struct { + Requested string `json:"requested,omitempty"` + Compatible []panel.VizCompat `json:"compatible"` + Edits []fanql.VizEdit `json:"edits"` + } `json:"viz"` + Notices []fanql.Notice `json:"notices"` + }{ + Version: fanql.Version, Query: compiled.Query, Canonical: compiled.Canonical, + Viz: struct { + Requested string `json:"requested,omitempty"` + Compatible []panel.VizCompat `json:"compatible"` + Edits []fanql.VizEdit `json:"edits"` + }{Requested: req.Viz, Compatible: compiled.Compatible, Edits: compiled.Edits}, + Notices: fanqlNotices(compiled.Notices, missing), + }) +} + +func (h *FanQLHandler) format(c *echo.Context) error { + var req struct { + Version json.RawMessage `json:"version"` + Query panel.Query `json:"query"` + Viz string `json:"viz,omitempty"` + Variables []panel.Variable `json:"variables,omitempty"` + Panel *panel.Panel `json:"panel,omitempty"` + } + if err := decodeStrict(c, &req, 512<<10); err != nil { + return err + } + missing, err := checkFanQLVersion(req.Version) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(c.Request().Context(), panelDeadline) + defer cancel() + formatted, problems, err := fanql.Format(ctx, h.parser, req.Query, fanql.FormatOptions{Viz: req.Viz, Variables: req.Variables}) + if err != nil { + return fanqlError(err) + } + if len(problems) != 0 { + failure := newAPIError(http.StatusBadRequest, "invalid_spec", "The query spec is invalid.") + failure.Problems = panel.PresentProblems(problems) + return failure + } + formatted.Notices = fanqlNotices(formatted.Notices, missing) + return c.JSON(http.StatusOK, struct { + Version int `json:"version"` + *fanql.Formatted + }{Version: fanql.Version, Formatted: formatted}) +} + +func fanqlError(err error) error { + return newAPIError(http.StatusServiceUnavailable, "unavailable", panel.PresentError(err, panel.ReadError)) +} + +func (h *FanQLHandler) complete(c *echo.Context) error { + var req struct { + Version json.RawMessage `json:"version"` + Text string `json:"text"` + Cursor int `json:"cursor"` + Source string `json:"source,omitempty"` + Viz string `json:"viz,omitempty"` + Window *string `json:"window,omitempty"` + Namespace string `json:"namespace,omitempty"` + Variables []panel.Variable `json:"variables,omitempty"` + } + if err := decodeStrict(c, &req, 512<<10); err != nil { + return err + } + missing, err := checkFanQLVersion(req.Version) + if err != nil { + return err + } + window := "1h" + if req.Window != nil { + window = *req.Window + } + ctx, cancel := context.WithTimeout(c.Request().Context(), panelDeadline) + defer cancel() + out := h.completer.Complete(ctx, fanql.CompleteRequest{ + Text: req.Text, Cursor: req.Cursor, Source: req.Source, Viz: req.Viz, + Window: window, Namespace: req.Namespace, Variables: req.Variables, + }) + var notices []fanql.Notice + if missing { + notices = fanqlNotices(nil, true) + } + return c.JSON(http.StatusOK, struct { + Version int `json:"version"` + fanql.CompleteResponse + Notices []fanql.Notice `json:"notices,omitempty"` + }{Version: fanql.Version, CompleteResponse: out, Notices: notices}) +} + +func (h *FanQLHandler) reference(c *echo.Context) error { + var version json.RawMessage + if values, ok := c.Request().URL.Query()["version"]; ok { + if len(values) != 1 { + version = json.RawMessage(`null`) + } else { + version, _ = json.Marshal(values[0]) + if values[0] == strconv.Itoa(fanql.Version) { + version = json.RawMessage(values[0]) + } + } + } + missing, err := checkFanQLVersion(version) + if err != nil { + return err + } + text := fanql.Reference() + if missing { + text += "\n\nversion missing; assuming FanQL " + strconv.Itoa(fanql.Version) + "\n" + } + return c.Blob(http.StatusOK, "text/markdown; charset=utf-8", []byte(text)) +} diff --git a/internal/api/fanql_test.go b/internal/api/fanql_test.go new file mode 100644 index 00000000..f72712d4 --- /dev/null +++ b/internal/api/fanql_test.go @@ -0,0 +1,361 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + + "github.com/labstack/fanout/internal/auth" + "github.com/labstack/fanout/internal/fanql" + "github.com/labstack/fanout/internal/panel" +) + +type fakeFanQLParser struct { + panel.Parser + err error +} + +func (p *fakeFanQLParser) ParseSQL(ctx context.Context, text string) (map[string]any, error) { + if _, ok := ctx.Deadline(); !ok { + panic("format parser requires a deadline") + } + if p.err != nil { + return nil, p.err + } + if strings.Contains(text, "service") { + return map[string]any{"where_clause": map[string]any{ + "class": "COMPARISON", "type": "COMPARE_EQUAL", + "left": map[string]any{"class": "COLUMN_REF", "column_names": []any{"service"}}, + "right": map[string]any{"class": "CONSTANT", "literal": map[string]any{"kind": "STRING", "value": "api"}}, + }}, nil + } + return map[string]any{}, nil +} + +func (*fakeFanQLParser) RenderSQL(context.Context, map[string]any) (string, error) { + return "SELECT 1 FROM spans WHERE service = 'api'", nil +} + +type fakeFanQLPanels struct{ fakePanels } + +func (*fakeFanQLPanels) Schema(_ context.Context, req panel.SchemaRequest) (*panel.Schema, error) { + return &panel.Schema{Window: req.Window, Signals: map[string]panel.SignalSchema{ + "logs": {Columns: []panel.ColumnSchema{{Field: panel.Field{Name: "severity", Type: panel.TypeString}, Values: []panel.Option{{Value: "ERROR"}, {Value: "INFO"}, {Value: "WARN"}}}}}, + }}, nil +} + +func serveFanQL(t *testing.T, parser panel.Parser, engine PanelEngine, method, path, body string) *httptest.ResponseRecorder { + t.Helper() + s := newTestAuthServer(t) + if _, err := s.users.CreateWithAudit("admin@example.com", "", "admin", auth.AuditEvent{EventType: "user.created", Outcome: "success"}); err != nil { + t.Fatal(err) + } + viewer, err := s.users.CreateWithAudit("viewer@example.com", "", "viewer", auth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatal(err) + } + RegisterFanQLRoutes(s.e, parser, engine) + req := sessionRequest(method, path, strings.NewReader(body), s.login(t, viewer)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + s.e.ServeHTTP(rec, req) + return rec +} + +func fanqlResponse(t *testing.T, rec *httptest.ResponseRecorder, status int, target any) { + t.Helper() + if rec.Code != status { + t.Fatalf("status %d, want %d: %s", rec.Code, status, rec.Body) + } + if err := json.Unmarshal(rec.Body.Bytes(), target); err != nil { + t.Fatal(err) + } +} + +func TestFanQLParseReturnsQueryCanonicalAndVizzes(t *testing.T) { + text := "spans where status:error | count() by service" + rec := serveFanQL(t, nil, &fakePanels{}, http.MethodPost, "/api/fanql/parse", `{"version":1,"text":"`+text+`"}`) + var body struct { + Version int `json:"version"` + Query panel.Query `json:"query"` + Canonical string `json:"canonical"` + Viz struct { + Compatible []panel.VizCompat `json:"compatible"` + Edits []fanql.VizEdit `json:"edits"` + } `json:"viz"` + Notices []fanql.Notice `json:"notices"` + } + fanqlResponse(t, rec, http.StatusOK, &body) + want := panel.Query{From: "spans", Where: []string{"status = 'STATUS_CODE_ERROR'"}, Measures: []string{"count()"}, By: []string{"service"}} + if body.Version != 1 || !reflect.DeepEqual(body.Query, want) || body.Canonical != text || body.Notices == nil || len(body.Notices) != 0 { + t.Fatalf("response: %s", rec.Body) + } + for _, viz := range []string{"bar", "table"} { + found := false + for _, compatible := range body.Viz.Compatible { + if compatible.Viz == viz && compatible.Requires != nil && len(compatible.Requires) == 0 { + found = true + } + } + if !found { + t.Errorf("missing compatible %s: %+v", viz, body.Viz) + } + } + found := false + for _, edit := range body.Viz.Edits { + if edit.Viz == "timeseries" && edit.Text == text+" every auto" { + found = true + } + } + if !found { + t.Fatalf("missing timeseries edit: %+v", body.Viz.Edits) + } +} + +func TestFanQLParseProblemsHaveNoQuery(t *testing.T) { + for _, preview := range []bool{false, true} { + rec := serveFanQL(t, nil, &fakePanels{}, http.MethodPost, "/api/fanql/parse", fmt.Sprintf(`{"text":"spans where a:1 b:2 or c:3 | p99(duration) by http_route every 1m","preview":%t}`, preview)) + var body struct { + Code string `json:"code"` + Message string `json:"message"` + Problems panel.Problems `json:"problems"` + Preview *struct { + Text string `json:"text"` + Note string `json:"note"` + } `json:"preview"` + } + fanqlResponse(t, rec, http.StatusBadRequest, &body) + if body.Code != "invalid_fanql" || body.Message != "The query has problems." || len(body.Problems) == 0 || body.Problems[0].Message != "mixed and/or needs parentheses" || body.Problems[0].Span == nil || len(body.Problems[0].FixIts) != 2 { + t.Fatalf("problem response: %s", rec.Body) + } + var keys map[string]json.RawMessage + if err := json.Unmarshal(rec.Body.Bytes(), &keys); err != nil { + t.Fatal(err) + } + if _, ok := keys["query"]; ok { + t.Fatal("invalid query must not be executable") + } + if preview { + if body.Preview == nil || body.Preview.Note != "not executable" || body.Preview.Text == "" { + t.Fatalf("preview: %s", rec.Body) + } + } else if _, ok := keys["preview"]; ok { + t.Fatal("unexpected preview") + } + } +} + +func TestFanQLParseSearchBarAndViz(t *testing.T) { + rec := serveFanQL(t, nil, &fakePanels{}, http.MethodPost, "/api/fanql/parse", `{"version":1,"text":"service:api timeout","source":"logs"}`) + var body struct { + Query panel.Query `json:"query"` + Viz struct { + Compatible []panel.VizCompat `json:"compatible"` + Requested string `json:"requested"` + } `json:"viz"` + Notices []fanql.Notice `json:"notices"` + } + fanqlResponse(t, rec, http.StatusOK, &body) + if len(body.Query.Where) != 2 || len(body.Viz.Compatible) != 1 || body.Viz.Compatible[0].Viz != "logs" || body.Viz.Compatible[0].Requires == nil { + t.Fatalf("search bar: %s", rec.Body) + } + rec = serveFanQL(t, nil, &fakePanels{}, http.MethodPost, "/api/fanql/parse", `{"text":"where service:api","source":"logs"}`) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "the page supplies where") { + t.Fatalf("where: %d %s", rec.Code, rec.Body) + } + rec = serveFanQL(t, nil, &fakePanels{}, http.MethodPost, "/api/fanql/parse", `{"version":1,"text":"spans | count() every 1m sort count","viz":"timeseries"}`) + fanqlResponse(t, rec, http.StatusOK, &body) + if body.Viz.Requested != "timeseries" || len(body.Notices) != 1 || !strings.Contains(body.Notices[0].Message, "sort does not apply to bucketed series") { + t.Fatalf("bucketed sort: %s", rec.Body) + } +} + +func TestFanQLVersionHandling(t *testing.T) { + for _, path := range []string{"parse", "format", "complete"} { + for _, version := range []string{"2", "0", "-1", `"1"`, "null"} { + rec := serveFanQL(t, nil, &fakePanels{}, http.MethodPost, "/api/fanql/"+path, `{"version":`+version+`}`) + var body struct { + Code string `json:"code"` + Hint string `json:"hint"` + } + fanqlResponse(t, rec, http.StatusBadRequest, &body) + if body.Code != "unsupported_fanql_version" || body.Hint != "this server reads FanQL 1" { + t.Fatalf("%s version %s: %s", path, version, rec.Body) + } + } + } + for _, path := range []string{"parse", "format"} { + input := `{"text":"spans"}` + if path == "format" { + input = `{"query":{"from":"spans"}}` + } + rec := serveFanQL(t, &fakeFanQLParser{}, &fakePanels{}, http.MethodPost, "/api/fanql/"+path, input) + var body struct { + Notices []fanql.Notice `json:"notices"` + } + fanqlResponse(t, rec, http.StatusOK, &body) + if len(body.Notices) != 1 || body.Notices[0].Message != "version missing; assuming FanQL 1" { + t.Fatalf("missing version: %s", rec.Body) + } + } + for _, version := range []string{"2", "bogus", ""} { + rec := serveFanQL(t, nil, &fakePanels{}, http.MethodGet, "/api/fanql/reference?version="+version, "") + var body struct { + Code string `json:"code"` + Hint string `json:"hint"` + } + fanqlResponse(t, rec, http.StatusBadRequest, &body) + if body.Code != "unsupported_fanql_version" || body.Hint != "this server reads FanQL 1" { + t.Fatalf("reference version: %s", rec.Body) + } + } +} + +func TestFanQLFormat(t *testing.T) { + rec := serveFanQL(t, &fakeFanQLParser{}, &fakePanels{}, http.MethodPost, "/api/fanql/format", `{"version":1,"query":{"from":"spans","where":["service='api'"],"measures":["p95( duration_ms )"]},"panel":{"id":"a","title":"A","viz":"stat"}}`) + var body struct { + Version int `json:"version"` + fanql.Formatted + } + fanqlResponse(t, rec, http.StatusOK, &body) + if body.Version != 1 || body.Text != "spans where service:api | p95(duration)" || body.Exactness != "normalized" || !body.Editable { + t.Fatalf("format: %s", rec.Body) + } + if len(body.Notices) == 0 || body.Notices[0].Message != `where[0] is shown as service:api; stored text is "service='api'"` { + t.Fatalf("notices: %s", rec.Body) + } + rec = serveFanQL(t, &fakeFanQLParser{}, &fakePanels{}, http.MethodPost, "/api/fanql/format", `{"query":{"from":"spans","measures":["count()"],"by":["a","b","c","d"]}}`) + var failure map[string]json.RawMessage + fanqlResponse(t, rec, http.StatusBadRequest, &failure) + if string(failure["code"]) != `"invalid_spec"` || failure["problems"] == nil { + t.Fatalf("shape: %s", rec.Body) + } + rec = serveFanQL(t, &fakeFanQLParser{err: context.DeadlineExceeded}, &fakePanels{}, http.MethodPost, "/api/fanql/format", `{"query":{"from":"logs","where":["coalesce(body, '') = ''"]}}`) + failure = nil + fanqlResponse(t, rec, http.StatusServiceUnavailable, &failure) + if string(failure["code"]) != `"unavailable"` || failure["problems"] != nil { + t.Fatalf("operational: %s", rec.Body) + } + q := panel.Query{From: "logs"} + for i := range 16 { + q.Where = append(q.Where, "body = '"+strings.Repeat("x", 480)+fmt.Sprint(i)+"'") + } + input, err := json.Marshal(map[string]any{"version": 1, "query": q}) + if err != nil { + t.Fatal(err) + } + rec = serveFanQL(t, &fakeFanQLParser{}, &fakePanels{}, http.MethodPost, "/api/fanql/format", string(input)) + fanqlResponse(t, rec, http.StatusOK, &body) + if body.Editable || !strings.HasPrefix(body.Reason, "formatted text is") { + t.Fatalf("oversized character format: %s", rec.Body) + } + for i := range 16 { + if !strings.Contains(body.Text, strings.Repeat("x", 480)+fmt.Sprint(i)) { + t.Fatal("format truncated a body literal") + } + } + q = panel.Query{From: "logs"} + for i := range 16 { + q.Where = append(q.Where, "coalesce(body, '"+strings.Repeat("𝔘", 110)+strings.Repeat("`", 30)+fmt.Sprint(i)+"') = ''") + } + input, err = json.Marshal(map[string]any{"version": 1, "query": q}) + if err != nil { + t.Fatal(err) + } + rec = serveFanQL(t, &fakeFanQLParser{}, &fakePanels{}, http.MethodPost, "/api/fanql/format", string(input)) + fanqlResponse(t, rec, http.StatusOK, &body) + if body.Editable || !strings.HasPrefix(body.Reason, "formatted text is") || len(body.Text) <= 8192 { + t.Fatalf("oversized format: %s", rec.Body) + } + for _, entry := range q.Where { + if !strings.Contains(body.Text, strings.ReplaceAll(entry, "`", "``")) { + t.Fatal("format truncated an entry") + } + } +} + +func TestFanQLComplete(t *testing.T) { + rec := serveFanQL(t, nil, &fakeFanQLPanels{}, http.MethodPost, "/api/fanql/complete", `{"version":1,"text":"logs where sev","cursor":14}`) + var body struct { + Version int `json:"version"` + Replace panel.TextSpan `json:"replace"` + Items []struct { + Label string `json:"label"` + } `json:"items"` + Schema struct { + Window string `json:"window"` + Warm bool `json:"warm"` + Recent bool `json:"recent"` + } `json:"schema"` + Notices []fanql.Notice `json:"notices"` + } + fanqlResponse(t, rec, http.StatusOK, &body) + if body.Version != 1 || body.Replace != (panel.TextSpan{Start: 11, End: 14}) || len(body.Items) == 0 || body.Items[0].Label != "severity" || body.Schema.Window != "1h" || body.Schema.Warm || body.Schema.Recent { + t.Fatalf("complete: %s", rec.Body) + } + rec = serveFanQL(t, nil, &fakeFanQLPanels{}, http.MethodPost, "/api/fanql/complete", `{"text":"logs where sev","cursor":14,"window":"","namespace":"prod"}`) + fanqlResponse(t, rec, http.StatusOK, &body) + if body.Schema.Window != "24h" || !body.Schema.Recent || len(body.Notices) != 1 || body.Notices[0].Message != "version missing; assuming FanQL 1" { + t.Fatalf("absolute completion: %s", rec.Body) + } +} + +func TestFanQLReference(t *testing.T) { + for _, path := range []string{"/api/fanql/reference", "/api/fanql/reference?version=1"} { + rec := serveFanQL(t, nil, &fakePanels{}, http.MethodGet, path, "") + if rec.Code != http.StatusOK || !strings.HasPrefix(rec.Header().Get("Content-Type"), "text/markdown") || !strings.Contains(rec.Body.String(), "FanQL 1") || !strings.Contains(rec.Body.String(), "Preview") { + t.Fatalf("reference: %d %s", rec.Code, rec.Body) + } + } +} + +func TestFanQLRoutesAreClassified(t *testing.T) { + for _, path := range []string{"parse", "format", "complete", "reference"} { + method, other := http.MethodPost, http.MethodGet + if path == "reference" { + method, other = other, method + } + policy, ok := classifyRoute(method, "/api/fanql/"+path) + if !ok || policy.kind != routePolicyCapability || policy.capability != ReadTelemetry { + t.Errorf("%s not telemetry:read", path) + } + if _, ok := classifyRoute(other, "/api/fanql/"+path); ok { + t.Errorf("%s %s classified", other, path) + } + } + s := newTestAuthServer(t) + RegisterFanQLRoutes(s.e, nil, &fakePanels{}) + rec := httptest.NewRecorder() + s.e.ServeHTTP(rec, sessionRequest(http.MethodPost, "/api/fanql/parse", strings.NewReader(`{"text":"spans"}`), nil)) + if rec.Code != http.StatusUnauthorized { + t.Fatalf("anonymous: %d %s", rec.Code, rec.Body) + } + rec = serveFanQL(t, nil, &fakePanels{}, http.MethodPost, "/api/fanql/parse", `{"text":"spans"}`) + if rec.Code != http.StatusOK { + t.Fatalf("viewer: %d %s", rec.Code, rec.Body) + } +} + +func TestFanQLBodyLimitsAndUnknownFields(t *testing.T) { + for _, path := range []string{"parse", "format", "complete"} { + valid := `{"text":"spans"}` + if path == "format" { + valid = `{"query":{"from":"spans"}}` + } + for _, input := range []string{`{"unknown":1}`, valid + strings.Repeat(" ", (512<<10)+1), `{} {}`} { + rec := serveFanQL(t, nil, &fakePanels{}, http.MethodPost, "/api/fanql/"+path, input) + if rec.Code != http.StatusBadRequest { + t.Errorf("%s bad body: %d %s", path, rec.Code, rec.Body) + } + } + } + rec := serveFanQL(t, nil, &fakePanels{}, http.MethodPost, "/api/fanql/parse", `{"text":"`+strings.Repeat("a", 4001)+`"}`) + if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), `"code":"invalid_fanql"`) || !strings.Contains(rec.Body.String(), "a query is at most 4000 characters (8192 bytes)") { + t.Fatalf("interactive bound: %d %s", rec.Code, rec.Body) + } +} diff --git a/internal/fanql/reference.go b/internal/fanql/reference.go new file mode 100644 index 00000000..19201c98 --- /dev/null +++ b/internal/fanql/reference.go @@ -0,0 +1,6 @@ +package fanql + +// Reference returns the current preview language reference. +func Reference() string { + return "# FanQL 1\n\nPreview: the syntax may change before GA\n" +} diff --git a/scripts/go-deadcode.allowlist b/scripts/go-deadcode.allowlist index c87824ff..39a69e4d 100644 --- a/scripts/go-deadcode.allowlist +++ b/scripts/go-deadcode.allowlist @@ -1,13 +1,5 @@ # Exact symbolreviewed reason for genuine non-main entry points only. github.com/labstack/fanout/internal/auth.OAuthTokenPair.String fmt.Stringer security boundary: formatting token pairs must redact both credentials; not a callable product action. -github.com/labstack/fanout/internal/panel.SignalColumns FanQL catalog library entry point; production HTTP/MCP/reference consumers land in batch 1 Tasks 8–10. +github.com/labstack/fanout/internal/fanql.expectAt Completion parser contract seam for token and expected-class fixtures; Complete shares its underlying context parser to avoid parsing twice. github.com/labstack/fanout/internal/panel.LowCardinalityColumns FanQL completion/reference library entry point; production consumers land in batch 1 Tasks 7–10. -github.com/labstack/fanout/internal/panel.MeasureSpecs FanQL resolver/reference library entry point; production consumers land in batch 1 Tasks 8–10. -github.com/labstack/fanout/internal/panel.BucketNames FanQL completion/reference library entry point; production consumers land in batch 1 Tasks 7–10. -github.com/labstack/fanout/internal/panel.FilterFunctionNames FanQL resolver/reference library entry point; production consumers land in batch 1 Tasks 8–10. -github.com/labstack/fanout/internal/panel.Suggest FanQL resolver library entry point; production HTTP/MCP consumers land in batch 1 Tasks 8–9. -github.com/labstack/fanout/internal/panel.QueryShape FanQL shape-check library entry point; production HTTP/MCP consumers land in batch 1 Tasks 8–9. -github.com/labstack/fanout/internal/panel.CompatibleVizzes FanQL visualization compatibility library entry point; production HTTP consumers land in batch 1 Task 8. github.com/labstack/fanout/internal/telemetry.SeverityAliases Shared FanQL vocabulary/reference library entry point; production consumers land in batch 1 Tasks 8–10. -github.com/labstack/fanout/internal/telemetry.SeverityRank FanQL severity range library entry point; production HTTP/MCP consumers land in batch 1 Tasks 8–9. -github.com/labstack/fanout/internal/panel.ParseMeasure FanQL stored-query formatting library entry point; production HTTP consumer lands in batch 1 Task 8. diff --git a/site/src/content/docs/reference/http-routes.mdx b/site/src/content/docs/reference/http-routes.mdx index bd8e717b..15331f9b 100644 --- a/site/src/content/docs/reference/http-routes.mdx +++ b/site/src/content/docs/reference/http-routes.mdx @@ -125,6 +125,10 @@ and path. [Roles](/reference/roles) maps capabilities to roles. | `GET` | `/api/dashboards/:id/versions` | `dashboards:manage-own` | | `GET` | `/api/dashboards/:id/versions/:version` | `dashboards:manage-own` | | `POST` | `/api/dashboards/:id/versions/:version/restore` | `dashboards:manage-own` | +| `POST` | `/api/fanql/complete` | `telemetry:read` | +| `POST` | `/api/fanql/format` | `telemetry:read` | +| `POST` | `/api/fanql/parse` | `telemetry:read` | +| `GET` | `/api/fanql/reference` | `telemetry:read` | | `GET` | `/api/intelligence` | `telemetry:read` | | `Any` | `/api/mcp` | `telemetry:read` | | `POST` | `/api/panels/exemplars` | `telemetry:read` | From 3ecbb6fffc50e4a9c1048e69df309fe70cb0075f Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 16:39:49 -0700 Subject: [PATCH 11/30] fix(fanql): address review findings for lexing through lift --- internal/fanql/lower.go | 15 ++- internal/fanql/print.go | 9 +- internal/fanql/resolve.go | 41 +++++++- internal/fanql/review_test.go | 170 ++++++++++++++++++++++++++++++++++ internal/fanql/spellings.go | 4 +- internal/panel/catalog.go | 4 +- internal/panel/filter.go | 2 +- internal/panel/shape_test.go | 19 ++++ 8 files changed, 252 insertions(+), 12 deletions(-) create mode 100644 internal/fanql/review_test.go diff --git a/internal/fanql/lower.go b/internal/fanql/lower.go index 963af36d..c61b5fcd 100644 --- a/internal/fanql/lower.go +++ b/internal/fanql/lower.go @@ -46,7 +46,7 @@ func lower(r *Resolved) (panel.Query, panel.Problems) { } if q.Sort != nil { key := q.Sort.Key - if key == "duration" { + if key == "duration" && !sortIsMeasureAlias(q) { key = "duration_ms" } out.Sort = key @@ -109,7 +109,14 @@ func lowerValue(f Field, v Value) string { return sqlString(text) } -func lowerEntry(e Expr) string { return lowerNegated(e, false) } +func lowerEntry(e Expr) string { + // A whole raw entry is the exact interchange spelling (section 0.8). + // Raw fragments inside boolean expressions are parenthesized below. + if raw, ok := e.(*RawExpr); ok { + return raw.Text + } + return lowerNegated(e, false) +} func lowerNegated(e Expr, neg bool) string { switch x := e.(type) { case *Not: @@ -241,7 +248,7 @@ func lowerNegated(e Expr, neg bool) string { if neg { return nullNegation(x.Text) } - return x.Text + return "(" + x.Text + ")" } return "" } @@ -305,7 +312,7 @@ func lowerCall(c *Call) string { if c.Cmp.Value.Kind == BooleanValue { v = strings.ToLower(v) } - if c.Cmp.Value.Kind != NumberValue && c.Cmp.Value.Kind != BooleanValue { + if c.Cmp.Value.Kind != NumberValue && c.Cmp.Value.Kind != BooleanValue && c.Cmp.Value.Kind != VariableValue { v = sqlString(v) } p += " " + c.Cmp.Op + " " + v diff --git a/internal/fanql/print.go b/internal/fanql/print.go index 7fbef331..5bd7c3c3 100644 --- a/internal/fanql/print.go +++ b/internal/fanql/print.go @@ -52,7 +52,7 @@ func Print(q *Query) string { text += "+" } key := q.Sort.Key - if key == "duration_ms" { + if key == "duration_ms" && !sortIsMeasureAlias(q) { key = "duration" } text += key @@ -245,6 +245,11 @@ func validPath(s string) bool { return identifierPath.MatchString(s) } func quoteText(s string) string { return `"` + strings.ReplaceAll(s, `"`, `""`) + `"` } func printValue(v Value, f Field, aliases bool) string { + if v.Kind == NumberValue && f.Ref != nil && f.Ref.Column == "duration_ms" && f.Ref.Key == "" { + if n, err := strconv.ParseFloat(v.Text, 64); err == nil { + return durationText(n) + } + } if aliases && v.Kind != VariableValue { stored := v.Stored if stored == "" { @@ -348,7 +353,7 @@ func bareValue(s string) bool { return false } for _, r := range s { - if unicode.IsSpace(r) || strings.ContainsRune("|(),:=!<>~\"'`[]#{}@", r) { + if unicode.IsSpace(r) || strings.ContainsRune("|(),:=!<>~\"'`[]#{}@$*", r) { return false } } diff --git a/internal/fanql/resolve.go b/internal/fanql/resolve.go index 7f872d81..7e78e554 100644 --- a/internal/fanql/resolve.go +++ b/internal/fanql/resolve.go @@ -2,8 +2,10 @@ package fanql import ( "fmt" + "math" "slices" "sort" + "strconv" "strings" "github.com/labstack/fanout/internal/panel" @@ -133,6 +135,9 @@ func (r *resolver) field(f *Field) { } key := f.Key scope := f.Scope + if f.Bracket && key == "" { + r.issue(f.At, "attribute keys must not be empty") + } if strings.HasPrefix(key, "$__") { r.issue(f.At, messages["variable"]) } @@ -250,14 +255,17 @@ func isRange(op string) bool { } func (r *resolver) value(f *Field, v *Value, op string, multi bool) { v.Stored = v.Text - if v.Kind == VariableValue { - r.variable(v.Text, f.Key, v.At, multi) + if !r.finiteValue(*v) { return } ref := f.Ref if ref.Column == "http_status_code" && ref.Key == "" && isRange(op) { ref.CompareAs = "integer" } + if v.Kind == VariableValue { + r.variable(v.Text, f.Key, v.At, multi) + return + } if v.Kind == DurationValue { if !strings.EqualFold(f.Key, "duration") || f.Scope != "" { text := v.Text @@ -346,6 +354,20 @@ func (r *resolver) value(f *Field, v *Value, op string, multi bool) { } } +func (r *resolver) finiteValue(v Value) bool { + var n float64 + if v.Kind == NumberValue { + n, _ = strconv.ParseFloat(v.Text, 64) + } else if v.Kind == DurationValue { + n, _ = durationMS(v.Text) + } + if math.IsInf(n, 0) || math.IsNaN(n) { + r.issue(v.At, "number must be finite") + return false + } + return true +} + func (r *resolver) bands(f Field, op string, lo Value, hi *Value) []string { level := telemetry.SeverityFromText(lo.Text) rank, ok := telemetry.SeverityRank(level) @@ -446,6 +468,10 @@ func (r *resolver) call(c *Call) { } if c.Cmp != nil { c.Cmp.Value.Stored = c.Cmp.Value.Text + r.finiteValue(c.Cmp.Value) + if c.Cmp.Value.Kind == VariableValue { + r.variable(c.Cmp.Value.Text, "", c.Cmp.Value.At, false) + } } } @@ -551,6 +577,17 @@ func measureAlias(m Measure, all []Measure) string { return c.Name } +func sortIsMeasureAlias(q *Query) bool { + if q.Sort != nil && q.Stage != nil { + for _, m := range q.Stage.Measures { + if measureAlias(m, q.Stage.Measures) == q.Sort.Key { + return true + } + } + } + return false +} + func (r *resolver) sort() { q := r.out.Query r.path = "sort" diff --git a/internal/fanql/review_test.go b/internal/fanql/review_test.go new file mode 100644 index 00000000..477c131c --- /dev/null +++ b/internal/fanql/review_test.go @@ -0,0 +1,170 @@ +package fanql + +import ( + "database/sql" + "reflect" + "testing" + + "github.com/labstack/fanout/internal/panel" +) + +func TestRawFragmentsPreservePrecedence(t *testing.T) { + c, ps := Compile("logs where (`body = 'a' OR body = 'b'` service:api)", Options{}) + if len(ps) != 0 { + t.Fatal(ps) + } + want := []string{"((body = 'a' OR body = 'b') AND service = 'api')"} + if !reflect.DeepEqual(c.Query.Where, want) { + t.Fatalf("got %q, want %q", c.Query.Where, want) + } +} + +func TestPrintQuotedLexicalCharacters(t *testing.T) { + for _, text := range []string{`logs where "api*"`, `logs where "api$svc"`, `logs where service:"api*"`, `logs where service:"api$svc"`} { + t.Run(text, func(t *testing.T) { + a, ps := Compile(text, Options{}) + if len(ps) != 0 { + t.Fatal(ps) + } + b, ps := Compile(a.Canonical, Options{}) + if len(ps) != 0 { + t.Fatalf("canonical %q: %+v", a.Canonical, ps) + } + if b.Canonical != a.Canonical || !reflect.DeepEqual(a.Query, b.Query) { + t.Fatalf("not a fixed point: %+v -> %+v", a, b) + } + }) + } +} + +func TestPrintParsePrintFixtureCorpus(t *testing.T) { + texts := append([]string(nil), glanceExamples...) + for _, fixture := range lowerFixtures { + texts = append(texts, fixture.text) + } + for _, fixture := range canonicalCases { + texts = append(texts, fixture[0]) + } + for _, text := range texts { + a, ps := Compile(text, Options{}) + if len(ps) != 0 { + t.Fatal(text, ps) + } + b, ps := Compile(a.Canonical, Options{}) + if len(ps) != 0 { + t.Fatalf("%q -> %q: %+v", text, a.Canonical, ps) + } + if a.Canonical != b.Canonical || !reflect.DeepEqual(a.Query, b.Query) { + t.Fatalf("not a fixed point: %q -> %q -> %q", text, a.Canonical, b.Canonical) + } + } +} + +func TestPrintDurationMSKeepsUnit(t *testing.T) { + a, ps := Compile(`spans where duration_ms>500`, Options{}) + if len(ps) != 0 { + t.Fatal(ps) + } + if a.Canonical != `spans where duration>500ms` { + t.Fatalf("canonical: %q", a.Canonical) + } + b, ps := Compile(a.Canonical, Options{}) + if len(ps) != 0 || !reflect.DeepEqual(a.Query, b.Query) { + t.Fatalf("round trip: %+v %+v", b, ps) + } +} + +func TestSortPreservesMeasureAliasDuration(t *testing.T) { + for _, alias := range []string{"duration", "duration_ms"} { + text := "spans | count() as " + alias + " sort " + alias + a, ps := Compile(text, Options{Viz: "table"}) + if len(ps) != 0 { + t.Fatal(text, ps) + } + if a.Query.Sort != alias || a.Canonical != text { + t.Fatalf("alias rewritten: %+v", a) + } + } +} + +func TestHTTPStatusVariableRangeUsesNumericCast(t *testing.T) { + c, ps := Compile(`spans where http_status_code>=$code`, Options{Variables: []panel.Variable{{Name: "code"}}}) + if len(ps) != 0 { + t.Fatal(ps) + } + if got := c.Query.Where[0]; got != `TRY_CAST(http_status_code AS INTEGER) >= $code` { + t.Fatal(got) + } + // The string dashboard value "500" must have the same numeric ordering as + // the literal 500, including a status such as "60" that sorts after "500". + d, _ := newTestEngine(t) + var n int + err := d.QueryRowScan(t.Context(), []any{&n}, `SELECT count(*) AS n FROM (VALUES ('500'), ('60')) t(http_status_code) WHERE `+c.Query.Where[0], sql.Named("code", "500")) + if err != nil { + t.Fatal(err) + } + if n != 1 { + t.Fatalf("matched %d rows, want 1", n) + } +} + +func TestComparedCallVariablesBindAndRespectCountIf(t *testing.T) { + t.Run("bind", func(t *testing.T) { + c, ps := Compile(`logs where lower(service)=$svc`, Options{Variables: []panel.Variable{{Name: "svc"}}}) + if len(ps) != 0 { + t.Fatal(ps) + } + if got := c.Query.Where[0]; got != `lower(service) = $svc` { + t.Fatal(got) + } + }) + t.Run("count_if", func(t *testing.T) { + c, ps := Compile(`spans | count_if(length(operation)>$x)`, Options{}) + if c != nil || len(ps) != 1 || ps[0].Message != "variables are not allowed inside count_if" || ps[0].Span == nil { + t.Fatalf("got %+v %+v", c, ps) + } + }) +} + +func TestNonFiniteLiteralsHavePositionedProblems(t *testing.T) { + for _, text := range []string{`spans where duration_ms>1e309`, `spans where duration>1e308h`} { + t.Run(text, func(t *testing.T) { + c, ps := Compile(text, Options{}) + if c != nil || len(ps) != 1 || ps[0].Message != "number must be finite" || ps[0].Span == nil || ps[0].Span.End != len(text) { + t.Fatalf("got %+v %+v", c, ps) + } + }) + } +} + +func TestEmptyBracketKeyIsRejected(t *testing.T) { + c, ps := Compile(`logs where attributes['']:x`, Options{}) + if c != nil || len(ps) != 1 || ps[0].Message != "attribute keys must not be empty" || ps[0].Span == nil { + t.Fatalf("got %+v %+v", c, ps) + } +} + +func TestGroupByAcceptsLiteralKeys(t *testing.T) { + engine, _ := newTestEngine(t) + for _, text := range []string{`spans | count() by attributes['user name']`, `spans | count() by attributes['user''s name']`, `spans | count() by resource['𝔘 [name]']`} { + c, ps := Compile(text, Options{Viz: "table"}) + if len(ps) != 0 { + t.Fatal(text, ps) + } + if len(c.Query.By) != 1 { + t.Fatal(c) + } + if text == `spans | count() by attributes['user name']` && c.Query.By[0] != `attributes['user name']` { + t.Fatal(c.Query.By) + } + d, ps := Compile(c.Canonical, Options{Viz: "table"}) + if len(ps) != 0 || !reflect.DeepEqual(c.Query, d.Query) { + t.Fatalf("round trip: %+v %+v", d, ps) + } + dashboard := panel.Dashboard{Name: "keys", Panels: []panel.Panel{{ID: "keys", Title: "Keys", Viz: "table", Query: &c.Query}}} + panel.Normalize(&dashboard) + if _, ps, err := panel.Check(t.Context(), engine, &dashboard); len(ps) != 0 || err != nil { + t.Fatalf("engine check for %q: %+v %v", text, ps, err) + } + } +} diff --git a/internal/fanql/spellings.go b/internal/fanql/spellings.go index 02a8be1e..be646d08 100644 --- a/internal/fanql/spellings.go +++ b/internal/fanql/spellings.go @@ -1,6 +1,7 @@ package fanql import ( + "math" "regexp" "strconv" "strings" @@ -21,7 +22,8 @@ func durationMS(text string) (float64, bool) { }{{"us", .001}, {"ms", 1}, {"s", 1000}, {"m", 60000}, {"h", 3600000}} { if strings.HasSuffix(text, u.name) { n, err := strconv.ParseFloat(strings.TrimSuffix(text, u.name), 64) - return n * u.scale, err == nil + ms := n * u.scale + return ms, err == nil && !math.IsNaN(ms) && !math.IsInf(ms, 0) } } return 0, false diff --git a/internal/panel/catalog.go b/internal/panel/catalog.go index 15590c13..a73e4dd9 100644 --- a/internal/panel/catalog.go +++ b/internal/panel/catalog.go @@ -147,12 +147,12 @@ type FieldRef struct { Unit string } -var attributePattern = regexp.MustCompile(`^(attributes|resource)\['([A-Za-z0-9_.\-/:@]{1,128})'\]$`) +var attributePattern = regexp.MustCompile(`(?s)^(attributes|resource)\['((?:[^']|'')+)'\]$`) func (s *signal) field(text string) (FieldRef, error) { text = strings.TrimSpace(text) if m := attributePattern.FindStringSubmatch(text); m != nil { - return FieldRef{Text: text, Column: m[1], Key: m[2], Type: TypeString, Unit: "none"}, nil + return FieldRef{Text: text, Column: m[1], Key: strings.ReplaceAll(m[2], "''", "'"), Type: TypeString, Unit: "none"}, nil } f, ok := s.index[text] if !ok { diff --git a/internal/panel/filter.go b/internal/panel/filter.go index ce1f9b78..2275fa60 100644 --- a/internal/panel/filter.go +++ b/internal/panel/filter.go @@ -300,7 +300,7 @@ func checkAttributeLookup(v map[string]any) error { } key, _ := children[1].(map[string]any) text := constantText(key) - if key["class"] != "CONSTANT" || !attributePattern.MatchString(fmt.Sprintf("%s['%s']", names[0], text)) { + if key["class"] != "CONSTANT" || !attributePattern.MatchString(fmt.Sprintf("%s[%s]", names[0], sqlString(text))) { return errors.New("attribute keys must be literal strings such as attributes['http.route']") } return nil diff --git a/internal/panel/shape_test.go b/internal/panel/shape_test.go index b2c1e8d0..a10bf7fe 100644 --- a/internal/panel/shape_test.go +++ b/internal/panel/shape_test.go @@ -62,6 +62,25 @@ func TestQueryShapeRequires(t *testing.T) { } } +func TestQueryShapeRejectsIncompleteMeasure(t *testing.T) { + q := &Query{From: "spans", Measures: []string{"count() + as x"}} + got, _ := QueryShape(q, "table", nil) + if len(got) == 0 { + t.Fatal("shape accepted an incomplete arithmetic expression") + } + d := Dashboard{Name: "test", Panels: []Panel{{ID: "t", Title: "t", Viz: "table", Query: q}}} + var want Problems + for _, p := range Validate(&d) { + if strings.HasPrefix(p.Path, "panels[0].query.") { + p.Path = strings.TrimPrefix(p.Path, "panels[0].query.") + want = append(want, p) + } + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("shape = %+v; validate = %+v", got, want) + } +} + func TestQueryShapeCountIfDefaultAlias(t *testing.T) { q := &Query{From: "spans", Measures: []string{"count_if(status = 'STATUS_CODE_ERROR')"}, Sort: "count_if"} if problems, _ := QueryShape(q, "table", nil); len(problems) != 0 { From 0f67f8e8c3f400d4c53ef541a7836a88767d5ebe Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 16:50:25 -0700 Subject: [PATCH 12/30] feat(mcp): accept FanQL text in query_telemetry and publish the reference resource --- internal/mcp/fanql_resource.go | 19 +++ internal/mcp/fanql_test.go | 137 ++++++++++++++++++ internal/mcp/fragments.go | 28 +++- internal/mcp/panels.go | 2 +- internal/mcp/server.go | 1 + site/src/content/docs/reference/mcp-tools.mdx | 4 +- 6 files changed, 185 insertions(+), 6 deletions(-) create mode 100644 internal/mcp/fanql_resource.go create mode 100644 internal/mcp/fanql_test.go diff --git a/internal/mcp/fanql_resource.go b/internal/mcp/fanql_resource.go new file mode 100644 index 00000000..d43299bd --- /dev/null +++ b/internal/mcp/fanql_resource.go @@ -0,0 +1,19 @@ +package mcp + +import ( + "context" + + "github.com/labstack/fanout/internal/fanql" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +const fanqlReferenceURI = "fanout://fanql/reference" + +func (s *Server) registerFanQLResource() { + s.mcp.AddResource(&mcp.Resource{ + URI: fanqlReferenceURI, Name: "FanQL reference", MIMEType: "text/markdown", + Description: "The FanQL preview language reference, generated from the server registries.", + }, func(_ context.Context, _ *mcp.ReadResourceRequest) (*mcp.ReadResourceResult, error) { + return &mcp.ReadResourceResult{Contents: []*mcp.ResourceContents{{URI: fanqlReferenceURI, MIMEType: "text/markdown", Text: fanql.Reference()}}}, nil + }) +} diff --git a/internal/mcp/fanql_test.go b/internal/mcp/fanql_test.go new file mode 100644 index 00000000..55321017 --- /dev/null +++ b/internal/mcp/fanql_test.go @@ -0,0 +1,137 @@ +package mcp + +import ( + "context" + "encoding/json" + "reflect" + "strings" + "testing" + + "github.com/labstack/fanout/internal/fanql" + "github.com/labstack/fanout/internal/panel" + "github.com/labstack/fanout/internal/toolerror" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +func TestQueryTelemetryAcceptsFanQLText(t *testing.T) { + s := panelServerFixture(t, true) + p := panel.Panel{ID: "t", Title: "t", Viz: "table"} + input := QueryTelemetryInput{Panel: p, Text: "spans where status:error | count() by service"} + _, got, err := s.queryTelemetry(t.Context(), nil, input) + if err != nil { + t.Fatal(err) + } + want := &panel.Query{From: "spans", Where: []string{"status = 'STATUS_CODE_ERROR'"}, Measures: []string{"count()"}, By: []string{"service"}} + if !reflect.DeepEqual(got.Dashboard.Panels[0].Query, want) { + t.Fatalf("query: %+v", got.Dashboard.Panels[0].Query) + } + p.Query = want + _, structured, err := s.queryTelemetry(t.Context(), nil, QueryTelemetryInput{Panel: p, Time: &got.Dashboard.Time}) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got.Results[0].Frame, structured.Results[0].Frame) { + t.Fatalf("text frame %+v; structured %+v", got.Results[0].Frame, structured.Results[0].Frame) + } + if input.Panel.Query != nil { + t.Fatal("mutated caller's panel") + } +} + +type fanqlRunCounter struct { + panelExecutor + calls int +} + +func (e *fanqlRunCounter) Run(ctx context.Context, req panel.RunRequest) ([]panel.Result, error) { + e.calls++ + return e.panelExecutor.Run(ctx, req) +} + +func checkFanQLToolFailure(t *testing.T, input QueryTelemetryInput, code, message string) { + t.Helper() + s := newPanelServer(t) + counter := &fanqlRunCounter{panelExecutor: s.panels} + s.panels = counter + _, _, err := s.queryTelemetry(t.Context(), nil, input) + if err == nil { + t.Fatal("invalid input accepted") + } + var failure toolerror.Result + if json.Unmarshal([]byte(err.Error()), &failure) != nil || failure.Error == nil || failure.Error.Code != code || !strings.Contains(failure.Error.Message, message) { + t.Fatalf("error: %v", err) + } + if counter.calls != 0 { + t.Fatalf("executor ran %d times", counter.calls) + } +} + +func TestQueryTelemetryRejectsTextWithQueryOrSQL(t *testing.T) { + for _, p := range []panel.Panel{{Query: &panel.Query{From: "spans"}}, {SQL: "SELECT 1"}} { + checkFanQLToolFailure(t, QueryTelemetryInput{Panel: p, Text: "spans"}, "invalid_input", "text cannot be combined with panel.query or panel.sql") + } +} + +func TestQueryTelemetryReportsFanQLProblems(t *testing.T) { + checkFanQLToolFailure(t, QueryTelemetryInput{Text: "spans where a:1 b:2 or c:3"}, "invalid_fanql", "mixed and/or needs parentheses") +} + +func TestQueryTelemetryRejectsUnsupportedFanQLVersion(t *testing.T) { + checkFanQLToolFailure(t, QueryTelemetryInput{Text: "spans", FanQLVersion: 2}, "unsupported_fanql_version", "this server reads FanQL 1") +} + +func TestFanQLReferenceResource(t *testing.T) { + s := newPanelServer(t) + client := connectTestClient(t, s, nil) + listed, err := client.ListResources(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + found := false + for _, r := range listed.Resources { + if r.URI == "fanout://fanql/reference" { + found = true + if r.Name != "FanQL reference" || r.MIMEType != "text/markdown" { + t.Fatal(r) + } + } + } + if !found { + t.Fatal("FanQL reference missing from resources/list") + } + r, err := client.ReadResource(t.Context(), &mcp.ReadResourceParams{URI: "fanout://fanql/reference"}) + if err != nil { + t.Fatal(err) + } + if len(r.Contents) != 1 || r.Contents[0].MIMEType != "text/markdown" || r.Contents[0].Text != fanql.Reference() || !strings.Contains(r.Contents[0].Text, "FanQL 1") || !strings.Contains(r.Contents[0].Text, "Preview") { + t.Fatal(r) + } +} + +func TestQueryTelemetryDescriptionPrefersStructuredInput(t *testing.T) { + client := connectTestClient(t, newPanelServer(t), nil) + listed, err := client.ListTools(t.Context(), nil) + if err != nil { + t.Fatal(err) + } + for _, tool := range listed.Tools { + if tool.Name != "query_telemetry" { + continue + } + d := tool.Description + if !strings.Contains(d, "panel.query") || strings.Index(d, "text") < strings.Index(d, "panel.query") || !strings.Contains(d, "fanout://fanql/reference") { + t.Fatal(d) + } + if tool.Annotations == nil || !tool.Annotations.ReadOnlyHint { + t.Fatal("query must remain read-only") + } + raw, _ := json.Marshal(tool.InputSchema) + for _, field := range []string{`"text"`, `"fanql_version"`} { + if !strings.Contains(string(raw), field) { + t.Fatalf("missing %s: %s", field, raw) + } + } + return + } + t.Fatal("query_telemetry missing") +} diff --git a/internal/mcp/fragments.go b/internal/mcp/fragments.go index 789c240e..b75b0510 100644 --- a/internal/mcp/fragments.go +++ b/internal/mcp/fragments.go @@ -14,16 +14,19 @@ import ( "unicode/utf8" "github.com/google/jsonschema-go/jsonschema" + "github.com/labstack/fanout/internal/fanql" "github.com/labstack/fanout/internal/observability" "github.com/labstack/fanout/internal/panel" "github.com/modelcontextprotocol/go-sdk/mcp" ) type QueryTelemetryInput struct { - Panel panel.Panel `json:"panel" jsonschema:"One v1 panel to display in the answer"` - Variables []panel.Variable `json:"variables,omitempty" jsonschema:"Optional v1 variable definitions used by this panel"` - Time *panel.Time `json:"time,omitempty" jsonschema:"Optional dashboard time override: exact from/to or a relative range"` - Vars map[string]panel.Value `json:"vars,omitempty" jsonschema:"Resolved variable values: strings or lists; preserves $__all and empty lists"` + Panel panel.Panel `json:"panel" jsonschema:"One v1 panel to display in the answer"` + Text string `json:"text,omitempty" jsonschema:"FanQL text that becomes panel.query; prefer panel.query (structured) or panel.sql; see fanout://fanql/reference"` + FanQLVersion int `json:"fanql_version,omitempty" jsonschema:"FanQL version of text; this server reads 1"` + Variables []panel.Variable `json:"variables,omitempty" jsonschema:"Optional v1 variable definitions used by this panel"` + Time *panel.Time `json:"time,omitempty" jsonschema:"Optional dashboard time override: exact from/to or a relative range"` + Vars map[string]panel.Value `json:"vars,omitempty" jsonschema:"Resolved variable values: strings or lists; preserves $__all and empty lists"` } type FragmentView struct { Kind string `json:"kind" jsonschema:"View kind: preset or query"` @@ -160,6 +163,23 @@ func (s *Server) executeFragment(ctx context.Context, req panel.RunRequest) (Pan return PanelFragment{Dashboard: req.Dashboard, Results: results, Vars: req.Vars}, nil } func (s *Server) queryTelemetry(ctx context.Context, _ *mcp.CallToolRequest, input QueryTelemetryInput) (*mcp.CallToolResult, PanelFragment, error) { + if input.Text != "" && (input.Panel.Query != nil || input.Panel.SQL != "") { + return nil, PanelFragment{}, guidanceError("invalid_input", "text cannot be combined with panel.query or panel.sql") + } + if input.FanQLVersion != 0 && input.FanQLVersion != fanql.Version { + return nil, PanelFragment{}, guidanceError("unsupported_fanql_version", "this server reads FanQL 1") + } + if input.Text != "" { + compiled, problems := fanql.Compile(input.Text, fanql.Options{Viz: input.Panel.Viz, Variables: input.Variables}) + if len(problems) != 0 { + messages := make([]string, len(problems)) + for i, p := range problems { + messages[i] = p.Message + } + return nil, PanelFragment{}, guidanceError("invalid_fanql", strings.Join(messages, "; ")) + } + input.Panel.Query = &compiled.Query + } d := panel.Dashboard{Name: input.Panel.Title, Variables: input.Variables, Panels: []panel.Panel{input.Panel}} return s.runFragment(ctx, panel.RunRequest{Dashboard: d, Time: input.Time, Vars: input.Vars}) } diff --git a/internal/mcp/panels.go b/internal/mcp/panels.go index a938d29e..078dfe4a 100644 --- a/internal/mcp/panels.go +++ b/internal/mcp/panels.go @@ -48,7 +48,7 @@ const baseSpecGuide = `A dashboard is {name, description, time:{range}, variable func (s *Server) registerPanelTools() { readOnly := &mcp.ToolAnnotations{ReadOnlyHint: true, OpenWorldHint: boolPtr(false)} - fragmentTool(s, &mcp.Tool{Name: "query_telemetry", Title: "Telemetry panel", Description: "Display one v1 panel in chat as an executable dashboard fragment. Use get_telemetry_schema to discover fields; see create_dashboard for the spec guide. The authored spec plus vars must fit 128 KiB (131072 serialized JSON bytes); larger inputs are rejected with their actual size.", Annotations: readOnly, Meta: appToolMeta(panelsAppURI)}, s.queryTelemetry) + fragmentTool(s, &mcp.Tool{Name: "query_telemetry", Title: "Telemetry panel", Description: "Display one v1 panel in chat as an executable dashboard fragment. Use get_telemetry_schema to discover fields; see create_dashboard for the spec guide. The authored spec plus vars must fit 128 KiB (131072 serialized JSON bytes); larger inputs are rejected with their actual size. Agents: write panel.query (structured JSON) first, or panel.sql for complex work; text accepts the human FanQL form (fanout://fanql/reference) and is never required.", Annotations: readOnly, Meta: appToolMeta(panelsAppURI)}, s.queryTelemetry) fragmentTool(s, &mcp.Tool{Name: "query_panel_fragment", Title: "Refresh telemetry panels", Description: "Run every panel in a dashboard fragment; panel subsets are forbidden.", Annotations: readOnly, Meta: appHelperMeta()}, func(ctx context.Context, req *mcp.CallToolRequest, input fragmentInput) (*mcp.CallToolResult, PanelFragment, error) { return s.queryPanelFragment(ctx, req, panel.RunRequest{Dashboard: input.Dashboard, Time: input.Time, Vars: input.Vars, Widths: input.Widths, Compare: input.Compare}) }) diff --git a/internal/mcp/server.go b/internal/mcp/server.go index 0abd4174..8c1f41c9 100644 --- a/internal/mcp/server.go +++ b/internal/mcp/server.go @@ -142,6 +142,7 @@ func newServer(queries Observability, dashboards *dashboard.Service, panels *pan s.registerPanelTools() s.registerDashboardTools() s.registerAppResources() + s.registerFanQLResource() s.mcp.AddReceivingMiddleware(limitLegacySessions(s.mcp), normalizeToolErrors, recoverToolPanic, addStaticCacheHints, filterMCPAppToolMetadata, s.validateToolArguments) return s } diff --git a/site/src/content/docs/reference/mcp-tools.mdx b/site/src/content/docs/reference/mcp-tools.mdx index 7a848437..c6b3162f 100644 --- a/site/src/content/docs/reference/mcp-tools.mdx +++ b/site/src/content/docs/reference/mcp-tools.mdx @@ -266,7 +266,7 @@ Read-only. ## query_telemetry -**Telemetry panel** — Display one v1 panel in chat as an executable dashboard fragment. Use get_telemetry_schema to discover fields; see create_dashboard for the spec guide. The authored spec plus vars must fit 128 KiB (131072 serialized JSON bytes); larger inputs are rejected with their actual size. All-empty results return no_data guidance instead of a view. State no matching data findings in the answer and prefer signals the service actually has. +**Telemetry panel** — Display one v1 panel in chat as an executable dashboard fragment. Use get_telemetry_schema to discover fields; see create_dashboard for the spec guide. The authored spec plus vars must fit 128 KiB (131072 serialized JSON bytes); larger inputs are rejected with their actual size. Agents: write panel.query (structured JSON) first, or panel.sql for complex work; text accepts the human FanQL form (fanout://fanql/reference) and is never required. All-empty results return no_data guidance instead of a view. State no matching data findings in the answer and prefer signals the service actually has. Read-only. @@ -275,6 +275,8 @@ Read-only. | Input | Type | Required | Means | |---|---|---|---| | `panel` | `object` | **yes** | One v1 panel to display in the answer | +| `fanql_version` | `integer` | no | FanQL version of text; this server reads 1 | +| `text` | `string` | no | FanQL text that becomes panel.query; prefer panel.query (structured) or panel.sql; see fanout://fanql/reference | | `time` | `object` | no | Optional dashboard time override: exact from/to or a relative range | | `variables` | `array` | no | Optional v1 variable definitions used by this panel | | `vars` | `object` | no | Resolved variable values: strings or lists; preserves $__all and empty lists | From 06946c37100cf39f07f146a7d24621daf73c5372 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 16:50:29 -0700 Subject: [PATCH 13/30] feat(fanql): generate the FanQL reference from the registries --- cmd/fanout-docgen/main.go | 2 + cmd/fanout-docgen/main_test.go | 21 ++ internal/fanql/reference.go | 177 +++++++++++- internal/fanql/reference_test.go | 99 +++++++ scripts/go-deadcode.allowlist | 2 - scripts/site-tables.test.ts | 32 +++ site/scripts/check-tables.mjs | 5 +- site/src/content/docs/reference/fanql.md | 332 +++++++++++++++++++++++ 8 files changed, 665 insertions(+), 5 deletions(-) create mode 100644 internal/fanql/reference_test.go create mode 100644 scripts/site-tables.test.ts create mode 100644 site/src/content/docs/reference/fanql.md diff --git a/cmd/fanout-docgen/main.go b/cmd/fanout-docgen/main.go index 0850ae24..517d14ad 100644 --- a/cmd/fanout-docgen/main.go +++ b/cmd/fanout-docgen/main.go @@ -40,6 +40,7 @@ import ( "github.com/labstack/fanout/internal/alert" "github.com/labstack/fanout/internal/config" + "github.com/labstack/fanout/internal/fanql" ) func main() { @@ -117,6 +118,7 @@ func run(source, alertSource, routeDirs, outDir, envExample string, check bool) return err } pages["mcp-tools.mdx"] = toolsPage + pages["fanql.md"] = []byte("---\ntitle: \"FanQL\"\ndescription: \"The preview text syntax for structured telemetry queries.\"\nsummary: \"FanQL 1 syntax, fields, functions, variables, null semantics and examples, generated from query registries.\"\nstatus: preview\ngenerated: true\n---\n\n" + fanql.Reference()) outputs := map[string][]byte{envExample: renderEnvironment(fields)} for name, body := range pages { diff --git a/cmd/fanout-docgen/main_test.go b/cmd/fanout-docgen/main_test.go index a3430930..043d1f4a 100644 --- a/cmd/fanout-docgen/main_test.go +++ b/cmd/fanout-docgen/main_test.go @@ -7,10 +7,31 @@ import ( "testing" "github.com/labstack/fanout/internal/config" + "github.com/labstack/fanout/internal/fanql" ) const configSource = "../../internal/config/config.go" +func TestDocgenWritesFanQLReference(t *testing.T) { + dir := t.TempDir() + out := filepath.Join(dir, "reference") + if err := run(configSource, "../../internal/alert/types.go", strings.Join(routeDirs, ","), out, filepath.Join(dir, ".env.example"), false); err != nil { + t.Fatal(err) + } + raw, err := os.ReadFile(filepath.Join(out, "fanql.md")) + if err != nil { + t.Fatal(err) + } + page := string(raw) + if !strings.HasPrefix(page, "---\n") || !strings.Contains(page, "generated: true\n") || !strings.Contains(page, "summary: ") { + t.Fatal("missing site front matter") + } + _, content, ok := strings.Cut(page, "\n---\n\n") + if !ok || content != fanql.Reference() { + t.Fatalf("page content differs from the API/MCP reference: %q", page) + } +} + // The generator's value is that a page cannot describe a setting the binary // does not accept. That holds only while reflection and the source parse agree, // so the cross-check is the thing worth testing. diff --git a/internal/fanql/reference.go b/internal/fanql/reference.go index 19201c98..3b81e029 100644 --- a/internal/fanql/reference.go +++ b/internal/fanql/reference.go @@ -1,6 +1,179 @@ package fanql -// Reference returns the current preview language reference. +import ( + "fmt" + "slices" + "strings" + + "github.com/labstack/fanout/internal/panel" + "github.com/labstack/fanout/internal/telemetry" +) + +// Reference is the shared API, MCP resource and generated-site reference. +// Registry-owned names, field metadata and vocabularies are read on every call. func Reference() string { - return "# FanQL 1\n\nPreview: the syntax may change before GA\n" + var b strings.Builder + fmt.Fprintf(&b, "# FanQL %d\n\nPreview: the syntax may change before GA\n\n", Version) + b.WriteString("FanQL is the text form of a structured telemetry query. It produces the same `panel.Query` that dashboards store and the panel engine executes. Panels store the query; text is derived. Problems prevent execution; notices never block it.\n\n") + b.WriteString("## Shape and entry points\n\n`source [where] filters | measures by fields every bucket sort key limit n`\n\nExplore accepts a whole query. Logs and Traces search bars accept filters only; the page supplies source, `where` and visualization. The visualization picker accepts the query as written. Adding `| count() every auto` to make a timeseries is a visible edit. One aggregation stage is allowed; another pipe may introduce only `sort` or `limit`, and canonical text drops that pipe.\n\n") + b.WriteString("## Sources and words\n\n") + fmt.Fprintf(&b, "Sources: %s, recognized only as the first token. A bare source selects all rows in the chosen time range. `where` is optional; canonical text supplies it when filters exist.\n\n", referenceWords(referenceKeys(sources))) + fmt.Fprintf(&b, "Clause words: %s and `|`, recognized at depth zero, outside quotes and brackets, at a term boundary. After operators they are values (`service:where`, `service in (sort, limit)`). Quote a clause word to search for it.\n\nExpression words: %s, recognized only in their grammatical positions. Modifiers: %s. Keywords, columns, functions, units and vocabulary aliases ignore case. Values and attribute/resource keys preserve case.\n\n", referenceWords(referenceKeys(clauses)), referenceWords(referenceKeys(expressionWords)), referenceWords(referenceKeys(modifiers))) + b.WriteString("A word is a field only before a field operator; otherwise it searches log `body` or span `operation`. Metrics require an explicit field. Quotes use doubling as the only escape; backslashes are literal. Quoted `api*` and embedded `$` stay quoted. Wildcards are unsupported except `k:*` and `count(*)`. A leading `-` is negation except when a numeric value is expected. `+` is legal in a sort key or exponent.\n\n") + b.WriteString("## Operators and missing values\n\n| Operator | Meaning |\n|---|---|\n") + for _, row := range [][2]string{ + {":", "Equality with vocabulary aliases; missing values are excluded."}, {"=", "Equality, with the same typing and alias rules as `:`."}, + {"!=", "SQL spelling, SQL meaning: rows without `k` are excluded; `-k:v` includes them."}, {"<>", "SQL inequality, equivalent to `!=`; missing values are excluded."}, + {">", "Greater than; missing values are excluded."}, {">=", "Greater than or equal; missing values are excluded."}, {"<", "Less than; missing values are excluded."}, {"<=", "Less than or equal; missing values are excluded."}, + {"~", "Case-insensitive substring; `%` and `_` are ordinary characters."}, {"!~", "Null-inclusive substring exclusion, like `-k ~ v`."}, + {"in", "Membership in a nonempty list or multi-value variable; missing values are excluded."}, {"not in", "SQL spelling, SQL meaning: missing values are excluded; prefix `-` includes them."}, + {"between", "Inclusive lower and upper bounds separated by `and`; missing values are excluded."}, {"not between", "SQL spelling, SQL meaning: missing values are excluded; prefix `-` includes them."}, + {"is null", "Matches missing values, canonical `-k:*`."}, {"is not null", "Matches present values, canonical `k:*`."}, + {"like", "Case-sensitive SQL pattern; requires quoted text; `%` and `_` are wildcards."}, {"ilike", "Case-insensitive SQL pattern; requires quoted text."}, + {"not like", "SQL spelling, SQL meaning: missing values are excluded; prefix `-` includes them."}, {"not ilike", "SQL spelling, SQL meaning: missing values are excluded; prefix `-` includes them."}, + } { + fmt.Fprintf(&b, "| `%s` | %s |\n", row[0], row[1]) + } + b.WriteString("\nPrefix `-` or `not` excludes a term and includes rows where its predicate is NULL. Repeated negation cancels in pairs. SQL operators retain SQL null behavior. Compound negation follows De Morgan's law. TRY_CAST failures are NULL, so `-http_status_code between 400 and 599` includes uncastable codes.\n\nWhitespace and `and` join filters. An `or` chain must occupy its whole filter list or be parenthesized: `a:1 (b:2 or c:3)` and `(a:1 b:2) or c:3` differ. This rule also applies inside groups and `count_if`. Mixing conjunction and `or` without parentheses is a problem with suggested repairs.\n\n") + b.WriteString("## Fields\n\nA single identifier is a source column when one exists, otherwise an attribute key with a notice. Dotted `http.target` means `attributes['http.target']`; `resource.k8s.pod.name` means `resource['k8s.pod.name']`. Explicit `attributes.` uses the attributes map. Bracket keys are literal nonempty strings, including spaces, Unicode, punctuation and doubled quotes. Keys beginning `resource.` or `attributes.` retain brackets where needed to preserve the map.\n\nCanonical text brackets single-segment attribute keys, so new columns cannot reinterpret canonical or stored text. Map columns require a key. `duration` denotes `duration_ms` in filters, measure arguments and trace sorts. `duration_ms>500` takes a number; `duration>500ms` requires a unit. A measure alias named duration or duration_ms stays that alias in sort. Time columns accept range comparisons against quoted timestamps, not equality shorthand.\n\n") + for _, signal := range panel.SignalNames() { + fmt.Fprintf(&b, "### %s\n\n| Name | Type | Unit | Low cardinality | Description |\n|---|---|---|---|---|\n", signal) + columns, _ := panel.SignalColumns(signal) + lowCard := panel.LowCardinalityColumns(signal) + for _, column := range columns { + unit, low := column.Unit, "" + if unit == "" { + unit = "none" + } + if slices.Contains(lowCard, column.Name) { + low = "yes" + } + fmt.Fprintf(&b, "| `%s` | `%s` | `%s` | %s | %s |\n", column.Name, column.Type, unit, low, referenceCell(column.Description)) + } + b.WriteByte('\n') + } + b.WriteString("`http_status_code` is text. `<`, `<=`, `>`, `>=` and `between` use `TRY_CAST(http_status_code AS INTEGER)` for literals and variables alike. Equality and membership stay text, so `http_status_code:500` means `'500'`.\n\n") + b.WriteString("## Vocabularies and severity\n\nAliases apply under equality, inequality and membership, including prefix negation. Quoted values, contains, SQL patterns and function arguments are literal. Stored spellings are also accepted bare.\n\n") + for _, vocabulary := range []struct { + name string + aliases map[string]string + }{{"status (spans)", statusAliases}, {"kind (spans)", kindAliases}, {"type (metrics)", typeAliases}, {"severity (logs)", telemetry.SeverityAliases()}} { + fmt.Fprintf(&b, "### %s\n\n| Input | Stored |\n|---|---|\n", vocabulary.name) + for _, alias := range referenceKeys(vocabulary.aliases) { + fmt.Fprintf(&b, "| `%s` | `%s` |\n", alias, vocabulary.aliases[alias]) + } + b.WriteByte('\n') + } + fmt.Fprintf(&b, "Severity bands, lowest first: %s. `unspecified` maps to `UNSPECIFIED`; unknown names are uppercased. Trailing digits are dropped (`INFO2` becomes `INFO`). Unknown severity is legal for equality; sampled stored levels may provide a notice. Unknown status or kind aliases are problems.\n\n", referenceWords(telemetry.SeverityBands[:])) + b.WriteString("Every stored log severity is normalized once: a positive severity number has authority (21+ FATAL, 17+ ERROR, 13+ WARN, 9+ INFO, 5+ DEBUG, 1+ TRACE); absent/nonpositive numbers fall back to text. Invariant: no stored log row bypasses normalization. Severity ranges expand to contiguous band membership, never CASE. `severity>=warn` means WARN, ERROR, FATAL; `severity=14` for sublevels. Empty or reversed ranges are problems.\n\nOn normalized log rows, `error_rate()` counts exactly `severity>=error`. Its backend test is `upper(severity) IN ('ERROR', 'FATAL', 'CRITICAL') OR severity_number >= 17`; normalization makes legacy CRITICAL redundant. Span `error_rate()` counts `status:error`.\n\n") + b.WriteString("## Literals and durations\n\n| Literal | Rule |\n|---|---|\n| String | Bare words or single/double quotes; double a quote to escape it. Quoted values are strings and bypass aliases. |\n| Number | Integers, decimals and exponents (`500`, `1.5`, `2e3`, `-3`); non-finite values are rejected. Numbers stay numeric on number columns and attributes, and stay text as typed on string columns. |\n| Boolean | Bare `true`/`false`, case-insensitive; attributes retain boolean type, string columns compare text, number columns reject them. |\n| Duration | `us`, `ms`, `s`, `m`, `h`, only on `duration`; converted to milliseconds. Examples: `500ms`, `1.5s`, `250us`, `2m`, `1h`. Negative, compound and overflowing durations are rejected. |\n| Timestamp | Quoted RFC 3339 or `YYYY-MM-DD HH:MM:SS`, optional fraction/offset; no offset means UTC. Time comparisons retain nanoseconds through TIMESTAMPTZ_NS. |\n| Existence | `k:*` is IS NOT NULL; `-k:*` is IS NULL. |\n| Free text | Case-insensitive substring of log body or span operation; explicit field required on metrics. |\n\nContains emits `contains(lower(field), lower(value))`; map values first cast to VARCHAR. SQL LIKE/ILIKE require quoted patterns; ESCAPE is not expressible, so use `~` when `%` should be literal.\n\n") + b.WriteString("## Buckets\n\n") + fmt.Fprintf(&b, "%s. `auto` lets the engine choose an interval. A bucket follows `every` and belongs to an aggregate query.\n\n", referenceWords(panel.BucketNames())) + b.WriteString("## Measures\n\nThe registry defines accepted functions and signal availability. Fields follow the filter/grouping resolution rules. Numeric attribute measures use TRY_CAST AS DOUBLE; nonnumeric values become NULL. `count(*)` canonicalizes to `count()`.\n\n| Name | Form | Signals | Unit | Semantics |\n|---|---|---|---|---|\n") + for _, m := range panel.MeasureSpecs() { + form := m.Name + "()" + if m.Args == 1 { + form = m.Name + "(f)" + } else if m.Args == 2 { + form = m.Name + "(f, q)" + } + signals := m.Signals + if len(signals) == 0 { + signals = panel.SignalNames() + } + unit := m.Unit + if unit == "" { + unit = "field unit" + } + fmt.Fprintf(&b, "| `%s` | `%s` | %s | %s | %s |\n", m.Name, form, strings.Join(signals, ", "), unit, referenceMeasureMeaning(m.Name)) + } + b.WriteString("\nMetric aggregates require a standalone `name:` equality entry. Counters use per-series increases and reset handling; gauge/updown use point values; histograms use observation counts, sums and buckets; summaries use available stored aggregates. Unsupported kind/function combinations report a diagnosis instead of treating counters as gauges.\n\n`histogram(duration)` on spans uses count with log2 duration buckets; `histogram(value)` on metrics uses explicit histogram buckets. Distributions stand alone, with at most one `by` field for a histogram; `every` selects a heatmap.\n\n") + b.WriteString("## Expressions and ranking\n\n`count_if(filters)` takes a FanQL filter list as one entry and compiles to checked `count(*) FILTER (WHERE ...)::DOUBLE`. Raw entries are allowed; variables are forbidden. Spans and logs support `+ - * /`, constants, unary minus and parentheses on aggregate vizzes. Metrics, distributions and log_patterns do not support arithmetic. Every expression needs at least one aggregate. Other than a single call, an expression requires `as alias`; aliases are 1–40 lowercase letters/digits/underscores and start with a letter. `share()` stands alone. Division emits `a / nullif(b, 0)`, so zero denominators yield NULL.\n\nCount-family ratios use ratio units, `* 100` makes percent, addition/subtraction retains equal units, scaling retains the measure unit, other combinations use none. Expressions are not additive. Affine transformations inherit the underlying ranking and flip direction for a negative scale. Binomial count_if/count ratios use Wilson ranking with a 20-sample floor; other expressions use value ranking with leaf/denominator support. Ineligible series follow eligible ones by support, then dimension; result metadata discloses them.\n\nApdex uses disjoint predicates: `(count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex`. Exactly 500 ms counts once; NULL duration counts in the population and neither numerator.\n\nEach measure allows 256 tokens, 64 nodes, depth 8 and 8 aggregates. A query allows 256 expression nodes and 24 aggregates across at most 6 measures. A count_if filter is at most 500 bytes. Whitespace is not a token. Budgets apply to structured inputs too.\n\n") + b.WriteString("## Filter functions and raw entries\n\n| Function | Signature |\n|---|---|\n") + for _, name := range panel.FilterFunctionNames() { + args := "field" + if name == "starts_with" || name == "contains" || name == "regexp_matches" { + args = "field, quoted_string" + } + fmt.Fprintf(&b, "| `%s` | `%s(%s)` |\n", name, name, args) + } + b.WriteString("\n`lower`, `upper` and `length` need a comparison. `starts_with`, `contains` and `regexp_matches` are predicates alone. Calls have no space before `(`. Variables may compare call results, but remain forbidden inside count_if.\n\nA backtick-delimited raw entry passes SQL to the existing filter gate; double a backtick to include it. A whole raw entry retains its stored spelling; raw fragments composed with other predicates are parenthesized. The gate accepts columns, literal `attributes['k']`/`resource['k']`, comparisons, boolean logic, IN, LIKE, IS NULL, BETWEEN, coalesce, variables, the filter functions above and casts to VARCHAR, BIGINT, INTEGER, DOUBLE, BOOLEAN, UBIGINT and TIMESTAMPTZ_NS. It rejects CASE, DISTINCT, ORDER BY and FILTER inside functions, qualified columns, subqueries and other functions. Raw cannot bypass the gate.\n\n") + b.WriteString("## Variables and entry boundaries\n\n`$name` is a dashboard variable; `$__` names are reserved. It stays a parameter, never a string literal. `k in $multi` accepts multiple values; scalar operators reject multi variables. Without declarations, references produce notices so editing can continue; execution checks them.\n\nAll rule: a filter that mentions a variable set to All is removed; keep fixed conditions in their own terms. An empty variable list makes its entry FALSE. Top-level terms are separate entries; a parenthesized group, raw entry or OR chain is one entry. Stored order and boundaries survive formatting.\n\n| Filters | Entries | `$service` = All |\n|---|---|---|\n| `service:$service status:error` | 2 | Keep status. |\n| `(service:$service status:error)` | 1 | Drop both. |\n| `service:$service or service:worker` | 1 | Drop whole entry. |\n| `service:$service (status:error or status:unset)` | 2 | Keep status group. |\n| `-service:$service` | 1 | Drop entry; nothing excluded. |\n| Raw SQL mentioning `$service` | 1 | Drop whole entry. |\n| `count_if(service:$service)` | n/a | Rejected. |\n\n") + b.WriteString("## Visualization and trace semantics\n\nLogs/traces use logs/spans respectively and forbid measures, grouping, buckets and histogram. Log_patterns uses `count() by body_template`, optionally a bucket. Timeseries needs a bucket and at most one grouping field, with one measure when grouped. Tables allow three grouping fields; bars two, with one measure when grouped by two. Stat/gauge need one measure and no grouping/bucket; gauge needs min/max. Scatter needs two measures and one or two grouping fields. State_timeline needs one measure, one grouping field, a bucket and thresholds.\n\nTraces are `(namespace, trace_id)` candidates with at least one matching span in the window, ranked by matching spans' max(duration_ms), or min(start_time) for `sort +start`. Limit applies to candidates; the engine reads at most 1,001 for truncation detection. Each returns one root span, or its earliest span in the window if the root is outside it, with error status if any span in the trace errored. Displayed service and duration are root service and root duration. A child can match while the returned root has different values.\n\nTrace sorts: descending `duration` (stored duration_ms), `errors`, or ascending `+start`. `sort errors` is the legacy combined key: it also filters to error spans, then orders by duration. Prefer `status:error` with `sort duration`. Logs sort by `time` or `+time`; log_patterns by `count`. Aggregate sorts name a measure alias. Default/desc is descending; +/asc is ascending; choose one direction. Bucketed families use time order and options.top for series selection; sort/limit are accepted with a notice when ignored.\n\n") + b.WriteString("## Reserved words and foreign syntax\n\n") + fmt.Fprintf(&b, "%s are reserved at clause positions. Quote them to search for the word. Foreign syntax gets a diagnostic and FanQL hint, never an alias; an ordinary foreign word in filter position stays free text.\n\n", referenceWords(referenceKeys(reserved))) + fmt.Fprintf(&b, "Recognized foreign stages: %s. Foreign call shapes: %s. `from`, `index=`, `source=`, first-token `search`, `ago(`, `now(`, `earliest=`, `_time:`, `order by`, `group by`, `facet`, `==`, `=~`, `|=`, `|~`, `::`, selectors and `@field:` get targeted hints. Time ranges belong to the time picker.\n\n", referenceWords(referenceKeys(foreignStages)), referenceWords(referenceKeys(foreignCalls))) + b.WriteString("## Bounds and diagnostics\n\nInteractive text allows 4,000 code points and 8,192 bytes, 1,024 tokens, 512 AST nodes, nesting depth 16 and lists of 100 values. Queries lower to 16 entries of 500 bytes each, 6 measures and 3 grouping fields, further constrained by the viz. Completion returns at most 50 items. Problems have code-point spans and optional fix-its, follow source order and are capped at 20 plus a final more-problems diagnostic. Any problem prevents execution; requested repair previews are labeled not executable.\n\nFormat returns complete text and exactness `exact` or `normalized`, with notices for normalization. Raw preserves whole SQL entries. Editable canonical text reparses under its tier without merging entries. Beyond any interactive bound, `editable: false` carries a reason and complete text; the envelope must preserve the original query and consumers must not parse the oversized text.\n\n") + b.WriteString("## Examples\n\n```fanql\n") + for _, example := range referenceExamples { + b.WriteString(example) + b.WriteByte('\n') + } + b.WriteString("```\n\n## Versioning and transport\n\nThe language version is separate from product CalVer and the panel contract. Machine text inputs carry the FanQL version plus visualization, time, comparison, declarations, resolved values, namespace and options as needed. The structured query is required when editable is false. Panels keep storing queries, never text. Unsupported versions produce unsupported_fanql_version.\n\nA version bump is required when accepted text changes meaning or stops parsing, including columns that reinterpret bare identifiers and severity aliases that reinterpret accepted literals. New status/kind aliases that were errors, stage words and filter functions are additive. Canonical spelling is frozen per version; preview changes can rewrite through the shared structured query.\n\nHTTP exposes `/api/fanql/parse`, `/api/fanql/format`, `/api/fanql/complete` and `/api/fanql/reference?version=1`, requiring telemetry:read. MCP query_telemetry accepts text with fanql_version beside panel; agents should prefer panel.query, or panel.sql for complex work. This reference is also `fanout://fanql/reference`.\n") + return b.String() +} + +func referenceKeys[V any](table map[string]V) []string { + keys := make([]string, 0, len(table)) + for key := range table { + keys = append(keys, key) + } + slices.Sort(keys) + return keys +} + +func referenceWords(words []string) string { + quoted := make([]string, len(words)) + for i, word := range words { + quoted[i] = "`" + word + "`" + } + return strings.Join(quoted, ", ") +} + +func referenceCell(text string) string { + return strings.NewReplacer("|", "\\|", "\n", " ", "<", "<", ">", ">").Replace(text) +} + +func referenceMeasureMeaning(name string) string { + switch name { + case "count": + return "Rows; metric observation/point count according to kind." + case "rate": + return "Spans/logs: rows per second over bucket/window. Metrics: coverage-weighted counter increase per second; counters only." + case "error_rate": + return "Spans: percent status:error. Logs: percent severity>=error on normalized rows. Unavailable for metrics." + case "share": + return "Percent of scoped rows in the group; metrics use series population. Standalone only." + case "avg": + return "Numeric average. Metrics: gauge/updown point average; histogram sum/count; counter has no value and reports a diagnosis." + case "min": + return "Minimum numeric value, retaining metric-kind semantics." + case "max": + return "Maximum numeric value, retaining metric-kind semantics." + case "sum": + return "Numeric total; metric counters use increases instead of summing cumulative points." + case "last": + return "Metrics only: kind-aware last value." + case "count_distinct": + return "Distinct values of any field, including string attributes." + case "quantile": + return "Quantile q strictly between 0 and 1; numeric observations or native metric distribution semantics." + default: + return "Registered percentile of numeric observations; metric distributions retain native semantics." + } +} + +var referenceExamples = []string{ + "spans where kind:server | error_rate() by service every 1m", + "spans where service:checkout duration>500ms sort duration limit 50", + "spans where service:$service (status:error or status:unset) | count() by http_route", + "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route", + "spans where kind:server | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex", + "spans | histogram(duration) by service", + "spans where service:checkout status:error -http.target:/healthz | count() by http_route", + "spans where user.id:* | count_distinct(user.id) by service", + "logs where service:api severity:error timeout sort time limit 200", + "logs where severity>=warn | count() by body_template sort count limit 10", + "metrics where name:http.server.requests | rate() by service every 1m", + "metrics where name:k8s.container.restarts | last(value) by resource.k8s.pod.name", } diff --git a/internal/fanql/reference_test.go b/internal/fanql/reference_test.go new file mode 100644 index 00000000..64bc8a52 --- /dev/null +++ b/internal/fanql/reference_test.go @@ -0,0 +1,99 @@ +package fanql + +import ( + "fmt" + "strings" + "testing" + + "github.com/labstack/fanout/internal/panel" + "github.com/labstack/fanout/internal/telemetry" +) + +func TestReferenceCoversEveryRegistryEntry(t *testing.T) { + ref := Reference() + check := func(entry string) { + t.Helper() + if !strings.Contains(ref, "`"+entry+"`") { + t.Errorf("reference omits %q", entry) + } + } + for _, m := range panel.MeasureSpecs() { + check(m.Name) + } + for _, bucket := range panel.BucketNames() { + check(bucket) + } + for _, name := range panel.FilterFunctionNames() { + check(name) + } + for _, signal := range panel.SignalNames() { + columns, _ := panel.SignalColumns(signal) + for _, column := range columns { + if !strings.Contains(ref, "| `"+column.Name+"` | `"+string(column.Type)+"` |") { + t.Errorf("missing %s column %s with type", signal, column.Name) + } + } + } + for _, table := range []map[string]string{statusAliases, kindAliases, typeAliases, telemetry.SeverityAliases()} { + for alias, stored := range table { + check(alias) + check(stored) + } + } + for _, band := range telemetry.SeverityBands { + check(band) + } + for _, op := range []string{":", "=", "!=", "<>", ">", ">=", "<", "<=", "~", "!~", "in", "not in", "between", "not between", "is null", "is not null", "like", "ilike", "not like", "not ilike"} { + check(op) + } + for _, table := range []map[string]bool{sources, clauses, expressionWords, modifiers, reserved} { + for word := range table { + check(word) + } + } +} + +func TestReferenceIsDeterministicAndMarksPreview(t *testing.T) { + ref := Reference() + for range 10 { + if Reference() != ref { + t.Fatal("reference order is unstable") + } + } + if !strings.HasPrefix(ref, fmt.Sprintf("# FanQL %d\n", Version)) || !strings.Contains(ref, "Preview: the syntax may change before GA") { + t.Fatal("missing version/preview") + } +} + +func TestReferenceExamplesCompile(t *testing.T) { + inFence, examples := false, 0 + for _, line := range strings.Split(Reference(), "\n") { + if strings.HasPrefix(line, "```") { + inFence = !inFence + continue + } + if !inFence || strings.TrimSpace(line) == "" { + continue + } + examples++ + if _, problems := Compile(line, Options{}); len(problems) != 0 { + t.Errorf("%q: %+v", line, problems) + } + } + if examples != len(glanceExamples) { + t.Fatalf("got %d examples, want all %d at-a-glance queries", examples, len(glanceExamples)) + } + for _, example := range glanceExamples { + if !strings.Contains(Reference(), example+"\n") { + t.Errorf("missing at-a-glance example %q", example) + } + } +} + +func TestReferenceStatesTheNullRule(t *testing.T) { + for _, rule := range []string{"rows without `k` are excluded; `-k:v` includes them", "SQL spelling, SQL meaning", "a filter that mentions a variable set to All is removed; keep fixed conditions in their own terms", "no stored log row bypasses", "root service", "root duration", "nullif", "256 tokens", "24 aggregates"} { + if !strings.Contains(Reference(), rule) { + t.Errorf("missing rule %q", rule) + } + } +} diff --git a/scripts/go-deadcode.allowlist b/scripts/go-deadcode.allowlist index 39a69e4d..2f9a0af1 100644 --- a/scripts/go-deadcode.allowlist +++ b/scripts/go-deadcode.allowlist @@ -1,5 +1,3 @@ # Exact symbolreviewed reason for genuine non-main entry points only. github.com/labstack/fanout/internal/auth.OAuthTokenPair.String fmt.Stringer security boundary: formatting token pairs must redact both credentials; not a callable product action. github.com/labstack/fanout/internal/fanql.expectAt Completion parser contract seam for token and expected-class fixtures; Complete shares its underlying context parser to avoid parsing twice. -github.com/labstack/fanout/internal/panel.LowCardinalityColumns FanQL completion/reference library entry point; production consumers land in batch 1 Tasks 7–10. -github.com/labstack/fanout/internal/telemetry.SeverityAliases Shared FanQL vocabulary/reference library entry point; production consumers land in batch 1 Tasks 8–10. diff --git a/scripts/site-tables.test.ts b/scripts/site-tables.test.ts new file mode 100644 index 00000000..f65531c0 --- /dev/null +++ b/scripts/site-tables.test.ts @@ -0,0 +1,32 @@ +import { afterEach, expect, test } from "bun:test"; +import { copyFileSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +const roots: string[] = []; +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +function check(html: string) { + const root = mkdtempSync(join(tmpdir(), "fanout-site-tables-")); + roots.push(root); + mkdirSync(join(root, "scripts")); + mkdirSync(join(root, "dist")); + const script = join(root, "scripts/check-tables.mjs"); + copyFileSync(resolve(import.meta.dir, "../site/scripts/check-tables.mjs"), script); + writeFileSync(join(root, "dist/reference.html"), html); + return Bun.spawnSync([process.execPath, script]); +} + +test("table checker accepts Markdown whitespace inside a scroll wrapper", () => { + const result = check('
' + "\n".repeat(300) + "
field
"); + expect(result.exitCode).toBe(0); + expect(result.stdout.toString()).toContain("1 table(s) across 1 page(s), all wrapped"); +}); + +test("table checker rejects a bare table after a closed scroll wrapper", () => { + const result = check('
' + "\n".repeat(300) + "
field
"); + expect(result.exitCode).toBe(1); + expect(result.stderr.toString()).toContain("reference.html: 1 of 1"); +}); diff --git a/site/scripts/check-tables.mjs b/site/scripts/check-tables.mjs index 748dea86..de76b92e 100644 --- a/site/scripts/check-tables.mjs +++ b/site/scripts/check-tables.mjs @@ -38,7 +38,10 @@ function unwrappedTables(html) { for (;;) { const at = html.indexOf("` | SQL inequality, equivalent to `!=`; missing values are excluded. | +| `>` | Greater than; missing values are excluded. | +| `>=` | Greater than or equal; missing values are excluded. | +| `<` | Less than; missing values are excluded. | +| `<=` | Less than or equal; missing values are excluded. | +| `~` | Case-insensitive substring; `%` and `_` are ordinary characters. | +| `!~` | Null-inclusive substring exclusion, like `-k ~ v`. | +| `in` | Membership in a nonempty list or multi-value variable; missing values are excluded. | +| `not in` | SQL spelling, SQL meaning: missing values are excluded; prefix `-` includes them. | +| `between` | Inclusive lower and upper bounds separated by `and`; missing values are excluded. | +| `not between` | SQL spelling, SQL meaning: missing values are excluded; prefix `-` includes them. | +| `is null` | Matches missing values, canonical `-k:*`. | +| `is not null` | Matches present values, canonical `k:*`. | +| `like` | Case-sensitive SQL pattern; requires quoted text; `%` and `_` are wildcards. | +| `ilike` | Case-insensitive SQL pattern; requires quoted text. | +| `not like` | SQL spelling, SQL meaning: missing values are excluded; prefix `-` includes them. | +| `not ilike` | SQL spelling, SQL meaning: missing values are excluded; prefix `-` includes them. | + +Prefix `-` or `not` excludes a term and includes rows where its predicate is NULL. Repeated negation cancels in pairs. SQL operators retain SQL null behavior. Compound negation follows De Morgan's law. TRY_CAST failures are NULL, so `-http_status_code between 400 and 599` includes uncastable codes. + +Whitespace and `and` join filters. An `or` chain must occupy its whole filter list or be parenthesized: `a:1 (b:2 or c:3)` and `(a:1 b:2) or c:3` differ. This rule also applies inside groups and `count_if`. Mixing conjunction and `or` without parentheses is a problem with suggested repairs. + +## Fields + +A single identifier is a source column when one exists, otherwise an attribute key with a notice. Dotted `http.target` means `attributes['http.target']`; `resource.k8s.pod.name` means `resource['k8s.pod.name']`. Explicit `attributes.` uses the attributes map. Bracket keys are literal nonempty strings, including spaces, Unicode, punctuation and doubled quotes. Keys beginning `resource.` or `attributes.` retain brackets where needed to preserve the map. + +Canonical text brackets single-segment attribute keys, so new columns cannot reinterpret canonical or stored text. Map columns require a key. `duration` denotes `duration_ms` in filters, measure arguments and trace sorts. `duration_ms>500` takes a number; `duration>500ms` requires a unit. A measure alias named duration or duration_ms stays that alias in sort. Time columns accept range comparisons against quoted timestamps, not equality shorthand. + +### spans + +| Name | Type | Unit | Low cardinality | Description | +|---|---|---|---|---| +| `namespace` | `string` | `none` | | OpenTelemetry service namespace | +| `service` | `string` | `none` | yes | Service name | +| `operation` | `string` | `none` | | Span name | +| `kind` | `string` | `none` | yes | SPAN_KIND_SERVER, SPAN_KIND_CLIENT, SPAN_KIND_INTERNAL, SPAN_KIND_PRODUCER or SPAN_KIND_CONSUMER | +| `status` | `string` | `none` | yes | STATUS_CODE_OK, STATUS_CODE_ERROR or STATUS_CODE_UNSET | +| `status_message` | `string` | `none` | | Status description | +| `trace_id` | `string` | `none` | | Trace identifier | +| `span_id` | `string` | `none` | | Span identifier | +| `parent_span_id` | `string` | `none` | | Parent span identifier; empty for roots | +| `start_time` | `time` | `none` | | Span start | +| `end_time` | `time` | `none` | | Span end | +| `duration_ms` | `number` | `ms` | | Span duration in milliseconds | +| `http_method` | `string` | `none` | yes | HTTP method | +| `http_status_code` | `string` | `none` | | HTTP response status code as text | +| `http_route` | `string` | `none` | | HTTP route template | +| `db_system` | `string` | `none` | yes | Database system, e.g. postgresql, redis | +| `rpc_method` | `string` | `none` | | RPC method | +| `rpc_service` | `string` | `none` | | RPC service | +| `peer_service` | `string` | `none` | | Remote service named by the caller | +| `service_version` | `string` | `none` | yes | service.version resource attribute | +| `deployment_env` | `string` | `none` | yes | deployment.environment resource attribute | +| `exception_type` | `string` | `none` | | Exception type from the span's exception event | +| `exception_message` | `string` | `none` | | Exception message | +| `messaging_system` | `string` | `none` | yes | messaging.system attribute | +| `messaging_destination` | `string` | `none` | | messaging.destination.name attribute | +| `scope_name` | `string` | `none` | | Instrumentation scope | +| `attributes` | `map` | `none` | | Span attributes; use attributes['key'] | +| `resource` | `map` | `none` | | Resource attributes; use resource['key'] | + +### logs + +| Name | Type | Unit | Low cardinality | Description | +|---|---|---|---|---| +| `namespace` | `string` | `none` | | OpenTelemetry service namespace | +| `service` | `string` | `none` | yes | Service name | +| `time` | `time` | `none` | | Log time | +| `severity` | `string` | `none` | yes | Severity text, e.g. ERROR, WARN, INFO | +| `severity_number` | `number` | `none` | | OpenTelemetry severity number; 17 and above is an error | +| `body` | `string` | `none` | | Redacted log body | +| `body_template` | `string` | `none` | | Body with variable parts replaced by <*>; groups similar messages | +| `trace_id` | `string` | `none` | | Trace identifier | +| `span_id` | `string` | `none` | | Span identifier | +| `scope_name` | `string` | `none` | | Instrumentation scope | +| `attributes` | `map` | `none` | | Log attributes; use attributes['key'] | +| `resource` | `map` | `none` | | Resource attributes; use resource['key'] | + +### metrics + +| Name | Type | Unit | Low cardinality | Description | +|---|---|---|---|---| +| `namespace` | `string` | `none` | | OpenTelemetry service namespace | +| `service` | `string` | `none` | yes | Service name | +| `time` | `time` | `none` | | Data point time | +| `name` | `string` | `none` | | Metric name | +| `unit` | `string` | `none` | | Metric unit as reported | +| `type` | `string` | `none` | yes | gauge, counter, updown, histogram or summary | +| `temporality` | `string` | `none` | yes | cumulative or delta; empty for gauge and summary | +| `start_time` | `time` | `none` | | Data point start time; NULL when absent | +| `value` | `number` | `none` | | Gauge or sum value | +| `hist_count` | `number` | `count` | | Histogram point count | +| `hist_sum` | `number` | `none` | | Histogram point sum | +| `attributes` | `map` | `none` | | Data point attributes; use attributes['key'] | +| `resource` | `map` | `none` | | Resource attributes; use resource['key'] | + +`http_status_code` is text. `<`, `<=`, `>`, `>=` and `between` use `TRY_CAST(http_status_code AS INTEGER)` for literals and variables alike. Equality and membership stay text, so `http_status_code:500` means `'500'`. + +## Vocabularies and severity + +Aliases apply under equality, inequality and membership, including prefix negation. Quoted values, contains, SQL patterns and function arguments are literal. Stored spellings are also accepted bare. + +### status (spans) + +| Input | Stored | +|---|---| +| `error` | `STATUS_CODE_ERROR` | +| `ok` | `STATUS_CODE_OK` | +| `unset` | `STATUS_CODE_UNSET` | + +### kind (spans) + +| Input | Stored | +|---|---| +| `client` | `SPAN_KIND_CLIENT` | +| `consumer` | `SPAN_KIND_CONSUMER` | +| `internal` | `SPAN_KIND_INTERNAL` | +| `producer` | `SPAN_KIND_PRODUCER` | +| `server` | `SPAN_KIND_SERVER` | +| `unspecified` | `SPAN_KIND_UNSPECIFIED` | + +### type (metrics) + +| Input | Stored | +|---|---| +| `counter` | `counter` | +| `gauge` | `gauge` | +| `histogram` | `histogram` | +| `summary` | `summary` | +| `updown` | `updown` | + +### severity (logs) + +| Input | Stored | +|---|---| +| `alert` | `FATAL` | +| `crit` | `FATAL` | +| `critical` | `FATAL` | +| `dbg` | `DEBUG` | +| `debug` | `DEBUG` | +| `emerg` | `FATAL` | +| `emergency` | `FATAL` | +| `err` | `ERROR` | +| `error` | `ERROR` | +| `exception` | `ERROR` | +| `fatal` | `FATAL` | +| `fine` | `DEBUG` | +| `finest` | `TRACE` | +| `info` | `INFO` | +| `information` | `INFO` | +| `informational` | `INFO` | +| `notice` | `INFO` | +| `panic` | `FATAL` | +| `severe` | `ERROR` | +| `trace` | `TRACE` | +| `verbose` | `TRACE` | +| `warn` | `WARN` | +| `warning` | `WARN` | + +Severity bands, lowest first: `TRACE`, `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`. `unspecified` maps to `UNSPECIFIED`; unknown names are uppercased. Trailing digits are dropped (`INFO2` becomes `INFO`). Unknown severity is legal for equality; sampled stored levels may provide a notice. Unknown status or kind aliases are problems. + +Every stored log severity is normalized once: a positive severity number has authority (21+ FATAL, 17+ ERROR, 13+ WARN, 9+ INFO, 5+ DEBUG, 1+ TRACE); absent/nonpositive numbers fall back to text. Invariant: no stored log row bypasses normalization. Severity ranges expand to contiguous band membership, never CASE. `severity>=warn` means WARN, ERROR, FATAL; `severity=14` for sublevels. Empty or reversed ranges are problems. + +On normalized log rows, `error_rate()` counts exactly `severity>=error`. Its backend test is `upper(severity) IN ('ERROR', 'FATAL', 'CRITICAL') OR severity_number >= 17`; normalization makes legacy CRITICAL redundant. Span `error_rate()` counts `status:error`. + +## Literals and durations + +| Literal | Rule | +|---|---| +| String | Bare words or single/double quotes; double a quote to escape it. Quoted values are strings and bypass aliases. | +| Number | Integers, decimals and exponents (`500`, `1.5`, `2e3`, `-3`); non-finite values are rejected. Numbers stay numeric on number columns and attributes, and stay text as typed on string columns. | +| Boolean | Bare `true`/`false`, case-insensitive; attributes retain boolean type, string columns compare text, number columns reject them. | +| Duration | `us`, `ms`, `s`, `m`, `h`, only on `duration`; converted to milliseconds. Examples: `500ms`, `1.5s`, `250us`, `2m`, `1h`. Negative, compound and overflowing durations are rejected. | +| Timestamp | Quoted RFC 3339 or `YYYY-MM-DD HH:MM:SS`, optional fraction/offset; no offset means UTC. Time comparisons retain nanoseconds through TIMESTAMPTZ_NS. | +| Existence | `k:*` is IS NOT NULL; `-k:*` is IS NULL. | +| Free text | Case-insensitive substring of log body or span operation; explicit field required on metrics. | + +Contains emits `contains(lower(field), lower(value))`; map values first cast to VARCHAR. SQL LIKE/ILIKE require quoted patterns; ESCAPE is not expressible, so use `~` when `%` should be literal. + +## Buckets + +`auto`, `10s`, `30s`, `1m`, `5m`, `10m`, `15m`, `30m`, `1h`, `3h`, `6h`, `12h`, `1d`. `auto` lets the engine choose an interval. A bucket follows `every` and belongs to an aggregate query. + +## Measures + +The registry defines accepted functions and signal availability. Fields follow the filter/grouping resolution rules. Numeric attribute measures use TRY_CAST AS DOUBLE; nonnumeric values become NULL. `count(*)` canonicalizes to `count()`. + +| Name | Form | Signals | Unit | Semantics | +|---|---|---|---|---| +| `avg` | `avg(f)` | spans, logs, metrics | field unit | Numeric average. Metrics: gauge/updown point average; histogram sum/count; counter has no value and reports a diagnosis. | +| `count` | `count()` | spans, logs, metrics | count | Rows; metric observation/point count according to kind. | +| `count_distinct` | `count_distinct(f)` | spans, logs, metrics | count | Distinct values of any field, including string attributes. | +| `error_rate` | `error_rate()` | spans, logs | percent | Spans: percent status:error. Logs: percent severity>=error on normalized rows. Unavailable for metrics. | +| `last` | `last(f)` | metrics | field unit | Metrics only: kind-aware last value. | +| `max` | `max(f)` | spans, logs, metrics | field unit | Maximum numeric value, retaining metric-kind semantics. | +| `min` | `min(f)` | spans, logs, metrics | field unit | Minimum numeric value, retaining metric-kind semantics. | +| `p50` | `p50(f)` | spans, logs, metrics | field unit | Registered percentile of numeric observations; metric distributions retain native semantics. | +| `p75` | `p75(f)` | spans, logs, metrics | field unit | Registered percentile of numeric observations; metric distributions retain native semantics. | +| `p90` | `p90(f)` | spans, logs, metrics | field unit | Registered percentile of numeric observations; metric distributions retain native semantics. | +| `p95` | `p95(f)` | spans, logs, metrics | field unit | Registered percentile of numeric observations; metric distributions retain native semantics. | +| `p99` | `p99(f)` | spans, logs, metrics | field unit | Registered percentile of numeric observations; metric distributions retain native semantics. | +| `quantile` | `quantile(f, q)` | spans, logs, metrics | field unit | Quantile q strictly between 0 and 1; numeric observations or native metric distribution semantics. | +| `rate` | `rate()` | spans, logs, metrics | per_second | Spans/logs: rows per second over bucket/window. Metrics: coverage-weighted counter increase per second; counters only. | +| `share` | `share()` | spans, logs, metrics | percent | Percent of scoped rows in the group; metrics use series population. Standalone only. | +| `sum` | `sum(f)` | spans, logs, metrics | field unit | Numeric total; metric counters use increases instead of summing cumulative points. | + +Metric aggregates require a standalone `name:` equality entry. Counters use per-series increases and reset handling; gauge/updown use point values; histograms use observation counts, sums and buckets; summaries use available stored aggregates. Unsupported kind/function combinations report a diagnosis instead of treating counters as gauges. + +`histogram(duration)` on spans uses count with log2 duration buckets; `histogram(value)` on metrics uses explicit histogram buckets. Distributions stand alone, with at most one `by` field for a histogram; `every` selects a heatmap. + +## Expressions and ranking + +`count_if(filters)` takes a FanQL filter list as one entry and compiles to checked `count(*) FILTER (WHERE ...)::DOUBLE`. Raw entries are allowed; variables are forbidden. Spans and logs support `+ - * /`, constants, unary minus and parentheses on aggregate vizzes. Metrics, distributions and log_patterns do not support arithmetic. Every expression needs at least one aggregate. Other than a single call, an expression requires `as alias`; aliases are 1–40 lowercase letters/digits/underscores and start with a letter. `share()` stands alone. Division emits `a / nullif(b, 0)`, so zero denominators yield NULL. + +Count-family ratios use ratio units, `* 100` makes percent, addition/subtraction retains equal units, scaling retains the measure unit, other combinations use none. Expressions are not additive. Affine transformations inherit the underlying ranking and flip direction for a negative scale. Binomial count_if/count ratios use Wilson ranking with a 20-sample floor; other expressions use value ranking with leaf/denominator support. Ineligible series follow eligible ones by support, then dimension; result metadata discloses them. + +Apdex uses disjoint predicates: `(count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex`. Exactly 500 ms counts once; NULL duration counts in the population and neither numerator. + +Each measure allows 256 tokens, 64 nodes, depth 8 and 8 aggregates. A query allows 256 expression nodes and 24 aggregates across at most 6 measures. A count_if filter is at most 500 bytes. Whitespace is not a token. Budgets apply to structured inputs too. + +## Filter functions and raw entries + +| Function | Signature | +|---|---| +| `contains` | `contains(field, quoted_string)` | +| `length` | `length(field)` | +| `lower` | `lower(field)` | +| `regexp_matches` | `regexp_matches(field, quoted_string)` | +| `starts_with` | `starts_with(field, quoted_string)` | +| `upper` | `upper(field)` | + +`lower`, `upper` and `length` need a comparison. `starts_with`, `contains` and `regexp_matches` are predicates alone. Calls have no space before `(`. Variables may compare call results, but remain forbidden inside count_if. + +A backtick-delimited raw entry passes SQL to the existing filter gate; double a backtick to include it. A whole raw entry retains its stored spelling; raw fragments composed with other predicates are parenthesized. The gate accepts columns, literal `attributes['k']`/`resource['k']`, comparisons, boolean logic, IN, LIKE, IS NULL, BETWEEN, coalesce, variables, the filter functions above and casts to VARCHAR, BIGINT, INTEGER, DOUBLE, BOOLEAN, UBIGINT and TIMESTAMPTZ_NS. It rejects CASE, DISTINCT, ORDER BY and FILTER inside functions, qualified columns, subqueries and other functions. Raw cannot bypass the gate. + +## Variables and entry boundaries + +`$name` is a dashboard variable; `$__` names are reserved. It stays a parameter, never a string literal. `k in $multi` accepts multiple values; scalar operators reject multi variables. Without declarations, references produce notices so editing can continue; execution checks them. + +All rule: a filter that mentions a variable set to All is removed; keep fixed conditions in their own terms. An empty variable list makes its entry FALSE. Top-level terms are separate entries; a parenthesized group, raw entry or OR chain is one entry. Stored order and boundaries survive formatting. + +| Filters | Entries | `$service` = All | +|---|---|---| +| `service:$service status:error` | 2 | Keep status. | +| `(service:$service status:error)` | 1 | Drop both. | +| `service:$service or service:worker` | 1 | Drop whole entry. | +| `service:$service (status:error or status:unset)` | 2 | Keep status group. | +| `-service:$service` | 1 | Drop entry; nothing excluded. | +| Raw SQL mentioning `$service` | 1 | Drop whole entry. | +| `count_if(service:$service)` | n/a | Rejected. | + +## Visualization and trace semantics + +Logs/traces use logs/spans respectively and forbid measures, grouping, buckets and histogram. Log_patterns uses `count() by body_template`, optionally a bucket. Timeseries needs a bucket and at most one grouping field, with one measure when grouped. Tables allow three grouping fields; bars two, with one measure when grouped by two. Stat/gauge need one measure and no grouping/bucket; gauge needs min/max. Scatter needs two measures and one or two grouping fields. State_timeline needs one measure, one grouping field, a bucket and thresholds. + +Traces are `(namespace, trace_id)` candidates with at least one matching span in the window, ranked by matching spans' max(duration_ms), or min(start_time) for `sort +start`. Limit applies to candidates; the engine reads at most 1,001 for truncation detection. Each returns one root span, or its earliest span in the window if the root is outside it, with error status if any span in the trace errored. Displayed service and duration are root service and root duration. A child can match while the returned root has different values. + +Trace sorts: descending `duration` (stored duration_ms), `errors`, or ascending `+start`. `sort errors` is the legacy combined key: it also filters to error spans, then orders by duration. Prefer `status:error` with `sort duration`. Logs sort by `time` or `+time`; log_patterns by `count`. Aggregate sorts name a measure alias. Default/desc is descending; +/asc is ascending; choose one direction. Bucketed families use time order and options.top for series selection; sort/limit are accepted with a notice when ignored. + +## Reserved words and foreign syntax + +`compare`, `correlate`, `eval`, `extend`, `fields`, `having`, `join`, `let`, `over`, `rename`, `since`, `top`, `until`, `window` are reserved at clause positions. Quote them to search for the word. Foreign syntax gets a diagnostic and FanQL hint, never an alias; an ordinary foreign word in filter position stays free text. + +Recognized foreign stages: `eval`, `extend`, `fields`, `head`, `order`, `project`, `rename`, `select`, `sort`, `stats`, `summarize`, `take`, `top`. Foreign call shapes: `bin`, `cardinality`, `count_over_time`, `dc`, `distinct_count`, `mean`, `median`, `pct`, `perc95`, `percentile`, `quantile_over_time`, `span`. `from`, `index=`, `source=`, first-token `search`, `ago(`, `now(`, `earliest=`, `_time:`, `order by`, `group by`, `facet`, `==`, `=~`, `|=`, `|~`, `::`, selectors and `@field:` get targeted hints. Time ranges belong to the time picker. + +## Bounds and diagnostics + +Interactive text allows 4,000 code points and 8,192 bytes, 1,024 tokens, 512 AST nodes, nesting depth 16 and lists of 100 values. Queries lower to 16 entries of 500 bytes each, 6 measures and 3 grouping fields, further constrained by the viz. Completion returns at most 50 items. Problems have code-point spans and optional fix-its, follow source order and are capped at 20 plus a final more-problems diagnostic. Any problem prevents execution; requested repair previews are labeled not executable. + +Format returns complete text and exactness `exact` or `normalized`, with notices for normalization. Raw preserves whole SQL entries. Editable canonical text reparses under its tier without merging entries. Beyond any interactive bound, `editable: false` carries a reason and complete text; the envelope must preserve the original query and consumers must not parse the oversized text. + +## Examples + +```fanql +spans where kind:server | error_rate() by service every 1m +spans where service:checkout duration>500ms sort duration limit 50 +spans where service:$service (status:error or status:unset) | count() by http_route +spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route +spans where kind:server | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex +spans | histogram(duration) by service +spans where service:checkout status:error -http.target:/healthz | count() by http_route +spans where user.id:* | count_distinct(user.id) by service +logs where service:api severity:error timeout sort time limit 200 +logs where severity>=warn | count() by body_template sort count limit 10 +metrics where name:http.server.requests | rate() by service every 1m +metrics where name:k8s.container.restarts | last(value) by resource.k8s.pod.name +``` + +## Versioning and transport + +The language version is separate from product CalVer and the panel contract. Machine text inputs carry the FanQL version plus visualization, time, comparison, declarations, resolved values, namespace and options as needed. The structured query is required when editable is false. Panels keep storing queries, never text. Unsupported versions produce unsupported_fanql_version. + +A version bump is required when accepted text changes meaning or stops parsing, including columns that reinterpret bare identifiers and severity aliases that reinterpret accepted literals. New status/kind aliases that were errors, stage words and filter functions are additive. Canonical spelling is frozen per version; preview changes can rewrite through the shared structured query. + +HTTP exposes `/api/fanql/parse`, `/api/fanql/format`, `/api/fanql/complete` and `/api/fanql/reference?version=1`, requiring telemetry:read. MCP query_telemetry accepts text with fanql_version beside panel; agents should prefer panel.query, or panel.sql for complex work. This reference is also `fanout://fanql/reference`. From 836324c810a84203f3c7d16ea2cca8c518dcb384 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 17:12:51 -0700 Subject: [PATCH 14/30] test(fanql): corpus, round-trip, truth-table, fuzz and latency acceptance --- internal/api/fanql_corpus_test.go | 114 + internal/fanql/bounds_test.go | 160 + internal/fanql/corpus_test.go | 155 + internal/fanql/fuzz_test.go | 233 + internal/fanql/instrumentation_plain_test.go | 5 + internal/fanql/instrumentation_race_test.go | 5 + internal/fanql/latency_test.go | 179 + internal/fanql/lift.go | 55 +- internal/fanql/parser.go | 68 +- internal/fanql/print.go | 83 +- internal/fanql/registry_growth_test.go | 113 + internal/fanql/resolve.go | 16 +- internal/fanql/review_test.go | 82 + internal/fanql/roundtrip_test.go | 476 ++ internal/fanql/semantics_test.go | 472 ++ internal/fanql/testdata/canonical.v1.golden | 414 + internal/fanql/testdata/corpus.txt | 7534 +++++++++++++++++ .../fuzz/FuzzFormatRoundTrip/literal_backtick | 2 + .../FuzzFormatRoundTrip/literal_group_key | 2 + .../fuzz/FuzzFormatRoundTrip/raw_negation | 2 + .../fuzz/FuzzLexParsePrint/72518d1cde34436d | 2 + .../fuzz/FuzzLexParsePrint/ac80e7dae538a502 | 2 + .../fuzz/FuzzLexParsePrint/aca3db284bc204d2 | 2 + .../fuzz/FuzzLexParsePrint/astral_diagnostic | 2 + .../fuzz/FuzzLexParsePrint/b4c83d8eaed5ec0b | 2 + .../embedded_variable_character | 2 + .../fuzz/FuzzLexParsePrint/quoted_wildcard | 2 + .../FuzzLexParsePrint/raw_boolean_fragment | 2 + internal/fanql/testhelpers_test.go | 2 +- internal/panel/filter.go | 2 +- 30 files changed, 10138 insertions(+), 52 deletions(-) create mode 100644 internal/api/fanql_corpus_test.go create mode 100644 internal/fanql/bounds_test.go create mode 100644 internal/fanql/corpus_test.go create mode 100644 internal/fanql/fuzz_test.go create mode 100644 internal/fanql/instrumentation_plain_test.go create mode 100644 internal/fanql/instrumentation_race_test.go create mode 100644 internal/fanql/latency_test.go create mode 100644 internal/fanql/registry_growth_test.go create mode 100644 internal/fanql/roundtrip_test.go create mode 100644 internal/fanql/semantics_test.go create mode 100644 internal/fanql/testdata/canonical.v1.golden create mode 100644 internal/fanql/testdata/corpus.txt create mode 100644 internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/literal_backtick create mode 100644 internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/literal_group_key create mode 100644 internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/raw_negation create mode 100644 internal/fanql/testdata/fuzz/FuzzLexParsePrint/72518d1cde34436d create mode 100644 internal/fanql/testdata/fuzz/FuzzLexParsePrint/ac80e7dae538a502 create mode 100644 internal/fanql/testdata/fuzz/FuzzLexParsePrint/aca3db284bc204d2 create mode 100644 internal/fanql/testdata/fuzz/FuzzLexParsePrint/astral_diagnostic create mode 100644 internal/fanql/testdata/fuzz/FuzzLexParsePrint/b4c83d8eaed5ec0b create mode 100644 internal/fanql/testdata/fuzz/FuzzLexParsePrint/embedded_variable_character create mode 100644 internal/fanql/testdata/fuzz/FuzzLexParsePrint/quoted_wildcard create mode 100644 internal/fanql/testdata/fuzz/FuzzLexParsePrint/raw_boolean_fragment diff --git a/internal/api/fanql_corpus_test.go b/internal/api/fanql_corpus_test.go new file mode 100644 index 00000000..d852047e --- /dev/null +++ b/internal/api/fanql_corpus_test.go @@ -0,0 +1,114 @@ +package api + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" + + "github.com/labstack/fanout/internal/auth" + "github.com/labstack/fanout/internal/fanql" + "github.com/labstack/fanout/internal/panel" +) + +type nonExecutingFanQLPanels struct { + fakePanels + calls int +} + +func (p *nonExecutingFanQLPanels) Run(context.Context, panel.RunRequest) ([]panel.Result, error) { + p.calls++ + return nil, fmt.Errorf("FanQL parsing must not execute telemetry") +} + +func TestNonExecution(t *testing.T) { + file, err := os.Open("../fanql/testdata/corpus.txt") + if err != nil { + t.Fatal(err) + } + defer file.Close() + + s := newTestAuthServer(t) + if _, err := s.users.CreateWithAudit("admin@example.com", "", "admin", auth.AuditEvent{EventType: "user.created", Outcome: "success"}); err != nil { + t.Fatal(err) + } + viewer, err := s.users.CreateWithAudit("viewer@example.com", "", "viewer", auth.AuditEvent{EventType: "user.created", Outcome: "success"}) + if err != nil { + t.Fatal(err) + } + cookie := s.login(t, viewer) + engine := &nonExecutingFanQLPanels{} + RegisterFanQLRoutes(s.e, nil, engine) + + decoder := json.NewDecoder(file) + negative := 0 + for fixture := 0; ; fixture++ { + var tc struct { + Text string `json:"text"` + Viz string `json:"viz"` + Query *panel.Query `json:"query"` + Problems panel.Problems `json:"problems"` + GateProblems bool `json:"gate_problems"` + } + if err := decoder.Decode(&tc); err == io.EOF { + break + } else if err != nil { + t.Fatalf("corpus fixture %d: %v", fixture, err) + } + // Raw SQL rejected only by the existing execution gate is clean FanQL. + // The parse route must retain the same Compile-only contract. + if tc.Query != nil || len(tc.Problems) == 0 || tc.GateProblems { + continue + } + negative++ + t.Run(fmt.Sprintf("%d/%s", fixture, tc.Text), func(t *testing.T) { + compiled, problems := fanql.Compile(tc.Text, fanql.Options{Viz: tc.Viz}) + if compiled != nil || len(problems) == 0 { + t.Fatalf("negative corpus text became executable: %+v %+v", compiled, problems) + } + for _, preview := range []bool{false, true} { + input, err := json.Marshal(map[string]any{"version": fanql.Version, "text": tc.Text, "viz": tc.Viz, "preview": preview}) + if err != nil { + t.Fatal(err) + } + req := sessionRequest(http.MethodPost, "/api/fanql/parse", strings.NewReader(string(input)), cookie) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + s.e.ServeHTTP(rec, req) + var body map[string]json.RawMessage + fanqlResponse(t, rec, http.StatusBadRequest, &body) + if string(body["code"]) != `"invalid_fanql"` || body["problems"] == nil { + t.Fatalf("preview=%t: wrong error contract: %s", preview, rec.Body) + } + if _, exists := body["query"]; exists { + t.Fatalf("preview=%t: problem response contains executable query: %s", preview, rec.Body) + } + if preview { + var got struct { + Text string `json:"text"` + Note string `json:"note"` + } + if err := json.Unmarshal(body["preview"], &got); err != nil { + t.Fatal(err) + } + if got.Text != tc.Text || got.Note != "not executable" { + t.Fatalf("preview lost authored text or execution warning: %s", rec.Body) + } + } else if _, exists := body["preview"]; exists { + t.Fatalf("unrequested preview: %s", rec.Body) + } + } + }) + } + if negative == 0 { + t.Fatal("corpus has no non-executable texts") + } + if engine.calls != 0 { + t.Fatalf("parse executed %d telemetry queries", engine.calls) + } +} diff --git a/internal/fanql/bounds_test.go b/internal/fanql/bounds_test.go new file mode 100644 index 00000000..cc6c96fc --- /dev/null +++ b/internal/fanql/bounds_test.go @@ -0,0 +1,160 @@ +package fanql + +import ( + "reflect" + "strings" + "testing" + + "github.com/labstack/fanout/internal/panel" +) + +func TestEachInteractiveBoundIndependently(t *testing.T) { + for _, tc := range []struct { + name, text, want string + compile bool + }{ + {"characters", strings.Repeat("a", 4001), "a query is at most 4000 characters (8192 bytes)", false}, + {"bytes", strings.Repeat("𝔘", 2049), "a query is at most 4000 characters (8192 bytes)", false}, + {"tokens", "logs where " + strings.Repeat("k:0 ", 342), "a query is at most 1024 tokens", false}, + {"nodes", "logs " + strings.Repeat("a ", 513), "a query is at most 512 nodes", false}, + {"depth", "logs where " + strings.Repeat("(", 17) + "body:x" + strings.Repeat(")", 17), "a query has at most 16 levels of nesting depth", false}, + {"entries", "logs where " + strings.Repeat("body:x ", 17), "at most 16 filters", true}, + {"entry_bytes", `logs where body:"` + strings.Repeat("x", 492) + `"`, "this filter lowers to 501 bytes; filters are at most 500", true}, + {"list", "logs where k in (" + strings.Repeat("0,", 100) + "0)", "an in list is at most 100 values", true}, + } { + t.Run(tc.name, func(t *testing.T) { + var problems panel.Problems + if tc.compile { + compiled, ps := Compile(tc.text, Options{}) + if compiled != nil { + t.Fatal("bound produced an executable query") + } + problems = ps + } else { + parsed, ps := Parse(tc.text, "") + if parsed != nil { + t.Fatal("bound produced a parsed query") + } + problems = ps + } + if len(problems) != 1 || problems[0].Message != tc.want || problems[0].Span == nil { + t.Fatalf("got %+v; want one positioned %q", problems, tc.want) + } + }) + } +} + +func TestAstralCharactersSpanInCodePoints(t *testing.T) { + const text = `logs where body:"𝔘𝔫𝔦" x:1` + parsed, ps := Parse(text, "") + if len(ps) != 0 || parsed == nil || len(parsed.Where) != 2 { + t.Fatal(parsed, ps) + } + if got := parsed.Where[1].Span(); got != (Span{Start: 22, End: 25}) { + t.Fatalf("second term span = %+v", got) + } + _, ps = Parse(text+" +", "") + if len(ps) != 1 || ps[0].Message != "unexpected +" || ps[0].Span == nil || *ps[0].Span != (panel.TextSpan{Start: 26, End: 27}) { + t.Fatalf("diagnostic after astral text = %+v", ps) + } +} + +func TestParseColonRecoveryAcrossWhitespace(t *testing.T) { + for _, text := range []string{`""A: 0:0`, `logs where service: api:x`, `logs where attributes['user name']: 'a b':c`} { + q, problems := Parse(text, "") + if q != nil || len(problems) == 0 { + t.Fatalf("malformed colon input accepted: %q", text) + } + found := false + for _, problem := range problems { + if problem.Span == nil || problem.Span.Start < 0 || problem.Span.End < problem.Span.Start || problem.Span.End > len([]rune(text)) { + t.Fatalf("invalid diagnostic span: %+v", problem) + } + if strings.HasPrefix(problem.Message, "unexpected : after ") { + found = true + } + } + if !found { + t.Fatalf("missing colon diagnostic for %q: %+v", text, problems) + } + } +} + +func TestParseQuotedTokensStayLiteral(t *testing.T) { + for _, tc := range []struct { + text string + entries int + }{ + {`logs 0 And in`, 2}, + {`logs where 0 "in"`, 2}, + {`logs where body "="`, 2}, + {`logs where body ":"`, 2}, + {`logs where body ">"`, 2}, + {`logs where body "!="`, 2}, + {`logs where body "~"`, 2}, + {`logs where body "!~"`, 2}, + {`logs where body "between"`, 2}, + {`logs where body "like"`, 2}, + {`logs where body "not" "in"`, 3}, + {`logs where body "is" "null"`, 3}, + {`logs where body "("`, 2}, + {`logs where body ")"`, 2}, + {`logs where body "|"`, 2}, + {`logs where service:api"*"`, 2}, + {`logs where service"*"`, 2}, + {`logs where starts_with(body, "x") "="`, 2}, + {`logs where (body "(")`, 1}, + {`logs where service:">"`, 1}, + {`logs where service:"="`, 1}, + {`logs where service:"<>"`, 1}, + } { + t.Run(tc.text, func(t *testing.T) { + compiled, problems := Compile(tc.text, Options{}) + if len(problems) != 0 || compiled == nil { + t.Fatalf("literal became syntax: %+v", problems) + } + if len(compiled.Query.Where) != tc.entries { + t.Fatalf("got %d entries, want %d", len(compiled.Query.Where), tc.entries) + } + again, problems := Compile(compiled.Canonical, Options{}) + if len(problems) != 0 || again == nil { + t.Fatalf("canonical %q: %+v", compiled.Canonical, problems) + } + if compiled.Canonical != again.Canonical || !reflect.DeepEqual(compiled.Query, again.Query) { + t.Fatalf("not a fixed point: %q -> %q", compiled.Canonical, again.Canonical) + } + }) + } + if q, ps := Parse(`logs | count"(")`, ""); q != nil || len(ps) == 0 { + t.Fatal("quoted parenthesis opened a measure call") + } +} + +func TestParseCallsRequireAnIdentifierAndAdjacentParenthesis(t *testing.T) { + for _, text := range []string{`spAns 0 -(0 0)`, `logs foo (bar baz)`, `logs 0 (foo bar)`, `logs 0(foo bar)`, `logs api-worker (a b)`, `logs user.name (a b)`} { + t.Run(text, func(t *testing.T) { + compiled, problems := Compile(text, Options{}) + if len(problems) != 0 || compiled == nil { + t.Fatalf("free text became a call: %+v", problems) + } + if len(compiled.Query.Where) != 2 { + t.Fatalf("entry count = %d, want 2", len(compiled.Query.Where)) + } + again, problems := Compile(compiled.Canonical, Options{}) + if len(problems) != 0 || again == nil { + t.Fatalf("canonical %q: %+v", compiled.Canonical, problems) + } + if compiled.Canonical != again.Canonical || !reflect.DeepEqual(compiled.Query, again.Query) { + t.Fatalf("not a fixed point: %q -> %q", compiled.Canonical, again.Canonical) + } + }) + } + parsed, problems := Parse(`logs mystery(body)`, "") + if len(problems) != 0 || parsed == nil { + t.Fatal(parsed, problems) + } + if _, ok := parsed.Where[0].(*Call); !ok { + t.Fatalf("an adjacent identifier must be parsed as a call: %T", parsed.Where[0]) + } + wantProblem(t, `logs starts_with (body, "x")`, "", "write starts_with(...) without a space", "") +} diff --git a/internal/fanql/corpus_test.go b/internal/fanql/corpus_test.go new file mode 100644 index 00000000..31a91160 --- /dev/null +++ b/internal/fanql/corpus_test.go @@ -0,0 +1,155 @@ +package fanql + +import ( + "encoding/json" + "fmt" + "io" + "os" + "reflect" + "testing" + + "github.com/labstack/fanout/internal/panel" +) + +// Each JSON block is an independently pinned input/output fixture. There is no +// update mode: changes to this oracle require review, including spans/fix-its. +type corpusFixture struct { + Text string `json:"text"` + Viz string `json:"viz,omitempty"` + Query *panel.Query `json:"query,omitempty"` + Problems panel.Problems `json:"problems,omitempty"` + GateProblems bool `json:"gate_problems,omitempty"` +} + +func readCorpus(t testing.TB) []corpusFixture { + t.Helper() + f, err := os.Open("testdata/corpus.txt") + if err != nil { + t.Fatal(err) + } + defer f.Close() + d := json.NewDecoder(f) + d.DisallowUnknownFields() + var out []corpusFixture + seen := map[string]bool{} + for { + var fixture corpusFixture + if err := d.Decode(&fixture); err == io.EOF { + break + } else if err != nil { + t.Fatal(err) + } + key := fixture.Text + "\x00" + fixture.Viz + if seen[key] { + t.Fatalf("duplicate corpus input %q", fixture.Text) + } + seen[key] = true + if (fixture.Query == nil) == (len(fixture.Problems) == 0) { + t.Fatalf("fixture needs exactly one of query/problems: %+v", fixture) + } + out = append(out, fixture) + } + if len(out) < 200 { + t.Fatalf("corpus has only %d fixtures", len(out)) + } + return out +} + +func TestCorpus(t *testing.T) { + positives, negatives := 0, 0 + for _, f := range readCorpus(t) { + t.Run(f.Text+"/"+f.Viz, func(t *testing.T) { + c, ps := Compile(f.Text, Options{Viz: f.Viz}) + if f.Query == nil { + negatives++ + if c != nil || !reflect.DeepEqual(ps, f.Problems) { + t.Fatalf("got %+v %#v; want %#v", c, ps, f.Problems) + } + } else { + positives++ + if len(ps) != 0 || c == nil { + t.Fatalf("compile: %+v", ps) + } + a, _ := json.Marshal(c.Query) + b, _ := json.Marshal(f.Query) + if string(a) != string(b) { + t.Fatalf("got %s; want %s", a, b) + } + } + }) + } + if positives < 100 || negatives < 60 { + t.Fatalf("need broad positive and negative coverage, got %d/%d", positives, negatives) + } +} + +func TestCanonicalFreeze(t *testing.T) { + path := fmt.Sprintf("testdata/canonical.v%d.golden", Version) + raw, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var golden map[string]string + if err := json.Unmarshal(raw, &golden); err != nil { + t.Fatal(err) + } + clean := map[string]bool{} + for _, f := range readCorpus(t) { + if f.Query == nil { + continue + } + clean[f.Text] = true + c, ps := Compile(f.Text, Options{Viz: f.Viz}) + if len(ps) != 0 { + t.Fatal(f.Text, ps) + } + if want, ok := golden[f.Text]; !ok || c.Canonical != want { + t.Fatalf("FanQL %d canonical changed for %q: %q; pinned %q", Version, f.Text, c.Canonical, want) + } + } + if len(golden) != len(clean) { + t.Fatalf("golden has %d entries, corpus has %d clean texts", len(golden), len(clean)) + } +} + +func TestCorpusIncludesVizContracts(t *testing.T) { + fixtures := readCorpus(t) + for _, context := range []struct{ text, viz string }{ + {"spans sort +duration", "traces"}, {"logs sort duration", "logs"}, + {"logs | count() by body_template sort rate", "log_patterns"}, + {"spans where status:error | count() by service", "table"}, + {"spans sort duration", "traces"}, {"logs sort +time", "logs"}, + {"spans | histogram(duration) by service", "histogram"}, + {"spans | count() by service every 1m", "timeseries"}, + } { + found := false + for _, fixture := range fixtures { + if fixture.Text == context.text && fixture.Viz == context.viz { + found = true + break + } + } + if !found { + t.Errorf("missing viz fixture %q (%s)", context.text, context.viz) + } + } +} + +func TestPrintParsePrintCorpus(t *testing.T) { + for _, f := range readCorpus(t) { + if f.Query == nil { + continue + } + a, ps := Compile(f.Text, Options{Viz: f.Viz}) + if len(ps) != 0 { + t.Fatal(f.Text, ps) + } + b, ps := Compile(a.Canonical, Options{Viz: f.Viz}) + if len(ps) != 0 { + t.Fatalf("%q -> %q: %+v", f.Text, a.Canonical, ps) + } + if a.Canonical != b.Canonical || !reflect.DeepEqual(a.Query, b.Query) { + t.Fatalf("not a fixed point: %q -> %q -> %+v", f.Text, a.Canonical, b) + } + } +} diff --git a/internal/fanql/fuzz_test.go b/internal/fanql/fuzz_test.go new file mode 100644 index 00000000..8301b942 --- /dev/null +++ b/internal/fanql/fuzz_test.go @@ -0,0 +1,233 @@ +package fanql + +import ( + "encoding/json" + "fmt" + "strings" + "testing" + "unicode/utf8" + + "github.com/labstack/fanout/internal/panel" +) + +func FuzzLexParsePrint(f *testing.F) { + for _, fixture := range readCorpus(f) { + f.Add(fixture.Text) + } + for _, text := range []string{"", "logs where \"api*\"", "logs where \"api$svc\"", "spans " + strings.Repeat("a:0 ", 256), "logs -(" + strings.Repeat("a ", 256) + ")", strings.Repeat("a", 4001), strings.Repeat("𝔘", 2049)} { + f.Add(text) + } + f.Fuzz(func(t *testing.T, text string) { + if len(text) > 65536 { + return + } + tokens := Lex(text) + runes := utf8.RuneCountInString(text) + if len(tokens) > runes+1 || len(tokens) == 0 || tokens[len(tokens)-1].Kind != EOF { + t.Fatalf("nonlinear or unterminated token stream: %d tokens for %d runes", len(tokens), runes) + } + for _, tok := range tokens { + if tok.Span.Start < 0 || tok.Span.End < tok.Span.Start || tok.Span.End > runes { + t.Fatalf("invalid token span: %+v", tok) + } + } + q, ps := Parse(text, "") + if len(ps) != 0 { + if q != nil { + t.Fatal("problems returned an executable tree") + } + if len(ps) > MaxProblems+1 { + t.Fatalf("too many problems: %d", len(ps)) + } + if runes > 4000 || len(text) > 8192 { + if len(ps) != 1 || ps[0].Message != "a query is at most 4000 characters (8192 bytes)" { + t.Fatalf("text bound: %+v", ps) + } + } else if len(tokens)-1 > 1024 { + if len(ps) != 1 || ps[0].Message != "a query is at most 1024 tokens" { + t.Fatalf("token bound: %+v", ps) + } + } + return + } + printed := Print(q) + var again *Query + if editableReason(printed) != "" { + // Printing is total and may expand short attribute spellings past an + // interactive bound, or De Morgan negation past the node bound. The + // internal exactness parser remains unbounded. + if rejected, problems := Parse(printed, ""); rejected != nil || len(problems) == 0 { + t.Fatal("expanded text ignored its bound") + } + p := &parser{runes: []rune(printed), tokens: Lex(printed), heights: make(map[any]int)} + again = p.query("") + if problems := p.finish(); len(problems) != 0 { + t.Fatalf("unbounded print reparse %q: %+v", printed, problems) + } + } else { + again, ps = Parse(printed, "") + if len(ps) != 0 { + t.Fatalf("print reparse %q: %+v", printed, ps) + } + } + if next := Print(again); next != printed { + t.Fatalf("not a fixed point: %q -> %q -> %q", text, printed, next) + } + }) +} + +// generatedStructuredQuery is generator B: a bounded grammar of SQL accepted +// by the existing gate, independent of FanQL's own lowerer and printer. +func generatedStructuredQuery(data []byte) panel.Query { + byteAt := func(i int) byte { + if len(data) == 0 { + return 0 + } + return data[i%len(data)] + } + source := []string{"spans", "logs", "metrics"}[int(byteAt(0))%3] + q := panel.Query{From: source, Measures: []string{[]string{"count()", "count( )", " count() ", "count ( )"}[int(byteAt(1))%4]}} + if byteAt(2)%5 == 0 { + // Every entry remains under 500 bytes; their complete text exceeds the + // interactive character bound without invalidating the structured Query. + for i := range 16 { + q.Where = append(q.Where, "service = '"+strings.Repeat("x", 475)+fmt.Sprint(i)+"'") + } + return q + } + count := 1 + int(byteAt(3))%16 + for i := range count { + value := []string{"api", "worker", "user's api", "api`worker", "api*", "$literal", "𝔘 [name]", "line\nvalue"}[int(byteAt(i+4))%8] + literal := "'" + strings.ReplaceAll(value, "'", "''") + "'" + var sql string + switch byteAt(i+5) % 13 { + case 0: + sql = "service = " + literal + case 1: + sql = "service=" + literal + case 2: + sql = fmt.Sprintf("attributes['k'] = %d", byteAt(i+6)) + case 3: + sql = "resource['k'] IS NULL" + case 4: + sql = "(service IS NULL OR service != " + literal + ")" + case 5: + sql = "service IN (" + literal + ", 'other')" + case 6: + sql = "coalesce(service, '') = " + literal + case 7: + sql = "NOT (attributes['k'] = " + literal + ")" + case 8: + sql = "lower(service) = " + literal + case 9: + sql = "CAST(service AS VARCHAR) = " + literal + case 10: + sql = "contains(lower(service),lower(" + literal + "))" + case 11: + sql = "service LIKE " + literal + case 12: + sql = "attributes['user''s name'] = " + literal + } + q.Where = append(q.Where, sql) + } + if byteAt(4)%3 == 0 { + q.By = []string{[]string{"service", "attributes['user name']", "resource['𝔘 [name]']"}[int(byteAt(5))%3]} + } + return q +} + +func FuzzFormatRoundTrip(f *testing.F) { + type seed struct { + Query panel.Query `json:"query"` + Variables []panel.Variable `json:"variables,omitempty"` + Viz string `json:"viz,omitempty"` + } + for _, fixture := range storedQueryFixtures(f) { + if fixture.Panel.Query == nil { + continue + } + raw, err := json.Marshal(seed{Query: *fixture.Panel.Query, Variables: fixture.Variables, Viz: fixture.Panel.Viz}) + if err != nil { + f.Fatal(err) + } + f.Add(raw) + } + for _, fixture := range readCorpus(f) { + if fixture.Query == nil { + continue + } + raw, err := json.Marshal(seed{Query: *fixture.Query, Viz: fixture.Viz}) + if err != nil { + f.Fatal(err) + } + f.Add(raw) + } + for _, data := range [][]byte{{0}, {1, 2, 3, 4, 5}, {2, 1, 9, 15, 17}} { + raw, _ := json.Marshal(seed{Query: generatedStructuredQuery(data)}) + f.Add(raw) + } + engine, _ := newTestEngine(f) + f.Fuzz(func(t *testing.T, data []byte) { + if len(data) > 65536 { + return + } + var input seed + if json.Unmarshal(data, &input) != nil || input.Query.From == "" { + input = seed{Query: generatedStructuredQuery(data)} + } + stored := input.Query + if len(panel.CompatibleVizzes(&stored, nil)) == 0 { + return + } + viz := input.Viz + if viz == "" { + viz = panel.CompatibleVizzes(&stored, nil)[0].Viz + } + checkedQuery := stored + dashboard := panel.Dashboard{Name: "Fuzz", Variables: input.Variables, Panels: []panel.Panel{{ID: "fuzz", Title: "Fuzz", Viz: viz, Query: &checkedQuery}}} + panel.Normalize(&dashboard) + // JSON mutation can produce syntactically invalid SQL in a shape-valid + // Query. The round-trip promise applies only to the gate's accepted input. + if _, problems, err := panel.Check(t.Context(), engine, &dashboard); err != nil { + t.Fatal(err) + } else if len(problems) != 0 { + return + } + formatted, ps, err := Format(t.Context(), engine, stored, FormatOptions{Variables: input.Variables}) + if err != nil || len(ps) != 0 || formatted == nil { + t.Fatalf("format %#v: %+v %v", stored, ps, err) + } + if !formatted.Editable { + // Complete, noneditable text is never sent through public Parse. + before, _ := json.Marshal(stored) + raw, err := json.Marshal(struct { + FanQL int `json:"fanql"` + Text string `json:"text"` + Editable bool `json:"editable"` + Query panel.Query `json:"query"` + }{Version, formatted.Text, false, stored}) + if err != nil { + t.Fatal(err) + } + var envelope struct { + Query panel.Query `json:"query"` + } + if err := json.Unmarshal(raw, &envelope); err != nil { + t.Fatal(err) + } + after, _ := json.Marshal(envelope.Query) + if string(after) != string(before) { + t.Fatalf("envelope changed query: %s != %s", after, before) + } + return + } + compiled, ps := Compile(formatted.Text, Options{}) + if len(ps) != 0 || compiled == nil { + t.Fatalf("recompile %q: %+v", formatted.Text, ps) + } + assertQueryTier(t, engine, stored, compiled.Query, formatted.Exactness) + if len(stored.Where) != len(compiled.Query.Where) { + t.Fatal("entry count changed") + } + }) +} diff --git a/internal/fanql/instrumentation_plain_test.go b/internal/fanql/instrumentation_plain_test.go new file mode 100644 index 00000000..66693862 --- /dev/null +++ b/internal/fanql/instrumentation_plain_test.go @@ -0,0 +1,5 @@ +//go:build !race + +package fanql + +const raceInstrumentation = false diff --git a/internal/fanql/instrumentation_race_test.go b/internal/fanql/instrumentation_race_test.go new file mode 100644 index 00000000..2463fcf9 --- /dev/null +++ b/internal/fanql/instrumentation_race_test.go @@ -0,0 +1,5 @@ +//go:build race + +package fanql + +const raceInstrumentation = true diff --git a/internal/fanql/latency_test.go b/internal/fanql/latency_test.go new file mode 100644 index 00000000..9fd1dd8e --- /dev/null +++ b/internal/fanql/latency_test.go @@ -0,0 +1,179 @@ +package fanql + +import ( + "context" + "math" + "os/exec" + "slices" + "testing" + "time" + "unicode/utf8" + + "github.com/labstack/fanout/internal/panel" +) + +type budgetParser struct { + panel.Parser + parseCalls, renderCalls int +} + +func (p *budgetParser) ParseSQL(ctx context.Context, text string) (map[string]any, error) { + p.parseCalls++ + return p.Parser.ParseSQL(ctx, text) +} + +func (p *budgetParser) RenderSQL(ctx context.Context, node map[string]any) (string, error) { + p.renderCalls++ + return p.Parser.RenderSQL(ctx, node) +} + +func latencyPercentile(samples []time.Duration, percentile float64) time.Duration { + ordered := slices.Clone(samples) + slices.Sort(ordered) + return ordered[max(0, int(math.Ceil(float64(len(ordered))*percentile))-1)] +} + +func TestLatencyBudgets(t *testing.T) { + if testing.Short() { + t.Skip("latency acceptance is excluded by -short") + } + if raceInstrumentation { + // Race instrumentation changes CPU cost by an order of magnitude. Keep + // the production budgets unchanged and actually assert them in a plain + // child build; all functional tests still run under the race detector. + // The pinned engine's GOFLAGS/CGO environment comes from the parent. + cmd := exec.CommandContext(t.Context(), "go", "test", "-race=false", "-run", "^TestLatencyBudgets$", "-count=1", "-v", ".") + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("production latency under race runner: %v\n%s", err, out) + } + t.Logf("production latency (uninstrumented):\n%s", out) + return + } + fixtures := readCorpus(t) + if len(fixtures) == 0 { + t.Fatal("latency needs the acceptance corpus") + } + engine, _ := newTestEngine(t) + parser := &budgetParser{Parser: engine} + warm := warmCompleter(t) + registryOnly := NewCompleter(nil) + var compileSamples, formatSamples, completeSamples, parseRankSamples []time.Duration + maxParse, maxRender := 0, 0 + // Prime code and data before measuring steady-state editing work. + for _, fixture := range fixtures { + _, _ = Compile(fixture.Text, Options{Viz: fixture.Viz}) + } + for range 3 { + for _, fixture := range fixtures { + started := time.Now() + _, _ = Compile(fixture.Text, Options{Viz: fixture.Viz}) + compileSamples = append(compileSamples, time.Since(started)) + req := CompleteRequest{Text: fixture.Text, Cursor: utf8.RuneCountInString(fixture.Text), Window: "1h", Viz: fixture.Viz} + started = time.Now() + response := warm.Complete(t.Context(), req) + completeSamples = append(completeSamples, time.Since(started)) + if !response.Schema.Warm { + t.Fatal("warm-cache measurement lost its schema") + } + started = time.Now() + _, _ = expectAt(req.Text, req.Cursor) + _ = registryOnly.Complete(t.Context(), req) + parseRankSamples = append(parseRankSamples, time.Since(started)) + } + } + stored := storedQueryFixtures(t) + for range 3 { + for _, fixture := range stored { + q := fixture.Panel.Query + if q == nil || len(q.Where) > 16 { + continue + } + if problems, _ := panel.QueryShape(q, fixture.Panel.Viz, nil); len(problems) != 0 { + t.Fatalf("stored fixture %q is not shape-valid: %+v", fixture.Name, problems) + } + parser.parseCalls, parser.renderCalls = 0, 0 + started := time.Now() + formatted, ps, err := Format(t.Context(), parser, *q, FormatOptions{Viz: fixture.Panel.Viz, Variables: fixture.Variables}) + formatSamples = append(formatSamples, time.Since(started)) + if err != nil || len(ps) != 0 || formatted == nil { + t.Fatalf("format %q: %+v %v", fixture.Name, ps, err) + } + maxParse, maxRender = max(maxParse, parser.parseCalls), max(maxRender, parser.renderCalls) + } + q := generatedStructuredQuery([]byte{0}) // 16 complete stored entries. + parser.parseCalls, parser.renderCalls = 0, 0 + started := time.Now() + formatted, ps, err := Format(t.Context(), parser, q, FormatOptions{}) + formatSamples = append(formatSamples, time.Since(started)) + if err != nil || len(ps) != 0 || formatted == nil { + t.Fatalf("format 16 entries: %+v %v", ps, err) + } + maxParse, maxRender = max(maxParse, parser.parseCalls), max(maxRender, parser.renderCalls) + } + for _, budget := range []struct { + name string + samples []time.Duration + percentile float64 + limit time.Duration + }{ + {"Compile", compileSamples, .99, time.Millisecond}, + {"Format", formatSamples, .99, 20 * time.Millisecond}, + {"Complete warm", completeSamples, .95, 30 * time.Millisecond}, + {"expectAt plus registry parse/rank", parseRankSamples, .95, 5 * time.Millisecond}, + } { + if len(budget.samples) == 0 { + t.Fatalf("no %s samples", budget.name) + } + got := latencyPercentile(budget.samples, budget.percentile) + t.Logf("%s p%.0f=%s, budget <%s, samples=%d", budget.name, budget.percentile*100, got, budget.limit, len(budget.samples)) + if got >= budget.limit { + t.Errorf("%s p%.0f=%s exceeds <%s", budget.name, budget.percentile*100, got, budget.limit) + } + } + t.Logf("Format engine calls per request: ParseSQL max=%d, RenderSQL max=%d", maxParse, maxRender) +} + +func BenchmarkCompile(b *testing.B) { + fixtures := readCorpus(b) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + fixture := fixtures[i%len(fixtures)] + _, _ = Compile(fixture.Text, Options{Viz: fixture.Viz}) + } +} + +func BenchmarkFormat(b *testing.B) { + engine, _ := newTestEngine(b) + fixtures := storedQueryFixtures(b) + queries := make([]storedQueryFixture, 0, len(fixtures)) + for _, fixture := range fixtures { + if fixture.Panel.Query != nil { + queries = append(queries, fixture) + } + } + if len(queries) == 0 { + b.Fatal("no stored query fixtures") + } + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + fixture := queries[i%len(queries)] + if _, ps, err := Format(b.Context(), engine, *fixture.Panel.Query, FormatOptions{Viz: fixture.Panel.Viz, Variables: fixture.Variables}); err != nil || len(ps) != 0 { + b.Fatal(ps, err) + } + } +} + +func BenchmarkComplete(b *testing.B) { + fixtures := readCorpus(b) + c := NewCompleter(nil) + c.cache[completionKey{window: "1h"}] = completionSchemaEntry{schema: completionFixtureSchema(), expires: time.Now().Add(time.Hour)} + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + fixture := fixtures[i%len(fixtures)] + _ = c.Complete(b.Context(), CompleteRequest{Text: fixture.Text, Cursor: utf8.RuneCountInString(fixture.Text), Window: "1h", Viz: fixture.Viz}) + } +} diff --git a/internal/fanql/lift.go b/internal/fanql/lift.go index 538b1763..36452812 100644 --- a/internal/fanql/lift.go +++ b/internal/fanql/lift.go @@ -364,36 +364,38 @@ func liftSQLValue(n any) (Value, bool) { return Value{}, false } -func spellingValue(f Field, v Value) Value { +func spellingValue(f Field, v Value, aliases bool) Value { if v.Kind == VariableValue { return v } if f.Ref.Column == "duration_ms" && f.Ref.Key == "" && v.Kind == NumberValue { - if n, err := strconv.ParseFloat(v.Text, 64); err == nil { + if n, err := strconv.ParseFloat(v.Text, 64); err == nil && n >= 0 { v.Kind = DurationValue v.Text = durationText(n) } return v } if v.Kind == StringValue && f.Ref.Key == "" && f.Ref.Type == panel.TypeString { - switch f.Ref.Column { - case "status": - if strings.HasPrefix(v.Text, "STATUS_CODE_") { - v.Kind = WordValue - v.Text = strings.ToLower(strings.TrimPrefix(v.Text, "STATUS_CODE_")) - return v - } - case "kind": - if strings.HasPrefix(v.Text, "SPAN_KIND_") { - v.Kind = WordValue - v.Text = strings.ToLower(strings.TrimPrefix(v.Text, "SPAN_KIND_")) - return v - } - case "severity": - if v.Text == strings.ToUpper(v.Text) && classify(Token{Kind: Word, Text: strings.ToLower(v.Text)}).Kind == WordValue { - v.Kind = WordValue - v.Text = strings.ToLower(v.Text) - return v + if aliases { + switch f.Ref.Column { + case "status": + if strings.HasPrefix(v.Text, "STATUS_CODE_") { + v.Kind = WordValue + v.Text = strings.ToLower(strings.TrimPrefix(v.Text, "STATUS_CODE_")) + return v + } + case "kind": + if strings.HasPrefix(v.Text, "SPAN_KIND_") { + v.Kind = WordValue + v.Text = strings.ToLower(strings.TrimPrefix(v.Text, "SPAN_KIND_")) + return v + } + case "severity": + if v.Text == strings.ToUpper(v.Text) && classify(Token{Kind: Word, Text: strings.ToLower(v.Text)}).Kind == WordValue { + v.Kind = WordValue + v.Text = strings.ToLower(v.Text) + return v + } } } if f.Ref.Column != "status" && f.Ref.Column != "kind" && f.Ref.Column != "severity" && f.Ref.Column != "type" && f.Ref.CompareAs == "" { @@ -427,7 +429,12 @@ func durationText(ms float64) string { }{{3600000, "h"}, {60000, "m"}, {1000, "s"}, {1, "ms"}, {0.001, "us"}} for _, u := range units { if ms >= u.value { - return strconv.FormatFloat(ms/u.value, 'f', -1, 64) + u.name + text := strconv.FormatFloat(ms/u.value, 'f', -1, 64) + u.name + // A shorter unit is safe only when parsing it recreates the exact + // threshold; 1.001s, for example, is not exactly 1001 milliseconds. + if restored, ok := durationMS(text); ok && restored == ms { + return text + } } } return strconv.FormatFloat(ms, 'f', -1, 64) + "ms" @@ -466,7 +473,7 @@ func liftSQLNode(signal string, n any) Expr { if ok && valid { op := map[string]string{"COMPARE_EQUAL": ":", "COMPARE_NOTEQUAL": "!=", "COMPARE_LESSTHAN": "<", "COMPARE_GREATERTHAN": ">", "COMPARE_LESSTHANOREQUALTO": "<=", "COMPARE_GREATERTHANOREQUALTO": ">="}[fmt.Sprint(node["type"])] if op != "" { - return &Compare{Field: f, Op: op, Value: spellingValue(f, v)} + return &Compare{Field: f, Op: op, Value: spellingValue(f, v, !isRange(op))} } } if call := liftSQLCall(signal, node["left"]); call != nil && valid { @@ -482,7 +489,7 @@ func liftSQLNode(signal string, n any) Expr { hi, b := liftSQLValue(node["upper"]) if ok && a && b { neg, _ := node["negated"].(bool) - return &Between{Field: f, Lo: spellingValue(f, lo), Hi: spellingValue(f, hi), Negated: neg} + return &Between{Field: f, Lo: spellingValue(f, lo, false), Hi: spellingValue(f, hi, false), Negated: neg} } case "OPERATOR": switch node["type"] { @@ -506,7 +513,7 @@ func liftSQLNode(signal string, n any) Expr { if !ok { return nil } - in.Values = append(in.Values, spellingValue(f, v)) + in.Values = append(in.Values, spellingValue(f, v, true)) } if len(in.Values) == 1 && in.Values[0].Kind == VariableValue { in.Variable = strings.TrimPrefix(in.Values[0].Text, "$") diff --git a/internal/fanql/parser.go b/internal/fanql/parser.go index 30fe1258..04218168 100644 --- a/internal/fanql/parser.go +++ b/internal/fanql/parser.go @@ -112,7 +112,17 @@ func (p *parser) take() Token { } return t } -func (p *parser) lower() string { return strings.ToLower(p.peek().Text) } + +// Quoted and raw tokens carry decoded text that can spell an operator or +// delimiter. Only unquoted grammar tokens may participate in syntax matching. +func grammarText(t Token) string { + if t.Kind == Word || t.Kind == Ident || t.Kind == Punct { + return strings.ToLower(t.Text) + } + return "" +} + +func (p *parser) lower() string { return grammarText(p.peek()) } func (p *parser) is(s string) bool { t := p.peek() return (t.Kind == Word || t.Kind == Ident || t.Kind == Punct) && strings.EqualFold(t.Text, s) @@ -233,7 +243,7 @@ func (p *parser) query(source string) *Query { p.skipRun() continue } - if p.is("sort") && strings.EqualFold(p.ahead(1).Text, "by") { + if p.is("sort") && grammarText(p.ahead(1)) == "by" { p.report(p.take().Span, "foreignStage", "sort") p.skipStage() continue @@ -437,6 +447,29 @@ func isFieldWordOperator(op string) bool { return false } +func (p *parser) filterCallStart() bool { + name, open := p.peek(), p.ahead(1) + if name.Kind != Word || grammarText(open) != "(" || name.Text == "" { + return false + } + for i, r := range name.Text { + if i == 0 && !identStart(r) || i > 0 && !identContinue(r) { + return false + } + } + if open.Span.Start == name.Span.End { + return true + } + // Preserve the useful typo diagnostic for registered functions, while an + // ordinary search word followed by whitespace and a group stays two terms. + for _, function := range resolveFilterFunctions() { + if strings.EqualFold(name.Text, function) { + return true + } + } + return false +} + func (p *parser) term(nested bool) Expr { p.expectTerm(nested) if p.is("-") || p.is("not") { @@ -501,14 +534,14 @@ func (p *parser) primary(nested bool) Expr { if p.foreignTerm() { return nil } - next := strings.ToLower(p.ahead(1).Text) - fieldOperator := isComparison(next) || next == ":" || next == "~" || next == "!~" || next == "is" || isFieldWordOperator(next) || next == "not" && isFieldWordOperator(strings.ToLower(p.ahead(2).Text)) + next := grammarText(p.ahead(1)) + fieldOperator := isComparison(next) || next == ":" || next == "~" || next == "!~" || next == "is" || isFieldWordOperator(next) || next == "not" && isFieldWordOperator(grammarText(p.ahead(2))) if reserved[word] && !fieldOperator { p.report(t.Span, "reserved", word) p.take() return nil } - if p.ahead(1).Text == "(" { + if p.filterCallStart() { return p.call() } field, ok := p.field() @@ -557,7 +590,7 @@ func (p *parser) primary(nested bool) Expr { p.colonProblem(field, v, at) return nil } - if p.peek().Text == "*" && p.peek().Span.Start == v.At.End { + if p.is("*") && p.peek().Span.Start == v.At.End { p.wildcard(v) return nil } @@ -575,7 +608,7 @@ func (p *parser) primary(nested bool) Expr { return x } neg := false - if expressionWords[op] && op == "not" && isFieldWordOperator(strings.ToLower(p.ahead(1).Text)) { + if expressionWords[op] && op == "not" && isFieldWordOperator(grammarText(p.ahead(1))) { neg = true p.take() op = p.lower() @@ -630,7 +663,7 @@ func (p *parser) primary(nested bool) Expr { p.report(t.Span, "unexpected", t.Text) return nil } - if p.peek().Text == "*" && p.peek().Span.Start == field.At.End { + if p.is("*") && p.peek().Span.Start == field.At.End { p.wildcard(Value{Text: t.Text, At: t.Span}) return nil } @@ -796,7 +829,7 @@ func (p *parser) call() *Call { before := p.i arg := CallArg{} switch t := p.peek(); { - case t.Kind == Word && p.ahead(1).Text == "(": + case p.filterCallStart(): arg.Call = p.call() case t.Kind == String || t.Kind == Number || t.Kind == Word && numberPattern.MatchString(t.Text) || p.is("-"): v, ok := p.value() @@ -859,7 +892,10 @@ func (p *parser) checkQuoted(t Token) { } func (p *parser) colonProblem(f Field, v Value, at Span) { - run := p.runSpan(at.Start) + // The field, operator and value may be separated by whitespace, or the + // quoted field/value may contain it. Recover through the offending colon's + // run rather than stopping before the value whose diagnostic we render. + run := Span{at.Start, p.runSpan(p.peek().Span.Start).End} value := p.text(Span{v.At.Start, run.End}) prefix := p.text(Span{f.At.Start, v.At.Start}) after := v.Text @@ -943,17 +979,17 @@ func (p *parser) foreignTerm() bool { } return true } - if (word == "ago" || word == "now") && p.ahead(1).Text == "(" { + if (word == "ago" || word == "now") && grammarText(p.ahead(1)) == "(" { p.report(t.Span, "timeCall", word) p.skipRun() return true } - if word == "earliest" && p.ahead(1).Text == "=" || word == "_time" && p.ahead(1).Text == ":" { + if word == "earliest" && grammarText(p.ahead(1)) == "=" || word == "_time" && grammarText(p.ahead(1)) == ":" { p.report(t.Span, "time", word) p.skipRun() return true } - if word == "facet" || (word == "order" || word == "group") && strings.EqualFold(p.ahead(1).Text, "by") { + if word == "facet" || (word == "order" || word == "group") && grammarText(p.ahead(1)) == "by" { p.report(t.Span, "foreignClause", word) p.skipRun() if p.is("by") { @@ -1054,12 +1090,12 @@ func (p *parser) stage(start int) *Stage { if p.peek().Kind == Ident && foreignStages[p.lower()] { t := p.take() p.report(t.Span, "foreignStage", strings.ToLower(t.Text)) - for p.peek().Kind != EOF && !p.is("|") && !p.is(",") && !clauses[p.lower()] && !foreignStages[p.lower()] && p.ahead(1).Text != "(" { + for p.peek().Kind != EOF && !p.is("|") && !p.is(",") && !clauses[p.lower()] && !foreignStages[p.lower()] && grammarText(p.ahead(1)) != "(" { p.take() } continue } - if p.peek().Kind == Ident && foreignCalls[p.lower()] && p.ahead(1).Text == "(" { + if p.peek().Kind == Ident && foreignCalls[p.lower()] && grammarText(p.ahead(1)) == "(" { p.report(p.peek().Span, "foreignCall", p.lower()) p.skipRun() continue @@ -1261,7 +1297,7 @@ func (p *parser) mfactor() MExpr { p.node(x) return x } - if t.Kind == Ident && p.ahead(1).Text == "(" { + if t.Kind == Ident && grammarText(p.ahead(1)) == "(" { return p.mcall() } if t.Kind == Bad { diff --git a/internal/fanql/print.go b/internal/fanql/print.go index 5bd7c3c3..bf28d1e9 100644 --- a/internal/fanql/print.go +++ b/internal/fanql/print.go @@ -22,6 +22,11 @@ func Print(q *Query) string { for i, e := range q.Where { entries[i] = printEntry(e, len(q.Where) > 1) } + for i := 0; i+1 < len(entries); i++ { + if strings.HasPrefix(entries[i+1], "(") { + entries[i] = quoteSearchBeforeGroup(q.Where[i], entries[i]) + } + } text += " where " + strings.Join(entries, " ") } if s := q.Stage; s != nil { @@ -99,6 +104,8 @@ func canonicalExpr(e Expr, neg bool) Expr { if x.Negated && len(x.Bands) > 0 { return canonicalExpr(bandMembership(x.Field, x.Bands, true), neg) } + case *IsNull: + return canonicalExpr(&Exists{Field: x.Field, At: x.At}, neg != !x.Negated) case *Compare: if x.Op == "~" && x.Value.Kind != VariableValue && x.Field.Ref != nil && x.Field.Ref.Key == "" && (x.Field.Ref.Column == "body" || x.Field.Ref.Column == "operation") { v := x.Value @@ -127,6 +134,11 @@ func printExpr(e Expr, grouped bool) string { for i, t := range x.Terms { terms[i] = printExpr(t, true) } + for i := 0; i+1 < len(terms); i++ { + if strings.HasPrefix(terms[i+1], "(") { + terms[i] = quoteSearchBeforeGroup(x.Terms[i], terms[i]) + } + } return "(" + strings.Join(terms, " ") + ")" case *Or: terms := make([]string, len(x.Terms)) @@ -165,9 +177,19 @@ func printExpr(e Expr, grouped bool) string { op = "!=" } if op == "~" || op == "!~" { - return printField(x.Field) + " " + op + " " + printValue(x.Value, x.Field, false) + value := x.Value + if value.Kind != VariableValue { + // Contains interprets every literal as text, including its exact + // exponent spelling; numeric normalization would change the search. + value.Kind = StringValue + if value.Stored != "" { + value.Text = value.Stored + } + } + return printField(x.Field) + " " + op + " " + printValue(value, x.Field, false) } - return printField(x.Field) + op + printValue(x.Value, x.Field, op == ":" || op == "=" || op == "!=" || op == "<>") + field, native := printFilterField(x.Field, x.Value) + return field + op + printFilterValue(x.Value, x.Field, op == ":" || op == "=" || op == "!=" || op == "<>", native) case *In: op := " in " if x.Negated { @@ -177,10 +199,11 @@ func printExpr(e Expr, grouped bool) string { return printField(x.Field) + op + "$" + x.Variable } vs := make([]string, len(x.Values)) + field, native := printFilterField(x.Field, x.Values...) for i, v := range x.Values { - vs[i] = printValue(v, x.Field, true) + vs[i] = printFilterValue(v, x.Field, true, native) } - return printField(x.Field) + op + "(" + strings.Join(vs, ", ") + ")" + return field + op + "(" + strings.Join(vs, ", ") + ")" case *Between: if len(x.Bands) > 0 && !x.Negated { return printBandRange(x.Field, x.Bands) @@ -189,7 +212,8 @@ func printExpr(e Expr, grouped bool) string { if x.Negated { op = " not between " } - return printField(x.Field) + op + printValue(x.Lo, x.Field, false) + " and " + printValue(x.Hi, x.Field, false) + field, native := printFilterField(x.Field, x.Lo, x.Hi) + return field + op + printFilterValue(x.Lo, x.Field, false, native) + " and " + printFilterValue(x.Hi, x.Field, false, native) case *Like: op := "like" if x.Insensitive { @@ -216,6 +240,28 @@ func printExpr(e Expr, grouped bool) string { return "" } +// Canonical negation can introduce a following group. A function-shaped search +// word needs quotes only in that context, where it would become a spaced call. +func quoteSearchBeforeGroup(e Expr, text string) string { + e = canonicalExpr(e, false) + neg := false + if n, ok := e.(*Not); ok { + neg, e = true, n.X + } + if x, ok := e.(*FreeText); ok { + for _, name := range resolveFilterFunctions() { + if strings.EqualFold(x.Value.Text, name) { + text = quoteText(x.Value.Text) + if neg { + text = "-" + text + } + return text + } + } + } + return text +} + func printField(f Field) string { column, key := f.Key, "" if f.Ref != nil { @@ -244,7 +290,34 @@ func validPath(s string) bool { return identifierPath.MatchString(s) } func quoteText(s string) string { return `"` + strings.ReplaceAll(s, `"`, `""`) + `"` } +// The explicit numeric column accepts negative numbers; the duration shorthand +// forbids negative units. Keep the numeric field for a whole mixed list/range. +func printFilterField(f Field, values ...Value) (string, bool) { + if f.Ref != nil && f.Ref.Column == "duration_ms" && f.Ref.Key == "" { + for _, v := range values { + if v.Kind == NumberValue { + if n, err := strconv.ParseFloat(v.Text, 64); err == nil && n < 0 { + return "duration_ms", true + } + } + } + } + return printField(f), false +} + +func printFilterValue(v Value, f Field, aliases, nativeDuration bool) string { + if nativeDuration && v.Kind == NumberValue { + return printLiteral(v, false) + } + return printValue(v, f, aliases) +} + func printValue(v Value, f Field, aliases bool) string { + // In alias-bearing positions, unresolved fields cannot prove that removing + // the user's quotes preserves the value. Keep them until that proof exists. + if aliases && v.Kind == StringValue && f.Ref == nil { + return quoteText(v.Text) + } if v.Kind == NumberValue && f.Ref != nil && f.Ref.Column == "duration_ms" && f.Ref.Key == "" { if n, err := strconv.ParseFloat(v.Text, 64); err == nil { return durationText(n) diff --git a/internal/fanql/registry_growth_test.go b/internal/fanql/registry_growth_test.go new file mode 100644 index 00000000..bcde968d --- /dev/null +++ b/internal/fanql/registry_growth_test.go @@ -0,0 +1,113 @@ +package fanql + +import ( + "encoding/json" + "reflect" + "slices" + "testing" + + "github.com/labstack/fanout/internal/panel" +) + +type registryMeaning struct { + query string + problems string +} + +func registrySnapshot(fixtures []corpusFixture) map[string]registryMeaning { + out := make(map[string]registryMeaning, len(fixtures)) + for _, fixture := range fixtures { + compiled, problems := Compile(fixture.Text, Options{Viz: fixture.Viz}) + var query []byte + if compiled != nil { + query, _ = json.Marshal(compiled.Query) + } + raw, _ := json.Marshal(problems) + key := fixture.Text + if fixture.Viz != "" { + key += "\n[viz=" + fixture.Viz + "]" + } + out[key] = registryMeaning{query: string(query), problems: string(raw)} + } + return out +} + +// Previously accepted text whose meaning changes is a version-bump event; +// newly accepted syntax is additive. The canonical attribute form stays stable. +func registryVersionBumpEvents(before, after map[string]registryMeaning) []string { + var changes []string + for text, original := range before { + if original.query != "" && original != after[text] { + changes = append(changes, text) + } + } + slices.Sort(changes) + return changes +} + +func TestRegistryGrowth(t *testing.T) { + fixtures := readCorpus(t) + fixtures = append(slices.Clone(fixtures), + corpusFixture{Text: `spans where value>-3`}, + corpusFixture{Text: `spans where attributes['value']>-3`}, + ) + baseline := registrySnapshot(fixtures) + columns, measures, functions := resolveColumns, resolveMeasures, resolveFilterFunctions + oldBuckets := buckets + t.Cleanup(func() { + resolveColumns, resolveMeasures, resolveFilterFunctions, buckets = columns, measures, functions, oldBuckets + }) + resolveMeasures = func() []panel.MeasureSpec { + out := measures() + out = append(out, panel.MeasureSpec{Name: "p42", Args: 1, Numeric: true, Quantile: .42, Signals: []string{"spans", "logs"}}) + return out + } + resolveFilterFunctions = func() []string { return append(functions(), "ltrim") } + buckets = make(map[string]bool, len(oldBuckets)+1) + for name, enabled := range oldBuckets { + buckets[name] = enabled + } + buckets["2m"] = true + afterAdditive := registrySnapshot(fixtures) + if !reflect.DeepEqual(baseline, afterAdditive) { + for text, before := range baseline { + if before != afterAdditive[text] { + // The corpus deliberately includes the previously unknown 2m + // bucket. Making rejected syntax valid is additive (section 0.13). + if text == "spans | count() every 2m" && before.query == "" && afterAdditive[text].query != "" { + continue + } + t.Errorf("additive registry growth changed %q: %+v -> %+v", text, before, afterAdditive[text]) + } + } + } + if events := registryVersionBumpEvents(baseline, afterAdditive); len(events) != 0 { + t.Fatalf("additive changes requested a version bump: %q", events) + } + for _, text := range []string{`spans | p42(duration)`, `spans | count() every 2m`, `logs where ltrim(service)="api"`} { + if c, ps := Compile(text, Options{}); len(ps) != 0 || c == nil { + t.Fatalf("synthetic registry hook didn't reach %q: %+v", text, ps) + } + } + resolveColumns = func(source string) ([]panel.Field, bool) { + out, ok := columns(source) + if source == "spans" { + out = append(out, panel.Field{Name: "value", Type: panel.TypeNumber, Unit: "none"}) + } + return out, ok + } + afterColumn := registrySnapshot(fixtures) + events := registryVersionBumpEvents(baseline, afterColumn) + if !slices.Contains(events, `spans where value>-3`) { + t.Fatalf("new column must report a version-bump event; got %q", events) + } + if baseline[`spans where attributes['value']>-3`] != afterColumn[`spans where attributes['value']>-3`] { + t.Fatal("new column changed canonical bracket meaning") + } + before := baseline[`spans where value>-3`].query + after := afterColumn[`spans where value>-3`].query + if before == after { + t.Fatal("column hook did not change hand-typed bare text") + } + t.Logf("registry detector: adding spans.value changes accepted bare text (%d corpus version-bump events)", len(events)) +} diff --git a/internal/fanql/resolve.go b/internal/fanql/resolve.go index 7e78e554..1ce6630e 100644 --- a/internal/fanql/resolve.go +++ b/internal/fanql/resolve.go @@ -37,6 +37,12 @@ type VizEdit struct { var resolveLower func(*Resolved) (panel.Query, panel.Problems) var resolvePrint func(*Query) string +// Catalog reads remain private and return snapshots. Tests can substitute a +// prospective registry to detect accepted text that would need a version bump. +var resolveColumns = panel.SignalColumns +var resolveMeasures = panel.MeasureSpecs +var resolveFilterFunctions = panel.FilterFunctionNames + type resolver struct { opts ResolveOptions out *Resolved @@ -144,7 +150,7 @@ func (r *resolver) field(f *Field) { if scope == "" && !f.Bracket && strings.EqualFold(key, "duration") { key = "duration_ms" } - columns, _ := panel.SignalColumns(r.out.Query.Source) + columns, _ := resolveColumns(r.out.Query.Source) if scope == "" && !f.Bracket && !strings.Contains(key, ".") { for _, c := range columns { if strings.EqualFold(key, c.Name) { @@ -165,7 +171,7 @@ func (r *resolver) field(f *Field) { f.Ref = &FieldRef{Column: scope, Key: key, Type: panel.TypeString, Unit: "none"} if f.Scope == "" && !f.Bracket && !strings.Contains(key, ".") { message := fmt.Sprintf("%q is not a %s column; reading attributes['%s']", key, r.out.Query.Source, key) - for _, m := range panel.MeasureSpecs() { + for _, m := range resolveMeasures() { if strings.EqualFold(m.Name, key) { message = fmt.Sprintf("%q is a measure, not a %s column; reading attributes['%s']", key, r.out.Query.Source, key) break @@ -233,7 +239,7 @@ func (r *resolver) expr(e Expr) { if r.out.Query.Source == "metrics" { r.issue(x.At, "free text needs a field on metrics; use name:http.server.duration") } - cols, _ := panel.SignalColumns(r.out.Query.Source) + cols, _ := resolveColumns(r.out.Query.Source) for _, c := range cols { if strings.EqualFold(c.Name, x.Value.Text) { r.notice(x.At, fmt.Sprintf("%q is a field; did you mean %s:?", x.Value.Text, c.Name)) @@ -432,7 +438,7 @@ func (r *resolver) variable(name, field string, at Span, multi bool) { } func (r *resolver) call(c *Call) { - if !slices.Contains(panel.FilterFunctionNames(), c.Name) { + if !slices.Contains(resolveFilterFunctions(), c.Name) { r.issue(c.At, "function "+c.Name+" is not allowed in a filter") return } @@ -479,7 +485,7 @@ func (r *resolver) measure(e MExpr) { switch x := e.(type) { case *MCall: var spec *panel.MeasureSpec - for _, s := range panel.MeasureSpecs() { + for _, s := range resolveMeasures() { if s.Name == x.Name { s := s spec = &s diff --git a/internal/fanql/review_test.go b/internal/fanql/review_test.go index 477c131c..e2fc6fc4 100644 --- a/internal/fanql/review_test.go +++ b/internal/fanql/review_test.go @@ -3,6 +3,7 @@ package fanql import ( "database/sql" "reflect" + "strconv" "testing" "github.com/labstack/fanout/internal/panel" @@ -60,6 +61,40 @@ func TestPrintParsePrintFixtureCorpus(t *testing.T) { } } +func TestPrintFunctionSearchWordsBeforeGroups(t *testing.T) { + for _, name := range resolveFilterFunctions() { + standalone, ps := Compile("logs "+name, Options{}) + if len(ps) != 0 || standalone.Canonical != "logs where "+name { + t.Fatalf("standalone search spelling: %+v %+v", standalone, ps) + } + text := "logs " + name + " -(a b)" + a, ps := Compile(text, Options{}) + if len(ps) != 0 { + t.Fatal(text, ps) + } + b, ps := Compile(a.Canonical, Options{}) + if len(ps) != 0 || b == nil { + t.Fatalf("%q -> %q: %+v", text, a.Canonical, ps) + } + if b.Canonical != a.Canonical || !reflect.DeepEqual(a.Query, b.Query) { + t.Fatalf("not fixed: %+v -> %+v", a, b) + } + } +} + +func TestPrintContainsKeepsStoredLiteralText(t *testing.T) { + for _, text := range []string{`spans where k ~ TRUE`, `spans where k !~ FALSE`, `logs where severity ~ TRUE`, `logs where service ~ FALSE`, `spans where k ~ 2E3`} { + a, ps := Compile(text, Options{}) + if len(ps) != 0 { + t.Fatal(text, ps) + } + b, ps := Compile(a.Canonical, Options{}) + if len(ps) != 0 || b == nil || !reflect.DeepEqual(a.Query, b.Query) { + t.Fatalf("%q -> %q: %+v %+v", text, a.Canonical, b, ps) + } + } +} + func TestPrintDurationMSKeepsUnit(t *testing.T) { a, ps := Compile(`spans where duration_ms>500`, Options{}) if len(ps) != 0 { @@ -74,6 +109,36 @@ func TestPrintDurationMSKeepsUnit(t *testing.T) { } } +func TestDurationSpellingPreservesMillisecondThresholds(t *testing.T) { + for _, ms := range []float64{1001, 1002, 1003, 60001, 3600001, .1, .001, .0001, 1.3, 1e100, 1e308} { + text := "spans where duration_ms>" + strconv.FormatFloat(ms, 'g', -1, 64) + a, ps := Compile(text, Options{}) + if len(ps) != 0 { + t.Fatal(text, ps) + } + b, ps := Compile(a.Canonical, Options{}) + if len(ps) != 0 || b == nil || !reflect.DeepEqual(a.Query, b.Query) { + t.Fatalf("%q -> %q: %+v %+v", text, a.Canonical, b, ps) + } + } +} + +func TestPrintNativeNegativeDurationRemainsNumeric(t *testing.T) { + for _, text := range []string{`spans where duration_ms>-3`, `spans where duration_ms between -3 and 5`, `spans where duration_ms in (-3, 5)`} { + a, ps := Compile(text, Options{}) + if len(ps) != 0 { + t.Fatal(ps) + } + b, ps := Compile(a.Canonical, Options{}) + if len(ps) != 0 || b == nil { + t.Fatalf("%q -> %q: %+v", text, a.Canonical, ps) + } + if !reflect.DeepEqual(a.Query, b.Query) { + t.Fatalf("query changed: %+v -> %+v", a.Query, b.Query) + } + } +} + func TestSortPreservesMeasureAliasDuration(t *testing.T) { for _, alias := range []string{"duration", "duration_ms"} { text := "spans | count() as " + alias + " sort " + alias @@ -168,3 +233,20 @@ func TestGroupByAcceptsLiteralKeys(t *testing.T) { } } } + +func TestLiteralKeyQuotesSurviveCheckedMetadata(t *testing.T) { + c, ps := Compile(`spans where attributes['user''s name']:api | count()`, Options{Viz: "table"}) + if len(ps) != 0 { + t.Fatal(ps) + } + engine, _ := newTestEngine(t) + d := panel.Dashboard{Name: "Keys", Panels: []panel.Panel{{ID: "keys", Title: "Keys", Viz: "table", Query: &c.Query}}} + panel.Normalize(&d) + checked, ps, err := panel.Check(t.Context(), engine, &d) + if err != nil || len(ps) != 0 { + t.Fatal(ps, err) + } + if field := checked.Filters["keys"][0].EqField; field != `attributes['user''s name']` { + t.Fatalf("unsafe metadata field: %q", field) + } +} diff --git a/internal/fanql/roundtrip_test.go b/internal/fanql/roundtrip_test.go new file mode 100644 index 00000000..349ddfb4 --- /dev/null +++ b/internal/fanql/roundtrip_test.go @@ -0,0 +1,476 @@ +package fanql + +import ( + "context" + "encoding/json" + "fmt" + "go/ast" + goparser "go/parser" + "go/token" + "math/rand" + "os" + "reflect" + "strconv" + "strings" + "testing" + + "github.com/labstack/fanout/internal/dashboard" + "github.com/labstack/fanout/internal/panel" +) + +type storedQueryFixture struct { + Name string + Panel panel.Panel + Variables []panel.Variable +} + +// Read the actual product fixtures, so additions to any dashboard automatically +// join the round-trip contract without a second manually maintained copy. +func storedQueryFixtures(t testing.TB) []storedQueryFixture { + t.Helper() + var out []storedQueryFixture + add := func(name string, p panel.Panel, vars []panel.Variable) { + if p.Query == nil { + return + } + d := panel.Dashboard{Name: name, Variables: vars, Panels: []panel.Panel{p}} + panel.Normalize(&d) + out = append(out, storedQueryFixture{Name: name, Panel: d.Panels[0], Variables: d.Variables}) + } + d := dashboard.DefaultSpec() + for _, p := range d.Panels { + add("default/"+p.ID, p, d.Variables) + } + raw, err := os.ReadFile("../../scripts/dashboard-eval/testdata/server.json") + if err != nil { + t.Fatal(err) + } + var root any + if err := json.Unmarshal(raw, &root); err != nil { + t.Fatal(err) + } + var walk func(any, string, []panel.Variable) + walk = func(v any, path string, vars []panel.Variable) { + switch x := v.(type) { + case map[string]any: + if value, ok := x["variables"]; ok { + b, _ := json.Marshal(value) + if err := json.Unmarshal(b, &vars); err != nil { + t.Fatal(err) + } + } + if _, ok := x["query"]; ok { + b, _ := json.Marshal(x) + var p panel.Panel + if err := json.Unmarshal(b, &p); err != nil { + t.Fatal(err) + } + add(path, p, vars) + } + for _, key := range referenceKeys(x) { + walk(x[key], path+"/"+key, vars) + } + case []any: + for i, item := range x { + walk(item, fmt.Sprintf("%s/%d", path, i), vars) + } + } + } + walk(root, "eval", nil) + source, err := goparser.ParseFile(token.NewFileSet(), "../mcp/panel_examples.go", nil, 0) + if err != nil { + t.Fatal(err) + } + ast.Inspect(source, func(n ast.Node) bool { + decl, ok := n.(*ast.ValueSpec) + if !ok || len(decl.Values) != 1 || !strings.HasSuffix(decl.Names[0].Name, "Example") { + return true + } + literal, ok := decl.Values[0].(*ast.BasicLit) + if !ok || literal.Kind != token.STRING { + return true + } + text, err := strconv.Unquote(literal.Value) + if err != nil { + t.Fatal(err) + } + var d panel.Dashboard + if err := json.Unmarshal([]byte(text), &d); err != nil { + t.Fatal(err) + } + for _, p := range d.Panels { + add("mcp/"+decl.Names[0].Name+"/"+p.ID, p, d.Variables) + } + return false + }) + if len(out) < 30 { + t.Fatalf("only %d stored fixture queries found", len(out)) + } + return out +} + +func canonicalSQL(t testing.TB, p panel.Parser, signal, filter string) string { + t.Helper() + n, err := p.ParseSQL(context.Background(), "SELECT 1 FROM "+signal+" WHERE ("+filter+")") + if err != nil { + t.Fatal(err) + } + s, err := p.RenderSQL(context.Background(), n) + if err != nil { + t.Fatal(err) + } + return s +} + +func measureMeaning(t testing.TB, p panel.Parser, signal string, expr panel.MeasureExpr) any { + t.Helper() + switch x := expr.(type) { + case panel.MeasureCall: + if x.Field != nil { + f := *x.Field + f.Text = "" + x.Field = &f + } + return x + case panel.MeasureCountIf: + return canonicalSQL(t, p, signal, x.Filter) + case panel.MeasureConst: + return x.Value + case panel.MeasureNeg: + return []any{"neg", measureMeaning(t, p, signal, x.X)} + case panel.MeasureBinary: + return []any{x.Op, measureMeaning(t, p, signal, x.L), measureMeaning(t, p, signal, x.R)} + default: + t.Fatalf("unknown measure expression %T", expr) + return nil + } +} + +func assertQueryTier(t testing.TB, p panel.Parser, stored, lowered panel.Query, tier string) { + t.Helper() + if len(stored.Where) != len(lowered.Where) { + t.Fatalf("entry boundaries changed: %+v -> %+v", stored, lowered) + } + if tier == "exact" { + if !reflect.DeepEqual(stored, lowered) { + t.Fatalf("not byte-exact: %#v -> %#v", stored, lowered) + } + return + } + if tier != "normalized" { + t.Fatalf("unexpected public tier %q", tier) + } + a, b := stored, lowered + a.Where, b.Where, a.Measures, b.Measures = nil, nil, nil, nil + if !reflect.DeepEqual(a, b) { + t.Fatalf("query structure changed: %#v -> %#v", a, b) + } + for i := range stored.Where { + if canonicalSQL(t, p, stored.From, stored.Where[i]) != canonicalSQL(t, p, lowered.From, lowered.Where[i]) { + t.Fatalf("filter meaning changed: %q -> %q", stored.Where[i], lowered.Where[i]) + } + } + if len(stored.Measures) != len(lowered.Measures) { + t.Fatal("measure count changed") + } + for i, text := range stored.Measures { + a, err := panel.ParseMeasure(stored.From, text) + if err != nil { + t.Fatal(err) + } + b, err := panel.ParseMeasure(lowered.From, lowered.Measures[i]) + if err != nil { + t.Fatal(err) + } + if a.Func != b.Func || a.Alias != b.Alias || a.Unit != b.Unit || !reflect.DeepEqual(measureMeaning(t, p, stored.From, a.Expr), measureMeaning(t, p, stored.From, b.Expr)) { + t.Fatalf("measure meaning changed: %q -> %q", text, lowered.Measures[i]) + } + } +} + +func TestRoundTripCorpusFixedPoint(t *testing.T) { + engine, _ := newTestEngine(t) + for _, fixture := range readCorpus(t) { + if fixture.Query == nil || fixture.GateProblems { + continue + } + c, ps := Compile(fixture.Text, Options{Viz: fixture.Viz}) + if len(ps) != 0 { + t.Fatal(ps) + } + // Section 0.11 explicitly keeps raw SQL and string-transform operands + // under the engine's authority. The structured Query has no origin + // metadata that could distinguish those authored forms from stored SQL. + p := &countingParser{Parser: engine, fail: !strings.ContainsRune(fixture.Text, '`') && !strings.Contains(strings.ToLower(fixture.Text), "lower(") && !strings.Contains(strings.ToLower(fixture.Text), "upper(")} + f, ps, err := Format(t.Context(), p, c.Query, FormatOptions{Viz: fixture.Viz}) + // Compile can parse filter-only metrics without a viz. There is no + // metrics row viz, so these are outside Format's valid-query contract. + if len(panel.CompatibleVizzes(&c.Query, nil)) == 0 { + if f != nil || len(ps) == 0 || err != nil { + t.Fatalf("invalid shape %q: %+v %+v %v", fixture.Text, f, ps, err) + } + continue + } + if err != nil || len(ps) != 0 { + t.Fatalf("%q: %+v %v", fixture.Text, ps, err) + } + if !f.Editable || f.Exactness != "exact" || p.fail && (f.Text != c.Canonical || p.calls != 0) { + t.Fatalf("%q: %+v; calls=%d; canonical %q", fixture.Text, f, p.calls, c.Canonical) + } + // A raw fragment may lower identically to native shorthand. Without + // origin metadata Format chooses that shorthand, preserving exact SQL. + if !p.fail { + again, ps := Compile(f.Text, Options{Viz: fixture.Viz}) + if len(ps) != 0 { + t.Fatal(ps) + } + assertQueryTier(t, engine, c.Query, again.Query, f.Exactness) + } + } +} + +func TestRoundTripStoredDashboards(t *testing.T) { + engine, _ := newTestEngine(t) + for _, fixture := range storedQueryFixtures(t) { + t.Run(fixture.Name, func(t *testing.T) { + p := fixture.Panel + stored := *p.Query + f, ps, err := Format(t.Context(), engine, stored, FormatOptions{Viz: p.Viz, Variables: fixture.Variables}) + if err != nil || len(ps) != 0 { + t.Fatalf("format: %+v %v", ps, err) + } + if !f.Editable { + for _, entry := range stored.Where { + if !strings.Contains(f.Text, entry) && !strings.Contains(f.Text, strings.ReplaceAll(entry, "`", "``")) { + t.Fatalf("oversized text lost %q", entry) + } + } + return + } + c, ps := Compile(f.Text, Options{Viz: p.Viz, Variables: fixture.Variables}) + if len(ps) != 0 { + t.Fatalf("%q: %+v", f.Text, ps) + } + assertQueryTier(t, engine, stored, c.Query, f.Exactness) + d := panel.Dashboard{Version: 1, Name: "round trip", Variables: fixture.Variables, Panels: []panel.Panel{p}} + panel.Normalize(&d) + _, before, err := panel.Check(t.Context(), engine, &d) + if err != nil { + t.Fatal(err) + } + d.Panels[0].Query = &c.Query + _, after, err := panel.Check(t.Context(), engine, &d) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(before, after) { + t.Fatalf("Check changed: %+v -> %+v", before, after) + } + }) + } +} + +func ownQueryText(r *rand.Rand, i int) string { + signal := panel.SignalNames()[r.Intn(3)] + columns, _ := panel.SignalColumns(signal) + var fields []panel.Field + for _, f := range columns { + if f.Type == panel.TypeNumber || f.Type == panel.TypeString { + fields = append(fields, f) + } + } + f := fields[r.Intn(len(fields))] + value := `"api*$'𝔘"` + if f.Type == panel.TypeNumber { + value = strconv.Itoa(r.Intn(1000) - 100) + } + filter := f.Name + ":" + value + if signal == "metrics" { + filter = "name:fixture " + filter + } + switch i % 8 { + case 0: + filter += " service:$svc" + case 1: + filter += " (attributes['flag']:true or resource['user name']:x)" + case 2: + filter += " -attributes['missing.key']:*" + case 3: + filter += " `coalesce(service, '``') = 'api'`" + case 4: + filter += " service in $svcs" + case 5: + filter += " -(attributes['n']>2 attributes['n']<9)" + } + if i%11 == 0 && signal != "logs" { + field := "duration" + if signal == "metrics" { + field = "value" + } + return signal + " where " + filter + " | histogram(" + field + ") by service" + } + var measures []panel.MeasureSpec + for _, m := range panel.MeasureSpecs() { + if m.Name == "count_if" { + continue + } + if len(m.Signals) == 0 || containsString(m.Signals, signal) { + measures = append(measures, m) + } + } + m := measures[r.Intn(len(measures))] + measure := m.Name + "()" + arg := "duration" + if signal == "logs" { + arg = "severity_number" + } else if signal == "metrics" { + arg = "value" + } + if m.Args == 1 { + measure = m.Name + "(" + arg + ")" + } else if m.Args == 2 { + measure = m.Name + "(" + arg + ", 0.95)" + } + if i%7 == 0 && signal != "metrics" { + measure = "count_if(service:\"api\") / count() * 100 as ratio" + } + return signal + " where " + filter + " | " + measure + " by service" +} + +func containsString(values []string, value string) bool { + for _, item := range values { + if item == value { + return true + } + } + return false +} + +func TestRoundTripProperties(t *testing.T) { + engine, _ := newTestEngine(t) + r := rand.New(rand.NewSource(20261029)) + vars := []panel.Variable{{Name: "svc", Kind: "text"}, {Name: "svcs", Kind: "custom", Options: []string{"api", "worker"}, Multi: true}} + for i := range 500 { + text := ownQueryText(r, i) + c, ps := Compile(text, Options{Variables: vars}) + if len(ps) != 0 { + t.Fatalf("A[%d] %q: %+v", i, text, ps) + } + p := &countingParser{Parser: engine, fail: !strings.ContainsRune(text, '`')} + f, ps, err := Format(t.Context(), p, c.Query, FormatOptions{Variables: vars}) + if err != nil || len(ps) != 0 || f == nil { + t.Fatalf("A[%d] %q: %+v %v", i, text, ps, err) + } + if !f.Editable || f.Exactness != "exact" || f.Text != c.Canonical || p.fail && p.calls != 0 { + t.Fatalf("A[%d] %q: %+v; calls=%d", i, text, f, p.calls) + } + again, ps := Compile(f.Text, Options{Variables: vars}) + if len(ps) != 0 { + t.Fatal(ps) + } + assertQueryTier(t, engine, c.Query, again.Query, f.Exactness) + bytes := make([]byte, 32) + _, _ = r.Read(bytes) + stored := generatedStructuredQuery(bytes) + formatted, ps, err := Format(t.Context(), engine, stored, FormatOptions{}) + if err != nil || len(ps) != 0 { + t.Fatalf("B[%d]: %+v %v", i, ps, err) + } + // Count runes/bytes/tokens independently; parser bounds cover AST size + // and depth in their own tests. Generator B stays within those bounds. + within := len([]rune(formatted.Text)) <= 4000 && len(formatted.Text) <= 8192 && len(Lex(formatted.Text))-1 <= 1024 + if formatted.Editable != within { + t.Fatalf("B[%d] editable disagrees with independent bounds: %+v", i, formatted) + } + if formatted.Editable { + lowered, ps := Compile(formatted.Text, Options{}) + if len(ps) != 0 { + t.Fatal(ps) + } + assertQueryTier(t, engine, stored, lowered.Query, formatted.Exactness) + p := panel.Panel{ID: "p", Title: "p", Viz: "table", Query: &stored} + d := panel.Dashboard{Name: "property", Panels: []panel.Panel{p}} + panel.Normalize(&d) + _, before, err := panel.Check(t.Context(), engine, &d) + if err != nil { + t.Fatal(err) + } + d.Panels[0].Query = &lowered.Query + _, after, err := panel.Check(t.Context(), engine, &d) + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(before, after) { + t.Fatalf("B[%d] Check changed: %+v -> %+v", i, before, after) + } + } + } +} + +func TestEntryBoundaryShapesDiffer(t *testing.T) { + engine, _ := newTestEngine(t) + queries := []panel.Query{{From: "spans", Where: []string{`attributes['a'] = 1`, `attributes['b'] = 2`}}, {From: "spans", Where: []string{`attributes['a'] = 1 AND attributes['b'] = 2`}}} + texts := []string{} + for _, q := range queries { + f, ps, err := Format(t.Context(), engine, q, FormatOptions{}) + if err != nil || len(ps) != 0 { + t.Fatal(ps, err) + } + texts = append(texts, f.Text) + c, ps := Compile(f.Text, Options{}) + if len(ps) != 0 { + t.Fatal(ps) + } + assertQueryTier(t, engine, q, c.Query, f.Exactness) + } + if texts[0] == texts[1] || texts[0] != `spans where attributes['a']:1 attributes['b']:2` || texts[1] != `spans where (attributes['a']:1 attributes['b']:2)` { + t.Fatal(texts) + } +} + +func TestEditableFalsePreservationThroughEnvelope(t *testing.T) { + q := panel.Query{From: "logs"} + for i := range 16 { + q.Where = append(q.Where, "body = '"+strings.Repeat("x", 480)+strconv.Itoa(i)+"'") + } + p := &countingParser{fail: true} + f, ps, err := Format(t.Context(), p, q, FormatOptions{Viz: "logs"}) + if err != nil || len(ps) != 0 || f == nil || f.Editable || f.Reason == "" || p.calls != 0 { + t.Fatalf("oversized format: %+v %+v %v; engine calls=%d", f, ps, err, p.calls) + } + type envelope struct { + FanQL int `json:"fanql"` + Text string `json:"text"` + Editable bool `json:"editable"` + Query panel.Query `json:"query"` + Viz string `json:"viz"` + Time panel.Time `json:"time"` + } + original := envelope{FanQL: Version, Text: f.Text, Query: q, Viz: "logs", Time: panel.Time{Range: "1h"}} + raw, err := json.Marshal(original) + if err != nil { + t.Fatal(err) + } + // The backend envelope carries the structured representation. Noneditable + // text is never submitted to the bounded public Parse interface here. + var decoded envelope + if err := json.Unmarshal(raw, &decoded); err != nil { + t.Fatal(err) + } + raw, err = json.Marshal(decoded) + if err != nil { + t.Fatal(err) + } + var saved envelope + if err := json.Unmarshal(raw, &saved); err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(original, saved) || saved.Editable || p.calls != 0 { + t.Fatalf("envelope lost structured state: %+v", saved) + } + for i := range 16 { + if !strings.Contains(saved.Text, strings.Repeat("x", 480)+strconv.Itoa(i)) { + t.Fatalf("lost literal %d", i) + } + } +} diff --git a/internal/fanql/semantics_test.go b/internal/fanql/semantics_test.go new file mode 100644 index 00000000..5b4025be --- /dev/null +++ b/internal/fanql/semantics_test.go @@ -0,0 +1,472 @@ +package fanql + +import ( + "context" + "fmt" + "math" + "reflect" + "regexp" + "strings" + "testing" + "time" + + "github.com/labstack/fanout/internal/config" + "github.com/labstack/fanout/internal/ingest" + "github.com/labstack/fanout/internal/panel" + "github.com/labstack/fanout/internal/query" + "github.com/labstack/fanout/internal/telemetry" + telemetrystore "github.com/labstack/fanout/internal/telemetry/store" + collectorlogs "go.opentelemetry.io/proto/otlp/collector/logs/v1" + commonpb "go.opentelemetry.io/proto/otlp/common/v1" + logspb "go.opentelemetry.io/proto/otlp/logs/v1" + "google.golang.org/grpc" +) + +var semanticStart = time.Date(2026, 10, 1, 12, 0, 0, 0, time.UTC) + +func semanticSpan(namespace string, index int, attributes map[string]any) telemetry.Span { + at := semanticStart.Add(time.Duration(index) * time.Second).UnixNano() + return telemetry.Span{ + Namespace: namespace, ServiceName: "api", TraceID: fmt.Sprintf("%s-trace-%d", namespace, index), SpanID: fmt.Sprintf("span-%d", index), + Name: "GET /api", Kind: "SPAN_KIND_SERVER", StatusCode: "STATUS_CODE_OK", HTTPRoute: "/api", StartUnixNanos: at, EndUnixNanos: at + 1e6, + DurationMS: 1, Attributes: attributes, IngestedAt: at, + } +} + +func semanticRun(t *testing.T, executor *panel.Executor, q panel.Query, variables []panel.Variable, vars map[string]panel.Value) panel.Result { + return semanticRunViz(t, executor, q, "table", variables, vars) +} + +func semanticRunViz(t *testing.T, executor *panel.Executor, q panel.Query, viz string, variables []panel.Variable, vars map[string]panel.Value) panel.Result { + t.Helper() + end := semanticStart.Add(time.Hour) + results, err := executor.Run(t.Context(), panel.RunRequest{ + Dashboard: panel.Dashboard{Name: "Semantics", Time: panel.Time{From: &semanticStart, To: &end}, Variables: variables, + Panels: []panel.Panel{{ID: "semantic", Title: "Semantics", Viz: viz, Query: &q}}}, Vars: vars, + }) + if err != nil { + t.Fatal(err) + } + if len(results) != 1 || results[0].Status == panel.StatusError || results[0].Frame == nil { + t.Fatalf("query %+v: %+v", q, results) + } + return results[0] +} + +func semanticValue(t *testing.T, result panel.Result, name string) float64 { + t.Helper() + for i, column := range result.Frame.Columns { + if column.Name == name { + if len(result.Frame.Values[i]) != 1 { + t.Fatalf("expected one aggregate value: %+v", result.Frame) + } + switch value := result.Frame.Values[i][0].(type) { + case float64: + return value + case int64: + return float64(value) + default: + t.Fatalf("unexpected numeric value %T: %v", value, value) + } + } + } + t.Fatalf("missing %s in %+v", name, result.Frame) + return 0 +} + +func semanticCompile(t *testing.T, text string, variables []panel.Variable) panel.Query { + t.Helper() + c, problems := Compile(text, Options{Viz: "table", Variables: variables}) + if len(problems) != 0 { + t.Fatalf("%q: %+v", text, problems) + } + return c.Query +} + +func TestTruthTable(t *testing.T) { + d, repo := newTestEngine(t) + var spans []telemetry.Span + for i, attributes := range []map[string]any{{"k": "v"}, {"k": "w"}, {}} { + spans = append(spans, semanticSpan("values", i, attributes)) + } + for i, code := range []string{"404", "200", "abc", ""} { + span := semanticSpan("http", i, nil) + span.HTTPStatusCode = code + spans = append(spans, span) + } + for i, attributes := range []map[string]any{{"k": "GET /x"}, {"k": "POST /x"}, {}} { + spans = append(spans, semanticSpan("patterns", i, attributes)) + } + for i, attributes := range []map[string]any{{"a": 1, "b": 2}, {"a": 1, "b": 3}, {"a": 0, "b": 2}, {}} { + spans = append(spans, semanticSpan("matrix", i, attributes)) + } + if err := repo.Commit(t.Context(), telemetrystore.Batch{ID: "truth-table", Spans: spans}); err != nil { + t.Fatal(err) + } + executor := panel.NewExecutor(d, 30) + cases := []struct { + namespace, filter string + want int + }{ + {"values", "k:v", 1}, {"values", "-k:v", 2}, {"values", "k!=v", 1}, {"values", "-k!=v", 2}, + {"values", "k ~ v", 1}, {"values", "-k ~ v", 2}, {"values", "k !~ v", 2}, + {"values", "k in (v, x)", 1}, {"values", "-k in (v, x)", 2}, {"values", "k not in (v, x)", 1}, {"values", "-k not in (v, x)", 2}, + {"values", "-k:*", 1}, {"values", "k:*", 2}, {"values", "k is null", 1}, {"values", "k is not null", 2}, + {"http", "http_status_code between 400 and 599", 1}, {"http", "-http_status_code between 400 and 599", 3}, + {"http", "http_status_code not between 400 and 599", 1}, {"http", "-http_status_code not between 400 and 599", 3}, + {"http", "http_status_code>=500", 0}, {"http", "-http_status_code>=500", 4}, + {"patterns", `k like "GET %"`, 1}, {"patterns", `k not like "GET %"`, 1}, {"patterns", `-k like "GET %"`, 2}, {"patterns", `-k not like "GET %"`, 2}, + {"matrix", "-(a:1 b:2)", 3}, {"matrix", "-(a:1 or b:2)", 1}, + {"values", "-`attributes['k'] = 'v'`", 2}, + } + for _, tc := range cases { + t.Run(tc.namespace+"/"+tc.filter, func(t *testing.T) { + q := semanticCompile(t, "spans where namespace:"+tc.namespace+" "+tc.filter+" | count()", nil) + result := semanticRun(t, executor, q, nil, nil) + if got := semanticValue(t, result, "count"); got != float64(tc.want) { + t.Fatalf("got %v, want %d; %s", got, tc.want, result.SQL) + } + }) + } + t.Run("stored SQL negative stays SQL", func(t *testing.T) { + q := panel.Query{From: "spans", Where: []string{"namespace = 'values'", "NOT (attributes['k'] = 'v')"}, Measures: []string{"count()"}} + f, problems, err := Format(t.Context(), d, q, FormatOptions{Viz: "table"}) + if err != nil || len(problems) != 0 { + t.Fatalf("format: %+v %v", problems, err) + } + if !strings.Contains(f.Text, "`NOT (attributes['k'] = 'v')`") { + t.Fatal(f.Text) + } + result := semanticRun(t, executor, semanticCompile(t, f.Text, nil), nil, nil) + if got := semanticValue(t, result, "count"); got != 1 { + t.Fatalf("stored NOT matched %v, want 1", got) + } + }) + t.Run("numeric variable uses literal ordering", func(t *testing.T) { + variables := []panel.Variable{{Name: "code", Kind: "text"}} + q := semanticCompile(t, "spans where namespace:http http_status_code>=$code | count()", variables) + result := semanticRun(t, executor, q, variables, map[string]panel.Value{"code": {Values: []string{"500"}}}) + if got := semanticValue(t, result, "count"); got != 0 { + t.Fatalf("string variable matched %v, want 0", got) + } + }) + // Canonical telemetry's body and HTTP columns are non-nullable strings. + // VALUES supplies actual SQL NULLs to exercise the complete leaf rule too. + for _, tc := range []struct { + text, values, column string + want int + }{ + {`logs where -length(body)>3`, "('long'), ('x'), (NULL)", "body", 2}, + {`spans where -starts_with(http_route, "/api")`, "('/api/cart'), ('/other'), (NULL)", "http_route", 2}, + {`spans where http_status_code between 400 and 599`, "('404'), ('200'), ('abc'), (NULL)", "http_status_code", 1}, + {`spans where -http_status_code between 400 and 599`, "('404'), ('200'), ('abc'), (NULL)", "http_status_code", 3}, + {`spans where http_status_code not between 400 and 599`, "('404'), ('200'), ('abc'), (NULL)", "http_status_code", 1}, + {`spans where -http_status_code not between 400 and 599`, "('404'), ('200'), ('abc'), (NULL)", "http_status_code", 3}, + {`spans where http_status_code>=500`, "('404'), ('200'), ('abc'), (NULL)", "http_status_code", 0}, + {`spans where -http_status_code>=500`, "('404'), ('200'), ('abc'), (NULL)", "http_status_code", 4}, + } { + t.Run("actual NULL/"+tc.text, func(t *testing.T) { + c, problems := Compile(tc.text, Options{}) + if len(problems) != 0 { + t.Fatal(problems) + } + var count int + if err := d.QueryRowScan(t.Context(), []any{&count}, "SELECT count(*) FROM (VALUES "+tc.values+") t("+tc.column+") WHERE "+c.Query.Where[0]); err != nil { + t.Fatal(err) + } + if count != tc.want { + t.Fatalf("got %d, want %d", count, tc.want) + } + }) + } +} + +func TestVariablesUnderAllPerConstruct(t *testing.T) { + d, repo := newTestEngine(t) + var spans []telemetry.Span + for i, status := range []string{"STATUS_CODE_ERROR", "STATUS_CODE_OK", "STATUS_CODE_ERROR", "STATUS_CODE_UNSET"} { + span := semanticSpan("all", i, map[string]any{"x": true}) + span.StatusCode = status + if i > 1 { + span.ServiceName = "worker" + } + spans = append(spans, span) + } + if err := repo.Commit(t.Context(), telemetrystore.Batch{ID: "all-constructs", Spans: spans}); err != nil { + t.Fatal(err) + } + executor := panel.NewExecutor(d, 30) + variables := []panel.Variable{{Name: "service", Kind: "query", From: "spans", Field: "service", IncludeAll: true}} + for _, tc := range []struct { + filter string + entries, remaining, rows int + }{ + {"service:$service status:error", 2, 1, 2}, + {"(service:$service status:error)", 1, 0, 4}, + {"service:$service or service:worker", 1, 0, 4}, + {"service:$service (status:error or status:unset)", 2, 1, 3}, + {"-service:$service", 1, 0, 4}, + {"`service = $service AND attributes['x'] = true`", 1, 0, 4}, + } { + t.Run(tc.filter, func(t *testing.T) { + q := semanticCompile(t, "spans where "+tc.filter+" | count()", variables) + if len(q.Where) != tc.entries { + t.Fatalf("authored entries %d, want %d", len(q.Where), tc.entries) + } + result := semanticRun(t, executor, q, variables, map[string]panel.Value{"service": {All: true}}) + if got := semanticValue(t, result, "count"); got != float64(tc.rows) { + t.Fatalf("got %v, want %d", got, tc.rows) + } + if got := strings.Count(result.SQL, " AND (("); got != tc.remaining { + t.Fatalf("remaining filters %d, want %d: %s", got, tc.remaining, result.SQL) + } + if strings.Contains(result.SQL, "$service") { + t.Fatal("All variable reached execution SQL") + } + }) + } + c, problems := Compile("spans | count_if(service:$service)", Options{Variables: variables}) + if c != nil || len(problems) != 1 || problems[0].Message != "variables are not allowed inside count_if" { + t.Fatalf("count_if: %+v %+v", c, problems) + } +} + +type semanticSubmitter struct { + repo *telemetrystore.Repository + bands []string +} + +func (s *semanticSubmitter) Submit(ctx context.Context, batch telemetrystore.Batch) error { + for _, row := range batch.Logs { + s.bands = append(s.bands, row.Severity) + } + batch.ID = "severity-ingress" + return s.repo.Commit(ctx, batch) +} + +type semanticRegistrar struct { + logs collectorlogs.LogsServiceServer +} + +func (r *semanticRegistrar) RegisterService(_ *grpc.ServiceDesc, service any) { + if logs, ok := service.(collectorlogs.LogsServiceServer); ok { + r.logs = logs + } +} + +func TestSeverityBandsEndToEnd(t *testing.T) { + d, repo := newTestEngine(t) + submitter := &semanticSubmitter{repo: repo} + registrar := &semanticRegistrar{} + ingest.RegisterOTLP(registrar, ingest.NewServer(config.Config{DefaultNamespace: "severity"}, submitter)) + pairs := []struct { + text string + number int32 + }{{"WARN2", 14}, {"ERROR", 9}, {"FATAL", 0}, {"INFO2", 0}, {"custom", 0}, {"", 0}, {"info", 9}, {"error", 17}} + var records []*logspb.LogRecord + for i, pair := range pairs { + records = append(records, &logspb.LogRecord{TimeUnixNano: uint64(semanticStart.Add(time.Duration(i) * time.Second).UnixNano()), + SeverityText: pair.text, SeverityNumber: logspb.SeverityNumber(pair.number), Body: &commonpb.AnyValue{Value: &commonpb.AnyValue_StringValue{StringValue: fmt.Sprintf("row-%d", i)}}}) + } + _, err := registrar.logs.Export(t.Context(), &collectorlogs.ExportLogsServiceRequest{ResourceLogs: []*logspb.ResourceLogs{{ScopeLogs: []*logspb.ScopeLogs{{LogRecords: records}}}}}) + if err != nil { + t.Fatal(err) + } + wantBands := []string{"WARN", "INFO", "FATAL", "INFO", "CUSTOM", "UNSPECIFIED", "INFO", "ERROR"} + if !reflect.DeepEqual(submitter.bands, wantBands) { + t.Fatalf("ingress bands %v, want %v", submitter.bands, wantBands) + } + executor := panel.NewExecutor(d, 30) + for _, tc := range []struct { + filter string + want int + }{ + {"severity>=warn", 3}, {"severity=error", 2}, {"severity:custom", 1}, + {"severity>=trace", 6}, {"severity>=trace severity:custom", 0}, {"severity>=trace severity:unspecified", 0}, + } { + t.Run(tc.filter, func(t *testing.T) { + q := semanticCompile(t, "logs where "+tc.filter+" | count()", nil) + result := semanticRun(t, executor, q, nil, nil) + if got := semanticValue(t, result, "count"); got != float64(tc.want) { + t.Fatalf("got %v, want %d", got, tc.want) + } + }) + } + q := semanticCompile(t, "logs | error_rate()", nil) + if got := semanticValue(t, semanticRun(t, executor, q, nil, nil), "error_rate"); math.Abs(got-25) > 1e-9 { + t.Fatalf("error_rate = %v, want 25%% (2 of 8 rows)", got) + } +} + +var semanticVariables = regexp.MustCompile(`\$([A-Za-z_][A-Za-z_0-9]*)`) + +func semanticCheckQuery(t *testing.T, d *query.Duck, q panel.Query) { + t.Helper() + var variables []panel.Variable + seen := map[string]bool{} + for _, match := range semanticVariables.FindAllStringSubmatch(strings.Join(q.Where, " "), -1) { + name := match[1] + if !seen[name] { + variables = append(variables, panel.Variable{Name: name, Kind: "text"}) + seen[name] = true + } + } + dashboard := panel.Dashboard{Name: "Binding", Variables: variables, Panels: []panel.Panel{{ID: "binding", Title: "Binding", Viz: "table", Query: &q}}} + panel.Normalize(&dashboard) + if _, problems, err := panel.Check(t.Context(), d, &dashboard); err != nil || len(problems) != 0 { + t.Fatalf("query %+v: %+v %v", q, problems, err) + } +} + +func TestEngineBindingOfEveryLoweredShape(t *testing.T) { + d, _ := newTestEngine(t) + seen := map[string]bool{} + for _, fixture := range readCorpus(t) { + if fixture.Query == nil || fixture.GateProblems { + continue + } + for _, entry := range fixture.Query.Where { + key := fixture.Query.From + "\x00" + entry + if seen[key] { + continue + } + seen[key] = true + t.Run(fixture.Query.From+"/"+entry, func(t *testing.T) { + semanticCheckQuery(t, d, panel.Query{From: fixture.Query.From, Where: []string{entry}, Measures: []string{"count()"}}) + }) + } + for _, measure := range fixture.Query.Measures { + if !strings.Contains(measure, "count_if(") { + continue + } + key := fixture.Query.From + "\x00measure:" + measure + if seen[key] { + continue + } + seen[key] = true + t.Run(fixture.Query.From+"/"+measure, func(t *testing.T) { + semanticCheckQuery(t, d, panel.Query{From: fixture.Query.From, Measures: []string{measure}}) + }) + } + } + if len(seen) < 20 { + t.Fatalf("only %d distinct corpus shapes were bound", len(seen)) + } + c, problems := Compile("spans where k in ("+strings.TrimSuffix(strings.Repeat("0,", 100), ",")+") | count()", Options{Viz: "table"}) + if len(problems) != 0 { + t.Fatal(problems) + } + if len(c.Query.Where[0]) > 500 { + t.Fatal("the 100-value fixture crossed the filter byte bound") + } + semanticCheckQuery(t, d, c.Query) +} + +func TestWorkloadsEndToEnd(t *testing.T) { + d, repo := newTestEngine(t) + batch := telemetrystore.Batch{ID: "v1-workloads"} + for minute := range 60 { + attributes := map[string]any{"http.target": "/cart", "db.statement": "SELECT * FROM orders"} + if minute%10 != 0 { + attributes["user.id"] = fmt.Sprintf("user-%d", minute%3) + } + span := semanticSpan("workloads", minute, attributes) + span.StartUnixNanos = semanticStart.Add(time.Duration(minute) * time.Minute).UnixNano() + span.ServiceName, span.HTTPRoute, span.TraceID = "checkout", "/cart", fmt.Sprintf("trace-%d", minute) + span.DurationMS = 100 + if minute%2 == 0 { + span.DurationMS = 900 + } else { + span.HTTPRoute = "/payment" + } + span.EndUnixNanos = span.StartUnixNanos + int64(span.DurationMS*1e6) + switch minute % 3 { + case 0: + span.HTTPStatusCode, span.StatusCode, span.DBSystem, span.Name = "500", "STATUS_CODE_ERROR", "postgresql", "SELECT orders" + case 1: + span.HTTPStatusCode, span.StatusCode = "404", "STATUS_CODE_UNSET" + default: + span.HTTPStatusCode, span.StatusCode = "200", "STATUS_CODE_OK" + } + batch.Spans = append(batch.Spans, span) + } + for minute := range 12 { + at := semanticStart.Add(time.Duration(minute) * time.Minute).UnixNano() + severity := "INFO" + if minute%3 == 0 { + severity = "ERROR" + } + batch.Logs = append(batch.Logs, telemetry.Log{Namespace: "workloads", ServiceName: "api", EventUnixNanos: at, TimeUnixNanos: at, IngestedAt: at, + Severity: severity, Body: fmt.Sprintf("timeout request %d failed", minute), BodyTemplate: "timeout request <*> failed", TraceID: fmt.Sprintf("trace-%d", minute)}) + } + for scrape := range 3 { + // last(value) deliberately observes only the final five minutes. + at := semanticStart.Add(time.Duration(scrape+57) * time.Minute).UnixNano() + base := telemetry.Metric{Namespace: "workloads", ServiceName: "checkout", EventUnixNanos: at, TimeUnixNanos: at, IngestedAt: at, + Resource: map[string]any{"k8s.pod.name": "checkout-0"}} + counter := base + counter.Name, counter.Type, counter.Monotonic, counter.Temporality = "http.server.requests", "sum", true, "cumulative" + counter.StartTimeUnixNanos, counter.Value = semanticStart.UnixNano(), float64((scrape+1)*10) + queue := base + queue.Name, queue.Type, queue.Value = "queue.lag", "gauge", float64(4-scrape) + restarts := base + restarts.Name, restarts.Type, restarts.Value = "k8s.container.restarts", "gauge", float64(2+scrape) + histogram := base + histogram.Name, histogram.Type, histogram.Temporality, histogram.Unit = "http.server.duration", "histogram", "delta", "ms" + histogram.StartTimeUnixNanos = semanticStart.Add(time.Duration(scrape+56) * time.Minute).UnixNano() + histogram.HistBoundsJSON, histogram.HistCountsJSON, histogram.HistCount, histogram.HistSum = "[100,500]", "[2,3,5]", 10, 1500 + for _, metric := range []telemetry.Metric{counter, queue, restarts, histogram} { + metric.SeriesID = telemetry.MetricSeriesID(metric) + batch.Metrics = append(batch.Metrics, metric) + } + } + if err := repo.Commit(t.Context(), batch); err != nil { + t.Fatal(err) + } + executor := panel.NewExecutor(d, 30) + variables := []panel.Variable{{Name: "service", Kind: "query", From: "spans", Field: "service", IncludeAll: true}} + vars := map[string]panel.Value{"service": {Values: []string{"checkout"}}} + vizzes := []string{"timeseries", "traces", "table", "table", "stat", "histogram", "table", "table", "logs", "log_patterns", "timeseries", "table"} + cases := make([]struct{ text, viz string }, 0, len(glanceExamples)+10) + for i, text := range glanceExamples { + cases = append(cases, struct{ text, viz string }{text, vizzes[i]}) + } + cases = append(cases, []struct{ text, viz string }{ + {`spans where kind:server | p99(duration) by http_route every 1m`, "timeseries"}, + {`spans | p95(duration) by operation sort p95 limit 10`, "table"}, + {`logs where trace_id:trace-0`, "logs"}, + {`metrics where name:http.server.duration | histogram(value)`, "histogram"}, + {`spans | count_if(http_status_code>=400 http_status_code<500) as client_errors, count_if(http_status_code>=500) as server_errors by http_route`, "table"}, + {`spans where db_system:postgresql duration>500ms | count() by attributes['db.statement']`, "table"}, + {`metrics where name:queue.lag | last(value) by service`, "table"}, + {`spans | count_if(status:error) / count() * 100 as error_pct by http_route`, "table"}, + {`spans | count_if(status:error) as errors, count() as total, count_if(status:error) / count() * 100 as error_pct by http_route`, "table"}, + {`spans where -user.id:* | count()`, "table"}, + }...) + for _, tc := range cases { + t.Run(tc.text, func(t *testing.T) { + c, problems := Compile(tc.text, Options{Viz: tc.viz, Variables: variables}) + if len(problems) != 0 { + t.Fatalf("compile: %+v", problems) + } + dashboard := panel.Dashboard{Name: "V1 workload", Variables: variables, Panels: []panel.Panel{{ID: "workload", Title: "Workload", Viz: tc.viz, Query: &c.Query}}} + panel.Normalize(&dashboard) + if _, problems, err := panel.Check(t.Context(), d, &dashboard); len(problems) != 0 || err != nil { + t.Fatalf("check: %+v %v", problems, err) + } + result := semanticRunViz(t, executor, c.Query, tc.viz, variables, vars) + if result.Status != panel.StatusOK || result.Frame.Rows == 0 { + t.Fatalf("workload returned no matching data: %+v", result) + } + if strings.Contains(tc.text, "name:queue.lag") && semanticValue(t, result, "last") != 2 { + t.Fatalf("queue lag: %+v", result.Frame) + } + if strings.Contains(tc.text, "name:k8s.container.restarts") && semanticValue(t, result, "last") != 4 { + t.Fatalf("pod restarts: %+v", result.Frame) + } + if tc.text == `spans where -user.id:* | count()` && semanticValue(t, result, "count") != 6 { + t.Fatalf("missing users: %+v", result.Frame) + } + }) + } +} diff --git a/internal/fanql/testdata/canonical.v1.golden b/internal/fanql/testdata/canonical.v1.golden new file mode 100644 index 00000000..1fa68072 --- /dev/null +++ b/internal/fanql/testdata/canonical.v1.golden @@ -0,0 +1,414 @@ +{ + "logs": "logs", + "logs sort +time": "logs sort +time", + "logs sort duration": "logs sort duration", + "logs sort time": "logs sort time", + "logs where \"api$svc\"": "logs where \"api$svc\"", + "logs where \"api*\"": "logs where \"api*\"", + "logs where \"http://x:8080/y\"": "logs where \"http://x:8080/y\"", + "logs where \"limit\"": "logs where \"limit\"", + "logs where (`body = 'a' OR body = 'b'` service:api)": "logs where (`body = 'a' OR body = 'b'` service:api)", + "logs where --severity is null": "logs where -severity:*", + "logs where --severity:error": "logs where severity:error", + "logs where -`coalesce(body, '') = ''`": "logs where -`coalesce(body, '') = ''`", + "logs where -body like \"GET %\"": "logs where -body like \"GET %\"", + "logs where -body not like \"GET %\"": "logs where -body not like \"GET %\"", + "logs where -body ~ \"100%\"": "logs where -100%", + "logs where -length(body) > 1000": "logs where -length(body)>1000", + "logs where -not a:1": "logs where attributes['a']:1", + "logs where -severity not between info and error": "logs where -severity not in (info, warn, error)", + "logs where -severity not in (warn, error, fatal)": "logs where -severity not in (warn, error, fatal)", + "logs where -severity>=warn": "logs where -severity>=warn", + "logs where 2e3": "logs where 2e3", + "logs where `coalesce(body, '``') = ''`": "logs where `coalesce(body, '``') = ''`", + "logs where `coalesce(body,'|')=''` | count()": "logs where `coalesce(body,'|')=''` | count()", + "logs where attributes['top']:x": "logs where attributes['top']:x", + "logs where attributes['𝔘.key']:\"✓\" resource.k8s.pod.name:x a.b:y": "logs where attributes['𝔘.key']:✓ resource.k8s.pod.name:x a.b:y", + "logs where body ilike \"%a_b%\"": "logs where body ilike \"%a_b%\"", + "logs where body not like \"GET %\"": "logs where body not like \"GET %\"", + "logs where body ~ \"a_b\"": "logs where a_b", + "logs where body ~ $term": "logs where body ~ $term", + "logs where body ~ 2e3": "logs where 2e3", + "logs where body:\"a | b sort c\" attributes['x.by']:y": "logs where body:\"a | b sort c\" x.by:y", + "logs where body:\"héllo ✓\" x": "logs where body:\"héllo ✓\" x", + "logs where length(body) > 1000": "logs where length(body)>1000", + "logs where length(body)>1000": "logs where length(body)>1000", + "logs where length(body)>1e3": "logs where length(body)>1000", + "logs where lower(service)=$svc": "logs where lower(service)=$svc", + "logs where not not a:1": "logs where attributes['a']:1", + "logs where regexp_matches(body, \"error.*\")": "logs where regexp_matches(body, \"error.*\")", + "logs where ser": "logs where ser", + "logs where service": "logs where service", + "logs where service in (sort, limit)": "logs where service in (\"sort\", \"limit\")", + "logs where service:\"TRUE\"": "logs where service:\"TRUE\"", + "logs where service:\"api$svc\"": "logs where service:\"api$svc\"", + "logs where service:\"api*\"": "logs where service:\"api*\"", + "logs where service:api severity:error timeout sort time limit 200": "logs where service:api severity:error timeout sort time limit 200", + "logs where service:where": "logs where service:\"where\"", + "logs where severity ": "logs where severity", + "logs where severity between info and error": "logs where severity between info and error", + "logs where severity in (info, warn, error)": "logs where severity between info and error", + "logs where severity not between info and error": "logs where severity not in (info, warn, error)", + "logs where severity ~ \"ERROR\"": "logs where severity ~ ERROR", + "logs where severity ~ ERROR": "logs where severity ~ ERROR", + "logs where severity ~ error": "logs where severity ~ error", + "logs where severity:\"1H\"": "logs where severity:\"1H\"", + "logs where severity:\"ERROR\"": "logs where severity:error", + "logs where severity:\"TRUE\"": "logs where severity:\"TRUE\"", + "logs where severity:\"error\"": "logs where severity:\"error\"", + "logs where severity:14": "logs where severity:14", + "logs where severity:DEBUG": "logs where severity:debug", + "logs where severity:ERROR": "logs where severity:error", + "logs where severity:Error": "logs where severity:error", + "logs where severity:FATAL": "logs where severity:fatal", + "logs where severity:INFO": "logs where severity:info", + "logs where severity:TRACE": "logs where severity:trace", + "logs where severity:WARN": "logs where severity:warn", + "logs where severity:alert": "logs where severity:fatal", + "logs where severity:crit": "logs where severity:fatal", + "logs where severity:critical": "logs where severity:fatal", + "logs where severity:custom": "logs where severity:custom", + "logs where severity:dbg": "logs where severity:debug", + "logs where severity:debug": "logs where severity:debug", + "logs where severity:emerg": "logs where severity:fatal", + "logs where severity:emergency": "logs where severity:fatal", + "logs where severity:err": "logs where severity:error", + "logs where severity:error": "logs where severity:error", + "logs where severity:exception": "logs where severity:error", + "logs where severity:fatal": "logs where severity:fatal", + "logs where severity:fine": "logs where severity:debug", + "logs where severity:finest": "logs where severity:trace", + "logs where severity:info": "logs where severity:info", + "logs where severity:information": "logs where severity:info", + "logs where severity:informational": "logs where severity:info", + "logs where severity:notice": "logs where severity:info", + "logs where severity:panic": "logs where severity:fatal", + "logs where severity:severe": "logs where severity:error", + "logs where severity:trace": "logs where severity:trace", + "logs where severity:true": "logs where severity:true", + "logs where severity:verbose": "logs where severity:trace", + "logs where severity:warn": "logs where severity:warn", + "logs where severity:warning": "logs where severity:warn", + "logs where severity:where": "logs where severity:\"WHERE\"", + "logs where severity=warn": "logs where severity>=warn", + "logs where severity>=warn | count() by body_template sort count limit 10": "logs where severity>=warn | count() by body_template sort count limit 10", + "logs where severity>error": "logs where severity>=fatal", + "logs where severity_number>=14": "logs where severity_number>=14", + "logs where time>\"2026-10-29T10:00:00Z\" time<\"2026-10-29T10:01:00Z\"": "logs where time>\"2026-10-29T10:00:00Z\" time<\"2026-10-29T10:01:00Z\"", + "logs where top:x": "logs where attributes['top']:x", + "logs where trace_id:trace1": "logs where trace_id:trace1", + "logs | count() by body_template sort count": "logs | count() by body_template sort count", + "metrics": "metrics", + "metrics ": "metrics", + "metrics where name:http.server.duration": "metrics where name:http.server.duration", + "metrics where name:http.server.duration | histogram(value)": "metrics where name:http.server.duration | histogram(value)", + "metrics where name:http.server.requests | rate() by service every 1m": "metrics where name:http.server.requests | rate() by service every 1m", + "metrics where name:k8s.container.restarts | last(value) by resource.k8s.pod.name": "metrics where name:k8s.container.restarts | last(value) by resource.k8s.pod.name", + "metrics where name:queue.lag | last(value) by service": "metrics where name:queue.lag | last(value) by service", + "metrics where name:x | histogram(value) every 1m": "metrics where name:x | histogram(value) every 1m", + "metrics where rate:x": "metrics where attributes['rate']:x", + "metrics where type:\"counter\" | count()": "metrics where type:counter | count()", + "metrics where type:COUNTER | count()": "metrics where type:counter | count()", + "metrics where type:counter": "metrics where type:counter", + "metrics where type:counter | count()": "metrics where type:counter | count()", + "metrics where type:false": "metrics where type:false", + "metrics where type:false | count()": "metrics where type:false | count()", + "metrics where type:gauge | count()": "metrics where type:gauge | count()", + "metrics where type:histogram | count()": "metrics where type:histogram | count()", + "metrics where type:summary | count()": "metrics where type:summary | count()", + "metrics where type:updown | count()": "metrics where type:updown | count()", + "metrics where value>-3": "metrics where value>-3", + "metrics | avg(value)": "metrics | avg(value)", + "metrics | last(value) by resource.k8s.pod.name": "metrics | last(value) by resource.k8s.pod.name", + "spans": "spans", + "spans ": "spans", + "spans sort +duration": "spans sort +duration", + "spans sort +start": "spans sort +start", + "spans sort duration": "spans sort duration", + "spans sort errors": "spans sort errors", + "spans sort errors limit 50": "spans sort errors limit 50", + "spans status:error": "spans where status:error", + "spans status:error | count()": "spans where status:error | count()", + "spans status:error | count() by service": "spans where status:error | count() by service", + "spans where (a:1 b:2)": "spans where (attributes['a']:1 attributes['b']:2)", + "spans where (a:1 b:2) or c:3": "spans where (attributes['a']:1 attributes['b']:2) or attributes['c']:3", + "spans where (a:1)": "spans where attributes['a']:1", + "spans where (attributes['a']:1 attributes['b']:2)": "spans where (attributes['a']:1 attributes['b']:2)", + "spans where (attributes['a']:1 or attributes['b']:2) service:api": "spans where (attributes['a']:1 or attributes['b']:2) service:api", + "spans where (service:$service status:error)": "spans where (service:$service status:error)", + "spans where -(a:1 or b:2)": "spans where (-attributes['a']:1 -attributes['b']:2)", + "spans where -(status:error kind:server)": "spans where -status:error or -kind:server", + "spans where -attributes['k'] between 1 and 5": "spans where -attributes['k'] between 1 and 5", + "spans where -attributes['k'] ilike \"GET %\"": "spans where -attributes['k'] ilike \"GET %\"", + "spans where -attributes['k'] in (1, true, api, \"api*\")": "spans where -attributes['k'] in (1, true, api, \"api*\")", + "spans where -attributes['k'] is not null": "spans where -attributes['k']:*", + "spans where -attributes['k'] is null": "spans where attributes['k']:*", + "spans where -attributes['k'] like \"GET %\"": "spans where -attributes['k'] like \"GET %\"", + "spans where -attributes['k'] not between 1 and 5": "spans where -attributes['k'] not between 1 and 5", + "spans where -attributes['k'] not ilike \"GET %\"": "spans where -attributes['k'] not ilike \"GET %\"", + "spans where -attributes['k'] not in (1, true, api, \"api*\")": "spans where -attributes['k'] not in (1, true, api, \"api*\")", + "spans where -attributes['k'] not like \"GET %\"": "spans where -attributes['k'] not like \"GET %\"", + "spans where -duration not between 1s and 2s": "spans where -duration not between 1s and 2s", + "spans where -duration>1s": "spans where -duration>1s", + "spans where -http_status_code between 400 and 599": "spans where -http_status_code between 400 and 599", + "spans where -http_status_code not between 400 and 599": "spans where -http_status_code not between 400 and 599", + "spans where -http_status_code:500": "spans where -http_status_code:500", + "spans where -http_status_code>=500": "spans where -http_status_code>=500", + "spans where -k ~ v": "spans where -attributes['k'] ~ v", + "spans where -k:$v": "spans where -attributes['k']:$v", + "spans where -service in (a, b)": "spans where -service in (a, b)", + "spans where -service not in (a, b)": "spans where -service not in (a, b)", + "spans where -service!=api": "spans where -service!=api", + "spans where -starts_with(http_route, \"/api\")": "spans where -starts_with(http_route, \"/api\")", + "spans where -user.id:*": "spans where -user.id:*", + "spans where HTTP.Target:x": "spans where HTTP.Target:x", + "spans where Service:api": "spans where service:api", + "spans where a:1 (b:2 or c:3)": "spans where attributes['a']:1 (attributes['b']:2 or attributes['c']:3)", + "spans where a:1 b:2 (c:3 or d:4) (e:5 f:6)": "spans where attributes['a']:1 attributes['b']:2 (attributes['c']:3 or attributes['d']:4) (attributes['e']:5 attributes['f']:6)", + "spans where a:1 or b:2": "spans where attributes['a']:1 or attributes['b']:2", + "spans where a:1 or c:3": "spans where attributes['a']:1 or attributes['c']:3", + "spans where a:1 | count_if(status:error -http.target:/healthz) / count() * 1.5 as x by resource.k8s.pod.name every 1m": "spans where attributes['a']:1 | count_if(status:error -http.target:/healthz) / count() * 1.5 as x by resource.k8s.pod.name every 1m", + "spans where attr": "spans where attr", + "spans where attributes.http.target:/h": "spans where http.target:/h", + "spans where attributes['Resource.k']:x": "spans where attributes['Resource.k']:x", + "spans where attributes['a']:1 or attributes['b']:2": "spans where attributes['a']:1 or attributes['b']:2", + "spans where attributes['attributes.k']:x": "spans where attributes['attributes.k']:x", + "spans where attributes['flag']:true": "spans where attributes['flag']:true", + "spans where attributes['k'] between 1 and 5": "spans where attributes['k'] between 1 and 5", + "spans where attributes['k'] ilike \"GET %\"": "spans where attributes['k'] ilike \"GET %\"", + "spans where attributes['k'] in (1, true, api, \"api*\")": "spans where attributes['k'] in (1, true, api, \"api*\")", + "spans where attributes['k'] is not null": "spans where attributes['k']:*", + "spans where attributes['k'] is null": "spans where -attributes['k']:*", + "spans where attributes['k'] like \"GET %\"": "spans where attributes['k'] like \"GET %\"", + "spans where attributes['k'] not between 1 and 5": "spans where attributes['k'] not between 1 and 5", + "spans where attributes['k'] not ilike \"GET %\"": "spans where attributes['k'] not ilike \"GET %\"", + "spans where attributes['k'] not in (1, true, api, \"api*\")": "spans where attributes['k'] not in (1, true, api, \"api*\")", + "spans where attributes['k'] not like \"GET %\"": "spans where attributes['k'] not like \"GET %\"", + "spans where attributes['k']!=\"a$svc\"": "spans where attributes['k']!=\"a$svc\"", + "spans where attributes['k']!=\"api*\"": "spans where attributes['k']!=\"api*\"", + "spans where attributes['k']!=-3": "spans where attributes['k']!=-3", + "spans where attributes['k']!=1.5": "spans where attributes['k']!=1.5", + "spans where attributes['k']!=2e3": "spans where attributes['k']!=2000", + "spans where attributes['k']!=5": "spans where attributes['k']!=5", + "spans where attributes['k']!=api": "spans where attributes['k']!=api", + "spans where attributes['k']!=false": "spans where attributes['k']!=false", + "spans where attributes['k']!=true": "spans where attributes['k']!=true", + "spans where attributes['k']!~\"a$svc\"": "spans where -attributes['k'] ~ \"a$svc\"", + "spans where attributes['k']!~\"api*\"": "spans where -attributes['k'] ~ \"api*\"", + "spans where attributes['k']!~-3": "spans where -attributes['k'] ~ \"-3\"", + "spans where attributes['k']!~1.5": "spans where -attributes['k'] ~ \"1.5\"", + "spans where attributes['k']!~2e3": "spans where -attributes['k'] ~ \"2e3\"", + "spans where attributes['k']!~5": "spans where -attributes['k'] ~ \"5\"", + "spans where attributes['k']!~api": "spans where -attributes['k'] ~ api", + "spans where attributes['k']!~false": "spans where -attributes['k'] ~ \"false\"", + "spans where attributes['k']!~true": "spans where -attributes['k'] ~ \"true\"", + "spans where attributes['k']:\"a$svc\"": "spans where attributes['k']:\"a$svc\"", + "spans where attributes['k']:\"api*\"": "spans where attributes['k']:\"api*\"", + "spans where attributes['k']:-3": "spans where attributes['k']:-3", + "spans where attributes['k']:1.5": "spans where attributes['k']:1.5", + "spans where attributes['k']:2e3": "spans where attributes['k']:2000", + "spans where attributes['k']:5": "spans where attributes['k']:5", + "spans where attributes['k']:api": "spans where attributes['k']:api", + "spans where attributes['k']:false": "spans where attributes['k']:false", + "spans where attributes['k']:true": "spans where attributes['k']:true", + "spans where attributes['k']<\"a$svc\"": "spans where attributes['k']<\"a$svc\"", + "spans where attributes['k']<\"api*\"": "spans where attributes['k']<\"api*\"", + "spans where attributes['k']<-3": "spans where attributes['k']<-3", + "spans where attributes['k']<1.5": "spans where attributes['k']<1.5", + "spans where attributes['k']<2e3": "spans where attributes['k']<2000", + "spans where attributes['k']<5": "spans where attributes['k']<5", + "spans where attributes['k']<=\"a$svc\"": "spans where attributes['k']<=\"a$svc\"", + "spans where attributes['k']<=\"api*\"": "spans where attributes['k']<=\"api*\"", + "spans where attributes['k']<=-3": "spans where attributes['k']<=-3", + "spans where attributes['k']<=1.5": "spans where attributes['k']<=1.5", + "spans where attributes['k']<=2e3": "spans where attributes['k']<=2000", + "spans where attributes['k']<=5": "spans where attributes['k']<=5", + "spans where attributes['k']<=api": "spans where attributes['k']<=api", + "spans where attributes['k']<=false": "spans where attributes['k']<=false", + "spans where attributes['k']<=true": "spans where attributes['k']<=true", + "spans where attributes['k']<>\"a$svc\"": "spans where attributes['k']!=\"a$svc\"", + "spans where attributes['k']<>\"api*\"": "spans where attributes['k']!=\"api*\"", + "spans where attributes['k']<>-3": "spans where attributes['k']!=-3", + "spans where attributes['k']<>1.5": "spans where attributes['k']!=1.5", + "spans where attributes['k']<>2e3": "spans where attributes['k']!=2000", + "spans where attributes['k']<>5": "spans where attributes['k']!=5", + "spans where attributes['k']<>api": "spans where attributes['k']!=api", + "spans where attributes['k']<>false": "spans where attributes['k']!=false", + "spans where attributes['k']<>true": "spans where attributes['k']!=true", + "spans where attributes['k']\"a$svc\"": "spans where attributes['k']>\"a$svc\"", + "spans where attributes['k']>\"api*\"": "spans where attributes['k']>\"api*\"", + "spans where attributes['k']>-3": "spans where attributes['k']>-3", + "spans where attributes['k']>1.5": "spans where attributes['k']>1.5", + "spans where attributes['k']>2e3": "spans where attributes['k']>2000", + "spans where attributes['k']>5": "spans where attributes['k']>5", + "spans where attributes['k']>=\"a$svc\"": "spans where attributes['k']>=\"a$svc\"", + "spans where attributes['k']>=\"api*\"": "spans where attributes['k']>=\"api*\"", + "spans where attributes['k']>=-3": "spans where attributes['k']>=-3", + "spans where attributes['k']>=1.5": "spans where attributes['k']>=1.5", + "spans where attributes['k']>=2e3": "spans where attributes['k']>=2000", + "spans where attributes['k']>=5": "spans where attributes['k']>=5", + "spans where attributes['k']>=api": "spans where attributes['k']>=api", + "spans where attributes['k']>=false": "spans where attributes['k']>=false", + "spans where attributes['k']>=true": "spans where attributes['k']>=true", + "spans where attributes['k']>api": "spans where attributes['k']>api", + "spans where attributes['k']>false": "spans where attributes['k']>false", + "spans where attributes['k']>true": "spans where attributes['k']>true", + "spans where attributes['k']~\"a$svc\"": "spans where attributes['k'] ~ \"a$svc\"", + "spans where attributes['k']~\"api*\"": "spans where attributes['k'] ~ \"api*\"", + "spans where attributes['k']~-3": "spans where attributes['k'] ~ \"-3\"", + "spans where attributes['k']~1.5": "spans where attributes['k'] ~ \"1.5\"", + "spans where attributes['k']~2e3": "spans where attributes['k'] ~ \"2e3\"", + "spans where attributes['k']~5": "spans where attributes['k'] ~ \"5\"", + "spans where attributes['k']~api": "spans where attributes['k'] ~ api", + "spans where attributes['k']~false": "spans where attributes['k'] ~ \"false\"", + "spans where attributes['k']~true": "spans where attributes['k'] ~ \"true\"", + "spans where attributes['own']:api": "spans where attributes['own']:api", + "spans where attributes['resource.k']:x": "spans where attributes['resource.k']:x", + "spans where attributes['é.x']:api": "spans where attributes['é.x']:api", + "spans where db_system:postgresql db.statement ~ \"SELECT\" duration>500ms sort duration limit 10": "spans where db_system:postgresql db.statement ~ SELECT duration>500ms sort duration limit 10", + "spans where duration ": "spans where duration", + "spans where duration > 500ms": "spans where duration>500ms", + "spans where duration between 1s and 2s status:error": "spans where duration between 1s and 2s status:error", + "spans where duration>500ms": "spans where duration>500ms", + "spans where duration_ms>500": "spans where duration>500ms", + "spans where flag:\"true\"": "spans where attributes['flag']:\"true\"", + "spans where flag:true": "spans where attributes['flag']:true", + "spans where htt": "spans where htt", + "spans where http.": "spans where http.", + "spans where http.target:\"/a:b\"": "spans where http.target:\"/a:b\"", + "spans where http.target:/h": "spans where http.target:/h", + "spans where http_status_code not between 400 and 599": "spans where http_status_code not between 400 and 599", + "spans where http_status_code:2e3": "spans where http_status_code:2e3", + "spans where http_status_code:500": "spans where http_status_code:500", + "spans where http_status_code>=$code": "spans where http_status_code>=$code", + "spans where http_status_code>=500": "spans where http_status_code>=500", + "spans where http_status_code>=warn": "spans where http_status_code>=warn", + "spans where k not a:1": "spans where k -attributes['a']:1", + "spans where k ~ v": "spans where attributes['k'] ~ v", + "spans where k:*": "spans where attributes['k']:*", + "spans where k:>5": "spans where attributes['k']>5", + "spans where kind:\"SPAN_KIND_SERVER\"": "spans where kind:server", + "spans where kind:SPAN_KIND_CLIENT": "spans where kind:client", + "spans where kind:SPAN_KIND_CONSUMER": "spans where kind:consumer", + "spans where kind:SPAN_KIND_INTERNAL": "spans where kind:internal", + "spans where kind:SPAN_KIND_PRODUCER": "spans where kind:producer", + "spans where kind:SPAN_KIND_SERVER": "spans where kind:server", + "spans where kind:SPAN_KIND_UNSPECIFIED": "spans where kind:unspecified", + "spans where kind:client": "spans where kind:client", + "spans where kind:consumer": "spans where kind:consumer", + "spans where kind:internal": "spans where kind:internal", + "spans where kind:producer": "spans where kind:producer", + "spans where kind:server": "spans where kind:server", + "spans where kind:server | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex": "spans where kind:server | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex", + "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route": "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route", + "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route every auto": "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route every auto", + "spans where kind:server | count_if(status:error -http.target:/healthz) / count() * 100 as e": "spans where kind:server | count_if(status:error -http.target:/healthz) / count() * 100 as e", + "spans where kind:server | count_if(status:error) / count() * 100 as err_pct": "spans where kind:server | count_if(status:error) / count() * 100 as err_pct", + "spans where kind:server | error_rate() by service every 1m": "spans where kind:server | error_rate() by service every 1m", + "spans where kind:unspecified": "spans where kind:unspecified", + "spans where lower(service) = \"api\"": "spans where lower(service)=\"api\"", + "spans where not a:1 b:2": "spans where -attributes['a']:1 attributes['b']:2", + "spans where res": "spans where res", + "spans where resource.k8s.pod.name:x": "spans where resource.k8s.pod.name:x", + "spans where resource.serv": "spans where resource.serv", + "spans where resource.wh": "spans where resource.wh", + "spans where resource[\"own\"]:api": "spans where resource.own:api", + "spans where servce:api": "spans where attributes['servce']:api", + "spans where service": "spans where service", + "spans where service in $svcs": "spans where service in $svcs", + "spans where service in (a, b)": "spans where service in (a, b)", + "spans where service not in (a, b)": "spans where service not in (a, b)", + "spans where service-": "spans where service-", + "spans where service:$ser": "spans where service:$ser", + "spans where service:$service (status:error or status:unset)": "spans where service:$service (status:error or status:unset)", + "spans where service:$service (status:error or status:unset) | count() by http_route": "spans where service:$service (status:error or status:unset) | count() by http_route", + "spans where service:$service status:error": "spans where service:$service status:error", + "spans where service:$x": "spans where service:$x", + "spans where service:API | count() every 1m": "spans where service:API | count() every 1m", + "spans where service:api ": "spans where service:api", + "spans where service:checkout duration>500ms sort duration limit 50": "spans where service:checkout duration>500ms sort duration limit 50", + "spans where service:checkout http.": "spans where service:checkout http.", + "spans where service:checkout status:error -http.target:/healthz | count() by http_route": "spans where service:checkout status:error -http.target:/healthz | count() by http_route", + "spans where start_time ": "spans where start_time", + "spans where start_time>\"2026-10-29 10:00:00\"": "spans where start_time>\"2026-10-29 10:00:00\"", + "spans where start_time>\"2026-10-29T10:00:00Z\"": "spans where start_time>\"2026-10-29T10:00:00Z\"", + "spans where starts_with(http_route, \"/api\")": "spans where starts_with(http_route, \"/api\")", + "spans where stats": "spans where stats", + "spans where status in (error, ok)": "spans where status in (error, ok)", + "spans where status ~ STATUS_CODE_ERROR": "spans where status ~ STATUS_CODE_ERROR", + "spans where status:\"STATUS_CODE_ERROR\"": "spans where status:error", + "spans where status:\"error\"": "spans where status:\"error\"", + "spans where status:500": "spans where status:500", + "spans where status:STATUS_CODE_ERROR": "spans where status:error", + "spans where status:STATUS_CODE_OK": "spans where status:ok", + "spans where status:STATUS_CODE_UNSET": "spans where status:unset", + "spans where status:error": "spans where status:error", + "spans where status:error | count() by service": "spans where status:error | count() by service", + "spans where status:ok": "spans where status:ok", + "spans where status:unset": "spans where status:unset", + "spans where status>STATUS_CODE_ERROR": "spans where status>STATUS_CODE_ERROR", + "spans where tar": "spans where tar", + "spans where user.id:* | count_distinct(user.id) by service": "spans where user.id:* | count_distinct(user.id) by service", + "spans where value>-3": "spans where attributes['value']>-3", + "spans | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex": "spans | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex", + "spans | P95(Duration)": "spans | p95(duration)", + "spans | avg(attributes.http.response_size) as sz": "spans | avg(http.response_size) as sz", + "spans | avg(http.response_size) as sz": "spans | avg(http.response_size) as sz", + "spans | count()": "spans | count()", + "spans | count() ": "spans | count()", + "spans | count() * -1 as neg": "spans | count() * -1 as neg", + "spans | count() * 0 as zero": "spans | count() * 0 as zero", + "spans | count() * 1e3 as k": "spans | count() * 1000 as k", + "spans | count() as duration sort duration": "spans | count() as duration sort duration", + "spans | count() by attributes['user name']": "spans | count() by attributes['user name']", + "spans | count() by attributes['user''s name']": "spans | count() by attributes['user''s name']", + "spans | count() by resource['𝔘 [name]']": "spans | count() by resource['𝔘 [name]']", + "spans | count() by service every 1m": "spans | count() by service every 1m", + "spans | count() by service every auto sort count limit 10": "spans | count() by service every auto sort count limit 10", + "spans | count() by service sort -count": "spans | count() by service sort count", + "spans | count() by service sort count": "spans | count() by service sort count", + "spans | count() by service sort count limit 10": "spans | count() by service sort count limit 10", + "spans | count() by service | sort count | limit 10": "spans | count() by service sort count limit 10", + "spans | count() every 1m sort count": "spans | count() every 1m sort count", + "spans | count()*100 as c100": "spans | count() * 100 as c100", + "spans | count()/count() as one": "spans | count() / count() as one", + "spans | count(*)": "spans | count()", + "spans | count_distinct(attributes['flag'])": "spans | count_distinct(attributes['flag'])", + "spans | count_distinct(attributes['user.id'])": "spans | count_distinct(user.id)", + "spans | count_distinct(flag)": "spans | count_distinct(attributes['flag'])", + "spans | count_distinct(user.id)": "spans | count_distinct(user.id)", + "spans | count_distinct(user.id) + avg(attributes.http.response_size) - p95(resource.k) * 1e3 as spread": "spans | count_distinct(user.id) + avg(http.response_size) - p95(resource.k) * 1000 as spread", + "spans | count_distinct(user.id) by service": "spans | count_distinct(user.id) by service", + "spans | count_distinct(user.id), p95(resource.k)": "spans | count_distinct(user.id), p95(resource.k)", + "spans | count_if(a:1 or b:2) / count() as r": "spans | count_if(attributes['a']:1 or attributes['b']:2) / count() as r", + "spans | count_if(body:\"a)b\" `x = ')'`) / count() as r": "spans | count_if(attributes['body']:\"a)b\" `x = ')'`) / count() as r", + "spans | count_if(http_status_code between 400 and 499) as client_errors, count_if(http_status_code>=500) as server_errors": "spans | count_if(http_status_code between 400 and 499) as client_errors, count_if(http_status_code>=500) as server_errors", + "spans | count_if(status:error -http.target:/healthz) as errs": "spans | count_if(status:error -http.target:/healthz) as errs", + "spans | count_if(status:error)": "spans | count_if(status:error)", + "spans | count_if(status:error) / count() * 100 as err_pct by http_route every 1m sort err_pct limit 10": "spans | count_if(status:error) / count() * 100 as err_pct by http_route every 1m sort err_pct limit 10", + "spans | count_if(status:error) / count() as r by http_route": "spans | count_if(status:error) / count() as r by http_route", + "spans | count_if(status:error) as errors, count() as total, count_if(status:error) / count() as ratio by service": "spans | count_if(status:error) as errors, count() as total, count_if(status:error) / count() as ratio by service", + "spans | histogram(duration)": "spans | histogram(duration)", + "spans | histogram(duration) by service": "spans | histogram(duration) by service", + "spans | p95(duration)": "spans | p95(duration)", + "spans | p95(duration) by operation sort p95 limit 10": "spans | p95(duration) by operation sort p95 limit 10", + "spans | p95(duration)-p50(duration) as spread": "spans | p95(duration) - p50(duration) as spread", + "spans | p95(resource.k) as x": "spans | p95(resource.k) as x", + "spans | p99(duration) by http_route every 1m": "spans | p99(duration) by http_route every 1m", + "spans | quantile(duration, 0.999) as q": "spans | quantile(duration, 0.999) as q", + "spans | share() ": "spans | share()" +} diff --git a/internal/fanql/testdata/corpus.txt b/internal/fanql/testdata/corpus.txt new file mode 100644 index 00000000..47fcc582 --- /dev/null +++ b/internal/fanql/testdata/corpus.txt @@ -0,0 +1,7534 @@ +{ + "text": "", + "problems": [ + { + "path": "text", + "message": "unknown source \"\"", + "hint": "use spans, logs or metrics", + "span": { + "start": 0, + "end": 0 + } + } + ] +} + +{ + "text": "from spans", + "problems": [ + { + "path": "text", + "message": "\"from\" is not FanQL; start with the source: spans where ...", + "span": { + "start": 0, + "end": 4 + } + } + ] +} + +{ + "text": "logs", + "query": { + "from": "logs" + } +} + +{ + "text": "logs limit ", + "problems": [ + { + "path": "text", + "message": "limit needs a whole number from 1 to 1000; e.g. limit 50", + "span": { + "start": 11, + "end": 11 + } + } + ] +} + +{ + "text": "logs sort +time", + "query": { + "from": "logs", + "sort": "+time" + } +} + +{ + "text": "logs sort +time", + "viz": "logs", + "query": { + "from": "logs", + "sort": "+time" + } +} + +{ + "text": "logs sort duration", + "query": { + "from": "logs", + "sort": "duration_ms" + }, + "gate_problems": true +} + +{ + "text": "logs sort duration", + "viz": "logs", + "problems": [ + { + "path": "sort", + "message": "logs sort by time or +time only", + "span": { + "start": 5, + "end": 18 + } + } + ] +} + +{ + "text": "logs sort time", + "query": { + "from": "logs", + "sort": "time" + } +} + +{ + "text": "logs where ", + "problems": [ + { + "path": "text", + "message": "where needs a filter", + "span": { + "start": 5, + "end": 10 + } + } + ] +} + +{ + "text": "logs where \"", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with \"", + "span": { + "start": 11, + "end": 12 + } + } + ] +} + +{ + "text": "logs where \"api$svc\"", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower('api$svc'))" + ] + } +} + +{ + "text": "logs where \"api*\"", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower('api*'))" + ] + } +} + +{ + "text": "logs where \"http://x:8080/y\"", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower('http://x:8080/y'))" + ] + } +} + +{ + "text": "logs where \"limit\"", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower('limit'))" + ] + } +} + +{ + "text": "logs where \"unclosed ", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with \"", + "span": { + "start": 11, + "end": 21 + } + } + ] +} + +{ + "text": "logs where (`body = 'a' OR body = 'b'` service:api)", + "query": { + "from": "logs", + "where": [ + "((body = 'a' OR body = 'b') AND service = 'api')" + ] + } +} + +{ + "text": "logs where --severity is null", + "query": { + "from": "logs", + "where": [ + "severity IS NULL" + ] + } +} + +{ + "text": "logs where --severity:error", + "query": { + "from": "logs", + "where": [ + "severity = 'ERROR'" + ] + } +} + +{ + "text": "logs where -`coalesce(body, '') = ''`", + "query": { + "from": "logs", + "where": [ + "NOT coalesce((coalesce(body, '') = ''), FALSE)" + ] + } +} + +{ + "text": "logs where -body like \"GET %\"", + "query": { + "from": "logs", + "where": [ + "(body IS NULL OR body !~~ 'GET %')" + ] + } +} + +{ + "text": "logs where -body not like \"GET %\"", + "query": { + "from": "logs", + "where": [ + "(body IS NULL OR body ~~ 'GET %')" + ] + } +} + +{ + "text": "logs where -body ~ \"100%\"", + "query": { + "from": "logs", + "where": [ + "(body IS NULL OR NOT contains(lower(body), lower('100%')))" + ] + } +} + +{ + "text": "logs where -length(body) > 1000", + "query": { + "from": "logs", + "where": [ + "NOT coalesce((length(body) > 1000), FALSE)" + ] + } +} + +{ + "text": "logs where -not a:1", + "query": { + "from": "logs", + "where": [ + "attributes['a'] = 1" + ] + } +} + +{ + "text": "logs where -severity not between info and error", + "query": { + "from": "logs", + "where": [ + "(severity IS NULL OR severity IN ('INFO', 'WARN', 'ERROR'))" + ] + } +} + +{ + "text": "logs where -severity not in (warn, error, fatal)", + "query": { + "from": "logs", + "where": [ + "(severity IS NULL OR severity IN ('WARN', 'ERROR', 'FATAL'))" + ] + } +} + +{ + "text": "logs where -severity>=warn", + "query": { + "from": "logs", + "where": [ + "(severity IS NULL OR severity NOT IN ('WARN', 'ERROR', 'FATAL'))" + ] + } +} + +{ + "text": "logs where 2e3", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower('2e3'))" + ] + } +} + +{ + "text": "logs where _time:now", + "problems": [ + { + "path": "text", + "message": "the time range is not part of FanQL 1; use the time picker (_time is reserved)", + "span": { + "start": 11, + "end": 16 + } + } + ] +} + +{ + "text": "logs where `", + "problems": [ + { + "path": "text", + "message": "unclosed raw filter; close it with `", + "span": { + "start": 11, + "end": 12 + } + } + ] +} + +{ + "text": "logs where `coalesce(body, '``') = ''`", + "query": { + "from": "logs", + "where": [ + "coalesce(body, '`') = ''" + ] + } +} + +{ + "text": "logs where `coalesce(body,'|') ", + "problems": [ + { + "path": "text", + "message": "unclosed raw filter; close it with `", + "span": { + "start": 11, + "end": 31 + } + } + ] +} + +{ + "text": "logs where `coalesce(body,'|')=''` | count()", + "query": { + "from": "logs", + "where": [ + "coalesce(body,'|')=''" + ], + "measures": [ + "count()" + ] + } +} + +{ + "text": "logs where ago(1h)", + "problems": [ + { + "path": "text", + "message": "ago(...) is not FanQL; use the time picker", + "span": { + "start": 11, + "end": 14 + } + } + ] +} + +{ + "text": "logs where attributes['']:x", + "problems": [ + { + "path": "where[0]", + "message": "attribute keys must not be empty", + "span": { + "start": 11, + "end": 25 + } + } + ] +} + +{ + "text": "logs where attributes['long']:\"", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with \"", + "span": { + "start": 30, + "end": 31 + } + } + ] +} + +{ + "text": "logs where attributes['top']:x", + "query": { + "from": "logs", + "where": [ + "attributes['top'] = 'x'" + ] + } +} + +{ + "text": "logs where attributes['𝔘.key']:\"✓\" resource.k8s.pod.name:x a.b:y", + "query": { + "from": "logs", + "where": [ + "attributes['𝔘.key'] = '✓'", + "resource['k8s.pod.name'] = 'x'", + "attributes['a.b'] = 'y'" + ] + } +} + +{ + "text": "logs where body == x", + "problems": [ + { + "path": "text", + "message": "== is not FanQL; use key:value or =", + "span": { + "start": 16, + "end": 18 + } + } + ] +} + +{ + "text": "logs where body =~ x", + "problems": [ + { + "path": "text", + "message": "=~ is not FanQL; ~ is contains; use regexp_matches(field, 're') for a regular expression", + "span": { + "start": 16, + "end": 18 + } + } + ] +} + +{ + "text": "logs where body ilike \"%a_b%\"", + "query": { + "from": "logs", + "where": [ + "body ~~* '%a_b%'" + ] + } +} + +{ + "text": "logs where body not like \"GET %\"", + "query": { + "from": "logs", + "where": [ + "body !~~ 'GET %'" + ] + } +} + +{ + "text": "logs where body |= x", + "problems": [ + { + "path": "text", + "message": "|= is not FanQL; use body ~ \"text\" for contains", + "span": { + "start": 16, + "end": 18 + } + } + ] +} + +{ + "text": "logs where body |~ x", + "problems": [ + { + "path": "text", + "message": "|~ is not FanQL; use body ~ \"text\" for contains", + "span": { + "start": 16, + "end": 18 + } + } + ] +} + +{ + "text": "logs where body ~ \"a_b\"", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower('a_b'))" + ] + } +} + +{ + "text": "logs where body ~ $term", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower($term))" + ] + } +} + +{ + "text": "logs where body ~ 2e3", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower('2e3'))" + ] + } +} + +{ + "text": "logs where body:\"a | b sort c\" attributes['x.by']:y", + "query": { + "from": "logs", + "where": [ + "body = 'a | b sort c'", + "attributes['x.by'] = 'y'" + ] + } +} + +{ + "text": "logs where body:\"héllo ✓\" x", + "query": { + "from": "logs", + "where": [ + "body = 'héllo ✓'", + "contains(lower(body), lower('x'))" + ] + } +} + +{ + "text": "logs where body::VARCHAR:x", + "problems": [ + { + "path": "text", + "message": ":: is not FanQL; use field comparisons or a backtick raw filter", + "span": { + "start": 15, + "end": 17 + } + } + ] +} + +{ + "text": "logs where earliest=1h", + "problems": [ + { + "path": "text", + "message": "the time range is not part of FanQL 1; use the time picker (earliest is reserved)", + "span": { + "start": 11, + "end": 19 + } + } + ] +} + +{ + "text": "logs where http://x:8080/y", + "problems": [ + { + "path": "text", + "message": "unexpected : after http", + "hint": "quote the value: \"http://x:8080/y\"", + "span": { + "start": 11, + "end": 26 + } + } + ] +} + +{ + "text": "logs where length(body)", + "problems": [ + { + "path": "where[0]", + "message": "length(...) needs a comparison", + "span": { + "start": 11, + "end": 23 + } + } + ] +} + +{ + "text": "logs where length(body) > 1000", + "query": { + "from": "logs", + "where": [ + "length(body) > 1000" + ] + } +} + +{ + "text": "logs where length(body)>1000", + "query": { + "from": "logs", + "where": [ + "length(body) > 1000" + ] + } +} + +{ + "text": "logs where length(body)>1e3", + "query": { + "from": "logs", + "where": [ + "length(body) > 1000" + ] + } +} + +{ + "text": "logs where limit 10", + "problems": [ + { + "path": "text", + "message": "where needs a filter", + "hint": "quote \"limit\" to search for the word, or drop where", + "span": { + "start": 5, + "end": 10 + } + } + ] +} + +{ + "text": "logs where lower(service)=$svc", + "query": { + "from": "logs", + "where": [ + "lower(service) = $svc" + ] + } +} + +{ + "text": "logs where not not a:1", + "query": { + "from": "logs", + "where": [ + "attributes['a'] = 1" + ] + } +} + +{ + "text": "logs where now()", + "problems": [ + { + "path": "text", + "message": "now(...) is not FanQL; use the time picker", + "span": { + "start": 11, + "end": 14 + } + } + ] +} + +{ + "text": "logs where regexp_matches(body, \"error.*\")", + "query": { + "from": "logs", + "where": [ + "regexp_matches(body, 'error.*')" + ] + } +} + +{ + "text": "logs where ser", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower('ser'))" + ] + } +} + +{ + "text": "logs where service", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower('service'))" + ] + } +} + +{ + "text": "logs where service in (api, ", + "problems": [ + { + "path": "text", + "message": "in needs a list or variable, e.g. in (api, web)", + "span": { + "start": 28, + "end": 28 + } + } + ] +} + +{ + "text": "logs where service in (sort, limit)", + "query": { + "from": "logs", + "where": [ + "service IN ('sort', 'limit')" + ] + } +} + +{ + "text": "logs where service:", + "problems": [ + { + "path": "text", + "message": "service: needs a value; e.g. service:api", + "span": { + "start": 11, + "end": 19 + } + } + ] +} + +{ + "text": "logs where service:\"TRUE\"", + "query": { + "from": "logs", + "where": [ + "service = 'TRUE'" + ] + } +} + +{ + "text": "logs where service:\"api$svc\"", + "query": { + "from": "logs", + "where": [ + "service = 'api$svc'" + ] + } +} + +{ + "text": "logs where service:\"api*\"", + "query": { + "from": "logs", + "where": [ + "service = 'api*'" + ] + } +} + +{ + "text": "logs where service:api and severity:error or body:timeout | count() by ", + "problems": [ + { + "path": "text", + "message": "mixed and/or needs parentheses", + "hint": "write service:api and (severity:error or body:timeout) or (service:api and severity:error) or body:timeout", + "span": { + "start": 11, + "end": 57 + }, + "fix_its": [ + { + "label": "service:api and (severity:error or body:timeout)", + "span": { + "start": 11, + "end": 57 + }, + "text": "service:api and (severity:error or body:timeout)" + }, + { + "label": "(service:api and severity:error) or body:timeout", + "span": { + "start": 11, + "end": 57 + }, + "text": "(service:api and severity:error) or body:timeout" + } + ] + }, + { + "path": "text", + "message": "a field needs a name, e.g. service or attributes['key']", + "span": { + "start": 71, + "end": 71 + } + } + ] +} + +{ + "text": "logs where service:api severity:error timeout sort time limit 200", + "query": { + "from": "logs", + "where": [ + "service = 'api'", + "severity = 'ERROR'", + "contains(lower(body), lower('timeout'))" + ], + "sort": "time", + "limit": 200 + } +} + +{ + "text": "logs where service:where", + "query": { + "from": "logs", + "where": [ + "service = 'where'" + ] + } +} + +{ + "text": "logs where severity ", + "query": { + "from": "logs", + "where": [ + "contains(lower(body), lower('severity'))" + ] + } +} + +{ + "text": "logs where severity between error and info", + "problems": [ + { + "path": "where[0]", + "message": "between needs the lower level first: severity between info and error", + "span": { + "start": 28, + "end": 33 + } + } + ] +} + +{ + "text": "logs where severity between info and error", + "query": { + "from": "logs", + "where": [ + "severity IN ('INFO', 'WARN', 'ERROR')" + ] + } +} + +{ + "text": "logs where severity in (info, warn, error)", + "query": { + "from": "logs", + "where": [ + "severity IN ('INFO', 'WARN', 'ERROR')" + ] + } +} + +{ + "text": "logs where severity not between info and error", + "query": { + "from": "logs", + "where": [ + "severity NOT IN ('INFO', 'WARN', 'ERROR')" + ] + } +} + +{ + "text": "logs where severity ~ \"ERROR\"", + "query": { + "from": "logs", + "where": [ + "contains(lower(severity), lower('ERROR'))" + ] + } +} + +{ + "text": "logs where severity ~ ERROR", + "query": { + "from": "logs", + "where": [ + "contains(lower(severity), lower('ERROR'))" + ] + } +} + +{ + "text": "logs where severity ~ error", + "query": { + "from": "logs", + "where": [ + "contains(lower(severity), lower('error'))" + ] + } +} + +{ + "text": "logs where severity:", + "problems": [ + { + "path": "text", + "message": "severity: needs a value; e.g. severity:api", + "span": { + "start": 11, + "end": 20 + } + } + ] +} + +{ + "text": "logs where severity:\"1H\"", + "query": { + "from": "logs", + "where": [ + "severity = '1H'" + ] + } +} + +{ + "text": "logs where severity:\"ERROR\"", + "query": { + "from": "logs", + "where": [ + "severity = 'ERROR'" + ] + } +} + +{ + "text": "logs where severity:\"TRUE\"", + "query": { + "from": "logs", + "where": [ + "severity = 'TRUE'" + ] + } +} + +{ + "text": "logs where severity:\"error\"", + "query": { + "from": "logs", + "where": [ + "severity = 'error'" + ] + } +} + +{ + "text": "logs where severity:14", + "query": { + "from": "logs", + "where": [ + "severity = '14'" + ] + } +} + +{ + "text": "logs where severity:DEBUG", + "query": { + "from": "logs", + "where": [ + "severity = 'DEBUG'" + ] + } +} + +{ + "text": "logs where severity:ERROR", + "query": { + "from": "logs", + "where": [ + "severity = 'ERROR'" + ] + } +} + +{ + "text": "logs where severity:Error", + "query": { + "from": "logs", + "where": [ + "severity = 'ERROR'" + ] + } +} + +{ + "text": "logs where severity:FATAL", + "query": { + "from": "logs", + "where": [ + "severity = 'FATAL'" + ] + } +} + +{ + "text": "logs where severity:INFO", + "query": { + "from": "logs", + "where": [ + "severity = 'INFO'" + ] + } +} + +{ + "text": "logs where severity:TRACE", + "query": { + "from": "logs", + "where": [ + "severity = 'TRACE'" + ] + } +} + +{ + "text": "logs where severity:WARN", + "query": { + "from": "logs", + "where": [ + "severity = 'WARN'" + ] + } +} + +{ + "text": "logs where severity:alert", + "query": { + "from": "logs", + "where": [ + "severity = 'FATAL'" + ] + } +} + +{ + "text": "logs where severity:crit", + "query": { + "from": "logs", + "where": [ + "severity = 'FATAL'" + ] + } +} + +{ + "text": "logs where severity:critical", + "query": { + "from": "logs", + "where": [ + "severity = 'FATAL'" + ] + } +} + +{ + "text": "logs where severity:custom", + "query": { + "from": "logs", + "where": [ + "severity = 'CUSTOM'" + ] + } +} + +{ + "text": "logs where severity:dbg", + "query": { + "from": "logs", + "where": [ + "severity = 'DEBUG'" + ] + } +} + +{ + "text": "logs where severity:debug", + "query": { + "from": "logs", + "where": [ + "severity = 'DEBUG'" + ] + } +} + +{ + "text": "logs where severity:emerg", + "query": { + "from": "logs", + "where": [ + "severity = 'FATAL'" + ] + } +} + +{ + "text": "logs where severity:emergency", + "query": { + "from": "logs", + "where": [ + "severity = 'FATAL'" + ] + } +} + +{ + "text": "logs where severity:err", + "query": { + "from": "logs", + "where": [ + "severity = 'ERROR'" + ] + } +} + +{ + "text": "logs where severity:error", + "query": { + "from": "logs", + "where": [ + "severity = 'ERROR'" + ] + } +} + +{ + "text": "logs where severity:exception", + "query": { + "from": "logs", + "where": [ + "severity = 'ERROR'" + ] + } +} + +{ + "text": "logs where severity:fatal", + "query": { + "from": "logs", + "where": [ + "severity = 'FATAL'" + ] + } +} + +{ + "text": "logs where severity:fine", + "query": { + "from": "logs", + "where": [ + "severity = 'DEBUG'" + ] + } +} + +{ + "text": "logs where severity:finest", + "query": { + "from": "logs", + "where": [ + "severity = 'TRACE'" + ] + } +} + +{ + "text": "logs where severity:info", + "query": { + "from": "logs", + "where": [ + "severity = 'INFO'" + ] + } +} + +{ + "text": "logs where severity:information", + "query": { + "from": "logs", + "where": [ + "severity = 'INFO'" + ] + } +} + +{ + "text": "logs where severity:informational", + "query": { + "from": "logs", + "where": [ + "severity = 'INFO'" + ] + } +} + +{ + "text": "logs where severity:notice", + "query": { + "from": "logs", + "where": [ + "severity = 'INFO'" + ] + } +} + +{ + "text": "logs where severity:panic", + "query": { + "from": "logs", + "where": [ + "severity = 'FATAL'" + ] + } +} + +{ + "text": "logs where severity:severe", + "query": { + "from": "logs", + "where": [ + "severity = 'ERROR'" + ] + } +} + +{ + "text": "logs where severity:trace", + "query": { + "from": "logs", + "where": [ + "severity = 'TRACE'" + ] + } +} + +{ + "text": "logs where severity:true", + "query": { + "from": "logs", + "where": [ + "severity = 'true'" + ] + } +} + +{ + "text": "logs where severity:verbose", + "query": { + "from": "logs", + "where": [ + "severity = 'TRACE'" + ] + } +} + +{ + "text": "logs where severity:warn", + "query": { + "from": "logs", + "where": [ + "severity = 'WARN'" + ] + } +} + +{ + "text": "logs where severity:warning", + "query": { + "from": "logs", + "where": [ + "severity = 'WARN'" + ] + } +} + +{ + "text": "logs where severity:where", + "query": { + "from": "logs", + "where": [ + "severity = 'WHERE'" + ] + } +} + +{ + "text": "logs where severity=", + "problems": [ + { + "path": "text", + "message": "severity>= needs a value; e.g. severity>=api", + "span": { + "start": 11, + "end": 21 + } + } + ] +} + +{ + "text": "logs where severity>=custom", + "problems": [ + { + "path": "where[0]", + "message": "\"custom\" has no severity rank; use trace, debug, info, warn, error or fatal", + "span": { + "start": 21, + "end": 27 + } + } + ] +} + +{ + "text": "logs where severity>=unspecified", + "problems": [ + { + "path": "where[0]", + "message": "\"unspecified\" has no severity rank; use trace, debug, info, warn, error or fatal", + "span": { + "start": 21, + "end": 32 + } + } + ] +} + +{ + "text": "logs where severity>=warn", + "query": { + "from": "logs", + "where": [ + "severity IN ('WARN', 'ERROR', 'FATAL')" + ] + } +} + +{ + "text": "logs where severity>=warn | count() by body_template sort count limit 10", + "query": { + "from": "logs", + "where": [ + "severity IN ('WARN', 'ERROR', 'FATAL')" + ], + "measures": [ + "count()" + ], + "by": [ + "body_template" + ], + "sort": "count", + "limit": 10 + } +} + +{ + "text": "logs where severity>error", + "query": { + "from": "logs", + "where": [ + "severity IN ('FATAL')" + ] + } +} + +{ + "text": "logs where severity>fatal", + "problems": [ + { + "path": "where[0]", + "message": "severity>fatal matches no level; use severity:fatal", + "span": { + "start": 20, + "end": 25 + } + } + ] +} + +{ + "text": "logs where severity_number>=14", + "query": { + "from": "logs", + "where": [ + "severity_number >= 14" + ] + } +} + +{ + "text": "logs where starts_with (x, \"y\")", + "problems": [ + { + "path": "text", + "message": "write starts_with(...) without a space", + "span": { + "start": 11, + "end": 24 + } + } + ] +} + +{ + "text": "logs where time:x", + "problems": [ + { + "path": "where[0]", + "message": "\"time\" is a time column; compare it with > or <", + "span": { + "start": 11, + "end": 15 + } + } + ] +} + +{ + "text": "logs where time>\"2026-10-29T10:00:00Z\" time<\"2026-10-29T10:01:00Z\"", + "query": { + "from": "logs", + "where": [ + "time > '2026-10-29T10:00:00Z'::TIMESTAMPTZ_NS", + "time < '2026-10-29T10:01:00Z'::TIMESTAMPTZ_NS" + ] + } +} + +{ + "text": "logs where top:x", + "query": { + "from": "logs", + "where": [ + "attributes['top'] = 'x'" + ] + } +} + +{ + "text": "logs where trace_id:trace1", + "query": { + "from": "logs", + "where": [ + "trace_id = 'trace1'" + ] + } +} + +{ + "text": "logs | count() by body_template sort count", + "query": { + "from": "logs", + "measures": [ + "count()" + ], + "by": [ + "body_template" + ], + "sort": "count" + } +} + +{ + "text": "logs | count() by body_template sort rate", + "problems": [ + { + "path": "sort", + "message": "sort \"rate\" must name a measure alias; aliases here: count", + "span": { + "start": 32, + "end": 41 + } + } + ] +} + +{ + "text": "logs | count() by body_template sort rate", + "viz": "log_patterns", + "problems": [ + { + "path": "sort", + "message": "log_patterns sort by count only", + "span": { + "start": 32, + "end": 41 + } + } + ] +} + +{ + "text": "metrics", + "query": { + "from": "metrics" + } +} + +{ + "text": "metrics ", + "query": { + "from": "metrics" + } +} + +{ + "text": "metrics where name:", + "problems": [ + { + "path": "text", + "message": "name: needs a value; e.g. name:api", + "span": { + "start": 14, + "end": 19 + } + } + ] +} + +{ + "text": "metrics where name:http.server.duration", + "query": { + "from": "metrics", + "where": [ + "name = 'http.server.duration'" + ] + } +} + +{ + "text": "metrics where name:http.server.duration | histogram(value)", + "query": { + "from": "metrics", + "where": [ + "name = 'http.server.duration'" + ], + "measures": [ + "count()" + ], + "histogram": { + "field": "value", + "buckets": "explicit" + } + } +} + +{ + "text": "metrics where name:http.server.requests | rate() by service every 1m", + "query": { + "from": "metrics", + "where": [ + "name = 'http.server.requests'" + ], + "measures": [ + "rate()" + ], + "by": [ + "service" + ], + "bucket": "1m" + } +} + +{ + "text": "metrics where name:k8s.container.restarts | last(value) by resource.k8s.pod.name", + "query": { + "from": "metrics", + "where": [ + "name = 'k8s.container.restarts'" + ], + "measures": [ + "last(value)" + ], + "by": [ + "resource['k8s.pod.name']" + ] + } +} + +{ + "text": "metrics where name:queue.lag | last(value) by service", + "query": { + "from": "metrics", + "where": [ + "name = 'queue.lag'" + ], + "measures": [ + "last(value)" + ], + "by": [ + "service" + ] + } +} + +{ + "text": "metrics where name:x | histogram(value) every 1m", + "query": { + "from": "metrics", + "where": [ + "name = 'x'" + ], + "measures": [ + "count()" + ], + "bucket": "1m", + "histogram": { + "field": "value", + "buckets": "explicit" + } + } +} + +{ + "text": "metrics where rate:x", + "query": { + "from": "metrics", + "where": [ + "attributes['rate'] = 'x'" + ] + } +} + +{ + "text": "metrics where timeout", + "problems": [ + { + "path": "where[0]", + "message": "free text needs a field on metrics; use name:http.server.duration", + "span": { + "start": 14, + "end": 21 + } + } + ] +} + +{ + "text": "metrics where type:\"counter\" | count()", + "query": { + "from": "metrics", + "where": [ + "type = 'counter'" + ], + "measures": [ + "count()" + ] + } +} + +{ + "text": "metrics where type:COUNTER | count()", + "query": { + "from": "metrics", + "where": [ + "type = 'counter'" + ], + "measures": [ + "count()" + ] + } +} + +{ + "text": "metrics where type:counter", + "query": { + "from": "metrics", + "where": [ + "type = 'counter'" + ] + } +} + +{ + "text": "metrics where type:counter | count()", + "query": { + "from": "metrics", + "where": [ + "type = 'counter'" + ], + "measures": [ + "count()" + ] + } +} + +{ + "text": "metrics where type:false", + "query": { + "from": "metrics", + "where": [ + "type = 'false'" + ] + } +} + +{ + "text": "metrics where type:false | count()", + "query": { + "from": "metrics", + "where": [ + "type = 'false'" + ], + "measures": [ + "count()" + ] + } +} + +{ + "text": "metrics where type:gauge | count()", + "query": { + "from": "metrics", + "where": [ + "type = 'gauge'" + ], + "measures": [ + "count()" + ] + } +} + +{ + "text": "metrics where type:histogram | count()", + "query": { + "from": "metrics", + "where": [ + "type = 'histogram'" + ], + "measures": [ + "count()" + ] + } +} + +{ + "text": "metrics where type:summary | count()", + "query": { + "from": "metrics", + "where": [ + "type = 'summary'" + ], + "measures": [ + "count()" + ] + } +} + +{ + "text": "metrics where type:updown | count()", + "query": { + "from": "metrics", + "where": [ + "type = 'updown'" + ], + "measures": [ + "count()" + ] + } +} + +{ + "text": "metrics where value>-3", + "query": { + "from": "metrics", + "where": [ + "value > -3" + ] + } +} + +{ + "text": "metrics | ", + "problems": [ + { + "path": "text", + "message": "a measure needs a call, number or parenthesised expression", + "span": { + "start": 10, + "end": 10 + } + } + ] +} + +{ + "text": "metrics | -avg(value) as neg", + "problems": [ + { + "path": "measures[0]", + "message": "measure arithmetic is not available for metrics", + "span": { + "start": 10, + "end": 21 + } + } + ] +} + +{ + "text": "metrics | avg(value)", + "query": { + "from": "metrics", + "measures": [ + "avg(value)" + ] + }, + "gate_problems": true +} + +{ + "text": "metrics | count_if(name:x) as n", + "problems": [ + { + "path": "measures[0]", + "message": "measure arithmetic is not available for metrics", + "span": { + "start": 10, + "end": 26 + } + } + ] +} + +{ + "text": "metrics | error_rate()", + "problems": [ + { + "path": "measures[0]", + "message": "error_rate is not available for metrics", + "span": { + "start": 10, + "end": 22 + } + } + ] +} + +{ + "text": "metrics | last(value) by resource.k8s.pod.name", + "query": { + "from": "metrics", + "measures": [ + "last(value)" + ], + "by": [ + "resource['k8s.pod.name']" + ] + }, + "gate_problems": true +} + +{ + "text": "spans", + "query": { + "from": "spans" + } +} + +{ + "text": "spans ", + "query": { + "from": "spans" + } +} + +{ + "text": "spans facet service", + "problems": [ + { + "path": "text", + "message": "facet is not FanQL; use by after measures, e.g. | count() by service", + "span": { + "start": 6, + "end": 11 + } + } + ] +} + +{ + "text": "spans group by service", + "problems": [ + { + "path": "text", + "message": "group is not FanQL; use by after measures, e.g. | count() by service", + "span": { + "start": 6, + "end": 11 + } + } + ] +} + +{ + "text": "spans limit 10 sort duration", + "problems": [ + { + "path": "text", + "message": "limit comes before sort here; write ... sort duration limit 10", + "span": { + "start": 15, + "end": 19 + } + } + ] +} + +{ + "text": "spans service in (", + "problems": [ + { + "path": "text", + "message": "a list needs a value after each comma", + "span": { + "start": 18, + "end": 18 + } + }, + { + "path": "text", + "message": "in needs a list or variable, e.g. in (api, web)", + "span": { + "start": 18, + "end": 18 + } + } + ] +} + +{ + "text": "spans since 1h", + "problems": [ + { + "path": "text", + "message": "the time range is not part of FanQL 1; use the time picker (since is reserved)", + "span": { + "start": 6, + "end": 11 + } + } + ] +} + +{ + "text": "spans sort ", + "problems": [ + { + "path": "text", + "message": "sort needs a key, e.g. sort duration", + "span": { + "start": 11, + "end": 11 + } + } + ] +} + +{ + "text": "spans sort +duration", + "query": { + "from": "spans", + "sort": "+duration_ms" + }, + "gate_problems": true +} + +{ + "text": "spans sort +duration", + "viz": "traces", + "problems": [ + { + "path": "sort", + "message": "traces sort descending by duration, by errors, or ascending by start only", + "span": { + "start": 6, + "end": 20 + } + } + ] +} + +{ + "text": "spans sort +start", + "query": { + "from": "spans", + "sort": "+start" + } +} + +{ + "text": "spans sort -p95 asc", + "problems": [ + { + "path": "text", + "message": "sort takes one direction", + "span": { + "start": 16, + "end": 19 + } + } + ] +} + +{ + "text": "spans sort duration", + "query": { + "from": "spans", + "sort": "duration_ms" + } +} + +{ + "text": "spans sort duration", + "viz": "traces", + "query": { + "from": "spans", + "sort": "duration_ms" + } +} + +{ + "text": "spans sort errors", + "query": { + "from": "spans", + "sort": "errors" + } +} + +{ + "text": "spans sort errors limit 50", + "query": { + "from": "spans", + "sort": "errors", + "limit": 50 + } +} + +{ + "text": "spans status:error", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_ERROR'" + ] + } +} + +{ + "text": "spans status:error | count()", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_ERROR'" + ], + "measures": [ + "count()" + ] + } +} + +{ + "text": "spans status:error | count() by service", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_ERROR'" + ], + "measures": [ + "count()" + ], + "by": [ + "service" + ] + } +} + +{ + "text": "spans until 1h", + "problems": [ + { + "path": "text", + "message": "the time range is not part of FanQL 1; use the time picker (until is reserved)", + "span": { + "start": 6, + "end": 11 + } + } + ] +} + +{ + "text": "spans where ", + "problems": [ + { + "path": "text", + "message": "where needs a filter", + "span": { + "start": 6, + "end": 11 + } + } + ] +} + +{ + "text": "spans where !service:api", + "problems": [ + { + "path": "text", + "message": "! negation is not FanQL; write -service:api", + "span": { + "start": 12, + "end": 24 + } + } + ] +} + +{ + "text": "spans where \"abc", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with \"", + "span": { + "start": 12, + "end": 16 + } + } + ] +} + +{ + "text": "spans where $__window:x", + "problems": [ + { + "path": "where[0]", + "message": "$__ names are reserved; use a dashboard variable name", + "span": { + "start": 12, + "end": 21 + } + }, + { + "path": "where[0]", + "message": "\"$__window\" needs brackets", + "span": { + "start": 12, + "end": 21 + } + } + ] +} + +{ + "text": "spans where (a:1", + "problems": [ + { + "path": "text", + "message": "unclosed (; add ) before |, sort, limit or the end", + "span": { + "start": 12, + "end": 13 + } + } + ] +} + +{ + "text": "spans where (a:1 b:2 or c:3)", + "problems": [ + { + "path": "text", + "message": "mixed and/or needs parentheses", + "hint": "write a:1 (b:2 or c:3) or (a:1 b:2) or c:3", + "span": { + "start": 13, + "end": 27 + }, + "fix_its": [ + { + "label": "a:1 (b:2 or c:3)", + "span": { + "start": 13, + "end": 27 + }, + "text": "a:1 (b:2 or c:3)" + }, + { + "label": "(a:1 b:2) or c:3", + "span": { + "start": 13, + "end": 27 + }, + "text": "(a:1 b:2) or c:3" + } + ] + } + ] +} + +{ + "text": "spans where (a:1 b:2)", + "query": { + "from": "spans", + "where": [ + "(attributes['a'] = 1 AND attributes['b'] = 2)" + ] + } +} + +{ + "text": "spans where (a:1 b:2) or c:3", + "query": { + "from": "spans", + "where": [ + "((attributes['a'] = 1 AND attributes['b'] = 2) OR attributes['c'] = 3)" + ] + } +} + +{ + "text": "spans where (a:1)", + "query": { + "from": "spans", + "where": [ + "attributes['a'] = 1" + ] + } +} + +{ + "text": "spans where (attributes['a']:1 attributes['b']:2)", + "query": { + "from": "spans", + "where": [ + "(attributes['a'] = 1 AND attributes['b'] = 2)" + ] + } +} + +{ + "text": "spans where (attributes['a']:1 or attributes['b']:2) service:api", + "query": { + "from": "spans", + "where": [ + "(attributes['a'] = 1 OR attributes['b'] = 2)", + "service = 'api'" + ] + } +} + +{ + "text": "spans where (service:$service status:error)", + "query": { + "from": "spans", + "where": [ + "(service = $service AND status = 'STATUS_CODE_ERROR')" + ] + } +} + +{ + "text": "spans where *foo", + "problems": [ + { + "path": "text", + "message": "* wildcards are not in FanQL 1", + "hint": "use ~ for contains, or quote \"*foo\"", + "span": { + "start": 12, + "end": 16 + } + } + ] +} + +{ + "text": "spans where -(a:1 or b:2)", + "query": { + "from": "spans", + "where": [ + "((attributes['a'] IS NULL OR attributes['a'] != 1) AND (attributes['b'] IS NULL OR attributes['b'] != 2))" + ] + } +} + +{ + "text": "spans where -(status:error kind:server)", + "query": { + "from": "spans", + "where": [ + "((status IS NULL OR status != 'STATUS_CODE_ERROR') OR (kind IS NULL OR kind != 'SPAN_KIND_SERVER'))" + ] + } +} + +{ + "text": "spans where -attributes['k'] between 1 and 5", + "query": { + "from": "spans", + "where": [ + "NOT coalesce((attributes['k'] BETWEEN 1 AND 5), FALSE)" + ] + } +} + +{ + "text": "spans where -attributes['k'] ilike \"GET %\"", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR attributes['k'] !~~* 'GET %')" + ] + } +} + +{ + "text": "spans where -attributes['k'] in (1, true, api, \"api*\")", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR attributes['k'] NOT IN (1, true, 'api', 'api*'))" + ] + } +} + +{ + "text": "spans where -attributes['k'] is not null", + "query": { + "from": "spans", + "where": [ + "attributes['k'] IS NULL" + ] + } +} + +{ + "text": "spans where -attributes['k'] is null", + "query": { + "from": "spans", + "where": [ + "attributes['k'] IS NOT NULL" + ] + } +} + +{ + "text": "spans where -attributes['k'] like \"GET %\"", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR attributes['k'] !~~ 'GET %')" + ] + } +} + +{ + "text": "spans where -attributes['k'] not between 1 and 5", + "query": { + "from": "spans", + "where": [ + "NOT coalesce((attributes['k'] NOT BETWEEN 1 AND 5), FALSE)" + ] + } +} + +{ + "text": "spans where -attributes['k'] not ilike \"GET %\"", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR attributes['k'] ~~* 'GET %')" + ] + } +} + +{ + "text": "spans where -attributes['k'] not in (1, true, api, \"api*\")", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR attributes['k'] IN (1, true, 'api', 'api*'))" + ] + } +} + +{ + "text": "spans where -attributes['k'] not like \"GET %\"", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR attributes['k'] ~~ 'GET %')" + ] + } +} + +{ + "text": "spans where -duration not between 1s and 2s", + "query": { + "from": "spans", + "where": [ + "(duration_ms IS NULL OR duration_ms BETWEEN 1000 AND 2000)" + ] + } +} + +{ + "text": "spans where -duration>1s", + "query": { + "from": "spans", + "where": [ + "(duration_ms IS NULL OR duration_ms <= 1000)" + ] + } +} + +{ + "text": "spans where -http_status_code between 400 and 599", + "query": { + "from": "spans", + "where": [ + "NOT coalesce((TRY_CAST(http_status_code AS INTEGER) BETWEEN 400 AND 599), FALSE)" + ] + } +} + +{ + "text": "spans where -http_status_code not between 400 and 599", + "query": { + "from": "spans", + "where": [ + "NOT coalesce((TRY_CAST(http_status_code AS INTEGER) NOT BETWEEN 400 AND 599), FALSE)" + ] + } +} + +{ + "text": "spans where -http_status_code:500", + "query": { + "from": "spans", + "where": [ + "(http_status_code IS NULL OR http_status_code != '500')" + ] + } +} + +{ + "text": "spans where -http_status_code>=500", + "query": { + "from": "spans", + "where": [ + "NOT coalesce((TRY_CAST(http_status_code AS INTEGER) >= 500), FALSE)" + ] + } +} + +{ + "text": "spans where -k ~ v", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('v')))" + ] + } +} + +{ + "text": "spans where -k:$v", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR attributes['k'] != $v)" + ] + } +} + +{ + "text": "spans where -service in (a, b)", + "query": { + "from": "spans", + "where": [ + "(service IS NULL OR service NOT IN ('a', 'b'))" + ] + } +} + +{ + "text": "spans where -service not in (a, b)", + "query": { + "from": "spans", + "where": [ + "(service IS NULL OR service IN ('a', 'b'))" + ] + } +} + +{ + "text": "spans where -service!=api", + "query": { + "from": "spans", + "where": [ + "(service IS NULL OR service = 'api')" + ] + } +} + +{ + "text": "spans where -starts_with(http_route, \"/api\")", + "query": { + "from": "spans", + "where": [ + "NOT coalesce((starts_with(http_route, '/api')), FALSE)" + ] + } +} + +{ + "text": "spans where -user.id:*", + "query": { + "from": "spans", + "where": [ + "attributes['user.id'] IS NULL" + ] + } +} + +{ + "text": "spans where 500>3", + "problems": [ + { + "path": "text", + "message": "a filter needs a field before >", + "span": { + "start": 12, + "end": 15 + } + } + ] +} + +{ + "text": "spans where >500ms", + "problems": [ + { + "path": "text", + "message": "a filter needs a field before >", + "span": { + "start": 12, + "end": 13 + } + } + ] +} + +{ + "text": "spans where @http.target:x", + "problems": [ + { + "path": "text", + "message": "\"@http.target\" is not a field name; write the attribute without @: http.target", + "span": { + "start": 12, + "end": 24 + } + } + ] +} + +{ + "text": "spans where HTTP.Target:x", + "query": { + "from": "spans", + "where": [ + "attributes['HTTP.Target'] = 'x'" + ] + } +} + +{ + "text": "spans where P95(Duration)", + "problems": [ + { + "path": "where[0]", + "message": "function p95 is not allowed in a filter", + "span": { + "start": 12, + "end": 25 + } + } + ] +} + +{ + "text": "spans where Service:api", + "query": { + "from": "spans", + "where": [ + "service = 'api'" + ] + } +} + +{ + "text": "spans where _time:x", + "problems": [ + { + "path": "text", + "message": "the time range is not part of FanQL 1; use the time picker (_time is reserved)", + "span": { + "start": 12, + "end": 17 + } + } + ] +} + +{ + "text": "spans where `coalesce(a", + "problems": [ + { + "path": "text", + "message": "unclosed raw filter; close it with `", + "span": { + "start": 12, + "end": 23 + } + } + ] +} + +{ + "text": "spans where a:1 (b:2 or c:3)", + "query": { + "from": "spans", + "where": [ + "attributes['a'] = 1", + "(attributes['b'] = 2 OR attributes['c'] = 3)" + ] + } +} + +{ + "text": "spans where a:1 and b:2 or c:3", + "problems": [ + { + "path": "text", + "message": "mixed and/or needs parentheses", + "hint": "write a:1 and (b:2 or c:3) or (a:1 and b:2) or c:3", + "span": { + "start": 12, + "end": 30 + }, + "fix_its": [ + { + "label": "a:1 and (b:2 or c:3)", + "span": { + "start": 12, + "end": 30 + }, + "text": "a:1 and (b:2 or c:3)" + }, + { + "label": "(a:1 and b:2) or c:3", + "span": { + "start": 12, + "end": 30 + }, + "text": "(a:1 and b:2) or c:3" + } + ] + } + ] +} + +{ + "text": "spans where a:1 b:2 (c:3 or d:4) (e:5 f:6)", + "query": { + "from": "spans", + "where": [ + "attributes['a'] = 1", + "attributes['b'] = 2", + "(attributes['c'] = 3 OR attributes['d'] = 4)", + "(attributes['e'] = 5 AND attributes['f'] = 6)" + ] + } +} + +{ + "text": "spans where a:1 b:2 or c:3", + "problems": [ + { + "path": "text", + "message": "mixed and/or needs parentheses", + "hint": "write a:1 (b:2 or c:3) or (a:1 b:2) or c:3", + "span": { + "start": 12, + "end": 26 + }, + "fix_its": [ + { + "label": "a:1 (b:2 or c:3)", + "span": { + "start": 12, + "end": 26 + }, + "text": "a:1 (b:2 or c:3)" + }, + { + "label": "(a:1 b:2) or c:3", + "span": { + "start": 12, + "end": 26 + }, + "text": "(a:1 b:2) or c:3" + } + ] + } + ] +} + +{ + "text": "spans where a:1 b:2 or c:3 | p99(duration) by http_route every 1m", + "problems": [ + { + "path": "text", + "message": "mixed and/or needs parentheses", + "hint": "write a:1 (b:2 or c:3) or (a:1 b:2) or c:3", + "span": { + "start": 12, + "end": 26 + }, + "fix_its": [ + { + "label": "a:1 (b:2 or c:3)", + "span": { + "start": 12, + "end": 26 + }, + "text": "a:1 (b:2 or c:3)" + }, + { + "label": "(a:1 b:2) or c:3", + "span": { + "start": 12, + "end": 26 + }, + "text": "(a:1 b:2) or c:3" + } + ] + } + ] +} + +{ + "text": "spans where a:1 or", + "problems": [ + { + "path": "text", + "message": "or needs a filter on both sides", + "span": { + "start": 16, + "end": 18 + } + } + ] +} + +{ + "text": "spans where a:1 or b:2", + "query": { + "from": "spans", + "where": [ + "(attributes['a'] = 1 OR attributes['b'] = 2)" + ] + } +} + +{ + "text": "spans where a:1 or b:2 c:3", + "problems": [ + { + "path": "text", + "message": "mixed and/or needs parentheses", + "hint": "write a:1 or (b:2 c:3) or (a:1 or b:2) c:3", + "span": { + "start": 12, + "end": 26 + }, + "fix_its": [ + { + "label": "a:1 or (b:2 c:3)", + "span": { + "start": 12, + "end": 26 + }, + "text": "a:1 or (b:2 c:3)" + }, + { + "label": "(a:1 or b:2) c:3", + "span": { + "start": 12, + "end": 26 + }, + "text": "(a:1 or b:2) c:3" + } + ] + } + ] +} + +{ + "text": "spans where a:1 or c:3", + "query": { + "from": "spans", + "where": [ + "(attributes['a'] = 1 OR attributes['c'] = 3)" + ] + } +} + +{ + "text": "spans where a:1 where b:2", + "problems": [ + { + "path": "text", + "message": "where appears twice; combine the filters into one where", + "span": { + "start": 16, + "end": 21 + } + } + ] +} + +{ + "text": "spans where a:1 | count_if(status:error -http.target:/healthz) / count() * 1.5 as x by resource.k8s.pod.name every 1m", + "query": { + "from": "spans", + "where": [ + "attributes['a'] = 1" + ], + "measures": [ + "count_if(status = 'STATUS_CODE_ERROR' AND (attributes['http.target'] IS NULL OR attributes['http.target'] != '/healthz')) / count() * 1.5 as x" + ], + "by": [ + "resource['k8s.pod.name']" + ], + "bucket": "1m" + } +} + +{ + "text": "spans where a:1)", + "problems": [ + { + "path": "text", + "message": "unmatched ); remove it or add the opening (", + "span": { + "start": 15, + "end": 16 + } + } + ] +} + +{ + "text": "spans where ago(1h)", + "problems": [ + { + "path": "text", + "message": "ago(...) is not FanQL; use the time picker", + "span": { + "start": 12, + "end": 15 + } + } + ] +} + +{ + "text": "spans where attr", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('attr'))" + ] + } +} + +{ + "text": "spans where attributes.http.target:/h", + "query": { + "from": "spans", + "where": [ + "attributes['http.target'] = '/h'" + ] + } +} + +{ + "text": "spans where attributes['Resource.k']:x", + "query": { + "from": "spans", + "where": [ + "attributes['Resource.k'] = 'x'" + ] + } +} + +{ + "text": "spans where attributes['a']:1 or attributes['b']:2", + "query": { + "from": "spans", + "where": [ + "(attributes['a'] = 1 OR attributes['b'] = 2)" + ] + } +} + +{ + "text": "spans where attributes['attributes.k']:x", + "query": { + "from": "spans", + "where": [ + "attributes['attributes.k'] = 'x'" + ] + } +} + +{ + "text": "spans where attributes['flag']:true", + "query": { + "from": "spans", + "where": [ + "attributes['flag'] = true" + ] + } +} + +{ + "text": "spans where attributes['ht", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with '", + "span": { + "start": 23, + "end": 26 + } + }, + { + "path": "text", + "message": "a bracket field needs a quoted key and ]", + "span": { + "start": 23, + "end": 26 + } + } + ] +} + +{ + "text": "spans where attributes['htt", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with '", + "span": { + "start": 23, + "end": 27 + } + }, + { + "path": "text", + "message": "a bracket field needs a quoted key and ]", + "span": { + "start": 23, + "end": 27 + } + } + ] +} + +{ + "text": "spans where attributes['k'] between 1 and 5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] BETWEEN 1 AND 5" + ] + } +} + +{ + "text": "spans where attributes['k'] ilike \"GET %\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] ~~* 'GET %'" + ] + } +} + +{ + "text": "spans where attributes['k'] in (1, true, api, \"api*\")", + "query": { + "from": "spans", + "where": [ + "attributes['k'] IN (1, true, 'api', 'api*')" + ] + } +} + +{ + "text": "spans where attributes['k'] is not null", + "query": { + "from": "spans", + "where": [ + "attributes['k'] IS NOT NULL" + ] + } +} + +{ + "text": "spans where attributes['k'] is null", + "query": { + "from": "spans", + "where": [ + "attributes['k'] IS NULL" + ] + } +} + +{ + "text": "spans where attributes['k'] like \"GET %\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] ~~ 'GET %'" + ] + } +} + +{ + "text": "spans where attributes['k'] not between 1 and 5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] NOT BETWEEN 1 AND 5" + ] + } +} + +{ + "text": "spans where attributes['k'] not ilike \"GET %\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] !~~* 'GET %'" + ] + } +} + +{ + "text": "spans where attributes['k'] not in (1, true, api, \"api*\")", + "query": { + "from": "spans", + "where": [ + "attributes['k'] NOT IN (1, true, 'api', 'api*')" + ] + } +} + +{ + "text": "spans where attributes['k'] not like \"GET %\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] !~~ 'GET %'" + ] + } +} + +{ + "text": "spans where attributes['k']!=\"a$svc\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 'a$svc'" + ] + } +} + +{ + "text": "spans where attributes['k']!=\"api*\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 'api*'" + ] + } +} + +{ + "text": "spans where attributes['k']!=-3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != -3" + ] + } +} + +{ + "text": "spans where attributes['k']!=1.5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 1.5" + ] + } +} + +{ + "text": "spans where attributes['k']!=2e3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 2000" + ] + } +} + +{ + "text": "spans where attributes['k']!=5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 5" + ] + } +} + +{ + "text": "spans where attributes['k']!=api", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 'api'" + ] + } +} + +{ + "text": "spans where attributes['k']!=false", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != false" + ] + } +} + +{ + "text": "spans where attributes['k']!=true", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != true" + ] + } +} + +{ + "text": "spans where attributes['k']!~\"a$svc\"", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('a$svc')))" + ] + } +} + +{ + "text": "spans where attributes['k']!~\"api*\"", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('api*')))" + ] + } +} + +{ + "text": "spans where attributes['k']!~-3", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('-3')))" + ] + } +} + +{ + "text": "spans where attributes['k']!~1.5", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('1.5')))" + ] + } +} + +{ + "text": "spans where attributes['k']!~2e3", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('2e3')))" + ] + } +} + +{ + "text": "spans where attributes['k']!~5", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('5')))" + ] + } +} + +{ + "text": "spans where attributes['k']!~api", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('api')))" + ] + } +} + +{ + "text": "spans where attributes['k']!~false", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('false')))" + ] + } +} + +{ + "text": "spans where attributes['k']!~true", + "query": { + "from": "spans", + "where": [ + "(attributes['k'] IS NULL OR NOT contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('true')))" + ] + } +} + +{ + "text": "spans where attributes['k']:\"a$svc\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] = 'a$svc'" + ] + } +} + +{ + "text": "spans where attributes['k']:\"api*\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] = 'api*'" + ] + } +} + +{ + "text": "spans where attributes['k']:-3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] = -3" + ] + } +} + +{ + "text": "spans where attributes['k']:1.5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] = 1.5" + ] + } +} + +{ + "text": "spans where attributes['k']:2e3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] = 2000" + ] + } +} + +{ + "text": "spans where attributes['k']:5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] = 5" + ] + } +} + +{ + "text": "spans where attributes['k']:api", + "query": { + "from": "spans", + "where": [ + "attributes['k'] = 'api'" + ] + } +} + +{ + "text": "spans where attributes['k']:false", + "query": { + "from": "spans", + "where": [ + "attributes['k'] = false" + ] + } +} + +{ + "text": "spans where attributes['k']:true", + "query": { + "from": "spans", + "where": [ + "attributes['k'] = true" + ] + } +} + +{ + "text": "spans where attributes['k']<\"a$svc\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] < 'a$svc'" + ] + } +} + +{ + "text": "spans where attributes['k']<\"api*\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] < 'api*'" + ] + } +} + +{ + "text": "spans where attributes['k']<-3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] < -3" + ] + } +} + +{ + "text": "spans where attributes['k']<1.5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] < 1.5" + ] + } +} + +{ + "text": "spans where attributes['k']<2e3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] < 2000" + ] + } +} + +{ + "text": "spans where attributes['k']<5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] < 5" + ] + } +} + +{ + "text": "spans where attributes['k']<=\"a$svc\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] <= 'a$svc'" + ] + } +} + +{ + "text": "spans where attributes['k']<=\"api*\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] <= 'api*'" + ] + } +} + +{ + "text": "spans where attributes['k']<=-3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] <= -3" + ] + } +} + +{ + "text": "spans where attributes['k']<=1.5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] <= 1.5" + ] + } +} + +{ + "text": "spans where attributes['k']<=2e3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] <= 2000" + ] + } +} + +{ + "text": "spans where attributes['k']<=5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] <= 5" + ] + } +} + +{ + "text": "spans where attributes['k']<=api", + "query": { + "from": "spans", + "where": [ + "attributes['k'] <= 'api'" + ] + } +} + +{ + "text": "spans where attributes['k']<=false", + "query": { + "from": "spans", + "where": [ + "attributes['k'] <= false" + ] + } +} + +{ + "text": "spans where attributes['k']<=true", + "query": { + "from": "spans", + "where": [ + "attributes['k'] <= true" + ] + } +} + +{ + "text": "spans where attributes['k']<>\"a$svc\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 'a$svc'" + ] + } +} + +{ + "text": "spans where attributes['k']<>\"api*\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 'api*'" + ] + } +} + +{ + "text": "spans where attributes['k']<>-3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != -3" + ] + } +} + +{ + "text": "spans where attributes['k']<>1.5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 1.5" + ] + } +} + +{ + "text": "spans where attributes['k']<>2e3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 2000" + ] + } +} + +{ + "text": "spans where attributes['k']<>5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 5" + ] + } +} + +{ + "text": "spans where attributes['k']<>api", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != 'api'" + ] + } +} + +{ + "text": "spans where attributes['k']<>false", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != false" + ] + } +} + +{ + "text": "spans where attributes['k']<>true", + "query": { + "from": "spans", + "where": [ + "attributes['k'] != true" + ] + } +} + +{ + "text": "spans where attributes['k']\"a$svc\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] > 'a$svc'" + ] + } +} + +{ + "text": "spans where attributes['k']>\"api*\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] > 'api*'" + ] + } +} + +{ + "text": "spans where attributes['k']>-3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] > -3" + ] + } +} + +{ + "text": "spans where attributes['k']>1.5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] > 1.5" + ] + } +} + +{ + "text": "spans where attributes['k']>2e3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] > 2000" + ] + } +} + +{ + "text": "spans where attributes['k']>5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] > 5" + ] + } +} + +{ + "text": "spans where attributes['k']>=\"a$svc\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] >= 'a$svc'" + ] + } +} + +{ + "text": "spans where attributes['k']>=\"api*\"", + "query": { + "from": "spans", + "where": [ + "attributes['k'] >= 'api*'" + ] + } +} + +{ + "text": "spans where attributes['k']>=-3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] >= -3" + ] + } +} + +{ + "text": "spans where attributes['k']>=1.5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] >= 1.5" + ] + } +} + +{ + "text": "spans where attributes['k']>=2e3", + "query": { + "from": "spans", + "where": [ + "attributes['k'] >= 2000" + ] + } +} + +{ + "text": "spans where attributes['k']>=5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] >= 5" + ] + } +} + +{ + "text": "spans where attributes['k']>=api", + "query": { + "from": "spans", + "where": [ + "attributes['k'] >= 'api'" + ] + } +} + +{ + "text": "spans where attributes['k']>=false", + "query": { + "from": "spans", + "where": [ + "attributes['k'] >= false" + ] + } +} + +{ + "text": "spans where attributes['k']>=true", + "query": { + "from": "spans", + "where": [ + "attributes['k'] >= true" + ] + } +} + +{ + "text": "spans where attributes['k']>api", + "query": { + "from": "spans", + "where": [ + "attributes['k'] > 'api'" + ] + } +} + +{ + "text": "spans where attributes['k']>false", + "query": { + "from": "spans", + "where": [ + "attributes['k'] > false" + ] + } +} + +{ + "text": "spans where attributes['k']>true", + "query": { + "from": "spans", + "where": [ + "attributes['k'] > true" + ] + } +} + +{ + "text": "spans where attributes['k']~\"a$svc\"", + "query": { + "from": "spans", + "where": [ + "contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('a$svc'))" + ] + } +} + +{ + "text": "spans where attributes['k']~\"api*\"", + "query": { + "from": "spans", + "where": [ + "contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('api*'))" + ] + } +} + +{ + "text": "spans where attributes['k']~-3", + "query": { + "from": "spans", + "where": [ + "contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('-3'))" + ] + } +} + +{ + "text": "spans where attributes['k']~1.5", + "query": { + "from": "spans", + "where": [ + "contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('1.5'))" + ] + } +} + +{ + "text": "spans where attributes['k']~2e3", + "query": { + "from": "spans", + "where": [ + "contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('2e3'))" + ] + } +} + +{ + "text": "spans where attributes['k']~5", + "query": { + "from": "spans", + "where": [ + "contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('5'))" + ] + } +} + +{ + "text": "spans where attributes['k']~api", + "query": { + "from": "spans", + "where": [ + "contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('api'))" + ] + } +} + +{ + "text": "spans where attributes['k']~false", + "query": { + "from": "spans", + "where": [ + "contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('false'))" + ] + } +} + +{ + "text": "spans where attributes['k']~true", + "query": { + "from": "spans", + "where": [ + "contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('true'))" + ] + } +} + +{ + "text": "spans where attributes['own", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with '", + "span": { + "start": 23, + "end": 27 + } + }, + { + "path": "text", + "message": "a bracket field needs a quoted key and ]", + "span": { + "start": 23, + "end": 27 + } + } + ] +} + +{ + "text": "spans where attributes['own']:api", + "query": { + "from": "spans", + "where": [ + "attributes['own'] = 'api'" + ] + } +} + +{ + "text": "spans where attributes['owner''", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with '", + "span": { + "start": 23, + "end": 31 + } + }, + { + "path": "text", + "message": "a bracket field needs a quoted key and ]", + "span": { + "start": 23, + "end": 31 + } + } + ] +} + +{ + "text": "spans where attributes['resource.k']:x", + "query": { + "from": "spans", + "where": [ + "attributes['resource.k'] = 'x'" + ] + } +} + +{ + "text": "spans where attributes['é.x']:api", + "query": { + "from": "spans", + "where": [ + "attributes['é.x'] = 'api'" + ] + } +} + +{ + "text": "spans where attributes['😀", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with '", + "span": { + "start": 23, + "end": 25 + } + }, + { + "path": "text", + "message": "a bracket field needs a quoted key and ]", + "span": { + "start": 23, + "end": 25 + } + } + ] +} + +{ + "text": "spans where body =~ \"re\"", + "problems": [ + { + "path": "text", + "message": "=~ is not FanQL; ~ is contains; use regexp_matches(field, 're') for a regular expression", + "span": { + "start": 17, + "end": 19 + } + } + ] +} + +{ + "text": "spans where body::text", + "problems": [ + { + "path": "text", + "message": ":: is not FanQL; use field comparisons or a backtick raw filter", + "span": { + "start": 16, + "end": 18 + } + } + ] +} + +{ + "text": "spans where compare", + "problems": [ + { + "path": "text", + "message": "\"compare\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 19 + } + } + ] +} + +{ + "text": "spans where correlate", + "problems": [ + { + "path": "text", + "message": "\"correlate\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 21 + } + } + ] +} + +{ + "text": "spans where db_system:postgresql db.statement ~ \"SELECT\" duration>500ms sort duration limit 10", + "query": { + "from": "spans", + "where": [ + "db_system = 'postgresql'", + "contains(lower(CAST(attributes['db.statement'] AS VARCHAR)), lower('SELECT'))", + "duration_ms > 500" + ], + "sort": "duration_ms", + "limit": 10 + } +} + +{ + "text": "spans where duration ", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('duration'))" + ] + } +} + +{ + "text": "spans where duration > 500ms", + "query": { + "from": "spans", + "where": [ + "duration_ms > 500" + ] + } +} + +{ + "text": "spans where duration between 1s", + "problems": [ + { + "path": "text", + "message": "between needs two values", + "span": { + "start": 12, + "end": 31 + } + } + ] +} + +{ + "text": "spans where duration between 1s and 2s status:error", + "query": { + "from": "spans", + "where": [ + "duration_ms BETWEEN 1000 AND 2000", + "status = 'STATUS_CODE_ERROR'" + ] + } +} + +{ + "text": "spans where duration:", + "problems": [ + { + "path": "text", + "message": "duration: needs a value; e.g. duration:500ms", + "span": { + "start": 12, + "end": 21 + } + } + ] +} + +{ + "text": "spans where duration>", + "problems": [ + { + "path": "text", + "message": "duration> needs a value; e.g. duration>500ms", + "span": { + "start": 12, + "end": 21 + } + } + ] +} + +{ + "text": "spans where duration>-1ms", + "problems": [ + { + "path": "where[0]", + "message": "durations are not negative", + "span": { + "start": 21, + "end": 25 + } + } + ] +} + +{ + "text": "spans where duration>1e308h", + "problems": [ + { + "path": "where[0]", + "message": "number must be finite", + "span": { + "start": 21, + "end": 27 + } + } + ] +} + +{ + "text": "spans where duration>1h30m", + "problems": [ + { + "path": "where[0]", + "message": "duration needs a unit; e.g. duration>500ms", + "span": { + "start": 21, + "end": 26 + } + } + ] +} + +{ + "text": "spans where duration>500", + "problems": [ + { + "path": "where[0]", + "message": "duration needs a unit; e.g. duration>500ms", + "span": { + "start": 21, + "end": 24 + } + } + ] +} + +{ + "text": "spans where duration>500ms", + "query": { + "from": "spans", + "where": [ + "duration_ms > 500" + ] + } +} + +{ + "text": "spans where duration_ms:true", + "problems": [ + { + "path": "where[0]", + "message": "duration_ms needs a number", + "span": { + "start": 24, + "end": 28 + } + } + ] +} + +{ + "text": "spans where duration_ms>1e309", + "problems": [ + { + "path": "where[0]", + "message": "number must be finite", + "span": { + "start": 24, + "end": 29 + } + } + ] +} + +{ + "text": "spans where duration_ms>500", + "query": { + "from": "spans", + "where": [ + "duration_ms > 500" + ] + } +} + +{ + "text": "spans where earliest=1h", + "problems": [ + { + "path": "text", + "message": "the time range is not part of FanQL 1; use the time picker (earliest is reserved)", + "span": { + "start": 12, + "end": 20 + } + } + ] +} + +{ + "text": "spans where enabled:", + "problems": [ + { + "path": "text", + "message": "enabled: needs a value; e.g. enabled:api", + "span": { + "start": 12, + "end": 20 + } + } + ] +} + +{ + "text": "spans where eval", + "problems": [ + { + "path": "text", + "message": "\"eval\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 16 + } + } + ] +} + +{ + "text": "spans where extend", + "problems": [ + { + "path": "text", + "message": "\"extend\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 18 + } + } + ] +} + +{ + "text": "spans where fields", + "problems": [ + { + "path": "text", + "message": "\"fields\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 18 + } + } + ] +} + +{ + "text": "spans where flag:\"true\"", + "query": { + "from": "spans", + "where": [ + "attributes['flag'] = 'true'" + ] + } +} + +{ + "text": "spans where flag:true", + "query": { + "from": "spans", + "where": [ + "attributes['flag'] = true" + ] + } +} + +{ + "text": "spans where having", + "problems": [ + { + "path": "text", + "message": "\"having\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 18 + } + } + ] +} + +{ + "text": "spans where htt", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('htt'))" + ] + } +} + +{ + "text": "spans where http.", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('http.'))" + ] + } +} + +{ + "text": "spans where http.target:\"/a:b\"", + "query": { + "from": "spans", + "where": [ + "attributes['http.target'] = '/a:b'" + ] + } +} + +{ + "text": "spans where http.target:/a:b", + "problems": [ + { + "path": "text", + "message": "unexpected : after /a", + "hint": "quote the value: http.target:\"/a:b\"", + "span": { + "start": 12, + "end": 28 + } + } + ] +} + +{ + "text": "spans where http.target:/a:b duration>=500ms -k:v us-east-1 $svc", + "problems": [ + { + "path": "text", + "message": "unexpected : after /a", + "hint": "quote the value: http.target:\"/a:b\"", + "span": { + "start": 12, + "end": 28 + } + } + ] +} + +{ + "text": "spans where http.target:/h", + "query": { + "from": "spans", + "where": [ + "attributes['http.target'] = '/h'" + ] + } +} + +{ + "text": "spans where http_status_code not between 400 and 599", + "query": { + "from": "spans", + "where": [ + "TRY_CAST(http_status_code AS INTEGER) NOT BETWEEN 400 AND 599" + ] + } +} + +{ + "text": "spans where http_status_code:2e3", + "query": { + "from": "spans", + "where": [ + "http_status_code = '2e3'" + ] + } +} + +{ + "text": "spans where http_status_code:500", + "query": { + "from": "spans", + "where": [ + "http_status_code = '500'" + ] + } +} + +{ + "text": "spans where http_status_code>500ms", + "problems": [ + { + "path": "where[0]", + "message": "units apply to duration only; write http_status_code>500", + "span": { + "start": 29, + "end": 34 + } + } + ] +} + +{ + "text": "spans where http_status_code>=$code", + "query": { + "from": "spans", + "where": [ + "TRY_CAST(http_status_code AS INTEGER) >= $code" + ] + } +} + +{ + "text": "spans where http_status_code>=500", + "query": { + "from": "spans", + "where": [ + "TRY_CAST(http_status_code AS INTEGER) >= 500" + ] + } +} + +{ + "text": "spans where http_status_code>=warn", + "query": { + "from": "spans", + "where": [ + "TRY_CAST(http_status_code AS INTEGER) >= 'warn'" + ] + } +} + +{ + "text": "spans where join", + "problems": [ + { + "path": "text", + "message": "\"join\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 16 + } + } + ] +} + +{ + "text": "spans where k in (", + "problems": [ + { + "path": "text", + "message": "a list needs a value after each comma", + "span": { + "start": 18, + "end": 18 + } + }, + { + "path": "text", + "message": "in needs a list or variable, e.g. in (api, web)", + "span": { + "start": 18, + "end": 18 + } + } + ] +} + +{ + "text": "spans where k like a%", + "problems": [ + { + "path": "text", + "message": "like needs a quoted pattern", + "span": { + "start": 12, + "end": 21 + } + } + ] +} + +{ + "text": "spans where k not a:1", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('k'))", + "(attributes['a'] IS NULL OR attributes['a'] != 1)" + ] + } +} + +{ + "text": "spans where k ~ v", + "query": { + "from": "spans", + "where": [ + "contains(lower(CAST(attributes['k'] AS VARCHAR)), lower('v'))" + ] + } +} + +{ + "text": "spans where k:*", + "query": { + "from": "spans", + "where": [ + "attributes['k'] IS NOT NULL" + ] + } +} + +{ + "text": "spans where k:+3", + "problems": [ + { + "path": "text", + "message": "unexpected +", + "span": { + "start": 14, + "end": 15 + } + } + ] +} + +{ + "text": "spans where k:-foo", + "problems": [ + { + "path": "text", + "message": "k: needs a value; e.g. k:api", + "span": { + "start": 12, + "end": 14 + } + } + ] +} + +{ + "text": "spans where k:>5", + "query": { + "from": "spans", + "where": [ + "attributes['k'] > 5" + ] + } +} + +{ + "text": "spans where kind:\"SPAN_KIND_SERVER\"", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_SERVER'" + ] + } +} + +{ + "text": "spans where kind:SPAN_KIND_CLIENT", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_CLIENT'" + ] + } +} + +{ + "text": "spans where kind:SPAN_KIND_CONSUMER", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_CONSUMER'" + ] + } +} + +{ + "text": "spans where kind:SPAN_KIND_INTERNAL", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_INTERNAL'" + ] + } +} + +{ + "text": "spans where kind:SPAN_KIND_PRODUCER", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_PRODUCER'" + ] + } +} + +{ + "text": "spans where kind:SPAN_KIND_SERVER", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_SERVER'" + ] + } +} + +{ + "text": "spans where kind:SPAN_KIND_UNSPECIFIED", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_UNSPECIFIED'" + ] + } +} + +{ + "text": "spans where kind:client", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_CLIENT'" + ] + } +} + +{ + "text": "spans where kind:consumer", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_CONSUMER'" + ] + } +} + +{ + "text": "spans where kind:http", + "problems": [ + { + "path": "where[0]", + "message": "unknown kind \"http\"; use kind:server, kind:client, kind:internal, kind:producer, kind:consumer or kind:unspecified", + "span": { + "start": 17, + "end": 21 + } + } + ] +} + +{ + "text": "spans where kind:internal", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_INTERNAL'" + ] + } +} + +{ + "text": "spans where kind:producer", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_PRODUCER'" + ] + } +} + +{ + "text": "spans where kind:server", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_SERVER'" + ] + } +} + +{ + "text": "spans where kind:server | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_SERVER'" + ], + "measures": [ + "(count_if(duration_ms <= 500) + count_if(duration_ms > 500 AND duration_ms <= 2000) / 2) / count() as apdex" + ] + } +} + +{ + "text": "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_SERVER'" + ], + "measures": [ + "count_if(TRY_CAST(http_status_code AS INTEGER) >= 500) / count() * 100 as pct_5xx" + ], + "by": [ + "http_route" + ] + } +} + +{ + "text": "spans where kind:server | count_if(http_status_code>=500) / count() * 100 as pct_5xx by http_route every auto", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_SERVER'" + ], + "measures": [ + "count_if(TRY_CAST(http_status_code AS INTEGER) >= 500) / count() * 100 as pct_5xx" + ], + "by": [ + "http_route" + ], + "bucket": "auto" + } +} + +{ + "text": "spans where kind:server | count_if(status:error -http.target:/healthz) / count() * 100 as e", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_SERVER'" + ], + "measures": [ + "count_if(status = 'STATUS_CODE_ERROR' AND (attributes['http.target'] IS NULL OR attributes['http.target'] != '/healthz')) / count() * 100 as e" + ] + } +} + +{ + "text": "spans where kind:server | count_if(status:error) / count() * 100 as err_pct", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_SERVER'" + ], + "measures": [ + "count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as err_pct" + ] + } +} + +{ + "text": "spans where kind:server | error_rate() by service every 1m", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_SERVER'" + ], + "measures": [ + "error_rate()" + ], + "by": [ + "service" + ], + "bucket": "1m" + } +} + +{ + "text": "spans where kind:unspecified", + "query": { + "from": "spans", + "where": [ + "kind = 'SPAN_KIND_UNSPECIFIED'" + ] + } +} + +{ + "text": "spans where let", + "problems": [ + { + "path": "text", + "message": "\"let\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 15 + } + } + ] +} + +{ + "text": "spans where lower(k)", + "problems": [ + { + "path": "where[0]", + "message": "lower(...) needs a comparison", + "span": { + "start": 12, + "end": 20 + } + } + ] +} + +{ + "text": "spans where lower(service) = \"api\"", + "query": { + "from": "spans", + "where": [ + "lower(service) = 'api'" + ] + } +} + +{ + "text": "spans where not a:1 b:2", + "query": { + "from": "spans", + "where": [ + "(attributes['a'] IS NULL OR attributes['a'] != 1)", + "attributes['b'] = 2" + ] + } +} + +{ + "text": "spans where now()", + "problems": [ + { + "path": "text", + "message": "now(...) is not FanQL; use the time picker", + "span": { + "start": 12, + "end": 15 + } + } + ] +} + +{ + "text": "spans where over", + "problems": [ + { + "path": "text", + "message": "\"over\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 16 + } + } + ] +} + +{ + "text": "spans where rename", + "problems": [ + { + "path": "text", + "message": "\"rename\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 18 + } + } + ] +} + +{ + "text": "spans where res", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('res'))" + ] + } +} + +{ + "text": "spans where resource.k8s.pod.name:x", + "query": { + "from": "spans", + "where": [ + "resource['k8s.pod.name'] = 'x'" + ] + } +} + +{ + "text": "spans where resource.serv", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('resource.serv'))" + ] + } +} + +{ + "text": "spans where resource.wh", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('resource.wh'))" + ] + } +} + +{ + "text": "spans where resource[\"k8s.", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with \"", + "span": { + "start": 21, + "end": 26 + } + }, + { + "path": "text", + "message": "a bracket field needs a quoted key and ]", + "span": { + "start": 21, + "end": 26 + } + } + ] +} + +{ + "text": "spans where resource[\"own", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with \"", + "span": { + "start": 21, + "end": 25 + } + }, + { + "path": "text", + "message": "a bracket field needs a quoted key and ]", + "span": { + "start": 21, + "end": 25 + } + } + ] +} + +{ + "text": "spans where resource[\"own\"]:api", + "query": { + "from": "spans", + "where": [ + "resource['own'] = 'api'" + ] + } +} + +{ + "text": "spans where resource[\"owner\"\"", + "problems": [ + { + "path": "text", + "message": "unclosed quote; close the value with \"", + "span": { + "start": 21, + "end": 29 + } + }, + { + "path": "text", + "message": "a bracket field needs a quoted key and ]", + "span": { + "start": 21, + "end": 29 + } + } + ] +} + +{ + "text": "spans where servce:api", + "query": { + "from": "spans", + "where": [ + "attributes['servce'] = 'api'" + ] + } +} + +{ + "text": "spans where service", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('service'))" + ] + } +} + +{ + "text": "spans where service == \"api\"", + "problems": [ + { + "path": "text", + "message": "== is not FanQL; use key:value or =", + "span": { + "start": 20, + "end": 22 + } + } + ] +} + +{ + "text": "spans where service in $svcs", + "query": { + "from": "spans", + "where": [ + "service IN $svcs" + ] + } +} + +{ + "text": "spans where service in (*)", + "problems": [ + { + "path": "text", + "message": "* wildcards are not in FanQL 1", + "hint": "use ~ for contains, or quote \"*\"", + "span": { + "start": 24, + "end": 25 + } + } + ] +} + +{ + "text": "spans where service in (a, b)", + "query": { + "from": "spans", + "where": [ + "service IN ('a', 'b')" + ] + } +} + +{ + "text": "spans where service not in (a, b)", + "query": { + "from": "spans", + "where": [ + "service NOT IN ('a', 'b')" + ] + } +} + +{ + "text": "spans where service-", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('service-'))" + ] + } +} + +{ + "text": "spans where service:", + "problems": [ + { + "path": "text", + "message": "service: needs a value; e.g. service:api", + "span": { + "start": 12, + "end": 20 + } + } + ] +} + +{ + "text": "spans where service:$ser", + "query": { + "from": "spans", + "where": [ + "service = $ser" + ] + } +} + +{ + "text": "spans where service:$service (status:error or status:unset)", + "query": { + "from": "spans", + "where": [ + "service = $service", + "(status = 'STATUS_CODE_ERROR' OR status = 'STATUS_CODE_UNSET')" + ] + } +} + +{ + "text": "spans where service:$service (status:error or status:unset) | count() by http_route", + "query": { + "from": "spans", + "where": [ + "service = $service", + "(status = 'STATUS_CODE_ERROR' OR status = 'STATUS_CODE_UNSET')" + ], + "measures": [ + "count()" + ], + "by": [ + "http_route" + ] + } +} + +{ + "text": "spans where service:$service status:error", + "query": { + "from": "spans", + "where": [ + "service = $service", + "status = 'STATUS_CODE_ERROR'" + ] + } +} + +{ + "text": "spans where service:$x", + "query": { + "from": "spans", + "where": [ + "service = $x" + ] + } +} + +{ + "text": "spans where service:API | count() every 1m", + "query": { + "from": "spans", + "where": [ + "service = 'API'" + ], + "measures": [ + "count()" + ], + "bucket": "1m" + } +} + +{ + "text": "spans where service:api ", + "query": { + "from": "spans", + "where": [ + "service = 'api'" + ] + } +} + +{ + "text": "spans where service:api order by duration", + "problems": [ + { + "path": "text", + "message": "order is not FanQL; use by after measures, e.g. | count() by service", + "span": { + "start": 24, + "end": 29 + } + } + ] +} + +{ + "text": "spans where service:api*", + "problems": [ + { + "path": "text", + "message": "* wildcards are not in FanQL 1", + "hint": "use ~ for contains, or quote \"api*\"", + "span": { + "start": 20, + "end": 24 + } + } + ] +} + +{ + "text": "spans where service:checkout duration>500ms sort duration limit 50", + "query": { + "from": "spans", + "where": [ + "service = 'checkout'", + "duration_ms > 500" + ], + "sort": "duration_ms", + "limit": 50 + } +} + +{ + "text": "spans where service:checkout http.", + "query": { + "from": "spans", + "where": [ + "service = 'checkout'", + "contains(lower(operation), lower('http.'))" + ] + } +} + +{ + "text": "spans where service:checkout status:error -http.target:/healthz | count() by http_route", + "query": { + "from": "spans", + "where": [ + "service = 'checkout'", + "status = 'STATUS_CODE_ERROR'", + "(attributes['http.target'] IS NULL OR attributes['http.target'] != '/healthz')" + ], + "measures": [ + "count()" + ], + "by": [ + "http_route" + ] + } +} + +{ + "text": "spans where since", + "problems": [ + { + "path": "text", + "message": "the time range is not part of FanQL 1; use the time picker (since is reserved)", + "span": { + "start": 12, + "end": 17 + } + } + ] +} + +{ + "text": "spans where start_time ", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('start_time'))" + ] + } +} + +{ + "text": "spans where start_time>\"2026-10-29 10:00:00\"", + "query": { + "from": "spans", + "where": [ + "start_time > '2026-10-29 10:00:00'::TIMESTAMPTZ_NS" + ] + } +} + +{ + "text": "spans where start_time>\"2026-10-29T10:00:00Z\"", + "query": { + "from": "spans", + "where": [ + "start_time > '2026-10-29T10:00:00Z'::TIMESTAMPTZ_NS" + ] + } +} + +{ + "text": "spans where start_time>\"yesterday\"", + "problems": [ + { + "path": "where[0]", + "message": "time needs a quoted timestamp in RFC 3339 or YYYY-MM-DD HH:MM:SS form (optional fraction and offset)", + "span": { + "start": 23, + "end": 34 + } + } + ] +} + +{ + "text": "spans where starts_with(http_route, \"/api\")", + "query": { + "from": "spans", + "where": [ + "starts_with(http_route, '/api')" + ] + } +} + +{ + "text": "spans where starts_with(http_route, \"/api\") > 1", + "problems": [ + { + "path": "where[0]", + "message": "predicates are not compared; use starts_with(...) alone", + "span": { + "start": 12, + "end": 47 + } + } + ] +} + +{ + "text": "spans where starts_with(http_route, /api)", + "problems": [ + { + "path": "where[0]", + "message": "starts_with needs a quoted string", + "span": { + "start": 12, + "end": 41 + } + } + ] +} + +{ + "text": "spans where stats", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('stats'))" + ] + } +} + +{ + "text": "spans where status in (error, ok)", + "query": { + "from": "spans", + "where": [ + "status IN ('STATUS_CODE_ERROR', 'STATUS_CODE_OK')" + ] + } +} + +{ + "text": "spans where status ~ STATUS_CODE_ERROR", + "query": { + "from": "spans", + "where": [ + "contains(lower(status), lower('STATUS_CODE_ERROR'))" + ] + } +} + +{ + "text": "spans where status:\"STATUS_CODE_ERROR\"", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_ERROR'" + ] + } +} + +{ + "text": "spans where status:\"error\"", + "query": { + "from": "spans", + "where": [ + "status = 'error'" + ] + } +} + +{ + "text": "spans where status:500", + "query": { + "from": "spans", + "where": [ + "status = '500'" + ] + } +} + +{ + "text": "spans where status:STATUS_CODE_ERROR", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_ERROR'" + ] + } +} + +{ + "text": "spans where status:STATUS_CODE_OK", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_OK'" + ] + } +} + +{ + "text": "spans where status:STATUS_CODE_UNSET", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_UNSET'" + ] + } +} + +{ + "text": "spans where status:error", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_ERROR'" + ] + } +} + +{ + "text": "spans where status:error | count() by service", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_ERROR'" + ], + "measures": [ + "count()" + ], + "by": [ + "service" + ] + } +} + +{ + "text": "spans where status:error | count() by service", + "viz": "table", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_ERROR'" + ], + "measures": [ + "count()" + ], + "by": [ + "service" + ] + } +} + +{ + "text": "spans where status:fail", + "problems": [ + { + "path": "where[0]", + "message": "unknown status \"fail\"; use status:error, status:ok or status:unset", + "span": { + "start": 19, + "end": 23 + } + } + ] +} + +{ + "text": "spans where status:ok", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_OK'" + ] + } +} + +{ + "text": "spans where status:unset", + "query": { + "from": "spans", + "where": [ + "status = 'STATUS_CODE_UNSET'" + ] + } +} + +{ + "text": "spans where status>STATUS_CODE_ERROR", + "query": { + "from": "spans", + "where": [ + "status > 'STATUS_CODE_ERROR'" + ] + } +} + +{ + "text": "spans where tar", + "query": { + "from": "spans", + "where": [ + "contains(lower(operation), lower('tar'))" + ] + } +} + +{ + "text": "spans where top", + "problems": [ + { + "path": "text", + "message": "\"top\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 15 + } + } + ] +} + +{ + "text": "spans where until", + "problems": [ + { + "path": "text", + "message": "the time range is not part of FanQL 1; use the time picker (until is reserved)", + "span": { + "start": 12, + "end": 17 + } + } + ] +} + +{ + "text": "spans where user.id:* | count_distinct(user.id) by service", + "query": { + "from": "spans", + "where": [ + "attributes['user.id'] IS NOT NULL" + ], + "measures": [ + "count_distinct(attributes['user.id'])" + ], + "by": [ + "service" + ] + } +} + +{ + "text": "spans where value>-3", + "query": { + "from": "spans", + "where": [ + "attributes['value'] > -3" + ] + } +} + +{ + "text": "spans where window", + "problems": [ + { + "path": "text", + "message": "\"window\" is reserved for a future FanQL feature", + "hint": "quote it to search for the word", + "span": { + "start": 12, + "end": 18 + } + } + ] +} + +{ + "text": "spans where x-y.z:1", + "problems": [ + { + "path": "where[0]", + "message": "\"x-y.z\" needs brackets", + "span": { + "start": 12, + "end": 17 + } + } + ] +} + +{ + "text": "spans where {service=\"api\"}", + "problems": [ + { + "path": "text", + "message": "{ selectors are not FanQL; write labels as key:value, e.g. service:api", + "span": { + "start": 12, + "end": 13 + } + } + ] +} + +{ + "text": "spans where {service=api}", + "problems": [ + { + "path": "text", + "message": "{ selectors are not FanQL; write labels as key:value, e.g. service:api", + "span": { + "start": 12, + "end": 13 + } + } + ] +} + +{ + "text": "spans | ", + "problems": [ + { + "path": "text", + "message": "a measure needs a call, number or parenthesised expression", + "span": { + "start": 8, + "end": 8 + } + } + ] +} + +{ + "text": "spans | (count_if(duration<=500ms) + count_if(duration>500ms duration<=2s) / 2) / count() as apdex", + "query": { + "from": "spans", + "measures": [ + "(count_if(duration_ms <= 500) + count_if(duration_ms > 500 AND duration_ms <= 2000) / 2) / count() as apdex" + ] + } +} + +{ + "text": "spans | P95(Duration)", + "query": { + "from": "spans", + "measures": [ + "p95(duration_ms)" + ] + } +} + +{ + "text": "spans | avg(*)", + "problems": [ + { + "path": "text", + "message": "* is only allowed as the sole argument of count(*)", + "span": { + "start": 12, + "end": 13 + } + } + ] +} + +{ + "text": "spans | avg(attributes.http.response_size) as sz", + "query": { + "from": "spans", + "measures": [ + "avg(attributes['http.response_size']) as sz" + ] + } +} + +{ + "text": "spans | avg(duration), avg(user.score) sort ", + "problems": [ + { + "path": "text", + "message": "sort needs a key, e.g. sort duration", + "span": { + "start": 44, + "end": 44 + } + } + ] +} + +{ + "text": "spans | avg(http.response_size) as sz", + "query": { + "from": "spans", + "measures": [ + "avg(attributes['http.response_size']) as sz" + ] + } +} + +{ + "text": "spans | avg(user.)", + "problems": [ + { + "path": "text", + "message": "unclosed call; add )", + "span": { + "start": 11, + "end": 12 + } + }, + { + "path": "text", + "message": "separate measures with a comma", + "span": { + "start": 16, + "end": 17 + } + }, + { + "path": "text", + "message": "unexpected . after user; write the full key, e.g. user.id", + "span": { + "start": 16, + "end": 17 + } + } + ] +} + +{ + "text": "spans | bin(duration)", + "problems": [ + { + "path": "text", + "message": "bin(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 11 + } + } + ] +} + +{ + "text": "spans | cardinality(duration)", + "problems": [ + { + "path": "text", + "message": "cardinality(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 19 + } + } + ] +} + +{ + "text": "spans | count(", + "problems": [ + { + "path": "text", + "message": "unclosed call; add )", + "span": { + "start": 13, + "end": 14 + } + } + ] +} + +{ + "text": "spans | count()", + "query": { + "from": "spans", + "measures": [ + "count()" + ] + } +} + +{ + "text": "spans | count() ", + "query": { + "from": "spans", + "measures": [ + "count()" + ] + } +} + +{ + "text": "spans | count() * -1 as neg", + "query": { + "from": "spans", + "measures": [ + "count() * -1 as neg" + ] + } +} + +{ + "text": "spans | count() * 0 as zero", + "query": { + "from": "spans", + "measures": [ + "count() * 0 as zero" + ] + } +} + +{ + "text": "spans | count() * 1e3 as k", + "query": { + "from": "spans", + "measures": [ + "count() * 1000 as k" + ] + } +} + +{ + "text": "spans | count() +", + "problems": [ + { + "path": "text", + "message": "+ needs a measure or number on both sides", + "span": { + "start": 16, + "end": 17 + } + } + ] +} + +{ + "text": "spans | count() + histogram(duration) as x", + "problems": [ + { + "path": "text", + "message": "distribution counts require count(); histogram(...) stands alone", + "span": { + "start": 8, + "end": 37 + } + } + ] +} + +{ + "text": "spans | count() / 2", + "problems": [ + { + "path": "text", + "message": "name this expression with as, e.g. count() / 2 as half", + "span": { + "start": 8, + "end": 19 + } + } + ] +} + +{ + "text": "spans | count() as ", + "problems": [ + { + "path": "text", + "message": "as needs a measure alias", + "span": { + "start": 19, + "end": 19 + } + } + ] +} + +{ + "text": "spans | count() as P95", + "problems": [ + { + "path": "measures[0]", + "message": "alias \"P95\" must be lowercase letters, digits and underscores", + "span": { + "start": 8, + "end": 22 + } + } + ] +} + +{ + "text": "spans | count() as duration sort duration", + "query": { + "from": "spans", + "measures": [ + "count() as duration" + ], + "sort": "duration" + } +} + +{ + "text": "spans | count() by a, b, c, d", + "problems": [ + { + "path": "text", + "message": "at most 3 grouping fields", + "span": { + "start": 28, + "end": 29 + } + } + ] +} + +{ + "text": "spans | count() by attributes['user name']", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "attributes['user name']" + ] + } +} + +{ + "text": "spans | count() by attributes['user''s name']", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "attributes['user''s name']" + ] + } +} + +{ + "text": "spans | count() by resource['𝔘 [name]']", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "resource['𝔘 [name]']" + ] + } +} + +{ + "text": "spans | count() by service every 1m", + "viz": "timeseries", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "service" + ], + "bucket": "1m" + } +} + +{ + "text": "spans | count() by service every auto sort count limit 10", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "service" + ], + "bucket": "auto", + "sort": "count", + "limit": 10 + } +} + +{ + "text": "spans | count() by service sort ", + "problems": [ + { + "path": "text", + "message": "sort needs a key, e.g. sort duration", + "span": { + "start": 32, + "end": 32 + } + } + ] +} + +{ + "text": "spans | count() by service sort -count", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "service" + ], + "sort": "count" + } +} + +{ + "text": "spans | count() by service sort count", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "service" + ], + "sort": "count" + } +} + +{ + "text": "spans | count() by service sort count limit 10", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "service" + ], + "sort": "count", + "limit": 10 + } +} + +{ + "text": "spans | count() by service sort p95", + "problems": [ + { + "path": "sort", + "message": "sort \"p95\" must name a measure alias; aliases here: count", + "span": { + "start": 27, + "end": 35 + } + } + ] +} + +{ + "text": "spans | count() by service | sort count | limit 10", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "service" + ], + "sort": "count", + "limit": 10 + } +} + +{ + "text": "spans | count() by service | top 3 by count", + "problems": [ + { + "path": "text", + "message": "FanQL 1 runs one aggregation stage", + "hint": "remove the second |; more stages come in a later version", + "span": { + "start": 27, + "end": 28 + } + } + ] +} + +{ + "text": "spans | count() by service, ", + "problems": [ + { + "path": "text", + "message": "a field needs a name, e.g. service or attributes['key']", + "span": { + "start": 28, + "end": 28 + } + } + ] +} + +{ + "text": "spans | count() every ", + "problems": [ + { + "path": "text", + "message": "unknown bucket \"\"; use auto or one of 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h, 1d", + "span": { + "start": 22, + "end": 22 + } + } + ] +} + +{ + "text": "spans | count() every 1m sort count", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "bucket": "1m", + "sort": "count" + } +} + +{ + "text": "spans | count() every 2m", + "problems": [ + { + "path": "text", + "message": "unknown bucket \"2m\"; use auto or one of 10s, 30s, 1m, 5m, 10m, 15m, 30m, 1h, 3h, 6h, 12h, 1d", + "span": { + "start": 22, + "end": 24 + } + } + ] +} + +{ + "text": "spans | count() limit ", + "problems": [ + { + "path": "text", + "message": "limit needs a whole number from 1 to 1000; e.g. limit 50", + "span": { + "start": 22, + "end": 22 + } + } + ] +} + +{ + "text": "spans | count() limit 0", + "problems": [ + { + "path": "text", + "message": "limit needs a whole number from 1 to 1000; e.g. limit 50", + "span": { + "start": 22, + "end": 23 + } + } + ] +} + +{ + "text": "spans | count() rate()", + "problems": [ + { + "path": "text", + "message": "separate measures with a comma", + "span": { + "start": 16, + "end": 20 + } + } + ] +} + +{ + "text": "spans | count()*100 as c100", + "query": { + "from": "spans", + "measures": [ + "count() * 100 as c100" + ] + } +} + +{ + "text": "spans | count(), count()", + "problems": [ + { + "path": "measures[1]", + "message": "two measures are named count; add distinct aliases with as", + "span": { + "start": 17, + "end": 24 + } + } + ] +} + +{ + "text": "spans | count()/count() as one", + "query": { + "from": "spans", + "measures": [ + "count() / count() as one" + ] + } +} + +{ + "text": "spans | count(*)", + "query": { + "from": "spans", + "measures": [ + "count()" + ] + } +} + +{ + "text": "spans | count_distinct(", + "problems": [ + { + "path": "text", + "message": "unclosed call; add )", + "span": { + "start": 22, + "end": 23 + } + } + ] +} + +{ + "text": "spans | count_distinct(attributes['flag'])", + "query": { + "from": "spans", + "measures": [ + "count_distinct(attributes['flag'])" + ] + } +} + +{ + "text": "spans | count_distinct(attributes['user.id'])", + "query": { + "from": "spans", + "measures": [ + "count_distinct(attributes['user.id'])" + ] + } +} + +{ + "text": "spans | count_distinct(flag)", + "query": { + "from": "spans", + "measures": [ + "count_distinct(attributes['flag'])" + ] + } +} + +{ + "text": "spans | count_distinct(user.id)", + "query": { + "from": "spans", + "measures": [ + "count_distinct(attributes['user.id'])" + ] + } +} + +{ + "text": "spans | count_distinct(user.id) + avg(attributes.http.response_size) - p95(resource.k) * 1e3 as spread", + "query": { + "from": "spans", + "measures": [ + "count_distinct(attributes['user.id']) + avg(attributes['http.response_size']) - p95(resource['k']) * 1000 as spread" + ] + } +} + +{ + "text": "spans | count_distinct(user.id) by service", + "query": { + "from": "spans", + "measures": [ + "count_distinct(attributes['user.id'])" + ], + "by": [ + "service" + ] + } +} + +{ + "text": "spans | count_distinct(user.id), p95(resource.k)", + "query": { + "from": "spans", + "measures": [ + "count_distinct(attributes['user.id'])", + "p95(resource['k'])" + ] + } +} + +{ + "text": "spans | count_distinct(x-y)", + "problems": [ + { + "path": "text", + "message": "unclosed call; add )", + "span": { + "start": 22, + "end": 23 + } + }, + { + "path": "text", + "message": "a measure needs a call, number or parenthesised expression", + "span": { + "start": 25, + "end": 26 + } + }, + { + "path": "text", + "message": "separate measures with a comma", + "span": { + "start": 26, + "end": 27 + } + }, + { + "path": "text", + "message": "a measure needs a call, number or parenthesised expression", + "span": { + "start": 26, + "end": 27 + } + } + ] +} + +{ + "text": "spans | count_if(a:1 b:2 or c:3) as x", + "problems": [ + { + "path": "text", + "message": "mixed and/or needs parentheses", + "hint": "write a:1 (b:2 or c:3) or (a:1 b:2) or c:3", + "span": { + "start": 17, + "end": 31 + }, + "fix_its": [ + { + "label": "a:1 (b:2 or c:3)", + "span": { + "start": 17, + "end": 31 + }, + "text": "a:1 (b:2 or c:3)" + }, + { + "label": "(a:1 b:2) or c:3", + "span": { + "start": 17, + "end": 31 + }, + "text": "(a:1 b:2) or c:3" + } + ] + } + ] +} + +{ + "text": "spans | count_if(a:1 or b:2) / count() as r", + "query": { + "from": "spans", + "measures": [ + "count_if((attributes['a'] = 1 OR attributes['b'] = 2)) / count() as r" + ] + } +} + +{ + "text": "spans | count_if(body:\"a)b\" `x = ')'`) / count() as r", + "query": { + "from": "spans", + "measures": [ + "count_if(attributes['body'] = 'a)b' AND (x = ')')) / count() as r" + ] + }, + "gate_problems": true +} + +{ + "text": "spans | count_if(http_status_code between 400 and 499) as client_errors, count_if(http_status_code>=500) as server_errors", + "query": { + "from": "spans", + "measures": [ + "count_if(TRY_CAST(http_status_code AS INTEGER) BETWEEN 400 AND 499) as client_errors", + "count_if(TRY_CAST(http_status_code AS INTEGER) >= 500) as server_errors" + ] + } +} + +{ + "text": "spans | count_if(length(operation)>$x)", + "problems": [ + { + "path": "measures[0]", + "message": "variables are not allowed inside count_if", + "span": { + "start": 35, + "end": 37 + } + } + ] +} + +{ + "text": "spans | count_if(service:$s) as n", + "problems": [ + { + "path": "measures[0]", + "message": "variables are not allowed inside count_if", + "span": { + "start": 25, + "end": 27 + } + } + ] +} + +{ + "text": "spans | count_if(status:error -http.target:/healthz) as errs", + "query": { + "from": "spans", + "measures": [ + "count_if(status = 'STATUS_CODE_ERROR' AND (attributes['http.target'] IS NULL OR attributes['http.target'] != '/healthz')) as errs" + ] + } +} + +{ + "text": "spans | count_if(status:error)", + "query": { + "from": "spans", + "measures": [ + "count_if(status = 'STATUS_CODE_ERROR')" + ] + } +} + +{ + "text": "spans | count_if(status:error) / count() * 100 as err_pct by http_route every 1m sort err_pct limit 10", + "query": { + "from": "spans", + "measures": [ + "count_if(status = 'STATUS_CODE_ERROR') / count() * 100 as err_pct" + ], + "by": [ + "http_route" + ], + "bucket": "1m", + "sort": "err_pct", + "limit": 10 + } +} + +{ + "text": "spans | count_if(status:error) / count() as r by http_route", + "query": { + "from": "spans", + "measures": [ + "count_if(status = 'STATUS_CODE_ERROR') / count() as r" + ], + "by": [ + "http_route" + ] + } +} + +{ + "text": "spans | count_if(status:error) as errors, count() as total, count_if(status:error) / count() as ratio by service", + "query": { + "from": "spans", + "measures": [ + "count_if(status = 'STATUS_CODE_ERROR') as errors", + "count() as total", + "count_if(status = 'STATUS_CODE_ERROR') / count() as ratio" + ], + "by": [ + "service" + ] + } +} + +{ + "text": "spans | count_over_time(duration)", + "problems": [ + { + "path": "text", + "message": "count_over_time(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 23 + } + } + ] +} + +{ + "text": "spans | dc(duration)", + "problems": [ + { + "path": "text", + "message": "dc(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 10 + } + } + ] +} + +{ + "text": "spans | distinct_count(duration)", + "problems": [ + { + "path": "text", + "message": "distinct_count(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 22 + } + } + ] +} + +{ + "text": "spans | eval count() by service", + "problems": [ + { + "path": "text", + "message": "\"eval\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 12 + } + } + ] +} + +{ + "text": "spans | every 1m", + "problems": [ + { + "path": "text", + "message": "every needs measures first; write | count() every 1m", + "span": { + "start": 8, + "end": 13 + } + } + ] +} + +{ + "text": "spans | extend count() by service", + "problems": [ + { + "path": "text", + "message": "\"extend\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 14 + } + } + ] +} + +{ + "text": "spans | fields count() by service", + "problems": [ + { + "path": "text", + "message": "\"fields\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 14 + } + } + ] +} + +{ + "text": "spans | head count() by service", + "problems": [ + { + "path": "text", + "message": "\"head\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 12 + } + } + ] +} + +{ + "text": "spans | histogram(duration)", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "histogram": { + "field": "duration_ms", + "buckets": "log2" + } + } +} + +{ + "text": "spans | histogram(duration) + count() as x", + "problems": [ + { + "path": "text", + "message": "distribution counts require count(); histogram(...) stands alone", + "span": { + "start": 8, + "end": 37 + } + } + ] +} + +{ + "text": "spans | histogram(duration) as x", + "problems": [ + { + "path": "text", + "message": "histogram(...) does not take an alias", + "span": { + "start": 8, + "end": 32 + } + } + ] +} + +{ + "text": "spans | histogram(duration) by service", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "service" + ], + "histogram": { + "field": "duration_ms", + "buckets": "log2" + } + } +} + +{ + "text": "spans | histogram(duration) by service", + "viz": "histogram", + "query": { + "from": "spans", + "measures": [ + "count()" + ], + "by": [ + "service" + ], + "histogram": { + "field": "duration_ms", + "buckets": "log2" + } + } +} + +{ + "text": "spans | histogram(duration), count()", + "problems": [ + { + "path": "text", + "message": "distribution counts require count(); histogram(...) stands alone", + "span": { + "start": 29, + "end": 36 + } + } + ] +} + +{ + "text": "spans | histogram(duration), histogram(value)", + "problems": [ + { + "path": "text", + "message": "distribution counts require count(); histogram(...) stands alone", + "span": { + "start": 29, + "end": 45 + } + } + ] +} + +{ + "text": "spans | last(value)", + "problems": [ + { + "path": "measures[0]", + "message": "last is not available for spans", + "span": { + "start": 8, + "end": 19 + } + } + ] +} + +{ + "text": "spans | mean(duration)", + "problems": [ + { + "path": "text", + "message": "mean(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 12 + } + } + ] +} + +{ + "text": "spans | median(duration)", + "problems": [ + { + "path": "text", + "message": "median(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 14 + } + } + ] +} + +{ + "text": "spans | order count() by service", + "problems": [ + { + "path": "text", + "message": "\"order\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 13 + } + } + ] +} + +{ + "text": "spans | p9", + "problems": [ + { + "path": "text", + "message": "a measure needs a call, number or parenthesised expression", + "span": { + "start": 8, + "end": 10 + } + } + ] +} + +{ + "text": "spans | p95()", + "problems": [ + { + "path": "measures[0]", + "message": "p95 takes 1 argument(s), got 0; e.g. p95(duration)", + "span": { + "start": 8, + "end": 13 + } + } + ] +} + +{ + "text": "spans | p95(duration)", + "query": { + "from": "spans", + "measures": [ + "p95(duration_ms)" + ] + } +} + +{ + "text": "spans | p95(duration) by operation sort p95 limit 10", + "query": { + "from": "spans", + "measures": [ + "p95(duration_ms)" + ], + "by": [ + "operation" + ], + "sort": "p95", + "limit": 10 + } +} + +{ + "text": "spans | p95(duration)-p50(duration) as spread", + "query": { + "from": "spans", + "measures": [ + "p95(duration_ms) - p50(duration_ms) as spread" + ] + } +} + +{ + "text": "spans | p95(resource.k) as x", + "query": { + "from": "spans", + "measures": [ + "p95(resource['k']) as x" + ] + } +} + +{ + "text": "spans | p95(service)", + "problems": [ + { + "path": "measures[0]", + "message": "p95 needs a numeric field; service is string", + "span": { + "start": 12, + "end": 19 + } + } + ] +} + +{ + "text": "spans | p99(duration) by http_route every 1m", + "query": { + "from": "spans", + "measures": [ + "p99(duration_ms)" + ], + "by": [ + "http_route" + ], + "bucket": "1m" + } +} + +{ + "text": "spans | pct(duration)", + "problems": [ + { + "path": "text", + "message": "pct(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 11 + } + } + ] +} + +{ + "text": "spans | perc95(duration)", + "problems": [ + { + "path": "text", + "message": "perc95(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 14 + } + } + ] +} + +{ + "text": "spans | percentile(duration)", + "problems": [ + { + "path": "text", + "message": "percentile(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 18 + } + } + ] +} + +{ + "text": "spans | project count() by service", + "problems": [ + { + "path": "text", + "message": "\"project\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 15 + } + } + ] +} + +{ + "text": "spans | quantile(duration, ", + "problems": [ + { + "path": "text", + "message": "unclosed call; add )", + "span": { + "start": 16, + "end": 17 + } + } + ] +} + +{ + "text": "spans | quantile(duration, 0.999) as q", + "query": { + "from": "spans", + "measures": [ + "quantile(duration_ms, 0.999) as q" + ] + } +} + +{ + "text": "spans | quantile(duration, 2)", + "problems": [ + { + "path": "measures[0]", + "message": "quantile q must be a number between 0 and 1", + "span": { + "start": 8, + "end": 29 + } + } + ] +} + +{ + "text": "spans | quantile_over_time(duration)", + "problems": [ + { + "path": "text", + "message": "quantile_over_time(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 26 + } + } + ] +} + +{ + "text": "spans | rate(", + "problems": [ + { + "path": "text", + "message": "unclosed call; add )", + "span": { + "start": 12, + "end": 13 + } + } + ] +} + +{ + "text": "spans | rename count() by service", + "problems": [ + { + "path": "text", + "message": "\"rename\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 14 + } + } + ] +} + +{ + "text": "spans | select count() by service", + "problems": [ + { + "path": "text", + "message": "\"select\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 14 + } + } + ] +} + +{ + "text": "spans | share() ", + "query": { + "from": "spans", + "measures": [ + "share()" + ] + } +} + +{ + "text": "spans | share() / 2 as half", + "problems": [ + { + "path": "text", + "message": "share() cannot be combined; it is already a percentage of the scope", + "hint": "use share() alone, or count_if(...) / count() * 100 for a custom ratio", + "span": { + "start": 8, + "end": 19 + } + } + ] +} + +{ + "text": "spans | sort by service", + "problems": [ + { + "path": "text", + "message": "\"sort\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 12 + } + } + ] +} + +{ + "text": "spans | sort count() by service", + "problems": [ + { + "path": "text", + "message": "unexpected (", + "span": { + "start": 18, + "end": 19 + } + }, + { + "path": "text", + "message": "unmatched ); remove it or add the opening (", + "span": { + "start": 19, + "end": 20 + } + }, + { + "path": "text", + "message": "by needs measures first; write | count() by service", + "span": { + "start": 21, + "end": 23 + } + } + ] +} + +{ + "text": "spans | span(duration)", + "problems": [ + { + "path": "text", + "message": "span(...) is not FanQL; use the FanQL measure functions", + "span": { + "start": 8, + "end": 12 + } + } + ] +} + +{ + "text": "spans | stats count() by service", + "problems": [ + { + "path": "text", + "message": "\"stats\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 13 + } + } + ] +} + +{ + "text": "spans | sum(", + "problems": [ + { + "path": "text", + "message": "unclosed call; add )", + "span": { + "start": 11, + "end": 12 + } + } + ] +} + +{ + "text": "spans | summarize count() by service", + "problems": [ + { + "path": "text", + "message": "\"summarize\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 17 + } + } + ] +} + +{ + "text": "spans | take count() by service", + "problems": [ + { + "path": "text", + "message": "\"take\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 12 + } + } + ] +} + +{ + "text": "spans | top count() by service", + "problems": [ + { + "path": "text", + "message": "\"top\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 8, + "end": 11 + } + } + ] +} + +{ + "text": "spans |= err", + "problems": [ + { + "path": "text", + "message": "|= is not FanQL; use body ~ \"text\" for contains", + "span": { + "start": 6, + "end": 8 + } + } + ] +} + +{ + "text": "spans |~ err", + "problems": [ + { + "path": "text", + "message": "|~ is not FanQL; use body ~ \"text\" for contains", + "span": { + "start": 6, + "end": 8 + } + } + ] +} + +{ + "text": "traces where a:1", + "problems": [ + { + "path": "text", + "message": "unknown source \"traces\"", + "hint": "use spans; traces is a viz of spans", + "span": { + "start": 0, + "end": 6 + } + } + ] +} + +{ + "text": "traces | stats x take 5", + "problems": [ + { + "path": "text", + "message": "unknown source \"traces\"", + "hint": "use spans; traces is a viz of spans", + "span": { + "start": 0, + "end": 6 + } + }, + { + "path": "text", + "message": "\"stats\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 9, + "end": 14 + } + }, + { + "path": "text", + "message": "\"take\" is not FanQL; write the measures after |, e.g. | count() by service", + "span": { + "start": 17, + "end": 21 + } + } + ] +} diff --git a/internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/literal_backtick b/internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/literal_backtick new file mode 100644 index 00000000..506a7a3f --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/literal_backtick @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"query\":{\"from\":\"logs\",\"where\":[\"coalesce(body, '`') = ''\"],\"measures\":[\"count( )\"]}}") diff --git a/internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/literal_group_key b/internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/literal_group_key new file mode 100644 index 00000000..e82f51fc --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/literal_group_key @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"query\":{\"from\":\"spans\",\"measures\":[\"count()\"],\"by\":[\"attributes['user name']\"]},\"viz\":\"table\"}") diff --git a/internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/raw_negation b/internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/raw_negation new file mode 100644 index 00000000..2228a088 --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzFormatRoundTrip/raw_negation @@ -0,0 +1,2 @@ +go test fuzz v1 +[]byte("{\"query\":{\"from\":\"spans\",\"where\":[\"NOT (attributes['k'] = 'v')\"],\"measures\":[\"count()\"]}}") diff --git a/internal/fanql/testdata/fuzz/FuzzLexParsePrint/72518d1cde34436d b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/72518d1cde34436d new file mode 100644 index 00000000..6d1334fe --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/72518d1cde34436d @@ -0,0 +1,2 @@ +go test fuzz v1 +string("\"\"A: 0:0") diff --git a/internal/fanql/testdata/fuzz/FuzzLexParsePrint/ac80e7dae538a502 b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/ac80e7dae538a502 new file mode 100644 index 00000000..14cb0cdc --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/ac80e7dae538a502 @@ -0,0 +1,2 @@ +go test fuzz v1 +string("logs 0 And in") diff --git a/internal/fanql/testdata/fuzz/FuzzLexParsePrint/aca3db284bc204d2 b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/aca3db284bc204d2 new file mode 100644 index 00000000..d7e45b60 --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/aca3db284bc204d2 @@ -0,0 +1,2 @@ +go test fuzz v1 +string("spAns 0 -(0 0)") diff --git a/internal/fanql/testdata/fuzz/FuzzLexParsePrint/astral_diagnostic b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/astral_diagnostic new file mode 100644 index 00000000..324946c4 --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/astral_diagnostic @@ -0,0 +1,2 @@ +go test fuzz v1 +string("logs where body:\"𝔘𝔫𝔦\" x:1 +") diff --git a/internal/fanql/testdata/fuzz/FuzzLexParsePrint/b4c83d8eaed5ec0b b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/b4c83d8eaed5ec0b new file mode 100644 index 00000000..dfb16306 --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/b4c83d8eaed5ec0b @@ -0,0 +1,2 @@ +go test fuzz v1 +string("logs severity:\"aA\"") diff --git a/internal/fanql/testdata/fuzz/FuzzLexParsePrint/embedded_variable_character b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/embedded_variable_character new file mode 100644 index 00000000..7e4acced --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/embedded_variable_character @@ -0,0 +1,2 @@ +go test fuzz v1 +string("logs where \"api$svc\"") diff --git a/internal/fanql/testdata/fuzz/FuzzLexParsePrint/quoted_wildcard b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/quoted_wildcard new file mode 100644 index 00000000..a438fb48 --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/quoted_wildcard @@ -0,0 +1,2 @@ +go test fuzz v1 +string("logs where \"api*\"") diff --git a/internal/fanql/testdata/fuzz/FuzzLexParsePrint/raw_boolean_fragment b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/raw_boolean_fragment new file mode 100644 index 00000000..ef39ab76 --- /dev/null +++ b/internal/fanql/testdata/fuzz/FuzzLexParsePrint/raw_boolean_fragment @@ -0,0 +1,2 @@ +go test fuzz v1 +string("logs where (`body = 'a' OR body = 'b'` service:api)") diff --git a/internal/fanql/testhelpers_test.go b/internal/fanql/testhelpers_test.go index eff2183f..a24175ac 100644 --- a/internal/fanql/testhelpers_test.go +++ b/internal/fanql/testhelpers_test.go @@ -9,7 +9,7 @@ import ( telemetrystore "github.com/labstack/fanout/internal/telemetry/store" ) -func newTestEngine(t *testing.T) (*query.Duck, *telemetrystore.Repository) { +func newTestEngine(t testing.TB) (*query.Duck, *telemetrystore.Repository) { t.Helper() cfg := config.Config{DataDir: t.TempDir(), DuckDBMemory: "256MB", DuckDBThreads: 2, DuckDBMaxConns: 4, RollupInterval: time.Hour} repo, err := telemetrystore.Open(cfg.TelemetryDir()) diff --git a/internal/panel/filter.go b/internal/panel/filter.go index 2275fa60..79d25c70 100644 --- a/internal/panel/filter.go +++ b/internal/panel/filter.go @@ -341,7 +341,7 @@ func fieldText(n any) string { key, _ := children[1].(map[string]any) text := constantText(key) if len(names) == 1 { - return fmt.Sprintf("%s['%s']", names[0], text) + return fmt.Sprintf("%s[%s]", names[0], sqlString(text)) } } } From 6c4131bb44c3b1296a8e6e6e2f90b84851c1b8e9 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 21:00:54 -0700 Subject: [PATCH 15/30] fix(fanql): bound completion fetches and harden quoting, numbers and comments --- internal/fanql/complete.go | 27 +++++---------- internal/fanql/complete_test.go | 45 +++++++++++++++++++++++++ internal/fanql/fuzz_test.go | 51 ++++++++++++++++++++++++++++- internal/fanql/lift.go | 5 ++- internal/fanql/lift_test.go | 33 +++++++++++++++++++ internal/fanql/lower.go | 15 +++++++-- internal/fanql/lower_test.go | 40 ++++++++++++++++++++++ internal/fanql/print.go | 8 ++--- internal/fanql/print_test.go | 23 +++++++++++++ internal/panel/measure.go | 29 ++++++++++++++-- internal/panel/measure_expr_test.go | 25 ++++++++++++++ scripts/go-deadcode.allowlist | 1 - 12 files changed, 273 insertions(+), 29 deletions(-) diff --git a/internal/fanql/complete.go b/internal/fanql/complete.go index 9a4b3597..d73af6b1 100644 --- a/internal/fanql/complete.go +++ b/internal/fanql/complete.go @@ -22,13 +22,6 @@ type Expect struct { Scope string } -// expectAt replaces a whole lexical token even when the cursor is in its middle. -// Punctuation is consumed by the grammar: a cursor after ':' expects a value. -func expectAt(text string, cursor int) (Token, []Expect) { - token, p := completionPrefix(text, cursor, "") - return token, p.expected -} - func completionPrefix(text string, cursor int, source string) (token Token, p *parser) { runes := []rune(text) cursor = max(0, min(cursor, len(runes))) @@ -107,8 +100,8 @@ type completionSchemaEntry struct { failed bool } -// Schema work is limited across all Completers, including requests queued after -// their HTTP contexts have gone away. No request waits for this semaphore. +// Schema work is admitted before spawning across all Completers. No request +// waits or queues work when the slots are full; a later completion can retry. var completionSchemaSlots = make(chan struct{}, 4) type Completer struct { @@ -159,6 +152,11 @@ func (c *Completer) schema(ctx context.Context, key completionKey) (*panel.Schem return nil, false, false } if _, ok := c.inflight[key]; !ok { + select { + case completionSchemaSlots <- struct{}{}: + default: + return nil, false, false + } done := make(chan struct{}) c.inflight[key] = done go c.fetch(context.WithoutCancel(ctx), key, done) @@ -167,17 +165,10 @@ func (c *Completer) schema(ctx context.Context, key completionKey) (*panel.Schem } func (c *Completer) fetch(parent context.Context, key completionKey, done chan struct{}) { + defer func() { <-completionSchemaSlots }() ctx, cancel := context.WithTimeout(parent, 20*time.Second) defer cancel() - var schema *panel.Schema - var err error - select { - case completionSchemaSlots <- struct{}{}: - schema, err = c.source.Schema(ctx, panel.SchemaRequest{Window: key.window, Namespace: key.namespace}) - <-completionSchemaSlots - case <-ctx.Done(): - err = ctx.Err() - } + schema, err := c.source.Schema(ctx, panel.SchemaRequest{Window: key.window, Namespace: key.namespace}) c.mu.Lock() defer c.mu.Unlock() now := c.now() diff --git a/internal/fanql/complete_test.go b/internal/fanql/complete_test.go index 396577fa..c6ce71e3 100644 --- a/internal/fanql/complete_test.go +++ b/internal/fanql/complete_test.go @@ -3,6 +3,7 @@ package fanql import ( "context" "errors" + "fmt" "reflect" "slices" "strings" @@ -16,6 +17,50 @@ import ( type completionSchemaFunc func(context.Context, panel.SchemaRequest) (*panel.Schema, error) +// expectAt replaces a whole lexical token even when the cursor is in its middle. +// Punctuation is consumed by the grammar: a cursor after ':' expects a value. +func expectAt(text string, cursor int) (Token, []Expect) { + token, p := completionPrefix(text, cursor, "") + return token, p.expected +} + +func TestCompleteBoundsDistinctNamespaceFetchAdmission(t *testing.T) { + gate := make(chan struct{}) + source := completionSchemaFunc(func(context.Context, panel.SchemaRequest) (*panel.Schema, error) { + <-gate + return completionFixtureSchema(), nil + }) + completers := []*Completer{NewCompleter(source), NewCompleter(source)} + defer func() { + var pending []chan struct{} + for _, c := range completers { + c.mu.Lock() + for _, done := range c.inflight { + pending = append(pending, done) + } + c.mu.Unlock() + } + close(gate) + for _, done := range pending { + <-done + } + }() + for i := 0; i < 256; i++ { + completers[i%2].Complete(context.Background(), CompleteRequest{ + Text: "logs ", Cursor: 5, Window: "1h", Namespace: fmt.Sprintf("namespace-%d", i), + }) + pending := 0 + for _, c := range completers { + c.mu.Lock() + pending += len(c.inflight) + c.mu.Unlock() + } + if pending > 4 { + t.Fatalf("%d distinct namespaces admitted %d fetches; cap is 4", i+1, pending) + } + } +} + func (f completionSchemaFunc) Schema(ctx context.Context, req panel.SchemaRequest) (*panel.Schema, error) { return f(ctx, req) } diff --git a/internal/fanql/fuzz_test.go b/internal/fanql/fuzz_test.go index 8301b942..a293bb7f 100644 --- a/internal/fanql/fuzz_test.go +++ b/internal/fanql/fuzz_test.go @@ -76,6 +76,42 @@ func FuzzLexParsePrint(f *testing.F) { }) } +func TestStructuredGeneratorCoversConditionalMeasuresAndArithmetic(t *testing.T) { + engine, _ := newTestEngine(t) + conditional, arithmetic := false, false + for source := range 2 { + for choice := range 16 { + // Fixed bytes keep the generated filters short while varying measures. + q := generatedStructuredQuery([]byte{byte(source), byte(choice), 1, 1, 1, 1, 1, 1}) + m, err := panel.ParseMeasure(q.From, q.Measures[0]) + if err != nil { + t.Fatal(err) + } + switch x := m.Expr.(type) { + case panel.MeasureCountIf: + conditional = true + case panel.MeasureBinary: + arithmetic = true + if _, ok := x.L.(panel.MeasureCountIf); ok { + conditional = true + } + } + f, ps, err := Format(t.Context(), engine, q, FormatOptions{}) + if err != nil || len(ps) != 0 || !f.Editable { + t.Fatalf("format %#v: %+v %v", q, ps, err) + } + c, ps := Compile(f.Text, Options{}) + if len(ps) != 0 { + t.Fatal(ps) + } + assertQueryTier(t, engine, q, c.Query, f.Exactness) + } + } + if !conditional || !arithmetic { + t.Fatalf("generator coverage: conditional=%t arithmetic=%t", conditional, arithmetic) + } +} + // generatedStructuredQuery is generator B: a bounded grammar of SQL accepted // by the existing gate, independent of FanQL's own lowerer and printer. func generatedStructuredQuery(data []byte) panel.Query { @@ -86,7 +122,20 @@ func generatedStructuredQuery(data []byte) panel.Query { return data[i%len(data)] } source := []string{"spans", "logs", "metrics"}[int(byteAt(0))%3] - q := panel.Query{From: source, Measures: []string{[]string{"count()", "count( )", " count() ", "count ( )"}[int(byteAt(1))%4]}} + measures := []string{"count()", "count( )", " count() ", "count ( )"} + if source != "metrics" { + measures = append(measures, + "count_if(service = '(')", + "count_if(service = ')') as n", + "count_if(attributes['( ) , |'] = ',') as n", + "count_if(service = 'api') / count() as ratio", + "(count_if(service = 'api') + count_if(service = 'worker')) / count() as ratio", + "count() * 2 as doubled", + "count() - count() as zero", + "count() / 2 as half", + ) + } + q := panel.Query{From: source, Measures: []string{measures[int(byteAt(1))%len(measures)]}} if byteAt(2)%5 == 0 { // Every entry remains under 500 bytes; their complete text exceeds the // interactive character bound without invalidating the structured Query. diff --git a/internal/fanql/lift.go b/internal/fanql/lift.go index 36452812..371d0c85 100644 --- a/internal/fanql/lift.go +++ b/internal/fanql/lift.go @@ -783,12 +783,15 @@ func liftCountIfBodies(ctx context.Context, p panel.Parser, signal, text string) var b strings.Builder end := 0 for i := 0; i+1 < len(tokens); i++ { - if !strings.EqualFold(tokens[i].text, "count_if") || tokens[i+1].text != "(" { + if tokens[i].quote != 0 || !strings.EqualFold(tokens[i].text, "count_if") || tokens[i+1].quote != 0 || tokens[i+1].text != "(" { continue } depth := 1 j := i + 2 for ; j < len(tokens); j++ { + if tokens[j].quote != 0 { + continue + } if tokens[j].text == "(" { depth++ } diff --git a/internal/fanql/lift_test.go b/internal/fanql/lift_test.go index eddb9aac..aaf70961 100644 --- a/internal/fanql/lift_test.go +++ b/internal/fanql/lift_test.go @@ -48,6 +48,39 @@ func TestFormatOwnLoweringNeedsNoEngine(t *testing.T) { } } +func TestFormatCountIfQuotedDelimiters(t *testing.T) { + for _, text := range []string{ + `spans | count_if(service:"(")`, + `spans | count_if(service:")")`, + `spans | count_if(service:",")`, + `spans | count_if(service:"|")`, + `spans | count_if(attributes['(']:x)`, + `spans | count_if(attributes[')']:x)`, + `spans | count_if(attributes[',']:x)`, + `spans | count_if(attributes['|']:x)`, + `spans | count_if(attributes['( ) , |']:"( ) , |") / count() as ratio`, + } { + t.Run(text, func(t *testing.T) { + c, ps := Compile(text, Options{}) + if len(ps) != 0 { + t.Fatal(ps) + } + p := &countingParser{fail: true} + f, ps, err := Format(t.Context(), p, c.Query, FormatOptions{}) + if err != nil || len(ps) != 0 { + t.Fatalf("format: %v %v", ps, err) + } + if f.Exactness != "exact" || !f.Editable || f.Text != c.Canonical || p.calls != 0 { + t.Fatalf("format: %+v, calls %d; want %q", f, p.calls, c.Canonical) + } + again, ps := Compile(f.Text, Options{}) + if len(ps) != 0 || !reflect.DeepEqual(again.Query, c.Query) { + t.Fatalf("recompile: %+v %v", again, ps) + } + }) + } +} + func TestLiftStoredSQLShapes(t *testing.T) { d, _ := newTestEngine(t) for _, tt := range []struct{ signal, sql, text, tier string }{ diff --git a/internal/fanql/lower.go b/internal/fanql/lower.go index c61b5fcd..07530ca3 100644 --- a/internal/fanql/lower.go +++ b/internal/fanql/lower.go @@ -2,6 +2,7 @@ package fanql import ( "fmt" + "math/big" "strconv" "strings" @@ -78,6 +79,17 @@ func compareField(f Field) string { } func sqlString(text string) string { return "'" + strings.ReplaceAll(text, "'", "''") + "'" } func decimal(n float64) string { return strconv.FormatFloat(n, 'f', -1, 64) } +func numberText(text string) string { + // Integer spelling carries precision that a float64 cannot preserve. + if n, ok := new(big.Int).SetString(text, 10); ok { + return n.String() + } + n, err := strconv.ParseFloat(text, 64) + if err != nil { + return text + } + return decimal(n) +} func lowerValue(f Field, v Value) string { text := v.Stored if text == "" { @@ -100,8 +112,7 @@ func lowerValue(f Field, v Value) string { return sqlString(text) } if v.Kind == NumberValue { - n, _ := strconv.ParseFloat(text, 64) - return decimal(n) + return numberText(text) } if v.Kind == BooleanValue { return strings.ToLower(text) diff --git a/internal/fanql/lower_test.go b/internal/fanql/lower_test.go index f1b5adc3..16582529 100644 --- a/internal/fanql/lower_test.go +++ b/internal/fanql/lower_test.go @@ -68,6 +68,46 @@ var lowerFixtures = []struct{ text, sql string }{ {`spans where -k:$v`, `(attributes['k'] IS NULL OR attributes['k'] != $v)`}, } +func TestLowerPreservesExactIntegerLiterals(t *testing.T) { + for _, value := range []string{ + "9007199254740991", "9007199254740992", "9007199254740993", + "-9007199254740991", "-9007199254740992", "-9007199254740993", + "9223372036854775807", "-9223372036854775808", + } { + t.Run(value, func(t *testing.T) { + text := "logs where attributes['id']:" + value + c, ps := Compile(text, Options{}) + if len(ps) != 0 { + t.Fatal(ps) + } + want := panel.Query{From: "logs", Where: []string{"attributes['id'] = " + value}} + if !reflect.DeepEqual(c.Query, want) { + t.Fatalf("lowered %#v; want %#v", c.Query, want) + } + again, ps := Compile(c.Canonical, Options{}) + if len(ps) != 0 || !reflect.DeepEqual(again.Query, want) { + t.Fatalf("canonical %q lost integer: %+v %v", c.Canonical, again, ps) + } + }) + } +} + +func TestLowerCountIfRawSQLComments(t *testing.T) { + for _, body := range []string{"body = 'x' /* ) */", "body = 'x' -- )\n", "body = 'it''s )' /* ) */"} { + text := "logs | count_if(`" + body + "`) as n" + c, ps := Compile(text, Options{}) + if len(ps) != 0 { + t.Fatalf("%q: %v", text, ps) + } + if want := "count_if(" + body + ") as n"; len(c.Query.Measures) != 1 || c.Query.Measures[0] != want { + t.Fatalf("%q: got %#v; want %q", text, c.Query.Measures, want) + } + if _, err := panel.ParseMeasure(c.Query.From, c.Query.Measures[0]); err != nil { + t.Fatalf("%q: %v", text, err) + } + } +} + func TestLowerPositiveFixtures(t *testing.T) { for _, tt := range lowerFixtures { t.Run(tt.text, func(t *testing.T) { diff --git a/internal/fanql/print.go b/internal/fanql/print.go index bf28d1e9..39369ad9 100644 --- a/internal/fanql/print.go +++ b/internal/fanql/print.go @@ -374,7 +374,9 @@ func printValue(v Value, f Field, aliases bool) string { if v.Kind == StringValue { if f.Ref != nil && f.Ref.Key == "" && f.Ref.Type == "string" && f.Ref.CompareAs == "" { if numberPattern.MatchString(v.Text) { - return v.Text + if _, err := strconv.ParseFloat(v.Text, 64); err == nil { + return v.Text + } } if v.Text == "true" || v.Text == "false" { return strings.ToLower(v.Text) @@ -399,9 +401,7 @@ func printLiteral(v Value, forceQuote bool) string { return v.Text } if v.Kind == NumberValue { - if n, err := strconv.ParseFloat(v.Text, 64); err == nil { - return strconv.FormatFloat(n, 'f', -1, 64) - } + return numberText(v.Text) } if v.Kind == BooleanValue { return strings.ToLower(v.Text) diff --git a/internal/fanql/print_test.go b/internal/fanql/print_test.go index 6855fffb..20037ef4 100644 --- a/internal/fanql/print_test.go +++ b/internal/fanql/print_test.go @@ -69,6 +69,29 @@ func TestPrintIsAFixedPoint(t *testing.T) { } } +func TestPrintPreservesQuotedNonFiniteNumbers(t *testing.T) { + for _, text := range []string{ + `logs where service:"1e309"`, + `logs where service:"-1e309"`, + `logs where service:"1e+309"`, + `logs where service in ("1e309", "-1e309")`, + } { + t.Run(text, func(t *testing.T) { + c, ps := Compile(text, Options{}) + if len(ps) != 0 { + t.Fatal(ps) + } + if c.Canonical != text { + t.Errorf("canonical %q; want %q", c.Canonical, text) + } + again, ps := Compile(c.Canonical, Options{}) + if len(ps) != 0 || !reflect.DeepEqual(again.Query, c.Query) { + t.Fatalf("recompile: %+v %v", again, ps) + } + }) + } +} + func TestPrintCompatibleEditPlacesBucketBeforeSortAndLimit(t *testing.T) { c, ps := Compile(`spans | count() by service sort count limit 10`, Options{}) if len(ps) > 0 { diff --git a/internal/panel/measure.go b/internal/panel/measure.go index 0592e5a3..78f13e77 100644 --- a/internal/panel/measure.go +++ b/internal/panel/measure.go @@ -128,8 +128,9 @@ type measureParser struct { message, hint string } -// Strings (including escaped SQL quotes) remain one token. The scanner counts -// SQL tokens inside count_if too, without interpreting or trusting that SQL. +// Strings (including escaped SQL quotes) remain one token, and SQL comments +// are skipped. The scanner counts SQL tokens inside count_if too, without +// interpreting or trusting that SQL. func measureTokens(text string) ([]measureToken, string) { var tokens []measureToken for i := 0; i < len(text); { @@ -141,6 +142,30 @@ func measureTokens(text string) ([]measureToken, string) { c := text[i] i++ switch { + case c == '-' && i < len(text) && text[i] == '-': + for i < len(text) && text[i] != '\n' && text[i] != '\r' { + i++ + } + continue + case c == '/' && i < len(text) && text[i] == '*': + i++ + depth := 1 + for i < len(text) && depth > 0 { + switch { + case i+1 < len(text) && text[i:i+2] == "/*": + depth++ + i += 2 + case i+1 < len(text) && text[i:i+2] == "*/": + depth-- + i += 2 + default: + i++ + } + } + if depth != 0 { + return nil, "unterminated block comment" + } + continue case c == '\'' || c == '"': closed := false for i < len(text) { diff --git a/internal/panel/measure_expr_test.go b/internal/panel/measure_expr_test.go index 3dd4bf7d..079a05af 100644 --- a/internal/panel/measure_expr_test.go +++ b/internal/panel/measure_expr_test.go @@ -99,6 +99,31 @@ func TestParseMeasureExpressions(t *testing.T) { } } +func TestParseMeasureCountIfIgnoresCommentDelimiters(t *testing.T) { + for _, body := range []string{ + "body = 'x' /* ) */", + "body = 'x' -- ) ( , |\n", + "body = 'x' /* ( /* ) */ ( */", + "body = 'it''s ) /* --' /* ) ' */", + `attributes[')'] = '(' /* ) */`, + "body = 'x' -- ' /* )\r\n", + } { + t.Run(body, func(t *testing.T) { + m, err := ParseMeasure("logs", "count_if("+body+") as n") + if err != nil { + t.Fatal(err) + } + conditional, ok := m.Expr.(MeasureCountIf) + if !ok || conditional.Filter != body || m.Alias != "n" { + t.Fatalf("parsed %+v; want complete filter %q and alias n", m, body) + } + }) + } + if _, err := ParseMeasure("logs", "count_if(body = 'x' /* ) as n"); err == nil { + t.Fatal("accepted an unterminated block comment") + } +} + // A balanced expression isolates node budgets from the independent depth cap. func balancedMeasureNodes(n int) string { return balancedMeasureTree(n, 0) } func balancedMeasureTree(n, level int) string { diff --git a/scripts/go-deadcode.allowlist b/scripts/go-deadcode.allowlist index 2f9a0af1..9aa78301 100644 --- a/scripts/go-deadcode.allowlist +++ b/scripts/go-deadcode.allowlist @@ -1,3 +1,2 @@ # Exact symbolreviewed reason for genuine non-main entry points only. github.com/labstack/fanout/internal/auth.OAuthTokenPair.String fmt.Stringer security boundary: formatting token pairs must redact both credentials; not a callable product action. -github.com/labstack/fanout/internal/fanql.expectAt Completion parser contract seam for token and expected-class fixtures; Complete shares its underlying context parser to avoid parsing twice. From 2e3713a468915d0fa2c4d7f4a98e69eca15ddff4 Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Thu, 29 Oct 2026 21:02:36 -0700 Subject: [PATCH 16/30] feat(ui): hide AI controls when chat is disabled --- .../dist/assets/WarningCircle.es-CClFvSYW.js | 1 - .../dist/assets/WarningCircle.es-CEJpUomm.js | 1 + internal/ui/dist/assets/chat-CgHTI0Fx.js | 2 - internal/ui/dist/assets/chat-D9q4mn0t.js | 2 + .../ui/dist/assets/chat._threadId-DMtKC6Qw.js | 1 - .../ui/dist/assets/chat._threadId-DOzBCpD0.js | 1 + .../ui/dist/assets/chat.index-DMtKC6Qw.js | 1 - .../ui/dist/assets/chat.index-DOzBCpD0.js | 1 + ....js => dashboard-change-chips-DKNHrHOk.js} | 2 +- ...js => dashboards._dashboardId-3NqeTTXq.js} | 2 +- ...MzfRRW.js => dashboards.index-CoF5-Lh4.js} | 2 +- internal/ui/dist/assets/index-BZ6fASDi.js | 136 ------------------ internal/ui/dist/assets/index-m8tRkNwz.js | 136 ++++++++++++++++++ .../ui/dist/assets/mcp-app-frame-B4umpmdI.js | 57 -------- .../ui/dist/assets/mcp-app-frame-BNA4_n4D.js | 57 ++++++++ .../{page-6_nmYeSY.js => page-DWbtzTMF.js} | 18 +-- ...0YOP-x.js => panel-sql-editor-CCiQZRwh.js} | 4 +- ...EHBQhIeL.js => preload-helper-DJZNfKNH.js} | 2 +- internal/ui/dist/assets/settings-og0efxIm.js | 16 +++ internal/ui/dist/assets/settings-taYHMo2-.js | 16 --- internal/ui/dist/index.html | 4 +- ui/host/src/app.test.tsx | 29 +++- ui/host/src/dashboards/grid.test.tsx | 12 ++ ui/host/src/dashboards/grid.tsx | 4 +- ui/host/src/rail.test.tsx | 28 ++++ ui/host/src/rail.tsx | 8 +- ui/host/src/settings.test.tsx | 22 +++ ui/host/src/settings.tsx | 11 ++ 28 files changed, 333 insertions(+), 243 deletions(-) delete mode 100644 internal/ui/dist/assets/WarningCircle.es-CClFvSYW.js create mode 100644 internal/ui/dist/assets/WarningCircle.es-CEJpUomm.js delete mode 100644 internal/ui/dist/assets/chat-CgHTI0Fx.js create mode 100644 internal/ui/dist/assets/chat-D9q4mn0t.js delete mode 100644 internal/ui/dist/assets/chat._threadId-DMtKC6Qw.js create mode 100644 internal/ui/dist/assets/chat._threadId-DOzBCpD0.js delete mode 100644 internal/ui/dist/assets/chat.index-DMtKC6Qw.js create mode 100644 internal/ui/dist/assets/chat.index-DOzBCpD0.js rename internal/ui/dist/assets/{dashboard-change-chips-BODDZoYU.js => dashboard-change-chips-DKNHrHOk.js} (99%) rename internal/ui/dist/assets/{dashboards._dashboardId-CHxQdhK6.js => dashboards._dashboardId-3NqeTTXq.js} (74%) rename internal/ui/dist/assets/{dashboards.index-CHMzfRRW.js => dashboards.index-CoF5-Lh4.js} (68%) delete mode 100644 internal/ui/dist/assets/index-BZ6fASDi.js create mode 100644 internal/ui/dist/assets/index-m8tRkNwz.js delete mode 100644 internal/ui/dist/assets/mcp-app-frame-B4umpmdI.js create mode 100644 internal/ui/dist/assets/mcp-app-frame-BNA4_n4D.js rename internal/ui/dist/assets/{page-6_nmYeSY.js => page-DWbtzTMF.js} (53%) rename internal/ui/dist/assets/{panel-sql-editor-CC0YOP-x.js => panel-sql-editor-CCiQZRwh.js} (98%) rename internal/ui/dist/assets/{preload-helper-EHBQhIeL.js => preload-helper-DJZNfKNH.js} (54%) create mode 100644 internal/ui/dist/assets/settings-og0efxIm.js delete mode 100644 internal/ui/dist/assets/settings-taYHMo2-.js diff --git a/internal/ui/dist/assets/WarningCircle.es-CClFvSYW.js b/internal/ui/dist/assets/WarningCircle.es-CClFvSYW.js deleted file mode 100644 index 2d7d2f2e..00000000 --- a/internal/ui/dist/assets/WarningCircle.es-CClFvSYW.js +++ /dev/null @@ -1 +0,0 @@ -import{i as e,r as t,s as n}from"./useRouter-ByJ6_rwb.js";import{M as r,Y as i,a,f as o,w as s}from"./brand-DUaZkIz1.js";import{G as c,J as l,K as u,Q as d,X as f,Y as p,Z as m,q as h}from"./index-BZ6fASDi.js";var g={root:`m_849cf0da`},_=t(),v={underline:`hover`},y=s(e=>{let{underline:t,className:n,unstyled:a,mod:s,...c}=r(`Anchor`,v,e);return(0,_.jsx)(o,{component:`a`,className:i({[g.root]:!a},n),...c,mod:[{underline:t},s],__staticSelector:`Anchor`,unstyled:a})});y.classes=g,y.displayName=`@mantine/core/Anchor`;var b=class extends h{#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),f(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&l(t.mutationKey)!==l(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}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??c();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){u.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},x=n(e(),1);function S(e,t){let n=d(t),[r]=x.useState(()=>new b(n,e));x.useEffect(()=>{r.setOptions(e)},[r,e]);let i=x.useSyncExternalStore(x.useCallback(e=>r.subscribe(u.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=x.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(p)},[r]);if(i.error&&m(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var C=new Map([[`bold`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M128,20A108,108,0,1,0,236,128,108.12,108.12,0,0,0,128,20Zm0,192a84,84,0,1,1,84-84A84.09,84.09,0,0,1,128,212Zm-12-80V80a12,12,0,0,1,24,0v52a12,12,0,0,1-24,0Zm28,40a16,16,0,1,1-16-16A16,16,0,0,1,144,172Z`}))],[`duotone`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z`,opacity:`0.2`}),x.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm-8-80V80a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm20,36a12,12,0,1,1-12-12A12,12,0,0,1,140,172Z`}))],[`fill`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-8,56a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm8,104a12,12,0,1,1,12-12A12,12,0,0,1,128,184Z`}))],[`light`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M128,26A102,102,0,1,0,230,128,102.12,102.12,0,0,0,128,26Zm0,192a90,90,0,1,1,90-90A90.1,90.1,0,0,1,128,218Zm-6-82V80a6,6,0,0,1,12,0v56a6,6,0,0,1-12,0Zm16,36a10,10,0,1,1-10-10A10,10,0,0,1,138,172Z`}))],[`regular`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm-8-80V80a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm20,36a12,12,0,1,1-12-12A12,12,0,0,1,140,172Z`}))],[`thin`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M128,28A100,100,0,1,0,228,128,100.11,100.11,0,0,0,128,28Zm0,192a92,92,0,1,1,92-92A92.1,92.1,0,0,1,128,220Zm-4-84V80a4,4,0,0,1,8,0v56a4,4,0,0,1-8,0Zm12,36a8,8,0,1,1-8-8A8,8,0,0,1,136,172Z`}))]]),w=x.forwardRef((e,t)=>x.createElement(a,{ref:t,...e,weights:C}));w.displayName=`WarningCircleIcon`;var T=w;export{S as n,y as r,T as t}; \ No newline at end of file diff --git a/internal/ui/dist/assets/WarningCircle.es-CEJpUomm.js b/internal/ui/dist/assets/WarningCircle.es-CEJpUomm.js new file mode 100644 index 00000000..02224691 --- /dev/null +++ b/internal/ui/dist/assets/WarningCircle.es-CEJpUomm.js @@ -0,0 +1 @@ +import{i as e,r as t,s as n}from"./useRouter-ByJ6_rwb.js";import{M as r,Y as i,a,f as o,w as s}from"./brand-DUaZkIz1.js";import{at as c,ct as l,it as u,nt as d,ot as f,rt as p,st as m,tt as h}from"./index-m8tRkNwz.js";var g={root:`m_849cf0da`},_=t(),v={underline:`hover`},y=s(e=>{let{underline:t,className:n,unstyled:a,mod:s,...c}=r(`Anchor`,v,e);return(0,_.jsx)(o,{component:`a`,className:i({[g.root]:!a},n),...c,mod:[{underline:t},s],__staticSelector:`Anchor`,unstyled:a})});y.classes=g,y.displayName=`@mantine/core/Anchor`;var b=class extends p{#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),f(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&u(t.mutationKey)!==u(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}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??h();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){d.batch(()=>{let t=this.#r;if(t&&this.hasListeners()){let n=this.#t.variables,r=this.#t.context,i={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{t.onSuccess?.(e.data,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(e.data,null,n,r,i)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{t.onError?.(e.error,n,r,i)}catch(e){Promise.reject(e)}try{t.onSettled?.(void 0,e.error,n,r,i)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}},x=n(e(),1);function S(e,t){let n=l(t),[r]=x.useState(()=>new b(n,e));x.useEffect(()=>{r.setOptions(e)},[r,e]);let i=x.useSyncExternalStore(x.useCallback(e=>r.subscribe(d.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=x.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(c)},[r]);if(i.error&&m(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}var C=new Map([[`bold`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M128,20A108,108,0,1,0,236,128,108.12,108.12,0,0,0,128,20Zm0,192a84,84,0,1,1,84-84A84.09,84.09,0,0,1,128,212Zm-12-80V80a12,12,0,0,1,24,0v52a12,12,0,0,1-24,0Zm28,40a16,16,0,1,1-16-16A16,16,0,0,1,144,172Z`}))],[`duotone`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z`,opacity:`0.2`}),x.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm-8-80V80a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm20,36a12,12,0,1,1-12-12A12,12,0,0,1,140,172Z`}))],[`fill`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-8,56a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm8,104a12,12,0,1,1,12-12A12,12,0,0,1,128,184Z`}))],[`light`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M128,26A102,102,0,1,0,230,128,102.12,102.12,0,0,0,128,26Zm0,192a90,90,0,1,1,90-90A90.1,90.1,0,0,1,128,218Zm-6-82V80a6,6,0,0,1,12,0v56a6,6,0,0,1-12,0Zm16,36a10,10,0,1,1-10-10A10,10,0,0,1,138,172Z`}))],[`regular`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm-8-80V80a8,8,0,0,1,16,0v56a8,8,0,0,1-16,0Zm20,36a12,12,0,1,1-12-12A12,12,0,0,1,140,172Z`}))],[`thin`,x.createElement(x.Fragment,null,x.createElement(`path`,{d:`M128,28A100,100,0,1,0,228,128,100.11,100.11,0,0,0,128,28Zm0,192a92,92,0,1,1,92-92A92.1,92.1,0,0,1,128,220Zm-4-84V80a4,4,0,0,1,8,0v56a4,4,0,0,1-8,0Zm12,36a8,8,0,1,1-8-8A8,8,0,0,1,136,172Z`}))]]),w=x.forwardRef((e,t)=>x.createElement(a,{ref:t,...e,weights:C}));w.displayName=`WarningCircleIcon`;var T=w;export{S as n,y as r,T as t}; \ No newline at end of file diff --git a/internal/ui/dist/assets/chat-CgHTI0Fx.js b/internal/ui/dist/assets/chat-CgHTI0Fx.js deleted file mode 100644 index 06c7e3b2..00000000 --- a/internal/ui/dist/assets/chat-CgHTI0Fx.js +++ /dev/null @@ -1,2 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mcp-app-frame-B4umpmdI.js","assets/useRouter-ByJ6_rwb.js","assets/brand-DUaZkIz1.js","assets/index-BZ6fASDi.js","assets/useNavigate-B1zgPEUp.js","assets/preload-helper-EHBQhIeL.js","assets/Tooltip-B3r3s_B9.js","assets/index-ADB9ThEc.css"])))=>i.map(i=>d[i]); -import{i as e,r as t,s as n}from"./useRouter-ByJ6_rwb.js";import{A as r,C as i,M as a,S as o,T as s,_ as c,a as l,c as u,d,f,i as p,l as m,m as h,n as g,o as _,p as v,r as y,tt as b,u as x,x as S,y as C}from"./brand-DUaZkIz1.js";import{c as w,d as T,g as E,h as D,l as O,m as ee,o as k,p as A,s as te,t as j,u as M}from"./preload-helper-EHBQhIeL.js";import{t as N}from"./Tooltip-B3r3s_B9.js";import{a as P,c as F,d as I,l as L,n as R,r as ne,t as re,u as ie}from"./dashboard-change-chips-BODDZoYU.js";import{zt as z}from"./index-BZ6fASDi.js";var B=n(e(),1),V=t(),ae=[`borderBottomWidth`,`borderLeftWidth`,`borderRightWidth`,`borderTopWidth`,`boxSizing`,`fontFamily`,`fontSize`,`fontStyle`,`fontWeight`,`letterSpacing`,`lineHeight`,`paddingBottom`,`paddingLeft`,`paddingRight`,`paddingTop`,`tabSize`,`textIndent`,`textRendering`,`textTransform`,`width`,`wordBreak`,`wordSpacing`,`scrollbarGutter`],H={"min-height":`0`,"max-height":`none`,height:`0`,visibility:`hidden`,overflow:`hidden`,position:`absolute`,"z-index":`-1000`,top:`0`,right:`0`,display:`block`};function U(e){Object.keys(H).forEach(t=>{e.style.setProperty(t,H[t],`important`)})}function oe(e){let t=window.getComputedStyle(e);if(t===null)return null;let n={};for(let e of ae)n[e]=t[e];return n.boxSizing===``?null:{sizingStyle:n,paddingSize:parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),borderSize:parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth)}}var W=null;function se(e,t,n=1,r=1/0){W||(W=document.createElement(`textarea`),W.setAttribute(`tabindex`,`-1`),W.setAttribute(`aria-hidden`,`true`),W.setAttribute(`aria-label`,`autosize measurement`),U(W)),W.parentNode===null&&document.body.appendChild(W);let{paddingSize:i,borderSize:a,sizingStyle:o}=e,{boxSizing:s}=o;Object.keys(o).forEach(e=>{W.style[e]=o[e]}),U(W),W.value=t;let c=s===`border-box`?W.scrollHeight+a:W.scrollHeight-i;W.value=t,c=s===`border-box`?W.scrollHeight+a:W.scrollHeight-i,W.value=`x`;let l=W.scrollHeight-i,u=l*n;s===`border-box`&&(u=u+i+a),c=Math.max(u,c);let d=l*r;return s===`border-box`&&(d=d+i+a),c=Math.min(d,c),[c,l]}function ce({maxRows:e,minRows:t,onChange:n,ref:r,...i}){let a=i.value!==void 0,o=(0,B.useRef)(null),s=b(o,r),c=(0,B.useRef)(0),l=(0,B.useRef)(0),u=()=>{let n=o.current;if(!n)return;let r=oe(n);if(!r)return;let[i]=se(r,n.value||n.placeholder||`x`,t,e);c.current!==i&&(c.current=i,n.style.setProperty(`height`,`${i}px`,`important`))},d=(0,B.useEffectEvent)(u),f=e=>{a||u(),n?.(e)};return(0,B.useLayoutEffect)(u),(0,B.useEffect)(()=>{let e=()=>u();return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,B.useEffect)(()=>{let e=o.current;if(!e||typeof ResizeObserver>`u`)return;l.current=e.offsetWidth;let t=0,n=new ResizeObserver(()=>{o.current&&o.current.offsetWidth!==l.current&&(l.current=o.current.offsetWidth,cancelAnimationFrame(t),t=requestAnimationFrame(d))});return n.observe(e),()=>{cancelAnimationFrame(t),n.disconnect()}},[]),(0,B.useEffect)(()=>{let e=()=>u();return document.fonts.addEventListener(`loadingdone`,e),()=>document.fonts.removeEventListener(`loadingdone`,e)},[]),(0,B.useEffect)(()=>{let e=e=>{if(o.current?.form===e.target&&!a){let e=o.current.value;requestAnimationFrame(()=>{o.current&&e!==o.current.value&&u()})}};return document.body.addEventListener(`reset`,e),()=>document.body.removeEventListener(`reset`,e)},[a]),(0,V.jsx)(`textarea`,{rows:t,...i,onChange:f,ref:s})}var G=s(e=>{let{autosize:t,maxRows:n,minRows:r,__staticSelector:i,resize:o,bottomSection:s,bottomSectionProps:c,...l}=a([`Input`,`InputWrapper`,`Textarea`],null,e),u=t&&I()!==`test`,d=u?{maxRows:n,minRows:r}:{};return(0,V.jsx)(h,{component:u?ce:`textarea`,...l,__staticSelector:i||`Textarea`,__bottomSection:s,__bottomSectionProps:c,multiline:!0,"data-no-overflow":t&&n===void 0||void 0,__vars:{"--input-resize":o},...d})});G.classes=h.classes,G.displayName=`@mantine/core/Textarea`;var K={root:`m_d08caa0`},q=s(e=>{let t=a(`Typography`,null,e),{classNames:n,className:o,style:s,styles:c,unstyled:l,attributes:u,...d}=t,f=r({name:`Typography`,classes:K,props:t,className:o,style:s,classNames:n,styles:c,unstyled:l,attributes:u});return(0,V.jsx)(i,{...f(`root`),...d})});q.classes=K,q.displayName=`@mantine/core/Typography`;var le=new Map([[`bold`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M208.49,152.49l-72,72a12,12,0,0,1-17,0l-72-72a12,12,0,0,1,17-17L116,187V40a12,12,0,0,1,24,0V187l51.51-51.52a12,12,0,0,1,17,17Z`}))],[`duotone`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M200,144l-72,72L56,144Z`,opacity:`0.2`}),B.createElement(`path`,{d:`M207.39,140.94A8,8,0,0,0,200,136H136V40a8,8,0,0,0-16,0v96H56a8,8,0,0,0-5.66,13.66l72,72a8,8,0,0,0,11.32,0l72-72A8,8,0,0,0,207.39,140.94ZM128,204.69,75.31,152H180.69Z`}))],[`fill`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M205.66,149.66l-72,72a8,8,0,0,1-11.32,0l-72-72A8,8,0,0,1,56,136h64V40a8,8,0,0,1,16,0v96h64a8,8,0,0,1,5.66,13.66Z`}))],[`light`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M204.24,148.24l-72,72a6,6,0,0,1-8.48,0l-72-72a6,6,0,0,1,8.48-8.48L122,201.51V40a6,6,0,0,1,12,0V201.51l61.76-61.75a6,6,0,0,1,8.48,8.48Z`}))],[`regular`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M205.66,149.66l-72,72a8,8,0,0,1-11.32,0l-72-72a8,8,0,0,1,11.32-11.32L120,196.69V40a8,8,0,0,1,16,0V196.69l58.34-58.35a8,8,0,0,1,11.32,11.32Z`}))],[`thin`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M202.83,146.83l-72,72a4,4,0,0,1-5.66,0l-72-72a4,4,0,0,1,5.66-5.66L124,206.34V40a4,4,0,0,1,8,0V206.34l65.17-65.17a4,4,0,0,1,5.66,5.66Z`}))]]),ue=new Map([[`bold`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M184.49,136.49l-80,80a12,12,0,0,1-17-17L159,128,87.51,56.49a12,12,0,1,1,17-17l80,80A12,12,0,0,1,184.49,136.49Z`}))],[`duotone`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M176,128,96,208V48Z`,opacity:`0.2`}),B.createElement(`path`,{d:`M181.66,122.34l-80-80A8,8,0,0,0,88,48V208a8,8,0,0,0,13.66,5.66l80-80A8,8,0,0,0,181.66,122.34ZM104,188.69V67.31L164.69,128Z`}))],[`fill`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M181.66,133.66l-80,80A8,8,0,0,1,88,208V48a8,8,0,0,1,13.66-5.66l80,80A8,8,0,0,1,181.66,133.66Z`}))],[`light`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M180.24,132.24l-80,80a6,6,0,0,1-8.48-8.48L167.51,128,91.76,52.24a6,6,0,0,1,8.48-8.48l80,80A6,6,0,0,1,180.24,132.24Z`}))],[`regular`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M181.66,133.66l-80,80a8,8,0,0,1-11.32-11.32L164.69,128,90.34,53.66a8,8,0,0,1,11.32-11.32l80,80A8,8,0,0,1,181.66,133.66Z`}))],[`thin`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M178.83,130.83l-80,80a4,4,0,0,1-5.66-5.66L170.34,128,93.17,50.83a4,4,0,0,1,5.66-5.66l80,80A4,4,0,0,1,178.83,130.83Z`}))]]),de=new Map([[`bold`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M230.14,25.86a20,20,0,0,0-19.57-5.11l-.22.07L18.44,79a20,20,0,0,0-3.06,37.25L99,157l40.71,83.65a19.81,19.81,0,0,0,18,11.38c.57,0,1.15,0,1.73-.07A19.82,19.82,0,0,0,177,237.56L235.18,45.65a1.42,1.42,0,0,0,.07-.22A20,20,0,0,0,230.14,25.86ZM156.91,221.07l-34.37-70.64,46-45.95a12,12,0,0,0-17-17l-46,46L34.93,99.09,210,46Z`}))],[`duotone`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M223.69,42.18l-58.22,192a8,8,0,0,1-14.92,1.25L108,148,20.58,105.45a8,8,0,0,1,1.25-14.92l192-58.22A8,8,0,0,1,223.69,42.18Z`,opacity:`0.2`}),B.createElement(`path`,{d:`M227.32,28.68a16,16,0,0,0-15.66-4.08l-.15,0L19.57,82.84a16,16,0,0,0-2.49,29.8L102,154l41.3,84.87A15.86,15.86,0,0,0,157.74,248q.69,0,1.38-.06a15.88,15.88,0,0,0,14-11.51l58.2-191.94c0-.05,0-.1,0-.15A16,16,0,0,0,227.32,28.68ZM157.83,231.85l-.05.14,0-.07-40.06-82.3,48-48a8,8,0,0,0-11.31-11.31l-48,48L24.08,98.25l-.07,0,.14,0L216,40Z`}))],[`fill`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M231.4,44.34s0,.1,0,.15l-58.2,191.94a15.88,15.88,0,0,1-14,11.51q-.69.06-1.38.06a15.86,15.86,0,0,1-14.42-9.15L107,164.15a4,4,0,0,1,.77-4.58l57.92-57.92a8,8,0,0,0-11.31-11.31L96.43,148.26a4,4,0,0,1-4.58.77L17.08,112.64a16,16,0,0,1,2.49-29.8l191.94-58.2.15,0A16,16,0,0,1,231.4,44.34Z`}))],[`light`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M225.88,30.12a13.83,13.83,0,0,0-13.7-3.58l-.11,0L20.14,84.77A14,14,0,0,0,18,110.85l85.56,41.64L145.12,238a13.87,13.87,0,0,0,12.61,8c.4,0,.81,0,1.21-.05a13.9,13.9,0,0,0,12.29-10.09l58.2-191.93,0-.11A13.83,13.83,0,0,0,225.88,30.12Zm-8,10.4L159.73,232.43l0,.11a2,2,0,0,1-3.76.26l-40.68-83.58,49-49a6,6,0,1,0-8.49-8.49l-49,49L23.15,100a2,2,0,0,1,.31-3.74l.11,0L215.48,38.08a1.94,1.94,0,0,1,1.92.52A2,2,0,0,1,217.92,40.52Z`}))],[`regular`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M227.32,28.68a16,16,0,0,0-15.66-4.08l-.15,0L19.57,82.84a16,16,0,0,0-2.49,29.8L102,154l41.3,84.87A15.86,15.86,0,0,0,157.74,248q.69,0,1.38-.06a15.88,15.88,0,0,0,14-11.51l58.2-191.94c0-.05,0-.1,0-.15A16,16,0,0,0,227.32,28.68ZM157.83,231.85l-.05.14,0-.07-40.06-82.3,48-48a8,8,0,0,0-11.31-11.31l-48,48L24.08,98.25l-.07,0,.14,0L216,40Z`}))],[`thin`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M224.47,31.52a11.87,11.87,0,0,0-11.82-3L20.74,86.67a12,12,0,0,0-1.91,22.38L105,151l41.92,86.15A11.88,11.88,0,0,0,157.74,244c.34,0,.69,0,1,0a11.89,11.89,0,0,0,10.52-8.63l58.21-192,0-.08A11.85,11.85,0,0,0,224.47,31.52Zm-4.62,9.54-58.23,192a4,4,0,0,1-7.48.59l-41.3-84.86,50-50a4,4,0,1,0-5.66-5.66l-50,50-84.9-41.31a3.88,3.88,0,0,1-2.27-4,3.93,3.93,0,0,1,3-3.54L214.9,36.16A3.93,3.93,0,0,1,216,36a4,4,0,0,1,2.79,1.19A3.93,3.93,0,0,1,219.85,41.06Z`}))]]),fe=new Map([[`bold`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M200,36H56A20,20,0,0,0,36,56V200a20,20,0,0,0,20,20H200a20,20,0,0,0,20-20V56A20,20,0,0,0,200,36Zm-4,160H60V60H196Z`}))],[`duotone`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M208,56V200a8,8,0,0,1-8,8H56a8,8,0,0,1-8-8V56a8,8,0,0,1,8-8H200A8,8,0,0,1,208,56Z`,opacity:`0.2`}),B.createElement(`path`,{d:`M200,40H56A16,16,0,0,0,40,56V200a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V56A16,16,0,0,0,200,40Zm0,160H56V56H200V200Z`}))],[`fill`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M216,56V200a16,16,0,0,1-16,16H56a16,16,0,0,1-16-16V56A16,16,0,0,1,56,40H200A16,16,0,0,1,216,56Z`}))],[`light`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M200,42H56A14,14,0,0,0,42,56V200a14,14,0,0,0,14,14H200a14,14,0,0,0,14-14V56A14,14,0,0,0,200,42Zm2,158a2,2,0,0,1-2,2H56a2,2,0,0,1-2-2V56a2,2,0,0,1,2-2H200a2,2,0,0,1,2,2Z`}))],[`regular`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M200,40H56A16,16,0,0,0,40,56V200a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V56A16,16,0,0,0,200,40Zm0,160H56V56H200V200Z`}))],[`thin`,B.createElement(B.Fragment,null,B.createElement(`path`,{d:`M200,44H56A12,12,0,0,0,44,56V200a12,12,0,0,0,12,12H200a12,12,0,0,0,12-12V56A12,12,0,0,0,200,44Zm4,156a4,4,0,0,1-4,4H56a4,4,0,0,1-4-4V56a4,4,0,0,1,4-4H200a4,4,0,0,1,4,4Z`}))]]),J=B.forwardRef((e,t)=>B.createElement(l,{ref:t,...e,weights:le}));J.displayName=`ArrowDownIcon`;var pe=J,Y=B.forwardRef((e,t)=>B.createElement(l,{ref:t,...e,weights:ue}));Y.displayName=`CaretRightIcon`;var X=Y,me=B.forwardRef((e,t)=>B.createElement(l,{ref:t,...e,weights:de}));me.displayName=`PaperPlaneTiltIcon`;var he=me,ge=B.forwardRef((e,t)=>B.createElement(l,{ref:t,...e,weights:fe}));ge.displayName=`StopIcon`;var _e=ge;function ve(e){return e.dashboard.panels.length===1?e.dashboard.panels[0].title:e.dashboard.name}function ye(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Missing panel view`);let t=e;if(!t.view||![`preset`,`query`].includes(t.view.kind)||!/^[a-f0-9]{64}$/.test(t.view.key))throw Error(`Invalid panel view identity`);if(t.dashboard?.version!==1||!Array.isArray(t.dashboard.panels)||!t.dashboard.panels.length||t.dashboard.panels.length>40||!Array.isArray(t.results)||t.dashboard.panels.some(e=>!e||typeof e.id!=`string`||!e.id)||t.results.some(e=>!e||typeof e.id!=`string`))throw Error(`Invalid panel view`);let n=new Set(t.dashboard.panels.map(e=>e.id));if(n.size!==t.dashboard.panels.length||t.results.length!==n.size||new Set(t.results.map(e=>e.id)).size!==n.size||t.results.some(e=>!n.has(e.id)||![`ok`,`empty`,`error`].includes(e.status)))throw Error(`Panel results do not match the view`);if(t.vars!==void 0&&(!t.vars||typeof t.vars!=`object`||Array.isArray(t.vars)||Object.values(t.vars).some(e=>typeof e!=`string`&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`)))))throw Error(`Invalid panel variables`);if(t.trace!==void 0&&(!t.trace?.data||!Array.isArray(t.trace.data.spans)||!Array.isArray(t.trace.data.logs)||!Array.isArray(t.trace.data.services)))throw Error(`Invalid trace detail`);return t}var be=new WeakSet;function xe(e){if(!e||typeof e!=`object`||Array.isArray(e))return;if(be.has(e))return e;let t=e;if(Object.keys(t).sort().join(`,`)===`is_error,resource_uri,tool_input,tool_name,tool_result`&&t.resource_uri===`ui://fanout/panels.html`&&typeof t.tool_name==`string`&&t.tool_name&&typeof t.is_error==`boolean`&&t.tool_input&&typeof t.tool_input==`object`&&!Array.isArray(t.tool_input)){try{ye(t.tool_result)}catch{return}return be.add(t),t}}var Se=16,Ce=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `]);function we(e){let t=(0,B.useRef)(null),n=(0,B.useRef)(null),r=(0,B.useRef)(null),i=(0,B.useRef)(!0),a=(0,B.useRef)(e),o=(0,B.useRef)(()=>{}),s=(0,B.useRef)(null),c=(0,B.useRef)(new Set),l=(0,B.useRef)(null),u=(0,B.useRef)(null),[d,f]=(0,B.useState)(!1),p=(0,B.useCallback)(()=>{let e=t.current,n=r.current?.lastElementChild,i=!e||!n||n.getBoundingClientRect().bottom>e.getBoundingClientRect().top+e.clientTop+e.clientHeight+1;f(!!e&&i&&e.scrollHeight-e.clientHeight-e.scrollTop>1)},[]),m=(0,B.useCallback)(()=>{let e=t.current;if(!e)return;let n=e.getBoundingClientRect().top+e.clientTop,r=[...e.querySelectorAll(`[data-chat-anchor]`)].find(e=>e.getBoundingClientRect().bottom>n);l.current=r?{node:r,top:r.getBoundingClientRect().top}:null},[]),h=(0,B.useCallback)((e,t)=>{e.scrollTop=t,u.current=e.scrollTop},[]),g=(0,B.useCallback)(()=>{let e=t.current;if(e){if(r.current){let t=n.current&&parseFloat(getComputedStyle(n.current).paddingBottom)||0;r.current.style.minHeight=`${Math.max(0,e.clientHeight-Se-t)}px`,i.current&&h(e,e.scrollTop+r.current.getBoundingClientRect().top-e.getBoundingClientRect().top-e.clientTop-Se)}if(!i.current){let t=l.current;t?.node.isConnected&&h(e,e.scrollTop+t.node.getBoundingClientRect().top-t.top),m()}p()}},[m,h,p]),_=(0,B.useCallback)(()=>{let e=t.current,i=n.current;if(!e||!i){s.current?.disconnect(),s.current=null,c.current.clear();return}s.current??=new ResizeObserver(g);let a=new Set([e,i,...i.querySelectorAll(`[data-chat-anchor]`)]);r.current&&a.add(r.current);for(let e of c.current)a.has(e)||s.current.unobserve(e);for(let e of a)c.current.has(e)||s.current.observe(e);c.current=a},[g]),v=(0,B.useCallback)(e=>{if(o.current(),t.current=e,u.current=null,l.current=null,i.current=!0,_(),!e)return;let n=!1,r=()=>{i.current=!1,m()},a=e=>{let t=e.target;!e.defaultPrevented&&Ce.has(e.key)&&(t instanceof HTMLElement&&(t.closest(`input, textarea, select, [contenteditable]`)||(e.key===` `?t.closest(`button`):t.closest(`[role=slider]`)))||r())},s=()=>{n=!0},c=()=>{n=!1},d=()=>{n&&e.scrollTop!==u.current&&r(),i.current||m(),p()};e.addEventListener(`scroll`,d,{passive:!0}),e.addEventListener(`wheel`,r,{passive:!0}),e.addEventListener(`touchmove`,r,{passive:!0}),e.addEventListener(`keydown`,a),e.addEventListener(`pointerdown`,s),window.addEventListener(`pointerup`,c),window.addEventListener(`pointercancel`,c),o.current=()=>{e.removeEventListener(`scroll`,d),e.removeEventListener(`wheel`,r),e.removeEventListener(`touchmove`,r),e.removeEventListener(`keydown`,a),e.removeEventListener(`pointerdown`,s),window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),o.current=()=>{}},g()},[g,m,_,p]),y=(0,B.useCallback)(e=>{n.current=e,_()},[_]),b=(0,B.useCallback)(e=>{r.current?.style.removeProperty(`min-height`),r.current=e,_()},[_]);return(0,B.useLayoutEffect)(()=>{a.current!==e&&(a.current=e,i.current=!0,l.current=null),_(),g()}),{scrollRef:v,contentRef:y,turnRef:b,showJump:d,jumpToLatest:(0,B.useCallback)(()=>{let e=t.current;e&&(e.focus({preventScroll:!0}),i.current=!1,h(e,e.scrollHeight),m(),p())},[m,h,p])}}function Te(e=1500){let[t,n]=(0,B.useState)(`idle`),r=(0,B.useRef)(null);(0,B.useEffect)(()=>()=>{r.current&&clearTimeout(r.current)},[]);function i(t){r.current&&clearTimeout(r.current),n(`idle`),(navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(Error(`clipboard unavailable`))).then(()=>n(`copied`),()=>n(`failed`)).finally(()=>{r.current=setTimeout(()=>n(`idle`),e)})}return{state:t,copy:i}}var Z=e=>`${(e/1e3).toFixed(1)} s`;function Ee({receipt:e,running:t=!1,activity:n=``,awaitingAnswer:r=!1}){let[i,a]=(0,B.useState)(!1),o=(0,B.useId)(),s=e.saved,l=s?.receipt.save_check,p=t=>Object.hasOwn(e.panel_titles,t)?e.panel_titles[t]:t,m=Object.values(e.stages).filter(e=>e.state===`complete`).length,h=[e.stages.schema.state===`complete`?`Read telemetry`:void 0,e.panel_count===void 0?void 0:`${e.panel_count} ${e.panel_count===1?`panel`:`panels`}`,l?.checked?`Checked in ${Z(l.elapsed_ms)}`:void 0,s?`Saved v${s.version}`:void 0].filter(Boolean).join(` · `)||`Building dashboard`,g=[...s?O(s.receipt):[],...new Map(e.corrections.map(e=>[e.panel_id,`Fixed ${e.title}`])).values()];return(0,V.jsx)(S,{"data-build-receipt":e.turn_id,"data-dashboard-result":s?.id,"data-chat-anchor":!0,withBorder:!0,radius:`md`,p:`sm`,children:(0,V.jsxs)(u,{gap:6,children:[(0,V.jsxs)(c,{gap:`xs`,justify:`space-between`,children:[(0,V.jsxs)(f,{size:`sm`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[h,(0,V.jsxs)(f,{span:!0,c:`dimmed`,size:`xs`,children:[` · `,m,` stages complete`]})]}),(0,V.jsxs)(d,{component:`button`,variant:`subtle`,color:`gray`,size:`compact-xs`,"aria-expanded":i,"aria-controls":o,onClick:()=>a(e=>!e),children:[`Details`,g.length>4?` (+${g.length-4})`:``]})]}),t&&r&&(0,V.jsxs)(c,{gap:`xs`,"data-build-running":!0,children:[(0,V.jsx)(C,{type:`dots`,size:`sm`}),(0,V.jsx)(f,{c:`dimmed`,size:`sm`,children:n||`Analyzing your system`})]}),(0,V.jsx)(re,{labels:g.slice(0,4)}),e.explanations.map(e=>t?e.split(` · `).filter(e=>!e.endsWith(`: incomplete`)).join(` · `):e).filter(Boolean).map((e,t)=>(0,V.jsx)(f,{size:`xs`,c:`dimmed`,"data-receipt-attention":!0,children:e},t)),s&&(0,V.jsx)(d,{renderRoot:e=>(0,V.jsx)(E,{...e,to:`/dashboards/$dashboardId`,params:{dashboardId:s.id},search:{}}),variant:`subtle`,size:`compact-sm`,color:`gray`,style:{alignSelf:`flex-start`},children:`Open dashboard`}),(0,V.jsx)(ie,{expanded:i,id:o,children:(0,V.jsxs)(u,{gap:4,children:[s&&(0,V.jsxs)(f,{size:`xs`,children:[s.label,` `,s.name,` · opens the current dashboard`]}),Object.entries(e.stages).map(([e,n])=>(0,V.jsxs)(f,{size:`xs`,c:`dimmed`,children:[T[e],`: `,t&&n.state===`incomplete`?`in progress`:n.state,n.elapsed_ms===void 0?``:` · ${Z(n.elapsed_ms)}`]},e)),e.save_attempts.map((e,t)=>e.state===`retried`&&(0,V.jsxs)(f,{size:`xs`,c:`dimmed`,children:[`Save attempt `,t+1,`: retried`]},e.call_id)),!!e.context_counts.deploys&&(0,V.jsxs)(f,{size:`xs`,children:[e.context_counts.deploys,` deploys observed`]}),!!e.context_counts.anomalies&&(0,V.jsxs)(f,{size:`xs`,children:[e.context_counts.anomalies,` anomalies observed`]}),e.panels.map(e=>(0,V.jsxs)(f,{size:`xs`,children:[`Preview · `,p(e.id),`: `,e.status,e.elapsed_ms===void 0?``:` · ${Z(e.elapsed_ms)}`]},e.id)),l&&(0,V.jsxs)(f,{size:`xs`,children:[`Save check: `,l.checked?`checked`:`incomplete`,` · `,Z(l.elapsed_ms)]}),l?.panels.map(e=>(0,V.jsxs)(f,{size:`xs`,children:[`Save · `,p(e.id),`: `,e.status,` · `,e.rows??0,` rows`,e.elapsed_ms===void 0?``:` · ${Z(e.elapsed_ms)}`]},e.id)),g.slice(4).map((e,t)=>(0,V.jsx)(f,{size:`xs`,children:e},t)),e.corrections.map((e,t)=>(0,V.jsxs)(f,{size:`xs`,children:[`Fixed `,e.title,`: `,e.message]},t))]})})]})})}var De=(0,B.lazy)(()=>j(()=>import(`./mcp-app-frame-B4umpmdI.js`),__vite__mapDeps([0,1,2,3,4,5,6,7]))),Oe=e=>e.tool_result.view.kind===`preset`;function ke(e){let t=new Map,n=new Set,r=[],i=()=>{let e=new Map;for(let t of r){let n=t.content.tool_result.view.key;e.set(n,t)}let i=new Set([...e.values()].map(e=>e.id)),a=[...e.values()].some(e=>Oe(e.content)),o=r.filter(e=>i.has(e.id)).at(-1)?.id;for(let e of r)i.has(e.id)?t.set(e.id,{content:e.content,expanded:Oe(e.content)||!a&&e.id===o}):n.add(e.id);r=[]};for(let t of e)if(t.role===`user`&&i(),t.role===`activity`&&t.activityType===`mcp-app`){let e=xe(t.content);e&&r.push({id:t.id,content:e})}return i(),{views:t,duplicates:n}}function Ae(e,t){return Array.isArray(e)?e.flatMap(e=>{if(!D(e)||typeof e.message!=`string`)return[];let n=typeof e.path==`string`?/^panels\[(\d+)\](?:\.|$)/.exec(e.path)?.[1]:void 0,r=n===void 0?void 0:t?.[Number(n)];return[r&&!e.message.startsWith(r)?`${r}: ${e.message}`:e.message]}):[]}function je(e){let t=new Map,n=new Map,r=new Map,i=`unattributed`;for(let a of e){if(a.role===`user`&&(n.clear(),r.clear(),i=a.id),a.role===`assistant`){i=a.id;for(let e of a.toolCalls??[]){let t=[`create_dashboard`,`replace_dashboard`].includes(e.function.name)?A(e.function.arguments)?.dashboard:void 0,r=D(t)&&Array.isArray(t.panels)?t.panels.map(e=>D(e)&&typeof e.title==`string`?e.title:``):void 0;n.set(e.id,{assistant:i,name:e.function.name,titles:r})}}if(a.role===`tool`){let e=A(a.content);if(!a.error&&!e?.error&&e?.isError!==!0)continue;let o=n.get(a.toolCallId);if(o&&ee.has(o.name)&&M(a))continue;let s=D(e?.error)?e?.error:void 0;if(s?.code===`no_data`||s?.code===`unknown_service`)continue;let c=o?.assistant??i,l=r.get(c)??a.id;r.set(c,l);let u=t.get(l)??[],d=typeof s?.message==`string`?s.message:typeof a.error==`string`&&a.error?a.error:`Could not complete this step. Try again.`,f=[`create_dashboard`,`edit_dashboard`,`replace_dashboard`].includes(o?.name??``)&&(s?.code===`invalid_spec`||s?.code===`dashboard_version_conflict`);u.push({name:k(o?.name??``),message:d,details:f?Ae(e?.problems,o?.titles):[],readOnly:s?.code===`answer_only`,rejected:f}),t.set(l,u)}}return t}function Me({failures:e}){let[t,n]=(0,B.useState)({rejected:!1,failed:!1}),r=e.filter(e=>e.rejected),a=e.filter(e=>!e.readOnly&&!e.rejected),s=[{key:`rejected`,items:r,label:`${r.length} ${r.length===1?`draft`:`drafts`} rejected`},{key:`failed`,items:a,label:`${a.length} ${a.length===1?`step`:`steps`} failed`}];return(0,V.jsxs)(i,{"data-chat-anchor":!0,children:[e.some(e=>e.readOnly)&&(0,V.jsx)(f,{size:`sm`,c:`dimmed`,children:`Not saved: Explain is read-only`}),s.map(({key:e,items:r,label:a})=>r.length>0&&(0,V.jsxs)(i,{children:[(0,V.jsxs)(o,{className:`chat-app-toggle`,"aria-expanded":t[e],onClick:()=>n(t=>({...t,[e]:!t[e]})),style:{color:`var(--mantine-color-dimmed)`},children:[(0,V.jsx)(`span`,{className:`chat-app-chevron`,"aria-hidden":`true`,children:t[e]?(0,V.jsx)(F,{size:14}):(0,V.jsx)(X,{size:14})}),(0,V.jsx)(`span`,{className:`chat-app-summary`,children:a})]}),t[e]&&(0,V.jsx)(u,{gap:`xs`,pl:`md`,children:r.flatMap((e,t)=>(e.details.length?e.details:[`${e.name}: ${e.message}`]).map((e,n)=>(0,V.jsx)(f,{size:`sm`,c:`dimmed`,style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},children:e},`${t}-${n}`)))})]},e))]})}function Ne({view:e}){let[t,n]=(0,B.useState)(e.expanded);(0,B.useEffect)(()=>n(e.expanded),[e.expanded]);let r=e.content.tool_result,i=ve(r),a=[...new Set(r.dashboard.panels.map(e=>e.viz===`timeseries`?`time series`:e.viz.replaceAll(`_`,` `)))].join(`, `),s=r.results.reduce((e,t)=>e+(t.frame?.rows??0),0),c=new Map;for(let e of r.results)e.status!==`ok`&&c.set(e.status,(c.get(e.status)??0)+1);let l=r.dashboard.panels.length>1?Array.from(c,([e,t])=>`${t} ${e}`).join(` · `):c.size?[...c.keys()].join(`, `):`${s} ${s===1?`row`:`rows`}`;return(0,V.jsxs)(S,{"data-chat-app":!0,"data-chat-anchor":!0,withBorder:!0,radius:`lg`,style:{overflow:`hidden`},children:[(0,V.jsxs)(o,{className:`chat-app-toggle`,"aria-expanded":t,onClick:()=>n(e=>!e),children:[(0,V.jsx)(`span`,{className:`chat-app-chevron`,"aria-hidden":`true`,children:t?(0,V.jsx)(F,{size:14}):(0,V.jsx)(X,{size:14})}),(0,V.jsx)(`span`,{className:`chat-app-summary`,children:[i,a,l].filter(Boolean).join(` · `)})]}),t&&(0,V.jsx)(B.Suspense,{fallback:(0,V.jsx)(x,{mih:180,children:(0,V.jsx)(C,{size:`sm`})}),children:(0,V.jsx)(De,{content:e.content})})]})}var Pe=[`Summarize system health for the last hour`,`Find the source of elevated errors`,`Map the current service dependencies`,`Show the slowest endpoints`];function Fe(){let{agentAvailable:e,messages:t,messageTimes:n,ready:r,running:a,activity:o,stopped:s,error:l,threadMissing:p,send:h,retry:g,reloadThread:y,newThread:b}=w(),T=te(t),E=t.filter(e=>e.role===`user`).at(-1)?.id,{scrollRef:D,contentRef:O,turnRef:ee,showJump:k,jumpToLatest:A}=we(E);if(!e)return(0,V.jsx)(m,{size:`sm`,py:96,children:(0,V.jsx)(S,{withBorder:!0,radius:`lg`,p:{base:`xl`,sm:40},children:(0,V.jsxs)(u,{gap:`md`,children:[(0,V.jsx)(f,{c:`brand`,fw:700,size:`xs`,tt:`uppercase`,lts:`0.12em`,children:`Optional capability`}),(0,V.jsx)(_,{order:1,fz:28,children:`Chat is not configured`}),(0,V.jsx)(f,{c:`dimmed`,children:`Add an AI provider key to enable chat. Telemetry ingest, dashboards, traces, logs, and metrics remain available without it.`}),(0,V.jsx)(d,{component:`a`,href:`/dashboards`,variant:`light`,mt:`sm`,children:`Open dashboards`})]})})});let j=ke(t),M=je(t),P=t.filter(e=>j.duplicates.has(e.id)?!1:e.role===`tool`?M.has(e.id):e.role===`assistant`?!e.toolCalls?.length&&typeof e.content==`string`&&e.content.trim().length>0:e.role===`activity`?e.activityType===`mcp-app`||e.activityType===`agent-outcome`:e.role===`user`),F=t.findIndex(e=>e.id===E),I=t.slice(F+1).some(e=>e.role===`assistant`&&!e.toolCalls?.length&&typeof e.content==`string`&&e.content.length>0),L=t.slice(F+1).filter(e=>e.role===`assistant`&&!e.toolCalls?.length&&typeof e.content==`string`&&e.content.trim().length>0).at(-1),R=[];for(let e of P)(e.role===`user`||R.length===0)&&R.push({id:e.id,messages:[]}),R.at(-1).messages.push(e);R.length===0&&R.push({id:`draft`,messages:[]});let ne=e=>M.has(e.id)?(0,V.jsx)(Me,{failures:M.get(e.id)},e.id):(0,V.jsxs)(i,{children:[(0,V.jsx)(Re,{message:e,time:n[e.id],appView:j.views.get(e.id)}),T.has(e.id)&&(0,V.jsx)(i,{mt:`sm`,children:(0,V.jsx)(Ee,{receipt:T.get(e.id),running:a&&e.id===E,awaitingAnswer:!I,activity:o})})]},e.id);return(0,V.jsxs)(i,{className:`chat-pane`,children:[(0,V.jsxs)(i,{className:`chat-viewport`,children:[(0,V.jsx)(i,{className:`chat-scroll`,ref:D,tabIndex:0,role:`log`,"aria-label":`Conversation`,children:(0,V.jsxs)(m,{size:880,px:{base:`md`,sm:`xl`},py:`lg`,ref:O,children:[p&&(0,V.jsx)(v,{color:`warn`,radius:`lg`,title:`This chat no longer exists`,children:(0,V.jsxs)(c,{justify:`space-between`,children:[(0,V.jsx)(f,{size:`sm`,children:`It was deleted, or the link is wrong.`}),(0,V.jsx)(d,{size:`compact-sm`,variant:`light`,onClick:b,children:`New chat`})]})}),!p&&!r&&l&&(0,V.jsx)(Q,{message:l,onRetry:y,onNewThread:b}),!p&&!r&&!l&&(0,V.jsxs)(x,{mih:`40vh`,children:[(0,V.jsx)(C,{size:`sm`}),(0,V.jsx)(f,{c:`dimmed`,size:`sm`,ml:`sm`,children:`Loading chat`})]}),!p&&r&&(0,V.jsxs)(V.Fragment,{children:[P.length===0&&(0,V.jsx)(Le,{onSelect:h}),(0,V.jsx)(u,{gap:`lg`,children:R.map((e,t)=>(0,V.jsxs)(u,{gap:`lg`,ref:e.id===E?ee:void 0,"data-chat-turn":e.id===E?E:void 0,children:[e.messages.filter(e=>e.id!==L?.id).map(ne),t===R.length-1&&(0,V.jsxs)(V.Fragment,{children:[L&&(0,V.jsx)(i,{"data-answer-position":!0,children:(0,V.jsx)(Re,{message:L,time:n[L.id]})},`answer-${E??`draft`}`),a&&!I&&!T.has(E??``)&&(0,V.jsxs)(c,{gap:`xs`,role:`status`,children:[(0,V.jsx)(C,{type:`dots`,size:`sm`}),(0,V.jsx)(f,{c:`dimmed`,size:`sm`,children:o||`Analyzing your system`})]}),s&&(0,V.jsx)(f,{c:`dimmed`,size:`sm`,children:`Stopped`}),l&&(0,V.jsx)(Q,{message:l,onRetry:g})]})]},e.id))})]})]})}),k&&(0,V.jsx)(N,{label:`Jump to latest`,children:(0,V.jsx)(z,{className:`chat-jump`,variant:`default`,size:36,radius:`xl`,"aria-label":`Jump to latest`,onClick:A,children:(0,V.jsx)(pe,{size:18,"aria-hidden":`true`})})})]}),!p&&(0,V.jsx)(Ie,{})]})}function Q({message:e,onRetry:t,onNewThread:n}){return(0,V.jsx)(v,{color:`bad`,radius:`lg`,title:`Something went wrong`,children:(0,V.jsxs)(c,{justify:`space-between`,gap:`sm`,wrap:`nowrap`,children:[(0,V.jsx)(f,{size:`sm`,children:e}),(0,V.jsxs)(c,{gap:`xs`,wrap:`nowrap`,children:[n&&(0,V.jsx)(d,{size:`compact-sm`,variant:`subtle`,color:`bad`,onClick:n,children:`New chat`}),(0,V.jsx)(d,{size:`compact-sm`,variant:`light`,color:`bad`,onClick:t,children:`Retry`})]})]})})}function Ie(){let{input:e,setInput:t,inputRef:n,submit:r,send:a,stop:o,ready:s,running:l}=w();return(0,V.jsx)(i,{className:`chat-composer`,children:(0,V.jsxs)(m,{size:880,px:{base:`md`,sm:`xl`},children:[(0,V.jsx)(S,{component:`form`,onSubmit:r,className:`chat-composer-field`,withBorder:!0,radius:24,py:6,pl:`lg`,pr:6,children:(0,V.jsxs)(c,{align:`flex-end`,gap:`xs`,wrap:`nowrap`,children:[(0,V.jsx)(G,{ref:n,"aria-label":`Message Fanout`,value:e,onChange:e=>t(e.currentTarget.value),onKeyDown:t=>{t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),a(e))},placeholder:l?`Fanout is working…`:`Ask about health, errors, or latency…`,disabled:!s,autosize:!0,minRows:1,maxRows:8,variant:`unstyled`,flex:1}),l?(0,V.jsx)(N,{label:`Stop`,children:(0,V.jsx)(z,{type:`button`,variant:`default`,size:40,radius:`xl`,"aria-label":`Stop`,onClick:o,children:(0,V.jsx)(_e,{size:16,weight:`fill`})})}):(0,V.jsx)(z,{type:`submit`,variant:`filled`,size:40,radius:`xl`,disabled:!e.trim()||!s,"aria-label":`Send message`,children:(0,V.jsx)(he,{size:17,weight:`fill`})})]})}),(0,V.jsx)(f,{c:`dimmed`,size:`xs`,ta:`center`,mt:6,children:`Enter to send, Shift+Enter for a new line`})]})})}function Le({onSelect:e}){return(0,V.jsxs)(u,{align:`center`,gap:`md`,pt:{base:32,sm:88},pb:`xl`,ta:`center`,children:[(0,V.jsx)(g,{size:`large`}),(0,V.jsx)(_,{order:1,fz:24,fw:500,lh:1.25,maw:560,children:`What do you want to know about your system?`}),(0,V.jsx)(c,{justify:`center`,gap:`xs`,mt:`xs`,maw:720,children:Pe.map(t=>(0,V.jsx)(d,{variant:`default`,size:`sm`,radius:`xl`,onClick:()=>void e(t),children:t},t))})]})}function Re({message:e,time:t,appView:n}){if(e.role===`activity`)return e.activityType===`agent-outcome`&&e.content&&typeof e.content==`object`&&`message`in e.content&&typeof e.content.message==`string`?`status`in e.content&&e.content.status===`stopped`?(0,V.jsx)(f,{c:`dimmed`,size:`sm`,"data-chat-anchor":!0,children:e.content.message}):(0,V.jsx)(v,{color:`bad`,title:`Something went wrong`,"data-chat-anchor":!0,children:e.content.message}):e.activityType===`mcp-app`?n?(0,V.jsx)(Ne,{view:n}):(0,V.jsx)(v,{color:`bad`,"data-chat-anchor":!0,children:`This view could not be loaded. Please try again.`}):null;if(e.role===`assistant`&&e.toolCalls?.length)return null;let r=typeof e.content==`string`?e.content:JSON.stringify(e.content);if(!r&&e.role===`assistant`)return null;let a=e.role===`user`,o=t?new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}).format(new Date(t)):``;return(0,V.jsxs)(i,{className:`chat-message`,"data-chat-anchor":!0,"data-role":a?`user`:`assistant`,children:[a?(0,V.jsx)(S,{radius:`lg`,px:`md`,py:`sm`,bg:`var(--mantine-color-brand-light)`,maw:`70%`,ml:`auto`,w:`fit-content`,children:(0,V.jsx)(f,{style:{whiteSpace:`pre-wrap`},children:r})}):(0,V.jsx)(q,{className:`chat-markdown`,children:(0,V.jsx)(ne,{remarkPlugins:[R],components:Be,children:r})}),(o||!a)&&(0,V.jsxs)(c,{className:`chat-message-meta`,gap:6,justify:a?`flex-end`:`flex-start`,mt:4,h:24,children:[o&&t&&(0,V.jsx)(f,{c:`dimmed`,size:`xs`,title:P(t),children:o}),!a&&(0,V.jsx)(ze,{text:r,label:`Copy message`})]})]})}function ze({text:e,label:t}){let{state:n,copy:r}=Te();return(0,V.jsx)(N,{label:n===`failed`?`Could not copy`:n===`copied`?`Copied`:t,children:(0,V.jsx)(z,{variant:`subtle`,color:`gray`,size:`sm`,"aria-label":t,"data-state":n===`idle`?void 0:n,onClick:()=>r(e),children:n===`copied`?(0,V.jsx)(p,{size:13,weight:`bold`}):(0,V.jsx)(y,{size:13})})})}var Be={table:({children:e})=>(0,V.jsx)(i,{className:`chat-table`,children:(0,V.jsx)(L,{striped:!0,highlightOnHover:!0,withTableBorder:!0,verticalSpacing:`xs`,fz:`sm`,children:e})}),thead:({children:e})=>(0,V.jsx)(L.Thead,{children:e}),tbody:({children:e})=>(0,V.jsx)(L.Tbody,{children:e}),tr:({children:e})=>(0,V.jsx)(L.Tr,{children:e}),th:({children:e})=>(0,V.jsx)(L.Th,{children:e}),td:({children:e})=>(0,V.jsx)(L.Td,{children:e}),pre:({children:e})=>(0,V.jsx)(Ve,{children:e}),a:({href:e,children:t})=>(0,V.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,children:t})};function Ve({children:e}){let t=$(e);return(0,V.jsxs)(i,{className:`chat-code`,pos:`relative`,children:[(0,V.jsx)(i,{className:`chat-code-actions`,pos:`absolute`,top:6,right:6,children:(0,V.jsx)(ze,{text:t,label:`Copy code`})}),(0,V.jsx)(`pre`,{children:e})]})}function $(e){return typeof e==`string`?e:Array.isArray(e)?e.map($).join(``):e&&typeof e==`object`&&`props`in e?$(e.props.children):``}export{xe as n,Fe as t}; \ No newline at end of file diff --git a/internal/ui/dist/assets/chat-D9q4mn0t.js b/internal/ui/dist/assets/chat-D9q4mn0t.js new file mode 100644 index 00000000..10e8090a --- /dev/null +++ b/internal/ui/dist/assets/chat-D9q4mn0t.js @@ -0,0 +1,2 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/mcp-app-frame-BNA4_n4D.js","assets/useRouter-ByJ6_rwb.js","assets/brand-DUaZkIz1.js","assets/index-m8tRkNwz.js","assets/useNavigate-B1zgPEUp.js","assets/preload-helper-DJZNfKNH.js","assets/Tooltip-B3r3s_B9.js","assets/index-ADB9ThEc.css"])))=>i.map(i=>d[i]); +import{i as e,r as t,s as n}from"./useRouter-ByJ6_rwb.js";import{A as r,C as i,M as a,S as o,T as s,_ as c,a as l,c as u,d,f,i as p,l as m,m as h,n as g,o as _,p as v,r as y,tt as b,u as x,x as S,y as C}from"./brand-DUaZkIz1.js";import{n as w,t as T}from"./preload-helper-DJZNfKNH.js";import{t as E}from"./Tooltip-B3r3s_B9.js";import{a as D,c as O,d as k,l as A,n as j,r as M,t as N,u as P}from"./dashboard-change-chips-DKNHrHOk.js";import{B as ee,G as F,H as I,K as L,R,U as z,V as te,W as ne,Yt as B,z as re}from"./index-m8tRkNwz.js";var V=n(e(),1),H=t(),ie=[`borderBottomWidth`,`borderLeftWidth`,`borderRightWidth`,`borderTopWidth`,`boxSizing`,`fontFamily`,`fontSize`,`fontStyle`,`fontWeight`,`letterSpacing`,`lineHeight`,`paddingBottom`,`paddingLeft`,`paddingRight`,`paddingTop`,`tabSize`,`textIndent`,`textRendering`,`textTransform`,`width`,`wordBreak`,`wordSpacing`,`scrollbarGutter`],U={"min-height":`0`,"max-height":`none`,height:`0`,visibility:`hidden`,overflow:`hidden`,position:`absolute`,"z-index":`-1000`,top:`0`,right:`0`,display:`block`};function W(e){Object.keys(U).forEach(t=>{e.style.setProperty(t,U[t],`important`)})}function ae(e){let t=window.getComputedStyle(e);if(t===null)return null;let n={};for(let e of ie)n[e]=t[e];return n.boxSizing===``?null:{sizingStyle:n,paddingSize:parseFloat(n.paddingBottom)+parseFloat(n.paddingTop),borderSize:parseFloat(n.borderBottomWidth)+parseFloat(n.borderTopWidth)}}var G=null;function oe(e,t,n=1,r=1/0){G||(G=document.createElement(`textarea`),G.setAttribute(`tabindex`,`-1`),G.setAttribute(`aria-hidden`,`true`),G.setAttribute(`aria-label`,`autosize measurement`),W(G)),G.parentNode===null&&document.body.appendChild(G);let{paddingSize:i,borderSize:a,sizingStyle:o}=e,{boxSizing:s}=o;Object.keys(o).forEach(e=>{G.style[e]=o[e]}),W(G),G.value=t;let c=s===`border-box`?G.scrollHeight+a:G.scrollHeight-i;G.value=t,c=s===`border-box`?G.scrollHeight+a:G.scrollHeight-i,G.value=`x`;let l=G.scrollHeight-i,u=l*n;s===`border-box`&&(u=u+i+a),c=Math.max(u,c);let d=l*r;return s===`border-box`&&(d=d+i+a),c=Math.min(d,c),[c,l]}function se({maxRows:e,minRows:t,onChange:n,ref:r,...i}){let a=i.value!==void 0,o=(0,V.useRef)(null),s=b(o,r),c=(0,V.useRef)(0),l=(0,V.useRef)(0),u=()=>{let n=o.current;if(!n)return;let r=ae(n);if(!r)return;let[i]=oe(r,n.value||n.placeholder||`x`,t,e);c.current!==i&&(c.current=i,n.style.setProperty(`height`,`${i}px`,`important`))},d=(0,V.useEffectEvent)(u),f=e=>{a||u(),n?.(e)};return(0,V.useLayoutEffect)(u),(0,V.useEffect)(()=>{let e=()=>u();return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]),(0,V.useEffect)(()=>{let e=o.current;if(!e||typeof ResizeObserver>`u`)return;l.current=e.offsetWidth;let t=0,n=new ResizeObserver(()=>{o.current&&o.current.offsetWidth!==l.current&&(l.current=o.current.offsetWidth,cancelAnimationFrame(t),t=requestAnimationFrame(d))});return n.observe(e),()=>{cancelAnimationFrame(t),n.disconnect()}},[]),(0,V.useEffect)(()=>{let e=()=>u();return document.fonts.addEventListener(`loadingdone`,e),()=>document.fonts.removeEventListener(`loadingdone`,e)},[]),(0,V.useEffect)(()=>{let e=e=>{if(o.current?.form===e.target&&!a){let e=o.current.value;requestAnimationFrame(()=>{o.current&&e!==o.current.value&&u()})}};return document.body.addEventListener(`reset`,e),()=>document.body.removeEventListener(`reset`,e)},[a]),(0,H.jsx)(`textarea`,{rows:t,...i,onChange:f,ref:s})}var K=s(e=>{let{autosize:t,maxRows:n,minRows:r,__staticSelector:i,resize:o,bottomSection:s,bottomSectionProps:c,...l}=a([`Input`,`InputWrapper`,`Textarea`],null,e),u=t&&k()!==`test`,d=u?{maxRows:n,minRows:r}:{};return(0,H.jsx)(h,{component:u?se:`textarea`,...l,__staticSelector:i||`Textarea`,__bottomSection:s,__bottomSectionProps:c,multiline:!0,"data-no-overflow":t&&n===void 0||void 0,__vars:{"--input-resize":o},...d})});K.classes=h.classes,K.displayName=`@mantine/core/Textarea`;var q={root:`m_d08caa0`},J=s(e=>{let t=a(`Typography`,null,e),{classNames:n,className:o,style:s,styles:c,unstyled:l,attributes:u,...d}=t,f=r({name:`Typography`,classes:q,props:t,className:o,style:s,classNames:n,styles:c,unstyled:l,attributes:u});return(0,H.jsx)(i,{...f(`root`),...d})});J.classes=q,J.displayName=`@mantine/core/Typography`;var ce=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M208.49,152.49l-72,72a12,12,0,0,1-17,0l-72-72a12,12,0,0,1,17-17L116,187V40a12,12,0,0,1,24,0V187l51.51-51.52a12,12,0,0,1,17,17Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M200,144l-72,72L56,144Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M207.39,140.94A8,8,0,0,0,200,136H136V40a8,8,0,0,0-16,0v96H56a8,8,0,0,0-5.66,13.66l72,72a8,8,0,0,0,11.32,0l72-72A8,8,0,0,0,207.39,140.94ZM128,204.69,75.31,152H180.69Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M205.66,149.66l-72,72a8,8,0,0,1-11.32,0l-72-72A8,8,0,0,1,56,136h64V40a8,8,0,0,1,16,0v96h64a8,8,0,0,1,5.66,13.66Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M204.24,148.24l-72,72a6,6,0,0,1-8.48,0l-72-72a6,6,0,0,1,8.48-8.48L122,201.51V40a6,6,0,0,1,12,0V201.51l61.76-61.75a6,6,0,0,1,8.48,8.48Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M205.66,149.66l-72,72a8,8,0,0,1-11.32,0l-72-72a8,8,0,0,1,11.32-11.32L120,196.69V40a8,8,0,0,1,16,0V196.69l58.34-58.35a8,8,0,0,1,11.32,11.32Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M202.83,146.83l-72,72a4,4,0,0,1-5.66,0l-72-72a4,4,0,0,1,5.66-5.66L124,206.34V40a4,4,0,0,1,8,0V206.34l65.17-65.17a4,4,0,0,1,5.66,5.66Z`}))]]),le=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M184.49,136.49l-80,80a12,12,0,0,1-17-17L159,128,87.51,56.49a12,12,0,1,1,17-17l80,80A12,12,0,0,1,184.49,136.49Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M176,128,96,208V48Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M181.66,122.34l-80-80A8,8,0,0,0,88,48V208a8,8,0,0,0,13.66,5.66l80-80A8,8,0,0,0,181.66,122.34ZM104,188.69V67.31L164.69,128Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M181.66,133.66l-80,80A8,8,0,0,1,88,208V48a8,8,0,0,1,13.66-5.66l80,80A8,8,0,0,1,181.66,133.66Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M180.24,132.24l-80,80a6,6,0,0,1-8.48-8.48L167.51,128,91.76,52.24a6,6,0,0,1,8.48-8.48l80,80A6,6,0,0,1,180.24,132.24Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M181.66,133.66l-80,80a8,8,0,0,1-11.32-11.32L164.69,128,90.34,53.66a8,8,0,0,1,11.32-11.32l80,80A8,8,0,0,1,181.66,133.66Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M178.83,130.83l-80,80a4,4,0,0,1-5.66-5.66L170.34,128,93.17,50.83a4,4,0,0,1,5.66-5.66l80,80A4,4,0,0,1,178.83,130.83Z`}))]]),ue=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M230.14,25.86a20,20,0,0,0-19.57-5.11l-.22.07L18.44,79a20,20,0,0,0-3.06,37.25L99,157l40.71,83.65a19.81,19.81,0,0,0,18,11.38c.57,0,1.15,0,1.73-.07A19.82,19.82,0,0,0,177,237.56L235.18,45.65a1.42,1.42,0,0,0,.07-.22A20,20,0,0,0,230.14,25.86ZM156.91,221.07l-34.37-70.64,46-45.95a12,12,0,0,0-17-17l-46,46L34.93,99.09,210,46Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M223.69,42.18l-58.22,192a8,8,0,0,1-14.92,1.25L108,148,20.58,105.45a8,8,0,0,1,1.25-14.92l192-58.22A8,8,0,0,1,223.69,42.18Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M227.32,28.68a16,16,0,0,0-15.66-4.08l-.15,0L19.57,82.84a16,16,0,0,0-2.49,29.8L102,154l41.3,84.87A15.86,15.86,0,0,0,157.74,248q.69,0,1.38-.06a15.88,15.88,0,0,0,14-11.51l58.2-191.94c0-.05,0-.1,0-.15A16,16,0,0,0,227.32,28.68ZM157.83,231.85l-.05.14,0-.07-40.06-82.3,48-48a8,8,0,0,0-11.31-11.31l-48,48L24.08,98.25l-.07,0,.14,0L216,40Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M231.4,44.34s0,.1,0,.15l-58.2,191.94a15.88,15.88,0,0,1-14,11.51q-.69.06-1.38.06a15.86,15.86,0,0,1-14.42-9.15L107,164.15a4,4,0,0,1,.77-4.58l57.92-57.92a8,8,0,0,0-11.31-11.31L96.43,148.26a4,4,0,0,1-4.58.77L17.08,112.64a16,16,0,0,1,2.49-29.8l191.94-58.2.15,0A16,16,0,0,1,231.4,44.34Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M225.88,30.12a13.83,13.83,0,0,0-13.7-3.58l-.11,0L20.14,84.77A14,14,0,0,0,18,110.85l85.56,41.64L145.12,238a13.87,13.87,0,0,0,12.61,8c.4,0,.81,0,1.21-.05a13.9,13.9,0,0,0,12.29-10.09l58.2-191.93,0-.11A13.83,13.83,0,0,0,225.88,30.12Zm-8,10.4L159.73,232.43l0,.11a2,2,0,0,1-3.76.26l-40.68-83.58,49-49a6,6,0,1,0-8.49-8.49l-49,49L23.15,100a2,2,0,0,1,.31-3.74l.11,0L215.48,38.08a1.94,1.94,0,0,1,1.92.52A2,2,0,0,1,217.92,40.52Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M227.32,28.68a16,16,0,0,0-15.66-4.08l-.15,0L19.57,82.84a16,16,0,0,0-2.49,29.8L102,154l41.3,84.87A15.86,15.86,0,0,0,157.74,248q.69,0,1.38-.06a15.88,15.88,0,0,0,14-11.51l58.2-191.94c0-.05,0-.1,0-.15A16,16,0,0,0,227.32,28.68ZM157.83,231.85l-.05.14,0-.07-40.06-82.3,48-48a8,8,0,0,0-11.31-11.31l-48,48L24.08,98.25l-.07,0,.14,0L216,40Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224.47,31.52a11.87,11.87,0,0,0-11.82-3L20.74,86.67a12,12,0,0,0-1.91,22.38L105,151l41.92,86.15A11.88,11.88,0,0,0,157.74,244c.34,0,.69,0,1,0a11.89,11.89,0,0,0,10.52-8.63l58.21-192,0-.08A11.85,11.85,0,0,0,224.47,31.52Zm-4.62,9.54-58.23,192a4,4,0,0,1-7.48.59l-41.3-84.86,50-50a4,4,0,1,0-5.66-5.66l-50,50-84.9-41.31a3.88,3.88,0,0,1-2.27-4,3.93,3.93,0,0,1,3-3.54L214.9,36.16A3.93,3.93,0,0,1,216,36a4,4,0,0,1,2.79,1.19A3.93,3.93,0,0,1,219.85,41.06Z`}))]]),de=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M200,36H56A20,20,0,0,0,36,56V200a20,20,0,0,0,20,20H200a20,20,0,0,0,20-20V56A20,20,0,0,0,200,36Zm-4,160H60V60H196Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M208,56V200a8,8,0,0,1-8,8H56a8,8,0,0,1-8-8V56a8,8,0,0,1,8-8H200A8,8,0,0,1,208,56Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M200,40H56A16,16,0,0,0,40,56V200a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V56A16,16,0,0,0,200,40Zm0,160H56V56H200V200Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,56V200a16,16,0,0,1-16,16H56a16,16,0,0,1-16-16V56A16,16,0,0,1,56,40H200A16,16,0,0,1,216,56Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M200,42H56A14,14,0,0,0,42,56V200a14,14,0,0,0,14,14H200a14,14,0,0,0,14-14V56A14,14,0,0,0,200,42Zm2,158a2,2,0,0,1-2,2H56a2,2,0,0,1-2-2V56a2,2,0,0,1,2-2H200a2,2,0,0,1,2,2Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M200,40H56A16,16,0,0,0,40,56V200a16,16,0,0,0,16,16H200a16,16,0,0,0,16-16V56A16,16,0,0,0,200,40Zm0,160H56V56H200V200Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M200,44H56A12,12,0,0,0,44,56V200a12,12,0,0,0,12,12H200a12,12,0,0,0,12-12V56A12,12,0,0,0,200,44Zm4,156a4,4,0,0,1-4,4H56a4,4,0,0,1-4-4V56a4,4,0,0,1,4-4H200a4,4,0,0,1,4,4Z`}))]]),Y=V.forwardRef((e,t)=>V.createElement(l,{ref:t,...e,weights:ce}));Y.displayName=`ArrowDownIcon`;var fe=Y,X=V.forwardRef((e,t)=>V.createElement(l,{ref:t,...e,weights:le}));X.displayName=`CaretRightIcon`;var pe=X,me=V.forwardRef((e,t)=>V.createElement(l,{ref:t,...e,weights:ue}));me.displayName=`PaperPlaneTiltIcon`;var he=me,ge=V.forwardRef((e,t)=>V.createElement(l,{ref:t,...e,weights:de}));ge.displayName=`StopIcon`;var _e=ge;function ve(e){return e.dashboard.panels.length===1?e.dashboard.panels[0].title:e.dashboard.name}function ye(e){if(!e||typeof e!=`object`||Array.isArray(e))throw Error(`Missing panel view`);let t=e;if(!t.view||![`preset`,`query`].includes(t.view.kind)||!/^[a-f0-9]{64}$/.test(t.view.key))throw Error(`Invalid panel view identity`);if(t.dashboard?.version!==1||!Array.isArray(t.dashboard.panels)||!t.dashboard.panels.length||t.dashboard.panels.length>40||!Array.isArray(t.results)||t.dashboard.panels.some(e=>!e||typeof e.id!=`string`||!e.id)||t.results.some(e=>!e||typeof e.id!=`string`))throw Error(`Invalid panel view`);let n=new Set(t.dashboard.panels.map(e=>e.id));if(n.size!==t.dashboard.panels.length||t.results.length!==n.size||new Set(t.results.map(e=>e.id)).size!==n.size||t.results.some(e=>!n.has(e.id)||![`ok`,`empty`,`error`].includes(e.status)))throw Error(`Panel results do not match the view`);if(t.vars!==void 0&&(!t.vars||typeof t.vars!=`object`||Array.isArray(t.vars)||Object.values(t.vars).some(e=>typeof e!=`string`&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`)))))throw Error(`Invalid panel variables`);if(t.trace!==void 0&&(!t.trace?.data||!Array.isArray(t.trace.data.spans)||!Array.isArray(t.trace.data.logs)||!Array.isArray(t.trace.data.services)))throw Error(`Invalid trace detail`);return t}var be=new WeakSet;function xe(e){if(!e||typeof e!=`object`||Array.isArray(e))return;if(be.has(e))return e;let t=e;if(Object.keys(t).sort().join(`,`)===`is_error,resource_uri,tool_input,tool_name,tool_result`&&t.resource_uri===`ui://fanout/panels.html`&&typeof t.tool_name==`string`&&t.tool_name&&typeof t.is_error==`boolean`&&t.tool_input&&typeof t.tool_input==`object`&&!Array.isArray(t.tool_input)){try{ye(t.tool_result)}catch{return}return be.add(t),t}}var Se=16,Ce=new Set([`ArrowUp`,`ArrowDown`,`PageUp`,`PageDown`,`Home`,`End`,` `]);function we(e){let t=(0,V.useRef)(null),n=(0,V.useRef)(null),r=(0,V.useRef)(null),i=(0,V.useRef)(!0),a=(0,V.useRef)(e),o=(0,V.useRef)(()=>{}),s=(0,V.useRef)(null),c=(0,V.useRef)(new Set),l=(0,V.useRef)(null),u=(0,V.useRef)(null),[d,f]=(0,V.useState)(!1),p=(0,V.useCallback)(()=>{let e=t.current,n=r.current?.lastElementChild,i=!e||!n||n.getBoundingClientRect().bottom>e.getBoundingClientRect().top+e.clientTop+e.clientHeight+1;f(!!e&&i&&e.scrollHeight-e.clientHeight-e.scrollTop>1)},[]),m=(0,V.useCallback)(()=>{let e=t.current;if(!e)return;let n=e.getBoundingClientRect().top+e.clientTop,r=[...e.querySelectorAll(`[data-chat-anchor]`)].find(e=>e.getBoundingClientRect().bottom>n);l.current=r?{node:r,top:r.getBoundingClientRect().top}:null},[]),h=(0,V.useCallback)((e,t)=>{e.scrollTop=t,u.current=e.scrollTop},[]),g=(0,V.useCallback)(()=>{let e=t.current;if(e){if(r.current){let t=n.current&&parseFloat(getComputedStyle(n.current).paddingBottom)||0;r.current.style.minHeight=`${Math.max(0,e.clientHeight-Se-t)}px`,i.current&&h(e,e.scrollTop+r.current.getBoundingClientRect().top-e.getBoundingClientRect().top-e.clientTop-Se)}if(!i.current){let t=l.current;t?.node.isConnected&&h(e,e.scrollTop+t.node.getBoundingClientRect().top-t.top),m()}p()}},[m,h,p]),_=(0,V.useCallback)(()=>{let e=t.current,i=n.current;if(!e||!i){s.current?.disconnect(),s.current=null,c.current.clear();return}s.current??=new ResizeObserver(g);let a=new Set([e,i,...i.querySelectorAll(`[data-chat-anchor]`)]);r.current&&a.add(r.current);for(let e of c.current)a.has(e)||s.current.unobserve(e);for(let e of a)c.current.has(e)||s.current.observe(e);c.current=a},[g]),v=(0,V.useCallback)(e=>{if(o.current(),t.current=e,u.current=null,l.current=null,i.current=!0,_(),!e)return;let n=!1,r=()=>{i.current=!1,m()},a=e=>{let t=e.target;!e.defaultPrevented&&Ce.has(e.key)&&(t instanceof HTMLElement&&(t.closest(`input, textarea, select, [contenteditable]`)||(e.key===` `?t.closest(`button`):t.closest(`[role=slider]`)))||r())},s=()=>{n=!0},c=()=>{n=!1},d=()=>{n&&e.scrollTop!==u.current&&r(),i.current||m(),p()};e.addEventListener(`scroll`,d,{passive:!0}),e.addEventListener(`wheel`,r,{passive:!0}),e.addEventListener(`touchmove`,r,{passive:!0}),e.addEventListener(`keydown`,a),e.addEventListener(`pointerdown`,s),window.addEventListener(`pointerup`,c),window.addEventListener(`pointercancel`,c),o.current=()=>{e.removeEventListener(`scroll`,d),e.removeEventListener(`wheel`,r),e.removeEventListener(`touchmove`,r),e.removeEventListener(`keydown`,a),e.removeEventListener(`pointerdown`,s),window.removeEventListener(`pointerup`,c),window.removeEventListener(`pointercancel`,c),o.current=()=>{}},g()},[g,m,_,p]),y=(0,V.useCallback)(e=>{n.current=e,_()},[_]),b=(0,V.useCallback)(e=>{r.current?.style.removeProperty(`min-height`),r.current=e,_()},[_]);return(0,V.useLayoutEffect)(()=>{a.current!==e&&(a.current=e,i.current=!0,l.current=null),_(),g()}),{scrollRef:v,contentRef:y,turnRef:b,showJump:d,jumpToLatest:(0,V.useCallback)(()=>{let e=t.current;e&&(e.focus({preventScroll:!0}),i.current=!1,h(e,e.scrollHeight),m(),p())},[m,h,p])}}function Te(e=1500){let[t,n]=(0,V.useState)(`idle`),r=(0,V.useRef)(null);(0,V.useEffect)(()=>()=>{r.current&&clearTimeout(r.current)},[]);function i(t){r.current&&clearTimeout(r.current),n(`idle`),(navigator.clipboard?navigator.clipboard.writeText(t):Promise.reject(Error(`clipboard unavailable`))).then(()=>n(`copied`),()=>n(`failed`)).finally(()=>{r.current=setTimeout(()=>n(`idle`),e)})}return{state:t,copy:i}}var Z=e=>`${(e/1e3).toFixed(1)} s`;function Ee({receipt:e,running:t=!1,activity:n=``,awaitingAnswer:r=!1}){let[i,a]=(0,V.useState)(!1),o=(0,V.useId)(),s=e.saved,l=s?.receipt.save_check,p=t=>Object.hasOwn(e.panel_titles,t)?e.panel_titles[t]:t,m=Object.values(e.stages).filter(e=>e.state===`complete`).length,h=[e.stages.schema.state===`complete`?`Read telemetry`:void 0,e.panel_count===void 0?void 0:`${e.panel_count} ${e.panel_count===1?`panel`:`panels`}`,l?.checked?`Checked in ${Z(l.elapsed_ms)}`:void 0,s?`Saved v${s.version}`:void 0].filter(Boolean).join(` · `)||`Building dashboard`,g=[...s?te(s.receipt):[],...new Map(e.corrections.map(e=>[e.panel_id,`Fixed ${e.title}`])).values()];return(0,H.jsx)(S,{"data-build-receipt":e.turn_id,"data-dashboard-result":s?.id,"data-chat-anchor":!0,withBorder:!0,radius:`md`,p:`sm`,children:(0,H.jsxs)(u,{gap:6,children:[(0,H.jsxs)(c,{gap:`xs`,justify:`space-between`,children:[(0,H.jsxs)(f,{size:`sm`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:[h,(0,H.jsxs)(f,{span:!0,c:`dimmed`,size:`xs`,children:[` · `,m,` stages complete`]})]}),(0,H.jsxs)(d,{component:`button`,variant:`subtle`,color:`gray`,size:`compact-xs`,"aria-expanded":i,"aria-controls":o,onClick:()=>a(e=>!e),children:[`Details`,g.length>4?` (+${g.length-4})`:``]})]}),t&&r&&(0,H.jsxs)(c,{gap:`xs`,"data-build-running":!0,children:[(0,H.jsx)(C,{type:`dots`,size:`sm`}),(0,H.jsx)(f,{c:`dimmed`,size:`sm`,children:n||`Analyzing your system`})]}),(0,H.jsx)(N,{labels:g.slice(0,4)}),e.explanations.map(e=>t?e.split(` · `).filter(e=>!e.endsWith(`: incomplete`)).join(` · `):e).filter(Boolean).map((e,t)=>(0,H.jsx)(f,{size:`xs`,c:`dimmed`,"data-receipt-attention":!0,children:e},t)),s&&(0,H.jsx)(d,{renderRoot:e=>(0,H.jsx)(w,{...e,to:`/dashboards/$dashboardId`,params:{dashboardId:s.id},search:{}}),variant:`subtle`,size:`compact-sm`,color:`gray`,style:{alignSelf:`flex-start`},children:`Open dashboard`}),(0,H.jsx)(P,{expanded:i,id:o,children:(0,H.jsxs)(u,{gap:4,children:[s&&(0,H.jsxs)(f,{size:`xs`,children:[s.label,` `,s.name,` · opens the current dashboard`]}),Object.entries(e.stages).map(([e,n])=>(0,H.jsxs)(f,{size:`xs`,c:`dimmed`,children:[z[e],`: `,t&&n.state===`incomplete`?`in progress`:n.state,n.elapsed_ms===void 0?``:` · ${Z(n.elapsed_ms)}`]},e)),e.save_attempts.map((e,t)=>e.state===`retried`&&(0,H.jsxs)(f,{size:`xs`,c:`dimmed`,children:[`Save attempt `,t+1,`: retried`]},e.call_id)),!!e.context_counts.deploys&&(0,H.jsxs)(f,{size:`xs`,children:[e.context_counts.deploys,` deploys observed`]}),!!e.context_counts.anomalies&&(0,H.jsxs)(f,{size:`xs`,children:[e.context_counts.anomalies,` anomalies observed`]}),e.panels.map(e=>(0,H.jsxs)(f,{size:`xs`,children:[`Preview · `,p(e.id),`: `,e.status,e.elapsed_ms===void 0?``:` · ${Z(e.elapsed_ms)}`]},e.id)),l&&(0,H.jsxs)(f,{size:`xs`,children:[`Save check: `,l.checked?`checked`:`incomplete`,` · `,Z(l.elapsed_ms)]}),l?.panels.map(e=>(0,H.jsxs)(f,{size:`xs`,children:[`Save · `,p(e.id),`: `,e.status,` · `,e.rows??0,` rows`,e.elapsed_ms===void 0?``:` · ${Z(e.elapsed_ms)}`]},e.id)),g.slice(4).map((e,t)=>(0,H.jsx)(f,{size:`xs`,children:e},t)),e.corrections.map((e,t)=>(0,H.jsxs)(f,{size:`xs`,children:[`Fixed `,e.title,`: `,e.message]},t))]})})]})})}var De=(0,V.lazy)(()=>T(()=>import(`./mcp-app-frame-BNA4_n4D.js`),__vite__mapDeps([0,1,2,3,4,5,6,7]))),Oe=e=>e.tool_result.view.kind===`preset`;function ke(e){let t=new Map,n=new Set,r=[],i=()=>{let e=new Map;for(let t of r){let n=t.content.tool_result.view.key;e.set(n,t)}let i=new Set([...e.values()].map(e=>e.id)),a=[...e.values()].some(e=>Oe(e.content)),o=r.filter(e=>i.has(e.id)).at(-1)?.id;for(let e of r)i.has(e.id)?t.set(e.id,{content:e.content,expanded:Oe(e.content)||!a&&e.id===o}):n.add(e.id);r=[]};for(let t of e)if(t.role===`user`&&i(),t.role===`activity`&&t.activityType===`mcp-app`){let e=xe(t.content);e&&r.push({id:t.id,content:e})}return i(),{views:t,duplicates:n}}function Ae(e,t){return Array.isArray(e)?e.flatMap(e=>{if(!L(e)||typeof e.message!=`string`)return[];let n=typeof e.path==`string`?/^panels\[(\d+)\](?:\.|$)/.exec(e.path)?.[1]:void 0,r=n===void 0?void 0:t?.[Number(n)];return[r&&!e.message.startsWith(r)?`${r}: ${e.message}`:e.message]}):[]}function je(e){let t=new Map,n=new Map,r=new Map,i=`unattributed`;for(let a of e){if(a.role===`user`&&(n.clear(),r.clear(),i=a.id),a.role===`assistant`){i=a.id;for(let e of a.toolCalls??[]){let t=[`create_dashboard`,`replace_dashboard`].includes(e.function.name)?ne(e.function.arguments)?.dashboard:void 0,r=L(t)&&Array.isArray(t.panels)?t.panels.map(e=>L(e)&&typeof e.title==`string`?e.title:``):void 0;n.set(e.id,{assistant:i,name:e.function.name,titles:r})}}if(a.role===`tool`){let e=ne(a.content);if(!a.error&&!e?.error&&e?.isError!==!0)continue;let o=n.get(a.toolCallId);if(o&&F.has(o.name)&&I(a))continue;let s=L(e?.error)?e?.error:void 0;if(s?.code===`no_data`||s?.code===`unknown_service`)continue;let c=o?.assistant??i,l=r.get(c)??a.id;r.set(c,l);let u=t.get(l)??[],d=typeof s?.message==`string`?s.message:typeof a.error==`string`&&a.error?a.error:`Could not complete this step. Try again.`,f=[`create_dashboard`,`edit_dashboard`,`replace_dashboard`].includes(o?.name??``)&&(s?.code===`invalid_spec`||s?.code===`dashboard_version_conflict`);u.push({name:R(o?.name??``),message:d,details:f?Ae(e?.problems,o?.titles):[],readOnly:s?.code===`answer_only`,rejected:f}),t.set(l,u)}}return t}function Me({failures:e}){let[t,n]=(0,V.useState)({rejected:!1,failed:!1}),r=e.filter(e=>e.rejected),a=e.filter(e=>!e.readOnly&&!e.rejected),s=[{key:`rejected`,items:r,label:`${r.length} ${r.length===1?`draft`:`drafts`} rejected`},{key:`failed`,items:a,label:`${a.length} ${a.length===1?`step`:`steps`} failed`}];return(0,H.jsxs)(i,{"data-chat-anchor":!0,children:[e.some(e=>e.readOnly)&&(0,H.jsx)(f,{size:`sm`,c:`dimmed`,children:`Not saved: Explain is read-only`}),s.map(({key:e,items:r,label:a})=>r.length>0&&(0,H.jsxs)(i,{children:[(0,H.jsxs)(o,{className:`chat-app-toggle`,"aria-expanded":t[e],onClick:()=>n(t=>({...t,[e]:!t[e]})),style:{color:`var(--mantine-color-dimmed)`},children:[(0,H.jsx)(`span`,{className:`chat-app-chevron`,"aria-hidden":`true`,children:t[e]?(0,H.jsx)(O,{size:14}):(0,H.jsx)(pe,{size:14})}),(0,H.jsx)(`span`,{className:`chat-app-summary`,children:a})]}),t[e]&&(0,H.jsx)(u,{gap:`xs`,pl:`md`,children:r.flatMap((e,t)=>(e.details.length?e.details:[`${e.name}: ${e.message}`]).map((e,n)=>(0,H.jsx)(f,{size:`sm`,c:`dimmed`,style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`},children:e},`${t}-${n}`)))})]},e))]})}function Ne({view:e}){let[t,n]=(0,V.useState)(e.expanded);(0,V.useEffect)(()=>n(e.expanded),[e.expanded]);let r=e.content.tool_result,i=ve(r),a=[...new Set(r.dashboard.panels.map(e=>e.viz===`timeseries`?`time series`:e.viz.replaceAll(`_`,` `)))].join(`, `),s=r.results.reduce((e,t)=>e+(t.frame?.rows??0),0),c=new Map;for(let e of r.results)e.status!==`ok`&&c.set(e.status,(c.get(e.status)??0)+1);let l=r.dashboard.panels.length>1?Array.from(c,([e,t])=>`${t} ${e}`).join(` · `):c.size?[...c.keys()].join(`, `):`${s} ${s===1?`row`:`rows`}`;return(0,H.jsxs)(S,{"data-chat-app":!0,"data-chat-anchor":!0,withBorder:!0,radius:`lg`,style:{overflow:`hidden`},children:[(0,H.jsxs)(o,{className:`chat-app-toggle`,"aria-expanded":t,onClick:()=>n(e=>!e),children:[(0,H.jsx)(`span`,{className:`chat-app-chevron`,"aria-hidden":`true`,children:t?(0,H.jsx)(O,{size:14}):(0,H.jsx)(pe,{size:14})}),(0,H.jsx)(`span`,{className:`chat-app-summary`,children:[i,a,l].filter(Boolean).join(` · `)})]}),t&&(0,H.jsx)(V.Suspense,{fallback:(0,H.jsx)(x,{mih:180,children:(0,H.jsx)(C,{size:`sm`})}),children:(0,H.jsx)(De,{content:e.content})})]})}var Pe=[`Summarize system health for the last hour`,`Find the source of elevated errors`,`Map the current service dependencies`,`Show the slowest endpoints`];function Fe(){let{agentAvailable:e,messages:t,messageTimes:n,ready:r,running:a,activity:o,stopped:s,error:l,threadMissing:p,send:h,retry:g,reloadThread:y,newThread:b}=ee(),w=re(t),T=t.filter(e=>e.role===`user`).at(-1)?.id,{scrollRef:D,contentRef:O,turnRef:k,showJump:A,jumpToLatest:j}=we(T);if(!e)return(0,H.jsx)(m,{size:`sm`,py:96,children:(0,H.jsx)(S,{withBorder:!0,radius:`lg`,p:{base:`xl`,sm:40},children:(0,H.jsxs)(u,{gap:`md`,children:[(0,H.jsx)(f,{c:`brand`,fw:700,size:`xs`,tt:`uppercase`,lts:`0.12em`,children:`Optional capability`}),(0,H.jsx)(_,{order:1,fz:28,children:`Chat is not configured`}),(0,H.jsx)(f,{c:`dimmed`,children:`Add an AI provider key to enable chat. Telemetry ingest, dashboards, traces, logs, and metrics remain available without it.`}),(0,H.jsx)(d,{component:`a`,href:`/dashboards`,variant:`light`,mt:`sm`,children:`Open dashboards`})]})})});let M=ke(t),N=je(t),P=t.filter(e=>M.duplicates.has(e.id)?!1:e.role===`tool`?N.has(e.id):e.role===`assistant`?!e.toolCalls?.length&&typeof e.content==`string`&&e.content.trim().length>0:e.role===`activity`?e.activityType===`mcp-app`||e.activityType===`agent-outcome`:e.role===`user`),F=t.findIndex(e=>e.id===T),I=t.slice(F+1).some(e=>e.role===`assistant`&&!e.toolCalls?.length&&typeof e.content==`string`&&e.content.length>0),L=t.slice(F+1).filter(e=>e.role===`assistant`&&!e.toolCalls?.length&&typeof e.content==`string`&&e.content.trim().length>0).at(-1),R=[];for(let e of P)(e.role===`user`||R.length===0)&&R.push({id:e.id,messages:[]}),R.at(-1).messages.push(e);R.length===0&&R.push({id:`draft`,messages:[]});let z=e=>N.has(e.id)?(0,H.jsx)(Me,{failures:N.get(e.id)},e.id):(0,H.jsxs)(i,{children:[(0,H.jsx)(Re,{message:e,time:n[e.id],appView:M.views.get(e.id)}),w.has(e.id)&&(0,H.jsx)(i,{mt:`sm`,children:(0,H.jsx)(Ee,{receipt:w.get(e.id),running:a&&e.id===T,awaitingAnswer:!I,activity:o})})]},e.id);return(0,H.jsxs)(i,{className:`chat-pane`,children:[(0,H.jsxs)(i,{className:`chat-viewport`,children:[(0,H.jsx)(i,{className:`chat-scroll`,ref:D,tabIndex:0,role:`log`,"aria-label":`Conversation`,children:(0,H.jsxs)(m,{size:880,px:{base:`md`,sm:`xl`},py:`lg`,ref:O,children:[p&&(0,H.jsx)(v,{color:`warn`,radius:`lg`,title:`This chat no longer exists`,children:(0,H.jsxs)(c,{justify:`space-between`,children:[(0,H.jsx)(f,{size:`sm`,children:`It was deleted, or the link is wrong.`}),(0,H.jsx)(d,{size:`compact-sm`,variant:`light`,onClick:b,children:`New chat`})]})}),!p&&!r&&l&&(0,H.jsx)(Q,{message:l,onRetry:y,onNewThread:b}),!p&&!r&&!l&&(0,H.jsxs)(x,{mih:`40vh`,children:[(0,H.jsx)(C,{size:`sm`}),(0,H.jsx)(f,{c:`dimmed`,size:`sm`,ml:`sm`,children:`Loading chat`})]}),!p&&r&&(0,H.jsxs)(H.Fragment,{children:[P.length===0&&(0,H.jsx)(Le,{onSelect:h}),(0,H.jsx)(u,{gap:`lg`,children:R.map((e,t)=>(0,H.jsxs)(u,{gap:`lg`,ref:e.id===T?k:void 0,"data-chat-turn":e.id===T?T:void 0,children:[e.messages.filter(e=>e.id!==L?.id).map(z),t===R.length-1&&(0,H.jsxs)(H.Fragment,{children:[L&&(0,H.jsx)(i,{"data-answer-position":!0,children:(0,H.jsx)(Re,{message:L,time:n[L.id]})},`answer-${T??`draft`}`),a&&!I&&!w.has(T??``)&&(0,H.jsxs)(c,{gap:`xs`,role:`status`,children:[(0,H.jsx)(C,{type:`dots`,size:`sm`}),(0,H.jsx)(f,{c:`dimmed`,size:`sm`,children:o||`Analyzing your system`})]}),s&&(0,H.jsx)(f,{c:`dimmed`,size:`sm`,children:`Stopped`}),l&&(0,H.jsx)(Q,{message:l,onRetry:g})]})]},e.id))})]})]})}),A&&(0,H.jsx)(E,{label:`Jump to latest`,children:(0,H.jsx)(B,{className:`chat-jump`,variant:`default`,size:36,radius:`xl`,"aria-label":`Jump to latest`,onClick:j,children:(0,H.jsx)(fe,{size:18,"aria-hidden":`true`})})})]}),!p&&(0,H.jsx)(Ie,{})]})}function Q({message:e,onRetry:t,onNewThread:n}){return(0,H.jsx)(v,{color:`bad`,radius:`lg`,title:`Something went wrong`,children:(0,H.jsxs)(c,{justify:`space-between`,gap:`sm`,wrap:`nowrap`,children:[(0,H.jsx)(f,{size:`sm`,children:e}),(0,H.jsxs)(c,{gap:`xs`,wrap:`nowrap`,children:[n&&(0,H.jsx)(d,{size:`compact-sm`,variant:`subtle`,color:`bad`,onClick:n,children:`New chat`}),(0,H.jsx)(d,{size:`compact-sm`,variant:`light`,color:`bad`,onClick:t,children:`Retry`})]})]})})}function Ie(){let{input:e,setInput:t,inputRef:n,submit:r,send:a,stop:o,ready:s,running:l}=ee();return(0,H.jsx)(i,{className:`chat-composer`,children:(0,H.jsxs)(m,{size:880,px:{base:`md`,sm:`xl`},children:[(0,H.jsx)(S,{component:`form`,onSubmit:r,className:`chat-composer-field`,withBorder:!0,radius:24,py:6,pl:`lg`,pr:6,children:(0,H.jsxs)(c,{align:`flex-end`,gap:`xs`,wrap:`nowrap`,children:[(0,H.jsx)(K,{ref:n,"aria-label":`Message Fanout`,value:e,onChange:e=>t(e.currentTarget.value),onKeyDown:t=>{t.key===`Enter`&&!t.shiftKey&&(t.preventDefault(),a(e))},placeholder:l?`Fanout is working…`:`Ask about health, errors, or latency…`,disabled:!s,autosize:!0,minRows:1,maxRows:8,variant:`unstyled`,flex:1}),l?(0,H.jsx)(E,{label:`Stop`,children:(0,H.jsx)(B,{type:`button`,variant:`default`,size:40,radius:`xl`,"aria-label":`Stop`,onClick:o,children:(0,H.jsx)(_e,{size:16,weight:`fill`})})}):(0,H.jsx)(B,{type:`submit`,variant:`filled`,size:40,radius:`xl`,disabled:!e.trim()||!s,"aria-label":`Send message`,children:(0,H.jsx)(he,{size:17,weight:`fill`})})]})}),(0,H.jsx)(f,{c:`dimmed`,size:`xs`,ta:`center`,mt:6,children:`Enter to send, Shift+Enter for a new line`})]})})}function Le({onSelect:e}){return(0,H.jsxs)(u,{align:`center`,gap:`md`,pt:{base:32,sm:88},pb:`xl`,ta:`center`,children:[(0,H.jsx)(g,{size:`large`}),(0,H.jsx)(_,{order:1,fz:24,fw:500,lh:1.25,maw:560,children:`What do you want to know about your system?`}),(0,H.jsx)(c,{justify:`center`,gap:`xs`,mt:`xs`,maw:720,children:Pe.map(t=>(0,H.jsx)(d,{variant:`default`,size:`sm`,radius:`xl`,onClick:()=>void e(t),children:t},t))})]})}function Re({message:e,time:t,appView:n}){if(e.role===`activity`)return e.activityType===`agent-outcome`&&e.content&&typeof e.content==`object`&&`message`in e.content&&typeof e.content.message==`string`?`status`in e.content&&e.content.status===`stopped`?(0,H.jsx)(f,{c:`dimmed`,size:`sm`,"data-chat-anchor":!0,children:e.content.message}):(0,H.jsx)(v,{color:`bad`,title:`Something went wrong`,"data-chat-anchor":!0,children:e.content.message}):e.activityType===`mcp-app`?n?(0,H.jsx)(Ne,{view:n}):(0,H.jsx)(v,{color:`bad`,"data-chat-anchor":!0,children:`This view could not be loaded. Please try again.`}):null;if(e.role===`assistant`&&e.toolCalls?.length)return null;let r=typeof e.content==`string`?e.content:JSON.stringify(e.content);if(!r&&e.role===`assistant`)return null;let a=e.role===`user`,o=t?new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}).format(new Date(t)):``;return(0,H.jsxs)(i,{className:`chat-message`,"data-chat-anchor":!0,"data-role":a?`user`:`assistant`,children:[a?(0,H.jsx)(S,{radius:`lg`,px:`md`,py:`sm`,bg:`var(--mantine-color-brand-light)`,maw:`70%`,ml:`auto`,w:`fit-content`,children:(0,H.jsx)(f,{style:{whiteSpace:`pre-wrap`},children:r})}):(0,H.jsx)(J,{className:`chat-markdown`,children:(0,H.jsx)(M,{remarkPlugins:[j],components:Be,children:r})}),(o||!a)&&(0,H.jsxs)(c,{className:`chat-message-meta`,gap:6,justify:a?`flex-end`:`flex-start`,mt:4,h:24,children:[o&&t&&(0,H.jsx)(f,{c:`dimmed`,size:`xs`,title:D(t),children:o}),!a&&(0,H.jsx)(ze,{text:r,label:`Copy message`})]})]})}function ze({text:e,label:t}){let{state:n,copy:r}=Te();return(0,H.jsx)(E,{label:n===`failed`?`Could not copy`:n===`copied`?`Copied`:t,children:(0,H.jsx)(B,{variant:`subtle`,color:`gray`,size:`sm`,"aria-label":t,"data-state":n===`idle`?void 0:n,onClick:()=>r(e),children:n===`copied`?(0,H.jsx)(p,{size:13,weight:`bold`}):(0,H.jsx)(y,{size:13})})})}var Be={table:({children:e})=>(0,H.jsx)(i,{className:`chat-table`,children:(0,H.jsx)(A,{striped:!0,highlightOnHover:!0,withTableBorder:!0,verticalSpacing:`xs`,fz:`sm`,children:e})}),thead:({children:e})=>(0,H.jsx)(A.Thead,{children:e}),tbody:({children:e})=>(0,H.jsx)(A.Tbody,{children:e}),tr:({children:e})=>(0,H.jsx)(A.Tr,{children:e}),th:({children:e})=>(0,H.jsx)(A.Th,{children:e}),td:({children:e})=>(0,H.jsx)(A.Td,{children:e}),pre:({children:e})=>(0,H.jsx)(Ve,{children:e}),a:({href:e,children:t})=>(0,H.jsx)(`a`,{href:e,target:`_blank`,rel:`noopener noreferrer`,children:t})};function Ve({children:e}){let t=$(e);return(0,H.jsxs)(i,{className:`chat-code`,pos:`relative`,children:[(0,H.jsx)(i,{className:`chat-code-actions`,pos:`absolute`,top:6,right:6,children:(0,H.jsx)(ze,{text:t,label:`Copy code`})}),(0,H.jsx)(`pre`,{children:e})]})}function $(e){return typeof e==`string`?e:Array.isArray(e)?e.map($).join(``):e&&typeof e==`object`&&`props`in e?$(e.props.children):``}export{xe as n,Fe as t}; \ No newline at end of file diff --git a/internal/ui/dist/assets/chat._threadId-DMtKC6Qw.js b/internal/ui/dist/assets/chat._threadId-DMtKC6Qw.js deleted file mode 100644 index 1090e5ca..00000000 --- a/internal/ui/dist/assets/chat._threadId-DMtKC6Qw.js +++ /dev/null @@ -1 +0,0 @@ -import{t as e}from"./chat-CgHTI0Fx.js";var t=e;export{t as component}; \ No newline at end of file diff --git a/internal/ui/dist/assets/chat._threadId-DOzBCpD0.js b/internal/ui/dist/assets/chat._threadId-DOzBCpD0.js new file mode 100644 index 00000000..b63b6a33 --- /dev/null +++ b/internal/ui/dist/assets/chat._threadId-DOzBCpD0.js @@ -0,0 +1 @@ +import{t as e}from"./chat-D9q4mn0t.js";var t=e;export{t as component}; \ No newline at end of file diff --git a/internal/ui/dist/assets/chat.index-DMtKC6Qw.js b/internal/ui/dist/assets/chat.index-DMtKC6Qw.js deleted file mode 100644 index 1090e5ca..00000000 --- a/internal/ui/dist/assets/chat.index-DMtKC6Qw.js +++ /dev/null @@ -1 +0,0 @@ -import{t as e}from"./chat-CgHTI0Fx.js";var t=e;export{t as component}; \ No newline at end of file diff --git a/internal/ui/dist/assets/chat.index-DOzBCpD0.js b/internal/ui/dist/assets/chat.index-DOzBCpD0.js new file mode 100644 index 00000000..b63b6a33 --- /dev/null +++ b/internal/ui/dist/assets/chat.index-DOzBCpD0.js @@ -0,0 +1 @@ +import{t as e}from"./chat-D9q4mn0t.js";var t=e;export{t as component}; \ No newline at end of file diff --git a/internal/ui/dist/assets/dashboard-change-chips-BODDZoYU.js b/internal/ui/dist/assets/dashboard-change-chips-DKNHrHOk.js similarity index 99% rename from internal/ui/dist/assets/dashboard-change-chips-BODDZoYU.js rename to internal/ui/dist/assets/dashboard-change-chips-DKNHrHOk.js index caf5e46c..912fa466 100644 --- a/internal/ui/dist/assets/dashboard-change-chips-BODDZoYU.js +++ b/internal/ui/dist/assets/dashboard-change-chips-DKNHrHOk.js @@ -1,4 +1,4 @@ -import{a as e,i as t,o as n,r,s as i}from"./useRouter-ByJ6_rwb.js";import{A as a,C as o,K as s,M as c,P as l,Q as u,T as d,X as f,_ as p,_t as m,a as h,et as g,mt as _,rt as v,ut as y,z as b}from"./brand-DUaZkIz1.js";import{E as x,S,o as C}from"./Tooltip-B3r3s_B9.js";import{It as w}from"./index-BZ6fASDi.js";var T=i(t(),1),E=i(m(),1);function D(e){if(!e||typeof e==`string`)return 0;let t=e/36;return Math.round((4+15*t**.25+t/5)*10)}function O(e){return e.current?e.current.scrollHeight:`auto`}function k(e){return typeof e==`number`&&e>0}function ee({transitionDuration:e,transitionTimingFunction:t=`ease`,onTransitionEnd:n,onTransitionStart:r,expanded:i,keepMounted:a}){let o={height:0,overflow:`hidden`,...a?{}:{display:`none`}},s=(0,T.useEffectEvent)(()=>r?.()),c=(0,T.useEffectEvent)(()=>n?.()),l=(0,T.useRef)(null),[u,d]=(0,T.useState)(i?{}:o),[f,p]=(0,T.useState)(i?`entered`:`exited`),m=e=>{(0,E.flushSync)(()=>d(e))},h=e=>{m(t=>({...t,...e}))},_=n=>{let r=e??D(n);return{transition:`height ${r}ms ${t}, opacity ${r}ms ${t}`}},y=(0,T.useRef)(0);v(()=>{y.current+=1;let t=y.current,n=()=>y.current===t;e!==0&&s(),i?window.requestAnimationFrame(()=>{n()&&l.current&&((0,E.flushSync)(()=>p(`entering`)),h({willChange:`height`,display:`block`,overflow:`hidden`}),window.requestAnimationFrame(()=>{if(!n()||!l.current)return;let e=O(l);if(!k(e)){m({}),p(`entered`),c();return}h({..._(e),height:e})}))}):window.requestAnimationFrame(()=>{if(!n()||!l.current)return;(0,E.flushSync)(()=>p(`exiting`));let e=O(l);if(!k(e)){m(o),p(`exited`),c();return}h({..._(e),willChange:`height`,height:e}),window.requestAnimationFrame(()=>{n()&&l.current&&h({height:0,overflow:`hidden`})})})},[i]);let b=e=>{if(e.target===l.current&&e.propertyName===`height`){if(i){let e=O(l);e===u.height?m({}):h({height:e}),p(`entered`),c()}else u.height===0&&(m(o),p(`exited`),c())}};return{state:f,getCollapseProps:e=>({"aria-hidden":!i,inert:!i,ref:g(l,e?.ref),onTransitionEnd:b,style:{boxSizing:`border-box`,...e?.style,...u}})}}function te(e){if(!e||typeof e==`string`)return 0;let t=e/36;return Math.round((4+15*t**.25+t/5)*10)}function A(e){return e.current?e.current.scrollWidth:`auto`}function j({transitionDuration:e,transitionTimingFunction:t=`ease`,onTransitionEnd:n,onTransitionStart:r,expanded:i,keepMounted:a}){let o={width:0,overflow:`hidden`,...a?{}:{display:`none`}},s=(0,T.useEffectEvent)(()=>r?.()),c=(0,T.useEffectEvent)(()=>n?.()),l=(0,T.useRef)(null),[u,d]=(0,T.useState)(i?{}:o),[f,p]=(0,T.useState)(i?`entered`:`exited`),m=e=>{(0,E.flushSync)(()=>d(e))},h=e=>{m(t=>({...t,...e}))},_=n=>{let r=e??te(n);return{transition:`width ${r}ms ${t}, opacity ${r}ms ${t}`}},y=(0,T.useRef)(0);v(()=>{y.current+=1;let t=y.current,n=()=>y.current===t;e!==0&&s(),i?window.requestAnimationFrame(()=>{n()&&l.current&&((0,E.flushSync)(()=>p(`entering`)),h({willChange:`width`,display:`block`,overflow:`hidden`}),window.requestAnimationFrame(()=>{if(!n()||!l.current)return;let e=A(l);if(!k(e)){m({}),p(`entered`),c();return}h({..._(e),width:e})}))}):window.requestAnimationFrame(()=>{if(!n()||!l.current)return;(0,E.flushSync)(()=>p(`exiting`));let e=A(l);if(!k(e)){m(o),p(`exited`),c();return}h({..._(e),willChange:`width`,width:e}),window.requestAnimationFrame(()=>{n()&&l.current&&h({width:0,overflow:`hidden`})})})},[i]);let b=e=>{if(e.target===l.current&&e.propertyName===`width`){if(i){let e=A(l);e===u.width?m({}):h({width:e}),p(`entered`),c()}else u.width===0&&(m(o),p(`exited`),c())}};return{state:f,getCollapseProps:e=>({"aria-hidden":!i,inert:!i,ref:g(l,e?.ref),onTransitionEnd:b,style:{boxSizing:`border-box`,...e?.style,...u}})}}function ne(){return`development`}var M=r(),N={transitionDuration:200,transitionTimingFunction:`ease`,animateOpacity:!0,orientation:`vertical`,keepMounted:!0,keepMountedMode:`activity`},re=d(e=>{let{children:t,expanded:n,transitionDuration:r,transitionTimingFunction:i,style:a,onTransitionEnd:s,onTransitionStart:d,animateOpacity:f,keepMounted:p,keepMountedMode:m,ref:h,orientation:g,..._}=c(`Collapse`,N,e),v=b(),y=l(),x=u(),C=y.respectReducedMotion&&x?0:r,w=(g===`horizontal`?j:ee)({expanded:n,transitionDuration:C,transitionTimingFunction:i,onTransitionEnd:s,onTransitionStart:d,keepMounted:!1});if(C===0)return p===!0&&(m===`display-none`||v!==`test`)?m===`display-none`?(0,M.jsx)(o,{..._,style:{...S(a,y),...n?{}:{display:`none`}},ref:h,children:t}):(0,M.jsx)(T.Activity,{mode:n?`visible`:`hidden`,children:(0,M.jsx)(o,{..._,style:a,ref:h,children:t})}):n?(0,M.jsx)(o,{..._,style:a,ref:h,children:t}):null;let E=w.state===`exited`,D;return D=p===!1?E?null:t:p===!0?m===`display-none`?t:(0,M.jsx)(T.Activity,{mode:E?`hidden`:`visible`,children:t}):t,(0,M.jsx)(o,{..._,...w.getCollapseProps({style:{opacity:n||!f?1:0,transition:f?`opacity ${C}ms ${i}`:`none`,...S(a,y),...p&&m===`display-none`&&E?{display:`none`}:{}},ref:h}),children:D})});re.displayName=`@mantine/core/Collapse`;var[ie,ae]=x(`Table component was not found in the tree`),oe={table:`m_b23fa0ef`,th:`m_4e7aa4f3`,tr:`m_4e7aa4fd`,td:`m_4e7aa4ef`,tbody:`m_b2404537`,thead:`m_b242d975`,caption:`m_9e5a3ac7`,scrollContainer:`m_a100c15`,scrollContainerInner:`m_62259741`};function se(e,t){if(!t)return;let n={};return t.columnBorder&&e.withColumnBorders&&(n[`data-with-column-border`]=!0),t.rowBorder&&e.withRowBorders&&(n[`data-with-row-border`]=!0),t.striped&&e.striped&&(n[`data-striped`]=e.striped),t.highlightOnHover&&e.highlightOnHover&&(n[`data-hover`]=!0),t.captionSide&&e.captionSide&&(n[`data-side`]=e.captionSide),t.stickyHeader&&e.stickyHeader&&(n[`data-sticky`]=!0),n}function ce(e,t){let n=`Table${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=d(r=>{let i=c(n,{},r),{classNames:a,className:s,style:l,styles:u,...d}=i,f=ae();return(0,M.jsx)(o,{component:e,...se(f,t),...f.getStyles(e,{className:s,classNames:a,style:l,styles:u,props:i}),...d})});return r.displayName=`@mantine/core/${n}`,r.classes=oe,r}var le=ce(`th`,{columnBorder:!0}),ue=ce(`td`,{columnBorder:!0}),de=ce(`tr`,{rowBorder:!0,striped:!0,highlightOnHover:!0}),fe=ce(`thead`,{stickyHeader:!0}),pe=ce(`tbody`),me=ce(`tfoot`),he=ce(`caption`,{captionSide:!0}),ge={type:`scrollarea`},_e=f((e,{minWidth:t,maxHeight:n,type:r})=>({scrollContainer:{"--table-min-width":_(t),"--table-max-height":_(n),"--table-overflow":r===`native`?`auto`:void 0}})),ve=d(e=>{let t=c(`TableScrollContainer`,ge,e),{classNames:n,className:r,style:i,styles:s,unstyled:l,vars:u,children:d,minWidth:f,maxHeight:p,type:m,scrollAreaProps:h,attributes:g,..._}=t,v=a({name:`TableScrollContainer`,classes:oe,props:t,className:r,style:i,classNames:n,styles:s,unstyled:l,attributes:g,vars:u,varsResolver:_e,rootSelector:`scrollContainer`});return(0,M.jsx)(o,{component:m===`scrollarea`?C:`div`,...m===`scrollarea`?p?{offsetScrollbars:`xy`,...h}:{offsetScrollbars:`x`,...h}:{},...v(`scrollContainer`),..._,children:(0,M.jsx)(`div`,{...v(`scrollContainerInner`),children:d})})});ve.classes=oe,ve.varsResolver=_e,ve.displayName=`@mantine/core/TableScrollContainer`;function ye({data:e}){return(0,M.jsxs)(M.Fragment,{children:[e.caption&&(0,M.jsx)(he,{children:e.caption}),e.head&&(0,M.jsx)(fe,{children:(0,M.jsx)(de,{children:e.head.map((e,t)=>(0,M.jsx)(le,{children:e},t))})}),e.body&&(0,M.jsx)(pe,{children:e.body.map((e,t)=>(0,M.jsx)(de,{children:e.map((e,t)=>(0,M.jsx)(ue,{children:e},t))},t))}),e.foot&&(0,M.jsx)(me,{children:(0,M.jsx)(de,{children:e.foot.map((e,t)=>(0,M.jsx)(le,{children:e},t))})})]})}ye.displayName=`@mantine/core/TableDataRenderer`;var be={withRowBorders:!0,verticalSpacing:7},xe=f((e,{layout:t,captionSide:n,horizontalSpacing:r,verticalSpacing:i,borderColor:a,stripedColor:o,highlightOnHoverColor:c,striped:l,highlightOnHover:u,stickyHeaderOffset:d,stickyHeader:f})=>({table:{"--table-layout":t,"--table-caption-side":n,"--table-horizontal-spacing":y(r),"--table-vertical-spacing":y(i),"--table-border-color":a?s(a,e):void 0,"--table-striped-color":l&&o?s(o,e):void 0,"--table-highlight-on-hover-color":u&&c?s(c,e):void 0,"--table-sticky-header-offset":f?_(d):void 0}})),P=d(e=>{let t=c(`Table`,be,e),{classNames:n,className:r,style:i,styles:s,unstyled:l,vars:u,horizontalSpacing:d,verticalSpacing:f,captionSide:p,stripedColor:m,highlightOnHoverColor:h,striped:g,highlightOnHover:_,withColumnBorders:v,withRowBorders:y,withTableBorder:b,borderColor:x,layout:S,data:C,children:w,stickyHeader:E,stickyHeaderOffset:D,mod:O,tabularNums:k,attributes:ee,...te}=t,A=a({name:`Table`,props:t,className:r,style:i,classes:oe,classNames:n,styles:s,unstyled:l,attributes:ee,rootSelector:`table`,vars:u,varsResolver:xe,stable:!0}),j=g===!0?`odd`:g||void 0,ne=p||`bottom`,N=(0,T.useMemo)(()=>({getStyles:A,stickyHeader:E,striped:j,highlightOnHover:_,withColumnBorders:v,withRowBorders:y,captionSide:ne}),[A,E,j,_,v,y,ne]);return(0,M.jsx)(ie,{value:N,children:(0,M.jsx)(o,{component:`table`,mod:[{withTableBorder:b,tabularNums:k},O],...A(`table`),...te,children:w||!!C&&(0,M.jsx)(ye,{data:C})})})});P.classes=oe,P.varsResolver=xe,P.displayName=`@mantine/core/Table`,P.Td=ue,P.Th=le,P.Tr=de,P.Thead=fe,P.Tbody=pe,P.Tfoot=me,P.Caption=he,P.ScrollContainer=ve,P.DataRenderer=ye;var Se=new Map([[`bold`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M216.49,104.49l-80,80a12,12,0,0,1-17,0l-80-80a12,12,0,0,1,17-17L128,159l71.51-71.52a12,12,0,0,1,17,17Z`}))],[`duotone`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M208,96l-80,80L48,96Z`,opacity:`0.2`}),T.createElement(`path`,{d:`M215.39,92.94A8,8,0,0,0,208,88H48a8,8,0,0,0-5.66,13.66l80,80a8,8,0,0,0,11.32,0l80-80A8,8,0,0,0,215.39,92.94ZM128,164.69,67.31,104H188.69Z`}))],[`fill`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M213.66,101.66l-80,80a8,8,0,0,1-11.32,0l-80-80A8,8,0,0,1,48,88H208a8,8,0,0,1,5.66,13.66Z`}))],[`light`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M212.24,100.24l-80,80a6,6,0,0,1-8.48,0l-80-80a6,6,0,0,1,8.48-8.48L128,167.51l75.76-75.75a6,6,0,0,1,8.48,8.48Z`}))],[`regular`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M213.66,101.66l-80,80a8,8,0,0,1-11.32,0l-80-80A8,8,0,0,1,53.66,90.34L128,164.69l74.34-74.35a8,8,0,0,1,11.32,11.32Z`}))],[`thin`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M210.83,98.83l-80,80a4,4,0,0,1-5.66,0l-80-80a4,4,0,0,1,5.66-5.66L128,170.34l77.17-77.17a4,4,0,1,1,5.66,5.66Z`}))]]),Ce=T.forwardRef((e,t)=>T.createElement(h,{ref:t,...e,weights:Se}));Ce.displayName=`CaretDownIcon`;var we=Ce,Te=new Intl.NumberFormat(void 0,{maximumFractionDigits:0});function Ee(e){return Number.isFinite(e)?e>0&&e<1e-4?`<0.01%`:`${(e*100).toFixed(e>=.1?1:2)}%`:`—`}function De(e){if(!Number.isFinite(e))return`—`;if(e<0)return`-${De(-e)}`;if(e===0)return`0ms`;if(e<.01)return`<0.01ms`;if(e<1)return`${e.toFixed(2)}ms`;if(Math.round(e*10)/10<100)return`${e.toFixed(1)}ms`;if(Math.round(e)<1e3)return`${Math.round(e)}ms`;let t=Math.round(e/100)/10;if(t<10)return`${(e/1e3).toFixed(2)}s`;if(t<60)return`${t.toFixed(1)}s`;let n=Math.round(e/1e3),r=Math.floor(n/60),i=n%60;if(r<60)return i===0?`${r}m`:`${r}m ${i}s`;let a=Math.floor(r/60),o=r%60;return o===0?`${a}h`:`${a}h ${o}m`}function Oe(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.valueOf())?String(e):t.toLocaleString([],{year:`numeric`,month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`})}function ke(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var Ae=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,je=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Me={};function Ne(e,t){return((t||Me).jsx?je:Ae).test(e)}var Pe=/[ \t\n\f\r]/g;function Fe(e){return typeof e==`object`?e.type===`text`&&Ie(e.value):Ie(e)}function Ie(e){return e.replace(Pe,``)===``}var Le=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};Le.prototype.normal={},Le.prototype.property={},Le.prototype.space=void 0;function Re(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new Le(n,r,t)}function ze(e){return e.toLowerCase()}var F=class{constructor(e,t){this.attribute=t,this.property=e}};F.prototype.attribute=``,F.prototype.booleanish=!1,F.prototype.boolean=!1,F.prototype.commaOrSpaceSeparated=!1,F.prototype.commaSeparated=!1,F.prototype.defined=!1,F.prototype.mustUseProperty=!1,F.prototype.number=!1,F.prototype.overloadedBoolean=!1,F.prototype.property=``,F.prototype.spaceSeparated=!1,F.prototype.space=void 0;var Be=n({boolean:()=>I,booleanish:()=>L,commaOrSpaceSeparated:()=>B,commaSeparated:()=>Ue,number:()=>R,overloadedBoolean:()=>He,spaceSeparated:()=>z}),Ve=0,I=We(),L=We(),He=We(),R=We(),z=We(),Ue=We(),B=We();function We(){return 2**++Ve}var Ge=Object.keys(Be),Ke=class extends F{constructor(e,t,n,r){let i=-1;if(super(e,t),qe(this,`space`,r),typeof n==`number`)for(;++i4&&n.slice(0,4)===`data`&&ot.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(at,lt);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!at.test(e)){let n=e.replace(it,ct);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=Ke}return new i(r,t)}function ct(e){return`-`+e.toLowerCase()}function lt(e){return e.charAt(1).toUpperCase()}var ut=Re([Ye,Qe,et,tt,nt],`html`),dt=Re([Ye,$e,et,tt,nt],`svg`);function ft(e){return e.join(` `).trim()}var pt=e(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g;function u(e,t){if(typeof e!=`string`)throw TypeError(`First argument must be a string`);if(!e)return[];t||={};var l=1,u=1;function f(e){var t=e.match(r);t&&(l+=t.length);var n=e.lastIndexOf(` +import{a as e,i as t,o as n,r,s as i}from"./useRouter-ByJ6_rwb.js";import{A as a,C as o,K as s,M as c,P as l,Q as u,T as d,X as f,_ as p,_t as m,a as h,et as g,mt as _,rt as v,ut as y,z as b}from"./brand-DUaZkIz1.js";import{E as x,S,o as C}from"./Tooltip-B3r3s_B9.js";import{Kt as w}from"./index-m8tRkNwz.js";var T=i(t(),1),E=i(m(),1);function D(e){if(!e||typeof e==`string`)return 0;let t=e/36;return Math.round((4+15*t**.25+t/5)*10)}function O(e){return e.current?e.current.scrollHeight:`auto`}function k(e){return typeof e==`number`&&e>0}function ee({transitionDuration:e,transitionTimingFunction:t=`ease`,onTransitionEnd:n,onTransitionStart:r,expanded:i,keepMounted:a}){let o={height:0,overflow:`hidden`,...a?{}:{display:`none`}},s=(0,T.useEffectEvent)(()=>r?.()),c=(0,T.useEffectEvent)(()=>n?.()),l=(0,T.useRef)(null),[u,d]=(0,T.useState)(i?{}:o),[f,p]=(0,T.useState)(i?`entered`:`exited`),m=e=>{(0,E.flushSync)(()=>d(e))},h=e=>{m(t=>({...t,...e}))},_=n=>{let r=e??D(n);return{transition:`height ${r}ms ${t}, opacity ${r}ms ${t}`}},y=(0,T.useRef)(0);v(()=>{y.current+=1;let t=y.current,n=()=>y.current===t;e!==0&&s(),i?window.requestAnimationFrame(()=>{n()&&l.current&&((0,E.flushSync)(()=>p(`entering`)),h({willChange:`height`,display:`block`,overflow:`hidden`}),window.requestAnimationFrame(()=>{if(!n()||!l.current)return;let e=O(l);if(!k(e)){m({}),p(`entered`),c();return}h({..._(e),height:e})}))}):window.requestAnimationFrame(()=>{if(!n()||!l.current)return;(0,E.flushSync)(()=>p(`exiting`));let e=O(l);if(!k(e)){m(o),p(`exited`),c();return}h({..._(e),willChange:`height`,height:e}),window.requestAnimationFrame(()=>{n()&&l.current&&h({height:0,overflow:`hidden`})})})},[i]);let b=e=>{if(e.target===l.current&&e.propertyName===`height`){if(i){let e=O(l);e===u.height?m({}):h({height:e}),p(`entered`),c()}else u.height===0&&(m(o),p(`exited`),c())}};return{state:f,getCollapseProps:e=>({"aria-hidden":!i,inert:!i,ref:g(l,e?.ref),onTransitionEnd:b,style:{boxSizing:`border-box`,...e?.style,...u}})}}function te(e){if(!e||typeof e==`string`)return 0;let t=e/36;return Math.round((4+15*t**.25+t/5)*10)}function A(e){return e.current?e.current.scrollWidth:`auto`}function j({transitionDuration:e,transitionTimingFunction:t=`ease`,onTransitionEnd:n,onTransitionStart:r,expanded:i,keepMounted:a}){let o={width:0,overflow:`hidden`,...a?{}:{display:`none`}},s=(0,T.useEffectEvent)(()=>r?.()),c=(0,T.useEffectEvent)(()=>n?.()),l=(0,T.useRef)(null),[u,d]=(0,T.useState)(i?{}:o),[f,p]=(0,T.useState)(i?`entered`:`exited`),m=e=>{(0,E.flushSync)(()=>d(e))},h=e=>{m(t=>({...t,...e}))},_=n=>{let r=e??te(n);return{transition:`width ${r}ms ${t}, opacity ${r}ms ${t}`}},y=(0,T.useRef)(0);v(()=>{y.current+=1;let t=y.current,n=()=>y.current===t;e!==0&&s(),i?window.requestAnimationFrame(()=>{n()&&l.current&&((0,E.flushSync)(()=>p(`entering`)),h({willChange:`width`,display:`block`,overflow:`hidden`}),window.requestAnimationFrame(()=>{if(!n()||!l.current)return;let e=A(l);if(!k(e)){m({}),p(`entered`),c();return}h({..._(e),width:e})}))}):window.requestAnimationFrame(()=>{if(!n()||!l.current)return;(0,E.flushSync)(()=>p(`exiting`));let e=A(l);if(!k(e)){m(o),p(`exited`),c();return}h({..._(e),willChange:`width`,width:e}),window.requestAnimationFrame(()=>{n()&&l.current&&h({width:0,overflow:`hidden`})})})},[i]);let b=e=>{if(e.target===l.current&&e.propertyName===`width`){if(i){let e=A(l);e===u.width?m({}):h({width:e}),p(`entered`),c()}else u.width===0&&(m(o),p(`exited`),c())}};return{state:f,getCollapseProps:e=>({"aria-hidden":!i,inert:!i,ref:g(l,e?.ref),onTransitionEnd:b,style:{boxSizing:`border-box`,...e?.style,...u}})}}function ne(){return`development`}var M=r(),N={transitionDuration:200,transitionTimingFunction:`ease`,animateOpacity:!0,orientation:`vertical`,keepMounted:!0,keepMountedMode:`activity`},re=d(e=>{let{children:t,expanded:n,transitionDuration:r,transitionTimingFunction:i,style:a,onTransitionEnd:s,onTransitionStart:d,animateOpacity:f,keepMounted:p,keepMountedMode:m,ref:h,orientation:g,..._}=c(`Collapse`,N,e),v=b(),y=l(),x=u(),C=y.respectReducedMotion&&x?0:r,w=(g===`horizontal`?j:ee)({expanded:n,transitionDuration:C,transitionTimingFunction:i,onTransitionEnd:s,onTransitionStart:d,keepMounted:!1});if(C===0)return p===!0&&(m===`display-none`||v!==`test`)?m===`display-none`?(0,M.jsx)(o,{..._,style:{...S(a,y),...n?{}:{display:`none`}},ref:h,children:t}):(0,M.jsx)(T.Activity,{mode:n?`visible`:`hidden`,children:(0,M.jsx)(o,{..._,style:a,ref:h,children:t})}):n?(0,M.jsx)(o,{..._,style:a,ref:h,children:t}):null;let E=w.state===`exited`,D;return D=p===!1?E?null:t:p===!0?m===`display-none`?t:(0,M.jsx)(T.Activity,{mode:E?`hidden`:`visible`,children:t}):t,(0,M.jsx)(o,{..._,...w.getCollapseProps({style:{opacity:n||!f?1:0,transition:f?`opacity ${C}ms ${i}`:`none`,...S(a,y),...p&&m===`display-none`&&E?{display:`none`}:{}},ref:h}),children:D})});re.displayName=`@mantine/core/Collapse`;var[ie,ae]=x(`Table component was not found in the tree`),oe={table:`m_b23fa0ef`,th:`m_4e7aa4f3`,tr:`m_4e7aa4fd`,td:`m_4e7aa4ef`,tbody:`m_b2404537`,thead:`m_b242d975`,caption:`m_9e5a3ac7`,scrollContainer:`m_a100c15`,scrollContainerInner:`m_62259741`};function se(e,t){if(!t)return;let n={};return t.columnBorder&&e.withColumnBorders&&(n[`data-with-column-border`]=!0),t.rowBorder&&e.withRowBorders&&(n[`data-with-row-border`]=!0),t.striped&&e.striped&&(n[`data-striped`]=e.striped),t.highlightOnHover&&e.highlightOnHover&&(n[`data-hover`]=!0),t.captionSide&&e.captionSide&&(n[`data-side`]=e.captionSide),t.stickyHeader&&e.stickyHeader&&(n[`data-sticky`]=!0),n}function ce(e,t){let n=`Table${e.charAt(0).toUpperCase()}${e.slice(1)}`,r=d(r=>{let i=c(n,{},r),{classNames:a,className:s,style:l,styles:u,...d}=i,f=ae();return(0,M.jsx)(o,{component:e,...se(f,t),...f.getStyles(e,{className:s,classNames:a,style:l,styles:u,props:i}),...d})});return r.displayName=`@mantine/core/${n}`,r.classes=oe,r}var le=ce(`th`,{columnBorder:!0}),ue=ce(`td`,{columnBorder:!0}),de=ce(`tr`,{rowBorder:!0,striped:!0,highlightOnHover:!0}),fe=ce(`thead`,{stickyHeader:!0}),pe=ce(`tbody`),me=ce(`tfoot`),he=ce(`caption`,{captionSide:!0}),ge={type:`scrollarea`},_e=f((e,{minWidth:t,maxHeight:n,type:r})=>({scrollContainer:{"--table-min-width":_(t),"--table-max-height":_(n),"--table-overflow":r===`native`?`auto`:void 0}})),ve=d(e=>{let t=c(`TableScrollContainer`,ge,e),{classNames:n,className:r,style:i,styles:s,unstyled:l,vars:u,children:d,minWidth:f,maxHeight:p,type:m,scrollAreaProps:h,attributes:g,..._}=t,v=a({name:`TableScrollContainer`,classes:oe,props:t,className:r,style:i,classNames:n,styles:s,unstyled:l,attributes:g,vars:u,varsResolver:_e,rootSelector:`scrollContainer`});return(0,M.jsx)(o,{component:m===`scrollarea`?C:`div`,...m===`scrollarea`?p?{offsetScrollbars:`xy`,...h}:{offsetScrollbars:`x`,...h}:{},...v(`scrollContainer`),..._,children:(0,M.jsx)(`div`,{...v(`scrollContainerInner`),children:d})})});ve.classes=oe,ve.varsResolver=_e,ve.displayName=`@mantine/core/TableScrollContainer`;function ye({data:e}){return(0,M.jsxs)(M.Fragment,{children:[e.caption&&(0,M.jsx)(he,{children:e.caption}),e.head&&(0,M.jsx)(fe,{children:(0,M.jsx)(de,{children:e.head.map((e,t)=>(0,M.jsx)(le,{children:e},t))})}),e.body&&(0,M.jsx)(pe,{children:e.body.map((e,t)=>(0,M.jsx)(de,{children:e.map((e,t)=>(0,M.jsx)(ue,{children:e},t))},t))}),e.foot&&(0,M.jsx)(me,{children:(0,M.jsx)(de,{children:e.foot.map((e,t)=>(0,M.jsx)(le,{children:e},t))})})]})}ye.displayName=`@mantine/core/TableDataRenderer`;var be={withRowBorders:!0,verticalSpacing:7},xe=f((e,{layout:t,captionSide:n,horizontalSpacing:r,verticalSpacing:i,borderColor:a,stripedColor:o,highlightOnHoverColor:c,striped:l,highlightOnHover:u,stickyHeaderOffset:d,stickyHeader:f})=>({table:{"--table-layout":t,"--table-caption-side":n,"--table-horizontal-spacing":y(r),"--table-vertical-spacing":y(i),"--table-border-color":a?s(a,e):void 0,"--table-striped-color":l&&o?s(o,e):void 0,"--table-highlight-on-hover-color":u&&c?s(c,e):void 0,"--table-sticky-header-offset":f?_(d):void 0}})),P=d(e=>{let t=c(`Table`,be,e),{classNames:n,className:r,style:i,styles:s,unstyled:l,vars:u,horizontalSpacing:d,verticalSpacing:f,captionSide:p,stripedColor:m,highlightOnHoverColor:h,striped:g,highlightOnHover:_,withColumnBorders:v,withRowBorders:y,withTableBorder:b,borderColor:x,layout:S,data:C,children:w,stickyHeader:E,stickyHeaderOffset:D,mod:O,tabularNums:k,attributes:ee,...te}=t,A=a({name:`Table`,props:t,className:r,style:i,classes:oe,classNames:n,styles:s,unstyled:l,attributes:ee,rootSelector:`table`,vars:u,varsResolver:xe,stable:!0}),j=g===!0?`odd`:g||void 0,ne=p||`bottom`,N=(0,T.useMemo)(()=>({getStyles:A,stickyHeader:E,striped:j,highlightOnHover:_,withColumnBorders:v,withRowBorders:y,captionSide:ne}),[A,E,j,_,v,y,ne]);return(0,M.jsx)(ie,{value:N,children:(0,M.jsx)(o,{component:`table`,mod:[{withTableBorder:b,tabularNums:k},O],...A(`table`),...te,children:w||!!C&&(0,M.jsx)(ye,{data:C})})})});P.classes=oe,P.varsResolver=xe,P.displayName=`@mantine/core/Table`,P.Td=ue,P.Th=le,P.Tr=de,P.Thead=fe,P.Tbody=pe,P.Tfoot=me,P.Caption=he,P.ScrollContainer=ve,P.DataRenderer=ye;var Se=new Map([[`bold`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M216.49,104.49l-80,80a12,12,0,0,1-17,0l-80-80a12,12,0,0,1,17-17L128,159l71.51-71.52a12,12,0,0,1,17,17Z`}))],[`duotone`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M208,96l-80,80L48,96Z`,opacity:`0.2`}),T.createElement(`path`,{d:`M215.39,92.94A8,8,0,0,0,208,88H48a8,8,0,0,0-5.66,13.66l80,80a8,8,0,0,0,11.32,0l80-80A8,8,0,0,0,215.39,92.94ZM128,164.69,67.31,104H188.69Z`}))],[`fill`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M213.66,101.66l-80,80a8,8,0,0,1-11.32,0l-80-80A8,8,0,0,1,48,88H208a8,8,0,0,1,5.66,13.66Z`}))],[`light`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M212.24,100.24l-80,80a6,6,0,0,1-8.48,0l-80-80a6,6,0,0,1,8.48-8.48L128,167.51l75.76-75.75a6,6,0,0,1,8.48,8.48Z`}))],[`regular`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M213.66,101.66l-80,80a8,8,0,0,1-11.32,0l-80-80A8,8,0,0,1,53.66,90.34L128,164.69l74.34-74.35a8,8,0,0,1,11.32,11.32Z`}))],[`thin`,T.createElement(T.Fragment,null,T.createElement(`path`,{d:`M210.83,98.83l-80,80a4,4,0,0,1-5.66,0l-80-80a4,4,0,0,1,5.66-5.66L128,170.34l77.17-77.17a4,4,0,1,1,5.66,5.66Z`}))]]),Ce=T.forwardRef((e,t)=>T.createElement(h,{ref:t,...e,weights:Se}));Ce.displayName=`CaretDownIcon`;var we=Ce,Te=new Intl.NumberFormat(void 0,{maximumFractionDigits:0});function Ee(e){return Number.isFinite(e)?e>0&&e<1e-4?`<0.01%`:`${(e*100).toFixed(e>=.1?1:2)}%`:`—`}function De(e){if(!Number.isFinite(e))return`—`;if(e<0)return`-${De(-e)}`;if(e===0)return`0ms`;if(e<.01)return`<0.01ms`;if(e<1)return`${e.toFixed(2)}ms`;if(Math.round(e*10)/10<100)return`${e.toFixed(1)}ms`;if(Math.round(e)<1e3)return`${Math.round(e)}ms`;let t=Math.round(e/100)/10;if(t<10)return`${(e/1e3).toFixed(2)}s`;if(t<60)return`${t.toFixed(1)}s`;let n=Math.round(e/1e3),r=Math.floor(n/60),i=n%60;if(r<60)return i===0?`${r}m`:`${r}m ${i}s`;let a=Math.floor(r/60),o=r%60;return o===0?`${a}h`:`${a}h ${o}m`}function Oe(e){let t=e instanceof Date?e:new Date(e);return Number.isNaN(t.valueOf())?String(e):t.toLocaleString([],{year:`numeric`,month:`short`,day:`numeric`,hour:`numeric`,minute:`2-digit`,second:`2-digit`,timeZoneName:`short`})}function ke(e,t){let n=t||{};return(e[e.length-1]===``?[...e,``]:e).join((n.padRight?` `:``)+`,`+(n.padLeft===!1?``:` `)).trim()}var Ae=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,je=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,Me={};function Ne(e,t){return((t||Me).jsx?je:Ae).test(e)}var Pe=/[ \t\n\f\r]/g;function Fe(e){return typeof e==`object`?e.type===`text`&&Ie(e.value):Ie(e)}function Ie(e){return e.replace(Pe,``)===``}var Le=class{constructor(e,t,n){this.normal=t,this.property=e,n&&(this.space=n)}};Le.prototype.normal={},Le.prototype.property={},Le.prototype.space=void 0;function Re(e,t){let n={},r={};for(let t of e)Object.assign(n,t.property),Object.assign(r,t.normal);return new Le(n,r,t)}function ze(e){return e.toLowerCase()}var F=class{constructor(e,t){this.attribute=t,this.property=e}};F.prototype.attribute=``,F.prototype.booleanish=!1,F.prototype.boolean=!1,F.prototype.commaOrSpaceSeparated=!1,F.prototype.commaSeparated=!1,F.prototype.defined=!1,F.prototype.mustUseProperty=!1,F.prototype.number=!1,F.prototype.overloadedBoolean=!1,F.prototype.property=``,F.prototype.spaceSeparated=!1,F.prototype.space=void 0;var Be=n({boolean:()=>I,booleanish:()=>L,commaOrSpaceSeparated:()=>B,commaSeparated:()=>Ue,number:()=>R,overloadedBoolean:()=>He,spaceSeparated:()=>z}),Ve=0,I=We(),L=We(),He=We(),R=We(),z=We(),Ue=We(),B=We();function We(){return 2**++Ve}var Ge=Object.keys(Be),Ke=class extends F{constructor(e,t,n,r){let i=-1;if(super(e,t),qe(this,`space`,r),typeof n==`number`)for(;++i4&&n.slice(0,4)===`data`&&ot.test(t)){if(t.charAt(4)===`-`){let e=t.slice(5).replace(at,lt);r=`data`+e.charAt(0).toUpperCase()+e.slice(1)}else{let e=t.slice(4);if(!at.test(e)){let n=e.replace(it,ct);n.charAt(0)!==`-`&&(n=`-`+n),t=`data`+n}}i=Ke}return new i(r,t)}function ct(e){return`-`+e.toLowerCase()}function lt(e){return e.charAt(1).toUpperCase()}var ut=Re([Ye,Qe,et,tt,nt],`html`),dt=Re([Ye,$e,et,tt,nt],`svg`);function ft(e){return e.join(` `).trim()}var pt=e(((e,t)=>{var n=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,r=/\n/g,i=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,o=/^:\s*/,s=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,c=/^[;\s]*/,l=/^\s+|\s+$/g;function u(e,t){if(typeof e!=`string`)throw TypeError(`First argument must be a string`);if(!e)return[];t||={};var l=1,u=1;function f(e){var t=e.match(r);t&&(l+=t.length);var n=e.lastIndexOf(` `);u=~n?e.length-n:u+e.length}function p(){var e={line:l,column:u};return function(t){return t.position=new m(e),_(),t}}function m(e){this.start=e,this.end={line:l,column:u},this.source=t.source}m.prototype.content=e;function h(n){var r=Error(t.source+`:`+l+`:`+u+`: `+n);if(r.reason=n,r.filename=t.source,r.line=l,r.column=u,r.source=e,!t.silent)throw r}function g(t){var n=t.exec(e);if(n){var r=n[0];return f(r),e=e.slice(r.length),n}}function _(){g(i)}function v(e){var t;for(e||=[];t=y();)t!==!1&&e.push(t);return e}function y(){var t=p();if(e.charAt(0)==`/`&&e.charAt(1)==`*`){for(var n=2;e.charAt(n)!=``&&(e.charAt(n)!=`*`||e.charAt(n+1)!=`/`);)++n;if(n+=2,e.charAt(n-1)===``)return h(`End of comment missing`);var r=e.slice(2,n-2);return u+=2,f(r),e=e.slice(n),u+=2,t({type:`comment`,comment:r})}}function b(){var e=p(),t=g(a);if(t){if(y(),!g(o))return h(`property missing ':'`);var r=g(s),i=e({type:`declaration`,property:d(t[0].replace(n,``)),value:r?d(r[0].replace(n,``)):``});return g(c),i}}function x(){var e=[];v(e);for(var t;t=b();)t!==!1&&(e.push(t),v(e));return e}return _(),x()}function d(e){return e?e.replace(l,``):``}t.exports=u})),mt=e((e=>{var t=e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(e,"__esModule",{value:!0}),e.default=r;var n=t(pt());function r(e,t){let r=null;if(!e||typeof e!=`string`)return r;let i=(0,n.default)(e),a=typeof t==`function`;return i.forEach(e=>{if(e.type!==`declaration`)return;let{property:n,value:i}=e;a?t(n,i,e):i&&(r||={},r[n]=i)}),r}})),ht=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.camelCase=void 0;var t=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,r=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,a=/^-(ms)-/,o=function(e){return!e||r.test(e)||t.test(e)},s=function(e,t){return t.toUpperCase()},c=function(e,t){return`${t}-`};e.camelCase=function(e,t){return t===void 0&&(t={}),o(e)?e:(e=e.toLowerCase(),e=t.reactCompat?e.replace(a,c):e.replace(i,c),e.replace(n,s))}})),gt=e(((e,t)=>{var n=(e&&e.__importDefault||function(e){return e&&e.__esModule?e:{default:e}})(mt()),r=ht();function i(e,t){var i={};return!e||typeof e!=`string`||(0,n.default)(e,function(e,n){e&&n&&(i[(0,r.camelCase)(e,t)]=n)}),i}i.default=i,t.exports=i})),_t=yt(`end`),vt=yt(`start`);function yt(e){return t;function t(t){let n=t&&t.position&&t.position[e]||{};if(typeof n.line==`number`&&n.line>0&&typeof n.column==`number`&&n.column>0)return{line:n.line,column:n.column,offset:typeof n.offset==`number`&&n.offset>-1?n.offset:void 0}}}function bt(e){let t=vt(e),n=_t(e);if(t&&n)return{start:t,end:n}}function xt(e){return!e||typeof e!=`object`?``:`position`in e||`type`in e?Ct(e.position):`start`in e||`end`in e?Ct(e):`line`in e||`column`in e?St(e):``}function St(e){return wt(e&&e.line)+`:`+wt(e&&e.column)}function Ct(e){return St(e&&e.start)+`-`+St(e&&e.end)}function wt(e){return e&&typeof e==`number`?e:1}var V=class extends Error{constructor(e,t,n){super(),typeof t==`string`&&(n=t,t=void 0);let r=``,i={},a=!1;if(t&&(i=`line`in t&&`column`in t||`start`in t&&`end`in t?{place:t}:`type`in t?{ancestors:[t],place:t.position}:{...t}),typeof e==`string`?r=e:!i.cause&&e&&(a=!0,r=e.message,i.cause=e),!i.ruleId&&!i.source&&typeof n==`string`){let e=n.indexOf(`:`);e===-1?i.ruleId=n:(i.source=n.slice(0,e),i.ruleId=n.slice(e+1))}if(!i.place&&i.ancestors&&i.ancestors){let e=i.ancestors[i.ancestors.length-1];e&&(i.place=e.position)}let o=i.place&&`start`in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file=``,this.message=r,this.line=o?o.line:void 0,this.name=xt(i.place)||`1:1`,this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=a&&i.cause&&typeof i.cause.stack==`string`?i.cause.stack:``,this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}};V.prototype.file=``,V.prototype.name=``,V.prototype.reason=``,V.prototype.message=``,V.prototype.stack=``,V.prototype.column=void 0,V.prototype.line=void 0,V.prototype.ancestors=void 0,V.prototype.cause=void 0,V.prototype.fatal=void 0,V.prototype.place=void 0,V.prototype.ruleId=void 0,V.prototype.source=void 0;var Tt=i(gt(),1),Et={}.hasOwnProperty,Dt=new Map,Ot=/[A-Z]/g,kt=new Set([`table`,`tbody`,`thead`,`tfoot`,`tr`]),At=new Set([`td`,`th`]),jt=`https://github.com/syntax-tree/hast-util-to-jsx-runtime`;function Mt(e,t){if(!t||t.Fragment===void 0)throw TypeError("Expected `Fragment` in options");let n=t.filePath||void 0,r;if(t.development){if(typeof t.jsxDEV!=`function`)throw TypeError("Expected `jsxDEV` in options when `development: true`");r=Ut(n,t.jsxDEV)}else{if(typeof t.jsx!=`function`)throw TypeError("Expected `jsx` in production options");if(typeof t.jsxs!=`function`)throw TypeError("Expected `jsxs` in production options");r=Ht(n,t.jsx,t.jsxs)}let i={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||`react`,evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space===`svg`?dt:ut,stylePropertyNameCase:t.stylePropertyNameCase||`dom`,tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},a=Nt(i,e,void 0);return a&&typeof a!=`string`?a:i.create(e,i.Fragment,{children:a||void 0},void 0)}function Nt(e,t,n){if(t.type===`element`)return Pt(e,t,n);if(t.type===`mdxFlowExpression`||t.type===`mdxTextExpression`)return Ft(e,t);if(t.type===`mdxJsxFlowElement`||t.type===`mdxJsxTextElement`)return Lt(e,t,n);if(t.type===`mdxjsEsm`)return It(e,t);if(t.type===`root`)return Rt(e,t,n);if(t.type===`text`)return zt(e,t)}function Pt(e,t,n){let r=e.schema,i=r;t.tagName.toLowerCase()===`svg`&&r.space===`html`&&(i=dt,e.schema=i),e.ancestors.push(t);let a=Yt(e,t.tagName,!1),o=Wt(e,t),s=Kt(e,t);return kt.has(t.tagName)&&(s=s.filter(function(e){return typeof e!=`string`||!Fe(e)})),Bt(e,o,a,t),Vt(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function Ft(e,t){if(t.data&&t.data.estree&&e.evaluater){let n=t.data.estree.body[0];return n.type,e.evaluater.evaluateExpression(n.expression)}Xt(e,t.position)}function It(e,t){if(t.data&&t.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(t.data.estree);Xt(e,t.position)}function Lt(e,t,n){let r=e.schema,i=r;t.name===`svg`&&r.space===`html`&&(i=dt,e.schema=i),e.ancestors.push(t);let a=t.name===null?e.Fragment:Yt(e,t.name,!0),o=Gt(e,t),s=Kt(e,t);return Bt(e,o,a,t),Vt(o,s),e.ancestors.pop(),e.schema=r,e.create(t,a,o,n)}function Rt(e,t,n){let r={};return Vt(r,Kt(e,t)),e.create(t,e.Fragment,r,n)}function zt(e,t){return t.value}function Bt(e,t,n,r){typeof n!=`string`&&n!==e.Fragment&&e.passNode&&(t.node=r)}function Vt(e,t){if(t.length>0){let n=t.length>1?t:t[0];n&&(e.children=n)}}function Ht(e,t,n){return r;function r(e,r,i,a){let o=Array.isArray(i.children)?n:t;return a?o(r,i,a):o(r,i)}}function Ut(e,t){return n;function n(n,r,i,a){let o=Array.isArray(i.children),s=vt(n);return t(r,i,a,o,{columnNumber:s?s.column-1:void 0,fileName:e,lineNumber:s?s.line:void 0},void 0)}}function Wt(e,t){let n={},r,i;for(i in t.properties)if(i!==`children`&&Et.call(t.properties,i)){let a=qt(e,i,t.properties[i]);if(a){let[i,o]=a;e.tableCellAlignToStyle&&i===`align`&&typeof o==`string`&&At.has(t.tagName)?r=o:n[i]=o}}if(r){let t=n.style||={};t[e.stylePropertyNameCase===`css`?`text-align`:`textAlign`]=r}return n}function Gt(e,t){let n={};for(let r of t.attributes)if(r.type===`mdxJsxExpressionAttribute`){if(r.data&&r.data.estree&&e.evaluater){let t=r.data.estree.body[0];t.type;let i=t.expression;i.type;let a=i.properties[0];a.type,Object.assign(n,e.evaluater.evaluateExpression(a.argument))}else Xt(e,t.position)}else{let i=r.name,a;if(r.value&&typeof r.value==`object`){if(r.value.data&&r.value.data.estree&&e.evaluater){let t=r.value.data.estree.body[0];t.type,a=e.evaluater.evaluateExpression(t.expression)}else Xt(e,t.position)}else a=r.value===null||r.value;n[i]=a}return n}function Kt(e,t){let n=[],r=-1,i=e.passKeys?new Map:Dt;for(;++ri?0:i+t:t>i?i:t,n=n>0?n:0,r.length<1e4)o=Array.from(r),o.unshift(t,n),e.splice(...o);else for(n&&e.splice(t,n);a0?(H(e,e.length,0,t),e):t}var ln={}.hasOwnProperty;function un(e){let t={},n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)==65535||(n&65535)==65534||n>1114111?`�`:String.fromCodePoint(n)}function W(e){return e.replace(/[\t\n\r ]+/g,` `).replace(/^ | $/g,``).toLowerCase().toUpperCase()}var G=xn(/[A-Za-z]/),K=xn(/[\dA-Za-z]/),mn=xn(/[#-'*+\--9=?A-Z^-~]/);function hn(e){return e!==null&&(e<32||e===127)}var gn=xn(/\d/),_n=xn(/[\dA-Fa-f]/),vn=xn(/[!-/:-@[-`{-~]/);function q(e){return e!==null&&e<-2}function J(e){return e!==null&&(e<0||e===32)}function Y(e){return e===-2||e===-1||e===32}var yn=xn(/\p{P}|\p{S}/u),bn=xn(/\s/);function xn(e){return t;function t(t){return t!==null&&t>-1&&e.test(String.fromCharCode(t))}}function Sn(e){let t=[],n=-1,r=0,i=0;for(;++n55295&&a<57344){let t=e.charCodeAt(n+1);a<56320&&t>56319&&t<57344?(o=String.fromCharCode(a,t),i=1):o=`�`}else o=String.fromCharCode(a);o&&=(t.push(e.slice(r,n),encodeURIComponent(o)),r=n+i+1,``),i&&=(n+=i,0)}return t.join(``)+e.slice(r)}function X(e,t,n,r){let i=r?r-1:1/0,a=0;return o;function o(r){return Y(r)?(e.enter(n),s(r)):t(r)}function s(r){return Y(r)&&a++0&&Y(t)?(e.enter(r),c(t)):l(t)}function c(t){return Y(t)&&o=i?t(e):n(e)}}var wn={tokenize:Tn};function Tn(e){let t=e.attempt(this.parser.constructs.contentInitial,r,i),n;return t;function r(n){if(n===null){e.consume(n);return}return e.enter(`lineEnding`),e.consume(n),e.exit(`lineEnding`),X(e,t,`linePrefix`)}function i(t){return e.enter(`paragraph`),a(t)}function a(t){let r=e.enter(`chunkText`,{contentType:`text`,previous:n});return n&&(n.next=r),n=r,o(t)}function o(t){if(t===null){e.exit(`chunkText`),e.exit(`paragraph`),e.consume(t);return}return q(t)?(e.consume(t),e.exit(`chunkText`),a):(e.consume(t),o)}}var En=class{constructor(){this.index=new Map,this.map=[]}add(e,t,n){Dn(this,e,t,n,!1)}addBefore(e,t,n){Dn(this,e,t,n,!0)}consume(e){if(this.map.sort(function(e,t){return e[0]-t[0]}),this.map.length===0)return;let t=this.map.length,n=[];for(;t>0;)--t,n.push(e.slice(this.map[t][0]+this.map[t][1]),this.map[t][2]),e.length=this.map[t][0];n.push(e.slice()),e.length=0;let r=n.pop();for(;r;){for(let t of r)e.push(t);r=n.pop()}this.map.length=0,this.index.clear()}};function Dn(e,t,n,r,i){if(n===0&&r.length===0)return;let a=e.index.get(t);if(a){a[1]+=n,i?(r.push(...a[2]),a[2]=r):a[2].push(...r);return}let o=[t,n,r];e.map.push(o),e.index.set(t,o)}var On={tokenize:An},kn={tokenize:jn};function An(e){let t=this,n=[],r=0,i,a,o;return s;function s(i){if(ro))return;let n=t.events.length,a=n,s,c;for(;a--;)if(t.events[a][0]===`exit`&&t.events[a][1].type===`chunkFlow`){if(s){c=t.events[a][1].end;break}s=!0}for(_(r),e=n;er;){let r=n[i];t.containerState=r[1],r[0].exit.call(t,e)}n.length=r}function v(){i.write([null]),a=void 0,i=void 0,t.containerState._closeFlow=void 0}}function jn(e,t,n){return X(e,e.attempt(this.parser.constructs.document,t,n),`linePrefix`,this.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)}function Mn(e){if(e===null||J(e)||bn(e))return 1;if(yn(e))return 2}function Nn(e,t,n){let r=[],i=-1;for(;++i1&&e[n][1].end.offset-e[n][1].start.offset>1?2:1,o={...e[i][1].end},s={...e[n][1].start};Ln(o,-a),Ln(s,a);let c={type:a>1?`strongSequence`:`emphasisSequence`,start:o,end:{...e[i][1].end}},l={type:a>1?`strongSequence`:`emphasisSequence`,start:{...e[n][1].start},end:s},u={type:a>1?`strongText`:`emphasisText`,start:{...e[i][1].end},end:{...e[n][1].start}},d={type:a>1?`strong`:`emphasis`,start:{...c.start},end:{...l.end}};e[i][1].end={...c.start},e[n][1].start={...l.end},r=[],e[i][1].end.offset-e[i][1].start.offset&&(r=U(r,[[`enter`,e[i][1],t],[`exit`,e[i][1],t]])),r=U(r,[[`enter`,d,t],[`enter`,c,t],[`exit`,c,t],[`enter`,u,t]]),r=U(r,Nn(t.parser.constructs.insideSpan.null,e.slice(i+1,n),t)),r=U(r,[[`exit`,u,t],[`enter`,l,t],[`exit`,l,t],[`exit`,d,t]]);let f=0;e[n][1].end.offset-e[n][1].start.offset&&(f=2,r=U(r,[[`enter`,e[n][1],t],[`exit`,e[n][1],t]])),H(e,i-1,n-i+3,r),n=i+r.length-f-2;break}}for(n=-1;++n0&&Y(t)?X(e,v,`linePrefix`,a+1)(t):v(t)}function v(t){return t===null||q(t)?e.check(Xn,h,b)(t):(e.enter(`codeFlowValue`),y(t))}function y(t){return t===null||q(t)?(e.exit(`codeFlowValue`),v(t)):(e.consume(t),y)}function b(n){return e.exit(`codeFenced`),t(n)}function x(e,t,n){let i=0;return a;function a(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),c}function c(t){return e.enter(`codeFencedFence`),Y(t)?X(e,l,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):l(t)}function l(t){return t===s?(e.enter(`codeFencedFenceSequence`),u(t)):n(t)}function u(t){return t===s?(i++,e.consume(t),u):i>=o?(e.exit(`codeFencedFenceSequence`),Y(t)?X(e,d,`whitespace`)(t):d(t)):n(t)}function d(r){return r===null||q(r)?(e.exit(`codeFencedFence`),t(r)):n(r)}}}var er={name:`codeIndented`,tokenize:nr},tr={partial:!0,tokenize:rr};function nr(e,t,n){return r;function r(t){return e.enter(`codeIndented`),Cn(e,i,n,`linePrefix`,4,4)(t)}function i(t){return t===null?o(t):q(t)?e.attempt(tr,i,o)(t):(e.enter(`codeFlowValue`),a(t))}function a(t){return t===null||q(t)?(e.exit(`codeFlowValue`),i(t)):(e.consume(t),a)}function o(n){return e.exit(`codeIndented`),t(n)}}function rr(e,t,n){let r=this;return i;function i(o){return r.parser.lazy[r.now().line]?n(o):q(o)?(e.enter(`lineEnding`),e.consume(o),e.exit(`lineEnding`),i):Cn(e,t,a,`linePrefix`,4,4)(o)}function a(e){return q(e)?i(e):n(e)}}var ir={name:`codeText`,previous:or,resolve:ar,tokenize:sr};function ar(e){let t=e.length-4,n=3,r,i;if((e[n][1].type===`lineEnding`||e[n][1].type===`space`)&&(e[t][1].type===`lineEnding`||e[t][1].type===`space`)){for(r=n;++r=this.left.length+this.right.length)throw RangeError("Cannot access index `"+e+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return ethis.left.length?this.right.slice(this.right.length-n+this.left.length,this.right.length-e+this.left.length).reverse():this.left.slice(e).concat(this.right.slice(this.right.length-n+this.left.length).reverse())}splice(e,t,n){let r=t||0;this.setCursor(Math.trunc(e));let i=this.right.splice(this.right.length-r,1/0);return n&&lr(this.left,n),i.reverse()}pop(){return this.setCursor(1/0),this.left.pop()}push(e){this.setCursor(1/0),this.left.push(e)}pushMany(e){this.setCursor(1/0),lr(this.left,e)}unshift(e){this.setCursor(0),this.right.push(e)}unshiftMany(e){this.setCursor(0),lr(this.right,e.reverse())}setCursor(e){if(!(e===this.left.length||e>this.left.length&&this.right.length===0||e<0&&this.left.length===0)){if(e=4?t(i):e.interrupt(r.parser.constructs.flow,n,t)(i)}}function _r(e,t,n,r,i,a,o,s,c){let l=c||1/0,u=0;return d;function d(t){return t===60?(e.enter(r),e.enter(i),e.enter(a),e.consume(t),e.exit(a),f):t===null||t===32||t===41||hn(t)?n(t):(e.enter(r),e.enter(o),e.enter(s),e.enter(`chunkString`,{contentType:`string`}),h(t))}function f(n){return n===62?(e.enter(a),e.consume(n),e.exit(a),e.exit(i),e.exit(r),t):(e.enter(s),e.enter(`chunkString`,{contentType:`string`}),p(n))}function p(t){return t===62?(e.exit(`chunkString`),e.exit(s),f(t)):t===null||t===60||q(t)?n(t):(e.consume(t),t===92?m:p)}function m(t){return t===60||t===62||t===92?(e.consume(t),p):p(t)}function h(i){return!u&&(i===null||i===41||J(i))?(e.exit(`chunkString`),e.exit(s),e.exit(o),e.exit(r),t(i)):u999||l===null||l===91||l===93&&!c||l===94&&!s&&`_hiddenFootnoteSupport`in o.parser.constructs?n(l):l===93?(e.exit(a),e.enter(i),e.consume(l),e.exit(i),e.exit(r),t):q(l)?(e.enter(`lineEnding`),e.consume(l),e.exit(`lineEnding`),u):(e.enter(`chunkString`,{contentType:`string`}),d(l))}function d(t){return t===null||t===91||t===93||q(t)||s++>999?(e.exit(`chunkString`),u(t)):(e.consume(t),c||=!Y(t),t===92?f:d)}function f(t){return t===91||t===92||t===93?(e.consume(t),s++,d):d(t)}}function yr(e,t,n,r,i,a){let o;return s;function s(t){return t===34||t===39||t===40?(e.enter(r),e.enter(i),e.consume(t),e.exit(i),o=t===40?41:t,c):n(t)}function c(n){return n===o?(e.enter(i),e.consume(n),e.exit(i),e.exit(r),t):(e.enter(a),l(n))}function l(t){return t===o?(e.exit(a),c(o)):t===null?n(t):q(t)?(e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),X(e,l,`linePrefix`)):(e.enter(`chunkString`,{contentType:`string`}),u(t))}function u(t){return t===o||t===null||q(t)?(e.exit(`chunkString`),l(t)):(e.consume(t),t===92?d:u)}function d(t){return t===o||t===92?(e.consume(t),u):u(t)}}function br(e,t){let n;return r;function r(i){return q(i)?(e.enter(`lineEnding`),e.consume(i),e.exit(`lineEnding`),n=!0,r):Y(i)?X(e,r,n?`linePrefix`:`lineSuffix`)(i):t(i)}}var xr={name:`definition`,tokenize:Cr},Sr={partial:!0,tokenize:wr};function Cr(e,t,n){let r=this,i;return a;function a(t){return e.enter(`definition`),o(t)}function o(t){return vr.call(r,e,s,n,`definitionLabel`,`definitionLabelMarker`,`definitionLabelString`)(t)}function s(t){return i=W(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),t===58?(e.enter(`definitionMarker`),e.consume(t),e.exit(`definitionMarker`),c):n(t)}function c(t){return J(t)?br(e,l)(t):l(t)}function l(t){return _r(e,u,n,`definitionDestination`,`definitionDestinationLiteral`,`definitionDestinationLiteralMarker`,`definitionDestinationRaw`,`definitionDestinationString`)(t)}function u(t){return e.attempt(Sr,d,d)(t)}function d(t){return Y(t)?X(e,f,`whitespace`)(t):f(t)}function f(a){return a===null||q(a)?(e.exit(`definition`),r.parser.defined.push(i),t(a)):n(a)}}function wr(e,t,n){return r;function r(t){return J(t)?br(e,i)(t):n(t)}function i(t){return yr(e,a,n,`definitionTitle`,`definitionTitleMarker`,`definitionTitleString`)(t)}function a(t){return Y(t)?X(e,o,`whitespace`)(t):o(t)}function o(e){return e===null||q(e)?t(e):n(e)}}var Tr={name:`hardBreakEscape`,tokenize:Er};function Er(e,t,n){return r;function r(t){return e.enter(`hardBreakEscape`),e.consume(t),i}function i(r){return q(r)?(e.exit(`hardBreakEscape`),t(r)):n(r)}}var Dr={name:`headingAtx`,resolve:Or,tokenize:kr};function Or(e,t){let n=e.length-2,r=3;if(e[r][1].type===`whitespace`&&(r+=2),n-2>r&&e[n][1].type===`whitespace`&&(n-=2),e[n][1].type===`atxHeadingSequence`&&(r===n-1||n-4>r&&e[n-2][1].type===`whitespace`)&&(n-=r+1===n?2:4),n>r){let i={type:`atxHeadingText`,start:e[r][1].start,end:e[n][1].end},a={type:`chunkText`,start:e[r][1].start,end:e[n][1].end,contentType:`text`};H(e,r,n-r+1,[[`enter`,i,t],[`enter`,a,t],[`exit`,a,t],[`exit`,i,t]])}return e}function kr(e,t,n){let r=0;return i;function i(t){return e.enter(`atxHeading`),a(t)}function a(t){return e.enter(`atxHeadingSequence`),o(t)}function o(t){return t===35&&r++<6?(e.consume(t),o):t===null||J(t)?(e.exit(`atxHeadingSequence`),s(t)):n(t)}function s(n){return n===35?(e.enter(`atxHeadingSequence`),c(n)):n===null||q(n)?(e.exit(`atxHeading`),t(n)):Y(n)?X(e,s,`whitespace`)(n):(e.enter(`atxHeadingText`),l(n))}function c(t){return t===35?(e.consume(t),c):(e.exit(`atxHeadingSequence`),s(t))}function l(t){return t===null||t===35||J(t)?(e.exit(`atxHeadingText`),s(t)):(e.consume(t),l)}}var Ar=`address.article.aside.base.basefont.blockquote.body.caption.center.col.colgroup.dd.details.dialog.dir.div.dl.dt.fieldset.figcaption.figure.footer.form.frame.frameset.h1.h2.h3.h4.h5.h6.head.header.hr.html.iframe.legend.li.link.main.menu.menuitem.nav.noframes.ol.optgroup.option.p.param.search.section.summary.table.tbody.td.tfoot.th.thead.title.tr.track.ul`.split(`.`),jr=[`pre`,`script`,`style`,`textarea`],Mr={concrete:!0,name:`htmlFlow`,resolveTo:Pr,tokenize:Fr},Nr={partial:!0,tokenize:Ir};function Pr(e){let t=e.length;for(;t--&&(e[t][0]!==`enter`||e[t][1].type!==`htmlFlow`););return t>1&&e[t-2][1].type===`linePrefix`&&(e[t][1].start=e[t-2][1].start,e[t+1][1].start=e[t-2][1].start,e.splice(t-2,2)),e}function Fr(e,t,n){let r=this,i,a,o,s,c;return l;function l(e){return u(e)}function u(t){return e.enter(`htmlFlow`),e.enter(`htmlFlowData`),e.consume(t),d}function d(s){return s===33?(e.consume(s),f):s===47?(e.consume(s),a=!0,h):s===63?(e.consume(s),i=3,r.interrupt?t:N):G(s)?(e.consume(s),o=String.fromCharCode(s),g):n(s)}function f(a){return a===45?(e.consume(a),i=2,p):a===91?(e.consume(a),i=5,s=0,m):G(a)?(e.consume(a),i=4,r.interrupt?t:N):n(a)}function p(i){return i===45?(e.consume(i),r.interrupt?t:N):n(i)}function m(i){return i===`CDATA[`.charCodeAt(s++)?(e.consume(i),s===6?r.interrupt?t:O:m):n(i)}function h(t){return G(t)?(e.consume(t),o=String.fromCharCode(t),g):n(t)}function g(s){if(s===null||s===47||s===62||J(s)){let c=s===47,l=o.toLowerCase();return!c&&!a&&jr.includes(l)?(i=1,r.interrupt?t(s):O(s)):Ar.includes(o.toLowerCase())?(i=6,c?(e.consume(s),_):r.interrupt?t(s):O(s)):(i=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(s):a?v(s):y(s))}return s===45||K(s)?(e.consume(s),o+=String.fromCharCode(s),g):n(s)}function _(i){return i===62?(e.consume(i),r.interrupt?t:O):n(i)}function v(t){return Y(t)?(e.consume(t),v):E(t)}function y(t){return t===47?(e.consume(t),E):t===58||t===95||G(t)?(e.consume(t),b):Y(t)?(e.consume(t),y):E(t)}function b(t){return t===45||t===46||t===58||t===95||K(t)?(e.consume(t),b):x(t)}function x(t){return t===61?(e.consume(t),S):Y(t)?(e.consume(t),x):y(t)}function S(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),c=t,C):Y(t)?(e.consume(t),S):w(t)}function C(t){return t===c?(e.consume(t),c=null,T):t===null||q(t)?n(t):(e.consume(t),C)}function w(t){return t===null||t===34||t===39||t===47||t===60||t===61||t===62||t===96||J(t)?x(t):(e.consume(t),w)}function T(e){return e===47||e===62||Y(e)?y(e):n(e)}function E(t){return t===62?(e.consume(t),D):n(t)}function D(t){return t===null||q(t)?O(t):Y(t)?(e.consume(t),D):n(t)}function O(t){return t===45&&i===2?(e.consume(t),A):t===60&&i===1?(e.consume(t),j):t===62&&i===4?(e.consume(t),re):t===63&&i===3?(e.consume(t),N):t===93&&i===5?(e.consume(t),M):q(t)&&(i===6||i===7)?(e.exit(`htmlFlowData`),e.check(Nr,ie,k)(t)):t===null||q(t)?(e.exit(`htmlFlowData`),k(t)):(e.consume(t),O)}function k(t){return e.check(Xn,ee,ie)(t)}function ee(t){return e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),te}function te(t){return t===null||q(t)?k(t):(e.enter(`htmlFlowData`),O(t))}function A(t){return t===45?(e.consume(t),N):O(t)}function j(t){return t===47?(e.consume(t),o=``,ne):O(t)}function ne(t){if(t===62){let n=o.toLowerCase();return jr.includes(n)?(e.consume(t),re):O(t)}return G(t)&&o.length<8?(e.consume(t),o+=String.fromCharCode(t),ne):O(t)}function M(t){return t===93?(e.consume(t),N):O(t)}function N(t){return t===62?(e.consume(t),re):t===45&&i===2?(e.consume(t),N):O(t)}function re(t){return t===null||q(t)?(e.exit(`htmlFlowData`),ie(t)):(e.consume(t),re)}function ie(n){return e.exit(`htmlFlow`),t(n)}}function Ir(e,t,n){return r;function r(r){return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),e.attempt(Bn,t,n)}}var Lr={name:`htmlText`,tokenize:Rr};function Rr(e,t,n){let r=this,i,a,o;return s;function s(t){return e.enter(`htmlText`),e.enter(`htmlTextData`),e.consume(t),c}function c(t){return t===33?(e.consume(t),l):t===47?(e.consume(t),x):t===63?(e.consume(t),y):G(t)?(e.consume(t),w):n(t)}function l(t){return t===45?(e.consume(t),u):t===91?(e.consume(t),a=0,m):G(t)?(e.consume(t),v):n(t)}function u(t){return t===45?(e.consume(t),p):n(t)}function d(t){return t===null?n(t):t===45?(e.consume(t),f):q(t)?(o=d,j(t)):(e.consume(t),d)}function f(t){return t===45?(e.consume(t),p):d(t)}function p(e){return e===62?A(e):e===45?f(e):d(e)}function m(t){return t===`CDATA[`.charCodeAt(a++)?(e.consume(t),a===6?h:m):n(t)}function h(t){return t===null?n(t):t===93?(e.consume(t),g):q(t)?(o=h,j(t)):(e.consume(t),h)}function g(t){return t===93?(e.consume(t),_):h(t)}function _(t){return t===62?A(t):t===93?(e.consume(t),_):h(t)}function v(t){return t===null||t===62?A(t):q(t)?(o=v,j(t)):(e.consume(t),v)}function y(t){return t===null?n(t):t===63?(e.consume(t),b):q(t)?(o=y,j(t)):(e.consume(t),y)}function b(e){return e===62?A(e):y(e)}function x(t){return G(t)?(e.consume(t),S):n(t)}function S(t){return t===45||K(t)?(e.consume(t),S):C(t)}function C(t){return q(t)?(o=C,j(t)):Y(t)?(e.consume(t),C):A(t)}function w(t){return t===45||K(t)?(e.consume(t),w):t===47||t===62||J(t)?T(t):n(t)}function T(t){return t===47?(e.consume(t),A):t===58||t===95||G(t)?(e.consume(t),E):q(t)?(o=T,j(t)):Y(t)?(e.consume(t),T):A(t)}function E(t){return t===45||t===46||t===58||t===95||K(t)?(e.consume(t),E):D(t)}function D(t){return t===61?(e.consume(t),O):q(t)?(o=D,j(t)):Y(t)?(e.consume(t),D):T(t)}function O(t){return t===null||t===60||t===61||t===62||t===96?n(t):t===34||t===39?(e.consume(t),i=t,k):q(t)?(o=O,j(t)):Y(t)?(e.consume(t),O):(e.consume(t),ee)}function k(t){return t===i?(e.consume(t),i=void 0,te):t===null?n(t):q(t)?(o=k,j(t)):(e.consume(t),k)}function ee(t){return t===null||t===34||t===39||t===60||t===61||t===96?n(t):t===47||t===62||J(t)?T(t):(e.consume(t),ee)}function te(e){return e===47||e===62||J(e)?T(e):n(e)}function A(r){return r===62?(e.consume(r),e.exit(`htmlTextData`),e.exit(`htmlText`),t):n(r)}function j(t){return e.exit(`htmlTextData`),e.enter(`lineEnding`),e.consume(t),e.exit(`lineEnding`),ne}function ne(t){return Y(t)?X(e,M,`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(t):M(t)}function M(t){return e.enter(`htmlTextData`),o(t)}}var zr={name:`labelEnd`,resolveAll:Ur,resolveTo:Wr,tokenize:Gr},Br={tokenize:Kr},Vr={tokenize:qr},Hr={tokenize:Jr};function Ur(e){let t=-1,n=[];for(;++t0&&i[i.length-1]._balanced;)i.pop();a=i[i.length-1]}return s;function s(t){return a?a._inactive?d(t):(o=r.parser.defined.includes(W(r.sliceSerialize({start:a.end,end:r.now()}))),e.enter(`labelEnd`),e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),e.exit(`labelEnd`),c):n(t)}function c(t){return t===40?e.attempt(Br,u,o?u:d)(t):t===91?e.attempt(Vr,u,o?l:d)(t):o?u(t):d(t)}function l(t){return e.attempt(Hr,u,d)(t)}function u(e){return i.pop(),t(e)}function d(e){return a._balanced=!0,n(e)}}function Kr(e,t,n){return r;function r(t){return e.enter(`resource`),e.enter(`resourceMarker`),e.consume(t),e.exit(`resourceMarker`),i}function i(t){return J(t)?br(e,a)(t):a(t)}function a(t){return t===41?u(t):_r(e,o,s,`resourceDestination`,`resourceDestinationLiteral`,`resourceDestinationLiteralMarker`,`resourceDestinationRaw`,`resourceDestinationString`,32)(t)}function o(t){return J(t)?br(e,c)(t):u(t)}function s(e){return n(e)}function c(t){return t===34||t===39||t===40?yr(e,l,n,`resourceTitle`,`resourceTitleMarker`,`resourceTitleString`)(t):u(t)}function l(t){return J(t)?br(e,u)(t):u(t)}function u(r){return r===41?(e.enter(`resourceMarker`),e.consume(r),e.exit(`resourceMarker`),e.exit(`resource`),t):n(r)}}function qr(e,t,n){let r=this;return i;function i(t){return vr.call(r,e,a,o,`reference`,`referenceMarker`,`referenceString`)(t)}function a(e){return r.parser.defined.includes(W(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)))?t(e):n(e)}function o(e){return n(e)}}function Jr(e,t,n){return r;function r(t){return e.enter(`reference`),e.enter(`referenceMarker`),e.consume(t),e.exit(`referenceMarker`),i}function i(r){return r===93?(e.enter(`referenceMarker`),e.consume(r),e.exit(`referenceMarker`),e.exit(`reference`),t):n(r)}}var Yr={name:`labelStartImage`,resolveAll:zr.resolveAll,tokenize:Xr};function Xr(e,t,n){let r=this,i;return a;function a(t){return e.enter(`labelImage`),e.enter(`labelImageMarker`),e.consume(t),e.exit(`labelImageMarker`),o}function o(t){return t===91?(e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),i=e.exit(`labelImage`),s):n(t)}function s(e){return e===94&&`_hiddenFootnoteSupport`in r.parser.constructs?n(e):(r._labelStarts=r._labelStarts||[],r._labelStarts.push(i),t(e))}}var Zr={name:`labelStartLink`,resolveAll:zr.resolveAll,tokenize:Qr};function Qr(e,t,n){let r=this,i;return a;function a(t){return e.enter(`labelLink`),e.enter(`labelMarker`),e.consume(t),e.exit(`labelMarker`),i=e.exit(`labelLink`),o}function o(e){return e===94&&`_hiddenFootnoteSupport`in r.parser.constructs?n(e):(r._labelStarts=r._labelStarts||[],r._labelStarts.push(i),t(e))}}var $r={name:`lineEnding`,tokenize:ei};function ei(e,t){return n;function n(n){return e.enter(`lineEnding`),e.consume(n),e.exit(`lineEnding`),X(e,t,`linePrefix`)}}var ti={name:`thematicBreak`,tokenize:ni};function ni(e,t,n){let r=0,i;return a;function a(t){return e.enter(`thematicBreak`),o(t)}function o(e){return i=e,s(e)}function s(a){return a===i?(e.enter(`thematicBreakSequence`),c(a)):r>=3&&(a===null||q(a))?(e.exit(`thematicBreak`),t(a)):n(a)}function c(t){return t===i?(e.consume(t),r++,c):(e.exit(`thematicBreakSequence`),Y(t)?X(e,s,`whitespace`)(t):s(t))}}var Z={continuation:{tokenize:oi},exit:ci,name:`list`,tokenize:ai},ri={partial:!0,tokenize:li},ii={partial:!0,tokenize:si};function ai(e,t,n){let r=this,i=r.events[r.events.length-1],a=i&&i[1].type===`linePrefix`?i[2].sliceSerialize(i[1],!0).length:0,o=0;return s;function s(t){let i=r.containerState.type||(t===42||t===43||t===45?`listUnordered`:`listOrdered`);if(i===`listUnordered`?!r.containerState.marker||t===r.containerState.marker:gn(t)){if(r.containerState.type||(r.containerState.type=i,e.enter(i,{_container:!0})),i===`listUnordered`)return e.enter(`listItemPrefix`),t===42||t===45?e.check(ti,n,l)(t):l(t);if(!r.interrupt||t===49)return e.enter(`listItemPrefix`),e.enter(`listItemValue`),c(t)}return n(t)}function c(t){return gn(t)&&++o<10?(e.consume(t),c):(!r.interrupt||o<2)&&(r.containerState.marker?t===r.containerState.marker:t===41||t===46)?(e.exit(`listItemValue`),l(t)):n(t)}function l(t){return e.enter(`listItemMarker`),e.consume(t),e.exit(`listItemMarker`),r.containerState.marker=r.containerState.marker||t,e.check(Bn,r.interrupt?n:u,e.attempt(ri,f,d))}function u(e){return r.containerState.initialBlankLine=!0,a++,f(e)}function d(t){return Y(t)?(e.enter(`listItemPrefixWhitespace`),e.consume(t),e.exit(`listItemPrefixWhitespace`),f):n(t)}function f(n){return r.containerState.size=a+r.sliceSerialize(e.exit(`listItemPrefix`),!0).length,t(n)}}function oi(e,t,n){let r=this;return r.containerState._closeFlow=void 0,e.check(Bn,i,a);function i(n){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,X(e,t,`listItemIndent`,r.containerState.size+1)(n)}function a(n){return r.containerState.furtherBlankLines||!Y(n)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,o(n)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,e.attempt(ii,t,o)(n))}function o(i){return r.containerState._closeFlow=!0,r.interrupt=void 0,X(e,e.attempt(Z,t,n),`linePrefix`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:4)(i)}}function si(e,t,n){let r=this;return X(e,i,`listItemIndent`,r.containerState.size+1);function i(e){let i=r.events[r.events.length-1];return i&&i[1].type===`listItemIndent`&&i[2].sliceSerialize(i[1],!0).length===r.containerState.size?t(e):n(e)}}function ci(e){e.exit(this.containerState.type)}function li(e,t,n){let r=this;return X(e,i,`listItemPrefixWhitespace`,r.parser.constructs.disable.null.includes(`codeIndented`)?void 0:5);function i(e){let i=r.events[r.events.length-1];return!Y(e)&&i&&i[1].type===`listItemPrefixWhitespace`?t(e):n(e)}}var ui={name:`setextUnderline`,resolveTo:di,tokenize:fi};function di(e,t){let n=new En,r=e.length,i,a,o;for(;r--;)if(e[r][0]===`enter`){if(e[r][1].type===`content`){i=r;break}e[r][1].type===`paragraph`&&(a=r)}else e[r][1].type===`content`&&n.add(r,1,[]),!o&&e[r][1].type===`definition`&&(o=r);let s={type:`setextHeading`,start:{...e[i][1].start},end:{...e[e.length-1][1].end}};return e[a][1].type=`setextHeadingText`,o?(n.add(a,0,[[`enter`,s,t]]),n.add(o+1,0,[[`exit`,e[i][1],t]]),e[i][1].end={...e[o][1].end}):e[i][1]=s,n.add(e.length,0,[[`exit`,s,t]]),n.consume(e),e}function fi(e,t,n){let r=this,i;return a;function a(t){let a=r.events.length,s;for(;a--;)if(r.events[a][1].type!==`lineEnding`&&r.events[a][1].type!==`linePrefix`&&r.events[a][1].type!==`content`){s=r.events[a][1].type===`paragraph`;break}return!r.parser.lazy[r.now().line]&&(r.interrupt||s)?(e.enter(`setextHeadingLine`),i=t,o(t)):n(t)}function o(t){return e.enter(`setextHeadingLineSequence`),s(t)}function s(t){return t===i?(e.consume(t),s):(e.exit(`setextHeadingLineSequence`),Y(t)?X(e,c,`lineSuffix`)(t):c(t))}function c(r){return r===null||q(r)?(e.exit(`setextHeadingLine`),t(r)):n(r)}}var pi={tokenize:mi};function mi(e){let t=this,n=e.attempt(Bn,r,e.attempt(this.parser.constructs.flowInitial,i,X(e,e.attempt(this.parser.constructs.flow,i,e.attempt(fr,i)),`linePrefix`)));return n;function r(r){if(r===null){e.consume(r);return}return e.enter(`lineEndingBlank`),e.consume(r),e.exit(`lineEndingBlank`),t.currentConstruct=void 0,n}function i(r){if(r===null){e.consume(r);return}return e.enter(`lineEnding`),e.consume(r),e.exit(`lineEnding`),t.currentConstruct=void 0,n}}var hi={resolveAll:yi()},gi=vi(`string`),_i=vi(`text`);function vi(e){return{resolveAll:yi(e===`text`?bi:void 0),tokenize:t};function t(t){let n=this,r=this.parser.constructs[e],i=t.attempt(r,a,o);return a;function a(e){return c(e)?i(e):o(e)}function o(e){if(e===null){t.consume(e);return}return t.enter(`data`),t.consume(e),s}function s(e){return c(e)?(t.exit(`data`),i(e)):(t.consume(e),s)}function c(e){if(e===null)return!0;let t=r[e],i=-1;if(t)for(;++iki,contentInitial:()=>Ci,disable:()=>Ai,document:()=>Si,flow:()=>Ti,flowInitial:()=>wi,insideSpan:()=>Oi,string:()=>Ei,text:()=>Di}),Si={42:Z,43:Z,45:Z,48:Z,49:Z,50:Z,51:Z,52:Z,53:Z,54:Z,55:Z,56:Z,57:Z,62:Hn},Ci={91:xr},wi={[-2]:er,[-1]:er,32:er},Ti={35:Dr,42:ti,45:[ui,ti],60:Mr,61:ui,95:ti,96:Qn,126:Qn},Ei={38:Jn,92:Kn},Di={[-5]:$r,[-4]:$r,[-3]:$r,33:Yr,38:Jn,42:Pn,60:[Rn,Lr],91:Zr,92:[Tr,Kn],93:zr,95:Pn,96:ir},Oi={null:[Pn,hi]},ki={null:[42,95]},Ai={null:[]};function ji(e,t,n){let r={_bufferIndex:-1,_index:0,line:n&&n.line||1,column:n&&n.column||1,offset:n&&n.offset||0},i={},a=[],o=[],s=[],c={attempt:C(x),check:C(S),consume:v,enter:y,exit:b,interrupt:C(S,{interrupt:!0})},l={code:null,containerState:{},defineSkip:h,events:[],now:m,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:d},u=t.tokenize.call(l,c);return t.resolveAll&&a.push(t),l;function d(e){return o=U(o,e),g(),o[o.length-1]===null?(w(t,0),l.events=Nn(a,l.events,l),l.events):[]}function f(e,t){return Ni(p(e),t)}function p(e){return Mi(o,e)}function m(){let{_bufferIndex:e,_index:t,line:n,column:i,offset:a}=r;return{_bufferIndex:e,_index:t,line:n,column:i,offset:a}}function h(e){i[e.line]=e.column,E()}function g(){for(;r._index-1){let e=o[0];typeof e==`string`?o[0]=e.slice(r):o.shift()}a>0&&o.push(e[i].slice(0,a))}return o}function Ni(e,t){let n=-1,r=[],i;for(;++n0){let e=a.tokenStack[a.tokenStack.length-1];(e[1]||qi).call(a,void 0,e[0])}for(r.position={start:Wi(e.length>0?e[0][1].start:{line:1,column:1,offset:0}),end:Wi(e.length>0?e[e.length-2][1].end:{line:1,column:1,offset:0})},d=-1;++dvoid c({to:`/dashboards/$dashboardId`,params:{dashboardId:t},search:a(n),replace:r,resetScroll:t!==e});return(0,o.jsx)(n,{dashboardId:e,search:s,onSearch:(t,n)=>l(e,t,n),onOpen:(e,t)=>l(e,{},t)})}export{s as component}; \ No newline at end of file +import{r as e}from"./useRouter-ByJ6_rwb.js";import{n as t}from"./useNavigate-B1zgPEUp.js";import{t as n}from"./page-DWbtzTMF.js";import{f as r,g as i,y as a}from"./index-m8tRkNwz.js";var o=e();function s(){let{dashboardId:e}=r.useParams(),s=i(r.useSearch()),c=t(),l=(t,n,r)=>void c({to:`/dashboards/$dashboardId`,params:{dashboardId:t},search:a(n),replace:r,resetScroll:t!==e});return(0,o.jsx)(n,{dashboardId:e,search:s,onSearch:(t,n)=>l(e,t,n),onOpen:(e,t)=>l(e,{},t)})}export{s as component}; \ No newline at end of file diff --git a/internal/ui/dist/assets/dashboards.index-CHMzfRRW.js b/internal/ui/dist/assets/dashboards.index-CoF5-Lh4.js similarity index 68% rename from internal/ui/dist/assets/dashboards.index-CHMzfRRW.js rename to internal/ui/dist/assets/dashboards.index-CoF5-Lh4.js index 09002d3f..0f11a8ee 100644 --- a/internal/ui/dist/assets/dashboards.index-CHMzfRRW.js +++ b/internal/ui/dist/assets/dashboards.index-CoF5-Lh4.js @@ -1 +1 @@ -import{r as e}from"./useRouter-ByJ6_rwb.js";import{n as t}from"./useNavigate-B1zgPEUp.js";import{t as n}from"./page-6_nmYeSY.js";import{g as r,p as i,y as a}from"./index-BZ6fASDi.js";var o=e();function s(){let e=r(i.useSearch()),s=t();return(0,o.jsx)(n,{search:e,onSearch:()=>void 0,onOpen:(t,n)=>void s({to:`/dashboards/$dashboardId`,params:{dashboardId:t},search:a(e),replace:n})})}export{s as component}; \ No newline at end of file +import{r as e}from"./useRouter-ByJ6_rwb.js";import{n as t}from"./useNavigate-B1zgPEUp.js";import{t as n}from"./page-DWbtzTMF.js";import{g as r,p as i,y as a}from"./index-m8tRkNwz.js";var o=e();function s(){let e=r(i.useSearch()),s=t();return(0,o.jsx)(n,{search:e,onSearch:()=>void 0,onOpen:(t,n)=>void s({to:`/dashboards/$dashboardId`,params:{dashboardId:t},search:a(e),replace:n})})}export{s as component}; \ No newline at end of file diff --git a/internal/ui/dist/assets/index-BZ6fASDi.js b/internal/ui/dist/assets/index-BZ6fASDi.js deleted file mode 100644 index 256aa0e9..00000000 --- a/internal/ui/dist/assets/index-BZ6fASDi.js +++ /dev/null @@ -1,136 +0,0 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/routes-D2AdaqvY.js","assets/useRouter-ByJ6_rwb.js","assets/useNavigate-B1zgPEUp.js","assets/settings-taYHMo2-.js","assets/brand-DUaZkIz1.js","assets/Tooltip-B3r3s_B9.js","assets/WarningCircle.es-CClFvSYW.js","assets/chat.index-DMtKC6Qw.js","assets/chat-CgHTI0Fx.js","assets/preload-helper-EHBQhIeL.js","assets/dashboard-change-chips-BODDZoYU.js","assets/chat._threadId-DMtKC6Qw.js","assets/dashboards.index-CHMzfRRW.js","assets/page-6_nmYeSY.js","assets/dashboards._dashboardId-CHxQdhK6.js"])))=>i.map(i=>d[i]); -import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./useRouter-ByJ6_rwb.js";import{$ as s,A as c,B as l,C as u,F as d,G as f,H as p,I as m,J as h,K as g,L as _,M as v,N as y,P as b,Q as x,R as S,S as C,T as w,U as T,V as ee,W as E,X as D,Y as O,Z as te,_ as ne,_t as re,a as k,at as ie,b as ae,c as oe,ct as se,d as ce,dt as le,f as ue,gt as de,h as fe,ht as pe,i as me,it as he,j as ge,k as _e,l as ve,lt as ye,m as A,mt as j,nt as be,o as xe,ot as Se,p as Ce,pt as we,q as Te,r as Ee,rt as De,st as Oe,t as ke,tt as Ae,u as je,ut as Me,v as Ne,w as Pe,x as Fe,y as Ie,z as Le}from"./brand-DUaZkIz1.js";import{i as Re,n as ze,r as Be,t as Ve}from"./useNavigate-B1zgPEUp.js";import{A as He,C as Ue,D as We,E as Ge,M as Ke,O as qe,T as Je,_ as Ye,a as Xe,b as Ze,c as Qe,f as $e,g as et,i as tt,j as nt,k as rt,n as it,r as at,t as ot,v as st,w as ct,y as lt}from"./preload-helper-EHBQhIeL.js";import{C as ut,E as dt,T as ft,_ as pt,a as mt,c as ht,d as gt,f as _t,g as vt,h as yt,i as bt,l as xt,m as St,n as Ct,o as wt,p as Tt,r as Et,s as Dt,t as Ot,u as kt,v as At,x as jt,y as Mt}from"./Tooltip-B3r3s_B9.js";(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 Nt=e((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,D());else{var t=n(l);t!==null&&ne(x,t.startTime-e)}}}var S=!1,C=-1,w=5,T=-1;function ee(){return g?!0:!(e.unstable_now()-Tt&&ee());){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&&ne(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?D():S=!1}}}var D;if(typeof y==`function`)D=function(){y(E)};else if(typeof MessageChannel<`u`){var O=new MessageChannel,te=O.port2;O.port1.onmessage=E,D=function(){te.postMessage(null)}}else D=function(){_(E,0)};function ne(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,ne(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,D()))),r},e.unstable_shouldYield=ee,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),Pt=e(((e,t)=>{t.exports=Nt()})),Ft=e((e=>{var n=Pt(),r=t(),i=re();function a(e){var t=`https://react.dev/errors/`+e;if(1Se||(e.current=xe[Se],xe[Se]=null,Se--)}function Te(e,t){Se++,xe[Se]=e.current,e.current=t}var Ee=Ce(null),De=Ce(null),Oe=Ce(null),ke=Ce(null);function Ae(e,t){switch(Te(Oe,t),Te(De,e),Te(Ee,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?xp(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=xp(t),e=Sp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}we(Ee),Te(Ee,e)}function je(){we(Ee),we(De),we(Oe)}function Me(e){var t=e.memoizedState;t!==null&&(vh._currentValue=t.memoizedState,Te(ke,e)),t=Ee.current;var n=Sp(t,e.type);t!==n&&(Te(De,e),Te(Ee,n))}function Ne(e){De.current===e&&(we(Ee),we(De)),ke.current===e&&(we(ke),vh._currentValue=be)}var Pe,Fe;function Ie(e){if(Pe===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Pe=t&&t[1]||``,Fe=-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{Le=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ie(n):``}function ze(e,t){switch(e.tag){case 26:case 27:case 5:return Ie(e.type);case 16:return Ie(`Lazy`);case 13:return e.child!==t&&t!==null?Ie(`Suspense Fallback`):Ie(`Suspense`);case 19:return Ie(`SuspenseList`);case 0:case 15:return Re(e.type,!1);case 11:return Re(e.type.render,!1);case 1:return Re(e.type,!0);case 31:return Ie(`Activity`);case 30:return Ie(`ViewTransition`);default:return``}}function Be(e){try{var t=``,n=null;do t+=ze(e,n),n=e,e=e.return;while(e);return t}catch(e){return` -Error generating stack: `+e.message+` -`+e.stack}}var Ve=Object.prototype.hasOwnProperty,He=n.unstable_scheduleCallback,Ue=n.unstable_cancelCallback,We=n.unstable_shouldYield,Ge=n.unstable_requestPaint,Ke=n.unstable_now,qe=n.unstable_getCurrentPriorityLevel,Je=n.unstable_ImmediatePriority,Ye=n.unstable_UserBlockingPriority,Xe=n.unstable_NormalPriority,Ze=n.unstable_LowPriority,Qe=n.unstable_IdlePriority,$e=n.log,et=n.unstable_setDisableYieldValue,tt=null,nt=null;function rt(e){if(typeof $e==`function`&&et(e),nt&&typeof nt.setStrictMode==`function`)try{nt.setStrictMode(tt,e)}catch{}}var it=Math.clz32?Math.clz32:st,at=Math.log,ot=Math.LN2;function st(e){return e>>>=0,e===0?32:31-(at(e)/ot|0)|0}var ct=256,lt=262144,ut=4194304;function dt(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&-e;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 ft(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=dt(n))):i=dt(o):i=dt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=dt(n))):i=dt(o)):i=dt(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 pt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function mt(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0n;n++)t.push(e);return t}function vt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function yt(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=vr),xr=` `,Sr=!1;function Cr(e,t){switch(e){case`keyup`:return gr.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function wr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var Tr=!1;function Er(e,t){switch(e){case`compositionend`:return wr(t);case`keypress`:return t.which===32?(Sr=!0,xr):null;case`textInput`:return e=t.data,e===xr&&Sr?null:e;default:return null}}function Dr(e,t){if(Tr)return e===`compositionend`||!_r&&Cr(e,t)?(e=zn(),Rn=Ln=In=null,Tr=!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=Xr(n)}}function Qr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Qr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function $r(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Yr(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=Yr(e.document)}return t}function ei(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 ti=Nn&&`documentMode`in document&&11>=document.documentMode,ni=null,ri=null,ii=null,ai=!1;function oi(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ai||ni==null||ni!==Yr(r)||(r=ni,`selectionStart`in r&&ei(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}),ii&&Jr(ii,r)||(ii=r,r=ap(ri,`onSelect`),0>=o,i-=o,na=1<<32-it(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),P&&ia(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(i,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(i,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(i,h),P&&ia(i,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(i,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return P&&ia(i,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,i,g,v.value,l),v!==null&&(e&&(_=v.alternate,_!==null&&h.delete(_.key===null?g:_.key)),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(i,e)}),P&&ia(i,g),u}function _(e,r,o,c){if(typeof o==`object`&&o&&o.type===O&&o.key===null&&o.props.ref===void 0&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case E:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===O){if(r.tag===7){n(e,r.sibling),c=i(r,o.props.children),ho(c,o),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===le&&so(l)===r.type){n(e,r.sibling),c=i(r,o.props),ho(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===O?(c=Ui(o.props.children,e.mode,c,o.key),ho(c,o),c.return=e,e=c):(c=Hi(o.type,o.key,o.props,null,e.mode,c),ho(c,o),c.return=e,e=c)}return s(e);case D: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=i(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=Ki(o,e.mode,c),c.return=e,e=c}return s(e);case le:return o=so(o),_(e,r,o,c)}if(ye(o))return h(e,r,o,c);if(ge(o)){if(l=ge(o),typeof l!=`function`)throw Error(a(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return _(e,r,mo(o),c);if(o.$$typeof===ie)return _(e,r,Ma(e,o),c);go(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=i(r,o),c.return=e,e=c):(n(e,r),c=Wi(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{po=0;var i=_(e,t,n,r);return fo=null,i}catch(t){if(t===to||t===ro)throw t;var a=Ri(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var vo=_o(!0),yo=_o(!1),bo=!1;function xo(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function So(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 Co(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function wo(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,cd&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=Fi(e),Pi(e,null,n),t}return ji(e,r,t,n),Fi(e)}function To(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,xt(e,n)}}function Eo(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 Do=!1;function Oo(){if(Do){var e=Ka;if(e!==null)throw e}}function ko(e,t,n,r){Do=!1;var i=e.updateQueue;bo=!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 f=s.lane&-536870913,p=f!==s.lane;if(p?(ud&f)===f:(r&f)===f){f!==0&&f===Ga&&(Do=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,h=s;f=t;var g=n;switch(h.tag){case 1:if(m=h.payload,typeof m==`function`){d=m.call(g,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m==`function`?m.call(g,d,f):m,f==null)break a;d=T({},d,f);break a;case 2:bo=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,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),vd|=o,e.lanes=o,e.memoizedState=d}}function Ao(e,t){if(typeof e!=`function`)throw Error(a(191,e));e.call(t)}function jo(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=A.T,s={};s.types=o===null?null:o.types,A.T=s,vc(e,!1,t,n);try{var c=i(),l=A.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?_c(e,t,Ya(c,r),Hd(e)):_c(e,t,r,Hd(e))}catch(n){_c(e,t,{then:function(){},status:`rejected`,reason:n},Hd())}finally{j.p=a,o!==null&&s.types!==null&&(o.types=s.types),A.T=o}}function sc(){}function cc(e,t,n,r){if(e.tag!==5)throw Error(a(476));var i=lc(e).queue;oc(e,i,t,be,n===null?sc:function(){return uc(e),n(r)})}function lc(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:be,baseState:be,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ys,lastRenderedState:be},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ys,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function uc(e){var t=lc(e);t.next===null&&(t=e.alternate.memoizedState),_c(e,t.next.queue,{},Hd())}function dc(){return ja(vh)}function fc(){return ms().memoizedState}function pc(){return ms().memoizedState}function mc(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=Hd();e=Co(n);var r=wo(t,e,n);r!==null&&(Gd(r,t,n),To(r,t,n)),t={cache:Ra()},e.payload=t;return}t=t.return}}function hc(e,t,n){var r=Hd();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},yc(e)?bc(t,n):(n=Mi(e,t,n,r),n!==null&&(Gd(n,e,r),xc(n,t,r)))}function gc(e,t,n){_c(e,t,n,Hd())}function _c(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(yc(e))bc(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,qr(s,o))return ji(e,t,i,0),ld===null&&Ai(),!1}catch{}if(n=Mi(e,t,i,r),n!==null)return Gd(n,e,r),xc(n,t,r),!0}return!1}function vc(e,t,n,r){if(r={lane:2,revertLane:Gf(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},yc(e)){if(t)throw Error(a(479))}else t=Mi(e,n,r,2),t!==null&&Gd(t,e,2)}function yc(e){var t=e.alternate;return e===F||t!==null&&t===F}function bc(e,t){Qo=Zo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function xc(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,xt(e,n)}}var Sc={readContext:ja,use:_s,useCallback:is,useContext:is,useEffect:is,useImperativeHandle:is,useLayoutEffect:is,useInsertionEffect:is,useMemo:is,useReducer:is,useRef:is,useState:is,useDebugValue:is,useDeferredValue:is,useTransition:is,useSyncExternalStore:is,useId:is,useHostTransitionStatus:is,useFormState:is,useActionState:is,useOptimistic:is,useMemoCache:is,useCacheRefresh:is,useEffectEvent:is},Cc={readContext:ja,use:_s,useCallback:function(e,t){return ps().memoizedState=[e,t===void 0?null:t],e},useContext:ja,useEffect:qs,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),Gs(4194308,4,$s.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Gs(4194308,4,e,t)},useInsertionEffect:function(e,t){Gs(4,2,e,t)},useMemo:function(e,t){var n=ps();t=t===void 0?null:t;var r=e();if($o){rt(!0);try{e()}finally{rt(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=ps();if(n!==void 0){var i=n(t);if($o){rt(!0);try{n(t)}finally{rt(!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=hc.bind(null,F,e),[r.memoizedState,e]},useRef:function(e){var t=ps();return e={current:e},t.memoizedState=e},useState:function(e){e=ks(e);var t=e.queue,n=gc.bind(null,F,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:tc,useDeferredValue:function(e,t){return ic(ps(),e,t)},useTransition:function(){var e=ks(!1);return e=oc.bind(null,F,e.queue,!0,!1),ps().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=F,i=ps();if(P){if(n===void 0)throw Error(a(407));n=n()}else{if(n=t(),ld===null)throw Error(a(349));ud&127||ws(r,t,n)}i.memoizedState=n;var o={value:n,getSnapshot:t};return i.queue=o,qs(Es.bind(null,r,o,e),[e]),r.flags|=2048,Us(9,{destroy:void 0},Ts.bind(null,r,o,n,t),null),n},useId:function(){var e=ps(),t=ld.identifierPrefix;if(P){var n=ra,r=na;n=(r&~(1<<32-it(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=es++,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(i,{is:r.is}):s.createElement(i)}}o[Ot]=t,o[kt]=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(pp(o,i,r),i){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&yl(t)}}return wl(t),t.subtreeFlags&=-33554433,bl(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&yl(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(a(166));if(e=Oe.current,_a(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,i=la,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}e[Ot]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||up(e.nodeValue,n)),e||ma(t,!0)}else e=bp(e).createTextNode(r),e[Ot]=t,t.stateNode=e}return wl(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=_a(t),n!==null){if(e===null){if(!r)throw Error(a(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(a(557));e[Ot]=t}else va(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;wl(t),e=!1}else n=ya(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(Uo(t),t):(Uo(t),null);if(t.flags&128)throw Error(a(558))}return wl(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(i=_a(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(a(318));if(i=t.memoizedState,i=i===null?null:i.dehydrated,!i)throw Error(a(317));i[Ot]=t}else va(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;wl(t),i=!1}else i=ya(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),i=!0;if(!i)return t.flags&256?(Uo(t),t):(Uo(t),null)}return Uo(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==i&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Sl(t,t.updateQueue),wl(t),null);case 4:return je(),e===null&&tp(t.stateNode.containerInfo),t.flags|=67108864,wl(t),null;case 10:return Ta(t.type),wl(t),null;case 19:if(Ko(t),r=t.memoizedState,r===null)return wl(t),null;if(i=!!(t.flags&128),o=r.rendering,o===null){if(i)Cl(r,!1);else{if(_d!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=qo(e),o!==null){for(t.flags|=128,Cl(r,!1),e=o.updateQueue,t.updateQueue=e,Sl(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)Vi(n,e),n=n.sibling;return Go(t,Wo.current&1|2),P&&ia(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ke()>Dd&&(t.flags|=128,i=!0,Cl(r,!1),t.lanes=4194304)}}else{if(!i){if(e=qo(o),e!==null){if(t.flags|=128,i=!0,e=e.updateQueue,t.updateQueue=e,Sl(t,e),Cl(r,!0),r.tail===null&&r.tailMode!==`collapsed`&&r.tailMode!==`visible`&&!o.alternate&&!P)return wl(t),null}else 2*Ke()-r.renderingStartTime>Dd&&n!==536870912&&(t.flags|=128,i=!0,Cl(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)}if(r.tail!==null){e=r.tail;a:{for(n=e;n!==null;){if(n.alternate!==null){n=!1;break a}n=n.sibling}n=!0}return r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ke(),e.sibling=null,o=Wo.current,o=i?o&1|2:o&1,r.tailMode===`visible`||r.tailMode===`collapsed`||!n||P?Go(t,o):(n=o,Te(Lo,t),Te(Wo,n),Ro===null&&(Ro=t)),P&&ia(t,r.treeForkCount),e}return wl(t),null;case 22:case 23:return Uo(t),Io(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(wl(t),t.subtreeFlags&6&&(t.flags|=8192)):wl(t),n=t.updateQueue,n!==null&&Sl(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&&we(Za),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),Ta(La),wl(t),null;case 25:return null;case 30:return t.flags|=33554432,wl(t),null}throw Error(a(156,t.tag))}function El(e,t){switch(sa(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return Ta(La),je(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Ne(t),null;case 31:if(t.memoizedState!==null){if(Uo(t),t.alternate===null)throw Error(a(340));va()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Uo(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(a(340));va()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Ko(t),e=t.flags,e&65536?(t.flags=e&-65537|128,e=t.memoizedState,e!==null&&(e.rendering=null,e.tail=null),t.flags|=4,t):null;case 4:return je(),null;case 10:return Ta(t.type),null;case 22:case 23:return Uo(t),Io(),e!==null&&we(Za),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return Ta(La),null;case 25:return null;default:return null}}function Dl(e,t){switch(sa(t),t.tag){case 3:Ta(La),je();break;case 26:case 27:case 5:Ne(t);break;case 4:je();break;case 31:t.memoizedState!==null&&Uo(t);break;case 13:Uo(t);break;case 19:Ko(t);break;case 10:Ta(t.type);break;case 22:case 23:Uo(t),Io(),e!==null&&we(Za);break;case 24:Ta(La)}}function Ol(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){wf(t,t.return,e)}}function kl(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){wf(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){wf(t,t.return,e)}}function Al(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{jo(t,n)}catch(t){wf(e,e.return,t)}}}function jl(e,t,n){n.props=Ac(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){wf(e,t,n)}}function Ml(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:var i=e.stateNode,a=Ci(e.memoizedProps,i);(i.ref===null||i.ref.name!==a)&&(i.ref=Gp(a)),r=i.ref;break;case 7:if(e.stateNode===null){var o=new Kp(e);p(e.child,!1,lm,o,void 0,void 0),e.stateNode=o}r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){wf(e,t,n)}}function Nl(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){wf(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){wf(e,t,n)}else n.current=null}}function Pl(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var n=0;n title`))),pp(r,t,n),r[Ot]=e,Vt(r),t=r;break a;case`link`:if(o=nh(`link`,`href`,i).get(t+(n.href||``))){for(s=0;sg&&(o=g,g=h,h=o);var _=Zr(s,h),v=Zr(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,A.T=null,n=Fd,Fd=null;var o=jd,s=Nd;if(Ad=0,Md=jd=null,Nd=0,cd&6)throw Error(a(331));var c=cd;if(cd|=4,rd(o.current),Yu(o,o.current,s,n),cd=c,Rf(0,!1),nt&&typeof nt.onPostCommitFiberRoot==`function`)try{nt.onPostCommitFiberRoot(tt,o)}catch{}return!0}finally{j.p=i,A.T=r,bf(e,t)}}function Cf(e,t,n){t=Ji(n,t),t=Ic(e.stateNode,t,2),e=wo(e,t,2),e!==null&&(vt(e,2),Lf(e))}function wf(e,t,n){if(e.tag===3)Cf(e,e,n);else for(;t!==null;){if(t.tag===3){Cf(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(kd===null||!kd.has(r))){e=Ji(n,e),n=Lc(2),r=wo(t,n,2),r!==null&&(Rc(n,r,t,e),vt(r,2),Lf(r));break}}t=t.return}}function Tf(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new sd;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)||(hd=!0,i.add(n),e=Ef.bind(null,e,t,n),t.then(e,e))}function Ef(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,ld===e&&(ud&n)===n&&(_d===4||_d===3&&(ud&62914560)===ud&&300>Ke()-Td?cd&2?bd|=n:Qd(e,0):bd|=n,Sd===ud&&(Sd=0)),Lf(e)}function Df(e,t){t===0&&(t=gt()),e=Ni(e,t),e!==null&&(vt(e,t),Lf(e))}function Of(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Df(e,n)}function kf(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(a(314))}r!==null&&r.delete(t),Df(e,n)}function Af(e,t){return He(e,t)}var jf=null,Mf=null,Nf=!1,Pf=!1,Ff=!1,If=0;function Lf(e){e!==Mf&&e.next===null&&(Mf===null?jf=Mf=e:Mf=Mf.next=e),Pf=!0,Nf||(Nf=!0,Wf())}function Rf(e,t){if(!Ff&&Pf){Ff=!0;do for(var n=!1,r=jf;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-it(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,Uf(r,a))}else a=ud,a=ft(r,r===ld?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||pt(r,a)||(n=!0,Uf(r,a))}r=r.next}while(n);Ff=!1}}function zf(){Bf()}function Bf(){Pf=Nf=!1;var e=0;If!==0&&Ep()&&(e=If);for(var t=Ke(),n=null,r=jf;r!==null;){var i=r.next,a=Vf(r,t);a===0?(r.next=null,n===null?jf=i:n.next=i,i===null&&(Mf=n)):(n=r,(e!==0||a&3)&&(Pf=!0)),r=i}Ad!==0&&Ad!==5||Rf(e,!1),If!==0&&(If=0)}function Vf(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&&gp(d)&&(c=c.responseEnd,o+=u*(cuh){s.length=o;break}f=new Promise(Hp.bind(f)),s.push(f)}}}if(0`u`?null:document;function Im(e,t,n){var r=Fm;if(r&&typeof t==`string`&&t){var i=ln(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),Am.has(i)||(Am.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),pp(t,`link`,e),Vt(t),r.head.appendChild(t)))}}function Lm(e){Mm.D(e),Im(`dns-prefetch`,e,null)}function Rm(e,t){Mm.C(e,t),Im(`preconnect`,e,t)}function zm(e,t,n){Mm.L(e,t,n);var r=Fm;if(r&&e&&t){var i=`link[rel="preload"][as="`+ln(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+ln(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+ln(n.imageSizes)+`"]`)):i+=`[href="`+ln(e)+`"]`;var a=i;switch(t){case`style`:a=Gm(e);break;case`script`:a=Ym(e)}if(!(km.has(a)||(e=T({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),km.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Km(a))||t===`script`&&r.querySelector(Xm(a))))){var o=r.createElement(`link`);pp(o,`link`,e),t===`style`&&(o[Lt]=!0,o.onload=o.onerror=function(){Ht(o)}),Vt(o),r.head.appendChild(o)}}}function Bm(e,t){Mm.m(e,t);var n=Fm;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+ln(r)+`"][href="`+ln(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Ym(e)}if(!km.has(a)&&(e=T({rel:`modulepreload`,href:e},t),km.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Xm(a)))return}r=n.createElement(`link`),pp(r,`link`,e),Vt(r),n.head.appendChild(r)}}}function Vm(e,t,n){Mm.S(e,t,n);var r=Fm;if(r&&e){var i=Bt(r).hoistableStyles,a=Gm(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Km(a)))s.loading=5;else{e=T({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=km.get(a))&&$m(e,n);var c=o=r.createElement(`link`);Vt(c),pp(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,Qm(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Hm(e,t){Mm.X(e,t);var n=Fm;if(n&&e){var r=Bt(n).hoistableScripts,i=Ym(e),a=r.get(i);a||(a=n.querySelector(Xm(i)),a||(e=T({src:e,async:!0},t),(t=km.get(i))&&eh(e,t),a=n.createElement(`script`),Vt(a),pp(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Um(e,t){Mm.M(e,t);var n=Fm;if(n&&e){var r=Bt(n).hoistableScripts,i=Ym(e),a=r.get(i);a||(a=n.querySelector(Xm(i)),a||(e=T({src:e,async:!0,type:`module`},t),(t=km.get(i))&&eh(e,t),a=n.createElement(`script`),Vt(a),pp(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Wm(e,t,n,r){var i=(i=Oe.current)?jm(i):null;if(!i)throw Error(a(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(n=Gm(n.href),t=Bt(i).hoistableStyles,r=t.get(n),r||(r={type:`style`,instance:null,count:0,state:null},t.set(n,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=Gm(n.href);var o=Bt(i).hoistableStyles,s=o.get(e);if(s||(i=i.ownerDocument||i,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=i.querySelector(Km(e)))?o._p||(s.instance=o,s.state.loading=5):(o=km.get(e),o||(o={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},km.set(e,o)),Jm(i,e,o,s.state))),t&&r===null)throw Error(a(528,``));return s}if(t&&r!==null)throw Error(a(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(n=Ym(n),t=Bt(i).hoistableScripts,r=t.get(n),r||(r={type:`script`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(a(444,e))}}function Gm(e){return`href="`+ln(e)+`"`}function Km(e){return`link[rel="stylesheet"][`+e+`]`}function qm(e){return T({},e,{"data-precedence":e.precedence,precedence:null})}function Jm(e,t,n,r){if(t=e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)){if(!0!==t[Lt]){r.loading=1;return}}else t=e.createElement(`link`),t[Lt]=!0,t.onload=t.onerror=Ht.bind(null,t),pp(t,`link`,n),Vt(t),e.head.appendChild(t);r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2})}function Ym(e){return`[src="`+ln(e)+`"]`}function Xm(e){return`script[async]`+e}function Zm(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+ln(n.href)+`"]`);if(r)return t.instance=r,Vt(r),r;var i=T({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),Vt(r),pp(r,`style`,i),Qm(r,n.precedence,e),t.instance=r;case`stylesheet`:i=Gm(n.href);var o=e.querySelector(Km(i));if(o)return t.state.loading|=4,t.instance=o,Vt(o),o;r=qm(n),(i=km.get(i))&&$m(r,i),o=(e.ownerDocument||e).createElement(`link`),Vt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),pp(o,`link`,r),t.state.loading|=4,Qm(o,n.precedence,e),t.instance=o;case`script`:return o=Ym(n.src),(i=e.querySelector(Xm(o)))?(t.instance=i,Vt(i),i):(r=n,(i=km.get(o))&&(r=T({},n),eh(r,i)),e=e.ownerDocument||e,i=e.createElement(`script`),Vt(i),pp(i,`link`,r),e.head.appendChild(i),t.instance=i);case`void`:return null;default:throw Error(a(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Qm(r,n.precedence,e));return t.instance}function Qm(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 ih(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 ah(e,t){return e===`img`&&t.src!=null&&t.src!==``&&t.onLoad==null&&t.loading!==`lazy`}function oh(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function sh(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio==`number`?devicePixelRatio:1)*.25}function ch(e,t){typeof t.decode==`function`&&(e.imgCount++,t.complete||(e.imgBytes+=sh(t),e.suspenseyImages.push(t)),e=mh.bind(e),t.decode().then(e,e))}function lh(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=Gm(r.href),a=t.querySelector(Km(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=ph.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,Vt(a);return}a=t.ownerDocument||t,r=qm(r),(i=km.get(i))&&$m(r,i),a=a.createElement(`link`),Vt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),pp(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=ph.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var uh=0;function dh(e,t){return e.stylesheets&&e.count===0&&gh(e,e.stylesheets),0uh?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function fh(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)gh(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function ph(){this.count--,fh(this)}function mh(){this.imgCount--,fh(this)}var hh=null;function gh(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,hh=new Map,t.forEach(_h,e),hh=null,ph.call(e))}function _h(e,t){if(!(t.state.loading&4)){var n=hh.get(e);if(n)var r=n.get(null);else{n=new Map,hh.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=Ft()})),Lt=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e,this._branch=void 0;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=ct:this.parentRoute||rt();let r=n?ct:t?.path;r&&r!==`/`&&(r=We(r));let i=t?.id||r,a=n?ct:Ge((this.parentRoute.id===`__root__`?``:this.parentRoute.id)+`/`+(i??``));r===`__root__`&&(r=`/`);let o=a===`__root__`?`/`:r===void 0?this.parentRoute.fullPath:Ge(this.parentRoute.fullPath+`/`+r);this._path=r,this._id=a,this._fullPath=o,this._to=qe(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>Ue({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},Rt=class extends Lt{constructor(e){super(e)}},M=a(t(),1),N=i(),zt=class extends M.Component{constructor(...e){super(...e),this.state={error:0},this.reset=()=>{this.setState({error:0})}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:0}:{resetKey:n}}static getDerivedStateFromError(e){return{error:[e]}}componentDidCatch(e,t){this.props.onCatch?.(e,t)}render(){let e=this.state.error;return e?M.createElement(this.props.errorComponent??Bt,{error:e[0],reset:this.reset}):this.props.children}};function Bt({error:e}){let[t,n]=M.useState(!1);return(0,N.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,N.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,N.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,N.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,N.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,N.jsx)(`div`,{children:(0,N.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e?.message?(0,N.jsx)(`code`,{children:e.message}):null})}):null]})}var Vt=()=>!0,Ht=()=>!1;function Ut({children:e,fallback:t=null}){return(0,N.jsx)(M.Fragment,{children:Wt()?e:t})}function Wt(e=!0){return M.useSyncExternalStore(Gt,Vt,e?Ht:Vt)}function Gt(){return()=>{}}function Kt({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(1)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(1)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function qt(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var Jt=[],Yt=0,{link:Xt,unlink:Zt,propagate:Qt,checkDirty:$t,shallowPropagate:en}=Kt({update(e){return e._update()},notify(e){Jt[nn++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,sn(e))}}),tn=0,nn=0,rn,an=0;function on(e){try{++an,e()}finally{--an||cn()}}function sn(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=Zt(n,e)}function cn(){if(!(an>0)){for(;tn{i.get(),n.current?(rn=void 0,t.next?.(i._snapshot)):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=rn,o=t?.compare??Object.is;if(n)rn=i,++Yt,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{rn=a,n&&(i.flags&=-5),sn(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&$t(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&en(e)}}else e&32&&(i.flags=e&-33);return rn!==void 0&&Xt(i,rn,Yt),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Qt(e),en(e),cn())}},i}function un(e){let t=()=>{let t=rn;rn=n,++Yt,n.depsTail=void 0,n.flags=6;try{return e()}finally{rn=t,n.flags&=-5,sn(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&$t(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,sn(this)}};return t(),n}var dn=e((e=>{var n=t();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useState,o=n.useEffect,s=n.useLayoutEffect,c=n.useDebugValue;function l(e,t){var n=t(),r=a({inst:{value:n,getSnapshot:t}}),i=r[0].inst,l=r[1];return s(function(){i.value=n,i.getSnapshot=t,u(i)&&l({inst:i})},[e,n,t]),o(function(){return u(i)&&l({inst:i}),e(function(){u(i)&&l({inst:i})})},[e]),c(n),n}function u(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!i(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:l;e.useSyncExternalStore=n.useSyncExternalStore===void 0?f:n.useSyncExternalStore})),fn=e(((e,t)=>{t.exports=dn()})),pn=e((e=>{var n=t(),r=fn();function i(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var a=typeof Object.is==`function`?Object.is:i,o=r.useSyncExternalStore,s=n.useRef,c=n.useEffect,l=n.useMemo,u=n.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var d=s(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=l(function(){function e(e){if(!o){if(o=!0,s=e,e=r(e),i!==void 0&&f.hasValue){var t=f.value;if(i(t,e))return c=t}return c=e}if(t=c,a(s,e))return t;var n=r(e);return i!==void 0&&i(t,n)?(s=e,t):(s=e,c=n)}var o=!1,s,c,l=n===void 0?null:n;return[function(){return e(t())},l===null?void 0:function(){return e(l())}]},[t,n,r,i]);var p=o(e,d[0],d[1]);return c(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}})),mn=e(((e,t)=>{t.exports=pn()}))();function hn(e,t){return e===t}function gn(e,t=e=>e,n){let r=n?.compare??hn,i=(0,M.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,M.useCallback)(()=>e.get(),[e]);return(0,mn.useSyncExternalStoreWithSelector)(i,a,a,t,r)}var _n={};function vn(e,t){let n=M.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=Ke(n.current,i):i}}function yn(e){let t=o(),n=M.useContext(e.from?Ye:st),r=e.from??n,i=t.stores.getMatchStore(r),a=vn(e,t),s=gn(i,e=>e?a(e):_n);if(s!==_n)return s;(e.shouldThrow??!0)&&rt()}function bn(e){return yn({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function xn(e){let{select:t,...n}=e;return yn({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function Sn(e){return yn({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function Cn(e){return yn({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function wn(e){return yn({...e,select:t=>e.select?e.select(t.context):t.context})}var Tn=class extends Lt{constructor(e){super(e),this.useMatch=e=>yn({...e,from:this.id}),this.useRouteContext=e=>wn({...e,from:this.id}),this.useSearch=e=>Cn({...e,from:this.id}),this.useParams=e=>Sn({...e,from:this.id}),this.useLoaderDeps=e=>xn({...e,from:this.id}),this.useLoaderData=e=>bn({...e,from:this.id}),this.useNavigate=()=>ze({from:this.fullPath}),this.Link=M.forwardRef((e,t)=>(0,N.jsx)(et,{ref:t,from:this.fullPath,...e}))}};function En(e){return new Tn(e)}var Dn=class extends Rt{constructor(e){super(e),this.useMatch=e=>yn({...e,from:this.id}),this.useRouteContext=e=>wn({...e,from:this.id}),this.useSearch=e=>Cn({...e,from:this.id}),this.useParams=e=>Sn({...e,from:this.id}),this.useLoaderDeps=e=>xn({...e,from:this.id}),this.useLoaderData=e=>bn({...e,from:this.id}),this.useNavigate=()=>ze({from:this.fullPath}),this.Link=M.forwardRef((e,t)=>(0,N.jsx)(et,{ref:t,from:this.fullPath,...e}))}};function On(e){return new Dn(e)}function kn(e){return e=>{let t=En(e);return t.isRoot=!1,t}}function An(e,t){let n,r,i,a=()=>(n||=(i=void 0,e().then(e=>{n=void 0,o.preload=void 0,r=e[t??`default`]}).catch(e=>{n=void 0,i=e})),n),o=function(e){if(i){if(nt(i)&&typeof sessionStorage<`u`){let e=`tanstack_router_reload:${i.message}`;if(!sessionStorage.getItem(e))throw sessionStorage.setItem(e,`1`),window.location.reload(),new Promise(()=>{})}throw i}if(!r){if(Be)Be(a());else throw a()}return M.createElement(r,e)};return o.preload=a,o}function jn(e){let t=o(),n=`not-found-${gn(t.stores.location,e=>e.pathname)}-${gn(t.stores.status)}`;return(0,N.jsx)(zt,{getResetKey:()=>n,onCatch:(t,n)=>{if(Je(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(Je(t))return e.fallback?.(t);throw t},children:e.children})}function Mn(){return(0,N.jsx)(`p`,{children:`Not Found`})}function Nn(e,t,n){return t.options.notFoundComponent?(0,N.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,N.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,N.jsx)(Mn,{})}function Pn(e,t){let n=t?.options.pendingComponent??e.options.defaultPendingComponent;return n?(0,N.jsx)(n,{}):null}var Fn=(e,t)=>e[0]===t[0]&&e[1]===t[1],In=(e,t,n)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||n===!1||n===`data-only`||!e.ssr,Ln=M.memo(function({routeId:e}){let t=o();return Rn(t,gn(t.stores.getMatchStore(e)))});function Rn(e,t){let n=e.routesById[t.routeId],r=Pn(e,n),i=n.options.errorComponent??e.options.defaultErrorComponent,a=n.options.onCatch??e.options.defaultOnCatch,o=n.isRoot?n.options.notFoundComponent??e.options.notFoundRoute?.options.component:n.options.notFoundComponent,s=t.ssr===!1||t.ssr===`data-only`,c=In(e,n,t.ssr)&&(n.options.wrapInSuspense??r??(n.options.errorComponent?.preload||s)),l=(0,N.jsx)(zn,{match:t});s&&(l=(0,N.jsx)(Ut,{fallback:r,children:l})),o&&(l=(0,N.jsx)(jn,{fallback:e=>{if(e.routeId??=t.routeId,e.routeId!==t.routeId)throw e;return M.createElement(o,e)},children:l})),i&&(l=(0,N.jsx)(zt,{getResetKey:()=>t,errorComponent:i,onCatch:(e,n)=>{if(Je(e))throw e.routeId??=t.routeId,e;a?.(e,n)},children:l})),c&&(l=(0,N.jsx)(M.Suspense,{fallback:r,children:l}));let u=n.isRoot&&n.options.shellComponent;return u?(0,N.jsx)(st.Provider,{value:t.routeId,children:(0,N.jsxs)(u,{children:[l,null]})}):(0,N.jsxs)(st.Provider,{value:t.routeId,children:[l,null]})}var zn=M.memo(function({match:e}){let t=o(),n=e.routeId,r=t.routesById[n],i=M.useMemo(()=>{let i=(r.options.remountDeps??t.options.defaultRemountDeps)?.({routeId:n,loaderDeps:e.loaderDeps,params:e._strictParams,search:e._strictSearch});return i?JSON.stringify(i):void 0},[n,e.loaderDeps,e._strictParams,e._strictSearch,r.options.remountDeps,t.options.defaultRemountDeps]),a=M.useMemo(()=>{let e=r.options.component??t.options.defaultComponent;return e?(0,N.jsx)(e,{},i):(0,N.jsx)(Bn,{})},[i,r.options.component,t.options.defaultComponent]);if(e.status===`pending`){if(t.ssr&&!In(t,r,e.ssr))return a;if(t._tx)throw t._tx[5];return Pn(t,r)}if(e.status===`notFound`)return Nn(t,r,e.error);if(e.status===`error`)throw e.error;return a}),Bn=M.memo(function(){let e=o(),t=M.useContext(st),n,r,i;{let a=e.stores.getMatchStore(t);[n,r]=gn(a,e=>[!!e._notFound,e.error],{compare:Fn}),i=gn(e.stores.ids,e=>e[e.indexOf(t)+1])}if(n)return Nn(e,e.routesById[t],r);if(!i)return null;let a=(0,N.jsx)(Ln,{routeId:i});return t===`__root__`?(0,N.jsx)(M.Suspense,{fallback:Pn(e),children:a}):a});function Vn(e,t){let n=e[1];e.length=0,n?.(t)}function Hn({t:e}){let t=o(),n=t._rendered??=[];return t.startTransition=(r,i)=>new Promise(a=>{Vn(n,!1),n.push(i,a),e(t),M.startTransition(r)}),Re(()=>{let e=t.history.subscribe(t.load);t.updateLatestLocation();let r=t.latestLocation,i=t.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(qe(r.publicHref)!==qe(i.publicHref))return t.commitLocation({...i,replace:!0,ignoreBlocker:!0}),e;let a=t.stores.resolvedLocation.get();return a?.href===r.href&&a.state.__TSR_key===r.state.__TSR_key?n.push(t.stores.matches.get(),e=>{e&&t.emit({type:`onRendered`,...Ze(a,a)})}):t._tx||t.load({sync:!0}).catch(console.error),e},[t,t.history]),null}function Un(){let e=o(),t=e.routesById[ct],n=Pn(e,t),r=(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(Hn,{t:M.useState()[1]}),e.ssr?(0,N.jsx)(Wn,{}):(0,N.jsx)(M.Suspense,{fallback:n,children:(0,N.jsx)(Wn,{})})]});return e.options.InnerWrap?(0,N.jsx)(e.options.InnerWrap,{children:r}):r}function Wn(){let e=o(),t=e._rendered,n=gn(e.stores.matches,e=>t[0]??e),r=n[0],i=r?.routeId;Re(()=>{t[0]===n&&Vn(t,!0)},[t,n]);let a=i?(0,N.jsx)(Ln,{routeId:i}):null;return e.options.disableGlobalCatchBoundary?a:(0,N.jsx)(zt,{getResetKey:()=>r,onCatch:void 0,children:a})}var Gn=e=>({createMutableStore:ln,createReadonlyStore:ln,batch:on}),Kn=e=>new qn(e),qn=class extends lt{constructor(e){super(e,Gn)}};function Jn({router:e,children:t,...r}){He(r)&&e.update({...e.options,...r,context:{...e.options.context,...r.context}});let i=(0,N.jsx)(n.Provider,{value:e,children:t});return e.options.Wrap?(0,N.jsx)(e.options.Wrap,{children:i}):i}function Yn({router:e,...t}){return(0,N.jsx)(Jn,{router:e,...t,children:(0,N.jsx)(Un,{})})}function Xn(e){let t=o({warn:e?.router===void 0}),n=e?.router||t;return gn(n.stores.__store,vn(e,n))}function Zn(e){return typeof e!=`string`||!e.includes(`var(--mantine-scale)`)?e:e.match(/^calc\((.*?)\)$/)?.[1].split(`*`)[0].trim()}function Qn(e){let t=Zn(e);return typeof t==`number`?t:typeof t==`string`?t.includes(`calc`)||t.includes(`var`)?t:t.includes(`px`)?Number(t.replace(`px`,``)):t.includes(`rem`)?Number(t.replace(`rem`,``))*16:t.includes(`em`)?Number(t.replace(`em`,``))*16:Number(t):NaN}function $n(e,t){let n=e;for(;(n=n.parentElement)&&!n.matches(t););return n}function er(e,t,n){for(let n=e-1;n>=0;--n)if(!t[n].disabled)return n;if(n){for(let e=t.length-1;e>-1;--e)if(!t[e].disabled)return e}return e}function tr(e,t,n){for(let n=e+1;n{n?.(s);let c=Array.from($n(s.currentTarget,e)?.querySelectorAll(t)||[]).filter(t=>nr(s.currentTarget,t,e)),l=c.findIndex(e=>s.currentTarget===e),u=tr(l,c,r),d=er(l,c,r),f=a===`rtl`?d:u,p=a===`rtl`?u:d;switch(s.key){case`ArrowRight`:o===`horizontal`&&(s.stopPropagation(),s.preventDefault(),c[f].focus(),i&&c[f].click());break;case`ArrowLeft`:o===`horizontal`&&(s.stopPropagation(),s.preventDefault(),c[p].focus(),i&&c[p].click());break;case`ArrowUp`:o===`vertical`&&(s.stopPropagation(),s.preventDefault(),c[d].focus(),i&&c[d].click());break;case`ArrowDown`:o===`vertical`&&(s.stopPropagation(),s.preventDefault(),c[u].focus(),i&&c[u].click());break;case`Home`:s.stopPropagation(),s.preventDefault(),c[tr(-1,c,!1)]?.focus();break;case`End`:s.stopPropagation(),s.preventDefault(),c[er(c.length,c,!1)]?.focus()}}}var ir=()=>{};function ar(e,t={active:!0}){return typeof e!=`function`||!t.active?t.onKeyDown||ir:n=>{n.key===`Escape`&&(e(n),t.onTrigger?.())}}function or(e,t){return n=>{e?.(n),t?.(n)}}function sr(e,t){return e in t?Qn(t[e]):Qn(e)}function cr(e,t){let n=e.map(e=>({value:e,px:sr(e,t)}));return n.sort((e,t)=>e.px-t.px),n}function lr(e,t,n){return n?Array.from($n(n,t)?.querySelectorAll(e)||[]).findIndex(e=>e===n):null}var ur=[`mousedown`,`touchstart`];function dr(e,t,n,r=!0,i=!1){let a=(0,M.useRef)(null),o=t||ur,s=(0,M.useEffectEvent)(t=>{let{target:r}=t??{};if(!document.body.contains(r)&&r?.tagName!==`HTML`)return;let i=t.composedPath();Array.isArray(n)?n.every(e=>!!e&&!i.includes(e))&&e(t):a.current&&!i.includes(a.current)&&e(t)}),c=o.join(`,`);return(0,M.useEffect)(()=>{if(!r)return;let e=c.split(`,`);return e.forEach(e=>document.addEventListener(e,s,i)),()=>{e.forEach(e=>document.removeEventListener(e,s,i))}},[c,r,i]),a}function fr(e,t){return ie(`(prefers-color-scheme: dark)`,e===`dark`,t)?`dark`:`light`}function pr(e,t,n={leading:!1}){let[r,i]=(0,M.useState)(e),a=(0,M.useRef)(!1),o=(0,M.useRef)(null),s=(0,M.useRef)(!1),c=(0,M.useRef)(e);c.current=e;let l=(0,M.useCallback)(()=>{window.clearTimeout(o.current),o.current=null},[]),u=(0,M.useCallback)(()=>{l(),s.current=!1},[]),d=(0,M.useCallback)(()=>{o.current&&(u(),s.current=!1,i(c.current))},[]);return(0,M.useEffect)(()=>{a.current&&(l(),!s.current&&n.leading?(s.current=!0,i(e),o.current=window.setTimeout(()=>{s.current=!1},t)):o.current=window.setTimeout(()=>{s.current=!1,i(e)},t))},[e,n.leading,t]),(0,M.useEffect)(()=>(a.current=!0,u),[]),[r,u,{cancel:u,flush:d}]}function mr({opened:e,shouldReturnFocus:t=!0}){let n=(0,M.useRef)(null),r=()=>{n.current&&`focus`in n.current&&typeof n.current.focus==`function`&&n.current?.focus({preventScroll:!0})};return De(()=>{let i=-1,a=e=>{e.key===`Tab`&&window.clearTimeout(i)};if(document.addEventListener(`keydown`,a),e)n.current=document.activeElement;else if(t){let e=document.activeElement;i=window.setTimeout(()=>{let t=document.activeElement;(t===null||t===document.body||t===e)&&r()},10)}return()=>{window.clearTimeout(i),document.removeEventListener(`keydown`,a)}},[e,t]),r}var hr=/input|select|textarea|button|object/,gr=`a, input, select, textarea, button, object, [tabindex]`;function _r(e){return e.style.display===`none`}function vr(e){if(e.getAttribute(`aria-hidden`)||e.getAttribute(`hidden`)||e.getAttribute(`type`)===`hidden`)return!1;let t=e;for(;t&&t!==document.body&&t.nodeType!==11;){if(_r(t))return!1;t=t.parentNode}return!0}function yr(e){let t=e.getAttribute(`tabindex`);return t===null&&(t=void 0),parseInt(t,10)}function br(e){let t=e.nodeName.toLowerCase(),n=!Number.isNaN(yr(e));return(hr.test(t)&&!e.disabled||e instanceof HTMLAnchorElement&&e.href||n)&&vr(e)}function xr(e){let t=yr(e);return(Number.isNaN(t)||t>=0)&&br(e)}function Sr(e){return Array.from(e.querySelectorAll(gr)).filter(xr)}function Cr(e,t){let n=Sr(e);if(!n.length){t.preventDefault();return}let r=n[t.shiftKey?0:n.length-1],i=e.getRootNode(),a=r===i.activeElement||e===i.activeElement,o=i.activeElement;if(o.tagName===`INPUT`&&o.getAttribute(`type`)===`radio`&&(a=n.filter(e=>e.getAttribute(`type`)===`radio`&&e.getAttribute(`name`)===o.getAttribute(`name`)).includes(r)),!a)return;t.preventDefault();let s=n[t.shiftKey?n.length-1:0];s&&s.focus()}function wr(e=!0){let t=(0,M.useRef)(null),n=e=>{let t=e.querySelector(`[data-autofocus]`);if(!t){let n=Array.from(e.querySelectorAll(gr));t=n.find(xr)||n.find(br)||null,!t&&br(e)&&(t=e)}t?t.focus({preventScroll:!0}):console.warn(`[@mantine/hooks/use-focus-trap] Failed to find focusable element within provided node`,e)},r=(0,M.useCallback)(r=>{if(e){if(r===null){t.current=null;return}t.current!==r&&(setTimeout(()=>{r.getRootNode()?n(r):console.warn(`[@mantine/hooks/use-focus-trap] Ref node is not part of the dom`,r)}),t.current=r)}},[e]);return(0,M.useEffect)(()=>{if(!e)return;t.current&&setTimeout(()=>{t.current&&n(t.current)});let r=e=>{e.key===`Tab`&&t.current&&Cr(t.current,e)};return document.addEventListener(`keydown`,r),()=>document.removeEventListener(`keydown`,r)},[e]),r}function Tr(e,t,n){let r=(0,M.useEffectEvent)(t);(0,M.useEffect)(()=>(window.addEventListener(e,r,n),()=>window.removeEventListener(e,r,n)),[e])}function Er({value:e,defaultValue:t,finalValue:n,onChange:r=()=>{}}){let[i,a]=(0,M.useState)(t===void 0?n:t);return e===void 0?[i,(e,...t)=>{a(e),r?.(e,...t)},!1]:[e,r,!0]}function Dr(e=!1,t={}){let[n,r]=(0,M.useState)(e),i=(0,M.useCallback)(()=>{r(e=>e||(t.onOpen?.(),!0))},[t.onOpen]),a=(0,M.useCallback)(()=>{r(e=>e&&(t.onClose?.(),!1))},[t.onClose]);return[n,{open:i,close:a,toggle:(0,M.useCallback)(()=>{n?a():i()},[a,i,n]),set:r}]}var Or=[`mouse`,`touch`],kr=10;function Ar(e,t={}){let{threshold:n=400,events:r=Or,cancelOnMove:i=!1,onStart:a,onFinish:o,onCancel:s}=t,c=(0,M.useRef)(!1),l=(0,M.useRef)(!1),u=(0,M.useRef)(-1),d=(0,M.useRef)(null);(0,M.useEffect)(()=>()=>window.clearTimeout(u.current),[]);let f=r.join(`,`);return(0,M.useMemo)(()=>{if(typeof e!=`function`)return{};let t=i!==!1,f=i===!0?kr:i===!1?0:i,p=t=>{(Nr(t)||Mr(t))&&(a&&a(t),d.current=jr(t),l.current=!0,u.current=window.setTimeout(()=>{e(t),c.current=!0},n))},m=e=>{(Nr(e)||Mr(e))&&(c.current?o&&o(e):l.current&&s&&s(e),c.current=!1,l.current=!1,d.current=null,u.current!==-1&&(window.clearTimeout(u.current),u.current=-1))},h=e=>{if(!t||!l.current||c.current)return;let n=jr(e);if(!n||!d.current)return;let r=n.x-d.current.x,i=n.y-d.current.y;Math.sqrt(r*r+i*i)>f&&m(e)},g={};return r.includes(`mouse`)&&(g.onMouseDown=p,g.onMouseUp=m,g.onMouseLeave=m,t&&(g.onMouseMove=h)),r.includes(`touch`)&&(g.onTouchStart=p,g.onTouchEnd=m,g.onTouchCancel=m,t&&(g.onTouchMove=h)),g},[e,n,s,o,a,i,f])}function jr(e){if(Mr(e)){let t=e.touches[0]??e.changedTouches[0];return t?{x:t.clientX,y:t.clientY}:null}return{x:e.clientX,y:e.clientY}}function Mr(e){return window.TouchEvent?e.nativeEvent instanceof TouchEvent:`touches`in e.nativeEvent}function Nr(e){return e.nativeEvent instanceof MouseEvent}function Pr(e){return e===`auto`||e===`dark`||e===`light`}function Fr({key:e=`mantine-color-scheme-value`}={}){let t;return{get:t=>{if(typeof window>`u`)return t;try{let n=window.localStorage.getItem(e);return Pr(n)?n:t}catch{return t}},set:t=>{try{window.localStorage.setItem(e,t)}catch(e){console.warn(`[@mantine/core] Local storage color scheme manager was unable to save color scheme.`,e)}},subscribe:n=>{t=t=>{t.storageArea===window.localStorage&&t.key===e&&Pr(t.newValue)&&n(t.newValue)},window.addEventListener(`storage`,t)},unsubscribe:()=>{window.removeEventListener(`storage`,t)},clear:()=>{window.localStorage.removeItem(e)}}}function Ir({color:e,theme:t,autoContrast:n,colorScheme:r}){return(typeof n==`boolean`?n:t.autoContrast)&&Te({color:e||t.primaryColor,theme:t,colorScheme:r}).isLight?`var(--mantine-color-black)`:`var(--mantine-color-white)`}function Lr(e,t,n){return Ir({color:n===`dark`?e.dark:e.light,theme:t,colorScheme:n,autoContrast:!0})}function Rr(e,t){let n=e.colors[e.primaryColor];return f(n)?e.autoContrast?Lr(n,e,t):`var(--mantine-color-white)`:Ir({color:n[h(e,t)],theme:e,autoContrast:null})}function zr(e){let t=document.createElement(`style`);return t.setAttribute(`data-mantine-styles`,`inline`),t.innerHTML=`*, *::before, *::after {transition: none !important;}`,t.setAttribute(`data-mantine-disable-transition`,`true`),e&&t.setAttribute(`nonce`,e),document.head.appendChild(t),()=>document.querySelectorAll(`[data-mantine-disable-transition]`).forEach(e=>e.remove())}function Br({keepTransitions:e}={}){let t=(0,M.useRef)(ir),n=(0,M.useRef)(-1),r=(0,M.use)(m),i=l(),a=(0,M.useRef)(i?.());if(!r)throw Error(`[@mantine/core] MantineProvider was not found in tree`);let o=i=>{r.setColorScheme(i),t.current=e?()=>{}:zr(a.current),window.clearTimeout(n.current),n.current=window.setTimeout(()=>{t.current?.()},10)},s=()=>{r.clearColorScheme(),t.current=e?()=>{}:zr(a.current),window.clearTimeout(n.current),n.current=window.setTimeout(()=>{t.current?.()},10)},c=fr(`light`,{getInitialValueInEffect:!1}),u=r.colorScheme===`auto`?c:r.colorScheme,d=(0,M.useCallback)(()=>o(u===`light`?`dark`:`light`),[o,u]);return(0,M.useEffect)(()=>()=>{t.current?.(),window.clearTimeout(n.current)},[]),{colorScheme:r.colorScheme,setColorScheme:o,clearColorScheme:s,toggleColorScheme:d}}function Vr(e,t){let n=typeof window<`u`&&`matchMedia`in window&&window.matchMedia(`(prefers-color-scheme: dark)`)?.matches,r=e===`auto`?n?`dark`:`light`:e;t()?.setAttribute(`data-mantine-color-scheme`,r)}function Hr({manager:e,defaultColorScheme:t,getRootElement:n,forceColorScheme:r}){let i=(0,M.useRef)(null),[a,o]=(0,M.useState)(()=>e.get(t)),s=r||a,c=(0,M.useCallback)(t=>{r||(Vr(t,n),o(t),e.set(t))},[e.set,s,r]),l=(0,M.useCallback)(()=>{o(t),Vr(t,n),e.clear()},[e.clear,t]);return(0,M.useEffect)(()=>(e.subscribe(c),e.unsubscribe),[e.subscribe,e.unsubscribe]),he(()=>{Vr(e.get(t),n)},[]),(0,M.useEffect)(()=>{if(r)return Vr(r,n),()=>{};r===void 0&&Vr(a,n),typeof window<`u`&&`matchMedia`in window&&(i.current=window.matchMedia(`(prefers-color-scheme: dark)`));let e=e=>{a===`auto`&&Vr(e.matches?`dark`:`light`,n)};return i.current?.addEventListener(`change`,e),()=>i.current?.removeEventListener(`change`,e)},[a,r]),{colorScheme:s,setColorScheme:c,clearColorScheme:l}}function Ur(e,t={getInitialValueInEffect:!0}){let n=fr(e,t),{colorScheme:r}=Br();return r===`auto`?n:r}function Wr(e){return Object.entries(e).map(([e,t])=>`${e}: ${t};`).join(``)}function Gr(e,t){let n=t?[t]:[`:root`,`:host`],r=Wr(e.variables),i=r?`${n.join(`, `)}{${r}}`:``,a=Wr(e.dark),o=Wr(e.light),s=e=>n.map(t=>t===`:host`?`${t}([data-mantine-color-scheme="${e}"])`:`${t}[data-mantine-color-scheme="${e}"]`).join(`, `);return`${i}\n\n${a?`${s(`dark`)}{${a}}`:``}\n\n${o?`${s(`light`)}{${o}}`:``}`}function Kr({theme:e,color:t,colorScheme:n,name:r=t,withColorValues:i=!0}){if(!e.colors[t])return{};if(n===`light`){let n=h(e,`light`),a={[`--mantine-color-${r}-text`]:`var(--mantine-color-${r}-filled)`,[`--mantine-color-${r}-filled`]:`var(--mantine-color-${r}-${n})`,[`--mantine-color-${r}-filled-hover`]:`var(--mantine-color-${r}-${n===9?8:n+1})`,[`--mantine-color-${r}-light`]:`var(--mantine-color-${r}-1)`,[`--mantine-color-${r}-light-hover`]:`var(--mantine-color-${r}-2)`,[`--mantine-color-${r}-light-color`]:`var(--mantine-color-${r}-9)`,[`--mantine-color-${r}-outline`]:`var(--mantine-color-${r}-${n})`,[`--mantine-color-${r}-outline-hover`]:p(e.colors[t][n],.05)};return i?{[`--mantine-color-${r}-0`]:e.colors[t][0],[`--mantine-color-${r}-1`]:e.colors[t][1],[`--mantine-color-${r}-2`]:e.colors[t][2],[`--mantine-color-${r}-3`]:e.colors[t][3],[`--mantine-color-${r}-4`]:e.colors[t][4],[`--mantine-color-${r}-5`]:e.colors[t][5],[`--mantine-color-${r}-6`]:e.colors[t][6],[`--mantine-color-${r}-7`]:e.colors[t][7],[`--mantine-color-${r}-8`]:e.colors[t][8],[`--mantine-color-${r}-9`]:e.colors[t][9],...a}:a}let a=h(e,`dark`),o={[`--mantine-color-${r}-text`]:`var(--mantine-color-${r}-4)`,[`--mantine-color-${r}-filled`]:`var(--mantine-color-${r}-${a})`,[`--mantine-color-${r}-filled-hover`]:`var(--mantine-color-${r}-${a===9?8:a+1})`,[`--mantine-color-${r}-light`]:E(e.colors[t][9],.5),[`--mantine-color-${r}-light-hover`]:E(e.colors[t][9],.3),[`--mantine-color-${r}-light-color`]:`var(--mantine-color-${r}-0)`,[`--mantine-color-${r}-outline`]:`var(--mantine-color-${r}-${Math.max(a-4,0)})`,[`--mantine-color-${r}-outline-hover`]:p(e.colors[t][Math.max(a-4,0)],.05)};return i?{[`--mantine-color-${r}-0`]:e.colors[t][0],[`--mantine-color-${r}-1`]:e.colors[t][1],[`--mantine-color-${r}-2`]:e.colors[t][2],[`--mantine-color-${r}-3`]:e.colors[t][3],[`--mantine-color-${r}-4`]:e.colors[t][4],[`--mantine-color-${r}-5`]:e.colors[t][5],[`--mantine-color-${r}-6`]:e.colors[t][6],[`--mantine-color-${r}-7`]:e.colors[t][7],[`--mantine-color-${r}-8`]:e.colors[t][8],[`--mantine-color-${r}-9`]:e.colors[t][9],...o}:o}function qr(e,t,n){de(t).forEach(r=>Object.assign(e,{[`--mantine-${n}-${r}`]:t[r]}))}var Jr=e=>{let t=h(e,`light`),n=e.defaultRadius in e.radius?e.radius[e.defaultRadius]:j(e.defaultRadius),r={variables:{"--mantine-z-index-app":`100`,"--mantine-z-index-modal":`200`,"--mantine-z-index-popover":`300`,"--mantine-z-index-overlay":`400`,"--mantine-z-index-max":`9999`,"--mantine-scale":e.scale.toString(),"--mantine-cursor-type":e.cursorType,"--mantine-webkit-font-smoothing":e.fontSmoothing?`antialiased`:`unset`,"--mantine-moz-font-smoothing":e.fontSmoothing?`grayscale`:`unset`,"--mantine-color-white":e.white,"--mantine-color-black":e.black,"--mantine-line-height":e.lineHeights.md,"--mantine-font-family":e.fontFamily,"--mantine-font-family-monospace":e.fontFamilyMonospace,"--mantine-font-family-headings":e.headings.fontFamily,"--mantine-heading-font-weight":e.headings.fontWeight,"--mantine-heading-text-wrap":e.headings.textWrap,"--mantine-radius-default":n,"--mantine-primary-color-filled":`var(--mantine-color-${e.primaryColor}-filled)`,"--mantine-primary-color-filled-hover":`var(--mantine-color-${e.primaryColor}-filled-hover)`,"--mantine-primary-color-light":`var(--mantine-color-${e.primaryColor}-light)`,"--mantine-primary-color-light-hover":`var(--mantine-color-${e.primaryColor}-light-hover)`,"--mantine-primary-color-light-color":`var(--mantine-color-${e.primaryColor}-light-color)`},light:{"--mantine-color-scheme":`light`,"--mantine-primary-color-contrast":Rr(e,`light`),"--mantine-color-bright":`var(--mantine-color-black)`,"--mantine-color-text":e.black,"--mantine-color-body":e.white,"--mantine-color-error":`var(--mantine-color-red-6)`,"--mantine-color-success":`var(--mantine-color-teal-8)`,"--mantine-color-placeholder":`var(--mantine-color-gray-5)`,"--mantine-color-anchor":`var(--mantine-color-${e.primaryColor}-${t})`,"--mantine-color-default":`var(--mantine-color-white)`,"--mantine-color-default-hover":`var(--mantine-color-gray-0)`,"--mantine-color-default-color":`var(--mantine-color-black)`,"--mantine-color-default-border":`var(--mantine-color-gray-4)`,"--mantine-color-dimmed":`var(--mantine-color-gray-6)`,"--mantine-color-disabled":`var(--mantine-color-gray-2)`,"--mantine-color-disabled-color":`var(--mantine-color-gray-5)`,"--mantine-color-disabled-border":`var(--mantine-color-gray-3)`},dark:{"--mantine-color-scheme":`dark`,"--mantine-primary-color-contrast":Rr(e,`dark`),"--mantine-color-bright":`var(--mantine-color-white)`,"--mantine-color-text":`var(--mantine-color-dark-0)`,"--mantine-color-body":`var(--mantine-color-dark-7)`,"--mantine-color-error":`var(--mantine-color-red-8)`,"--mantine-color-success":`var(--mantine-color-teal-8)`,"--mantine-color-placeholder":`var(--mantine-color-dark-3)`,"--mantine-color-anchor":`var(--mantine-color-${e.primaryColor}-4)`,"--mantine-color-default":`var(--mantine-color-dark-6)`,"--mantine-color-default-hover":`var(--mantine-color-dark-5)`,"--mantine-color-default-color":`var(--mantine-color-white)`,"--mantine-color-default-border":`var(--mantine-color-dark-4)`,"--mantine-color-dimmed":`var(--mantine-color-dark-2)`,"--mantine-color-disabled":`var(--mantine-color-dark-6)`,"--mantine-color-disabled-color":`var(--mantine-color-dark-3)`,"--mantine-color-disabled-border":`var(--mantine-color-dark-4)`}};qr(r.variables,e.breakpoints,`breakpoint`),qr(r.variables,e.spacing,`spacing`),qr(r.variables,e.fontSizes,`font-size`),qr(r.variables,e.lineHeights,`line-height`),qr(r.variables,e.shadows,`shadow`),qr(r.variables,e.radius,`radius`),qr(r.variables,e.fontWeights,`font-weight`),e.colors[e.primaryColor].forEach((t,n)=>{r.variables[`--mantine-primary-color-${n}`]=`var(--mantine-color-${e.primaryColor}-${n})`}),de(e.colors).forEach(t=>{let n=e.colors[t];if(f(n)){Object.assign(r.light,Kr({theme:e,name:n.name,color:n.light,colorScheme:`light`,withColorValues:!0})),Object.assign(r.dark,Kr({theme:e,name:n.name,color:n.dark,colorScheme:`dark`,withColorValues:!0})),r.light[`--mantine-color-${n.name}-contrast`]=Lr(n,e,`light`),r.dark[`--mantine-color-${n.name}-contrast`]=Lr(n,e,`dark`);return}n.forEach((e,n)=>{r.variables[`--mantine-color-${t}-${n}`]=e}),Object.assign(r.light,Kr({theme:e,color:t,colorScheme:`light`,withColorValues:!1})),Object.assign(r.dark,Kr({theme:e,color:t,colorScheme:`dark`,withColorValues:!1}))});let i=e.headings.sizes;return de(i).forEach(t=>{r.variables[`--mantine-${t}-font-size`]=i[t].fontSize,r.variables[`--mantine-${t}-line-height`]=i[t].lineHeight,r.variables[`--mantine-${t}-font-weight`]=i[t].fontWeight||e.headings.fontWeight}),r};function Yr(){let e=b(),t=l(),n=de(e.breakpoints).reduce((t,n)=>{let r=e.breakpoints[n].includes(`px`),i=Qn(e.breakpoints[n]);return`${t}@media (max-width: ${r?`${i-.1}px`:we(i-.1)}) {.mantine-visible-from-${n} {display: none !important;}}@media (min-width: ${r?`${i}px`:we(i)}) {.mantine-hidden-from-${n} {display: none !important;}}`},``);return(0,N.jsx)(`style`,{"data-mantine-styles":`classes`,nonce:t?.(),dangerouslySetInnerHTML:{__html:n}})}function Xr({theme:e,generator:t}){let n=Jr(e),r=t?.(e);return r?pe(n,r):n}var Zr=Jr(d);function Qr(e){let t={variables:{},light:{},dark:{}};return de(e.variables).forEach(n=>{Zr.variables[n]!==e.variables[n]&&(t.variables[n]=e.variables[n])}),de(e.light).forEach(n=>{Zr.light[n]!==e.light[n]&&(t.light[n]=e.light[n])}),de(e.dark).forEach(n=>{Zr.dark[n]!==e.dark[n]&&(t.dark[n]=e.dark[n])}),t}function $r(e){return Gr({variables:{},dark:{"--mantine-color-scheme":`dark`},light:{"--mantine-color-scheme":`light`}},e)}function ei({cssVariablesSelector:e,deduplicateCssVariables:t}){let n=b(),r=l(),i=Xr({theme:n,generator:S()}),a=(e===void 0||e===`:root`||e===`:host`)&&t,o=Gr(a?Qr(i):i,e);return o?(0,N.jsx)(`style`,{"data-mantine-styles":!0,nonce:r?.(),dangerouslySetInnerHTML:{__html:`${o}${a?``:$r(e)}`}}):null}ei.displayName=`@mantine/CssVariables`;function ti({respectReducedMotion:e,getRootElement:t}){he(()=>{e&&t()?.setAttribute(`data-respect-reduced-motion`,`true`)},[e])}function ni({theme:e,children:t,getStyleNonce:n,withStaticClasses:r=!0,withGlobalClasses:i=!0,deduplicateCssVariables:a=!0,withCssVariables:o=!0,cssVariablesSelector:s,classNamesPrefix:c=`mantine`,colorSchemeManager:l=Fr(),defaultColorScheme:u=`light`,getRootElement:d=()=>document.documentElement,cssVariablesResolver:f,forceColorScheme:p,stylesTransform:h,env:g,deduplicateInlineStyles:_=!1}){let{colorScheme:v,setColorScheme:b,clearColorScheme:x}=Hr({defaultColorScheme:u,forceColorScheme:p,manager:l,getRootElement:d});return ti({respectReducedMotion:e?.respectReducedMotion||!1,getRootElement:d}),(0,N.jsx)(m,{value:{colorScheme:v,setColorScheme:b,clearColorScheme:x,getRootElement:d,classNamesPrefix:c,getStyleNonce:n,cssVariablesResolver:f,cssVariablesSelector:s??`:root`,withStaticClasses:r,stylesTransform:h,env:g,deduplicateInlineStyles:_},children:(0,N.jsxs)(y,{theme:e,children:[o&&(0,N.jsx)(ei,{cssVariablesSelector:s,deduplicateCssVariables:a}),i&&(0,N.jsx)(Yr,{}),t]})})}ni.displayName=`@mantine/core/MantineProvider`;function ri(e){return e}var ii={root:`m_515a97f8`},ai=w(e=>{let t=v(`VisuallyHidden`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,attributes:l,...d}=t,f=c({name:`VisuallyHidden`,classes:ii,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:l});return(0,N.jsx)(u,{component:`span`,...f(`root`),...d})});ai.classes=ii,ai.displayName=`@mantine/core/VisuallyHidden`;function oi({open:e,close:t,openDelay:n,closeDelay:r}){let i=(0,M.useRef)(-1),a=(0,M.useRef)(-1),o=()=>{window.clearTimeout(i.current),window.clearTimeout(a.current)};return(0,M.useEffect)(()=>o,[]),{openDropdown:()=>{o(),n===0||n===void 0?e():i.current=window.setTimeout(e,n)},closeDropdown:()=>{o(),r===0||r===void 0?t():a.current=window.setTimeout(t,r)}}}var si={root:`m_9814e45f`},ci={zIndex:ft(`modal`)},li=D((e,{gradient:t,color:n,backgroundOpacity:r,blur:i,radius:a,zIndex:o})=>({root:{"--overlay-bg":t||(n!==void 0||r!==void 0)&&T(n||`#000`,r??.6)||void 0,"--overlay-filter":i?`blur(${j(i)})`:void 0,"--overlay-radius":a===void 0?void 0:Oe(a),"--overlay-z-index":o?.toString()}})),ui=Pe(e=>{let t=v(`Overlay`,ci,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,fixed:l,center:d,children:f,radius:p,zIndex:m,gradient:h,blur:g,color:_,backgroundOpacity:y,mod:b,attributes:x,...S}=t,C=c({name:`Overlay`,props:t,classes:si,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:x,vars:s,varsResolver:li});return(0,N.jsx)(u,{...C(`root`),mod:[{center:d,fixed:l},b],...S,children:f})});ui.classes=si,ui.varsResolver=li,ui.displayName=`@mantine/core/Overlay`;var[di,fi]=dt(`Popover component was not found in the tree`);function pi({childProps:e,disabled:t,opened:n,longPressDelay:r=500,setReference:i,open:a}){let o=(0,M.useRef)(!1),s=(0,M.useRef)(!1),c=(0,M.useRef)(null),l=(0,M.useRef)(t);l.current=t;let u=(e,t,n)=>{i({getBoundingClientRect:()=>({x:e,y:t,width:0,height:0,top:t,left:e,right:e,bottom:t,toJSON:()=>void 0}),contextElement:n}),a()},d=or(e.onMouseDown,e=>{t||e.button===2&&e.stopPropagation()}),f=or(e.onContextMenu,e=>{t||e.defaultPrevented||(e.preventDefault(),!s.current&&(u(e.clientX,e.clientY,e.currentTarget),o.current&&(s.current=!0)))}),p=Ar(e=>{if(l.current||s.current)return;let t=e,n=t.touches[0]??t.changedTouches[0];n&&(u(n.clientX,n.clientY,c.current),s.current=!0)},{threshold:r,events:[`touch`],cancelOnMove:!0,onStart:e=>{o.current=!0,s.current=!1,c.current=e.currentTarget},onFinish:e=>{o.current=!1,s.current=!1,l.current||e.preventDefault()},onCancel:()=>{o.current=!1,s.current=!1}});return{onContextMenu:f,onMouseDown:d,onTouchStart:or(e.onTouchStart,p.onTouchStart),onTouchEnd:or(e.onTouchEnd,p.onTouchEnd),onTouchCancel:or(e.onTouchCancel,p.onTouchCancel),onTouchMove:or(e.onTouchMove,p.onTouchMove),style:t?e.style:{...e.style,WebkitTouchCallout:`none`,WebkitUserSelect:`none`,userSelect:`none`},"data-expanded":n?!0:void 0}}function mi(e){let{children:t,disabled:n,longPressDelay:r}=v(`PopoverContextMenu`,null,e),i=te(t);if(!i)throw Error(`Popover.ContextMenu component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let a=fi(),o=pi({childProps:i.props,disabled:n||a.disabled,opened:a.opened,longPressDelay:r,setReference:a.reference,open:()=>{a.opened||a.onToggle()}});return(0,M.cloneElement)(i,o)}mi.displayName=`@mantine/core/PopoverContextMenu`;function hi({children:e,active:t=!0,refProp:n=`ref`,innerRef:r}){let i=wr(t),a=Ae(i,r),o=te(e);return o?(0,M.cloneElement)(o,{[n]:a}):e}function gi(e){return(0,N.jsx)(ai,{tabIndex:-1,"data-autofocus":!0,...e})}hi.displayName=`@mantine/core/FocusTrap`,gi.displayName=`@mantine/core/FocusTrapInitialFocus`,hi.InitialFocus=gi;var _i={dropdown:`m_38a85659`,arrow:`m_a31dc6c1`,overlay:`m_3d7bc908`},vi=w(e=>{let t=v(`PopoverDropdown`,null,e),{className:n,style:r,vars:i,children:a,onKeyDownCapture:o,variant:s,classNames:c,styles:l,ref:d,...f}=t,p=fi(),{dir:m}=jt(),h=p.arrowPosition===`merge`&&p.withArrow?mt({position:p.placement,dir:m}):void 0,g=mr({opened:p.opened,shouldReturnFocus:p.returnFocus}),_=p.withRoles?{"aria-labelledby":p.getTargetId(),id:p.getDropdownId(),role:`dialog`,tabIndex:-1}:{},y=Ae(d,p.floating);return p.disabled?null:(0,N.jsx)(Ct,{...p.portalProps,withinPortal:p.withinPortal,children:(0,N.jsx)(ae,{mounted:p.opened,...p.transitionProps,transition:p.transitionProps?.transition||`fade`,duration:p.transitionProps?.duration??150,keepMounted:p.keepMounted,keepMountedMode:p.keepMountedMode,exitDuration:typeof p.transitionProps?.exitDuration==`number`?p.transitionProps.exitDuration:p.transitionProps?.duration,children:e=>(0,N.jsx)(hi,{active:p.trapFocus&&p.opened,innerRef:y,children:(0,N.jsxs)(u,{..._,...f,variant:s,onKeyDownCapture:ar(()=>{p.onClose?.(),p.onDismiss?.()},{active:p.closeOnEscape,onTrigger:g,onKeyDown:o}),"data-position":p.placement,"data-fixed":p.floatingStrategy===`fixed`||void 0,...p.getStyles(`dropdown`,{className:n,props:t,classNames:c,styles:l,style:[{...e,...h,zIndex:p.zIndex,top:p.y??0,left:p.x??0,width:p.width===`target`?void 0:j(p.width),...p.referenceHidden?{display:`none`}:null},p.resolvedStyles?.dropdown,l?.dropdown,r]}),children:[a,(0,N.jsx)(bt,{ref:p.arrowRef,arrowX:p.arrowX,arrowY:p.arrowY,visible:p.withArrow,position:p.placement,arrowSize:p.arrowSize,arrowRadius:p.arrowRadius,arrowOffset:p.arrowOffset,arrowPosition:p.arrowPosition,...p.getStyles(`arrow`,{props:t,classNames:c,styles:l})})]})})})})});vi.classes=_i,vi.displayName=`@mantine/core/PopoverDropdown`;var yi={refProp:`ref`,popupType:`dialog`},bi=w(e=>{let{children:t,refProp:n,popupType:r,ref:i,...a}=v(`PopoverTarget`,yi,e),o=te(t);if(!o)throw Error(`Popover.Target component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let s=a,c=fi(),l=Ae(c.reference,ut(o),i),u=c.withRoles?{"aria-haspopup":r,"aria-expanded":c.opened,"aria-controls":c.opened?c.getDropdownId():void 0,id:c.getTargetId()}:{},d=o.props;return(0,M.cloneElement)(o,{...s,...u,...c.targetProps,className:O(c.targetProps.className,s.className,d.className),[n]:l,...c.controlled?null:{onClick:e=>{c.onToggle(),d.onClick?.(e)}}})});bi.displayName=`@mantine/core/PopoverTarget`;function xi(e){if(e===void 0)return{shift:!0,flip:!0};let t={...e};return e.shift===void 0&&(t.shift=!0),e.flip===void 0&&(t.flip=!0),t}function Si(e,t,n,r){let i=xi(e.middlewares),a=[vt(e.offset),Tt()];if(i.flip&&!n){let e=typeof i.flip==`boolean`?{}:i.flip,t=r?{fallbackStrategy:`initialPlacement`,...e}:e;a.push(_t(t))}if(i.shift){let t=typeof i.shift==`boolean`?{}:i.shift;a.push(pt(n=>{let r=n.placement.startsWith(`top`)||n.placement.startsWith(`bottom`);return{limiter:yt(),padding:5,...e.width===`target`&&r?{mainAxis:!1}:null,...t}}))}return i.inline&&a.push(typeof i.inline==`boolean`?St():St(i.inline)),a.push(gt({element:e.arrowRef,padding:e.arrowOffset})),(i.size||e.width===`target`)&&a.push(At({...typeof i.size==`boolean`?{}:i.size,apply({rects:n,availableWidth:r,availableHeight:a,...o}){let s=t().refs.floating.current?.style??{};i.size&&(typeof i.size==`object`&&i.size.apply?i.size.apply({rects:n,availableWidth:r,availableHeight:a,...o}):Object.assign(s,{maxWidth:`${r}px`,maxHeight:`${a}px`})),e.width===`target`&&Object.assign(s,{width:`${n.reference.width}px`})}})),a}function Ci(e){let[t,n]=Er({value:e.opened,defaultValue:e.defaultOpened,finalValue:!1,onChange:e.onChange}),r=(0,M.useRef)(t),i=(0,M.useRef)(!1),[a,o]=(0,M.useState)(null),s=e.preventPositionChangeWhenVisible!==!1,c=(0,M.useRef)(t);t!==c.current&&(c.current=t,t&&a!==null&&o(null));let l=(0,M.useRef)(e.position);e.position!==l.current&&(l.current=e.position,i.current=!1,a!==null&&o(null));let u=(0,M.useCallback)(()=>o(null),[]),d=()=>{t&&!e.disabled&&n(!1)},f=()=>{e.disabled||n(!t)},p=ht({open:t,strategy:e.strategy,placement:s?a??e.position:e.position,middleware:Si(e,()=>p,s&&a!==null,s),whileElementsMounted:e.keepMounted?void 0:Mt});(0,M.useEffect)(()=>{if(!e.keepMounted)return;let n=p.refs.reference.current,r=p.refs.floating.current;if(t&&n&&r)return Mt(n,r,p.update)},[e.keepMounted,t,p.update,p.elements.reference,p.elements.floating]),he(()=>{if(!t){i.current=!1;return}if(!s||a!==null)return;let e=p.refs.floating.current;if(e&&e.offsetHeight!==0&&e.offsetWidth!==0){if(!i.current){i.current=!0,p.update();return}p.isPositioned&&o(p.placement)}},[s,t,p.isPositioned,p.placement,a,p.update]);let m=(0,M.useRef)(p.placement);return he(()=>{m.current!==p.placement&&(m.current=p.placement,e.onPositionChange?.(p.placement))},[p.placement]),De(()=>{t!==r.current&&(t?e.onOpen?.():e.onClose?.()),r.current=t},[t,e.onClose,e.onOpen]),{floating:p,controlled:typeof e.opened==`boolean`,opened:t,onClose:d,onToggle:f,resetLockedPlacement:u}}var wi={position:`bottom`,offset:8,transitionProps:{transition:`fade`,duration:150},middlewares:{flip:!0,shift:!0,inline:!1},arrowSize:7,arrowOffset:5,arrowRadius:0,arrowPosition:`side`,closeOnClickOutside:!0,withinPortal:!0,closeOnEscape:!0,trapFocus:!1,withRoles:!0,returnFocus:!1,withOverlay:!1,hideDetached:!0,preventPositionChangeWhenVisible:!0,clickOutsideEvents:[`mousedown`,`touchstart`],clickOutsideCapture:!1,zIndex:ft(`popover`),__staticSelector:`Popover`,width:`max-content`},Ti=D((e,{radius:t,shadow:n})=>({dropdown:{"--popover-radius":t===void 0?void 0:Oe(t),"--popover-shadow":se(n)}}));function Ei(e){let t=v(`Popover`,wi,e),{children:n,position:r,offset:i,onPositionChange:a,opened:o,transitionProps:s,onExitTransitionEnd:l,onEnterTransitionEnd:u,width:d,middlewares:f,withArrow:p,arrowSize:m,arrowOffset:h,arrowRadius:g,arrowPosition:_,unstyled:y,classNames:b,styles:x,closeOnClickOutside:S,withinPortal:C,portalProps:w,closeOnEscape:T,clickOutsideEvents:ee,clickOutsideCapture:E,trapFocus:D,onClose:O,onDismiss:te,onOpen:ne,onChange:re,zIndex:k,radius:ie,shadow:oe,id:se,defaultOpened:ce,__staticSelector:le,withRoles:ue,disabled:de,returnFocus:fe,variant:pe,keepMounted:me,keepMountedMode:he,vars:_e,floatingStrategy:ve,withOverlay:ye,overlayProps:A,hideDetached:j,attributes:xe,preventPositionChangeWhenVisible:Se,...Ce}=t,we=c({name:le,props:t,classes:_i,classNames:b,styles:x,unstyled:y,attributes:xe,rootSelector:`dropdown`,vars:_e,varsResolver:Ti}),{resolvedStyles:Te}=ge({classNames:b,styles:x,props:t}),Ee=(0,M.useRef)(null),[De,Oe]=(0,M.useState)(null),[ke,Ae]=(0,M.useState)(null),{dir:je}=jt(),Me=Le(),Ne=be(se),Pe=Ci({middlewares:f,width:d,position:Et(je,r),offset:typeof i==`number`?i+(p?m/2:0):i,arrowRef:Ee,arrowOffset:h,onPositionChange:a,opened:o,defaultOpened:ce,onChange:re,onOpen:ne,onClose:O,onDismiss:te,strategy:ve,disabled:de,preventPositionChangeWhenVisible:Se,keepMounted:me});dr(()=>{S&&(Pe.onClose(),te?.())},ee,[De,ke],!0,E);let Fe=(0,M.useCallback)(e=>{Oe(e),Pe.floating.refs.setReference(e)},[Pe.floating.refs.setReference]),Ie=(0,M.useCallback)(e=>{Ae(e),Pe.floating.refs.setFloating(e)},[Pe.floating.refs.setFloating]),Re=(0,M.useCallback)(()=>{s?.onExited?.(),l?.(),Pe.resetLockedPlacement()},[s?.onExited,l,Pe.resetLockedPlacement]),ze=(0,M.useCallback)(()=>{s?.onEntered?.(),u?.()},[s?.onEntered,u]);return(0,N.jsxs)(di,{value:{returnFocus:fe,disabled:de,controlled:Pe.controlled,reference:Fe,floating:Ie,x:Pe.floating.x,y:Pe.floating.y,arrowX:Pe.floating?.middlewareData?.arrow?.x,arrowY:Pe.floating?.middlewareData?.arrow?.y,opened:Pe.opened,arrowRef:Ee,transitionProps:{...s,onExited:Re,onEntered:ze},width:d,withArrow:p,arrowSize:m,arrowOffset:h,arrowRadius:g,arrowPosition:_,placement:Pe.floating.placement,trapFocus:D,withinPortal:C,portalProps:w,zIndex:k,radius:ie,shadow:oe,closeOnEscape:T,onDismiss:te,onClose:Pe.onClose,onToggle:Pe.onToggle,getTargetId:()=>Ne,getDropdownId:()=>`${Ne}-dropdown`,withRoles:ue,targetProps:Ce,__staticSelector:le,classNames:b,styles:x,unstyled:y,variant:pe,keepMounted:me,keepMountedMode:he,getStyles:we,resolvedStyles:Te,floatingStrategy:ve,referenceHidden:j&&Me!==`test`?Pe.floating.middlewareData.hide?.referenceHidden:!1},children:[n,ye&&(0,N.jsx)(ae,{transition:`fade`,mounted:Pe.opened,duration:s?.duration||250,exitDuration:s?.exitDuration||250,children:e=>(0,N.jsx)(Ct,{withinPortal:C,children:(0,N.jsx)(ui,{...A,...we(`overlay`,{className:A?.className,style:[e,A?.style]})})})})]})}Ei.Target=bi,Ei.Dropdown=vi,Ei.ContextMenu=mi,Ei.varsResolver=Ti,Ei.displayName=`@mantine/core/Popover`,Ei.extend=e=>e,Ei.withProps=e=>{let t=t=>(0,N.jsx)(Ei,{...e,...t});return t.extend=Ei.extend,t.displayName=`WithProps(${Ei.displayName})`,t};var Di={root:`m_8d3f4000`,icon:`m_8d3afb97`,loader:`m_302b9fb1`,group:`m_1a0f1b21`,groupSection:`m_437b6484`},Oi={orientation:`horizontal`},ki=D((e,{borderWidth:t})=>({group:{"--ai-border-width":j(t)}})),Ai=w(e=>{let t=v(`ActionIconGroup`,Oi,e),{className:n,style:r,classNames:i,styles:a,unstyled:o,orientation:s,vars:l,borderWidth:d,variant:f,mod:p,attributes:m,...h}=t,g=c({name:`ActionIconGroup`,props:t,classes:Di,className:n,style:r,classNames:i,styles:a,unstyled:o,attributes:m,vars:l,varsResolver:ki,rootSelector:`group`});return(0,N.jsx)(u,{...g(`group`),variant:f,mod:[{orientation:s},p],role:`group`,...h})});Ai.classes=Di,Ai.varsResolver=ki,Ai.displayName=`@mantine/core/ActionIconGroup`;var ji=D((e,{radius:t,color:n,gradient:r,variant:i,autoContrast:a,size:o})=>{let s=e.variantColorResolver({color:n||e.primaryColor,theme:e,gradient:r,variant:i||`filled`,autoContrast:a});return{groupSection:{"--section-height":ye(o,`section-height`),"--section-padding-x":ye(o,`section-padding-x`),"--section-fz":Se(o),"--section-radius":t===void 0?void 0:Oe(t),"--section-bg":n||i?s.background:void 0,"--section-color":s.color,"--section-bd":n||i?s.border:void 0}}}),Mi=w(e=>{let t=v(`ActionIconGroupSection`,null,e),{className:n,style:r,classNames:i,styles:a,unstyled:o,vars:s,variant:l,gradient:d,radius:f,autoContrast:p,attributes:m,...h}=t,g=c({name:`ActionIconGroupSection`,props:t,classes:Di,className:n,style:r,classNames:i,styles:a,unstyled:o,attributes:m,vars:s,varsResolver:ji,rootSelector:`groupSection`});return(0,N.jsx)(u,{...g(`groupSection`),variant:l,...h})});Mi.classes=Di,Mi.varsResolver=ji,Mi.displayName=`@mantine/core/ActionIconGroupSection`;var Ni=D((e,{size:t,radius:n,variant:r,gradient:i,color:a,autoContrast:o})=>{let s=e.variantColorResolver({color:a||e.primaryColor,theme:e,gradient:i,variant:r||`filled`,autoContrast:o});return{root:{"--ai-size":ye(t,`ai-size`),"--ai-radius":n===void 0?void 0:Oe(n),"--ai-bg":a||r?s.background:void 0,"--ai-hover":a||r?s.hover:void 0,"--ai-hover-color":a||r?s.hoverColor:void 0,"--ai-color":s.color,"--ai-bd":a||r?s.border:void 0}}}),Pi=Pe(e=>{let t=v(`ActionIcon`,null,e),{className:n,unstyled:r,variant:i,classNames:a,styles:o,style:s,loading:l,loaderProps:d,size:f,color:p,radius:m,__staticSelector:h,gradient:g,vars:_,children:y,disabled:b,"data-disabled":x,autoContrast:S,mod:w,attributes:T,...ee}=t,E=c({name:[`ActionIcon`,h],props:t,className:n,style:s,classes:Di,classNames:a,styles:o,unstyled:r,attributes:T,vars:_,varsResolver:Ni});return(0,N.jsxs)(C,{...E(`root`,{active:!b&&!l&&!x}),"aria-busy":l||void 0,...ee,unstyled:r,variant:i,size:f,disabled:b||l,mod:[{loading:l,disabled:b||x},w],children:[typeof l==`boolean`&&(0,N.jsx)(ae,{mounted:l,transition:`slide-down`,duration:150,children:e=>(0,N.jsx)(u,{component:`span`,...E(`loader`,{style:e}),"aria-hidden":!0,children:(0,N.jsx)(Ie,{color:`var(--ai-color)`,size:`calc(var(--ai-size) * 0.55)`,...d})})}),(0,N.jsx)(u,{component:`span`,mod:{loading:l},...E(`icon`),children:y})]})});Pi.classes=Di,Pi.varsResolver=Ni,Pi.displayName=`@mantine/core/ActionIcon`,Pi.Group=Ai,Pi.GroupSection=Mi;var[Fi,Ii]=dt(`ModalBase component was not found in tree`);function Li({opened:e,transitionDuration:t}){let[n,r]=(0,M.useState)(e),i=(0,M.useRef)(-1),a=x()?0:t;return(0,M.useEffect)(()=>(e?(r(!0),window.clearTimeout(i.current)):a===0?r(!1):i.current=window.setTimeout(()=>r(!1),a),()=>window.clearTimeout(i.current)),[e,a]),n}function Ri({id:e,transitionProps:t,opened:n,trapFocus:r,closeOnEscape:i,onClose:a,returnFocus:o,handledEscapeEvents:s}){let c=be(e),[l,u]=(0,M.useState)(!1),[d,f]=(0,M.useState)(!1),p=Li({opened:n,transitionDuration:typeof t?.duration==`number`?t?.duration:200});return Tr(`keydown`,e=>{e.key===`Escape`&&i&&!e.isComposing&&n&&!s?.has(e)&&e.target?.getAttribute(`data-mantine-stop-propagation`)!==`true`&&(s?.add(e),a())},{capture:!0}),mr({opened:n,shouldReturnFocus:r&&o}),{_id:c,titleMounted:l,bodyMounted:d,shouldLockScroll:p,setTitleMounted:u,setBodyMounted:f}}var zi=function(){return zi=Object.assign||function(e){for(var t,n=1,r=arguments.length;n`u`)return pa;var t=ha(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},_a=fa(),va=`data-scroll-locked`,ya=function(e,t,n,r){var i=e.left,a=e.top,o=e.right,s=e.gap;return n===void 0&&(n=`margin`),` - .${Wi} { - overflow: hidden ${r}; - padding-right: ${s}px ${r}; - } - body[${va}] { - overflow: hidden ${r}; - overscroll-behavior: contain; - ${[t&&`position: relative ${r};`,n===`margin`&&` - padding-left: ${i}px; - padding-top: ${a}px; - padding-right: ${o}px; - margin-left:0; - margin-top:0; - margin-right: ${s}px ${r}; - `,n===`padding`&&`padding-right: ${s}px ${r};`].filter(Boolean).join(``)} - } - - .${Hi} { - right: ${s}px ${r}; - } - - .${Ui} { - margin-right: ${s}px ${r}; - } - - .${Hi} .${Hi} { - right: 0 ${r}; - } - - .${Ui} .${Ui} { - margin-right: 0 ${r}; - } - - body[${va}] { - ${Gi}: ${s}px; - } -`},ba=function(){var e=parseInt(document.body.getAttribute(`data-scroll-locked`)||`0`,10);return isFinite(e)?e:0},xa=function(){M.useEffect(function(){return document.body.setAttribute(va,(ba()+1).toString()),function(){var e=ba()-1;e<=0?document.body.removeAttribute(va):document.body.setAttribute(va,e.toString())}},[])},Sa=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?`margin`:r;xa();var a=M.useMemo(function(){return ga(i)},[i]);return M.createElement(_a,{styles:ya(a,!t,i,n?``:`!important`)})},Ca=!1;if(typeof window<`u`)try{var wa=Object.defineProperty({},"passive",{get:function(){return Ca=!0,!0}});window.addEventListener(`test`,wa,wa),window.removeEventListener(`test`,wa,wa)}catch{Ca=!1}var Ta=Ca?{passive:!1}:!1,Ea=function(e){return e.tagName===`TEXTAREA`},Da=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!==`hidden`&&!(n.overflowY===n.overflowX&&!Ea(e)&&n[t]===`visible`)},Oa=function(e){return Da(e,`overflowY`)},ka=function(e){return Da(e,`overflowX`)},Aa=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<`u`&&r instanceof ShadowRoot&&(r=r.host),Na(e,r)){var i=Pa(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},ja=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},Ma=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},Na=function(e,t){return e===`v`?Oa(t):ka(t)},Pa=function(e,t){return e===`v`?ja(t):Ma(t)},Fa=function(e,t){return e===`h`&&t===`rtl`?-1:1},Ia=function(e,t,n,r,i){var a=Fa(e,window.getComputedStyle(t).direction),o=a*r,s=n.target,c=t.contains(s),l=!1,u=o>0,d=0,f=0;do{if(!s)break;var p=Pa(e,s),m=p[0],h=p[1]-p[2]-a*m;(m||h)&&Na(e,s)&&(d+=h,f+=m);var g=s.parentNode;s=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}while(!c&&s!==document.body||c&&(t.contains(s)||t===s));return(u&&(i&&Math.abs(d)<1||!i&&o>d)||!u&&(i&&Math.abs(f)<1||!i&&-o>f))&&(l=!0),l},La=function(e){return`changedTouches`in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},Ra=function(e){return[e.deltaX,e.deltaY]},za=function(e){return e&&`current`in e?e.current:e},Ba=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Va=function(e){return` - .block-interactivity-${e} {pointer-events: none;} - .allow-interactivity-${e} {pointer-events: all;} -`},Ha=0,Ua=[];function Wa(e){var t=M.useRef([]),n=M.useRef([0,0]),r=M.useRef(),i=M.useState(Ha++)[0],a=M.useState(fa)[0],o=M.useRef(e);M.useEffect(function(){o.current=e},[e]),M.useEffect(function(){if(e.inert){document.body.classList.add(`block-interactivity-${i}`);var t=Vi([e.lockRef.current],(e.shards||[]).map(za),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add(`allow-interactivity-${i}`)}),function(){document.body.classList.remove(`block-interactivity-${i}`),t.forEach(function(e){return e.classList.remove(`allow-interactivity-${i}`)})}}},[e.inert,e.lockRef.current,e.shards]);var s=M.useCallback(function(e,t){if(`touches`in e&&e.touches.length===2||e.type===`wheel`&&e.ctrlKey)return!o.current.allowPinchZoom;var i=La(e),a=n.current,s=`deltaX`in e?e.deltaX:a[0]-i[0],c=`deltaY`in e?e.deltaY:a[1]-i[1],l,u=e.target,d=Math.abs(s)>Math.abs(c)?`h`:`v`;if(`touches`in e&&d===`h`&&u.type===`range`)return!1;var f=window.getSelection(),p=f&&f.anchorNode;if(p&&(p===u||p.contains(u)))return!1;var m=Aa(d,u);if(!m)return!0;if(m?l=d:(l=d===`v`?`h`:`v`,m=Aa(d,u)),!m)return!1;if(!r.current&&`changedTouches`in e&&(s||c)&&(r.current=l),!l)return!0;var h=r.current||l;return Ia(h,t,e,h===`h`?s:c,!0)},[]),c=M.useCallback(function(e){var n=e;if(Ua.length&&Ua[Ua.length-1]===a){var r=`deltaY`in n?Ra(n):La(n),i=t.current.filter(function(e){return e.name===n.type&&(e.target===n.target||n.target===e.shadowParent)&&Ba(e.delta,r)})[0];if(i&&i.should){n.cancelable&&n.preventDefault();return}if(!i){var c=(o.current.shards||[]).map(za).filter(Boolean).filter(function(e){return e.contains(n.target)});(c.length>0?s(n,c[0]):!o.current.noIsolation)&&n.cancelable&&n.preventDefault()}}},[]),l=M.useCallback(function(e,n,r,i){var a={name:e,delta:n,target:r,should:i,shadowParent:Ga(r)};t.current.push(a),setTimeout(function(){t.current=t.current.filter(function(e){return e!==a})},1)},[]),u=M.useCallback(function(e){n.current=La(e),r.current=void 0},[]),d=M.useCallback(function(t){l(t.type,Ra(t),t.target,s(t,e.lockRef.current))},[]),f=M.useCallback(function(t){l(t.type,La(t),t.target,s(t,e.lockRef.current))},[]);M.useEffect(function(){return Ua.push(a),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener(`wheel`,c,Ta),document.addEventListener(`touchmove`,c,Ta),document.addEventListener(`touchstart`,u,Ta),function(){Ua=Ua.filter(function(e){return e!==a}),document.removeEventListener(`wheel`,c,Ta),document.removeEventListener(`touchmove`,c,Ta),document.removeEventListener(`touchstart`,u,Ta)}},[]);var p=e.removeScrollBar,m=e.inert;return M.createElement(M.Fragment,null,m?M.createElement(a,{styles:Va(i)}):null,p?M.createElement(Sa,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Ga(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var Ka=ra(ia,Wa),qa=M.forwardRef(function(e,t){return M.createElement(oa,zi({},e,{ref:t,sideCar:Ka}))});qa.classNames=oa.classNames;function Ja({keepMounted:e,keepMountedMode:t=`activity`,opened:n,onClose:r,id:i,transitionProps:a,onExitTransitionEnd:o,onEnterTransitionEnd:s,trapFocus:c,closeOnEscape:l,returnFocus:d,closeOnClickOutside:f,withinPortal:p,portalProps:m,lockScroll:h,children:g,zIndex:_,shadow:v,padding:y,__vars:b,unstyled:x,removeScrollProps:S,__handledEscapeEvents:C,...w}){let{_id:T,titleMounted:ee,bodyMounted:E,shouldLockScroll:D,setTitleMounted:O,setBodyMounted:te}=Ri({id:i,transitionProps:a,opened:n,trapFocus:c,closeOnEscape:l,onClose:r,returnFocus:d,handledEscapeEvents:C}),{key:ne,...re}=S||{};return(0,N.jsx)(Ct,{...m,withinPortal:p,children:(0,N.jsx)(Fi,{value:{opened:n,onClose:r,closeOnClickOutside:f,onExitTransitionEnd:o,onEnterTransitionEnd:s,transitionProps:{...a,keepMounted:e,keepMountedMode:t},getTitleId:()=>`${T}-title`,getBodyId:()=>`${T}-body`,titleMounted:ee,bodyMounted:E,setTitleMounted:O,setBodyMounted:te,trapFocus:c,closeOnEscape:l,zIndex:_,unstyled:x},children:(0,N.jsx)(qa,{enabled:D&&h,...re,children:(0,N.jsx)(u,{...w,id:T,__vars:{...b,"--mb-z-index":(_||ft(`modal`)).toString(),"--mb-shadow":se(v),"--mb-padding":Me(y)},children:g})},ne)})})}Ja.displayName=`@mantine/core/ModalBase`;function Ya(){let e=Ii();return(0,M.useEffect)(()=>(e.setBodyMounted(!0),()=>e.setBodyMounted(!1)),[]),e.getBodyId()}var Xa={title:`m_615af6c9`,header:`m_b5489c3c`,inner:`m_60c222c7`,content:`m_fd1ab0aa`,close:`m_606cb269`,body:`m_5df29311`};function Za({className:e,...t}){let n=Ya(),r=Ii();return(0,N.jsx)(u,{id:n,className:O({[Xa.body]:!r.unstyled},e),...t})}Za.displayName=`@mantine/core/ModalBaseBody`;function Qa({className:e,onClick:t,...n}){let r=Ii();return(0,N.jsx)(Ne,{...n,onClick:e=>{r.onClose(),t?.(e)},className:O({[Xa.close]:!r.unstyled},e),unstyled:r.unstyled})}Qa.displayName=`@mantine/core/ModalBaseCloseButton`;function $a({transitionProps:e,className:t,innerProps:n,onKeyDown:r,style:i,ref:a,...o}){let s=Ii();return(0,N.jsx)(ae,{mounted:s.opened,transition:`pop`,...s.transitionProps,onExited:()=>{s.onExitTransitionEnd?.(),s.transitionProps?.onExited?.()},onEntered:()=>{s.onEnterTransitionEnd?.(),s.transitionProps?.onEntered?.()},...e,children:e=>(0,N.jsx)(`div`,{...n,className:O({[Xa.inner]:!s.unstyled},n.className),children:(0,N.jsx)(hi,{active:s.opened&&s.trapFocus,innerRef:a,children:(0,N.jsx)(Fe,{...o,component:`section`,role:`dialog`,tabIndex:-1,"aria-modal":!0,"aria-describedby":s.bodyMounted?s.getBodyId():void 0,"aria-labelledby":s.titleMounted?s.getTitleId():void 0,style:[i,e],className:O({[Xa.content]:!s.unstyled},t),unstyled:s.unstyled,children:o.children})})})})}$a.displayName=`@mantine/core/ModalBaseContent`;function eo({className:e,...t}){let n=Ii();return(0,N.jsx)(u,{component:`header`,className:O({[Xa.header]:!n.unstyled},e),...t})}eo.displayName=`@mantine/core/ModalBaseHeader`;var to={duration:200,timingFunction:`ease`,transition:`fade`};function no(e){let t=Ii();return{...to,...t.transitionProps,...e}}function ro({onClick:e,transitionProps:t,style:n,visible:r,...i}){let a=Ii(),o=no(t);return(0,N.jsx)(ae,{mounted:r===void 0?a.opened:r,...o,transition:`fade`,children:t=>(0,N.jsx)(ui,{fixed:!0,style:[n,t],zIndex:a.zIndex,unstyled:a.unstyled,onClick:t=>{e?.(t),a.closeOnClickOutside&&a.onClose()},...i})})}ro.displayName=`@mantine/core/ModalBaseOverlay`;function io(){let e=Ii();return(0,M.useEffect)(()=>(e.setTitleMounted(!0),()=>e.setTitleMounted(!1)),[]),e.getTitleId()}function ao({className:e,...t}){let n=io(),r=Ii();return(0,N.jsx)(u,{component:`h2`,className:O({[Xa.title]:!r.unstyled},e),id:n,...t})}ao.displayName=`@mantine/core/ModalBaseTitle`;function oo({children:e}){return(0,N.jsx)(N.Fragment,{children:e})}function so({style:e,size:t=16,...n}){return(0,N.jsx)(`svg`,{viewBox:`0 0 15 15`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,style:{...e,width:j(t),height:j(t),display:`block`},...n,children:(0,N.jsx)(`path`,{d:`M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})}so.displayName=`@mantine/core/AccordionChevron`;var[co,lo]=dt(`AppShell was not found in tree`);function uo({size:e,min:t,max:n,viewportMax:r}){let i=Math.min(n??1/0,r);return Math.max(Math.min(t??0,i),Math.min(e,i))}function fo(e,t){return t!==void 0&&ef.axis===`horizontal`?window.innerWidth:window.innerHeight,[h,g]=(0,M.useState)(0),[_,v]=(0,M.useState)(void 0),y=()=>m()/d.scale,x=e=>{let t=e.getBoundingClientRect();return((f.axis===`horizontal`?t.width:t.height)-go(e,f.safeAreaVariable))/d.scale},S=t=>{let r=n.rootRef.current;if(!r)return;let i=j(t);r.style.setProperty(f.sizeVariable,i),n.resizeOffsets[e]&&r.style.setProperty(f.offsetVariable,i),n.mode===`static`&&f.gridWidthVariable&&r.style.setProperty(f.gridWidthVariable,i)},C=()=>{let e=n.rootRef.current;e&&(e.style.removeProperty(f.sizeVariable),e.style.removeProperty(f.offsetVariable),f.gridWidthVariable&&e.style.removeProperty(f.gridWidthVariable))},w=()=>{s.current?.abort(),s.current=null,o.current=null;let e=c.current;c.current=null,e&&(xo(`user-select`,e.userSelect),xo(`-webkit-user-select`,e.webkitUserSelect),xo(`cursor`,e.cursor))},T=()=>{r?.reportCollapse(e,fo(a.current.startSize,p.collapseThreshold)),r?.endResize(e,null)},ee=t=>{if(t.pointerId!==o.current)return;a.current.moved=!0;let n=ho({section:e,deltaX:t.clientX-a.current.startX,deltaY:t.clientY-a.current.startY,dir:l})/d.scale,s=a.current.startSize+n,c=uo({size:s,min:p.min,max:p.max,viewportMax:y()});a.current.size=c,S(c),i.current?.setAttribute(`aria-valuenow`,String(Math.round(c))),r?.previewResize(e,c),r?.reportCollapse(e,fo(s,p.collapseThreshold))},E=t=>{if(t.pointerId===o.current){if(w(),!a.current.moved){r?.endResize(e,null);return}r?.endResize(e,a.current.size)}},D=e=>{e.pointerId===o.current&&(w(),C(),T())},O=e=>{e.key===`Escape`&&(e.preventDefault(),w(),C(),i.current?.setAttribute(`aria-valuenow`,String(Math.round(a.current.startSize))),T())},te=()=>{let t=r?.[e].size;if(t!==void 0)return t;let n=i.current?.parentElement;return n?x(n):0},ne=t=>{r?.initCollapse(e,fo(te(),p.collapseThreshold)),r?.reportCollapse(e,fo(t,p.collapseThreshold)),r?.endResize(e,uo({size:t,min:p.min,max:p.max,viewportMax:y()}))},re=t=>{let n=t.shiftKey?yo:vo;if(t.key===`Home`){t.preventDefault(),ne(p.min??0);return}if(t.key===`End`){t.preventDefault(),ne(p.max??y());return}let r=bo[t.key];if(!r)return;let i=ho({section:e,...r,dir:l});i!==0&&(t.preventDefault(),ne(te()+i*n))},k=()=>{C(),r?.[e].reset()},ie=t=>{if(t.button!==0||s.current!==null)return;let n=i.current?.parentElement;if(!n)return;let l=x(n);a.current={startSize:l,startX:t.clientX,startY:t.clientY,size:l,moved:!1},o.current=t.pointerId,r?.initCollapse(e,fo(l,p.collapseThreshold));let u=new AbortController;s.current=u;let{signal:d}=u;c.current={userSelect:document.body.style.getPropertyValue(`user-select`),webkitUserSelect:document.body.style.getPropertyValue(`-webkit-user-select`),cursor:document.body.style.getPropertyValue(`cursor`)},document.body.style.setProperty(`user-select`,`none`),document.body.style.setProperty(`-webkit-user-select`,`none`),document.body.style.setProperty(`cursor`,f.axis===`horizontal`?`col-resize`:`row-resize`),r?.startResize(e),document.addEventListener(`pointermove`,ee,{signal:d}),document.addEventListener(`pointerup`,E,{signal:d}),document.addEventListener(`pointercancel`,D,{signal:d}),document.addEventListener(`keydown`,O,{signal:d})};if(he(()=>{r&&r.activeSection!==e&&C()},[r?.activeSection,r?.[e].size]),he(()=>{g(m());let e=()=>g(m());return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[f.axis]),he(()=>{r?.[e].size===void 0&&v(te())},[r?.[e].size,h]),he(()=>()=>{let e=s.current!==null;w(),C(),e&&T()},[]),!r?.[e].enabled)return null;let ae=h/d.scale,oe=Math.min(p.max??ae,ae),se=r[e].size,ce=se!==void 0&&h>0?Math.min(se,ae):se??_;return(0,N.jsx)(u,{ref:i,role:`separator`,tabIndex:0,"aria-label":p.label??_o[e],"aria-controls":t,"aria-orientation":f.orientation,"aria-valuemin":p.min??0,"aria-valuemax":Math.round(oe),"aria-valuenow":ce===void 0?void 0:Math.round(ce),onPointerDown:ie,onKeyDown:re,onDoubleClick:k,mod:{section:e,orientation:f.orientation,active:r[e].active},...n.getStyles(`resizeHandle`)})}So.displayName=`@mantine/core/AppShellResizeHandle`;var Co={root:`m_89ab340`,navbar:`m_45252eee`,aside:`m_9cdde9a`,header:`m_3b16f56b`,main:`m_8983817`,footer:`m_3840c879`,section:`m_6dcfc7c7`,resizeHandle:`m_3b25945a`},wo=w(e=>{let{classNames:t,className:n,style:r,styles:i,unstyled:a,vars:o,withBorder:s,zIndex:c,mod:l,...d}=v(`AppShellAside`,null,e),f=lo(),p=be(d.id);if(f.disabled)return null;let m=f.resize?.aside.enabled??!1,h=f.getStyles(`aside`,{className:O({[qa.classNames.zeroRight]:f.offsetScrollbars},n),classNames:t,styles:i,style:r});if(!m)return(0,N.jsx)(u,{component:`aside`,mod:[{"with-border":s??f.withBorder},l],...h,...d,__vars:{"--app-shell-aside-z-index":`calc(${c??f.zIndex} + 1)`}});let{children:g,dangerouslySetInnerHTML:_,...y}=d;return(0,N.jsxs)(u,{component:`aside`,mod:[{"with-border":s??f.withBorder},l],...h,...y,__vars:{"--app-shell-aside-z-index":`calc(${c??f.zIndex} + 1)`},id:p,children:[_?(0,N.jsx)(`div`,{style:{display:`contents`},dangerouslySetInnerHTML:_}):g,(0,N.jsx)(So,{section:`aside`,sectionId:p})]})});wo.classes=Co,wo.displayName=`@mantine/core/AppShellAside`;var To=w(e=>{let{classNames:t,className:n,style:r,styles:i,unstyled:a,vars:o,withBorder:s,zIndex:c,mod:l,...d}=v(`AppShellFooter`,null,e),f=lo(),p=be(d.id);if(f.disabled)return null;let m=f.resize?.footer.enabled??!1,h=f.getStyles(`footer`,{className:O({[qa.classNames.zeroRight]:f.offsetScrollbars},n),classNames:t,styles:i,style:r});if(!m)return(0,N.jsx)(u,{component:`footer`,mod:[{"with-border":s??f.withBorder},l],...h,...d,__vars:{"--app-shell-footer-z-index":(c??f.zIndex)?.toString()}});let{children:g,dangerouslySetInnerHTML:_,...y}=d;return(0,N.jsxs)(u,{component:`footer`,mod:[{"with-border":s??f.withBorder},l],...h,...y,__vars:{"--app-shell-footer-z-index":(c??f.zIndex)?.toString()},id:p,children:[_?(0,N.jsx)(`div`,{style:{display:`contents`},dangerouslySetInnerHTML:_}):g,(0,N.jsx)(So,{section:`footer`,sectionId:p})]})});To.classes=Co,To.displayName=`@mantine/core/AppShellFooter`;var Eo=w(e=>{let{classNames:t,className:n,style:r,styles:i,unstyled:a,vars:o,withBorder:s,zIndex:c,mod:l,...d}=v(`AppShellHeader`,null,e),f=lo(),p=be(d.id);if(f.disabled)return null;let m=f.resize?.header.enabled??!1,h=f.getStyles(`header`,{className:O({[qa.classNames.zeroRight]:f.offsetScrollbars},n),classNames:t,styles:i,style:r});if(!m)return(0,N.jsx)(u,{component:`header`,mod:[{"with-border":s??f.withBorder},l],...h,...d,__vars:{"--app-shell-header-z-index":(c??f.zIndex)?.toString()}});let{children:g,dangerouslySetInnerHTML:_,...y}=d;return(0,N.jsxs)(u,{component:`header`,mod:[{"with-border":s??f.withBorder},l],...h,...y,__vars:{"--app-shell-header-z-index":(c??f.zIndex)?.toString()},id:p,children:[_?(0,N.jsx)(`div`,{style:{display:`contents`},dangerouslySetInnerHTML:_}):g,(0,N.jsx)(So,{section:`header`,sectionId:p})]})});Eo.classes=Co,Eo.displayName=`@mantine/core/AppShellHeader`;var Do=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`AppShellMain`,null,e),s=lo();return(0,N.jsx)(u,{component:`main`,...s.getStyles(`main`,{className:n,style:r,classNames:t,styles:i}),...o})});Do.classes=Co,Do.displayName=`@mantine/core/AppShellMain`;var Oo=w(e=>{let{classNames:t,className:n,style:r,styles:i,unstyled:a,vars:o,withBorder:s,zIndex:c,mod:l,...d}=v(`AppShellNavbar`,null,e),f=lo(),p=be(d.id);if(f.disabled)return null;let m=f.resize?.navbar.enabled??!1,h=f.getStyles(`navbar`,{className:n,classNames:t,styles:i,style:r});if(!m)return(0,N.jsx)(u,{component:`nav`,mod:[{"with-border":s??f.withBorder},l],...h,...d,__vars:{"--app-shell-navbar-z-index":`calc(${c??f.zIndex} + 1)`}});let{children:g,dangerouslySetInnerHTML:_,...y}=d;return(0,N.jsxs)(u,{component:`nav`,mod:[{"with-border":s??f.withBorder},l],...h,...y,__vars:{"--app-shell-navbar-z-index":`calc(${c??f.zIndex} + 1)`},id:p,children:[_?(0,N.jsx)(`div`,{style:{display:`contents`},dangerouslySetInnerHTML:_}):g,(0,N.jsx)(So,{section:`navbar`,sectionId:p})]})});Oo.classes=Co,Oo.displayName=`@mantine/core/AppShellNavbar`;var ko=Pe(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,grow:o,mod:s,...c}=v(`AppShellSection`,null,e),l=lo();return(0,N.jsx)(u,{mod:[{grow:o},s],...l.getStyles(`section`,{className:n,style:r,classNames:t,styles:i}),...c})});ko.classes=Co,ko.displayName=`@mantine/core/AppShellSection`;function Ao(e){return typeof e==`object`?e.base:e}function jo(e,t){return`min(${j(e)}, ${t===`horizontal`?`100vw`:`100dvh`})`}function Mo(e){let t=typeof e==`object`&&!!e&&e.base!==void 0&&Object.keys(e).length===1;return typeof e==`number`||typeof e==`string`||t}function No(e){return!(typeof e!=`object`||!e||Object.keys(e).length===1&&`base`in e)}function Po({baseStyles:e,minMediaStyles:t,maxMediaStyles:n,aside:r,theme:i,mode:a,resizedSize:o,resizable:s}){let c=r?.width,l=`translateX(var(--app-shell-aside-width))`,u=`translateX(calc(var(--app-shell-aside-width) * -1))`;if(r?.breakpoint!==void 0&&!r?.collapsed?.mobile&&(n[r?.breakpoint]=n[r?.breakpoint]||{},a===`fixed`?(n[r?.breakpoint][`--app-shell-aside-width`]=`100%`,n[r?.breakpoint][`--app-shell-aside-offset`]=`0px`):(n[r?.breakpoint][`--app-shell-aside-width`]=`0px`,n[r?.breakpoint][`--app-shell-aside-offset`]=`0px`),s&&(n[r.breakpoint][`--app-shell-aside-resize-handle-display`]=`none`)),o!==void 0){let t=jo(o,`horizontal`);e[`--app-shell-aside-width`]=t,e[`--app-shell-aside-offset`]=t,a===`static`&&(e[`--app-shell-aside-grid-width`]=t)}else{if(Mo(c)){let t=j(Ao(c));e[`--app-shell-aside-width`]=t,e[`--app-shell-aside-offset`]=t}No(c)&&(c.base!==void 0&&(e[`--app-shell-aside-width`]=j(c.base),e[`--app-shell-aside-offset`]=j(c.base)),de(c).forEach(e=>{e!==`base`&&(t[e]=t[e]||{},t[e][`--app-shell-aside-width`]=j(c[e]),t[e][`--app-shell-aside-offset`]=j(c[e]))}))}if(r?.breakpoint!==void 0&&a===`static`&&(t[r.breakpoint]=t[r.breakpoint]||{},t[r.breakpoint][`--app-shell-aside-position`]=`sticky`,t[r.breakpoint][`--app-shell-aside-grid-row`]=`2`,t[r.breakpoint][`--app-shell-aside-grid-column`]=`3`,t[r.breakpoint][`--app-shell-main-column-end`]=`3`),r?.collapsed?.desktop){let e=r.breakpoint;t[e]=t[e]||{},t[e][`--app-shell-aside-transform`]=l,t[e][`--app-shell-aside-transform-rtl`]=u,a===`fixed`?t[e][`--app-shell-aside-offset`]=`0px !important`:(t[e][`--app-shell-aside-width`]=`0px`,t[e][`--app-shell-aside-display`]=`none`,t[e][`--app-shell-main-column-end`]=`-1`),t[e][`--app-shell-aside-scroll-locked-visibility`]=`hidden`,s&&(t[e][`--app-shell-aside-resize-handle-display`]=`none`)}if(r?.collapsed?.mobile){let e=sr(r.breakpoint,i.breakpoints)-.1;n[e]=n[e]||{},a===`fixed`?(n[e][`--app-shell-aside-width`]=`100%`,n[e][`--app-shell-aside-offset`]=`0px`):n[e][`--app-shell-aside-width`]=`0px`,n[e][`--app-shell-aside-transform`]=l,n[e][`--app-shell-aside-transform-rtl`]=u,n[e][`--app-shell-aside-scroll-locked-visibility`]=`hidden`,s&&(n[e][`--app-shell-aside-resize-handle-display`]=`none`)}}function Fo({baseStyles:e,minMediaStyles:t,footer:n,mode:r,resizedSize:i,resizable:a}){let o=n?.height,s=r===`static`?!0:n?.offset??!0;if(r===`static`&&n&&(e[`--app-shell-footer-position`]=`sticky`,e[`--app-shell-footer-grid-column`]=`1 / -1`,e[`--app-shell-footer-grid-row`]=`3`),i!==void 0){let t=jo(i,`vertical`);e[`--app-shell-footer-height`]=t,s&&(e[`--app-shell-footer-offset`]=t)}else{if(Mo(o)){let t=j(Ao(o));e[`--app-shell-footer-height`]=t,s&&(e[`--app-shell-footer-offset`]=t)}No(o)&&(o.base!==void 0&&(e[`--app-shell-footer-height`]=j(o.base),s&&(e[`--app-shell-footer-offset`]=j(o.base))),de(o).forEach(e=>{e!==`base`&&(t[e]=t[e]||{},t[e][`--app-shell-footer-height`]=j(o[e]),s&&(t[e][`--app-shell-footer-offset`]=j(o[e])))}))}n?.collapsed&&(e[`--app-shell-footer-transform`]=`translateY(var(--app-shell-footer-height))`,r===`fixed`&&(e[`--app-shell-footer-offset`]=`0px !important`),a&&(e[`--app-shell-footer-resize-handle-display`]=`none`))}function Io({baseStyles:e,minMediaStyles:t,header:n,mode:r,resizedSize:i,resizable:a}){let o=n?.height,s=r===`static`?!0:n?.offset??!0;if(r===`static`&&n&&(e[`--app-shell-header-position`]=`sticky`,e[`--app-shell-header-grid-column`]=`1 / -1`,e[`--app-shell-header-grid-row`]=`1`),i!==void 0){let t=jo(i,`vertical`);e[`--app-shell-header-height`]=t,s&&(e[`--app-shell-header-offset`]=t)}else{if(Mo(o)){let t=j(Ao(o));e[`--app-shell-header-height`]=t,s&&(e[`--app-shell-header-offset`]=t)}No(o)&&(o.base!==void 0&&(e[`--app-shell-header-height`]=j(o.base),s&&(e[`--app-shell-header-offset`]=j(o.base))),de(o).forEach(e=>{e!==`base`&&(t[e]=t[e]||{},t[e][`--app-shell-header-height`]=j(o[e]),s&&(t[e][`--app-shell-header-offset`]=j(o[e])))}))}n?.collapsed&&(e[`--app-shell-header-transform`]=`translateY(calc(var(--app-shell-header-height) * -1))`,r===`fixed`&&(e[`--app-shell-header-offset`]=`0px !important`),a&&(e[`--app-shell-header-resize-handle-display`]=`none`))}function Lo({baseStyles:e,minMediaStyles:t,maxMediaStyles:n,navbar:r,theme:i,mode:a,resizedSize:o,resizable:s}){let c=r?.width,l=`translateX(calc(var(--app-shell-navbar-width) * -1))`,u=`translateX(var(--app-shell-navbar-width))`;if(r?.breakpoint!==void 0&&!r?.collapsed?.mobile&&(n[r?.breakpoint]=n[r?.breakpoint]||{},n[r?.breakpoint][`--app-shell-navbar-offset`]=`0px`,n[r?.breakpoint][`--app-shell-navbar-width`]=`100%`,a===`static`&&(n[r?.breakpoint][`--app-shell-navbar-grid-width`]=`0px`),s&&(n[r.breakpoint][`--app-shell-navbar-resize-handle-display`]=`none`)),o!==void 0){let t=jo(o,`horizontal`);e[`--app-shell-navbar-width`]=t,e[`--app-shell-navbar-offset`]=t,a===`static`&&(e[`--app-shell-navbar-grid-width`]=t)}else{if(Mo(c)){let t=j(Ao(c));e[`--app-shell-navbar-width`]=t,e[`--app-shell-navbar-offset`]=t,a===`static`&&(e[`--app-shell-navbar-grid-width`]=t)}No(c)&&(c.base!==void 0&&(e[`--app-shell-navbar-width`]=j(c.base),e[`--app-shell-navbar-offset`]=j(c.base),a===`static`&&(e[`--app-shell-navbar-grid-width`]=j(c.base))),de(c).forEach(e=>{e!==`base`&&(t[e]=t[e]||{},t[e][`--app-shell-navbar-width`]=j(c[e]),t[e][`--app-shell-navbar-offset`]=j(c[e]),a===`static`&&(t[e][`--app-shell-navbar-grid-width`]=j(c[e])))}))}if(r?.breakpoint!==void 0&&a===`static`&&(t[r.breakpoint]=t[r.breakpoint]||{},t[r.breakpoint][`--app-shell-navbar-position`]=`sticky`,t[r.breakpoint][`--app-shell-navbar-grid-row`]=`2`,t[r.breakpoint][`--app-shell-navbar-grid-column`]=`1`,t[r.breakpoint][`--app-shell-main-column-start`]=`2`),r?.collapsed?.desktop){let e=r.breakpoint;t[e]=t[e]||{},t[e][`--app-shell-navbar-transform`]=l,t[e][`--app-shell-navbar-transform-rtl`]=u,a===`fixed`?t[e][`--app-shell-navbar-offset`]=`0px !important`:(t[e][`--app-shell-navbar-width`]=`0px`,t[e][`--app-shell-navbar-display`]=`none`,t[e][`--app-shell-main-column-start`]=`1`),s&&(t[e][`--app-shell-navbar-resize-handle-display`]=`none`)}if(r?.collapsed?.mobile){let e=sr(r.breakpoint,i.breakpoints)-.1;n[e]=n[e]||{},n[e][`--app-shell-navbar-width`]=`100%`,n[e][`--app-shell-navbar-offset`]=`0px`,a===`static`&&(n[e][`--app-shell-navbar-grid-width`]=`0px`),n[e][`--app-shell-navbar-transform`]=l,n[e][`--app-shell-navbar-transform-rtl`]=u,s&&(n[e][`--app-shell-navbar-resize-handle-display`]=`none`)}}function Ro(e){return Number(e)===0?`0px`:Me(e)}function zo({padding:e,baseStyles:t,minMediaStyles:n}){Mo(e)&&(t[`--app-shell-padding`]=Ro(Ao(e))),No(e)&&(e.base&&(t[`--app-shell-padding`]=Ro(e.base)),de(e).forEach(t=>{t!==`base`&&(n[t]=n[t]||{},n[t][`--app-shell-padding`]=Ro(e[t]))}))}function Bo({navbar:e,header:t,footer:n,aside:r,padding:i,theme:a,mode:o,resize:s}){let c={},l={},u={};o===`static`&&(u[`--app-shell-main-grid-column`]=`1 / -1`,u[`--app-shell-main-grid-row`]=`2`),Lo({baseStyles:u,minMediaStyles:c,maxMediaStyles:l,navbar:e,theme:a,mode:o,resizedSize:s?.sizes.navbar,resizable:s?.enabled.navbar}),Po({baseStyles:u,minMediaStyles:c,maxMediaStyles:l,aside:r,theme:a,mode:o,resizedSize:s?.sizes.aside,resizable:s?.enabled.aside}),Io({baseStyles:u,minMediaStyles:c,header:t,mode:o,resizedSize:s?.sizes.header,resizable:s?.enabled.header}),Fo({baseStyles:u,minMediaStyles:c,footer:n,mode:o,resizedSize:s?.sizes.footer,resizable:s?.enabled.footer}),zo({baseStyles:u,minMediaStyles:c,padding:i});let d=cr(de(c),a.breakpoints).map(e=>({query:`(min-width: ${we(e.px)})`,styles:c[e.value]})),f=cr(de(l),a.breakpoints).map(e=>({query:`(max-width: ${we(e.px)})`,styles:l[e.value]}));return{baseStyles:u,media:[...d,...f]}}function Vo({navbar:e,header:t,aside:n,footer:r,padding:i,mode:a,selector:o,resize:s}){let c=b(),l=_(),{media:u,baseStyles:d}=Bo({navbar:e,header:t,footer:r,aside:n,padding:i,theme:c,mode:a,resize:s});return(0,N.jsx)(_e,{media:u,styles:d,selector:o||l.cssVariablesSelector})}function Ho(e){return e>=128||e===45||e===95||e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122}function Uo(e){return e>=48&&e<=57}function Wo(e){let t=``;for(let n=0;n=1&&r<=31||r===127||n===0&&Uo(r)||n===1&&Uo(r)&&e.charCodeAt(0)===45?t+=`\\${r.toString(16)} `:n===0&&e.length===1&&r===45?t+=`\\${i}`:Ho(r)?t+=i:t+=`\\${i}`}return t}function Go({transitionDuration:e,disabled:t,resizeKey:n}){let[r,i]=(0,M.useState)(!0),[a,o]=(0,M.useState)({key:n,active:!1}),s=(0,M.useRef)(-1),c=(0,M.useRef)(-1);return a.key!==n&&o({key:n,active:!0}),(0,M.useEffect)(()=>{if(!a.active)return;let t=window.setTimeout(()=>(0,M.startTransition)(()=>{o(e=>({...e,active:!1}))}),e||0);return()=>window.clearTimeout(t)},[a,e]),Tr(`resize`,()=>{i(!0),clearTimeout(s.current),s.current=window.setTimeout(()=>(0,M.startTransition)(()=>{i(!1)}),200)}),he(()=>{i(!0),clearTimeout(c.current),c.current=window.setTimeout(()=>(0,M.startTransition)(()=>{i(!1)}),e||0)},[t,e]),r||a.active}var Ko={withBorder:!0,padding:0,transitionDuration:200,transitionTimingFunction:`ease`,zIndex:ft(`app`),mode:`fixed`},qo=D((e,{transitionDuration:t,transitionTimingFunction:n})=>({root:{"--app-shell-transition-duration":`${t}ms`,"--app-shell-transition-timing-function":n,"--app-shell-resize-handle-size":void 0}})),Jo=w(e=>{let t=v(`AppShell`,Ko,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,navbar:l,withBorder:d,padding:f,transitionDuration:p,transitionTimingFunction:m,header:h,zIndex:g,layout:_,disabled:y,aside:b,footer:x,offsetScrollbars:S=!0,mode:C,mod:w,attributes:T,id:ee,resize:E,ref:D,...O}=t,te=c({name:`AppShell`,classes:Co,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:T,vars:s,varsResolver:qo}),ne=Go({disabled:y,transitionDuration:p,resizeKey:E?mo.map(e=>E.sizes[e]).join(`|`):void 0}),re=be(ee),k=(0,M.useRef)(null),ie=E?{sizes:E.sizes,enabled:{navbar:E.navbar.enabled,aside:E.aside.enabled,header:E.header.enabled,footer:E.footer.enabled}}:void 0,ae={navbar:!0,aside:!0,header:C===`static`?!0:h?.offset??!0,footer:C===`static`?!0:x?.offset??!0};return(0,N.jsxs)(co,{value:{getStyles:te,withBorder:d,zIndex:g,disabled:y,offsetScrollbars:S,mode:C,resize:E,rootRef:k,resizeOffsets:ae},children:[(0,N.jsx)(Vo,{navbar:l,header:h,aside:b,footer:x,padding:f,mode:C,resize:ie,selector:E||C===`static`?`#${Wo(re)}`:void 0}),(0,N.jsx)(u,{...te(`root`),id:re,ref:Ae(D,k),mod:[{resizing:ne||E?.activeSection!=null,layout:_,disabled:y,mode:C},w],...O})]})});Jo.classes=Co,Jo.varsResolver=qo,Jo.displayName=`@mantine/core/AppShell`,Jo.Navbar=Oo,Jo.Header=Eo,Jo.Main=Do,Jo.Aside=wo,Jo.Footer=To,Jo.Section=ko;function F({size:e,style:t,...n}){let r=e===void 0?t:{width:j(e),height:j(e),...t};return(0,N.jsx)(`svg`,{viewBox:`0 0 10 7`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,style:r,"aria-hidden":!0,...n,children:(0,N.jsx)(`path`,{d:`M4 4.586L1.707 2.293A1 1 0 1 0 .293 3.707l3 3a.997.997 0 0 0 1.414 0l5-5A1 1 0 1 0 8.293.293L4 4.586z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})}var Yo={group:`m_11def92b`,root:`m_f85678b6`,image:`m_11f8ac07`,placeholder:`m_104cd71f`},Xo=(0,M.createContext)({withinGroup:!1}),Zo=D((e,{spacing:t})=>({group:{"--ag-spacing":Me(t)}})),Qo=w(e=>{let t=v(`AvatarGroup`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,spacing:l,attributes:d,...f}=t,p=c({name:`AvatarGroup`,classes:Yo,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:d,vars:s,varsResolver:Zo,rootSelector:`group`});return(0,N.jsx)(Xo,{value:{withinGroup:!0},children:(0,N.jsx)(u,{...p(`group`),...f})})});Qo.classes=Yo,Qo.varsResolver=Zo,Qo.displayName=`@mantine/core/AvatarGroup`;function $o(e){return(0,N.jsx)(`svg`,{...e,"data-avatar-placeholder-icon":!0,viewBox:`0 0 15 15`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,N.jsx)(`path`,{d:`M0.877014 7.49988C0.877014 3.84219 3.84216 0.877045 7.49985 0.877045C11.1575 0.877045 14.1227 3.84219 14.1227 7.49988C14.1227 11.1575 11.1575 14.1227 7.49985 14.1227C3.84216 14.1227 0.877014 11.1575 0.877014 7.49988ZM7.49985 1.82704C4.36683 1.82704 1.82701 4.36686 1.82701 7.49988C1.82701 8.97196 2.38774 10.3131 3.30727 11.3213C4.19074 9.94119 5.73818 9.02499 7.50023 9.02499C9.26206 9.02499 10.8093 9.94097 11.6929 11.3208C12.6121 10.3127 13.1727 8.97172 13.1727 7.49988C13.1727 4.36686 10.6328 1.82704 7.49985 1.82704ZM10.9818 11.9787C10.2839 10.7795 8.9857 9.97499 7.50023 9.97499C6.01458 9.97499 4.71624 10.7797 4.01845 11.9791C4.97952 12.7272 6.18765 13.1727 7.49985 13.1727C8.81227 13.1727 10.0206 12.727 10.9818 11.9787ZM5.14999 6.50487C5.14999 5.207 6.20212 4.15487 7.49999 4.15487C8.79786 4.15487 9.84999 5.207 9.84999 6.50487C9.84999 7.80274 8.79786 8.85487 7.49999 8.85487C6.20212 8.85487 5.14999 7.80274 5.14999 6.50487ZM7.49999 5.10487C6.72679 5.10487 6.09999 5.73167 6.09999 6.50487C6.09999 7.27807 6.72679 7.90487 7.49999 7.90487C8.27319 7.90487 8.89999 7.27807 8.89999 6.50487C8.89999 5.73167 8.27319 5.10487 7.49999 5.10487Z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})}function es(e){let t=0;for(let n=0;ne[0]).slice(0,t).join(``).toUpperCase()}var is=D((e,{size:t,radius:n,variant:r,gradient:i,color:a,autoContrast:o,name:s,allowedInitialsColors:c})=>{let l=a===`initials`&&typeof s==`string`?ns(s,c):a,u=e.variantColorResolver({color:l||`gray`,theme:e,gradient:i,variant:r||`light`,autoContrast:o});return{root:{"--avatar-size":ye(t,`avatar-size`),"--avatar-radius":n===void 0?void 0:Oe(n),"--avatar-bg":l||r?u.background:void 0,"--avatar-color":l||r?u.color:void 0,"--avatar-bd":l||r?u.border:void 0}}}),as=Pe(e=>{let t=v(`Avatar`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,src:l,alt:d,radius:f,color:p,gradient:m,imageProps:h,children:g,autoContrast:_,mod:y,name:b,allowedInitialsColors:x,attributes:S,...C}=t,w=(0,M.use)(Xo),[T,ee]=(0,M.useState)(!l),E=c({name:`Avatar`,props:t,classes:Yo,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:S,vars:s,varsResolver:is});return(0,M.useEffect)(()=>ee(!l),[l]),(0,N.jsx)(u,{...E(`root`),mod:[{"within-group":w.withinGroup},y],...C,children:T||!l?(0,N.jsx)(`span`,{...E(`placeholder`),title:d,children:g||typeof b==`string`&&rs(b)||(0,N.jsx)($o,{})}):(0,N.jsx)(`img`,{...h,...E(`image`),src:l,alt:d,onError:e=>{ee(!0),h?.onError?.(e)}})})});as.classes=Yo,as.varsResolver=is,as.displayName=`@mantine/core/Avatar`,as.Group=Qo;var os={root:`m_347db0ec`,"root--dot":`m_fbd81e3d`,label:`m_5add502a`,section:`m_91fdda9b`},ss=D((e,{radius:t,color:n,gradient:r,variant:i,size:a,autoContrast:o,circle:s})=>{let c=e.variantColorResolver({color:n||e.primaryColor,theme:e,gradient:r,variant:i||`filled`,autoContrast:o});return{root:{"--badge-height":ye(a,`badge-height`),"--badge-padding-x":ye(a,`badge-padding-x`),"--badge-fz":ye(a,`badge-fz`),"--badge-radius":s||t===void 0?void 0:Oe(t),"--badge-bg":n||i?c.background:void 0,"--badge-color":n||i?c.color:void 0,"--badge-bd":n||i?c.border:void 0,"--badge-dot-color":i===`dot`?g(n,e):void 0}}}),cs=Pe(e=>{let t=v(`Badge`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,radius:l,color:d,gradient:f,leftSection:p,rightSection:m,children:h,variant:g,fullWidth:_,autoContrast:y,circle:b,mod:x,attributes:S,...C}=t,w=c({name:`Badge`,props:t,classes:os,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:S,vars:s,varsResolver:ss});return(0,N.jsxs)(u,{variant:g,mod:[{block:_,circle:b,"with-right-section":!!m,"with-left-section":!!p},x],...w(`root`,{variant:g}),...C,children:[p&&(0,N.jsx)(`span`,{...w(`section`),"data-position":`left`,children:p}),(0,N.jsx)(`span`,{...w(`label`),children:h}),m&&(0,N.jsx)(`span`,{...w(`section`),"data-position":`right`,children:m})]})});cs.classes=os,cs.varsResolver=ss,cs.displayName=`@mantine/core/Badge`;var ls={root:`m_fea6bf1a`,burger:`m_d4fb9cad`},us=D((e,{color:t,size:n,lineSize:r,transitionDuration:i,transitionTimingFunction:a})=>({root:{"--burger-color":t?g(t,e):void 0,"--burger-size":ye(n,`burger-size`),"--burger-line-size":r?j(r):void 0,"--burger-transition-duration":i===void 0?void 0:`${i}ms`,"--burger-transition-timing-function":a}})),ds=w(e=>{let t=v(`Burger`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,opened:l,children:d,transitionDuration:f,transitionTimingFunction:p,lineSize:m,attributes:h,...g}=t,_=c({name:`Burger`,classes:ls,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:h,vars:s,varsResolver:us});return(0,N.jsxs)(C,{..._(`root`),...g,children:[(0,N.jsx)(u,{mod:[`reduce-motion`,{opened:l}],..._(`burger`)}),d]})});ds.classes=ls,ds.varsResolver=us,ds.displayName=`@mantine/core/Burger`;var fs={root:`m_b183c0a2`},ps=D((e,{color:t})=>({root:{"--code-bg":t?g(t,e):void 0}})),ms=w(e=>{let t=v(`Code`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,color:l,block:d,mod:f,attributes:p,...m}=t,h=c({name:`Code`,props:t,classes:fs,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:p,vars:s,varsResolver:ps});return(0,N.jsx)(u,{component:d?`pre`:`code`,mod:[{block:d},f],...h(`root`),...m,dir:`ltr`})});ms.classes=fs,ms.varsResolver=ps,ms.displayName=`@mantine/core/Code`;var[hs,gs]=dt(`Drawer component was not found in tree`),_s={root:`m_f11b401e`,header:`m_5a7c2c9`,content:`m_b8a05bbd`,inner:`m_31cd769a`},vs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`DrawerBody`,null,e),s=gs();return(0,N.jsx)(Za,{...s.getStyles(`body`,{classNames:t,style:r,styles:i,className:n}),...o})});vs.classes=_s,vs.displayName=`@mantine/core/DrawerBody`;var ys=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`DrawerCloseButton`,null,e),s=gs();return(0,N.jsx)(Qa,{...s.getStyles(`close`,{classNames:t,style:r,styles:i,className:n}),...o})});ys.classes=_s,ys.displayName=`@mantine/core/DrawerCloseButton`;var bs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,children:o,radius:s,__hidden:c,...l}=v(`DrawerContent`,null,e),u=gs(),d=u.scrollAreaComponent||oo;return(0,N.jsx)($a,{...u.getStyles(`content`,{className:n,style:r,styles:i,classNames:t}),innerProps:u.getStyles(`inner`,{className:n,style:r,styles:i,classNames:t}),...l,radius:s||u.radius||0,"data-hidden":c||void 0,children:(0,N.jsx)(d,{style:{height:`calc(100vh - var(--drawer-offset) * 2)`},children:o})})});bs.classes=_s,bs.displayName=`@mantine/core/DrawerContent`;var xs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`DrawerHeader`,null,e),s=gs();return(0,N.jsx)(eo,{...s.getStyles(`header`,{classNames:t,style:r,styles:i,className:n}),...o})});xs.classes=_s,xs.displayName=`@mantine/core/DrawerHeader`;var Ss=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`DrawerOverlay`,null,e),s=gs();return(0,N.jsx)(ro,{...s.getStyles(`overlay`,{classNames:t,style:r,styles:i,className:n}),...o})});Ss.classes=_s,Ss.displayName=`@mantine/core/DrawerOverlay`;function Cs(e){switch(e){case`top`:return`flex-start`;case`bottom`:return`flex-end`;default:return}}function ws(e){if(e===`top`||e===`bottom`)return`0 0 calc(100% - var(--drawer-offset, 0rem) * 2)`}var Ts={top:`slide-down`,bottom:`slide-up`,left:`slide-right`,right:`slide-left`},Es={top:`slide-down`,bottom:`slide-up`,right:`slide-right`,left:`slide-left`},Ds={closeOnClickOutside:!0,withinPortal:!0,lockScroll:!0,trapFocus:!0,returnFocus:!0,closeOnEscape:!0,keepMounted:!1,zIndex:ft(`modal`),position:`left`},Os=D((e,{position:t,size:n,offset:r})=>({root:{"--drawer-size":ye(n,`drawer-size`),"--drawer-flex":ws(t),"--drawer-height":t===`left`||t===`right`?void 0:`var(--drawer-size)`,"--drawer-align":Cs(t),"--drawer-justify":t===`right`?`flex-end`:void 0,"--drawer-offset":j(r)}})),ks=w(e=>{let t=v(`DrawerRoot`,Ds,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,scrollAreaComponent:l,position:u,transitionProps:d,radius:f,attributes:p,...m}=t,{dir:h}=jt(),g=c({name:`Drawer`,classes:_s,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:p,vars:s,varsResolver:Os}),_=(h===`rtl`?Es:Ts)[u];return(0,N.jsx)(hs,{value:{scrollAreaComponent:l,getStyles:g,radius:f},children:(0,N.jsx)(Ja,{...g(`root`),transitionProps:{transition:_,...d},"data-offset-scrollbars":l===wt.Autosize||void 0,unstyled:o,...m})})});ks.classes=_s,ks.varsResolver=Os,ks.displayName=`@mantine/core/DrawerRoot`;var As=(0,M.createContext)(null);function js({children:e}){let[t,n]=(0,M.useState)([]),[r,i]=(0,M.useState)(ft(`modal`)),[a]=(0,M.useState)(()=>new WeakSet);return(0,N.jsx)(As,{value:{stack:t,addModal:(e,t)=>{n(t=>[...new Set([...t,e])]),i(e=>typeof t==`number`&&typeof e==`number`?Math.max(e,t):e)},removeModal:e=>n(t=>t.filter(t=>t!==e)),getZIndex:e=>`calc(${r} + ${t.indexOf(e)} + 1)`,currentId:t[t.length-1],maxZIndex:r,handledEscapeEvents:a},children:e})}js.displayName=`@mantine/core/DrawerStack`;var Ms=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`DrawerTitle`,null,e),s=gs();return(0,N.jsx)(ao,{...s.getStyles(`title`,{classNames:t,style:r,styles:i,className:n}),...o})});Ms.classes=_s,Ms.displayName=`@mantine/core/DrawerTitle`;var Ns={closeOnClickOutside:!0,withinPortal:!0,lockScroll:!0,trapFocus:!0,returnFocus:!0,closeOnEscape:!0,keepMounted:!1,zIndex:ft(`modal`),withOverlay:!0,withCloseButton:!0},Ps=w(e=>{let{title:t,withOverlay:n,overlayProps:r,withCloseButton:i,closeButtonProps:a,children:o,opened:s,stackId:c,zIndex:l,...u}=v(`Drawer`,Ns,e),d=(0,M.use)(As),f=!!t||i,p=d&&c?{closeOnEscape:d.currentId===c,trapFocus:d.currentId===c,zIndex:d.getZIndex(c),__handledEscapeEvents:d.handledEscapeEvents}:{},m=n===!1?!1:c&&d?d.currentId===c:s;return(0,M.useEffect)(()=>{d&&c&&(s?d.addModal(c,l||ft(`modal`)):d.removeModal(c))},[s,c,l]),(0,N.jsxs)(ks,{opened:s,zIndex:d&&c?d.getZIndex(c):l,...u,...p,children:[n&&(0,N.jsx)(Ss,{visible:m,transitionProps:d&&c?{duration:0}:void 0,...r}),(0,N.jsxs)(bs,{__hidden:d&&c&&s?c!==d.currentId:!1,children:[f&&(0,N.jsxs)(xs,{children:[t&&(0,N.jsx)(Ms,{children:t}),i&&(0,N.jsx)(ys,{...a})]}),(0,N.jsx)(vs,{children:o})]})]})});Ps.classes=_s,Ps.displayName=`@mantine/core/Drawer`,Ps.Root=ks,Ps.Overlay=Ss,Ps.Content=bs,Ps.Body=vs,Ps.Header=xs,Ps.Title=Ms,Ps.CloseButton=ys,Ps.Stack=js;var Fs={root:`m_dc6f14e2`},Is=D((e,{size:t})=>({root:{"--kbd-fz":ye(t,`kbd-fz`)}})),Ls=w(e=>{let t=v(`Kbd`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,attributes:l,...d}=t,f=c({name:`Kbd`,classes:Fs,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:l,vars:s,varsResolver:Is});return(0,N.jsx)(u,{component:`kbd`,...f(`root`),...d})});Ls.classes=Fs,Ls.varsResolver=Is,Ls.displayName=`@mantine/core/Kbd`;var[Rs,zs]=dt(`Menu component was not found in the tree`),Bs=(0,M.createContext)(null);function Vs(e){let{value:t,defaultValue:n,onChange:r,children:i}=v(`MenuCheckboxGroup`,null,e),[a,o]=Er({value:t,defaultValue:n,finalValue:[],onChange:r}),s=(0,M.useCallback)(e=>{o(a.includes(e)?a.filter(t=>t!==e):[...a,e])},[a,o]);return(0,N.jsx)(Bs,{value:{values:a,onChange:s},children:i})}Vs.displayName=`@mantine/core/MenuCheckboxGroup`;var Hs=(0,M.createContext)(null);function Us({role:e,checked:t,indicator:n,onSelect:r,color:i,closeMenuOnClick:a,rightSection:o,children:s,disabled:c,dataDisabled:l,className:u,style:d,styles:f,classNames:p,buttonRef:m,others:h}){let g=zs(),_=(0,M.use)(Hs),v=b(),{dir:y}=jt(),x=(0,M.useRef)(null),S=or(h.onClick,()=>{l||(r(),a&&g.closeDropdownImmediately())}),w=or(h.onMouseMove,()=>{if(!g.hasSearch)return;let e=x.current?.closest(`[data-menu-dropdown]`);e&&e.querySelectorAll(`[data-menu-active]`).forEach(t=>{t!==x.current&&t.closest(`[data-menu-dropdown]`)===e&&t.removeAttribute(`data-menu-active`)})}),T=or(h.onKeyDown,e=>{e.key===`ArrowLeft`&&_&&(_.close(),_.focusParentItem())}),ee=i?v.variantColorResolver({color:i,theme:v,variant:`light`}):void 0,E=i?Te({color:i,theme:v}):null,D=g.alignItemsLabels!==`none`||t;return(0,N.jsxs)(C,{onMouseDown:e=>e.preventDefault(),...h,unstyled:g.unstyled,tabIndex:g.menuItemTabIndex,...g.getStyles(`item`,{className:u,style:d,styles:f,classNames:p}),ref:Ae(x,m),role:e,"aria-checked":t,disabled:c,"data-menu-item":!0,"data-checked":t||void 0,"data-disabled":c||l||void 0,"data-mantine-stop-propagation":!0,onClick:S,onMouseMove:w,onKeyDown:rr({siblingSelector:`[data-menu-item]:not([data-disabled])`,parentSelector:`[data-menu-dropdown]`,activateOnFocus:!1,loop:g.loop,dir:y,orientation:`vertical`,onKeyDown:T}),__vars:{"--menu-item-color":E?.isThemeColor&&E?.shade===void 0?`var(--mantine-color-${E.color}-6)`:ee?.color,"--menu-item-hover":ee?.hover},children:[D&&(0,N.jsx)(`div`,{...g.getStyles(`itemIndicator`,{styles:f,classNames:p}),"data-checked":t||void 0,children:t?n:null}),s&&(0,N.jsx)(`div`,{...g.getStyles(`itemLabel`,{styles:f,classNames:p}),"data-menu-item-label":!0,children:s}),o&&(0,N.jsx)(`div`,{...g.getStyles(`itemSection`,{styles:f,classNames:p}),"data-position":`right`,children:o})]})}var Ws={dropdown:`m_dc9b7c9f`,label:`m_9bfac126`,divider:`m_efdf90cb`,item:`m_99ac2aa1`,search:`m_ef8769b6`,itemLabel:`m_5476e0d3`,itemIndicator:`m_8395186e`,itemSection:`m_8b75e504`,chevron:`m_b85b0bed`},Gs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,color:o,closeMenuOnClick:s,rightSection:c,children:l,disabled:u,"data-disabled":d,value:f,checked:p,defaultChecked:m,onChange:h,checkIcon:g,ref:_,...y}=v(`MenuCheckboxItem`,null,e),b=zs(),x=(0,M.use)(Bs),S=x&&f!==void 0?x.values.includes(f):void 0,[C,w]=Er({value:p??S,defaultValue:m,finalValue:!1,onChange:h}),T=g??b.checkIcon??(0,N.jsx)(F,{size:10});return(0,N.jsx)(Us,{role:`menuitemcheckbox`,checked:C,indicator:T,onSelect:()=>{h?w(!C):x&&f!==void 0?x.onChange(f):w(!C)},color:o,closeMenuOnClick:s,rightSection:c,disabled:u,dataDisabled:d,className:n,style:r,styles:i,classNames:t,buttonRef:_,others:y,children:l})});Gs.classes=Ws,Gs.displayName=`@mantine/core/MenuCheckboxItem`;function Ks(e){let{children:t,disabled:n,longPressDelay:r}=v(`MenuContextMenu`,null,e),i=te(t);if(!i)throw Error(`Menu.ContextMenu component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let a=zs(),o=fi(),s=pi({childProps:i.props,disabled:n||o.disabled,opened:a.opened,longPressDelay:r,setReference:o.reference,open:()=>a.openDropdown()});return(0,M.cloneElement)(i,s)}Ks.displayName=`@mantine/core/MenuContextMenu`;var qs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`MenuDivider`,null,e),s=zs();return(0,N.jsx)(u,{...s.getStyles(`divider`,{className:n,style:r,styles:i,classNames:t}),...o})});qs.classes=Ws,qs.displayName=`@mantine/core/MenuDivider`;var Js=500;function Ys(e){return((e.querySelector(`[data-menu-item-label]`)??e).textContent??``).trim().toLowerCase()}function Xs(e){return e.length>1&&e.split(``).every(t=>t===e[0])}function Zs({enabled:e,opened:t,getDropdown:n}){let r=(0,M.useRef)({buffer:``,timeoutId:null});return(0,M.useEffect)(()=>{if(t&&e)return;let n=r.current;n.timeoutId!==null&&(window.clearTimeout(n.timeoutId),n.timeoutId=null),n.buffer=``},[t,e]),(0,M.useEffect)(()=>()=>{let{timeoutId:e}=r.current;e!==null&&window.clearTimeout(e)},[]),t=>{if(!e||t.defaultPrevented||t.ctrlKey||t.metaKey||t.altKey||t.key.length!==1||t.key===` `)return;let i=t.target;if(i&&(i.tagName===`INPUT`||i.tagName===`TEXTAREA`||i.tagName===`SELECT`||i.isContentEditable))return;let a=n();if(!a)return;let o=Array.from(a.querySelectorAll(`[data-menu-item]:not([data-disabled])`)).filter(e=>e.closest(`[data-menu-dropdown]`)===a);if(o.length===0)return;let s=r.current;s.buffer=(s.buffer+t.key).toLowerCase(),s.timeoutId!==null&&window.clearTimeout(s.timeoutId),s.timeoutId=window.setTimeout(()=>{s.buffer=``,s.timeoutId=null},Js);let c=document.activeElement,l=c?o.indexOf(c):-1,u=null;if(s.buffer.length===1||Xs(s.buffer)){let e=s.buffer[0],t=l+1;for(let n=0;n{let{classNames:t,className:n,style:r,styles:i,vars:a,onMouseEnter:o,onMouseLeave:s,onKeyDown:c,children:l,ref:u,...d}=v(`MenuDropdown`,null,e),f=(0,M.useRef)(null),p=zs(),m=Zs({enabled:!p.hasSearch,opened:p.opened,getDropdown:()=>f.current}),h=or(c,e=>{m(e),!(e.defaultPrevented||p.hasSearch)&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&(e.preventDefault(),f.current?.querySelectorAll(`[data-menu-item]:not(:disabled)`)[0]?.focus())}),g=or(o,()=>(p.trigger===`hover`||p.trigger===`click-hover`)&&p.openDropdown()),_=or(s,()=>(p.trigger===`hover`||p.trigger===`click-hover`)&&p.closeDropdown());return(0,N.jsxs)(Ei.Dropdown,{...d,onMouseEnter:g,onMouseLeave:_,role:`menu`,"aria-orientation":`vertical`,ref:Ae(u,f),...p.getStyles(`dropdown`,{className:n,style:r,styles:i,classNames:t,withStaticClass:!1}),tabIndex:-1,"data-menu-dropdown":!0,onKeyDown:h,children:[p.withInitialFocusPlaceholder&&!p.hasSearch&&(0,N.jsx)(`div`,{role:`presentation`,tabIndex:-1,"data-autofocus":!0,"data-mantine-stop-propagation":!0,style:{outline:0}}),l]})});Qs.classes=Ws,Qs.displayName=`@mantine/core/MenuDropdown`;var $s=Pe(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,color:o,closeMenuOnClick:s,leftSection:c,rightSection:l,children:u,disabled:d,"data-disabled":f,ref:p,...m}=v(`MenuItem`,null,e),h=zs(),g=(0,M.use)(Hs),_=b(),{dir:y}=jt(),x=(0,M.useRef)(null),S=m,w=or(S.onClick,()=>{f||(typeof s==`boolean`?s&&h.closeDropdownImmediately():h.closeOnItemClick&&h.closeDropdownImmediately())}),T=or(S.onMouseMove,()=>{if(!h.hasSearch)return;let e=x.current?.closest(`[data-menu-dropdown]`);e&&e.querySelectorAll(`[data-menu-active]`).forEach(t=>{t!==x.current&&t.closest(`[data-menu-dropdown]`)===e&&t.removeAttribute(`data-menu-active`)})}),ee=o?_.variantColorResolver({color:o,theme:_,variant:`light`}):void 0,E=o?Te({color:o,theme:_}):null,D=or(S.onKeyDown,e=>{e.key===`ArrowLeft`&&g&&(g.close(),g.focusParentItem())});return(0,N.jsxs)(C,{onMouseDown:e=>e.preventDefault(),...m,unstyled:h.unstyled,tabIndex:h.menuItemTabIndex,...h.getStyles(`item`,{className:n,style:r,styles:i,classNames:t}),ref:Ae(x,p),role:`menuitem`,disabled:d,"data-menu-item":!0,"data-disabled":d||f||void 0,"data-mantine-stop-propagation":!0,onClick:w,onMouseMove:T,onKeyDown:rr({siblingSelector:`[data-menu-item]:not([data-disabled])`,parentSelector:`[data-menu-dropdown]`,activateOnFocus:!1,loop:h.loop,dir:y,orientation:`vertical`,onKeyDown:D}),__vars:{"--menu-item-color":E?.isThemeColor&&E?.shade===void 0?`var(--mantine-color-${E.color}-6)`:ee?.color,"--menu-item-hover":ee?.hover},children:[h.alignItemsLabels===`all`&&(0,N.jsx)(`div`,{...h.getStyles(`itemIndicator`,{styles:i,classNames:t}),"data-placeholder":!0}),c&&(0,N.jsx)(`div`,{...h.getStyles(`itemSection`,{styles:i,classNames:t}),"data-position":`left`,children:c}),u&&(0,N.jsx)(`div`,{...h.getStyles(`itemLabel`,{styles:i,classNames:t}),"data-menu-item-label":!0,children:u}),l&&(0,N.jsx)(`div`,{...h.getStyles(`itemSection`,{styles:i,classNames:t}),"data-position":`right`,children:l})]})});$s.classes=Ws,$s.displayName=`@mantine/core/MenuItem`;var ec=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`MenuLabel`,null,e),s=zs();return(0,N.jsx)(u,{...s.getStyles(`label`,{className:n,style:r,styles:i,classNames:t}),...o})});ec.classes=Ws,ec.displayName=`@mantine/core/MenuLabel`;var tc=(0,M.createContext)(null);function nc(e){let{value:t,defaultValue:n,onChange:r,children:i}=v(`MenuRadioGroup`,null,e),[a,o]=Er({value:t,defaultValue:n,finalValue:null,onChange:r});return(0,N.jsx)(tc,{value:{value:a,onChange:e=>o(e)},children:i})}nc.displayName=`@mantine/core/MenuRadioGroup`;function rc({size:e,style:t,...n}){return(0,N.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 5 5`,style:{width:j(e),height:j(e),...t},"aria-hidden":!0,...n,children:(0,N.jsx)(`circle`,{cx:`2.5`,cy:`2.5`,r:`2.5`,fill:`currentColor`})})}var ic=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,color:o,closeMenuOnClick:s,rightSection:c,children:l,disabled:u,"data-disabled":d,value:f,checked:p,onChange:m,checkIcon:h,ref:g,..._}=v(`MenuRadioItem`,null,e),y=zs(),b=(0,M.use)(tc),x=p??(b?b.value===f:!1),S=h??y.checkIcon??(0,N.jsx)(rc,{size:5});return(0,N.jsx)(Us,{role:`menuitemradio`,checked:x,indicator:S,onSelect:()=>{x||(m?m(f):b&&b.onChange(f))},color:o,closeMenuOnClick:s,rightSection:c,disabled:u,dataDisabled:d,className:n,style:r,styles:i,classNames:t,buttonRef:g,others:_,children:l})});ic.classes=Ws,ic.displayName=`@mantine/core/MenuRadioItem`;var ac=`[data-menu-item]:not([data-disabled])`,oc=`[data-menu-active]`;function sc(e){return e?.closest(`[data-menu-dropdown]`)}function cc(e){return e?Array.from(e.querySelectorAll(ac)).filter(t=>t.closest(`[data-menu-dropdown]`)===e):[]}function lc(e){e&&e.querySelectorAll(oc).forEach(t=>{t.closest(`[data-menu-dropdown]`)===e&&t.removeAttribute(`data-menu-active`)})}function uc(e,t){lc(t),e&&(e.setAttribute(`data-menu-active`,`true`),e.scrollIntoView({block:`nearest`}))}function dc(e){return e.findIndex(e=>e.hasAttribute(`data-menu-active`))}var fc={clearSearchOnClose:!0},pc=w(e=>{let{classNames:t,styles:n,onKeyDown:r,onChange:i,size:a,clearSearchOnClose:o,ref:s,...c}=v(`MenuSearch`,fc,e),l=zs(),u=(0,M.useRef)(null),d=Ae(s,u),f=(0,M.useRef)(i);f.current=i,(0,M.useEffect)(()=>l.registerSearch(),[l.registerSearch]),(0,M.useEffect)(()=>{o?l.searchExitClearRef.current=()=>{f.current?.({currentTarget:{value:``}})}:l.searchExitClearRef.current=null},[o,l.searchExitClearRef]),(0,M.useEffect)(()=>{l.opened||lc(sc(u.current))},[l.opened]);let p=or(i,e=>{lc(sc(e.currentTarget))}),m=or(r,e=>{if(e.defaultPrevented)return;let t=sc(e.currentTarget),n=cc(t);if(e.key===`ArrowDown`){if(e.preventDefault(),n.length===0)return;let r=dc(n);uc(n[r>=n.length-1?l.loop?0:r:r+1]??null,t)}else if(e.key===`ArrowUp`){if(e.preventDefault(),n.length===0)return;let r=dc(n);uc(n[r<=0?r===-1||l.loop?n.length-1:0:r-1]??null,t)}else if(e.key===`Home`)e.preventDefault(),n.length>0&&uc(n[0],t);else if(e.key===`End`)e.preventDefault(),n.length>0&&uc(n[n.length-1],t);else if(e.key===`Enter`){if(e.nativeEvent.isComposing||e.nativeEvent.keyCode===229)return;let t=n[dc(n)];t&&(e.preventDefault(),t.hasAttribute(`data-sub-menu-item`)?(t.focus(),t.dispatchEvent(new KeyboardEvent(`keydown`,{key:`ArrowRight`,bubbles:!0}))):t.click())}}),h=l.getStyles(`search`);return(0,N.jsx)(fe,{"data-autofocus":!0,"data-mantine-stop-propagation":!0,type:`search`,size:a,...c,ref:d,classNames:[{input:h.className},t],styles:[{input:h.style},n],onKeyDown:m,onChange:p,__staticSelector:`Menu`})});pc.classes=Ws,pc.displayName=`@mantine/core/MenuSearch`;var mc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,onMouseEnter:o,onMouseLeave:s,onPointerEnter:c,onPointerLeave:l,onKeyDown:u,children:d,ref:f,...p}=v(`MenuSubDropdown`,null,e),m=(0,M.useRef)(null),h=zs(),g=(0,M.use)(Hs),_=Zs({enabled:!h.hasSearch,opened:g?.opened??!1,getDropdown:()=>m.current}),y=or(u,e=>{_(e),!e.ctrlKey&&!e.metaKey&&!e.altKey&&e.key.length===1&&e.key!==` `&&e.stopPropagation()}),b=g?.getFloatingProps({onMouseEnter:o,onMouseLeave:s,onPointerEnter:c,onPointerLeave:l});return(0,N.jsx)(Ei.Dropdown,{...p,...b,role:`menu`,"aria-orientation":`vertical`,ref:Ae(f,m,g?.setFloating),...h.getStyles(`dropdown`,{className:n,style:r,styles:i,classNames:t,withStaticClass:!1}),tabIndex:-1,"data-menu-dropdown":!0,onKeyDown:y,children:d})});mc.classes=Ws,mc.displayName=`@mantine/core/MenuSubDropdown`;var hc=Pe(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,color:o,leftSection:s,rightSection:c,children:l,disabled:u,"data-disabled":d,closeMenuOnClick:f,ref:p,...m}=v(`MenuSubItem`,null,e),h=zs(),g=(0,M.use)(Hs),_=b(),{dir:y}=jt(),x=(0,M.useRef)(null),S=m,w=o?_.variantColorResolver({color:o,theme:_,variant:`light`}):void 0,T=o?Te({color:o,theme:_}):null,ee=or(S.onKeyDown,e=>{e.key===`ArrowRight`&&(g?.open(),g?.focusFirstItem()),e.key===`ArrowLeft`&&g?.parentContext&&(g.parentContext.close(),g.parentContext.focusParentItem())}),E=or(S.onClick,()=>{!d&&f&&h.closeDropdownImmediately()}),D=or(S.onMouseMove,()=>{if(!h.hasSearch)return;let e=x.current?.closest(`[data-menu-dropdown]`);e&&e.querySelectorAll(`[data-menu-active]`).forEach(t=>{t!==x.current&&t.closest(`[data-menu-dropdown]`)===e&&t.removeAttribute(`data-menu-active`)})}),O=g?.getReferenceProps({onMouseEnter:S.onMouseEnter,onMouseLeave:S.onMouseLeave,onPointerEnter:S.onPointerEnter,onPointerLeave:S.onPointerLeave});return(0,N.jsxs)(C,{onMouseDown:e=>e.preventDefault(),...m,...O,unstyled:h.unstyled,tabIndex:h.menuItemTabIndex,...h.getStyles(`item`,{className:n,style:r,styles:i,classNames:t}),ref:Ae(x,p,g?.setReference),role:`menuitem`,disabled:u,"data-menu-item":!0,"data-sub-menu-item":!0,"data-disabled":u||d||void 0,"data-mantine-stop-propagation":!0,onClick:E,onMouseMove:D,onKeyDown:rr({siblingSelector:`[data-menu-item]:not([data-disabled])`,parentSelector:`[data-menu-dropdown]`,activateOnFocus:!1,loop:h.loop,dir:y,orientation:`vertical`,onKeyDown:ee}),__vars:{"--menu-item-color":T?.isThemeColor&&T?.shade===void 0?`var(--mantine-color-${T.color}-6)`:w?.color,"--menu-item-hover":w?.hover},children:[h.alignItemsLabels===`all`&&(0,N.jsx)(`div`,{...h.getStyles(`itemIndicator`,{styles:i,classNames:t}),"data-placeholder":!0}),s&&(0,N.jsx)(`div`,{...h.getStyles(`itemSection`,{styles:i,classNames:t}),"data-position":`left`,children:s}),l&&(0,N.jsx)(`div`,{...h.getStyles(`itemLabel`,{styles:i,classNames:t}),"data-menu-item-label":!0,children:l}),(0,N.jsx)(`div`,{...h.getStyles(`itemSection`,{styles:i,classNames:t}),"data-position":`right`,children:c||(0,N.jsx)(so,{...h.getStyles(`chevron`),size:14})})]})});hc.classes=Ws,hc.displayName=`@mantine/core/MenuSubItem`;function gc({children:e,refProp:t}){if(!le(e))throw Error(`Menu.Sub.Target component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);return zs(),(0,N.jsx)(Ei.Target,{refProp:t,popupType:`menu`,children:e})}gc.displayName=`@mantine/core/MenuSubTarget`;var _c={offset:0,position:`right-start`,safeAreaPolygon:!0,transitionProps:{duration:0},openDelay:0,middlewares:{shift:{crossAxis:!0}}};function vc(e){let{children:t,closeDelay:n,openDelay:r,position:i,safeAreaPolygon:a,opened:o,onChange:s,...c}=v(`MenuSub`,_c,e),l=be(),[u,d]=Er({value:o,finalValue:!1,onChange:s}),f=(0,M.use)(Hs),p=zs(),{dir:m}=jt(),h=Et(m,i),g=f?.registerOpenSub??p.registerOpenSub,_=(0,M.useRef)(null),y=(0,M.useCallback)(e=>{let t=_.current;return t&&t!==e&&t(),_.current=e,()=>{_.current===e&&(_.current=null)}},[]),b=(0,M.useRef)(d);b.current=d;let x=(0,M.useCallback)(()=>b.current(!0),[]),S=(0,M.useCallback)(()=>b.current(!1),[]);(0,M.useEffect)(()=>{if(u)return g(S)},[u,g,S]);let{context:C,refs:w}=ht({placement:h,open:u,onOpenChange:e=>{e?x():S()}}),{getReferenceProps:T,getFloatingProps:ee}=kt([xt(C,{handleClose:a?Dt(typeof a==`object`?a:void 0):void 0,delay:{open:r,close:n}})]);return(0,N.jsx)(Hs,{value:{opened:u,close:S,open:x,focusFirstItem:()=>window.setTimeout(()=>{document.getElementById(`${l}-dropdown`)?.querySelectorAll(`[data-menu-item]:not([data-disabled])`)[0]?.focus()},16),focusParentItem:()=>window.setTimeout(()=>{document.getElementById(`${l}-target`)?.focus()},16),parentContext:f,setReference:w.setReference,setFloating:w.setFloating,getReferenceProps:T,getFloatingProps:ee,registerOpenSub:y},children:(0,N.jsx)(Ei,{opened:u,onChange:e=>e?x():S(),withArrow:!1,id:l,position:i,...c,withinPortal:!1,children:t})})}vc.extend=e=>e,vc.displayName=`@mantine/core/MenuSub`,vc.Target=gc,vc.Dropdown=mc,vc.Item=hc;var yc={refProp:`ref`};function bc(e){let{children:t,refProp:n,...r}=v(`MenuTarget`,yc,e),i=te(t);if(!i)throw Error(`Menu.Target component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let a=zs(),o=i.props,s=or(o.onClick,()=>{a.trigger===`click`?a.toggleDropdown():a.trigger===`click-hover`&&(a.setOpenedViaClick(!0),a.opened||a.openDropdown())}),c=or(o.onMouseEnter,()=>(a.trigger===`hover`||a.trigger===`click-hover`)&&a.openDropdown()),l=or(o.onMouseLeave,()=>{(a.trigger===`hover`||a.trigger===`click-hover`&&!a.openedViaClick)&&a.closeDropdown()});return(0,N.jsx)(Ei.Target,{refProp:n,popupType:`menu`,...r,children:(0,M.cloneElement)(i,{onClick:s,onMouseEnter:c,onMouseLeave:l,"data-expanded":a.opened?!0:void 0})})}bc.displayName=`@mantine/core/MenuTarget`;var xc={trapFocus:!0,closeOnItemClick:!0,withInitialFocusPlaceholder:!0,clickOutsideEvents:[`mousedown`,`touchstart`,`keydown`],loop:!0,trigger:`click`,openDelay:0,closeDelay:100,menuItemTabIndex:-1,alignItemsLabels:`with-indicators`},Sc=w(e=>{let t=v(`Menu`,xc,e),{children:n,onOpen:r,onClose:i,opened:a,defaultOpened:o,trapFocus:s,onChange:l,closeOnItemClick:u,loop:d,closeOnEscape:f,trigger:p,openDelay:m,closeDelay:h,classNames:g,styles:_,unstyled:y,variant:b,vars:x,menuItemTabIndex:S,keepMounted:C,withInitialFocusPlaceholder:w,attributes:T,onExitTransitionEnd:ee,alignItemsLabels:E,checkIcon:D,...O}=t,te=c({name:`Menu`,classes:Ws,props:t,classNames:g,styles:_,unstyled:y,attributes:T}),[ne,re]=Er({value:a,defaultValue:o,finalValue:!1,onChange:l}),[k,ie]=(0,M.useState)(!1),ae=()=>{re(!1),ie(!1),ne&&i?.()},oe=()=>{re(!0),!ne&&r?.()},se=()=>{ne?ae():oe()},{openDropdown:ce,closeDropdown:le}=oi({open:oe,close:ae,closeDelay:h,openDelay:m}),ue=(0,M.useRef)(null),de=(0,M.useCallback)(e=>{let t=ue.current;return t&&t!==e&&t(),ue.current=e,()=>{ue.current===e&&(ue.current=null)}},[]),fe=(0,M.useRef)(0),[pe,me]=(0,M.useState)(!1),he=(0,M.useCallback)(()=>(fe.current+=1,fe.current===1&&me(!0),()=>{--fe.current,fe.current===0&&me(!1)}),[]),_e=(0,M.useRef)(null),ve=()=>{_e.current?.(),ee?.()},ye=e=>lr(`[data-menu-item]`,`[data-menu-dropdown]`,e),{resolvedClassNames:A,resolvedStyles:j}=ge({classNames:g,styles:_,props:t});return(0,N.jsx)(Rs,{value:{getStyles:te,opened:ne,toggleDropdown:se,getItemIndex:ye,openedViaClick:k,setOpenedViaClick:ie,closeOnItemClick:u,closeDropdown:p===`click`?ae:le,openDropdown:p===`click`?oe:ce,closeDropdownImmediately:ae,loop:d,trigger:p,unstyled:y,menuItemTabIndex:S,withInitialFocusPlaceholder:w,registerOpenSub:de,hasSearch:pe,registerSearch:he,searchExitClearRef:_e,alignItemsLabels:E,checkIcon:D},children:(0,N.jsx)(Ei,{returnFocus:!0,...O,opened:ne,onChange:se,defaultOpened:o,trapFocus:!C&&s,closeOnEscape:f,__staticSelector:`Menu`,classNames:A,styles:j,unstyled:y,variant:b,keepMounted:C,onExitTransitionEnd:ve,children:n})})});Sc.displayName=`@mantine/core/Menu`,Sc.classes=Ws,Sc.Item=$s,Sc.Label=ec,Sc.Dropdown=Qs,Sc.Target=bc,Sc.Divider=qs,Sc.Search=pc,Sc.Sub=vc,Sc.CheckboxItem=Gs,Sc.CheckboxGroup=Vs,Sc.RadioItem=ic,Sc.RadioGroup=nc,Sc.ContextMenu=Ks;var[Cc,wc]=dt(`Modal component was not found in tree`),Tc={root:`m_9df02822`,content:`m_54c44539`,inner:`m_1f958f16`,header:`m_d0e2b9cd`},Ec=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`ModalBody`,null,e),s=wc();return(0,N.jsx)(Za,{...s.getStyles(`body`,{classNames:t,style:r,styles:i,className:n}),...o})});Ec.classes=Tc,Ec.displayName=`@mantine/core/ModalBody`;var Dc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`ModalCloseButton`,null,e),s=wc();return(0,N.jsx)(Qa,{...s.getStyles(`close`,{classNames:t,style:r,styles:i,className:n}),...o})});Dc.classes=Tc,Dc.displayName=`@mantine/core/ModalCloseButton`;var Oc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,children:o,__hidden:s,...c}=v(`ModalContent`,null,e),l=wc(),u=l.scrollAreaComponent||oo;return(0,N.jsx)($a,{...l.getStyles(`content`,{className:n,style:r,styles:i,classNames:t}),innerProps:l.getStyles(`inner`,{className:n,style:r,styles:i,classNames:t}),"data-full-screen":l.fullScreen||void 0,"data-modal-content":!0,"data-hidden":s||void 0,...c,children:(0,N.jsx)(u,{style:{maxHeight:l.fullScreen?`100dvh`:`calc(100dvh - (${j(l.yOffset)} * 2))`},children:o})})});Oc.classes=Tc,Oc.displayName=`@mantine/core/ModalContent`;var kc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`ModalHeader`,null,e),s=wc();return(0,N.jsx)(eo,{...s.getStyles(`header`,{classNames:t,style:r,styles:i,className:n}),...o})});kc.classes=Tc,kc.displayName=`@mantine/core/ModalHeader`;var Ac=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`ModalOverlay`,null,e),s=wc();return(0,N.jsx)(ro,{...s.getStyles(`overlay`,{classNames:t,style:r,styles:i,className:n}),...o})});Ac.classes=Tc,Ac.displayName=`@mantine/core/ModalOverlay`;var jc={__staticSelector:`Modal`,closeOnClickOutside:!0,withinPortal:!0,lockScroll:!0,trapFocus:!0,returnFocus:!0,closeOnEscape:!0,keepMounted:!1,zIndex:ft(`modal`),transitionProps:{duration:200,transition:`fade-down`},yOffset:`5dvh`},Mc=D((e,{radius:t,size:n,yOffset:r,xOffset:i})=>({root:{"--modal-radius":t===void 0?void 0:Oe(t),"--modal-size":ye(n,`modal-size`),"--modal-y-offset":j(r),"--modal-x-offset":j(i)}})),Nc=w(e=>{let t=v(`ModalRoot`,jc,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,yOffset:l,scrollAreaComponent:u,radius:d,fullScreen:f,centered:p,xOffset:m,__staticSelector:h,attributes:g,..._}=t,y=c({name:h,classes:Tc,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:g,vars:s,varsResolver:Mc});return(0,N.jsx)(Cc,{value:{yOffset:l,scrollAreaComponent:u,getStyles:y,fullScreen:f},children:(0,N.jsx)(Ja,{...y(`root`),"data-full-screen":f||void 0,"data-centered":p||void 0,"data-offset-scrollbars":u===wt.Autosize||void 0,unstyled:o,..._})})});Nc.classes=Tc,Nc.varsResolver=Mc,Nc.displayName=`@mantine/core/ModalRoot`;var Pc=(0,M.createContext)(null);function Fc({children:e}){let[t,n]=(0,M.useState)([]),[r,i]=(0,M.useState)(ft(`modal`)),[a]=(0,M.useState)(()=>new WeakSet);return(0,N.jsx)(Pc,{value:{stack:t,addModal:(e,t)=>{n(t=>[...new Set([...t,e])]),i(e=>typeof t==`number`&&typeof e==`number`?Math.max(e,t):e)},removeModal:e=>n(t=>t.filter(t=>t!==e)),getZIndex:e=>`calc(${r} + ${t.indexOf(e)} + 1)`,currentId:t[t.length-1],maxZIndex:r,handledEscapeEvents:a},children:e})}Fc.displayName=`@mantine/core/ModalStack`;var Ic=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`ModalTitle`,null,e),s=wc();return(0,N.jsx)(ao,{...s.getStyles(`title`,{classNames:t,style:r,styles:i,className:n}),...o})});Ic.classes=Tc,Ic.displayName=`@mantine/core/ModalTitle`;var Lc={closeOnClickOutside:!0,withinPortal:!0,lockScroll:!0,trapFocus:!0,returnFocus:!0,closeOnEscape:!0,keepMounted:!1,zIndex:ft(`modal`),transitionProps:{duration:200,transition:`fade-down`},withOverlay:!0,withCloseButton:!0},Rc=w(e=>{let{title:t,withOverlay:n,overlayProps:r,withCloseButton:i,closeButtonProps:a,children:o,radius:s,opened:c,stackId:l,zIndex:u,...d}=v(`Modal`,Lc,e),f=(0,M.use)(Pc),p=!!t||i,m=f&&l?{closeOnEscape:f.currentId===l,trapFocus:f.currentId===l,zIndex:f.getZIndex(l),__handledEscapeEvents:f.handledEscapeEvents}:{},h=n===!1?!1:l&&f?f.currentId===l:c;return(0,M.useEffect)(()=>{f&&l&&(c?f.addModal(l,u||ft(`modal`)):f.removeModal(l))},[c,l,u]),(0,N.jsxs)(Nc,{radius:s,opened:c,zIndex:f&&l?f.getZIndex(l):u,...d,...m,children:[n&&(0,N.jsx)(Ac,{visible:h,transitionProps:f&&l?{duration:0}:void 0,...r}),(0,N.jsxs)(Oc,{radius:s,__hidden:f&&l&&c?l!==f.currentId:!1,children:[p&&(0,N.jsxs)(kc,{children:[t&&(0,N.jsx)(Ic,{children:t}),i&&(0,N.jsx)(Dc,{...a})]}),(0,N.jsx)(Ec,{children:o})]})]})});Rc.classes=Tc,Rc.displayName=`@mantine/core/Modal`,Rc.Root=Nc,Rc.Overlay=Ac,Rc.Content=Oc,Rc.Body=Ec,Rc.Header=kc,Rc.Title=Ic,Rc.CloseButton=Dc,Rc.Stack=Fc;function zc(e,t){if(e<1)return[];let n=Array(e).fill(``);if(t){let r=t.trim().split(``);for(let t=0;t({root:{"--pin-input-size":ye(t??`sm`,`pin-input-size`)}})),Wc=w(e=>{let{name:t,form:n,className:r,value:i,defaultValue:a,variant:o,gap:l,style:u,size:d,classNames:f,styles:p,unstyled:m,length:h,onChange:g,onComplete:_,manageFocus:y,autoFocus:b,error:x,success:S,radius:C,disabled:w,oneTimeCode:T,placeholder:ee,type:E,mask:D,readOnly:O,inputType:te,inputMode:re,ariaLabel:k,vars:ie,id:ae,hiddenInputProps:oe,rootRef:se,getInputProps:ce,attributes:le,ref:ue,...de}=v([`Input`,`PinInput`],Hc,e),pe=be(ae),me=c({name:`PinInput`,classes:Bc,props:e,className:r,style:u,classNames:f,styles:p,unstyled:m,attributes:le,vars:ie,varsResolver:Uc}),{resolvedClassNames:he,resolvedStyles:_e}=ge({classNames:f,styles:p,props:e}),[ve,ye]=(0,M.useState)(-1),A=(0,M.useRef)([]),j=h??4,xe=(0,M.useRef)(!1),[Se,Ce]=Er({value:i===void 0?void 0:zc(j,i),defaultValue:a?.split(``).slice(0,j),finalValue:zc(j,``),onChange:e=>{let t=e.join(``).trim();g?.(t),t.length===j&&!xe.current?(xe.current=!0,_?.(t)):t.length(E instanceof RegExp?E:E&&E in Vc?Vc[E]:null)?.test(e),De=(e,t)=>{if(y){if(e===`next`){let e=t+1;e=0&&A.current[e]?.focus()}}},Oe=(e,t)=>{let n=[...we];return n[t]=e,Ce(n),n},ke=(e,t)=>{let n=e.target.value;if(n.length>1){if(n.length>2){if(Ee(n)){Ce(zc(j,n));let e=Math.min(n.length,j);e{let{ctrlKey:n,metaKey:r,key:i,shiftKey:a,target:o}=e,s=o.value;if(re===`numeric`){let t=[`Backspace`,`Tab`,`Control`,`Delete`,`ArrowLeft`,`ArrowRight`],a=n||r;if(!(t.includes(i)||a||!Number.isNaN(Number(i)))){e.preventDefault();return}}switch(i){case`ArrowLeft`:e.preventDefault(),De(`prev`,t);break;case`ArrowRight`:e.preventDefault(),De(`next`,t);break;case`Tab`:a&&t>0&&y&&(e.preventDefault(),De(`prev`,t));break;case` `:e.preventDefault(),De(`next`,t);break;case`Delete`:e.preventDefault(),O||Oe(``,t);break;case`Backspace`:O?e.preventDefault():s===``?(e.preventDefault(),De(`prev`,t)):(Oe(``,t),t0&&i===we[t]&&(e.preventDefault(),De(`next`,t))}},je=(e,t)=>{e.target.select(),ye(t)},Me=()=>{ye(-1)},Ne=e=>{if(e.preventDefault(),O)return;let t=e.clipboardData.getData(`text/plain`).replace(/[\n\r\s]+/g,``);if(Ee(t.trim())){let e=zc(j,t);Ce(e);let n=e.filter(e=>e!==``).length;n>=j?A.current[j-1]?.focus():A.current[n]?.focus()}};return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(ne,{...de,...me(`root`),ref:se,role:`group`,id:pe,gap:l,unstyled:m,wrap:`nowrap`,variant:o,__size:d,dir:`ltr`,children:we.map((e,t)=>(0,M.createElement)(fe,{component:`input`,...me(`pinInput`,{style:{"--input-padding":`0`,"--input-text-align":`center`}}),classNames:he,styles:_e,size:d,__staticSelector:`PinInput`,id:`${pe}-${t+1}`,key:`${pe}-${t}`,inputMode:re||(E===`number`?`numeric`:`text`),onChange:e=>ke(e,t),onKeyDown:e=>Ae(e,t),onFocus:e=>je(e,t),onBlur:Me,onPaste:Ne,type:te||(D?`password`:E===`number`?`tel`:`text`),radius:C,error:x,success:S,variant:o,disabled:w,ref:e=>{e&&(t===0&&s(ue,e),A.current[t]=e)},autoComplete:T?`one-time-code`:`off`,placeholder:ve===t?``:ee,value:e,autoFocus:b&&t===0,unstyled:m,"aria-label":k,readOnly:O,...ce?.(t)}))}),(0,N.jsx)(`input`,{type:`hidden`,name:t,form:n,value:Te,...oe})]})});Wc.classes={...Bc,...A.classes},Wc.varsResolver=Uc,Wc.displayName=`@mantine/core/PinInput`;var Gc=w(e=>{let t=v([`Input`,`InputWrapper`,`TextInput`],null,e);return(0,N.jsx)(A,{component:`input`,...t,__staticSelector:`TextInput`})});Gc.classes=A.classes,Gc.displayName=`@mantine/core/TextInput`;var Kc=[];for(let e=0;e<256;++e)Kc.push((e+256).toString(16).slice(1));function qc(e,t=0){return(Kc[e[t+0]]+Kc[e[t+1]]+Kc[e[t+2]]+Kc[e[t+3]]+`-`+Kc[e[t+4]]+Kc[e[t+5]]+`-`+Kc[e[t+6]]+Kc[e[t+7]]+`-`+Kc[e[t+8]]+Kc[e[t+9]]+`-`+Kc[e[t+10]]+Kc[e[t+11]]+Kc[e[t+12]]+Kc[e[t+13]]+Kc[e[t+14]]+Kc[e[t+15]]).toLowerCase()}var Jc,Yc=new Uint8Array(16);function Xc(){if(!Jc){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);Jc=crypto.getRandomValues.bind(crypto)}return Jc(Yc)}var Zc={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Qc(e,t,n){if(Zc.randomUUID&&!t&&!e)return Zc.randomUUID();e||={};let r=e.random??e.rng?.()??Xc();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return qc(r)}var $c=It(),I=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e.SUBAGENT_STARTED=`SUBAGENT_STARTED`,e.SUBAGENT_FINISHED=`SUBAGENT_FINISHED`,e.SUBAGENT_ERROR=`SUBAGENT_ERROR`,e}({}),el={TextMessageStartEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`role`,`name`],fields:{}},TextMessageContentEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},TextMessageEndEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},TextMessageChunkEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`messageId`,`role`,`delta`,`name`],fields:{}},ToolCallStartEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`parentMessageId`],fields:{}},ToolCallArgsEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ToolCallEndEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ToolCallChunkEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`toolCallId`,`toolCallName`,`parentMessageId`,`delta`],fields:{}},TextPart:{optional:[`id`,`metadata`],fields:{}},DataSource:{optional:[],fields:{}},UrlSource:{optional:[`mimeType`],fields:{}},FileSource:{optional:[`provider`,`mimeType`],fields:{}},PartSource:{discriminator:`type`,variants:{data:`DataSource`,url:`UrlSource`,file:`FileSource`}},ImagePart:{optional:[`id`,`metadata`],fields:{source:`PartSource`}},AudioPart:{optional:[`id`,`metadata`],fields:{source:`PartSource`}},VideoPart:{optional:[`id`,`metadata`],fields:{source:`PartSource`}},DocumentPart:{optional:[`id`,`metadata`],fields:{source:`PartSource`}},ContentPart:{discriminator:`type`,variants:{text:`TextPart`,image:`ImagePart`,audio:`AudioPart`,video:`VideoPart`,document:`DocumentPart`}},ToolCallResultEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`role`],fields:{content:{array:`ContentPart`}}},StateSnapshotEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},AddOperation:{optional:[],fields:{}},RemoveOperation:{optional:[],fields:{}},ReplaceOperation:{optional:[],fields:{}},MoveOperation:{optional:[],fields:{}},CopyOperation:{optional:[],fields:{}},TestOperation:{optional:[],fields:{}},JsonPatchOperation:{discriminator:`op`,variants:{add:`AddOperation`,remove:`RemoveOperation`,replace:`ReplaceOperation`,move:`MoveOperation`,copy:`CopyOperation`,test:`TestOperation`}},StateDeltaEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{delta:{array:`JsonPatchOperation`}}},DeveloperMessage:{optional:[`subagentRunId`,`name`,`encryptedValue`,`metadata`],fields:{}},SystemMessage:{optional:[`subagentRunId`,`name`,`encryptedValue`,`metadata`],fields:{}},FunctionCall:{optional:[],fields:{}},ToolCall:{optional:[`encryptedValue`,`metadata`],fields:{function:`FunctionCall`}},AssistantMessage:{optional:[`subagentRunId`,`name`,`encryptedValue`,`metadata`,`content`,`toolCalls`],fields:{toolCalls:{array:`ToolCall`}}},UserMessage:{optional:[`subagentRunId`,`name`,`encryptedValue`,`metadata`],fields:{content:{array:`ContentPart`}}},ToolMessage:{optional:[`subagentRunId`,`error`,`encryptedValue`,`metadata`],fields:{content:{array:`ContentPart`}}},ActivityMessage:{optional:[`subagentRunId`,`metadata`],fields:{}},ReasoningMessage:{optional:[`subagentRunId`,`encryptedValue`,`metadata`],fields:{}},Message:{discriminator:`role`,variants:{developer:`DeveloperMessage`,system:`SystemMessage`,assistant:`AssistantMessage`,user:`UserMessage`,tool:`ToolMessage`,activity:`ActivityMessage`,reasoning:`ReasoningMessage`}},MessagesSnapshotEvent:{optional:[`timestamp`,`rawEvent`,`metadata`],fields:{messages:{array:`Message`}}},ActivitySnapshotEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`replace`],fields:{}},ActivityDeltaEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{patch:{array:`JsonPatchOperation`}}},RawEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`source`],fields:{}},CustomEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},Tool:{optional:[`parameters`,`metadata`],fields:{}},Context:{optional:[],fields:{}},ResumeEntry:{optional:[`payload`,`metadata`],fields:{}},RunAgentInput:{optional:[`protocolVersion`,`parentRunId`,`state`,`tools`,`context`,`forwardedProps`,`resume`],fields:{messages:{array:`Message`},tools:{array:`Tool`},context:{array:`Context`},resume:{array:`ResumeEntry`}}},RunStartedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`protocolVersion`,`parentRunId`,`input`],fields:{input:`RunAgentInput`}},RunFinishedSuccessOutcome:{optional:[`pendingToolCallIds`],fields:{}},Interrupt:{optional:[`subagentRunId`,`message`,`toolCallId`,`responseSchema`,`expiresAt`,`metadata`],fields:{}},RunFinishedInterruptOutcome:{optional:[],fields:{interrupts:{array:`Interrupt`}}},RunFinishedCancelledOutcome:{optional:[],fields:{}},RunFinishedOutcome:{discriminator:`type`,variants:{success:`RunFinishedSuccessOutcome`,interrupt:`RunFinishedInterruptOutcome`,cancelled:`RunFinishedCancelledOutcome`}},TokenUsage:{optional:[`provider`,`model`,`inputTokens`,`outputTokens`,`totalTokens`,`reasoningTokens`,`cachedInputTokens`,`cacheWriteInputTokens`],fields:{}},RunFinishedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`result`,`outcome`,`usage`],fields:{outcome:`RunFinishedOutcome`,usage:{array:`TokenUsage`}}},RunErrorEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`code`,`usage`],fields:{usage:{array:`TokenUsage`}}},StepStartedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},StepFinishedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningStartEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningMessageStartEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningMessageContentEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningMessageEndEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningMessageChunkEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`messageId`,`delta`],fields:{}},ReasoningEndEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningEncryptedValueEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},SubagentStartedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`description`,`parentSubagentRunId`,`parentToolCallId`,`parentMessageId`],fields:{}},SubagentFinishedSuccessOutcome:{optional:[],fields:{}},SubagentFinishedSuspendedOutcome:{optional:[`interruptIds`],fields:{}},SubagentFinishedOutcome:{discriminator:`type`,variants:{success:`SubagentFinishedSuccessOutcome`,suspended:`SubagentFinishedSuspendedOutcome`}},SubagentFinishedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`result`,`outcome`],fields:{outcome:`SubagentFinishedOutcome`}},SubagentErrorEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`code`],fields:{}},Event:{discriminator:`type`,variants:{TEXT_MESSAGE_START:`TextMessageStartEvent`,TEXT_MESSAGE_CONTENT:`TextMessageContentEvent`,TEXT_MESSAGE_END:`TextMessageEndEvent`,TEXT_MESSAGE_CHUNK:`TextMessageChunkEvent`,TOOL_CALL_START:`ToolCallStartEvent`,TOOL_CALL_ARGS:`ToolCallArgsEvent`,TOOL_CALL_END:`ToolCallEndEvent`,TOOL_CALL_CHUNK:`ToolCallChunkEvent`,TOOL_CALL_RESULT:`ToolCallResultEvent`,STATE_SNAPSHOT:`StateSnapshotEvent`,STATE_DELTA:`StateDeltaEvent`,MESSAGES_SNAPSHOT:`MessagesSnapshotEvent`,ACTIVITY_SNAPSHOT:`ActivitySnapshotEvent`,ACTIVITY_DELTA:`ActivityDeltaEvent`,RAW:`RawEvent`,CUSTOM:`CustomEvent`,RUN_STARTED:`RunStartedEvent`,RUN_FINISHED:`RunFinishedEvent`,RUN_ERROR:`RunErrorEvent`,STEP_STARTED:`StepStartedEvent`,STEP_FINISHED:`StepFinishedEvent`,REASONING_START:`ReasoningStartEvent`,REASONING_MESSAGE_START:`ReasoningMessageStartEvent`,REASONING_MESSAGE_CONTENT:`ReasoningMessageContentEvent`,REASONING_MESSAGE_END:`ReasoningMessageEndEvent`,REASONING_MESSAGE_CHUNK:`ReasoningMessageChunkEvent`,REASONING_END:`ReasoningEndEvent`,REASONING_ENCRYPTED_VALUE:`ReasoningEncryptedValueEvent`,SUBAGENT_STARTED:`SubagentStartedEvent`,SUBAGENT_FINISHED:`SubagentFinishedEvent`,SUBAGENT_ERROR:`SubagentErrorEvent`}},SubagentInfo:{optional:[`description`],fields:{}},IdentityCapabilities:{optional:[`name`,`type`,`description`,`version`,`provider`,`documentationUrl`,`metadata`],fields:{}},TransportCapabilities:{optional:[`streaming`,`websocket`,`httpBinary`,`pushNotifications`,`resumable`],fields:{}},ToolsCapabilities:{optional:[`supported`,`items`,`parallelCalls`,`clientProvided`],fields:{items:{array:`Tool`}}},OutputCapabilities:{optional:[`structuredOutput`,`supportedMimeTypes`],fields:{}},StateCapabilities:{optional:[`snapshots`,`deltas`,`memory`,`persistentState`],fields:{}},MultiAgentCapabilities:{optional:[`supported`,`delegation`,`handoffs`,`subagents`],fields:{subagents:{array:`SubagentInfo`}}},ReasoningCapabilities:{optional:[`supported`,`streaming`,`encrypted`],fields:{}},MultimodalInputCapabilities:{optional:[`image`,`audio`,`video`,`pdf`,`file`],fields:{}},MultimodalOutputCapabilities:{optional:[`image`,`audio`],fields:{}},MultimodalCapabilities:{optional:[`input`,`output`],fields:{input:`MultimodalInputCapabilities`,output:`MultimodalOutputCapabilities`}},ExecutionCapabilities:{optional:[`codeExecution`,`sandboxed`,`maxIterations`,`maxExecutionTime`],fields:{}},HumanInTheLoopCapabilities:{optional:[`supported`,`approvals`,`interventions`,`feedback`,`interrupts`,`approveWithEdits`],fields:{}},AgentCapabilities:{optional:[`identity`,`transport`,`tools`,`output`,`state`,`multiAgent`,`reasoning`,`multimodal`,`execution`,`humanInTheLoop`,`custom`],fields:{identity:`IdentityCapabilities`,transport:`TransportCapabilities`,tools:`ToolsCapabilities`,output:`OutputCapabilities`,state:`StateCapabilities`,multiAgent:`MultiAgentCapabilities`,reasoning:`ReasoningCapabilities`,multimodal:`MultimodalCapabilities`,execution:`ExecutionCapabilities`,humanInTheLoop:`HumanInTheLoopCapabilities`}}};function tl(e,t){if(typeof t==`string`)return tl(e,el[t]);if(`array`in t){if(!Array.isArray(e))return e;let n=e.map(e=>tl(e,t.array));return n.every((t,n)=>t===e[n])?e:n}if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e;if(`discriminator`in t){let r=n[t.discriminator];return typeof r==`string`&&Object.prototype.hasOwnProperty.call(t.variants,r)?tl(e,t.variants[r]):e}let r=n;for(let e of t.optional)Object.prototype.hasOwnProperty.call(n,e)&&n[e]===null&&(r===n&&(r={...n}),delete r[e]);for(let[e,i]of Object.entries(t.fields)){if(!Object.prototype.hasOwnProperty.call(r,e))continue;let t=tl(r[e],i);t!==r[e]&&(r===n&&(r={...n}),r[e]=t)}return r}function nl(e,t){return tl(e,t)}var L=class extends Error{constructor(e){super(e)}},rl=class extends L{constructor(){super(`Connect not implemented. This method is not supported by the current agent.`)}};function il(e,t){return t===void 0?e:e===void 0?{...t}:{...e,...t}}function al(e){return e===void 0?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function ol(e){return Array.isArray(e)&&e.some(e=>e.type!==`text`)}var sl=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),cl=Object.prototype.hasOwnProperty;function ll(e,t){return cl.call(e,t)}function ul(e){if(Array.isArray(e)){for(var t=Array(e.length),n=0;n=48&&r<=57){t++;continue}return!1}return!0}function pl(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ml(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function hl(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;tyl,_areEquals:()=>kl,applyOperation:()=>wl,applyPatch:()=>Tl,applyReducer:()=>El,deepClone:()=>bl,getValueByPointer:()=>Cl,validate:()=>Ol,validator:()=>Dl}),yl=_l,bl=dl,xl={add:function(e,t,n){return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){var r=Cl(n,this.path);r&&=dl(r);var i=wl(n,{op:`remove`,path:this.from}).removed;return wl(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){var r=Cl(n,this.from);return wl(n,{op:`add`,path:this.path,value:dl(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:kl(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},Sl={add:function(e,t,n){return fl(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:xl.move,copy:xl.copy,test:xl.test,_get:xl._get};function Cl(e,t){if(t==``)return e;var n={op:`_get`,path:t};return wl(e,n),n.value}function wl(e,t,n,r,i,a){if(n===void 0&&(n=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),a===void 0&&(a=0),n&&(typeof n==`function`?n(t,0,e,t.path):Dl(t,0)),t.path===``){var o={newDocument:e};if(t.op===`add`)return o.newDocument=t.value,o;if(t.op===`replace`)return o.newDocument=t.value,o.removed=e,o;if(t.op===`move`||t.op===`copy`)return o.newDocument=Cl(e,t.from),t.op===`move`&&(o.removed=e),o;if(t.op===`test`){if(o.test=kl(e,t.value),o.test===!1)throw new yl(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o.newDocument=e,o}if(t.op===`remove`)return o.removed=e,o.newDocument=null,o;if(t.op===`_get`)return t.value=e,o;if(n)throw new yl("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);return o}r||(e=dl(e));var s=(t.path||``).split(`/`),c=e,l=1,u=s.length,d=void 0,f=void 0,p=void 0;for(p=typeof n==`function`?n:Dl;;){if(f=s[l],f&&f.indexOf(`~`)!=-1&&(f=ml(f)),i&&(f==`__proto__`||f==`prototype`&&l>0&&s[l-1]==`constructor`))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(c[f]===void 0?d=s.slice(0,l).join(`/`):l==u-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),l++,Array.isArray(c)){if(f===`-`)f=c.length;else if(n&&!fl(f))throw new yl(`Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index`,`OPERATION_PATH_ILLEGAL_ARRAY_INDEX`,a,t,e);else fl(f)&&(f=~~f);if(l>=u){if(n&&t.op===`add`&&f>c.length)throw new yl(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);var o=Sl[t.op].call(t,c,f,e);if(o.test===!1)throw new yl(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}}else if(l>=u){var o=xl[t.op].call(t,c,f,e);if(o.test===!1)throw new yl(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}if(c=c[f],n&&l0)throw new yl('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new yl("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new yl("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&hl(e.value))throw new yl("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new yl("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new yl(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=Ol([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new yl(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function Ol(e,t,n){try{if(!Array.isArray(e))throw new yl(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)Tl(dl(t),dl(e),n||!0);else{n||=Dl;for(var r=0;rVl,generate:()=>zl,observe:()=>Rl,unobserve:()=>Ll}),jl=new WeakMap,Ml=function(){function e(e){this.observers=new Map,this.obj=e}return e}(),Nl=function(){function e(e,t){this.callback=e,this.observer=t}return e}();function Pl(e){return jl.get(e)}function Fl(e,t){return e.observers.get(t)}function Il(e,t){e.observers.delete(t.callback)}function Ll(e,t){t.unobserve()}function Rl(e,t){var n=[],r,i=Pl(e);if(!i)i=new Ml(e),jl.set(e,i);else{var a=Fl(i,t);r=a&&a.observer}if(r)return r;if(r={},i.value=dl(e),t){r.callback=t,r.next=null;var o=function(){zl(r)},s=function(){clearTimeout(r.next),r.next=setTimeout(o)};typeof window<`u`&&(window.addEventListener(`mouseup`,s),window.addEventListener(`keyup`,s),window.addEventListener(`mousedown`,s),window.addEventListener(`keydown`,s),window.addEventListener(`change`,s))}return r.patches=n,r.object=e,r.unobserve=function(){zl(r),clearTimeout(r.next),Il(i,r),typeof window<`u`&&(window.removeEventListener(`mouseup`,s),window.removeEventListener(`keyup`,s),window.removeEventListener(`mousedown`,s),window.removeEventListener(`keydown`,s),window.removeEventListener(`change`,s))},i.observers.set(t,new Nl(t,r)),r}function zl(e,t){t===void 0&&(t=!1);var n=jl.get(e.object);Bl(n.value,e.object,e.patches,``,t),e.patches.length&&Tl(n.value,e.patches);var r=e.patches;return r.length>0&&(e.patches=[],e.callback&&e.callback(r)),r}function Bl(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=ul(t),o=ul(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(ll(t,l)&&(t[l]!==void 0||u===void 0||Array.isArray(t)!==!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?Bl(u,d,n,r+`/`+pl(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+pl(l),value:dl(u)}),n.push({op:`replace`,path:r+`/`+pl(l),value:dl(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+pl(l),value:dl(u)}),n.push({op:`remove`,path:r+`/`+pl(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(s||a.length!=o.length)for(var c=0;c0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Jl(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function Yl(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof Xl?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function Ql(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof ql==`function`?ql(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function $l(e){return typeof e==`function`}function eu(e){var t=e(function(e){Error.call(e),e.stack=Error().stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var tu=eu(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription: -`+t.map(function(e,t){return t+1+`) `+e.toString()}).join(` - `):``,this.name=`UnsubscriptionError`,this.errors=t}});function nu(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var ru=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var e,t,n,r,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a){if(this._parentage=null,Array.isArray(a))try{for(var o=ql(a),s=o.next();!s.done;s=o.next())s.value.remove(this)}catch(t){e={error:t}}finally{try{s&&!s.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else a.remove(this)}var c=this.initialTeardown;if($l(c))try{c()}catch(e){i=e instanceof tu?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var u=ql(l),d=u.next();!d.done;d=u.next()){var f=d.value;try{ou(f)}catch(e){i??=[],e instanceof tu?i=Yl(Yl([],Jl(i)),Jl(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}}if(i)throw new tu(i)}},e.prototype.add=function(t){if(t&&t!==this){if(this.closed)ou(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=this._finalizers??[]).push(t)}}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&nu(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&nu(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e}(),iu=ru.EMPTY;function au(e){return e instanceof ru||e&&`closed`in e&&$l(e.remove)&&$l(e.add)&&$l(e.unsubscribe)}function ou(e){$l(e)?e():e.unsubscribe()}var su={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},cu={setTimeout:function(e,t){var n=[...arguments].slice(2),r=cu.delegate;return r?.setTimeout?r.setTimeout.apply(r,Yl([e,t],Jl(n))):setTimeout.apply(void 0,Yl([e,t],Jl(n)))},clearTimeout:function(e){return(cu.delegate?.clearTimeout||clearTimeout)(e)},delegate:void 0};function lu(e){cu.setTimeout(function(){var t=su.onUnhandledError;if(t)t(e);else throw e})}function uu(){}var du=(function(){return mu(`C`,void 0,void 0)})();function fu(e){return mu(`E`,void 0,e)}function pu(e){return mu(`N`,e,void 0)}function mu(e,t,n){return{kind:e,value:t,error:n}}var hu=null;function gu(e){if(su.useDeprecatedSynchronousErrorHandling){var t=!hu;if(t&&(hu={errorThrown:!1,error:null}),e(),t){var n=hu,r=n.errorThrown,i=n.error;if(hu=null,r)throw i}}else e()}function _u(e){su.useDeprecatedSynchronousErrorHandling&&hu&&(hu.errorThrown=!0,hu.error=e)}var vu=function(e){Wl(t,e);function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,au(t)&&t.add(n)):n.destination=Eu,n}return t.create=function(e,t,n){return new Su(e,t,n)},t.prototype.next=function(e){this.isStopped?Tu(pu(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?Tu(fu(e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?Tu(du,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(ru),yu=Function.prototype.bind;function bu(e,t){return yu.call(e,t)}var xu=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){Cu(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){Cu(e)}else Cu(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){Cu(e)}},e}(),Su=function(e){Wl(t,e);function t(t,n,r){var i=e.call(this)||this,a;if($l(t)||!t)a={next:t??void 0,error:n??void 0,complete:r??void 0};else{var o;i&&su.useDeprecatedNextContext?(o=Object.create(t),o.unsubscribe=function(){return i.unsubscribe()},a={next:t.next&&bu(t.next,o),error:t.error&&bu(t.error,o),complete:t.complete&&bu(t.complete,o)}):a=t}return i.destination=new xu(a),i}return t}(vu);function Cu(e){su.useDeprecatedSynchronousErrorHandling?_u(e):lu(e)}function wu(e){throw e}function Tu(e,t){var n=su.onStoppedNotification;n&&cu.setTimeout(function(){return n(e,t)})}var Eu={closed:!0,next:uu,error:wu,complete:uu},Du=(function(){return typeof Symbol==`function`&&Symbol.observable||`@@observable`})();function Ou(e){return e}function ku(){return Au([...arguments])}function Au(e){return e.length===0?Ou:e.length===1?e[0]:function(t){return e.reduce(function(e,t){return t(e)},t)}}var ju=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r=this,i=Pu(e)?e:new Su(e,t,n);return gu(function(){var e=r,t=e.operator,n=e.source;i.add(t?t.call(i,n):n?r._subscribe(i):r._trySubscribe(i))}),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return t=Mu(t),new t(function(t,r){var i=new Su({next:function(t){try{e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:t});n.subscribe(i)})},e.prototype._subscribe=function(e){return this.source?.subscribe(e)},e.prototype[Du]=function(){return this},e.prototype.pipe=function(){return Au([...arguments])(this)},e.prototype.toPromise=function(e){var t=this;return e=Mu(e),new e(function(e,n){var r;t.subscribe(function(e){return r=e},function(e){return n(e)},function(){return e(r)})})},e.create=function(t){return new e(t)},e}();function Mu(e){return e??su.Promise??Promise}function Nu(e){return e&&$l(e.next)&&$l(e.error)&&$l(e.complete)}function Pu(e){return e&&e instanceof vu||Nu(e)&&au(e)}function Fu(e){return $l(e?.lift)}function Iu(e){return function(t){if(Fu(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw TypeError(`Unable to lift unknown Observable type`)}}function Lu(e,t,n,r,i){return new Ru(e,t,n,r,i)}var Ru=function(e){Wl(t,e);function t(t,n,r,i,a,o){var s=e.call(this,t)||this;return s.onFinalize=a,s.shouldUnsubscribe=o,s._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,s._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,s._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,s}return t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)==null||t.call(this))}},t}(vu),zu=eu(function(e){return function(){e(this),this.name=`ObjectUnsubscribedError`,this.message=`object unsubscribed`}}),Bu=function(e){Wl(t,e);function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return t.prototype.lift=function(e){var t=new Vu(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new zu},t.prototype.next=function(e){var t=this;gu(function(){var n,r;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||=Array.from(t.observers);try{for(var i=ql(t.currentObservers),a=i.next();!a.done;a=i.next())a.value.next(e)}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}})},t.prototype.error=function(e){var t=this;gu(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var n=t.observers;n.length;)n.shift().error(e)}})},t.prototype.complete=function(){var e=this;gu(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){return this.observers?.length>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,n=this,r=n.hasError,i=n.isStopped,a=n.observers;return r||i?iu:(this.currentObservers=null,a.push(e),new ru(function(){t.currentObservers=null,nu(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,n=t.hasError,r=t.thrownError,i=t.isStopped;n?e.error(r):i&&e.complete()},t.prototype.asObservable=function(){var e=new ju;return e.source=this,e},t.create=function(e,t){return new Vu(e,t)},t}(ju),Vu=function(e){Wl(t,e);function t(t,n){var r=e.call(this)||this;return r.destination=t,r.source=n,r}return t.prototype.next=function(e){var t,n;(n=(t=this.destination)?.next)==null||n.call(t,e)},t.prototype.error=function(e){var t,n;(n=(t=this.destination)?.error)==null||n.call(t,e)},t.prototype.complete=function(){var e,t;(t=(e=this.destination)?.complete)==null||t.call(e)},t.prototype._subscribe=function(e){return this.source?.subscribe(e)??iu},t}(Bu),Hu={now:function(){return(Hu.delegate||Date).now()},delegate:void 0},Uu=function(e){Wl(t,e);function t(t,n,r){t===void 0&&(t=1/0),n===void 0&&(n=1/0),r===void 0&&(r=Hu);var i=e.call(this)||this;return i._bufferSize=t,i._windowTime=n,i._timestampProvider=r,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,t),i._windowTime=Math.max(1,n),i}return t.prototype.next=function(t){var n=this,r=n.isStopped,i=n._buffer,a=n._infiniteTimeWindow,o=n._timestampProvider,s=n._windowTime;r||(i.push(t),!a&&i.push(o.now()+s)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),n=this,r=n._infiniteTimeWindow,i=n._buffer.slice(),a=0;a=0}function Hd(e){for(var t=[`topLevel`],n=0,r,i,a,o=function(e){return t.push(e)},s=function(e){return t[t.length-1]=e},c=function(e){r??(r=n,i=t.length,a=e)},l=function(e){e===a&&(r=void 0,i=void 0,a=void 0)},u=function(){return t.pop()},d=function(){return n--},f=function(e){if(`0`<=e&&e<=`9`){o(`number`);return}switch(e){case`"`:o(`string`);return;case`-`:o(`numberNeedsDigit`);return;case`t`:o(`true`);return;case`f`:o(`false`);return;case`n`:o(`null`);return;case`[`:o(`arrayNeedsValue`);return;case`{`:o(`objectNeedsKey`);return}},p=e.length;n`9`)&&(d(),u());break;case`numberNeedsDigit`:s(`number`);break;case`numberNeedsExponent`:s(m===`+`||m===`-`?`numberNeedsDigit`:`number`);break;case`true`:case`false`:case`null`:(m<`a`||m>`z`)&&(d(),u());break;case`arrayNeedsValue`:m===`]`?u():Vd(m)||(l(`collectionItem`),s(`arrayNeedsComma`),f(m));break;case`arrayNeedsComma`:m===`]`?u():m===`,`&&(c(`collectionItem`),s(`arrayNeedsValue`));break;case`objectNeedsKey`:m===`}`?u():m===`"`&&(c(`collectionItem`),s(`objectNeedsColon`),o(`string`));break;case`objectNeedsColon`:m===`:`&&s(`objectNeedsValue`);break;case`objectNeedsValue`:Vd(m)||(l(`collectionItem`),s(`objectNeedsComma`),f(m));break;case`objectNeedsComma`:m===`}`?u():m===`,`&&(c(`collectionItem`),s(`objectNeedsKey`))}}i!=null&&(t.length=i);for(var h=[r==null?e:e.slice(0,r)],g=function(t){return h.push(t.slice(e.length-e.lastIndexOf(t[0])))},_=t.length-1;_>=0;_--)switch(t[_]){case`string`:h.push(`"`);break;case`numberNeedsDigit`:case`numberNeedsExponent`:h.push(`0`);break;case`true`:g(`true`);break;case`false`:g(`false`);break;case`null`:g(`null`);break;case`arrayNeedsValue`:case`arrayNeedsComma`:h.push(`]`);break;case`objectNeedsKey`:case`objectNeedsColon`:case`objectNeedsValue`:case`objectNeedsComma`:h.push(`}`)}return h.join(``)}function Ud(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Wd(e,t=`|`){return e.map(e=>vf(e)).join(t)}function Gd(e,t){return typeof t==`bigint`?t.toString():t}var Kd=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function qd(e){return new Kd(e)}function Jd(e){return e==null}function Yd(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Xd(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r){let e=t._zod.def.shape[a];return r?r(e,a):e}):rf(e,a,r?r(n.value,a):n.value))}}function of(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?nf(e,n,()=>t[n]):rf(e,n,r.value))}}function sf(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function cf(e){return JSON.stringify(e)}function lf(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var uf=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function df(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var ff=qd(()=>{if(cp.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function pf(e){if(df(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return df(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function mf(e){return pf(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var hf=new Set([`string`,`number`,`symbol`]);function gf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function _f(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function B(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function vf(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function yf(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}var bf={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},xf={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]};function Sf(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return af(i,e,Cf(e,t)),_f(e,sf(n,{shape:i,checks:[]}))}function Cf(e,t){let n=tf(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function wf(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(Cf(e,t)),a={};return af(a,e,Reflect.ownKeys(tf(e)).filter(e=>!i.has(e))),_f(e,sf(n,{shape:a,checks:[]}))}function Tf(e,t){if(!pf(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=tf(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return _f(e,sf(e._zod.def,{shape:Ef(e,t)}))}function Ef(e,t){let n={};return af(n,e,Reflect.ownKeys(tf(e))),of(n,t),n}function Df(e,t){if(!pf(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return _f(e,sf(e._zod.def,{shape:Ef(e,t)}))}function Of(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return af(n,e,Reflect.ownKeys(tf(e))),af(n,t,Reflect.ownKeys(tf(t))),_f(e,sf(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function kf(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(Cf(t,n)):void 0,o={};return af(o,t,Reflect.ownKeys(tf(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),_f(t,sf(t._zod.def,{shape:o,checks:[]}))}function Af(e,t,n){let r=n?new Set(Cf(t,n)):void 0,i={};return af(i,t,Reflect.ownKeys(tf(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),_f(t,sf(t._zod.def,{shape:i}))}function jf(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Pf(e){return typeof e==`string`?e:e?.message}function Ff(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function If(e,t,n){var r;for(let i=t;ie;return t[$f]=!0,t}var tp,np=Object.freeze({status:`aborted`}),rp={value:void 0,enumerable:!1},ip=`captureStackTrace`in Error?Error:null;function ap(e){let t=ip;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return ip=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function H(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){rp.value=new a(r);try{Object.defineProperty(n,"_zod",rp)}finally{rp.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),Uf(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?ap(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var op=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},sp=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(tp=globalThis).__zod_globalConfig??(tp.__zod_globalConfig={});var cp=globalThis.__zod_globalConfig;function lp(e){return e&&Object.assign(cp,e),cp}function up(){let e=this._zod;return e.message??=JSON.stringify(e.def,Gd,2),e.message}function dp(e){this._zod.message=e}var fp={get:up,set:dp,enumerable:!0,configurable:!0},pp={value:void 0,enumerable:!1},mp=new WeakSet([Object.prototype,Error.prototype]),hp=(e,t)=>{e.name=`$ZodError`,pp.value=t,Object.defineProperty(e,"issues",pp),pp.value=void 0,Object.defineProperty(e,"message",fp);let n=Object.getPrototypeOf(e);mp.has(n)||(mp.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},gp=H(`$ZodError`,hp);H(`$ZodError`,hp,void 0,{Parent:Error});function _p(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function vp(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?_p(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function yp(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new op;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>Lf(e,o,lp())));throw uf(n,a?.callee??t),n}return s.value};return t},Sp=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>Lf(e,o,lp())));throw uf(n,a?.callee??t),n}return s.value};return t},Cp=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new op;return a.issues.length?wp(e,a.issues,i):{success:!0,data:a.value}};function wp(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>Lf(e,n,lp()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var Tp=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?wp(e,a.issues,i):{success:!0,data:a.value}},Ep=Symbol.for(`zod.compile.invalid`),Dp=Symbol.for(`zod.compile.fallback`),Op=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==Ep)return!0;if(r.definite===!0&&n===void 0)return!1}return kp(e,t,n)});function kp(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[Dp]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new op;return a.issues.length===0}var Ap=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},jp=e=>{let t=xp(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,bp(n,a))};return n},Mp=e=>{let t=xp(e),n=(e,r,i,a)=>t(e,r,i,bp(n,a));return n},Np=e=>{let t=Sp(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,bp(n,a))};return n},Pp=e=>{let t=Sp(e),n=async(e,r,i,a)=>await t(e,r,i,bp(n,a));return n},Fp=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Cp(e)(t,n,i)},Ip=e=>(t,n,r)=>Cp(e)(t,n,r),Lp=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Tp(e)(t,n,i)},Rp=e=>async(t,n,r)=>Tp(e)(t,n,r),zp=/^[cC][0-9a-z]{6,}$/,Bp=/^[0-9a-z]+$/,Vp=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Hp=/^[0-9a-vA-V]{20}$/,Up=/^[A-Za-z0-9]{27}$/,Wp=/^[a-zA-Z0-9_-]{21}$/;function Gp(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Kp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,qp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Jp=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Yp=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Xp=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;function Zp(){return new RegExp(Xp,`u`)}var Qp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,$p=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,em=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,tm=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,nm=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,rm=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,im=/^https?$/,am=/^\+[1-9]\d{6,14}$/,om=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function sm(e){return RegExp(`^${e}$`)}var cm=sm(om);function lm(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function um(e){return RegExp(`^${lm(e)}$`)}function dm(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${lm({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${lm({precision:e.precision})}`:n;return RegExp(`^${om}T(?:${r})$`)}var fm=/^[\s\S]{0,}$/,pm=/^-?\d+$/,mm=/^-?\d+(?:\.\d+)?$/,hm=/^(?:true|false)$/i,gm=/^null$/i,_m=/^undefined$/i,vm=/^[^A-Z]*$/,ym=/^[^a-z]*$/,bm=H(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),xm=e=>{let t=e.value;return!Jd(t)&&t.length!==void 0},Sm={number:`number`,bigint:`bigint`,object:`date`},Cm=H(`$ZodCheckLessThan`,(e,t)=>{bm.init(e,t);let n=Sm[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value{bm.init(e,t);let n=Sm[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Sm[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Tm=H(`$ZodCheckMultipleOf`,(e,t)=>{bm.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Xd(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Em=H(`$ZodCheckNumberFormat`,(e,t)=>{bm.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=bf[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),Dm=H(`$ZodCheckMaxLength`,(e,t)=>{var n;bm.init(e,t),(n=e._zod.def).when??(n.when=xm),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?zf(r):i)<=t.maximum)return;let a=Bf(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Om=H(`$ZodCheckMinLength`,(e,t)=>{var n;bm.init(e,t),(n=e._zod.def).when??(n.when=xm),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i=t.minimum)return;let a=Bf(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),km=H(`$ZodCheckLengthEquals`,(e,t)=>{var n;bm.init(e,t),(n=e._zod.def).when??(n.when=xm),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?zf(r):i;if(a===t.length)return;let o=Bf(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Am=H(`$ZodCheckStringFormat`,(e,t)=>{var n,r;bm.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),jm=H(`$ZodCheckRegex`,(e,t)=>{Am.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Mm=H(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=vm,Am.init(e,t)}),Nm=H(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=ym,Am.init(e,t)}),Pm=H(`$ZodCheckIncludes`,(e,t)=>{bm.init(e,t);let n=gf(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),Fm=H(`$ZodCheckStartsWith`,(e,t)=>{bm.init(e,t);let n=RegExp(`^${gf(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Im=H(`$ZodCheckEndsWith`,(e,t)=>{bm.init(e,t);let n=RegExp(`.*${gf(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),Lm=H(`$ZodCheckOverwrite`,(e,t)=>{bm.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Rm=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` -`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(` -`)}\n};`)(...Object.values(this.closed))}},zm={major:4,minor:6,patch:6},Bm=H(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=zm;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=jf(t),a;for(let o of n){if(o._zod.def.when){if(Mf(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new op;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(If(t.issues,n,e),i||=jf(t,n))});else{if(t.issues.length===n)continue;If(t.issues,n,e),i||=jf(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(jf(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new op;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new op;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return Gf(this,`~standard`,Um(this))},set"~standard"(e){Wf(this,`~standard`,e)}}),Vm=(e,t)=>e.issues.length?{issues:e.issues.map(e=>Lf(e,t,lp()))}:{value:e.value};async function Hm(e,t){let n={async:!0};return Vm(await e._zod.run({value:t,issues:[]},n),n)}function Um(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Vm(r,n)}catch{}return Hm(e,t)},vendor:`zod`,version:1}}var Wm=H(`$ZodString`,(e,t)=>{Bm.init(e,t),e._zod.pattern=t.pattern??fm,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),Gm=H(`$ZodStringFormat`,(e,t)=>{Am.init(e,t),Wm.init(e,t)}),Km=H(`$ZodGUID`,(e,t)=>{t.pattern??=qp,Gm.init(e,t)}),qm=H(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Jp(e)}else t.pattern??=Jp();Gm.init(e,t)}),Jm=H(`$ZodEmail`,(e,t)=>{t.pattern??=Yp,Gm.init(e,t)});function Ym(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function Xm(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?Ym(e)||2:Zm(e,t)}function Zm(e,t){if(!t.normalize&&t.protocol?.source===im.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}var Qm=/[\t\n\r]/g;function $m(e){return e.replace(Qm,``)}function eh(e,t){return t.lastIndex=0,t.test(e.hostname)}function th(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}var nh=H(`$ZodURL`,(e,t)=>{Gm.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=Xm(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=$m(r);return}t.hostname&&!eh(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!th(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:$m(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),rh=H(`$ZodEmoji`,(e,t)=>{t.pattern??=Zp(),Gm.init(e,t)}),ih=H(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?Wp:Gp(t.length),Gm.init(e,t)}),ah=H(`$ZodCUID`,(e,t)=>{t.pattern??=zp,Gm.init(e,t)}),oh=H(`$ZodCUID2`,(e,t)=>{t.pattern??=Bp,Gm.init(e,t)}),sh=H(`$ZodULID`,(e,t)=>{t.pattern??=Vp,Gm.init(e,t)}),ch=H(`$ZodXID`,(e,t)=>{t.pattern??=Hp,Gm.init(e,t)}),lh=H(`$ZodKSUID`,(e,t)=>{t.pattern??=Up,Gm.init(e,t)}),uh=H(`$ZodISODateTime`,(e,t)=>{t.pattern??=dm(t),Gm.init(e,t)}),dh=H(`$ZodISODate`,(e,t)=>{t.pattern??=cm,Gm.init(e,t)}),fh=H(`$ZodISOTime`,(e,t)=>{t.pattern??=um(t),Gm.init(e,t)}),ph=H(`$ZodISODuration`,(e,t)=>{t.pattern??=Kp,Gm.init(e,t)}),mh=H(`$ZodIPv4`,(e,t)=>{t.pattern??=Qp,Gm.init(e,t)}),hh=/^[0-9a-fA-F:.]+$/;function gh(e){return hh.test(e)?Ym(`http://[${e}]`):!1}var _h=H(`$ZodIPv6`,(e,t)=>{t.pattern??=$p,Gm.init(e,t),e._zod.check=n=>{gh(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),vh=H(`$ZodCIDRv4`,(e,t)=>{t.pattern??=em,Gm.init(e,t)});function yh(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:gh(n)}var bh=H(`$ZodCIDRv6`,(e,t)=>{t.pattern??=tm,Gm.init(e,t),e._zod.check=n=>{yh(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function xh(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Sh=/^[0-9a-zA-Z+/]*={0,2}$/,Ch=H(`$ZodBase64`,(e,t)=>{t.pattern??=Sh,Gm.init(e,t),e._zod.check=n=>{xh(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),wh=/^[A-Za-z0-9_-]*$/;function Th(e){if(!wh.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return xh(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var Eh=H(`$ZodBase64URL`,(e,t)=>{t.pattern??=wh,Gm.init(e,t),e._zod.check=n=>{Th(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Dh=H(`$ZodE164`,(e,t)=>{t.pattern??=am,Gm.init(e,t)});function Oh(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var kh=H(`$ZodJWT`,(e,t)=>{Gm.init(e,t),e._zod.check=n=>{Oh(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Ah=H(`$ZodNumber`,(e,t)=>{Bm.init(e,t),e._zod.pattern=mm,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),jh=H(`$ZodNumberFormat`,(e,t)=>{Em.init(e,t),Ah.init(e,t)}),Mh=H(`$ZodBoolean`,(e,t)=>{Bm.init(e,t),e._zod.pattern=hm,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Nh=H(`$ZodUndefined`,(e,t)=>{Bm.init(e,t),e._zod.pattern=_m,e._zod.values=new Set([void 0]),e._zod.parse=(t,n)=>{let r=t.value;return r===void 0||t.issues.push({expected:`undefined`,code:`invalid_type`,input:r,inst:e}),t}}),Ph=H(`$ZodNull`,(e,t)=>{Bm.init(e,t),e._zod.pattern=gm,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),Fh=H(`$ZodAny`,(e,t)=>{Bm.init(e,t),e._zod.parse=e=>e}),Ih=H(`$ZodUnknown`,(e,t)=>{Bm.init(e,t),e._zod.parse=e=>e}),Lh=H(`$ZodNever`,(e,t)=>{Bm.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Rh(e,t){let n=Ff(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of Ff(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,If(n.issues,t,e),n}}return i(n,a)}}var zh=e=>Array.isArray(e)?e.length:-1;function Bh(e,t,n){e.issues.length&&t.issues.push(...Nf(n,e.issues)),t.value[n]=e.value}var Vh=H(`$ZodArray`,(e,t)=>{Bm.init(e,t);let n=cp.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;eBh(t,r,e)));else if(Bh(c,r,e),s&&c.issues.length!==0&&jf(c))break}return o.length?Promise.all(o).then(()=>r):r},Rh(e,zh)});function Hh(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...Nf(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}var Uh=[];function Wh(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Uh,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=yf(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function Gh(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(jf(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Hh(e,n,i,t,d,f))):Hh(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var Kh=H(`$ZodObject`,(e,t)=>{Bm.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=qd(()=>Wh(t));Qf(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||$d(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=df,o=t.catchall,s,c=cp.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(jf(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>Hh(n,t,e,r,a,o))):Hh(s,t,e,r,a,o)}return o?Gh(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),qh=H(`$ZodObjectJIT`,(e,t)=>{Kh.init(e,t);let n=e._zod.parse,r=qd(()=>Wh(t)),i=cp.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new Rm([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>` - let ${e}_ab = false; - for (let i = 0; i < ${e}.issues.length; i++) { - const iss = ${e}.issues[i]; - iss.path = iss.path ? [${t}, ...iss.path] : [${t}]; - payload.issues.push(iss); - if (iss.continue !== true) ${e}_ab = true; - } - if (${e}_ab && ctx && ctx.abortEarly) { - payload.value = newResult; - return payload; - }`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:cf(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(` - const ${n}_present = ${i}; - if (!${n}.issues.length || ${n}_present) { - if (${n}.issues.length) {${c(n,r)} - } - - if (${e}) { - newResult[${r}] = ${n}.value; - } - } - - `)}else f?(o.write(` - if (${n}.issues.length) {${c(n,r)} - } - `),d===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(` - if (${n}.value !== undefined || ${i}) { - newResult[${r}] = ${n}.value; - } - `)):o.write(` - const ${n}_present = ${i}; - if (${n}.issues.length) {${c(n,r)} - } - if (!${n}_present && !${n}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${r}] - }); - if (ctx && ctx.abortEarly) { - payload.value = newResult; - return payload; - } - } - - if (${n}_present) { - newResult[${r}] = ${n}.value; - } - - `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=df,c=!cp.jitless,l=c&&ff.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?Gh([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Jh(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!jf(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>Lf(e,r,lp())))}),t)}var Yh=H(`$ZodUnion`,(e,t)=>{Bm.init(e,t),Qf(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),Qf(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),Qf(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),Qf(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Yd(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Jh(t,r,e,i)):Jh(o,r,e,i)}});function Xh(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}var Zh=H(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Yh.init(e,t);let n=e._zod.parse;Qf(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||$d(t,e,new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=ef(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=qd(()=>Xh(t));e._zod.parse=(i,a)=>{let o=i.value;if(!df(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),Qh=H(`$ZodIntersection`,(e,t)=>{Bm.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>eg(e,t,n)):eg(e,i,a)}});function $h(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(pf(e)&&pf(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=$h(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=$h(t.value,n.value);if(!c.valid){if(jf(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var tg=H(`$ZodRecord`,(e,t)=>{Bm.init(e,t);let n=cp.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!pf(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>Lf(e,i,lp())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...Nf(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...Nf(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&mm.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>Lf(e,i,lp())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...Nf(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...Nf(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),ng=H(`$ZodEnum`,(e,t)=>{Bm.init(e,t);let n=Ud(t.entries),r=new Set(n);e._zod.values=r,Qf(e,`pattern`,e=>{let t=Ud(e.def.entries).filter(e=>hf.has(typeof e));return RegExp(t.length?`^(${t.map(e=>gf(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),rg=H(`$ZodLiteral`,(e,t)=>{Bm.init(e,t);let n=new Set(t.values);e._zod.values=n,Qf(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?gf(e):e?gf(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),ig=H(`$ZodTransform`,(e,t)=>{Bm.init(e,t),e._zod.optin=`optional`,cp.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new sp(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new op;return n.value=i,n}});function ag(e,t){return e.value=t.issues.length?void 0:t.value,e}var og=H(`$ZodOptional`,(e,t)=>{Bm.init(e,t),Qf(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,Qf(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),Qf(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Yd(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>ag(e,t)):ag(e,r)}return t.innerType._zod.run(e,n)}}),sg=H(`$ZodExactOptional`,(e,t)=>{og.init(e,t),Qf(e,`values`,e=>e.def.innerType._zod.values),Qf(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),cg=H(`$ZodNullable`,(e,t)=>{Bm.init(e,t),Qf(e,`optin`,e=>e.def.innerType._zod.optin),Qf(e,`optout`,e=>e.def.innerType._zod.optout),Qf(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Yd(t.source)}|null)$`):void 0}),Qf(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),lg=H(`$ZodDefault`,(e,t)=>{Bm.init(e,t),e._zod.optin=`defaulted`,Qf(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>ug(e,t)):ug(r,t)}});function ug(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var dg=H(`$ZodPrefault`,(e,t)=>{Bm.init(e,t),e._zod.optin=`defaulted`,Qf(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),fg=H(`$ZodNonOptional`,(e,t)=>{Bm.init(e,t),Qf(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>pg(t,e)):pg(i,e)}});function pg(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function mg(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>Lf(e,r,lp()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var hg=H(`$ZodCatch`,(e,t)=>{Bm.init(e,t),Qf(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),Qf(e,`optout`,e=>e.def.innerType._zod.optout),Qf(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>mg(e,r,t,n)):mg(e,r,t,n)}}),gg=H(`$ZodPipe`,(e,t)=>{Bm.init(e,t),Qf(e,`values`,e=>e.def.in._zod.values),Qf(e,`optin`,e=>e.def.in._zod.optin),Qf(e,`optout`,e=>e.def.out._zod.optout),Qf(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>_g(e,t.in,n)):_g(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>_g(e,t.out,n)):_g(r,t.out,n)}});function _g(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var vg=H(`$ZodPreprocess`,(e,t)=>{gg.init(e,t)}),yg=H(`$ZodReadonly`,(e,t)=>{Bm.init(e,t),Qf(e,`propValues`,e=>e.def.innerType._zod.propValues),Qf(e,`values`,e=>e.def.innerType._zod.values),Qf(e,`optin`,e=>e.def.innerType?._zod?.optin),Qf(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(bg):bg(r)}});function bg(e){return e.memo||(e.value=Object.freeze(e.value)),e}var xg=H(`$ZodLazy`,(e,t)=>{Bm.init(e,t),Qd(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),Qf(e,`pattern`,e=>e.innerType?._zod?.pattern),Qf(e,`propValues`,e=>e.innerType?._zod?.propValues),Qf(e,`optin`,e=>e.innerType?._zod?.optin??void 0),Qf(e,`optout`,e=>e.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Sg=H(`$ZodCustom`,(e,t)=>{bm.init(e,t),Bm.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Cg(t,n,r,e));Cg(i,n,r,e)}});function Cg(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(Hf(e))}}var wg=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},Tg=`~memo`,Eg=[];function Dg(e){return typeof e==`object`&&!!e}function Og(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var kg=new WeakMap,Ag=0,jg=1,Mg=2;function Ng(e,t,n){let r=kg.get(e);if(r!==void 0)return r?Mg:Ag;if(t.has(e))return Mg;t.add(e);let i=Ag,a=e=>{if(i!==Mg&&e?._zod){let r=Ng(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=Ag;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?jg:o.value?._zod?Ng(o.value,t,n):Ag;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=ef(c);s(e?o(e,!0):jg),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Ng(r,t,!1):jg);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),Pg(e,i)}function Pg(e,t){return t!==jg&&kg.set(e,t===Mg),t}function Fg(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var Ig,Lg=[],Rg={alloc(e,t,n){let r=Ig;if(!r)return n;Ig=void 0;let i={value:n,issues:null};return r.set(t.value,i),Lg.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Bg(n,e.value))throw new wg;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Ng(e,new Set,!1);if(i===Ag)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===Mg||r?n=!0:r=!0}let l=s.value;if(!Dg(l))return t(s,c);let u=c[Tg];u||(u={buckets:new WeakMap,backEdges:void 0},c[Tg]=u);let d;i===c?d=a:(d=Fg(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Og(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;Ig=d;let p=Lg.length,m=t(s,c);Ig=void 0;let h=Lg.length>p?Lg.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?Og(e.issues):Eg),e)):(h&&(h.issues=m.issues.length?Og(m.issues):Eg),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function zg(){return Rg}function Bg(e,t){let n=e[Tg]?.backEdges;return n!==void 0&&Dg(t)&&n.has(t)}var Vg=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(Vf(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${vf(e.values[0])}`:`Invalid option: expected one of ${Wd(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${Wd(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Hg(){return{localeError:Vg()}}var Ug,Wg=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function Gg(){return new Wg}(Ug=globalThis).__zod_globalRegistry??(Ug.__zod_globalRegistry=Gg());var Kg=globalThis.__zod_globalRegistry;function qg(e){return e.checks&&=[...e.checks],e}function Jg(e,t){return new e(qg({type:`string`,...B(t)}))}function Yg(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...B(t)})}function Xg(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...B(t)})}function Zg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...B(t)})}function Qg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...B(t)})}function $g(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...B(t)})}function e_(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...B(t)})}function t_(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...B(t)})}function n_(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...B(t)})}function r_(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...B(t)})}function i_(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...B(t)})}function a_(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...B(t)})}function o_(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...B(t)})}function s_(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...B(t)})}function c_(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...B(t)})}function l_(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...B(t)})}function u_(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...B(t)})}function d_(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...B(t)})}function f_(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...B(t)})}function p_(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...B(t)})}function m_(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...B(t)})}function h_(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...B(t)})}function g_(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...B(t)})}function __(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...B(t)})}function v_(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...B(t)})}function y_(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...B(t)})}function b_(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...B(t)})}function x_(e,t){return new e(qg({type:`number`,checks:[],...B(t)}))}function S_(e,t){return new e(qg({type:`number`,coerce:!0,checks:[],...B(t)}))}function C_(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...B(t)})}function w_(e,t){return new e({type:`boolean`,...B(t)})}function T_(e,t){return new e({type:`undefined`,...B(t)})}function E_(e,t){return new e({type:`null`,...B(t)})}function D_(e){return new e({type:`any`})}function O_(e){return new e({type:`unknown`})}function k_(e,t){return new e({type:`never`,...B(t)})}function A_(e,t){return new Cm({check:`less_than`,...B(t),value:e,inclusive:!1})}function j_(e,t){return new Cm({check:`less_than`,...B(t),value:e,inclusive:!0})}function M_(e,t){return new wm({check:`greater_than`,...B(t),value:e,inclusive:!1})}function N_(e,t){return new wm({check:`greater_than`,...B(t),value:e,inclusive:!0})}function P_(e,t){return new Tm({check:`multiple_of`,...B(t),value:e})}function F_(e,t){return new Dm({check:`max_length`,...B(t),maximum:e})}function I_(e,t){return new Om({check:`min_length`,...B(t),minimum:e})}function L_(e,t){return new km({check:`length_equals`,...B(t),length:e})}function R_(e,t){return new jm({check:`string_format`,format:`regex`,...B(t),pattern:e})}function z_(e){return new Mm({check:`string_format`,format:`lowercase`,...B(e)})}function B_(e){return new Nm({check:`string_format`,format:`uppercase`,...B(e)})}function V_(e,t){return new Pm({check:`string_format`,format:`includes`,...B(t),includes:e})}function H_(e,t){return new Fm({check:`string_format`,format:`starts_with`,...B(t),prefix:e})}function U_(e,t){return new Im({check:`string_format`,format:`ends_with`,...B(t),suffix:e})}function W_(e){return new Lm({check:`overwrite`,tx:e})}function G_(e){return W_(t=>t.normalize(e))}function K_(){return W_(e=>e.trim())}function q_(){return W_(e=>e.toLowerCase())}function J_(){return W_(e=>e.toUpperCase())}function Y_(){return W_(e=>lf(e))}function X_(e,t,n){return new e({type:`array`,element:t,...B(n)})}function Z_(e,t,n){let r=B(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function Q_(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...B(n)})}function $_(e,t){let n=ev(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(Hf(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(Hf(r))}},e(t.value,t)),t);return n}function ev(e,t){let n=new bm({check:`custom`,...B(t)});return n._zod.check=e,n}function tv(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&$d(e,t,n[t]);return e}function nv(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Kg,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function rv(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function iv(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,iv(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&tv(o.schema,c),t.io===`input`&&mv(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function av(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ov(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${av(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+av(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ - -Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function sv(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;sv(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var cv=new Set([`type`,`properties`,`required`,`additionalProperties`]),lv=[`oneOf`,`anyOf`];function uv(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function dv(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!cv.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??uv(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}$d(n,r,e.length===1?e[0]:dv(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=uv(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function fv(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of cv)if(t in e)return;let n=t.filter(e=>lv.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=dv(t);else{let e=n[0],i=lv.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>dv([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,tv(e,r))}function pv(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):tv(i,s),tv(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())sv(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])fv(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}tv(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,$d(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:gv(t,`input`,e.processors),output:gv(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function mv(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return mv(r.element,n);if(r.type===`set`)return mv(r.valueType,n);if(r.type===`lazy`)return mv(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return mv(r.innerType,n);if(r.type===`intersection`)return mv(r.left,n)||mv(r.right,n);if(r.type===`record`||r.type===`map`)return mv(r.keyType,n)||mv(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:mv(r.in,n)||mv(r.out,n);if(r.type===`object`){for(let e in r.shape)if(mv(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(mv(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(mv(e,n))return!0;return!!(r.rest&&mv(r.rest,n))}return!1}var hv=(e,t={})=>n=>{let r=nv({...n,processors:t});return iv(e,r),ov(r,e),pv(r,e)},gv=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=nv({...i??{},target:a,io:t,processors:n});return iv(e,o),ov(o,e),pv(o,e)},_v=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},vv=(e,t,n)=>{(e[t]===void 0||n{_v(e,`minimum`,t),vv(e,`maximum`,t)},bv=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},xv=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},Sv=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Cv=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},wv=(e,t)=>_v(e,`minimum`,t.minimum),Tv=(e,t)=>vv(e,`maximum`,t.maximum),Ev=e=>(t,n)=>{Cv(t,n.format);let[r,i]=e[n.format];_v(t,`minimum`,r),vv(t,`maximum`,i)},Dv={greater_than:(e,t)=>_v(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>vv(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>bv(e,t.value),number_format:Ev(bf),bigint_format:Ev(xf),min_length:wv,max_length:Tv,length_equals:(e,t)=>yv(e,t.length),min_size:wv,max_size:Tv,size_equals:(e,t)=>yv(e,t.size),string_format:(e,t)=>{Cv(e,t.format),t.pattern&&xv(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Sv(e,t.mime)};function Ov(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Dv[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&_v(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&_v(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&vv(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&vv(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&bv(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Sv(t,i.mime);for(let e of i.patterns??[])xv(t,e);return t}var kv={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Av=new Map([[Sh,nm],[wh,rm]]),jv=e=>Av.get(e)??e,Mv=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Ov(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=kv[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(jv);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Nv=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Ov(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):rv(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Pv=(e,t,n,r)=>{n.type=`boolean`},Fv=(e,t,n,r)=>{rv(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},Iv=(e,t,n,r)=>{rv(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},Lv=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Rv=(e,t,n,r)=>{rv(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},zv=(e,t,n,r)=>{rv(e,t,n,r,`Void cannot be represented in JSON Schema`)},Bv=(e,t,n,r)=>{n.not={}},Vv=(e,t,n,r)=>{},Hv=(e,t,n,r)=>{},Uv=(e,t,n,r)=>{rv(e,t,n,r,`Date cannot be represented in JSON Schema`)},Wv=(e,t,n,r)=>{let i=e._zod.def,a=Ud(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Gv=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(rv(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(rv(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Kv=(e,t,n,r)=>{rv(e,t,n,r,`NaN cannot be represented in JSON Schema`)},qv=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Jv=(e,t,n,r)=>{let i=n;i.type=`string`,i.format=`binary`,i.contentEncoding=`binary`;let{minimum:a,maximum:o,mime:s}=Ov(e);a!==void 0&&(i.minLength=a),o!==void 0&&(i.maxLength=o),s&&(s.length===0?i.not={}:s.length===1?i.contentMediaType=s[0]:i.anyOf=s.map(e=>({contentMediaType:e})))},Yv=(e,t,n,r)=>{n.type=`boolean`},Xv=(e,t,n,r)=>{rv(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Zv=(e,t,n,r)=>{rv(e,t,n,r,`Function types cannot be represented in JSON Schema`)},Qv=(e,t,n,r)=>{rv(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},$v=(e,t,n,r)=>{rv(e,t,n,r,`Map cannot be represented in JSON Schema`)},ey=(e,t,n,r)=>{rv(e,t,n,r,`Set cannot be represented in JSON Schema`)},ty=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Ov(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=iv(a.element,t,{...r,path:[...r.path,`items`]})};function ny(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?ny(t.out):t.type===`catch`?ny(t.innerType):e._zod.optin}var ry=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&rv(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)$d(i.properties,e,iv(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?ny(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=iv(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},iy=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>iv(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},ay=(e,t,n,r)=>{let i=e._zod.def,a=iv(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=iv(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},oy=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>iv(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?iv(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?ny(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=Ov(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function sy(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=sy(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>sy(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?mm:pm).source),p):p}var cy=new WeakMap;function ly(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of cy.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=sy(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var uy=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Ov(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=iv(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)$d(i.patternProperties,jv(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=iv(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=cy.get(t);n||(n=[],cy.set(t,n),t.deferred.push(()=>ly(t))),n.push(e)}i.additionalProperties=iv(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&ny(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},dy=(e,t,n,r)=>{let i=e._zod.def,a=iv(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},fy=(e,t,n,r)=>{let i=e._zod.def;iv(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},py=Symbol();function my(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(rv(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),py):JSON.parse(o)}var hy=(e,t,n,r)=>{let i=e._zod.def;iv(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=my(i.defaultValue,e,t,n,r);o!==py&&(n.default=o)},gy=(e,t,n,r)=>{let i=e._zod.def;iv(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=my(i.defaultValue,e,t,n,r);o!==py&&(n._prefault=o)},_y=(e,t,n,r)=>{let i=e._zod.def;iv(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{rv(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},vy=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;iv(o,t,r);let s=t.seen.get(e);s.ref=o},yy=(e,t,n,r)=>{let i=e._zod.def;iv(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},by=(e,t,n,r)=>{let i=e._zod.def;iv(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},xy=(e,t,n,r)=>{let i=e._zod.def;iv(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Sy=(e,t,n,r)=>{let i=e._zod.innerType;iv(i,t,r);let a=t.seen.get(e);a.ref=i},Cy={string:Mv,number:Nv,boolean:Pv,bigint:Fv,symbol:Iv,null:Lv,undefined:Rv,void:zv,never:Bv,any:Vv,unknown:Hv,date:Uv,enum:Wv,literal:Gv,nan:Kv,template_literal:qv,file:Jv,success:Yv,custom:Xv,function:Zv,transform:Qv,map:$v,set:ey,array:ty,object:ry,union:iy,intersection:ay,tuple:oy,record:uy,nullable:dy,nonoptional:fy,default:hy,prefault:gy,catch:_y,pipe:vy,readonly:yy,promise:by,optional:xy,lazy:Sy};function wy(e,t){if(`_idmap`in e){let n=e,r=nv({...t,processors:Cy}),i={};for(let e of n._idmap.entries()){let[t,n]=e;iv(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;ov(r,n),$d(a,t,pv(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=nv({...t,processors:Cy});return iv(e,n),ov(n,e),pv(n,e)}var Ty=new WeakSet([Object.prototype,Error.prototype]);function Ey(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var Dy=H(`ZodError`,(e,t)=>{gp.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);Ty.has(n)||(Ty.add(n),Ey(n,`format`,e=>t=>yp(e,t)),Ey(n,`flatten`,e=>t=>vp(e,t)),Ey(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Gd,2)}),Ey(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Gd,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Oy=xp(Dy),ky=Sp(Dy),Ay=Cp(Dy),jy=Tp(Dy),My=jp(Dy),Ny=Mp(Dy),Py=Np(Dy),Fy=Pp(Dy),Iy=Fp(Dy),Ly=Ip(Dy),Ry=Lp(Dy),zy=Rp(Dy);function By(){cp.localeError||lp(Hg())}function Vy(){cp.memoizer||lp({memoizer:zg()})}var Hy=H(`ZodType`,(e,t)=>(By(),Bm.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(sf(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return _f(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(_x(e,t))},superRefine(e,t){return this.check(vx(e,t))},overwrite(e){return this.check(W_(e))},optional(){return Yb(this)},exactOptional(){return Zb(this)},nullable(){return $b(this)},nullish(){return Yb($b(this))},nonoptional(e){return ax(this,e)},array(){return Mb(this)},or(e){return Ib([this,e])},and(e){return Bb(this,e)},transform(e){return lx(this,qb(e))},default(e){return tx(this,e)},prefault(e){return rx(this,e)},catch(e){return sx(this,e)},pipe(e){return lx(this,e)},readonly(){return fx(this)},describe(e){let t=this.clone();return Kg.add(t,{description:e}),t},meta(...e){if(e.length===0)return Kg.get(this);let t=this.clone();return Kg.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Gf(this,`~standard`,{...Um(this),jsonSchema:{input:gv(this,`input`),output:gv(this,`output`)}})},set"~standard"(e){Wf(this,`~standard`,e)},parse:function e(t,n){return Oy(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await ky(this,t,n,{callee:e})},safeParse(e,t){return Ay(this,e,t)},async safeParseAsync(e,t){return jy(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Wf(this,`spa`,e)},validate(e,t){return Op(this,e,t)},validateAsync(e,t){return Ap(this,e,t)},encode:function e(t,n){return My(this,t,n,{callee:e})},decode:function e(t,n){return Ny(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Py(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Fy(this,t,n,{callee:e})},safeEncode(e,t){return Iy(this,e,t)},safeDecode(e,t){return Ly(this,e,t)},async safeEncodeAsync(e,t){return Ry(this,e,t)},async safeDecodeAsync(e,t){return zy(this,e,t)},toJSONSchema(e){return hv(this,{})(e)},get description(){return Kg.get(this)?.description},get _def(){return this._zod.def}}),Uy=H(`_ZodString`,(e,t)=>{Wm.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mv(e,t,n,r)},Kf({format:e=>Ov(e).format??null,minLength:e=>Ov(e).minimum??null,maxLength:e=>Ov(e).maximum??null},{regex(...e){return this.check(R_(...e))},includes(...e){return this.check(V_(...e))},startsWith(...e){return this.check(H_(...e))},endsWith(...e){return this.check(U_(...e))},min(...e){return this.check(I_(...e))},max(...e){return this.check(F_(...e))},length(...e){return this.check(L_(...e))},nonempty(...e){return this.check(I_(1,...e))},lowercase(e){return this.check(z_(e))},uppercase(e){return this.check(B_(e))},trim(){return this.check(K_())},normalize(...e){return this.check(G_(...e))},toLowerCase(){return this.check(q_())},toUpperCase(){return this.check(J_())},slugify(){return this.check(Y_())}})),Wy=H(`ZodString`,(e,t)=>{Wm.init(e,t),Uy.init(e,t)},{email(e){return this.check(Yg(Xy,e))},url(e){return this.check(t_(eb,e))},jwt(e){return this.check(g_(gb,e))},emoji(e){return this.check(n_(nb,e))},guid(e){return this.check(Xg(Qy,e))},uuid(e){return this.check(Zg($y,e))},uuidv4(e){return this.check(Qg($y,e))},uuidv6(e){return this.check($g($y,e))},uuidv7(e){return this.check(e_($y,e))},nanoid(e){return this.check(r_(rb,e))},cuid(e){return this.check(i_(ib,e))},cuid2(e){return this.check(a_(ab,e))},ulid(e){return this.check(o_(ob,e))},base64(e){return this.check(p_(pb,e))},base64url(e){return this.check(m_(mb,e))},xid(e){return this.check(s_(sb,e))},ksuid(e){return this.check(c_(cb,e))},ipv4(e){return this.check(l_(lb,e))},ipv6(e){return this.check(u_(ub,e))},cidrv4(e){return this.check(d_(db,e))},cidrv6(e){return this.check(f_(fb,e))},e164(e){return this.check(h_(hb,e))},datetime(e){return this.check(__(Ky,e))},date(e){return this.check(v_(qy,e))},time(e){return this.check(y_(Jy,e))},duration(e){return this.check(b_(Yy,e))}});function U(e){return Jg(Wy,e)}var Gy=H(`ZodStringFormat`,(e,t)=>{Gm.init(e,t),Uy.init(e,t)}),Ky=H(`ZodISODateTime`,(e,t)=>{uh.init(e,t),Gy.init(e,t)}),qy=H(`ZodISODate`,(e,t)=>{dh.init(e,t),Gy.init(e,t)}),Jy=H(`ZodISOTime`,(e,t)=>{fh.init(e,t),Gy.init(e,t)}),Yy=H(`ZodISODuration`,(e,t)=>{ph.init(e,t),Gy.init(e,t)}),Xy=H(`ZodEmail`,(e,t)=>{Jm.init(e,t),Gy.init(e,t)});function Zy(e){return Yg(Xy,e)}var Qy=H(`ZodGUID`,(e,t)=>{Km.init(e,t),Gy.init(e,t)}),$y=H(`ZodUUID`,(e,t)=>{qm.init(e,t),Gy.init(e,t)}),eb=H(`ZodURL`,(e,t)=>{nh.init(e,t),Gy.init(e,t)});function tb(e){return t_(eb,e)}var nb=H(`ZodEmoji`,(e,t)=>{rh.init(e,t),Gy.init(e,t)}),rb=H(`ZodNanoID`,(e,t)=>{ih.init(e,t),Gy.init(e,t)}),ib=H(`ZodCUID`,(e,t)=>{ah.init(e,t),Gy.init(e,t)}),ab=H(`ZodCUID2`,(e,t)=>{oh.init(e,t),Gy.init(e,t)}),ob=H(`ZodULID`,(e,t)=>{sh.init(e,t),Gy.init(e,t)}),sb=H(`ZodXID`,(e,t)=>{ch.init(e,t),Gy.init(e,t)}),cb=H(`ZodKSUID`,(e,t)=>{lh.init(e,t),Gy.init(e,t)}),lb=H(`ZodIPv4`,(e,t)=>{mh.init(e,t),Gy.init(e,t)}),ub=H(`ZodIPv6`,(e,t)=>{_h.init(e,t),Gy.init(e,t)}),db=H(`ZodCIDRv4`,(e,t)=>{vh.init(e,t),Gy.init(e,t)}),fb=H(`ZodCIDRv6`,(e,t)=>{bh.init(e,t),Gy.init(e,t)}),pb=H(`ZodBase64`,(e,t)=>{Ch.init(e,t),Gy.init(e,t)}),mb=H(`ZodBase64URL`,(e,t)=>{Eh.init(e,t),Gy.init(e,t)}),hb=H(`ZodE164`,(e,t)=>{Dh.init(e,t),Gy.init(e,t)}),gb=H(`ZodJWT`,(e,t)=>{kh.init(e,t),Gy.init(e,t)}),_b=H(`ZodNumber`,(e,t)=>{Ah.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nv(e,t,n,r),e.isFinite=!0},Kf({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Ov(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Ov(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Ov(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Ov(e).format??null},{gt(e,t){return this.check(M_(e,t))},gte(e,t){return this.check(N_(e,t))},min(e,t){return this.check(N_(e,t))},lt(e,t){return this.check(A_(e,t))},lte(e,t){return this.check(j_(e,t))},max(e,t){return this.check(j_(e,t))},int(e){return this.check(W(e))},safe(e){return this.check(W(e))},positive(e){return this.check(M_(0,e))},nonnegative(e){return this.check(N_(0,e))},negative(e){return this.check(A_(0,e))},nonpositive(e){return this.check(j_(0,e))},multipleOf(e,t){return this.check(P_(e,t))},step(e,t){return this.check(P_(e,t))},finite(){return this}}));function vb(e){return x_(_b,e)}var yb=H(`ZodNumberFormat`,(e,t)=>{jh.init(e,t),_b.init(e,t)});function W(e){return C_(yb,e)}var bb=H(`ZodBoolean`,(e,t)=>{Mh.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pv(e,t,n,r)});function xb(e){return w_(bb,e)}var Sb=H(`ZodUndefined`,(e,t)=>{Nh.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rv(e,t,n,r)});function Cb(e){return T_(Sb,e)}var wb=H(`ZodNull`,(e,t)=>{Ph.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lv(e,t,n,r)});function Tb(e){return E_(wb,e)}var Eb=H(`ZodAny`,(e,t)=>{Fh.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function G(){return D_(Eb)}var Db=H(`ZodUnknown`,(e,t)=>{Ih.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Ob(){return O_(Db)}var kb=H(`ZodNever`,(e,t)=>{Lh.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bv(e,t,n,r)});function Ab(e){return k_(kb,e)}var jb=H(`ZodArray`,(e,t)=>{Vy(),Vh.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ty(e,t,n,r),e.element=t.element},{min(e,t){return this.check(I_(e,t))},nonempty(e){return this.check(I_(1,e))},max(e,t){return this.check(F_(e,t))},length(e,t){return this.check(L_(e,t))},unwrap(){return this.element}});function Mb(e,t){return X_(jb,e,t)}var Nb=H(`ZodObject`,(e,t)=>{Vy(),qh.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ry(e,t,n,r),V(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return Wb(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(sf(this._zod.def,{catchall:e}))},passthrough(){return this.clone(sf(this._zod.def,{catchall:Ob()}))},loose(){return this.clone(sf(this._zod.def,{catchall:Ob()}))},strict(){return this.clone(sf(this._zod.def,{catchall:Ab()}))},strip(){return this.clone(sf(this._zod.def,{catchall:void 0}))},extend(e){return Tf(this,e)},safeExtend(e){return Df(this,e)},merge(e){return Of(this,e)},pick(e){return Sf(this,e)},omit(e){return wf(this,e)},partial(...e){return kf(Jb,this,e[0])},exactPartial(...e){return kf(Xb,this,e[0],`exactPartial`)},required(...e){return Af(ix,this,e[0])}});function Pb(e,t){return new Nb({type:`object`,shape:e??{},...B(t)})}function K(e,t){return new Nb({type:`object`,shape:e,catchall:Ob(),...B(t)})}var Fb=H(`ZodUnion`,(e,t)=>{Yh.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>iy(e,t,n,r),e.options=t.options});function Ib(e,t){return new Fb({type:`union`,options:e,...B(t)})}var Lb=H(`ZodDiscriminatedUnion`,(e,t)=>{Fb.init(e,t),Zh.init(e,t)});function Rb(e,t,n){return new Lb({type:`union`,options:t,discriminator:e,...B(n)})}var zb=H(`ZodIntersection`,(e,t)=>{Qh.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ay(e,t,n,r)});function Bb(e,t){return new zb({type:`intersection`,left:e,right:t})}var Vb=H(`ZodRecord`,(e,t)=>{Vy(),tg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uy(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Hb(e,t,n){return!t||!t._zod?new Vb({type:`record`,keyType:U(),valueType:e,...B(t)}):new Vb({type:`record`,keyType:e,valueType:t,...B(n)})}var Ub=H(`ZodEnum`,(e,t)=>{ng.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wv(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Ub({...t,checks:[],...B(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Ub({...t,checks:[],...B(r),entries:i})}});function Wb(e,t){return new Ub({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...B(t)})}var Gb=H(`ZodLiteral`,(e,t)=>{rg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Gv(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function q(e,t){return new Gb({type:`literal`,values:Array.isArray(e)?e:[e],...B(t)})}var Kb=H(`ZodTransform`,(e,t)=>{Vy(),ig.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qv(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new sp(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(Hf(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(Hf(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function qb(e){return new Kb({type:`transform`,transform:e})}var Jb=H(`ZodOptional`,(e,t)=>{og.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Yb(e){return new Jb({type:`optional`,innerType:e})}var Xb=H(`ZodExactOptional`,(e,t)=>{sg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Zb(e){return new Xb({type:`optional`,innerType:e})}var Qb=H(`ZodNullable`,(e,t)=>{cg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function $b(e){return new Qb({type:`nullable`,innerType:e})}var ex=H(`ZodDefault`,(e,t)=>{lg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function tx(e,t){return new ex({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():mf(t)}})}var nx=H(`ZodPrefault`,(e,t)=>{dg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function rx(e,t){return new nx({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():mf(t)}})}var ix=H(`ZodNonOptional`,(e,t)=>{fg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ax(e,t){return new ix({type:`nonoptional`,innerType:e,...B(t)})}var ox=H(`ZodCatch`,(e,t)=>{hg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_y(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function sx(e,t){return new ox({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:ep(t)})}var cx=H(`ZodPipe`,(e,t)=>{gg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vy(e,t,n,r),e.in=t.in,e.out=t.out});function lx(e,t){return new cx({type:`pipe`,in:e,out:t})}var ux=H(`ZodPreprocess`,(e,t)=>{cx.init(e,t),vg.init(e,t)}),dx=H(`ZodReadonly`,(e,t)=>{yg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function fx(e){return new dx({type:`readonly`,innerType:e})}var px=H(`ZodLazy`,(e,t)=>{xg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sy(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function mx(e){return new px({type:`lazy`,getter:e})}var hx=H(`ZodCustom`,(e,t)=>{Sg.init(e,t),Hy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Xv(e,t,n,r)});function gx(e,t){return Z_(hx,e??(()=>!0),t)}function _x(e,t={}){return Q_(hx,e,t)}function vx(e,t){return $_(e,t)}function yx(e,t){return new ux({type:`pipe`,in:qb(e),out:t})}var bx=Wb(I),J=gx(e=>typeof e==`object`&&!!e&&!Array.isArray(e)),xx=U(),Sx=Wb([`developer`,`system`,`assistant`,`user`]),Cx=K({type:q(I.TEXT_MESSAGE_START),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U(),role:Sx.optional(),name:U().optional()}),wx=K({type:q(I.TEXT_MESSAGE_CONTENT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U(),delta:U()}),Tx=K({type:q(I.TEXT_MESSAGE_END),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U()}),Ex=K({type:q(I.TEXT_MESSAGE_CHUNK),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U().optional(),role:Sx.optional(),delta:U().optional(),name:U().optional()}),Dx=K({type:q(I.TOOL_CALL_START),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),toolCallId:U(),toolCallName:U(),parentMessageId:U().optional()}),Ox=K({type:q(I.TOOL_CALL_ARGS),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),toolCallId:U(),delta:U()}),kx=K({type:q(I.TOOL_CALL_END),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),toolCallId:U()}),Ax=K({type:q(I.TOOL_CALL_CHUNK),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),toolCallId:U().optional(),toolCallName:U().optional(),parentMessageId:U().optional(),delta:U().optional()}),jx=K({type:q(`text`),id:U().optional(),text:U(),metadata:G().refine(e=>e!==null).optional()}),Mx=Rb(`type`,[K({type:q(`data`),value:U(),mimeType:U()}),K({type:q(`url`),value:U(),mimeType:U().optional()}),K({type:q(`file`),value:U(),provider:U().optional(),mimeType:U().optional()})]),Nx=Rb(`type`,[jx,K({type:q(`image`),id:U().optional(),source:Mx,metadata:G().refine(e=>e!==null).optional()}),K({type:q(`audio`),id:U().optional(),source:Mx,metadata:G().refine(e=>e!==null).optional()}),K({type:q(`video`),id:U().optional(),source:Mx,metadata:G().refine(e=>e!==null).optional()}),K({type:q(`document`),id:U().optional(),source:Mx,metadata:G().refine(e=>e!==null).optional()})]),Px=K({type:q(I.TOOL_CALL_RESULT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U(),toolCallId:U(),content:Ib([U(),Mb(Nx)]),role:q(`tool`).optional()}),Fx=G(),Ix=K({type:q(I.STATE_SNAPSHOT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),snapshot:Fx.refine(e=>e!==void 0)}),Lx=U().regex(RegExp(`^(/([^/~]|~[01])*)*$`)),Rx=Mb(Rb(`op`,[K({op:q(`add`),path:Lx,value:G().refine(e=>e!==void 0)}).meta({specOpen:!0}),K({op:q(`remove`),path:Lx}).meta({specOpen:!0}),K({op:q(`replace`),path:Lx,value:G().refine(e=>e!==void 0)}).meta({specOpen:!0}),K({op:q(`move`),from:Lx,path:Lx}).meta({specOpen:!0}),K({op:q(`copy`),from:Lx,path:Lx}).meta({specOpen:!0}),K({op:q(`test`),path:Lx,value:G().refine(e=>e!==void 0)}).meta({specOpen:!0})])),zx=K({type:q(I.STATE_DELTA),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),delta:Rx}),Bx=K({subagentRunId:xx.optional(),id:U(),role:q(`developer`),name:U().optional(),encryptedValue:U().optional(),metadata:J.optional(),content:U()}),Vx=K({subagentRunId:xx.optional(),id:U(),role:q(`system`),name:U().optional(),encryptedValue:U().optional(),metadata:J.optional(),content:U()}),Hx=K({name:U(),arguments:U()}),Ux=K({id:U(),type:q(`function`),function:Hx,encryptedValue:U().optional(),metadata:J.optional()}),Wx=Rb(`role`,[Bx,Vx,K({subagentRunId:xx.optional(),id:U(),role:q(`assistant`),name:U().optional(),encryptedValue:U().optional(),metadata:J.optional(),content:U().optional(),toolCalls:Mb(Ux).optional()}),K({subagentRunId:xx.optional(),id:U(),role:q(`user`),name:U().optional(),encryptedValue:U().optional(),metadata:J.optional(),content:Ib([U(),Mb(Nx)])}),K({subagentRunId:xx.optional(),id:U(),role:q(`tool`),content:Ib([U(),Mb(Nx)]),toolCallId:U(),error:U().optional(),encryptedValue:U().optional(),metadata:J.optional()}),K({subagentRunId:xx.optional(),id:U(),role:q(`activity`),activityType:U(),content:gx(e=>typeof e==`object`&&!!e&&!Array.isArray(e)),metadata:J.optional()}),K({subagentRunId:xx.optional(),id:U(),role:q(`reasoning`),content:U(),encryptedValue:U().optional(),metadata:J.optional()})]),Gx=K({type:q(I.MESSAGES_SNAPSHOT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),messages:Mb(Wx)}),Kx=K({type:q(I.ACTIVITY_SNAPSHOT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U(),activityType:U(),content:gx(e=>typeof e==`object`&&!!e&&!Array.isArray(e)),replace:xb().optional()}),qx=K({type:q(I.ACTIVITY_DELTA),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U(),activityType:U(),patch:Rx}),Jx=K({type:q(I.RAW),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),event:G().refine(e=>e!==void 0),source:U().optional()}),Yx=K({type:q(I.CUSTOM),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),name:U(),value:G().refine(e=>e!==void 0)}),Xx=K({name:U(),description:U(),parameters:G().refine(e=>e!==null).optional(),metadata:J.optional()}),Zx=K({description:U(),value:U()}),Qx=K({interruptId:U(),status:Wb([`resolved`,`cancelled`]),payload:G().refine(e=>e!==null).optional(),metadata:J.optional()}),$x=K({threadId:U(),runId:U(),protocolVersion:U().optional(),parentRunId:U().optional(),state:Fx.refine(e=>e!==null).nullable().transform(e=>e??void 0).optional(),messages:Mb(Wx),tools:Mb(Xx).default(()=>[]),context:Mb(Zx).default(()=>[]),forwardedProps:G().refine(e=>e!==null).optional(),resume:Mb(Qx).optional()}),eS=K({type:q(I.RUN_STARTED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),threadId:U(),runId:U(),protocolVersion:U().optional(),parentRunId:U().optional(),input:$x.optional()}),tS=K({type:q(`success`),pendingToolCallIds:Mb(U()).optional()}),nS=K({subagentRunId:xx.optional(),id:U(),reason:U(),message:U().optional(),toolCallId:U().optional(),responseSchema:gx(e=>typeof e==`object`&&!!e&&!Array.isArray(e)).optional(),expiresAt:U().optional(),metadata:J.optional()}),rS=Rb(`type`,[tS,K({type:q(`interrupt`),interrupts:Mb(nS).min(1)}),K({type:q(`cancelled`)})]),iS=K({provider:U().optional(),model:U().optional(),inputTokens:W().min(0).max(9007199254740991).optional(),outputTokens:W().min(0).max(9007199254740991).optional(),totalTokens:W().min(0).max(9007199254740991).optional(),reasoningTokens:W().min(0).max(9007199254740991).optional(),cachedInputTokens:W().min(0).max(9007199254740991).optional(),cacheWriteInputTokens:W().min(0).max(9007199254740991).optional()}),aS=K({type:q(I.RUN_FINISHED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),threadId:U(),runId:U(),result:G().refine(e=>e!==null).optional(),outcome:rS.optional(),usage:Mb(iS).optional()}),oS=K({type:q(I.RUN_ERROR),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),message:U(),code:U().optional(),usage:Mb(iS).optional()}),sS=K({type:q(I.STEP_STARTED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),stepName:U()}),cS=K({type:q(I.STEP_FINISHED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),stepName:U()}),lS=K({type:q(I.REASONING_START),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U()}),uS=K({type:q(I.REASONING_MESSAGE_START),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U(),role:q(`reasoning`)}),dS=K({type:q(I.REASONING_MESSAGE_CONTENT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U(),delta:U()}),fS=K({type:q(I.REASONING_MESSAGE_END),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U()}),pS=K({type:q(I.REASONING_MESSAGE_CHUNK),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U().optional(),delta:U().optional()}),mS=K({type:q(I.REASONING_END),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),messageId:U()}),hS=Wb([`tool-call`,`message`]),gS=K({type:q(I.REASONING_ENCRYPTED_VALUE),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx.optional(),subtype:hS,entityId:U(),encryptedValue:U()}),_S=K({type:q(I.SUBAGENT_STARTED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx,name:U(),description:U().optional(),parentSubagentRunId:xx.optional(),parentToolCallId:U().optional(),parentMessageId:U().optional()}),vS=Rb(`type`,[K({type:q(`success`)}),K({type:q(`suspended`),interruptIds:Mb(U()).optional()})]),yS=Rb(`type`,[Cx,wx,Tx,Ex,Dx,Ox,kx,Ax,Px,Ix,zx,Gx,Kx,qx,Jx,Yx,eS,aS,oS,sS,cS,lS,uS,dS,fS,pS,mS,gS,_S,K({type:q(I.SUBAGENT_FINISHED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx,result:G().refine(e=>e!==null).optional(),outcome:vS.optional()}),K({type:q(I.SUBAGENT_ERROR),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:xx,message:U(),code:U().optional()})]);Wb([`developer`,`system`,`assistant`,`user`,`tool`,`activity`,`reasoning`]);var bS=K({name:U(),description:U().optional()}),xS=K({name:U().optional(),type:U().optional(),description:U().optional(),version:U().optional(),provider:U().optional(),documentationUrl:U().optional(),metadata:J.optional()}),SS=K({streaming:xb().optional(),websocket:xb().optional(),httpBinary:xb().optional(),pushNotifications:xb().optional(),resumable:xb().optional()}),CS=K({supported:xb().optional(),items:Mb(Xx).optional(),parallelCalls:xb().optional(),clientProvided:xb().optional()}),wS=K({structuredOutput:xb().optional(),supportedMimeTypes:Mb(U()).optional()}),TS=K({snapshots:xb().optional(),deltas:xb().optional(),memory:xb().optional(),persistentState:xb().optional()}),ES=K({supported:xb().optional(),delegation:xb().optional(),handoffs:xb().optional(),subagents:Mb(bS).optional()}),DS=K({supported:xb().optional(),streaming:xb().optional(),encrypted:xb().optional()}),OS=K({image:xb().optional(),audio:xb().optional(),video:xb().optional(),pdf:xb().optional(),file:xb().optional()}),kS=K({image:xb().optional(),audio:xb().optional()}),AS=K({input:OS.optional(),output:kS.optional()}),jS=K({codeExecution:xb().optional(),sandboxed:xb().optional(),maxIterations:W().min(0).max(9007199254740991).optional(),maxExecutionTime:W().min(0).max(9007199254740991).optional()}),MS=K({supported:xb().optional(),approvals:xb().optional(),interventions:xb().optional(),feedback:xb().optional(),interrupts:xb().optional(),approveWithEdits:xb().optional()});K({identity:xS.optional(),transport:SS.optional(),tools:CS.optional(),output:wS.optional(),state:TS.optional(),multiAgent:ES.optional(),reasoning:DS.optional(),multimodal:AS.optional(),execution:jS.optional(),humanInTheLoop:MS.optional(),custom:gx(e=>typeof e==`object`&&!!e&&!Array.isArray(e)).optional()}),K({subagentRunId:xx.optional()}),K({type:bx,timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional()}),K({subagentRunId:xx.optional(),id:U(),role:U(),name:U().optional(),encryptedValue:U().optional(),metadata:J.optional()}),J.optional();function NS(){let e=this.buf,t=this.pos,n=0,r=0;for(let i=0;i<28;i+=7){let a=e[t++];if(n|=(a&127)<>4,!(i&128)){this.pos=t,this.assertBounds(),this.varint64Lo=n,this.varint64Hi=r;return}for(let i=3;i<=31;i+=7){let a=e[t++];if(r|=(a&127)<=PS&&(i+=r/PS|0,r%=PS)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?BS(r,i):zS(r,i)}function IS(e,t){let n=zS(e,t),r=n.hi&2147483648;r&&(n=BS(n.lo,n.hi));let i=LS(n.lo,n.hi);return r?`-`+i:i}function LS(e,t){if({lo:e,hi:t}=RS(e,t),t<=2097151)return String(PS*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,i=t>>16&65535,a=n+r*6777216+i*6710656,o=r+i*8147497,s=i*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+VS(o)+VS(a)}function RS(e,t){return{lo:e>>>0,hi:t>>>0}}function zS(e,t){return{lo:e|0,hi:t|0}}function BS(e,t){return t=~t,e?e=~e+1:t+=1,zS(e,t)}var VS=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function HS(){let e=this.buf[this.pos++];if(!(e&128))return this.assertBounds(),e;let t=e&127;if(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}var US=WS();function WS(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(globalThis.Deno||globalThis.Bun||typeof process!=`object`||{}.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||ri||ta.call(e)),JS(i)}return qS}function XS(e){return(t,n)=>{let r=e(t);return n.set(r),{written:r.byteLength}}}var ZS;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(ZS||={});var Y=class{constructor(e){this.stackPos=[],this.encodeUtf8Into=e?XS(e):YS().encodeUtf8Into,this.buffer=eC,this.viewCache=tC,this.pos=0}ensureCapacity(e){let t=this.pos+e;if(t>this.buffer.length){let e=this.buffer.length||QS;for(;e0&&n.set(this.buffer),this.buffer=n}}view(){let e=this.buffer,t=this.viewCache;if(t.byteLength===e.byteLength)return t;let n=new DataView(e.buffer);return this.viewCache=n,n}finish(){let e=this.buffer.slice(0,this.pos);return this.pos=0,this.stackPos=[],e}fork(){return this.stackPos.push(this.pos),this.ensureCapacity($S),this.buffer[this.pos++]=0,this}join(){let e=this.stackPos.pop();if(e===void 0)throw Error(`invalid state, fork stack empty`);let t=this.pos-e-$S,n=rC(t);return n>$S&&(this.ensureCapacity(n-$S),this.buffer.copyWithin(e+n,e+$S,this.pos)),this.pos=e,this.uint32(t),this.pos+=t,this}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.ensureCapacity(e.length),this.buffer.set(e,this.pos),this.pos+=e.length,this}uint32(e){if(aC(e),this.ensureCapacity(5),e<128)return this.buffer[this.pos++]=e,this;for(;e>127;)this.buffer[this.pos++]=e&127|128,e>>>=7;return this.buffer[this.pos++]=e,this}int32(e){if(iC(e),e>=0)return this.uint32(e);this.ensureCapacity(10);for(let t=0;t<9;t++)this.buffer[this.pos++]=e&127|128,e>>=7;return this.buffer[this.pos++]=1,this}bool(e){return this.ensureCapacity(1),this.buffer[this.pos++]=+!!e,this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){typeof e!=`string`&&(e=String(e));let t=e.length;if(t<=nC){this.ensureCapacity(t+1);let n=this.buffer,r=this.pos;n[r++]=t;let i=0;for(;i127)break;n[r++]=t}if(i==t)return this.pos=r,this}this.ensureCapacity(t*3+5);let n=rC(t),r=this.buffer,i=this.pos,{written:a}=this.encodeUtf8Into(e,r.subarray(i+n)),o=rC(a);return o!=n&&r.copyWithin(i+o,i+n,i+n+a),this.uint32(a),this.pos+=a,this}float(e){return oC(e),this.ensureCapacity(4),this.view().setFloat32(this.pos,e,!0),this.pos+=4,this}double(e){return this.ensureCapacity(8),this.view().setFloat64(this.pos,e,!0),this.pos+=8,this}fixed32(e){return aC(e),this.ensureCapacity(4),this.view().setUint32(this.pos,e,!0),this.pos+=4,this}sfixed32(e){return iC(e),this.ensureCapacity(4),this.view().setInt32(this.pos,e,!0),this.pos+=4,this}sint32(e){return iC(e),this.uint32((e<<1^e>>31)>>>0)}sfixed64(e){let t=US.enc(e);this.ensureCapacity(8);let n=this.view();return n.setInt32(this.pos,t.lo,!0),n.setInt32(this.pos+4,t.hi,!0),this.pos+=8,this}fixed64(e){let t=US.uEnc(e);this.ensureCapacity(8);let n=this.view();return n.setInt32(this.pos,t.lo,!0),n.setInt32(this.pos+4,t.hi,!0),this.pos+=8,this}int64(e){let t=US.enc(e);return this.writeVarint64(t.lo,t.hi)}sint64(e){let t=US.enc(e),n=t.hi>>31,r=t.lo<<1^n,i=(t.hi<<1|t.lo>>>31)^n;return this.writeVarint64(r,i)}uint64(e){let t=US.uEnc(e);return this.writeVarint64(t.lo,t.hi)}writeVarint64(e,t){this.ensureCapacity(10);let n=this.buffer,r=this.pos;for(let i=0;i<28;i+=7){let a=e>>>i,o=!(!(a>>>7)&&t==0);if(n[r++]=(o?a|128:a)&255,!o)return this.pos=r,this}let i=e>>>28&15|(t&7)<<4,a=!!(t>>3);if(n[r++]=(a?i|128:i)&255,!a)return this.pos=r,this;for(let e=3;e<31;e+=7){let i=t>>>e,a=!!(i>>>7);if(n[r++]=(a?i|128:i)&255,!a)return this.pos=r,this}return n[r++]=t>>>31&1,this.pos=r,this}},QS=128,$S=1,eC=new Uint8Array,tC=new DataView(eC.buffer),nC=32;function rC(e){return e<128?1:e<16384?2:e<2097152?3:e<268435456?4:5}var X=class{constructor(e,t=YS().decodeUtf8){this.decodeUtf8=t,this.varint64Lo=0,this.varint64Hi=0,this.varint64=NS,this.uint32=HS,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.pos,t=this.uint32(),n=this.pos-e;if(n>5||n==5&&this.buf[this.pos-1]>15)throw Error(`illegal tag: varint overflows uint32`);let r=t>>>3,i=t&7;if(r<=0||i>5)throw Error(`illegal tag: field no `+r+` wire type `+i);return[r,i]}skip(e,t,n=100){let r=this.pos;switch(e){case ZS.Varint:for(;this.buf[this.pos++]&128;);break;case ZS.Bit64:this.pos+=4;case ZS.Bit32:this.pos+=4;break;case ZS.LengthDelimited:let r=this.uint32();this.pos+=r;break;case ZS.StartGroup:if(n<=0)throw Error(`maximum recursion depth reached`);for(;;){let[e,r]=this.tag();if(r===ZS.EndGroup){if(t!==void 0&&e!==t)throw Error(`invalid end group tag`);break}this.skip(r,e,n-1)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return this.varint64(),US.dec(this.varint64Lo,this.varint64Hi)}uint64(){return this.varint64(),US.uDec(this.varint64Lo,this.varint64Hi)}sint64(){this.varint64();let e=this.varint64Lo,t=this.varint64Hi,n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,US.dec(e,t)}bool(){let e=this.buf[this.pos];return e<128?(this.pos++,e!==0):(this.varint64(),this.varint64Lo!==0||this.varint64Hi!==0)}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return US.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return US.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(e){let t=this.bytes(),n=t.length;if(n<=nC){let r=Array(n);for(let i=0;i127)return this.decodeUtf8(t,e);r[i]=n}return String.fromCharCode.apply(String,r)}return this.decodeUtf8(t,e)}};function iC(e){if(typeof e==`string`)e=Number(e);else if(typeof e!=`number`)throw Error(`invalid int32: `+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw Error(`invalid int32: `+e)}function aC(e){if(typeof e==`string`)e=Number(e);else if(typeof e!=`number`)throw Error(`invalid uint32: `+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw Error(`invalid uint32: `+e)}function oC(e){if(typeof e==`string`){let t=e;if(e=Number(e),Number.isNaN(e)&&t!==`NaN`)throw Error(`invalid float32: `+t)}else if(typeof e!=`number`)throw Error(`invalid float32: `+typeof e);if(!Number.isFinite(Math.fround(e))&&Number.isFinite(e))throw Error(`invalid float32: `+e)}var sC=function(e){return e[e.NULL_VALUE=0]=`NULL_VALUE`,e[e.UNRECOGNIZED=-1]=`UNRECOGNIZED`,e}({});function cC(){return{fields:{}}}var lC={encode(e,t=new Y){return Object.entries(e.fields).forEach(([e,n])=>{n!==void 0&&dC.encode({key:e,value:n},t.uint32(10).fork()).join()}),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=cC();for(;n.pos>>3){case 1:{if(e!==10)break;let t=dC.decode(n,n.uint32());t.value!==void 0&&(i.fields[t.key]=t.value);continue}}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return lC.fromPartial(e??{})},fromPartial(e){let t=cC();return t.fields=Object.entries(e.fields??{}).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),{}),t},wrap(e){let t=cC();if(e!==void 0)for(let n of Object.keys(e))t.fields[n]=e[n];return t},unwrap(e){let t={};if(e.fields)for(let n of Object.keys(e.fields))t[n]=e.fields[n];return t}};function uC(){return{key:``,value:void 0}}var dC={encode(e,t=new Y){return e.key!==``&&t.uint32(10).string(e.key),e.value!==void 0&&Z.encode(Z.wrap(e.value),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=uC();for(;n.pos>>3){case 1:if(e!==10)break;i.key=n.string();continue;case 2:if(e!==18)break;i.value=Z.unwrap(Z.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return dC.fromPartial(e??{})},fromPartial(e){let t=uC();return t.key=e.key??``,t.value=e.value??void 0,t}};function fC(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var Z={encode(e,t=new Y){return e.nullValue!==void 0&&t.uint32(8).int32(e.nullValue),e.numberValue!==void 0&&t.uint32(17).double(e.numberValue),e.stringValue!==void 0&&t.uint32(26).string(e.stringValue),e.boolValue!==void 0&&t.uint32(32).bool(e.boolValue),e.structValue!==void 0&&lC.encode(lC.wrap(e.structValue),t.uint32(42).fork()).join(),e.listValue!==void 0&&mC.encode(mC.wrap(e.listValue),t.uint32(50).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=fC();for(;n.pos>>3){case 1:if(e!==8)break;i.nullValue=n.int32();continue;case 2:if(e!==17)break;i.numberValue=n.double();continue;case 3:if(e!==26)break;i.stringValue=n.string();continue;case 4:if(e!==32)break;i.boolValue=n.bool();continue;case 5:if(e!==42)break;i.structValue=lC.unwrap(lC.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.listValue=mC.unwrap(mC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Z.fromPartial(e??{})},fromPartial(e){let t=fC();return t.nullValue=e.nullValue??void 0,t.numberValue=e.numberValue??void 0,t.stringValue=e.stringValue??void 0,t.boolValue=e.boolValue??void 0,t.structValue=e.structValue??void 0,t.listValue=e.listValue??void 0,t},wrap(e){let t=fC();if(e===null)t.nullValue=sC.NULL_VALUE;else if(typeof e==`boolean`)t.boolValue=e;else if(typeof e==`number`)t.numberValue=e;else if(typeof e==`string`)t.stringValue=e;else if(globalThis.Array.isArray(e))t.listValue=e;else if(typeof e==`object`)t.structValue=e;else if(e!==void 0)throw new globalThis.Error(`Unsupported any value type: `+typeof e);return t},unwrap(e){if(e.stringValue!==void 0)return e.stringValue;if(e?.numberValue!==void 0)return e.numberValue;if(e?.boolValue!==void 0)return e.boolValue;if(e?.structValue!==void 0)return e.structValue;if(e?.listValue!==void 0)return e.listValue;if(e?.nullValue!==void 0)return null}};function pC(){return{values:[]}}var mC={encode(e,t=new Y){for(let n of e.values)Z.encode(Z.wrap(n),t.uint32(10).fork()).join();return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=pC();for(;n.pos>>3){case 1:if(e!==10)break;i.values.push(Z.unwrap(Z.decode(n,n.uint32())));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return mC.fromPartial(e??{})},fromPartial(e){let t=pC();return t.values=e.values?.map(e=>e)||[],t},wrap(e){let t=pC();return t.values=e??[],t},unwrap(e){return e?.hasOwnProperty(`values`)&&globalThis.Array.isArray(e.values)?e.values:e}},hC=function(e){return e[e.ADD=0]=`ADD`,e[e.REMOVE=1]=`REMOVE`,e[e.REPLACE=2]=`REPLACE`,e[e.MOVE=3]=`MOVE`,e[e.COPY=4]=`COPY`,e[e.TEST=5]=`TEST`,e[e.UNRECOGNIZED=-1]=`UNRECOGNIZED`,e}({});function gC(){return{op:0,path:``,from:void 0,value:void 0}}var _C={encode(e,t=new Y){return e.op!==0&&t.uint32(8).int32(e.op),e.path!==``&&t.uint32(18).string(e.path),e.from!==void 0&&t.uint32(26).string(e.from),e.value!==void 0&&Z.encode(Z.wrap(e.value),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=gC();for(;n.pos>>3){case 1:if(e!==8)break;i.op=n.int32();continue;case 2:if(e!==18)break;i.path=n.string();continue;case 3:if(e!==26)break;i.from=n.string();continue;case 4:if(e!==34)break;i.value=Z.unwrap(Z.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return _C.fromPartial(e??{})},fromPartial(e){let t=gC();return t.op=e.op??0,t.path=e.path??``,t.from=e.from??void 0,t.value=e.value??void 0,t}};function vC(){return{text:``,id:void 0,metadata:void 0}}var yC={encode(e,t=new Y){return e.text!==``&&t.uint32(10).string(e.text),e.id!==void 0&&t.uint32(18).string(e.id),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(26).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=vC();for(;n.pos>>3){case 1:if(e!==10)break;i.text=n.string();continue;case 2:if(e!==18)break;i.id=n.string();continue;case 3:if(e!==26)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return yC.fromPartial(e??{})},fromPartial(e){let t=vC();return t.text=e.text??``,t.id=e.id??void 0,t.metadata=e.metadata??void 0,t}};function bC(){return{source:void 0,metadata:void 0,id:void 0}}var xC={encode(e,t=new Y){return e.source!==void 0&&kC.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(18).fork()).join(),e.id!==void 0&&t.uint32(26).string(e.id),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=bC();for(;n.pos>>3){case 1:if(e!==10)break;i.source=kC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.id=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return xC.fromPartial(e??{})},fromPartial(e){let t=bC();return t.source=e.source!==void 0&&e.source!==null?kC.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t.id=e.id??void 0,t}};function SC(){return{value:``,mimeType:``}}var CC={encode(e,t=new Y){return e.value!==``&&t.uint32(10).string(e.value),e.mimeType!==``&&t.uint32(18).string(e.mimeType),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=SC();for(;n.pos>>3){case 1:if(e!==10)break;i.value=n.string();continue;case 2:if(e!==18)break;i.mimeType=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return CC.fromPartial(e??{})},fromPartial(e){let t=SC();return t.value=e.value??``,t.mimeType=e.mimeType??``,t}};function wC(){return{value:``,mimeType:void 0}}var TC={encode(e,t=new Y){return e.value!==``&&t.uint32(10).string(e.value),e.mimeType!==void 0&&t.uint32(18).string(e.mimeType),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=wC();for(;n.pos>>3){case 1:if(e!==10)break;i.value=n.string();continue;case 2:if(e!==18)break;i.mimeType=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return TC.fromPartial(e??{})},fromPartial(e){let t=wC();return t.value=e.value??``,t.mimeType=e.mimeType??void 0,t}};function EC(){return{value:``,provider:void 0,mimeType:void 0}}var DC={encode(e,t=new Y){return e.value!==``&&t.uint32(10).string(e.value),e.provider!==void 0&&t.uint32(18).string(e.provider),e.mimeType!==void 0&&t.uint32(26).string(e.mimeType),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=EC();for(;n.pos>>3){case 1:if(e!==10)break;i.value=n.string();continue;case 2:if(e!==18)break;i.provider=n.string();continue;case 3:if(e!==26)break;i.mimeType=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return DC.fromPartial(e??{})},fromPartial(e){let t=EC();return t.value=e.value??``,t.provider=e.provider??void 0,t.mimeType=e.mimeType??void 0,t}};function OC(){return{data:void 0,url:void 0,file:void 0}}var kC={encode(e,t=new Y){return e.data!==void 0&&CC.encode(e.data,t.uint32(10).fork()).join(),e.url!==void 0&&TC.encode(e.url,t.uint32(18).fork()).join(),e.file!==void 0&&DC.encode(e.file,t.uint32(26).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=OC();for(;n.pos>>3){case 1:if(e!==10)break;i.data=CC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.url=TC.decode(n,n.uint32());continue;case 3:if(e!==26)break;i.file=DC.decode(n,n.uint32());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return kC.fromPartial(e??{})},fromPartial(e){let t=OC();return t.data=e.data!==void 0&&e.data!==null?CC.fromPartial(e.data):void 0,t.url=e.url!==void 0&&e.url!==null?TC.fromPartial(e.url):void 0,t.file=e.file!==void 0&&e.file!==null?DC.fromPartial(e.file):void 0,t}};function AC(){return{source:void 0,metadata:void 0,id:void 0}}var jC={encode(e,t=new Y){return e.source!==void 0&&kC.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(18).fork()).join(),e.id!==void 0&&t.uint32(26).string(e.id),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=AC();for(;n.pos>>3){case 1:if(e!==10)break;i.source=kC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.id=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return jC.fromPartial(e??{})},fromPartial(e){let t=AC();return t.source=e.source!==void 0&&e.source!==null?kC.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t.id=e.id??void 0,t}};function MC(){return{source:void 0,metadata:void 0,id:void 0}}var NC={encode(e,t=new Y){return e.source!==void 0&&kC.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(18).fork()).join(),e.id!==void 0&&t.uint32(26).string(e.id),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=MC();for(;n.pos>>3){case 1:if(e!==10)break;i.source=kC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.id=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return NC.fromPartial(e??{})},fromPartial(e){let t=MC();return t.source=e.source!==void 0&&e.source!==null?kC.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t.id=e.id??void 0,t}};function PC(){return{source:void 0,metadata:void 0,id:void 0}}var FC={encode(e,t=new Y){return e.source!==void 0&&kC.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(18).fork()).join(),e.id!==void 0&&t.uint32(26).string(e.id),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=PC();for(;n.pos>>3){case 1:if(e!==10)break;i.source=kC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.id=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return FC.fromPartial(e??{})},fromPartial(e){let t=PC();return t.source=e.source!==void 0&&e.source!==null?kC.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t.id=e.id??void 0,t}};function IC(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var LC={encode(e,t=new Y){return e.text!==void 0&&yC.encode(e.text,t.uint32(10).fork()).join(),e.image!==void 0&&xC.encode(e.image,t.uint32(18).fork()).join(),e.audio!==void 0&&jC.encode(e.audio,t.uint32(26).fork()).join(),e.video!==void 0&&NC.encode(e.video,t.uint32(34).fork()).join(),e.document!==void 0&&FC.encode(e.document,t.uint32(42).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=IC();for(;n.pos>>3){case 1:if(e!==10)break;i.text=yC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.image=xC.decode(n,n.uint32());continue;case 3:if(e!==26)break;i.audio=jC.decode(n,n.uint32());continue;case 4:if(e!==34)break;i.video=NC.decode(n,n.uint32());continue;case 5:if(e!==42)break;i.document=FC.decode(n,n.uint32());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return LC.fromPartial(e??{})},fromPartial(e){let t=IC();return t.text=e.text!==void 0&&e.text!==null?yC.fromPartial(e.text):void 0,t.image=e.image!==void 0&&e.image!==null?xC.fromPartial(e.image):void 0,t.audio=e.audio!==void 0&&e.audio!==null?jC.fromPartial(e.audio):void 0,t.video=e.video!==void 0&&e.video!==null?NC.fromPartial(e.video):void 0,t.document=e.document!==void 0&&e.document!==null?FC.fromPartial(e.document):void 0,t}};function RC(){return{id:``,type:``,function:void 0,metadata:void 0,encryptedValue:void 0}}var zC={encode(e,t=new Y){return e.id!==``&&t.uint32(10).string(e.id),e.type!==``&&t.uint32(18).string(e.type),e.function!==void 0&&VC.encode(e.function,t.uint32(26).fork()).join(),e.metadata!==void 0&&lC.encode(lC.wrap(e.metadata),t.uint32(34).fork()).join(),e.encryptedValue!==void 0&&t.uint32(42).string(e.encryptedValue),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=RC();for(;n.pos>>3){case 1:if(e!==10)break;i.id=n.string();continue;case 2:if(e!==18)break;i.type=n.string();continue;case 3:if(e!==26)break;i.function=VC.decode(n,n.uint32());continue;case 4:if(e!==34)break;i.metadata=lC.unwrap(lC.decode(n,n.uint32()));continue;case 5:if(e!==42)break;i.encryptedValue=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return zC.fromPartial(e??{})},fromPartial(e){let t=RC();return t.id=e.id??``,t.type=e.type??``,t.function=e.function!==void 0&&e.function!==null?VC.fromPartial(e.function):void 0,t.metadata=e.metadata??void 0,t.encryptedValue=e.encryptedValue??void 0,t}};function BC(){return{name:``,arguments:``}}var VC={encode(e,t=new Y){return e.name!==``&&t.uint32(10).string(e.name),e.arguments!==``&&t.uint32(18).string(e.arguments),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=BC();for(;n.pos>>3){case 1:if(e!==10)break;i.name=n.string();continue;case 2:if(e!==18)break;i.arguments=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return VC.fromPartial(e??{})},fromPartial(e){let t=BC();return t.name=e.name??``,t.arguments=e.arguments??``,t}};function HC(){return{id:``,role:``,content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[],metadata:void 0,subagentRunId:void 0,encryptedValue:void 0,activityType:void 0,activityContent:void 0}}var UC={encode(e,t=new Y){e.id!==``&&t.uint32(10).string(e.id),e.role!==``&&t.uint32(18).string(e.role),e.content!==void 0&&t.uint32(26).string(e.content),e.name!==void 0&&t.uint32(34).string(e.name);for(let n of e.toolCalls)zC.encode(n,t.uint32(42).fork()).join();e.toolCallId!==void 0&&t.uint32(50).string(e.toolCallId),e.error!==void 0&&t.uint32(58).string(e.error);for(let n of e.contentParts)LC.encode(n,t.uint32(66).fork()).join();return e.metadata!==void 0&&lC.encode(lC.wrap(e.metadata),t.uint32(74).fork()).join(),e.subagentRunId!==void 0&&t.uint32(82).string(e.subagentRunId),e.encryptedValue!==void 0&&t.uint32(90).string(e.encryptedValue),e.activityType!==void 0&&t.uint32(98).string(e.activityType),e.activityContent!==void 0&&lC.encode(lC.wrap(e.activityContent),t.uint32(106).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=HC();for(;n.pos>>3){case 1:if(e!==10)break;i.id=n.string();continue;case 2:if(e!==18)break;i.role=n.string();continue;case 3:if(e!==26)break;i.content=n.string();continue;case 4:if(e!==34)break;i.name=n.string();continue;case 5:if(e!==42)break;i.toolCalls.push(zC.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.toolCallId=n.string();continue;case 7:if(e!==58)break;i.error=n.string();continue;case 8:if(e!==66)break;i.contentParts.push(LC.decode(n,n.uint32()));continue;case 9:if(e!==74)break;i.metadata=lC.unwrap(lC.decode(n,n.uint32()));continue;case 10:if(e!==82)break;i.subagentRunId=n.string();continue;case 11:if(e!==90)break;i.encryptedValue=n.string();continue;case 12:if(e!==98)break;i.activityType=n.string();continue;case 13:if(e!==106)break;i.activityContent=lC.unwrap(lC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return UC.fromPartial(e??{})},fromPartial(e){let t=HC();return t.id=e.id??``,t.role=e.role??``,t.content=e.content??void 0,t.name=e.name??void 0,t.toolCalls=e.toolCalls?.map(e=>zC.fromPartial(e))||[],t.toolCallId=e.toolCallId??void 0,t.error=e.error??void 0,t.contentParts=e.contentParts?.map(e=>LC.fromPartial(e))||[],t.metadata=e.metadata??void 0,t.subagentRunId=e.subagentRunId??void 0,t.encryptedValue=e.encryptedValue??void 0,t.activityType=e.activityType??void 0,t.activityContent=e.activityContent??void 0,t}};function WC(){return{name:``,description:``,parameters:void 0,metadata:void 0}}var GC={encode(e,t=new Y){return e.name!==``&&t.uint32(10).string(e.name),e.description!==``&&t.uint32(18).string(e.description),e.parameters!==void 0&&Z.encode(Z.wrap(e.parameters),t.uint32(26).fork()).join(),e.metadata!==void 0&&lC.encode(lC.wrap(e.metadata),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=WC();for(;n.pos>>3){case 1:if(e!==10)break;i.name=n.string();continue;case 2:if(e!==18)break;i.description=n.string();continue;case 3:if(e!==26)break;i.parameters=Z.unwrap(Z.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.metadata=lC.unwrap(lC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return GC.fromPartial(e??{})},fromPartial(e){let t=WC();return t.name=e.name??``,t.description=e.description??``,t.parameters=e.parameters??void 0,t.metadata=e.metadata??void 0,t}};function KC(){return{description:``,value:``}}var qC={encode(e,t=new Y){return e.description!==``&&t.uint32(10).string(e.description),e.value!==``&&t.uint32(18).string(e.value),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=KC();for(;n.pos>>3){case 1:if(e!==10)break;i.description=n.string();continue;case 2:if(e!==18)break;i.value=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return qC.fromPartial(e??{})},fromPartial(e){let t=KC();return t.description=e.description??``,t.value=e.value??``,t}};function JC(){return{interruptId:``,status:``,payload:void 0,metadata:void 0}}var YC={encode(e,t=new Y){return e.interruptId!==``&&t.uint32(10).string(e.interruptId),e.status!==``&&t.uint32(18).string(e.status),e.payload!==void 0&&Z.encode(Z.wrap(e.payload),t.uint32(26).fork()).join(),e.metadata!==void 0&&lC.encode(lC.wrap(e.metadata),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=JC();for(;n.pos>>3){case 1:if(e!==10)break;i.interruptId=n.string();continue;case 2:if(e!==18)break;i.status=n.string();continue;case 3:if(e!==26)break;i.payload=Z.unwrap(Z.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.metadata=lC.unwrap(lC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return YC.fromPartial(e??{})},fromPartial(e){let t=JC();return t.interruptId=e.interruptId??``,t.status=e.status??``,t.payload=e.payload??void 0,t.metadata=e.metadata??void 0,t}};function XC(){return{threadId:``,runId:``,parentRunId:void 0,state:void 0,messages:[],tools:[],context:[],forwardedProps:void 0,resume:[],protocolVersion:void 0}}var ZC={encode(e,t=new Y){e.threadId!==``&&t.uint32(10).string(e.threadId),e.runId!==``&&t.uint32(18).string(e.runId),e.parentRunId!==void 0&&t.uint32(26).string(e.parentRunId),e.state!==void 0&&Z.encode(Z.wrap(e.state),t.uint32(34).fork()).join();for(let n of e.messages)UC.encode(n,t.uint32(42).fork()).join();for(let n of e.tools)GC.encode(n,t.uint32(50).fork()).join();for(let n of e.context)qC.encode(n,t.uint32(58).fork()).join();e.forwardedProps!==void 0&&Z.encode(Z.wrap(e.forwardedProps),t.uint32(66).fork()).join();for(let n of e.resume)YC.encode(n,t.uint32(74).fork()).join();return e.protocolVersion!==void 0&&t.uint32(82).string(e.protocolVersion),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=XC();for(;n.pos>>3){case 1:if(e!==10)break;i.threadId=n.string();continue;case 2:if(e!==18)break;i.runId=n.string();continue;case 3:if(e!==26)break;i.parentRunId=n.string();continue;case 4:if(e!==34)break;i.state=Z.unwrap(Z.decode(n,n.uint32()));continue;case 5:if(e!==42)break;i.messages.push(UC.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.tools.push(GC.decode(n,n.uint32()));continue;case 7:if(e!==58)break;i.context.push(qC.decode(n,n.uint32()));continue;case 8:if(e!==66)break;i.forwardedProps=Z.unwrap(Z.decode(n,n.uint32()));continue;case 9:if(e!==74)break;i.resume.push(YC.decode(n,n.uint32()));continue;case 10:if(e!==82)break;i.protocolVersion=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return ZC.fromPartial(e??{})},fromPartial(e){let t=XC();return t.threadId=e.threadId??``,t.runId=e.runId??``,t.parentRunId=e.parentRunId??void 0,t.state=e.state??void 0,t.messages=e.messages?.map(e=>UC.fromPartial(e))||[],t.tools=e.tools?.map(e=>GC.fromPartial(e))||[],t.context=e.context?.map(e=>qC.fromPartial(e))||[],t.forwardedProps=e.forwardedProps??void 0,t.resume=e.resume?.map(e=>YC.fromPartial(e))||[],t.protocolVersion=e.protocolVersion??void 0,t}};function QC(){return{id:``,reason:``,message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0,subagentRunId:void 0}}var $C={encode(e,t=new Y){return e.id!==``&&t.uint32(10).string(e.id),e.reason!==``&&t.uint32(18).string(e.reason),e.message!==void 0&&t.uint32(26).string(e.message),e.toolCallId!==void 0&&t.uint32(34).string(e.toolCallId),e.responseSchema!==void 0&&Z.encode(Z.wrap(e.responseSchema),t.uint32(42).fork()).join(),e.expiresAt!==void 0&&t.uint32(50).string(e.expiresAt),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(58).fork()).join(),e.subagentRunId!==void 0&&t.uint32(66).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=QC();for(;n.pos>>3){case 1:if(e!==10)break;i.id=n.string();continue;case 2:if(e!==18)break;i.reason=n.string();continue;case 3:if(e!==26)break;i.message=n.string();continue;case 4:if(e!==34)break;i.toolCallId=n.string();continue;case 5:if(e!==42)break;i.responseSchema=Z.unwrap(Z.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.expiresAt=n.string();continue;case 7:if(e!==58)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue;case 8:if(e!==66)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return $C.fromPartial(e??{})},fromPartial(e){let t=QC();return t.id=e.id??``,t.reason=e.reason??``,t.message=e.message??void 0,t.toolCallId=e.toolCallId??void 0,t.responseSchema=e.responseSchema??void 0,t.expiresAt=e.expiresAt??void 0,t.metadata=e.metadata??void 0,t.subagentRunId=e.subagentRunId??void 0,t}},ew=function(e){return e[e.TEXT_MESSAGE_START=0]=`TEXT_MESSAGE_START`,e[e.TEXT_MESSAGE_CONTENT=1]=`TEXT_MESSAGE_CONTENT`,e[e.TEXT_MESSAGE_END=2]=`TEXT_MESSAGE_END`,e[e.TOOL_CALL_START=3]=`TOOL_CALL_START`,e[e.TOOL_CALL_ARGS=4]=`TOOL_CALL_ARGS`,e[e.TOOL_CALL_END=5]=`TOOL_CALL_END`,e[e.STATE_SNAPSHOT=6]=`STATE_SNAPSHOT`,e[e.STATE_DELTA=7]=`STATE_DELTA`,e[e.MESSAGES_SNAPSHOT=8]=`MESSAGES_SNAPSHOT`,e[e.RAW=9]=`RAW`,e[e.CUSTOM=10]=`CUSTOM`,e[e.RUN_STARTED=11]=`RUN_STARTED`,e[e.RUN_FINISHED=12]=`RUN_FINISHED`,e[e.RUN_ERROR=13]=`RUN_ERROR`,e[e.STEP_STARTED=14]=`STEP_STARTED`,e[e.STEP_FINISHED=15]=`STEP_FINISHED`,e[e.SUBAGENT_STARTED=16]=`SUBAGENT_STARTED`,e[e.SUBAGENT_FINISHED=17]=`SUBAGENT_FINISHED`,e[e.SUBAGENT_ERROR=18]=`SUBAGENT_ERROR`,e[e.TEXT_MESSAGE_CHUNK=19]=`TEXT_MESSAGE_CHUNK`,e[e.TOOL_CALL_CHUNK=20]=`TOOL_CALL_CHUNK`,e[e.TOOL_CALL_RESULT=21]=`TOOL_CALL_RESULT`,e[e.ACTIVITY_SNAPSHOT=22]=`ACTIVITY_SNAPSHOT`,e[e.ACTIVITY_DELTA=23]=`ACTIVITY_DELTA`,e[e.REASONING_START=24]=`REASONING_START`,e[e.REASONING_MESSAGE_START=25]=`REASONING_MESSAGE_START`,e[e.REASONING_MESSAGE_CONTENT=26]=`REASONING_MESSAGE_CONTENT`,e[e.REASONING_MESSAGE_END=27]=`REASONING_MESSAGE_END`,e[e.REASONING_MESSAGE_CHUNK=28]=`REASONING_MESSAGE_CHUNK`,e[e.REASONING_END=29]=`REASONING_END`,e[e.REASONING_ENCRYPTED_VALUE=30]=`REASONING_ENCRYPTED_VALUE`,e[e.UNRECOGNIZED=-1]=`UNRECOGNIZED`,e}({});function tw(){return{type:0,timestamp:void 0,rawEvent:void 0,metadata:void 0}}var Q={encode(e,t=new Y){return e.type!==0&&t.uint32(8).int32(e.type),e.timestamp!==void 0&&t.uint32(16).int64(e.timestamp),e.rawEvent!==void 0&&Z.encode(Z.wrap(e.rawEvent),t.uint32(26).fork()).join(),e.metadata!==void 0&&lC.encode(lC.wrap(e.metadata),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=tw();for(;n.pos>>3){case 1:if(e!==8)break;i.type=n.int32();continue;case 2:if(e!==16)break;i.timestamp=mT(n.int64());continue;case 3:if(e!==26)break;i.rawEvent=Z.unwrap(Z.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.metadata=lC.unwrap(lC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Q.fromPartial(e??{})},fromPartial(e){let t=tw();return t.type=e.type??0,t.timestamp=e.timestamp??void 0,t.rawEvent=e.rawEvent??void 0,t.metadata=e.metadata??void 0,t}};function nw(){return{baseEvent:void 0,messageId:``,role:void 0,name:void 0,subagentRunId:void 0}}var rw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==``&&t.uint32(18).string(e.messageId),e.role!==void 0&&t.uint32(26).string(e.role),e.name!==void 0&&t.uint32(34).string(e.name),e.subagentRunId!==void 0&&t.uint32(42).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=nw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.role=n.string();continue;case 4:if(e!==34)break;i.name=n.string();continue;case 5:if(e!==42)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return rw.fromPartial(e??{})},fromPartial(e){let t=nw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??``,t.role=e.role??void 0,t.name=e.name??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function iw(){return{baseEvent:void 0,messageId:``,delta:``,subagentRunId:void 0}}var aw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==``&&t.uint32(18).string(e.messageId),e.delta!==``&&t.uint32(26).string(e.delta),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=iw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.delta=n.string();continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return aw.fromPartial(e??{})},fromPartial(e){let t=iw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??``,t.delta=e.delta??``,t.subagentRunId=e.subagentRunId??void 0,t}};function ow(){return{baseEvent:void 0,messageId:``,subagentRunId:void 0}}var sw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==``&&t.uint32(18).string(e.messageId),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=ow();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return sw.fromPartial(e??{})},fromPartial(e){let t=ow();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??``,t.subagentRunId=e.subagentRunId??void 0,t}};function cw(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0,subagentRunId:void 0}}var lw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==void 0&&t.uint32(18).string(e.messageId),e.role!==void 0&&t.uint32(26).string(e.role),e.delta!==void 0&&t.uint32(34).string(e.delta),e.name!==void 0&&t.uint32(42).string(e.name),e.subagentRunId!==void 0&&t.uint32(50).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=cw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.role=n.string();continue;case 4:if(e!==34)break;i.delta=n.string();continue;case 5:if(e!==42)break;i.name=n.string();continue;case 6:if(e!==50)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return lw.fromPartial(e??{})},fromPartial(e){let t=cw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??void 0,t.role=e.role??void 0,t.delta=e.delta??void 0,t.name=e.name??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function uw(){return{baseEvent:void 0,toolCallId:``,toolCallName:``,parentMessageId:void 0,subagentRunId:void 0}}var dw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==``&&t.uint32(18).string(e.toolCallId),e.toolCallName!==``&&t.uint32(26).string(e.toolCallName),e.parentMessageId!==void 0&&t.uint32(34).string(e.parentMessageId),e.subagentRunId!==void 0&&t.uint32(42).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=uw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.toolCallName=n.string();continue;case 4:if(e!==34)break;i.parentMessageId=n.string();continue;case 5:if(e!==42)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return dw.fromPartial(e??{})},fromPartial(e){let t=uw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??``,t.toolCallName=e.toolCallName??``,t.parentMessageId=e.parentMessageId??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function fw(){return{baseEvent:void 0,toolCallId:``,delta:``,subagentRunId:void 0}}var pw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==``&&t.uint32(18).string(e.toolCallId),e.delta!==``&&t.uint32(26).string(e.delta),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=fw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.delta=n.string();continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return pw.fromPartial(e??{})},fromPartial(e){let t=fw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??``,t.delta=e.delta??``,t.subagentRunId=e.subagentRunId??void 0,t}};function mw(){return{baseEvent:void 0,toolCallId:``,subagentRunId:void 0}}var hw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==``&&t.uint32(18).string(e.toolCallId),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=mw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return hw.fromPartial(e??{})},fromPartial(e){let t=mw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??``,t.subagentRunId=e.subagentRunId??void 0,t}};function gw(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0,subagentRunId:void 0}}var _w={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==void 0&&t.uint32(18).string(e.toolCallId),e.toolCallName!==void 0&&t.uint32(26).string(e.toolCallName),e.parentMessageId!==void 0&&t.uint32(34).string(e.parentMessageId),e.delta!==void 0&&t.uint32(42).string(e.delta),e.subagentRunId!==void 0&&t.uint32(50).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=gw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.toolCallName=n.string();continue;case 4:if(e!==34)break;i.parentMessageId=n.string();continue;case 5:if(e!==42)break;i.delta=n.string();continue;case 6:if(e!==50)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return _w.fromPartial(e??{})},fromPartial(e){let t=gw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??void 0,t.toolCallName=e.toolCallName??void 0,t.parentMessageId=e.parentMessageId??void 0,t.delta=e.delta??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function vw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``,toolCallId:``,content:void 0,role:void 0,contentParts:[]}}var yw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),e.toolCallId!==``&&t.uint32(34).string(e.toolCallId),e.content!==void 0&&t.uint32(42).string(e.content),e.role!==void 0&&t.uint32(50).string(e.role);for(let n of e.contentParts)LC.encode(n,t.uint32(58).fork()).join();return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=vw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.toolCallId=n.string();continue;case 5:if(e!==42)break;i.content=n.string();continue;case 6:if(e!==50)break;i.role=n.string();continue;case 7:if(e!==58)break;i.contentParts.push(LC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return yw.fromPartial(e??{})},fromPartial(e){let t=vw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t.toolCallId=e.toolCallId??``,t.content=e.content??void 0,t.role=e.role??void 0,t.contentParts=e.contentParts?.map(e=>LC.fromPartial(e))||[],t}};function bw(){return{baseEvent:void 0,snapshot:void 0,subagentRunId:void 0}}var xw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.snapshot!==void 0&&Z.encode(Z.wrap(e.snapshot),t.uint32(18).fork()).join(),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=bw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.snapshot=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return xw.fromPartial(e??{})},fromPartial(e){let t=bw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.snapshot=e.snapshot??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function Sw(){return{baseEvent:void 0,delta:[],subagentRunId:void 0}}var Cw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join();for(let n of e.delta)_C.encode(n,t.uint32(18).fork()).join();return e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Sw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.delta.push(_C.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Cw.fromPartial(e??{})},fromPartial(e){let t=Sw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.delta=e.delta?.map(e=>_C.fromPartial(e))||[],t.subagentRunId=e.subagentRunId??void 0,t}};function ww(){return{baseEvent:void 0,messages:[]}}var Tw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join();for(let n of e.messages)UC.encode(n,t.uint32(18).fork()).join();return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=ww();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messages.push(UC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Tw.fromPartial(e??{})},fromPartial(e){let t=ww();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.messages=e.messages?.map(e=>UC.fromPartial(e))||[],t}};function Ew(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``,activityType:``,content:void 0,replace:void 0}}var Dw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),e.activityType!==``&&t.uint32(34).string(e.activityType),e.content!==void 0&&lC.encode(lC.wrap(e.content),t.uint32(42).fork()).join(),e.replace!==void 0&&t.uint32(48).bool(e.replace),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Ew();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.activityType=n.string();continue;case 5:if(e!==42)break;i.content=lC.unwrap(lC.decode(n,n.uint32()));continue;case 6:if(e!==48)break;i.replace=n.bool();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Dw.fromPartial(e??{})},fromPartial(e){let t=Ew();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t.activityType=e.activityType??``,t.content=e.content??void 0,t.replace=e.replace??void 0,t}};function Ow(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``,activityType:``,patch:[]}}var kw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),e.activityType!==``&&t.uint32(34).string(e.activityType);for(let n of e.patch)_C.encode(n,t.uint32(42).fork()).join();return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Ow();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.activityType=n.string();continue;case 5:if(e!==42)break;i.patch.push(_C.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return kw.fromPartial(e??{})},fromPartial(e){let t=Ow();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t.activityType=e.activityType??``,t.patch=e.patch?.map(e=>_C.fromPartial(e))||[],t}};function Aw(){return{baseEvent:void 0,event:void 0,source:void 0,subagentRunId:void 0}}var jw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.event!==void 0&&Z.encode(Z.wrap(e.event),t.uint32(18).fork()).join(),e.source!==void 0&&t.uint32(26).string(e.source),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Aw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.event=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.source=n.string();continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return jw.fromPartial(e??{})},fromPartial(e){let t=Aw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.event=e.event??void 0,t.source=e.source??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function Mw(){return{baseEvent:void 0,name:``,value:void 0,subagentRunId:void 0}}var Nw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.name!==``&&t.uint32(18).string(e.name),e.value!==void 0&&Z.encode(Z.wrap(e.value),t.uint32(26).fork()).join(),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Mw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.name=n.string();continue;case 3:if(e!==26)break;i.value=Z.unwrap(Z.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Nw.fromPartial(e??{})},fromPartial(e){let t=Mw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.name=e.name??``,t.value=e.value??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function Pw(){return{baseEvent:void 0,threadId:``,runId:``,parentRunId:void 0,input:void 0,protocolVersion:void 0}}var Fw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.threadId!==``&&t.uint32(18).string(e.threadId),e.runId!==``&&t.uint32(26).string(e.runId),e.parentRunId!==void 0&&t.uint32(34).string(e.parentRunId),e.input!==void 0&&ZC.encode(e.input,t.uint32(42).fork()).join(),e.protocolVersion!==void 0&&t.uint32(50).string(e.protocolVersion),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Pw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.threadId=n.string();continue;case 3:if(e!==26)break;i.runId=n.string();continue;case 4:if(e!==34)break;i.parentRunId=n.string();continue;case 5:if(e!==42)break;i.input=ZC.decode(n,n.uint32());continue;case 6:if(e!==50)break;i.protocolVersion=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Fw.fromPartial(e??{})},fromPartial(e){let t=Pw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.threadId=e.threadId??``,t.runId=e.runId??``,t.parentRunId=e.parentRunId??void 0,t.input=e.input!==void 0&&e.input!==null?ZC.fromPartial(e.input):void 0,t.protocolVersion=e.protocolVersion??void 0,t}};function Iw(){return{baseEvent:void 0,threadId:``,runId:``,result:void 0,outcome:``,interrupts:[],usage:[],pendingToolCallIds:[]}}var Lw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.threadId!==``&&t.uint32(18).string(e.threadId),e.runId!==``&&t.uint32(26).string(e.runId),e.result!==void 0&&Z.encode(Z.wrap(e.result),t.uint32(34).fork()).join(),e.outcome!==``&&t.uint32(42).string(e.outcome);for(let n of e.interrupts)$C.encode(n,t.uint32(50).fork()).join();for(let n of e.usage)pT.encode(n,t.uint32(58).fork()).join();for(let n of e.pendingToolCallIds)t.uint32(66).string(n);return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Iw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.threadId=n.string();continue;case 3:if(e!==26)break;i.runId=n.string();continue;case 4:if(e!==34)break;i.result=Z.unwrap(Z.decode(n,n.uint32()));continue;case 5:if(e!==42)break;i.outcome=n.string();continue;case 6:if(e!==50)break;i.interrupts.push($C.decode(n,n.uint32()));continue;case 7:if(e!==58)break;i.usage.push(pT.decode(n,n.uint32()));continue;case 8:if(e!==66)break;i.pendingToolCallIds.push(n.string());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Lw.fromPartial(e??{})},fromPartial(e){let t=Iw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.threadId=e.threadId??``,t.runId=e.runId??``,t.result=e.result??void 0,t.outcome=e.outcome??``,t.interrupts=e.interrupts?.map(e=>$C.fromPartial(e))||[],t.usage=e.usage?.map(e=>pT.fromPartial(e))||[],t.pendingToolCallIds=e.pendingToolCallIds?.map(e=>e)||[],t}};function Rw(){return{baseEvent:void 0,code:void 0,message:``,usage:[]}}var zw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.code!==void 0&&t.uint32(18).string(e.code),e.message!==``&&t.uint32(26).string(e.message);for(let n of e.usage)pT.encode(n,t.uint32(34).fork()).join();return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Rw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.code=n.string();continue;case 3:if(e!==26)break;i.message=n.string();continue;case 4:if(e!==34)break;i.usage.push(pT.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return zw.fromPartial(e??{})},fromPartial(e){let t=Rw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.code=e.code??void 0,t.message=e.message??``,t.usage=e.usage?.map(e=>pT.fromPartial(e))||[],t}};function Bw(){return{baseEvent:void 0,stepName:``,subagentRunId:void 0}}var Vw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.stepName!==``&&t.uint32(18).string(e.stepName),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Bw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.stepName=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Vw.fromPartial(e??{})},fromPartial(e){let t=Bw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.stepName=e.stepName??``,t.subagentRunId=e.subagentRunId??void 0,t}};function Hw(){return{baseEvent:void 0,stepName:``,subagentRunId:void 0}}var Uw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.stepName!==``&&t.uint32(18).string(e.stepName),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Hw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.stepName=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Uw.fromPartial(e??{})},fromPartial(e){let t=Hw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.stepName=e.stepName??``,t.subagentRunId=e.subagentRunId??void 0,t}};function Ww(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``}}var Gw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Ww();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Gw.fromPartial(e??{})},fromPartial(e){let t=Ww();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t}};function Kw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``,role:``}}var qw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),e.role!==``&&t.uint32(34).string(e.role),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Kw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.role=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return qw.fromPartial(e??{})},fromPartial(e){let t=Kw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t.role=e.role??``,t}};function Jw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``,delta:``}}var Yw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),e.delta!==``&&t.uint32(34).string(e.delta),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Jw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.delta=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Yw.fromPartial(e??{})},fromPartial(e){let t=Jw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t.delta=e.delta??``,t}};function Xw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``}}var Zw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Xw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Zw.fromPartial(e??{})},fromPartial(e){let t=Xw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t}};function Qw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:void 0,delta:void 0}}var $w={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==void 0&&t.uint32(26).string(e.messageId),e.delta!==void 0&&t.uint32(34).string(e.delta),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Qw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.delta=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return $w.fromPartial(e??{})},fromPartial(e){let t=Qw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??void 0,t.delta=e.delta??void 0,t}};function eT(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``}}var tT={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=eT();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return tT.fromPartial(e??{})},fromPartial(e){let t=eT();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t}};function nT(){return{baseEvent:void 0,subagentRunId:void 0,subtype:``,entityId:``,encryptedValue:``}}var rT={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.subtype!==``&&t.uint32(26).string(e.subtype),e.entityId!==``&&t.uint32(34).string(e.entityId),e.encryptedValue!==``&&t.uint32(42).string(e.encryptedValue),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=nT();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.subtype=n.string();continue;case 4:if(e!==34)break;i.entityId=n.string();continue;case 5:if(e!==42)break;i.encryptedValue=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return rT.fromPartial(e??{})},fromPartial(e){let t=nT();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.subtype=e.subtype??``,t.entityId=e.entityId??``,t.encryptedValue=e.encryptedValue??``,t}};function iT(){return{baseEvent:void 0,subagentRunId:``,name:``,description:void 0,parentSubagentRunId:void 0,parentToolCallId:void 0,parentMessageId:void 0}}var aT={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==``&&t.uint32(18).string(e.subagentRunId),e.name!==``&&t.uint32(26).string(e.name),e.description!==void 0&&t.uint32(34).string(e.description),e.parentSubagentRunId!==void 0&&t.uint32(42).string(e.parentSubagentRunId),e.parentToolCallId!==void 0&&t.uint32(50).string(e.parentToolCallId),e.parentMessageId!==void 0&&t.uint32(58).string(e.parentMessageId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=iT();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.name=n.string();continue;case 4:if(e!==34)break;i.description=n.string();continue;case 5:if(e!==42)break;i.parentSubagentRunId=n.string();continue;case 6:if(e!==50)break;i.parentToolCallId=n.string();continue;case 7:if(e!==58)break;i.parentMessageId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return aT.fromPartial(e??{})},fromPartial(e){let t=iT();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??``,t.name=e.name??``,t.description=e.description??void 0,t.parentSubagentRunId=e.parentSubagentRunId??void 0,t.parentToolCallId=e.parentToolCallId??void 0,t.parentMessageId=e.parentMessageId??void 0,t}};function oT(){return{baseEvent:void 0,subagentRunId:``,result:void 0,outcome:``,interruptIds:[]}}var sT={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==``&&t.uint32(18).string(e.subagentRunId),e.result!==void 0&&Z.encode(Z.wrap(e.result),t.uint32(26).fork()).join(),e.outcome!==``&&t.uint32(34).string(e.outcome);for(let n of e.interruptIds)t.uint32(42).string(n);return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=oT();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.result=Z.unwrap(Z.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.outcome=n.string();continue;case 5:if(e!==42)break;i.interruptIds.push(n.string());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return sT.fromPartial(e??{})},fromPartial(e){let t=oT();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??``,t.result=e.result??void 0,t.outcome=e.outcome??``,t.interruptIds=e.interruptIds?.map(e=>e)||[],t}};function cT(){return{baseEvent:void 0,subagentRunId:``,message:``,code:void 0}}var lT={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==``&&t.uint32(18).string(e.subagentRunId),e.message!==``&&t.uint32(26).string(e.message),e.code!==void 0&&t.uint32(34).string(e.code),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=cT();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.message=n.string();continue;case 4:if(e!==34)break;i.code=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return lT.fromPartial(e??{})},fromPartial(e){let t=cT();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??``,t.message=e.message??``,t.code=e.code??void 0,t}};function uT(){return{textMessageStart:void 0,textMessageContent:void 0,textMessageEnd:void 0,toolCallStart:void 0,toolCallArgs:void 0,toolCallEnd:void 0,stateSnapshot:void 0,stateDelta:void 0,messagesSnapshot:void 0,raw:void 0,custom:void 0,runStarted:void 0,runFinished:void 0,runError:void 0,stepStarted:void 0,stepFinished:void 0,textMessageChunk:void 0,toolCallChunk:void 0,subagentStarted:void 0,subagentFinished:void 0,subagentError:void 0,toolCallResult:void 0,activitySnapshot:void 0,activityDelta:void 0,reasoningStart:void 0,reasoningMessageStart:void 0,reasoningMessageContent:void 0,reasoningMessageEnd:void 0,reasoningMessageChunk:void 0,reasoningEnd:void 0,reasoningEncryptedValue:void 0}}var dT={encode(e,t=new Y){return e.textMessageStart!==void 0&&rw.encode(e.textMessageStart,t.uint32(10).fork()).join(),e.textMessageContent!==void 0&&aw.encode(e.textMessageContent,t.uint32(18).fork()).join(),e.textMessageEnd!==void 0&&sw.encode(e.textMessageEnd,t.uint32(26).fork()).join(),e.toolCallStart!==void 0&&dw.encode(e.toolCallStart,t.uint32(34).fork()).join(),e.toolCallArgs!==void 0&&pw.encode(e.toolCallArgs,t.uint32(42).fork()).join(),e.toolCallEnd!==void 0&&hw.encode(e.toolCallEnd,t.uint32(50).fork()).join(),e.stateSnapshot!==void 0&&xw.encode(e.stateSnapshot,t.uint32(58).fork()).join(),e.stateDelta!==void 0&&Cw.encode(e.stateDelta,t.uint32(66).fork()).join(),e.messagesSnapshot!==void 0&&Tw.encode(e.messagesSnapshot,t.uint32(74).fork()).join(),e.raw!==void 0&&jw.encode(e.raw,t.uint32(82).fork()).join(),e.custom!==void 0&&Nw.encode(e.custom,t.uint32(90).fork()).join(),e.runStarted!==void 0&&Fw.encode(e.runStarted,t.uint32(98).fork()).join(),e.runFinished!==void 0&&Lw.encode(e.runFinished,t.uint32(106).fork()).join(),e.runError!==void 0&&zw.encode(e.runError,t.uint32(114).fork()).join(),e.stepStarted!==void 0&&Vw.encode(e.stepStarted,t.uint32(122).fork()).join(),e.stepFinished!==void 0&&Uw.encode(e.stepFinished,t.uint32(130).fork()).join(),e.textMessageChunk!==void 0&&lw.encode(e.textMessageChunk,t.uint32(138).fork()).join(),e.toolCallChunk!==void 0&&_w.encode(e.toolCallChunk,t.uint32(146).fork()).join(),e.subagentStarted!==void 0&&aT.encode(e.subagentStarted,t.uint32(154).fork()).join(),e.subagentFinished!==void 0&&sT.encode(e.subagentFinished,t.uint32(162).fork()).join(),e.subagentError!==void 0&&lT.encode(e.subagentError,t.uint32(170).fork()).join(),e.toolCallResult!==void 0&&yw.encode(e.toolCallResult,t.uint32(178).fork()).join(),e.activitySnapshot!==void 0&&Dw.encode(e.activitySnapshot,t.uint32(186).fork()).join(),e.activityDelta!==void 0&&kw.encode(e.activityDelta,t.uint32(194).fork()).join(),e.reasoningStart!==void 0&&Gw.encode(e.reasoningStart,t.uint32(202).fork()).join(),e.reasoningMessageStart!==void 0&&qw.encode(e.reasoningMessageStart,t.uint32(210).fork()).join(),e.reasoningMessageContent!==void 0&&Yw.encode(e.reasoningMessageContent,t.uint32(218).fork()).join(),e.reasoningMessageEnd!==void 0&&Zw.encode(e.reasoningMessageEnd,t.uint32(226).fork()).join(),e.reasoningMessageChunk!==void 0&&$w.encode(e.reasoningMessageChunk,t.uint32(234).fork()).join(),e.reasoningEnd!==void 0&&tT.encode(e.reasoningEnd,t.uint32(242).fork()).join(),e.reasoningEncryptedValue!==void 0&&rT.encode(e.reasoningEncryptedValue,t.uint32(250).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=uT();for(;n.pos>>3){case 1:if(e!==10)break;i.textMessageStart=rw.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.textMessageContent=aw.decode(n,n.uint32());continue;case 3:if(e!==26)break;i.textMessageEnd=sw.decode(n,n.uint32());continue;case 4:if(e!==34)break;i.toolCallStart=dw.decode(n,n.uint32());continue;case 5:if(e!==42)break;i.toolCallArgs=pw.decode(n,n.uint32());continue;case 6:if(e!==50)break;i.toolCallEnd=hw.decode(n,n.uint32());continue;case 7:if(e!==58)break;i.stateSnapshot=xw.decode(n,n.uint32());continue;case 8:if(e!==66)break;i.stateDelta=Cw.decode(n,n.uint32());continue;case 9:if(e!==74)break;i.messagesSnapshot=Tw.decode(n,n.uint32());continue;case 10:if(e!==82)break;i.raw=jw.decode(n,n.uint32());continue;case 11:if(e!==90)break;i.custom=Nw.decode(n,n.uint32());continue;case 12:if(e!==98)break;i.runStarted=Fw.decode(n,n.uint32());continue;case 13:if(e!==106)break;i.runFinished=Lw.decode(n,n.uint32());continue;case 14:if(e!==114)break;i.runError=zw.decode(n,n.uint32());continue;case 15:if(e!==122)break;i.stepStarted=Vw.decode(n,n.uint32());continue;case 16:if(e!==130)break;i.stepFinished=Uw.decode(n,n.uint32());continue;case 17:if(e!==138)break;i.textMessageChunk=lw.decode(n,n.uint32());continue;case 18:if(e!==146)break;i.toolCallChunk=_w.decode(n,n.uint32());continue;case 19:if(e!==154)break;i.subagentStarted=aT.decode(n,n.uint32());continue;case 20:if(e!==162)break;i.subagentFinished=sT.decode(n,n.uint32());continue;case 21:if(e!==170)break;i.subagentError=lT.decode(n,n.uint32());continue;case 22:if(e!==178)break;i.toolCallResult=yw.decode(n,n.uint32());continue;case 23:if(e!==186)break;i.activitySnapshot=Dw.decode(n,n.uint32());continue;case 24:if(e!==194)break;i.activityDelta=kw.decode(n,n.uint32());continue;case 25:if(e!==202)break;i.reasoningStart=Gw.decode(n,n.uint32());continue;case 26:if(e!==210)break;i.reasoningMessageStart=qw.decode(n,n.uint32());continue;case 27:if(e!==218)break;i.reasoningMessageContent=Yw.decode(n,n.uint32());continue;case 28:if(e!==226)break;i.reasoningMessageEnd=Zw.decode(n,n.uint32());continue;case 29:if(e!==234)break;i.reasoningMessageChunk=$w.decode(n,n.uint32());continue;case 30:if(e!==242)break;i.reasoningEnd=tT.decode(n,n.uint32());continue;case 31:if(e!==250)break;i.reasoningEncryptedValue=rT.decode(n,n.uint32());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return dT.fromPartial(e??{})},fromPartial(e){let t=uT();return t.textMessageStart=e.textMessageStart!==void 0&&e.textMessageStart!==null?rw.fromPartial(e.textMessageStart):void 0,t.textMessageContent=e.textMessageContent!==void 0&&e.textMessageContent!==null?aw.fromPartial(e.textMessageContent):void 0,t.textMessageEnd=e.textMessageEnd!==void 0&&e.textMessageEnd!==null?sw.fromPartial(e.textMessageEnd):void 0,t.toolCallStart=e.toolCallStart!==void 0&&e.toolCallStart!==null?dw.fromPartial(e.toolCallStart):void 0,t.toolCallArgs=e.toolCallArgs!==void 0&&e.toolCallArgs!==null?pw.fromPartial(e.toolCallArgs):void 0,t.toolCallEnd=e.toolCallEnd!==void 0&&e.toolCallEnd!==null?hw.fromPartial(e.toolCallEnd):void 0,t.stateSnapshot=e.stateSnapshot!==void 0&&e.stateSnapshot!==null?xw.fromPartial(e.stateSnapshot):void 0,t.stateDelta=e.stateDelta!==void 0&&e.stateDelta!==null?Cw.fromPartial(e.stateDelta):void 0,t.messagesSnapshot=e.messagesSnapshot!==void 0&&e.messagesSnapshot!==null?Tw.fromPartial(e.messagesSnapshot):void 0,t.raw=e.raw!==void 0&&e.raw!==null?jw.fromPartial(e.raw):void 0,t.custom=e.custom!==void 0&&e.custom!==null?Nw.fromPartial(e.custom):void 0,t.runStarted=e.runStarted!==void 0&&e.runStarted!==null?Fw.fromPartial(e.runStarted):void 0,t.runFinished=e.runFinished!==void 0&&e.runFinished!==null?Lw.fromPartial(e.runFinished):void 0,t.runError=e.runError!==void 0&&e.runError!==null?zw.fromPartial(e.runError):void 0,t.stepStarted=e.stepStarted!==void 0&&e.stepStarted!==null?Vw.fromPartial(e.stepStarted):void 0,t.stepFinished=e.stepFinished!==void 0&&e.stepFinished!==null?Uw.fromPartial(e.stepFinished):void 0,t.textMessageChunk=e.textMessageChunk!==void 0&&e.textMessageChunk!==null?lw.fromPartial(e.textMessageChunk):void 0,t.toolCallChunk=e.toolCallChunk!==void 0&&e.toolCallChunk!==null?_w.fromPartial(e.toolCallChunk):void 0,t.subagentStarted=e.subagentStarted!==void 0&&e.subagentStarted!==null?aT.fromPartial(e.subagentStarted):void 0,t.subagentFinished=e.subagentFinished!==void 0&&e.subagentFinished!==null?sT.fromPartial(e.subagentFinished):void 0,t.subagentError=e.subagentError!==void 0&&e.subagentError!==null?lT.fromPartial(e.subagentError):void 0,t.toolCallResult=e.toolCallResult!==void 0&&e.toolCallResult!==null?yw.fromPartial(e.toolCallResult):void 0,t.activitySnapshot=e.activitySnapshot!==void 0&&e.activitySnapshot!==null?Dw.fromPartial(e.activitySnapshot):void 0,t.activityDelta=e.activityDelta!==void 0&&e.activityDelta!==null?kw.fromPartial(e.activityDelta):void 0,t.reasoningStart=e.reasoningStart!==void 0&&e.reasoningStart!==null?Gw.fromPartial(e.reasoningStart):void 0,t.reasoningMessageStart=e.reasoningMessageStart!==void 0&&e.reasoningMessageStart!==null?qw.fromPartial(e.reasoningMessageStart):void 0,t.reasoningMessageContent=e.reasoningMessageContent!==void 0&&e.reasoningMessageContent!==null?Yw.fromPartial(e.reasoningMessageContent):void 0,t.reasoningMessageEnd=e.reasoningMessageEnd!==void 0&&e.reasoningMessageEnd!==null?Zw.fromPartial(e.reasoningMessageEnd):void 0,t.reasoningMessageChunk=e.reasoningMessageChunk!==void 0&&e.reasoningMessageChunk!==null?$w.fromPartial(e.reasoningMessageChunk):void 0,t.reasoningEnd=e.reasoningEnd!==void 0&&e.reasoningEnd!==null?tT.fromPartial(e.reasoningEnd):void 0,t.reasoningEncryptedValue=e.reasoningEncryptedValue!==void 0&&e.reasoningEncryptedValue!==null?rT.fromPartial(e.reasoningEncryptedValue):void 0,t}};function fT(){return{provider:void 0,model:void 0,inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0,cacheWriteInputTokens:void 0}}var pT={encode(e,t=new Y){return e.provider!==void 0&&t.uint32(10).string(e.provider),e.model!==void 0&&t.uint32(18).string(e.model),e.inputTokens!==void 0&&t.uint32(24).int64(e.inputTokens),e.outputTokens!==void 0&&t.uint32(32).int64(e.outputTokens),e.totalTokens!==void 0&&t.uint32(40).int64(e.totalTokens),e.reasoningTokens!==void 0&&t.uint32(48).int64(e.reasoningTokens),e.cachedInputTokens!==void 0&&t.uint32(56).int64(e.cachedInputTokens),e.cacheWriteInputTokens!==void 0&&t.uint32(64).int64(e.cacheWriteInputTokens),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=fT();for(;n.pos>>3){case 1:if(e!==10)break;i.provider=n.string();continue;case 2:if(e!==18)break;i.model=n.string();continue;case 3:if(e!==24)break;i.inputTokens=mT(n.int64());continue;case 4:if(e!==32)break;i.outputTokens=mT(n.int64());continue;case 5:if(e!==40)break;i.totalTokens=mT(n.int64());continue;case 6:if(e!==48)break;i.reasoningTokens=mT(n.int64());continue;case 7:if(e!==56)break;i.cachedInputTokens=mT(n.int64());continue;case 8:if(e!==64)break;i.cacheWriteInputTokens=mT(n.int64());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return pT.fromPartial(e??{})},fromPartial(e){let t=fT();return t.provider=e.provider??void 0,t.model=e.model??void 0,t.inputTokens=e.inputTokens??void 0,t.outputTokens=e.outputTokens??void 0,t.totalTokens=e.totalTokens??void 0,t.reasoningTokens=e.reasoningTokens??void 0,t.cachedInputTokens=e.cachedInputTokens??void 0,t.cacheWriteInputTokens=e.cacheWriteInputTokens??void 0,t}};function mT(e){let t=globalThis.Number(e.toString());if(t>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error(`Value is larger than Number.MAX_SAFE_INTEGER`);if(te&&typeof e==`object`?e:void 0,gT=e=>Array.isArray(e)?e:[],_T=()=>typeof process<`u`&&!!{}.SUPPRESS_TRANSFORMATION_WARNINGS,vT=()=>{_T()||console.warn(`[ag-ui][proto] Dropped a content part this build does not know: the protocol has a variant this SDK predates.`)};new Set(Object.values(I));var yT={textMessageStart:`TEXT_MESSAGE_START`,textMessageContent:`TEXT_MESSAGE_CONTENT`,textMessageEnd:`TEXT_MESSAGE_END`,textMessageChunk:`TEXT_MESSAGE_CHUNK`,toolCallStart:`TOOL_CALL_START`,toolCallArgs:`TOOL_CALL_ARGS`,toolCallEnd:`TOOL_CALL_END`,toolCallChunk:`TOOL_CALL_CHUNK`,toolCallResult:`TOOL_CALL_RESULT`,stateSnapshot:`STATE_SNAPSHOT`,stateDelta:`STATE_DELTA`,messagesSnapshot:`MESSAGES_SNAPSHOT`,activitySnapshot:`ACTIVITY_SNAPSHOT`,activityDelta:`ACTIVITY_DELTA`,raw:`RAW`,custom:`CUSTOM`,runStarted:`RUN_STARTED`,runFinished:`RUN_FINISHED`,runError:`RUN_ERROR`,stepStarted:`STEP_STARTED`,stepFinished:`STEP_FINISHED`,reasoningStart:`REASONING_START`,reasoningMessageStart:`REASONING_MESSAGE_START`,reasoningMessageContent:`REASONING_MESSAGE_CONTENT`,reasoningMessageEnd:`REASONING_MESSAGE_END`,reasoningMessageChunk:`REASONING_MESSAGE_CHUNK`,reasoningEnd:`REASONING_END`,reasoningEncryptedValue:`REASONING_ENCRYPTED_VALUE`,subagentStarted:`SUBAGENT_STARTED`,subagentFinished:`SUBAGENT_FINISHED`,subagentError:`SUBAGENT_ERROR`},bT=new Set([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]),xT=e=>{let t=hT(e);if(t){if([t.data,t.url,t.file].filter(Boolean).length>1)throw Error(`Invalid event: source carries more than one arm`);if(t.data){let e=t.data;return{type:`data`,value:e.value,mimeType:e.mimeType}}if(t.url){let e=t.url;return{type:`url`,value:e.value,mimeType:e.mimeType}}if(t.file){let e=t.file;return{type:`file`,value:e.value,provider:e.provider,mimeType:e.mimeType}}}},ST=e=>{let t=hT(e);if(t){if([t.text,t.image,t.audio,t.video,t.document].filter(Boolean).length>1)throw Error(`Invalid event: content part carries more than one arm`);if(t.text){let e=t.text;return{type:`text`,id:e.id,text:e.text,metadata:e.metadata}}if(t.image){let e=t.image;return e.source!==void 0&&xT(e.source)===void 0?void 0:{type:`image`,id:e.id,source:xT(e.source),metadata:e.metadata}}if(t.audio){let e=t.audio;return e.source!==void 0&&xT(e.source)===void 0?void 0:{type:`audio`,id:e.id,source:xT(e.source),metadata:e.metadata}}if(t.video){let e=t.video;return e.source!==void 0&&xT(e.source)===void 0?void 0:{type:`video`,id:e.id,source:xT(e.source),metadata:e.metadata}}if(t.document){let e=t.document;return e.source!==void 0&&xT(e.source)===void 0?void 0:{type:`document`,id:e.id,source:xT(e.source),metadata:e.metadata}}}},CT=new Set([`activity`]),wT=new Set([`user`,`tool`]),TT=new Set([`developer`,`system`,`assistant`,`user`,`tool`,`activity`,`reasoning`]),ET=e=>{let t=hT(e)??{},n={...t},r=typeof t.role==`string`?t.role:``,i=TT.has(r),a=i?wT.has(r):gT(t.contentParts).length>0,o=i?CT.has(r):!a&&t.activityContent!==void 0;if(!i&&(t.content===void 0?0:1)+ +(gT(t.contentParts).length>0)+(t.activityContent===void 0?0:1)>1)throw Error(`Invalid event: message carries more than one content form`);if(i){if(!a&&gT(t.contentParts).length>0)throw Error(`Invalid event: message carries content parts for a role that has none`);if(t.activityContent!==void 0&&!o)throw Error(`Invalid event: message carries activity content for a non-activity role`);if(o&&t.content!==void 0)throw Error(`Invalid event: activity content cannot ride with other content forms`);if(a&&t.content!==void 0&&gT(t.contentParts).length>0)throw Error(`Invalid event: message carries both string content and content parts`)}return a&&t.content===void 0&&(n.content=gT(t.contentParts).map(e=>{let t=ST(e);return t===void 0&&vT(),t}).filter(e=>e!==void 0)),o&&t.activityContent!==void 0&&(n.content=t.activityContent),delete n.activityContent,delete n.contentParts,gT(t.toolCalls).length===0&&delete n.toolCalls,Object.keys(n).forEach(e=>{n[e]===void 0&&delete n[e]}),n},DT=e=>{if(Array.isArray(e)){for(let t of e)DT(t);return}let t=hT(e);if(t)for(let e of Object.keys(t))t[e]===void 0?delete t[e]:DT(t[e])},OT=e=>{let t=hT(e);if(!t)return;let n={};return t.threadId!==void 0&&(n.threadId=t.threadId),t.runId!==void 0&&(n.runId=t.runId),t.protocolVersion!==void 0&&(n.protocolVersion=t.protocolVersion),t.parentRunId!==void 0&&(n.parentRunId=t.parentRunId),t.state!==void 0&&(n.state=t.state),n.messages=gT(t.messages).map(ET).filter(e=>e!==void 0),n.tools=gT(t.tools),n.context=gT(t.context),t.forwardedProps!==void 0&&(n.forwardedProps=t.forwardedProps),n.resume=gT(t.resume),n},kT={TextMessageStartEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},BaseEvent:{singular:new Set([3,4]),descend:{},google:{3:`google.protobuf.Value`,4:`google.protobuf.Struct`}},TextMessageContentEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},TextMessageEndEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ToolCallStartEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ToolCallArgsEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ToolCallEndEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},StateSnapshotEvent:{singular:new Set([1,2]),descend:{1:`BaseEvent`},google:{2:`google.protobuf.Value`}},StateDeltaEvent:{singular:new Set([1]),descend:{1:`BaseEvent`,2:`JsonPatchOperation`}},JsonPatchOperation:{singular:new Set([4]),descend:{},google:{4:`google.protobuf.Value`}},MessagesSnapshotEvent:{singular:new Set([1]),descend:{1:`BaseEvent`,2:`Message`}},Message:{singular:new Set([9,13]),descend:{5:`ToolCall`,8:`InputContent`},google:{9:`google.protobuf.Struct`,13:`google.protobuf.Struct`}},ToolCall:{singular:new Set([3,4]),descend:{},google:{4:`google.protobuf.Struct`}},InputContent:{singular:new Set([1,2,3,4,5]),descend:{1:`TextInputPart`,2:`ImageInputPart`,3:`AudioInputPart`,4:`VideoInputPart`,5:`DocumentInputPart`},arms:new Set([1,2,3,4,5])},TextInputPart:{singular:new Set([3]),descend:{},google:{3:`google.protobuf.Value`}},ImageInputPart:{singular:new Set([1,2]),descend:{1:`InputContentSource`},google:{2:`google.protobuf.Value`}},InputContentSource:{singular:new Set([1,2,3]),descend:{},arms:new Set([1,2,3])},AudioInputPart:{singular:new Set([1,2]),descend:{1:`InputContentSource`},google:{2:`google.protobuf.Value`}},VideoInputPart:{singular:new Set([1,2]),descend:{1:`InputContentSource`},google:{2:`google.protobuf.Value`}},DocumentInputPart:{singular:new Set([1,2]),descend:{1:`InputContentSource`},google:{2:`google.protobuf.Value`}},RawEvent:{singular:new Set([1,2]),descend:{1:`BaseEvent`},google:{2:`google.protobuf.Value`}},CustomEvent:{singular:new Set([1,3]),descend:{1:`BaseEvent`},google:{3:`google.protobuf.Value`}},RunStartedEvent:{singular:new Set([1,5]),descend:{1:`BaseEvent`,5:`RunAgentInput`}},RunAgentInput:{singular:new Set([4,8]),descend:{5:`Message`,6:`Tool`,9:`ResumeEntry`},google:{4:`google.protobuf.Value`,8:`google.protobuf.Value`}},Tool:{singular:new Set([3,4]),descend:{},google:{3:`google.protobuf.Value`,4:`google.protobuf.Struct`}},ResumeEntry:{singular:new Set([3,4]),descend:{},google:{3:`google.protobuf.Value`,4:`google.protobuf.Struct`}},RunFinishedEvent:{singular:new Set([1,4]),descend:{1:`BaseEvent`,6:`Interrupt`},google:{4:`google.protobuf.Value`}},Interrupt:{singular:new Set([5,7]),descend:{},google:{5:`google.protobuf.Value`,7:`google.protobuf.Value`}},RunErrorEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},StepStartedEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},StepFinishedEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},TextMessageChunkEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ToolCallChunkEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},SubagentStartedEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},SubagentFinishedEvent:{singular:new Set([1,3]),descend:{1:`BaseEvent`},google:{3:`google.protobuf.Value`}},SubagentErrorEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ToolCallResultEvent:{singular:new Set([1]),descend:{1:`BaseEvent`,7:`InputContent`}},ActivitySnapshotEvent:{singular:new Set([1,5]),descend:{1:`BaseEvent`},google:{5:`google.protobuf.Struct`}},ActivityDeltaEvent:{singular:new Set([1]),descend:{1:`BaseEvent`,5:`JsonPatchOperation`}},ReasoningStartEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningMessageStartEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningMessageContentEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningMessageEndEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningMessageChunkEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningEndEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningEncryptedValueEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},"google.protobuf.Struct":{singular:new Set,descend:{1:`google.protobuf.Struct.FieldsEntry`}},"google.protobuf.Struct.FieldsEntry":{singular:new Set([2]),descend:{2:`google.protobuf.Value`}},"google.protobuf.Value":{singular:new Set([5,6]),descend:{5:`google.protobuf.Struct`,6:`google.protobuf.ListValue`},arms:new Set([1,2,3,4,5,6]),armWireTypes:{1:0,2:1,3:2,4:0,5:2,6:2}},"google.protobuf.ListValue":{singular:new Set,descend:{1:`google.protobuf.Value`}}},AT={1:`TextMessageStartEvent`,2:`TextMessageContentEvent`,3:`TextMessageEndEvent`,4:`ToolCallStartEvent`,5:`ToolCallArgsEvent`,6:`ToolCallEndEvent`,7:`StateSnapshotEvent`,8:`StateDeltaEvent`,9:`MessagesSnapshotEvent`,10:`RawEvent`,11:`CustomEvent`,12:`RunStartedEvent`,13:`RunFinishedEvent`,14:`RunErrorEvent`,15:`StepStartedEvent`,16:`StepFinishedEvent`,17:`TextMessageChunkEvent`,18:`ToolCallChunkEvent`,19:`SubagentStartedEvent`,20:`SubagentFinishedEvent`,21:`SubagentErrorEvent`,22:`ToolCallResultEvent`,23:`ActivitySnapshotEvent`,24:`ActivityDeltaEvent`,25:`ReasoningStartEvent`,26:`ReasoningMessageStartEvent`,27:`ReasoningMessageContentEvent`,28:`ReasoningMessageEndEvent`,29:`ReasoningMessageChunkEvent`,30:`ReasoningEndEvent`,31:`ReasoningEncryptedValueEvent`};function jT(e,t){let n=0,r=0;for(;;){if(t.offset>=e.length)throw Error(`Invalid event`);let i=e[t.offset++];if(r<28?n+=(i&127)*2**r:r===28&&(n+=(i&15)*2**28),r+=7,!(i&128))return n}}function MT(e,t){let n={offset:0},r=0,i=0;for(;n.offsete.length)throw Error(`Invalid event`);if(r===0){if(t.arms?.has(o)){if(i!==0&&i!==o)throw Error(`Invalid event`);i=o}let r=t.descend[o];if(r!==void 0){let t=kT[r];t!==void 0&&MT(e.subarray(n.offset,n.offset+a),t)}}n.offset+=a}else if(s===5)n.offset+=4;else throw Error(`Invalid event`);if(n.offset>e.length)throw Error(`Invalid event`)}if(r!==0)throw Error(`Invalid event`)}function NT(e){let t=new Set,n={offset:0},r=0;for(;n.offset0&&!t.has(a))throw Error(`Invalid event`);t.add(a)}if(o===0)jT(e,n);else if(o===1)n.offset+=8;else if(o===2){let t=jT(e,n);if(n.offset+t>e.length)throw Error(`Invalid event`);if(r===0){let r=AT[a];if(r!==void 0){let i=kT[r];i!==void 0&&MT(e.subarray(n.offset,n.offset+t),i)}}n.offset+=t}else if(o===5)n.offset+=4;else throw Error(`Invalid event`);if(n.offset>e.length)throw Error(`Invalid event`)}if(r!==0)throw Error(`Invalid event`)}function PT(e){if(e.length===1)return e[0];let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function FT(e,t){let n=new X(e),r=[],i=new Map,a,o=!1;for(;n.pos1||n!==t){s.push(new Y().uint32(e.number*8+2).bytes(n).finish()),o=!0;continue}}s.push(e.raw)}return o?PT(s):e}var IT=class extends Error{constructor(e=`Unknown event type`){super(e),this.name=`AGUIUnknownEventTypeError`}};function LT(e,t,n,r){let i=0,a=0,o=0;for(;;){if(t.offset>=e.length||o>=n)return-1;let s=e[t.offset++];if(o+=1,o===n&&s>r)return-1;if(i+=(s&127)*2**a,a+=7,!(s&128))return i}}var RT=(e,t)=>LT(e,t,5,15),zT=(e,t)=>LT(e,t,10,1);function BT(e){let t={offset:0},n=[];for(;t.offsete.length)return!1;t.offset+=n}else return!1;if(t.offset>e.length)return!1}return n.length===0}function VT(e){let t={offset:0},n=[],r=0;for(;t.offsete.length)return!1;if(s){if(bT.has(a)||!BT(e.subarray(t.offset,t.offset+n)))return!1;r+=1}t.offset+=n}else return!1;if(t.offset>e.length)return!1}return n.length===0&&r>0}function HT(e){NT(e);let t=dT.decode(FT(e,{singular:bT,descend:AT})),n=Object.entries(t).filter(([,e])=>e!==void 0);if(n.length!==1)throw n.length===0&&VT(e)?new IT:Error(`Invalid event`);let r=n[0],i=yT[r[0]];if(i===void 0)throw Error(`Invalid event`);let a=r[1],o=hT(a.baseEvent);if(!o)throw Error(`Invalid event`);let s=ew[o.type];if(s!==i)throw Error(`Invalid event: envelope carries `+i+` but the base event declares `+String(s));if(a.type=i,a.timestamp=o.timestamp,a.rawEvent=o.rawEvent,o.metadata!==void 0&&(a.metadata=o.metadata),delete a.baseEvent,a.type===`MESSAGES_SNAPSHOT`&&Array.isArray(a.messages)&&(a.messages=a.messages.map(ET).filter(e=>e!==void 0)),a.type===`RUN_FINISHED`){let e=a,t=typeof e.outcome==`string`&&e.outcome!==``?e.outcome:void 0,n={};n.pendingToolCallIds=e.pendingToolCallIds,delete e.pendingToolCallIds,n.interrupts=e.interrupts,delete e.interrupts,delete e.outcome,t===void 0&&(gT(n.pendingToolCallIds).length>0&&(e.pendingToolCallIds=n.pendingToolCallIds),gT(n.interrupts).length>0&&(e.interrupts=n.interrupts)),t===`success`&&(e.outcome={type:`success`,...gT(n.pendingToolCallIds).length>0?{pendingToolCallIds:n.pendingToolCallIds}:{},...gT(n.interrupts).length>0?{interrupts:n.interrupts}:{}}),t===`interrupt`&&(e.outcome={type:`interrupt`,interrupts:gT(n.interrupts),...gT(n.pendingToolCallIds).length>0?{pendingToolCallIds:n.pendingToolCallIds}:{}}),t===`cancelled`&&(e.outcome={type:`cancelled`,...gT(n.pendingToolCallIds).length>0?{pendingToolCallIds:n.pendingToolCallIds}:{},...gT(n.interrupts).length>0?{interrupts:n.interrupts}:{}}),t!==void 0&&![`success`,`interrupt`,`cancelled`].includes(t)&&(e.outcome={type:t,...gT(n.pendingToolCallIds).length>0?{pendingToolCallIds:n.pendingToolCallIds}:{},...gT(n.interrupts).length>0?{interrupts:n.interrupts}:{}})}if(a.type===`SUBAGENT_FINISHED`){let e=a,t=typeof e.outcome==`string`&&e.outcome!==``?e.outcome:void 0,n={};n.interruptIds=e.interruptIds,delete e.interruptIds,delete e.outcome,t===void 0&&gT(n.interruptIds).length>0&&(e.interruptIds=n.interruptIds),t===`success`&&(e.outcome={type:`success`,...gT(n.interruptIds).length>0?{interruptIds:n.interruptIds}:{}}),t===`suspended`&&(e.outcome={type:`suspended`,...gT(n.interruptIds).length>0?{interruptIds:n.interruptIds}:{}}),t!==void 0&&![`success`,`suspended`].includes(t)&&(e.outcome={type:t,...gT(n.interruptIds).length>0?{interruptIds:n.interruptIds}:{}})}if(a.type===`STATE_DELTA`&&Array.isArray(a.delta)&&(a.delta=a.delta.map(e=>{let t=hC[e.op];return e.op=typeof t==`string`&&t!==`UNRECOGNIZED`?t.toLowerCase():String(e.op),Object.keys(e).forEach(t=>{e[t]===void 0&&delete e[t]}),e})),a.type===`ACTIVITY_DELTA`&&Array.isArray(a.patch)&&(a.patch=a.patch.map(e=>{let t=hC[e.op];return e.op=typeof t==`string`&&t!==`UNRECOGNIZED`?t.toLowerCase():String(e.op),Object.keys(e).forEach(t=>{e[t]===void 0&&delete e[t]}),e})),a.type===`RUN_FINISHED`&&Array.isArray(a.usage)&&a.usage.length===0&&delete a.usage,a.type===`RUN_ERROR`&&Array.isArray(a.usage)&&a.usage.length===0&&delete a.usage,a.type===`TOOL_CALL_RESULT`){let e=a;if(e.content!==void 0&&gT(e.contentParts).length>0)throw Error(`Invalid event: content carries both string content and content parts`);e.content===void 0&&(e.content=gT(e.contentParts).map(e=>{let t=ST(e);return t===void 0&&vT(),t}).filter(e=>e!==void 0)),delete e.contentParts}return a.type===`RUN_STARTED`&&a.input!==void 0&&(a.input=OT(a.input)),DT(a),a}var UT=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,WT=e=>{if(typeof e!=`string`)throw TypeError(`Invalid argument expected string`);let t=e.match(UT);if(!t)throw Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},GT=e=>e===`*`||e===`x`||e===`X`,KT=e=>{let t=parseInt(e,10);return isNaN(t)?e:t},qT=(e,t)=>typeof e==typeof t?[e,t]:[String(e),String(t)],JT=(e,t)=>{if(GT(e)||GT(t))return 0;let[n,r]=qT(KT(e),KT(t));return n>r?1:n{for(let n=0;n{let n=WT(e),r=WT(t),i=n.pop(),a=r.pop(),o=YT(n,r);return o===0?i&&a?YT(i.split(`.`),a.split(`.`)):i||a?i?-1:1:0:o},ZT=e=>typeof e==`string`&&/^[v\d]/.test(e)&&UT.test(e);Object.freeze({status:`aborted`});function $(e,t,n){function r(n,r){var i;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var QT=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},$T={};function eE(e){return e&&Object.assign($T,e),$T}function tE(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function nE(e,t){return typeof t==`bigint`?t.toString():t}function rE(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function iE(e){return e==null}function aE(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function oE(e,t,n){Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function sE(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function cE(e){return JSON.stringify(e)}var lE=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function uE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var dE=rE(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function fE(e){if(uE(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return uE(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}var pE=new Set([`string`,`number`,`symbol`]);function mE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function hE(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function gE(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function _E(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}function vE(e,t){let n={},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(n[e]=r.shape[e])}return hE(e,{...e._zod.def,shape:n,checks:[]})}function yE(e,t){let n={...e._zod.def.shape},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return hE(e,{...e._zod.def,shape:n,checks:[]})}function bE(e,t){if(!fE(t))throw Error(`Invalid input to extend: expected a plain object`);return hE(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return sE(this,`shape`,n),n},checks:[]})}function xE(e,t){return hE(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return sE(this,`shape`,n),n},catchall:t._zod.def.catchall,checks:[]})}function SE(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return hE(t,{...t._zod.def,shape:i,checks:[]})}function CE(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return hE(t,{...t._zod.def,shape:i,checks:[]})}function wE(e,t=0){for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function EE(e){return typeof e==`string`?e:e?.message}function DE(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=EE(e.inst?._zod.def?.error?.(e))??EE(t?.error?.(e))??EE(n.customError?.(e))??EE(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function OE(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function kE(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var AE=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,nE,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},jE=$(`$ZodError`,AE),ME=$(`$ZodError`,AE,{Parent:Error});function NE(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function PE(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new QT;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>DE(e,a,eE())));throw lE(t,i?.callee),t}return o.value},IE=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>DE(e,a,eE())));throw lE(t,i?.callee),t}return o.value},LE=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new QT;return a.issues.length?{success:!1,error:new(e??jE)(a.issues.map(e=>DE(e,i,eE())))}:{success:!0,data:a.value}},RE=LE(ME),zE=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>DE(e,i,eE())))}:{success:!0,data:a.value}},BE=zE(ME),VE=$(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),HE=$(`$ZodCheckMaxLength`,(e,t)=>{var n;VE.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!iE(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=OE(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),UE=$(`$ZodCheckMinLength`,(e,t)=>{var n;VE.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!iE(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=OE(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),WE=$(`$ZodCheckLengthEquals`,(e,t)=>{var n;VE.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!iE(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=OE(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),GE=$(`$ZodCheckOverwrite`,(e,t)=>{VE.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),KE=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` -`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(` -`))}},qE={major:4,minor:0,patch:0},JE=$(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=qE;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=wE(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new QT;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=wE(e,t))});else{if(e.issues.length===t)continue;r||=wE(e,t)}}return i?i.then(()=>e):e};e._zod.run=(n,i)=>{let a=e._zod.parse(n,i);if(a instanceof Promise){if(i.async===!1)throw new QT;return a.then(e=>t(e,r,i))}return t(a,r,i)}}e[`~standard`]={validate:t=>{try{let n=RE(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return BE(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),YE=$(`$ZodUnknown`,(e,t)=>{JE.init(e,t),e._zod.parse=e=>e}),XE=$(`$ZodNever`,(e,t)=>{JE.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function ZE(e,t,n){e.issues.length&&t.issues.push(...TE(n,e.issues)),t.value[n]=e.value}var QE=$(`$ZodArray`,(e,t)=>{JE.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;eZE(t,n,e))):ZE(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function $E(e,t,n){e.issues.length&&t.issues.push(...TE(n,e.issues)),t.value[n]=e.value}function eD(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...TE(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}var tD=$(`$ZodObject`,(e,t)=>{JE.init(e,t);let n=rE(()=>{let e=Object.keys(t.shape);for(let n of e)if(!(t.shape[n]instanceof JE))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=_E(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}});oE(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=e=>{let t=new KE([`shape`,`payload`,`ctx`]),r=n.value,i=e=>{let t=cE(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of r.keys)a[e]=`key_${o++}`;t.write(`const newResult = {}`);for(let e of r.keys)if(r.optionalKeys.has(e)){let n=a[e];t.write(`const ${n} = ${i(e)};`);let r=cE(e);t.write(` - if (${n}.issues.length) { - if (input[${r}] === undefined) { - if (${r} in input) { - newResult[${r}] = undefined; - } - } else { - payload.issues = payload.issues.concat( - ${n}.issues.map((iss) => ({ - ...iss, - path: iss.path ? [${r}, ...iss.path] : [${r}], - })) - ); - } - } else if (${n}.value === undefined) { - if (${r} in input) newResult[${r}] = undefined; - } else { - newResult[${r}] = ${n}.value; - } - `)}else{let n=a[e];t.write(`const ${n} = ${i(e)};`),t.write(` - if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${cE(e)}, ...iss.path] : [${cE(e)}] - })));`),t.write(`newResult[${cE(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=uE,o=!$T.jitless,s=o&&dE.value,c=t.catchall,l;e._zod.parse=(u,d)=>{l??=n.value;let f=u.value;if(!a(f))return u.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),u;let p=[];if(o&&s&&d?.async===!1&&d.jitless!==!0)i||=r(t.shape),u=i(u,d);else{u.value={};let e=l.shape;for(let t of l.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?eD(e,u,t,f):$E(e,u,t))):i?eD(r,u,t,f):$E(r,u,t)}}if(!c)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=l.keySet,g=c._zod,_=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(_===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>$E(t,u,e))):$E(t,u,e)}return m.length&&u.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>u):u}});function nD(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>DE(e,r,eE())))}),t}var rD=$(`$ZodUnion`,(e,t)=>{JE.init(e,t),oE(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),oE(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),oE(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),oE(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>aE(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>nD(t,n,e,r)):nD(a,n,e,r)}}),iD=$(`$ZodIntersection`,(e,t)=>{JE.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>oD(e,t,n)):oD(e,i,a)}});function aD(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(fE(e)&&fE(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=aD(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r{JE.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!fE(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...TE(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...TE(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s??=[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>DE(e,r,eE())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...TE(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...TE(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),cD=$(`$ZodEnum`,(e,t)=>{JE.init(e,t);let n=tE(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>pE.has(typeof e)).map(e=>typeof e==`string`?mE(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),lD=$(`$ZodLiteral`,(e,t)=>{JE.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?mE(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),uD=$(`$ZodTransform`,(e,t)=>{JE.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new QT;return e.value=r,e}}),dD=$(`$ZodOptional`,(e,t)=>{JE.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,oE(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),oE(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${aE(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),fD=$(`$ZodNullable`,(e,t)=>{JE.init(e,t),oE(e._zod,`optin`,()=>t.innerType._zod.optin),oE(e._zod,`optout`,()=>t.innerType._zod.optout),oE(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${aE(e.source)}|null)$`):void 0}),oE(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),pD=$(`$ZodDefault`,(e,t)=>{JE.init(e,t),e._zod.optin=`optional`,oE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>mD(e,t)):mD(r,t)}});function mD(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var hD=$(`$ZodPrefault`,(e,t)=>{JE.init(e,t),e._zod.optin=`optional`,oE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),gD=$(`$ZodNonOptional`,(e,t)=>{JE.init(e,t),oE(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>_D(t,e)):_D(i,e)}});function _D(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var vD=$(`$ZodCatch`,(e,t)=>{JE.init(e,t),e._zod.optin=`optional`,oE(e._zod,`optout`,()=>t.innerType._zod.optout),oE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>DE(e,n,eE()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>DE(e,n,eE()))},input:e.value}),e.issues=[]),e)}}),yD=$(`$ZodPipe`,(e,t)=>{JE.init(e,t),oE(e._zod,`values`,()=>t.in._zod.values),oE(e._zod,`optin`,()=>t.in._zod.optin),oE(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>bD(e,t,n)):bD(r,t,n)}});function bD(e,t,n){return wE(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}var xD=$(`$ZodReadonly`,(e,t)=>{JE.init(e,t),oE(e._zod,`propValues`,()=>t.innerType._zod.propValues),oE(e._zod,`values`,()=>t.innerType._zod.values),oE(e._zod,`optin`,()=>t.innerType._zod.optin),oE(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(SD):SD(r)}});function SD(e){return e.value=Object.freeze(e.value),e}var CD=$(`$ZodLazy`,(e,t)=>{JE.init(e,t),oE(e._zod,`innerType`,()=>t.getter()),oE(e._zod,`pattern`,()=>e._zod.innerType._zod.pattern),oE(e._zod,`propValues`,()=>e._zod.innerType._zod.propValues),oE(e._zod,`optin`,()=>e._zod.innerType._zod.optin),oE(e._zod,`optout`,()=>e._zod.innerType._zod.optout),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),wD=$(`$ZodCustom`,(e,t)=>{VE.init(e,t),JE.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>TD(t,n,r,e));TD(i,n,r,e)}});function TD(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(kE(e))}}var ED=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function DD(){return new ED}var OD=DD();function kD(e){return new e({type:`unknown`})}function AD(e,t){return new e({type:`never`,...gE(t)})}function jD(e,t){return new HE({check:`max_length`,...gE(t),maximum:e})}function MD(e,t){return new UE({check:`min_length`,...gE(t),minimum:e})}function ND(e,t){return new WE({check:`length_equals`,...gE(t),length:e})}function PD(e){return new GE({check:`overwrite`,tx:e})}function FD(e,t,n){return new e({type:`array`,element:t,...gE(n)})}function ID(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...gE(n)})}var LD=(e,t)=>{jE.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>PE(e,t)},flatten:{value:t=>NE(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})};$(`ZodError`,LD);var RD=$(`ZodError`,LD,{Parent:Error}),zD=FE(RD),BD=IE(RD),VD=LE(RD),HD=zE(RD),UD=$(`ZodType`,(e,t)=>(JE.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>hE(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>zD(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>VD(e,t,n),e.parseAsync=async(t,n)=>BD(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>HD(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(EO(t,n)),e.superRefine=t=>e.check(DO(t)),e.overwrite=t=>e.check(PD(t)),e.optional=()=>cO(e),e.nullable=()=>uO(e),e.nullish=()=>cO(uO(e)),e.nonoptional=t=>gO(e,t),e.array=()=>YD(e),e.or=t=>QD([e,t]),e.and=t=>eO(e,t),e.transform=t=>bO(e,oO(t)),e.default=t=>fO(e,t),e.prefault=t=>mO(e,t),e.catch=t=>vO(e,t),e.pipe=t=>bO(e,t),e.readonly=()=>SO(e),e.describe=t=>{let n=e.clone();return OD.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return OD.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return OD.get(e);let n=e.clone();return OD.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),WD=$(`ZodUnknown`,(e,t)=>{YE.init(e,t),UD.init(e,t)});function GD(){return kD(WD)}var KD=$(`ZodNever`,(e,t)=>{XE.init(e,t),UD.init(e,t)});function qD(e){return AD(KD,e)}var JD=$(`ZodArray`,(e,t)=>{QE.init(e,t),UD.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(MD(t,n)),e.nonempty=t=>e.check(MD(1,t)),e.max=(t,n)=>e.check(jD(t,n)),e.length=(t,n)=>e.check(ND(t,n)),e.unwrap=()=>e.element});function YD(e,t){return FD(JD,e,t)}var XD=$(`ZodObject`,(e,t)=>{tD.init(e,t),UD.init(e,t),oE(e,`shape`,()=>t.shape),e.keyof=()=>rO(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:GD()}),e.loose=()=>e.clone({...e._zod.def,catchall:GD()}),e.strict=()=>e.clone({...e._zod.def,catchall:qD()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>bE(e,t),e.merge=t=>xE(e,t),e.pick=t=>vE(e,t),e.omit=t=>yE(e,t),e.partial=(...t)=>SE(sO,e,t[0]),e.required=(...t)=>CE(hO,e,t[0])}),ZD=$(`ZodUnion`,(e,t)=>{rD.init(e,t),UD.init(e,t),e.options=t.options});function QD(e,t){return new ZD({type:`union`,options:e,...gE(t)})}var $D=$(`ZodIntersection`,(e,t)=>{iD.init(e,t),UD.init(e,t)});function eO(e,t){return new $D({type:`intersection`,left:e,right:t})}var tO=$(`ZodRecord`,(e,t)=>{sD.init(e,t),UD.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}),nO=$(`ZodEnum`,(e,t)=>{cD.init(e,t),UD.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new nO({...t,checks:[],...gE(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new nO({...t,checks:[],...gE(r),entries:i})}});function rO(e,t){return new nO({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...gE(t)})}var iO=$(`ZodLiteral`,(e,t)=>{lD.init(e,t),UD.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})}),aO=$(`ZodTransform`,(e,t)=>{uD.init(e,t),UD.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(kE(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,t.continue??=!0,n.issues.push(kE(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function oO(e){return new aO({type:`transform`,transform:e})}var sO=$(`ZodOptional`,(e,t)=>{dD.init(e,t),UD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function cO(e){return new sO({type:`optional`,innerType:e})}var lO=$(`ZodNullable`,(e,t)=>{fD.init(e,t),UD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function uO(e){return new lO({type:`nullable`,innerType:e})}var dO=$(`ZodDefault`,(e,t)=>{pD.init(e,t),UD.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function fO(e,t){return new dO({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}var pO=$(`ZodPrefault`,(e,t)=>{hD.init(e,t),UD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function mO(e,t){return new pO({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}var hO=$(`ZodNonOptional`,(e,t)=>{gD.init(e,t),UD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function gO(e,t){return new hO({type:`nonoptional`,innerType:e,...gE(t)})}var _O=$(`ZodCatch`,(e,t)=>{vD.init(e,t),UD.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function vO(e,t){return new _O({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var yO=$(`ZodPipe`,(e,t)=>{yD.init(e,t),UD.init(e,t),e.in=t.in,e.out=t.out});function bO(e,t){return new yO({type:`pipe`,in:e,out:t})}var xO=$(`ZodReadonly`,(e,t)=>{xD.init(e,t),UD.init(e,t)});function SO(e){return new xO({type:`readonly`,innerType:e})}var CO=$(`ZodLazy`,(e,t)=>{CD.init(e,t),UD.init(e,t),e.unwrap=()=>e._zod.def.getter()}),wO=$(`ZodCustom`,(e,t)=>{wD.init(e,t),UD.init(e,t)});function TO(e){let t=new VE({check:`custom`});return t._zod.check=e,t}function EO(e,t={}){return ID(wO,e,t)}function DO(e){let t=TO(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(kE(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(kE(r))}},e(n.value,n)));return t}var OO=`@ag-ui/client`;function kO(e){if(!e.metadata||!Object.prototype.hasOwnProperty.call(e.metadata,OO))return;let t=e.metadata?.[OO];if(!t||typeof t!=`object`||Array.isArray(t))return[];if(!Object.prototype.hasOwnProperty.call(t,`authoritativeActivityTypes`))return;let n=t.authoritativeActivityTypes;return n===null?null:Array.isArray(n)&&n.every(e=>typeof e==`string`)?n:[]}var AO=e=>{if(typeof structuredClone==`function`)return structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch{return Array.isArray(e)?[...e]:{...e}}};function jO(){return Qc()}function MO(e){return e instanceof TypeError&&/read[- ]?only|not extensible|cannot add property|cannot delete property|can't be deleted|unable to delete property|object is frozen|is not writable/i.test(e.message)}function NO(e){if(Object.freeze(e),typeof e==`object`&&e)for(let t of Object.values(e))typeof t==`object`&&t&&!Object.isFrozen(t)&&NO(t);return e}var PO=524288;function FO(e,t,n){let r=0,i=[e,t],a=new WeakSet;for(;i.length>0;){let e=i.pop();if(typeof e==`string`){if(r+=e.length,r>n)return!0}else if(typeof e==`object`&&e){if(a.has(e))continue;if(a.add(e),Array.isArray(e))for(let t=0;tn)return!0;i.push(e[o])}}}}return!1}async function IO(e,t,n,r){let i=typeof process<`u`&&!0,a=i&&!!{}.VITEST_WORKER_ID,o=i&&!!{}.VITEST_WORKER_ID,s=o&&!FO(t,n,PO),c=s?AO(t):t,l=s?AO(n):n,u=!1,d=!1,f;for(let t of e)try{s&&(NO(c),NO(l));let e=await r(t,c,l);if(e===void 0)continue;let n=!1;if(e.messages!==void 0&&e.messages!==c&&(c=AO(e.messages),u=!0,n=!0),e.state!==void 0&&e.state!==l&&(l=AO(e.state),d=!0,n=!0),s&&n&&FO(c,l,PO)&&(s=!1),f=e.stopPropagation,f===!0)break}catch(e){if(a&&e instanceof TypeError)throw e;s&&o&&MO(e)?console.error(`AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.`,e):console.error(`Subscriber error:`,e);continue}return{...u?{messages:Object.isFrozen(c)?AO(c):c}:{},...d?{state:Object.isFrozen(l)?AO(l):l}:{},...f===void 0?{}:{stopPropagation:f}}}function LO(e){if(!e)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(e===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let t=e.events??!0,n=e.lifecycle??!0,r=e.verbose??!1;return{enabled:t||n,events:t,lifecycle:n,verbose:r}}function RO(e){if(e instanceof zO)return e;if(e===!0)return new zO(LO(!0))}var zO=class{constructor(e){this.config=e}event(e,t,n,r){this.config.events&&(this.config.verbose?console.debug(`[${e}] ${t}`,typeof n==`string`?n:JSON.stringify(n)):console.debug(`[${e}] ${t}`,r??n))}lifecycle(e,t,n){this.config.lifecycle&&(n?console.debug(`[${e}] ${t}`,n):console.debug(`[${e}] ${t}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function BO(e){return e.enabled?new zO(e):void 0}function VO(e,t,n){if(t){let r=e.find(e=>e.id===t);if(r?.role===`assistant`)return r;r&&console.warn(`TOOL_CALL_START: parentMessageId '${t}' matches a '${r.role}' message, not assistant — falling back to toolCallId`);let i={id:r?n:t,role:`assistant`,toolCalls:[]};return e.push(i),i}let r={id:n,role:`assistant`,toolCalls:[]};return e.push(r),r}function HO(e,t){return!e||t.metadata===void 0?!1:(e.metadata=il(e.metadata,AO(t.metadata)),!0)}var UO=(e,t,n,r,i)=>{let a=RO(i),o=AO(n.messages),s=AO(e.state),c={},l=[],u=new Set,d=e=>{let t=e.outcome?.type===`success`?e.outcome.pendingToolCallIds:void 0;return t!==void 0&&t.length>0?[...t]:l.filter(e=>!u.has(e))},f=e=>{e.messages!==void 0&&(o=e.messages,c.messages=e.messages),e.state!==void 0&&(s=e.state,c.state=e.state)},p=()=>{let e=AO(c);return c={},e.messages!==void 0||e.state!==void 0?Sd(e):Wu};return t.pipe(Nd(async t=>{let i=await IO(r,o,s,(r,i,a)=>r.onEvent?.({event:t,agent:n,input:e,messages:i,state:a}));if(f(i),i.stopPropagation===!0?a?.event(`APPLY`,`Event dropped:`,t,{type:t.type,reason:`stopPropagation by subscriber`}):a?.event(`APPLY`,`Event applied:`,t,{type:t.type,subscribers:r.length}),i.stopPropagation===!0)return p();switch(t.type){case I.TEXT_MESSAGE_START:{let i=await IO(r,o,s,(r,i,a)=>r.onTextMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{messageId:e,role:n=`assistant`,name:r,subagentRunId:i}=t,a=o.find(t=>t.id===e);if(a?.role===`activity`)return console.warn(`TEXT_MESSAGE_START: Message '${e}' is an activity message — message ids must be unique across activity and text messages`),p();let s=a;if(!s){let t={id:e,role:n,content:``,...r!==void 0&&{name:r},...i!=null&&{subagentRunId:i}};o.push(t),s=t}let c=HO(s,t);(!a||c)&&f({messages:o})}return p()}case I.TEXT_MESSAGE_CONTENT:{let{messageId:i,delta:a}=t,c=o.find(e=>e.id===i);if(!c)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${i}'`),p();if(c.role===`activity`)return console.warn(`TEXT_MESSAGE_CONTENT: Message '${i}' is an activity message — message ids must be unique across activity and text messages`),p();let l=await IO(r,o,s,(r,i,a)=>r.onTextMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,textMessageBuffer:typeof c.content==`string`?c.content:``}));return f(l),l.stopPropagation!==!0&&(c.content=`${typeof c.content==`string`?c.content:``}${a}`,HO(c,t),f({messages:o})),p()}case I.TEXT_MESSAGE_END:{let{messageId:i}=t,a=o.find(e=>e.id===i);if(!a)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${i}'`),p();if(a.role===`activity`)return console.warn(`TEXT_MESSAGE_END: Message '${i}' is an activity message — message ids must be unique across activity and text messages`),p();let c=await IO(r,o,s,(r,i,o)=>r.onTextMessageEndEvent?.({event:t,messages:i,state:o,agent:n,input:e,textMessageBuffer:typeof a.content==`string`?a.content:``}));return f(c),c.stopPropagation!==!0&&HO(a,t)&&f({messages:o}),await Promise.all(r.map(t=>{t.onNewMessage?.({message:a,messages:o,state:s,agent:n,input:e})})),p()}case I.TOOL_CALL_START:{let i=await IO(r,o,s,(r,i,a)=>r.onToolCallStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{toolCallId:e,toolCallName:n,parentMessageId:r,subagentRunId:i}=t;l.includes(e)||l.push(e);let a=o.find(t=>t.toolCalls?.some(t=>t.id===e))?.toolCalls?.find(t=>t.id===e);if(a){let r=a.function.name!==n;return r&&(console.warn(`TOOL_CALL_START: tool call '${e}' already exists with name '${a.function.name}' — updating it to '${n}'`),a.function.name=n),(HO(a,t)||r)&&f({messages:o}),p()}let s=new Set(o.map(e=>e.id)),c=VO(o,r,e);!s.has(c.id)&&i!=null&&c.subagentRunId===void 0&&(c.subagentRunId=i),c.toolCalls??=[];let u={id:e,type:`function`,function:{name:n,arguments:``}};c.toolCalls.push(u),HO(u,t),f({messages:o})}return p()}case I.TOOL_CALL_ARGS:{let{toolCallId:i,delta:a}=t,c=o.find(e=>e.toolCalls?.some(e=>e.id===i));if(!c)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${i}'`),p();let l=c.toolCalls?.find(e=>e.id===i);if(!l)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${i}'`),p();let u=await IO(r,o,s,(r,i,a)=>{let o=l.function.arguments,s=l.function.name,c={};try{c=Hd(o)}catch{}return r.onToolCallArgsEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallBuffer:o,toolCallName:s,partialToolCallArgs:c})});return f(u),u.stopPropagation!==!0&&(l.function.arguments+=a,HO(l,t),f({messages:o})),p()}case I.TOOL_CALL_END:{let{toolCallId:i}=t,a=o.find(e=>e.toolCalls?.some(e=>e.id===i));if(!a)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${i}'`),p();let c=a.toolCalls?.find(e=>e.id===i);if(!c)return console.warn(`TOOL_CALL_END: No tool call found with ID '${i}'`),p();let l=await IO(r,o,s,(r,i,a)=>{let o=c.function.arguments,s=c.function.name,l={};try{l=JSON.parse(o)}catch{}return r.onToolCallEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallName:s,toolCallArgs:l})});return f(l),l.stopPropagation!==!0&&HO(c,t)&&f({messages:o}),await Promise.all(r.map(t=>{t.onNewToolCall?.({toolCall:c,messages:o,state:s,agent:n,input:e})})),p()}case I.TOOL_CALL_RESULT:{let i=await IO(r,o,s,(r,i,a)=>r.onToolCallResultEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{messageId:i,toolCallId:a,content:c,role:l,subagentRunId:d}=t;u.add(a);let p={id:i,toolCallId:a,role:l||`tool`,content:c,...d!=null&&{subagentRunId:d}};HO(p,t);let m=o.findIndex(e=>e.role===`assistant`&&e.toolCalls?.some(e=>e.id===a));if(m===-1)o.push(p);else{let e=m+1;for(;e{t.onNewMessage?.({message:p,messages:o,state:s,agent:n,input:e})})),f({messages:o})}return p()}case I.STATE_SNAPSHOT:{let i=await IO(r,o,s,(r,i,a)=>r.onStateSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{snapshot:e}=t;s=e,f({state:s})}return p()}case I.STATE_DELTA:{let i=await IO(r,o,s,(r,i,a)=>r.onStateDeltaEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{delta:e}=t;try{s=Hl.applyPatch(s,e,!0,!1).newDocument,f({state:s})}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Failed to apply state patch:\nCurrent state: ${JSON.stringify(s,null,2)}\nPatch operations: ${JSON.stringify(e,null,2)}\nError: ${n}`)}}return p()}case I.MESSAGES_SNAPSHOT:{let i=await IO(r,o,s,(r,i,a)=>r.onMessagesSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{messages:e}=t,n=e.map(e=>{if(e.subagentRunId!==null)return e;let t={...e};return delete t.subagentRunId,t}),r=new Map(n.map(e=>[e.id,e])),i=kO(t),a=n.some(e=>e.role===`activity`),s=n.some(e=>e.role===`reasoning`),c=e=>e.role===`activity`&&(i?!i.includes(e.activityType):i!==null&&!a)||e.role===`reasoning`&&!s;o=o.filter(e=>r.has(e.id)||c(e)).map(e=>r.get(e.id)??e);let l=new Set(o.map(e=>e.id));for(let e of n)l.has(e.id)||o.push(e);f({messages:o})}return p()}case I.ACTIVITY_SNAPSHOT:{let i=t,a=o.findIndex(e=>e.id===i.messageId),c=a>=0?o[a]:void 0,l=c?.role===`activity`?c:void 0,u=i.replace??!0,d=await IO(r,o,s,(t,r,a)=>t.onActivitySnapshotEvent?.({event:i,messages:r,state:a,agent:n,input:e,activityMessage:l,existingMessage:c}));if(f(d),d.stopPropagation!==!0){let t={id:i.messageId,role:`activity`,activityType:i.activityType,content:AO(i.content),...i.subagentRunId!=null&&{subagentRunId:i.subagentRunId}},c,d;a===-1?(o.push(t),c=t,d=t):l?(u&&(o[a]={...l,activityType:i.activityType,content:AO(i.content),subagentRunId:i.subagentRunId},i.subagentRunId??delete o[a].subagentRunId),d=o[a]):u&&(o[a]=t,c=t,d=t),HO(d,i),f({messages:o}),c&&await Promise.all(r.map(t=>t.onNewMessage?.({message:c,messages:o,state:s,agent:n,input:e})))}return p()}case I.ACTIVITY_DELTA:{let i=t,a=o.findIndex(e=>e.id===i.messageId);if(a===-1)return p();let c=o[a];if(c.role!==`activity`)return console.warn(`ACTIVITY_DELTA: Message '${i.messageId}' is not an activity message`),p();let l=c,u=await IO(r,o,s,(t,r,a)=>t.onActivityDeltaEvent?.({event:i,messages:r,state:a,agent:n,input:e,activityMessage:l}));if(f(u),u.stopPropagation!==!0)try{HO(l,i)&&f({messages:o});let e=AO(l.content??{}),t=Hl.applyPatch(e,i.patch??[],!0,!1).newDocument;o[a]={...l,content:AO(t),activityType:i.activityType},f({messages:o})}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`Failed to apply activity patch for '${i.messageId}': ${t}`)}return p()}case I.RAW:return f(await IO(r,o,s,(r,i,a)=>r.onRawEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case I.CUSTOM:return f(await IO(r,o,s,(r,i,a)=>r.onCustomEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case I.RUN_STARTED:{let i=await IO(r,o,s,(r,i,a)=>r.onRunStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),l=[],u=new Set,i.stopPropagation!==!0){let e=t;if(e.input?.messages){for(let t of e.input.messages){let e=t;if(t.subagentRunId===null){let n={...t};delete n.subagentRunId,e=n}o.find(t=>t.id===e.id)||o.push(e)}f({messages:o})}}return p()}case I.RUN_FINISHED:{let i=t,a=i.outcome?.type===`interrupt`?{event:i,outcome:`interrupt`,interrupts:i.outcome.interrupts}:i.outcome?.type===`cancelled`?{event:i,outcome:`cancelled`}:{event:i,outcome:`success`,result:i.result,pendingToolCallIds:d(i)},c=await IO(r,o,s,(t,r,i)=>t.onRunFinishedEvent?.({...a,messages:r,state:i,agent:n,input:e}));return f(c),c.stopPropagation!==!0&&(n.pendingInterrupts=a.outcome===`interrupt`?a.interrupts.map(e=>{if(e.subagentRunId!==null)return e;let t={...e};return delete t.subagentRunId,t}):[]),p()}case I.RUN_ERROR:return f(await IO(r,o,s,(r,i,a)=>r.onRunErrorEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case I.STEP_STARTED:return f(await IO(r,o,s,(r,i,a)=>r.onStepStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case I.STEP_FINISHED:return f(await IO(r,o,s,(r,i,a)=>r.onStepFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case I.TEXT_MESSAGE_CHUNK:throw Error(`TEXT_MESSAGE_CHUNK must be transformed before being applied`);case I.TOOL_CALL_CHUNK:throw Error(`TOOL_CALL_CHUNK must be transformed before being applied`);case I.REASONING_START:return f(await IO(r,o,s,(r,i,a)=>r.onReasoningStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case I.REASONING_MESSAGE_START:{let i=await IO(r,o,s,(r,i,a)=>r.onReasoningMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{messageId:e,subagentRunId:n}=t,r=o.find(t=>t.id===e);if(r?.role===`activity`)return console.warn(`REASONING_MESSAGE_START: Message '${e}' is an activity message — message ids must be unique across activity and reasoning messages`),p();let i=r;if(!i){let t={id:e,role:`reasoning`,content:``,...n!=null&&{subagentRunId:n}};o.push(t),i=t}let a=HO(i,t);(!r||a)&&f({messages:o})}return p()}case I.REASONING_MESSAGE_CONTENT:{let{messageId:i,delta:a}=t,c=o.find(e=>e.id===i);if(!c)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${i}'`),p();if(c.role===`activity`)return console.warn(`REASONING_MESSAGE_CONTENT: Message '${i}' is an activity message — message ids must be unique across activity and reasoning messages`),p();let l=await IO(r,o,s,(r,i,a)=>r.onReasoningMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,reasoningMessageBuffer:typeof c.content==`string`?c.content:``}));return f(l),l.stopPropagation!==!0&&(c.content=`${typeof c.content==`string`?c.content:``}${a}`,HO(c,t),f({messages:o})),p()}case I.REASONING_MESSAGE_END:{let{messageId:i}=t,a=o.find(e=>e.id===i);if(!a)return console.warn(`REASONING_MESSAGE_END: No message found with ID '${i}'`),p();if(a.role===`activity`)return console.warn(`REASONING_MESSAGE_END: Message '${i}' is an activity message — message ids must be unique across activity and reasoning messages`),p();let c=await IO(r,o,s,(r,i,o)=>r.onReasoningMessageEndEvent?.({event:t,messages:i,state:o,agent:n,input:e,reasoningMessageBuffer:typeof a.content==`string`?a.content:``}));return f(c),c.stopPropagation!==!0&&HO(a,t)&&f({messages:o}),await Promise.all(r.map(t=>{t.onNewMessage?.({message:a,messages:o,state:s,agent:n,input:e})})),p()}case I.REASONING_MESSAGE_CHUNK:throw Error(`REASONING_MESSAGE_CHUNK must be transformed before being applied`);case I.REASONING_END:return f(await IO(r,o,s,(r,i,a)=>r.onReasoningEndEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case I.REASONING_ENCRYPTED_VALUE:{let{subtype:i,entityId:a,encryptedValue:l}=t,u=await IO(r,o,s,(r,i,a)=>r.onReasoningEncryptedValueEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(u),u.stopPropagation!==!0){let e=!1;if(i===`tool-call`){for(let t of o)if(t.role===`assistant`&&t.toolCalls){let n=t.toolCalls.find(e=>e.id===a);if(n){n.encryptedValue=l,e=!0;break}}}else{let t=o.find(e=>e.id===a);t?.role!==`activity`&&t&&(t.encryptedValue=l,e=!0)}e&&(c.messages=o)}return p()}case I.SUBAGENT_STARTED:return f(await IO(r,o,s,(r,i,a)=>r.onSubagentStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case I.SUBAGENT_FINISHED:return f(await IO(r,o,s,(r,i,a)=>r.onSubagentFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case I.SUBAGENT_ERROR:return f(await IO(r,o,s,(r,i,a)=>r.onSubagentErrorEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p()}return t.type,p()}),Od(),r.length>0?Id({}):e=>e)};function WO(e,t){typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`[ag-ui][compat] Converting deprecated ${e} to ${t}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`)}var GO=e=>t=>{let n=RO(e),r=new Set,i=new Set,a=new Set,o=new Set,s={message:new Map,toolCall:new Map,activity:new Map,reasoning:new Map},c=!1,l=!1,u=!1,d=new Map,f=e=>{let t=d.get(e);return t||(t=new Map,d.set(e,t)),t},p=()=>{for(let e of d.values())if(e.size>0)return!0;return!1},m=new Map,h=new Set,g=!1,_=!1,v=()=>{_=!1,r.clear(),i.clear(),a.clear(),o.clear(),s.message.clear(),s.toolCall.clear(),s.activity.clear(),s.reasoning.clear(),d.clear(),m.clear(),h.clear(),c=!1,l=!1,g=!0},y=(e,t)=>{let n=e??[];if(Array.isArray(n))for(let e of n){if(!e||typeof e.id!=`string`)continue;if(e.subagentRunId===null)return new L(`Cannot send a message (id '${e.id}') with 'subagentRunId: null'. The field is optional — omit it entirely.`);let n=e.role===`reasoning`?s.reasoning:e.role===`activity`?s.activity:s.message;(t||!n.has(e.id))&&n.set(e.id,{subagentRunId:e.subagentRunId});for(let n of e.toolCalls??[])n&&typeof n.id==`string`&&(t||!s.toolCall.has(n.id))&&s.toolCall.set(n.id,{subagentRunId:e.subagentRunId??void 0})}},b=(e,t,n,r,i)=>{if(t!==void 0&&n&&n.subagentRunId!==t)return new L(`Cannot send '${e}': subagentRunId '${t}' does not match the ${r} '${i}' opener's subagent '${n.subagentRunId??`(the parent agent)`}'.`)};return t.pipe(Dd(e=>{let t=e.type;if(n?.event(`VERIFY`,`Event:`,e,{type:e.type}),l&&t!==I.RUN_STARTED)return z(()=>new L(`Cannot send event type '${t}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(c&&t!==I.RUN_ERROR&&t!==I.RUN_STARTED)return z(()=>new L(`Cannot send event type '${t}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(!u){if(u=!0,t!==I.RUN_STARTED&&t!==I.RUN_ERROR)return z(()=>new L(`First event must be 'RUN_STARTED'`))}else if(t===I.RUN_STARTED){if(g&&!c&&!l)return z(()=>new L(`Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run.`));(c||l)&&v()}if(e.subagentRunId===null){_||(_=!0,WO(`subagentRunId: null`,`an absent field`));let{subagentRunId:t,...n}=e;e=n}if(t===I.SUBAGENT_STARTED||t===I.SUBAGENT_FINISHED||t===I.SUBAGENT_ERROR){let n=t===I.SUBAGENT_STARTED?[`description`,`parentSubagentRunId`,`parentToolCallId`,`parentMessageId`]:t===I.SUBAGENT_FINISHED?[`outcome`]:[`code`];for(let r of n)if(e[r]===null)return z(()=>new L(`Cannot send '${t}' with '${r}: null'. The field is optional — omit it entirely.`));let r=e.outcome;if(r!=null&&r.type!==`success`&&r.type!==`suspended`)return z(()=>new L(`Cannot send '${t}' with outcome type '${String(r.type)}'. The outcome is either { type: "success" } or { type: "suspended" }.`));if(r&&r.interruptIds===null)return z(()=>new L(`Cannot send '${t}' with 'outcome.interruptIds: null'. The field is optional — omit it entirely.`));if(r&&Array.isArray(r.interruptIds)&&r.interruptIds.some(e=>typeof e!=`string`))return z(()=>new L(`Cannot send '${t}' with a non-string entry in 'outcome.interruptIds'. Interrupt ids are strings.`))}if(t===I.RUN_FINISHED){let t=e.outcome;if(t?.type===`interrupt`&&Array.isArray(t.interrupts)){for(let e of t.interrupts)if(e&&e.subagentRunId===null)return z(()=>new L(`Cannot send 'RUN_FINISHED' with an interrupt (id '${e.id}') carrying 'subagentRunId: null'. The field is optional — omit it entirely.`))}}switch(t){case I.TEXT_MESSAGE_START:{let n=e.messageId;if(r.has(n))return z(()=>new L(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${n}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`));let i=s.message.get(n);if(i){let r=b(t,e.subagentRunId,i,`message`,n);if(r)return z(()=>r)}return r.add(n),i||s.message.set(n,{subagentRunId:e.subagentRunId}),Sd(e)}case I.TEXT_MESSAGE_CONTENT:{let n=e.messageId;if(!r.has(n))return z(()=>new L(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${n}'. Start a text message with 'TEXT_MESSAGE_START' first.`));let i=b(t,e.subagentRunId,s.message.get(n),`message`,n);return i?z(()=>i):Sd(e)}case I.TEXT_MESSAGE_END:{let n=e.messageId;if(!r.has(n))return z(()=>new L(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${n}'. A 'TEXT_MESSAGE_START' event must be sent first.`));let i=b(t,e.subagentRunId,s.message.get(n),`message`,n);return i?z(()=>i):(r.delete(n),Sd(e))}case I.TOOL_CALL_START:{let n=e.toolCallId;if(i.has(n))return z(()=>new L(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${n}' is already in progress. Complete it with 'TOOL_CALL_END' first.`));let r=e.parentMessageId,a=e.subagentRunId,o;if(r!==void 0){let e=s.message.get(r);if(e){if(a!==void 0&&a!==e.subagentRunId)return z(()=>new L(`Cannot send 'TOOL_CALL_START': subagentRunId '${a}' does not match its parent message '${r}' owner '${e.subagentRunId??`(the parent agent)`}'. A tool call belongs to the message that carries it.`));o=e}}let c=s.toolCall.get(n);if(c){let e=b(t,a,c,`tool call`,n);if(e)return z(()=>e);if(a===void 0&&o&&o.subagentRunId!==c.subagentRunId)return z(()=>new L(`Cannot send 'TOOL_CALL_START': tool call '${n}' is owned by '${c.subagentRunId??`(the parent agent)`}' but its parent message '${r}' is owned by '${o.subagentRunId??`(the parent agent)`}'. A tool call belongs to the message that carries it.`))}return i.add(n),c||s.toolCall.set(n,a===void 0?o??{subagentRunId:void 0}:{subagentRunId:a}),Sd(e)}case I.TOOL_CALL_ARGS:{let n=e.toolCallId;if(!i.has(n))return z(()=>new L(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${n}'. Start a tool call with 'TOOL_CALL_START' first.`));let r=b(t,e.subagentRunId,s.toolCall.get(n),`tool call`,n);return r?z(()=>r):Sd(e)}case I.TOOL_CALL_END:{let n=e.toolCallId;if(!i.has(n))return z(()=>new L(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${n}'. A 'TOOL_CALL_START' event must be sent first.`));let r=b(t,e.subagentRunId,s.toolCall.get(n),`tool call`,n);return r?z(()=>r):(i.delete(n),Sd(e))}case I.STEP_STARTED:{let t=e.stepName,n=e.subagentRunId;return f(n).has(t)?z(()=>new L(`Step "${t}" is already active for 'STEP_STARTED'${n===void 0?``:` in subagent '${n}'`}`)):(f(n).set(t,!0),Sd(e))}case I.STEP_FINISHED:{let t=e.stepName,n=e.subagentRunId;if(!f(n).has(t)){let e,r=!1;for(let[i,a]of d)if(i!==n&&a.has(t)){e=i,r=!0;break}return z(r?()=>new L(`Cannot send 'STEP_FINISHED' for step "${t}" attributed to ${n===void 0?`the parent agent`:`subagent '${n}'`}: that step is open under ${e===void 0?`the parent agent`:`subagent '${e}'`}. A step must be finished by whoever started it.`):()=>new L(`Cannot send 'STEP_FINISHED' for step "${t}" that was not started`))}return f(n).delete(t),Sd(e)}case I.ACTIVITY_SNAPSHOT:{let t=e.messageId;return(!s.activity.has(t)||e.replace!==!1)&&s.activity.set(t,{subagentRunId:e.subagentRunId}),Sd(e)}case I.TOOL_CALL_RESULT:{let t=e.messageId;return typeof t==`string`&&s.message.set(t,{subagentRunId:e.subagentRunId}),Sd(e)}case I.REASONING_START:case I.REASONING_MESSAGE_START:{let n=e.messageId,r=t===I.REASONING_START,i=r?a:o;if(i.has(n))return z(()=>new L(r?`Cannot send 'REASONING_START' event: A reasoning span with ID '${n}' is already in progress. Complete it with 'REASONING_END' first.`:`Cannot send 'REASONING_MESSAGE_START' event: A reasoning message with ID '${n}' is already in progress. Complete it with 'REASONING_MESSAGE_END' first.`));let c=s.reasoning.get(n);if(c){let r=b(t,e.subagentRunId,c,`reasoning message`,n);if(r)return z(()=>r)}return i.add(n),c||s.reasoning.set(n,{subagentRunId:e.subagentRunId}),Sd(e)}case I.REASONING_MESSAGE_CONTENT:case I.REASONING_MESSAGE_END:case I.REASONING_END:{let n=e.messageId,r=t===I.REASONING_END,i=r?a:o;if(!i.has(n))return z(()=>new L(r?`Cannot send 'REASONING_END' event: No active reasoning span found with ID '${n}'. A 'REASONING_START' event must be sent first.`:`Cannot send '${t}' event: No active reasoning message found with ID '${n}'. Start a reasoning message with 'REASONING_MESSAGE_START' first.`));let c=b(t,e.subagentRunId,s.reasoning.get(n),`reasoning message`,n);return c?z(()=>c):((t===I.REASONING_END||t===I.REASONING_MESSAGE_END)&&i.delete(n),Sd(e))}case I.REASONING_ENCRYPTED_VALUE:{let n=e.entityId,r=e.subtype,i=r===`tool-call`?s.toolCall.get(n):r===`message`?s.message.get(n)??s.reasoning.get(n):s.reasoning.get(n),a=r===`tool-call`?`tool call`:r===`message`?`message`:`reasoning message`,o=b(t,e.subagentRunId,i,a,n);return o?z(()=>o):Sd(e)}case I.ACTIVITY_DELTA:{let n=e.messageId,r=b(t,e.subagentRunId,s.activity.get(n),`activity`,n);return r?z(()=>r):Sd(e)}case I.SUBAGENT_STARTED:{if(typeof e.subagentRunId!=`string`)return z(()=>new L(`Cannot send 'SUBAGENT_STARTED' without a 'subagentRunId'.`));if(typeof e.name!=`string`)return z(()=>new L(`Cannot send 'SUBAGENT_STARTED' without a 'name'.`));let t=e.subagentRunId,n=e.parentSubagentRunId;return m.has(t)?z(()=>new L(`Cannot send 'SUBAGENT_STARTED': subagent '${t}' is already active. Finish it with 'SUBAGENT_FINISHED' first.`)):h.has(t)?z(()=>new L(`Cannot send 'SUBAGENT_STARTED': subagent '${t}' has already finished in this run. Subagent IDs are per-invocation and cannot be reused.`)):n!==void 0&&!m.has(n)&&!h.has(n)?z(()=>new L(`Cannot send 'SUBAGENT_STARTED': parentSubagentRunId '${n}' has not been started in this run.`)):(m.set(t,!0),Sd(e))}case I.SUBAGENT_FINISHED:case I.SUBAGENT_ERROR:{if(typeof e.subagentRunId!=`string`)return z(()=>new L(`Cannot send '${t}' without a 'subagentRunId'.`));if(t===I.SUBAGENT_ERROR&&typeof e.message!=`string`)return z(()=>new L(`Cannot send 'SUBAGENT_ERROR' without a 'message'.`));let n=e.subagentRunId;return m.has(n)?(m.delete(n),h.add(n),Sd(e)):z(()=>new L(`Cannot send '${t}': no active subagent found with ID '${n}'. A 'SUBAGENT_STARTED' event must be sent first.`))}case I.MESSAGES_SNAPSHOT:{let t=y(e.messages,!0);if(t)return z(()=>t)}return Sd(e);case I.RUN_STARTED:g=!0;{let t=y((e.input??{}).messages,!1);if(t)return z(()=>t)}return Sd(e);case I.RUN_FINISHED:if(p()){let e=[];for(let[t,n]of d)for(let r of n.keys())e.push(t===void 0?r:`${r} (subagent '${t}')`);let t=e.join(`, `);return z(()=>new L(`Cannot send 'RUN_FINISHED' while steps are still active: ${t}`))}if(r.size>0){let e=Array.from(r.keys()).join(`, `);return z(()=>new L(`Cannot send 'RUN_FINISHED' while text messages are still active: ${e}`))}if(o.size>0){let e=Array.from(o.keys()).join(`, `);return z(()=>new L(`Cannot send 'RUN_FINISHED' while reasoning messages are still active: ${e}`))}if(a.size>0){let e=Array.from(a.keys()).join(`, `);return z(()=>new L(`Cannot send 'RUN_FINISHED' while reasoning spans are still active: ${e}`))}if(i.size>0){let e=Array.from(i.keys()).join(`, `);return z(()=>new L(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${e}`))}if(m.size>0){let e=Array.from(m.keys()).join(`, `);return z(()=>new L(`Cannot send 'RUN_FINISHED' while subagents are still active: ${e}`))}return c=!0,Sd(e);case I.RUN_ERROR:return l=!0,Sd(e);case I.CUSTOM:return Sd(e);default:return Sd(e)}}))},KO=function(e){return e.HEADERS=`headers`,e.DATA=`data`,e}({}),qO=e=>Ad(()=>xd(e())).pipe(Rd(e=>{if(!e.ok){let t=e.headers.get(`content-type`)||``;return xd(e.text()).pipe(Dd(n=>{let r=n;if(t.includes(`application/json`))try{r=JSON.parse(n)}catch{}let i=Error(`HTTP ${e.status}: ${typeof r==`string`?r:JSON.stringify(r)}`);return i.status=e.status,i.payload=r,z(()=>i)}))}let t={type:KO.HEADERS,status:e.status,headers:e.headers},n=e.body?.getReader();return n?new ju(e=>{let r=!1;return e.next(t),(async()=>{try{for(;!e.closed;){let{done:t,value:i}=await n.read();if(t){r=!0;break}let a={type:KO.DATA,data:i};e.next(a)}e.complete()}catch(t){r=!0,e.error(t)}})(),()=>{r||n.cancel().catch(e=>{e?.name!==`AbortError`&&console.warn(`Failed to cancel HTTP response stream:`,e)})}}):z(()=>Error(`Failed to getReader() from response`))})),JO=10485760,YO=(e,t)=>{let n=RO(t),r=new Bu,i=new TextDecoder(`utf-8`,{fatal:!1}),a=``;e.subscribe({next:e=>{if(e.type!==KO.HEADERS&&e.type===KO.DATA&&e.data){let t=i.decode(e.data,{stream:!0});a+=t;let n=a.split(/\n\n/);a=n.pop()||``;for(let e of n)o(e);if(a.length>JO){r.error(Error(`SSE buffer size exceeded maximum limit of ${JO/1048576} MB`));return}}},error:e=>r.error(e),complete:()=>{a&&(a+=i.decode(),o(a)),r.complete()}});function o(e){let t=e.split(` -`),i=[];for(let e of t)e.startsWith(`data:`)&&i.push(e.slice(5).replace(/^ /,``));if(i.length>0)try{let e=i.join(` -`),t=JSON.parse(e);n?.event(`SSE`,`Event received:`,t,{type:t?.type}),r.next(t)}catch(e){r.error(e)}}return r.asObservable()},XO=10485760,ZO=()=>typeof process<`u`&&!!{}.SUPPRESS_TRANSFORMATION_WARNINGS,QO=(e,t)=>{let n=RO(t),r=new Bu,i=new Uint8Array,a=!1;e.subscribe({next:e=>{if(e.type!==KO.HEADERS&&e.type===KO.DATA&&e.data){let t=new Uint8Array(i.length+e.data.length);t.set(i,0),t.set(e.data,i.length),i=t,o()}},error:e=>r.error(e),complete:()=>{if(o(),!a){if(i.length>0){r.error(Error(`The binary stream ended mid-frame: ${i.length} trailing bytes could not be read as a complete message.`));return}r.complete()}}});function o(){if(!a)for(;i.length>=4;){let e=4+new DataView(i.buffer,i.byteOffset,4).getUint32(0,!1);if(e>XO){r.error(Error(`Protobuf message size exceeded maximum limit of ${XO/1048576} MB`));return}if(i.length{let n=RO(t),r=new Bu,i=new Uu(1),a=!1,o,s=!1,c=()=>{s=!0,o?.unsubscribe()},l=e=>{c(),r.error(e)},u=()=>{c(),r.complete()};return o=e.subscribe({next:e=>{if(i.next(e),e.type===KO.HEADERS&&!a){a=!0;let t=e.headers.get(`content-type`);n?.lifecycle(`HTTP`,`Stream format detected:`,{contentType:t,parser:t===`application/vnd.ag-ui.event+proto`?`protobuf`:`sse`}),t===`application/vnd.ag-ui.event+proto`?QO(i,n).subscribe({next:e=>r.next(e),error:e=>l(e),complete:()=>u()}):YO(i,n).subscribe({next:e=>{if(typeof e!=`object`||!e||Array.isArray(e)){let t=Error(`Invalid event: the frame is not a JSON object.`);n?.event(`HTTP`,`Event invalid:`,{json:e,error:String(t)}),l(t);return}let t=e;if(typeof t.type!=`string`||t.type.length===0){let t=Error(`Invalid event: the frame carries no event type.`);n?.event(`HTTP`,`Event invalid:`,{json:e,error:String(t)}),l(t);return}n?.event(`HTTP`,`Event received:`,e,{type:t.type}),r.next(e)},error:e=>{if(e?.name===`AbortError`){r.next({type:I.RUN_ERROR,message:e.message||`Request aborted`,code:`abort`,rawEvent:e}),u();return}return l(e)},complete:()=>u()})}else a||l(Error(`No headers event received before data events`))},error:e=>{i.error(e),l(e)},complete:()=>{i.complete()}}),s&&o.unsubscribe(),r.asObservable()},ek={TextMessageStart:`TextMessageStart`,TextMessageContent:`TextMessageContent`,TextMessageEnd:`TextMessageEnd`,ActionExecutionStart:`ActionExecutionStart`,ActionExecutionArgs:`ActionExecutionArgs`,ActionExecutionEnd:`ActionExecutionEnd`,ActionExecutionResult:`ActionExecutionResult`,AgentStateMessage:`AgentStateMessage`,MetaEvent:`MetaEvent`,RunStarted:`RunStarted`,RunFinished:`RunFinished`,RunError:`RunError`,NodeStarted:`NodeStarted`,NodeFinished:`NodeFinished`},tk=e=>{if(typeof e==`string`)return e;if(!Array.isArray(e))return;let t=e.filter(e=>e.type===`text`).map(e=>e.text).filter(e=>e.length>0);if(t.length!==0)return t.join(` -`)};function nk(e,t){return ol(t)&&rk(`[ag-ui][legacy] The result of tool call '${e}' carries content parts the legacy protocol cannot represent; only its text parts are bridged and the rest is dropped.`),al(t)}var rk=e=>{typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(e)},ik=(e,t,n)=>r=>{let i={},a=!0,o=!0,s=``,c=null,l=null,u=[],d={},f=!1,p=e=>{typeof e==`object`&&e&&(`messages`in e&&delete e.messages,i=e)};return r.pipe(Dd(r=>{switch(r.type){case I.TEXT_MESSAGE_START:{let e=r;return[{type:ek.TextMessageStart,messageId:e.messageId,role:e.role}]}case I.TEXT_MESSAGE_CONTENT:{let e=r;return[{type:ek.TextMessageContent,messageId:e.messageId,content:e.delta}]}case I.TEXT_MESSAGE_END:{let e=r;return[{type:ek.TextMessageEnd,messageId:e.messageId}]}case I.TOOL_CALL_START:{let e=r;return u.push({id:e.toolCallId,type:`function`,function:{name:e.toolCallName,arguments:``}}),o=!0,d[e.toolCallId]=e.toolCallName,[{type:ek.ActionExecutionStart,actionExecutionId:e.toolCallId,actionName:e.toolCallName,parentMessageId:e.parentMessageId}]}case I.TOOL_CALL_ARGS:{let c=r,d=u.find(e=>e.id===c.toolCallId);if(!d)return rk(`[ag-ui][legacy] TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];d.function.arguments+=c.delta;let f=!1;if(l){let e=l.find(e=>e.tool==d.function.name);if(e)try{let t=JSON.parse(Hd(d.function.arguments));e.tool_argument&&e.tool_argument in t?(p({...i,[e.state_key]:t[e.tool_argument]}),f=!0):e.tool_argument||(p({...i,[e.state_key]:t}),f=!0)}catch{}}return[{type:ek.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...f?[{type:ek.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}]:[]]}case I.TOOL_CALL_END:{let e=r;return[{type:ek.ActionExecutionEnd,actionExecutionId:e.toolCallId}]}case I.TOOL_CALL_RESULT:{let e=r,t=d[e.toolCallId];return(t===void 0||t===``)&&rk(`[ag-ui][legacy] No usable tool name was seen for tool call '${e.toolCallId}' (${t===void 0?`no TOOL_CALL_START reached this bridge`:`its TOOL_CALL_START carried an empty toolCallName`}), so its result is being bridged with the fabricated action name "unknown". Downstream consumers route on that name.`),[{type:ek.ActionExecutionResult,actionExecutionId:e.toolCallId,result:nk(e.toolCallId,e.content),actionName:t||`unknown`}]}case I.RAW:return f||(f=!0,rk(`[ag-ui][legacy] Dropping RAW events: the legacy runtime protocol has no equivalent, so the provider payloads they carry do not reach the legacy stream. Reported once per stream.`)),[];case I.CUSTOM:{let e=r;switch(e.name){case`Exit`:a=!1;break;case`PredictState`:l=e.value}return[{type:ek.MetaEvent,name:e.name,value:e.value}]}case I.STATE_SNAPSHOT:return p(r.snapshot),[{type:ek.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}];case I.STATE_DELTA:{let c=r,l;try{l=Hl.applyPatch(i,c.delta,!0,!1).newDocument}catch(e){let t=e instanceof Error?e.message:String(e);return rk(`[ag-ui][legacy] Failed to apply state patch:\nCurrent state: ${JSON.stringify(i,null,2)}\nPatch operations: ${JSON.stringify(c.delta,null,2)}\nError: ${t}`),[]}return p(l),[{type:ek.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}]}case I.MESSAGES_SNAPSHOT:return c=r.messages,[{type:ek.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify({...i,...c?{messages:c}:{}}),active:!0}];case I.RUN_STARTED:return[];case I.RUN_FINISHED:{if(c&&(i.messages=c),Object.keys(i).length===0)return[];let r=null;if(c)try{r=ak(c)}catch(e){return[{type:ek.RunError,message:e.message}]}return[{type:ek.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify({...i,...r?{messages:r}:{}}),active:!1}]}case I.RUN_ERROR:{let e=r;return[{type:ek.RunError,message:e.message,code:e.code}]}case I.STEP_STARTED:return s=r.stepName,u=[],l=null,[{type:ek.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:!0}];case I.STEP_FINISHED:return u=[],l=null,[{type:ek.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:!1}];default:return[]}}))};function ak(e){let t=[];for(let n of e)if(n.role===`assistant`||n.role===`user`||n.role===`system`){let e=tk(n.content);if(e){let r={id:n.id,role:n.role,content:e};t.push(r)}if(n.role===`assistant`&&n.toolCalls&&n.toolCalls.length>0)for(let e of n.toolCalls){let r;try{r=JSON.parse(e.function.arguments)}catch(t){throw Error(`Failed to parse arguments for tool call '${e.id}' (${e.function.name}): ${t.message}`)}let i={id:e.id,name:e.function.name,arguments:r,parentMessageId:n.id};t.push(i)}}else if(n.role===`tool`){let r=`unknown`;for(let t of e)if(t.role===`assistant`&&t.toolCalls?.length){for(let e of t.toolCalls)if(e.id===n.toolCallId){r=e.function.name;break}}let i={id:n.id,result:nk(n.toolCallId,n.content),actionExecutionId:n.toolCallId,actionName:r};t.push(i)}return t}var ok=e=>e.kind===`tool`?e.fields.toolCallId:e.fields.messageId,sk=e=>e===`tool`?`toolCallId`:`messageId`,ck=(e,t,n,r,i)=>{if(r!==void 0&&r!==i)throw Error(`Cannot continue ${e} '${t}': chunk ${n} '${r}' does not match the open stream's ${n} ${i===void 0?`(absent)`:`'${i}'`}.`)},lk=(e,t)=>t.metadata===void 0?e:{...e,metadata:t.metadata},uk=(e,t)=>{let n=lk(e,t);return t.rawEvent===void 0?n:{...n,rawEvent:t.rawEvent}},dk=e=>new Set(Object.keys(e.shape)),fk=dk(Ex),pk=dk(Ax),mk=dk(pS),hk=(e,t)=>{let n;for(let r of Object.keys(e))t.has(r)||((n??={})[r]=e[r]);return n},gk=e=>{typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`[ag-ui][transform] ${e} Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`)},_k=(e,t,n,r)=>{if(t===void 0||n||e.length===0)return;let i=e[e.length-1],a=Object.keys(t).filter(e=>Object.prototype.hasOwnProperty.call(i,e));a.length>0&&gk(`A ${r} carried ${a.map(e=>`'${e}'`).join(`, `)}, which the synthesized ${String(i.type)} already describes. The synthesized value is kept and the chunk's is dropped — this stage does not judge a described field, so the producer's value cannot be substituted for its own.`),e[e.length-1]={...t,...i}},vk=e=>t=>{let n=RO(e),r=new Map,i=e=>{let t=r.get(e);if(!t)return[];switch(r.delete(e),t.kind){case`text`:{let e={type:I.TEXT_MESSAGE_END,messageId:t.fields.messageId,...t.fields.subagentRunId!==void 0&&{subagentRunId:t.fields.subagentRunId}};return n?.event(`TRANSFORM`,`TEXT_MESSAGE_END`,e,{messageId:e.messageId}),[e]}case`tool`:{let e={type:I.TOOL_CALL_END,toolCallId:t.fields.toolCallId,...t.fields.subagentRunId!==void 0&&{subagentRunId:t.fields.subagentRunId}};return n?.event(`TRANSFORM`,`TOOL_CALL_END`,e,{toolCallId:e.toolCallId}),[e]}case`reasoning`:{let e={type:I.REASONING_MESSAGE_END,messageId:t.fields.messageId,...t.fields.subagentRunId!==void 0&&{subagentRunId:t.fields.subagentRunId}};return n?.event(`TRANSFORM`,`REASONING_MESSAGE_END`,e,{messageId:e.messageId}),[e]}}},a=()=>[...r.keys()].flatMap(e=>i(e)),o=(e,t)=>{for(let[n,i]of r)if(i.kind===e&&ok(i)===t)return{owner:n}},s=(e,t,n,i,a)=>{if(t!==void 0){let r=o(e,t);if(r){if(n!==void 0&&n!==r.owner)throw Error(`Cannot continue ${a} '${t}': chunk subagentRunId '${n}' does not match the open stream's subagent '${r.owner??`(the parent agent)`}'.`);return r.owner}return n}if(n!==void 0)return n;if(r.get(void 0)?.kind===e)return;let s=[...r.entries()].filter(([,t])=>t.kind===e);if(s.length===1)return s[0][0];if(s.length>1)throw Error(`Ambiguous ${i}: it carries neither a ${sk(e)} nor a subagentRunId, but ${s.length} lanes have an open ${a}. Attribute the chunk to the subagent it belongs to.`)};return t.pipe(Dd(e=>{switch(e.type){case I.TEXT_MESSAGE_START:case I.TEXT_MESSAGE_CONTENT:case I.TEXT_MESSAGE_END:case I.TOOL_CALL_START:case I.TOOL_CALL_ARGS:case I.TOOL_CALL_END:case I.TOOL_CALL_RESULT:case I.STATE_SNAPSHOT:case I.STATE_DELTA:case I.CUSTOM:case I.STEP_STARTED:case I.STEP_FINISHED:case I.REASONING_START:case I.REASONING_MESSAGE_START:case I.REASONING_MESSAGE_CONTENT:case I.REASONING_MESSAGE_END:case I.REASONING_END:return[...i(e.subagentRunId??void 0),e];case I.RUN_STARTED:case I.RUN_FINISHED:case I.RUN_ERROR:case I.MESSAGES_SNAPSHOT:return[...a(),e];case I.RAW:case I.ACTIVITY_SNAPSHOT:case I.ACTIVITY_DELTA:case I.REASONING_ENCRYPTED_VALUE:case I.SUBAGENT_STARTED:return[e];case I.SUBAGENT_FINISHED:case I.SUBAGENT_ERROR:{let t=e.subagentRunId;return t==null?[e]:[...i(t),e]}case I.TEXT_MESSAGE_CHUNK:{let t=e,a=hk(e,fk),o=s(`text`,t.messageId,t.subagentRunId??void 0,`TEXT_MESSAGE_CHUNK`,`text message`),c=r.get(o),l=[],u=!1,d;if(c?.kind===`text`&&(t.messageId===void 0||t.messageId===c.fields.messageId))ck(`text message`,c.fields.messageId,`role`,t.role,c.fields.role),ck(`text message`,c.fields.messageId,`name`,t.name,c.fields.name),d=c.fields;else{if(l.push(...i(o)),t.messageId===void 0)throw Error(`First TEXT_MESSAGE_CHUNK must have a messageId`);d={messageId:t.messageId,role:t.role===void 0?`assistant`:t.role,name:t.name,subagentRunId:t.subagentRunId},r.set(o,{kind:`text`,fields:d});let e=lk({type:I.TEXT_MESSAGE_START,messageId:t.messageId,role:d.role,...t.name!==void 0&&{name:t.name},...t.subagentRunId!==void 0&&{subagentRunId:t.subagentRunId}},t);l.push(e),n?.event(`TRANSFORM`,`TEXT_MESSAGE_START`,e,{messageId:t.messageId})}if(t.delta!==void 0||t.rawEvent!==void 0){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId,r=uk({...a,type:I.TEXT_MESSAGE_CONTENT,messageId:d.messageId,delta:t.delta===void 0?``:t.delta,...e!==void 0&&{subagentRunId:e}},t);l.push(r),u=!0,n?.event(`TRANSFORM`,`TEXT_MESSAGE_CONTENT`,r,{messageId:d.messageId})}if(l.length===0&&(t.metadata!==void 0||t.rawEvent!==void 0||t.subagentRunId===null||a!==void 0)){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId;l.push({...a,type:I.TEXT_MESSAGE_CONTENT,messageId:d.messageId,delta:``,...t.metadata!==void 0&&{metadata:t.metadata},...t.rawEvent!==void 0&&{rawEvent:t.rawEvent},...e!==void 0&&{subagentRunId:e}}),u=!0}return _k(l,a,u,`TEXT_MESSAGE_CHUNK`),l}case I.TOOL_CALL_CHUNK:{let t=e,a=hk(e,pk),o=s(`tool`,t.toolCallId,t.subagentRunId??void 0,`TOOL_CALL_CHUNK`,`tool call`),c=r.get(o),l=[],u=!1,d;if(c?.kind===`tool`&&(t.toolCallId===void 0||t.toolCallId===c.fields.toolCallId))ck(`tool call`,c.fields.toolCallId,`toolCallName`,t.toolCallName,c.fields.toolCallName),ck(`tool call`,c.fields.toolCallId,`parentMessageId`,t.parentMessageId,c.fields.parentMessageId),d=c.fields;else{if(l.push(...i(o)),t.toolCallId===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallId`);if(t.toolCallName===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallName`);d={toolCallId:t.toolCallId,toolCallName:t.toolCallName,parentMessageId:t.parentMessageId,subagentRunId:t.subagentRunId},r.set(o,{kind:`tool`,fields:d});let e=lk({type:I.TOOL_CALL_START,toolCallId:t.toolCallId,toolCallName:t.toolCallName,...t.parentMessageId!==void 0&&{parentMessageId:t.parentMessageId},...t.subagentRunId!==void 0&&{subagentRunId:t.subagentRunId}},t);l.push(e),n?.event(`TRANSFORM`,`TOOL_CALL_START`,e,{toolCallId:t.toolCallId,toolCallName:t.toolCallName})}if(t.delta!==void 0||t.rawEvent!==void 0){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId,r=uk({...a,type:I.TOOL_CALL_ARGS,toolCallId:d.toolCallId,delta:t.delta===void 0?``:t.delta,...e!==void 0&&{subagentRunId:e}},t);l.push(r),u=!0,n?.event(`TRANSFORM`,`TOOL_CALL_ARGS`,r,{toolCallId:d.toolCallId})}if(l.length===0&&(t.metadata!==void 0||t.rawEvent!==void 0||t.subagentRunId===null||a!==void 0)){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId;l.push({...a,type:I.TOOL_CALL_ARGS,toolCallId:d.toolCallId,delta:``,...t.metadata!==void 0&&{metadata:t.metadata},...t.rawEvent!==void 0&&{rawEvent:t.rawEvent},...e!==void 0&&{subagentRunId:e}}),u=!0}return _k(l,a,u,`TOOL_CALL_CHUNK`),l}case I.REASONING_MESSAGE_CHUNK:{let t=e,a=hk(e,mk),o=s(`reasoning`,t.messageId,t.subagentRunId??void 0,`REASONING_MESSAGE_CHUNK`,`reasoning message`),c=r.get(o),l=[],u=!1,d;if(c?.kind===`reasoning`&&(t.messageId===void 0||t.messageId===c.fields.messageId))d=c.fields;else{if(l.push(...i(o)),t.messageId===void 0)throw Error(`First REASONING_MESSAGE_CHUNK must have a messageId`);d={messageId:t.messageId,subagentRunId:t.subagentRunId},r.set(o,{kind:`reasoning`,fields:d});let e=lk({type:I.REASONING_MESSAGE_START,messageId:t.messageId,role:`reasoning`,...t.subagentRunId!==void 0&&{subagentRunId:t.subagentRunId}},t);l.push(e),n?.event(`TRANSFORM`,`REASONING_MESSAGE_START`,e,{messageId:t.messageId})}if(t.delta!==void 0||t.rawEvent!==void 0){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId,r=uk({...a,type:I.REASONING_MESSAGE_CONTENT,messageId:d.messageId,delta:t.delta===void 0?``:t.delta,...e!==void 0&&{subagentRunId:e}},t);l.push(r),u=!0,n?.event(`TRANSFORM`,`REASONING_MESSAGE_CONTENT`,r,{messageId:d.messageId})}if(l.length===0&&(t.metadata!==void 0||t.rawEvent!==void 0||t.subagentRunId===null||a!==void 0)){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId;l.push({...a,type:I.REASONING_MESSAGE_CONTENT,messageId:d.messageId,delta:``,...t.metadata!==void 0&&{metadata:t.metadata},...t.rawEvent!==void 0&&{rawEvent:t.rawEvent},...e!==void 0&&{subagentRunId:e}}),u=!0}return _k(l,a,u,`REASONING_MESSAGE_CHUNK`),l}}return e.type,[e]}),Ld(()=>{a()}))},yk=Symbol(`agui.strip.drop`);function bk(e){let t=e;for(;;){if(t instanceof sO||t instanceof lO||t instanceof dO||t instanceof xO||t instanceof _O){t=t.unwrap();continue}if(t instanceof yO){t=t.def.in;continue}if(t instanceof CO){t=t.def.getter();continue}return t}}function xk(e){let t=e.def;return typeof t?.discriminator==`string`?t.discriminator:void 0}function Sk(e){let t=e,n=Array.isArray(t.def?.values)?t.def.values:t.values?Array.from(t.values):void 0;return n&&n.length===1?n[0]:t.value}function Ck(e){let t=bk(e);return t instanceof iO?Sk(t):void 0}function wk(e,t,n,r){let i=bk(t);if(i instanceof XD){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t=i.shape,a=e,o={},s=i.meta()?.specOpen===!0;for(let e of Object.keys(a)){let i=Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;if(i===void 0){if(s){o[e]=a[e];continue}r.push(`${n}/${e}`);continue}let c=r.length,l=wk(a[e],i,`${n}/${e}`,r);if(l===yk){if(r.length=c,i.safeParse(void 0).success){r.push(`${n}/${e}`);continue}return yk}o[e]=l}return o}if(i instanceof JD){if(!Array.isArray(e))return e;let t=i.element,a=[];return e.forEach((e,i)=>{let o=r.length,s=wk(e,t,`${n}/${i}`,r);if(s===yk){r.length=o,r.push(`${n}/${i}`);return}a.push(s)}),a}if(i instanceof tO){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t=i.def.valueType,a=e,o={};for(let e of Object.keys(a)){let i=r.length,s=wk(a[e],t,`${n}/${e}`,r);if(s===yk){r.length=i,r.push(`${n}/${e}`);continue}o[e]=s}return o}if(i instanceof ZD){let t=i.options,a=xk(i);if(a!==void 0){if(typeof e!=`object`||!e||Array.isArray(e))return e;let i=e[a];for(let o of t){let t=bk(o);if(!(t instanceof XD))continue;let s=t.shape;if(Ck(s[a])===i)return wk(e,o,n,r)}return yk}let o=t.filter(e=>bk(e)instanceof XD),s=typeof e==`object`&&!!e&&!Array.isArray(e);if(o.length>1&&s)return e;for(let i of t){let t=bk(i);if(t instanceof JD&&Array.isArray(e)||t instanceof XD&&s)return wk(e,i,n,r)}return e}return e}function Tk(e,t){let n=[],r=wk(e,t,``,n);if(r===yk)throw Error(`Internal error: the stripper found the whole value unrecognisable, which the schemas are not supposed to allow — schema/stripper mismatch.`);return{value:r,stripped:n}}var Ek=new Set(Object.values(I));function Dk(e){return Ek.has(e.type)}var Ok=new Map(yS.options.map(e=>{let t=e.shape;return[String(Sk(t.type)),e]})),kk=()=>typeof process<`u`&&!!{}.SUPPRESS_TRANSFORMATION_WARNINGS;function Ak(e){kk()||console.warn(`[ag-ui][enforce] ${e}`)}var jk=e=>t=>{let n=RO(e);return t.pipe(Dd(e=>{if(!Dk(e))return Ak(`Dropping unrecognised event '${String(e.type)}': no middleware translated it and the protocol does not describe it.`),n?.event(`ENFORCE`,`Unrecognised event dropped:`,e,{type:e.type}),Wu;let t=Ok.get(e.type);if(t===void 0)throw Error(`No validator for recognised event type '${String(e.type)}'`);let{value:r,stripped:i}=Tk(e,t);for(let t of i)Ak(`Removed unrecognised material at '${t}' on ${String(e.type)}. Nothing handled it; see the repo-root DEPRECATIONS.md if it is a retired shape.`);return Sd(t.parse(r))}))};function Mk(e){let{value:t,stripped:n}=Tk(nl(e,`RunAgentInput`),$x);for(let e of n)Ak(`Removed unrecognised material at '${e}' from the outgoing input.`);return $x.parse(t)}var Nk=class{runNext(e,t){return t.run(e).pipe(vk(!1))}runNextWithState(e,t){let n=AO(e.messages||[]),r=AO(e.state===void 0?{}:e.state),i=new Uu;return UO(e,i,t,[]).subscribe({next:e=>{e.messages!==void 0&&(n=e.messages),e.state!==void 0&&(r=e.state)},error:()=>{}}),this.runNext(e,t).pipe(Nd(async e=>(i.next(e),await new Promise(e=>setTimeout(e,0)),{event:e,messages:AO(n),state:AO(r)})))}},Pk=class extends Nk{constructor(e){super(),this.fn=e}run(e,t){return this.fn(e,t)}};function Fk(e){return e.startsWith(`image/`)?`image`:e.startsWith(`audio/`)?`audio`:e.startsWith(`video/`)?`video`:`document`}function Ik(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`binary`&&`mimeType`in e&&typeof e.mimeType==`string`}function Lk(e){let t=Fk(e.mimeType);return e.data?{type:t,source:{type:`data`,value:e.data,mimeType:e.mimeType},...e.filename?{metadata:{filename:e.filename}}:{}}:e.url?{type:t,source:{type:`url`,value:e.url,mimeType:e.mimeType},...e.filename?{metadata:{filename:e.filename}}:{}}:((typeof process>`u`||!{}.SUPPRESS_TRANSFORMATION_WARNINGS)&&console.warn(`[ag-ui][compat] A binary content part carries only an id ('${e.id??``}') and cannot be converted to a modern media part; a 1.0 peer will not accept it. Provide data or a url. See the repo-root DEPRECATIONS.md.`),e)}function Rk(e,t,n){if(typeof e!=`object`||!e||!(`type`in e)||e.type!==t.type||!(`source`in e))return!1;let r=e.source;return typeof r!=`object`||!r||!(`type`in r)||r.type!==t.source.type||!(`value`in r)||r.value!==t.source.value||!(`mimeType`in r)||r.mimeType!==t.source.mimeType?!1:!n||`metadata`in e&&typeof e.metadata==`object`&&e.metadata!==null&&`filename`in e.metadata&&e.metadata.filename===n}function zk(e){let t=e.content;if(!Array.isArray(t))return e;let n=t.flatMap(e=>{if(Ik(e)){let n=Lk(e);return n.type!==`binary`&&t.some(t=>Rk(t,n,e.filename))?[]:[n]}return[e]});return{...e,content:n}}var Bk=`THINKING_START`,Vk=`THINKING_END`,Hk=`THINKING_TEXT_MESSAGE_START`,Uk=`THINKING_TEXT_MESSAGE_CONTENT`,Wk=`THINKING_TEXT_MESSAGE_END`;function Gk(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Kk={event:[`rawEvent`,`subagentRunId`],[I.RUN_STARTED]:[`parentRunId`,`input`],[I.RUN_FINISHED]:[`result`,`outcome`],[I.RUN_ERROR]:[`usage`],[I.SUBAGENT_FINISHED]:[`result`],[I.TOOL_CALL_START]:[`parentMessageId`],[I.TOOL_CALL_CHUNK]:[`parentMessageId`],[I.TOOL_CALL_RESULT]:[`role`],"RUN_FINISHED.outcome":[`pendingToolCallIds`],"RUN_FINISHED.usage[]":[`provider`,`reasoningTokens`,`cachedInputTokens`,`cacheWriteInputTokens`],RunAgentInput:[`forwardedProps`],Tool:[`parameters`],ResumeEntry:[`payload`],"input content":[`metadata`]},qk=new Map(Object.entries(Kk).filter(([e])=>Object.values(I).includes(e))),Jk=e=>WO(e,`an absent field`);function Yk(e,t,n,r){if(!Gk(e))return e;let i;for(let a of t)e[a]===null&&(r(n===void 0?`${a}: null`:`${n}.${a}: null`),i??={...e},delete i[a]);return i??e}function Xk(e,t,n){if(!Gk(e)||!Array.isArray(e[t]))return e;let r=e[t],i=r.map(n);return i.some((e,t)=>e!==r[t])?{...e,[t]:i}:e}function Zk(e,t){return Xk(e,`content`,e=>{if(!Gk(e))return e;switch(e.type){case`image`:case`audio`:case`video`:case`document`:return Yk(e,Kk[`input content`],`${e.type} input content`,t);default:return e}})}function Qk(e,t=Jk){let n=Yk(e,Kk.RunAgentInput,`RunAgentInput`,t);return n=Xk(n,`tools`,e=>Yk(e,Kk.Tool,`Tool`,t)),n=Xk(n,`resume`,e=>Yk(e,Kk.ResumeEntry,`ResumeEntry`,t)),Xk(n,`messages`,e=>Zk(e,t))}var $k=class extends Nk{constructor(...e){super(...e),this.currentReasoningId=null,this.currentMessageId=null,this.nullsNoticedThisRun=new Set,this.noticeNullOncePerRun=e=>{this.nullsNoticedThisRun.has(e)||(this.nullsNoticedThisRun.add(e),WO(e,`an absent field`))}}warn(e,t){WO(e,t)}mintedContinuationId(e,t){if(t!==null)return t;let n=jO();return this.warnAside(`Minting a messageId ('${n}') for ${e}: no THINKING opener preceded it, so there was no id to continue. The id is this client's invention, not the producer's, and verification will reject the translated event for naming something nothing opened.`),n}warnAside(e){typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`[ag-ui][compat] ${e} Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`)}run(e,t){return this.currentReasoningId=null,this.currentMessageId=null,this.nullsNoticedThisRun.clear(),e.messages=e.messages.map(zk),t.run(e).pipe(Td(e=>this.transformEvent(e)))}transformEvent(e){let t=this.noticeNullOncePerRun;e.type===I.RUN_STARTED&&this.nullsNoticedThisRun.clear(),e=Yk(e,Kk.event,void 0,t);let n=qk.get(e.type);switch(n&&(e=Yk(e,n,e.type,t)),e.type){case Bk:{this.currentReasoningId=jO();let{title:t,...n}=e;return this.warn(Bk,I.REASONING_START),t!==void 0&&this.warnAside(`Dropping ${Bk}.title ${JSON.stringify(t)}: ${I.REASONING_START} has no title field, so the span's label cannot be carried and nothing downstream can recover it.`),{...n,type:I.REASONING_START,messageId:this.currentReasoningId}}case Hk:return this.currentMessageId=jO(),this.warn(Hk,I.REASONING_MESSAGE_START),{...e,type:I.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:`reasoning`};case Uk:{let{delta:t,...n}=e;return this.warn(Uk,I.REASONING_MESSAGE_CONTENT),{...n,type:I.REASONING_MESSAGE_CONTENT,messageId:this.mintedContinuationId(Uk,this.currentMessageId),delta:t}}case Wk:{let t=this.mintedContinuationId(Wk,this.currentMessageId);return this.currentMessageId=null,this.warn(Wk,I.REASONING_MESSAGE_END),{...e,type:I.REASONING_MESSAGE_END,messageId:t}}case Vk:{let t=this.mintedContinuationId(Vk,this.currentReasoningId);return this.currentReasoningId=null,this.warn(Vk,I.REASONING_END),{...e,type:I.REASONING_END,messageId:t}}case I.RUN_FINISHED:{let n=e,r=Yk(n.outcome,Kk[`RUN_FINISHED.outcome`],`RUN_FINISHED.outcome`,t);return Xk(r===n.outcome?n:{...n,outcome:r},`usage`,e=>Yk(e,Kk[`RUN_FINISHED.usage[]`],`RUN_FINISHED.usage[]`,t))}case I.MESSAGES_SNAPSHOT:{let t=e;return Array.isArray(t.messages)?{...t,messages:t.messages.map(e=>this.upgradeInboundMessage(e))}:e}case I.RUN_STARTED:{let n=Qk(e.input,t),r=n===e.input?e:{...e,input:n},i=r;return!i.input||!Array.isArray(i.input.messages)?r:{...i,input:{...i.input,messages:i.input.messages.map(e=>this.upgradeInboundMessage(e))}}}default:return e}}upgradeInboundMessage(e){e=Zk(e,this.noticeNullOncePerRun);let t=e.content;return!Array.isArray(t)||!t.some(e=>typeof e==`object`&&!!e&&e.type===`binary`)?e:(this.warn(`binary input content`,`the modern media content parts`),zk(e))}},eA=()=>e=>Ad(()=>{let t=new $k;return e.pipe(Td(e=>t.transformEvent(e)))});function tA(e,t=new Date){return e.expiresAt!==void 0&&new Date(e.expiresAt)<=t}function nA(){return typeof process<`u`&&!!{}.SUPPRESS_TRANSFORMATION_WARNINGS}function rA(e){nA()||console.warn(`[ag-ui][compat] Flattening message content for a <=0.0.39 peer DROPS non-text parts (${e.join(`, `)}). The peer cannot receive them; upgrade it to keep media content. See the repo-root DEPRECATIONS.md.`)}function iA(e){nA()||console.warn(`[ag-ui][compat] Not flattening message content for a <=0.0.39 peer: ${e} content part(s) claim type "text" but carry a malformed 'text' value. That is a defect in the message, not media the peer cannot represent, and a downgrade must not repair it — the content is passed on unchanged so the outgoing enforcement boundary reports it. See the repo-root DEPRECATIONS.md.`)}function aA(e){let t=e.content;if(Array.isArray(t)){let n=e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`,r=e=>n(e)&&typeof e.text==`string`,i=t.filter(e=>n(e)&&!r(e));if(i.length>0)return iA(i.length),e;let a=t.filter(e=>!r(e)).map(e=>typeof e==`object`&&e&&`type`in e?String(e.type):typeof e);a.length>0&&rA(a);let o=t.filter(r).map(e=>e.text).join(``);return{...e,content:o}}return typeof t==`string`?e:t===void 0?{...e,content:``}:e}var oA=class extends Nk{run(e,t){let{parentRunId:n,...r}=e,i={...r,messages:r.messages.map(aA)};return this.runNext(i,t)}},sA=`THINKING_START`,cA=`THINKING_END`,lA=`THINKING_TEXT_MESSAGE_START`,uA=`THINKING_TEXT_MESSAGE_CONTENT`,dA=`THINKING_TEXT_MESSAGE_END`,fA=class extends Nk{constructor(...e){super(...e),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(e,t){typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${e} to ${t}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(e,t).pipe(Td(e=>this.transformEvent(e)))}transformEvent(e){switch(e.type){case sA:{this.currentReasoningId=jO();let{title:t,...n}=e;return this.warnAboutTransformation(sA,I.REASONING_START),{...n,type:I.REASONING_START,messageId:this.currentReasoningId}}case lA:return this.currentMessageId=jO(),this.warnAboutTransformation(lA,I.REASONING_MESSAGE_START),{...e,type:I.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:`reasoning`};case uA:{let{delta:t,...n}=e;return this.warnAboutTransformation(uA,I.REASONING_MESSAGE_CONTENT),{...n,type:I.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??jO(),delta:t}}case dA:{let t=this.currentMessageId??jO();return this.warnAboutTransformation(dA,I.REASONING_MESSAGE_END),{...e,type:I.REASONING_MESSAGE_END,messageId:t}}case cA:{let t=this.currentReasoningId??jO();return this.warnAboutTransformation(cA,I.REASONING_END),{...e,type:I.REASONING_END,messageId:t}}default:return e}}},pA=`SUBAGENT_STARTED`,mA=`SUBAGENT_FINISHED`,hA=`SUBAGENT_ERROR`;function gA(e){if(e&&typeof e==`object`&&`subagentRunId`in e){let{subagentRunId:t,...n}=e;return n}return e}function _A(e){return e.map(e=>gA(e))}var vA=class extends Nk{warnDroppedLifecycleEvent(e){typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is dropping ${e} because the target agent predates subagent support. To remove this warning, upgrade your AG-UI integration package. To suppress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){let n={...e,messages:(e.messages??[]).map(e=>gA(e))};return this.runNext(n,t).pipe(Bd(e=>{let t=e.type;(t===pA||t===mA||t===hA)&&this.warnDroppedLifecycleEvent(t)}),jd(e=>{let t=e.type;return t!==pA&&t!==mA&&t!==hA}),Td(e=>{let t=gA(e);if(t.type===I.MESSAGES_SNAPSHOT){let e=t;if(Array.isArray(e.messages))return{...e,messages:_A(e.messages)}}if(t.type===I.RUN_FINISHED){let e=t;if(e.outcome&&Array.isArray(e.outcome.interrupts))return{...e,outcome:{...e.outcome,interrupts:e.outcome.interrupts.map(e=>gA(e))}}}if(t.type===I.RUN_STARTED){let e=t;if(e.input&&Array.isArray(e.input.messages))return{...e,input:{...e.input,messages:_A(e.input.messages)}}}return t}))}},yA=`1.0.2`,bA=!1,xA=new WeakSet,SA=(e,t)=>/^\d+\.\d+$/.test(e)?XT(e,t)>0?`newer`:`not-newer`:`uninterpretable`,CA=e=>{let t=e.protocolVersion;if(t!==void 0&&t!==`1.0`)switch(SA(t,`1.0`)){case`uninterpretable`:console.warn(`[ag-ui] The producer declared protocol version '${t}', which this client cannot interpret.`);return;case`newer`:console.warn(`[ag-ui] The producer speaks protocol ${t}; this client speaks 1.0. Unrecognised material will be stripped with warnings.`);return;case`not-newer`:return}},wA=class e{resolvePeerCeiling(t){if(this.resolvingPeerCeiling)return yA;let n=Object.getOwnPropertyDescriptor(this,`maxVersion`),r=Object.getOwnPropertyDescriptor(this,`maxProtocolVersion`),i=Object.getPrototypeOf(this);for(;i&&i!==e.prototype;)n??=Object.getOwnPropertyDescriptor(i,`maxVersion`),r??=Object.getOwnPropertyDescriptor(i,`maxProtocolVersion`),i=Object.getPrototypeOf(i);if(t===`maxVersion`&&n)return yA;let a=t===`maxProtocolVersion`?n:r;if(!a)return yA;this.resolvingPeerCeiling=!0;try{return a.get?a.get.call(this):a.value}finally{this.resolvingPeerCeiling=!1}}get maxProtocolVersion(){return this.resolvePeerCeiling(`maxProtocolVersion`)}get maxVersion(){return!this.resolvingPeerCeiling&&!bA&&(bA=!0,console.warn(`[ag-ui] AbstractAgent.maxVersion is deprecated — use maxProtocolVersion. Same value; the new name says whose version it is and that it is a ceiling.`)),this.resolvePeerCeiling(`maxVersion`)}get debug(){return this._debug}set debug(e){this._debug=LO(e),this._debugLogger=BO(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(e){this._debugLogger=typeof e==`boolean`?e?BO(LO(!0)):void 0:e}resolvedCeilingDuringConstruction(){let e=this.maxProtocolVersion;if(typeof e!=`string`||!ZT(e))throw new L(`maxProtocolVersion resolved to ${JSON.stringify(e)} during construction, which is not a version this client can compare. A ceiling read from an instance field is not available yet — return a literal from the getter.`);return e}constructor({agentId:e,description:t,threadId:n,initialMessages:r,initialState:i,debug:a}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.resolvingPeerCeiling=!1,this.agentId=e,this.description=t??``,this.threadId=n??Qc(),this.messages=AO(r??[]),this.state=AO(i??{}),this._debug=LO(a),this._debugLogger=BO(this._debug);let o=this.resolvedCeilingDuringConstruction();XT(o,`0.0.39`)<=0&&this.middlewares.unshift(new oA),XT(o,`0.0.45`)<=0&&this.middlewares.unshift(new fA),XT(o,`0.0.57`)<=0&&this.middlewares.unshift(new vA)}subscribe(e){return this.subscribers.push(e),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e)}}}use(...e){let t=e.map(e=>typeof e==`function`?new Pk(e):e);return this.middlewares.push(...t),this}async runAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??Qc();let n=this.prepareRunAgentInput(e);this.debugLogger?.lifecycle(`LIFECYCLE`,`Run started:`,{agentId:this.agentId,threadId:this.threadId});let r,i=new Set(this.messages.map(e=>e.id)),a=[{onRunStartedEvent:({event:e})=>CA(e),onRunFinishedEvent:e=>{e.outcome===`success`&&(r=e.result)}},...this.subscribers,t??{}];xA.add(n),await this.onInitialize(n,a),this.activeRunDetach$=new Bu;let o;this.activeRunCompletionPromise=new Promise(e=>{o=e}),await wd(ku(()=>[...this.middlewares,new $k].reduceRight((e,t)=>({run:n=>t.run(n,e),get messages(){return e.messages},get state(){return e.state}}),this).run(n),jk(this.debugLogger),vk(this.debugLogger),GO(this.debugLogger),e=>e.pipe(zd(this.activeRunDetach$)),e=>this.applyBeforeSourceError(n,e,a),Md(e=>(this.debugLogger?.lifecycle(`LIFECYCLE`,`Run errored:`,{agentId:this.agentId,error:e instanceof Error?e.message:String(e)}),this.isRunning=!1,this.onError(n,e,a))),Ld(()=>{this.debugLogger?.lifecycle(`LIFECYCLE`,`Run finished:`,{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,a),o?.(),o=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(Sd(null)));let s=AO(this.messages).filter(e=>!i.has(e.id));return{result:r,newMessages:s}}finally{this.isRunning=!1}}connect(e){throw new rl}async connectAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??Qc();let n=this.prepareRunAgentInput(e),r,i=new Set(this.messages.map(e=>e.id)),a=[{onRunStartedEvent:({event:e})=>CA(e),onRunFinishedEvent:e=>{e.outcome===`success`&&(r=e.result)}},...this.subscribers,t??{}];await this.onInitialize(n,a),this.activeRunDetach$=new Bu;let o;this.activeRunCompletionPromise=new Promise(e=>{o=e}),await wd(ku(()=>Ad(()=>this.connect(n)),e=>jk(this.debugLogger)(eA()(e)),vk(this.debugLogger),GO(this.debugLogger),e=>e.pipe(zd(this.activeRunDetach$)),e=>this.applyBeforeSourceError(n,e,a),Md(e=>(this.isRunning=!1,e instanceof rl?Wu:this.onError(n,e,a))),Ld(()=>{this.isRunning=!1,this.onFinalize(n,a),o?.(),o=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(Sd(null)),{defaultValue:void 0});let s=AO(this.messages).filter(e=>!i.has(e.id));return{result:r,newMessages:s}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let e=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await e}applyBeforeSourceError(e,t,n){return Ad(()=>{let r,i=t.pipe(Md(e=>(r={error:e},Wu)));return this.processApplyEvents(e,this.apply(e,i,n),n).pipe(Fd(Ad(()=>{let e=r;return e?z(()=>e.error):Wu})))})}apply(e,t,n){return UO(e,t,this,n,this.debugLogger)}processApplyEvents(e,t,n){return t.pipe(Bd(t=>{t.messages&&(this.messages=t.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),t.state!==void 0&&(this.state=t.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}))}prepareRunAgentInput(e){let t=AO(this.messages);for(let e of t)e.subagentRunId===null&&delete e.subagentRunId;let n=t.filter(e=>e.role!==`activity`);return{threadId:this.threadId,runId:e?.runId||Qc(),...XT(this.maxProtocolVersion,yA)>=0&&{protocolVersion:`1.0`},tools:AO(e?.tools??[]),context:AO(e?.context??[]),forwardedProps:AO(e?.forwardedProps??{}),state:AO(this.state),messages:n,...e?.resume===void 0?{}:{resume:AO(e.resume)}}}async onInitialize(e,t){if(xA.has(e)&&this.pendingInterrupts.length>0){let t=new Set((e.resume??[]).map(e=>e.interruptId)),n=this.pendingInterrupts.map(e=>e.id).filter(e=>!t.has(e));if(n.length>0)throw new L(`Thread has ${n.length} pending interrupt(s) not addressed by resume: ${n.join(`, `)}`);for(let t of this.pendingInterrupts)if(tA(t)&&(e.resume??[]).find(e=>e.interruptId===t.id)?.status!==`cancelled`)throw new L(`Interrupt ${t.id} expired at ${t.expiresAt} and can no longer be answered. Cancel it to continue the thread.`)}let n=await IO(t,this.messages,this.state,(t,n,r)=>t.onRunInitialized?.({messages:n,state:r,agent:this,input:e}));if(n.messages!==void 0||n.state!==void 0){if(n.messages){this.messages=n.messages;for(let e of n.messages)e.subagentRunId===null&&delete e.subagentRunId;e.messages=n.messages.filter(e=>e.role!==`activity`),t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})}n.state!==void 0&&(this.state=n.state,e.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}}onError(e,t,n){return xd(IO(n,this.messages,this.state,(n,r,i)=>n.onRunFailed?.({error:t,messages:r,state:i,agent:this,input:e}))).pipe(Td(r=>{let i=r;if((i.messages!==void 0||i.state!==void 0)&&(i.messages!==void 0&&(this.messages=i.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),i.state!==void 0&&(this.state=i.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))),i.stopPropagation!==!0){let e=String(t);if(t.name!==`AbortError`&&t.message!==`Fetch is aborted`&&t.message!==`signal is aborted without reason`&&t.message!==`component unmounted`&&e!==`component unmounted`)throw console.error(`Agent execution failed:`,t),t}return{}}))}async onFinalize(e,t){let n=await IO(t,this.messages,this.state,(t,n,r)=>t.onRunFinalized?.({messages:n,state:r,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state!==void 0&&(this.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}clone(){let e=Object.create(Object.getPrototypeOf(this));return e.agentId=this.agentId,e.description=this.description,e.threadId=this.threadId,e.messages=AO(this.messages),e.state=AO(this.state),e._debug=this._debug,e._debugLogger=this._debugLogger,e.isRunning=this.isRunning,e.subscribers=[...this.subscribers],e.middlewares=[...this.middlewares],e.pendingInterrupts=AO(this.pendingInterrupts),e}addMessage(e){this.messages.push(e),(async()=>{for(let t of this.subscribers)await t.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role===`assistant`&&e.toolCalls)for(let t of e.toolCalls)for(let e of this.subscribers)await e.onNewToolCall?.({toolCall:t,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(e){this.messages.push(...e),(async()=>{for(let t of e){for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)for(let t of this.subscribers)await t.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(e){this.messages=AO(e),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(e){this.state=AO(e),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(e){this.agentId=this.agentId??Qc();let t=this.prepareRunAgentInput(e);return[...this.middlewares,new $k].reduceRight((e,t)=>({run:n=>t.run(n,e),get messages(){return e.messages},get state(){return e.state}}),this).run(t).pipe(jk(this.debugLogger),vk(this.debugLogger),GO(this.debugLogger),ik(this.threadId,t.runId,this.agentId),e=>e.pipe(Td(e=>(this.debugLogger?.event(`LEGACY`,`Event:`,e,{type:e.type}),e))))}};function TA(e){if(!Array.isArray(e.messages))return e;let t=!1,n=e.messages.map(e=>{if(e.subagentRunId===null){t=!0;let n={...e};return delete n.subagentRunId,n}return e});return t?{...e,messages:n}:e}var EA=class extends wA{requestInit(e){return{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify(TA(e)),signal:this.abortController.signal}}runAgent(e,t){return this.abortController=e?.abortController??new AbortController,super.runAgent(e,t)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(e){super(e),this.abortController=new AbortController,this.url=e.url,this.headers=AO(e.headers??{}),this.fetch=e.fetch??((e,t)=>fetch(e,t))}run(e){return $O(qO(()=>this.fetch(this.url,this.requestInit(Mk(e)))),this.debugLogger)}clone(){let e=super.clone();e.url=this.url,e.headers=AO(this.headers??{}),e.fetch=this.fetch;let t=new AbortController,n=this.abortController.signal;return n.aborted&&t.abort(n.reason),e.abortController=t,e}},DA=M.createContext(void 0),OA=e=>{let t=M.useContext(DA);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},kA=({client:e,children:t})=>(M.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,N.jsx)(DA.Provider,{value:e,children:t})),AA={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},jA=new class{#e=AA;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 MA(e){setTimeout(e,0)}var NA=typeof window>`u`||`Deno`in globalThis;function PA(){}function FA(e,t){return typeof e==`function`?e(t):e}function IA(e){return typeof e==`number`&&e>=0&&e!==1/0}function LA(e,t){return Math.max(e+(t||0)-Date.now(),0)}function RA(e,t){return typeof e==`function`?e(t):e}function zA(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==VA(o,t.options))return!1}else if(!UA(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 BA(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(HA(t.options.mutationKey)!==HA(a))return!1}else if(!UA(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function VA(e,t){return(t?.queryKeyHashFn||HA)(e)}function HA(e){return JSON.stringify(e,(e,t)=>JA(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function UA(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)){if(t.length>e.length)return!1;for(let n=0;n500)return t;let r=qA(e)&&qA(t);if(!r&&!(JA(e)&&JA(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{jA.setTimeout(t,e)})}function ZA(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:GA(e,t)}function QA(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function $A(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var ej=Symbol();function tj(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===ej?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function nj(e,t){return typeof e==`function`?e(...t):!!e}function rj(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 ij=()=>NA,aj=()=>ij(),oj=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(){}},sj=new class extends oj{#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`}},cj=MA;function lj(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=cj,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 uj=lj(),dj=new class extends oj{#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 fj(e){return Math.min(1e3*2**e,3e4)}function pj(e){return(e??`online`)!==`online`||dj.isOnline()}var mj=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function hj(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(PA);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new mj(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>sj.isFocused()&&(e.networkMode===`always`||dj.isOnline())&&e.canRun(),p=()=>pj(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())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(m).catch(r=>{if(c())return;let i=e.retry??(aj()?0:3),a=e.retryDelay??fj,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&nf()?void 0:g(f)).then(()=>{t?h(r):_()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g(p).then(_),s)}}var gj=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),IA(this.gcTime)&&(this.#e=jA.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(aj()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(jA.clearTimeout(this.#e),this.#e=void 0)}};function _j(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=>{rj(e,()=>t.signal,()=>n=!0)},u=tj(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?$A:QA;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?yj:vj,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:vj(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 vj(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 yj(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function bj(e,t){return t?vj(e,t)!=null:!1}function xj(e,t){return!t||!e.getPreviousPageParam?!1:yj(e,t)!=null}var Sj=class extends gj{#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=Tj(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=Tj(this.options);e.data!==void 0&&(this.setState(wj(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=ZA(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(PA).catch(PA):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=>RA(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===ej||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>RA(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:!LA(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){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({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=tj(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`?_j(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=hj({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof mj&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.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 mj){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(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,...Cj(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...wj(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),uj.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Cj(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:pj(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function wj(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Tj(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 Ej=class extends oj{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Oj(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return kj(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return kj(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 RA(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&&!KA(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Aj(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||RA(this.options.enabled,this.#t)!==RA(t.enabled,this.#t)||RA(this.options.staleTime,this.#t)!==RA(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||RA(this.options.enabled,this.#t)!==RA(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return KA(this.getCurrentResult(),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),Reflect.get(e,n))})}trackProp(e){this.#p.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),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(PA)),t}#h(e){return!aj()&&RA(this.options.enabled,this.#t)!==!1&&IA(e)}#g(){this.#b();let e=RA(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=LA(this.#r.dataUpdatedAt,e)+1;this.#u=jA.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return RA(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=jA.setInterval(()=>{(this.options.refetchIntervalInBackground||sj.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(jA.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(jA.clearInterval(this.#d),this.#d=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&&Oj(e,t),o=i&&Aj(e,n,t,r);(a||o)&&(l={...l,...Cj(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.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=ZA(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=ZA(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{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&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:jj(e,t),refetch:this.refetch,isEnabled:RA(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),KA(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);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)})})();uj.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#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()}};function Dj(e,t){return RA(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||RA(t.retryOnMount,e)!==!1)}function Oj(e,t){return Dj(e,t)||e.state.data!==void 0&&kj(e,t,t.refetchOnMount)}function kj(e,t,n){if(RA(t.enabled,e)!==!1&&RA(t.staleTime,e)!==`static`){let r=RA(n,e);return r===`always`||r!==!1&&jj(e,t)}return!1}function Aj(e,t,n,r){return(e!==t||RA(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&jj(e,n)}function jj(e,t){return RA(t.enabled,e)!==!1&&e.isStaleByTime(RA(t.staleTime,e))}var Mj=class extends Ej{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:bj(t,n.data),hasPreviousPage:xj(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}},Nj=class extends gj{#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||Pj(),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.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=hj({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)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),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:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}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.#r===r&&(this.#r=void 0),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),uj.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Pj(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var Fj=class extends oj{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new Nj({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=Ij(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=Ij(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=Ij(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=Ij(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){uj.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=>BA(t,e))}findAll(e={}){return this.getAll().filter(t=>BA(e,t))}notify(e){uj.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return uj.batch(()=>Promise.all(e.map(e=>e.continue().catch(PA))))}};function Ij(e){return e.options.scope?.id}var Lj=class extends oj{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??VA(r,t),a=this.get(i);return a||(a=new Sj({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){this.#e.get(e.queryHash)===e&&(e.destroy(),this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){uj.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=>zA(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>zA(e,t)):t}notify(e){uj.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){uj.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){uj.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Rj=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Lj,this.#t=e.mutationCache||new Fj,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=sj.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=dj.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(RA(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=FA(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return uj.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;uj.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return uj.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=uj.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(PA).catch(PA)}invalidateQueries(e,t={}){return uj.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=uj.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(PA)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(PA)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(RA(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(RA(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(PA).catch(PA)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(PA).catch(PA)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return dj.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(HA(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{UA(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(HA(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{UA(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||=VA(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===ej&&(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()}},zj=M.createContext(!1),Bj=()=>M.useContext(zj);zj.Provider;function Vj(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Hj=M.createContext(Vj()),Uj=()=>M.useContext(Hj),Wj=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?nj(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},Gj=e=>{M.useEffect(()=>{e.clearReset()},[e])},Kj=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||nj(n,[e.error,r])),qj=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))}},Jj=(e,t)=>e?.suspense&&t.isPending,Yj=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Xj(e,t,n){let r=Bj(),i=Uj(),a=OA(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,qj(o),Wj(o,i,s),Gj(i);let[l]=M.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(M.useSyncExternalStore(M.useCallback(e=>{let t=d?l.subscribe(uj.batchCalls(e)):PA;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),M.useEffect(()=>{l.setOptions(o)},[o,l]),Jj(o,u))throw Yj(o,l,i);if(Kj({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function Zj(e,t){return Xj(e,Ej,t)}function Qj(e,t){return Xj(e,Mj,t)}var $j=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M228,128a12,12,0,0,1-12,12H69l51.52,51.51a12,12,0,0,1-17,17l-72-72a12,12,0,0,1,0-17l72-72a12,12,0,0,1,17,17L69,116H216A12,12,0,0,1,228,128Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M112,56V200L40,128Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M216,120H120V56a8,8,0,0,0-13.66-5.66l-72,72a8,8,0,0,0,0,11.32l72,72A8,8,0,0,0,120,200V136h96a8,8,0,0,0,0-16ZM104,180.69,51.31,128,104,75.31Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224,128a8,8,0,0,1-8,8H120v64a8,8,0,0,1-13.66,5.66l-72-72a8,8,0,0,1,0-11.32l72-72A8,8,0,0,1,120,56v64h96A8,8,0,0,1,224,128Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M222,128a6,6,0,0,1-6,6H54.49l61.75,61.76a6,6,0,1,1-8.48,8.48l-72-72a6,6,0,0,1,0-8.48l72-72a6,6,0,0,1,8.48,8.48L54.49,122H216A6,6,0,0,1,222,128Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224,128a8,8,0,0,1-8,8H59.31l58.35,58.34a8,8,0,0,1-11.32,11.32l-72-72a8,8,0,0,1,0-11.32l72-72a8,8,0,0,1,11.32,11.32L59.31,120H216A8,8,0,0,1,224,128Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M220,128a4,4,0,0,1-4,4H49.66l65.17,65.17a4,4,0,0,1-5.66,5.66l-72-72a4,4,0,0,1,0-5.66l72-72a4,4,0,0,1,5.66,5.66L49.66,124H216A4,4,0,0,1,220,128Z`}))]]),eM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224.49,136.49l-72,72a12,12,0,0,1-17-17L187,140H40a12,12,0,0,1,0-24H187L135.51,64.48a12,12,0,0,1,17-17l72,72A12,12,0,0,1,224.49,136.49Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,128l-72,72V56Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M221.66,122.34l-72-72A8,8,0,0,0,136,56v64H40a8,8,0,0,0,0,16h96v64a8,8,0,0,0,13.66,5.66l72-72A8,8,0,0,0,221.66,122.34ZM152,180.69V75.31L204.69,128Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M221.66,133.66l-72,72A8,8,0,0,1,136,200V136H40a8,8,0,0,1,0-16h96V56a8,8,0,0,1,13.66-5.66l72,72A8,8,0,0,1,221.66,133.66Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M220.24,132.24l-72,72a6,6,0,0,1-8.48-8.48L201.51,134H40a6,6,0,0,1,0-12H201.51L139.76,60.24a6,6,0,0,1,8.48-8.48l72,72A6,6,0,0,1,220.24,132.24Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M221.66,133.66l-72,72a8,8,0,0,1-11.32-11.32L196.69,136H40a8,8,0,0,1,0-16H196.69L138.34,61.66a8,8,0,0,1,11.32-11.32l72,72A8,8,0,0,1,221.66,133.66Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M218.83,130.83l-72,72a4,4,0,0,1-5.66-5.66L206.34,132H40a4,4,0,0,1,0-8H206.34L141.17,58.83a4,4,0,0,1,5.66-5.66l72,72A4,4,0,0,1,218.83,130.83Z`}))]]),tM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232,44H160a43.86,43.86,0,0,0-32,13.85A43.86,43.86,0,0,0,96,44H24A12,12,0,0,0,12,56V200a12,12,0,0,0,12,12H96a20,20,0,0,1,20,20,12,12,0,0,0,24,0,20,20,0,0,1,20-20h72a12,12,0,0,0,12-12V56A12,12,0,0,0,232,44ZM96,188H36V68H96a20,20,0,0,1,20,20V192.81A43.79,43.79,0,0,0,96,188Zm124,0H160a43.71,43.71,0,0,0-20,4.83V88a20,20,0,0,1,20-20h60Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232,56V200H160a32,32,0,0,0-32,32,32,32,0,0,0-32-32H24V56H96a32,32,0,0,1,32,32,32,32,0,0,1,32-32Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M232,48H160a40,40,0,0,0-32,16A40,40,0,0,0,96,48H24a8,8,0,0,0-8,8V200a8,8,0,0,0,8,8H96a24,24,0,0,1,24,24,8,8,0,0,0,16,0,24,24,0,0,1,24-24h72a8,8,0,0,0,8-8V56A8,8,0,0,0,232,48ZM96,192H32V64H96a24,24,0,0,1,24,24V200A39.81,39.81,0,0,0,96,192Zm128,0H160a39.81,39.81,0,0,0-24,8V88a24,24,0,0,1,24-24h64Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M240,56V200a8,8,0,0,1-8,8H160a24,24,0,0,0-24,23.94,7.9,7.9,0,0,1-5.12,7.55A8,8,0,0,1,120,232a24,24,0,0,0-24-24H24a8,8,0,0,1-8-8V56a8,8,0,0,1,8-8H88a32,32,0,0,1,32,32v87.73a8.17,8.17,0,0,0,7.47,8.25,8,8,0,0,0,8.53-8V80a32,32,0,0,1,32-32h64A8,8,0,0,1,240,56Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232,50H160a38,38,0,0,0-32,17.55A38,38,0,0,0,96,50H24a6,6,0,0,0-6,6V200a6,6,0,0,0,6,6H96a26,26,0,0,1,26,26,6,6,0,0,0,12,0,26,26,0,0,1,26-26h72a6,6,0,0,0,6-6V56A6,6,0,0,0,232,50ZM96,194H30V62H96a26,26,0,0,1,26,26V204.31A37.86,37.86,0,0,0,96,194Zm130,0H160a37.87,37.87,0,0,0-26,10.32V88a26,26,0,0,1,26-26h66Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232,48H160a40,40,0,0,0-32,16A40,40,0,0,0,96,48H24a8,8,0,0,0-8,8V200a8,8,0,0,0,8,8H96a24,24,0,0,1,24,24,8,8,0,0,0,16,0,24,24,0,0,1,24-24h72a8,8,0,0,0,8-8V56A8,8,0,0,0,232,48ZM96,192H32V64H96a24,24,0,0,1,24,24V200A39.81,39.81,0,0,0,96,192Zm128,0H160a39.81,39.81,0,0,0-24,8V88a24,24,0,0,1,24-24h64Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232,52H160a36,36,0,0,0-32,19.54A36,36,0,0,0,96,52H24a4,4,0,0,0-4,4V200a4,4,0,0,0,4,4H96a28,28,0,0,1,28,28,4,4,0,0,0,8,0,28,28,0,0,1,28-28h72a4,4,0,0,0,4-4V56A4,4,0,0,0,232,52ZM96,196H28V60H96a28,28,0,0,1,28,28V209.4A35.93,35.93,0,0,0,96,196Zm132,0H160a35.94,35.94,0,0,0-28,13.41V88a28,28,0,0,1,28-28h68Z`}))]]),nM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M144,128a16,16,0,1,1-16-16A16,16,0,0,1,144,128ZM60,112a16,16,0,1,0,16,16A16,16,0,0,0,60,112Zm136,0a16,16,0,1,0,16,16A16,16,0,0,0,196,112Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M240,96v64a16,16,0,0,1-16,16H32a16,16,0,0,1-16-16V96A16,16,0,0,1,32,80H224A16,16,0,0,1,240,96Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M140,128a12,12,0,1,1-12-12A12,12,0,0,1,140,128Zm56-12a12,12,0,1,0,12,12A12,12,0,0,0,196,116ZM60,116a12,12,0,1,0,12,12A12,12,0,0,0,60,116Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224,80H32A16,16,0,0,0,16,96v64a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V96A16,16,0,0,0,224,80ZM60,140a12,12,0,1,1,12-12A12,12,0,0,1,60,140Zm68,0a12,12,0,1,1,12-12A12,12,0,0,1,128,140Zm68,0a12,12,0,1,1,12-12A12,12,0,0,1,196,140Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M138,128a10,10,0,1,1-10-10A10,10,0,0,1,138,128ZM60,118a10,10,0,1,0,10,10A10,10,0,0,0,60,118Zm136,0a10,10,0,1,0,10,10A10,10,0,0,0,196,118Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M140,128a12,12,0,1,1-12-12A12,12,0,0,1,140,128Zm56-12a12,12,0,1,0,12,12A12,12,0,0,0,196,116ZM60,116a12,12,0,1,0,12,12A12,12,0,0,0,60,116Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M136,128a8,8,0,1,1-8-8A8,8,0,0,1,136,128Zm-76-8a8,8,0,1,0,8,8A8,8,0,0,0,60,120Zm136,0a8,8,0,1,0,8,8A8,8,0,0,0,196,120Z`}))]]),rM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232.49,215.51,185,168a92.12,92.12,0,1,0-17,17l47.53,47.54a12,12,0,0,0,17-17ZM44,112a68,68,0,1,1,68,68A68.07,68.07,0,0,1,44,112Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M192,112a80,80,0,1,1-80-80A80,80,0,0,1,192,112Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M229.66,218.34,179.6,168.28a88.21,88.21,0,1,0-11.32,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM40,112a72,72,0,1,1,72,72A72.08,72.08,0,0,1,40,112Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M168,112a56,56,0,1,1-56-56A56,56,0,0,1,168,112Zm61.66,117.66a8,8,0,0,1-11.32,0l-50.06-50.07a88,88,0,1,1,11.32-11.31l50.06,50.06A8,8,0,0,1,229.66,229.66ZM112,184a72,72,0,1,0-72-72A72.08,72.08,0,0,0,112,184Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M228.24,219.76l-51.38-51.38a86.15,86.15,0,1,0-8.48,8.48l51.38,51.38a6,6,0,0,0,8.48-8.48ZM38,112a74,74,0,1,1,74,74A74.09,74.09,0,0,1,38,112Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M229.66,218.34l-50.07-50.06a88.11,88.11,0,1,0-11.31,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM40,112a72,72,0,1,1,72,72A72.08,72.08,0,0,1,40,112Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M226.83,221.17l-52.7-52.7a84.1,84.1,0,1,0-5.66,5.66l52.7,52.7a4,4,0,0,0,5.66-5.66ZM36,112a76,76,0,1,1,76,76A76.08,76.08,0,0,1,36,112Z`}))]]),iM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M236.37,139.4a12,12,0,0,0-12-3A84.07,84.07,0,0,1,119.6,31.59a12,12,0,0,0-15-15A108.86,108.86,0,0,0,49.69,55.07,108,108,0,0,0,136,228a107.09,107.09,0,0,0,64.93-21.69,108.86,108.86,0,0,0,38.44-54.94A12,12,0,0,0,236.37,139.4Zm-49.88,47.74A84,84,0,0,1,68.86,69.51,84.93,84.93,0,0,1,92.27,48.29Q92,52.13,92,56A108.12,108.12,0,0,0,200,164q3.87,0,7.71-.27A84.79,84.79,0,0,1,186.49,187.14Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M227.89,147.89A96,96,0,1,1,108.11,28.11,96.09,96.09,0,0,0,227.89,147.89Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M233.54,142.23a8,8,0,0,0-8-2,88.08,88.08,0,0,1-109.8-109.8,8,8,0,0,0-10-10,104.84,104.84,0,0,0-52.91,37A104,104,0,0,0,136,224a103.09,103.09,0,0,0,62.52-20.88,104.84,104.84,0,0,0,37-52.91A8,8,0,0,0,233.54,142.23ZM188.9,190.34A88,88,0,0,1,65.66,67.11a89,89,0,0,1,31.4-26A106,106,0,0,0,96,56,104.11,104.11,0,0,0,200,160a106,106,0,0,0,14.92-1.06A89,89,0,0,1,188.9,190.34Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M235.54,150.21a104.84,104.84,0,0,1-37,52.91A104,104,0,0,1,32,120,103.09,103.09,0,0,1,52.88,57.48a104.84,104.84,0,0,1,52.91-37,8,8,0,0,1,10,10,88.08,88.08,0,0,0,109.8,109.8,8,8,0,0,1,10,10Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232.13,143.64a6,6,0,0,0-6-1.49A90.07,90.07,0,0,1,113.86,29.85a6,6,0,0,0-7.49-7.48A102.88,102.88,0,0,0,54.48,58.68,102,102,0,0,0,197.32,201.52a102.88,102.88,0,0,0,36.31-51.89A6,6,0,0,0,232.13,143.64Zm-42,48.29a90,90,0,0,1-126-126A90.9,90.9,0,0,1,99.65,37.66,102.06,102.06,0,0,0,218.34,156.35,90.9,90.9,0,0,1,190.1,191.93Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M233.54,142.23a8,8,0,0,0-8-2,88.08,88.08,0,0,1-109.8-109.8,8,8,0,0,0-10-10,104.84,104.84,0,0,0-52.91,37A104,104,0,0,0,136,224a103.09,103.09,0,0,0,62.52-20.88,104.84,104.84,0,0,0,37-52.91A8,8,0,0,0,233.54,142.23ZM188.9,190.34A88,88,0,0,1,65.66,67.11a89,89,0,0,1,31.4-26A106,106,0,0,0,96,56,104.11,104.11,0,0,0,200,160a106,106,0,0,0,14.92-1.06A89,89,0,0,1,188.9,190.34Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M230.72,145.06a4,4,0,0,0-4-1A92.08,92.08,0,0,1,111.94,29.27a4,4,0,0,0-5-5A100.78,100.78,0,0,0,56.08,59.88a100,100,0,0,0,140,140,100.78,100.78,0,0,0,35.59-50.87A4,4,0,0,0,230.72,145.06ZM191.3,193.53A92,92,0,0,1,62.47,64.7a93,93,0,0,1,39.88-30.35,100.09,100.09,0,0,0,119.3,119.3A93,93,0,0,1,191.3,193.53Z`}))]]),aM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M230.14,70.54,185.46,25.85a20,20,0,0,0-28.29,0L33.86,149.17A19.85,19.85,0,0,0,28,163.31V208a20,20,0,0,0,20,20H92.69a19.86,19.86,0,0,0,14.14-5.86L230.14,98.82a20,20,0,0,0,0-28.28ZM91,204H52V165l84-84,39,39ZM192,103,153,64l18.34-18.34,39,39Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M221.66,90.34,192,120,136,64l29.66-29.66a8,8,0,0,1,11.31,0L221.66,79A8,8,0,0,1,221.66,90.34Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM92.69,208H48V163.31l88-88L180.69,120ZM192,108.68,147.31,64l24-24L216,84.68Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM192,108.68,147.31,64l24-24L216,84.68Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M225.9,74.78,181.21,30.09a14,14,0,0,0-19.8,0L38.1,153.41a13.94,13.94,0,0,0-4.1,9.9V208a14,14,0,0,0,14,14H92.69a13.94,13.94,0,0,0,9.9-4.1L225.9,94.58a14,14,0,0,0,0-19.8ZM94.1,209.41a2,2,0,0,1-1.41.59H48a2,2,0,0,1-2-2V163.31a2,2,0,0,1,.59-1.41L136,72.48,183.51,120ZM217.41,86.1,192,111.51,144.49,64,169.9,38.58a2,2,0,0,1,2.83,0l44.68,44.69a2,2,0,0,1,0,2.83Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM92.69,208H48V163.31l88-88L180.69,120ZM192,108.68,147.31,64l24-24L216,84.68Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224.49,76.2,179.8,31.51a12,12,0,0,0-17,0L133.17,61.17h0L39.52,154.83A11.9,11.9,0,0,0,36,163.31V208a12,12,0,0,0,12,12H92.69a12,12,0,0,0,8.48-3.51L224.48,93.17a12,12,0,0,0,0-17Zm-129,134.63A4,4,0,0,1,92.69,212H48a4,4,0,0,1-4-4V163.31a4,4,0,0,1,1.17-2.83L136,69.65,186.34,120ZM218.83,87.51,192,114.34,141.66,64l26.82-26.83a4,4,0,0,1,5.66,0l44.69,44.68a4,4,0,0,1,0,5.66Z`}))]]),oM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M240.49,15.51a12,12,0,0,0-17,0L173.94,65.09l-2.54-2.55a36.05,36.05,0,0,0-50.91,0L100,83l-3.51-3.52a12,12,0,0,0-17,17L83,100,62.54,120.49a36,36,0,0,0,0,50.91l2.55,2.54L15.51,223.51a12,12,0,0,0,17,17l49.57-49.58,2.54,2.55a36.06,36.06,0,0,0,50.91,0L156,173l3.51,3.52a12,12,0,0,0,17-17L173,156l20.49-20.49a36,36,0,0,0,0-50.91l-2.55-2.54,49.58-49.57A12,12,0,0,0,240.49,15.51Zm-121.95,161a12,12,0,0,1-17,0L79.51,154.43a12,12,0,0,1,0-17L100,117l39,39Zm58-57.95h0L156,139l-39-39,20.49-20.49a12,12,0,0,1,17,0l22.06,22.06a12,12,0,0,1,0,17ZM85.27,33.37a12,12,0,0,1,21.46-10.74l8,16A12,12,0,1,1,93.27,49.37Zm-68,57.26a12,12,0,0,1,16.1-5.36l16,8a12,12,0,1,1-10.74,21.46l-16-8A12,12,0,0,1,17.27,90.63Zm221.46,74.74a12,12,0,0,1-16.1,5.36l-16-8a12,12,0,0,1,10.74-21.46l16,8A12,12,0,0,1,238.73,165.37Zm-68,57.26a12,12,0,1,1-21.46,10.74l-8-16a12,12,0,0,1,21.46-10.74Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M185,127,127,185a24,24,0,0,1-33.94,0L71,162.91A24,24,0,0,1,71,129L129,71a24,24,0,0,1,33.94,0L185,93.09A24,24,0,0,1,185,127Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M237.66,18.34a8,8,0,0,0-11.32,0l-52.4,52.41-5.37-5.38a32.05,32.05,0,0,0-45.26,0L100,88.69l-6.34-6.35A8,8,0,0,0,82.34,93.66L88.69,100,65.37,123.31a32,32,0,0,0,0,45.26l5.38,5.37-52.41,52.4a8,8,0,0,0,11.32,11.32l52.4-52.41,5.37,5.38a32.06,32.06,0,0,0,45.26,0L156,167.31l6.34,6.35a8,8,0,0,0,11.32-11.32L167.31,156l23.32-23.31a32,32,0,0,0,0-45.26l-5.38-5.37,52.41-52.4A8,8,0,0,0,237.66,18.34Zm-116.29,161a16,16,0,0,1-22.62,0L76.69,157.25a16,16,0,0,1,0-22.62L100,111.31,144.69,156Zm57.94-57.94h0L156,144.69,111.31,100l23.32-23.31a16,16,0,0,1,22.62,0l22.06,22a16,16,0,0,1,0,22.63ZM88.57,35A8,8,0,0,1,103.43,29l8,20A8,8,0,0,1,96.57,55ZM24.57,93A8,8,0,0,1,35,88.57l20,8A8,8,0,0,1,49,111.43l-20-8A8,8,0,0,1,24.57,93ZM231.43,163a8,8,0,0,1-10.4,4.46l-20-8A8,8,0,1,1,207,144.57l20,8A8,8,0,0,1,231.43,163Zm-64,58.06A8,8,0,0,1,152.57,227l-8-20A8,8,0,0,1,159.43,201Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M88.57,35A8,8,0,0,1,103.43,29l8,20A8,8,0,0,1,96.57,55ZM29,103.43l20,8A8,8,0,1,0,55,96.57l-20-8A8,8,0,0,0,29,103.43ZM227,152.57l-20-8A8,8,0,1,0,201,159.43l20,8A8,8,0,0,0,227,152.57ZM159.43,201A8,8,0,0,0,144.57,207l8,20A8,8,0,1,0,167.43,221ZM237.91,18.52a8,8,0,0,0-11.5-.18L174,70.75l-5.38-5.38a32,32,0,0,0-45.28,0L106.14,82.54a4,4,0,0,0,0,5.66l61.7,61.66a4,4,0,0,0,5.66,0l16.74-16.74a32.76,32.76,0,0,0,9.81-22.52,31.82,31.82,0,0,0-9.37-23.17l-5.38-5.37,52.2-52.17A8.22,8.22,0,0,0,237.91,18.52ZM85.64,90.34a8,8,0,0,0-11.49.18,8.22,8.22,0,0,0,.41,11.37L80.67,108,65.34,123.31A31.82,31.82,0,0,0,56,146.47,32.75,32.75,0,0,0,65.77,169l5,4.94L18.49,226.13a8.21,8.21,0,0,0-.61,11.1,8,8,0,0,0,11.72.43L82,185.25l5.37,5.38a32.1,32.1,0,0,0,45.29,0L148,175.31l6.34,6.35a8,8,0,0,0,11.32-11.32Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M236.24,19.76a6,6,0,0,0-8.48,0L173.94,73.57l-6.79-6.78a30,30,0,0,0-42.42,0L100,91.51l-7.76-7.75a6,6,0,0,0-8.48,8.48L91.51,100,66.79,124.73a30,30,0,0,0,0,42.42l6.78,6.79L19.76,227.76a6,6,0,1,0,8.48,8.48l53.82-53.81,6.79,6.78a30,30,0,0,0,42.42,0L156,164.49l7.76,7.75a6,6,0,0,0,8.48-8.48L164.49,156l24.72-24.73a30,30,0,0,0,0-42.42l-6.78-6.79,53.81-53.82A6,6,0,0,0,236.24,19.76Zm-113.45,161a18,18,0,0,1-25.46,0L75.27,158.67a18,18,0,0,1,0-25.46L100,108.49,147.51,156Zm57.94-57.94L156,147.51,108.49,100l24.72-24.73a18,18,0,0,1,25.46,0l22.06,22.06a18,18,0,0,1,0,25.46ZM90.43,34.23a6,6,0,0,1,11.14-4.46l8,20a6,6,0,1,1-11.14,4.46Zm-64,59.54a6,6,0,0,1,7.8-3.34l20,8a6,6,0,1,1-4.46,11.14l-20-8A6,6,0,0,1,26.43,93.77Zm203.14,68.46a6,6,0,0,1-7.8,3.34l-20-8a6,6,0,0,1,4.46-11.14l20,8A6,6,0,0,1,229.57,162.23Zm-64,59.54a6,6,0,1,1-11.14,4.46l-8-20a6,6,0,0,1,11.14-4.46Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M237.66,18.34a8,8,0,0,0-11.32,0l-52.4,52.41-5.37-5.38a32.05,32.05,0,0,0-45.26,0L100,88.69l-6.34-6.35A8,8,0,0,0,82.34,93.66L88.69,100,65.37,123.31a32,32,0,0,0,0,45.26l5.38,5.37-52.41,52.4a8,8,0,0,0,11.32,11.32l52.4-52.41,5.37,5.38a32,32,0,0,0,45.26,0L156,167.31l6.34,6.35a8,8,0,0,0,11.32-11.32L167.31,156l23.32-23.31a32,32,0,0,0,0-45.26l-5.38-5.37,52.41-52.4A8,8,0,0,0,237.66,18.34Zm-116.29,161a16,16,0,0,1-22.62,0L76.69,157.25a16,16,0,0,1,0-22.62L100,111.31,144.69,156Zm57.94-57.94L156,144.69,111.31,100l23.32-23.31a16,16,0,0,1,22.62,0l22.06,22A16,16,0,0,1,179.31,121.37ZM88.57,35A8,8,0,0,1,103.43,29l8,20A8,8,0,0,1,96.57,55ZM24.57,93A8,8,0,0,1,35,88.57l20,8A8,8,0,0,1,49,111.43l-20-8A8,8,0,0,1,24.57,93ZM231.43,163a8,8,0,0,1-10.4,4.46l-20-8A8,8,0,1,1,207,144.57l20,8A8,8,0,0,1,231.43,163Zm-64,58.06A8,8,0,0,1,152.57,227l-8-20A8,8,0,0,1,159.43,201Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M234.83,21.17a4,4,0,0,0-5.66,0L173.94,76.4l-8.2-8.2a28,28,0,0,0-39.6,0L100,94.34l-9.17-9.17a4,4,0,0,0-5.66,5.66L94.34,100,68.2,126.14a28,28,0,0,0,0,39.6l8.2,8.2L21.17,229.17a4,4,0,0,0,5.66,5.66L82.06,179.6l8.2,8.2a28,28,0,0,0,39.6,0L156,161.66l9.17,9.17a4,4,0,0,0,5.66-5.66L161.66,156l26.14-26.14a28,28,0,0,0,0-39.6l-8.2-8.2,55.23-55.23A4,4,0,0,0,234.83,21.17Zm-110.63,161a20,20,0,0,1-28.28,0L73.86,160.08a20,20,0,0,1,0-28.28L100,105.66,150.34,156Zm57.94-57.94L156,150.34,105.66,100,131.8,73.86a20,20,0,0,1,28.28,0l22.06,22.06A20,20,0,0,1,182.14,124.2ZM92.29,33.49a4,4,0,1,1,7.42-3l8,20a4,4,0,0,1-2.22,5.2A3.91,3.91,0,0,1,104,56a4,4,0,0,1-3.71-2.51Zm-64,61a4,4,0,0,1,5.2-2.22l20,8A4,4,0,0,1,52,108a3.91,3.91,0,0,1-1.49-.29l-20-8A4,4,0,0,1,28.29,94.51Zm199.42,67A4,4,0,0,1,224,164a3.91,3.91,0,0,1-1.49-.29l-20-8a4,4,0,1,1,3-7.42l20,8A4,4,0,0,1,227.71,161.49Zm-64,61a4,4,0,0,1-2.22,5.2A3.91,3.91,0,0,1,160,228a4,4,0,0,1-3.71-2.51l-8-20a4,4,0,0,1,7.42-3Z`}))]]),sM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M228,128a12,12,0,0,1-12,12H140v76a12,12,0,0,1-24,0V140H40a12,12,0,0,1,0-24h76V40a12,12,0,0,1,24,0v76h76A12,12,0,0,1,228,128Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,56V200a16,16,0,0,1-16,16H56a16,16,0,0,1-16-16V56A16,16,0,0,1,56,40H200A16,16,0,0,1,216,56Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M224,128a8,8,0,0,1-8,8H136v80a8,8,0,0,1-16,0V136H40a8,8,0,0,1,0-16h80V40a8,8,0,0,1,16,0v80h80A8,8,0,0,1,224,128Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M208,32H48A16,16,0,0,0,32,48V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V48A16,16,0,0,0,208,32ZM184,136H136v48a8,8,0,0,1-16,0V136H72a8,8,0,0,1,0-16h48V72a8,8,0,0,1,16,0v48h48a8,8,0,0,1,0,16Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M222,128a6,6,0,0,1-6,6H134v82a6,6,0,0,1-12,0V134H40a6,6,0,0,1,0-12h82V40a6,6,0,0,1,12,0v82h82A6,6,0,0,1,222,128Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224,128a8,8,0,0,1-8,8H136v80a8,8,0,0,1-16,0V136H40a8,8,0,0,1,0-16h80V40a8,8,0,0,1,16,0v80h80A8,8,0,0,1,224,128Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M220,128a4,4,0,0,1-4,4H132v84a4,4,0,0,1-8,0V132H40a4,4,0,0,1,0-8h84V40a4,4,0,0,1,8,0v84h84A4,4,0,0,1,220,128Z`}))]]),cM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M124,216a12,12,0,0,1-12,12H48a12,12,0,0,1-12-12V40A12,12,0,0,1,48,28h64a12,12,0,0,1,0,24H60V204h52A12,12,0,0,1,124,216Zm108.49-96.49-40-40a12,12,0,0,0-17,17L195,116H112a12,12,0,0,0,0,24h83l-19.52,19.51a12,12,0,0,0,17,17l40-40A12,12,0,0,0,232.49,119.51Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224,56V200a16,16,0,0,1-16,16H48V40H208A16,16,0,0,1,224,56Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M120,216a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V40a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H56V208h56A8,8,0,0,1,120,216Zm109.66-93.66-40-40a8,8,0,0,0-11.32,11.32L204.69,120H112a8,8,0,0,0,0,16h92.69l-26.35,26.34a8,8,0,0,0,11.32,11.32l40-40A8,8,0,0,0,229.66,122.34Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M120,216a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V40a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H56V208h56A8,8,0,0,1,120,216Zm109.66-93.66-40-40A8,8,0,0,0,176,88v32H112a8,8,0,0,0,0,16h64v32a8,8,0,0,0,13.66,5.66l40-40A8,8,0,0,0,229.66,122.34Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M118,216a6,6,0,0,1-6,6H48a6,6,0,0,1-6-6V40a6,6,0,0,1,6-6h64a6,6,0,0,1,0,12H54V210h58A6,6,0,0,1,118,216Zm110.24-92.24-40-40a6,6,0,0,0-8.48,8.48L209.51,122H112a6,6,0,0,0,0,12h97.51l-29.75,29.76a6,6,0,1,0,8.48,8.48l40-40A6,6,0,0,0,228.24,123.76Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M120,216a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V40a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H56V208h56A8,8,0,0,1,120,216Zm109.66-93.66-40-40a8,8,0,0,0-11.32,11.32L204.69,120H112a8,8,0,0,0,0,16h92.69l-26.35,26.34a8,8,0,0,0,11.32,11.32l40-40A8,8,0,0,0,229.66,122.34Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M116,216a4,4,0,0,1-4,4H48a4,4,0,0,1-4-4V40a4,4,0,0,1,4-4h64a4,4,0,0,1,0,8H52V212h60A4,4,0,0,1,116,216Zm110.83-90.83-40-40a4,4,0,0,0-5.66,5.66L214.34,124H112a4,4,0,0,0,0,8H214.34l-33.17,33.17a4,4,0,0,0,5.66,5.66l40-40A4,4,0,0,0,226.83,125.17Z`}))]]),lM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M199,125.31l-49.88-18.39L130.69,57a19.92,19.92,0,0,0-37.38,0L74.92,106.92,25,125.31a19.92,19.92,0,0,0,0,37.38l49.88,18.39L93.31,231a19.92,19.92,0,0,0,37.38,0l18.39-49.88L199,162.69a19.92,19.92,0,0,0,0-37.38Zm-63.38,35.16a12,12,0,0,0-7.11,7.11L112,212.28l-16.47-44.7a12,12,0,0,0-7.11-7.11L43.72,144l44.7-16.47a12,12,0,0,0,7.11-7.11L112,75.72l16.47,44.7a12,12,0,0,0,7.11,7.11L180.28,144ZM140,40a12,12,0,0,1,12-12h12V16a12,12,0,0,1,24,0V28h12a12,12,0,0,1,0,24H188V64a12,12,0,0,1-24,0V52H152A12,12,0,0,1,140,40ZM252,88a12,12,0,0,1-12,12h-4v4a12,12,0,0,1-24,0v-4h-4a12,12,0,0,1,0-24h4V72a12,12,0,0,1,24,0v4h4A12,12,0,0,1,252,88Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M194.82,151.43l-55.09,20.3-20.3,55.09a7.92,7.92,0,0,1-14.86,0l-20.3-55.09-55.09-20.3a7.92,7.92,0,0,1,0-14.86l55.09-20.3,20.3-55.09a7.92,7.92,0,0,1,14.86,0l20.3,55.09,55.09,20.3A7.92,7.92,0,0,1,194.82,151.43Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M197.58,129.06,146,110l-19-51.62a15.92,15.92,0,0,0-29.88,0L78,110l-51.62,19a15.92,15.92,0,0,0,0,29.88L78,178l19,51.62a15.92,15.92,0,0,0,29.88,0L146,178l51.62-19a15.92,15.92,0,0,0,0-29.88ZM137,164.22a8,8,0,0,0-4.74,4.74L112,223.85,91.78,169A8,8,0,0,0,87,164.22L32.15,144,87,123.78A8,8,0,0,0,91.78,119L112,64.15,132.22,119a8,8,0,0,0,4.74,4.74L191.85,144ZM144,40a8,8,0,0,1,8-8h16V16a8,8,0,0,1,16,0V32h16a8,8,0,0,1,0,16H184V64a8,8,0,0,1-16,0V48H152A8,8,0,0,1,144,40ZM248,88a8,8,0,0,1-8,8h-8v8a8,8,0,0,1-16,0V96h-8a8,8,0,0,1,0-16h8V72a8,8,0,0,1,16,0v8h8A8,8,0,0,1,248,88Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M208,144a15.78,15.78,0,0,1-10.42,14.94L146,178l-19,51.62a15.92,15.92,0,0,1-29.88,0L78,178l-51.62-19a15.92,15.92,0,0,1,0-29.88L78,110l19-51.62a15.92,15.92,0,0,1,29.88,0L146,110l51.62,19A15.78,15.78,0,0,1,208,144ZM152,48h16V64a8,8,0,0,0,16,0V48h16a8,8,0,0,0,0-16H184V16a8,8,0,0,0-16,0V32H152a8,8,0,0,0,0,16Zm88,32h-8V72a8,8,0,0,0-16,0v8h-8a8,8,0,0,0,0,16h8v8a8,8,0,0,0,16,0V96h8a8,8,0,0,0,0-16Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M196.89,130.94,144.4,111.6,125.06,59.11a13.92,13.92,0,0,0-26.12,0L79.6,111.6,27.11,130.94a13.92,13.92,0,0,0,0,26.12L79.6,176.4l19.34,52.49a13.92,13.92,0,0,0,26.12,0L144.4,176.4l52.49-19.34a13.92,13.92,0,0,0,0-26.12Zm-4.15,14.86-55.08,20.3a6,6,0,0,0-3.56,3.56l-20.3,55.08a1.92,1.92,0,0,1-3.6,0L89.9,169.66a6,6,0,0,0-3.56-3.56L31.26,145.8a1.92,1.92,0,0,1,0-3.6l55.08-20.3a6,6,0,0,0,3.56-3.56l20.3-55.08a1.92,1.92,0,0,1,3.6,0l20.3,55.08a6,6,0,0,0,3.56,3.56l55.08,20.3a1.92,1.92,0,0,1,0,3.6ZM146,40a6,6,0,0,1,6-6h18V16a6,6,0,0,1,12,0V34h18a6,6,0,0,1,0,12H182V64a6,6,0,0,1-12,0V46H152A6,6,0,0,1,146,40ZM246,88a6,6,0,0,1-6,6H230v10a6,6,0,0,1-12,0V94H208a6,6,0,0,1,0-12h10V72a6,6,0,0,1,12,0V82h10A6,6,0,0,1,246,88Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M197.58,129.06,146,110l-19-51.62a15.92,15.92,0,0,0-29.88,0L78,110l-51.62,19a15.92,15.92,0,0,0,0,29.88L78,178l19,51.62a15.92,15.92,0,0,0,29.88,0L146,178l51.62-19a15.92,15.92,0,0,0,0-29.88ZM137,164.22a8,8,0,0,0-4.74,4.74L112,223.85,91.78,169A8,8,0,0,0,87,164.22L32.15,144,87,123.78A8,8,0,0,0,91.78,119L112,64.15,132.22,119a8,8,0,0,0,4.74,4.74L191.85,144ZM144,40a8,8,0,0,1,8-8h16V16a8,8,0,0,1,16,0V32h16a8,8,0,0,1,0,16H184V64a8,8,0,0,1-16,0V48H152A8,8,0,0,1,144,40ZM248,88a8,8,0,0,1-8,8h-8v8a8,8,0,0,1-16,0V96h-8a8,8,0,0,1,0-16h8V72a8,8,0,0,1,16,0v8h8A8,8,0,0,1,248,88Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M196.2,132.81l-53.36-19.65L123.19,59.8a11.93,11.93,0,0,0-22.38,0L81.16,113.16,27.8,132.81a11.93,11.93,0,0,0,0,22.38l53.36,19.65,19.65,53.36a11.93,11.93,0,0,0,22.38,0l19.65-53.36,53.36-19.65a11.93,11.93,0,0,0,0-22.38Zm-2.77,14.87L138.35,168a4,4,0,0,0-2.37,2.37l-20.3,55.08a3.92,3.92,0,0,1-7.36,0L88,170.35A4,4,0,0,0,85.65,168l-55.08-20.3a3.92,3.92,0,0,1,0-7.36L85.65,120A4,4,0,0,0,88,117.65l20.3-55.08a3.92,3.92,0,0,1,7.36,0L136,117.65a4,4,0,0,0,2.37,2.37l55.08,20.3a3.92,3.92,0,0,1,0,7.36ZM148,40a4,4,0,0,1,4-4h20V16a4,4,0,0,1,8,0V36h20a4,4,0,0,1,0,8H180V64a4,4,0,0,1-8,0V44H152A4,4,0,0,1,148,40Zm96,48a4,4,0,0,1-4,4H228v12a4,4,0,0,1-8,0V92H208a4,4,0,0,1,0-8h12V72a4,4,0,0,1,8,0V84h12A4,4,0,0,1,244,88Z`}))]]),uM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M116,36V20a12,12,0,0,1,24,0V36a12,12,0,0,1-24,0Zm80,92a68,68,0,1,1-68-68A68.07,68.07,0,0,1,196,128Zm-24,0a44,44,0,1,0-44,44A44.05,44.05,0,0,0,172,128ZM51.51,68.49a12,12,0,1,0,17-17l-12-12a12,12,0,0,0-17,17Zm0,119-12,12a12,12,0,0,0,17,17l12-12a12,12,0,1,0-17-17ZM196,72a12,12,0,0,0,8.49-3.51l12-12a12,12,0,0,0-17-17l-12,12A12,12,0,0,0,196,72Zm8.49,115.51a12,12,0,0,0-17,17l12,12a12,12,0,0,0,17-17ZM48,128a12,12,0,0,0-12-12H20a12,12,0,0,0,0,24H36A12,12,0,0,0,48,128Zm80,80a12,12,0,0,0-12,12v16a12,12,0,0,0,24,0V220A12,12,0,0,0,128,208Zm108-92H220a12,12,0,0,0,0,24h16a12,12,0,0,0,0-24Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M184,128a56,56,0,1,1-56-56A56,56,0,0,1,184,128Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M120,40V16a8,8,0,0,1,16,0V40a8,8,0,0,1-16,0Zm72,88a64,64,0,1,1-64-64A64.07,64.07,0,0,1,192,128Zm-16,0a48,48,0,1,0-48,48A48.05,48.05,0,0,0,176,128ZM58.34,69.66A8,8,0,0,0,69.66,58.34l-16-16A8,8,0,0,0,42.34,53.66Zm0,116.68-16,16a8,8,0,0,0,11.32,11.32l16-16a8,8,0,0,0-11.32-11.32ZM192,72a8,8,0,0,0,5.66-2.34l16-16a8,8,0,0,0-11.32-11.32l-16,16A8,8,0,0,0,192,72Zm5.66,114.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32-11.32ZM48,128a8,8,0,0,0-8-8H16a8,8,0,0,0,0,16H40A8,8,0,0,0,48,128Zm80,80a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V216A8,8,0,0,0,128,208Zm112-88H216a8,8,0,0,0,0,16h24a8,8,0,0,0,0-16Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M120,40V16a8,8,0,0,1,16,0V40a8,8,0,0,1-16,0Zm8,24a64,64,0,1,0,64,64A64.07,64.07,0,0,0,128,64ZM58.34,69.66A8,8,0,0,0,69.66,58.34l-16-16A8,8,0,0,0,42.34,53.66Zm0,116.68-16,16a8,8,0,0,0,11.32,11.32l16-16a8,8,0,0,0-11.32-11.32ZM192,72a8,8,0,0,0,5.66-2.34l16-16a8,8,0,0,0-11.32-11.32l-16,16A8,8,0,0,0,192,72Zm5.66,114.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32-11.32ZM48,128a8,8,0,0,0-8-8H16a8,8,0,0,0,0,16H40A8,8,0,0,0,48,128Zm80,80a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V216A8,8,0,0,0,128,208Zm112-88H216a8,8,0,0,0,0,16h24a8,8,0,0,0,0-16Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M122,40V16a6,6,0,0,1,12,0V40a6,6,0,0,1-12,0Zm68,88a62,62,0,1,1-62-62A62.07,62.07,0,0,1,190,128Zm-12,0a50,50,0,1,0-50,50A50.06,50.06,0,0,0,178,128ZM59.76,68.24a6,6,0,1,0,8.48-8.48l-16-16a6,6,0,0,0-8.48,8.48Zm0,119.52-16,16a6,6,0,1,0,8.48,8.48l16-16a6,6,0,1,0-8.48-8.48ZM192,70a6,6,0,0,0,4.24-1.76l16-16a6,6,0,0,0-8.48-8.48l-16,16A6,6,0,0,0,192,70Zm4.24,117.76a6,6,0,0,0-8.48,8.48l16,16a6,6,0,0,0,8.48-8.48ZM46,128a6,6,0,0,0-6-6H16a6,6,0,0,0,0,12H40A6,6,0,0,0,46,128Zm82,82a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V216A6,6,0,0,0,128,210Zm112-88H216a6,6,0,0,0,0,12h24a6,6,0,0,0,0-12Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M120,40V16a8,8,0,0,1,16,0V40a8,8,0,0,1-16,0Zm72,88a64,64,0,1,1-64-64A64.07,64.07,0,0,1,192,128Zm-16,0a48,48,0,1,0-48,48A48.05,48.05,0,0,0,176,128ZM58.34,69.66A8,8,0,0,0,69.66,58.34l-16-16A8,8,0,0,0,42.34,53.66Zm0,116.68-16,16a8,8,0,0,0,11.32,11.32l16-16a8,8,0,0,0-11.32-11.32ZM192,72a8,8,0,0,0,5.66-2.34l16-16a8,8,0,0,0-11.32-11.32l-16,16A8,8,0,0,0,192,72Zm5.66,114.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32-11.32ZM48,128a8,8,0,0,0-8-8H16a8,8,0,0,0,0,16H40A8,8,0,0,0,48,128Zm80,80a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V216A8,8,0,0,0,128,208Zm112-88H216a8,8,0,0,0,0,16h24a8,8,0,0,0,0-16Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M124,40V16a4,4,0,0,1,8,0V40a4,4,0,0,1-8,0Zm64,88a60,60,0,1,1-60-60A60.07,60.07,0,0,1,188,128Zm-8,0a52,52,0,1,0-52,52A52.06,52.06,0,0,0,180,128ZM61.17,66.83a4,4,0,0,0,5.66-5.66l-16-16a4,4,0,0,0-5.66,5.66Zm0,122.34-16,16a4,4,0,0,0,5.66,5.66l16-16a4,4,0,0,0-5.66-5.66ZM192,68a4,4,0,0,0,2.83-1.17l16-16a4,4,0,1,0-5.66-5.66l-16,16A4,4,0,0,0,192,68Zm2.83,121.17a4,4,0,0,0-5.66,5.66l16,16a4,4,0,0,0,5.66-5.66ZM40,124H16a4,4,0,0,0,0,8H40a4,4,0,0,0,0-8Zm88,88a4,4,0,0,0-4,4v24a4,4,0,0,0,8,0V216A4,4,0,0,0,128,212Zm112-88H216a4,4,0,0,0,0,8h24a4,4,0,0,0,0-8Z`}))]]),dM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,48H180V36A28,28,0,0,0,152,8H104A28,28,0,0,0,76,36V48H40a12,12,0,0,0,0,24h4V208a20,20,0,0,0,20,20H192a20,20,0,0,0,20-20V72h4a12,12,0,0,0,0-24ZM100,36a4,4,0,0,1,4-4h48a4,4,0,0,1,4,4V48H100Zm88,168H68V72H188ZM116,104v64a12,12,0,0,1-24,0V104a12,12,0,0,1,24,0Zm48,0v64a12,12,0,0,1-24,0V104a12,12,0,0,1,24,0Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M200,56V208a8,8,0,0,1-8,8H64a8,8,0,0,1-8-8V56Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM96,40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8v8H96Zm96,168H64V64H192ZM112,104v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM112,168a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm0-120H96V40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,50H174V40a22,22,0,0,0-22-22H104A22,22,0,0,0,82,40V50H40a6,6,0,0,0,0,12H50V208a14,14,0,0,0,14,14H192a14,14,0,0,0,14-14V62h10a6,6,0,0,0,0-12ZM94,40a10,10,0,0,1,10-10h48a10,10,0,0,1,10,10V50H94ZM194,208a2,2,0,0,1-2,2H64a2,2,0,0,1-2-2V62H194ZM110,104v64a6,6,0,0,1-12,0V104a6,6,0,0,1,12,0Zm48,0v64a6,6,0,0,1-12,0V104a6,6,0,0,1,12,0Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM96,40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8v8H96Zm96,168H64V64H192ZM112,104v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,52H172V40a20,20,0,0,0-20-20H104A20,20,0,0,0,84,40V52H40a4,4,0,0,0,0,8H52V208a12,12,0,0,0,12,12H192a12,12,0,0,0,12-12V60h12a4,4,0,0,0,0-8ZM92,40a12,12,0,0,1,12-12h48a12,12,0,0,1,12,12V52H92ZM196,208a4,4,0,0,1-4,4H64a4,4,0,0,1-4-4V60H196ZM108,104v64a4,4,0,0,1-8,0V104a4,4,0,0,1,8,0Zm48,0v64a4,4,0,0,1-8,0V104a4,4,0,0,1,8,0Z`}))]]),fM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M256,136a12,12,0,0,1-12,12h-8v8a12,12,0,0,1-24,0v-8h-8a12,12,0,0,1,0-24h8v-8a12,12,0,0,1,24,0v8h8A12,12,0,0,1,256,136Zm-54.81,56.28a12,12,0,1,1-18.38,15.44C169.12,191.42,145,172,108,172c-28.89,0-55.46,12.68-74.81,35.72a12,12,0,0,1-18.38-15.44A124.08,124.08,0,0,1,63.5,156.53a72,72,0,1,1,89,0A124,124,0,0,1,201.19,192.28ZM108,148a48,48,0,1,0-48-48A48.05,48.05,0,0,0,108,148Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M168,100a60,60,0,1,1-60-60A60,60,0,0,1,168,100Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M256,136a8,8,0,0,1-8,8H232v16a8,8,0,0,1-16,0V144H200a8,8,0,0,1,0-16h16V112a8,8,0,0,1,16,0v16h16A8,8,0,0,1,256,136Zm-57.87,58.85a8,8,0,0,1-12.26,10.3C165.75,181.19,138.09,168,108,168s-57.75,13.19-77.87,37.15a8,8,0,0,1-12.25-10.3c14.94-17.78,33.52-30.41,54.17-37.17a68,68,0,1,1,71.9,0C164.6,164.44,183.18,177.07,198.13,194.85ZM108,152a52,52,0,1,0-52-52A52.06,52.06,0,0,0,108,152Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M256,136a8,8,0,0,1-8,8H232v16a8,8,0,0,1-16,0V144H200a8,8,0,0,1,0-16h16V112a8,8,0,0,1,16,0v16h16A8,8,0,0,1,256,136ZM144,157.68a68,68,0,1,0-71.9,0c-20.65,6.76-39.23,19.39-54.17,37.17A8,8,0,0,0,24,208H192a8,8,0,0,0,6.13-13.15C183.18,177.07,164.6,164.44,144,157.68Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M254,136a6,6,0,0,1-6,6H230v18a6,6,0,0,1-12,0V142H200a6,6,0,0,1,0-12h18V112a6,6,0,0,1,12,0v18h18A6,6,0,0,1,254,136Zm-57.41,60.14a6,6,0,1,1-9.18,7.72C166.9,179.45,138.69,166,108,166s-58.89,13.45-79.41,37.86a6,6,0,0,1-9.18-7.72C35.14,177.41,55,164.48,77,158.25a66,66,0,1,1,62,0C161,164.48,180.86,177.41,196.59,196.14ZM108,154a54,54,0,1,0-54-54A54.06,54.06,0,0,0,108,154Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M256,136a8,8,0,0,1-8,8H232v16a8,8,0,0,1-16,0V144H200a8,8,0,0,1,0-16h16V112a8,8,0,0,1,16,0v16h16A8,8,0,0,1,256,136Zm-57.87,58.85a8,8,0,0,1-12.26,10.3C165.75,181.19,138.09,168,108,168s-57.75,13.19-77.87,37.15a8,8,0,0,1-12.25-10.3c14.94-17.78,33.52-30.41,54.17-37.17a68,68,0,1,1,71.9,0C164.6,164.44,183.18,177.07,198.13,194.85ZM108,152a52,52,0,1,0-52-52A52.06,52.06,0,0,0,108,152Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M252,136a4,4,0,0,1-4,4H228v20a4,4,0,0,1-8,0V140H200a4,4,0,0,1,0-8h20V112a4,4,0,0,1,8,0v20h20A4,4,0,0,1,252,136Zm-56.94,61.43a4,4,0,0,1-6.12,5.14C168,177.7,139.3,164,108,164s-60,13.7-80.94,38.57a4,4,0,1,1-6.12-5.14c16.71-19.9,38.13-33.13,61.89-38.59a64,64,0,1,1,50.34,0C156.93,164.3,178.35,177.53,195.06,197.43ZM108,156a56,56,0,1,0-56-56A56.06,56.06,0,0,0,108,156Z`}))]]),pM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:$j}));pM.displayName=`ArrowLeftIcon`;var mM=pM,hM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:eM}));hM.displayName=`ArrowRightIcon`;var gM=hM,_M=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:tM}));_M.displayName=`BookOpenIcon`;var vM=_M,yM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:nM}));yM.displayName=`DotsThreeIcon`;var bM=yM,xM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:rM}));xM.displayName=`MagnifyingGlassIcon`;var SM=xM,CM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:iM}));CM.displayName=`MoonIcon`;var wM=CM,TM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:aM}));TM.displayName=`PencilSimpleIcon`;var EM=TM,DM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:oM}));DM.displayName=`PlugsConnectedIcon`;var OM=DM,kM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:sM}));kM.displayName=`PlusIcon`;var AM=kM,jM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:cM}));jM.displayName=`SignOutIcon`;var MM=jM,NM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:lM}));NM.displayName=`SparkleIcon`;var PM=NM,FM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:uM}));FM.displayName=`SunIcon`;var IM=FM,LM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:dM}));LM.displayName=`TrashIcon`;var RM=LM,zM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:fM}));zM.displayName=`UserPlusIcon`;var BM=zM,VM=class extends Error{status;problems;code;constructor(e,t,n=[],r=``){super(e),this.status=t,this.problems=n,this.code=r}},HM=`fanout:unauthorized`;function UM(){let e=new URLSearchParams(window.location.search).get(`return_to`);if(!e)return``;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin||t.pathname!==`/api/auth/oauth/authorize`?``:`${t.pathname}${t.search}`}function WM(e){return!e||typeof e!=`object`||!(`id`in e)||typeof e.id!=`string`||e.id===``?`none`:`user`}function GM(){window.dispatchEvent(new Event(HM))}async function KM(e,t={}){let n=new Headers(t.headers);n.set(`Fanout-Request`,`1`);let r=await fetch(e,{...t,headers:n,credentials:`same-origin`});if(r.status===401&&GM(),r.status===403){let e=await r.clone().json().catch(()=>({}));throw new VM(e.message??`You do not have permission to perform this action.`,r.status,[],e.code??``)}return r}async function qM(){let e=await KM(`/api/auth/logout`,{method:`POST`});if(!e.ok&&e.status!==401)throw Error(`Sign-out failed — your session is still active.`);e.status!==401&&GM(),window.location.assign(`/`)}var JM=(0,M.createContext)(null);function YM(){let e=(0,M.useContext)(JM);if(!e)throw Error(`Fanout runtime status is unavailable`);return e}var XM=(0,M.createContext)(null);function ZM(){let e=(0,M.useContext)(XM);if(!e)throw Error(`Fanout viewer is unavailable`);return e}function QM(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.id!=`string`||t.id===``||t.status!==`active`&&t.status!==`suspended`?null:{id:t.id,email:typeof t.email==`string`?t.email:``,display_name:typeof t.display_name==`string`?t.display_name:``,status:t.status,role:typeof t.role==`string`?t.role:``}}async function $M(e,t){let n=await fetch(e,{method:t===void 0?`GET`:`POST`,headers:t===void 0?void 0:{"Content-Type":`application/json`},body:t===void 0?void 0:JSON.stringify(t),credentials:`same-origin`}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.message??`Request failed (${n.status})`);return r}function eN({children:e,wide:t=!1}){return(0,N.jsx)(u,{mih:`100dvh`,style:{background:`radial-gradient(circle at 50% -12%, var(--mantine-color-brand-light), transparent 38%), linear-gradient(180deg, var(--mantine-color-default-hover), var(--mantine-color-body) 62%)`},children:(0,N.jsx)(je,{mih:`100dvh`,px:`md`,py:48,children:(0,N.jsx)(ve,{size:t?680:480,w:`100%`,children:(0,N.jsx)(Fe,{radius:28,p:{base:24,sm:40},style:{background:`var(--mantine-color-body)`,border:`1px solid var(--mantine-color-default-border)`,boxShadow:`var(--mantine-shadow-xl)`},children:e})})})})}function tN(){return typeof window>`u`?``:new URLSearchParams(window.location.search).get(`setup_token`)??``}function nN(){return typeof window>`u`?``:new URLSearchParams(window.location.search).get(`login_token`)??``}function rN({children:e}){let t=ze(),[n,r]=(0,M.useState)(null),[i,a]=(0,M.useState)(!1),[o,s]=(0,M.useState)(`none`),[c,l]=(0,M.useState)(null),[d,f]=(0,M.useState)(!1),[p,m]=(0,M.useState)(``),[h,g]=(0,M.useState)(``),[_,v]=(0,M.useState)(tN),[y,b]=(0,M.useState)(nN),[x,S]=(0,M.useState)(``),[C,w]=(0,M.useState)(!1),[T,ee]=(0,M.useState)(0),[E,D]=(0,M.useState)(()=>Date.now()),[O,te]=(0,M.useState)(!1),[re,k]=(0,M.useState)(``),[ie,ae]=(0,M.useState)(null),[se,le]=(0,M.useState)(!1),de=(0,M.useRef)(null),fe=UM(),pe=o===`user`;async function he(){let e=await fetch(`/api/auth/me`,{credentials:`same-origin`});if(!e.ok){s(`none`),l(null);return}let t=await e.json().catch(()=>null);s(WM(t)),l(QM(t))}async function ge(){try{let e=await fetch(`/api/auth/me`,{credentials:`same-origin`});if(!e.ok)return;l(QM(await e.json().catch(()=>null)))}catch{}}(0,M.useEffect)(()=>{let e=new URL(window.location.href);(e.searchParams.has(`setup_token`)||e.searchParams.has(`login_token`))&&(e.searchParams.delete(`setup_token`),e.searchParams.delete(`login_token`),t({href:e.pathname+e.search+e.hash,replace:!0}))},[t]),(0,M.useEffect)(()=>{$M(`/api/auth/status`).then(r).catch(e=>k(String(e))).finally(()=>a(!0)),he().catch(()=>s(`none`)).finally(()=>f(!0));let e=()=>{s(`none`),l(null)};return window.addEventListener(HM,e),()=>window.removeEventListener(HM,e)},[]),(0,M.useEffect)(()=>{d&&o===`none`&&y&&(te(!0),k(``),$M(`/api/auth/link/verify`,{token:y}).then(()=>{s(`user`),ge()}).catch(e=>k(e instanceof Error?e.message:String(e))).finally(()=>{b(``),te(!1)}))},[y,d,o]),(0,M.useEffect)(()=>{pe&&d&&fe&&window.location.replace(fe)},[pe,fe,d]),(0,M.useEffect)(()=>{if(T<=Date.now())return;let e=setInterval(()=>{D(Date.now()),Date.now()>=T&&clearInterval(e)},1e3);return()=>clearInterval(e)},[T]);let _e=Math.max(0,Math.ceil((T-E)/1e3));(0,M.useEffect)(()=>{C&&!O&&re&&de.current?.querySelector(`input`)?.focus()},[O,C,re]);async function ve(e){try{await navigator.clipboard.writeText(e),le(!0)}catch{k(`Clipboard access failed. Select and copy the token manually.`)}}if(ie?.ingest_token)return(0,N.jsx)(eN,{wide:!0,children:(0,N.jsxs)(oe,{gap:`lg`,children:[(0,N.jsx)(ke,{}),(0,N.jsxs)(`div`,{children:[(0,N.jsx)(ue,{c:`brand`,fw:700,size:`xs`,tt:`uppercase`,lts:`0.12em`,children:`Setup complete`}),(0,N.jsx)(xe,{order:1,mt:`xs`,fz:{base:28,sm:32},lh:1.08,children:`Save your ingest token`})]}),(0,N.jsx)(ue,{c:`dimmed`,children:`Fanout shows this token once. Store it with your collector secrets before continuing.`}),(0,N.jsxs)(oe,{gap:`xs`,children:[(0,N.jsx)(ue,{size:`sm`,fw:600,children:`OTLP endpoint`}),(0,N.jsx)(ms,{block:!0,children:ie.suggested_endpoint??window.location.origin})]}),(0,N.jsxs)(oe,{gap:`xs`,children:[(0,N.jsx)(ue,{size:`sm`,fw:600,children:`Header`}),(0,N.jsxs)(ms,{block:!0,children:[ie.ingest_header_name??`Authorization`,`: Bearer `,ie.ingest_token]})]}),re&&(0,N.jsx)(Ce,{color:`bad`,radius:`md`,children:re}),(0,N.jsxs)(ne,{grow:!0,align:`stretch`,children:[(0,N.jsx)(ce,{variant:`light`,radius:`md`,leftSection:se?(0,N.jsx)(me,{size:16,weight:`bold`}):(0,N.jsx)(Ee,{size:16}),onClick:()=>void ve(`${ie.ingest_header_name??`Authorization`}: Bearer ${ie.ingest_token}`),children:se?`Copied`:`Copy header`}),(0,N.jsx)(ce,{radius:`md`,rightSection:(0,N.jsx)(gM,{size:16,weight:`bold`}),onClick:()=>{s(`user`),ae(null),ge()},children:`Continue to Fanout`})]}),(0,N.jsx)(ce,{variant:`subtle`,size:`compact-xs`,onClick:()=>void ve(ie.ingest_token??``),children:`Copy token only`})]})});if(!d||!i||y)return(0,N.jsx)(je,{mih:`100dvh`,children:(0,N.jsx)(Ie,{size:`sm`})});if(!n)return(0,N.jsx)(eN,{children:(0,N.jsxs)(oe,{gap:`lg`,children:[(0,N.jsx)(ke,{}),(0,N.jsx)(xe,{order:1,children:`Fanout is unavailable`}),(0,N.jsx)(Ce,{color:`bad`,radius:`md`,children:re||`Authentication status could not be loaded.`})]})});if(pe&&fe)return null;if(pe)return(0,N.jsx)(JM.Provider,{value:n,children:(0,N.jsx)(XM.Provider,{value:c??{id:``,email:p,display_name:h,status:`active`,role:``},children:e})});if(n&&!n.setup_required&&n.auth_mode===`oidc`){let e=fe?`/api/auth/oidc/start?return_to=${encodeURIComponent(fe)}`:`/api/auth/oidc/start`;return(0,N.jsx)(eN,{children:(0,N.jsxs)(oe,{gap:28,children:[(0,N.jsx)(ke,{}),(0,N.jsxs)(oe,{gap:10,children:[(0,N.jsx)(ue,{c:`brand`,fw:700,size:`xs`,tt:`uppercase`,lts:`0.12em`,children:`Secure workspace`}),(0,N.jsx)(xe,{order:1,fz:{base:28,sm:32},lh:1.08,children:`Sign in`}),(0,N.jsx)(ue,{c:`dimmed`,size:`md`,lh:1.6,children:`Use your organization's identity provider to continue.`})]}),re&&(0,N.jsx)(Ce,{color:`bad`,radius:`md`,children:re}),(0,N.jsx)(ce,{component:`a`,href:e,size:`md`,radius:`md`,rightSection:(0,N.jsx)(gM,{size:17,weight:`bold`}),children:`Continue with SSO`})]})})}async function ye(){te(!0),k(``);try{await $M(`/api/auth/code/send`,{email:p}),w(!0),S(``),ee(Date.now()+3e4),D(Date.now())}catch(e){k(e instanceof Error?e.message:String(e))}finally{te(!1)}}async function A(e){te(!0),k(``);try{await $M(`/api/auth/code/verify`,{email:p,code:e}),s(`user`),w(!1),S(``),ee(0),ge()}catch(e){S(``),k(e instanceof Error?e.message:String(e))}finally{te(!1)}}function j(){w(!1),S(``),k(``)}async function be(e){e.preventDefault(),te(!0),k(``);try{if(n?.setup_required){let e=await $M(`/api/auth/setup`,{email:p,display_name:h,setup_token:_});e.ingest_token?ae(e):(s(`user`),ge())}else if(C){await A(x);return}else{await ye();return}}catch(e){k(e instanceof Error?e.message:String(e))}finally{te(!1)}}let Se=C&&!n?.setup_required,we=n?.setup_required?`Create the first admin`:Se?`Check your email`:n?.self_signup?`Sign in or create an account`:`Sign in`,Te=n?.setup_required?`Use the one-time token printed by the Fanout process.`:n?.smtp_configured?Se?`We sent a code to ${p}.`:n?.self_signup?`Enter your email to sign in or create a viewer account. No password needed.`:`Enter your email and we’ll send a short verification code. No password needed.`:`Email delivery is not configured. Ask the operator to run fanout login-link with your email address.`;return(0,N.jsx)(eN,{children:(0,N.jsxs)(oe,{gap:28,children:[(0,N.jsx)(ke,{}),(0,N.jsxs)(oe,{gap:10,children:[(0,N.jsx)(ue,{c:`brand`,fw:700,size:`xs`,tt:`uppercase`,lts:`0.12em`,children:n?.setup_required?`One-time setup`:`Secure workspace`}),(0,N.jsx)(xe,{order:1,fz:{base:28,sm:32},lh:1.08,children:we}),Te&&(0,N.jsx)(ue,{c:`dimmed`,size:`md`,lh:1.6,maw:390,children:Te})]}),(0,N.jsx)(`form`,{onSubmit:be,children:(0,N.jsxs)(oe,{gap:`md`,children:[(0,N.jsx)(Gc,{label:`Email`,placeholder:`you@company.com`,type:`email`,required:!0,value:p,onChange:e=>m(e.currentTarget.value),disabled:C,variant:`filled`,radius:`md`,size:`md`,autoFocus:!C}),n?.setup_required&&(0,N.jsx)(Gc,{label:`Display name`,placeholder:`Your display name`,value:h,onChange:e=>g(e.currentTarget.value),variant:`filled`,radius:`md`,size:`md`}),n?.setup_required&&(0,N.jsx)(Gc,{label:`Setup token`,placeholder:`from the setup URL printed at startup`,required:!0,value:_,onChange:e=>v(e.currentTarget.value),autoComplete:`one-time-code`,variant:`filled`,radius:`md`,size:`md`}),Se&&(0,N.jsxs)(oe,{gap:`xs`,children:[(0,N.jsx)(ue,{size:`sm`,fw:600,children:`Verification code`}),(0,N.jsx)(u,{ref:de,children:(0,N.jsx)(Wc,{length:6,type:`number`,oneTimeCode:!0,autoFocus:!0,value:x,onChange:S,onComplete:e=>void A(e),disabled:O,error:!!re,size:`md`,radius:`md`,"aria-label":`Verification code`,getInputProps:e=>({"aria-label":`Digit ${e+1}`})})}),(0,N.jsxs)(ne,{justify:`space-between`,gap:`xs`,children:[(0,N.jsxs)(ue,{c:`dimmed`,size:`xs`,children:[`Sent to `,p]}),(0,N.jsx)(ce,{variant:`subtle`,size:`compact-xs`,leftSection:(0,N.jsx)(mM,{size:12,weight:`bold`}),onClick:j,disabled:O,children:`Change email`})]}),(0,N.jsxs)(ne,{justify:`space-between`,gap:`xs`,children:[(0,N.jsx)(ue,{c:`dimmed`,size:`xs`,children:`Codes expire in 5 minutes`}),(0,N.jsx)(ce,{variant:`subtle`,size:`compact-xs`,onClick:()=>void ye(),disabled:O||_e>0,children:_e>0?`Resend in ${_e}s`:`Resend code`})]})]}),re&&(0,N.jsx)(Ce,{color:`bad`,radius:`md`,children:re}),Se?(0,N.jsx)(ce,{type:`submit`,size:`md`,radius:`md`,mt:4,loading:O,disabled:O||x.length<6,rightSection:(0,N.jsx)(gM,{size:17,weight:`bold`}),children:`Verify code`}):(0,N.jsx)(ce,{type:`submit`,size:`md`,radius:`md`,mt:4,loading:O,disabled:!n||!n.setup_required&&!n.smtp_configured,leftSection:n?.setup_required?(0,N.jsx)(BM,{size:17,weight:`bold`}):void 0,rightSection:n?.setup_required?void 0:(0,N.jsx)(gM,{size:17,weight:`bold`}),children:n?.setup_required?`Create admin`:`Send code`})]})})]})})}var iN=[`agent-threads`];async function aN(e){let t=await KM(e);if(!t.ok)throw Error(`Request failed (${t.status})`);return t.json()}var oN=[];for(let e=0;e<256;++e)oN.push((e+256).toString(16).slice(1));function sN(e,t=0){return(oN[e[t+0]]+oN[e[t+1]]+oN[e[t+2]]+oN[e[t+3]]+`-`+oN[e[t+4]]+oN[e[t+5]]+`-`+oN[e[t+6]]+oN[e[t+7]]+`-`+oN[e[t+8]]+oN[e[t+9]]+`-`+oN[e[t+10]]+oN[e[t+11]]+oN[e[t+12]]+oN[e[t+13]]+oN[e[t+14]]+oN[e[t+15]]).toLowerCase()}var cN=new Uint8Array(16);function lN(){return crypto.getRandomValues(cN)}var uN={};function dN(e,t,n){let r;if(e)r=pN(e.random??e.rng?.()??lN(),e.msecs,e.seq,t,n);else{let e=Date.now(),i=lN();fN(uN,e,i),r=pN(i,uN.msecs,uN.seq,t,n)}return t??sN(r)}function fN(e,t,n){return e.msecs??=-1/0,e.seq??=0,t>e.msecs?(e.seq=mN(n),e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function pN(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=mN(e),r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}function mN(e){return(e[6]&127)<<24|e[7]<<16|e[8]<<8|e[9]}function hN(){return dN()}var gN=[`dashboards`],_N=3e4;async function vN(e,t){let{json:n,...r}=t??{},i=new Headers(r.headers),a=r.body;n!==void 0&&(i.set(`content-type`,`application/json`),a=JSON.stringify(n));let o=await KM(e,{...r,headers:i,body:a}),s=await o.json().catch(()=>({}));if(!o.ok)throw new VM(s.message??`Request failed (${o.status})`,o.status,s.problems??[],s.code??``);return s}var yN=e=>`/api/dashboards/${encodeURIComponent(e)}`,bN=()=>vN(`/api/dashboards`).then(e=>e.dashboards),xN=(e,t)=>vN(yN(e),{signal:t}),SN=(e,t)=>vN(`${yN(e)}/versions`,{signal:t}).then(e=>e.versions),CN=(e,t,n)=>vN(`${yN(e)}/versions/${t}`,{signal:n}),wN=(e,t)=>vN(`${yN(e)}/versions/${t}/restore`,{method:`POST`}),TN=(e,t,n,r)=>vN(yN(e),{method:`PUT`,json:{spec:t,base_version:n,message:r}}),EN=(e,t,n,r)=>vN(yN(e),{method:`PATCH`,json:{operations:t,base_version:n,message:r}}),DN=(e,t)=>vN(`/api/panels/query`,{method:`POST`,json:e,signal:t}).then(e=>e.results),ON=e=>vN(`/api/telemetry/schema`,{signal:e}),kN=(e,t)=>vN(`/api/annotations`,{method:`POST`,json:e,signal:t}),AN=(e,t)=>vN(`/api/panels/variables/resolve`,{method:`POST`,json:e,signal:t}).then(e=>e.options),jN=(e,t)=>vN(`/api/panels/exemplars`,{method:`POST`,json:e,signal:t});function MN(e,t){let n=new URLSearchParams({namespace:e.namespace??``,from:e.window_from,to:e.window_to,limit:`200`});return vN(`/api/traces/${encodeURIComponent(e.trace_id??``)}?${n}`,{signal:t})}function NN(){let{setColorScheme:e}=Br(),t=Ur(`light`,{getInitialValueInEffect:!0}),n=t===`dark`?`light`:`dark`,[r,i]=(0,M.useState)(!1);return(0,N.jsx)(Ot,{label:`Switch to ${n} theme`,opened:r,children:(0,N.jsx)(Pi,{variant:`subtle`,color:`gray`,"aria-label":`Switch to ${n} theme`,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),onClick:()=>{i(!1),e(n)},children:t===`dark`?(0,N.jsx)(IM,{size:17,weight:`bold`}):(0,N.jsx)(wM,{size:17,weight:`bold`})})})}var PN={home:`https://fanout.run/start/what-fanout-is`,ingest:`https://fanout.run/start/send-telemetry`,connect:`https://fanout.run/guides/connect-over-mcp`};async function FN(e,t){let n=new URLSearchParams({page_size:`30`});e&&n.set(`q`,e),t&&n.set(`cursor`,t);let r=await KM(`/api/agent/threads?${n}`);if(!r.ok)throw Error(`Unable to load chats (${r.status})`);return r.json()}function IN({agentAvailable:e,activeThreadID:t,activeDashboardID:n,autoFocusSearch:r=!1,onNewChat:i,onSelectThread:a,onDeletedThread:o,onSelectDashboard:s,onCreateDashboard:c,onInvestigateService:l,ref:u}){let d=OA(),[f,p]=(0,M.useState)(``),[m]=pr(f.trim(),250),[h,g]=(0,M.useState)(null),[_,v]=(0,M.useState)(null),[y,b]=(0,M.useState)(``),[x,S]=(0,M.useState)(``),[w,T]=(0,M.useState)(!1),ee=(0,M.useRef)(null);(0,M.useImperativeHandle)(u,()=>({focusSearch:()=>ee.current?.focus()}),[]),(0,M.useEffect)(()=>{r&&requestAnimationFrame(()=>ee.current?.focus())},[r]);let E=Qj({queryKey:[...iN,m],queryFn:({pageParam:e})=>FN(m,e),initialPageParam:``,getNextPageParam:e=>e.next_cursor??void 0,enabled:e}),D=Zj({queryKey:gN,queryFn:bN,refetchInterval:3e4,staleTime:_N}),O=(0,M.useMemo)(()=>E.data?.pages.flatMap(e=>e.items)??[],[E.data]),te=(0,M.useMemo)(()=>HN(O),[O]),re=Zj({queryKey:[`telemetry-schema`,`1h`],queryFn:()=>aN(`/api/telemetry/schema?window=1h`),enabled:!!m&&!!l,staleTime:6e4}),k=(0,M.useMemo)(()=>{if(!m)return[];let e=m.toLowerCase();return(re.data?.services??[]).map(e=>e.value).filter(t=>t.toLowerCase().includes(e)).slice(0,6)},[re.data,m]),ie=(0,M.useMemo)(()=>{let e=D.data??[],t=m.toLowerCase();return t?e.filter(e=>e.name.toLowerCase().includes(t)):e},[D.data,m]);function ae(e){S(``),b(e.title),g(e)}async function se(){if(h&&y.trim()){T(!0),S(``);try{let e=await KM(`/api/agent/threads/${encodeURIComponent(h.id)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({title:y.trim()})});if(!e.ok)throw Error(`Unable to rename chat (${e.status})`);await d.invalidateQueries({queryKey:iN}),g(null)}catch(e){S(e instanceof Error?e.message:`Unable to rename this chat.`)}finally{T(!1)}}}async function le(){if(_){T(!0),S(``);try{let e=await KM(`/api/agent/threads/${encodeURIComponent(_.id)}`,{method:`DELETE`});if(!e.ok)throw Error(`Unable to delete chat (${e.status})`);let t=_.id;v(null),await d.invalidateQueries({queryKey:iN}),await d.invalidateQueries({queryKey:gN}),o(t)}catch(e){S(e instanceof Error?e.message:`Unable to delete this chat.`)}finally{T(!1)}}}return(0,N.jsxs)(oe,{gap:`sm`,h:`100%`,component:`nav`,"aria-label":`Navigation`,children:[e&&(0,N.jsx)(ce,{leftSection:(0,N.jsx)(AM,{size:16,weight:`bold`}),onClick:i,children:`New chat`}),(0,N.jsx)(wt,{type:`auto`,offsetScrollbars:!0,flex:1,mx:-4,px:4,children:(0,N.jsxs)(oe,{gap:`lg`,pb:`sm`,children:[e&&(0,N.jsxs)(oe,{gap:4,children:[(0,N.jsx)(LN,{children:`Chats`}),E.isLoading&&(0,N.jsx)(je,{py:`md`,children:(0,N.jsx)(Ie,{size:`xs`})}),E.isError&&(0,N.jsx)(Ce,{color:`bad`,radius:`md`,p:`xs`,children:`Chats could not be loaded.`}),!E.isLoading&&!E.isError&&O.length===0&&(0,N.jsx)(ue,{c:`dimmed`,size:`sm`,px:`sm`,py:`xs`,children:m?`No matching chats`:`No chats yet`}),te.map(e=>(0,N.jsxs)(oe,{gap:2,children:[te.length>1&&(0,N.jsx)(ue,{c:`dimmed`,size:`xs`,px:`sm`,pt:4,children:e.label}),e.threads.map(e=>(0,N.jsx)(RN,{thread:e,active:e.id===t,onSelect:()=>a(e.id),onRename:()=>ae(e),onDelete:()=>{S(``),v(e)}},e.id))]},e.label)),E.hasNextPage&&(0,N.jsx)(ce,{variant:`subtle`,color:`gray`,size:`compact-sm`,loading:E.isFetchingNextPage,onClick:()=>void E.fetchNextPage(),children:`See all`})]}),m&&l&&re.isLoading&&(0,N.jsx)(je,{py:`md`,children:(0,N.jsx)(Ie,{size:`xs`})}),m&&l&&(re.isSuccess||re.isError)&&(0,N.jsxs)(oe,{gap:4,children:[(0,N.jsx)(LN,{children:`Services`}),re.isError&&(0,N.jsx)(ue,{c:`dimmed`,size:`sm`,px:`sm`,children:`Services could not be searched`}),re.isSuccess&&k.length===0&&(0,N.jsx)(ue,{c:`dimmed`,size:`sm`,px:`sm`,children:`No matching services`}),k.map(e=>(0,N.jsx)(C,{className:`rail-row`,p:`sm`,onClick:()=>l(e),children:(0,N.jsx)(ue,{size:`sm`,fw:500,truncate:!0,children:e})},e))]}),(0,N.jsxs)(oe,{gap:4,children:[(0,N.jsx)(LN,{children:`Dashboards`}),D.isLoading&&(0,N.jsx)(je,{py:`md`,children:(0,N.jsx)(Ie,{size:`xs`})}),D.isError&&(0,N.jsx)(Ce,{color:`bad`,radius:`md`,p:`xs`,children:`Dashboards could not be loaded.`}),!D.isLoading&&!D.isError&&m&&ie.length===0&&(0,N.jsx)(ue,{c:`dimmed`,size:`sm`,px:`sm`,py:`xs`,children:`No matching dashboards`}),ie.map(e=>{let t=e.id===n;return(0,N.jsxs)(oe,{gap:0,children:[(0,N.jsx)(C,{component:`a`,href:`/dashboards/${encodeURIComponent(e.id)}`,className:`rail-row`,"data-active":t||void 0,"aria-current":t?`page`:void 0,p:`sm`,onClick:t=>{t.button!==0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),s(e.id))},children:(0,N.jsxs)(ne,{justify:`space-between`,gap:`sm`,wrap:`nowrap`,children:[(0,N.jsx)(ue,{size:`sm`,fw:t?600:500,truncate:!0,children:e.name}),e.is_default&&(0,N.jsx)(cs,{size:`xs`,variant:`light`,color:`gray`,children:`Default`})]})}),e.origin&&(0,N.jsx)(C,{component:`a`,href:`/chat/${encodeURIComponent(e.origin.thread_id)}`,"data-request-provenance":!0,px:`sm`,pb:`xs`,onClick:t=>{t.button!==0||t.metaKey||t.ctrlKey||t.shiftKey||t.altKey||(t.preventDefault(),a(e.origin.thread_id))},children:(0,N.jsxs)(ue,{size:`xs`,c:`dimmed`,lineClamp:2,children:[`Built from: `,e.origin.request_excerpt]})})]},e.id)}),e&&(0,N.jsx)(ce,{variant:`subtle`,color:`gray`,size:`compact-sm`,justify:`flex-start`,leftSection:(0,N.jsx)(PM,{size:14,weight:`fill`}),onClick:c,children:D.data?.length===0?`New dashboard`:`Create with AI`})]})]})}),(0,N.jsx)(Gc,{ref:ee,value:f,onChange:e=>p(e.currentTarget.value),leftSection:(0,N.jsx)(SM,{size:15}),rightSection:(0,N.jsx)(Ls,{size:`xs`,children:`⌘K`}),rightSectionWidth:44,placeholder:`Search`,"aria-label":`Search chats, dashboards and services`,size:`sm`}),(0,N.jsx)(Rc,{opened:h!==null,onClose:()=>!w&&g(null),title:`Rename chat`,centered:!0,children:(0,N.jsx)(`form`,{onSubmit:e=>{e.preventDefault(),se()},children:(0,N.jsxs)(oe,{children:[(0,N.jsx)(Gc,{label:`Name`,value:y,onChange:e=>b(e.currentTarget.value),maxLength:120,autoFocus:!0}),x&&(0,N.jsx)(Ce,{color:`bad`,children:x}),(0,N.jsxs)(ne,{justify:`flex-end`,children:[(0,N.jsx)(ce,{variant:`default`,onClick:()=>g(null),disabled:w,children:`Cancel`}),(0,N.jsx)(ce,{type:`submit`,loading:w,disabled:!y.trim(),children:`Save`})]})]})})}),(0,N.jsx)(Rc,{opened:_!==null,onClose:()=>!w&&v(null),title:`Delete chat?`,centered:!0,children:(0,N.jsxs)(oe,{children:[(0,N.jsxs)(ue,{size:`sm`,children:[`This permanently removes `,(0,N.jsx)(ue,{span:!0,fw:650,children:_?.title}),` and its saved messages.`]}),x&&(0,N.jsx)(Ce,{color:`bad`,children:x}),(0,N.jsxs)(ne,{justify:`flex-end`,children:[(0,N.jsx)(ce,{variant:`default`,onClick:()=>v(null),disabled:w,children:`Cancel`}),(0,N.jsx)(ce,{color:`bad`,loading:w,onClick:()=>void le(),children:`Delete`})]})]})})]})}function LN({children:e}){return(0,N.jsx)(ue,{c:`dimmed`,size:`xs`,fw:700,tt:`uppercase`,lts:`0.08em`,px:`sm`,children:e})}function RN({thread:e,active:t,onSelect:n,onRename:r,onDelete:i}){return(0,N.jsx)(u,{"data-active":t||void 0,className:`rail-row`,children:(0,N.jsxs)(ne,{gap:2,wrap:`nowrap`,children:[(0,N.jsx)(C,{onClick:n,"aria-current":t?`page`:void 0,p:`sm`,flex:1,style:{minWidth:0},children:(0,N.jsxs)(oe,{gap:0,children:[(0,N.jsx)(ue,{size:`sm`,fw:t?600:500,truncate:!0,children:e.title}),(0,N.jsx)(ue,{c:`dimmed`,size:`xs`,children:UN(e.updated_at)})]})}),(0,N.jsxs)(Sc,{position:`bottom-end`,withinPortal:!0,children:[(0,N.jsx)(Sc.Target,{children:(0,N.jsx)(Pi,{className:`rail-row-actions`,variant:`subtle`,color:`gray`,size:`sm`,mr:4,"aria-label":`Actions for ${e.title}`,children:(0,N.jsx)(bM,{size:18,weight:`bold`})})}),(0,N.jsxs)(Sc.Dropdown,{children:[(0,N.jsx)(Sc.Item,{leftSection:(0,N.jsx)(EM,{size:15}),onClick:r,children:`Rename`}),(0,N.jsx)(Sc.Item,{color:`bad`,leftSection:(0,N.jsx)(RM,{size:15}),onClick:i,children:`Delete`})]})]})]})})}function zN(e){return e.includes(`T`)?new Date(e):new Date(`${e.replace(` `,`T`)}Z`)}function BN(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}var VN=[`Today`,`Yesterday`,`Previous 7 days`,`Older`];function HN(e){let t=BN(new Date),n=new Map;for(let r of e){let e=Math.floor((t-BN(zN(r.updated_at)))/864e5),i=e<=0?`Today`:e===1?`Yesterday`:e<=7?`Previous 7 days`:`Older`,a=n.get(i)??[];a.push(r),n.set(i,a)}return VN.filter(e=>n.has(e)).map(e=>({label:e,threads:n.get(e)}))}function UN(e){let t=zN(e),n=BN(new Date);return Math.floor((n-BN(t))/864e5)<=1?new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}).format(t):new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`}).format(t)}function WN({children:e}){let{agentAvailable:t,threadID:n,threadMissing:r,newThread:i,selectThread:a,openChat:o}=Qe(),s=ze(),c=Xn({select:e=>e.location.pathname}),{dashboardId:l}=Sn({strict:!1}),u=c===`/chat`||c.startsWith(`/chat/`),[d,f]=Dr(!1),[p,m]=(0,M.useState)(!1),[h,g]=(0,M.useState)(``),_=(0,M.useRef)(null),v=ie(`(max-width: 62em)`),y=(0,M.useRef)(v);y.current=v,(0,M.useEffect)(()=>{f.close()},[c]),(0,M.useEffect)(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`&&(e.preventDefault(),y.current?(m(!0),f.open()):_.current?.focusSearch())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let b={agentAvailable:t,activeThreadID:u&&!r&&c!==`/chat`?n:void 0,activeDashboardID:l,onNewChat:i,onSelectThread:a,onDeletedThread:e=>{e===n&&i()},onSelectDashboard:e=>void s({to:`/dashboards/$dashboardId`,params:{dashboardId:e},search:{}}),onCreateDashboard:()=>o(tt),onInvestigateService:e=>o(`Investigate the ${e} service. Explain its errors and latency.`)};return(0,N.jsxs)(Jo,{header:{height:52},navbar:{width:256,breakpoint:`md`,collapsed:{mobile:!0}},padding:0,children:[(0,N.jsx)(Jo.Header,{children:(0,N.jsxs)(ne,{h:`100%`,px:{base:`sm`,sm:`md`},justify:`space-between`,wrap:`nowrap`,children:[(0,N.jsxs)(ne,{gap:`sm`,wrap:`nowrap`,children:[(0,N.jsx)(ds,{hiddenFrom:`md`,opened:d,onClick:()=>{m(!1),f.toggle()},size:`sm`,"aria-label":d?`Close navigation`:`Open navigation`}),(0,N.jsx)(ke,{size:`small`})]}),(0,N.jsxs)(ne,{gap:`xs`,wrap:`nowrap`,children:[(0,N.jsx)(Ot,{label:`Documentation`,children:(0,N.jsx)(Pi,{component:`a`,href:PN.home,target:`_blank`,rel:`noopener noreferrer`,variant:`subtle`,color:`gray`,"aria-label":`Documentation`,children:(0,N.jsx)(vM,{size:17,weight:`bold`})})}),(0,N.jsx)(NN,{}),(0,N.jsx)(GN,{onError:g})]})]})}),(0,N.jsx)(Jo.Navbar,{p:`sm`,children:(0,N.jsx)(IN,{ref:_,...b})}),(0,N.jsx)(Ps,{opened:d,onClose:f.close,hiddenFrom:`md`,size:288,padding:`sm`,title:(0,N.jsx)(ke,{size:`small`}),overlayProps:{backgroundOpacity:.24,blur:1},children:(0,N.jsx)(IN,{...b,autoFocusSearch:d&&p})}),(0,N.jsxs)(Jo.Main,{children:[h&&(0,N.jsx)(Ce,{color:`bad`,m:`md`,withCloseButton:!0,onClose:()=>g(``),children:h}),e]})]})}function GN({onError:e}){let t=ze(),n=ZM(),r=(n.display_name.trim()||n.email.trim()||`?`).charAt(0).toUpperCase();return(0,N.jsxs)(Sc,{position:`bottom-end`,withinPortal:!0,shadow:`md`,children:[(0,N.jsx)(Sc.Target,{children:(0,N.jsx)(Pi,{variant:`subtle`,color:`gray`,size:`lg`,radius:`xl`,"aria-label":`${r} account menu`,children:(0,N.jsx)(as,{size:26,radius:`xl`,color:`brand`,children:r})})}),(0,N.jsxs)(Sc.Dropdown,{children:[(0,N.jsx)(Sc.Label,{children:n.email||`Signed in`}),(0,N.jsx)(Sc.Item,{leftSection:(0,N.jsx)(OM,{size:15}),onClick:()=>void t({to:`/settings`}),children:`Connect telemetry`}),(0,N.jsx)(Sc.Divider,{}),(0,N.jsx)(Sc.Item,{leftSection:(0,N.jsx)(MM,{size:15}),onClick:()=>void qM().catch(t=>e(t instanceof Error?t.message:`Sign-out failed — your session is still active.`)),children:`Sign out`})]})]})}function KN(){let{agent_available:e}=YM(),t=ze(),n=OA(),{threadId:r}=Sn({strict:!1}),[i,a]=(0,M.useState)(hN),o=(0,M.useRef)(new Set),s=r??i,[c,l]=(0,M.useState)([]),[u,d]=(0,M.useState)({}),[f,p]=(0,M.useState)(``),[m,h]=(0,M.useState)(!1),[g,_]=(0,M.useState)(!1),[v,y]=(0,M.useState)(``),[b,x]=(0,M.useState)(!1),S=(0,M.useRef)(!1),[C,w]=(0,M.useState)(``),[T,ee]=(0,M.useState)(``),[E,D]=(0,M.useState)(0),O=(0,M.useRef)(null),te=(0,M.useRef)({}),ne=(0,M.useRef)(null),re=(0,M.useRef)(new Map),k=(0,M.useMemo)(()=>new EA({url:`/api/agent/runs`,threadId:s,fetch:(e,t)=>KM(e,t)}),[s]),ie=!e||f===s;function ae(){re.current.clear(),y(``)}function oe(e){return S.current||e instanceof Error&&e.name===`AbortError`}(0,M.useEffect)(()=>{let t=!0;if(l([]),te.current={},d({}),p(``),h(!1),_(!1),S.current=!1,x(!1),ae(),ee(``),!e){p(s);return}!r||o.current.has(s)?(k.setMessages([]),p(s)):KM(`/api/agent/threads/${encodeURIComponent(s)}`).then(async e=>{if(e.status===404)return null;if(!e.ok)throw Error(`Unable to load thread (${e.status})`);return e.json()}).then(e=>{if(t){if(e===null){h(!0),p(s);return}k.setMessages(e.messages??[]),l(e.messages??[]),p(s)}}).catch(()=>{t&&(O.current=null,ee(`This chat could not be restored. Start a new chat or try again.`))});let i=k.subscribe({onMessagesChanged:({messages:e})=>l([...e]),onRunInitialized:()=>{S.current=!1,x(!1),_(!0),ee(``)},onTextMessageContentEvent:({event:e})=>{e.delta&&y(``)},onToolCallStartEvent:({event:e})=>{re.current.set(e.toolCallId,at(e.toolCallName)),y(at(e.toolCallName))},onToolCallResultEvent:({event:e,messages:t})=>{re.current.delete(e.toolCallId),y([...re.current.values()].at(-1)??`Analyzing your system`);let r=$e(e.toolCallId,e.content,t);r&&(n.invalidateQueries({queryKey:gN}),n.invalidateQueries({queryKey:[`dashboard`,r.id]}),n.invalidateQueries({queryKey:[`dashboard-versions`,r.id]}))},onRunErrorEvent:({event:e})=>{e.code===`abort`||S.current?(ee(``),x(!0)):(console.warn(`Agent run error`,e.code),ee(Xe(e.code))),_(!1),ae()},onRunFinalized:({messages:e})=>{let t=[...e];l(t),d(e=>{let n={...e};for(let e of t)e.role===`assistant`&&!n[e.id]&&(n[e.id]=Date.now());return n}),_(!1),ae(),o.current.delete(s),n.invalidateQueries({queryKey:iN})},onRunFailed:e=>{oe(e.error)?(ee(``),x(!0)):(console.error(`Agent run failed`,e),ee(Xe())),_(!1),ae(),o.current.delete(s),n.invalidateQueries({queryKey:iN})}});return()=>{t=!1,i.unsubscribe(),k.abortRun()}},[k,e,n,E,s]),(0,M.useEffect)(()=>{if(!e)return;let n=e=>{let n=e.target,i=n?.matches(`input, textarea, [contenteditable='true']`);e.key===`/`&&!i&&(e.preventDefault(),r?requestAnimationFrame(()=>ne.current?.focus()):t({to:`/chat`}).then(()=>requestAnimationFrame(()=>ne.current?.focus()))),e.key===`Escape`&&n===ne.current&&(w(``),ne.current?.blur())};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t,r]);async function se(){_(!0),ee(``);try{let{context:e=[],...t}=te.current;await k.runAgent({context:e,forwardedProps:t})}catch(e){oe(e)?(ee(``),x(!0)):(console.error(`Agent run failed`,e),ee(Xe())),_(!1),ae(),o.current.delete(s)}}async function ce(n,i){let a=n.trim();if(!e||!a||g||!ie||m)return;te.current={...i},r||(o.current.add(s),t({to:`/chat/$threadId`,params:{threadId:s},replace:!0}));let c={id:hN(),role:`user`,content:a};k.addMessage(c),l([...k.messages]),d(e=>({...e,[c.id]:Date.now()})),w(``),await se()}(0,M.useEffect)(()=>{let e=O.current;ie&&r&&e&&(O.current=null,ce(e.text,e.options))},[ie,r,s]);function le(e){e.preventDefault(),ce(C)}function ue(){S.current=!0,ee(``),x(!0),k.abortRun(),_(!1),ae(),o.current.delete(s)}function de(){!g&&k.messages.some(e=>e.role===`user`)&&se()}function fe(n,r){if(!e)return;let i=hN();o.current.add(i),O.current=n?{text:n,options:{...r}}:null,t({to:`/chat/$threadId`,params:{threadId:i}})}function pe(){k.abortRun(),O.current=null,te.current={},a(hN()),t({to:`/chat`})}function me(e){O.current=null,te.current={},t({to:`/chat/$threadId`,params:{threadId:e}})}function he(){D(e=>e+1)}return(0,N.jsx)(it.Provider,{value:{agentAvailable:e,threadID:s,threadMissing:m,messages:c,messageTimes:u,ready:ie,running:g,activity:v,stopped:b,input:C,setInput:w,error:T,inputRef:ne,send:ce,submit:le,stop:ue,retry:de,reloadThread:he,openChat:fe,newThread:pe,selectThread:me},children:(0,N.jsx)(WN,{children:(0,N.jsx)(Bn,{})})})}function qN(){let e=(0,M.useMemo)(()=>new Rj,[]);return(0,N.jsx)(kA,{client:e,children:(0,N.jsx)(rN,{children:(0,N.jsx)(KN,{})})})}var JN=On({component:qN,notFoundComponent:()=>(0,N.jsx)(Ve,{to:`/`,replace:!0})}),YN=kn(`/`)({component:An(()=>ot(()=>import(`./routes-D2AdaqvY.js`),__vite__mapDeps([0,1,2])),`component`)}),XN=kn(`/settings`)({component:An(()=>ot(()=>import(`./settings-taYHMo2-.js`),__vite__mapDeps([3,1,4,5,6])),`component`)}),ZN=kn(`/chat/`)({component:An(()=>ot(()=>import(`./chat.index-DMtKC6Qw.js`),__vite__mapDeps([7,8,1,4,9,5,10])),`component`)}),QN=kn(`/chat/$threadId`)({component:An(()=>ot(()=>import(`./chat._threadId-DMtKC6Qw.js`),__vite__mapDeps([11,8,1,4,9,5,10])),`component`)});function $N(e){try{let t=typeof e==`string`?e:JSON.stringify(e);if(!t||t.length>4096)return;let n=typeof e==`string`?JSON.parse(e):e;if(!n||typeof n!=`object`)return;let r=n;return typeof r.panel_id!=`string`||!/^([a-z][a-z0-9_]{0,39})$/.test(r.panel_id)||r.kind!==`traces`&&r.kind!==`logs`||typeof r.from!=`string`||typeof r.to!=`string`||!Number.isFinite(Date.parse(r.from))||!Number.isFinite(Date.parse(r.to))||Date.parse(r.from)>=Date.parse(r.to)||Date.parse(r.to)-Date.parse(r.from)>2592e6||typeof r.window_from!=`string`||typeof r.window_to!=`string`||!Number.isFinite(Date.parse(r.window_from))||!Number.isFinite(Date.parse(r.window_to))||Date.parse(r.window_from)>=Date.parse(r.window_to)||Date.parse(r.window_to)-Date.parse(r.window_from)>2592e6||Date.parse(r.from)Date.parse(r.window_to)||!r.dimensions||Array.isArray(r.dimensions)||typeof r.dimensions!=`object`||Object.keys(r.dimensions).length>3||Object.values(r.dimensions).some(e=>typeof e!=`string`||e.length>500)||r.trace_id!==void 0&&(typeof r.trace_id!=`string`||r.trace_id.length>128)||r.namespace!==void 0&&(typeof r.namespace!=`string`||r.namespace.length>200)||r.bucket&&(!Number.isFinite(r.bucket.lower)||r.bucket.lower<0||r.bucket.upper!==void 0&&(!Number.isFinite(r.bucket.upper)||r.bucket.upper<=r.bucket.lower))?void 0:{panel_id:r.panel_id,kind:r.kind,from:r.from,to:r.to,window_from:r.window_from,window_to:r.window_to,dimensions:r.dimensions,trace_id:r.trace_id,namespace:r.namespace,bucket:r.bucket}}catch{return}}function eP(e,t,n){if(!e.drill&&e.viz!==`service_map`&&!n.trace_id||t.from_ms===void 0||t.to_ms===void 0)return;let r=t.from_ms,i=t.to_ms;if(n.from!==void 0&&n.to!==void 0&&(r=Math.max(r,Date.parse(n.from)),i=Math.min(i,Date.parse(n.to))),n.time!==void 0&&!n.trace_id){let e=/^(\d+)(s|m|h|d)$/.exec(t.interval??``),a=e?Number(e[1])*{s:1e3,m:6e4,h:36e5,d:864e5}[e[2]]:6e4;r=Math.max(r,n.time),i=Math.min(i,n.time+a)}return $N(JSON.stringify({panel_id:e.id,kind:n.trace_id||e.viz===`service_map`?`traces`:e.drill,from:n.from&&Date.parse(n.from)===r?n.from:new Date(r).toISOString(),to:n.to&&Date.parse(n.to)===i?n.to:new Date(i).toISOString(),window_from:new Date(t.from_ms).toISOString(),window_to:new Date(t.to_ms).toISOString(),dimensions:n.dimensions,trace_id:n.trace_id,namespace:n.namespace,bucket:n.bucket}))}function tP(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r]){if(e===void 0)continue;let r=typeof e==`string`&&/^[{"]/.test(e);t.append(n,r||typeof e==`object`&&e?JSON.stringify(e):String(e))}let n=t.toString();return n?`?${n}`:``}function nP(e){let t=Object.create(null),n=e=>{if(e.startsWith(`{`)||e.startsWith(`"`))try{let t=JSON.parse(e);if(typeof t==`string`)return/^[{"]/.test(t)?t:e;if(typeof t==`object`&&t&&!Array.isArray(t))return t}catch{}return e},r=new URLSearchParams(e);for(let e of new Set(r.keys())){let i=r.getAll(e).map(n);t[e]=i.length===1?i[0]:i}return t}var rP=[`5m`,`15m`,`1h`,`3h`,`6h`,`12h`,`24h`,`2d`,`7d`,`30d`],iP=[`off`,`10s`,`30s`,`1m`,`5m`],aP=e=>{if(typeof e!=`string`||!/^\d{4}-\d{2}-\d{2}[Tt](?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:[Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(e)||Number.isNaN(Date.parse(e)))return!1;let[t,n,r]=e.slice(0,10).split(`-`).map(Number),i=new Date(0);return i.setUTCFullYear(t,n-1,r),i.setUTCHours(0,0,0,0),i.getUTCFullYear()===t&&i.getUTCMonth()===n-1&&i.getUTCDate()===r},oP=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`?String(e):void 0;function sP(e){let t={};typeof e.range==`string`&&rP.includes(e.range)?t.range=e.range:aP(e.from)&&aP(e.to)&&Date.parse(e.from)typeof e==`string`)&&(i[e]=t)}}else{let t=oP(n);t!==void 0&&(i[e]=t)}}}Object.keys(i).length>0&&(t.vars=i);let a=$N(e.drill);return a&&(t.drill=JSON.stringify(a)),t}function cP(e){let t={};e.drill&&(t.drill=JSON.parse(e.drill)),e.range&&(t.range=e.range),e.from&&e.to&&(t.from=e.from,t.to=e.to),e.compare&&(t.compare=e.compare),e.view&&(t.view=e.view),e.edit&&(t.edit=e.edit);for(let[n,r]of Object.entries(e.vars??{}))t[`var-${n}`]=Array.isArray(r)?{values:r}:r;return t}function lP(e,t){let n=new URL(e);return n.search=tP(cP({...sP(nP(n.search)),drill:JSON.stringify(t)})),n.href}function uP(e,t){let n=e.time.refresh??`30s`;return t.from&&t.to?{from:t.from,to:t.to,refresh:n}:t.range?{range:t.range,refresh:n}:{...e.time,refresh:n}}var dP=kn(`/dashboards/`)({component:An(()=>ot(()=>import(`./dashboards.index-CHMzfRRW.js`),__vite__mapDeps([12,1,2,13,4,9,5,10,6])),`component`),validateSearch:e=>cP(sP(e))}),fP=kn(`/dashboards/$dashboardId`)({component:An(()=>ot(()=>import(`./dashboards._dashboardId-CHxQdhK6.js`),__vite__mapDeps([14,1,2,13,4,9,5,10,6])),`component`),validateSearch:e=>cP(sP(e))}),pP=YN.update({id:`/`,path:`/`,getParentRoute:()=>JN}),mP=XN.update({id:`/settings`,path:`/settings`,getParentRoute:()=>JN}),hP=ZN.update({id:`/chat/`,path:`/chat/`,getParentRoute:()=>JN}),gP=QN.update({id:`/chat/$threadId`,path:`/chat/$threadId`,getParentRoute:()=>JN}),_P=dP.update({id:`/dashboards/`,path:`/dashboards/`,getParentRoute:()=>JN}),vP={IndexRoute:pP,SettingsRoute:mP,ChatThreadIdRoute:gP,DashboardsDashboardIdRoute:fP.update({id:`/dashboards/$dashboardId`,path:`/dashboards/$dashboardId`,getParentRoute:()=>JN}),ChatIndexRoute:hP,DashboardsIndexRoute:_P},yP=Kn({routeTree:JN._addFileChildren(vP)._addFileTypes(),parseSearch:nP,stringifySearch:tP,defaultPreload:`intent`,scrollRestoration:!0}),bP=[`#fafafa`,`#e6e4de`,`#bfbdb6`,`#8b8e99`,`#565b69`,`#1d2433`,`#131721`,`#0b0e14`,`#080a10`,`#05070b`],xP=[`#f3ecfd`,`#ece3fb`,`#dcc9f7`,`#d2a6ff`,`#bf94ec`,`#a97ce0`,`#9163d6`,`#7c4dcc`,`#5b32a3`,`#40236f`],SP=[`#eefbe6`,`#dcf7cc`,`#c2f0a6`,`#a5e880`,`#8fe06c`,`#7fd962`,`#66c04b`,`#4f9c3a`,`#3b7a2c`,`#2a5a1f`],CP=[`#fff5e6`,`#ffe9c9`,`#ffd79b`,`#ffc571`,`#ffbc62`,`#ffb454`,`#ef9c33`,`#c87d21`,`#9c5f16`,`#74460f`],wP=[`#fdecee`,`#fbd9dc`,`#f8b6bc`,`#f59099`,`#f37d87`,`#f26d78`,`#e04d5a`,`#c03642`,`#96262f`,`#6f1a21`],TP=[`#e8f6ff`,`#ccebff`,`#a3daff`,`#7dcbff`,`#66c5ff`,`#59c2ff`,`#33a7e6`,`#1e86bd`,`#146694`,`#0d4a6d`],EP={dark:{text:`#bfbdb6`,muted:`#8b8e99`,grid:`#1d2433`,surface:`#131721`,border:`#626777`},light:{text:`#4a5058`,muted:`#6b7280`,grid:`#eceef0`,surface:`#fcfcfc`,border:`#8c939d`}},DP={dark:[`#3987e5`,`#d95926`,`#199e70`,`#9085e9`,`#c98500`,`#d55181`],light:[`#2a78d6`,`#eb6834`,`#1baf7a`,`#4a3aa7`,`#eda100`,`#e87ba4`]},OP={micro:11,small:12,body:14,title:16,section:22,page:32},kP={display:`"Geist Mono Variable", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`,body:`"Geist Variable", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`},AP={brand:xP,ok:SP,warn:CP,bad:wP,info:TP},jP={light:7,dark:5};function MP(e){let t=e.replace(`#`,``),n=t.length===3?[...t].map(e=>e+e).join(``):t,r=e=>{let t=parseInt(n.slice(e,e+2),16)/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4};return .2126*r(0)+.7152*r(2)+.0722*r(4)}function NP(e){let t=MP(e),n=1.05/(t+.05);return(t+.05)/.05>n?`var(--mantine-color-black)`:`var(--mantine-color-white)`}function PP(e){return Object.fromEntries(Object.entries(AP).map(([t,n])=>[`--fanout-color-${t}-contrast`,NP(n[jP[e]])]))}function FP(e){return t=>{let n=t.color??RP.primaryColor,r=e({...t,color:n}),i=t.variant===`filled`||t.variant===void 0;return t.autoContrast===!1||!i||!Object.hasOwn(AP,n)?r:{...r,color:`var(--fanout-color-${n}-contrast)`}}}var IP=.25,LP={xs:9,sm:10,md:11,lg:13,xl:16},RP={primaryColor:`brand`,primaryShade:jP,autoContrast:!0,luminanceThreshold:IP,colors:{dark:bP,brand:xP,ok:SP,warn:CP,bad:wP,info:TP},defaultRadius:`md`,fontFamily:kP.body,fontFamilyMonospace:kP.display,headings:{fontFamily:kP.body,fontWeight:`600`},cursorType:`pointer`,components:{Tabs:{styles:(e,t)=>({tab:VP(t.color,`--tabs-text-color`)})},Pagination:{styles:(e,t)=>({control:VP(t.color,`--pagination-active-color`)})},Badge:{vars:(e,t)=>({root:BP(t.size)})},Menu:{defaultProps:{withInitialFocusPlaceholder:!1}},Drawer:{defaultProps:{closeButtonProps:{"aria-label":`Close`}}},Modal:{defaultProps:{closeButtonProps:{"aria-label":`Close`}}}}},zP=()=>({variables:{"--mantine-color-error":`var(--mantine-color-bad-filled)`},light:{"--mantine-color-dimmed":EP.light.muted,...PP(`light`)},dark:PP(`dark`)});function BP(e){let t=LP[e??`md`];return t===void 0||t>=OP.micro?{}:{"--badge-fz":`${OP.micro/16}rem`}}function VP(e,t){return!e||e===RP.primaryColor?{[t]:`var(--fanout-color-${RP.primaryColor}-contrast)`}:{}}var HP=FP(ee),UP=ri({...RP,variantColorResolver:HP});(0,$c.createRoot)(document.getElementById(`root`)).render((0,N.jsx)(M.StrictMode,{children:(0,N.jsx)(ni,{theme:UP,defaultColorScheme:`auto`,cssVariablesResolver:zP,children:(0,N.jsx)(Yn,{router:yP})})}));export{qy as $,EN as A,Gc as At,VM as B,Ei as Bt,gN as C,tb as Ct,CN as D,v_ as Dt,MN as E,S_ as Et,AN as F,ms as Ft,Pj as G,Er as Gt,EM as H,ai as Ht,wN as I,cs as It,HA as J,Qn as Jt,uj as K,cr as Kt,aN as L,F as Lt,jN as M,Sc as Mt,DN as N,Ls as Nt,bN as O,__ as Ot,TN as P,Ps as Pt,OA as Q,ZM as R,so as Rt,PN as S,Ob as St,ON as T,wy as Tt,bM as U,Ur as Ut,RM as V,hi as Vt,Zj as W,Ir as Wt,KA as X,on as Xt,PA as Y,gn as Yt,nj as Z,ln as Zt,rP as _,Yb as _t,EP as a,G as at,eP as b,U as bt,SP as c,Rb as ct,CP as d,mx as dt,Ky as et,fP as f,q as ft,sP as g,Pb as gt,uP as h,vb as ht,xP as i,Cb as it,kN as j,Rc as jt,SN as k,np as kt,DP as l,Zy as lt,lP as m,Ab as mt,MP as n,Wb as nt,kP as o,Mb as ot,dP as p,K as pt,oj as q,rr as qt,wP as r,Tb as rt,TP as s,xb as st,NP as t,_b as tt,OP as u,Bb as ut,iP as v,yx as vt,xN as w,Ay as wt,$N as x,Ib as xt,cP as y,Hb as yt,KM as z,Pi as zt}; \ No newline at end of file diff --git a/internal/ui/dist/assets/index-m8tRkNwz.js b/internal/ui/dist/assets/index-m8tRkNwz.js new file mode 100644 index 00000000..a020a892 --- /dev/null +++ b/internal/ui/dist/assets/index-m8tRkNwz.js @@ -0,0 +1,136 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/routes-D2AdaqvY.js","assets/useRouter-ByJ6_rwb.js","assets/useNavigate-B1zgPEUp.js","assets/settings-og0efxIm.js","assets/brand-DUaZkIz1.js","assets/Tooltip-B3r3s_B9.js","assets/WarningCircle.es-CEJpUomm.js","assets/chat.index-DOzBCpD0.js","assets/chat-D9q4mn0t.js","assets/preload-helper-DJZNfKNH.js","assets/dashboard-change-chips-DKNHrHOk.js","assets/chat._threadId-DOzBCpD0.js","assets/dashboards.index-CoF5-Lh4.js","assets/page-DWbtzTMF.js","assets/dashboards._dashboardId-3NqeTTXq.js"])))=>i.map(i=>d[i]); +import{a as e,i as t,n,o as r,r as i,s as a,t as o}from"./useRouter-ByJ6_rwb.js";import{$ as s,A as c,B as l,C as u,F as d,G as f,H as p,I as m,J as h,K as g,L as _,M as v,N as y,P as b,Q as x,R as S,S as C,T as w,U as T,V as ee,W as E,X as D,Y as O,Z as te,_ as ne,_t as re,a as k,at as ie,b as ae,c as oe,ct as se,d as ce,dt as le,f as ue,gt as de,h as fe,ht as pe,i as me,it as he,j as ge,k as _e,l as ve,lt as ye,m as A,mt as j,nt as be,o as xe,ot as Se,p as Ce,pt as we,q as Te,r as Ee,rt as De,st as Oe,t as ke,tt as Ae,u as je,ut as Me,v as Ne,w as Pe,x as Fe,y as Ie,z as Le}from"./brand-DUaZkIz1.js";import{i as Re,n as ze,r as Be,t as Ve}from"./useNavigate-B1zgPEUp.js";import{_ as He,a as Ue,d as We,f as Ge,g as Ke,h as qe,i as Je,l as Ye,m as Xe,n as Ze,o as Qe,p as $e,r as et,t as tt,u as nt,v as rt}from"./preload-helper-DJZNfKNH.js";import{C as it,E as at,T as ot,_ as st,a as ct,c as lt,d as ut,f as dt,g as ft,h as pt,i as mt,l as ht,m as gt,n as _t,o as vt,p as yt,r as bt,s as xt,t as St,u as Ct,v as wt,x as Tt,y as Et}from"./Tooltip-B3r3s_B9.js";(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 Dt=e((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,D());else{var t=n(l);t!==null&&ne(x,t.startTime-e)}}}var S=!1,C=-1,w=5,T=-1;function ee(){return g?!0:!(e.unstable_now()-Tt&&ee());){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&&ne(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?D():S=!1}}}var D;if(typeof y==`function`)D=function(){y(E)};else if(typeof MessageChannel<`u`){var O=new MessageChannel,te=O.port2;O.port1.onmessage=E,D=function(){te.postMessage(null)}}else D=function(){_(E,0)};function ne(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,ne(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,D()))),r},e.unstable_shouldYield=ee,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=e(((e,t)=>{t.exports=Dt()})),kt=e((e=>{var n=Ot(),r=t(),i=re();function a(e){var t=`https://react.dev/errors/`+e;if(1Se||(e.current=xe[Se],xe[Se]=null,Se--)}function Te(e,t){Se++,xe[Se]=e.current,e.current=t}var Ee=Ce(null),De=Ce(null),Oe=Ce(null),ke=Ce(null);function Ae(e,t){switch(Te(Oe,t),Te(De,e),Te(Ee,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?xp(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=xp(t),e=Sp(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}we(Ee),Te(Ee,e)}function je(){we(Ee),we(De),we(Oe)}function Me(e){var t=e.memoizedState;t!==null&&(vh._currentValue=t.memoizedState,Te(ke,e)),t=Ee.current;var n=Sp(t,e.type);t!==n&&(Te(De,e),Te(Ee,n))}function Ne(e){De.current===e&&(we(Ee),we(De)),ke.current===e&&(we(ke),vh._currentValue=be)}var Pe,Fe;function Ie(e){if(Pe===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Pe=t&&t[1]||``,Fe=-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{Le=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Ie(n):``}function ze(e,t){switch(e.tag){case 26:case 27:case 5:return Ie(e.type);case 16:return Ie(`Lazy`);case 13:return e.child!==t&&t!==null?Ie(`Suspense Fallback`):Ie(`Suspense`);case 19:return Ie(`SuspenseList`);case 0:case 15:return Re(e.type,!1);case 11:return Re(e.type.render,!1);case 1:return Re(e.type,!0);case 31:return Ie(`Activity`);case 30:return Ie(`ViewTransition`);default:return``}}function Be(e){try{var t=``,n=null;do t+=ze(e,n),n=e,e=e.return;while(e);return t}catch(e){return` +Error generating stack: `+e.message+` +`+e.stack}}var Ve=Object.prototype.hasOwnProperty,He=n.unstable_scheduleCallback,Ue=n.unstable_cancelCallback,We=n.unstable_shouldYield,Ge=n.unstable_requestPaint,Ke=n.unstable_now,qe=n.unstable_getCurrentPriorityLevel,Je=n.unstable_ImmediatePriority,Ye=n.unstable_UserBlockingPriority,Xe=n.unstable_NormalPriority,Ze=n.unstable_LowPriority,Qe=n.unstable_IdlePriority,$e=n.log,et=n.unstable_setDisableYieldValue,tt=null,nt=null;function rt(e){if(typeof $e==`function`&&et(e),nt&&typeof nt.setStrictMode==`function`)try{nt.setStrictMode(tt,e)}catch{}}var it=Math.clz32?Math.clz32:st,at=Math.log,ot=Math.LN2;function st(e){return e>>>=0,e===0?32:31-(at(e)/ot|0)|0}var ct=256,lt=262144,ut=4194304;function dt(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&-e;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 ft(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=dt(n))):i=dt(o):i=dt(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=dt(n))):i=dt(o)):i=dt(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 pt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function mt(e,t){t&8&&(t|=t&32);var n=e.entangledLanes;if(n!==0)for(e=e.entanglements,n&=t;0n;n++)t.push(e);return t}function vt(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function yt(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=_r),br=` `,xr=!1;function Sr(e,t){switch(e){case`keyup`:return hr.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function Cr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var wr=!1;function Tr(e,t){switch(e){case`compositionend`:return Cr(t);case`keypress`:return t.which===32?(xr=!0,br):null;case`textInput`:return e=t.data,e===br&&xr?null:e;default:return null}}function Er(e,t){if(wr)return e===`compositionend`||!gr&&Sr(e,t)?(e=Rn(),Ln=In=Fn=null,wr=!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=Yr(n)}}function Zr(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Zr(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Qr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Jr(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=Jr(e.document)}return t}function $r(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 ei=Mn&&`documentMode`in document&&11>=document.documentMode,ti=null,ni=null,ri=null,ii=!1;function ai(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;ii||ti==null||ti!==Jr(r)||(r=ti,`selectionStart`in r&&$r(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}),ri&&qr(ri,r)||(ri=r,r=ip(ni,`onSelect`),0>=o,i-=o,ta=1<<32-it(t)+i|n<h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),F&&ra(i,h),l;if(d===null){for(;hg?(_=h,h=null):_=h.sibling;var y=p(i,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(i,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(i,h),F&&ra(i,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(i,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return F&&ra(i,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,i,g,v.value,l),v!==null&&(e&&(_=v.alternate,_!==null&&h.delete(_.key===null?g:_.key)),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(i,e)}),F&&ra(i,g),u}function _(e,r,o,c){if(typeof o==`object`&&o&&o.type===O&&o.key===null&&o.props.ref===void 0&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case E:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===O){if(r.tag===7){n(e,r.sibling),c=i(r,o.props.children),mo(c,o),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===le&&oo(l)===r.type){n(e,r.sibling),c=i(r,o.props),mo(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===O?(c=Hi(o.props.children,e.mode,c,o.key),mo(c,o),c.return=e,e=c):(c=Vi(o.type,o.key,o.props,null,e.mode,c),mo(c,o),c.return=e,e=c)}return s(e);case D: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=i(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 le:return o=oo(o),_(e,r,o,c)}if(ye(o))return h(e,r,o,c);if(ge(o)){if(l=ge(o),typeof l!=`function`)throw Error(a(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return _(e,r,po(o),c);if(o.$$typeof===ie)return _(e,r,ja(e,o),c);ho(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=i(r,o),c.return=e,e=c):(n(e,r),c=Ui(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{fo=0;var i=_(e,t,n,r);return uo=null,i}catch(t){if(t===eo||t===no)throw t;var a=Li(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var _o=go(!0),vo=go(!1),yo=!1;function bo(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function xo(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 So(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function Co(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,sd&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=Pi(e),Ni(e,null,n),t}return Ai(e,r,t,n),Pi(e)}function wo(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,xt(e,n)}}function To(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 Eo=!1;function Do(){if(Eo){var e=Ga;if(e!==null)throw e}}function Oo(e,t,n,r){Eo=!1;var i=e.updateQueue;yo=!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 f=s.lane&-536870913,p=f!==s.lane;if(p?(ud&f)===f:(r&f)===f){f!==0&&f===Wa&&(Eo=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,h=s;f=t;var g=n;switch(h.tag){case 1:if(m=h.payload,typeof m==`function`){d=m.call(g,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=h.payload,f=typeof m==`function`?m.call(g,d,f):m,f==null)break a;d=T({},d,f);break a;case 2:yo=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,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),_d|=o,e.lanes=o,e.memoizedState=d}}function ko(e,t){if(typeof e!=`function`)throw Error(a(191,e));e.call(t)}function Ao(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;ea?a:8;var o=A.T,s={};s.types=o===null?null:o.types,A.T=s,_c(e,!1,t,n);try{var c=i(),l=A.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?gc(e,t,Ja(c,r),Hd(e)):gc(e,t,r,Hd(e))}catch(n){gc(e,t,{then:function(){},status:`rejected`,reason:n},Hd())}finally{j.p=a,o!==null&&s.types!==null&&(o.types=s.types),A.T=o}}function oc(){}function sc(e,t,n,r){if(e.tag!==5)throw Error(a(476));var i=cc(e).queue;ac(e,i,t,be,n===null?oc:function(){return lc(e),n(r)})}function cc(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:be,baseState:be,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:vs,lastRenderedState:be},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:vs,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function lc(e){var t=cc(e);t.next===null&&(t=e.alternate.memoizedState),gc(e,t.next.queue,{},Hd())}function uc(){return Aa(vh)}function dc(){return ps().memoizedState}function fc(){return ps().memoizedState}function pc(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=Hd();e=So(n);var r=Co(t,e,n);r!==null&&(Gd(r,t,n),wo(r,t,n)),t={cache:La()},e.payload=t;return}t=t.return}}function mc(e,t,n){var r=Hd();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},vc(e)?yc(t,n):(n=ji(e,t,n,r),n!==null&&(Gd(n,e,r),bc(n,t,r)))}function hc(e,t,n){gc(e,t,n,Hd())}function gc(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(vc(e))yc(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,Kr(s,o))return Ai(e,t,i,0),cd===null&&ki(),!1}catch{}if(n=ji(e,t,i,r),n!==null)return Gd(n,e,r),bc(n,t,r),!0}return!1}function _c(e,t,n,r){if(r={lane:2,revertLane:Gf(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},vc(e)){if(t)throw Error(a(479))}else t=ji(e,n,r,2),t!==null&&Gd(t,e,2)}function vc(e){var t=e.alternate;return e===I||t!==null&&t===I}function yc(e,t){Zo=Xo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function bc(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,xt(e,n)}}var xc={readContext:Aa,use:gs,useCallback:rs,useContext:rs,useEffect:rs,useImperativeHandle:rs,useLayoutEffect:rs,useInsertionEffect:rs,useMemo:rs,useReducer:rs,useRef:rs,useState:rs,useDebugValue:rs,useDeferredValue:rs,useTransition:rs,useSyncExternalStore:rs,useId:rs,useHostTransitionStatus:rs,useFormState:rs,useActionState:rs,useOptimistic:rs,useMemoCache:rs,useCacheRefresh:rs,useEffectEvent:rs},Sc={readContext:Aa,use:gs,useCallback:function(e,t){return fs().memoizedState=[e,t===void 0?null:t],e},useContext:Aa,useEffect:Ks,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),Ws(4194308,4,Qs.bind(null,t,e),n)},useLayoutEffect:function(e,t){return Ws(4194308,4,e,t)},useInsertionEffect:function(e,t){Ws(4,2,e,t)},useMemo:function(e,t){var n=fs();t=t===void 0?null:t;var r=e();if(Qo){rt(!0);try{e()}finally{rt(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=fs();if(n!==void 0){var i=n(t);if(Qo){rt(!0);try{n(t)}finally{rt(!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=mc.bind(null,I,e),[r.memoizedState,e]},useRef:function(e){var t=fs();return e={current:e},t.memoizedState=e},useState:function(e){e=Os(e);var t=e.queue,n=hc.bind(null,I,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:ec,useDeferredValue:function(e,t){return rc(fs(),e,t)},useTransition:function(){var e=Os(!1);return e=ac.bind(null,I,e.queue,!0,!1),fs().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=I,i=fs();if(F){if(n===void 0)throw Error(a(407));n=n()}else{if(n=t(),cd===null)throw Error(a(349));ud&127||Cs(r,t,n)}i.memoizedState=n;var o={value:n,getSnapshot:t};return i.queue=o,Ks(Ts.bind(null,r,o,e),[e]),r.flags|=2048,Hs(9,{destroy:void 0},ws.bind(null,r,o,n,t),null),n},useId:function(){var e=fs(),t=cd.identifierPrefix;if(F){var n=na,r=ta;n=(r&~(1<<32-it(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=$o++,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(i,{is:r.is}):s.createElement(i)}}o[kt]=t,o[At]=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(pp(o,i,r),i){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&vl(t)}}return Cl(t),t.subtreeFlags&=-33554433,yl(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&vl(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(a(166));if(e=Oe.current,ga(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,i=ca,i!==null)switch(i.tag){case 27:case 5:r=i.memoizedProps}e[kt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||up(e.nodeValue,n)),e||pa(t,!0)}else e=bp(e).createTextNode(r),e[kt]=t,t.stateNode=e}return Cl(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=ga(t),n!==null){if(e===null){if(!r)throw Error(a(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(a(557));e[kt]=t}else _a(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Cl(t),e=!1}else n=va(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(Ho(t),t):(Ho(t),null);if(t.flags&128)throw Error(a(558))}return Cl(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(i=ga(t),r!==null&&r.dehydrated!==null){if(e===null){if(!i)throw Error(a(318));if(i=t.memoizedState,i=i===null?null:i.dehydrated,!i)throw Error(a(317));i[kt]=t}else _a(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Cl(t),i=!1}else i=va(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=i),i=!0;if(!i)return t.flags&256?(Ho(t),t):(Ho(t),null)}return Ho(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,i=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(i=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==i&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),xl(t,t.updateQueue),Cl(t),null);case 4:return je(),e===null&&ep(t.stateNode.containerInfo),t.flags|=67108864,Cl(t),null;case 10:return wa(t.type),Cl(t),null;case 19:if(Go(t),r=t.memoizedState,r===null)return Cl(t),null;if(i=!!(t.flags&128),o=r.rendering,o===null){if(i)Sl(r,!1);else{if(z!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=Ko(e),o!==null){for(t.flags|=128,Sl(r,!1),e=o.updateQueue,t.updateQueue=e,xl(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)Bi(n,e),n=n.sibling;return Wo(t,Uo.current&1|2),F&&ra(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Ke()>Dd&&(t.flags|=128,i=!0,Sl(r,!1),t.lanes=4194304)}}else{if(!i){if(e=Ko(o),e!==null){if(t.flags|=128,i=!0,e=e.updateQueue,t.updateQueue=e,xl(t,e),Sl(r,!0),r.tail===null&&r.tailMode!==`collapsed`&&r.tailMode!==`visible`&&!o.alternate&&!F)return Cl(t),null}else 2*Ke()-r.renderingStartTime>Dd&&n!==536870912&&(t.flags|=128,i=!0,Sl(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)}if(r.tail!==null){e=r.tail;a:{for(n=e;n!==null;){if(n.alternate!==null){n=!1;break a}n=n.sibling}n=!0}return r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Ke(),e.sibling=null,o=Uo.current,o=i?o&1|2:o&1,r.tailMode===`visible`||r.tailMode===`collapsed`||!n||F?Wo(t,o):(n=o,Te(Io,t),Te(Uo,n),Lo===null&&(Lo=t)),F&&ra(t,r.treeForkCount),e}return Cl(t),null;case 22:case 23:return Ho(t),Fo(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Cl(t),t.subtreeFlags&6&&(t.flags|=8192)):Cl(t),n=t.updateQueue,n!==null&&xl(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&&we(Xa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),wa(Ia),Cl(t),null;case 25:return null;case 30:return t.flags|=33554432,Cl(t),null}throw Error(a(156,t.tag))}function Tl(e,t){switch(oa(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return wa(Ia),je(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Ne(t),null;case 31:if(t.memoizedState!==null){if(Ho(t),t.alternate===null)throw Error(a(340));_a()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Ho(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(a(340));_a()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Go(t),e=t.flags,e&65536?(t.flags=e&-65537|128,e=t.memoizedState,e!==null&&(e.rendering=null,e.tail=null),t.flags|=4,t):null;case 4:return je(),null;case 10:return wa(t.type),null;case 22:case 23:return Ho(t),Fo(),e!==null&&we(Xa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return wa(Ia),null;case 25:return null;default:return null}}function El(e,t){switch(oa(t),t.tag){case 3:wa(Ia),je();break;case 26:case 27:case 5:Ne(t);break;case 4:je();break;case 31:t.memoizedState!==null&&Ho(t);break;case 13:Ho(t);break;case 19:Go(t);break;case 10:wa(t.type);break;case 22:case 23:Ho(t),Fo(),e!==null&&we(Xa);break;case 24:wa(Ia)}}function Dl(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){wf(t,t.return,e)}}function Ol(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){wf(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){wf(t,t.return,e)}}function kl(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{Ao(t,n)}catch(t){wf(e,e.return,t)}}}function Al(e,t,n){n.props=kc(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){wf(e,t,n)}}function jl(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:var i=e.stateNode,a=Si(e.memoizedProps,i);(i.ref===null||i.ref.name!==a)&&(i.ref=Gp(a)),r=i.ref;break;case 7:if(e.stateNode===null){var o=new Kp(e);p(e.child,!1,lm,o,void 0,void 0),e.stateNode=o}r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){wf(e,t,n)}}function Ml(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){wf(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){wf(e,t,n)}else n.current=null}}function Nl(e,t){if((e.tag===5||e.tag===27||e.tag===6)&&e.alternate===null&&t!==null)for(var n=0;n title`))),pp(r,t,n),r[kt]=e,Vt(r),t=r;break a;case`link`:if(o=nh(`link`,`href`,i).get(t+(n.href||``))){for(s=0;sg&&(o=g,g=h,h=o);var _=Xr(s,h),v=Xr(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,A.T=null,n=Fd,Fd=null;var o=jd,s=Nd;if(Ad=0,Md=jd=null,Nd=0,sd&6)throw Error(a(331));var c=sd;if(sd|=4,nd(o.current),Ju(o,o.current,s,n),sd=c,Rf(0,!1),nt&&typeof nt.onPostCommitFiberRoot==`function`)try{nt.onPostCommitFiberRoot(tt,o)}catch{}return!0}finally{j.p=i,A.T=r,bf(e,t)}}function Cf(e,t,n){t=qi(n,t),t=Fc(e.stateNode,t,2),e=Co(e,t,2),e!==null&&(vt(e,2),Lf(e))}function wf(e,t,n){if(e.tag===3)Cf(e,e,n);else for(;t!==null;){if(t.tag===3){Cf(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(kd===null||!kd.has(r))){e=qi(n,e),n=Ic(2),r=Co(t,n,2),r!==null&&(Lc(n,r,t,e),vt(r,2),Lf(r));break}}t=t.return}}function Tf(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new od;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)||(hd=!0,i.add(n),e=Ef.bind(null,e,t,n),t.then(e,e))}function Ef(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,cd===e&&(ud&n)===n&&(z===4||z===3&&(ud&62914560)===ud&&300>Ke()-Td?sd&2?yd|=n:Qd(e,0):yd|=n,xd===ud&&(xd=0)),Lf(e)}function Df(e,t){t===0&&(t=gt()),e=Mi(e,t),e!==null&&(vt(e,t),Lf(e))}function Of(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),Df(e,n)}function kf(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,i=e.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(a(314))}r!==null&&r.delete(t),Df(e,n)}function Af(e,t){return He(e,t)}var jf=null,Mf=null,Nf=!1,Pf=!1,Ff=!1,If=0;function Lf(e){e!==Mf&&e.next===null&&(Mf===null?jf=Mf=e:Mf=Mf.next=e),Pf=!0,Nf||(Nf=!0,Wf())}function Rf(e,t){if(!Ff&&Pf){Ff=!0;do for(var n=!1,r=jf;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-it(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,Uf(r,a))}else a=ud,a=ft(r,r===cd?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||pt(r,a)||(n=!0,Uf(r,a))}r=r.next}while(n);Ff=!1}}function zf(){Bf()}function Bf(){Pf=Nf=!1;var e=0;If!==0&&Ep()&&(e=If);for(var t=Ke(),n=null,r=jf;r!==null;){var i=r.next,a=Vf(r,t);a===0?(r.next=null,n===null?jf=i:n.next=i,i===null&&(Mf=n)):(n=r,(e!==0||a&3)&&(Pf=!0)),r=i}Ad!==0&&Ad!==5||Rf(e,!1),If!==0&&(If=0)}function Vf(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&&gp(d)&&(c=c.responseEnd,o+=u*(cuh){s.length=o;break}f=new Promise(Hp.bind(f)),s.push(f)}}}if(0`u`?null:document;function Im(e,t,n){var r=Fm;if(r&&typeof t==`string`&&t){var i=cn(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),Am.has(i)||(Am.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),pp(t,`link`,e),Vt(t),r.head.appendChild(t)))}}function Lm(e){Mm.D(e),Im(`dns-prefetch`,e,null)}function Rm(e,t){Mm.C(e,t),Im(`preconnect`,e,t)}function zm(e,t,n){Mm.L(e,t,n);var r=Fm;if(r&&e&&t){var i=`link[rel="preload"][as="`+cn(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+cn(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+cn(n.imageSizes)+`"]`)):i+=`[href="`+cn(e)+`"]`;var a=i;switch(t){case`style`:a=Gm(e);break;case`script`:a=Ym(e)}if(!(km.has(a)||(e=T({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),km.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Km(a))||t===`script`&&r.querySelector(Xm(a))))){var o=r.createElement(`link`);pp(o,`link`,e),t===`style`&&(o[Ft]=!0,o.onload=o.onerror=function(){Ht(o)}),Vt(o),r.head.appendChild(o)}}}function Bm(e,t){Mm.m(e,t);var n=Fm;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+cn(r)+`"][href="`+cn(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=Ym(e)}if(!km.has(a)&&(e=T({rel:`modulepreload`,href:e},t),km.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(Xm(a)))return}r=n.createElement(`link`),pp(r,`link`,e),Vt(r),n.head.appendChild(r)}}}function Vm(e,t,n){Mm.S(e,t,n);var r=Fm;if(r&&e){var i=Bt(r).hoistableStyles,a=Gm(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Km(a)))s.loading=5;else{e=T({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=km.get(a))&&$m(e,n);var c=o=r.createElement(`link`);Vt(c),pp(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,Qm(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Hm(e,t){Mm.X(e,t);var n=Fm;if(n&&e){var r=Bt(n).hoistableScripts,i=Ym(e),a=r.get(i);a||(a=n.querySelector(Xm(i)),a||(e=T({src:e,async:!0},t),(t=km.get(i))&&eh(e,t),a=n.createElement(`script`),Vt(a),pp(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Um(e,t){Mm.M(e,t);var n=Fm;if(n&&e){var r=Bt(n).hoistableScripts,i=Ym(e),a=r.get(i);a||(a=n.querySelector(Xm(i)),a||(e=T({src:e,async:!0,type:`module`},t),(t=km.get(i))&&eh(e,t),a=n.createElement(`script`),Vt(a),pp(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Wm(e,t,n,r){var i=(i=Oe.current)?jm(i):null;if(!i)throw Error(a(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(n=Gm(n.href),t=Bt(i).hoistableStyles,r=t.get(n),r||(r={type:`style`,instance:null,count:0,state:null},t.set(n,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=Gm(n.href);var o=Bt(i).hoistableStyles,s=o.get(e);if(s||(i=i.ownerDocument||i,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=i.querySelector(Km(e)))?o._p||(s.instance=o,s.state.loading=5):(o=km.get(e),o||(o={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},km.set(e,o)),Jm(i,e,o,s.state))),t&&r===null)throw Error(a(528,``));return s}if(t&&r!==null)throw Error(a(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(n=Ym(n),t=Bt(i).hoistableScripts,r=t.get(n),r||(r={type:`script`,instance:null,count:0,state:null},t.set(n,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(a(444,e))}}function Gm(e){return`href="`+cn(e)+`"`}function Km(e){return`link[rel="stylesheet"][`+e+`]`}function qm(e){return T({},e,{"data-precedence":e.precedence,precedence:null})}function Jm(e,t,n,r){if(t=e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)){if(!0!==t[Ft]){r.loading=1;return}}else t=e.createElement(`link`),t[Ft]=!0,t.onload=t.onerror=Ht.bind(null,t),pp(t,`link`,n),Vt(t),e.head.appendChild(t);r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2})}function Ym(e){return`[src="`+cn(e)+`"]`}function Xm(e){return`script[async]`+e}function Zm(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+cn(n.href)+`"]`);if(r)return t.instance=r,Vt(r),r;var i=T({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),Vt(r),pp(r,`style`,i),Qm(r,n.precedence,e),t.instance=r;case`stylesheet`:i=Gm(n.href);var o=e.querySelector(Km(i));if(o)return t.state.loading|=4,t.instance=o,Vt(o),o;r=qm(n),(i=km.get(i))&&$m(r,i),o=(e.ownerDocument||e).createElement(`link`),Vt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),pp(o,`link`,r),t.state.loading|=4,Qm(o,n.precedence,e),t.instance=o;case`script`:return o=Ym(n.src),(i=e.querySelector(Xm(o)))?(t.instance=i,Vt(i),i):(r=n,(i=km.get(o))&&(r=T({},n),eh(r,i)),e=e.ownerDocument||e,i=e.createElement(`script`),Vt(i),pp(i,`link`,r),e.head.appendChild(i),t.instance=i);case`void`:return null;default:throw Error(a(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,Qm(r,n.precedence,e));return t.instance}function Qm(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 ih(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 ah(e,t){return e===`img`&&t.src!=null&&t.src!==``&&t.onLoad==null&&t.loading!==`lazy`}function oh(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function sh(e){return(e.width||100)*(e.height||100)*(typeof devicePixelRatio==`number`?devicePixelRatio:1)*.25}function ch(e,t){typeof t.decode==`function`&&(e.imgCount++,t.complete||(e.imgBytes+=sh(t),e.suspenseyImages.push(t)),e=mh.bind(e),t.decode().then(e,e))}function lh(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=Gm(r.href),a=t.querySelector(Km(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=ph.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,Vt(a);return}a=t.ownerDocument||t,r=qm(r),(i=km.get(i))&&$m(r,i),a=a.createElement(`link`),Vt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),pp(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=ph.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var uh=0;function dh(e,t){return e.stylesheets&&e.count===0&&gh(e,e.stylesheets),0uh?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function fh(e){if(e.count===0&&(e.imgCount===0||!e.waitingForImages)){if(e.stylesheets)gh(e,e.stylesheets);else if(e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}}}function ph(){this.count--,fh(this)}function mh(){this.imgCount--,fh(this)}var hh=null;function gh(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,hh=new Map,t.forEach(_h,e),hh=null,ph.call(e))}function _h(e,t){if(!(t.state.loading&4)){var n=hh.get(e);if(n)var r=n.get(null);else{n=new Map,hh.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=kt()})),jt=class{get to(){return this._to}get id(){return this._id}get path(){return this._path}get fullPath(){return this._fullPath}constructor(e){if(this.init=e=>{this.originalIndex=e,this._branch=void 0;let t=this.options,n=!t?.path&&!t?.id;this.parentRoute=this.options.getParentRoute?.(),n?this._path=nt:this.parentRoute||qe();let r=n?nt:t?.path;r&&r!==`/`&&(r=$e(r));let i=t?.id||r,a=n?nt:Ge((this.parentRoute.id===`__root__`?``:this.parentRoute.id)+`/`+(i??``));r===`__root__`&&(r=`/`);let o=a===`__root__`?`/`:r===void 0?this.parentRoute.fullPath:Ge(this.parentRoute.fullPath+`/`+r);this._path=r,this._id=a,this._fullPath=o,this._to=Xe(o)},this.addChildren=e=>this._addFileChildren(e),this._addFileChildren=e=>(Array.isArray(e)&&(this.children=e),typeof e==`object`&&e&&(this.children=Object.values(e)),this),this._addFileTypes=()=>this,this.updateLoader=e=>(Object.assign(this.options,e),this),this.update=e=>(Object.assign(this.options,e),this),this.lazy=e=>(this.lazyFn=e,this),this.redirect=e=>Ye({from:this.fullPath,...e}),this.options=e||{},this.isRoot=!e?.getParentRoute,e?.id&&e?.path)throw Error(`Route cannot have both an 'id' and a 'path' option.`)}},Mt=class extends jt{constructor(e){super(e)}},M=a(t(),1),N=i(),Nt=class extends M.Component{constructor(...e){super(...e),this.state={error:0},this.reset=()=>{this.setState({error:0})}}static getDerivedStateFromProps(e,t){let n=e.getResetKey();return t.error&&t.resetKey!==n?{resetKey:n,error:0}:{resetKey:n}}static getDerivedStateFromError(e){return{error:[e]}}componentDidCatch(e,t){this.props.onCatch?.(e,t)}render(){let e=this.state.error;return e?M.createElement(this.props.errorComponent??Pt,{error:e[0],reset:this.reset}):this.props.children}};function Pt({error:e}){let[t,n]=M.useState(!1);return(0,N.jsxs)(`div`,{style:{padding:`.5rem`,maxWidth:`100%`},children:[(0,N.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:`.5rem`},children:[(0,N.jsx)(`strong`,{style:{fontSize:`1rem`},children:`Something went wrong!`}),(0,N.jsx)(`button`,{style:{appearance:`none`,fontSize:`.6em`,border:`1px solid currentColor`,padding:`.1rem .2rem`,fontWeight:`bold`,borderRadius:`.25rem`},onClick:()=>n(e=>!e),children:t?`Hide Error`:`Show Error`})]}),(0,N.jsx)(`div`,{style:{height:`.25rem`}}),t?(0,N.jsx)(`div`,{children:(0,N.jsx)(`pre`,{style:{fontSize:`.7em`,border:`1px solid red`,borderRadius:`.25rem`,padding:`.3rem`,color:`red`,overflow:`auto`},children:e?.message?(0,N.jsx)(`code`,{children:e.message}):null})}):null]})}var Ft=()=>!0,It=()=>!1;function Lt({children:e,fallback:t=null}){return(0,N.jsx)(M.Fragment,{children:Rt()?e:t})}function Rt(e=!0){return M.useSyncExternalStore(zt,Ft,e?It:Ft)}function zt(){return()=>{}}function Bt({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(1)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(1)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function Vt(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var Ht=[],Ut=0,{link:Wt,unlink:Gt,propagate:Kt,checkDirty:qt,shallowPropagate:Jt}=Bt({update(e){return e._update()},notify(e){Ht[Xt++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,$t(e))}}),Yt=0,Xt=0,P,Zt=0;function Qt(e){try{++Zt,e()}finally{--Zt||en()}}function $t(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=Gt(n,e)}function en(){if(!(Zt>0)){for(;Yt{i.get(),n.current?(P=void 0,t.next?.(i._snapshot)):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=P,o=t?.compare??Object.is;if(n)P=i,++Ut,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{P=a,n&&(i.flags&=-5),$t(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&qt(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&Jt(e)}}else e&32&&(i.flags=e&-33);return P!==void 0&&Wt(i,P,Ut),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Kt(e),Jt(e),en())}},i}function nn(e){let t=()=>{let t=P;P=n,++Ut,n.depsTail=void 0,n.flags=6;try{return e()}finally{P=t,n.flags&=-5,$t(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&qt(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,$t(this)}};return t(),n}var rn=e((e=>{var n=t();function r(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:r,a=n.useState,o=n.useEffect,s=n.useLayoutEffect,c=n.useDebugValue;function l(e,t){var n=t(),r=a({inst:{value:n,getSnapshot:t}}),i=r[0].inst,l=r[1];return s(function(){i.value=n,i.getSnapshot=t,u(i)&&l({inst:i})},[e,n,t]),o(function(){return u(i)&&l({inst:i}),e(function(){u(i)&&l({inst:i})})},[e]),c(n),n}function u(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!i(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:l;e.useSyncExternalStore=n.useSyncExternalStore===void 0?f:n.useSyncExternalStore})),an=e(((e,t)=>{t.exports=rn()})),on=e((e=>{var n=t(),r=an();function i(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var a=typeof Object.is==`function`?Object.is:i,o=r.useSyncExternalStore,s=n.useRef,c=n.useEffect,l=n.useMemo,u=n.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var d=s(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=l(function(){function e(e){if(!o){if(o=!0,s=e,e=r(e),i!==void 0&&f.hasValue){var t=f.value;if(i(t,e))return c=t}return c=e}if(t=c,a(s,e))return t;var n=r(e);return i!==void 0&&i(t,n)?(s=e,t):(s=e,c=n)}var o=!1,s,c,l=n===void 0?null:n;return[function(){return e(t())},l===null?void 0:function(){return e(l())}]},[t,n,r,i]);var p=o(e,d[0],d[1]);return c(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}})),sn=e(((e,t)=>{t.exports=on()}))();function cn(e,t){return e===t}function ln(e,t=e=>e,n){let r=n?.compare??cn,i=(0,M.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,M.useCallback)(()=>e.get(),[e]);return(0,sn.useSyncExternalStoreWithSelector)(i,a,a,t,r)}var un={};function dn(e,t){let n=M.useRef();return r=>{let i=e?.select?e.select(r):r;return e?.structuralSharing??t.options.defaultStructuralSharing?n.current=rt(n.current,i):i}}function fn(e){let t=o(),n=M.useContext(e.from?et:Je),r=e.from??n,i=t.stores.getMatchStore(r),a=dn(e,t),s=ln(i,e=>e?a(e):un);if(s!==un)return s;(e.shouldThrow??!0)&&qe()}function pn(e){return fn({from:e.from,strict:e.strict,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.loaderData):t.loaderData})}function mn(e){let{select:t,...n}=e;return fn({...n,select:e=>t?t(e.loaderDeps):e.loaderDeps})}function hn(e){return fn({from:e.from,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,strict:e.strict,select:t=>{let n=e.strict===!1?t.params:t._strictParams;return e.select?e.select(n):n}})}function gn(e){return fn({from:e.from,strict:e.strict,shouldThrow:e.shouldThrow,structuralSharing:e.structuralSharing,select:t=>e.select?e.select(t.search):t.search})}function _n(e){return fn({...e,select:t=>e.select?e.select(t.context):t.context})}var vn=class extends jt{constructor(e){super(e),this.useMatch=e=>fn({...e,from:this.id}),this.useRouteContext=e=>_n({...e,from:this.id}),this.useSearch=e=>gn({...e,from:this.id}),this.useParams=e=>hn({...e,from:this.id}),this.useLoaderDeps=e=>mn({...e,from:this.id}),this.useLoaderData=e=>pn({...e,from:this.id}),this.useNavigate=()=>ze({from:this.fullPath}),this.Link=M.forwardRef((e,t)=>(0,N.jsx)(Ze,{ref:t,from:this.fullPath,...e}))}};function yn(e){return new vn(e)}var bn=class extends Mt{constructor(e){super(e),this.useMatch=e=>fn({...e,from:this.id}),this.useRouteContext=e=>_n({...e,from:this.id}),this.useSearch=e=>gn({...e,from:this.id}),this.useParams=e=>hn({...e,from:this.id}),this.useLoaderDeps=e=>mn({...e,from:this.id}),this.useLoaderData=e=>pn({...e,from:this.id}),this.useNavigate=()=>ze({from:this.fullPath}),this.Link=M.forwardRef((e,t)=>(0,N.jsx)(Ze,{ref:t,from:this.fullPath,...e}))}};function xn(e){return new bn(e)}function Sn(e){return e=>{let t=yn(e);return t.isRoot=!1,t}}function Cn(e,t){let n,r,i,a=()=>(n||=(i=void 0,e().then(e=>{n=void 0,o.preload=void 0,r=e[t??`default`]}).catch(e=>{n=void 0,i=e})),n),o=function(e){if(i){if(He(i)&&typeof sessionStorage<`u`){let e=`tanstack_router_reload:${i.message}`;if(!sessionStorage.getItem(e))throw sessionStorage.setItem(e,`1`),window.location.reload(),new Promise(()=>{})}throw i}if(!r){if(Be)Be(a());else throw a()}return M.createElement(r,e)};return o.preload=a,o}function wn(e){let t=o(),n=`not-found-${ln(t.stores.location,e=>e.pathname)}-${ln(t.stores.status)}`;return(0,N.jsx)(Nt,{getResetKey:()=>n,onCatch:(t,n)=>{if(We(t))e.onCatch?.(t,n);else throw t},errorComponent:({error:t})=>{if(We(t))return e.fallback?.(t);throw t},children:e.children})}function Tn(){return(0,N.jsx)(`p`,{children:`Not Found`})}function En(e,t,n){return t.options.notFoundComponent?(0,N.jsx)(t.options.notFoundComponent,{...n}):e.options.defaultNotFoundComponent?(0,N.jsx)(e.options.defaultNotFoundComponent,{...n}):(0,N.jsx)(Tn,{})}function Dn(e,t){let n=t?.options.pendingComponent??e.options.defaultPendingComponent;return n?(0,N.jsx)(n,{}):null}var On=(e,t)=>e[0]===t[0]&&e[1]===t[1],kn=(e,t,n)=>!t.isRoot||t.options.shellComponent||t.options.wrapInSuspense||n===!1||n===`data-only`||!e.ssr,An=M.memo(function({routeId:e}){let t=o();return jn(t,ln(t.stores.getMatchStore(e)))});function jn(e,t){let n=e.routesById[t.routeId],r=Dn(e,n),i=n.options.errorComponent??e.options.defaultErrorComponent,a=n.options.onCatch??e.options.defaultOnCatch,o=n.isRoot?n.options.notFoundComponent??e.options.notFoundRoute?.options.component:n.options.notFoundComponent,s=t.ssr===!1||t.ssr===`data-only`,c=kn(e,n,t.ssr)&&(n.options.wrapInSuspense??r??(n.options.errorComponent?.preload||s)),l=(0,N.jsx)(Mn,{match:t});s&&(l=(0,N.jsx)(Lt,{fallback:r,children:l})),o&&(l=(0,N.jsx)(wn,{fallback:e=>{if(e.routeId??=t.routeId,e.routeId!==t.routeId)throw e;return M.createElement(o,e)},children:l})),i&&(l=(0,N.jsx)(Nt,{getResetKey:()=>t,errorComponent:i,onCatch:(e,n)=>{if(We(e))throw e.routeId??=t.routeId,e;a?.(e,n)},children:l})),c&&(l=(0,N.jsx)(M.Suspense,{fallback:r,children:l}));let u=n.isRoot&&n.options.shellComponent;return u?(0,N.jsx)(Je.Provider,{value:t.routeId,children:(0,N.jsxs)(u,{children:[l,null]})}):(0,N.jsxs)(Je.Provider,{value:t.routeId,children:[l,null]})}var Mn=M.memo(function({match:e}){let t=o(),n=e.routeId,r=t.routesById[n],i=M.useMemo(()=>{let i=(r.options.remountDeps??t.options.defaultRemountDeps)?.({routeId:n,loaderDeps:e.loaderDeps,params:e._strictParams,search:e._strictSearch});return i?JSON.stringify(i):void 0},[n,e.loaderDeps,e._strictParams,e._strictSearch,r.options.remountDeps,t.options.defaultRemountDeps]),a=M.useMemo(()=>{let e=r.options.component??t.options.defaultComponent;return e?(0,N.jsx)(e,{},i):(0,N.jsx)(Nn,{})},[i,r.options.component,t.options.defaultComponent]);if(e.status===`pending`){if(t.ssr&&!kn(t,r,e.ssr))return a;if(t._tx)throw t._tx[5];return Dn(t,r)}if(e.status===`notFound`)return En(t,r,e.error);if(e.status===`error`)throw e.error;return a}),Nn=M.memo(function(){let e=o(),t=M.useContext(Je),n,r,i;{let a=e.stores.getMatchStore(t);[n,r]=ln(a,e=>[!!e._notFound,e.error],{compare:On}),i=ln(e.stores.ids,e=>e[e.indexOf(t)+1])}if(n)return En(e,e.routesById[t],r);if(!i)return null;let a=(0,N.jsx)(An,{routeId:i});return t===`__root__`?(0,N.jsx)(M.Suspense,{fallback:Dn(e),children:a}):a});function Pn(e,t){let n=e[1];e.length=0,n?.(t)}function Fn({t:e}){let t=o(),n=t._rendered??=[];return t.startTransition=(r,i)=>new Promise(a=>{Pn(n,!1),n.push(i,a),e(t),M.startTransition(r)}),Re(()=>{let e=t.history.subscribe(t.load);t.updateLatestLocation();let r=t.latestLocation,i=t.buildLocation({to:r.pathname,search:!0,params:!0,hash:!0,state:!0,_includeValidateSearch:!0});if(Xe(r.publicHref)!==Xe(i.publicHref))return t.commitLocation({...i,replace:!0,ignoreBlocker:!0}),e;let a=t.stores.resolvedLocation.get();return a?.href===r.href&&a.state.__TSR_key===r.state.__TSR_key?n.push(t.stores.matches.get(),e=>{e&&t.emit({type:`onRendered`,...Qe(a,a)})}):t._tx||t.load({sync:!0}).catch(console.error),e},[t,t.history]),null}function In(){let e=o(),t=e.routesById[nt],n=Dn(e,t),r=(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(Fn,{t:M.useState()[1]}),e.ssr?(0,N.jsx)(Ln,{}):(0,N.jsx)(M.Suspense,{fallback:n,children:(0,N.jsx)(Ln,{})})]});return e.options.InnerWrap?(0,N.jsx)(e.options.InnerWrap,{children:r}):r}function Ln(){let e=o(),t=e._rendered,n=ln(e.stores.matches,e=>t[0]??e),r=n[0],i=r?.routeId;Re(()=>{t[0]===n&&Pn(t,!0)},[t,n]);let a=i?(0,N.jsx)(An,{routeId:i}):null;return e.options.disableGlobalCatchBoundary?a:(0,N.jsx)(Nt,{getResetKey:()=>r,onCatch:void 0,children:a})}var Rn=e=>({createMutableStore:tn,createReadonlyStore:tn,batch:Qt}),zn=e=>new Bn(e),Bn=class extends Ue{constructor(e){super(e,Rn)}};function Vn({router:e,children:t,...r}){Ke(r)&&e.update({...e.options,...r,context:{...e.options.context,...r.context}});let i=(0,N.jsx)(n.Provider,{value:e,children:t});return e.options.Wrap?(0,N.jsx)(e.options.Wrap,{children:i}):i}function Hn({router:e,...t}){return(0,N.jsx)(Vn,{router:e,...t,children:(0,N.jsx)(In,{})})}function Un(e){let t=o({warn:e?.router===void 0}),n=e?.router||t;return ln(n.stores.__store,dn(e,n))}function Wn(e){return typeof e!=`string`||!e.includes(`var(--mantine-scale)`)?e:e.match(/^calc\((.*?)\)$/)?.[1].split(`*`)[0].trim()}function Gn(e){let t=Wn(e);return typeof t==`number`?t:typeof t==`string`?t.includes(`calc`)||t.includes(`var`)?t:t.includes(`px`)?Number(t.replace(`px`,``)):t.includes(`rem`)?Number(t.replace(`rem`,``))*16:t.includes(`em`)?Number(t.replace(`em`,``))*16:Number(t):NaN}function Kn(e,t){let n=e;for(;(n=n.parentElement)&&!n.matches(t););return n}function qn(e,t,n){for(let n=e-1;n>=0;--n)if(!t[n].disabled)return n;if(n){for(let e=t.length-1;e>-1;--e)if(!t[e].disabled)return e}return e}function Jn(e,t,n){for(let n=e+1;n{n?.(s);let c=Array.from(Kn(s.currentTarget,e)?.querySelectorAll(t)||[]).filter(t=>Yn(s.currentTarget,t,e)),l=c.findIndex(e=>s.currentTarget===e),u=Jn(l,c,r),d=qn(l,c,r),f=a===`rtl`?d:u,p=a===`rtl`?u:d;switch(s.key){case`ArrowRight`:o===`horizontal`&&(s.stopPropagation(),s.preventDefault(),c[f].focus(),i&&c[f].click());break;case`ArrowLeft`:o===`horizontal`&&(s.stopPropagation(),s.preventDefault(),c[p].focus(),i&&c[p].click());break;case`ArrowUp`:o===`vertical`&&(s.stopPropagation(),s.preventDefault(),c[d].focus(),i&&c[d].click());break;case`ArrowDown`:o===`vertical`&&(s.stopPropagation(),s.preventDefault(),c[u].focus(),i&&c[u].click());break;case`Home`:s.stopPropagation(),s.preventDefault(),c[Jn(-1,c,!1)]?.focus();break;case`End`:s.stopPropagation(),s.preventDefault(),c[qn(c.length,c,!1)]?.focus()}}}var Zn=()=>{};function Qn(e,t={active:!0}){return typeof e!=`function`||!t.active?t.onKeyDown||Zn:n=>{n.key===`Escape`&&(e(n),t.onTrigger?.())}}function $n(e,t){return n=>{e?.(n),t?.(n)}}function er(e,t){return e in t?Gn(t[e]):Gn(e)}function tr(e,t){let n=e.map(e=>({value:e,px:er(e,t)}));return n.sort((e,t)=>e.px-t.px),n}function nr(e,t,n){return n?Array.from(Kn(n,t)?.querySelectorAll(e)||[]).findIndex(e=>e===n):null}var rr=[`mousedown`,`touchstart`];function ir(e,t,n,r=!0,i=!1){let a=(0,M.useRef)(null),o=t||rr,s=(0,M.useEffectEvent)(t=>{let{target:r}=t??{};if(!document.body.contains(r)&&r?.tagName!==`HTML`)return;let i=t.composedPath();Array.isArray(n)?n.every(e=>!!e&&!i.includes(e))&&e(t):a.current&&!i.includes(a.current)&&e(t)}),c=o.join(`,`);return(0,M.useEffect)(()=>{if(!r)return;let e=c.split(`,`);return e.forEach(e=>document.addEventListener(e,s,i)),()=>{e.forEach(e=>document.removeEventListener(e,s,i))}},[c,r,i]),a}function ar(e,t){return ie(`(prefers-color-scheme: dark)`,e===`dark`,t)?`dark`:`light`}function or(e,t,n={leading:!1}){let[r,i]=(0,M.useState)(e),a=(0,M.useRef)(!1),o=(0,M.useRef)(null),s=(0,M.useRef)(!1),c=(0,M.useRef)(e);c.current=e;let l=(0,M.useCallback)(()=>{window.clearTimeout(o.current),o.current=null},[]),u=(0,M.useCallback)(()=>{l(),s.current=!1},[]),d=(0,M.useCallback)(()=>{o.current&&(u(),s.current=!1,i(c.current))},[]);return(0,M.useEffect)(()=>{a.current&&(l(),!s.current&&n.leading?(s.current=!0,i(e),o.current=window.setTimeout(()=>{s.current=!1},t)):o.current=window.setTimeout(()=>{s.current=!1,i(e)},t))},[e,n.leading,t]),(0,M.useEffect)(()=>(a.current=!0,u),[]),[r,u,{cancel:u,flush:d}]}function sr({opened:e,shouldReturnFocus:t=!0}){let n=(0,M.useRef)(null),r=()=>{n.current&&`focus`in n.current&&typeof n.current.focus==`function`&&n.current?.focus({preventScroll:!0})};return De(()=>{let i=-1,a=e=>{e.key===`Tab`&&window.clearTimeout(i)};if(document.addEventListener(`keydown`,a),e)n.current=document.activeElement;else if(t){let e=document.activeElement;i=window.setTimeout(()=>{let t=document.activeElement;(t===null||t===document.body||t===e)&&r()},10)}return()=>{window.clearTimeout(i),document.removeEventListener(`keydown`,a)}},[e,t]),r}var cr=/input|select|textarea|button|object/,lr=`a, input, select, textarea, button, object, [tabindex]`;function ur(e){return e.style.display===`none`}function dr(e){if(e.getAttribute(`aria-hidden`)||e.getAttribute(`hidden`)||e.getAttribute(`type`)===`hidden`)return!1;let t=e;for(;t&&t!==document.body&&t.nodeType!==11;){if(ur(t))return!1;t=t.parentNode}return!0}function fr(e){let t=e.getAttribute(`tabindex`);return t===null&&(t=void 0),parseInt(t,10)}function pr(e){let t=e.nodeName.toLowerCase(),n=!Number.isNaN(fr(e));return(cr.test(t)&&!e.disabled||e instanceof HTMLAnchorElement&&e.href||n)&&dr(e)}function mr(e){let t=fr(e);return(Number.isNaN(t)||t>=0)&&pr(e)}function hr(e){return Array.from(e.querySelectorAll(lr)).filter(mr)}function gr(e,t){let n=hr(e);if(!n.length){t.preventDefault();return}let r=n[t.shiftKey?0:n.length-1],i=e.getRootNode(),a=r===i.activeElement||e===i.activeElement,o=i.activeElement;if(o.tagName===`INPUT`&&o.getAttribute(`type`)===`radio`&&(a=n.filter(e=>e.getAttribute(`type`)===`radio`&&e.getAttribute(`name`)===o.getAttribute(`name`)).includes(r)),!a)return;t.preventDefault();let s=n[t.shiftKey?n.length-1:0];s&&s.focus()}function _r(e=!0){let t=(0,M.useRef)(null),n=e=>{let t=e.querySelector(`[data-autofocus]`);if(!t){let n=Array.from(e.querySelectorAll(lr));t=n.find(mr)||n.find(pr)||null,!t&&pr(e)&&(t=e)}t?t.focus({preventScroll:!0}):console.warn(`[@mantine/hooks/use-focus-trap] Failed to find focusable element within provided node`,e)},r=(0,M.useCallback)(r=>{if(e){if(r===null){t.current=null;return}t.current!==r&&(setTimeout(()=>{r.getRootNode()?n(r):console.warn(`[@mantine/hooks/use-focus-trap] Ref node is not part of the dom`,r)}),t.current=r)}},[e]);return(0,M.useEffect)(()=>{if(!e)return;t.current&&setTimeout(()=>{t.current&&n(t.current)});let r=e=>{e.key===`Tab`&&t.current&&gr(t.current,e)};return document.addEventListener(`keydown`,r),()=>document.removeEventListener(`keydown`,r)},[e]),r}function vr(e,t,n){let r=(0,M.useEffectEvent)(t);(0,M.useEffect)(()=>(window.addEventListener(e,r,n),()=>window.removeEventListener(e,r,n)),[e])}function yr({value:e,defaultValue:t,finalValue:n,onChange:r=()=>{}}){let[i,a]=(0,M.useState)(t===void 0?n:t);return e===void 0?[i,(e,...t)=>{a(e),r?.(e,...t)},!1]:[e,r,!0]}function br(e=!1,t={}){let[n,r]=(0,M.useState)(e),i=(0,M.useCallback)(()=>{r(e=>e||(t.onOpen?.(),!0))},[t.onOpen]),a=(0,M.useCallback)(()=>{r(e=>e&&(t.onClose?.(),!1))},[t.onClose]);return[n,{open:i,close:a,toggle:(0,M.useCallback)(()=>{n?a():i()},[a,i,n]),set:r}]}var xr=[`mouse`,`touch`],Sr=10;function Cr(e,t={}){let{threshold:n=400,events:r=xr,cancelOnMove:i=!1,onStart:a,onFinish:o,onCancel:s}=t,c=(0,M.useRef)(!1),l=(0,M.useRef)(!1),u=(0,M.useRef)(-1),d=(0,M.useRef)(null);(0,M.useEffect)(()=>()=>window.clearTimeout(u.current),[]);let f=r.join(`,`);return(0,M.useMemo)(()=>{if(typeof e!=`function`)return{};let t=i!==!1,f=i===!0?Sr:i===!1?0:i,p=t=>{(Er(t)||Tr(t))&&(a&&a(t),d.current=wr(t),l.current=!0,u.current=window.setTimeout(()=>{e(t),c.current=!0},n))},m=e=>{(Er(e)||Tr(e))&&(c.current?o&&o(e):l.current&&s&&s(e),c.current=!1,l.current=!1,d.current=null,u.current!==-1&&(window.clearTimeout(u.current),u.current=-1))},h=e=>{if(!t||!l.current||c.current)return;let n=wr(e);if(!n||!d.current)return;let r=n.x-d.current.x,i=n.y-d.current.y;Math.sqrt(r*r+i*i)>f&&m(e)},g={};return r.includes(`mouse`)&&(g.onMouseDown=p,g.onMouseUp=m,g.onMouseLeave=m,t&&(g.onMouseMove=h)),r.includes(`touch`)&&(g.onTouchStart=p,g.onTouchEnd=m,g.onTouchCancel=m,t&&(g.onTouchMove=h)),g},[e,n,s,o,a,i,f])}function wr(e){if(Tr(e)){let t=e.touches[0]??e.changedTouches[0];return t?{x:t.clientX,y:t.clientY}:null}return{x:e.clientX,y:e.clientY}}function Tr(e){return window.TouchEvent?e.nativeEvent instanceof TouchEvent:`touches`in e.nativeEvent}function Er(e){return e.nativeEvent instanceof MouseEvent}function Dr(e){return e===`auto`||e===`dark`||e===`light`}function Or({key:e=`mantine-color-scheme-value`}={}){let t;return{get:t=>{if(typeof window>`u`)return t;try{let n=window.localStorage.getItem(e);return Dr(n)?n:t}catch{return t}},set:t=>{try{window.localStorage.setItem(e,t)}catch(e){console.warn(`[@mantine/core] Local storage color scheme manager was unable to save color scheme.`,e)}},subscribe:n=>{t=t=>{t.storageArea===window.localStorage&&t.key===e&&Dr(t.newValue)&&n(t.newValue)},window.addEventListener(`storage`,t)},unsubscribe:()=>{window.removeEventListener(`storage`,t)},clear:()=>{window.localStorage.removeItem(e)}}}function kr({color:e,theme:t,autoContrast:n,colorScheme:r}){return(typeof n==`boolean`?n:t.autoContrast)&&Te({color:e||t.primaryColor,theme:t,colorScheme:r}).isLight?`var(--mantine-color-black)`:`var(--mantine-color-white)`}function Ar(e,t,n){return kr({color:n===`dark`?e.dark:e.light,theme:t,colorScheme:n,autoContrast:!0})}function jr(e,t){let n=e.colors[e.primaryColor];return f(n)?e.autoContrast?Ar(n,e,t):`var(--mantine-color-white)`:kr({color:n[h(e,t)],theme:e,autoContrast:null})}function Mr(e){let t=document.createElement(`style`);return t.setAttribute(`data-mantine-styles`,`inline`),t.innerHTML=`*, *::before, *::after {transition: none !important;}`,t.setAttribute(`data-mantine-disable-transition`,`true`),e&&t.setAttribute(`nonce`,e),document.head.appendChild(t),()=>document.querySelectorAll(`[data-mantine-disable-transition]`).forEach(e=>e.remove())}function Nr({keepTransitions:e}={}){let t=(0,M.useRef)(Zn),n=(0,M.useRef)(-1),r=(0,M.use)(m),i=l(),a=(0,M.useRef)(i?.());if(!r)throw Error(`[@mantine/core] MantineProvider was not found in tree`);let o=i=>{r.setColorScheme(i),t.current=e?()=>{}:Mr(a.current),window.clearTimeout(n.current),n.current=window.setTimeout(()=>{t.current?.()},10)},s=()=>{r.clearColorScheme(),t.current=e?()=>{}:Mr(a.current),window.clearTimeout(n.current),n.current=window.setTimeout(()=>{t.current?.()},10)},c=ar(`light`,{getInitialValueInEffect:!1}),u=r.colorScheme===`auto`?c:r.colorScheme,d=(0,M.useCallback)(()=>o(u===`light`?`dark`:`light`),[o,u]);return(0,M.useEffect)(()=>()=>{t.current?.(),window.clearTimeout(n.current)},[]),{colorScheme:r.colorScheme,setColorScheme:o,clearColorScheme:s,toggleColorScheme:d}}function Pr(e,t){let n=typeof window<`u`&&`matchMedia`in window&&window.matchMedia(`(prefers-color-scheme: dark)`)?.matches,r=e===`auto`?n?`dark`:`light`:e;t()?.setAttribute(`data-mantine-color-scheme`,r)}function Fr({manager:e,defaultColorScheme:t,getRootElement:n,forceColorScheme:r}){let i=(0,M.useRef)(null),[a,o]=(0,M.useState)(()=>e.get(t)),s=r||a,c=(0,M.useCallback)(t=>{r||(Pr(t,n),o(t),e.set(t))},[e.set,s,r]),l=(0,M.useCallback)(()=>{o(t),Pr(t,n),e.clear()},[e.clear,t]);return(0,M.useEffect)(()=>(e.subscribe(c),e.unsubscribe),[e.subscribe,e.unsubscribe]),he(()=>{Pr(e.get(t),n)},[]),(0,M.useEffect)(()=>{if(r)return Pr(r,n),()=>{};r===void 0&&Pr(a,n),typeof window<`u`&&`matchMedia`in window&&(i.current=window.matchMedia(`(prefers-color-scheme: dark)`));let e=e=>{a===`auto`&&Pr(e.matches?`dark`:`light`,n)};return i.current?.addEventListener(`change`,e),()=>i.current?.removeEventListener(`change`,e)},[a,r]),{colorScheme:s,setColorScheme:c,clearColorScheme:l}}function Ir(e,t={getInitialValueInEffect:!0}){let n=ar(e,t),{colorScheme:r}=Nr();return r===`auto`?n:r}function Lr(e){return Object.entries(e).map(([e,t])=>`${e}: ${t};`).join(``)}function Rr(e,t){let n=t?[t]:[`:root`,`:host`],r=Lr(e.variables),i=r?`${n.join(`, `)}{${r}}`:``,a=Lr(e.dark),o=Lr(e.light),s=e=>n.map(t=>t===`:host`?`${t}([data-mantine-color-scheme="${e}"])`:`${t}[data-mantine-color-scheme="${e}"]`).join(`, `);return`${i}\n\n${a?`${s(`dark`)}{${a}}`:``}\n\n${o?`${s(`light`)}{${o}}`:``}`}function zr({theme:e,color:t,colorScheme:n,name:r=t,withColorValues:i=!0}){if(!e.colors[t])return{};if(n===`light`){let n=h(e,`light`),a={[`--mantine-color-${r}-text`]:`var(--mantine-color-${r}-filled)`,[`--mantine-color-${r}-filled`]:`var(--mantine-color-${r}-${n})`,[`--mantine-color-${r}-filled-hover`]:`var(--mantine-color-${r}-${n===9?8:n+1})`,[`--mantine-color-${r}-light`]:`var(--mantine-color-${r}-1)`,[`--mantine-color-${r}-light-hover`]:`var(--mantine-color-${r}-2)`,[`--mantine-color-${r}-light-color`]:`var(--mantine-color-${r}-9)`,[`--mantine-color-${r}-outline`]:`var(--mantine-color-${r}-${n})`,[`--mantine-color-${r}-outline-hover`]:p(e.colors[t][n],.05)};return i?{[`--mantine-color-${r}-0`]:e.colors[t][0],[`--mantine-color-${r}-1`]:e.colors[t][1],[`--mantine-color-${r}-2`]:e.colors[t][2],[`--mantine-color-${r}-3`]:e.colors[t][3],[`--mantine-color-${r}-4`]:e.colors[t][4],[`--mantine-color-${r}-5`]:e.colors[t][5],[`--mantine-color-${r}-6`]:e.colors[t][6],[`--mantine-color-${r}-7`]:e.colors[t][7],[`--mantine-color-${r}-8`]:e.colors[t][8],[`--mantine-color-${r}-9`]:e.colors[t][9],...a}:a}let a=h(e,`dark`),o={[`--mantine-color-${r}-text`]:`var(--mantine-color-${r}-4)`,[`--mantine-color-${r}-filled`]:`var(--mantine-color-${r}-${a})`,[`--mantine-color-${r}-filled-hover`]:`var(--mantine-color-${r}-${a===9?8:a+1})`,[`--mantine-color-${r}-light`]:E(e.colors[t][9],.5),[`--mantine-color-${r}-light-hover`]:E(e.colors[t][9],.3),[`--mantine-color-${r}-light-color`]:`var(--mantine-color-${r}-0)`,[`--mantine-color-${r}-outline`]:`var(--mantine-color-${r}-${Math.max(a-4,0)})`,[`--mantine-color-${r}-outline-hover`]:p(e.colors[t][Math.max(a-4,0)],.05)};return i?{[`--mantine-color-${r}-0`]:e.colors[t][0],[`--mantine-color-${r}-1`]:e.colors[t][1],[`--mantine-color-${r}-2`]:e.colors[t][2],[`--mantine-color-${r}-3`]:e.colors[t][3],[`--mantine-color-${r}-4`]:e.colors[t][4],[`--mantine-color-${r}-5`]:e.colors[t][5],[`--mantine-color-${r}-6`]:e.colors[t][6],[`--mantine-color-${r}-7`]:e.colors[t][7],[`--mantine-color-${r}-8`]:e.colors[t][8],[`--mantine-color-${r}-9`]:e.colors[t][9],...o}:o}function Br(e,t,n){de(t).forEach(r=>Object.assign(e,{[`--mantine-${n}-${r}`]:t[r]}))}var Vr=e=>{let t=h(e,`light`),n=e.defaultRadius in e.radius?e.radius[e.defaultRadius]:j(e.defaultRadius),r={variables:{"--mantine-z-index-app":`100`,"--mantine-z-index-modal":`200`,"--mantine-z-index-popover":`300`,"--mantine-z-index-overlay":`400`,"--mantine-z-index-max":`9999`,"--mantine-scale":e.scale.toString(),"--mantine-cursor-type":e.cursorType,"--mantine-webkit-font-smoothing":e.fontSmoothing?`antialiased`:`unset`,"--mantine-moz-font-smoothing":e.fontSmoothing?`grayscale`:`unset`,"--mantine-color-white":e.white,"--mantine-color-black":e.black,"--mantine-line-height":e.lineHeights.md,"--mantine-font-family":e.fontFamily,"--mantine-font-family-monospace":e.fontFamilyMonospace,"--mantine-font-family-headings":e.headings.fontFamily,"--mantine-heading-font-weight":e.headings.fontWeight,"--mantine-heading-text-wrap":e.headings.textWrap,"--mantine-radius-default":n,"--mantine-primary-color-filled":`var(--mantine-color-${e.primaryColor}-filled)`,"--mantine-primary-color-filled-hover":`var(--mantine-color-${e.primaryColor}-filled-hover)`,"--mantine-primary-color-light":`var(--mantine-color-${e.primaryColor}-light)`,"--mantine-primary-color-light-hover":`var(--mantine-color-${e.primaryColor}-light-hover)`,"--mantine-primary-color-light-color":`var(--mantine-color-${e.primaryColor}-light-color)`},light:{"--mantine-color-scheme":`light`,"--mantine-primary-color-contrast":jr(e,`light`),"--mantine-color-bright":`var(--mantine-color-black)`,"--mantine-color-text":e.black,"--mantine-color-body":e.white,"--mantine-color-error":`var(--mantine-color-red-6)`,"--mantine-color-success":`var(--mantine-color-teal-8)`,"--mantine-color-placeholder":`var(--mantine-color-gray-5)`,"--mantine-color-anchor":`var(--mantine-color-${e.primaryColor}-${t})`,"--mantine-color-default":`var(--mantine-color-white)`,"--mantine-color-default-hover":`var(--mantine-color-gray-0)`,"--mantine-color-default-color":`var(--mantine-color-black)`,"--mantine-color-default-border":`var(--mantine-color-gray-4)`,"--mantine-color-dimmed":`var(--mantine-color-gray-6)`,"--mantine-color-disabled":`var(--mantine-color-gray-2)`,"--mantine-color-disabled-color":`var(--mantine-color-gray-5)`,"--mantine-color-disabled-border":`var(--mantine-color-gray-3)`},dark:{"--mantine-color-scheme":`dark`,"--mantine-primary-color-contrast":jr(e,`dark`),"--mantine-color-bright":`var(--mantine-color-white)`,"--mantine-color-text":`var(--mantine-color-dark-0)`,"--mantine-color-body":`var(--mantine-color-dark-7)`,"--mantine-color-error":`var(--mantine-color-red-8)`,"--mantine-color-success":`var(--mantine-color-teal-8)`,"--mantine-color-placeholder":`var(--mantine-color-dark-3)`,"--mantine-color-anchor":`var(--mantine-color-${e.primaryColor}-4)`,"--mantine-color-default":`var(--mantine-color-dark-6)`,"--mantine-color-default-hover":`var(--mantine-color-dark-5)`,"--mantine-color-default-color":`var(--mantine-color-white)`,"--mantine-color-default-border":`var(--mantine-color-dark-4)`,"--mantine-color-dimmed":`var(--mantine-color-dark-2)`,"--mantine-color-disabled":`var(--mantine-color-dark-6)`,"--mantine-color-disabled-color":`var(--mantine-color-dark-3)`,"--mantine-color-disabled-border":`var(--mantine-color-dark-4)`}};Br(r.variables,e.breakpoints,`breakpoint`),Br(r.variables,e.spacing,`spacing`),Br(r.variables,e.fontSizes,`font-size`),Br(r.variables,e.lineHeights,`line-height`),Br(r.variables,e.shadows,`shadow`),Br(r.variables,e.radius,`radius`),Br(r.variables,e.fontWeights,`font-weight`),e.colors[e.primaryColor].forEach((t,n)=>{r.variables[`--mantine-primary-color-${n}`]=`var(--mantine-color-${e.primaryColor}-${n})`}),de(e.colors).forEach(t=>{let n=e.colors[t];if(f(n)){Object.assign(r.light,zr({theme:e,name:n.name,color:n.light,colorScheme:`light`,withColorValues:!0})),Object.assign(r.dark,zr({theme:e,name:n.name,color:n.dark,colorScheme:`dark`,withColorValues:!0})),r.light[`--mantine-color-${n.name}-contrast`]=Ar(n,e,`light`),r.dark[`--mantine-color-${n.name}-contrast`]=Ar(n,e,`dark`);return}n.forEach((e,n)=>{r.variables[`--mantine-color-${t}-${n}`]=e}),Object.assign(r.light,zr({theme:e,color:t,colorScheme:`light`,withColorValues:!1})),Object.assign(r.dark,zr({theme:e,color:t,colorScheme:`dark`,withColorValues:!1}))});let i=e.headings.sizes;return de(i).forEach(t=>{r.variables[`--mantine-${t}-font-size`]=i[t].fontSize,r.variables[`--mantine-${t}-line-height`]=i[t].lineHeight,r.variables[`--mantine-${t}-font-weight`]=i[t].fontWeight||e.headings.fontWeight}),r};function Hr(){let e=b(),t=l(),n=de(e.breakpoints).reduce((t,n)=>{let r=e.breakpoints[n].includes(`px`),i=Gn(e.breakpoints[n]);return`${t}@media (max-width: ${r?`${i-.1}px`:we(i-.1)}) {.mantine-visible-from-${n} {display: none !important;}}@media (min-width: ${r?`${i}px`:we(i)}) {.mantine-hidden-from-${n} {display: none !important;}}`},``);return(0,N.jsx)(`style`,{"data-mantine-styles":`classes`,nonce:t?.(),dangerouslySetInnerHTML:{__html:n}})}function Ur({theme:e,generator:t}){let n=Vr(e),r=t?.(e);return r?pe(n,r):n}var Wr=Vr(d);function Gr(e){let t={variables:{},light:{},dark:{}};return de(e.variables).forEach(n=>{Wr.variables[n]!==e.variables[n]&&(t.variables[n]=e.variables[n])}),de(e.light).forEach(n=>{Wr.light[n]!==e.light[n]&&(t.light[n]=e.light[n])}),de(e.dark).forEach(n=>{Wr.dark[n]!==e.dark[n]&&(t.dark[n]=e.dark[n])}),t}function Kr(e){return Rr({variables:{},dark:{"--mantine-color-scheme":`dark`},light:{"--mantine-color-scheme":`light`}},e)}function qr({cssVariablesSelector:e,deduplicateCssVariables:t}){let n=b(),r=l(),i=Ur({theme:n,generator:S()}),a=(e===void 0||e===`:root`||e===`:host`)&&t,o=Rr(a?Gr(i):i,e);return o?(0,N.jsx)(`style`,{"data-mantine-styles":!0,nonce:r?.(),dangerouslySetInnerHTML:{__html:`${o}${a?``:Kr(e)}`}}):null}qr.displayName=`@mantine/CssVariables`;function Jr({respectReducedMotion:e,getRootElement:t}){he(()=>{e&&t()?.setAttribute(`data-respect-reduced-motion`,`true`)},[e])}function Yr({theme:e,children:t,getStyleNonce:n,withStaticClasses:r=!0,withGlobalClasses:i=!0,deduplicateCssVariables:a=!0,withCssVariables:o=!0,cssVariablesSelector:s,classNamesPrefix:c=`mantine`,colorSchemeManager:l=Or(),defaultColorScheme:u=`light`,getRootElement:d=()=>document.documentElement,cssVariablesResolver:f,forceColorScheme:p,stylesTransform:h,env:g,deduplicateInlineStyles:_=!1}){let{colorScheme:v,setColorScheme:b,clearColorScheme:x}=Fr({defaultColorScheme:u,forceColorScheme:p,manager:l,getRootElement:d});return Jr({respectReducedMotion:e?.respectReducedMotion||!1,getRootElement:d}),(0,N.jsx)(m,{value:{colorScheme:v,setColorScheme:b,clearColorScheme:x,getRootElement:d,classNamesPrefix:c,getStyleNonce:n,cssVariablesResolver:f,cssVariablesSelector:s??`:root`,withStaticClasses:r,stylesTransform:h,env:g,deduplicateInlineStyles:_},children:(0,N.jsxs)(y,{theme:e,children:[o&&(0,N.jsx)(qr,{cssVariablesSelector:s,deduplicateCssVariables:a}),i&&(0,N.jsx)(Hr,{}),t]})})}Yr.displayName=`@mantine/core/MantineProvider`;function Xr(e){return e}var Zr={root:`m_515a97f8`},Qr=w(e=>{let t=v(`VisuallyHidden`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,attributes:l,...d}=t,f=c({name:`VisuallyHidden`,classes:Zr,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:l});return(0,N.jsx)(u,{component:`span`,...f(`root`),...d})});Qr.classes=Zr,Qr.displayName=`@mantine/core/VisuallyHidden`;function $r({open:e,close:t,openDelay:n,closeDelay:r}){let i=(0,M.useRef)(-1),a=(0,M.useRef)(-1),o=()=>{window.clearTimeout(i.current),window.clearTimeout(a.current)};return(0,M.useEffect)(()=>o,[]),{openDropdown:()=>{o(),n===0||n===void 0?e():i.current=window.setTimeout(e,n)},closeDropdown:()=>{o(),r===0||r===void 0?t():a.current=window.setTimeout(t,r)}}}var ei={root:`m_9814e45f`},ti={zIndex:ot(`modal`)},ni=D((e,{gradient:t,color:n,backgroundOpacity:r,blur:i,radius:a,zIndex:o})=>({root:{"--overlay-bg":t||(n!==void 0||r!==void 0)&&T(n||`#000`,r??.6)||void 0,"--overlay-filter":i?`blur(${j(i)})`:void 0,"--overlay-radius":a===void 0?void 0:Oe(a),"--overlay-z-index":o?.toString()}})),ri=Pe(e=>{let t=v(`Overlay`,ti,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,fixed:l,center:d,children:f,radius:p,zIndex:m,gradient:h,blur:g,color:_,backgroundOpacity:y,mod:b,attributes:x,...S}=t,C=c({name:`Overlay`,props:t,classes:ei,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:x,vars:s,varsResolver:ni});return(0,N.jsx)(u,{...C(`root`),mod:[{center:d,fixed:l},b],...S,children:f})});ri.classes=ei,ri.varsResolver=ni,ri.displayName=`@mantine/core/Overlay`;var[ii,ai]=at(`Popover component was not found in the tree`);function oi({childProps:e,disabled:t,opened:n,longPressDelay:r=500,setReference:i,open:a}){let o=(0,M.useRef)(!1),s=(0,M.useRef)(!1),c=(0,M.useRef)(null),l=(0,M.useRef)(t);l.current=t;let u=(e,t,n)=>{i({getBoundingClientRect:()=>({x:e,y:t,width:0,height:0,top:t,left:e,right:e,bottom:t,toJSON:()=>void 0}),contextElement:n}),a()},d=$n(e.onMouseDown,e=>{t||e.button===2&&e.stopPropagation()}),f=$n(e.onContextMenu,e=>{t||e.defaultPrevented||(e.preventDefault(),!s.current&&(u(e.clientX,e.clientY,e.currentTarget),o.current&&(s.current=!0)))}),p=Cr(e=>{if(l.current||s.current)return;let t=e,n=t.touches[0]??t.changedTouches[0];n&&(u(n.clientX,n.clientY,c.current),s.current=!0)},{threshold:r,events:[`touch`],cancelOnMove:!0,onStart:e=>{o.current=!0,s.current=!1,c.current=e.currentTarget},onFinish:e=>{o.current=!1,s.current=!1,l.current||e.preventDefault()},onCancel:()=>{o.current=!1,s.current=!1}});return{onContextMenu:f,onMouseDown:d,onTouchStart:$n(e.onTouchStart,p.onTouchStart),onTouchEnd:$n(e.onTouchEnd,p.onTouchEnd),onTouchCancel:$n(e.onTouchCancel,p.onTouchCancel),onTouchMove:$n(e.onTouchMove,p.onTouchMove),style:t?e.style:{...e.style,WebkitTouchCallout:`none`,WebkitUserSelect:`none`,userSelect:`none`},"data-expanded":n?!0:void 0}}function si(e){let{children:t,disabled:n,longPressDelay:r}=v(`PopoverContextMenu`,null,e),i=te(t);if(!i)throw Error(`Popover.ContextMenu component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let a=ai(),o=oi({childProps:i.props,disabled:n||a.disabled,opened:a.opened,longPressDelay:r,setReference:a.reference,open:()=>{a.opened||a.onToggle()}});return(0,M.cloneElement)(i,o)}si.displayName=`@mantine/core/PopoverContextMenu`;function ci({children:e,active:t=!0,refProp:n=`ref`,innerRef:r}){let i=_r(t),a=Ae(i,r),o=te(e);return o?(0,M.cloneElement)(o,{[n]:a}):e}function li(e){return(0,N.jsx)(Qr,{tabIndex:-1,"data-autofocus":!0,...e})}ci.displayName=`@mantine/core/FocusTrap`,li.displayName=`@mantine/core/FocusTrapInitialFocus`,ci.InitialFocus=li;var ui={dropdown:`m_38a85659`,arrow:`m_a31dc6c1`,overlay:`m_3d7bc908`},di=w(e=>{let t=v(`PopoverDropdown`,null,e),{className:n,style:r,vars:i,children:a,onKeyDownCapture:o,variant:s,classNames:c,styles:l,ref:d,...f}=t,p=ai(),{dir:m}=Tt(),h=p.arrowPosition===`merge`&&p.withArrow?ct({position:p.placement,dir:m}):void 0,g=sr({opened:p.opened,shouldReturnFocus:p.returnFocus}),_=p.withRoles?{"aria-labelledby":p.getTargetId(),id:p.getDropdownId(),role:`dialog`,tabIndex:-1}:{},y=Ae(d,p.floating);return p.disabled?null:(0,N.jsx)(_t,{...p.portalProps,withinPortal:p.withinPortal,children:(0,N.jsx)(ae,{mounted:p.opened,...p.transitionProps,transition:p.transitionProps?.transition||`fade`,duration:p.transitionProps?.duration??150,keepMounted:p.keepMounted,keepMountedMode:p.keepMountedMode,exitDuration:typeof p.transitionProps?.exitDuration==`number`?p.transitionProps.exitDuration:p.transitionProps?.duration,children:e=>(0,N.jsx)(ci,{active:p.trapFocus&&p.opened,innerRef:y,children:(0,N.jsxs)(u,{..._,...f,variant:s,onKeyDownCapture:Qn(()=>{p.onClose?.(),p.onDismiss?.()},{active:p.closeOnEscape,onTrigger:g,onKeyDown:o}),"data-position":p.placement,"data-fixed":p.floatingStrategy===`fixed`||void 0,...p.getStyles(`dropdown`,{className:n,props:t,classNames:c,styles:l,style:[{...e,...h,zIndex:p.zIndex,top:p.y??0,left:p.x??0,width:p.width===`target`?void 0:j(p.width),...p.referenceHidden?{display:`none`}:null},p.resolvedStyles?.dropdown,l?.dropdown,r]}),children:[a,(0,N.jsx)(mt,{ref:p.arrowRef,arrowX:p.arrowX,arrowY:p.arrowY,visible:p.withArrow,position:p.placement,arrowSize:p.arrowSize,arrowRadius:p.arrowRadius,arrowOffset:p.arrowOffset,arrowPosition:p.arrowPosition,...p.getStyles(`arrow`,{props:t,classNames:c,styles:l})})]})})})})});di.classes=ui,di.displayName=`@mantine/core/PopoverDropdown`;var fi={refProp:`ref`,popupType:`dialog`},pi=w(e=>{let{children:t,refProp:n,popupType:r,ref:i,...a}=v(`PopoverTarget`,fi,e),o=te(t);if(!o)throw Error(`Popover.Target component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let s=a,c=ai(),l=Ae(c.reference,it(o),i),u=c.withRoles?{"aria-haspopup":r,"aria-expanded":c.opened,"aria-controls":c.opened?c.getDropdownId():void 0,id:c.getTargetId()}:{},d=o.props;return(0,M.cloneElement)(o,{...s,...u,...c.targetProps,className:O(c.targetProps.className,s.className,d.className),[n]:l,...c.controlled?null:{onClick:e=>{c.onToggle(),d.onClick?.(e)}}})});pi.displayName=`@mantine/core/PopoverTarget`;function mi(e){if(e===void 0)return{shift:!0,flip:!0};let t={...e};return e.shift===void 0&&(t.shift=!0),e.flip===void 0&&(t.flip=!0),t}function hi(e,t,n,r){let i=mi(e.middlewares),a=[ft(e.offset),yt()];if(i.flip&&!n){let e=typeof i.flip==`boolean`?{}:i.flip,t=r?{fallbackStrategy:`initialPlacement`,...e}:e;a.push(dt(t))}if(i.shift){let t=typeof i.shift==`boolean`?{}:i.shift;a.push(st(n=>{let r=n.placement.startsWith(`top`)||n.placement.startsWith(`bottom`);return{limiter:pt(),padding:5,...e.width===`target`&&r?{mainAxis:!1}:null,...t}}))}return i.inline&&a.push(typeof i.inline==`boolean`?gt():gt(i.inline)),a.push(ut({element:e.arrowRef,padding:e.arrowOffset})),(i.size||e.width===`target`)&&a.push(wt({...typeof i.size==`boolean`?{}:i.size,apply({rects:n,availableWidth:r,availableHeight:a,...o}){let s=t().refs.floating.current?.style??{};i.size&&(typeof i.size==`object`&&i.size.apply?i.size.apply({rects:n,availableWidth:r,availableHeight:a,...o}):Object.assign(s,{maxWidth:`${r}px`,maxHeight:`${a}px`})),e.width===`target`&&Object.assign(s,{width:`${n.reference.width}px`})}})),a}function gi(e){let[t,n]=yr({value:e.opened,defaultValue:e.defaultOpened,finalValue:!1,onChange:e.onChange}),r=(0,M.useRef)(t),i=(0,M.useRef)(!1),[a,o]=(0,M.useState)(null),s=e.preventPositionChangeWhenVisible!==!1,c=(0,M.useRef)(t);t!==c.current&&(c.current=t,t&&a!==null&&o(null));let l=(0,M.useRef)(e.position);e.position!==l.current&&(l.current=e.position,i.current=!1,a!==null&&o(null));let u=(0,M.useCallback)(()=>o(null),[]),d=()=>{t&&!e.disabled&&n(!1)},f=()=>{e.disabled||n(!t)},p=lt({open:t,strategy:e.strategy,placement:s?a??e.position:e.position,middleware:hi(e,()=>p,s&&a!==null,s),whileElementsMounted:e.keepMounted?void 0:Et});(0,M.useEffect)(()=>{if(!e.keepMounted)return;let n=p.refs.reference.current,r=p.refs.floating.current;if(t&&n&&r)return Et(n,r,p.update)},[e.keepMounted,t,p.update,p.elements.reference,p.elements.floating]),he(()=>{if(!t){i.current=!1;return}if(!s||a!==null)return;let e=p.refs.floating.current;if(e&&e.offsetHeight!==0&&e.offsetWidth!==0){if(!i.current){i.current=!0,p.update();return}p.isPositioned&&o(p.placement)}},[s,t,p.isPositioned,p.placement,a,p.update]);let m=(0,M.useRef)(p.placement);return he(()=>{m.current!==p.placement&&(m.current=p.placement,e.onPositionChange?.(p.placement))},[p.placement]),De(()=>{t!==r.current&&(t?e.onOpen?.():e.onClose?.()),r.current=t},[t,e.onClose,e.onOpen]),{floating:p,controlled:typeof e.opened==`boolean`,opened:t,onClose:d,onToggle:f,resetLockedPlacement:u}}var _i={position:`bottom`,offset:8,transitionProps:{transition:`fade`,duration:150},middlewares:{flip:!0,shift:!0,inline:!1},arrowSize:7,arrowOffset:5,arrowRadius:0,arrowPosition:`side`,closeOnClickOutside:!0,withinPortal:!0,closeOnEscape:!0,trapFocus:!1,withRoles:!0,returnFocus:!1,withOverlay:!1,hideDetached:!0,preventPositionChangeWhenVisible:!0,clickOutsideEvents:[`mousedown`,`touchstart`],clickOutsideCapture:!1,zIndex:ot(`popover`),__staticSelector:`Popover`,width:`max-content`},vi=D((e,{radius:t,shadow:n})=>({dropdown:{"--popover-radius":t===void 0?void 0:Oe(t),"--popover-shadow":se(n)}}));function yi(e){let t=v(`Popover`,_i,e),{children:n,position:r,offset:i,onPositionChange:a,opened:o,transitionProps:s,onExitTransitionEnd:l,onEnterTransitionEnd:u,width:d,middlewares:f,withArrow:p,arrowSize:m,arrowOffset:h,arrowRadius:g,arrowPosition:_,unstyled:y,classNames:b,styles:x,closeOnClickOutside:S,withinPortal:C,portalProps:w,closeOnEscape:T,clickOutsideEvents:ee,clickOutsideCapture:E,trapFocus:D,onClose:O,onDismiss:te,onOpen:ne,onChange:re,zIndex:k,radius:ie,shadow:oe,id:se,defaultOpened:ce,__staticSelector:le,withRoles:ue,disabled:de,returnFocus:fe,variant:pe,keepMounted:me,keepMountedMode:he,vars:_e,floatingStrategy:ve,withOverlay:ye,overlayProps:A,hideDetached:j,attributes:xe,preventPositionChangeWhenVisible:Se,...Ce}=t,we=c({name:le,props:t,classes:ui,classNames:b,styles:x,unstyled:y,attributes:xe,rootSelector:`dropdown`,vars:_e,varsResolver:vi}),{resolvedStyles:Te}=ge({classNames:b,styles:x,props:t}),Ee=(0,M.useRef)(null),[De,Oe]=(0,M.useState)(null),[ke,Ae]=(0,M.useState)(null),{dir:je}=Tt(),Me=Le(),Ne=be(se),Pe=gi({middlewares:f,width:d,position:bt(je,r),offset:typeof i==`number`?i+(p?m/2:0):i,arrowRef:Ee,arrowOffset:h,onPositionChange:a,opened:o,defaultOpened:ce,onChange:re,onOpen:ne,onClose:O,onDismiss:te,strategy:ve,disabled:de,preventPositionChangeWhenVisible:Se,keepMounted:me});ir(()=>{S&&(Pe.onClose(),te?.())},ee,[De,ke],!0,E);let Fe=(0,M.useCallback)(e=>{Oe(e),Pe.floating.refs.setReference(e)},[Pe.floating.refs.setReference]),Ie=(0,M.useCallback)(e=>{Ae(e),Pe.floating.refs.setFloating(e)},[Pe.floating.refs.setFloating]),Re=(0,M.useCallback)(()=>{s?.onExited?.(),l?.(),Pe.resetLockedPlacement()},[s?.onExited,l,Pe.resetLockedPlacement]),ze=(0,M.useCallback)(()=>{s?.onEntered?.(),u?.()},[s?.onEntered,u]);return(0,N.jsxs)(ii,{value:{returnFocus:fe,disabled:de,controlled:Pe.controlled,reference:Fe,floating:Ie,x:Pe.floating.x,y:Pe.floating.y,arrowX:Pe.floating?.middlewareData?.arrow?.x,arrowY:Pe.floating?.middlewareData?.arrow?.y,opened:Pe.opened,arrowRef:Ee,transitionProps:{...s,onExited:Re,onEntered:ze},width:d,withArrow:p,arrowSize:m,arrowOffset:h,arrowRadius:g,arrowPosition:_,placement:Pe.floating.placement,trapFocus:D,withinPortal:C,portalProps:w,zIndex:k,radius:ie,shadow:oe,closeOnEscape:T,onDismiss:te,onClose:Pe.onClose,onToggle:Pe.onToggle,getTargetId:()=>Ne,getDropdownId:()=>`${Ne}-dropdown`,withRoles:ue,targetProps:Ce,__staticSelector:le,classNames:b,styles:x,unstyled:y,variant:pe,keepMounted:me,keepMountedMode:he,getStyles:we,resolvedStyles:Te,floatingStrategy:ve,referenceHidden:j&&Me!==`test`?Pe.floating.middlewareData.hide?.referenceHidden:!1},children:[n,ye&&(0,N.jsx)(ae,{transition:`fade`,mounted:Pe.opened,duration:s?.duration||250,exitDuration:s?.exitDuration||250,children:e=>(0,N.jsx)(_t,{withinPortal:C,children:(0,N.jsx)(ri,{...A,...we(`overlay`,{className:A?.className,style:[e,A?.style]})})})})]})}yi.Target=pi,yi.Dropdown=di,yi.ContextMenu=si,yi.varsResolver=vi,yi.displayName=`@mantine/core/Popover`,yi.extend=e=>e,yi.withProps=e=>{let t=t=>(0,N.jsx)(yi,{...e,...t});return t.extend=yi.extend,t.displayName=`WithProps(${yi.displayName})`,t};var bi={root:`m_8d3f4000`,icon:`m_8d3afb97`,loader:`m_302b9fb1`,group:`m_1a0f1b21`,groupSection:`m_437b6484`},xi={orientation:`horizontal`},Si=D((e,{borderWidth:t})=>({group:{"--ai-border-width":j(t)}})),Ci=w(e=>{let t=v(`ActionIconGroup`,xi,e),{className:n,style:r,classNames:i,styles:a,unstyled:o,orientation:s,vars:l,borderWidth:d,variant:f,mod:p,attributes:m,...h}=t,g=c({name:`ActionIconGroup`,props:t,classes:bi,className:n,style:r,classNames:i,styles:a,unstyled:o,attributes:m,vars:l,varsResolver:Si,rootSelector:`group`});return(0,N.jsx)(u,{...g(`group`),variant:f,mod:[{orientation:s},p],role:`group`,...h})});Ci.classes=bi,Ci.varsResolver=Si,Ci.displayName=`@mantine/core/ActionIconGroup`;var wi=D((e,{radius:t,color:n,gradient:r,variant:i,autoContrast:a,size:o})=>{let s=e.variantColorResolver({color:n||e.primaryColor,theme:e,gradient:r,variant:i||`filled`,autoContrast:a});return{groupSection:{"--section-height":ye(o,`section-height`),"--section-padding-x":ye(o,`section-padding-x`),"--section-fz":Se(o),"--section-radius":t===void 0?void 0:Oe(t),"--section-bg":n||i?s.background:void 0,"--section-color":s.color,"--section-bd":n||i?s.border:void 0}}}),Ti=w(e=>{let t=v(`ActionIconGroupSection`,null,e),{className:n,style:r,classNames:i,styles:a,unstyled:o,vars:s,variant:l,gradient:d,radius:f,autoContrast:p,attributes:m,...h}=t,g=c({name:`ActionIconGroupSection`,props:t,classes:bi,className:n,style:r,classNames:i,styles:a,unstyled:o,attributes:m,vars:s,varsResolver:wi,rootSelector:`groupSection`});return(0,N.jsx)(u,{...g(`groupSection`),variant:l,...h})});Ti.classes=bi,Ti.varsResolver=wi,Ti.displayName=`@mantine/core/ActionIconGroupSection`;var Ei=D((e,{size:t,radius:n,variant:r,gradient:i,color:a,autoContrast:o})=>{let s=e.variantColorResolver({color:a||e.primaryColor,theme:e,gradient:i,variant:r||`filled`,autoContrast:o});return{root:{"--ai-size":ye(t,`ai-size`),"--ai-radius":n===void 0?void 0:Oe(n),"--ai-bg":a||r?s.background:void 0,"--ai-hover":a||r?s.hover:void 0,"--ai-hover-color":a||r?s.hoverColor:void 0,"--ai-color":s.color,"--ai-bd":a||r?s.border:void 0}}}),Di=Pe(e=>{let t=v(`ActionIcon`,null,e),{className:n,unstyled:r,variant:i,classNames:a,styles:o,style:s,loading:l,loaderProps:d,size:f,color:p,radius:m,__staticSelector:h,gradient:g,vars:_,children:y,disabled:b,"data-disabled":x,autoContrast:S,mod:w,attributes:T,...ee}=t,E=c({name:[`ActionIcon`,h],props:t,className:n,style:s,classes:bi,classNames:a,styles:o,unstyled:r,attributes:T,vars:_,varsResolver:Ei});return(0,N.jsxs)(C,{...E(`root`,{active:!b&&!l&&!x}),"aria-busy":l||void 0,...ee,unstyled:r,variant:i,size:f,disabled:b||l,mod:[{loading:l,disabled:b||x},w],children:[typeof l==`boolean`&&(0,N.jsx)(ae,{mounted:l,transition:`slide-down`,duration:150,children:e=>(0,N.jsx)(u,{component:`span`,...E(`loader`,{style:e}),"aria-hidden":!0,children:(0,N.jsx)(Ie,{color:`var(--ai-color)`,size:`calc(var(--ai-size) * 0.55)`,...d})})}),(0,N.jsx)(u,{component:`span`,mod:{loading:l},...E(`icon`),children:y})]})});Di.classes=bi,Di.varsResolver=Ei,Di.displayName=`@mantine/core/ActionIcon`,Di.Group=Ci,Di.GroupSection=Ti;var[Oi,ki]=at(`ModalBase component was not found in tree`);function Ai({opened:e,transitionDuration:t}){let[n,r]=(0,M.useState)(e),i=(0,M.useRef)(-1),a=x()?0:t;return(0,M.useEffect)(()=>(e?(r(!0),window.clearTimeout(i.current)):a===0?r(!1):i.current=window.setTimeout(()=>r(!1),a),()=>window.clearTimeout(i.current)),[e,a]),n}function ji({id:e,transitionProps:t,opened:n,trapFocus:r,closeOnEscape:i,onClose:a,returnFocus:o,handledEscapeEvents:s}){let c=be(e),[l,u]=(0,M.useState)(!1),[d,f]=(0,M.useState)(!1),p=Ai({opened:n,transitionDuration:typeof t?.duration==`number`?t?.duration:200});return vr(`keydown`,e=>{e.key===`Escape`&&i&&!e.isComposing&&n&&!s?.has(e)&&e.target?.getAttribute(`data-mantine-stop-propagation`)!==`true`&&(s?.add(e),a())},{capture:!0}),sr({opened:n,shouldReturnFocus:r&&o}),{_id:c,titleMounted:l,bodyMounted:d,shouldLockScroll:p,setTitleMounted:u,setBodyMounted:f}}var Mi=function(){return Mi=Object.assign||function(e){for(var t,n=1,r=arguments.length;n`u`)return sa;var t=la(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},ua=oa(),da=`data-scroll-locked`,fa=function(e,t,n,r){var i=e.left,a=e.top,o=e.right,s=e.gap;return n===void 0&&(n=`margin`),` + .${Li} { + overflow: hidden ${r}; + padding-right: ${s}px ${r}; + } + body[${da}] { + overflow: hidden ${r}; + overscroll-behavior: contain; + ${[t&&`position: relative ${r};`,n===`margin`&&` + padding-left: ${i}px; + padding-top: ${a}px; + padding-right: ${o}px; + margin-left:0; + margin-top:0; + margin-right: ${s}px ${r}; + `,n===`padding`&&`padding-right: ${s}px ${r};`].filter(Boolean).join(``)} + } + + .${Fi} { + right: ${s}px ${r}; + } + + .${Ii} { + margin-right: ${s}px ${r}; + } + + .${Fi} .${Fi} { + right: 0 ${r}; + } + + .${Ii} .${Ii} { + margin-right: 0 ${r}; + } + + body[${da}] { + ${Ri}: ${s}px; + } +`},pa=function(){var e=parseInt(document.body.getAttribute(`data-scroll-locked`)||`0`,10);return isFinite(e)?e:0},ma=function(){M.useEffect(function(){return document.body.setAttribute(da,(pa()+1).toString()),function(){var e=pa()-1;e<=0?document.body.removeAttribute(da):document.body.setAttribute(da,e.toString())}},[])},ha=function(e){var t=e.noRelative,n=e.noImportant,r=e.gapMode,i=r===void 0?`margin`:r;ma();var a=M.useMemo(function(){return F(i)},[i]);return M.createElement(ua,{styles:fa(a,!t,i,n?``:`!important`)})},ga=!1;if(typeof window<`u`)try{var _a=Object.defineProperty({},"passive",{get:function(){return ga=!0,!0}});window.addEventListener(`test`,_a,_a),window.removeEventListener(`test`,_a,_a)}catch{ga=!1}var va=ga?{passive:!1}:!1,ya=function(e){return e.tagName===`TEXTAREA`},ba=function(e,t){if(!(e instanceof Element))return!1;var n=window.getComputedStyle(e);return n[t]!==`hidden`&&!(n.overflowY===n.overflowX&&!ya(e)&&n[t]===`visible`)},xa=function(e){return ba(e,`overflowY`)},Sa=function(e){return ba(e,`overflowX`)},Ca=function(e,t){var n=t.ownerDocument,r=t;do{if(typeof ShadowRoot<`u`&&r instanceof ShadowRoot&&(r=r.host),Ea(e,r)){var i=Da(e,r);if(i[1]>i[2])return!0}r=r.parentNode}while(r&&r!==n.body);return!1},wa=function(e){return[e.scrollTop,e.scrollHeight,e.clientHeight]},Ta=function(e){return[e.scrollLeft,e.scrollWidth,e.clientWidth]},Ea=function(e,t){return e===`v`?xa(t):Sa(t)},Da=function(e,t){return e===`v`?wa(t):Ta(t)},Oa=function(e,t){return e===`h`&&t===`rtl`?-1:1},ka=function(e,t,n,r,i){var a=Oa(e,window.getComputedStyle(t).direction),o=a*r,s=n.target,c=t.contains(s),l=!1,u=o>0,d=0,f=0;do{if(!s)break;var p=Da(e,s),m=p[0],h=p[1]-p[2]-a*m;(m||h)&&Ea(e,s)&&(d+=h,f+=m);var g=s.parentNode;s=g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE?g.host:g}while(!c&&s!==document.body||c&&(t.contains(s)||t===s));return(u&&(i&&Math.abs(d)<1||!i&&o>d)||!u&&(i&&Math.abs(f)<1||!i&&-o>f))&&(l=!0),l},Aa=function(e){return`changedTouches`in e?[e.changedTouches[0].clientX,e.changedTouches[0].clientY]:[0,0]},ja=function(e){return[e.deltaX,e.deltaY]},Ma=function(e){return e&&`current`in e?e.current:e},Na=function(e,t){return e[0]===t[0]&&e[1]===t[1]},Pa=function(e){return` + .block-interactivity-${e} {pointer-events: none;} + .allow-interactivity-${e} {pointer-events: all;} +`},Fa=0,Ia=[];function La(e){var t=M.useRef([]),n=M.useRef([0,0]),r=M.useRef(),i=M.useState(Fa++)[0],a=M.useState(oa)[0],o=M.useRef(e);M.useEffect(function(){o.current=e},[e]),M.useEffect(function(){if(e.inert){document.body.classList.add(`block-interactivity-${i}`);var t=Pi([e.lockRef.current],(e.shards||[]).map(Ma),!0).filter(Boolean);return t.forEach(function(e){return e.classList.add(`allow-interactivity-${i}`)}),function(){document.body.classList.remove(`block-interactivity-${i}`),t.forEach(function(e){return e.classList.remove(`allow-interactivity-${i}`)})}}},[e.inert,e.lockRef.current,e.shards]);var s=M.useCallback(function(e,t){if(`touches`in e&&e.touches.length===2||e.type===`wheel`&&e.ctrlKey)return!o.current.allowPinchZoom;var i=Aa(e),a=n.current,s=`deltaX`in e?e.deltaX:a[0]-i[0],c=`deltaY`in e?e.deltaY:a[1]-i[1],l,u=e.target,d=Math.abs(s)>Math.abs(c)?`h`:`v`;if(`touches`in e&&d===`h`&&u.type===`range`)return!1;var f=window.getSelection(),p=f&&f.anchorNode;if(p&&(p===u||p.contains(u)))return!1;var m=Ca(d,u);if(!m)return!0;if(m?l=d:(l=d===`v`?`h`:`v`,m=Ca(d,u)),!m)return!1;if(!r.current&&`changedTouches`in e&&(s||c)&&(r.current=l),!l)return!0;var h=r.current||l;return ka(h,t,e,h===`h`?s:c,!0)},[]),c=M.useCallback(function(e){var n=e;if(Ia.length&&Ia[Ia.length-1]===a){var r=`deltaY`in n?ja(n):Aa(n),i=t.current.filter(function(e){return e.name===n.type&&(e.target===n.target||n.target===e.shadowParent)&&Na(e.delta,r)})[0];if(i&&i.should){n.cancelable&&n.preventDefault();return}if(!i){var c=(o.current.shards||[]).map(Ma).filter(Boolean).filter(function(e){return e.contains(n.target)});(c.length>0?s(n,c[0]):!o.current.noIsolation)&&n.cancelable&&n.preventDefault()}}},[]),l=M.useCallback(function(e,n,r,i){var a={name:e,delta:n,target:r,should:i,shadowParent:Ra(r)};t.current.push(a),setTimeout(function(){t.current=t.current.filter(function(e){return e!==a})},1)},[]),u=M.useCallback(function(e){n.current=Aa(e),r.current=void 0},[]),d=M.useCallback(function(t){l(t.type,ja(t),t.target,s(t,e.lockRef.current))},[]),f=M.useCallback(function(t){l(t.type,Aa(t),t.target,s(t,e.lockRef.current))},[]);M.useEffect(function(){return Ia.push(a),e.setCallbacks({onScrollCapture:d,onWheelCapture:d,onTouchMoveCapture:f}),document.addEventListener(`wheel`,c,va),document.addEventListener(`touchmove`,c,va),document.addEventListener(`touchstart`,u,va),function(){Ia=Ia.filter(function(e){return e!==a}),document.removeEventListener(`wheel`,c,va),document.removeEventListener(`touchmove`,c,va),document.removeEventListener(`touchstart`,u,va)}},[]);var p=e.removeScrollBar,m=e.inert;return M.createElement(M.Fragment,null,m?M.createElement(a,{styles:Pa(i)}):null,p?M.createElement(ha,{noRelative:e.noRelative,gapMode:e.gapMode}):null)}function Ra(e){for(var t=null;e!==null;)e instanceof ShadowRoot&&(t=e.host,e=e.host),e=e.parentNode;return t}var za=Xi(Zi,La),Ba=M.forwardRef(function(e,t){return M.createElement($i,Mi({},e,{ref:t,sideCar:za}))});Ba.classNames=$i.classNames;function Va({keepMounted:e,keepMountedMode:t=`activity`,opened:n,onClose:r,id:i,transitionProps:a,onExitTransitionEnd:o,onEnterTransitionEnd:s,trapFocus:c,closeOnEscape:l,returnFocus:d,closeOnClickOutside:f,withinPortal:p,portalProps:m,lockScroll:h,children:g,zIndex:_,shadow:v,padding:y,__vars:b,unstyled:x,removeScrollProps:S,__handledEscapeEvents:C,...w}){let{_id:T,titleMounted:ee,bodyMounted:E,shouldLockScroll:D,setTitleMounted:O,setBodyMounted:te}=ji({id:i,transitionProps:a,opened:n,trapFocus:c,closeOnEscape:l,onClose:r,returnFocus:d,handledEscapeEvents:C}),{key:ne,...re}=S||{};return(0,N.jsx)(_t,{...m,withinPortal:p,children:(0,N.jsx)(Oi,{value:{opened:n,onClose:r,closeOnClickOutside:f,onExitTransitionEnd:o,onEnterTransitionEnd:s,transitionProps:{...a,keepMounted:e,keepMountedMode:t},getTitleId:()=>`${T}-title`,getBodyId:()=>`${T}-body`,titleMounted:ee,bodyMounted:E,setTitleMounted:O,setBodyMounted:te,trapFocus:c,closeOnEscape:l,zIndex:_,unstyled:x},children:(0,N.jsx)(Ba,{enabled:D&&h,...re,children:(0,N.jsx)(u,{...w,id:T,__vars:{...b,"--mb-z-index":(_||ot(`modal`)).toString(),"--mb-shadow":se(v),"--mb-padding":Me(y)},children:g})},ne)})})}Va.displayName=`@mantine/core/ModalBase`;function Ha(){let e=ki();return(0,M.useEffect)(()=>(e.setBodyMounted(!0),()=>e.setBodyMounted(!1)),[]),e.getBodyId()}var Ua={title:`m_615af6c9`,header:`m_b5489c3c`,inner:`m_60c222c7`,content:`m_fd1ab0aa`,close:`m_606cb269`,body:`m_5df29311`};function Wa({className:e,...t}){let n=Ha(),r=ki();return(0,N.jsx)(u,{id:n,className:O({[Ua.body]:!r.unstyled},e),...t})}Wa.displayName=`@mantine/core/ModalBaseBody`;function Ga({className:e,onClick:t,...n}){let r=ki();return(0,N.jsx)(Ne,{...n,onClick:e=>{r.onClose(),t?.(e)},className:O({[Ua.close]:!r.unstyled},e),unstyled:r.unstyled})}Ga.displayName=`@mantine/core/ModalBaseCloseButton`;function Ka({transitionProps:e,className:t,innerProps:n,onKeyDown:r,style:i,ref:a,...o}){let s=ki();return(0,N.jsx)(ae,{mounted:s.opened,transition:`pop`,...s.transitionProps,onExited:()=>{s.onExitTransitionEnd?.(),s.transitionProps?.onExited?.()},onEntered:()=>{s.onEnterTransitionEnd?.(),s.transitionProps?.onEntered?.()},...e,children:e=>(0,N.jsx)(`div`,{...n,className:O({[Ua.inner]:!s.unstyled},n.className),children:(0,N.jsx)(ci,{active:s.opened&&s.trapFocus,innerRef:a,children:(0,N.jsx)(Fe,{...o,component:`section`,role:`dialog`,tabIndex:-1,"aria-modal":!0,"aria-describedby":s.bodyMounted?s.getBodyId():void 0,"aria-labelledby":s.titleMounted?s.getTitleId():void 0,style:[i,e],className:O({[Ua.content]:!s.unstyled},t),unstyled:s.unstyled,children:o.children})})})})}Ka.displayName=`@mantine/core/ModalBaseContent`;function qa({className:e,...t}){let n=ki();return(0,N.jsx)(u,{component:`header`,className:O({[Ua.header]:!n.unstyled},e),...t})}qa.displayName=`@mantine/core/ModalBaseHeader`;var Ja={duration:200,timingFunction:`ease`,transition:`fade`};function Ya(e){let t=ki();return{...Ja,...t.transitionProps,...e}}function Xa({onClick:e,transitionProps:t,style:n,visible:r,...i}){let a=ki(),o=Ya(t);return(0,N.jsx)(ae,{mounted:r===void 0?a.opened:r,...o,transition:`fade`,children:t=>(0,N.jsx)(ri,{fixed:!0,style:[n,t],zIndex:a.zIndex,unstyled:a.unstyled,onClick:t=>{e?.(t),a.closeOnClickOutside&&a.onClose()},...i})})}Xa.displayName=`@mantine/core/ModalBaseOverlay`;function Za(){let e=ki();return(0,M.useEffect)(()=>(e.setTitleMounted(!0),()=>e.setTitleMounted(!1)),[]),e.getTitleId()}function Qa({className:e,...t}){let n=Za(),r=ki();return(0,N.jsx)(u,{component:`h2`,className:O({[Ua.title]:!r.unstyled},e),id:n,...t})}Qa.displayName=`@mantine/core/ModalBaseTitle`;function $a({children:e}){return(0,N.jsx)(N.Fragment,{children:e})}function eo({style:e,size:t=16,...n}){return(0,N.jsx)(`svg`,{viewBox:`0 0 15 15`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,style:{...e,width:j(t),height:j(t),display:`block`},...n,children:(0,N.jsx)(`path`,{d:`M3.13523 6.15803C3.3241 5.95657 3.64052 5.94637 3.84197 6.13523L7.5 9.56464L11.158 6.13523C11.3595 5.94637 11.6759 5.95657 11.8648 6.15803C12.0536 6.35949 12.0434 6.67591 11.842 6.86477L7.84197 10.6148C7.64964 10.7951 7.35036 10.7951 7.15803 10.6148L3.15803 6.86477C2.95657 6.67591 2.94637 6.35949 3.13523 6.15803Z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})}eo.displayName=`@mantine/core/AccordionChevron`;var[to,no]=at(`AppShell was not found in tree`);function ro({size:e,min:t,max:n,viewportMax:r}){let i=Math.min(n??1/0,r);return Math.max(Math.min(t??0,i),Math.min(e,i))}function io(e,t){return t!==void 0&&ef.axis===`horizontal`?window.innerWidth:window.innerHeight,[h,g]=(0,M.useState)(0),[_,v]=(0,M.useState)(void 0),y=()=>m()/d.scale,x=e=>{let t=e.getBoundingClientRect();return((f.axis===`horizontal`?t.width:t.height)-co(e,f.safeAreaVariable))/d.scale},S=t=>{let r=n.rootRef.current;if(!r)return;let i=j(t);r.style.setProperty(f.sizeVariable,i),n.resizeOffsets[e]&&r.style.setProperty(f.offsetVariable,i),n.mode===`static`&&f.gridWidthVariable&&r.style.setProperty(f.gridWidthVariable,i)},C=()=>{let e=n.rootRef.current;e&&(e.style.removeProperty(f.sizeVariable),e.style.removeProperty(f.offsetVariable),f.gridWidthVariable&&e.style.removeProperty(f.gridWidthVariable))},w=()=>{s.current?.abort(),s.current=null,o.current=null;let e=c.current;c.current=null,e&&(mo(`user-select`,e.userSelect),mo(`-webkit-user-select`,e.webkitUserSelect),mo(`cursor`,e.cursor))},T=()=>{r?.reportCollapse(e,io(a.current.startSize,p.collapseThreshold)),r?.endResize(e,null)},ee=t=>{if(t.pointerId!==o.current)return;a.current.moved=!0;let n=so({section:e,deltaX:t.clientX-a.current.startX,deltaY:t.clientY-a.current.startY,dir:l})/d.scale,s=a.current.startSize+n,c=ro({size:s,min:p.min,max:p.max,viewportMax:y()});a.current.size=c,S(c),i.current?.setAttribute(`aria-valuenow`,String(Math.round(c))),r?.previewResize(e,c),r?.reportCollapse(e,io(s,p.collapseThreshold))},E=t=>{if(t.pointerId===o.current){if(w(),!a.current.moved){r?.endResize(e,null);return}r?.endResize(e,a.current.size)}},D=e=>{e.pointerId===o.current&&(w(),C(),T())},O=e=>{e.key===`Escape`&&(e.preventDefault(),w(),C(),i.current?.setAttribute(`aria-valuenow`,String(Math.round(a.current.startSize))),T())},te=()=>{let t=r?.[e].size;if(t!==void 0)return t;let n=i.current?.parentElement;return n?x(n):0},ne=t=>{r?.initCollapse(e,io(te(),p.collapseThreshold)),r?.reportCollapse(e,io(t,p.collapseThreshold)),r?.endResize(e,ro({size:t,min:p.min,max:p.max,viewportMax:y()}))},re=t=>{let n=t.shiftKey?fo:uo;if(t.key===`Home`){t.preventDefault(),ne(p.min??0);return}if(t.key===`End`){t.preventDefault(),ne(p.max??y());return}let r=po[t.key];if(!r)return;let i=so({section:e,...r,dir:l});i!==0&&(t.preventDefault(),ne(te()+i*n))},k=()=>{C(),r?.[e].reset()},ie=t=>{if(t.button!==0||s.current!==null)return;let n=i.current?.parentElement;if(!n)return;let l=x(n);a.current={startSize:l,startX:t.clientX,startY:t.clientY,size:l,moved:!1},o.current=t.pointerId,r?.initCollapse(e,io(l,p.collapseThreshold));let u=new AbortController;s.current=u;let{signal:d}=u;c.current={userSelect:document.body.style.getPropertyValue(`user-select`),webkitUserSelect:document.body.style.getPropertyValue(`-webkit-user-select`),cursor:document.body.style.getPropertyValue(`cursor`)},document.body.style.setProperty(`user-select`,`none`),document.body.style.setProperty(`-webkit-user-select`,`none`),document.body.style.setProperty(`cursor`,f.axis===`horizontal`?`col-resize`:`row-resize`),r?.startResize(e),document.addEventListener(`pointermove`,ee,{signal:d}),document.addEventListener(`pointerup`,E,{signal:d}),document.addEventListener(`pointercancel`,D,{signal:d}),document.addEventListener(`keydown`,O,{signal:d})};if(he(()=>{r&&r.activeSection!==e&&C()},[r?.activeSection,r?.[e].size]),he(()=>{g(m());let e=()=>g(m());return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[f.axis]),he(()=>{r?.[e].size===void 0&&v(te())},[r?.[e].size,h]),he(()=>()=>{let e=s.current!==null;w(),C(),e&&T()},[]),!r?.[e].enabled)return null;let ae=h/d.scale,oe=Math.min(p.max??ae,ae),se=r[e].size,ce=se!==void 0&&h>0?Math.min(se,ae):se??_;return(0,N.jsx)(u,{ref:i,role:`separator`,tabIndex:0,"aria-label":p.label??lo[e],"aria-controls":t,"aria-orientation":f.orientation,"aria-valuemin":p.min??0,"aria-valuemax":Math.round(oe),"aria-valuenow":ce===void 0?void 0:Math.round(ce),onPointerDown:ie,onKeyDown:re,onDoubleClick:k,mod:{section:e,orientation:f.orientation,active:r[e].active},...n.getStyles(`resizeHandle`)})}ho.displayName=`@mantine/core/AppShellResizeHandle`;var go={root:`m_89ab340`,navbar:`m_45252eee`,aside:`m_9cdde9a`,header:`m_3b16f56b`,main:`m_8983817`,footer:`m_3840c879`,section:`m_6dcfc7c7`,resizeHandle:`m_3b25945a`},_o=w(e=>{let{classNames:t,className:n,style:r,styles:i,unstyled:a,vars:o,withBorder:s,zIndex:c,mod:l,...d}=v(`AppShellAside`,null,e),f=no(),p=be(d.id);if(f.disabled)return null;let m=f.resize?.aside.enabled??!1,h=f.getStyles(`aside`,{className:O({[Ba.classNames.zeroRight]:f.offsetScrollbars},n),classNames:t,styles:i,style:r});if(!m)return(0,N.jsx)(u,{component:`aside`,mod:[{"with-border":s??f.withBorder},l],...h,...d,__vars:{"--app-shell-aside-z-index":`calc(${c??f.zIndex} + 1)`}});let{children:g,dangerouslySetInnerHTML:_,...y}=d;return(0,N.jsxs)(u,{component:`aside`,mod:[{"with-border":s??f.withBorder},l],...h,...y,__vars:{"--app-shell-aside-z-index":`calc(${c??f.zIndex} + 1)`},id:p,children:[_?(0,N.jsx)(`div`,{style:{display:`contents`},dangerouslySetInnerHTML:_}):g,(0,N.jsx)(ho,{section:`aside`,sectionId:p})]})});_o.classes=go,_o.displayName=`@mantine/core/AppShellAside`;var vo=w(e=>{let{classNames:t,className:n,style:r,styles:i,unstyled:a,vars:o,withBorder:s,zIndex:c,mod:l,...d}=v(`AppShellFooter`,null,e),f=no(),p=be(d.id);if(f.disabled)return null;let m=f.resize?.footer.enabled??!1,h=f.getStyles(`footer`,{className:O({[Ba.classNames.zeroRight]:f.offsetScrollbars},n),classNames:t,styles:i,style:r});if(!m)return(0,N.jsx)(u,{component:`footer`,mod:[{"with-border":s??f.withBorder},l],...h,...d,__vars:{"--app-shell-footer-z-index":(c??f.zIndex)?.toString()}});let{children:g,dangerouslySetInnerHTML:_,...y}=d;return(0,N.jsxs)(u,{component:`footer`,mod:[{"with-border":s??f.withBorder},l],...h,...y,__vars:{"--app-shell-footer-z-index":(c??f.zIndex)?.toString()},id:p,children:[_?(0,N.jsx)(`div`,{style:{display:`contents`},dangerouslySetInnerHTML:_}):g,(0,N.jsx)(ho,{section:`footer`,sectionId:p})]})});vo.classes=go,vo.displayName=`@mantine/core/AppShellFooter`;var yo=w(e=>{let{classNames:t,className:n,style:r,styles:i,unstyled:a,vars:o,withBorder:s,zIndex:c,mod:l,...d}=v(`AppShellHeader`,null,e),f=no(),p=be(d.id);if(f.disabled)return null;let m=f.resize?.header.enabled??!1,h=f.getStyles(`header`,{className:O({[Ba.classNames.zeroRight]:f.offsetScrollbars},n),classNames:t,styles:i,style:r});if(!m)return(0,N.jsx)(u,{component:`header`,mod:[{"with-border":s??f.withBorder},l],...h,...d,__vars:{"--app-shell-header-z-index":(c??f.zIndex)?.toString()}});let{children:g,dangerouslySetInnerHTML:_,...y}=d;return(0,N.jsxs)(u,{component:`header`,mod:[{"with-border":s??f.withBorder},l],...h,...y,__vars:{"--app-shell-header-z-index":(c??f.zIndex)?.toString()},id:p,children:[_?(0,N.jsx)(`div`,{style:{display:`contents`},dangerouslySetInnerHTML:_}):g,(0,N.jsx)(ho,{section:`header`,sectionId:p})]})});yo.classes=go,yo.displayName=`@mantine/core/AppShellHeader`;var bo=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`AppShellMain`,null,e),s=no();return(0,N.jsx)(u,{component:`main`,...s.getStyles(`main`,{className:n,style:r,classNames:t,styles:i}),...o})});bo.classes=go,bo.displayName=`@mantine/core/AppShellMain`;var xo=w(e=>{let{classNames:t,className:n,style:r,styles:i,unstyled:a,vars:o,withBorder:s,zIndex:c,mod:l,...d}=v(`AppShellNavbar`,null,e),f=no(),p=be(d.id);if(f.disabled)return null;let m=f.resize?.navbar.enabled??!1,h=f.getStyles(`navbar`,{className:n,classNames:t,styles:i,style:r});if(!m)return(0,N.jsx)(u,{component:`nav`,mod:[{"with-border":s??f.withBorder},l],...h,...d,__vars:{"--app-shell-navbar-z-index":`calc(${c??f.zIndex} + 1)`}});let{children:g,dangerouslySetInnerHTML:_,...y}=d;return(0,N.jsxs)(u,{component:`nav`,mod:[{"with-border":s??f.withBorder},l],...h,...y,__vars:{"--app-shell-navbar-z-index":`calc(${c??f.zIndex} + 1)`},id:p,children:[_?(0,N.jsx)(`div`,{style:{display:`contents`},dangerouslySetInnerHTML:_}):g,(0,N.jsx)(ho,{section:`navbar`,sectionId:p})]})});xo.classes=go,xo.displayName=`@mantine/core/AppShellNavbar`;var So=Pe(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,grow:o,mod:s,...c}=v(`AppShellSection`,null,e),l=no();return(0,N.jsx)(u,{mod:[{grow:o},s],...l.getStyles(`section`,{className:n,style:r,classNames:t,styles:i}),...c})});So.classes=go,So.displayName=`@mantine/core/AppShellSection`;function Co(e){return typeof e==`object`?e.base:e}function wo(e,t){return`min(${j(e)}, ${t===`horizontal`?`100vw`:`100dvh`})`}function To(e){let t=typeof e==`object`&&!!e&&e.base!==void 0&&Object.keys(e).length===1;return typeof e==`number`||typeof e==`string`||t}function Eo(e){return!(typeof e!=`object`||!e||Object.keys(e).length===1&&`base`in e)}function Do({baseStyles:e,minMediaStyles:t,maxMediaStyles:n,aside:r,theme:i,mode:a,resizedSize:o,resizable:s}){let c=r?.width,l=`translateX(var(--app-shell-aside-width))`,u=`translateX(calc(var(--app-shell-aside-width) * -1))`;if(r?.breakpoint!==void 0&&!r?.collapsed?.mobile&&(n[r?.breakpoint]=n[r?.breakpoint]||{},a===`fixed`?(n[r?.breakpoint][`--app-shell-aside-width`]=`100%`,n[r?.breakpoint][`--app-shell-aside-offset`]=`0px`):(n[r?.breakpoint][`--app-shell-aside-width`]=`0px`,n[r?.breakpoint][`--app-shell-aside-offset`]=`0px`),s&&(n[r.breakpoint][`--app-shell-aside-resize-handle-display`]=`none`)),o!==void 0){let t=wo(o,`horizontal`);e[`--app-shell-aside-width`]=t,e[`--app-shell-aside-offset`]=t,a===`static`&&(e[`--app-shell-aside-grid-width`]=t)}else{if(To(c)){let t=j(Co(c));e[`--app-shell-aside-width`]=t,e[`--app-shell-aside-offset`]=t}Eo(c)&&(c.base!==void 0&&(e[`--app-shell-aside-width`]=j(c.base),e[`--app-shell-aside-offset`]=j(c.base)),de(c).forEach(e=>{e!==`base`&&(t[e]=t[e]||{},t[e][`--app-shell-aside-width`]=j(c[e]),t[e][`--app-shell-aside-offset`]=j(c[e]))}))}if(r?.breakpoint!==void 0&&a===`static`&&(t[r.breakpoint]=t[r.breakpoint]||{},t[r.breakpoint][`--app-shell-aside-position`]=`sticky`,t[r.breakpoint][`--app-shell-aside-grid-row`]=`2`,t[r.breakpoint][`--app-shell-aside-grid-column`]=`3`,t[r.breakpoint][`--app-shell-main-column-end`]=`3`),r?.collapsed?.desktop){let e=r.breakpoint;t[e]=t[e]||{},t[e][`--app-shell-aside-transform`]=l,t[e][`--app-shell-aside-transform-rtl`]=u,a===`fixed`?t[e][`--app-shell-aside-offset`]=`0px !important`:(t[e][`--app-shell-aside-width`]=`0px`,t[e][`--app-shell-aside-display`]=`none`,t[e][`--app-shell-main-column-end`]=`-1`),t[e][`--app-shell-aside-scroll-locked-visibility`]=`hidden`,s&&(t[e][`--app-shell-aside-resize-handle-display`]=`none`)}if(r?.collapsed?.mobile){let e=er(r.breakpoint,i.breakpoints)-.1;n[e]=n[e]||{},a===`fixed`?(n[e][`--app-shell-aside-width`]=`100%`,n[e][`--app-shell-aside-offset`]=`0px`):n[e][`--app-shell-aside-width`]=`0px`,n[e][`--app-shell-aside-transform`]=l,n[e][`--app-shell-aside-transform-rtl`]=u,n[e][`--app-shell-aside-scroll-locked-visibility`]=`hidden`,s&&(n[e][`--app-shell-aside-resize-handle-display`]=`none`)}}function Oo({baseStyles:e,minMediaStyles:t,footer:n,mode:r,resizedSize:i,resizable:a}){let o=n?.height,s=r===`static`?!0:n?.offset??!0;if(r===`static`&&n&&(e[`--app-shell-footer-position`]=`sticky`,e[`--app-shell-footer-grid-column`]=`1 / -1`,e[`--app-shell-footer-grid-row`]=`3`),i!==void 0){let t=wo(i,`vertical`);e[`--app-shell-footer-height`]=t,s&&(e[`--app-shell-footer-offset`]=t)}else{if(To(o)){let t=j(Co(o));e[`--app-shell-footer-height`]=t,s&&(e[`--app-shell-footer-offset`]=t)}Eo(o)&&(o.base!==void 0&&(e[`--app-shell-footer-height`]=j(o.base),s&&(e[`--app-shell-footer-offset`]=j(o.base))),de(o).forEach(e=>{e!==`base`&&(t[e]=t[e]||{},t[e][`--app-shell-footer-height`]=j(o[e]),s&&(t[e][`--app-shell-footer-offset`]=j(o[e])))}))}n?.collapsed&&(e[`--app-shell-footer-transform`]=`translateY(var(--app-shell-footer-height))`,r===`fixed`&&(e[`--app-shell-footer-offset`]=`0px !important`),a&&(e[`--app-shell-footer-resize-handle-display`]=`none`))}function ko({baseStyles:e,minMediaStyles:t,header:n,mode:r,resizedSize:i,resizable:a}){let o=n?.height,s=r===`static`?!0:n?.offset??!0;if(r===`static`&&n&&(e[`--app-shell-header-position`]=`sticky`,e[`--app-shell-header-grid-column`]=`1 / -1`,e[`--app-shell-header-grid-row`]=`1`),i!==void 0){let t=wo(i,`vertical`);e[`--app-shell-header-height`]=t,s&&(e[`--app-shell-header-offset`]=t)}else{if(To(o)){let t=j(Co(o));e[`--app-shell-header-height`]=t,s&&(e[`--app-shell-header-offset`]=t)}Eo(o)&&(o.base!==void 0&&(e[`--app-shell-header-height`]=j(o.base),s&&(e[`--app-shell-header-offset`]=j(o.base))),de(o).forEach(e=>{e!==`base`&&(t[e]=t[e]||{},t[e][`--app-shell-header-height`]=j(o[e]),s&&(t[e][`--app-shell-header-offset`]=j(o[e])))}))}n?.collapsed&&(e[`--app-shell-header-transform`]=`translateY(calc(var(--app-shell-header-height) * -1))`,r===`fixed`&&(e[`--app-shell-header-offset`]=`0px !important`),a&&(e[`--app-shell-header-resize-handle-display`]=`none`))}function Ao({baseStyles:e,minMediaStyles:t,maxMediaStyles:n,navbar:r,theme:i,mode:a,resizedSize:o,resizable:s}){let c=r?.width,l=`translateX(calc(var(--app-shell-navbar-width) * -1))`,u=`translateX(var(--app-shell-navbar-width))`;if(r?.breakpoint!==void 0&&!r?.collapsed?.mobile&&(n[r?.breakpoint]=n[r?.breakpoint]||{},n[r?.breakpoint][`--app-shell-navbar-offset`]=`0px`,n[r?.breakpoint][`--app-shell-navbar-width`]=`100%`,a===`static`&&(n[r?.breakpoint][`--app-shell-navbar-grid-width`]=`0px`),s&&(n[r.breakpoint][`--app-shell-navbar-resize-handle-display`]=`none`)),o!==void 0){let t=wo(o,`horizontal`);e[`--app-shell-navbar-width`]=t,e[`--app-shell-navbar-offset`]=t,a===`static`&&(e[`--app-shell-navbar-grid-width`]=t)}else{if(To(c)){let t=j(Co(c));e[`--app-shell-navbar-width`]=t,e[`--app-shell-navbar-offset`]=t,a===`static`&&(e[`--app-shell-navbar-grid-width`]=t)}Eo(c)&&(c.base!==void 0&&(e[`--app-shell-navbar-width`]=j(c.base),e[`--app-shell-navbar-offset`]=j(c.base),a===`static`&&(e[`--app-shell-navbar-grid-width`]=j(c.base))),de(c).forEach(e=>{e!==`base`&&(t[e]=t[e]||{},t[e][`--app-shell-navbar-width`]=j(c[e]),t[e][`--app-shell-navbar-offset`]=j(c[e]),a===`static`&&(t[e][`--app-shell-navbar-grid-width`]=j(c[e])))}))}if(r?.breakpoint!==void 0&&a===`static`&&(t[r.breakpoint]=t[r.breakpoint]||{},t[r.breakpoint][`--app-shell-navbar-position`]=`sticky`,t[r.breakpoint][`--app-shell-navbar-grid-row`]=`2`,t[r.breakpoint][`--app-shell-navbar-grid-column`]=`1`,t[r.breakpoint][`--app-shell-main-column-start`]=`2`),r?.collapsed?.desktop){let e=r.breakpoint;t[e]=t[e]||{},t[e][`--app-shell-navbar-transform`]=l,t[e][`--app-shell-navbar-transform-rtl`]=u,a===`fixed`?t[e][`--app-shell-navbar-offset`]=`0px !important`:(t[e][`--app-shell-navbar-width`]=`0px`,t[e][`--app-shell-navbar-display`]=`none`,t[e][`--app-shell-main-column-start`]=`1`),s&&(t[e][`--app-shell-navbar-resize-handle-display`]=`none`)}if(r?.collapsed?.mobile){let e=er(r.breakpoint,i.breakpoints)-.1;n[e]=n[e]||{},n[e][`--app-shell-navbar-width`]=`100%`,n[e][`--app-shell-navbar-offset`]=`0px`,a===`static`&&(n[e][`--app-shell-navbar-grid-width`]=`0px`),n[e][`--app-shell-navbar-transform`]=l,n[e][`--app-shell-navbar-transform-rtl`]=u,s&&(n[e][`--app-shell-navbar-resize-handle-display`]=`none`)}}function jo(e){return Number(e)===0?`0px`:Me(e)}function Mo({padding:e,baseStyles:t,minMediaStyles:n}){To(e)&&(t[`--app-shell-padding`]=jo(Co(e))),Eo(e)&&(e.base&&(t[`--app-shell-padding`]=jo(e.base)),de(e).forEach(t=>{t!==`base`&&(n[t]=n[t]||{},n[t][`--app-shell-padding`]=jo(e[t]))}))}function No({navbar:e,header:t,footer:n,aside:r,padding:i,theme:a,mode:o,resize:s}){let c={},l={},u={};o===`static`&&(u[`--app-shell-main-grid-column`]=`1 / -1`,u[`--app-shell-main-grid-row`]=`2`),Ao({baseStyles:u,minMediaStyles:c,maxMediaStyles:l,navbar:e,theme:a,mode:o,resizedSize:s?.sizes.navbar,resizable:s?.enabled.navbar}),Do({baseStyles:u,minMediaStyles:c,maxMediaStyles:l,aside:r,theme:a,mode:o,resizedSize:s?.sizes.aside,resizable:s?.enabled.aside}),ko({baseStyles:u,minMediaStyles:c,header:t,mode:o,resizedSize:s?.sizes.header,resizable:s?.enabled.header}),Oo({baseStyles:u,minMediaStyles:c,footer:n,mode:o,resizedSize:s?.sizes.footer,resizable:s?.enabled.footer}),Mo({baseStyles:u,minMediaStyles:c,padding:i});let d=tr(de(c),a.breakpoints).map(e=>({query:`(min-width: ${we(e.px)})`,styles:c[e.value]})),f=tr(de(l),a.breakpoints).map(e=>({query:`(max-width: ${we(e.px)})`,styles:l[e.value]}));return{baseStyles:u,media:[...d,...f]}}function Po({navbar:e,header:t,aside:n,footer:r,padding:i,mode:a,selector:o,resize:s}){let c=b(),l=_(),{media:u,baseStyles:d}=No({navbar:e,header:t,footer:r,aside:n,padding:i,theme:c,mode:a,resize:s});return(0,N.jsx)(_e,{media:u,styles:d,selector:o||l.cssVariablesSelector})}function Fo(e){return e>=128||e===45||e===95||e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122}function Io(e){return e>=48&&e<=57}function Lo(e){let t=``;for(let n=0;n=1&&r<=31||r===127||n===0&&Io(r)||n===1&&Io(r)&&e.charCodeAt(0)===45?t+=`\\${r.toString(16)} `:n===0&&e.length===1&&r===45?t+=`\\${i}`:Fo(r)?t+=i:t+=`\\${i}`}return t}function Ro({transitionDuration:e,disabled:t,resizeKey:n}){let[r,i]=(0,M.useState)(!0),[a,o]=(0,M.useState)({key:n,active:!1}),s=(0,M.useRef)(-1),c=(0,M.useRef)(-1);return a.key!==n&&o({key:n,active:!0}),(0,M.useEffect)(()=>{if(!a.active)return;let t=window.setTimeout(()=>(0,M.startTransition)(()=>{o(e=>({...e,active:!1}))}),e||0);return()=>window.clearTimeout(t)},[a,e]),vr(`resize`,()=>{i(!0),clearTimeout(s.current),s.current=window.setTimeout(()=>(0,M.startTransition)(()=>{i(!1)}),200)}),he(()=>{i(!0),clearTimeout(c.current),c.current=window.setTimeout(()=>(0,M.startTransition)(()=>{i(!1)}),e||0)},[t,e]),r||a.active}var zo={withBorder:!0,padding:0,transitionDuration:200,transitionTimingFunction:`ease`,zIndex:ot(`app`),mode:`fixed`},Bo=D((e,{transitionDuration:t,transitionTimingFunction:n})=>({root:{"--app-shell-transition-duration":`${t}ms`,"--app-shell-transition-timing-function":n,"--app-shell-resize-handle-size":void 0}})),Vo=w(e=>{let t=v(`AppShell`,zo,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,navbar:l,withBorder:d,padding:f,transitionDuration:p,transitionTimingFunction:m,header:h,zIndex:g,layout:_,disabled:y,aside:b,footer:x,offsetScrollbars:S=!0,mode:C,mod:w,attributes:T,id:ee,resize:E,ref:D,...O}=t,te=c({name:`AppShell`,classes:go,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:T,vars:s,varsResolver:Bo}),ne=Ro({disabled:y,transitionDuration:p,resizeKey:E?oo.map(e=>E.sizes[e]).join(`|`):void 0}),re=be(ee),k=(0,M.useRef)(null),ie=E?{sizes:E.sizes,enabled:{navbar:E.navbar.enabled,aside:E.aside.enabled,header:E.header.enabled,footer:E.footer.enabled}}:void 0,ae={navbar:!0,aside:!0,header:C===`static`?!0:h?.offset??!0,footer:C===`static`?!0:x?.offset??!0};return(0,N.jsxs)(to,{value:{getStyles:te,withBorder:d,zIndex:g,disabled:y,offsetScrollbars:S,mode:C,resize:E,rootRef:k,resizeOffsets:ae},children:[(0,N.jsx)(Po,{navbar:l,header:h,aside:b,footer:x,padding:f,mode:C,resize:ie,selector:E||C===`static`?`#${Lo(re)}`:void 0}),(0,N.jsx)(u,{...te(`root`),id:re,ref:Ae(D,k),mod:[{resizing:ne||E?.activeSection!=null,layout:_,disabled:y,mode:C},w],...O})]})});Vo.classes=go,Vo.varsResolver=Bo,Vo.displayName=`@mantine/core/AppShell`,Vo.Navbar=xo,Vo.Header=yo,Vo.Main=bo,Vo.Aside=_o,Vo.Footer=vo,Vo.Section=So;function Ho({size:e,style:t,...n}){let r=e===void 0?t:{width:j(e),height:j(e),...t};return(0,N.jsx)(`svg`,{viewBox:`0 0 10 7`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,style:r,"aria-hidden":!0,...n,children:(0,N.jsx)(`path`,{d:`M4 4.586L1.707 2.293A1 1 0 1 0 .293 3.707l3 3a.997.997 0 0 0 1.414 0l5-5A1 1 0 1 0 8.293.293L4 4.586z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})}var Uo={group:`m_11def92b`,root:`m_f85678b6`,image:`m_11f8ac07`,placeholder:`m_104cd71f`},Wo=(0,M.createContext)({withinGroup:!1}),Go=D((e,{spacing:t})=>({group:{"--ag-spacing":Me(t)}})),Ko=w(e=>{let t=v(`AvatarGroup`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,spacing:l,attributes:d,...f}=t,p=c({name:`AvatarGroup`,classes:Uo,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:d,vars:s,varsResolver:Go,rootSelector:`group`});return(0,N.jsx)(Wo,{value:{withinGroup:!0},children:(0,N.jsx)(u,{...p(`group`),...f})})});Ko.classes=Uo,Ko.varsResolver=Go,Ko.displayName=`@mantine/core/AvatarGroup`;function qo(e){return(0,N.jsx)(`svg`,{...e,"data-avatar-placeholder-icon":!0,viewBox:`0 0 15 15`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,children:(0,N.jsx)(`path`,{d:`M0.877014 7.49988C0.877014 3.84219 3.84216 0.877045 7.49985 0.877045C11.1575 0.877045 14.1227 3.84219 14.1227 7.49988C14.1227 11.1575 11.1575 14.1227 7.49985 14.1227C3.84216 14.1227 0.877014 11.1575 0.877014 7.49988ZM7.49985 1.82704C4.36683 1.82704 1.82701 4.36686 1.82701 7.49988C1.82701 8.97196 2.38774 10.3131 3.30727 11.3213C4.19074 9.94119 5.73818 9.02499 7.50023 9.02499C9.26206 9.02499 10.8093 9.94097 11.6929 11.3208C12.6121 10.3127 13.1727 8.97172 13.1727 7.49988C13.1727 4.36686 10.6328 1.82704 7.49985 1.82704ZM10.9818 11.9787C10.2839 10.7795 8.9857 9.97499 7.50023 9.97499C6.01458 9.97499 4.71624 10.7797 4.01845 11.9791C4.97952 12.7272 6.18765 13.1727 7.49985 13.1727C8.81227 13.1727 10.0206 12.727 10.9818 11.9787ZM5.14999 6.50487C5.14999 5.207 6.20212 4.15487 7.49999 4.15487C8.79786 4.15487 9.84999 5.207 9.84999 6.50487C9.84999 7.80274 8.79786 8.85487 7.49999 8.85487C6.20212 8.85487 5.14999 7.80274 5.14999 6.50487ZM7.49999 5.10487C6.72679 5.10487 6.09999 5.73167 6.09999 6.50487C6.09999 7.27807 6.72679 7.90487 7.49999 7.90487C8.27319 7.90487 8.89999 7.27807 8.89999 6.50487C8.89999 5.73167 8.27319 5.10487 7.49999 5.10487Z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})}function I(e){let t=0;for(let n=0;ne[0]).slice(0,t).join(``).toUpperCase()}var Zo=D((e,{size:t,radius:n,variant:r,gradient:i,color:a,autoContrast:o,name:s,allowedInitialsColors:c})=>{let l=a===`initials`&&typeof s==`string`?Yo(s,c):a,u=e.variantColorResolver({color:l||`gray`,theme:e,gradient:i,variant:r||`light`,autoContrast:o});return{root:{"--avatar-size":ye(t,`avatar-size`),"--avatar-radius":n===void 0?void 0:Oe(n),"--avatar-bg":l||r?u.background:void 0,"--avatar-color":l||r?u.color:void 0,"--avatar-bd":l||r?u.border:void 0}}}),Qo=Pe(e=>{let t=v(`Avatar`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,src:l,alt:d,radius:f,color:p,gradient:m,imageProps:h,children:g,autoContrast:_,mod:y,name:b,allowedInitialsColors:x,attributes:S,...C}=t,w=(0,M.use)(Wo),[T,ee]=(0,M.useState)(!l),E=c({name:`Avatar`,props:t,classes:Uo,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:S,vars:s,varsResolver:Zo});return(0,M.useEffect)(()=>ee(!l),[l]),(0,N.jsx)(u,{...E(`root`),mod:[{"within-group":w.withinGroup},y],...C,children:T||!l?(0,N.jsx)(`span`,{...E(`placeholder`),title:d,children:g||typeof b==`string`&&Xo(b)||(0,N.jsx)(qo,{})}):(0,N.jsx)(`img`,{...h,...E(`image`),src:l,alt:d,onError:e=>{ee(!0),h?.onError?.(e)}})})});Qo.classes=Uo,Qo.varsResolver=Zo,Qo.displayName=`@mantine/core/Avatar`,Qo.Group=Ko;var $o={root:`m_347db0ec`,"root--dot":`m_fbd81e3d`,label:`m_5add502a`,section:`m_91fdda9b`},es=D((e,{radius:t,color:n,gradient:r,variant:i,size:a,autoContrast:o,circle:s})=>{let c=e.variantColorResolver({color:n||e.primaryColor,theme:e,gradient:r,variant:i||`filled`,autoContrast:o});return{root:{"--badge-height":ye(a,`badge-height`),"--badge-padding-x":ye(a,`badge-padding-x`),"--badge-fz":ye(a,`badge-fz`),"--badge-radius":s||t===void 0?void 0:Oe(t),"--badge-bg":n||i?c.background:void 0,"--badge-color":n||i?c.color:void 0,"--badge-bd":n||i?c.border:void 0,"--badge-dot-color":i===`dot`?g(n,e):void 0}}}),ts=Pe(e=>{let t=v(`Badge`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,radius:l,color:d,gradient:f,leftSection:p,rightSection:m,children:h,variant:g,fullWidth:_,autoContrast:y,circle:b,mod:x,attributes:S,...C}=t,w=c({name:`Badge`,props:t,classes:$o,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:S,vars:s,varsResolver:es});return(0,N.jsxs)(u,{variant:g,mod:[{block:_,circle:b,"with-right-section":!!m,"with-left-section":!!p},x],...w(`root`,{variant:g}),...C,children:[p&&(0,N.jsx)(`span`,{...w(`section`),"data-position":`left`,children:p}),(0,N.jsx)(`span`,{...w(`label`),children:h}),m&&(0,N.jsx)(`span`,{...w(`section`),"data-position":`right`,children:m})]})});ts.classes=$o,ts.varsResolver=es,ts.displayName=`@mantine/core/Badge`;var ns={root:`m_fea6bf1a`,burger:`m_d4fb9cad`},rs=D((e,{color:t,size:n,lineSize:r,transitionDuration:i,transitionTimingFunction:a})=>({root:{"--burger-color":t?g(t,e):void 0,"--burger-size":ye(n,`burger-size`),"--burger-line-size":r?j(r):void 0,"--burger-transition-duration":i===void 0?void 0:`${i}ms`,"--burger-transition-timing-function":a}})),is=w(e=>{let t=v(`Burger`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,opened:l,children:d,transitionDuration:f,transitionTimingFunction:p,lineSize:m,attributes:h,...g}=t,_=c({name:`Burger`,classes:ns,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:h,vars:s,varsResolver:rs});return(0,N.jsxs)(C,{..._(`root`),...g,children:[(0,N.jsx)(u,{mod:[`reduce-motion`,{opened:l}],..._(`burger`)}),d]})});is.classes=ns,is.varsResolver=rs,is.displayName=`@mantine/core/Burger`;var as={root:`m_b183c0a2`},os=D((e,{color:t})=>({root:{"--code-bg":t?g(t,e):void 0}})),ss=w(e=>{let t=v(`Code`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,color:l,block:d,mod:f,attributes:p,...m}=t,h=c({name:`Code`,props:t,classes:as,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:p,vars:s,varsResolver:os});return(0,N.jsx)(u,{component:d?`pre`:`code`,mod:[{block:d},f],...h(`root`),...m,dir:`ltr`})});ss.classes=as,ss.varsResolver=os,ss.displayName=`@mantine/core/Code`;var[cs,ls]=at(`Drawer component was not found in tree`),us={root:`m_f11b401e`,header:`m_5a7c2c9`,content:`m_b8a05bbd`,inner:`m_31cd769a`},ds=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`DrawerBody`,null,e),s=ls();return(0,N.jsx)(Wa,{...s.getStyles(`body`,{classNames:t,style:r,styles:i,className:n}),...o})});ds.classes=us,ds.displayName=`@mantine/core/DrawerBody`;var fs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`DrawerCloseButton`,null,e),s=ls();return(0,N.jsx)(Ga,{...s.getStyles(`close`,{classNames:t,style:r,styles:i,className:n}),...o})});fs.classes=us,fs.displayName=`@mantine/core/DrawerCloseButton`;var ps=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,children:o,radius:s,__hidden:c,...l}=v(`DrawerContent`,null,e),u=ls(),d=u.scrollAreaComponent||$a;return(0,N.jsx)(Ka,{...u.getStyles(`content`,{className:n,style:r,styles:i,classNames:t}),innerProps:u.getStyles(`inner`,{className:n,style:r,styles:i,classNames:t}),...l,radius:s||u.radius||0,"data-hidden":c||void 0,children:(0,N.jsx)(d,{style:{height:`calc(100vh - var(--drawer-offset) * 2)`},children:o})})});ps.classes=us,ps.displayName=`@mantine/core/DrawerContent`;var ms=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`DrawerHeader`,null,e),s=ls();return(0,N.jsx)(qa,{...s.getStyles(`header`,{classNames:t,style:r,styles:i,className:n}),...o})});ms.classes=us,ms.displayName=`@mantine/core/DrawerHeader`;var hs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`DrawerOverlay`,null,e),s=ls();return(0,N.jsx)(Xa,{...s.getStyles(`overlay`,{classNames:t,style:r,styles:i,className:n}),...o})});hs.classes=us,hs.displayName=`@mantine/core/DrawerOverlay`;function gs(e){switch(e){case`top`:return`flex-start`;case`bottom`:return`flex-end`;default:return}}function _s(e){if(e===`top`||e===`bottom`)return`0 0 calc(100% - var(--drawer-offset, 0rem) * 2)`}var vs={top:`slide-down`,bottom:`slide-up`,left:`slide-right`,right:`slide-left`},ys={top:`slide-down`,bottom:`slide-up`,right:`slide-right`,left:`slide-left`},bs={closeOnClickOutside:!0,withinPortal:!0,lockScroll:!0,trapFocus:!0,returnFocus:!0,closeOnEscape:!0,keepMounted:!1,zIndex:ot(`modal`),position:`left`},xs=D((e,{position:t,size:n,offset:r})=>({root:{"--drawer-size":ye(n,`drawer-size`),"--drawer-flex":_s(t),"--drawer-height":t===`left`||t===`right`?void 0:`var(--drawer-size)`,"--drawer-align":gs(t),"--drawer-justify":t===`right`?`flex-end`:void 0,"--drawer-offset":j(r)}})),Ss=w(e=>{let t=v(`DrawerRoot`,bs,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,scrollAreaComponent:l,position:u,transitionProps:d,radius:f,attributes:p,...m}=t,{dir:h}=Tt(),g=c({name:`Drawer`,classes:us,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:p,vars:s,varsResolver:xs}),_=(h===`rtl`?ys:vs)[u];return(0,N.jsx)(cs,{value:{scrollAreaComponent:l,getStyles:g,radius:f},children:(0,N.jsx)(Va,{...g(`root`),transitionProps:{transition:_,...d},"data-offset-scrollbars":l===vt.Autosize||void 0,unstyled:o,...m})})});Ss.classes=us,Ss.varsResolver=xs,Ss.displayName=`@mantine/core/DrawerRoot`;var Cs=(0,M.createContext)(null);function ws({children:e}){let[t,n]=(0,M.useState)([]),[r,i]=(0,M.useState)(ot(`modal`)),[a]=(0,M.useState)(()=>new WeakSet);return(0,N.jsx)(Cs,{value:{stack:t,addModal:(e,t)=>{n(t=>[...new Set([...t,e])]),i(e=>typeof t==`number`&&typeof e==`number`?Math.max(e,t):e)},removeModal:e=>n(t=>t.filter(t=>t!==e)),getZIndex:e=>`calc(${r} + ${t.indexOf(e)} + 1)`,currentId:t[t.length-1],maxZIndex:r,handledEscapeEvents:a},children:e})}ws.displayName=`@mantine/core/DrawerStack`;var Ts=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`DrawerTitle`,null,e),s=ls();return(0,N.jsx)(Qa,{...s.getStyles(`title`,{classNames:t,style:r,styles:i,className:n}),...o})});Ts.classes=us,Ts.displayName=`@mantine/core/DrawerTitle`;var Es={closeOnClickOutside:!0,withinPortal:!0,lockScroll:!0,trapFocus:!0,returnFocus:!0,closeOnEscape:!0,keepMounted:!1,zIndex:ot(`modal`),withOverlay:!0,withCloseButton:!0},Ds=w(e=>{let{title:t,withOverlay:n,overlayProps:r,withCloseButton:i,closeButtonProps:a,children:o,opened:s,stackId:c,zIndex:l,...u}=v(`Drawer`,Es,e),d=(0,M.use)(Cs),f=!!t||i,p=d&&c?{closeOnEscape:d.currentId===c,trapFocus:d.currentId===c,zIndex:d.getZIndex(c),__handledEscapeEvents:d.handledEscapeEvents}:{},m=n===!1?!1:c&&d?d.currentId===c:s;return(0,M.useEffect)(()=>{d&&c&&(s?d.addModal(c,l||ot(`modal`)):d.removeModal(c))},[s,c,l]),(0,N.jsxs)(Ss,{opened:s,zIndex:d&&c?d.getZIndex(c):l,...u,...p,children:[n&&(0,N.jsx)(hs,{visible:m,transitionProps:d&&c?{duration:0}:void 0,...r}),(0,N.jsxs)(ps,{__hidden:d&&c&&s?c!==d.currentId:!1,children:[f&&(0,N.jsxs)(ms,{children:[t&&(0,N.jsx)(Ts,{children:t}),i&&(0,N.jsx)(fs,{...a})]}),(0,N.jsx)(ds,{children:o})]})]})});Ds.classes=us,Ds.displayName=`@mantine/core/Drawer`,Ds.Root=Ss,Ds.Overlay=hs,Ds.Content=ps,Ds.Body=ds,Ds.Header=ms,Ds.Title=Ts,Ds.CloseButton=fs,Ds.Stack=ws;var Os={root:`m_dc6f14e2`},ks=D((e,{size:t})=>({root:{"--kbd-fz":ye(t,`kbd-fz`)}})),As=w(e=>{let t=v(`Kbd`,null,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,attributes:l,...d}=t,f=c({name:`Kbd`,classes:Os,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:l,vars:s,varsResolver:ks});return(0,N.jsx)(u,{component:`kbd`,...f(`root`),...d})});As.classes=Os,As.varsResolver=ks,As.displayName=`@mantine/core/Kbd`;var[js,Ms]=at(`Menu component was not found in the tree`),Ns=(0,M.createContext)(null);function Ps(e){let{value:t,defaultValue:n,onChange:r,children:i}=v(`MenuCheckboxGroup`,null,e),[a,o]=yr({value:t,defaultValue:n,finalValue:[],onChange:r}),s=(0,M.useCallback)(e=>{o(a.includes(e)?a.filter(t=>t!==e):[...a,e])},[a,o]);return(0,N.jsx)(Ns,{value:{values:a,onChange:s},children:i})}Ps.displayName=`@mantine/core/MenuCheckboxGroup`;var Fs=(0,M.createContext)(null);function Is({role:e,checked:t,indicator:n,onSelect:r,color:i,closeMenuOnClick:a,rightSection:o,children:s,disabled:c,dataDisabled:l,className:u,style:d,styles:f,classNames:p,buttonRef:m,others:h}){let g=Ms(),_=(0,M.use)(Fs),v=b(),{dir:y}=Tt(),x=(0,M.useRef)(null),S=$n(h.onClick,()=>{l||(r(),a&&g.closeDropdownImmediately())}),w=$n(h.onMouseMove,()=>{if(!g.hasSearch)return;let e=x.current?.closest(`[data-menu-dropdown]`);e&&e.querySelectorAll(`[data-menu-active]`).forEach(t=>{t!==x.current&&t.closest(`[data-menu-dropdown]`)===e&&t.removeAttribute(`data-menu-active`)})}),T=$n(h.onKeyDown,e=>{e.key===`ArrowLeft`&&_&&(_.close(),_.focusParentItem())}),ee=i?v.variantColorResolver({color:i,theme:v,variant:`light`}):void 0,E=i?Te({color:i,theme:v}):null,D=g.alignItemsLabels!==`none`||t;return(0,N.jsxs)(C,{onMouseDown:e=>e.preventDefault(),...h,unstyled:g.unstyled,tabIndex:g.menuItemTabIndex,...g.getStyles(`item`,{className:u,style:d,styles:f,classNames:p}),ref:Ae(x,m),role:e,"aria-checked":t,disabled:c,"data-menu-item":!0,"data-checked":t||void 0,"data-disabled":c||l||void 0,"data-mantine-stop-propagation":!0,onClick:S,onMouseMove:w,onKeyDown:Xn({siblingSelector:`[data-menu-item]:not([data-disabled])`,parentSelector:`[data-menu-dropdown]`,activateOnFocus:!1,loop:g.loop,dir:y,orientation:`vertical`,onKeyDown:T}),__vars:{"--menu-item-color":E?.isThemeColor&&E?.shade===void 0?`var(--mantine-color-${E.color}-6)`:ee?.color,"--menu-item-hover":ee?.hover},children:[D&&(0,N.jsx)(`div`,{...g.getStyles(`itemIndicator`,{styles:f,classNames:p}),"data-checked":t||void 0,children:t?n:null}),s&&(0,N.jsx)(`div`,{...g.getStyles(`itemLabel`,{styles:f,classNames:p}),"data-menu-item-label":!0,children:s}),o&&(0,N.jsx)(`div`,{...g.getStyles(`itemSection`,{styles:f,classNames:p}),"data-position":`right`,children:o})]})}var Ls={dropdown:`m_dc9b7c9f`,label:`m_9bfac126`,divider:`m_efdf90cb`,item:`m_99ac2aa1`,search:`m_ef8769b6`,itemLabel:`m_5476e0d3`,itemIndicator:`m_8395186e`,itemSection:`m_8b75e504`,chevron:`m_b85b0bed`},Rs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,color:o,closeMenuOnClick:s,rightSection:c,children:l,disabled:u,"data-disabled":d,value:f,checked:p,defaultChecked:m,onChange:h,checkIcon:g,ref:_,...y}=v(`MenuCheckboxItem`,null,e),b=Ms(),x=(0,M.use)(Ns),S=x&&f!==void 0?x.values.includes(f):void 0,[C,w]=yr({value:p??S,defaultValue:m,finalValue:!1,onChange:h}),T=g??b.checkIcon??(0,N.jsx)(Ho,{size:10});return(0,N.jsx)(Is,{role:`menuitemcheckbox`,checked:C,indicator:T,onSelect:()=>{h?w(!C):x&&f!==void 0?x.onChange(f):w(!C)},color:o,closeMenuOnClick:s,rightSection:c,disabled:u,dataDisabled:d,className:n,style:r,styles:i,classNames:t,buttonRef:_,others:y,children:l})});Rs.classes=Ls,Rs.displayName=`@mantine/core/MenuCheckboxItem`;function zs(e){let{children:t,disabled:n,longPressDelay:r}=v(`MenuContextMenu`,null,e),i=te(t);if(!i)throw Error(`Menu.ContextMenu component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let a=Ms(),o=ai(),s=oi({childProps:i.props,disabled:n||o.disabled,opened:a.opened,longPressDelay:r,setReference:o.reference,open:()=>a.openDropdown()});return(0,M.cloneElement)(i,s)}zs.displayName=`@mantine/core/MenuContextMenu`;var Bs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`MenuDivider`,null,e),s=Ms();return(0,N.jsx)(u,{...s.getStyles(`divider`,{className:n,style:r,styles:i,classNames:t}),...o})});Bs.classes=Ls,Bs.displayName=`@mantine/core/MenuDivider`;var Vs=500;function Hs(e){return((e.querySelector(`[data-menu-item-label]`)??e).textContent??``).trim().toLowerCase()}function Us(e){return e.length>1&&e.split(``).every(t=>t===e[0])}function Ws({enabled:e,opened:t,getDropdown:n}){let r=(0,M.useRef)({buffer:``,timeoutId:null});return(0,M.useEffect)(()=>{if(t&&e)return;let n=r.current;n.timeoutId!==null&&(window.clearTimeout(n.timeoutId),n.timeoutId=null),n.buffer=``},[t,e]),(0,M.useEffect)(()=>()=>{let{timeoutId:e}=r.current;e!==null&&window.clearTimeout(e)},[]),t=>{if(!e||t.defaultPrevented||t.ctrlKey||t.metaKey||t.altKey||t.key.length!==1||t.key===` `)return;let i=t.target;if(i&&(i.tagName===`INPUT`||i.tagName===`TEXTAREA`||i.tagName===`SELECT`||i.isContentEditable))return;let a=n();if(!a)return;let o=Array.from(a.querySelectorAll(`[data-menu-item]:not([data-disabled])`)).filter(e=>e.closest(`[data-menu-dropdown]`)===a);if(o.length===0)return;let s=r.current;s.buffer=(s.buffer+t.key).toLowerCase(),s.timeoutId!==null&&window.clearTimeout(s.timeoutId),s.timeoutId=window.setTimeout(()=>{s.buffer=``,s.timeoutId=null},Vs);let c=document.activeElement,l=c?o.indexOf(c):-1,u=null;if(s.buffer.length===1||Us(s.buffer)){let e=s.buffer[0],t=l+1;for(let n=0;n{let{classNames:t,className:n,style:r,styles:i,vars:a,onMouseEnter:o,onMouseLeave:s,onKeyDown:c,children:l,ref:u,...d}=v(`MenuDropdown`,null,e),f=(0,M.useRef)(null),p=Ms(),m=Ws({enabled:!p.hasSearch,opened:p.opened,getDropdown:()=>f.current}),h=$n(c,e=>{m(e),!(e.defaultPrevented||p.hasSearch)&&(e.key===`ArrowUp`||e.key===`ArrowDown`)&&(e.preventDefault(),f.current?.querySelectorAll(`[data-menu-item]:not(:disabled)`)[0]?.focus())}),g=$n(o,()=>(p.trigger===`hover`||p.trigger===`click-hover`)&&p.openDropdown()),_=$n(s,()=>(p.trigger===`hover`||p.trigger===`click-hover`)&&p.closeDropdown());return(0,N.jsxs)(yi.Dropdown,{...d,onMouseEnter:g,onMouseLeave:_,role:`menu`,"aria-orientation":`vertical`,ref:Ae(u,f),...p.getStyles(`dropdown`,{className:n,style:r,styles:i,classNames:t,withStaticClass:!1}),tabIndex:-1,"data-menu-dropdown":!0,onKeyDown:h,children:[p.withInitialFocusPlaceholder&&!p.hasSearch&&(0,N.jsx)(`div`,{role:`presentation`,tabIndex:-1,"data-autofocus":!0,"data-mantine-stop-propagation":!0,style:{outline:0}}),l]})});Gs.classes=Ls,Gs.displayName=`@mantine/core/MenuDropdown`;var Ks=Pe(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,color:o,closeMenuOnClick:s,leftSection:c,rightSection:l,children:u,disabled:d,"data-disabled":f,ref:p,...m}=v(`MenuItem`,null,e),h=Ms(),g=(0,M.use)(Fs),_=b(),{dir:y}=Tt(),x=(0,M.useRef)(null),S=m,w=$n(S.onClick,()=>{f||(typeof s==`boolean`?s&&h.closeDropdownImmediately():h.closeOnItemClick&&h.closeDropdownImmediately())}),T=$n(S.onMouseMove,()=>{if(!h.hasSearch)return;let e=x.current?.closest(`[data-menu-dropdown]`);e&&e.querySelectorAll(`[data-menu-active]`).forEach(t=>{t!==x.current&&t.closest(`[data-menu-dropdown]`)===e&&t.removeAttribute(`data-menu-active`)})}),ee=o?_.variantColorResolver({color:o,theme:_,variant:`light`}):void 0,E=o?Te({color:o,theme:_}):null,D=$n(S.onKeyDown,e=>{e.key===`ArrowLeft`&&g&&(g.close(),g.focusParentItem())});return(0,N.jsxs)(C,{onMouseDown:e=>e.preventDefault(),...m,unstyled:h.unstyled,tabIndex:h.menuItemTabIndex,...h.getStyles(`item`,{className:n,style:r,styles:i,classNames:t}),ref:Ae(x,p),role:`menuitem`,disabled:d,"data-menu-item":!0,"data-disabled":d||f||void 0,"data-mantine-stop-propagation":!0,onClick:w,onMouseMove:T,onKeyDown:Xn({siblingSelector:`[data-menu-item]:not([data-disabled])`,parentSelector:`[data-menu-dropdown]`,activateOnFocus:!1,loop:h.loop,dir:y,orientation:`vertical`,onKeyDown:D}),__vars:{"--menu-item-color":E?.isThemeColor&&E?.shade===void 0?`var(--mantine-color-${E.color}-6)`:ee?.color,"--menu-item-hover":ee?.hover},children:[h.alignItemsLabels===`all`&&(0,N.jsx)(`div`,{...h.getStyles(`itemIndicator`,{styles:i,classNames:t}),"data-placeholder":!0}),c&&(0,N.jsx)(`div`,{...h.getStyles(`itemSection`,{styles:i,classNames:t}),"data-position":`left`,children:c}),u&&(0,N.jsx)(`div`,{...h.getStyles(`itemLabel`,{styles:i,classNames:t}),"data-menu-item-label":!0,children:u}),l&&(0,N.jsx)(`div`,{...h.getStyles(`itemSection`,{styles:i,classNames:t}),"data-position":`right`,children:l})]})});Ks.classes=Ls,Ks.displayName=`@mantine/core/MenuItem`;var qs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`MenuLabel`,null,e),s=Ms();return(0,N.jsx)(u,{...s.getStyles(`label`,{className:n,style:r,styles:i,classNames:t}),...o})});qs.classes=Ls,qs.displayName=`@mantine/core/MenuLabel`;var Js=(0,M.createContext)(null);function Ys(e){let{value:t,defaultValue:n,onChange:r,children:i}=v(`MenuRadioGroup`,null,e),[a,o]=yr({value:t,defaultValue:n,finalValue:null,onChange:r});return(0,N.jsx)(Js,{value:{value:a,onChange:e=>o(e)},children:i})}Ys.displayName=`@mantine/core/MenuRadioGroup`;function Xs({size:e,style:t,...n}){return(0,N.jsx)(`svg`,{xmlns:`http://www.w3.org/2000/svg`,fill:`none`,viewBox:`0 0 5 5`,style:{width:j(e),height:j(e),...t},"aria-hidden":!0,...n,children:(0,N.jsx)(`circle`,{cx:`2.5`,cy:`2.5`,r:`2.5`,fill:`currentColor`})})}var Zs=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,color:o,closeMenuOnClick:s,rightSection:c,children:l,disabled:u,"data-disabled":d,value:f,checked:p,onChange:m,checkIcon:h,ref:g,..._}=v(`MenuRadioItem`,null,e),y=Ms(),b=(0,M.use)(Js),x=p??(b?b.value===f:!1),S=h??y.checkIcon??(0,N.jsx)(Xs,{size:5});return(0,N.jsx)(Is,{role:`menuitemradio`,checked:x,indicator:S,onSelect:()=>{x||(m?m(f):b&&b.onChange(f))},color:o,closeMenuOnClick:s,rightSection:c,disabled:u,dataDisabled:d,className:n,style:r,styles:i,classNames:t,buttonRef:g,others:_,children:l})});Zs.classes=Ls,Zs.displayName=`@mantine/core/MenuRadioItem`;var Qs=`[data-menu-item]:not([data-disabled])`,$s=`[data-menu-active]`;function ec(e){return e?.closest(`[data-menu-dropdown]`)}function tc(e){return e?Array.from(e.querySelectorAll(Qs)).filter(t=>t.closest(`[data-menu-dropdown]`)===e):[]}function nc(e){e&&e.querySelectorAll($s).forEach(t=>{t.closest(`[data-menu-dropdown]`)===e&&t.removeAttribute(`data-menu-active`)})}function rc(e,t){nc(t),e&&(e.setAttribute(`data-menu-active`,`true`),e.scrollIntoView({block:`nearest`}))}function ic(e){return e.findIndex(e=>e.hasAttribute(`data-menu-active`))}var ac={clearSearchOnClose:!0},oc=w(e=>{let{classNames:t,styles:n,onKeyDown:r,onChange:i,size:a,clearSearchOnClose:o,ref:s,...c}=v(`MenuSearch`,ac,e),l=Ms(),u=(0,M.useRef)(null),d=Ae(s,u),f=(0,M.useRef)(i);f.current=i,(0,M.useEffect)(()=>l.registerSearch(),[l.registerSearch]),(0,M.useEffect)(()=>{o?l.searchExitClearRef.current=()=>{f.current?.({currentTarget:{value:``}})}:l.searchExitClearRef.current=null},[o,l.searchExitClearRef]),(0,M.useEffect)(()=>{l.opened||nc(ec(u.current))},[l.opened]);let p=$n(i,e=>{nc(ec(e.currentTarget))}),m=$n(r,e=>{if(e.defaultPrevented)return;let t=ec(e.currentTarget),n=tc(t);if(e.key===`ArrowDown`){if(e.preventDefault(),n.length===0)return;let r=ic(n);rc(n[r>=n.length-1?l.loop?0:r:r+1]??null,t)}else if(e.key===`ArrowUp`){if(e.preventDefault(),n.length===0)return;let r=ic(n);rc(n[r<=0?r===-1||l.loop?n.length-1:0:r-1]??null,t)}else if(e.key===`Home`)e.preventDefault(),n.length>0&&rc(n[0],t);else if(e.key===`End`)e.preventDefault(),n.length>0&&rc(n[n.length-1],t);else if(e.key===`Enter`){if(e.nativeEvent.isComposing||e.nativeEvent.keyCode===229)return;let t=n[ic(n)];t&&(e.preventDefault(),t.hasAttribute(`data-sub-menu-item`)?(t.focus(),t.dispatchEvent(new KeyboardEvent(`keydown`,{key:`ArrowRight`,bubbles:!0}))):t.click())}}),h=l.getStyles(`search`);return(0,N.jsx)(fe,{"data-autofocus":!0,"data-mantine-stop-propagation":!0,type:`search`,size:a,...c,ref:d,classNames:[{input:h.className},t],styles:[{input:h.style},n],onKeyDown:m,onChange:p,__staticSelector:`Menu`})});oc.classes=Ls,oc.displayName=`@mantine/core/MenuSearch`;var sc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,onMouseEnter:o,onMouseLeave:s,onPointerEnter:c,onPointerLeave:l,onKeyDown:u,children:d,ref:f,...p}=v(`MenuSubDropdown`,null,e),m=(0,M.useRef)(null),h=Ms(),g=(0,M.use)(Fs),_=Ws({enabled:!h.hasSearch,opened:g?.opened??!1,getDropdown:()=>m.current}),y=$n(u,e=>{_(e),!e.ctrlKey&&!e.metaKey&&!e.altKey&&e.key.length===1&&e.key!==` `&&e.stopPropagation()}),b=g?.getFloatingProps({onMouseEnter:o,onMouseLeave:s,onPointerEnter:c,onPointerLeave:l});return(0,N.jsx)(yi.Dropdown,{...p,...b,role:`menu`,"aria-orientation":`vertical`,ref:Ae(f,m,g?.setFloating),...h.getStyles(`dropdown`,{className:n,style:r,styles:i,classNames:t,withStaticClass:!1}),tabIndex:-1,"data-menu-dropdown":!0,onKeyDown:y,children:d})});sc.classes=Ls,sc.displayName=`@mantine/core/MenuSubDropdown`;var cc=Pe(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,color:o,leftSection:s,rightSection:c,children:l,disabled:u,"data-disabled":d,closeMenuOnClick:f,ref:p,...m}=v(`MenuSubItem`,null,e),h=Ms(),g=(0,M.use)(Fs),_=b(),{dir:y}=Tt(),x=(0,M.useRef)(null),S=m,w=o?_.variantColorResolver({color:o,theme:_,variant:`light`}):void 0,T=o?Te({color:o,theme:_}):null,ee=$n(S.onKeyDown,e=>{e.key===`ArrowRight`&&(g?.open(),g?.focusFirstItem()),e.key===`ArrowLeft`&&g?.parentContext&&(g.parentContext.close(),g.parentContext.focusParentItem())}),E=$n(S.onClick,()=>{!d&&f&&h.closeDropdownImmediately()}),D=$n(S.onMouseMove,()=>{if(!h.hasSearch)return;let e=x.current?.closest(`[data-menu-dropdown]`);e&&e.querySelectorAll(`[data-menu-active]`).forEach(t=>{t!==x.current&&t.closest(`[data-menu-dropdown]`)===e&&t.removeAttribute(`data-menu-active`)})}),O=g?.getReferenceProps({onMouseEnter:S.onMouseEnter,onMouseLeave:S.onMouseLeave,onPointerEnter:S.onPointerEnter,onPointerLeave:S.onPointerLeave});return(0,N.jsxs)(C,{onMouseDown:e=>e.preventDefault(),...m,...O,unstyled:h.unstyled,tabIndex:h.menuItemTabIndex,...h.getStyles(`item`,{className:n,style:r,styles:i,classNames:t}),ref:Ae(x,p,g?.setReference),role:`menuitem`,disabled:u,"data-menu-item":!0,"data-sub-menu-item":!0,"data-disabled":u||d||void 0,"data-mantine-stop-propagation":!0,onClick:E,onMouseMove:D,onKeyDown:Xn({siblingSelector:`[data-menu-item]:not([data-disabled])`,parentSelector:`[data-menu-dropdown]`,activateOnFocus:!1,loop:h.loop,dir:y,orientation:`vertical`,onKeyDown:ee}),__vars:{"--menu-item-color":T?.isThemeColor&&T?.shade===void 0?`var(--mantine-color-${T.color}-6)`:w?.color,"--menu-item-hover":w?.hover},children:[h.alignItemsLabels===`all`&&(0,N.jsx)(`div`,{...h.getStyles(`itemIndicator`,{styles:i,classNames:t}),"data-placeholder":!0}),s&&(0,N.jsx)(`div`,{...h.getStyles(`itemSection`,{styles:i,classNames:t}),"data-position":`left`,children:s}),l&&(0,N.jsx)(`div`,{...h.getStyles(`itemLabel`,{styles:i,classNames:t}),"data-menu-item-label":!0,children:l}),(0,N.jsx)(`div`,{...h.getStyles(`itemSection`,{styles:i,classNames:t}),"data-position":`right`,children:c||(0,N.jsx)(eo,{...h.getStyles(`chevron`),size:14})})]})});cc.classes=Ls,cc.displayName=`@mantine/core/MenuSubItem`;function lc({children:e,refProp:t}){if(!le(e))throw Error(`Menu.Sub.Target component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);return Ms(),(0,N.jsx)(yi.Target,{refProp:t,popupType:`menu`,children:e})}lc.displayName=`@mantine/core/MenuSubTarget`;var uc={offset:0,position:`right-start`,safeAreaPolygon:!0,transitionProps:{duration:0},openDelay:0,middlewares:{shift:{crossAxis:!0}}};function dc(e){let{children:t,closeDelay:n,openDelay:r,position:i,safeAreaPolygon:a,opened:o,onChange:s,...c}=v(`MenuSub`,uc,e),l=be(),[u,d]=yr({value:o,finalValue:!1,onChange:s}),f=(0,M.use)(Fs),p=Ms(),{dir:m}=Tt(),h=bt(m,i),g=f?.registerOpenSub??p.registerOpenSub,_=(0,M.useRef)(null),y=(0,M.useCallback)(e=>{let t=_.current;return t&&t!==e&&t(),_.current=e,()=>{_.current===e&&(_.current=null)}},[]),b=(0,M.useRef)(d);b.current=d;let x=(0,M.useCallback)(()=>b.current(!0),[]),S=(0,M.useCallback)(()=>b.current(!1),[]);(0,M.useEffect)(()=>{if(u)return g(S)},[u,g,S]);let{context:C,refs:w}=lt({placement:h,open:u,onOpenChange:e=>{e?x():S()}}),{getReferenceProps:T,getFloatingProps:ee}=Ct([ht(C,{handleClose:a?xt(typeof a==`object`?a:void 0):void 0,delay:{open:r,close:n}})]);return(0,N.jsx)(Fs,{value:{opened:u,close:S,open:x,focusFirstItem:()=>window.setTimeout(()=>{document.getElementById(`${l}-dropdown`)?.querySelectorAll(`[data-menu-item]:not([data-disabled])`)[0]?.focus()},16),focusParentItem:()=>window.setTimeout(()=>{document.getElementById(`${l}-target`)?.focus()},16),parentContext:f,setReference:w.setReference,setFloating:w.setFloating,getReferenceProps:T,getFloatingProps:ee,registerOpenSub:y},children:(0,N.jsx)(yi,{opened:u,onChange:e=>e?x():S(),withArrow:!1,id:l,position:i,...c,withinPortal:!1,children:t})})}dc.extend=e=>e,dc.displayName=`@mantine/core/MenuSub`,dc.Target=lc,dc.Dropdown=sc,dc.Item=cc;var fc={refProp:`ref`};function pc(e){let{children:t,refProp:n,...r}=v(`MenuTarget`,fc,e),i=te(t);if(!i)throw Error(`Menu.Target component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let a=Ms(),o=i.props,s=$n(o.onClick,()=>{a.trigger===`click`?a.toggleDropdown():a.trigger===`click-hover`&&(a.setOpenedViaClick(!0),a.opened||a.openDropdown())}),c=$n(o.onMouseEnter,()=>(a.trigger===`hover`||a.trigger===`click-hover`)&&a.openDropdown()),l=$n(o.onMouseLeave,()=>{(a.trigger===`hover`||a.trigger===`click-hover`&&!a.openedViaClick)&&a.closeDropdown()});return(0,N.jsx)(yi.Target,{refProp:n,popupType:`menu`,...r,children:(0,M.cloneElement)(i,{onClick:s,onMouseEnter:c,onMouseLeave:l,"data-expanded":a.opened?!0:void 0})})}pc.displayName=`@mantine/core/MenuTarget`;var mc={trapFocus:!0,closeOnItemClick:!0,withInitialFocusPlaceholder:!0,clickOutsideEvents:[`mousedown`,`touchstart`,`keydown`],loop:!0,trigger:`click`,openDelay:0,closeDelay:100,menuItemTabIndex:-1,alignItemsLabels:`with-indicators`},hc=w(e=>{let t=v(`Menu`,mc,e),{children:n,onOpen:r,onClose:i,opened:a,defaultOpened:o,trapFocus:s,onChange:l,closeOnItemClick:u,loop:d,closeOnEscape:f,trigger:p,openDelay:m,closeDelay:h,classNames:g,styles:_,unstyled:y,variant:b,vars:x,menuItemTabIndex:S,keepMounted:C,withInitialFocusPlaceholder:w,attributes:T,onExitTransitionEnd:ee,alignItemsLabels:E,checkIcon:D,...O}=t,te=c({name:`Menu`,classes:Ls,props:t,classNames:g,styles:_,unstyled:y,attributes:T}),[ne,re]=yr({value:a,defaultValue:o,finalValue:!1,onChange:l}),[k,ie]=(0,M.useState)(!1),ae=()=>{re(!1),ie(!1),ne&&i?.()},oe=()=>{re(!0),!ne&&r?.()},se=()=>{ne?ae():oe()},{openDropdown:ce,closeDropdown:le}=$r({open:oe,close:ae,closeDelay:h,openDelay:m}),ue=(0,M.useRef)(null),de=(0,M.useCallback)(e=>{let t=ue.current;return t&&t!==e&&t(),ue.current=e,()=>{ue.current===e&&(ue.current=null)}},[]),fe=(0,M.useRef)(0),[pe,me]=(0,M.useState)(!1),he=(0,M.useCallback)(()=>(fe.current+=1,fe.current===1&&me(!0),()=>{--fe.current,fe.current===0&&me(!1)}),[]),_e=(0,M.useRef)(null),ve=()=>{_e.current?.(),ee?.()},ye=e=>nr(`[data-menu-item]`,`[data-menu-dropdown]`,e),{resolvedClassNames:A,resolvedStyles:j}=ge({classNames:g,styles:_,props:t});return(0,N.jsx)(js,{value:{getStyles:te,opened:ne,toggleDropdown:se,getItemIndex:ye,openedViaClick:k,setOpenedViaClick:ie,closeOnItemClick:u,closeDropdown:p===`click`?ae:le,openDropdown:p===`click`?oe:ce,closeDropdownImmediately:ae,loop:d,trigger:p,unstyled:y,menuItemTabIndex:S,withInitialFocusPlaceholder:w,registerOpenSub:de,hasSearch:pe,registerSearch:he,searchExitClearRef:_e,alignItemsLabels:E,checkIcon:D},children:(0,N.jsx)(yi,{returnFocus:!0,...O,opened:ne,onChange:se,defaultOpened:o,trapFocus:!C&&s,closeOnEscape:f,__staticSelector:`Menu`,classNames:A,styles:j,unstyled:y,variant:b,keepMounted:C,onExitTransitionEnd:ve,children:n})})});hc.displayName=`@mantine/core/Menu`,hc.classes=Ls,hc.Item=Ks,hc.Label=qs,hc.Dropdown=Gs,hc.Target=pc,hc.Divider=Bs,hc.Search=oc,hc.Sub=dc,hc.CheckboxItem=Rs,hc.CheckboxGroup=Ps,hc.RadioItem=Zs,hc.RadioGroup=Ys,hc.ContextMenu=zs;var[gc,_c]=at(`Modal component was not found in tree`),vc={root:`m_9df02822`,content:`m_54c44539`,inner:`m_1f958f16`,header:`m_d0e2b9cd`},yc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`ModalBody`,null,e),s=_c();return(0,N.jsx)(Wa,{...s.getStyles(`body`,{classNames:t,style:r,styles:i,className:n}),...o})});yc.classes=vc,yc.displayName=`@mantine/core/ModalBody`;var bc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`ModalCloseButton`,null,e),s=_c();return(0,N.jsx)(Ga,{...s.getStyles(`close`,{classNames:t,style:r,styles:i,className:n}),...o})});bc.classes=vc,bc.displayName=`@mantine/core/ModalCloseButton`;var xc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,children:o,__hidden:s,...c}=v(`ModalContent`,null,e),l=_c(),u=l.scrollAreaComponent||$a;return(0,N.jsx)(Ka,{...l.getStyles(`content`,{className:n,style:r,styles:i,classNames:t}),innerProps:l.getStyles(`inner`,{className:n,style:r,styles:i,classNames:t}),"data-full-screen":l.fullScreen||void 0,"data-modal-content":!0,"data-hidden":s||void 0,...c,children:(0,N.jsx)(u,{style:{maxHeight:l.fullScreen?`100dvh`:`calc(100dvh - (${j(l.yOffset)} * 2))`},children:o})})});xc.classes=vc,xc.displayName=`@mantine/core/ModalContent`;var Sc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`ModalHeader`,null,e),s=_c();return(0,N.jsx)(qa,{...s.getStyles(`header`,{classNames:t,style:r,styles:i,className:n}),...o})});Sc.classes=vc,Sc.displayName=`@mantine/core/ModalHeader`;var Cc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`ModalOverlay`,null,e),s=_c();return(0,N.jsx)(Xa,{...s.getStyles(`overlay`,{classNames:t,style:r,styles:i,className:n}),...o})});Cc.classes=vc,Cc.displayName=`@mantine/core/ModalOverlay`;var wc={__staticSelector:`Modal`,closeOnClickOutside:!0,withinPortal:!0,lockScroll:!0,trapFocus:!0,returnFocus:!0,closeOnEscape:!0,keepMounted:!1,zIndex:ot(`modal`),transitionProps:{duration:200,transition:`fade-down`},yOffset:`5dvh`},Tc=D((e,{radius:t,size:n,yOffset:r,xOffset:i})=>({root:{"--modal-radius":t===void 0?void 0:Oe(t),"--modal-size":ye(n,`modal-size`),"--modal-y-offset":j(r),"--modal-x-offset":j(i)}})),Ec=w(e=>{let t=v(`ModalRoot`,wc,e),{classNames:n,className:r,style:i,styles:a,unstyled:o,vars:s,yOffset:l,scrollAreaComponent:u,radius:d,fullScreen:f,centered:p,xOffset:m,__staticSelector:h,attributes:g,..._}=t,y=c({name:h,classes:vc,props:t,className:r,style:i,classNames:n,styles:a,unstyled:o,attributes:g,vars:s,varsResolver:Tc});return(0,N.jsx)(gc,{value:{yOffset:l,scrollAreaComponent:u,getStyles:y,fullScreen:f},children:(0,N.jsx)(Va,{...y(`root`),"data-full-screen":f||void 0,"data-centered":p||void 0,"data-offset-scrollbars":u===vt.Autosize||void 0,unstyled:o,..._})})});Ec.classes=vc,Ec.varsResolver=Tc,Ec.displayName=`@mantine/core/ModalRoot`;var Dc=(0,M.createContext)(null);function Oc({children:e}){let[t,n]=(0,M.useState)([]),[r,i]=(0,M.useState)(ot(`modal`)),[a]=(0,M.useState)(()=>new WeakSet);return(0,N.jsx)(Dc,{value:{stack:t,addModal:(e,t)=>{n(t=>[...new Set([...t,e])]),i(e=>typeof t==`number`&&typeof e==`number`?Math.max(e,t):e)},removeModal:e=>n(t=>t.filter(t=>t!==e)),getZIndex:e=>`calc(${r} + ${t.indexOf(e)} + 1)`,currentId:t[t.length-1],maxZIndex:r,handledEscapeEvents:a},children:e})}Oc.displayName=`@mantine/core/ModalStack`;var kc=w(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...o}=v(`ModalTitle`,null,e),s=_c();return(0,N.jsx)(Qa,{...s.getStyles(`title`,{classNames:t,style:r,styles:i,className:n}),...o})});kc.classes=vc,kc.displayName=`@mantine/core/ModalTitle`;var Ac={closeOnClickOutside:!0,withinPortal:!0,lockScroll:!0,trapFocus:!0,returnFocus:!0,closeOnEscape:!0,keepMounted:!1,zIndex:ot(`modal`),transitionProps:{duration:200,transition:`fade-down`},withOverlay:!0,withCloseButton:!0},jc=w(e=>{let{title:t,withOverlay:n,overlayProps:r,withCloseButton:i,closeButtonProps:a,children:o,radius:s,opened:c,stackId:l,zIndex:u,...d}=v(`Modal`,Ac,e),f=(0,M.use)(Dc),p=!!t||i,m=f&&l?{closeOnEscape:f.currentId===l,trapFocus:f.currentId===l,zIndex:f.getZIndex(l),__handledEscapeEvents:f.handledEscapeEvents}:{},h=n===!1?!1:l&&f?f.currentId===l:c;return(0,M.useEffect)(()=>{f&&l&&(c?f.addModal(l,u||ot(`modal`)):f.removeModal(l))},[c,l,u]),(0,N.jsxs)(Ec,{radius:s,opened:c,zIndex:f&&l?f.getZIndex(l):u,...d,...m,children:[n&&(0,N.jsx)(Cc,{visible:h,transitionProps:f&&l?{duration:0}:void 0,...r}),(0,N.jsxs)(xc,{radius:s,__hidden:f&&l&&c?l!==f.currentId:!1,children:[p&&(0,N.jsxs)(Sc,{children:[t&&(0,N.jsx)(kc,{children:t}),i&&(0,N.jsx)(bc,{...a})]}),(0,N.jsx)(yc,{children:o})]})]})});jc.classes=vc,jc.displayName=`@mantine/core/Modal`,jc.Root=Ec,jc.Overlay=Cc,jc.Content=xc,jc.Body=yc,jc.Header=Sc,jc.Title=kc,jc.CloseButton=bc,jc.Stack=Oc;function Mc(e,t){if(e<1)return[];let n=Array(e).fill(``);if(t){let r=t.trim().split(``);for(let t=0;t({root:{"--pin-input-size":ye(t??`sm`,`pin-input-size`)}})),Lc=w(e=>{let{name:t,form:n,className:r,value:i,defaultValue:a,variant:o,gap:l,style:u,size:d,classNames:f,styles:p,unstyled:m,length:h,onChange:g,onComplete:_,manageFocus:y,autoFocus:b,error:x,success:S,radius:C,disabled:w,oneTimeCode:T,placeholder:ee,type:E,mask:D,readOnly:O,inputType:te,inputMode:re,ariaLabel:k,vars:ie,id:ae,hiddenInputProps:oe,rootRef:se,getInputProps:ce,attributes:le,ref:ue,...de}=v([`Input`,`PinInput`],Fc,e),pe=be(ae),me=c({name:`PinInput`,classes:Nc,props:e,className:r,style:u,classNames:f,styles:p,unstyled:m,attributes:le,vars:ie,varsResolver:Ic}),{resolvedClassNames:he,resolvedStyles:_e}=ge({classNames:f,styles:p,props:e}),[ve,ye]=(0,M.useState)(-1),A=(0,M.useRef)([]),j=h??4,xe=(0,M.useRef)(!1),[Se,Ce]=yr({value:i===void 0?void 0:Mc(j,i),defaultValue:a?.split(``).slice(0,j),finalValue:Mc(j,``),onChange:e=>{let t=e.join(``).trim();g?.(t),t.length===j&&!xe.current?(xe.current=!0,_?.(t)):t.length(E instanceof RegExp?E:E&&E in Pc?Pc[E]:null)?.test(e),De=(e,t)=>{if(y){if(e===`next`){let e=t+1;e=0&&A.current[e]?.focus()}}},Oe=(e,t)=>{let n=[...we];return n[t]=e,Ce(n),n},ke=(e,t)=>{let n=e.target.value;if(n.length>1){if(n.length>2){if(Ee(n)){Ce(Mc(j,n));let e=Math.min(n.length,j);e{let{ctrlKey:n,metaKey:r,key:i,shiftKey:a,target:o}=e,s=o.value;if(re===`numeric`){let t=[`Backspace`,`Tab`,`Control`,`Delete`,`ArrowLeft`,`ArrowRight`],a=n||r;if(!(t.includes(i)||a||!Number.isNaN(Number(i)))){e.preventDefault();return}}switch(i){case`ArrowLeft`:e.preventDefault(),De(`prev`,t);break;case`ArrowRight`:e.preventDefault(),De(`next`,t);break;case`Tab`:a&&t>0&&y&&(e.preventDefault(),De(`prev`,t));break;case` `:e.preventDefault(),De(`next`,t);break;case`Delete`:e.preventDefault(),O||Oe(``,t);break;case`Backspace`:O?e.preventDefault():s===``?(e.preventDefault(),De(`prev`,t)):(Oe(``,t),t0&&i===we[t]&&(e.preventDefault(),De(`next`,t))}},je=(e,t)=>{e.target.select(),ye(t)},Me=()=>{ye(-1)},Ne=e=>{if(e.preventDefault(),O)return;let t=e.clipboardData.getData(`text/plain`).replace(/[\n\r\s]+/g,``);if(Ee(t.trim())){let e=Mc(j,t);Ce(e);let n=e.filter(e=>e!==``).length;n>=j?A.current[j-1]?.focus():A.current[n]?.focus()}};return(0,N.jsxs)(N.Fragment,{children:[(0,N.jsx)(ne,{...de,...me(`root`),ref:se,role:`group`,id:pe,gap:l,unstyled:m,wrap:`nowrap`,variant:o,__size:d,dir:`ltr`,children:we.map((e,t)=>(0,M.createElement)(fe,{component:`input`,...me(`pinInput`,{style:{"--input-padding":`0`,"--input-text-align":`center`}}),classNames:he,styles:_e,size:d,__staticSelector:`PinInput`,id:`${pe}-${t+1}`,key:`${pe}-${t}`,inputMode:re||(E===`number`?`numeric`:`text`),onChange:e=>ke(e,t),onKeyDown:e=>Ae(e,t),onFocus:e=>je(e,t),onBlur:Me,onPaste:Ne,type:te||(D?`password`:E===`number`?`tel`:`text`),radius:C,error:x,success:S,variant:o,disabled:w,ref:e=>{e&&(t===0&&s(ue,e),A.current[t]=e)},autoComplete:T?`one-time-code`:`off`,placeholder:ve===t?``:ee,value:e,autoFocus:b&&t===0,unstyled:m,"aria-label":k,readOnly:O,...ce?.(t)}))}),(0,N.jsx)(`input`,{type:`hidden`,name:t,form:n,value:Te,...oe})]})});Lc.classes={...Nc,...A.classes},Lc.varsResolver=Ic,Lc.displayName=`@mantine/core/PinInput`;var Rc=w(e=>{let t=v([`Input`,`InputWrapper`,`TextInput`],null,e);return(0,N.jsx)(A,{component:`input`,...t,__staticSelector:`TextInput`})});Rc.classes=A.classes,Rc.displayName=`@mantine/core/TextInput`;var zc=[];for(let e=0;e<256;++e)zc.push((e+256).toString(16).slice(1));function Bc(e,t=0){return(zc[e[t+0]]+zc[e[t+1]]+zc[e[t+2]]+zc[e[t+3]]+`-`+zc[e[t+4]]+zc[e[t+5]]+`-`+zc[e[t+6]]+zc[e[t+7]]+`-`+zc[e[t+8]]+zc[e[t+9]]+`-`+zc[e[t+10]]+zc[e[t+11]]+zc[e[t+12]]+zc[e[t+13]]+zc[e[t+14]]+zc[e[t+15]]).toLowerCase()}var Vc,Hc=new Uint8Array(16);function Uc(){if(!Vc){if(typeof crypto>`u`||!crypto.getRandomValues)throw Error(`crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported`);Vc=crypto.getRandomValues.bind(crypto)}return Vc(Hc)}var Wc={randomUUID:typeof crypto<`u`&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Gc(e,t,n){if(Wc.randomUUID&&!t&&!e)return Wc.randomUUID();e||={};let r=e.random??e.rng?.()??Uc();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return Bc(r)}var Kc=At(),L=function(e){return e.TEXT_MESSAGE_START=`TEXT_MESSAGE_START`,e.TEXT_MESSAGE_CONTENT=`TEXT_MESSAGE_CONTENT`,e.TEXT_MESSAGE_END=`TEXT_MESSAGE_END`,e.TEXT_MESSAGE_CHUNK=`TEXT_MESSAGE_CHUNK`,e.TOOL_CALL_START=`TOOL_CALL_START`,e.TOOL_CALL_ARGS=`TOOL_CALL_ARGS`,e.TOOL_CALL_END=`TOOL_CALL_END`,e.TOOL_CALL_CHUNK=`TOOL_CALL_CHUNK`,e.TOOL_CALL_RESULT=`TOOL_CALL_RESULT`,e.STATE_SNAPSHOT=`STATE_SNAPSHOT`,e.STATE_DELTA=`STATE_DELTA`,e.MESSAGES_SNAPSHOT=`MESSAGES_SNAPSHOT`,e.ACTIVITY_SNAPSHOT=`ACTIVITY_SNAPSHOT`,e.ACTIVITY_DELTA=`ACTIVITY_DELTA`,e.RAW=`RAW`,e.CUSTOM=`CUSTOM`,e.RUN_STARTED=`RUN_STARTED`,e.RUN_FINISHED=`RUN_FINISHED`,e.RUN_ERROR=`RUN_ERROR`,e.STEP_STARTED=`STEP_STARTED`,e.STEP_FINISHED=`STEP_FINISHED`,e.REASONING_START=`REASONING_START`,e.REASONING_MESSAGE_START=`REASONING_MESSAGE_START`,e.REASONING_MESSAGE_CONTENT=`REASONING_MESSAGE_CONTENT`,e.REASONING_MESSAGE_END=`REASONING_MESSAGE_END`,e.REASONING_MESSAGE_CHUNK=`REASONING_MESSAGE_CHUNK`,e.REASONING_END=`REASONING_END`,e.REASONING_ENCRYPTED_VALUE=`REASONING_ENCRYPTED_VALUE`,e.SUBAGENT_STARTED=`SUBAGENT_STARTED`,e.SUBAGENT_FINISHED=`SUBAGENT_FINISHED`,e.SUBAGENT_ERROR=`SUBAGENT_ERROR`,e}({}),qc={TextMessageStartEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`role`,`name`],fields:{}},TextMessageContentEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},TextMessageEndEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},TextMessageChunkEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`messageId`,`role`,`delta`,`name`],fields:{}},ToolCallStartEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`parentMessageId`],fields:{}},ToolCallArgsEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ToolCallEndEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ToolCallChunkEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`toolCallId`,`toolCallName`,`parentMessageId`,`delta`],fields:{}},TextPart:{optional:[`id`,`metadata`],fields:{}},DataSource:{optional:[],fields:{}},UrlSource:{optional:[`mimeType`],fields:{}},FileSource:{optional:[`provider`,`mimeType`],fields:{}},PartSource:{discriminator:`type`,variants:{data:`DataSource`,url:`UrlSource`,file:`FileSource`}},ImagePart:{optional:[`id`,`metadata`],fields:{source:`PartSource`}},AudioPart:{optional:[`id`,`metadata`],fields:{source:`PartSource`}},VideoPart:{optional:[`id`,`metadata`],fields:{source:`PartSource`}},DocumentPart:{optional:[`id`,`metadata`],fields:{source:`PartSource`}},ContentPart:{discriminator:`type`,variants:{text:`TextPart`,image:`ImagePart`,audio:`AudioPart`,video:`VideoPart`,document:`DocumentPart`}},ToolCallResultEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`role`],fields:{content:{array:`ContentPart`}}},StateSnapshotEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},AddOperation:{optional:[],fields:{}},RemoveOperation:{optional:[],fields:{}},ReplaceOperation:{optional:[],fields:{}},MoveOperation:{optional:[],fields:{}},CopyOperation:{optional:[],fields:{}},TestOperation:{optional:[],fields:{}},JsonPatchOperation:{discriminator:`op`,variants:{add:`AddOperation`,remove:`RemoveOperation`,replace:`ReplaceOperation`,move:`MoveOperation`,copy:`CopyOperation`,test:`TestOperation`}},StateDeltaEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{delta:{array:`JsonPatchOperation`}}},DeveloperMessage:{optional:[`subagentRunId`,`name`,`encryptedValue`,`metadata`],fields:{}},SystemMessage:{optional:[`subagentRunId`,`name`,`encryptedValue`,`metadata`],fields:{}},FunctionCall:{optional:[],fields:{}},ToolCall:{optional:[`encryptedValue`,`metadata`],fields:{function:`FunctionCall`}},AssistantMessage:{optional:[`subagentRunId`,`name`,`encryptedValue`,`metadata`,`content`,`toolCalls`],fields:{toolCalls:{array:`ToolCall`}}},UserMessage:{optional:[`subagentRunId`,`name`,`encryptedValue`,`metadata`],fields:{content:{array:`ContentPart`}}},ToolMessage:{optional:[`subagentRunId`,`error`,`encryptedValue`,`metadata`],fields:{content:{array:`ContentPart`}}},ActivityMessage:{optional:[`subagentRunId`,`metadata`],fields:{}},ReasoningMessage:{optional:[`subagentRunId`,`encryptedValue`,`metadata`],fields:{}},Message:{discriminator:`role`,variants:{developer:`DeveloperMessage`,system:`SystemMessage`,assistant:`AssistantMessage`,user:`UserMessage`,tool:`ToolMessage`,activity:`ActivityMessage`,reasoning:`ReasoningMessage`}},MessagesSnapshotEvent:{optional:[`timestamp`,`rawEvent`,`metadata`],fields:{messages:{array:`Message`}}},ActivitySnapshotEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`replace`],fields:{}},ActivityDeltaEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{patch:{array:`JsonPatchOperation`}}},RawEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`source`],fields:{}},CustomEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},Tool:{optional:[`parameters`,`metadata`],fields:{}},Context:{optional:[],fields:{}},ResumeEntry:{optional:[`payload`,`metadata`],fields:{}},RunAgentInput:{optional:[`protocolVersion`,`parentRunId`,`state`,`tools`,`context`,`forwardedProps`,`resume`],fields:{messages:{array:`Message`},tools:{array:`Tool`},context:{array:`Context`},resume:{array:`ResumeEntry`}}},RunStartedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`protocolVersion`,`parentRunId`,`input`],fields:{input:`RunAgentInput`}},RunFinishedSuccessOutcome:{optional:[`pendingToolCallIds`],fields:{}},Interrupt:{optional:[`subagentRunId`,`message`,`toolCallId`,`responseSchema`,`expiresAt`,`metadata`],fields:{}},RunFinishedInterruptOutcome:{optional:[],fields:{interrupts:{array:`Interrupt`}}},RunFinishedCancelledOutcome:{optional:[],fields:{}},RunFinishedOutcome:{discriminator:`type`,variants:{success:`RunFinishedSuccessOutcome`,interrupt:`RunFinishedInterruptOutcome`,cancelled:`RunFinishedCancelledOutcome`}},TokenUsage:{optional:[`provider`,`model`,`inputTokens`,`outputTokens`,`totalTokens`,`reasoningTokens`,`cachedInputTokens`,`cacheWriteInputTokens`],fields:{}},RunFinishedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`result`,`outcome`,`usage`],fields:{outcome:`RunFinishedOutcome`,usage:{array:`TokenUsage`}}},RunErrorEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`code`,`usage`],fields:{usage:{array:`TokenUsage`}}},StepStartedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},StepFinishedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningStartEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningMessageStartEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningMessageContentEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningMessageEndEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningMessageChunkEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`,`messageId`,`delta`],fields:{}},ReasoningEndEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},ReasoningEncryptedValueEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`subagentRunId`],fields:{}},SubagentStartedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`description`,`parentSubagentRunId`,`parentToolCallId`,`parentMessageId`],fields:{}},SubagentFinishedSuccessOutcome:{optional:[],fields:{}},SubagentFinishedSuspendedOutcome:{optional:[`interruptIds`],fields:{}},SubagentFinishedOutcome:{discriminator:`type`,variants:{success:`SubagentFinishedSuccessOutcome`,suspended:`SubagentFinishedSuspendedOutcome`}},SubagentFinishedEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`result`,`outcome`],fields:{outcome:`SubagentFinishedOutcome`}},SubagentErrorEvent:{optional:[`timestamp`,`rawEvent`,`metadata`,`code`],fields:{}},Event:{discriminator:`type`,variants:{TEXT_MESSAGE_START:`TextMessageStartEvent`,TEXT_MESSAGE_CONTENT:`TextMessageContentEvent`,TEXT_MESSAGE_END:`TextMessageEndEvent`,TEXT_MESSAGE_CHUNK:`TextMessageChunkEvent`,TOOL_CALL_START:`ToolCallStartEvent`,TOOL_CALL_ARGS:`ToolCallArgsEvent`,TOOL_CALL_END:`ToolCallEndEvent`,TOOL_CALL_CHUNK:`ToolCallChunkEvent`,TOOL_CALL_RESULT:`ToolCallResultEvent`,STATE_SNAPSHOT:`StateSnapshotEvent`,STATE_DELTA:`StateDeltaEvent`,MESSAGES_SNAPSHOT:`MessagesSnapshotEvent`,ACTIVITY_SNAPSHOT:`ActivitySnapshotEvent`,ACTIVITY_DELTA:`ActivityDeltaEvent`,RAW:`RawEvent`,CUSTOM:`CustomEvent`,RUN_STARTED:`RunStartedEvent`,RUN_FINISHED:`RunFinishedEvent`,RUN_ERROR:`RunErrorEvent`,STEP_STARTED:`StepStartedEvent`,STEP_FINISHED:`StepFinishedEvent`,REASONING_START:`ReasoningStartEvent`,REASONING_MESSAGE_START:`ReasoningMessageStartEvent`,REASONING_MESSAGE_CONTENT:`ReasoningMessageContentEvent`,REASONING_MESSAGE_END:`ReasoningMessageEndEvent`,REASONING_MESSAGE_CHUNK:`ReasoningMessageChunkEvent`,REASONING_END:`ReasoningEndEvent`,REASONING_ENCRYPTED_VALUE:`ReasoningEncryptedValueEvent`,SUBAGENT_STARTED:`SubagentStartedEvent`,SUBAGENT_FINISHED:`SubagentFinishedEvent`,SUBAGENT_ERROR:`SubagentErrorEvent`}},SubagentInfo:{optional:[`description`],fields:{}},IdentityCapabilities:{optional:[`name`,`type`,`description`,`version`,`provider`,`documentationUrl`,`metadata`],fields:{}},TransportCapabilities:{optional:[`streaming`,`websocket`,`httpBinary`,`pushNotifications`,`resumable`],fields:{}},ToolsCapabilities:{optional:[`supported`,`items`,`parallelCalls`,`clientProvided`],fields:{items:{array:`Tool`}}},OutputCapabilities:{optional:[`structuredOutput`,`supportedMimeTypes`],fields:{}},StateCapabilities:{optional:[`snapshots`,`deltas`,`memory`,`persistentState`],fields:{}},MultiAgentCapabilities:{optional:[`supported`,`delegation`,`handoffs`,`subagents`],fields:{subagents:{array:`SubagentInfo`}}},ReasoningCapabilities:{optional:[`supported`,`streaming`,`encrypted`],fields:{}},MultimodalInputCapabilities:{optional:[`image`,`audio`,`video`,`pdf`,`file`],fields:{}},MultimodalOutputCapabilities:{optional:[`image`,`audio`],fields:{}},MultimodalCapabilities:{optional:[`input`,`output`],fields:{input:`MultimodalInputCapabilities`,output:`MultimodalOutputCapabilities`}},ExecutionCapabilities:{optional:[`codeExecution`,`sandboxed`,`maxIterations`,`maxExecutionTime`],fields:{}},HumanInTheLoopCapabilities:{optional:[`supported`,`approvals`,`interventions`,`feedback`,`interrupts`,`approveWithEdits`],fields:{}},AgentCapabilities:{optional:[`identity`,`transport`,`tools`,`output`,`state`,`multiAgent`,`reasoning`,`multimodal`,`execution`,`humanInTheLoop`,`custom`],fields:{identity:`IdentityCapabilities`,transport:`TransportCapabilities`,tools:`ToolsCapabilities`,output:`OutputCapabilities`,state:`StateCapabilities`,multiAgent:`MultiAgentCapabilities`,reasoning:`ReasoningCapabilities`,multimodal:`MultimodalCapabilities`,execution:`ExecutionCapabilities`,humanInTheLoop:`HumanInTheLoopCapabilities`}}};function Jc(e,t){if(typeof t==`string`)return Jc(e,qc[t]);if(`array`in t){if(!Array.isArray(e))return e;let n=e.map(e=>Jc(e,t.array));return n.every((t,n)=>t===e[n])?e:n}if(typeof e!=`object`||!e||Array.isArray(e))return e;let n=e;if(`discriminator`in t){let r=n[t.discriminator];return typeof r==`string`&&Object.prototype.hasOwnProperty.call(t.variants,r)?Jc(e,t.variants[r]):e}let r=n;for(let e of t.optional)Object.prototype.hasOwnProperty.call(n,e)&&n[e]===null&&(r===n&&(r={...n}),delete r[e]);for(let[e,i]of Object.entries(t.fields)){if(!Object.prototype.hasOwnProperty.call(r,e))continue;let t=Jc(r[e],i);t!==r[e]&&(r===n&&(r={...n}),r[e]=t)}return r}function Yc(e,t){return Jc(e,t)}var R=class extends Error{constructor(e){super(e)}},Xc=class extends R{constructor(){super(`Connect not implemented. This method is not supported by the current agent.`)}};function Zc(e,t){return t===void 0?e:e===void 0?{...t}:{...e,...t}}function Qc(e){return e===void 0?``:typeof e==`string`?e:e.filter(e=>e.type===`text`).map(e=>e.text).join(``)}function $c(e){return Array.isArray(e)&&e.some(e=>e.type!==`text`)}var el=(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})(),tl=Object.prototype.hasOwnProperty;function nl(e,t){return tl.call(e,t)}function rl(e){if(Array.isArray(e)){for(var t=Array(e.length),n=0;n=48&&r<=57){t++;continue}return!1}return!0}function ol(e){return e.indexOf(`/`)===-1&&e.indexOf(`~`)===-1?e:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function sl(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}function cl(e){if(e===void 0)return!0;if(e){if(Array.isArray(e)){for(var t=0,n=e.length;tfl,_areEquals:()=>Sl,applyOperation:()=>_l,applyPatch:()=>vl,applyReducer:()=>yl,deepClone:()=>pl,getValueByPointer:()=>gl,validate:()=>xl,validator:()=>bl}),fl=ul,pl=il,ml={add:function(e,t,n){return e[t]=this.value,{newDocument:n}},remove:function(e,t,n){var r=e[t];return delete e[t],{newDocument:n,removed:r}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:function(e,t,n){var r=gl(n,this.path);r&&=il(r);var i=_l(n,{op:`remove`,path:this.from}).removed;return _l(n,{op:`add`,path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(e,t,n){var r=gl(n,this.from);return _l(n,{op:`add`,path:this.path,value:il(r)}),{newDocument:n}},test:function(e,t,n){return{newDocument:n,test:Sl(e[t],this.value)}},_get:function(e,t,n){return this.value=e[t],{newDocument:n}}},hl={add:function(e,t,n){return al(t)?e.splice(t,0,this.value):e[t]=this.value,{newDocument:n,index:t}},remove:function(e,t,n){return{newDocument:n,removed:e.splice(t,1)[0]}},replace:function(e,t,n){var r=e[t];return e[t]=this.value,{newDocument:n,removed:r}},move:ml.move,copy:ml.copy,test:ml.test,_get:ml._get};function gl(e,t){if(t==``)return e;var n={op:`_get`,path:t};return _l(e,n),n.value}function _l(e,t,n,r,i,a){if(n===void 0&&(n=!1),r===void 0&&(r=!0),i===void 0&&(i=!0),a===void 0&&(a=0),n&&(typeof n==`function`?n(t,0,e,t.path):bl(t,0)),t.path===``){var o={newDocument:e};if(t.op===`add`)return o.newDocument=t.value,o;if(t.op===`replace`)return o.newDocument=t.value,o.removed=e,o;if(t.op===`move`||t.op===`copy`)return o.newDocument=gl(e,t.from),t.op===`move`&&(o.removed=e),o;if(t.op===`test`){if(o.test=Sl(e,t.value),o.test===!1)throw new fl(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o.newDocument=e,o}if(t.op===`remove`)return o.removed=e,o.newDocument=null,o;if(t.op===`_get`)return t.value=e,o;if(n)throw new fl("Operation `op` property is not one of operations defined in RFC-6902",`OPERATION_OP_INVALID`,a,t,e);return o}r||(e=il(e));var s=(t.path||``).split(`/`),c=e,l=1,u=s.length,d=void 0,f=void 0,p=void 0;for(p=typeof n==`function`?n:bl;;){if(f=s[l],f&&f.indexOf(`~`)!=-1&&(f=sl(f)),i&&(f==`__proto__`||f==`prototype`&&l>0&&s[l-1]==`constructor`))throw TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&d===void 0&&(c[f]===void 0?d=s.slice(0,l).join(`/`):l==u-1&&(d=t.path),d!==void 0&&p(t,0,e,d)),l++,Array.isArray(c)){if(f===`-`)f=c.length;else if(n&&!al(f))throw new fl(`Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index`,`OPERATION_PATH_ILLEGAL_ARRAY_INDEX`,a,t,e);else al(f)&&(f=~~f);if(l>=u){if(n&&t.op===`add`&&f>c.length)throw new fl(`The specified index MUST NOT be greater than the number of elements in the array`,`OPERATION_VALUE_OUT_OF_BOUNDS`,a,t,e);var o=hl[t.op].call(t,c,f,e);if(o.test===!1)throw new fl(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}}else if(l>=u){var o=ml[t.op].call(t,c,f,e);if(o.test===!1)throw new fl(`Test operation failed`,`TEST_OPERATION_FAILED`,a,t,e);return o}if(c=c[f],n&&l0)throw new fl('Operation `path` property must start with "/"',`OPERATION_PATH_INVALID`,t,e,n);if((e.op===`move`||e.op===`copy`)&&typeof e.from!=`string`)throw new fl("Operation `from` property is not present (applicable in `move` and `copy` operations)",`OPERATION_FROM_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&e.value===void 0)throw new fl("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_REQUIRED`,t,e,n);if((e.op===`add`||e.op===`replace`||e.op===`test`)&&cl(e.value))throw new fl("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)",`OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED`,t,e,n);if(n){if(e.op==`add`){var i=e.path.split(`/`).length,a=r.split(`/`).length;if(i!==a+1&&i!==a)throw new fl("Cannot perform an `add` operation at the desired path",`OPERATION_PATH_CANNOT_ADD`,t,e,n)}else if(e.op===`replace`||e.op===`remove`||e.op===`_get`){if(e.path!==r)throw new fl(`Cannot perform the operation at a path that does not exist`,`OPERATION_PATH_UNRESOLVABLE`,t,e,n)}else if(e.op===`move`||e.op===`copy`){var o=xl([{op:`_get`,path:e.from,value:void 0}],n);if(o&&o.name===`OPERATION_PATH_UNRESOLVABLE`)throw new fl(`Cannot perform the operation from a path that does not exist`,`OPERATION_FROM_UNRESOLVABLE`,t,e,n)}}}function xl(e,t,n){try{if(!Array.isArray(e))throw new fl(`Patch sequence must be an array`,`SEQUENCE_NOT_AN_ARRAY`);if(t)vl(il(t),il(e),n||!0);else{n||=bl;for(var r=0;rPl,generate:()=>Ml,observe:()=>jl,unobserve:()=>Al}),wl=new WeakMap,Tl=function(){function e(e){this.observers=new Map,this.obj=e}return e}(),El=function(){function e(e,t){this.callback=e,this.observer=t}return e}();function Dl(e){return wl.get(e)}function Ol(e,t){return e.observers.get(t)}function kl(e,t){e.observers.delete(t.callback)}function Al(e,t){t.unobserve()}function jl(e,t){var n=[],r,i=Dl(e);if(!i)i=new Tl(e),wl.set(e,i);else{var a=Ol(i,t);r=a&&a.observer}if(r)return r;if(r={},i.value=il(e),t){r.callback=t,r.next=null;var o=function(){Ml(r)},s=function(){clearTimeout(r.next),r.next=setTimeout(o)};typeof window<`u`&&(window.addEventListener(`mouseup`,s),window.addEventListener(`keyup`,s),window.addEventListener(`mousedown`,s),window.addEventListener(`keydown`,s),window.addEventListener(`change`,s))}return r.patches=n,r.object=e,r.unobserve=function(){Ml(r),clearTimeout(r.next),kl(i,r),typeof window<`u`&&(window.removeEventListener(`mouseup`,s),window.removeEventListener(`keyup`,s),window.removeEventListener(`mousedown`,s),window.removeEventListener(`keydown`,s),window.removeEventListener(`change`,s))},i.observers.set(t,new El(t,r)),r}function Ml(e,t){t===void 0&&(t=!1);var n=wl.get(e.object);Nl(n.value,e.object,e.patches,``,t),e.patches.length&&vl(n.value,e.patches);var r=e.patches;return r.length>0&&(e.patches=[],e.callback&&e.callback(r)),r}function Nl(e,t,n,r,i){if(t!==e){typeof t.toJSON==`function`&&(t=t.toJSON());for(var a=rl(t),o=rl(e),s=!1,c=o.length-1;c>=0;c--){var l=o[c],u=e[l];if(nl(t,l)&&(t[l]!==void 0||u===void 0||Array.isArray(t)!==!1)){var d=t[l];typeof u==`object`&&u&&typeof d==`object`&&d&&Array.isArray(u)===Array.isArray(d)?Nl(u,d,n,r+`/`+ol(l),i):u!==d&&(i&&n.push({op:`test`,path:r+`/`+ol(l),value:il(u)}),n.push({op:`replace`,path:r+`/`+ol(l),value:il(d)}))}else Array.isArray(e)===Array.isArray(t)?(i&&n.push({op:`test`,path:r+`/`+ol(l),value:il(u)}),n.push({op:`remove`,path:r+`/`+ol(l)}),s=!0):(i&&n.push({op:`test`,path:r,value:e}),n.push({op:`replace`,path:r,value:t}))}if(s||a.length!=o.length)for(var c=0;c0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Vl(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function Hl(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof Ul?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function Gl(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Bl==`function`?Bl(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function Kl(e){return typeof e==`function`}function ql(e){var t=e(function(e){Error.call(e),e.stack=Error().stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Jl=ql(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription: +`+t.map(function(e,t){return t+1+`) `+e.toString()}).join(` + `):``,this.name=`UnsubscriptionError`,this.errors=t}});function Yl(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var Xl=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var e,t,n,r,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a){if(this._parentage=null,Array.isArray(a))try{for(var o=Bl(a),s=o.next();!s.done;s=o.next())s.value.remove(this)}catch(t){e={error:t}}finally{try{s&&!s.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else a.remove(this)}var c=this.initialTeardown;if(Kl(c))try{c()}catch(e){i=e instanceof Jl?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var u=Bl(l),d=u.next();!d.done;d=u.next()){var f=d.value;try{$l(f)}catch(e){i??=[],e instanceof Jl?i=Hl(Hl([],Vl(i)),Vl(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}}if(i)throw new Jl(i)}},e.prototype.add=function(t){if(t&&t!==this){if(this.closed)$l(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=this._finalizers??[]).push(t)}}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Yl(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&Yl(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e}(),Zl=Xl.EMPTY;function Ql(e){return e instanceof Xl||e&&`closed`in e&&Kl(e.remove)&&Kl(e.add)&&Kl(e.unsubscribe)}function $l(e){Kl(e)?e():e.unsubscribe()}var eu={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},tu={setTimeout:function(e,t){var n=[...arguments].slice(2),r=tu.delegate;return r?.setTimeout?r.setTimeout.apply(r,Hl([e,t],Vl(n))):setTimeout.apply(void 0,Hl([e,t],Vl(n)))},clearTimeout:function(e){return(tu.delegate?.clearTimeout||clearTimeout)(e)},delegate:void 0};function nu(e){tu.setTimeout(function(){var t=eu.onUnhandledError;if(t)t(e);else throw e})}function ru(){}var iu=(function(){return su(`C`,void 0,void 0)})();function au(e){return su(`E`,void 0,e)}function ou(e){return su(`N`,e,void 0)}function su(e,t,n){return{kind:e,value:t,error:n}}var cu=null;function lu(e){if(eu.useDeprecatedSynchronousErrorHandling){var t=!cu;if(t&&(cu={errorThrown:!1,error:null}),e(),t){var n=cu,r=n.errorThrown,i=n.error;if(cu=null,r)throw i}}else e()}function uu(e){eu.useDeprecatedSynchronousErrorHandling&&cu&&(cu.errorThrown=!0,cu.error=e)}var du=function(e){Ll(t,e);function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Ql(t)&&t.add(n)):n.destination=yu,n}return t.create=function(e,t,n){return new hu(e,t,n)},t.prototype.next=function(e){this.isStopped?vu(ou(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?vu(au(e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?vu(iu,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(Xl),fu=Function.prototype.bind;function pu(e,t){return fu.call(e,t)}var mu=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){gu(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){gu(e)}else gu(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){gu(e)}},e}(),hu=function(e){Ll(t,e);function t(t,n,r){var i=e.call(this)||this,a;if(Kl(t)||!t)a={next:t??void 0,error:n??void 0,complete:r??void 0};else{var o;i&&eu.useDeprecatedNextContext?(o=Object.create(t),o.unsubscribe=function(){return i.unsubscribe()},a={next:t.next&&pu(t.next,o),error:t.error&&pu(t.error,o),complete:t.complete&&pu(t.complete,o)}):a=t}return i.destination=new mu(a),i}return t}(du);function gu(e){eu.useDeprecatedSynchronousErrorHandling?uu(e):nu(e)}function _u(e){throw e}function vu(e,t){var n=eu.onStoppedNotification;n&&tu.setTimeout(function(){return n(e,t)})}var yu={closed:!0,next:ru,error:_u,complete:ru},bu=(function(){return typeof Symbol==`function`&&Symbol.observable||`@@observable`})();function xu(e){return e}function Su(){return Cu([...arguments])}function Cu(e){return e.length===0?xu:e.length===1?e[0]:function(t){return e.reduce(function(e,t){return t(e)},t)}}var wu=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r=this,i=Du(e)?e:new hu(e,t,n);return lu(function(){var e=r,t=e.operator,n=e.source;i.add(t?t.call(i,n):n?r._subscribe(i):r._trySubscribe(i))}),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return t=Tu(t),new t(function(t,r){var i=new hu({next:function(t){try{e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:t});n.subscribe(i)})},e.prototype._subscribe=function(e){return this.source?.subscribe(e)},e.prototype[bu]=function(){return this},e.prototype.pipe=function(){return Cu([...arguments])(this)},e.prototype.toPromise=function(e){var t=this;return e=Tu(e),new e(function(e,n){var r;t.subscribe(function(e){return r=e},function(e){return n(e)},function(){return e(r)})})},e.create=function(t){return new e(t)},e}();function Tu(e){return e??eu.Promise??Promise}function Eu(e){return e&&Kl(e.next)&&Kl(e.error)&&Kl(e.complete)}function Du(e){return e&&e instanceof du||Eu(e)&&Ql(e)}function Ou(e){return Kl(e?.lift)}function ku(e){return function(t){if(Ou(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw TypeError(`Unable to lift unknown Observable type`)}}function Au(e,t,n,r,i){return new ju(e,t,n,r,i)}var ju=function(e){Ll(t,e);function t(t,n,r,i,a,o){var s=e.call(this,t)||this;return s.onFinalize=a,s.shouldUnsubscribe=o,s._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,s._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,s._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,s}return t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)==null||t.call(this))}},t}(du),Mu=ql(function(e){return function(){e(this),this.name=`ObjectUnsubscribedError`,this.message=`object unsubscribed`}}),Nu=function(e){Ll(t,e);function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return t.prototype.lift=function(e){var t=new Pu(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new Mu},t.prototype.next=function(e){var t=this;lu(function(){var n,r;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||=Array.from(t.observers);try{for(var i=Bl(t.currentObservers),a=i.next();!a.done;a=i.next())a.value.next(e)}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}})},t.prototype.error=function(e){var t=this;lu(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var n=t.observers;n.length;)n.shift().error(e)}})},t.prototype.complete=function(){var e=this;lu(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){return this.observers?.length>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,n=this,r=n.hasError,i=n.isStopped,a=n.observers;return r||i?Zl:(this.currentObservers=null,a.push(e),new Xl(function(){t.currentObservers=null,Yl(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,n=t.hasError,r=t.thrownError,i=t.isStopped;n?e.error(r):i&&e.complete()},t.prototype.asObservable=function(){var e=new wu;return e.source=this,e},t.create=function(e,t){return new Pu(e,t)},t}(wu),Pu=function(e){Ll(t,e);function t(t,n){var r=e.call(this)||this;return r.destination=t,r.source=n,r}return t.prototype.next=function(e){var t,n;(n=(t=this.destination)?.next)==null||n.call(t,e)},t.prototype.error=function(e){var t,n;(n=(t=this.destination)?.error)==null||n.call(t,e)},t.prototype.complete=function(){var e,t;(t=(e=this.destination)?.complete)==null||t.call(e)},t.prototype._subscribe=function(e){return this.source?.subscribe(e)??Zl},t}(Nu),Fu={now:function(){return(Fu.delegate||Date).now()},delegate:void 0},Iu=function(e){Ll(t,e);function t(t,n,r){t===void 0&&(t=1/0),n===void 0&&(n=1/0),r===void 0&&(r=Fu);var i=e.call(this)||this;return i._bufferSize=t,i._windowTime=n,i._timestampProvider=r,i._buffer=[],i._infiniteTimeWindow=!0,i._infiniteTimeWindow=n===1/0,i._bufferSize=Math.max(1,t),i._windowTime=Math.max(1,n),i}return t.prototype.next=function(t){var n=this,r=n.isStopped,i=n._buffer,a=n._infiniteTimeWindow,o=n._timestampProvider,s=n._windowTime;r||(i.push(t),!a&&i.push(o.now()+s)),this._trimBuffer(),e.prototype.next.call(this,t)},t.prototype._subscribe=function(e){this._throwIfClosed(),this._trimBuffer();for(var t=this._innerSubscribe(e),n=this,r=n._infiniteTimeWindow,i=n._buffer.slice(),a=0;a=0}function Id(e){for(var t=[`topLevel`],n=0,r,i,a,o=function(e){return t.push(e)},s=function(e){return t[t.length-1]=e},c=function(e){r??(r=n,i=t.length,a=e)},l=function(e){e===a&&(r=void 0,i=void 0,a=void 0)},u=function(){return t.pop()},d=function(){return n--},f=function(e){if(`0`<=e&&e<=`9`){o(`number`);return}switch(e){case`"`:o(`string`);return;case`-`:o(`numberNeedsDigit`);return;case`t`:o(`true`);return;case`f`:o(`false`);return;case`n`:o(`null`);return;case`[`:o(`arrayNeedsValue`);return;case`{`:o(`objectNeedsKey`);return}},p=e.length;n`9`)&&(d(),u());break;case`numberNeedsDigit`:s(`number`);break;case`numberNeedsExponent`:s(m===`+`||m===`-`?`numberNeedsDigit`:`number`);break;case`true`:case`false`:case`null`:(m<`a`||m>`z`)&&(d(),u());break;case`arrayNeedsValue`:m===`]`?u():Fd(m)||(l(`collectionItem`),s(`arrayNeedsComma`),f(m));break;case`arrayNeedsComma`:m===`]`?u():m===`,`&&(c(`collectionItem`),s(`arrayNeedsValue`));break;case`objectNeedsKey`:m===`}`?u():m===`"`&&(c(`collectionItem`),s(`objectNeedsColon`),o(`string`));break;case`objectNeedsColon`:m===`:`&&s(`objectNeedsValue`);break;case`objectNeedsValue`:Fd(m)||(l(`collectionItem`),s(`objectNeedsComma`),f(m));break;case`objectNeedsComma`:m===`}`?u():m===`,`&&(c(`collectionItem`),s(`objectNeedsKey`))}}i!=null&&(t.length=i);for(var h=[r==null?e:e.slice(0,r)],g=function(t){return h.push(t.slice(e.length-e.lastIndexOf(t[0])))},_=t.length-1;_>=0;_--)switch(t[_]){case`string`:h.push(`"`);break;case`numberNeedsDigit`:case`numberNeedsExponent`:h.push(`0`);break;case`true`:g(`true`);break;case`false`:g(`false`);break;case`null`:g(`null`);break;case`arrayNeedsValue`:case`arrayNeedsComma`:h.push(`]`);break;case`objectNeedsKey`:case`objectNeedsColon`:case`objectNeedsValue`:case`objectNeedsComma`:h.push(`}`)}return h.join(``)}function Ld(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Rd(e,t=`|`){return e.map(e=>ff(e)).join(t)}function zd(e,t){return typeof t==`bigint`?t.toString():t}var Bd=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function Vd(e){return new Bd(e)}function Hd(e){return e==null}function Ud(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Wd(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r){let e=t._zod.def.shape[a];return r?r(e,a):e}):Zd(e,a,r?r(n.value,a):n.value))}}function $d(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Xd(e,n,()=>t[n]):Zd(e,n,r.value))}}function ef(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function tf(e){return JSON.stringify(e)}function nf(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var rf=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function af(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var of=Vd(()=>{if(np.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function sf(e){if(af(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return af(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function cf(e){return sf(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var lf=new Set([`string`,`number`,`symbol`]);function uf(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function df(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function B(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function ff(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function pf(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}var mf={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},hf={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]};function gf(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return Qd(i,e,_f(e,t)),df(e,ef(n,{shape:i,checks:[]}))}function _f(e,t){let n=Yd(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function vf(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(_f(e,t)),a={};return Qd(a,e,Reflect.ownKeys(Yd(e)).filter(e=>!i.has(e))),df(e,ef(n,{shape:a,checks:[]}))}function yf(e,t){if(!sf(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=Yd(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return df(e,ef(e._zod.def,{shape:bf(e,t)}))}function bf(e,t){let n={};return Qd(n,e,Reflect.ownKeys(Yd(e))),$d(n,t),n}function xf(e,t){if(!sf(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return df(e,ef(e._zod.def,{shape:bf(e,t)}))}function Sf(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return Qd(n,e,Reflect.ownKeys(Yd(e))),Qd(n,t,Reflect.ownKeys(Yd(t))),df(e,ef(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function Cf(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(_f(t,n)):void 0,o={};return Qd(o,t,Reflect.ownKeys(Yd(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),df(t,ef(t._zod.def,{shape:o,checks:[]}))}function wf(e,t,n){let r=n?new Set(_f(t,n)):void 0,i={};return Qd(i,t,Reflect.ownKeys(Yd(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),df(t,ef(t._zod.def,{shape:i}))}function Tf(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function Of(e){return typeof e==`string`?e:e?.message}function kf(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function Af(e,t,n){var r;for(let i=t;ie;return t[Jf]=!0,t}var Xf,Zf=Object.freeze({status:`aborted`}),Qf={value:void 0,enumerable:!1},V=`captureStackTrace`in Error?Error:null;function $f(e){let t=V;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return V=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function H(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){Qf.value=new a(r);try{Object.defineProperty(n,"_zod",Qf)}finally{Qf.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),Lf(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?$f(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var ep=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},tp=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Xf=globalThis).__zod_globalConfig??(Xf.__zod_globalConfig={});var np=globalThis.__zod_globalConfig;function rp(e){return e&&Object.assign(np,e),np}function ip(){let e=this._zod;return e.message??=JSON.stringify(e.def,zd,2),e.message}function ap(e){this._zod.message=e}var op={get:ip,set:ap,enumerable:!0,configurable:!0},sp={value:void 0,enumerable:!1},cp=new WeakSet([Object.prototype,Error.prototype]),lp=(e,t)=>{e.name=`$ZodError`,sp.value=t,Object.defineProperty(e,"issues",sp),sp.value=void 0,Object.defineProperty(e,"message",op);let n=Object.getPrototypeOf(e);cp.has(n)||(cp.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},up=H(`$ZodError`,lp);H(`$ZodError`,lp,void 0,{Parent:Error});function dp(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function fp(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?dp(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function pp(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new ep;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>jf(e,o,rp())));throw rf(n,a?.callee??t),n}return s.value};return t},gp=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>jf(e,o,rp())));throw rf(n,a?.callee??t),n}return s.value};return t},_p=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new ep;return a.issues.length?vp(e,a.issues,i):{success:!0,data:a.value}};function vp(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>jf(e,n,rp()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var yp=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?vp(e,a.issues,i):{success:!0,data:a.value}},bp=Symbol.for(`zod.compile.invalid`),xp=Symbol.for(`zod.compile.fallback`),Sp=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==bp)return!0;if(r.definite===!0&&n===void 0)return!1}return Cp(e,t,n)});function Cp(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[xp]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new ep;return a.issues.length===0}var wp=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},Tp=e=>{let t=hp(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,mp(n,a))};return n},Ep=e=>{let t=hp(e),n=(e,r,i,a)=>t(e,r,i,mp(n,a));return n},Dp=e=>{let t=gp(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,mp(n,a))};return n},Op=e=>{let t=gp(e),n=async(e,r,i,a)=>await t(e,r,i,mp(n,a));return n},kp=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return _p(e)(t,n,i)},Ap=e=>(t,n,r)=>_p(e)(t,n,r),jp=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return yp(e)(t,n,i)},Mp=e=>async(t,n,r)=>yp(e)(t,n,r),Np=/^[cC][0-9a-z]{6,}$/,Pp=/^[0-9a-z]+$/,Fp=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Ip=/^[0-9a-vA-V]{20}$/,Lp=/^[A-Za-z0-9]{27}$/,Rp=/^[a-zA-Z0-9_-]{21}$/;function zp(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var Bp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Vp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Hp=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Up=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Wp=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;function Gp(){return new RegExp(Wp,`u`)}var Kp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,qp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Jp=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Yp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Xp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Zp=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Qp=/^https?$/,$p=/^\+[1-9]\d{6,14}$/,em=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function tm(e){return RegExp(`^${e}$`)}var nm=tm(em);function rm(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function im(e){return RegExp(`^${rm(e)}$`)}function am(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${rm({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${rm({precision:e.precision})}`:n;return RegExp(`^${em}T(?:${r})$`)}var om=/^[\s\S]{0,}$/,sm=/^-?\d+$/,cm=/^-?\d+(?:\.\d+)?$/,lm=/^(?:true|false)$/i,um=/^null$/i,dm=/^undefined$/i,fm=/^[^A-Z]*$/,pm=/^[^a-z]*$/,mm=H(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),hm=e=>{let t=e.value;return!Hd(t)&&t.length!==void 0},gm={number:`number`,bigint:`bigint`,object:`date`},_m=H(`$ZodCheckLessThan`,(e,t)=>{mm.init(e,t);let n=gm[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value{mm.init(e,t);let n=gm[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:gm[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ym=H(`$ZodCheckMultipleOf`,(e,t)=>{mm.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Wd(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),bm=H(`$ZodCheckNumberFormat`,(e,t)=>{mm.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=mf[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}sa&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),xm=H(`$ZodCheckMaxLength`,(e,t)=>{var n;mm.init(e,t),(n=e._zod.def).when??(n.when=hm),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?Nf(r):i)<=t.maximum)return;let a=Pf(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Sm=H(`$ZodCheckMinLength`,(e,t)=>{var n;mm.init(e,t),(n=e._zod.def).when??(n.when=hm),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i=t.minimum)return;let a=Pf(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),Cm=H(`$ZodCheckLengthEquals`,(e,t)=>{var n;mm.init(e,t),(n=e._zod.def).when??(n.when=hm),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?Nf(r):i;if(a===t.length)return;let o=Pf(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),wm=H(`$ZodCheckStringFormat`,(e,t)=>{var n,r;mm.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),Tm=H(`$ZodCheckRegex`,(e,t)=>{wm.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Em=H(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=fm,wm.init(e,t)}),Dm=H(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=pm,wm.init(e,t)}),Om=H(`$ZodCheckIncludes`,(e,t)=>{mm.init(e,t);let n=uf(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),km=H(`$ZodCheckStartsWith`,(e,t)=>{mm.init(e,t);let n=RegExp(`^${uf(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Am=H(`$ZodCheckEndsWith`,(e,t)=>{mm.init(e,t);let n=RegExp(`.*${uf(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),jm=H(`$ZodCheckOverwrite`,(e,t)=>{mm.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),Mm=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` +`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(` +`)}\n};`)(...Object.values(this.closed))}},Nm={major:4,minor:6,patch:6},Pm=H(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Nm;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=Tf(t),a;for(let o of n){if(o._zod.def.when){if(Ef(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new ep;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(Af(t.issues,n,e),i||=Tf(t,n))});else{if(t.issues.length===n)continue;Af(t.issues,n,e),i||=Tf(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(Tf(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new ep;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new ep;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return zf(this,`~standard`,Lm(this))},set"~standard"(e){Rf(this,`~standard`,e)}}),Fm=(e,t)=>e.issues.length?{issues:e.issues.map(e=>jf(e,t,rp()))}:{value:e.value};async function Im(e,t){let n={async:!0};return Fm(await e._zod.run({value:t,issues:[]},n),n)}function Lm(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return Fm(r,n)}catch{}return Im(e,t)},vendor:`zod`,version:1}}var Rm=H(`$ZodString`,(e,t)=>{Pm.init(e,t),e._zod.pattern=t.pattern??om,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),zm=H(`$ZodStringFormat`,(e,t)=>{wm.init(e,t),Rm.init(e,t)}),Bm=H(`$ZodGUID`,(e,t)=>{t.pattern??=Vp,zm.init(e,t)}),Vm=H(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Hp(e)}else t.pattern??=Hp();zm.init(e,t)}),Hm=H(`$ZodEmail`,(e,t)=>{t.pattern??=Up,zm.init(e,t)});function Um(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function Wm(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?Um(e)||2:Gm(e,t)}function Gm(e,t){if(!t.normalize&&t.protocol?.source===Qp.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}var Km=/[\t\n\r]/g;function qm(e){return e.replace(Km,``)}function Jm(e,t){return t.lastIndex=0,t.test(e.hostname)}function Ym(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}var Xm=H(`$ZodURL`,(e,t)=>{zm.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=Wm(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=qm(r);return}t.hostname&&!Jm(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!Ym(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:qm(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Zm=H(`$ZodEmoji`,(e,t)=>{t.pattern??=Gp(),zm.init(e,t)}),Qm=H(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?Rp:zp(t.length),zm.init(e,t)}),$m=H(`$ZodCUID`,(e,t)=>{t.pattern??=Np,zm.init(e,t)}),eh=H(`$ZodCUID2`,(e,t)=>{t.pattern??=Pp,zm.init(e,t)}),th=H(`$ZodULID`,(e,t)=>{t.pattern??=Fp,zm.init(e,t)}),nh=H(`$ZodXID`,(e,t)=>{t.pattern??=Ip,zm.init(e,t)}),rh=H(`$ZodKSUID`,(e,t)=>{t.pattern??=Lp,zm.init(e,t)}),ih=H(`$ZodISODateTime`,(e,t)=>{t.pattern??=am(t),zm.init(e,t)}),ah=H(`$ZodISODate`,(e,t)=>{t.pattern??=nm,zm.init(e,t)}),oh=H(`$ZodISOTime`,(e,t)=>{t.pattern??=im(t),zm.init(e,t)}),sh=H(`$ZodISODuration`,(e,t)=>{t.pattern??=Bp,zm.init(e,t)}),ch=H(`$ZodIPv4`,(e,t)=>{t.pattern??=Kp,zm.init(e,t)}),lh=/^[0-9a-fA-F:.]+$/;function uh(e){return lh.test(e)?Um(`http://[${e}]`):!1}var dh=H(`$ZodIPv6`,(e,t)=>{t.pattern??=qp,zm.init(e,t),e._zod.check=n=>{uh(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),fh=H(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Jp,zm.init(e,t)});function ph(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:uh(n)}var mh=H(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Yp,zm.init(e,t),e._zod.check=n=>{ph(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function hh(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var gh=/^[0-9a-zA-Z+/]*={0,2}$/,_h=H(`$ZodBase64`,(e,t)=>{t.pattern??=gh,zm.init(e,t),e._zod.check=n=>{hh(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),vh=/^[A-Za-z0-9_-]*$/;function yh(e){if(!vh.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return hh(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var bh=H(`$ZodBase64URL`,(e,t)=>{t.pattern??=vh,zm.init(e,t),e._zod.check=n=>{yh(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),xh=H(`$ZodE164`,(e,t)=>{t.pattern??=$p,zm.init(e,t)});function Sh(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var Ch=H(`$ZodJWT`,(e,t)=>{zm.init(e,t),e._zod.check=n=>{Sh(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),wh=H(`$ZodNumber`,(e,t)=>{Pm.init(e,t),e._zod.pattern=cm,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Th=H(`$ZodNumberFormat`,(e,t)=>{bm.init(e,t),wh.init(e,t)}),Eh=H(`$ZodBoolean`,(e,t)=>{Pm.init(e,t),e._zod.pattern=lm,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),Dh=H(`$ZodUndefined`,(e,t)=>{Pm.init(e,t),e._zod.pattern=dm,e._zod.values=new Set([void 0]),e._zod.parse=(t,n)=>{let r=t.value;return r===void 0||t.issues.push({expected:`undefined`,code:`invalid_type`,input:r,inst:e}),t}}),Oh=H(`$ZodNull`,(e,t)=>{Pm.init(e,t),e._zod.pattern=um,e._zod.values=new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),kh=H(`$ZodAny`,(e,t)=>{Pm.init(e,t),e._zod.parse=e=>e}),Ah=H(`$ZodUnknown`,(e,t)=>{Pm.init(e,t),e._zod.parse=e=>e}),jh=H(`$ZodNever`,(e,t)=>{Pm.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function Mh(e,t){let n=kf(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of kf(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,Af(n.issues,t,e),n}}return i(n,a)}}var Nh=e=>Array.isArray(e)?e.length:-1;function Ph(e,t,n){e.issues.length&&t.issues.push(...Df(n,e.issues)),t.value[n]=e.value}var Fh=H(`$ZodArray`,(e,t)=>{Pm.init(e,t);let n=np.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;ePh(t,r,e)));else if(Ph(c,r,e),s&&c.issues.length!==0&&Tf(c))break}return o.length?Promise.all(o).then(()=>r):r},Mh(e,Nh)});function Ih(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...Df(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}var Lh=[];function Rh(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:Lh,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=pf(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function zh(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(Tf(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>Ih(e,n,i,t,d,f))):Ih(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var Bh=H(`$ZodObject`,(e,t)=>{Pm.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=Vd(()=>Rh(t));Kf(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||qd(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=af,o=t.catchall,s,c=np.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(Tf(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>Ih(n,t,e,r,a,o))):Ih(s,t,e,r,a,o)}return o?zh(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),Vh=H(`$ZodObjectJIT`,(e,t)=>{Bh.init(e,t);let n=e._zod.parse,r=Vd(()=>Rh(t)),i=np.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new Mm([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>` + let ${e}_ab = false; + for (let i = 0; i < ${e}.issues.length; i++) { + const iss = ${e}.issues[i]; + iss.path = iss.path ? [${t}, ...iss.path] : [${t}]; + payload.issues.push(iss); + if (iss.continue !== true) ${e}_ab = true; + } + if (${e}_ab && ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + }`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:tf(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(` + const ${n}_present = ${i}; + if (!${n}.issues.length || ${n}_present) { + if (${n}.issues.length) {${c(n,r)} + } + + if (${e}) { + newResult[${r}] = ${n}.value; + } + } + + `)}else f?(o.write(` + if (${n}.issues.length) {${c(n,r)} + } + `),d===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(` + if (${n}.value !== undefined || ${i}) { + newResult[${r}] = ${n}.value; + } + `)):o.write(` + const ${n}_present = ${i}; + if (${n}.issues.length) {${c(n,r)} + } + if (!${n}_present && !${n}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${r}] + }); + if (ctx && ctx.abortEarly) { + payload.value = newResult; + return payload; + } + } + + if (${n}_present) { + newResult[${r}] = ${n}.value; + } + + `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=af,c=!np.jitless,l=c&&of.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?zh([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function Hh(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!Tf(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>jf(e,r,rp())))}),t)}var Uh=H(`$ZodUnion`,(e,t)=>{Pm.init(e,t),Kf(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),Kf(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),Kf(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),Kf(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Ud(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>Hh(t,r,e,i)):Hh(o,r,e,i)}});function Wh(e){let t=new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}var Gh=H(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Uh.init(e,t);let n=e._zod.parse;Kf(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||qd(t,e,new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=Jd(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=Vd(()=>Wh(t));e._zod.parse=(i,a)=>{let o=i.value;if(!af(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),Kh=H(`$ZodIntersection`,(e,t)=>{Pm.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>Jh(e,t,n)):Jh(e,i,a)}});function qh(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(sf(e)&&sf(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=qh(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=qh(t.value,n.value);if(!c.valid){if(Tf(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Yh=H(`$ZodRecord`,(e,t)=>{Pm.init(e,t);let n=np.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!sf(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>jf(e,i,rp())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...Df(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...Df(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&cm.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>jf(e,i,rp())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...Df(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...Df(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Xh=H(`$ZodEnum`,(e,t)=>{Pm.init(e,t);let n=Ld(t.entries),r=new Set(n);e._zod.values=r,Kf(e,`pattern`,e=>{let t=Ld(e.def.entries).filter(e=>lf.has(typeof e));return RegExp(t.length?`^(${t.map(e=>uf(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Zh=H(`$ZodLiteral`,(e,t)=>{Pm.init(e,t);let n=new Set(t.values);e._zod.values=n,Kf(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?uf(e):e?uf(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Qh=H(`$ZodTransform`,(e,t)=>{Pm.init(e,t),e._zod.optin=`optional`,np.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new tp(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new ep;return n.value=i,n}});function $h(e,t){return e.value=t.issues.length?void 0:t.value,e}var eg=H(`$ZodOptional`,(e,t)=>{Pm.init(e,t),Kf(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,Kf(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),Kf(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ud(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>$h(e,t)):$h(e,r)}return t.innerType._zod.run(e,n)}}),tg=H(`$ZodExactOptional`,(e,t)=>{eg.init(e,t),Kf(e,`values`,e=>e.def.innerType._zod.values),Kf(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),ng=H(`$ZodNullable`,(e,t)=>{Pm.init(e,t),Kf(e,`optin`,e=>e.def.innerType._zod.optin),Kf(e,`optout`,e=>e.def.innerType._zod.optout),Kf(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ud(t.source)}|null)$`):void 0}),Kf(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),rg=H(`$ZodDefault`,(e,t)=>{Pm.init(e,t),e._zod.optin=`defaulted`,Kf(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>ig(e,t)):ig(r,t)}});function ig(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var ag=H(`$ZodPrefault`,(e,t)=>{Pm.init(e,t),e._zod.optin=`defaulted`,Kf(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),og=H(`$ZodNonOptional`,(e,t)=>{Pm.init(e,t),Kf(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>sg(t,e)):sg(i,e)}});function sg(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function cg(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>jf(e,r,rp()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var lg=H(`$ZodCatch`,(e,t)=>{Pm.init(e,t),Kf(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),Kf(e,`optout`,e=>e.def.innerType._zod.optout),Kf(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>cg(e,r,t,n)):cg(e,r,t,n)}}),ug=H(`$ZodPipe`,(e,t)=>{Pm.init(e,t),Kf(e,`values`,e=>e.def.in._zod.values),Kf(e,`optin`,e=>e.def.in._zod.optin),Kf(e,`optout`,e=>e.def.out._zod.optout),Kf(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>dg(e,t.in,n)):dg(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>dg(e,t.out,n)):dg(r,t.out,n)}});function dg(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var fg=H(`$ZodPreprocess`,(e,t)=>{ug.init(e,t)}),pg=H(`$ZodReadonly`,(e,t)=>{Pm.init(e,t),Kf(e,`propValues`,e=>e.def.innerType._zod.propValues),Kf(e,`values`,e=>e.def.innerType._zod.values),Kf(e,`optin`,e=>e.def.innerType?._zod?.optin),Kf(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(mg):mg(r)}});function mg(e){return e.memo||(e.value=Object.freeze(e.value)),e}var hg=H(`$ZodLazy`,(e,t)=>{Pm.init(e,t),Kd(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),Kf(e,`pattern`,e=>e.innerType?._zod?.pattern),Kf(e,`propValues`,e=>e.innerType?._zod?.propValues),Kf(e,`optin`,e=>e.innerType?._zod?.optin??void 0),Kf(e,`optout`,e=>e.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),gg=H(`$ZodCustom`,(e,t)=>{mm.init(e,t),Pm.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>_g(t,n,r,e));_g(i,n,r,e)}});function _g(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(If(e))}}var vg=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},yg=`~memo`,bg=[];function xg(e){return typeof e==`object`&&!!e}function Sg(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var Cg=new WeakMap,wg=0,Tg=1,Eg=2;function Dg(e,t,n){let r=Cg.get(e);if(r!==void 0)return r?Eg:wg;if(t.has(e))return Eg;t.add(e);let i=wg,a=e=>{if(i!==Eg&&e?._zod){let r=Dg(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=wg;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?Tg:o.value?._zod?Dg(o.value,t,n):wg;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=Jd(c);s(e?o(e,!0):Tg),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Dg(r,t,!1):Tg);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),Og(e,i)}function Og(e,t){return t!==Tg&&Cg.set(e,t===Eg),t}function kg(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var Ag,jg=[],Mg={alloc(e,t,n){let r=Ag;if(!r)return n;Ag=void 0;let i={value:n,issues:null};return r.set(t.value,i),jg.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&Pg(n,e.value))throw new vg;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Dg(e,new Set,!1);if(i===wg)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===Eg||r?n=!0:r=!0}let l=s.value;if(!xg(l))return t(s,c);let u=c[yg];u||(u={buckets:new WeakMap,backEdges:void 0},c[yg]=u);let d;i===c?d=a:(d=kg(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...Sg(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;Ag=d;let p=jg.length,m=t(s,c);Ag=void 0;let h=jg.length>p?jg.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?Sg(e.issues):bg),e)):(h&&(h.issues=m.issues.length?Sg(m.issues):bg),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function Ng(){return Mg}function Pg(e,t){let n=e[yg]?.backEdges;return n!==void 0&&xg(t)&&n.has(t)}var Fg=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(Ff(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${ff(e.values[0])}`:`Invalid option: expected one of ${Rd(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${Rd(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function Ig(){return{localeError:Fg()}}var Lg,Rg=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function zg(){return new Rg}(Lg=globalThis).__zod_globalRegistry??(Lg.__zod_globalRegistry=zg());var Bg=globalThis.__zod_globalRegistry;function Vg(e){return e.checks&&=[...e.checks],e}function Hg(e,t){return new e(Vg({type:`string`,...B(t)}))}function Ug(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...B(t)})}function Wg(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...B(t)})}function Gg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...B(t)})}function Kg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...B(t)})}function qg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...B(t)})}function Jg(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...B(t)})}function Yg(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...B(t)})}function Xg(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...B(t)})}function Zg(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...B(t)})}function Qg(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...B(t)})}function $g(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...B(t)})}function e_(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...B(t)})}function t_(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...B(t)})}function n_(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...B(t)})}function r_(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...B(t)})}function i_(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...B(t)})}function a_(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...B(t)})}function o_(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...B(t)})}function s_(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...B(t)})}function c_(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...B(t)})}function l_(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...B(t)})}function u_(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...B(t)})}function d_(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...B(t)})}function f_(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...B(t)})}function p_(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...B(t)})}function m_(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...B(t)})}function h_(e,t){return new e(Vg({type:`number`,checks:[],...B(t)}))}function g_(e,t){return new e(Vg({type:`number`,coerce:!0,checks:[],...B(t)}))}function __(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...B(t)})}function v_(e,t){return new e({type:`boolean`,...B(t)})}function y_(e,t){return new e({type:`undefined`,...B(t)})}function b_(e,t){return new e({type:`null`,...B(t)})}function x_(e){return new e({type:`any`})}function S_(e){return new e({type:`unknown`})}function C_(e,t){return new e({type:`never`,...B(t)})}function w_(e,t){return new _m({check:`less_than`,...B(t),value:e,inclusive:!1})}function T_(e,t){return new _m({check:`less_than`,...B(t),value:e,inclusive:!0})}function E_(e,t){return new vm({check:`greater_than`,...B(t),value:e,inclusive:!1})}function D_(e,t){return new vm({check:`greater_than`,...B(t),value:e,inclusive:!0})}function O_(e,t){return new ym({check:`multiple_of`,...B(t),value:e})}function k_(e,t){return new xm({check:`max_length`,...B(t),maximum:e})}function A_(e,t){return new Sm({check:`min_length`,...B(t),minimum:e})}function j_(e,t){return new Cm({check:`length_equals`,...B(t),length:e})}function M_(e,t){return new Tm({check:`string_format`,format:`regex`,...B(t),pattern:e})}function N_(e){return new Em({check:`string_format`,format:`lowercase`,...B(e)})}function P_(e){return new Dm({check:`string_format`,format:`uppercase`,...B(e)})}function F_(e,t){return new Om({check:`string_format`,format:`includes`,...B(t),includes:e})}function I_(e,t){return new km({check:`string_format`,format:`starts_with`,...B(t),prefix:e})}function L_(e,t){return new Am({check:`string_format`,format:`ends_with`,...B(t),suffix:e})}function R_(e){return new jm({check:`overwrite`,tx:e})}function z_(e){return R_(t=>t.normalize(e))}function B_(){return R_(e=>e.trim())}function V_(){return R_(e=>e.toLowerCase())}function H_(){return R_(e=>e.toUpperCase())}function U_(){return R_(e=>nf(e))}function W_(e,t,n){return new e({type:`array`,element:t,...B(n)})}function G_(e,t,n){let r=B(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}function K_(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...B(n)})}function q_(e,t){let n=J_(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(If(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(If(r))}},e(t.value,t)),t);return n}function J_(e,t){let n=new mm({check:`custom`,...B(t)});return n._zod.check=e,n}function Y_(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&qd(e,t,n[t]);return e}function X_(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??Bg,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function Z_(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function Q_(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,Q_(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&Y_(o.schema,c),t.io===`input`&&cv(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function $_(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ev(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${$_(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+$_(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/ + +Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function tv(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;tv(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var nv=new Set([`type`,`properties`,`required`,`additionalProperties`]),rv=[`oneOf`,`anyOf`];function iv(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function av(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!nv.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??iv(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}qd(n,r,e.length===1?e[0]:av(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=iv(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function ov(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of nv)if(t in e)return;let n=t.filter(e=>rv.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=av(t);else{let e=n[0],i=rv.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>av([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Y_(e,r))}function sv(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):Y_(i,s),Y_(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())tv(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])ov(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}Y_(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,qd(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:uv(t,`input`,e.processors),output:uv(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function cv(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return cv(r.element,n);if(r.type===`set`)return cv(r.valueType,n);if(r.type===`lazy`)return cv(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return cv(r.innerType,n);if(r.type===`intersection`)return cv(r.left,n)||cv(r.right,n);if(r.type===`record`||r.type===`map`)return cv(r.keyType,n)||cv(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:cv(r.in,n)||cv(r.out,n);if(r.type===`object`){for(let e in r.shape)if(cv(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(cv(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(cv(e,n))return!0;return!!(r.rest&&cv(r.rest,n))}return!1}var lv=(e,t={})=>n=>{let r=X_({...n,processors:t});return Q_(e,r),ev(r,e),sv(r,e)},uv=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=X_({...i??{},target:a,io:t,processors:n});return Q_(e,o),ev(o,e),sv(o,e)},dv=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},fv=(e,t,n)=>{(e[t]===void 0||n{dv(e,`minimum`,t),fv(e,`maximum`,t)},mv=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},hv=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},gv=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},_v=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},vv=(e,t)=>dv(e,`minimum`,t.minimum),yv=(e,t)=>fv(e,`maximum`,t.maximum),bv=e=>(t,n)=>{_v(t,n.format);let[r,i]=e[n.format];dv(t,`minimum`,r),fv(t,`maximum`,i)},xv={greater_than:(e,t)=>dv(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>fv(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>mv(e,t.value),number_format:bv(mf),bigint_format:bv(hf),min_length:vv,max_length:yv,length_equals:(e,t)=>pv(e,t.length),min_size:vv,max_size:yv,size_equals:(e,t)=>pv(e,t.size),string_format:(e,t)=>{_v(e,t.format),t.pattern&&hv(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>gv(e,t.mime)};function Sv(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)xv[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&dv(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&dv(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&fv(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&fv(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&mv(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&gv(t,i.mime);for(let e of i.patterns??[])hv(t,e);return t}var Cv={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},wv=new Map([[gh,Xp],[vh,Zp]]),Tv=e=>wv.get(e)??e,Ev=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Sv(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Cv[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Tv);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Dv=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Sv(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):Z_(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},Ov=(e,t,n,r)=>{n.type=`boolean`},kv=(e,t,n,r)=>{Z_(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},Av=(e,t,n,r)=>{Z_(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},jv=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Mv=(e,t,n,r)=>{Z_(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},Nv=(e,t,n,r)=>{Z_(e,t,n,r,`Void cannot be represented in JSON Schema`)},Pv=(e,t,n,r)=>{n.not={}},Fv=(e,t,n,r)=>{},Iv=(e,t,n,r)=>{},Lv=(e,t,n,r)=>{Z_(e,t,n,r,`Date cannot be represented in JSON Schema`)},Rv=(e,t,n,r)=>{let i=e._zod.def,a=Ld(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},zv=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(Z_(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(Z_(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Bv=(e,t,n,r)=>{Z_(e,t,n,r,`NaN cannot be represented in JSON Schema`)},Vv=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Hv=(e,t,n,r)=>{let i=n;i.type=`string`,i.format=`binary`,i.contentEncoding=`binary`;let{minimum:a,maximum:o,mime:s}=Sv(e);a!==void 0&&(i.minLength=a),o!==void 0&&(i.maxLength=o),s&&(s.length===0?i.not={}:s.length===1?i.contentMediaType=s[0]:i.anyOf=s.map(e=>({contentMediaType:e})))},Uv=(e,t,n,r)=>{n.type=`boolean`},Wv=(e,t,n,r)=>{Z_(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Gv=(e,t,n,r)=>{Z_(e,t,n,r,`Function types cannot be represented in JSON Schema`)},Kv=(e,t,n,r)=>{Z_(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},qv=(e,t,n,r)=>{Z_(e,t,n,r,`Map cannot be represented in JSON Schema`)},Jv=(e,t,n,r)=>{Z_(e,t,n,r,`Set cannot be represented in JSON Schema`)},Yv=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Sv(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Q_(a.element,t,{...r,path:[...r.path,`items`]})};function Xv(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Xv(t.out):t.type===`catch`?Xv(t.innerType):e._zod.optin}var Zv=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Z_(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)qd(i.properties,e,Q_(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Xv(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Q_(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Qv=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Q_(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},$v=(e,t,n,r)=>{let i=e._zod.def,a=Q_(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Q_(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},ey=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>Q_(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?Q_(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Xv(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=Sv(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function ty(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=ty(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>ty(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?cm:sm).source),p):p}var ny=new WeakMap;function ry(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of ny.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=ty(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var iy=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Sv(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Q_(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)qd(i.patternProperties,Tv(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=Q_(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=ny.get(t);n||(n=[],ny.set(t,n),t.deferred.push(()=>ry(t))),n.push(e)}i.additionalProperties=Q_(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Xv(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},ay=(e,t,n,r)=>{let i=e._zod.def,a=Q_(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},oy=(e,t,n,r)=>{let i=e._zod.def;Q_(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},sy=Symbol();function cy(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Z_(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),sy):JSON.parse(o)}var ly=(e,t,n,r)=>{let i=e._zod.def;Q_(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=cy(i.defaultValue,e,t,n,r);o!==sy&&(n.default=o)},uy=(e,t,n,r)=>{let i=e._zod.def;Q_(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=cy(i.defaultValue,e,t,n,r);o!==sy&&(n._prefault=o)},dy=(e,t,n,r)=>{let i=e._zod.def;Q_(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Z_(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},fy=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Q_(o,t,r);let s=t.seen.get(e);s.ref=o},py=(e,t,n,r)=>{let i=e._zod.def;Q_(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},my=(e,t,n,r)=>{let i=e._zod.def;Q_(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},hy=(e,t,n,r)=>{let i=e._zod.def;Q_(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},gy=(e,t,n,r)=>{let i=e._zod.innerType;Q_(i,t,r);let a=t.seen.get(e);a.ref=i},_y={string:Ev,number:Dv,boolean:Ov,bigint:kv,symbol:Av,null:jv,undefined:Mv,void:Nv,never:Pv,any:Fv,unknown:Iv,date:Lv,enum:Rv,literal:zv,nan:Bv,template_literal:Vv,file:Hv,success:Uv,custom:Wv,function:Gv,transform:Kv,map:qv,set:Jv,array:Yv,object:Zv,union:Qv,intersection:$v,tuple:ey,record:iy,nullable:ay,nonoptional:oy,default:ly,prefault:uy,catch:dy,pipe:fy,readonly:py,promise:my,optional:hy,lazy:gy};function vy(e,t){if(`_idmap`in e){let n=e,r=X_({...t,processors:_y}),i={};for(let e of n._idmap.entries()){let[t,n]=e;Q_(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;ev(r,n),qd(a,t,sv(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=X_({...t,processors:_y});return Q_(e,n),ev(n,e),sv(n,e)}var yy=new WeakSet([Object.prototype,Error.prototype]);function by(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var xy=H(`ZodError`,(e,t)=>{up.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);yy.has(n)||(yy.add(n),by(n,`format`,e=>t=>pp(e,t)),by(n,`flatten`,e=>t=>fp(e,t)),by(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,zd,2)}),by(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,zd,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Sy=hp(xy),Cy=gp(xy),wy=_p(xy),Ty=yp(xy),Ey=Tp(xy),Dy=Ep(xy),Oy=Dp(xy),ky=Op(xy),Ay=kp(xy),jy=Ap(xy),My=jp(xy),Ny=Mp(xy);function Py(){np.localeError||rp(Ig())}function Fy(){np.memoizer||rp({memoizer:Ng()})}var Iy=H(`ZodType`,(e,t)=>(Py(),Pm.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(ef(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return df(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(dx(e,t))},superRefine(e,t){return this.check(fx(e,t))},overwrite(e){return this.check(R_(e))},optional(){return Ub(this)},exactOptional(){return Gb(this)},nullable(){return qb(this)},nullish(){return Ub(qb(this))},nonoptional(e){return $b(this,e)},array(){return Eb(this)},or(e){return Ab([this,e])},and(e){return Pb(this,e)},transform(e){return rx(this,Vb(e))},default(e){return Yb(this,e)},prefault(e){return Zb(this,e)},catch(e){return tx(this,e)},pipe(e){return rx(this,e)},readonly(){return ox(this)},describe(e){let t=this.clone();return Bg.add(t,{description:e}),t},meta(...e){if(e.length===0)return Bg.get(this);let t=this.clone();return Bg.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return zf(this,`~standard`,{...Lm(this),jsonSchema:{input:uv(this,`input`),output:uv(this,`output`)}})},set"~standard"(e){Rf(this,`~standard`,e)},parse:function e(t,n){return Sy(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await Cy(this,t,n,{callee:e})},safeParse(e,t){return wy(this,e,t)},async safeParseAsync(e,t){return Ty(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){Rf(this,`spa`,e)},validate(e,t){return Sp(this,e,t)},validateAsync(e,t){return wp(this,e,t)},encode:function e(t,n){return Ey(this,t,n,{callee:e})},decode:function e(t,n){return Dy(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await Oy(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await ky(this,t,n,{callee:e})},safeEncode(e,t){return Ay(this,e,t)},safeDecode(e,t){return jy(this,e,t)},async safeEncodeAsync(e,t){return My(this,e,t)},async safeDecodeAsync(e,t){return Ny(this,e,t)},toJSONSchema(e){return lv(this,{})(e)},get description(){return Bg.get(this)?.description},get _def(){return this._zod.def}}),Ly=H(`_ZodString`,(e,t)=>{Rm.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ev(e,t,n,r)},Bf({format:e=>Sv(e).format??null,minLength:e=>Sv(e).minimum??null,maxLength:e=>Sv(e).maximum??null},{regex(...e){return this.check(M_(...e))},includes(...e){return this.check(F_(...e))},startsWith(...e){return this.check(I_(...e))},endsWith(...e){return this.check(L_(...e))},min(...e){return this.check(A_(...e))},max(...e){return this.check(k_(...e))},length(...e){return this.check(j_(...e))},nonempty(...e){return this.check(A_(1,...e))},lowercase(e){return this.check(N_(e))},uppercase(e){return this.check(P_(e))},trim(){return this.check(B_())},normalize(...e){return this.check(z_(...e))},toLowerCase(){return this.check(V_())},toUpperCase(){return this.check(H_())},slugify(){return this.check(U_())}})),Ry=H(`ZodString`,(e,t)=>{Rm.init(e,t),Ly.init(e,t)},{email(e){return this.check(Ug(Wy,e))},url(e){return this.check(Yg(Jy,e))},jwt(e){return this.check(u_(ub,e))},emoji(e){return this.check(Xg(Xy,e))},guid(e){return this.check(Wg(Ky,e))},uuid(e){return this.check(Gg(qy,e))},uuidv4(e){return this.check(Kg(qy,e))},uuidv6(e){return this.check(qg(qy,e))},uuidv7(e){return this.check(Jg(qy,e))},nanoid(e){return this.check(Zg(Zy,e))},cuid(e){return this.check(Qg(Qy,e))},cuid2(e){return this.check($g($y,e))},ulid(e){return this.check(e_(eb,e))},base64(e){return this.check(s_(sb,e))},base64url(e){return this.check(c_(cb,e))},xid(e){return this.check(t_(tb,e))},ksuid(e){return this.check(n_(nb,e))},ipv4(e){return this.check(r_(rb,e))},ipv6(e){return this.check(i_(ib,e))},cidrv4(e){return this.check(a_(ab,e))},cidrv6(e){return this.check(o_(ob,e))},e164(e){return this.check(l_(lb,e))},datetime(e){return this.check(d_(By,e))},date(e){return this.check(f_(Vy,e))},time(e){return this.check(p_(Hy,e))},duration(e){return this.check(m_(Uy,e))}});function U(e){return Hg(Ry,e)}var zy=H(`ZodStringFormat`,(e,t)=>{zm.init(e,t),Ly.init(e,t)}),By=H(`ZodISODateTime`,(e,t)=>{ih.init(e,t),zy.init(e,t)}),Vy=H(`ZodISODate`,(e,t)=>{ah.init(e,t),zy.init(e,t)}),Hy=H(`ZodISOTime`,(e,t)=>{oh.init(e,t),zy.init(e,t)}),Uy=H(`ZodISODuration`,(e,t)=>{sh.init(e,t),zy.init(e,t)}),Wy=H(`ZodEmail`,(e,t)=>{Hm.init(e,t),zy.init(e,t)});function Gy(e){return Ug(Wy,e)}var Ky=H(`ZodGUID`,(e,t)=>{Bm.init(e,t),zy.init(e,t)}),qy=H(`ZodUUID`,(e,t)=>{Vm.init(e,t),zy.init(e,t)}),Jy=H(`ZodURL`,(e,t)=>{Xm.init(e,t),zy.init(e,t)});function Yy(e){return Yg(Jy,e)}var Xy=H(`ZodEmoji`,(e,t)=>{Zm.init(e,t),zy.init(e,t)}),Zy=H(`ZodNanoID`,(e,t)=>{Qm.init(e,t),zy.init(e,t)}),Qy=H(`ZodCUID`,(e,t)=>{$m.init(e,t),zy.init(e,t)}),$y=H(`ZodCUID2`,(e,t)=>{eh.init(e,t),zy.init(e,t)}),eb=H(`ZodULID`,(e,t)=>{th.init(e,t),zy.init(e,t)}),tb=H(`ZodXID`,(e,t)=>{nh.init(e,t),zy.init(e,t)}),nb=H(`ZodKSUID`,(e,t)=>{rh.init(e,t),zy.init(e,t)}),rb=H(`ZodIPv4`,(e,t)=>{ch.init(e,t),zy.init(e,t)}),ib=H(`ZodIPv6`,(e,t)=>{dh.init(e,t),zy.init(e,t)}),ab=H(`ZodCIDRv4`,(e,t)=>{fh.init(e,t),zy.init(e,t)}),ob=H(`ZodCIDRv6`,(e,t)=>{mh.init(e,t),zy.init(e,t)}),sb=H(`ZodBase64`,(e,t)=>{_h.init(e,t),zy.init(e,t)}),cb=H(`ZodBase64URL`,(e,t)=>{bh.init(e,t),zy.init(e,t)}),lb=H(`ZodE164`,(e,t)=>{xh.init(e,t),zy.init(e,t)}),ub=H(`ZodJWT`,(e,t)=>{Ch.init(e,t),zy.init(e,t)}),db=H(`ZodNumber`,(e,t)=>{wh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Dv(e,t,n,r),e.isFinite=!0},Bf({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Sv(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Sv(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Sv(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Sv(e).format??null},{gt(e,t){return this.check(E_(e,t))},gte(e,t){return this.check(D_(e,t))},min(e,t){return this.check(D_(e,t))},lt(e,t){return this.check(w_(e,t))},lte(e,t){return this.check(T_(e,t))},max(e,t){return this.check(T_(e,t))},int(e){return this.check(W(e))},safe(e){return this.check(W(e))},positive(e){return this.check(E_(0,e))},nonnegative(e){return this.check(D_(0,e))},negative(e){return this.check(w_(0,e))},nonpositive(e){return this.check(T_(0,e))},multipleOf(e,t){return this.check(O_(e,t))},step(e,t){return this.check(O_(e,t))},finite(){return this}}));function fb(e){return h_(db,e)}var pb=H(`ZodNumberFormat`,(e,t)=>{Th.init(e,t),db.init(e,t)});function W(e){return __(pb,e)}var mb=H(`ZodBoolean`,(e,t)=>{Eh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ov(e,t,n,r)});function hb(e){return v_(mb,e)}var gb=H(`ZodUndefined`,(e,t)=>{Dh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mv(e,t,n,r)});function _b(e){return y_(gb,e)}var vb=H(`ZodNull`,(e,t)=>{Oh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jv(e,t,n,r)});function yb(e){return b_(vb,e)}var bb=H(`ZodAny`,(e,t)=>{kh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function G(){return x_(bb)}var xb=H(`ZodUnknown`,(e,t)=>{Ah.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Sb(){return S_(xb)}var Cb=H(`ZodNever`,(e,t)=>{jh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pv(e,t,n,r)});function wb(e){return C_(Cb,e)}var Tb=H(`ZodArray`,(e,t)=>{Fy(),Fh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yv(e,t,n,r),e.element=t.element},{min(e,t){return this.check(A_(e,t))},nonempty(e){return this.check(A_(1,e))},max(e,t){return this.check(k_(e,t))},length(e,t){return this.check(j_(e,t))},unwrap(){return this.element}});function Eb(e,t){return W_(Tb,e,t)}var Db=H(`ZodObject`,(e,t)=>{Fy(),Vh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zv(e,t,n,r),qf(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return Rb(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(ef(this._zod.def,{catchall:e}))},passthrough(){return this.clone(ef(this._zod.def,{catchall:Sb()}))},loose(){return this.clone(ef(this._zod.def,{catchall:Sb()}))},strict(){return this.clone(ef(this._zod.def,{catchall:wb()}))},strip(){return this.clone(ef(this._zod.def,{catchall:void 0}))},extend(e){return yf(this,e)},safeExtend(e){return xf(this,e)},merge(e){return Sf(this,e)},pick(e){return gf(this,e)},omit(e){return vf(this,e)},partial(...e){return Cf(Hb,this,e[0])},exactPartial(...e){return Cf(Wb,this,e[0],`exactPartial`)},required(...e){return wf(Qb,this,e[0])}});function Ob(e,t){return new Db({type:`object`,shape:e??{},...B(t)})}function K(e,t){return new Db({type:`object`,shape:e,catchall:Sb(),...B(t)})}var kb=H(`ZodUnion`,(e,t)=>{Uh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qv(e,t,n,r),e.options=t.options});function Ab(e,t){return new kb({type:`union`,options:e,...B(t)})}var jb=H(`ZodDiscriminatedUnion`,(e,t)=>{kb.init(e,t),Gh.init(e,t)});function Mb(e,t,n){return new jb({type:`union`,options:t,discriminator:e,...B(n)})}var Nb=H(`ZodIntersection`,(e,t)=>{Kh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$v(e,t,n,r)});function Pb(e,t){return new Nb({type:`intersection`,left:e,right:t})}var Fb=H(`ZodRecord`,(e,t)=>{Fy(),Yh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>iy(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function Ib(e,t,n){return!t||!t._zod?new Fb({type:`record`,keyType:U(),valueType:e,...B(t)}):new Fb({type:`record`,keyType:e,valueType:t,...B(n)})}var Lb=H(`ZodEnum`,(e,t)=>{Xh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rv(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Lb({...t,checks:[],...B(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Lb({...t,checks:[],...B(r),entries:i})}});function Rb(e,t){return new Lb({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...B(t)})}var zb=H(`ZodLiteral`,(e,t)=>{Zh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zv(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function q(e,t){return new zb({type:`literal`,values:Array.isArray(e)?e:[e],...B(t)})}var Bb=H(`ZodTransform`,(e,t)=>{Fy(),Qh.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kv(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new tp(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(If(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(If(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Vb(e){return new Bb({type:`transform`,transform:e})}var Hb=H(`ZodOptional`,(e,t)=>{eg.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ub(e){return new Hb({type:`optional`,innerType:e})}var Wb=H(`ZodExactOptional`,(e,t)=>{tg.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>hy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Gb(e){return new Wb({type:`optional`,innerType:e})}var Kb=H(`ZodNullable`,(e,t)=>{ng.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ay(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function qb(e){return new Kb({type:`nullable`,innerType:e})}var Jb=H(`ZodDefault`,(e,t)=>{rg.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ly(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Yb(e,t){return new Jb({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():cf(t)}})}var Xb=H(`ZodPrefault`,(e,t)=>{ag.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Zb(e,t){return new Xb({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():cf(t)}})}var Qb=H(`ZodNonOptional`,(e,t)=>{og.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>oy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function $b(e,t){return new Qb({type:`nonoptional`,innerType:e,...B(t)})}var ex=H(`ZodCatch`,(e,t)=>{lg.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>dy(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function tx(e,t){return new ex({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Yf(t)})}var nx=H(`ZodPipe`,(e,t)=>{ug.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>fy(e,t,n,r),e.in=t.in,e.out=t.out});function rx(e,t){return new nx({type:`pipe`,in:e,out:t})}var ix=H(`ZodPreprocess`,(e,t)=>{nx.init(e,t),fg.init(e,t)}),ax=H(`ZodReadonly`,(e,t)=>{pg.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>py(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ox(e){return new ax({type:`readonly`,innerType:e})}var sx=H(`ZodLazy`,(e,t)=>{hg.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gy(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function cx(e){return new sx({type:`lazy`,getter:e})}var lx=H(`ZodCustom`,(e,t)=>{gg.init(e,t),Iy.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wv(e,t,n,r)});function ux(e,t){return G_(lx,e??(()=>!0),t)}function dx(e,t={}){return K_(lx,e,t)}function fx(e,t){return q_(e,t)}function px(e,t){return new ix({type:`pipe`,in:Vb(e),out:t})}var mx=Rb(L),J=ux(e=>typeof e==`object`&&!!e&&!Array.isArray(e)),hx=U(),gx=Rb([`developer`,`system`,`assistant`,`user`]),_x=K({type:q(L.TEXT_MESSAGE_START),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U(),role:gx.optional(),name:U().optional()}),vx=K({type:q(L.TEXT_MESSAGE_CONTENT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U(),delta:U()}),yx=K({type:q(L.TEXT_MESSAGE_END),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U()}),bx=K({type:q(L.TEXT_MESSAGE_CHUNK),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U().optional(),role:gx.optional(),delta:U().optional(),name:U().optional()}),xx=K({type:q(L.TOOL_CALL_START),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),toolCallId:U(),toolCallName:U(),parentMessageId:U().optional()}),Sx=K({type:q(L.TOOL_CALL_ARGS),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),toolCallId:U(),delta:U()}),Cx=K({type:q(L.TOOL_CALL_END),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),toolCallId:U()}),wx=K({type:q(L.TOOL_CALL_CHUNK),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),toolCallId:U().optional(),toolCallName:U().optional(),parentMessageId:U().optional(),delta:U().optional()}),Tx=K({type:q(`text`),id:U().optional(),text:U(),metadata:G().refine(e=>e!==null).optional()}),Ex=Mb(`type`,[K({type:q(`data`),value:U(),mimeType:U()}),K({type:q(`url`),value:U(),mimeType:U().optional()}),K({type:q(`file`),value:U(),provider:U().optional(),mimeType:U().optional()})]),Dx=Mb(`type`,[Tx,K({type:q(`image`),id:U().optional(),source:Ex,metadata:G().refine(e=>e!==null).optional()}),K({type:q(`audio`),id:U().optional(),source:Ex,metadata:G().refine(e=>e!==null).optional()}),K({type:q(`video`),id:U().optional(),source:Ex,metadata:G().refine(e=>e!==null).optional()}),K({type:q(`document`),id:U().optional(),source:Ex,metadata:G().refine(e=>e!==null).optional()})]),Ox=K({type:q(L.TOOL_CALL_RESULT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U(),toolCallId:U(),content:Ab([U(),Eb(Dx)]),role:q(`tool`).optional()}),kx=G(),Ax=K({type:q(L.STATE_SNAPSHOT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),snapshot:kx.refine(e=>e!==void 0)}),jx=U().regex(RegExp(`^(/([^/~]|~[01])*)*$`)),Mx=Eb(Mb(`op`,[K({op:q(`add`),path:jx,value:G().refine(e=>e!==void 0)}).meta({specOpen:!0}),K({op:q(`remove`),path:jx}).meta({specOpen:!0}),K({op:q(`replace`),path:jx,value:G().refine(e=>e!==void 0)}).meta({specOpen:!0}),K({op:q(`move`),from:jx,path:jx}).meta({specOpen:!0}),K({op:q(`copy`),from:jx,path:jx}).meta({specOpen:!0}),K({op:q(`test`),path:jx,value:G().refine(e=>e!==void 0)}).meta({specOpen:!0})])),Nx=K({type:q(L.STATE_DELTA),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),delta:Mx}),Px=K({subagentRunId:hx.optional(),id:U(),role:q(`developer`),name:U().optional(),encryptedValue:U().optional(),metadata:J.optional(),content:U()}),Fx=K({subagentRunId:hx.optional(),id:U(),role:q(`system`),name:U().optional(),encryptedValue:U().optional(),metadata:J.optional(),content:U()}),Ix=K({name:U(),arguments:U()}),Lx=K({id:U(),type:q(`function`),function:Ix,encryptedValue:U().optional(),metadata:J.optional()}),Rx=Mb(`role`,[Px,Fx,K({subagentRunId:hx.optional(),id:U(),role:q(`assistant`),name:U().optional(),encryptedValue:U().optional(),metadata:J.optional(),content:U().optional(),toolCalls:Eb(Lx).optional()}),K({subagentRunId:hx.optional(),id:U(),role:q(`user`),name:U().optional(),encryptedValue:U().optional(),metadata:J.optional(),content:Ab([U(),Eb(Dx)])}),K({subagentRunId:hx.optional(),id:U(),role:q(`tool`),content:Ab([U(),Eb(Dx)]),toolCallId:U(),error:U().optional(),encryptedValue:U().optional(),metadata:J.optional()}),K({subagentRunId:hx.optional(),id:U(),role:q(`activity`),activityType:U(),content:ux(e=>typeof e==`object`&&!!e&&!Array.isArray(e)),metadata:J.optional()}),K({subagentRunId:hx.optional(),id:U(),role:q(`reasoning`),content:U(),encryptedValue:U().optional(),metadata:J.optional()})]),zx=K({type:q(L.MESSAGES_SNAPSHOT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),messages:Eb(Rx)}),Bx=K({type:q(L.ACTIVITY_SNAPSHOT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U(),activityType:U(),content:ux(e=>typeof e==`object`&&!!e&&!Array.isArray(e)),replace:hb().optional()}),Vx=K({type:q(L.ACTIVITY_DELTA),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U(),activityType:U(),patch:Mx}),Hx=K({type:q(L.RAW),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),event:G().refine(e=>e!==void 0),source:U().optional()}),Ux=K({type:q(L.CUSTOM),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),name:U(),value:G().refine(e=>e!==void 0)}),Wx=K({name:U(),description:U(),parameters:G().refine(e=>e!==null).optional(),metadata:J.optional()}),Gx=K({description:U(),value:U()}),Kx=K({interruptId:U(),status:Rb([`resolved`,`cancelled`]),payload:G().refine(e=>e!==null).optional(),metadata:J.optional()}),qx=K({threadId:U(),runId:U(),protocolVersion:U().optional(),parentRunId:U().optional(),state:kx.refine(e=>e!==null).nullable().transform(e=>e??void 0).optional(),messages:Eb(Rx),tools:Eb(Wx).default(()=>[]),context:Eb(Gx).default(()=>[]),forwardedProps:G().refine(e=>e!==null).optional(),resume:Eb(Kx).optional()}),Jx=K({type:q(L.RUN_STARTED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),threadId:U(),runId:U(),protocolVersion:U().optional(),parentRunId:U().optional(),input:qx.optional()}),Yx=K({type:q(`success`),pendingToolCallIds:Eb(U()).optional()}),Xx=K({subagentRunId:hx.optional(),id:U(),reason:U(),message:U().optional(),toolCallId:U().optional(),responseSchema:ux(e=>typeof e==`object`&&!!e&&!Array.isArray(e)).optional(),expiresAt:U().optional(),metadata:J.optional()}),Zx=Mb(`type`,[Yx,K({type:q(`interrupt`),interrupts:Eb(Xx).min(1)}),K({type:q(`cancelled`)})]),Qx=K({provider:U().optional(),model:U().optional(),inputTokens:W().min(0).max(9007199254740991).optional(),outputTokens:W().min(0).max(9007199254740991).optional(),totalTokens:W().min(0).max(9007199254740991).optional(),reasoningTokens:W().min(0).max(9007199254740991).optional(),cachedInputTokens:W().min(0).max(9007199254740991).optional(),cacheWriteInputTokens:W().min(0).max(9007199254740991).optional()}),$x=K({type:q(L.RUN_FINISHED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),threadId:U(),runId:U(),result:G().refine(e=>e!==null).optional(),outcome:Zx.optional(),usage:Eb(Qx).optional()}),eS=K({type:q(L.RUN_ERROR),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),message:U(),code:U().optional(),usage:Eb(Qx).optional()}),tS=K({type:q(L.STEP_STARTED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),stepName:U()}),nS=K({type:q(L.STEP_FINISHED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),stepName:U()}),rS=K({type:q(L.REASONING_START),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U()}),iS=K({type:q(L.REASONING_MESSAGE_START),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U(),role:q(`reasoning`)}),aS=K({type:q(L.REASONING_MESSAGE_CONTENT),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U(),delta:U()}),oS=K({type:q(L.REASONING_MESSAGE_END),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U()}),sS=K({type:q(L.REASONING_MESSAGE_CHUNK),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U().optional(),delta:U().optional()}),cS=K({type:q(L.REASONING_END),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),messageId:U()}),lS=Rb([`tool-call`,`message`]),uS=K({type:q(L.REASONING_ENCRYPTED_VALUE),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx.optional(),subtype:lS,entityId:U(),encryptedValue:U()}),dS=K({type:q(L.SUBAGENT_STARTED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx,name:U(),description:U().optional(),parentSubagentRunId:hx.optional(),parentToolCallId:U().optional(),parentMessageId:U().optional()}),fS=Mb(`type`,[K({type:q(`success`)}),K({type:q(`suspended`),interruptIds:Eb(U()).optional()})]),pS=Mb(`type`,[_x,vx,yx,bx,xx,Sx,Cx,wx,Ox,Ax,Nx,zx,Bx,Vx,Hx,Ux,Jx,$x,eS,tS,nS,rS,iS,aS,oS,sS,cS,uS,dS,K({type:q(L.SUBAGENT_FINISHED),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx,result:G().refine(e=>e!==null).optional(),outcome:fS.optional()}),K({type:q(L.SUBAGENT_ERROR),timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional(),subagentRunId:hx,message:U(),code:U().optional()})]);Rb([`developer`,`system`,`assistant`,`user`,`tool`,`activity`,`reasoning`]);var mS=K({name:U(),description:U().optional()}),hS=K({name:U().optional(),type:U().optional(),description:U().optional(),version:U().optional(),provider:U().optional(),documentationUrl:U().optional(),metadata:J.optional()}),gS=K({streaming:hb().optional(),websocket:hb().optional(),httpBinary:hb().optional(),pushNotifications:hb().optional(),resumable:hb().optional()}),_S=K({supported:hb().optional(),items:Eb(Wx).optional(),parallelCalls:hb().optional(),clientProvided:hb().optional()}),vS=K({structuredOutput:hb().optional(),supportedMimeTypes:Eb(U()).optional()}),yS=K({snapshots:hb().optional(),deltas:hb().optional(),memory:hb().optional(),persistentState:hb().optional()}),bS=K({supported:hb().optional(),delegation:hb().optional(),handoffs:hb().optional(),subagents:Eb(mS).optional()}),xS=K({supported:hb().optional(),streaming:hb().optional(),encrypted:hb().optional()}),SS=K({image:hb().optional(),audio:hb().optional(),video:hb().optional(),pdf:hb().optional(),file:hb().optional()}),CS=K({image:hb().optional(),audio:hb().optional()}),wS=K({input:SS.optional(),output:CS.optional()}),TS=K({codeExecution:hb().optional(),sandboxed:hb().optional(),maxIterations:W().min(0).max(9007199254740991).optional(),maxExecutionTime:W().min(0).max(9007199254740991).optional()}),ES=K({supported:hb().optional(),approvals:hb().optional(),interventions:hb().optional(),feedback:hb().optional(),interrupts:hb().optional(),approveWithEdits:hb().optional()});K({identity:hS.optional(),transport:gS.optional(),tools:_S.optional(),output:vS.optional(),state:yS.optional(),multiAgent:bS.optional(),reasoning:xS.optional(),multimodal:wS.optional(),execution:TS.optional(),humanInTheLoop:ES.optional(),custom:ux(e=>typeof e==`object`&&!!e&&!Array.isArray(e)).optional()}),K({subagentRunId:hx.optional()}),K({type:mx,timestamp:W().min(-9007199254740991).max(9007199254740991).optional(),rawEvent:G().refine(e=>e!==null).optional(),metadata:J.optional()}),K({subagentRunId:hx.optional(),id:U(),role:U(),name:U().optional(),encryptedValue:U().optional(),metadata:J.optional()}),J.optional();function DS(){let e=this.buf,t=this.pos,n=0,r=0;for(let i=0;i<28;i+=7){let a=e[t++];if(n|=(a&127)<>4,!(i&128)){this.pos=t,this.assertBounds(),this.varint64Lo=n,this.varint64Hi=r;return}for(let i=3;i<=31;i+=7){let a=e[t++];if(r|=(a&127)<=OS&&(i+=r/OS|0,r%=OS)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?PS(r,i):NS(r,i)}function AS(e,t){let n=NS(e,t),r=n.hi&2147483648;r&&(n=PS(n.lo,n.hi));let i=jS(n.lo,n.hi);return r?`-`+i:i}function jS(e,t){if({lo:e,hi:t}=MS(e,t),t<=2097151)return String(OS*t+e);let n=e&16777215,r=(e>>>24|t<<8)&16777215,i=t>>16&65535,a=n+r*6777216+i*6710656,o=r+i*8147497,s=i*2,c=1e7;return a>=c&&(o+=Math.floor(a/c),a%=c),o>=c&&(s+=Math.floor(o/c),o%=c),s.toString()+FS(o)+FS(a)}function MS(e,t){return{lo:e>>>0,hi:t>>>0}}function NS(e,t){return{lo:e|0,hi:t|0}}function PS(e,t){return t=~t,e?e=~e+1:t+=1,NS(e,t)}var FS=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function IS(){let e=this.buf[this.pos++];if(!(e&128))return this.assertBounds(),e;let t=e&127;if(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}var LS=RS();function RS(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(globalThis.Deno||globalThis.Bun||typeof process!=`object`||{}.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||ri||ta.call(e)),HS(i)}return VS}function WS(e){return(t,n)=>{let r=e(t);return n.set(r),{written:r.byteLength}}}var GS;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(GS||={});var Y=class{constructor(e){this.stackPos=[],this.encodeUtf8Into=e?WS(e):US().encodeUtf8Into,this.buffer=JS,this.viewCache=YS,this.pos=0}ensureCapacity(e){let t=this.pos+e;if(t>this.buffer.length){let e=this.buffer.length||KS;for(;e0&&n.set(this.buffer),this.buffer=n}}view(){let e=this.buffer,t=this.viewCache;if(t.byteLength===e.byteLength)return t;let n=new DataView(e.buffer);return this.viewCache=n,n}finish(){let e=this.buffer.slice(0,this.pos);return this.pos=0,this.stackPos=[],e}fork(){return this.stackPos.push(this.pos),this.ensureCapacity(qS),this.buffer[this.pos++]=0,this}join(){let e=this.stackPos.pop();if(e===void 0)throw Error(`invalid state, fork stack empty`);let t=this.pos-e-qS,n=ZS(t);return n>qS&&(this.ensureCapacity(n-qS),this.buffer.copyWithin(e+n,e+qS,this.pos)),this.pos=e,this.uint32(t),this.pos+=t,this}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.ensureCapacity(e.length),this.buffer.set(e,this.pos),this.pos+=e.length,this}uint32(e){if($S(e),this.ensureCapacity(5),e<128)return this.buffer[this.pos++]=e,this;for(;e>127;)this.buffer[this.pos++]=e&127|128,e>>>=7;return this.buffer[this.pos++]=e,this}int32(e){if(QS(e),e>=0)return this.uint32(e);this.ensureCapacity(10);for(let t=0;t<9;t++)this.buffer[this.pos++]=e&127|128,e>>=7;return this.buffer[this.pos++]=1,this}bool(e){return this.ensureCapacity(1),this.buffer[this.pos++]=+!!e,this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){typeof e!=`string`&&(e=String(e));let t=e.length;if(t<=XS){this.ensureCapacity(t+1);let n=this.buffer,r=this.pos;n[r++]=t;let i=0;for(;i127)break;n[r++]=t}if(i==t)return this.pos=r,this}this.ensureCapacity(t*3+5);let n=ZS(t),r=this.buffer,i=this.pos,{written:a}=this.encodeUtf8Into(e,r.subarray(i+n)),o=ZS(a);return o!=n&&r.copyWithin(i+o,i+n,i+n+a),this.uint32(a),this.pos+=a,this}float(e){return eC(e),this.ensureCapacity(4),this.view().setFloat32(this.pos,e,!0),this.pos+=4,this}double(e){return this.ensureCapacity(8),this.view().setFloat64(this.pos,e,!0),this.pos+=8,this}fixed32(e){return $S(e),this.ensureCapacity(4),this.view().setUint32(this.pos,e,!0),this.pos+=4,this}sfixed32(e){return QS(e),this.ensureCapacity(4),this.view().setInt32(this.pos,e,!0),this.pos+=4,this}sint32(e){return QS(e),this.uint32((e<<1^e>>31)>>>0)}sfixed64(e){let t=LS.enc(e);this.ensureCapacity(8);let n=this.view();return n.setInt32(this.pos,t.lo,!0),n.setInt32(this.pos+4,t.hi,!0),this.pos+=8,this}fixed64(e){let t=LS.uEnc(e);this.ensureCapacity(8);let n=this.view();return n.setInt32(this.pos,t.lo,!0),n.setInt32(this.pos+4,t.hi,!0),this.pos+=8,this}int64(e){let t=LS.enc(e);return this.writeVarint64(t.lo,t.hi)}sint64(e){let t=LS.enc(e),n=t.hi>>31,r=t.lo<<1^n,i=(t.hi<<1|t.lo>>>31)^n;return this.writeVarint64(r,i)}uint64(e){let t=LS.uEnc(e);return this.writeVarint64(t.lo,t.hi)}writeVarint64(e,t){this.ensureCapacity(10);let n=this.buffer,r=this.pos;for(let i=0;i<28;i+=7){let a=e>>>i,o=!(!(a>>>7)&&t==0);if(n[r++]=(o?a|128:a)&255,!o)return this.pos=r,this}let i=e>>>28&15|(t&7)<<4,a=!!(t>>3);if(n[r++]=(a?i|128:i)&255,!a)return this.pos=r,this;for(let e=3;e<31;e+=7){let i=t>>>e,a=!!(i>>>7);if(n[r++]=(a?i|128:i)&255,!a)return this.pos=r,this}return n[r++]=t>>>31&1,this.pos=r,this}},KS=128,qS=1,JS=new Uint8Array,YS=new DataView(JS.buffer),XS=32;function ZS(e){return e<128?1:e<16384?2:e<2097152?3:e<268435456?4:5}var X=class{constructor(e,t=US().decodeUtf8){this.decodeUtf8=t,this.varint64Lo=0,this.varint64Hi=0,this.varint64=DS,this.uint32=IS,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength)}tag(){let e=this.pos,t=this.uint32(),n=this.pos-e;if(n>5||n==5&&this.buf[this.pos-1]>15)throw Error(`illegal tag: varint overflows uint32`);let r=t>>>3,i=t&7;if(r<=0||i>5)throw Error(`illegal tag: field no `+r+` wire type `+i);return[r,i]}skip(e,t,n=100){let r=this.pos;switch(e){case GS.Varint:for(;this.buf[this.pos++]&128;);break;case GS.Bit64:this.pos+=4;case GS.Bit32:this.pos+=4;break;case GS.LengthDelimited:let r=this.uint32();this.pos+=r;break;case GS.StartGroup:if(n<=0)throw Error(`maximum recursion depth reached`);for(;;){let[e,r]=this.tag();if(r===GS.EndGroup){if(t!==void 0&&e!==t)throw Error(`invalid end group tag`);break}this.skip(r,e,n-1)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(r,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return this.varint64(),LS.dec(this.varint64Lo,this.varint64Hi)}uint64(){return this.varint64(),LS.uDec(this.varint64Lo,this.varint64Hi)}sint64(){this.varint64();let e=this.varint64Lo,t=this.varint64Hi,n=-(e&1);return e=(e>>>1|(t&1)<<31)^n,t=t>>>1^n,LS.dec(e,t)}bool(){let e=this.buf[this.pos];return e<128?(this.pos++,e!==0):(this.varint64(),this.varint64Lo!==0||this.varint64Hi!==0)}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return LS.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return LS.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(e){let t=this.bytes(),n=t.length;if(n<=XS){let r=Array(n);for(let i=0;i127)return this.decodeUtf8(t,e);r[i]=n}return String.fromCharCode.apply(String,r)}return this.decodeUtf8(t,e)}};function QS(e){if(typeof e==`string`)e=Number(e);else if(typeof e!=`number`)throw Error(`invalid int32: `+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw Error(`invalid int32: `+e)}function $S(e){if(typeof e==`string`)e=Number(e);else if(typeof e!=`number`)throw Error(`invalid uint32: `+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw Error(`invalid uint32: `+e)}function eC(e){if(typeof e==`string`){let t=e;if(e=Number(e),Number.isNaN(e)&&t!==`NaN`)throw Error(`invalid float32: `+t)}else if(typeof e!=`number`)throw Error(`invalid float32: `+typeof e);if(!Number.isFinite(Math.fround(e))&&Number.isFinite(e))throw Error(`invalid float32: `+e)}var tC=function(e){return e[e.NULL_VALUE=0]=`NULL_VALUE`,e[e.UNRECOGNIZED=-1]=`UNRECOGNIZED`,e}({});function nC(){return{fields:{}}}var rC={encode(e,t=new Y){return Object.entries(e.fields).forEach(([e,n])=>{n!==void 0&&aC.encode({key:e,value:n},t.uint32(10).fork()).join()}),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=nC();for(;n.pos>>3){case 1:{if(e!==10)break;let t=aC.decode(n,n.uint32());t.value!==void 0&&(i.fields[t.key]=t.value);continue}}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return rC.fromPartial(e??{})},fromPartial(e){let t=nC();return t.fields=Object.entries(e.fields??{}).reduce((e,[t,n])=>(n!==void 0&&(e[t]=n),e),{}),t},wrap(e){let t=nC();if(e!==void 0)for(let n of Object.keys(e))t.fields[n]=e[n];return t},unwrap(e){let t={};if(e.fields)for(let n of Object.keys(e.fields))t[n]=e.fields[n];return t}};function iC(){return{key:``,value:void 0}}var aC={encode(e,t=new Y){return e.key!==``&&t.uint32(10).string(e.key),e.value!==void 0&&Z.encode(Z.wrap(e.value),t.uint32(18).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=iC();for(;n.pos>>3){case 1:if(e!==10)break;i.key=n.string();continue;case 2:if(e!==18)break;i.value=Z.unwrap(Z.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return aC.fromPartial(e??{})},fromPartial(e){let t=iC();return t.key=e.key??``,t.value=e.value??void 0,t}};function oC(){return{nullValue:void 0,numberValue:void 0,stringValue:void 0,boolValue:void 0,structValue:void 0,listValue:void 0}}var Z={encode(e,t=new Y){return e.nullValue!==void 0&&t.uint32(8).int32(e.nullValue),e.numberValue!==void 0&&t.uint32(17).double(e.numberValue),e.stringValue!==void 0&&t.uint32(26).string(e.stringValue),e.boolValue!==void 0&&t.uint32(32).bool(e.boolValue),e.structValue!==void 0&&rC.encode(rC.wrap(e.structValue),t.uint32(42).fork()).join(),e.listValue!==void 0&&cC.encode(cC.wrap(e.listValue),t.uint32(50).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=oC();for(;n.pos>>3){case 1:if(e!==8)break;i.nullValue=n.int32();continue;case 2:if(e!==17)break;i.numberValue=n.double();continue;case 3:if(e!==26)break;i.stringValue=n.string();continue;case 4:if(e!==32)break;i.boolValue=n.bool();continue;case 5:if(e!==42)break;i.structValue=rC.unwrap(rC.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.listValue=cC.unwrap(cC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Z.fromPartial(e??{})},fromPartial(e){let t=oC();return t.nullValue=e.nullValue??void 0,t.numberValue=e.numberValue??void 0,t.stringValue=e.stringValue??void 0,t.boolValue=e.boolValue??void 0,t.structValue=e.structValue??void 0,t.listValue=e.listValue??void 0,t},wrap(e){let t=oC();if(e===null)t.nullValue=tC.NULL_VALUE;else if(typeof e==`boolean`)t.boolValue=e;else if(typeof e==`number`)t.numberValue=e;else if(typeof e==`string`)t.stringValue=e;else if(globalThis.Array.isArray(e))t.listValue=e;else if(typeof e==`object`)t.structValue=e;else if(e!==void 0)throw new globalThis.Error(`Unsupported any value type: `+typeof e);return t},unwrap(e){if(e.stringValue!==void 0)return e.stringValue;if(e?.numberValue!==void 0)return e.numberValue;if(e?.boolValue!==void 0)return e.boolValue;if(e?.structValue!==void 0)return e.structValue;if(e?.listValue!==void 0)return e.listValue;if(e?.nullValue!==void 0)return null}};function sC(){return{values:[]}}var cC={encode(e,t=new Y){for(let n of e.values)Z.encode(Z.wrap(n),t.uint32(10).fork()).join();return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=sC();for(;n.pos>>3){case 1:if(e!==10)break;i.values.push(Z.unwrap(Z.decode(n,n.uint32())));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return cC.fromPartial(e??{})},fromPartial(e){let t=sC();return t.values=e.values?.map(e=>e)||[],t},wrap(e){let t=sC();return t.values=e??[],t},unwrap(e){return e?.hasOwnProperty(`values`)&&globalThis.Array.isArray(e.values)?e.values:e}},lC=function(e){return e[e.ADD=0]=`ADD`,e[e.REMOVE=1]=`REMOVE`,e[e.REPLACE=2]=`REPLACE`,e[e.MOVE=3]=`MOVE`,e[e.COPY=4]=`COPY`,e[e.TEST=5]=`TEST`,e[e.UNRECOGNIZED=-1]=`UNRECOGNIZED`,e}({});function uC(){return{op:0,path:``,from:void 0,value:void 0}}var dC={encode(e,t=new Y){return e.op!==0&&t.uint32(8).int32(e.op),e.path!==``&&t.uint32(18).string(e.path),e.from!==void 0&&t.uint32(26).string(e.from),e.value!==void 0&&Z.encode(Z.wrap(e.value),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=uC();for(;n.pos>>3){case 1:if(e!==8)break;i.op=n.int32();continue;case 2:if(e!==18)break;i.path=n.string();continue;case 3:if(e!==26)break;i.from=n.string();continue;case 4:if(e!==34)break;i.value=Z.unwrap(Z.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return dC.fromPartial(e??{})},fromPartial(e){let t=uC();return t.op=e.op??0,t.path=e.path??``,t.from=e.from??void 0,t.value=e.value??void 0,t}};function fC(){return{text:``,id:void 0,metadata:void 0}}var pC={encode(e,t=new Y){return e.text!==``&&t.uint32(10).string(e.text),e.id!==void 0&&t.uint32(18).string(e.id),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(26).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=fC();for(;n.pos>>3){case 1:if(e!==10)break;i.text=n.string();continue;case 2:if(e!==18)break;i.id=n.string();continue;case 3:if(e!==26)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return pC.fromPartial(e??{})},fromPartial(e){let t=fC();return t.text=e.text??``,t.id=e.id??void 0,t.metadata=e.metadata??void 0,t}};function mC(){return{source:void 0,metadata:void 0,id:void 0}}var hC={encode(e,t=new Y){return e.source!==void 0&&CC.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(18).fork()).join(),e.id!==void 0&&t.uint32(26).string(e.id),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=mC();for(;n.pos>>3){case 1:if(e!==10)break;i.source=CC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.id=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return hC.fromPartial(e??{})},fromPartial(e){let t=mC();return t.source=e.source!==void 0&&e.source!==null?CC.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t.id=e.id??void 0,t}};function gC(){return{value:``,mimeType:``}}var _C={encode(e,t=new Y){return e.value!==``&&t.uint32(10).string(e.value),e.mimeType!==``&&t.uint32(18).string(e.mimeType),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=gC();for(;n.pos>>3){case 1:if(e!==10)break;i.value=n.string();continue;case 2:if(e!==18)break;i.mimeType=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return _C.fromPartial(e??{})},fromPartial(e){let t=gC();return t.value=e.value??``,t.mimeType=e.mimeType??``,t}};function vC(){return{value:``,mimeType:void 0}}var yC={encode(e,t=new Y){return e.value!==``&&t.uint32(10).string(e.value),e.mimeType!==void 0&&t.uint32(18).string(e.mimeType),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=vC();for(;n.pos>>3){case 1:if(e!==10)break;i.value=n.string();continue;case 2:if(e!==18)break;i.mimeType=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return yC.fromPartial(e??{})},fromPartial(e){let t=vC();return t.value=e.value??``,t.mimeType=e.mimeType??void 0,t}};function bC(){return{value:``,provider:void 0,mimeType:void 0}}var xC={encode(e,t=new Y){return e.value!==``&&t.uint32(10).string(e.value),e.provider!==void 0&&t.uint32(18).string(e.provider),e.mimeType!==void 0&&t.uint32(26).string(e.mimeType),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=bC();for(;n.pos>>3){case 1:if(e!==10)break;i.value=n.string();continue;case 2:if(e!==18)break;i.provider=n.string();continue;case 3:if(e!==26)break;i.mimeType=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return xC.fromPartial(e??{})},fromPartial(e){let t=bC();return t.value=e.value??``,t.provider=e.provider??void 0,t.mimeType=e.mimeType??void 0,t}};function SC(){return{data:void 0,url:void 0,file:void 0}}var CC={encode(e,t=new Y){return e.data!==void 0&&_C.encode(e.data,t.uint32(10).fork()).join(),e.url!==void 0&&yC.encode(e.url,t.uint32(18).fork()).join(),e.file!==void 0&&xC.encode(e.file,t.uint32(26).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=SC();for(;n.pos>>3){case 1:if(e!==10)break;i.data=_C.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.url=yC.decode(n,n.uint32());continue;case 3:if(e!==26)break;i.file=xC.decode(n,n.uint32());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return CC.fromPartial(e??{})},fromPartial(e){let t=SC();return t.data=e.data!==void 0&&e.data!==null?_C.fromPartial(e.data):void 0,t.url=e.url!==void 0&&e.url!==null?yC.fromPartial(e.url):void 0,t.file=e.file!==void 0&&e.file!==null?xC.fromPartial(e.file):void 0,t}};function wC(){return{source:void 0,metadata:void 0,id:void 0}}var TC={encode(e,t=new Y){return e.source!==void 0&&CC.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(18).fork()).join(),e.id!==void 0&&t.uint32(26).string(e.id),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=wC();for(;n.pos>>3){case 1:if(e!==10)break;i.source=CC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.id=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return TC.fromPartial(e??{})},fromPartial(e){let t=wC();return t.source=e.source!==void 0&&e.source!==null?CC.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t.id=e.id??void 0,t}};function EC(){return{source:void 0,metadata:void 0,id:void 0}}var DC={encode(e,t=new Y){return e.source!==void 0&&CC.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(18).fork()).join(),e.id!==void 0&&t.uint32(26).string(e.id),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=EC();for(;n.pos>>3){case 1:if(e!==10)break;i.source=CC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.id=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return DC.fromPartial(e??{})},fromPartial(e){let t=EC();return t.source=e.source!==void 0&&e.source!==null?CC.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t.id=e.id??void 0,t}};function OC(){return{source:void 0,metadata:void 0,id:void 0}}var kC={encode(e,t=new Y){return e.source!==void 0&&CC.encode(e.source,t.uint32(10).fork()).join(),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(18).fork()).join(),e.id!==void 0&&t.uint32(26).string(e.id),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=OC();for(;n.pos>>3){case 1:if(e!==10)break;i.source=CC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.id=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return kC.fromPartial(e??{})},fromPartial(e){let t=OC();return t.source=e.source!==void 0&&e.source!==null?CC.fromPartial(e.source):void 0,t.metadata=e.metadata??void 0,t.id=e.id??void 0,t}};function AC(){return{text:void 0,image:void 0,audio:void 0,video:void 0,document:void 0}}var jC={encode(e,t=new Y){return e.text!==void 0&&pC.encode(e.text,t.uint32(10).fork()).join(),e.image!==void 0&&hC.encode(e.image,t.uint32(18).fork()).join(),e.audio!==void 0&&TC.encode(e.audio,t.uint32(26).fork()).join(),e.video!==void 0&&DC.encode(e.video,t.uint32(34).fork()).join(),e.document!==void 0&&kC.encode(e.document,t.uint32(42).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=AC();for(;n.pos>>3){case 1:if(e!==10)break;i.text=pC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.image=hC.decode(n,n.uint32());continue;case 3:if(e!==26)break;i.audio=TC.decode(n,n.uint32());continue;case 4:if(e!==34)break;i.video=DC.decode(n,n.uint32());continue;case 5:if(e!==42)break;i.document=kC.decode(n,n.uint32());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return jC.fromPartial(e??{})},fromPartial(e){let t=AC();return t.text=e.text!==void 0&&e.text!==null?pC.fromPartial(e.text):void 0,t.image=e.image!==void 0&&e.image!==null?hC.fromPartial(e.image):void 0,t.audio=e.audio!==void 0&&e.audio!==null?TC.fromPartial(e.audio):void 0,t.video=e.video!==void 0&&e.video!==null?DC.fromPartial(e.video):void 0,t.document=e.document!==void 0&&e.document!==null?kC.fromPartial(e.document):void 0,t}};function MC(){return{id:``,type:``,function:void 0,metadata:void 0,encryptedValue:void 0}}var NC={encode(e,t=new Y){return e.id!==``&&t.uint32(10).string(e.id),e.type!==``&&t.uint32(18).string(e.type),e.function!==void 0&&FC.encode(e.function,t.uint32(26).fork()).join(),e.metadata!==void 0&&rC.encode(rC.wrap(e.metadata),t.uint32(34).fork()).join(),e.encryptedValue!==void 0&&t.uint32(42).string(e.encryptedValue),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=MC();for(;n.pos>>3){case 1:if(e!==10)break;i.id=n.string();continue;case 2:if(e!==18)break;i.type=n.string();continue;case 3:if(e!==26)break;i.function=FC.decode(n,n.uint32());continue;case 4:if(e!==34)break;i.metadata=rC.unwrap(rC.decode(n,n.uint32()));continue;case 5:if(e!==42)break;i.encryptedValue=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return NC.fromPartial(e??{})},fromPartial(e){let t=MC();return t.id=e.id??``,t.type=e.type??``,t.function=e.function!==void 0&&e.function!==null?FC.fromPartial(e.function):void 0,t.metadata=e.metadata??void 0,t.encryptedValue=e.encryptedValue??void 0,t}};function PC(){return{name:``,arguments:``}}var FC={encode(e,t=new Y){return e.name!==``&&t.uint32(10).string(e.name),e.arguments!==``&&t.uint32(18).string(e.arguments),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=PC();for(;n.pos>>3){case 1:if(e!==10)break;i.name=n.string();continue;case 2:if(e!==18)break;i.arguments=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return FC.fromPartial(e??{})},fromPartial(e){let t=PC();return t.name=e.name??``,t.arguments=e.arguments??``,t}};function IC(){return{id:``,role:``,content:void 0,name:void 0,toolCalls:[],toolCallId:void 0,error:void 0,contentParts:[],metadata:void 0,subagentRunId:void 0,encryptedValue:void 0,activityType:void 0,activityContent:void 0}}var LC={encode(e,t=new Y){e.id!==``&&t.uint32(10).string(e.id),e.role!==``&&t.uint32(18).string(e.role),e.content!==void 0&&t.uint32(26).string(e.content),e.name!==void 0&&t.uint32(34).string(e.name);for(let n of e.toolCalls)NC.encode(n,t.uint32(42).fork()).join();e.toolCallId!==void 0&&t.uint32(50).string(e.toolCallId),e.error!==void 0&&t.uint32(58).string(e.error);for(let n of e.contentParts)jC.encode(n,t.uint32(66).fork()).join();return e.metadata!==void 0&&rC.encode(rC.wrap(e.metadata),t.uint32(74).fork()).join(),e.subagentRunId!==void 0&&t.uint32(82).string(e.subagentRunId),e.encryptedValue!==void 0&&t.uint32(90).string(e.encryptedValue),e.activityType!==void 0&&t.uint32(98).string(e.activityType),e.activityContent!==void 0&&rC.encode(rC.wrap(e.activityContent),t.uint32(106).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=IC();for(;n.pos>>3){case 1:if(e!==10)break;i.id=n.string();continue;case 2:if(e!==18)break;i.role=n.string();continue;case 3:if(e!==26)break;i.content=n.string();continue;case 4:if(e!==34)break;i.name=n.string();continue;case 5:if(e!==42)break;i.toolCalls.push(NC.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.toolCallId=n.string();continue;case 7:if(e!==58)break;i.error=n.string();continue;case 8:if(e!==66)break;i.contentParts.push(jC.decode(n,n.uint32()));continue;case 9:if(e!==74)break;i.metadata=rC.unwrap(rC.decode(n,n.uint32()));continue;case 10:if(e!==82)break;i.subagentRunId=n.string();continue;case 11:if(e!==90)break;i.encryptedValue=n.string();continue;case 12:if(e!==98)break;i.activityType=n.string();continue;case 13:if(e!==106)break;i.activityContent=rC.unwrap(rC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return LC.fromPartial(e??{})},fromPartial(e){let t=IC();return t.id=e.id??``,t.role=e.role??``,t.content=e.content??void 0,t.name=e.name??void 0,t.toolCalls=e.toolCalls?.map(e=>NC.fromPartial(e))||[],t.toolCallId=e.toolCallId??void 0,t.error=e.error??void 0,t.contentParts=e.contentParts?.map(e=>jC.fromPartial(e))||[],t.metadata=e.metadata??void 0,t.subagentRunId=e.subagentRunId??void 0,t.encryptedValue=e.encryptedValue??void 0,t.activityType=e.activityType??void 0,t.activityContent=e.activityContent??void 0,t}};function RC(){return{name:``,description:``,parameters:void 0,metadata:void 0}}var zC={encode(e,t=new Y){return e.name!==``&&t.uint32(10).string(e.name),e.description!==``&&t.uint32(18).string(e.description),e.parameters!==void 0&&Z.encode(Z.wrap(e.parameters),t.uint32(26).fork()).join(),e.metadata!==void 0&&rC.encode(rC.wrap(e.metadata),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=RC();for(;n.pos>>3){case 1:if(e!==10)break;i.name=n.string();continue;case 2:if(e!==18)break;i.description=n.string();continue;case 3:if(e!==26)break;i.parameters=Z.unwrap(Z.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.metadata=rC.unwrap(rC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return zC.fromPartial(e??{})},fromPartial(e){let t=RC();return t.name=e.name??``,t.description=e.description??``,t.parameters=e.parameters??void 0,t.metadata=e.metadata??void 0,t}};function BC(){return{description:``,value:``}}var VC={encode(e,t=new Y){return e.description!==``&&t.uint32(10).string(e.description),e.value!==``&&t.uint32(18).string(e.value),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=BC();for(;n.pos>>3){case 1:if(e!==10)break;i.description=n.string();continue;case 2:if(e!==18)break;i.value=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return VC.fromPartial(e??{})},fromPartial(e){let t=BC();return t.description=e.description??``,t.value=e.value??``,t}};function HC(){return{interruptId:``,status:``,payload:void 0,metadata:void 0}}var UC={encode(e,t=new Y){return e.interruptId!==``&&t.uint32(10).string(e.interruptId),e.status!==``&&t.uint32(18).string(e.status),e.payload!==void 0&&Z.encode(Z.wrap(e.payload),t.uint32(26).fork()).join(),e.metadata!==void 0&&rC.encode(rC.wrap(e.metadata),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=HC();for(;n.pos>>3){case 1:if(e!==10)break;i.interruptId=n.string();continue;case 2:if(e!==18)break;i.status=n.string();continue;case 3:if(e!==26)break;i.payload=Z.unwrap(Z.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.metadata=rC.unwrap(rC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return UC.fromPartial(e??{})},fromPartial(e){let t=HC();return t.interruptId=e.interruptId??``,t.status=e.status??``,t.payload=e.payload??void 0,t.metadata=e.metadata??void 0,t}};function WC(){return{threadId:``,runId:``,parentRunId:void 0,state:void 0,messages:[],tools:[],context:[],forwardedProps:void 0,resume:[],protocolVersion:void 0}}var GC={encode(e,t=new Y){e.threadId!==``&&t.uint32(10).string(e.threadId),e.runId!==``&&t.uint32(18).string(e.runId),e.parentRunId!==void 0&&t.uint32(26).string(e.parentRunId),e.state!==void 0&&Z.encode(Z.wrap(e.state),t.uint32(34).fork()).join();for(let n of e.messages)LC.encode(n,t.uint32(42).fork()).join();for(let n of e.tools)zC.encode(n,t.uint32(50).fork()).join();for(let n of e.context)VC.encode(n,t.uint32(58).fork()).join();e.forwardedProps!==void 0&&Z.encode(Z.wrap(e.forwardedProps),t.uint32(66).fork()).join();for(let n of e.resume)UC.encode(n,t.uint32(74).fork()).join();return e.protocolVersion!==void 0&&t.uint32(82).string(e.protocolVersion),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=WC();for(;n.pos>>3){case 1:if(e!==10)break;i.threadId=n.string();continue;case 2:if(e!==18)break;i.runId=n.string();continue;case 3:if(e!==26)break;i.parentRunId=n.string();continue;case 4:if(e!==34)break;i.state=Z.unwrap(Z.decode(n,n.uint32()));continue;case 5:if(e!==42)break;i.messages.push(LC.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.tools.push(zC.decode(n,n.uint32()));continue;case 7:if(e!==58)break;i.context.push(VC.decode(n,n.uint32()));continue;case 8:if(e!==66)break;i.forwardedProps=Z.unwrap(Z.decode(n,n.uint32()));continue;case 9:if(e!==74)break;i.resume.push(UC.decode(n,n.uint32()));continue;case 10:if(e!==82)break;i.protocolVersion=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return GC.fromPartial(e??{})},fromPartial(e){let t=WC();return t.threadId=e.threadId??``,t.runId=e.runId??``,t.parentRunId=e.parentRunId??void 0,t.state=e.state??void 0,t.messages=e.messages?.map(e=>LC.fromPartial(e))||[],t.tools=e.tools?.map(e=>zC.fromPartial(e))||[],t.context=e.context?.map(e=>VC.fromPartial(e))||[],t.forwardedProps=e.forwardedProps??void 0,t.resume=e.resume?.map(e=>UC.fromPartial(e))||[],t.protocolVersion=e.protocolVersion??void 0,t}};function KC(){return{id:``,reason:``,message:void 0,toolCallId:void 0,responseSchema:void 0,expiresAt:void 0,metadata:void 0,subagentRunId:void 0}}var qC={encode(e,t=new Y){return e.id!==``&&t.uint32(10).string(e.id),e.reason!==``&&t.uint32(18).string(e.reason),e.message!==void 0&&t.uint32(26).string(e.message),e.toolCallId!==void 0&&t.uint32(34).string(e.toolCallId),e.responseSchema!==void 0&&Z.encode(Z.wrap(e.responseSchema),t.uint32(42).fork()).join(),e.expiresAt!==void 0&&t.uint32(50).string(e.expiresAt),e.metadata!==void 0&&Z.encode(Z.wrap(e.metadata),t.uint32(58).fork()).join(),e.subagentRunId!==void 0&&t.uint32(66).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=KC();for(;n.pos>>3){case 1:if(e!==10)break;i.id=n.string();continue;case 2:if(e!==18)break;i.reason=n.string();continue;case 3:if(e!==26)break;i.message=n.string();continue;case 4:if(e!==34)break;i.toolCallId=n.string();continue;case 5:if(e!==42)break;i.responseSchema=Z.unwrap(Z.decode(n,n.uint32()));continue;case 6:if(e!==50)break;i.expiresAt=n.string();continue;case 7:if(e!==58)break;i.metadata=Z.unwrap(Z.decode(n,n.uint32()));continue;case 8:if(e!==66)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return qC.fromPartial(e??{})},fromPartial(e){let t=KC();return t.id=e.id??``,t.reason=e.reason??``,t.message=e.message??void 0,t.toolCallId=e.toolCallId??void 0,t.responseSchema=e.responseSchema??void 0,t.expiresAt=e.expiresAt??void 0,t.metadata=e.metadata??void 0,t.subagentRunId=e.subagentRunId??void 0,t}},JC=function(e){return e[e.TEXT_MESSAGE_START=0]=`TEXT_MESSAGE_START`,e[e.TEXT_MESSAGE_CONTENT=1]=`TEXT_MESSAGE_CONTENT`,e[e.TEXT_MESSAGE_END=2]=`TEXT_MESSAGE_END`,e[e.TOOL_CALL_START=3]=`TOOL_CALL_START`,e[e.TOOL_CALL_ARGS=4]=`TOOL_CALL_ARGS`,e[e.TOOL_CALL_END=5]=`TOOL_CALL_END`,e[e.STATE_SNAPSHOT=6]=`STATE_SNAPSHOT`,e[e.STATE_DELTA=7]=`STATE_DELTA`,e[e.MESSAGES_SNAPSHOT=8]=`MESSAGES_SNAPSHOT`,e[e.RAW=9]=`RAW`,e[e.CUSTOM=10]=`CUSTOM`,e[e.RUN_STARTED=11]=`RUN_STARTED`,e[e.RUN_FINISHED=12]=`RUN_FINISHED`,e[e.RUN_ERROR=13]=`RUN_ERROR`,e[e.STEP_STARTED=14]=`STEP_STARTED`,e[e.STEP_FINISHED=15]=`STEP_FINISHED`,e[e.SUBAGENT_STARTED=16]=`SUBAGENT_STARTED`,e[e.SUBAGENT_FINISHED=17]=`SUBAGENT_FINISHED`,e[e.SUBAGENT_ERROR=18]=`SUBAGENT_ERROR`,e[e.TEXT_MESSAGE_CHUNK=19]=`TEXT_MESSAGE_CHUNK`,e[e.TOOL_CALL_CHUNK=20]=`TOOL_CALL_CHUNK`,e[e.TOOL_CALL_RESULT=21]=`TOOL_CALL_RESULT`,e[e.ACTIVITY_SNAPSHOT=22]=`ACTIVITY_SNAPSHOT`,e[e.ACTIVITY_DELTA=23]=`ACTIVITY_DELTA`,e[e.REASONING_START=24]=`REASONING_START`,e[e.REASONING_MESSAGE_START=25]=`REASONING_MESSAGE_START`,e[e.REASONING_MESSAGE_CONTENT=26]=`REASONING_MESSAGE_CONTENT`,e[e.REASONING_MESSAGE_END=27]=`REASONING_MESSAGE_END`,e[e.REASONING_MESSAGE_CHUNK=28]=`REASONING_MESSAGE_CHUNK`,e[e.REASONING_END=29]=`REASONING_END`,e[e.REASONING_ENCRYPTED_VALUE=30]=`REASONING_ENCRYPTED_VALUE`,e[e.UNRECOGNIZED=-1]=`UNRECOGNIZED`,e}({});function YC(){return{type:0,timestamp:void 0,rawEvent:void 0,metadata:void 0}}var Q={encode(e,t=new Y){return e.type!==0&&t.uint32(8).int32(e.type),e.timestamp!==void 0&&t.uint32(16).int64(e.timestamp),e.rawEvent!==void 0&&Z.encode(Z.wrap(e.rawEvent),t.uint32(26).fork()).join(),e.metadata!==void 0&&rC.encode(rC.wrap(e.metadata),t.uint32(34).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=YC();for(;n.pos>>3){case 1:if(e!==8)break;i.type=n.int32();continue;case 2:if(e!==16)break;i.timestamp=cT(n.int64());continue;case 3:if(e!==26)break;i.rawEvent=Z.unwrap(Z.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.metadata=rC.unwrap(rC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Q.fromPartial(e??{})},fromPartial(e){let t=YC();return t.type=e.type??0,t.timestamp=e.timestamp??void 0,t.rawEvent=e.rawEvent??void 0,t.metadata=e.metadata??void 0,t}};function XC(){return{baseEvent:void 0,messageId:``,role:void 0,name:void 0,subagentRunId:void 0}}var ZC={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==``&&t.uint32(18).string(e.messageId),e.role!==void 0&&t.uint32(26).string(e.role),e.name!==void 0&&t.uint32(34).string(e.name),e.subagentRunId!==void 0&&t.uint32(42).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=XC();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.role=n.string();continue;case 4:if(e!==34)break;i.name=n.string();continue;case 5:if(e!==42)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return ZC.fromPartial(e??{})},fromPartial(e){let t=XC();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??``,t.role=e.role??void 0,t.name=e.name??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function QC(){return{baseEvent:void 0,messageId:``,delta:``,subagentRunId:void 0}}var $C={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==``&&t.uint32(18).string(e.messageId),e.delta!==``&&t.uint32(26).string(e.delta),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=QC();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.delta=n.string();continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return $C.fromPartial(e??{})},fromPartial(e){let t=QC();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??``,t.delta=e.delta??``,t.subagentRunId=e.subagentRunId??void 0,t}};function ew(){return{baseEvent:void 0,messageId:``,subagentRunId:void 0}}var tw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==``&&t.uint32(18).string(e.messageId),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=ew();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return tw.fromPartial(e??{})},fromPartial(e){let t=ew();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??``,t.subagentRunId=e.subagentRunId??void 0,t}};function nw(){return{baseEvent:void 0,messageId:void 0,role:void 0,delta:void 0,name:void 0,subagentRunId:void 0}}var rw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.messageId!==void 0&&t.uint32(18).string(e.messageId),e.role!==void 0&&t.uint32(26).string(e.role),e.delta!==void 0&&t.uint32(34).string(e.delta),e.name!==void 0&&t.uint32(42).string(e.name),e.subagentRunId!==void 0&&t.uint32(50).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=nw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messageId=n.string();continue;case 3:if(e!==26)break;i.role=n.string();continue;case 4:if(e!==34)break;i.delta=n.string();continue;case 5:if(e!==42)break;i.name=n.string();continue;case 6:if(e!==50)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return rw.fromPartial(e??{})},fromPartial(e){let t=nw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.messageId=e.messageId??void 0,t.role=e.role??void 0,t.delta=e.delta??void 0,t.name=e.name??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function iw(){return{baseEvent:void 0,toolCallId:``,toolCallName:``,parentMessageId:void 0,subagentRunId:void 0}}var aw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==``&&t.uint32(18).string(e.toolCallId),e.toolCallName!==``&&t.uint32(26).string(e.toolCallName),e.parentMessageId!==void 0&&t.uint32(34).string(e.parentMessageId),e.subagentRunId!==void 0&&t.uint32(42).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=iw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.toolCallName=n.string();continue;case 4:if(e!==34)break;i.parentMessageId=n.string();continue;case 5:if(e!==42)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return aw.fromPartial(e??{})},fromPartial(e){let t=iw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??``,t.toolCallName=e.toolCallName??``,t.parentMessageId=e.parentMessageId??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function ow(){return{baseEvent:void 0,toolCallId:``,delta:``,subagentRunId:void 0}}var sw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==``&&t.uint32(18).string(e.toolCallId),e.delta!==``&&t.uint32(26).string(e.delta),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=ow();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.delta=n.string();continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return sw.fromPartial(e??{})},fromPartial(e){let t=ow();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??``,t.delta=e.delta??``,t.subagentRunId=e.subagentRunId??void 0,t}};function cw(){return{baseEvent:void 0,toolCallId:``,subagentRunId:void 0}}var lw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==``&&t.uint32(18).string(e.toolCallId),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=cw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return lw.fromPartial(e??{})},fromPartial(e){let t=cw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??``,t.subagentRunId=e.subagentRunId??void 0,t}};function uw(){return{baseEvent:void 0,toolCallId:void 0,toolCallName:void 0,parentMessageId:void 0,delta:void 0,subagentRunId:void 0}}var dw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.toolCallId!==void 0&&t.uint32(18).string(e.toolCallId),e.toolCallName!==void 0&&t.uint32(26).string(e.toolCallName),e.parentMessageId!==void 0&&t.uint32(34).string(e.parentMessageId),e.delta!==void 0&&t.uint32(42).string(e.delta),e.subagentRunId!==void 0&&t.uint32(50).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=uw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.toolCallId=n.string();continue;case 3:if(e!==26)break;i.toolCallName=n.string();continue;case 4:if(e!==34)break;i.parentMessageId=n.string();continue;case 5:if(e!==42)break;i.delta=n.string();continue;case 6:if(e!==50)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return dw.fromPartial(e??{})},fromPartial(e){let t=uw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.toolCallId=e.toolCallId??void 0,t.toolCallName=e.toolCallName??void 0,t.parentMessageId=e.parentMessageId??void 0,t.delta=e.delta??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function fw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``,toolCallId:``,content:void 0,role:void 0,contentParts:[]}}var pw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),e.toolCallId!==``&&t.uint32(34).string(e.toolCallId),e.content!==void 0&&t.uint32(42).string(e.content),e.role!==void 0&&t.uint32(50).string(e.role);for(let n of e.contentParts)jC.encode(n,t.uint32(58).fork()).join();return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=fw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.toolCallId=n.string();continue;case 5:if(e!==42)break;i.content=n.string();continue;case 6:if(e!==50)break;i.role=n.string();continue;case 7:if(e!==58)break;i.contentParts.push(jC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return pw.fromPartial(e??{})},fromPartial(e){let t=fw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t.toolCallId=e.toolCallId??``,t.content=e.content??void 0,t.role=e.role??void 0,t.contentParts=e.contentParts?.map(e=>jC.fromPartial(e))||[],t}};function mw(){return{baseEvent:void 0,snapshot:void 0,subagentRunId:void 0}}var hw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.snapshot!==void 0&&Z.encode(Z.wrap(e.snapshot),t.uint32(18).fork()).join(),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=mw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.snapshot=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return hw.fromPartial(e??{})},fromPartial(e){let t=mw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.snapshot=e.snapshot??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function gw(){return{baseEvent:void 0,delta:[],subagentRunId:void 0}}var _w={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join();for(let n of e.delta)dC.encode(n,t.uint32(18).fork()).join();return e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=gw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.delta.push(dC.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return _w.fromPartial(e??{})},fromPartial(e){let t=gw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.delta=e.delta?.map(e=>dC.fromPartial(e))||[],t.subagentRunId=e.subagentRunId??void 0,t}};function vw(){return{baseEvent:void 0,messages:[]}}var yw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join();for(let n of e.messages)LC.encode(n,t.uint32(18).fork()).join();return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=vw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.messages.push(LC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return yw.fromPartial(e??{})},fromPartial(e){let t=vw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.messages=e.messages?.map(e=>LC.fromPartial(e))||[],t}};function bw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``,activityType:``,content:void 0,replace:void 0}}var xw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),e.activityType!==``&&t.uint32(34).string(e.activityType),e.content!==void 0&&rC.encode(rC.wrap(e.content),t.uint32(42).fork()).join(),e.replace!==void 0&&t.uint32(48).bool(e.replace),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=bw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.activityType=n.string();continue;case 5:if(e!==42)break;i.content=rC.unwrap(rC.decode(n,n.uint32()));continue;case 6:if(e!==48)break;i.replace=n.bool();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return xw.fromPartial(e??{})},fromPartial(e){let t=bw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t.activityType=e.activityType??``,t.content=e.content??void 0,t.replace=e.replace??void 0,t}};function Sw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``,activityType:``,patch:[]}}var Cw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),e.activityType!==``&&t.uint32(34).string(e.activityType);for(let n of e.patch)dC.encode(n,t.uint32(42).fork()).join();return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Sw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.activityType=n.string();continue;case 5:if(e!==42)break;i.patch.push(dC.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Cw.fromPartial(e??{})},fromPartial(e){let t=Sw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t.activityType=e.activityType??``,t.patch=e.patch?.map(e=>dC.fromPartial(e))||[],t}};function ww(){return{baseEvent:void 0,event:void 0,source:void 0,subagentRunId:void 0}}var Tw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.event!==void 0&&Z.encode(Z.wrap(e.event),t.uint32(18).fork()).join(),e.source!==void 0&&t.uint32(26).string(e.source),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=ww();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.event=Z.unwrap(Z.decode(n,n.uint32()));continue;case 3:if(e!==26)break;i.source=n.string();continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Tw.fromPartial(e??{})},fromPartial(e){let t=ww();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.event=e.event??void 0,t.source=e.source??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function Ew(){return{baseEvent:void 0,name:``,value:void 0,subagentRunId:void 0}}var Dw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.name!==``&&t.uint32(18).string(e.name),e.value!==void 0&&Z.encode(Z.wrap(e.value),t.uint32(26).fork()).join(),e.subagentRunId!==void 0&&t.uint32(34).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Ew();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.name=n.string();continue;case 3:if(e!==26)break;i.value=Z.unwrap(Z.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Dw.fromPartial(e??{})},fromPartial(e){let t=Ew();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.name=e.name??``,t.value=e.value??void 0,t.subagentRunId=e.subagentRunId??void 0,t}};function Ow(){return{baseEvent:void 0,threadId:``,runId:``,parentRunId:void 0,input:void 0,protocolVersion:void 0}}var kw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.threadId!==``&&t.uint32(18).string(e.threadId),e.runId!==``&&t.uint32(26).string(e.runId),e.parentRunId!==void 0&&t.uint32(34).string(e.parentRunId),e.input!==void 0&&GC.encode(e.input,t.uint32(42).fork()).join(),e.protocolVersion!==void 0&&t.uint32(50).string(e.protocolVersion),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Ow();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.threadId=n.string();continue;case 3:if(e!==26)break;i.runId=n.string();continue;case 4:if(e!==34)break;i.parentRunId=n.string();continue;case 5:if(e!==42)break;i.input=GC.decode(n,n.uint32());continue;case 6:if(e!==50)break;i.protocolVersion=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return kw.fromPartial(e??{})},fromPartial(e){let t=Ow();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.threadId=e.threadId??``,t.runId=e.runId??``,t.parentRunId=e.parentRunId??void 0,t.input=e.input!==void 0&&e.input!==null?GC.fromPartial(e.input):void 0,t.protocolVersion=e.protocolVersion??void 0,t}};function Aw(){return{baseEvent:void 0,threadId:``,runId:``,result:void 0,outcome:``,interrupts:[],usage:[],pendingToolCallIds:[]}}var jw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.threadId!==``&&t.uint32(18).string(e.threadId),e.runId!==``&&t.uint32(26).string(e.runId),e.result!==void 0&&Z.encode(Z.wrap(e.result),t.uint32(34).fork()).join(),e.outcome!==``&&t.uint32(42).string(e.outcome);for(let n of e.interrupts)qC.encode(n,t.uint32(50).fork()).join();for(let n of e.usage)sT.encode(n,t.uint32(58).fork()).join();for(let n of e.pendingToolCallIds)t.uint32(66).string(n);return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Aw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.threadId=n.string();continue;case 3:if(e!==26)break;i.runId=n.string();continue;case 4:if(e!==34)break;i.result=Z.unwrap(Z.decode(n,n.uint32()));continue;case 5:if(e!==42)break;i.outcome=n.string();continue;case 6:if(e!==50)break;i.interrupts.push(qC.decode(n,n.uint32()));continue;case 7:if(e!==58)break;i.usage.push(sT.decode(n,n.uint32()));continue;case 8:if(e!==66)break;i.pendingToolCallIds.push(n.string());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return jw.fromPartial(e??{})},fromPartial(e){let t=Aw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.threadId=e.threadId??``,t.runId=e.runId??``,t.result=e.result??void 0,t.outcome=e.outcome??``,t.interrupts=e.interrupts?.map(e=>qC.fromPartial(e))||[],t.usage=e.usage?.map(e=>sT.fromPartial(e))||[],t.pendingToolCallIds=e.pendingToolCallIds?.map(e=>e)||[],t}};function Mw(){return{baseEvent:void 0,code:void 0,message:``,usage:[]}}var Nw={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.code!==void 0&&t.uint32(18).string(e.code),e.message!==``&&t.uint32(26).string(e.message);for(let n of e.usage)sT.encode(n,t.uint32(34).fork()).join();return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Mw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.code=n.string();continue;case 3:if(e!==26)break;i.message=n.string();continue;case 4:if(e!==34)break;i.usage.push(sT.decode(n,n.uint32()));continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Nw.fromPartial(e??{})},fromPartial(e){let t=Mw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.code=e.code??void 0,t.message=e.message??``,t.usage=e.usage?.map(e=>sT.fromPartial(e))||[],t}};function Pw(){return{baseEvent:void 0,stepName:``,subagentRunId:void 0}}var Fw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.stepName!==``&&t.uint32(18).string(e.stepName),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Pw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.stepName=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Fw.fromPartial(e??{})},fromPartial(e){let t=Pw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.stepName=e.stepName??``,t.subagentRunId=e.subagentRunId??void 0,t}};function Iw(){return{baseEvent:void 0,stepName:``,subagentRunId:void 0}}var Lw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.stepName!==``&&t.uint32(18).string(e.stepName),e.subagentRunId!==void 0&&t.uint32(26).string(e.subagentRunId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Iw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.stepName=n.string();continue;case 3:if(e!==26)break;i.subagentRunId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Lw.fromPartial(e??{})},fromPartial(e){let t=Iw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.stepName=e.stepName??``,t.subagentRunId=e.subagentRunId??void 0,t}};function Rw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``}}var zw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Rw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return zw.fromPartial(e??{})},fromPartial(e){let t=Rw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t}};function Bw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``,role:``}}var Vw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),e.role!==``&&t.uint32(34).string(e.role),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Bw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.role=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Vw.fromPartial(e??{})},fromPartial(e){let t=Bw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t.role=e.role??``,t}};function Hw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``,delta:``}}var Uw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),e.delta!==``&&t.uint32(34).string(e.delta),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Hw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.delta=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Uw.fromPartial(e??{})},fromPartial(e){let t=Hw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t.delta=e.delta??``,t}};function Ww(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``}}var Gw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Ww();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Gw.fromPartial(e??{})},fromPartial(e){let t=Ww();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t}};function Kw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:void 0,delta:void 0}}var qw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==void 0&&t.uint32(26).string(e.messageId),e.delta!==void 0&&t.uint32(34).string(e.delta),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Kw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue;case 4:if(e!==34)break;i.delta=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return qw.fromPartial(e??{})},fromPartial(e){let t=Kw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??void 0,t.delta=e.delta??void 0,t}};function Jw(){return{baseEvent:void 0,subagentRunId:void 0,messageId:``}}var Yw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.messageId!==``&&t.uint32(26).string(e.messageId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Jw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.messageId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Yw.fromPartial(e??{})},fromPartial(e){let t=Jw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.messageId=e.messageId??``,t}};function Xw(){return{baseEvent:void 0,subagentRunId:void 0,subtype:``,entityId:``,encryptedValue:``}}var Zw={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==void 0&&t.uint32(18).string(e.subagentRunId),e.subtype!==``&&t.uint32(26).string(e.subtype),e.entityId!==``&&t.uint32(34).string(e.entityId),e.encryptedValue!==``&&t.uint32(42).string(e.encryptedValue),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Xw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.subtype=n.string();continue;case 4:if(e!==34)break;i.entityId=n.string();continue;case 5:if(e!==42)break;i.encryptedValue=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return Zw.fromPartial(e??{})},fromPartial(e){let t=Xw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??void 0,t.subtype=e.subtype??``,t.entityId=e.entityId??``,t.encryptedValue=e.encryptedValue??``,t}};function Qw(){return{baseEvent:void 0,subagentRunId:``,name:``,description:void 0,parentSubagentRunId:void 0,parentToolCallId:void 0,parentMessageId:void 0}}var $w={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==``&&t.uint32(18).string(e.subagentRunId),e.name!==``&&t.uint32(26).string(e.name),e.description!==void 0&&t.uint32(34).string(e.description),e.parentSubagentRunId!==void 0&&t.uint32(42).string(e.parentSubagentRunId),e.parentToolCallId!==void 0&&t.uint32(50).string(e.parentToolCallId),e.parentMessageId!==void 0&&t.uint32(58).string(e.parentMessageId),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=Qw();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.name=n.string();continue;case 4:if(e!==34)break;i.description=n.string();continue;case 5:if(e!==42)break;i.parentSubagentRunId=n.string();continue;case 6:if(e!==50)break;i.parentToolCallId=n.string();continue;case 7:if(e!==58)break;i.parentMessageId=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return $w.fromPartial(e??{})},fromPartial(e){let t=Qw();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??``,t.name=e.name??``,t.description=e.description??void 0,t.parentSubagentRunId=e.parentSubagentRunId??void 0,t.parentToolCallId=e.parentToolCallId??void 0,t.parentMessageId=e.parentMessageId??void 0,t}};function eT(){return{baseEvent:void 0,subagentRunId:``,result:void 0,outcome:``,interruptIds:[]}}var tT={encode(e,t=new Y){e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==``&&t.uint32(18).string(e.subagentRunId),e.result!==void 0&&Z.encode(Z.wrap(e.result),t.uint32(26).fork()).join(),e.outcome!==``&&t.uint32(34).string(e.outcome);for(let n of e.interruptIds)t.uint32(42).string(n);return t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=eT();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.result=Z.unwrap(Z.decode(n,n.uint32()));continue;case 4:if(e!==34)break;i.outcome=n.string();continue;case 5:if(e!==42)break;i.interruptIds.push(n.string());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return tT.fromPartial(e??{})},fromPartial(e){let t=eT();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??``,t.result=e.result??void 0,t.outcome=e.outcome??``,t.interruptIds=e.interruptIds?.map(e=>e)||[],t}};function nT(){return{baseEvent:void 0,subagentRunId:``,message:``,code:void 0}}var rT={encode(e,t=new Y){return e.baseEvent!==void 0&&Q.encode(e.baseEvent,t.uint32(10).fork()).join(),e.subagentRunId!==``&&t.uint32(18).string(e.subagentRunId),e.message!==``&&t.uint32(26).string(e.message),e.code!==void 0&&t.uint32(34).string(e.code),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=nT();for(;n.pos>>3){case 1:if(e!==10)break;i.baseEvent=Q.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.subagentRunId=n.string();continue;case 3:if(e!==26)break;i.message=n.string();continue;case 4:if(e!==34)break;i.code=n.string();continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return rT.fromPartial(e??{})},fromPartial(e){let t=nT();return t.baseEvent=e.baseEvent!==void 0&&e.baseEvent!==null?Q.fromPartial(e.baseEvent):void 0,t.subagentRunId=e.subagentRunId??``,t.message=e.message??``,t.code=e.code??void 0,t}};function iT(){return{textMessageStart:void 0,textMessageContent:void 0,textMessageEnd:void 0,toolCallStart:void 0,toolCallArgs:void 0,toolCallEnd:void 0,stateSnapshot:void 0,stateDelta:void 0,messagesSnapshot:void 0,raw:void 0,custom:void 0,runStarted:void 0,runFinished:void 0,runError:void 0,stepStarted:void 0,stepFinished:void 0,textMessageChunk:void 0,toolCallChunk:void 0,subagentStarted:void 0,subagentFinished:void 0,subagentError:void 0,toolCallResult:void 0,activitySnapshot:void 0,activityDelta:void 0,reasoningStart:void 0,reasoningMessageStart:void 0,reasoningMessageContent:void 0,reasoningMessageEnd:void 0,reasoningMessageChunk:void 0,reasoningEnd:void 0,reasoningEncryptedValue:void 0}}var aT={encode(e,t=new Y){return e.textMessageStart!==void 0&&ZC.encode(e.textMessageStart,t.uint32(10).fork()).join(),e.textMessageContent!==void 0&&$C.encode(e.textMessageContent,t.uint32(18).fork()).join(),e.textMessageEnd!==void 0&&tw.encode(e.textMessageEnd,t.uint32(26).fork()).join(),e.toolCallStart!==void 0&&aw.encode(e.toolCallStart,t.uint32(34).fork()).join(),e.toolCallArgs!==void 0&&sw.encode(e.toolCallArgs,t.uint32(42).fork()).join(),e.toolCallEnd!==void 0&&lw.encode(e.toolCallEnd,t.uint32(50).fork()).join(),e.stateSnapshot!==void 0&&hw.encode(e.stateSnapshot,t.uint32(58).fork()).join(),e.stateDelta!==void 0&&_w.encode(e.stateDelta,t.uint32(66).fork()).join(),e.messagesSnapshot!==void 0&&yw.encode(e.messagesSnapshot,t.uint32(74).fork()).join(),e.raw!==void 0&&Tw.encode(e.raw,t.uint32(82).fork()).join(),e.custom!==void 0&&Dw.encode(e.custom,t.uint32(90).fork()).join(),e.runStarted!==void 0&&kw.encode(e.runStarted,t.uint32(98).fork()).join(),e.runFinished!==void 0&&jw.encode(e.runFinished,t.uint32(106).fork()).join(),e.runError!==void 0&&Nw.encode(e.runError,t.uint32(114).fork()).join(),e.stepStarted!==void 0&&Fw.encode(e.stepStarted,t.uint32(122).fork()).join(),e.stepFinished!==void 0&&Lw.encode(e.stepFinished,t.uint32(130).fork()).join(),e.textMessageChunk!==void 0&&rw.encode(e.textMessageChunk,t.uint32(138).fork()).join(),e.toolCallChunk!==void 0&&dw.encode(e.toolCallChunk,t.uint32(146).fork()).join(),e.subagentStarted!==void 0&&$w.encode(e.subagentStarted,t.uint32(154).fork()).join(),e.subagentFinished!==void 0&&tT.encode(e.subagentFinished,t.uint32(162).fork()).join(),e.subagentError!==void 0&&rT.encode(e.subagentError,t.uint32(170).fork()).join(),e.toolCallResult!==void 0&&pw.encode(e.toolCallResult,t.uint32(178).fork()).join(),e.activitySnapshot!==void 0&&xw.encode(e.activitySnapshot,t.uint32(186).fork()).join(),e.activityDelta!==void 0&&Cw.encode(e.activityDelta,t.uint32(194).fork()).join(),e.reasoningStart!==void 0&&zw.encode(e.reasoningStart,t.uint32(202).fork()).join(),e.reasoningMessageStart!==void 0&&Vw.encode(e.reasoningMessageStart,t.uint32(210).fork()).join(),e.reasoningMessageContent!==void 0&&Uw.encode(e.reasoningMessageContent,t.uint32(218).fork()).join(),e.reasoningMessageEnd!==void 0&&Gw.encode(e.reasoningMessageEnd,t.uint32(226).fork()).join(),e.reasoningMessageChunk!==void 0&&qw.encode(e.reasoningMessageChunk,t.uint32(234).fork()).join(),e.reasoningEnd!==void 0&&Yw.encode(e.reasoningEnd,t.uint32(242).fork()).join(),e.reasoningEncryptedValue!==void 0&&Zw.encode(e.reasoningEncryptedValue,t.uint32(250).fork()).join(),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=iT();for(;n.pos>>3){case 1:if(e!==10)break;i.textMessageStart=ZC.decode(n,n.uint32());continue;case 2:if(e!==18)break;i.textMessageContent=$C.decode(n,n.uint32());continue;case 3:if(e!==26)break;i.textMessageEnd=tw.decode(n,n.uint32());continue;case 4:if(e!==34)break;i.toolCallStart=aw.decode(n,n.uint32());continue;case 5:if(e!==42)break;i.toolCallArgs=sw.decode(n,n.uint32());continue;case 6:if(e!==50)break;i.toolCallEnd=lw.decode(n,n.uint32());continue;case 7:if(e!==58)break;i.stateSnapshot=hw.decode(n,n.uint32());continue;case 8:if(e!==66)break;i.stateDelta=_w.decode(n,n.uint32());continue;case 9:if(e!==74)break;i.messagesSnapshot=yw.decode(n,n.uint32());continue;case 10:if(e!==82)break;i.raw=Tw.decode(n,n.uint32());continue;case 11:if(e!==90)break;i.custom=Dw.decode(n,n.uint32());continue;case 12:if(e!==98)break;i.runStarted=kw.decode(n,n.uint32());continue;case 13:if(e!==106)break;i.runFinished=jw.decode(n,n.uint32());continue;case 14:if(e!==114)break;i.runError=Nw.decode(n,n.uint32());continue;case 15:if(e!==122)break;i.stepStarted=Fw.decode(n,n.uint32());continue;case 16:if(e!==130)break;i.stepFinished=Lw.decode(n,n.uint32());continue;case 17:if(e!==138)break;i.textMessageChunk=rw.decode(n,n.uint32());continue;case 18:if(e!==146)break;i.toolCallChunk=dw.decode(n,n.uint32());continue;case 19:if(e!==154)break;i.subagentStarted=$w.decode(n,n.uint32());continue;case 20:if(e!==162)break;i.subagentFinished=tT.decode(n,n.uint32());continue;case 21:if(e!==170)break;i.subagentError=rT.decode(n,n.uint32());continue;case 22:if(e!==178)break;i.toolCallResult=pw.decode(n,n.uint32());continue;case 23:if(e!==186)break;i.activitySnapshot=xw.decode(n,n.uint32());continue;case 24:if(e!==194)break;i.activityDelta=Cw.decode(n,n.uint32());continue;case 25:if(e!==202)break;i.reasoningStart=zw.decode(n,n.uint32());continue;case 26:if(e!==210)break;i.reasoningMessageStart=Vw.decode(n,n.uint32());continue;case 27:if(e!==218)break;i.reasoningMessageContent=Uw.decode(n,n.uint32());continue;case 28:if(e!==226)break;i.reasoningMessageEnd=Gw.decode(n,n.uint32());continue;case 29:if(e!==234)break;i.reasoningMessageChunk=qw.decode(n,n.uint32());continue;case 30:if(e!==242)break;i.reasoningEnd=Yw.decode(n,n.uint32());continue;case 31:if(e!==250)break;i.reasoningEncryptedValue=Zw.decode(n,n.uint32());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return aT.fromPartial(e??{})},fromPartial(e){let t=iT();return t.textMessageStart=e.textMessageStart!==void 0&&e.textMessageStart!==null?ZC.fromPartial(e.textMessageStart):void 0,t.textMessageContent=e.textMessageContent!==void 0&&e.textMessageContent!==null?$C.fromPartial(e.textMessageContent):void 0,t.textMessageEnd=e.textMessageEnd!==void 0&&e.textMessageEnd!==null?tw.fromPartial(e.textMessageEnd):void 0,t.toolCallStart=e.toolCallStart!==void 0&&e.toolCallStart!==null?aw.fromPartial(e.toolCallStart):void 0,t.toolCallArgs=e.toolCallArgs!==void 0&&e.toolCallArgs!==null?sw.fromPartial(e.toolCallArgs):void 0,t.toolCallEnd=e.toolCallEnd!==void 0&&e.toolCallEnd!==null?lw.fromPartial(e.toolCallEnd):void 0,t.stateSnapshot=e.stateSnapshot!==void 0&&e.stateSnapshot!==null?hw.fromPartial(e.stateSnapshot):void 0,t.stateDelta=e.stateDelta!==void 0&&e.stateDelta!==null?_w.fromPartial(e.stateDelta):void 0,t.messagesSnapshot=e.messagesSnapshot!==void 0&&e.messagesSnapshot!==null?yw.fromPartial(e.messagesSnapshot):void 0,t.raw=e.raw!==void 0&&e.raw!==null?Tw.fromPartial(e.raw):void 0,t.custom=e.custom!==void 0&&e.custom!==null?Dw.fromPartial(e.custom):void 0,t.runStarted=e.runStarted!==void 0&&e.runStarted!==null?kw.fromPartial(e.runStarted):void 0,t.runFinished=e.runFinished!==void 0&&e.runFinished!==null?jw.fromPartial(e.runFinished):void 0,t.runError=e.runError!==void 0&&e.runError!==null?Nw.fromPartial(e.runError):void 0,t.stepStarted=e.stepStarted!==void 0&&e.stepStarted!==null?Fw.fromPartial(e.stepStarted):void 0,t.stepFinished=e.stepFinished!==void 0&&e.stepFinished!==null?Lw.fromPartial(e.stepFinished):void 0,t.textMessageChunk=e.textMessageChunk!==void 0&&e.textMessageChunk!==null?rw.fromPartial(e.textMessageChunk):void 0,t.toolCallChunk=e.toolCallChunk!==void 0&&e.toolCallChunk!==null?dw.fromPartial(e.toolCallChunk):void 0,t.subagentStarted=e.subagentStarted!==void 0&&e.subagentStarted!==null?$w.fromPartial(e.subagentStarted):void 0,t.subagentFinished=e.subagentFinished!==void 0&&e.subagentFinished!==null?tT.fromPartial(e.subagentFinished):void 0,t.subagentError=e.subagentError!==void 0&&e.subagentError!==null?rT.fromPartial(e.subagentError):void 0,t.toolCallResult=e.toolCallResult!==void 0&&e.toolCallResult!==null?pw.fromPartial(e.toolCallResult):void 0,t.activitySnapshot=e.activitySnapshot!==void 0&&e.activitySnapshot!==null?xw.fromPartial(e.activitySnapshot):void 0,t.activityDelta=e.activityDelta!==void 0&&e.activityDelta!==null?Cw.fromPartial(e.activityDelta):void 0,t.reasoningStart=e.reasoningStart!==void 0&&e.reasoningStart!==null?zw.fromPartial(e.reasoningStart):void 0,t.reasoningMessageStart=e.reasoningMessageStart!==void 0&&e.reasoningMessageStart!==null?Vw.fromPartial(e.reasoningMessageStart):void 0,t.reasoningMessageContent=e.reasoningMessageContent!==void 0&&e.reasoningMessageContent!==null?Uw.fromPartial(e.reasoningMessageContent):void 0,t.reasoningMessageEnd=e.reasoningMessageEnd!==void 0&&e.reasoningMessageEnd!==null?Gw.fromPartial(e.reasoningMessageEnd):void 0,t.reasoningMessageChunk=e.reasoningMessageChunk!==void 0&&e.reasoningMessageChunk!==null?qw.fromPartial(e.reasoningMessageChunk):void 0,t.reasoningEnd=e.reasoningEnd!==void 0&&e.reasoningEnd!==null?Yw.fromPartial(e.reasoningEnd):void 0,t.reasoningEncryptedValue=e.reasoningEncryptedValue!==void 0&&e.reasoningEncryptedValue!==null?Zw.fromPartial(e.reasoningEncryptedValue):void 0,t}};function oT(){return{provider:void 0,model:void 0,inputTokens:void 0,outputTokens:void 0,totalTokens:void 0,reasoningTokens:void 0,cachedInputTokens:void 0,cacheWriteInputTokens:void 0}}var sT={encode(e,t=new Y){return e.provider!==void 0&&t.uint32(10).string(e.provider),e.model!==void 0&&t.uint32(18).string(e.model),e.inputTokens!==void 0&&t.uint32(24).int64(e.inputTokens),e.outputTokens!==void 0&&t.uint32(32).int64(e.outputTokens),e.totalTokens!==void 0&&t.uint32(40).int64(e.totalTokens),e.reasoningTokens!==void 0&&t.uint32(48).int64(e.reasoningTokens),e.cachedInputTokens!==void 0&&t.uint32(56).int64(e.cachedInputTokens),e.cacheWriteInputTokens!==void 0&&t.uint32(64).int64(e.cacheWriteInputTokens),t},decode(e,t){let n=e instanceof X?e:new X(e),r=t===void 0?n.len:n.pos+t,i=oT();for(;n.pos>>3){case 1:if(e!==10)break;i.provider=n.string();continue;case 2:if(e!==18)break;i.model=n.string();continue;case 3:if(e!==24)break;i.inputTokens=cT(n.int64());continue;case 4:if(e!==32)break;i.outputTokens=cT(n.int64());continue;case 5:if(e!==40)break;i.totalTokens=cT(n.int64());continue;case 6:if(e!==48)break;i.reasoningTokens=cT(n.int64());continue;case 7:if(e!==56)break;i.cachedInputTokens=cT(n.int64());continue;case 8:if(e!==64)break;i.cacheWriteInputTokens=cT(n.int64());continue}if((e&7)==4||e===0)break;n.skip(e&7)}return i},create(e){return sT.fromPartial(e??{})},fromPartial(e){let t=oT();return t.provider=e.provider??void 0,t.model=e.model??void 0,t.inputTokens=e.inputTokens??void 0,t.outputTokens=e.outputTokens??void 0,t.totalTokens=e.totalTokens??void 0,t.reasoningTokens=e.reasoningTokens??void 0,t.cachedInputTokens=e.cachedInputTokens??void 0,t.cacheWriteInputTokens=e.cacheWriteInputTokens??void 0,t}};function cT(e){let t=globalThis.Number(e.toString());if(t>globalThis.Number.MAX_SAFE_INTEGER)throw new globalThis.Error(`Value is larger than Number.MAX_SAFE_INTEGER`);if(te&&typeof e==`object`?e:void 0,uT=e=>Array.isArray(e)?e:[],dT=()=>typeof process<`u`&&!!{}.SUPPRESS_TRANSFORMATION_WARNINGS,fT=()=>{dT()||console.warn(`[ag-ui][proto] Dropped a content part this build does not know: the protocol has a variant this SDK predates.`)};new Set(Object.values(L));var pT={textMessageStart:`TEXT_MESSAGE_START`,textMessageContent:`TEXT_MESSAGE_CONTENT`,textMessageEnd:`TEXT_MESSAGE_END`,textMessageChunk:`TEXT_MESSAGE_CHUNK`,toolCallStart:`TOOL_CALL_START`,toolCallArgs:`TOOL_CALL_ARGS`,toolCallEnd:`TOOL_CALL_END`,toolCallChunk:`TOOL_CALL_CHUNK`,toolCallResult:`TOOL_CALL_RESULT`,stateSnapshot:`STATE_SNAPSHOT`,stateDelta:`STATE_DELTA`,messagesSnapshot:`MESSAGES_SNAPSHOT`,activitySnapshot:`ACTIVITY_SNAPSHOT`,activityDelta:`ACTIVITY_DELTA`,raw:`RAW`,custom:`CUSTOM`,runStarted:`RUN_STARTED`,runFinished:`RUN_FINISHED`,runError:`RUN_ERROR`,stepStarted:`STEP_STARTED`,stepFinished:`STEP_FINISHED`,reasoningStart:`REASONING_START`,reasoningMessageStart:`REASONING_MESSAGE_START`,reasoningMessageContent:`REASONING_MESSAGE_CONTENT`,reasoningMessageEnd:`REASONING_MESSAGE_END`,reasoningMessageChunk:`REASONING_MESSAGE_CHUNK`,reasoningEnd:`REASONING_END`,reasoningEncryptedValue:`REASONING_ENCRYPTED_VALUE`,subagentStarted:`SUBAGENT_STARTED`,subagentFinished:`SUBAGENT_FINISHED`,subagentError:`SUBAGENT_ERROR`},mT=new Set([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31]),hT=e=>{let t=lT(e);if(t){if([t.data,t.url,t.file].filter(Boolean).length>1)throw Error(`Invalid event: source carries more than one arm`);if(t.data){let e=t.data;return{type:`data`,value:e.value,mimeType:e.mimeType}}if(t.url){let e=t.url;return{type:`url`,value:e.value,mimeType:e.mimeType}}if(t.file){let e=t.file;return{type:`file`,value:e.value,provider:e.provider,mimeType:e.mimeType}}}},gT=e=>{let t=lT(e);if(t){if([t.text,t.image,t.audio,t.video,t.document].filter(Boolean).length>1)throw Error(`Invalid event: content part carries more than one arm`);if(t.text){let e=t.text;return{type:`text`,id:e.id,text:e.text,metadata:e.metadata}}if(t.image){let e=t.image;return e.source!==void 0&&hT(e.source)===void 0?void 0:{type:`image`,id:e.id,source:hT(e.source),metadata:e.metadata}}if(t.audio){let e=t.audio;return e.source!==void 0&&hT(e.source)===void 0?void 0:{type:`audio`,id:e.id,source:hT(e.source),metadata:e.metadata}}if(t.video){let e=t.video;return e.source!==void 0&&hT(e.source)===void 0?void 0:{type:`video`,id:e.id,source:hT(e.source),metadata:e.metadata}}if(t.document){let e=t.document;return e.source!==void 0&&hT(e.source)===void 0?void 0:{type:`document`,id:e.id,source:hT(e.source),metadata:e.metadata}}}},_T=new Set([`activity`]),vT=new Set([`user`,`tool`]),yT=new Set([`developer`,`system`,`assistant`,`user`,`tool`,`activity`,`reasoning`]),bT=e=>{let t=lT(e)??{},n={...t},r=typeof t.role==`string`?t.role:``,i=yT.has(r),a=i?vT.has(r):uT(t.contentParts).length>0,o=i?_T.has(r):!a&&t.activityContent!==void 0;if(!i&&(t.content===void 0?0:1)+ +(uT(t.contentParts).length>0)+(t.activityContent===void 0?0:1)>1)throw Error(`Invalid event: message carries more than one content form`);if(i){if(!a&&uT(t.contentParts).length>0)throw Error(`Invalid event: message carries content parts for a role that has none`);if(t.activityContent!==void 0&&!o)throw Error(`Invalid event: message carries activity content for a non-activity role`);if(o&&t.content!==void 0)throw Error(`Invalid event: activity content cannot ride with other content forms`);if(a&&t.content!==void 0&&uT(t.contentParts).length>0)throw Error(`Invalid event: message carries both string content and content parts`)}return a&&t.content===void 0&&(n.content=uT(t.contentParts).map(e=>{let t=gT(e);return t===void 0&&fT(),t}).filter(e=>e!==void 0)),o&&t.activityContent!==void 0&&(n.content=t.activityContent),delete n.activityContent,delete n.contentParts,uT(t.toolCalls).length===0&&delete n.toolCalls,Object.keys(n).forEach(e=>{n[e]===void 0&&delete n[e]}),n},xT=e=>{if(Array.isArray(e)){for(let t of e)xT(t);return}let t=lT(e);if(t)for(let e of Object.keys(t))t[e]===void 0?delete t[e]:xT(t[e])},ST=e=>{let t=lT(e);if(!t)return;let n={};return t.threadId!==void 0&&(n.threadId=t.threadId),t.runId!==void 0&&(n.runId=t.runId),t.protocolVersion!==void 0&&(n.protocolVersion=t.protocolVersion),t.parentRunId!==void 0&&(n.parentRunId=t.parentRunId),t.state!==void 0&&(n.state=t.state),n.messages=uT(t.messages).map(bT).filter(e=>e!==void 0),n.tools=uT(t.tools),n.context=uT(t.context),t.forwardedProps!==void 0&&(n.forwardedProps=t.forwardedProps),n.resume=uT(t.resume),n},CT={TextMessageStartEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},BaseEvent:{singular:new Set([3,4]),descend:{},google:{3:`google.protobuf.Value`,4:`google.protobuf.Struct`}},TextMessageContentEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},TextMessageEndEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ToolCallStartEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ToolCallArgsEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ToolCallEndEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},StateSnapshotEvent:{singular:new Set([1,2]),descend:{1:`BaseEvent`},google:{2:`google.protobuf.Value`}},StateDeltaEvent:{singular:new Set([1]),descend:{1:`BaseEvent`,2:`JsonPatchOperation`}},JsonPatchOperation:{singular:new Set([4]),descend:{},google:{4:`google.protobuf.Value`}},MessagesSnapshotEvent:{singular:new Set([1]),descend:{1:`BaseEvent`,2:`Message`}},Message:{singular:new Set([9,13]),descend:{5:`ToolCall`,8:`InputContent`},google:{9:`google.protobuf.Struct`,13:`google.protobuf.Struct`}},ToolCall:{singular:new Set([3,4]),descend:{},google:{4:`google.protobuf.Struct`}},InputContent:{singular:new Set([1,2,3,4,5]),descend:{1:`TextInputPart`,2:`ImageInputPart`,3:`AudioInputPart`,4:`VideoInputPart`,5:`DocumentInputPart`},arms:new Set([1,2,3,4,5])},TextInputPart:{singular:new Set([3]),descend:{},google:{3:`google.protobuf.Value`}},ImageInputPart:{singular:new Set([1,2]),descend:{1:`InputContentSource`},google:{2:`google.protobuf.Value`}},InputContentSource:{singular:new Set([1,2,3]),descend:{},arms:new Set([1,2,3])},AudioInputPart:{singular:new Set([1,2]),descend:{1:`InputContentSource`},google:{2:`google.protobuf.Value`}},VideoInputPart:{singular:new Set([1,2]),descend:{1:`InputContentSource`},google:{2:`google.protobuf.Value`}},DocumentInputPart:{singular:new Set([1,2]),descend:{1:`InputContentSource`},google:{2:`google.protobuf.Value`}},RawEvent:{singular:new Set([1,2]),descend:{1:`BaseEvent`},google:{2:`google.protobuf.Value`}},CustomEvent:{singular:new Set([1,3]),descend:{1:`BaseEvent`},google:{3:`google.protobuf.Value`}},RunStartedEvent:{singular:new Set([1,5]),descend:{1:`BaseEvent`,5:`RunAgentInput`}},RunAgentInput:{singular:new Set([4,8]),descend:{5:`Message`,6:`Tool`,9:`ResumeEntry`},google:{4:`google.protobuf.Value`,8:`google.protobuf.Value`}},Tool:{singular:new Set([3,4]),descend:{},google:{3:`google.protobuf.Value`,4:`google.protobuf.Struct`}},ResumeEntry:{singular:new Set([3,4]),descend:{},google:{3:`google.protobuf.Value`,4:`google.protobuf.Struct`}},RunFinishedEvent:{singular:new Set([1,4]),descend:{1:`BaseEvent`,6:`Interrupt`},google:{4:`google.protobuf.Value`}},Interrupt:{singular:new Set([5,7]),descend:{},google:{5:`google.protobuf.Value`,7:`google.protobuf.Value`}},RunErrorEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},StepStartedEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},StepFinishedEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},TextMessageChunkEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ToolCallChunkEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},SubagentStartedEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},SubagentFinishedEvent:{singular:new Set([1,3]),descend:{1:`BaseEvent`},google:{3:`google.protobuf.Value`}},SubagentErrorEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ToolCallResultEvent:{singular:new Set([1]),descend:{1:`BaseEvent`,7:`InputContent`}},ActivitySnapshotEvent:{singular:new Set([1,5]),descend:{1:`BaseEvent`},google:{5:`google.protobuf.Struct`}},ActivityDeltaEvent:{singular:new Set([1]),descend:{1:`BaseEvent`,5:`JsonPatchOperation`}},ReasoningStartEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningMessageStartEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningMessageContentEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningMessageEndEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningMessageChunkEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningEndEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},ReasoningEncryptedValueEvent:{singular:new Set([1]),descend:{1:`BaseEvent`}},"google.protobuf.Struct":{singular:new Set,descend:{1:`google.protobuf.Struct.FieldsEntry`}},"google.protobuf.Struct.FieldsEntry":{singular:new Set([2]),descend:{2:`google.protobuf.Value`}},"google.protobuf.Value":{singular:new Set([5,6]),descend:{5:`google.protobuf.Struct`,6:`google.protobuf.ListValue`},arms:new Set([1,2,3,4,5,6]),armWireTypes:{1:0,2:1,3:2,4:0,5:2,6:2}},"google.protobuf.ListValue":{singular:new Set,descend:{1:`google.protobuf.Value`}}},wT={1:`TextMessageStartEvent`,2:`TextMessageContentEvent`,3:`TextMessageEndEvent`,4:`ToolCallStartEvent`,5:`ToolCallArgsEvent`,6:`ToolCallEndEvent`,7:`StateSnapshotEvent`,8:`StateDeltaEvent`,9:`MessagesSnapshotEvent`,10:`RawEvent`,11:`CustomEvent`,12:`RunStartedEvent`,13:`RunFinishedEvent`,14:`RunErrorEvent`,15:`StepStartedEvent`,16:`StepFinishedEvent`,17:`TextMessageChunkEvent`,18:`ToolCallChunkEvent`,19:`SubagentStartedEvent`,20:`SubagentFinishedEvent`,21:`SubagentErrorEvent`,22:`ToolCallResultEvent`,23:`ActivitySnapshotEvent`,24:`ActivityDeltaEvent`,25:`ReasoningStartEvent`,26:`ReasoningMessageStartEvent`,27:`ReasoningMessageContentEvent`,28:`ReasoningMessageEndEvent`,29:`ReasoningMessageChunkEvent`,30:`ReasoningEndEvent`,31:`ReasoningEncryptedValueEvent`};function TT(e,t){let n=0,r=0;for(;;){if(t.offset>=e.length)throw Error(`Invalid event`);let i=e[t.offset++];if(r<28?n+=(i&127)*2**r:r===28&&(n+=(i&15)*2**28),r+=7,!(i&128))return n}}function ET(e,t){let n={offset:0},r=0,i=0;for(;n.offsete.length)throw Error(`Invalid event`);if(r===0){if(t.arms?.has(o)){if(i!==0&&i!==o)throw Error(`Invalid event`);i=o}let r=t.descend[o];if(r!==void 0){let t=CT[r];t!==void 0&&ET(e.subarray(n.offset,n.offset+a),t)}}n.offset+=a}else if(s===5)n.offset+=4;else throw Error(`Invalid event`);if(n.offset>e.length)throw Error(`Invalid event`)}if(r!==0)throw Error(`Invalid event`)}function DT(e){let t=new Set,n={offset:0},r=0;for(;n.offset0&&!t.has(a))throw Error(`Invalid event`);t.add(a)}if(o===0)TT(e,n);else if(o===1)n.offset+=8;else if(o===2){let t=TT(e,n);if(n.offset+t>e.length)throw Error(`Invalid event`);if(r===0){let r=wT[a];if(r!==void 0){let i=CT[r];i!==void 0&&ET(e.subarray(n.offset,n.offset+t),i)}}n.offset+=t}else if(o===5)n.offset+=4;else throw Error(`Invalid event`);if(n.offset>e.length)throw Error(`Invalid event`)}if(r!==0)throw Error(`Invalid event`)}function OT(e){if(e.length===1)return e[0];let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}function kT(e,t){let n=new X(e),r=[],i=new Map,a,o=!1;for(;n.pos1||n!==t){s.push(new Y().uint32(e.number*8+2).bytes(n).finish()),o=!0;continue}}s.push(e.raw)}return o?OT(s):e}var AT=class extends Error{constructor(e=`Unknown event type`){super(e),this.name=`AGUIUnknownEventTypeError`}};function jT(e,t,n,r){let i=0,a=0,o=0;for(;;){if(t.offset>=e.length||o>=n)return-1;let s=e[t.offset++];if(o+=1,o===n&&s>r)return-1;if(i+=(s&127)*2**a,a+=7,!(s&128))return i}}var MT=(e,t)=>jT(e,t,5,15),NT=(e,t)=>jT(e,t,10,1);function PT(e){let t={offset:0},n=[];for(;t.offsete.length)return!1;t.offset+=n}else return!1;if(t.offset>e.length)return!1}return n.length===0}function FT(e){let t={offset:0},n=[],r=0;for(;t.offsete.length)return!1;if(s){if(mT.has(a)||!PT(e.subarray(t.offset,t.offset+n)))return!1;r+=1}t.offset+=n}else return!1;if(t.offset>e.length)return!1}return n.length===0&&r>0}function IT(e){DT(e);let t=aT.decode(kT(e,{singular:mT,descend:wT})),n=Object.entries(t).filter(([,e])=>e!==void 0);if(n.length!==1)throw n.length===0&&FT(e)?new AT:Error(`Invalid event`);let r=n[0],i=pT[r[0]];if(i===void 0)throw Error(`Invalid event`);let a=r[1],o=lT(a.baseEvent);if(!o)throw Error(`Invalid event`);let s=JC[o.type];if(s!==i)throw Error(`Invalid event: envelope carries `+i+` but the base event declares `+String(s));if(a.type=i,a.timestamp=o.timestamp,a.rawEvent=o.rawEvent,o.metadata!==void 0&&(a.metadata=o.metadata),delete a.baseEvent,a.type===`MESSAGES_SNAPSHOT`&&Array.isArray(a.messages)&&(a.messages=a.messages.map(bT).filter(e=>e!==void 0)),a.type===`RUN_FINISHED`){let e=a,t=typeof e.outcome==`string`&&e.outcome!==``?e.outcome:void 0,n={};n.pendingToolCallIds=e.pendingToolCallIds,delete e.pendingToolCallIds,n.interrupts=e.interrupts,delete e.interrupts,delete e.outcome,t===void 0&&(uT(n.pendingToolCallIds).length>0&&(e.pendingToolCallIds=n.pendingToolCallIds),uT(n.interrupts).length>0&&(e.interrupts=n.interrupts)),t===`success`&&(e.outcome={type:`success`,...uT(n.pendingToolCallIds).length>0?{pendingToolCallIds:n.pendingToolCallIds}:{},...uT(n.interrupts).length>0?{interrupts:n.interrupts}:{}}),t===`interrupt`&&(e.outcome={type:`interrupt`,interrupts:uT(n.interrupts),...uT(n.pendingToolCallIds).length>0?{pendingToolCallIds:n.pendingToolCallIds}:{}}),t===`cancelled`&&(e.outcome={type:`cancelled`,...uT(n.pendingToolCallIds).length>0?{pendingToolCallIds:n.pendingToolCallIds}:{},...uT(n.interrupts).length>0?{interrupts:n.interrupts}:{}}),t!==void 0&&![`success`,`interrupt`,`cancelled`].includes(t)&&(e.outcome={type:t,...uT(n.pendingToolCallIds).length>0?{pendingToolCallIds:n.pendingToolCallIds}:{},...uT(n.interrupts).length>0?{interrupts:n.interrupts}:{}})}if(a.type===`SUBAGENT_FINISHED`){let e=a,t=typeof e.outcome==`string`&&e.outcome!==``?e.outcome:void 0,n={};n.interruptIds=e.interruptIds,delete e.interruptIds,delete e.outcome,t===void 0&&uT(n.interruptIds).length>0&&(e.interruptIds=n.interruptIds),t===`success`&&(e.outcome={type:`success`,...uT(n.interruptIds).length>0?{interruptIds:n.interruptIds}:{}}),t===`suspended`&&(e.outcome={type:`suspended`,...uT(n.interruptIds).length>0?{interruptIds:n.interruptIds}:{}}),t!==void 0&&![`success`,`suspended`].includes(t)&&(e.outcome={type:t,...uT(n.interruptIds).length>0?{interruptIds:n.interruptIds}:{}})}if(a.type===`STATE_DELTA`&&Array.isArray(a.delta)&&(a.delta=a.delta.map(e=>{let t=lC[e.op];return e.op=typeof t==`string`&&t!==`UNRECOGNIZED`?t.toLowerCase():String(e.op),Object.keys(e).forEach(t=>{e[t]===void 0&&delete e[t]}),e})),a.type===`ACTIVITY_DELTA`&&Array.isArray(a.patch)&&(a.patch=a.patch.map(e=>{let t=lC[e.op];return e.op=typeof t==`string`&&t!==`UNRECOGNIZED`?t.toLowerCase():String(e.op),Object.keys(e).forEach(t=>{e[t]===void 0&&delete e[t]}),e})),a.type===`RUN_FINISHED`&&Array.isArray(a.usage)&&a.usage.length===0&&delete a.usage,a.type===`RUN_ERROR`&&Array.isArray(a.usage)&&a.usage.length===0&&delete a.usage,a.type===`TOOL_CALL_RESULT`){let e=a;if(e.content!==void 0&&uT(e.contentParts).length>0)throw Error(`Invalid event: content carries both string content and content parts`);e.content===void 0&&(e.content=uT(e.contentParts).map(e=>{let t=gT(e);return t===void 0&&fT(),t}).filter(e=>e!==void 0)),delete e.contentParts}return a.type===`RUN_STARTED`&&a.input!==void 0&&(a.input=ST(a.input)),xT(a),a}var LT=/^[v^~<>=]*?(\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+)(?:\.([x*]|\d+))?(?:-([\da-z\-]+(?:\.[\da-z\-]+)*))?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i,RT=e=>{if(typeof e!=`string`)throw TypeError(`Invalid argument expected string`);let t=e.match(LT);if(!t)throw Error(`Invalid argument not valid semver ('${e}' received)`);return t.shift(),t},zT=e=>e===`*`||e===`x`||e===`X`,BT=e=>{let t=parseInt(e,10);return isNaN(t)?e:t},VT=(e,t)=>typeof e==typeof t?[e,t]:[String(e),String(t)],HT=(e,t)=>{if(zT(e)||zT(t))return 0;let[n,r]=VT(BT(e),BT(t));return n>r?1:n{for(let n=0;n{let n=RT(e),r=RT(t),i=n.pop(),a=r.pop(),o=UT(n,r);return o===0?i&&a?UT(i.split(`.`),a.split(`.`)):i||a?i?-1:1:0:o},GT=e=>typeof e==`string`&&/^[v\d]/.test(e)&<.test(e);Object.freeze({status:`aborted`});function $(e,t,n){function r(n,r){var i;Object.defineProperty(n,"_zod",{value:n._zod??{},enumerable:!1}),(i=n._zod).traits??(i.traits=new Set),n._zod.traits.add(e),t(n,r);for(let e in o.prototype)e in n||Object.defineProperty(n,e,{value:o.prototype[e].bind(n)});n._zod.constr=o,n._zod.def=r}let i=n?.Parent??Object;class a extends i{}Object.defineProperty(a,"name",{value:e});function o(e){var t;let i=n?.Parent?new a:this;r(i,e),(t=i._zod).deferred??(t.deferred=[]);for(let e of i._zod.deferred)e();return i}return Object.defineProperty(o,"init",{value:r}),Object.defineProperty(o,Symbol.hasInstance,{value:t=>n?.Parent&&t instanceof n.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(o,"name",{value:e}),o}var KT=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},qT={};function JT(e){return e&&Object.assign(qT,e),qT}function YT(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function XT(e,t){return typeof t==`bigint`?t.toString():t}function ZT(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function QT(e){return e==null}function $T(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function eE(e,t,n){Object.defineProperty(e,t,{get(){{let r=n();return e[t]=r,r}},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function tE(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function nE(e){return JSON.stringify(e)}var rE=Error.captureStackTrace?Error.captureStackTrace:(...e)=>{};function iE(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var aE=ZT(()=>{if(typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function oE(e){if(iE(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;let n=t.prototype;return iE(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}var sE=new Set([`string`,`number`,`symbol`]);function cE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function lE(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function uE(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function dE(e){return Object.keys(e).filter(t=>e[t]._zod.optin===`optional`&&e[t]._zod.optout===`optional`)}function fE(e,t){let n={},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&(n[e]=r.shape[e])}return lE(e,{...e._zod.def,shape:n,checks:[]})}function pE(e,t){let n={...e._zod.def.shape},r=e._zod.def;for(let e in t){if(!(e in r.shape))throw Error(`Unrecognized key: "${e}"`);t[e]&&delete n[e]}return lE(e,{...e._zod.def,shape:n,checks:[]})}function mE(e,t){if(!oE(t))throw Error(`Invalid input to extend: expected a plain object`);return lE(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t};return tE(this,`shape`,n),n},checks:[]})}function hE(e,t){return lE(e,{...e._zod.def,get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return tE(this,`shape`,n),n},catchall:t._zod.def.catchall,checks:[]})}function gE(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in r))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t in r)i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return lE(t,{...t._zod.def,shape:i,checks:[]})}function _E(e,t,n){let r=t._zod.def.shape,i={...r};if(n)for(let t in n){if(!(t in i))throw Error(`Unrecognized key: "${t}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t in r)i[t]=new e({type:`nonoptional`,innerType:r[t]});return lE(t,{...t._zod.def,shape:i,checks:[]})}function vE(e,t=0){for(let n=t;n{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function bE(e){return typeof e==`string`?e:e?.message}function xE(e,t,n){let r={...e,path:e.path??[]};return e.message||(r.message=bE(e.inst?._zod.def?.error?.(e))??bE(t?.error?.(e))??bE(n.customError?.(e))??bE(n.localeError?.(e))??`Invalid input`),delete r.inst,delete r.continue,t?.reportInput||delete r.input,r}function SE(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function CE(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}var wE=(e,t)=>{e.name=`$ZodError`,Object.defineProperty(e,"_zod",{value:e._zod,enumerable:!1}),Object.defineProperty(e,"issues",{value:t,enumerable:!1}),Object.defineProperty(e,"message",{get(){return JSON.stringify(t,XT,2)},enumerable:!0}),Object.defineProperty(e,"toString",{value:()=>e.message,enumerable:!1})},TE=$(`$ZodError`,wE),EE=$(`$ZodError`,wE,{Parent:Error});function DE(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(t(i))):r.push(t(i));return{formErrors:r,fieldErrors:n}}function OE(e,t){let n=t||function(e){return e.message},r={_errors:[]},i=e=>{for(let t of e.issues)if(t.code===`invalid_union`&&t.errors.length)t.errors.map(e=>i({issues:e}));else if(t.code===`invalid_key`)i({issues:t.issues});else if(t.code===`invalid_element`)i({issues:t.issues});else if(t.path.length===0)r._errors.push(n(t));else{let e=r,i=0;for(;i(t,n,r,i)=>{let a=r?Object.assign(r,{async:!1}):{async:!1},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise)throw new KT;if(o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>xE(e,a,JT())));throw rE(t,i?.callee),t}return o.value},AE=e=>async(t,n,r,i)=>{let a=r?Object.assign(r,{async:!0}):{async:!0},o=t._zod.run({value:n,issues:[]},a);if(o instanceof Promise&&(o=await o),o.issues.length){let t=new((i?.Err)??e)(o.issues.map(e=>xE(e,a,JT())));throw rE(t,i?.callee),t}return o.value},jE=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new KT;return a.issues.length?{success:!1,error:new(e??TE)(a.issues.map(e=>xE(e,i,JT())))}:{success:!0,data:a.value}},ME=jE(EE),NE=e=>async(t,n,r)=>{let i=r?Object.assign(r,{async:!0}):{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>xE(e,i,JT())))}:{success:!0,data:a.value}},PE=NE(EE),FE=$(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),IE=$(`$ZodCheckMaxLength`,(e,t)=>{var n;FE.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!QT(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum{let r=n.value;if(r.length<=t.maximum)return;let i=SE(r);n.issues.push({origin:i,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),LE=$(`$ZodCheckMinLength`,(e,t)=>{var n;FE.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!QT(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value;if(r.length>=t.minimum)return;let i=SE(r);n.issues.push({origin:i,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),RE=$(`$ZodCheckLengthEquals`,(e,t)=>{var n;FE.init(e,t),(n=e._zod.def).when??(n.when=e=>{let t=e.value;return!QT(t)&&t.length!==void 0}),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length;if(i===t.length)return;let a=SE(r),o=i>t.length;n.issues.push({origin:a,...o?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),zE=$(`$ZodCheckOverwrite`,(e,t)=>{FE.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),BE=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(` +`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.args,n=[...(this?.content??[``]).map(e=>` ${e}`)];return new e(...t,n.join(` +`))}},VE={major:4,minor:0,patch:0},HE=$(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=VE;let r=[...e._zod.def.checks??[]];e._zod.traits.has(`$ZodCheck`)&&r.unshift(e);for(let t of r)for(let n of t._zod.onattach)n(e);if(r.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(e,t,n)=>{let r=vE(e),i;for(let a of t){if(a._zod.def.when){if(!a._zod.def.when(e))continue}else if(r)continue;let t=e.issues.length,o=a._zod.check(e);if(o instanceof Promise&&n?.async===!1)throw new KT;if(i||o instanceof Promise)i=(i??Promise.resolve()).then(async()=>{await o,e.issues.length!==t&&(r||=vE(e,t))});else{if(e.issues.length===t)continue;r||=vE(e,t)}}return i?i.then(()=>e):e};e._zod.run=(n,i)=>{let a=e._zod.parse(n,i);if(a instanceof Promise){if(i.async===!1)throw new KT;return a.then(e=>t(e,r,i))}return t(a,r,i)}}e[`~standard`]={validate:t=>{try{let n=ME(e,t);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return PE(e,t).then(e=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:`zod`,version:1}}),UE=$(`$ZodUnknown`,(e,t)=>{HE.init(e,t),e._zod.parse=e=>e}),WE=$(`$ZodNever`,(e,t)=>{HE.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function GE(e,t,n){e.issues.length&&t.issues.push(...yE(n,e.issues)),t.value[n]=e.value}var KE=$(`$ZodArray`,(e,t)=>{HE.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!Array.isArray(i))return n.issues.push({expected:`array`,code:`invalid_type`,input:i,inst:e}),n;n.value=Array(i.length);let a=[];for(let e=0;eGE(t,n,e))):GE(s,n,e)}return a.length?Promise.all(a).then(()=>n):n}});function qE(e,t,n){e.issues.length&&t.issues.push(...yE(n,e.issues)),t.value[n]=e.value}function JE(e,t,n,r){e.issues.length?r[n]===void 0?n in r?t.value[n]=void 0:t.value[n]=e.value:t.issues.push(...yE(n,e.issues)):e.value===void 0?n in r&&(t.value[n]=void 0):t.value[n]=e.value}var YE=$(`$ZodObject`,(e,t)=>{HE.init(e,t);let n=ZT(()=>{let e=Object.keys(t.shape);for(let n of e)if(!(t.shape[n]instanceof HE))throw Error(`Invalid element at key "${n}": expected a Zod schema`);let n=dE(t.shape);return{shape:t.shape,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}});eE(e._zod,`propValues`,()=>{let e=t.shape,n={};for(let t in e){let r=e[t]._zod;if(r.values){n[t]??(n[t]=new Set);for(let e of r.values)n[t].add(e)}}return n});let r=e=>{let t=new BE([`shape`,`payload`,`ctx`]),r=n.value,i=e=>{let t=nE(e);return`shape[${t}]._zod.run({ value: input[${t}], issues: [] }, ctx)`};t.write(`const input = payload.value;`);let a=Object.create(null),o=0;for(let e of r.keys)a[e]=`key_${o++}`;t.write(`const newResult = {}`);for(let e of r.keys)if(r.optionalKeys.has(e)){let n=a[e];t.write(`const ${n} = ${i(e)};`);let r=nE(e);t.write(` + if (${n}.issues.length) { + if (input[${r}] === undefined) { + if (${r} in input) { + newResult[${r}] = undefined; + } + } else { + payload.issues = payload.issues.concat( + ${n}.issues.map((iss) => ({ + ...iss, + path: iss.path ? [${r}, ...iss.path] : [${r}], + })) + ); + } + } else if (${n}.value === undefined) { + if (${r} in input) newResult[${r}] = undefined; + } else { + newResult[${r}] = ${n}.value; + } + `)}else{let n=a[e];t.write(`const ${n} = ${i(e)};`),t.write(` + if (${n}.issues.length) payload.issues = payload.issues.concat(${n}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${nE(e)}, ...iss.path] : [${nE(e)}] + })));`),t.write(`newResult[${nE(e)}] = ${n}.value`)}t.write(`payload.value = newResult;`),t.write(`return payload;`);let s=t.compile();return(t,n)=>s(e,t,n)},i,a=iE,o=!qT.jitless,s=o&&aE.value,c=t.catchall,l;e._zod.parse=(u,d)=>{l??=n.value;let f=u.value;if(!a(f))return u.issues.push({expected:`object`,code:`invalid_type`,input:f,inst:e}),u;let p=[];if(o&&s&&d?.async===!1&&d.jitless!==!0)i||=r(t.shape),u=i(u,d);else{u.value={};let e=l.shape;for(let t of l.keys){let n=e[t],r=n._zod.run({value:f[t],issues:[]},d),i=n._zod.optin===`optional`&&n._zod.optout===`optional`;r instanceof Promise?p.push(r.then(e=>i?JE(e,u,t,f):qE(e,u,t))):i?JE(r,u,t,f):qE(r,u,t)}}if(!c)return p.length?Promise.all(p).then(()=>u):u;let m=[],h=l.keySet,g=c._zod,_=g.def.type;for(let e of Object.keys(f)){if(h.has(e))continue;if(_===`never`){m.push(e);continue}let t=g.run({value:f[e],issues:[]},d);t instanceof Promise?p.push(t.then(t=>qE(t,u,e))):qE(t,u,e)}return m.length&&u.issues.push({code:`unrecognized_keys`,keys:m,input:f,inst:e}),p.length?Promise.all(p).then(()=>u):u}});function XE(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;return t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>xE(e,r,JT())))}),t}var ZE=$(`$ZodUnion`,(e,t)=>{HE.init(e,t),eE(e._zod,`optin`,()=>t.options.some(e=>e._zod.optin===`optional`)?`optional`:void 0),eE(e._zod,`optout`,()=>t.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),eE(e._zod,`values`,()=>{if(t.options.every(e=>e._zod.values))return new Set(t.options.flatMap(e=>Array.from(e._zod.values)))}),eE(e._zod,`pattern`,()=>{if(t.options.every(e=>e._zod.pattern)){let e=t.options.map(e=>e._zod.pattern);return RegExp(`^(${e.map(e=>$T(e.source)).join(`|`)})$`)}}),e._zod.parse=(n,r)=>{let i=!1,a=[];for(let e of t.options){let t=e._zod.run({value:n.value,issues:[]},r);if(t instanceof Promise)a.push(t),i=!0;else{if(t.issues.length===0)return t;a.push(t)}}return i?Promise.all(a).then(t=>XE(t,n,e,r)):XE(a,n,e,r)}}),QE=$(`$ZodIntersection`,(e,t)=>{HE.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>eD(e,t,n)):eD(e,i,a)}});function $E(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(oE(e)&&oE(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};for(let n of r){let r=$E(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r{HE.init(e,t),e._zod.parse=(n,r)=>{let i=n.value;if(!oE(i))return n.issues.push({expected:`record`,code:`invalid_type`,input:i,inst:e}),n;let a=[];if(t.keyType._zod.values){let o=t.keyType._zod.values;n.value={};for(let e of o)if(typeof e==`string`||typeof e==`number`||typeof e==`symbol`){let o=t.valueType._zod.run({value:i[e],issues:[]},r);o instanceof Promise?a.push(o.then(t=>{t.issues.length&&n.issues.push(...yE(e,t.issues)),n.value[e]=t.value})):(o.issues.length&&n.issues.push(...yE(e,o.issues)),n.value[e]=o.value)}let s;for(let e in i)o.has(e)||(s??=[],s.push(e));s&&s.length>0&&n.issues.push({code:`unrecognized_keys`,input:i,inst:e,keys:s})}else{n.value={};for(let o of Reflect.ownKeys(i)){if(o===`__proto__`)continue;let s=t.keyType._zod.run({value:o,issues:[]},r);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){n.issues.push({origin:`record`,code:`invalid_key`,issues:s.issues.map(e=>xE(e,r,JT())),input:o,path:[o],inst:e}),n.value[s.value]=s.value;continue}let c=t.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?a.push(c.then(e=>{e.issues.length&&n.issues.push(...yE(o,e.issues)),n.value[s.value]=e.value})):(c.issues.length&&n.issues.push(...yE(o,c.issues)),n.value[s.value]=c.value)}}return a.length?Promise.all(a).then(()=>n):n}}),nD=$(`$ZodEnum`,(e,t)=>{HE.init(e,t);let n=YT(t.entries);e._zod.values=new Set(n),e._zod.pattern=RegExp(`^(${n.filter(e=>sE.has(typeof e)).map(e=>typeof e==`string`?cE(e):e.toString()).join(`|`)})$`),e._zod.parse=(t,r)=>{let i=t.value;return e._zod.values.has(i)||t.issues.push({code:`invalid_value`,values:n,input:i,inst:e}),t}}),rD=$(`$ZodLiteral`,(e,t)=>{HE.init(e,t),e._zod.values=new Set(t.values),e._zod.pattern=RegExp(`^(${t.values.map(e=>typeof e==`string`?cE(e):e?e.toString():String(e)).join(`|`)})$`),e._zod.parse=(n,r)=>{let i=n.value;return e._zod.values.has(i)||n.issues.push({code:`invalid_value`,values:t.values,input:i,inst:e}),n}}),iD=$(`$ZodTransform`,(e,t)=>{HE.init(e,t),e._zod.parse=(e,n)=>{let r=t.transform(e.value,e);if(n.async)return(r instanceof Promise?r:Promise.resolve(r)).then(t=>(e.value=t,e));if(r instanceof Promise)throw new KT;return e.value=r,e}}),aD=$(`$ZodOptional`,(e,t)=>{HE.init(e,t),e._zod.optin=`optional`,e._zod.optout=`optional`,eE(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),eE(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${$T(e.source)})?$`):void 0}),e._zod.parse=(e,n)=>t.innerType._zod.optin===`optional`?t.innerType._zod.run(e,n):e.value===void 0?e:t.innerType._zod.run(e,n)}),oD=$(`$ZodNullable`,(e,t)=>{HE.init(e,t),eE(e._zod,`optin`,()=>t.innerType._zod.optin),eE(e._zod,`optout`,()=>t.innerType._zod.optout),eE(e._zod,`pattern`,()=>{let e=t.innerType._zod.pattern;return e?RegExp(`^(${$T(e.source)}|null)$`):void 0}),eE(e._zod,`values`,()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),sD=$(`$ZodDefault`,(e,t)=>{HE.init(e,t),e._zod.optin=`optional`,eE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>cD(e,t)):cD(r,t)}});function cD(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var lD=$(`$ZodPrefault`,(e,t)=>{HE.init(e,t),e._zod.optin=`optional`,eE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>(e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),uD=$(`$ZodNonOptional`,(e,t)=>{HE.init(e,t),eE(e._zod,`values`,()=>{let e=t.innerType._zod.values;return e?new Set([...e].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>dD(t,e)):dD(i,e)}});function dD(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}var fD=$(`$ZodCatch`,(e,t)=>{HE.init(e,t),e._zod.optin=`optional`,eE(e._zod,`optout`,()=>t.innerType._zod.optout),eE(e._zod,`values`,()=>t.innerType._zod.values),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(r=>(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>xE(e,n,JT()))},input:e.value}),e.issues=[]),e)):(e.value=r.value,r.issues.length&&(e.value=t.catchValue({...e,error:{issues:r.issues.map(e=>xE(e,n,JT()))},input:e.value}),e.issues=[]),e)}}),pD=$(`$ZodPipe`,(e,t)=>{HE.init(e,t),eE(e._zod,`values`,()=>t.in._zod.values),eE(e._zod,`optin`,()=>t.in._zod.optin),eE(e._zod,`optout`,()=>t.out._zod.optout),e._zod.parse=(e,n)=>{let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>mD(e,t,n)):mD(r,t,n)}});function mD(e,t,n){return vE(e)?e:t.out._zod.run({value:e.value,issues:e.issues},n)}var hD=$(`$ZodReadonly`,(e,t)=>{HE.init(e,t),eE(e._zod,`propValues`,()=>t.innerType._zod.propValues),eE(e._zod,`values`,()=>t.innerType._zod.values),eE(e._zod,`optin`,()=>t.innerType._zod.optin),eE(e._zod,`optout`,()=>t.innerType._zod.optout),e._zod.parse=(e,n)=>{let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(gD):gD(r)}});function gD(e){return e.value=Object.freeze(e.value),e}var _D=$(`$ZodLazy`,(e,t)=>{HE.init(e,t),eE(e._zod,`innerType`,()=>t.getter()),eE(e._zod,`pattern`,()=>e._zod.innerType._zod.pattern),eE(e._zod,`propValues`,()=>e._zod.innerType._zod.propValues),eE(e._zod,`optin`,()=>e._zod.innerType._zod.optin),eE(e._zod,`optout`,()=>e._zod.innerType._zod.optout),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),vD=$(`$ZodCustom`,(e,t)=>{FE.init(e,t),HE.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>yD(t,n,r,e));yD(i,n,r,e)}});function yD(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(CE(e))}}var bD=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){let n=t[0];if(this._map.set(e,n),n&&typeof n==`object`&&`id`in n){if(this._idmap.has(n.id))throw Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function xD(){return new bD}var SD=xD();function CD(e){return new e({type:`unknown`})}function wD(e,t){return new e({type:`never`,...uE(t)})}function TD(e,t){return new IE({check:`max_length`,...uE(t),maximum:e})}function ED(e,t){return new LE({check:`min_length`,...uE(t),minimum:e})}function DD(e,t){return new RE({check:`length_equals`,...uE(t),length:e})}function OD(e){return new zE({check:`overwrite`,tx:e})}function kD(e,t,n){return new e({type:`array`,element:t,...uE(n)})}function AD(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...uE(n)})}var jD=(e,t)=>{TE.init(e,t),e.name=`ZodError`,Object.defineProperties(e,{format:{value:t=>OE(e,t)},flatten:{value:t=>DE(e,t)},addIssue:{value:t=>e.issues.push(t)},addIssues:{value:t=>e.issues.push(...t)},isEmpty:{get(){return e.issues.length===0}}})};$(`ZodError`,jD);var MD=$(`ZodError`,jD,{Parent:Error}),ND=kE(MD),PD=AE(MD),FD=jE(MD),ID=NE(MD),LD=$(`ZodType`,(e,t)=>(HE.init(e,t),e.def=t,Object.defineProperty(e,"_def",{value:t}),e.check=(...n)=>e.clone({...t,checks:[...t.checks??[],...n.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),e.clone=(t,n)=>lE(e,t,n),e.brand=()=>e,e.register=((t,n)=>(t.add(e,n),e)),e.parse=(t,n)=>ND(e,t,n,{callee:e.parse}),e.safeParse=(t,n)=>FD(e,t,n),e.parseAsync=async(t,n)=>PD(e,t,n,{callee:e.parseAsync}),e.safeParseAsync=async(t,n)=>ID(e,t,n),e.spa=e.safeParseAsync,e.refine=(t,n)=>e.check(bO(t,n)),e.superRefine=t=>e.check(xO(t)),e.overwrite=t=>e.check(OD(t)),e.optional=()=>nO(e),e.nullable=()=>iO(e),e.nullish=()=>nO(iO(e)),e.nonoptional=t=>uO(e,t),e.array=()=>UD(e),e.or=t=>KD([e,t]),e.and=t=>JD(e,t),e.transform=t=>mO(e,eO(t)),e.default=t=>oO(e,t),e.prefault=t=>cO(e,t),e.catch=t=>fO(e,t),e.pipe=t=>mO(e,t),e.readonly=()=>gO(e),e.describe=t=>{let n=e.clone();return SD.add(n,{description:t}),n},Object.defineProperty(e,"description",{get(){return SD.get(e)?.description},configurable:!0}),e.meta=(...t)=>{if(t.length===0)return SD.get(e);let n=e.clone();return SD.add(n,t[0]),n},e.isOptional=()=>e.safeParse(void 0).success,e.isNullable=()=>e.safeParse(null).success,e)),RD=$(`ZodUnknown`,(e,t)=>{UE.init(e,t),LD.init(e,t)});function zD(){return CD(RD)}var BD=$(`ZodNever`,(e,t)=>{WE.init(e,t),LD.init(e,t)});function VD(e){return wD(BD,e)}var HD=$(`ZodArray`,(e,t)=>{KE.init(e,t),LD.init(e,t),e.element=t.element,e.min=(t,n)=>e.check(ED(t,n)),e.nonempty=t=>e.check(ED(1,t)),e.max=(t,n)=>e.check(TD(t,n)),e.length=(t,n)=>e.check(DD(t,n)),e.unwrap=()=>e.element});function UD(e,t){return kD(HD,e,t)}var WD=$(`ZodObject`,(e,t)=>{YE.init(e,t),LD.init(e,t),eE(e,`shape`,()=>t.shape),e.keyof=()=>ZD(Object.keys(e._zod.def.shape)),e.catchall=t=>e.clone({...e._zod.def,catchall:t}),e.passthrough=()=>e.clone({...e._zod.def,catchall:zD()}),e.loose=()=>e.clone({...e._zod.def,catchall:zD()}),e.strict=()=>e.clone({...e._zod.def,catchall:VD()}),e.strip=()=>e.clone({...e._zod.def,catchall:void 0}),e.extend=t=>mE(e,t),e.merge=t=>hE(e,t),e.pick=t=>fE(e,t),e.omit=t=>pE(e,t),e.partial=(...t)=>gE(tO,e,t[0]),e.required=(...t)=>_E(lO,e,t[0])}),GD=$(`ZodUnion`,(e,t)=>{ZE.init(e,t),LD.init(e,t),e.options=t.options});function KD(e,t){return new GD({type:`union`,options:e,...uE(t)})}var qD=$(`ZodIntersection`,(e,t)=>{QE.init(e,t),LD.init(e,t)});function JD(e,t){return new qD({type:`intersection`,left:e,right:t})}var YD=$(`ZodRecord`,(e,t)=>{tD.init(e,t),LD.init(e,t),e.keyType=t.keyType,e.valueType=t.valueType}),XD=$(`ZodEnum`,(e,t)=>{nD.init(e,t),LD.init(e,t),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new XD({...t,checks:[],...uE(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new XD({...t,checks:[],...uE(r),entries:i})}});function ZD(e,t){return new XD({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...uE(t)})}var QD=$(`ZodLiteral`,(e,t)=>{rD.init(e,t),LD.init(e,t),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})}),$D=$(`ZodTransform`,(e,t)=>{iD.init(e,t),LD.init(e,t),e._zod.parse=(n,r)=>{n.addIssue=r=>{if(typeof r==`string`)n.issues.push(CE(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,t.input??=n.value,t.inst??=e,t.continue??=!0,n.issues.push(CE(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function eO(e){return new $D({type:`transform`,transform:e})}var tO=$(`ZodOptional`,(e,t)=>{aD.init(e,t),LD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function nO(e){return new tO({type:`optional`,innerType:e})}var rO=$(`ZodNullable`,(e,t)=>{oD.init(e,t),LD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function iO(e){return new rO({type:`nullable`,innerType:e})}var aO=$(`ZodDefault`,(e,t)=>{sD.init(e,t),LD.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function oO(e,t){return new aO({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}var sO=$(`ZodPrefault`,(e,t)=>{lD.init(e,t),LD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function cO(e,t){return new sO({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():t}})}var lO=$(`ZodNonOptional`,(e,t)=>{uD.init(e,t),LD.init(e,t),e.unwrap=()=>e._zod.def.innerType});function uO(e,t){return new lO({type:`nonoptional`,innerType:e,...uE(t)})}var dO=$(`ZodCatch`,(e,t)=>{fD.init(e,t),LD.init(e,t),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function fO(e,t){return new dO({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:()=>t})}var pO=$(`ZodPipe`,(e,t)=>{pD.init(e,t),LD.init(e,t),e.in=t.in,e.out=t.out});function mO(e,t){return new pO({type:`pipe`,in:e,out:t})}var hO=$(`ZodReadonly`,(e,t)=>{hD.init(e,t),LD.init(e,t)});function gO(e){return new hO({type:`readonly`,innerType:e})}var _O=$(`ZodLazy`,(e,t)=>{_D.init(e,t),LD.init(e,t),e.unwrap=()=>e._zod.def.getter()}),vO=$(`ZodCustom`,(e,t)=>{vD.init(e,t),LD.init(e,t)});function yO(e){let t=new FE({check:`custom`});return t._zod.check=e,t}function bO(e,t={}){return AD(vO,e,t)}function xO(e){let t=yO(n=>(n.addIssue=e=>{if(typeof e==`string`)n.issues.push(CE(e,n.value,t._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,r.input??=n.value,r.inst??=t,r.continue??=!t._zod.def.abort,n.issues.push(CE(r))}},e(n.value,n)));return t}var SO=`@ag-ui/client`;function CO(e){if(!e.metadata||!Object.prototype.hasOwnProperty.call(e.metadata,SO))return;let t=e.metadata?.[SO];if(!t||typeof t!=`object`||Array.isArray(t))return[];if(!Object.prototype.hasOwnProperty.call(t,`authoritativeActivityTypes`))return;let n=t.authoritativeActivityTypes;return n===null?null:Array.isArray(n)&&n.every(e=>typeof e==`string`)?n:[]}var wO=e=>{if(typeof structuredClone==`function`)return structuredClone(e);try{return JSON.parse(JSON.stringify(e))}catch{return Array.isArray(e)?[...e]:{...e}}};function TO(){return Gc()}function EO(e){return e instanceof TypeError&&/read[- ]?only|not extensible|cannot add property|cannot delete property|can't be deleted|unable to delete property|object is frozen|is not writable/i.test(e.message)}function DO(e){if(Object.freeze(e),typeof e==`object`&&e)for(let t of Object.values(e))typeof t==`object`&&t&&!Object.isFrozen(t)&&DO(t);return e}var OO=524288;function kO(e,t,n){let r=0,i=[e,t],a=new WeakSet;for(;i.length>0;){let e=i.pop();if(typeof e==`string`){if(r+=e.length,r>n)return!0}else if(typeof e==`object`&&e){if(a.has(e))continue;if(a.add(e),Array.isArray(e))for(let t=0;tn)return!0;i.push(e[o])}}}}return!1}async function AO(e,t,n,r){let i=typeof process<`u`&&!0,a=i&&!!{}.VITEST_WORKER_ID,o=i&&!!{}.VITEST_WORKER_ID,s=o&&!kO(t,n,OO),c=s?wO(t):t,l=s?wO(n):n,u=!1,d=!1,f;for(let t of e)try{s&&(DO(c),DO(l));let e=await r(t,c,l);if(e===void 0)continue;let n=!1;if(e.messages!==void 0&&e.messages!==c&&(c=wO(e.messages),u=!0,n=!0),e.state!==void 0&&e.state!==l&&(l=wO(e.state),d=!0,n=!0),s&&n&&kO(c,l,OO)&&(s=!1),f=e.stopPropagation,f===!0)break}catch(e){if(a&&e instanceof TypeError)throw e;s&&o&&EO(e)?console.error(`AG-UI: Subscriber attempted to mutate frozen inputs in-place. Return mutations via AgentStateMutation instead of mutating directly.`,e):console.error(`Subscriber error:`,e);continue}return{...u?{messages:Object.isFrozen(c)?wO(c):c}:{},...d?{state:Object.isFrozen(l)?wO(l):l}:{},...f===void 0?{}:{stopPropagation:f}}}function jO(e){if(!e)return{enabled:!1,events:!1,lifecycle:!1,verbose:!1};if(e===!0)return{enabled:!0,events:!0,lifecycle:!0,verbose:!0};let t=e.events??!0,n=e.lifecycle??!0,r=e.verbose??!1;return{enabled:t||n,events:t,lifecycle:n,verbose:r}}function MO(e){if(e instanceof NO)return e;if(e===!0)return new NO(jO(!0))}var NO=class{constructor(e){this.config=e}event(e,t,n,r){this.config.events&&(this.config.verbose?console.debug(`[${e}] ${t}`,typeof n==`string`?n:JSON.stringify(n)):console.debug(`[${e}] ${t}`,r??n))}lifecycle(e,t,n){this.config.lifecycle&&(n?console.debug(`[${e}] ${t}`,n):console.debug(`[${e}] ${t}`))}get eventsEnabled(){return this.config.events}get lifecycleEnabled(){return this.config.lifecycle}get enabled(){return this.config.enabled}};function PO(e){return e.enabled?new NO(e):void 0}function FO(e,t,n){if(t){let r=e.find(e=>e.id===t);if(r?.role===`assistant`)return r;r&&console.warn(`TOOL_CALL_START: parentMessageId '${t}' matches a '${r.role}' message, not assistant — falling back to toolCallId`);let i={id:r?n:t,role:`assistant`,toolCalls:[]};return e.push(i),i}let r={id:n,role:`assistant`,toolCalls:[]};return e.push(r),r}function IO(e,t){return!e||t.metadata===void 0?!1:(e.metadata=Zc(e.metadata,wO(t.metadata)),!0)}var LO=(e,t,n,r,i)=>{let a=MO(i),o=wO(n.messages),s=wO(e.state),c={},l=[],u=new Set,d=e=>{let t=e.outcome?.type===`success`?e.outcome.pendingToolCallIds:void 0;return t!==void 0&&t.length>0?[...t]:l.filter(e=>!u.has(e))},f=e=>{e.messages!==void 0&&(o=e.messages,c.messages=e.messages),e.state!==void 0&&(s=e.state,c.state=e.state)},p=()=>{let e=wO(c);return c={},e.messages!==void 0||e.state!==void 0?gd(e):Lu};return t.pipe(Dd(async t=>{let i=await AO(r,o,s,(r,i,a)=>r.onEvent?.({event:t,agent:n,input:e,messages:i,state:a}));if(f(i),i.stopPropagation===!0?a?.event(`APPLY`,`Event dropped:`,t,{type:t.type,reason:`stopPropagation by subscriber`}):a?.event(`APPLY`,`Event applied:`,t,{type:t.type,subscribers:r.length}),i.stopPropagation===!0)return p();switch(t.type){case L.TEXT_MESSAGE_START:{let i=await AO(r,o,s,(r,i,a)=>r.onTextMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{messageId:e,role:n=`assistant`,name:r,subagentRunId:i}=t,a=o.find(t=>t.id===e);if(a?.role===`activity`)return console.warn(`TEXT_MESSAGE_START: Message '${e}' is an activity message — message ids must be unique across activity and text messages`),p();let s=a;if(!s){let t={id:e,role:n,content:``,...r!==void 0&&{name:r},...i!=null&&{subagentRunId:i}};o.push(t),s=t}let c=IO(s,t);(!a||c)&&f({messages:o})}return p()}case L.TEXT_MESSAGE_CONTENT:{let{messageId:i,delta:a}=t,c=o.find(e=>e.id===i);if(!c)return console.warn(`TEXT_MESSAGE_CONTENT: No message found with ID '${i}'`),p();if(c.role===`activity`)return console.warn(`TEXT_MESSAGE_CONTENT: Message '${i}' is an activity message — message ids must be unique across activity and text messages`),p();let l=await AO(r,o,s,(r,i,a)=>r.onTextMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,textMessageBuffer:typeof c.content==`string`?c.content:``}));return f(l),l.stopPropagation!==!0&&(c.content=`${typeof c.content==`string`?c.content:``}${a}`,IO(c,t),f({messages:o})),p()}case L.TEXT_MESSAGE_END:{let{messageId:i}=t,a=o.find(e=>e.id===i);if(!a)return console.warn(`TEXT_MESSAGE_END: No message found with ID '${i}'`),p();if(a.role===`activity`)return console.warn(`TEXT_MESSAGE_END: Message '${i}' is an activity message — message ids must be unique across activity and text messages`),p();let c=await AO(r,o,s,(r,i,o)=>r.onTextMessageEndEvent?.({event:t,messages:i,state:o,agent:n,input:e,textMessageBuffer:typeof a.content==`string`?a.content:``}));return f(c),c.stopPropagation!==!0&&IO(a,t)&&f({messages:o}),await Promise.all(r.map(t=>{t.onNewMessage?.({message:a,messages:o,state:s,agent:n,input:e})})),p()}case L.TOOL_CALL_START:{let i=await AO(r,o,s,(r,i,a)=>r.onToolCallStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{toolCallId:e,toolCallName:n,parentMessageId:r,subagentRunId:i}=t;l.includes(e)||l.push(e);let a=o.find(t=>t.toolCalls?.some(t=>t.id===e))?.toolCalls?.find(t=>t.id===e);if(a){let r=a.function.name!==n;return r&&(console.warn(`TOOL_CALL_START: tool call '${e}' already exists with name '${a.function.name}' — updating it to '${n}'`),a.function.name=n),(IO(a,t)||r)&&f({messages:o}),p()}let s=new Set(o.map(e=>e.id)),c=FO(o,r,e);!s.has(c.id)&&i!=null&&c.subagentRunId===void 0&&(c.subagentRunId=i),c.toolCalls??=[];let u={id:e,type:`function`,function:{name:n,arguments:``}};c.toolCalls.push(u),IO(u,t),f({messages:o})}return p()}case L.TOOL_CALL_ARGS:{let{toolCallId:i,delta:a}=t,c=o.find(e=>e.toolCalls?.some(e=>e.id===i));if(!c)return console.warn(`TOOL_CALL_ARGS: No message found containing tool call with ID '${i}'`),p();let l=c.toolCalls?.find(e=>e.id===i);if(!l)return console.warn(`TOOL_CALL_ARGS: No tool call found with ID '${i}'`),p();let u=await AO(r,o,s,(r,i,a)=>{let o=l.function.arguments,s=l.function.name,c={};try{c=Id(o)}catch{}return r.onToolCallArgsEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallBuffer:o,toolCallName:s,partialToolCallArgs:c})});return f(u),u.stopPropagation!==!0&&(l.function.arguments+=a,IO(l,t),f({messages:o})),p()}case L.TOOL_CALL_END:{let{toolCallId:i}=t,a=o.find(e=>e.toolCalls?.some(e=>e.id===i));if(!a)return console.warn(`TOOL_CALL_END: No message found containing tool call with ID '${i}'`),p();let c=a.toolCalls?.find(e=>e.id===i);if(!c)return console.warn(`TOOL_CALL_END: No tool call found with ID '${i}'`),p();let l=await AO(r,o,s,(r,i,a)=>{let o=c.function.arguments,s=c.function.name,l={};try{l=JSON.parse(o)}catch{}return r.onToolCallEndEvent?.({event:t,messages:i,state:a,agent:n,input:e,toolCallName:s,toolCallArgs:l})});return f(l),l.stopPropagation!==!0&&IO(c,t)&&f({messages:o}),await Promise.all(r.map(t=>{t.onNewToolCall?.({toolCall:c,messages:o,state:s,agent:n,input:e})})),p()}case L.TOOL_CALL_RESULT:{let i=await AO(r,o,s,(r,i,a)=>r.onToolCallResultEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{messageId:i,toolCallId:a,content:c,role:l,subagentRunId:d}=t;u.add(a);let p={id:i,toolCallId:a,role:l||`tool`,content:c,...d!=null&&{subagentRunId:d}};IO(p,t);let m=o.findIndex(e=>e.role===`assistant`&&e.toolCalls?.some(e=>e.id===a));if(m===-1)o.push(p);else{let e=m+1;for(;e{t.onNewMessage?.({message:p,messages:o,state:s,agent:n,input:e})})),f({messages:o})}return p()}case L.STATE_SNAPSHOT:{let i=await AO(r,o,s,(r,i,a)=>r.onStateSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{snapshot:e}=t;s=e,f({state:s})}return p()}case L.STATE_DELTA:{let i=await AO(r,o,s,(r,i,a)=>r.onStateDeltaEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{delta:e}=t;try{s=Fl.applyPatch(s,e,!0,!1).newDocument,f({state:s})}catch(t){let n=t instanceof Error?t.message:String(t);console.warn(`Failed to apply state patch:\nCurrent state: ${JSON.stringify(s,null,2)}\nPatch operations: ${JSON.stringify(e,null,2)}\nError: ${n}`)}}return p()}case L.MESSAGES_SNAPSHOT:{let i=await AO(r,o,s,(r,i,a)=>r.onMessagesSnapshotEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{messages:e}=t,n=e.map(e=>{if(e.subagentRunId!==null)return e;let t={...e};return delete t.subagentRunId,t}),r=new Map(n.map(e=>[e.id,e])),i=CO(t),a=n.some(e=>e.role===`activity`),s=n.some(e=>e.role===`reasoning`),c=e=>e.role===`activity`&&(i?!i.includes(e.activityType):i!==null&&!a)||e.role===`reasoning`&&!s;o=o.filter(e=>r.has(e.id)||c(e)).map(e=>r.get(e.id)??e);let l=new Set(o.map(e=>e.id));for(let e of n)l.has(e.id)||o.push(e);f({messages:o})}return p()}case L.ACTIVITY_SNAPSHOT:{let i=t,a=o.findIndex(e=>e.id===i.messageId),c=a>=0?o[a]:void 0,l=c?.role===`activity`?c:void 0,u=i.replace??!0,d=await AO(r,o,s,(t,r,a)=>t.onActivitySnapshotEvent?.({event:i,messages:r,state:a,agent:n,input:e,activityMessage:l,existingMessage:c}));if(f(d),d.stopPropagation!==!0){let t={id:i.messageId,role:`activity`,activityType:i.activityType,content:wO(i.content),...i.subagentRunId!=null&&{subagentRunId:i.subagentRunId}},c,d;a===-1?(o.push(t),c=t,d=t):l?(u&&(o[a]={...l,activityType:i.activityType,content:wO(i.content),subagentRunId:i.subagentRunId},i.subagentRunId??delete o[a].subagentRunId),d=o[a]):u&&(o[a]=t,c=t,d=t),IO(d,i),f({messages:o}),c&&await Promise.all(r.map(t=>t.onNewMessage?.({message:c,messages:o,state:s,agent:n,input:e})))}return p()}case L.ACTIVITY_DELTA:{let i=t,a=o.findIndex(e=>e.id===i.messageId);if(a===-1)return p();let c=o[a];if(c.role!==`activity`)return console.warn(`ACTIVITY_DELTA: Message '${i.messageId}' is not an activity message`),p();let l=c,u=await AO(r,o,s,(t,r,a)=>t.onActivityDeltaEvent?.({event:i,messages:r,state:a,agent:n,input:e,activityMessage:l}));if(f(u),u.stopPropagation!==!0)try{IO(l,i)&&f({messages:o});let e=wO(l.content??{}),t=Fl.applyPatch(e,i.patch??[],!0,!1).newDocument;o[a]={...l,content:wO(t),activityType:i.activityType},f({messages:o})}catch(e){let t=e instanceof Error?e.message:String(e);console.warn(`Failed to apply activity patch for '${i.messageId}': ${t}`)}return p()}case L.RAW:return f(await AO(r,o,s,(r,i,a)=>r.onRawEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case L.CUSTOM:return f(await AO(r,o,s,(r,i,a)=>r.onCustomEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case L.RUN_STARTED:{let i=await AO(r,o,s,(r,i,a)=>r.onRunStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),l=[],u=new Set,i.stopPropagation!==!0){let e=t;if(e.input?.messages){for(let t of e.input.messages){let e=t;if(t.subagentRunId===null){let n={...t};delete n.subagentRunId,e=n}o.find(t=>t.id===e.id)||o.push(e)}f({messages:o})}}return p()}case L.RUN_FINISHED:{let i=t,a=i.outcome?.type===`interrupt`?{event:i,outcome:`interrupt`,interrupts:i.outcome.interrupts}:i.outcome?.type===`cancelled`?{event:i,outcome:`cancelled`}:{event:i,outcome:`success`,result:i.result,pendingToolCallIds:d(i)},c=await AO(r,o,s,(t,r,i)=>t.onRunFinishedEvent?.({...a,messages:r,state:i,agent:n,input:e}));return f(c),c.stopPropagation!==!0&&(n.pendingInterrupts=a.outcome===`interrupt`?a.interrupts.map(e=>{if(e.subagentRunId!==null)return e;let t={...e};return delete t.subagentRunId,t}):[]),p()}case L.RUN_ERROR:return f(await AO(r,o,s,(r,i,a)=>r.onRunErrorEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case L.STEP_STARTED:return f(await AO(r,o,s,(r,i,a)=>r.onStepStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case L.STEP_FINISHED:return f(await AO(r,o,s,(r,i,a)=>r.onStepFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case L.TEXT_MESSAGE_CHUNK:throw Error(`TEXT_MESSAGE_CHUNK must be transformed before being applied`);case L.TOOL_CALL_CHUNK:throw Error(`TOOL_CALL_CHUNK must be transformed before being applied`);case L.REASONING_START:return f(await AO(r,o,s,(r,i,a)=>r.onReasoningStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case L.REASONING_MESSAGE_START:{let i=await AO(r,o,s,(r,i,a)=>r.onReasoningMessageStartEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(i),i.stopPropagation!==!0){let{messageId:e,subagentRunId:n}=t,r=o.find(t=>t.id===e);if(r?.role===`activity`)return console.warn(`REASONING_MESSAGE_START: Message '${e}' is an activity message — message ids must be unique across activity and reasoning messages`),p();let i=r;if(!i){let t={id:e,role:`reasoning`,content:``,...n!=null&&{subagentRunId:n}};o.push(t),i=t}let a=IO(i,t);(!r||a)&&f({messages:o})}return p()}case L.REASONING_MESSAGE_CONTENT:{let{messageId:i,delta:a}=t,c=o.find(e=>e.id===i);if(!c)return console.warn(`REASONING_MESSAGE_CONTENT: No message found with ID '${i}'`),p();if(c.role===`activity`)return console.warn(`REASONING_MESSAGE_CONTENT: Message '${i}' is an activity message — message ids must be unique across activity and reasoning messages`),p();let l=await AO(r,o,s,(r,i,a)=>r.onReasoningMessageContentEvent?.({event:t,messages:i,state:a,agent:n,input:e,reasoningMessageBuffer:typeof c.content==`string`?c.content:``}));return f(l),l.stopPropagation!==!0&&(c.content=`${typeof c.content==`string`?c.content:``}${a}`,IO(c,t),f({messages:o})),p()}case L.REASONING_MESSAGE_END:{let{messageId:i}=t,a=o.find(e=>e.id===i);if(!a)return console.warn(`REASONING_MESSAGE_END: No message found with ID '${i}'`),p();if(a.role===`activity`)return console.warn(`REASONING_MESSAGE_END: Message '${i}' is an activity message — message ids must be unique across activity and reasoning messages`),p();let c=await AO(r,o,s,(r,i,o)=>r.onReasoningMessageEndEvent?.({event:t,messages:i,state:o,agent:n,input:e,reasoningMessageBuffer:typeof a.content==`string`?a.content:``}));return f(c),c.stopPropagation!==!0&&IO(a,t)&&f({messages:o}),await Promise.all(r.map(t=>{t.onNewMessage?.({message:a,messages:o,state:s,agent:n,input:e})})),p()}case L.REASONING_MESSAGE_CHUNK:throw Error(`REASONING_MESSAGE_CHUNK must be transformed before being applied`);case L.REASONING_END:return f(await AO(r,o,s,(r,i,a)=>r.onReasoningEndEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case L.REASONING_ENCRYPTED_VALUE:{let{subtype:i,entityId:a,encryptedValue:l}=t,u=await AO(r,o,s,(r,i,a)=>r.onReasoningEncryptedValueEvent?.({event:t,messages:i,state:a,agent:n,input:e}));if(f(u),u.stopPropagation!==!0){let e=!1;if(i===`tool-call`){for(let t of o)if(t.role===`assistant`&&t.toolCalls){let n=t.toolCalls.find(e=>e.id===a);if(n){n.encryptedValue=l,e=!0;break}}}else{let t=o.find(e=>e.id===a);t?.role!==`activity`&&t&&(t.encryptedValue=l,e=!0)}e&&(c.messages=o)}return p()}case L.SUBAGENT_STARTED:return f(await AO(r,o,s,(r,i,a)=>r.onSubagentStartedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case L.SUBAGENT_FINISHED:return f(await AO(r,o,s,(r,i,a)=>r.onSubagentFinishedEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p();case L.SUBAGENT_ERROR:return f(await AO(r,o,s,(r,i,a)=>r.onSubagentErrorEvent?.({event:t,messages:i,state:a,agent:n,input:e}))),p()}return t.type,p()}),Sd(),r.length>0?Ad({}):e=>e)};function RO(e,t){typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`[ag-ui][compat] Converting deprecated ${e} to ${t}. The old shape leaves the protocol after its shim window — see the repo-root DEPRECATIONS.md. Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`)}var zO=e=>t=>{let n=MO(e),r=new Set,i=new Set,a=new Set,o=new Set,s={message:new Map,toolCall:new Map,activity:new Map,reasoning:new Map},c=!1,l=!1,u=!1,d=new Map,f=e=>{let t=d.get(e);return t||(t=new Map,d.set(e,t)),t},p=()=>{for(let e of d.values())if(e.size>0)return!0;return!1},m=new Map,h=new Set,g=!1,_=!1,v=()=>{_=!1,r.clear(),i.clear(),a.clear(),o.clear(),s.message.clear(),s.toolCall.clear(),s.activity.clear(),s.reasoning.clear(),d.clear(),m.clear(),h.clear(),c=!1,l=!1,g=!0},y=(e,t)=>{let n=e??[];if(Array.isArray(n))for(let e of n){if(!e||typeof e.id!=`string`)continue;if(e.subagentRunId===null)return new R(`Cannot send a message (id '${e.id}') with 'subagentRunId: null'. The field is optional — omit it entirely.`);let n=e.role===`reasoning`?s.reasoning:e.role===`activity`?s.activity:s.message;(t||!n.has(e.id))&&n.set(e.id,{subagentRunId:e.subagentRunId});for(let n of e.toolCalls??[])n&&typeof n.id==`string`&&(t||!s.toolCall.has(n.id))&&s.toolCall.set(n.id,{subagentRunId:e.subagentRunId??void 0})}},b=(e,t,n,r,i)=>{if(t!==void 0&&n&&n.subagentRunId!==t)return new R(`Cannot send '${e}': subagentRunId '${t}' does not match the ${r} '${i}' opener's subagent '${n.subagentRunId??`(the parent agent)`}'.`)};return t.pipe(xd(e=>{let t=e.type;if(n?.event(`VERIFY`,`Event:`,e,{type:e.type}),l&&t!==L.RUN_STARTED)return z(()=>new R(`Cannot send event type '${t}': The run has already errored with 'RUN_ERROR'. No further events can be sent.`));if(c&&t!==L.RUN_ERROR&&t!==L.RUN_STARTED)return z(()=>new R(`Cannot send event type '${t}': The run has already finished with 'RUN_FINISHED'. Start a new run with 'RUN_STARTED'.`));if(!u){if(u=!0,t!==L.RUN_STARTED&&t!==L.RUN_ERROR)return z(()=>new R(`First event must be 'RUN_STARTED'`))}else if(t===L.RUN_STARTED){if(g&&!c&&!l)return z(()=>new R(`Cannot send 'RUN_STARTED' while a run is still active. The previous run must be finished with 'RUN_FINISHED' before starting a new run.`));(c||l)&&v()}if(e.subagentRunId===null){_||(_=!0,RO(`subagentRunId: null`,`an absent field`));let{subagentRunId:t,...n}=e;e=n}if(t===L.SUBAGENT_STARTED||t===L.SUBAGENT_FINISHED||t===L.SUBAGENT_ERROR){let n=t===L.SUBAGENT_STARTED?[`description`,`parentSubagentRunId`,`parentToolCallId`,`parentMessageId`]:t===L.SUBAGENT_FINISHED?[`outcome`]:[`code`];for(let r of n)if(e[r]===null)return z(()=>new R(`Cannot send '${t}' with '${r}: null'. The field is optional — omit it entirely.`));let r=e.outcome;if(r!=null&&r.type!==`success`&&r.type!==`suspended`)return z(()=>new R(`Cannot send '${t}' with outcome type '${String(r.type)}'. The outcome is either { type: "success" } or { type: "suspended" }.`));if(r&&r.interruptIds===null)return z(()=>new R(`Cannot send '${t}' with 'outcome.interruptIds: null'. The field is optional — omit it entirely.`));if(r&&Array.isArray(r.interruptIds)&&r.interruptIds.some(e=>typeof e!=`string`))return z(()=>new R(`Cannot send '${t}' with a non-string entry in 'outcome.interruptIds'. Interrupt ids are strings.`))}if(t===L.RUN_FINISHED){let t=e.outcome;if(t?.type===`interrupt`&&Array.isArray(t.interrupts)){for(let e of t.interrupts)if(e&&e.subagentRunId===null)return z(()=>new R(`Cannot send 'RUN_FINISHED' with an interrupt (id '${e.id}') carrying 'subagentRunId: null'. The field is optional — omit it entirely.`))}}switch(t){case L.TEXT_MESSAGE_START:{let n=e.messageId;if(r.has(n))return z(()=>new R(`Cannot send 'TEXT_MESSAGE_START' event: A text message with ID '${n}' is already in progress. Complete it with 'TEXT_MESSAGE_END' first.`));let i=s.message.get(n);if(i){let r=b(t,e.subagentRunId,i,`message`,n);if(r)return z(()=>r)}return r.add(n),i||s.message.set(n,{subagentRunId:e.subagentRunId}),gd(e)}case L.TEXT_MESSAGE_CONTENT:{let n=e.messageId;if(!r.has(n))return z(()=>new R(`Cannot send 'TEXT_MESSAGE_CONTENT' event: No active text message found with ID '${n}'. Start a text message with 'TEXT_MESSAGE_START' first.`));let i=b(t,e.subagentRunId,s.message.get(n),`message`,n);return i?z(()=>i):gd(e)}case L.TEXT_MESSAGE_END:{let n=e.messageId;if(!r.has(n))return z(()=>new R(`Cannot send 'TEXT_MESSAGE_END' event: No active text message found with ID '${n}'. A 'TEXT_MESSAGE_START' event must be sent first.`));let i=b(t,e.subagentRunId,s.message.get(n),`message`,n);return i?z(()=>i):(r.delete(n),gd(e))}case L.TOOL_CALL_START:{let n=e.toolCallId;if(i.has(n))return z(()=>new R(`Cannot send 'TOOL_CALL_START' event: A tool call with ID '${n}' is already in progress. Complete it with 'TOOL_CALL_END' first.`));let r=e.parentMessageId,a=e.subagentRunId,o;if(r!==void 0){let e=s.message.get(r);if(e){if(a!==void 0&&a!==e.subagentRunId)return z(()=>new R(`Cannot send 'TOOL_CALL_START': subagentRunId '${a}' does not match its parent message '${r}' owner '${e.subagentRunId??`(the parent agent)`}'. A tool call belongs to the message that carries it.`));o=e}}let c=s.toolCall.get(n);if(c){let e=b(t,a,c,`tool call`,n);if(e)return z(()=>e);if(a===void 0&&o&&o.subagentRunId!==c.subagentRunId)return z(()=>new R(`Cannot send 'TOOL_CALL_START': tool call '${n}' is owned by '${c.subagentRunId??`(the parent agent)`}' but its parent message '${r}' is owned by '${o.subagentRunId??`(the parent agent)`}'. A tool call belongs to the message that carries it.`))}return i.add(n),c||s.toolCall.set(n,a===void 0?o??{subagentRunId:void 0}:{subagentRunId:a}),gd(e)}case L.TOOL_CALL_ARGS:{let n=e.toolCallId;if(!i.has(n))return z(()=>new R(`Cannot send 'TOOL_CALL_ARGS' event: No active tool call found with ID '${n}'. Start a tool call with 'TOOL_CALL_START' first.`));let r=b(t,e.subagentRunId,s.toolCall.get(n),`tool call`,n);return r?z(()=>r):gd(e)}case L.TOOL_CALL_END:{let n=e.toolCallId;if(!i.has(n))return z(()=>new R(`Cannot send 'TOOL_CALL_END' event: No active tool call found with ID '${n}'. A 'TOOL_CALL_START' event must be sent first.`));let r=b(t,e.subagentRunId,s.toolCall.get(n),`tool call`,n);return r?z(()=>r):(i.delete(n),gd(e))}case L.STEP_STARTED:{let t=e.stepName,n=e.subagentRunId;return f(n).has(t)?z(()=>new R(`Step "${t}" is already active for 'STEP_STARTED'${n===void 0?``:` in subagent '${n}'`}`)):(f(n).set(t,!0),gd(e))}case L.STEP_FINISHED:{let t=e.stepName,n=e.subagentRunId;if(!f(n).has(t)){let e,r=!1;for(let[i,a]of d)if(i!==n&&a.has(t)){e=i,r=!0;break}return z(r?()=>new R(`Cannot send 'STEP_FINISHED' for step "${t}" attributed to ${n===void 0?`the parent agent`:`subagent '${n}'`}: that step is open under ${e===void 0?`the parent agent`:`subagent '${e}'`}. A step must be finished by whoever started it.`):()=>new R(`Cannot send 'STEP_FINISHED' for step "${t}" that was not started`))}return f(n).delete(t),gd(e)}case L.ACTIVITY_SNAPSHOT:{let t=e.messageId;return(!s.activity.has(t)||e.replace!==!1)&&s.activity.set(t,{subagentRunId:e.subagentRunId}),gd(e)}case L.TOOL_CALL_RESULT:{let t=e.messageId;return typeof t==`string`&&s.message.set(t,{subagentRunId:e.subagentRunId}),gd(e)}case L.REASONING_START:case L.REASONING_MESSAGE_START:{let n=e.messageId,r=t===L.REASONING_START,i=r?a:o;if(i.has(n))return z(()=>new R(r?`Cannot send 'REASONING_START' event: A reasoning span with ID '${n}' is already in progress. Complete it with 'REASONING_END' first.`:`Cannot send 'REASONING_MESSAGE_START' event: A reasoning message with ID '${n}' is already in progress. Complete it with 'REASONING_MESSAGE_END' first.`));let c=s.reasoning.get(n);if(c){let r=b(t,e.subagentRunId,c,`reasoning message`,n);if(r)return z(()=>r)}return i.add(n),c||s.reasoning.set(n,{subagentRunId:e.subagentRunId}),gd(e)}case L.REASONING_MESSAGE_CONTENT:case L.REASONING_MESSAGE_END:case L.REASONING_END:{let n=e.messageId,r=t===L.REASONING_END,i=r?a:o;if(!i.has(n))return z(()=>new R(r?`Cannot send 'REASONING_END' event: No active reasoning span found with ID '${n}'. A 'REASONING_START' event must be sent first.`:`Cannot send '${t}' event: No active reasoning message found with ID '${n}'. Start a reasoning message with 'REASONING_MESSAGE_START' first.`));let c=b(t,e.subagentRunId,s.reasoning.get(n),`reasoning message`,n);return c?z(()=>c):((t===L.REASONING_END||t===L.REASONING_MESSAGE_END)&&i.delete(n),gd(e))}case L.REASONING_ENCRYPTED_VALUE:{let n=e.entityId,r=e.subtype,i=r===`tool-call`?s.toolCall.get(n):r===`message`?s.message.get(n)??s.reasoning.get(n):s.reasoning.get(n),a=r===`tool-call`?`tool call`:r===`message`?`message`:`reasoning message`,o=b(t,e.subagentRunId,i,a,n);return o?z(()=>o):gd(e)}case L.ACTIVITY_DELTA:{let n=e.messageId,r=b(t,e.subagentRunId,s.activity.get(n),`activity`,n);return r?z(()=>r):gd(e)}case L.SUBAGENT_STARTED:{if(typeof e.subagentRunId!=`string`)return z(()=>new R(`Cannot send 'SUBAGENT_STARTED' without a 'subagentRunId'.`));if(typeof e.name!=`string`)return z(()=>new R(`Cannot send 'SUBAGENT_STARTED' without a 'name'.`));let t=e.subagentRunId,n=e.parentSubagentRunId;return m.has(t)?z(()=>new R(`Cannot send 'SUBAGENT_STARTED': subagent '${t}' is already active. Finish it with 'SUBAGENT_FINISHED' first.`)):h.has(t)?z(()=>new R(`Cannot send 'SUBAGENT_STARTED': subagent '${t}' has already finished in this run. Subagent IDs are per-invocation and cannot be reused.`)):n!==void 0&&!m.has(n)&&!h.has(n)?z(()=>new R(`Cannot send 'SUBAGENT_STARTED': parentSubagentRunId '${n}' has not been started in this run.`)):(m.set(t,!0),gd(e))}case L.SUBAGENT_FINISHED:case L.SUBAGENT_ERROR:{if(typeof e.subagentRunId!=`string`)return z(()=>new R(`Cannot send '${t}' without a 'subagentRunId'.`));if(t===L.SUBAGENT_ERROR&&typeof e.message!=`string`)return z(()=>new R(`Cannot send 'SUBAGENT_ERROR' without a 'message'.`));let n=e.subagentRunId;return m.has(n)?(m.delete(n),h.add(n),gd(e)):z(()=>new R(`Cannot send '${t}': no active subagent found with ID '${n}'. A 'SUBAGENT_STARTED' event must be sent first.`))}case L.MESSAGES_SNAPSHOT:{let t=y(e.messages,!0);if(t)return z(()=>t)}return gd(e);case L.RUN_STARTED:g=!0;{let t=y((e.input??{}).messages,!1);if(t)return z(()=>t)}return gd(e);case L.RUN_FINISHED:if(p()){let e=[];for(let[t,n]of d)for(let r of n.keys())e.push(t===void 0?r:`${r} (subagent '${t}')`);let t=e.join(`, `);return z(()=>new R(`Cannot send 'RUN_FINISHED' while steps are still active: ${t}`))}if(r.size>0){let e=Array.from(r.keys()).join(`, `);return z(()=>new R(`Cannot send 'RUN_FINISHED' while text messages are still active: ${e}`))}if(o.size>0){let e=Array.from(o.keys()).join(`, `);return z(()=>new R(`Cannot send 'RUN_FINISHED' while reasoning messages are still active: ${e}`))}if(a.size>0){let e=Array.from(a.keys()).join(`, `);return z(()=>new R(`Cannot send 'RUN_FINISHED' while reasoning spans are still active: ${e}`))}if(i.size>0){let e=Array.from(i.keys()).join(`, `);return z(()=>new R(`Cannot send 'RUN_FINISHED' while tool calls are still active: ${e}`))}if(m.size>0){let e=Array.from(m.keys()).join(`, `);return z(()=>new R(`Cannot send 'RUN_FINISHED' while subagents are still active: ${e}`))}return c=!0,gd(e);case L.RUN_ERROR:return l=!0,gd(e);case L.CUSTOM:return gd(e);default:return gd(e)}}))},BO=function(e){return e.HEADERS=`headers`,e.DATA=`data`,e}({}),VO=e=>wd(()=>hd(e())).pipe(Md(e=>{if(!e.ok){let t=e.headers.get(`content-type`)||``;return hd(e.text()).pipe(xd(n=>{let r=n;if(t.includes(`application/json`))try{r=JSON.parse(n)}catch{}let i=Error(`HTTP ${e.status}: ${typeof r==`string`?r:JSON.stringify(r)}`);return i.status=e.status,i.payload=r,z(()=>i)}))}let t={type:BO.HEADERS,status:e.status,headers:e.headers},n=e.body?.getReader();return n?new wu(e=>{let r=!1;return e.next(t),(async()=>{try{for(;!e.closed;){let{done:t,value:i}=await n.read();if(t){r=!0;break}let a={type:BO.DATA,data:i};e.next(a)}e.complete()}catch(t){r=!0,e.error(t)}})(),()=>{r||n.cancel().catch(e=>{e?.name!==`AbortError`&&console.warn(`Failed to cancel HTTP response stream:`,e)})}}):z(()=>Error(`Failed to getReader() from response`))})),HO=10485760,UO=(e,t)=>{let n=MO(t),r=new Nu,i=new TextDecoder(`utf-8`,{fatal:!1}),a=``;e.subscribe({next:e=>{if(e.type!==BO.HEADERS&&e.type===BO.DATA&&e.data){let t=i.decode(e.data,{stream:!0});a+=t;let n=a.split(/\n\n/);a=n.pop()||``;for(let e of n)o(e);if(a.length>HO){r.error(Error(`SSE buffer size exceeded maximum limit of ${HO/1048576} MB`));return}}},error:e=>r.error(e),complete:()=>{a&&(a+=i.decode(),o(a)),r.complete()}});function o(e){let t=e.split(` +`),i=[];for(let e of t)e.startsWith(`data:`)&&i.push(e.slice(5).replace(/^ /,``));if(i.length>0)try{let e=i.join(` +`),t=JSON.parse(e);n?.event(`SSE`,`Event received:`,t,{type:t?.type}),r.next(t)}catch(e){r.error(e)}}return r.asObservable()},WO=10485760,GO=()=>typeof process<`u`&&!!{}.SUPPRESS_TRANSFORMATION_WARNINGS,KO=(e,t)=>{let n=MO(t),r=new Nu,i=new Uint8Array,a=!1;e.subscribe({next:e=>{if(e.type!==BO.HEADERS&&e.type===BO.DATA&&e.data){let t=new Uint8Array(i.length+e.data.length);t.set(i,0),t.set(e.data,i.length),i=t,o()}},error:e=>r.error(e),complete:()=>{if(o(),!a){if(i.length>0){r.error(Error(`The binary stream ended mid-frame: ${i.length} trailing bytes could not be read as a complete message.`));return}r.complete()}}});function o(){if(!a)for(;i.length>=4;){let e=4+new DataView(i.buffer,i.byteOffset,4).getUint32(0,!1);if(e>WO){r.error(Error(`Protobuf message size exceeded maximum limit of ${WO/1048576} MB`));return}if(i.length{let n=MO(t),r=new Nu,i=new Iu(1),a=!1,o,s=!1,c=()=>{s=!0,o?.unsubscribe()},l=e=>{c(),r.error(e)},u=()=>{c(),r.complete()};return o=e.subscribe({next:e=>{if(i.next(e),e.type===BO.HEADERS&&!a){a=!0;let t=e.headers.get(`content-type`);n?.lifecycle(`HTTP`,`Stream format detected:`,{contentType:t,parser:t===`application/vnd.ag-ui.event+proto`?`protobuf`:`sse`}),t===`application/vnd.ag-ui.event+proto`?KO(i,n).subscribe({next:e=>r.next(e),error:e=>l(e),complete:()=>u()}):UO(i,n).subscribe({next:e=>{if(typeof e!=`object`||!e||Array.isArray(e)){let t=Error(`Invalid event: the frame is not a JSON object.`);n?.event(`HTTP`,`Event invalid:`,{json:e,error:String(t)}),l(t);return}let t=e;if(typeof t.type!=`string`||t.type.length===0){let t=Error(`Invalid event: the frame carries no event type.`);n?.event(`HTTP`,`Event invalid:`,{json:e,error:String(t)}),l(t);return}n?.event(`HTTP`,`Event received:`,e,{type:t.type}),r.next(e)},error:e=>{if(e?.name===`AbortError`){r.next({type:L.RUN_ERROR,message:e.message||`Request aborted`,code:`abort`,rawEvent:e}),u();return}return l(e)},complete:()=>u()})}else a||l(Error(`No headers event received before data events`))},error:e=>{i.error(e),l(e)},complete:()=>{i.complete()}}),s&&o.unsubscribe(),r.asObservable()},JO={TextMessageStart:`TextMessageStart`,TextMessageContent:`TextMessageContent`,TextMessageEnd:`TextMessageEnd`,ActionExecutionStart:`ActionExecutionStart`,ActionExecutionArgs:`ActionExecutionArgs`,ActionExecutionEnd:`ActionExecutionEnd`,ActionExecutionResult:`ActionExecutionResult`,AgentStateMessage:`AgentStateMessage`,MetaEvent:`MetaEvent`,RunStarted:`RunStarted`,RunFinished:`RunFinished`,RunError:`RunError`,NodeStarted:`NodeStarted`,NodeFinished:`NodeFinished`},YO=e=>{if(typeof e==`string`)return e;if(!Array.isArray(e))return;let t=e.filter(e=>e.type===`text`).map(e=>e.text).filter(e=>e.length>0);if(t.length!==0)return t.join(` +`)};function XO(e,t){return $c(t)&&ZO(`[ag-ui][legacy] The result of tool call '${e}' carries content parts the legacy protocol cannot represent; only its text parts are bridged and the rest is dropped.`),Qc(t)}var ZO=e=>{typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(e)},QO=(e,t,n)=>r=>{let i={},a=!0,o=!0,s=``,c=null,l=null,u=[],d={},f=!1,p=e=>{typeof e==`object`&&e&&(`messages`in e&&delete e.messages,i=e)};return r.pipe(xd(r=>{switch(r.type){case L.TEXT_MESSAGE_START:{let e=r;return[{type:JO.TextMessageStart,messageId:e.messageId,role:e.role}]}case L.TEXT_MESSAGE_CONTENT:{let e=r;return[{type:JO.TextMessageContent,messageId:e.messageId,content:e.delta}]}case L.TEXT_MESSAGE_END:{let e=r;return[{type:JO.TextMessageEnd,messageId:e.messageId}]}case L.TOOL_CALL_START:{let e=r;return u.push({id:e.toolCallId,type:`function`,function:{name:e.toolCallName,arguments:``}}),o=!0,d[e.toolCallId]=e.toolCallName,[{type:JO.ActionExecutionStart,actionExecutionId:e.toolCallId,actionName:e.toolCallName,parentMessageId:e.parentMessageId}]}case L.TOOL_CALL_ARGS:{let c=r,d=u.find(e=>e.id===c.toolCallId);if(!d)return ZO(`[ag-ui][legacy] TOOL_CALL_ARGS: No tool call found with ID '${c.toolCallId}'`),[];d.function.arguments+=c.delta;let f=!1;if(l){let e=l.find(e=>e.tool==d.function.name);if(e)try{let t=JSON.parse(Id(d.function.arguments));e.tool_argument&&e.tool_argument in t?(p({...i,[e.state_key]:t[e.tool_argument]}),f=!0):e.tool_argument||(p({...i,[e.state_key]:t}),f=!0)}catch{}}return[{type:JO.ActionExecutionArgs,actionExecutionId:c.toolCallId,args:c.delta},...f?[{type:JO.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}]:[]]}case L.TOOL_CALL_END:{let e=r;return[{type:JO.ActionExecutionEnd,actionExecutionId:e.toolCallId}]}case L.TOOL_CALL_RESULT:{let e=r,t=d[e.toolCallId];return(t===void 0||t===``)&&ZO(`[ag-ui][legacy] No usable tool name was seen for tool call '${e.toolCallId}' (${t===void 0?`no TOOL_CALL_START reached this bridge`:`its TOOL_CALL_START carried an empty toolCallName`}), so its result is being bridged with the fabricated action name "unknown". Downstream consumers route on that name.`),[{type:JO.ActionExecutionResult,actionExecutionId:e.toolCallId,result:XO(e.toolCallId,e.content),actionName:t||`unknown`}]}case L.RAW:return f||(f=!0,ZO(`[ag-ui][legacy] Dropping RAW events: the legacy runtime protocol has no equivalent, so the provider payloads they carry do not reach the legacy stream. Reported once per stream.`)),[];case L.CUSTOM:{let e=r;switch(e.name){case`Exit`:a=!1;break;case`PredictState`:l=e.value}return[{type:JO.MetaEvent,name:e.name,value:e.value}]}case L.STATE_SNAPSHOT:return p(r.snapshot),[{type:JO.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}];case L.STATE_DELTA:{let c=r,l;try{l=Fl.applyPatch(i,c.delta,!0,!1).newDocument}catch(e){let t=e instanceof Error?e.message:String(e);return ZO(`[ag-ui][legacy] Failed to apply state patch:\nCurrent state: ${JSON.stringify(i,null,2)}\nPatch operations: ${JSON.stringify(c.delta,null,2)}\nError: ${t}`),[]}return p(l),[{type:JO.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:o}]}case L.MESSAGES_SNAPSHOT:return c=r.messages,[{type:JO.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify({...i,...c?{messages:c}:{}}),active:!0}];case L.RUN_STARTED:return[];case L.RUN_FINISHED:{if(c&&(i.messages=c),Object.keys(i).length===0)return[];let r=null;if(c)try{r=$O(c)}catch(e){return[{type:JO.RunError,message:e.message}]}return[{type:JO.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify({...i,...r?{messages:r}:{}}),active:!1}]}case L.RUN_ERROR:{let e=r;return[{type:JO.RunError,message:e.message,code:e.code}]}case L.STEP_STARTED:return s=r.stepName,u=[],l=null,[{type:JO.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:!0}];case L.STEP_FINISHED:return u=[],l=null,[{type:JO.AgentStateMessage,threadId:e,agentName:n,nodeName:s,runId:t,running:a,role:`assistant`,state:JSON.stringify(i),active:!1}];default:return[]}}))};function $O(e){let t=[];for(let n of e)if(n.role===`assistant`||n.role===`user`||n.role===`system`){let e=YO(n.content);if(e){let r={id:n.id,role:n.role,content:e};t.push(r)}if(n.role===`assistant`&&n.toolCalls&&n.toolCalls.length>0)for(let e of n.toolCalls){let r;try{r=JSON.parse(e.function.arguments)}catch(t){throw Error(`Failed to parse arguments for tool call '${e.id}' (${e.function.name}): ${t.message}`)}let i={id:e.id,name:e.function.name,arguments:r,parentMessageId:n.id};t.push(i)}}else if(n.role===`tool`){let r=`unknown`;for(let t of e)if(t.role===`assistant`&&t.toolCalls?.length){for(let e of t.toolCalls)if(e.id===n.toolCallId){r=e.function.name;break}}let i={id:n.id,result:XO(n.toolCallId,n.content),actionExecutionId:n.toolCallId,actionName:r};t.push(i)}return t}var ek=e=>e.kind===`tool`?e.fields.toolCallId:e.fields.messageId,tk=e=>e===`tool`?`toolCallId`:`messageId`,nk=(e,t,n,r,i)=>{if(r!==void 0&&r!==i)throw Error(`Cannot continue ${e} '${t}': chunk ${n} '${r}' does not match the open stream's ${n} ${i===void 0?`(absent)`:`'${i}'`}.`)},rk=(e,t)=>t.metadata===void 0?e:{...e,metadata:t.metadata},ik=(e,t)=>{let n=rk(e,t);return t.rawEvent===void 0?n:{...n,rawEvent:t.rawEvent}},ak=e=>new Set(Object.keys(e.shape)),ok=ak(bx),sk=ak(wx),ck=ak(sS),lk=(e,t)=>{let n;for(let r of Object.keys(e))t.has(r)||((n??={})[r]=e[r]);return n},uk=e=>{typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`[ag-ui][transform] ${e} Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`)},dk=(e,t,n,r)=>{if(t===void 0||n||e.length===0)return;let i=e[e.length-1],a=Object.keys(t).filter(e=>Object.prototype.hasOwnProperty.call(i,e));a.length>0&&uk(`A ${r} carried ${a.map(e=>`'${e}'`).join(`, `)}, which the synthesized ${String(i.type)} already describes. The synthesized value is kept and the chunk's is dropped — this stage does not judge a described field, so the producer's value cannot be substituted for its own.`),e[e.length-1]={...t,...i}},fk=e=>t=>{let n=MO(e),r=new Map,i=e=>{let t=r.get(e);if(!t)return[];switch(r.delete(e),t.kind){case`text`:{let e={type:L.TEXT_MESSAGE_END,messageId:t.fields.messageId,...t.fields.subagentRunId!==void 0&&{subagentRunId:t.fields.subagentRunId}};return n?.event(`TRANSFORM`,`TEXT_MESSAGE_END`,e,{messageId:e.messageId}),[e]}case`tool`:{let e={type:L.TOOL_CALL_END,toolCallId:t.fields.toolCallId,...t.fields.subagentRunId!==void 0&&{subagentRunId:t.fields.subagentRunId}};return n?.event(`TRANSFORM`,`TOOL_CALL_END`,e,{toolCallId:e.toolCallId}),[e]}case`reasoning`:{let e={type:L.REASONING_MESSAGE_END,messageId:t.fields.messageId,...t.fields.subagentRunId!==void 0&&{subagentRunId:t.fields.subagentRunId}};return n?.event(`TRANSFORM`,`REASONING_MESSAGE_END`,e,{messageId:e.messageId}),[e]}}},a=()=>[...r.keys()].flatMap(e=>i(e)),o=(e,t)=>{for(let[n,i]of r)if(i.kind===e&&ek(i)===t)return{owner:n}},s=(e,t,n,i,a)=>{if(t!==void 0){let r=o(e,t);if(r){if(n!==void 0&&n!==r.owner)throw Error(`Cannot continue ${a} '${t}': chunk subagentRunId '${n}' does not match the open stream's subagent '${r.owner??`(the parent agent)`}'.`);return r.owner}return n}if(n!==void 0)return n;if(r.get(void 0)?.kind===e)return;let s=[...r.entries()].filter(([,t])=>t.kind===e);if(s.length===1)return s[0][0];if(s.length>1)throw Error(`Ambiguous ${i}: it carries neither a ${tk(e)} nor a subagentRunId, but ${s.length} lanes have an open ${a}. Attribute the chunk to the subagent it belongs to.`)};return t.pipe(xd(e=>{switch(e.type){case L.TEXT_MESSAGE_START:case L.TEXT_MESSAGE_CONTENT:case L.TEXT_MESSAGE_END:case L.TOOL_CALL_START:case L.TOOL_CALL_ARGS:case L.TOOL_CALL_END:case L.TOOL_CALL_RESULT:case L.STATE_SNAPSHOT:case L.STATE_DELTA:case L.CUSTOM:case L.STEP_STARTED:case L.STEP_FINISHED:case L.REASONING_START:case L.REASONING_MESSAGE_START:case L.REASONING_MESSAGE_CONTENT:case L.REASONING_MESSAGE_END:case L.REASONING_END:return[...i(e.subagentRunId??void 0),e];case L.RUN_STARTED:case L.RUN_FINISHED:case L.RUN_ERROR:case L.MESSAGES_SNAPSHOT:return[...a(),e];case L.RAW:case L.ACTIVITY_SNAPSHOT:case L.ACTIVITY_DELTA:case L.REASONING_ENCRYPTED_VALUE:case L.SUBAGENT_STARTED:return[e];case L.SUBAGENT_FINISHED:case L.SUBAGENT_ERROR:{let t=e.subagentRunId;return t==null?[e]:[...i(t),e]}case L.TEXT_MESSAGE_CHUNK:{let t=e,a=lk(e,ok),o=s(`text`,t.messageId,t.subagentRunId??void 0,`TEXT_MESSAGE_CHUNK`,`text message`),c=r.get(o),l=[],u=!1,d;if(c?.kind===`text`&&(t.messageId===void 0||t.messageId===c.fields.messageId))nk(`text message`,c.fields.messageId,`role`,t.role,c.fields.role),nk(`text message`,c.fields.messageId,`name`,t.name,c.fields.name),d=c.fields;else{if(l.push(...i(o)),t.messageId===void 0)throw Error(`First TEXT_MESSAGE_CHUNK must have a messageId`);d={messageId:t.messageId,role:t.role===void 0?`assistant`:t.role,name:t.name,subagentRunId:t.subagentRunId},r.set(o,{kind:`text`,fields:d});let e=rk({type:L.TEXT_MESSAGE_START,messageId:t.messageId,role:d.role,...t.name!==void 0&&{name:t.name},...t.subagentRunId!==void 0&&{subagentRunId:t.subagentRunId}},t);l.push(e),n?.event(`TRANSFORM`,`TEXT_MESSAGE_START`,e,{messageId:t.messageId})}if(t.delta!==void 0||t.rawEvent!==void 0){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId,r=ik({...a,type:L.TEXT_MESSAGE_CONTENT,messageId:d.messageId,delta:t.delta===void 0?``:t.delta,...e!==void 0&&{subagentRunId:e}},t);l.push(r),u=!0,n?.event(`TRANSFORM`,`TEXT_MESSAGE_CONTENT`,r,{messageId:d.messageId})}if(l.length===0&&(t.metadata!==void 0||t.rawEvent!==void 0||t.subagentRunId===null||a!==void 0)){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId;l.push({...a,type:L.TEXT_MESSAGE_CONTENT,messageId:d.messageId,delta:``,...t.metadata!==void 0&&{metadata:t.metadata},...t.rawEvent!==void 0&&{rawEvent:t.rawEvent},...e!==void 0&&{subagentRunId:e}}),u=!0}return dk(l,a,u,`TEXT_MESSAGE_CHUNK`),l}case L.TOOL_CALL_CHUNK:{let t=e,a=lk(e,sk),o=s(`tool`,t.toolCallId,t.subagentRunId??void 0,`TOOL_CALL_CHUNK`,`tool call`),c=r.get(o),l=[],u=!1,d;if(c?.kind===`tool`&&(t.toolCallId===void 0||t.toolCallId===c.fields.toolCallId))nk(`tool call`,c.fields.toolCallId,`toolCallName`,t.toolCallName,c.fields.toolCallName),nk(`tool call`,c.fields.toolCallId,`parentMessageId`,t.parentMessageId,c.fields.parentMessageId),d=c.fields;else{if(l.push(...i(o)),t.toolCallId===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallId`);if(t.toolCallName===void 0)throw Error(`First TOOL_CALL_CHUNK must have a toolCallName`);d={toolCallId:t.toolCallId,toolCallName:t.toolCallName,parentMessageId:t.parentMessageId,subagentRunId:t.subagentRunId},r.set(o,{kind:`tool`,fields:d});let e=rk({type:L.TOOL_CALL_START,toolCallId:t.toolCallId,toolCallName:t.toolCallName,...t.parentMessageId!==void 0&&{parentMessageId:t.parentMessageId},...t.subagentRunId!==void 0&&{subagentRunId:t.subagentRunId}},t);l.push(e),n?.event(`TRANSFORM`,`TOOL_CALL_START`,e,{toolCallId:t.toolCallId,toolCallName:t.toolCallName})}if(t.delta!==void 0||t.rawEvent!==void 0){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId,r=ik({...a,type:L.TOOL_CALL_ARGS,toolCallId:d.toolCallId,delta:t.delta===void 0?``:t.delta,...e!==void 0&&{subagentRunId:e}},t);l.push(r),u=!0,n?.event(`TRANSFORM`,`TOOL_CALL_ARGS`,r,{toolCallId:d.toolCallId})}if(l.length===0&&(t.metadata!==void 0||t.rawEvent!==void 0||t.subagentRunId===null||a!==void 0)){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId;l.push({...a,type:L.TOOL_CALL_ARGS,toolCallId:d.toolCallId,delta:``,...t.metadata!==void 0&&{metadata:t.metadata},...t.rawEvent!==void 0&&{rawEvent:t.rawEvent},...e!==void 0&&{subagentRunId:e}}),u=!0}return dk(l,a,u,`TOOL_CALL_CHUNK`),l}case L.REASONING_MESSAGE_CHUNK:{let t=e,a=lk(e,ck),o=s(`reasoning`,t.messageId,t.subagentRunId??void 0,`REASONING_MESSAGE_CHUNK`,`reasoning message`),c=r.get(o),l=[],u=!1,d;if(c?.kind===`reasoning`&&(t.messageId===void 0||t.messageId===c.fields.messageId))d=c.fields;else{if(l.push(...i(o)),t.messageId===void 0)throw Error(`First REASONING_MESSAGE_CHUNK must have a messageId`);d={messageId:t.messageId,subagentRunId:t.subagentRunId},r.set(o,{kind:`reasoning`,fields:d});let e=rk({type:L.REASONING_MESSAGE_START,messageId:t.messageId,role:`reasoning`,...t.subagentRunId!==void 0&&{subagentRunId:t.subagentRunId}},t);l.push(e),n?.event(`TRANSFORM`,`REASONING_MESSAGE_START`,e,{messageId:t.messageId})}if(t.delta!==void 0||t.rawEvent!==void 0){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId,r=ik({...a,type:L.REASONING_MESSAGE_CONTENT,messageId:d.messageId,delta:t.delta===void 0?``:t.delta,...e!==void 0&&{subagentRunId:e}},t);l.push(r),u=!0,n?.event(`TRANSFORM`,`REASONING_MESSAGE_CONTENT`,r,{messageId:d.messageId})}if(l.length===0&&(t.metadata!==void 0||t.rawEvent!==void 0||t.subagentRunId===null||a!==void 0)){let e=t.subagentRunId===void 0?d.subagentRunId:t.subagentRunId;l.push({...a,type:L.REASONING_MESSAGE_CONTENT,messageId:d.messageId,delta:``,...t.metadata!==void 0&&{metadata:t.metadata},...t.rawEvent!==void 0&&{rawEvent:t.rawEvent},...e!==void 0&&{subagentRunId:e}}),u=!0}return dk(l,a,u,`REASONING_MESSAGE_CHUNK`),l}}return e.type,[e]}),jd(()=>{a()}))},pk=Symbol(`agui.strip.drop`);function mk(e){let t=e;for(;;){if(t instanceof tO||t instanceof rO||t instanceof aO||t instanceof hO||t instanceof dO){t=t.unwrap();continue}if(t instanceof pO){t=t.def.in;continue}if(t instanceof _O){t=t.def.getter();continue}return t}}function hk(e){let t=e.def;return typeof t?.discriminator==`string`?t.discriminator:void 0}function gk(e){let t=e,n=Array.isArray(t.def?.values)?t.def.values:t.values?Array.from(t.values):void 0;return n&&n.length===1?n[0]:t.value}function _k(e){let t=mk(e);return t instanceof QD?gk(t):void 0}function vk(e,t,n,r){let i=mk(t);if(i instanceof WD){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t=i.shape,a=e,o={},s=i.meta()?.specOpen===!0;for(let e of Object.keys(a)){let i=Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;if(i===void 0){if(s){o[e]=a[e];continue}r.push(`${n}/${e}`);continue}let c=r.length,l=vk(a[e],i,`${n}/${e}`,r);if(l===pk){if(r.length=c,i.safeParse(void 0).success){r.push(`${n}/${e}`);continue}return pk}o[e]=l}return o}if(i instanceof HD){if(!Array.isArray(e))return e;let t=i.element,a=[];return e.forEach((e,i)=>{let o=r.length,s=vk(e,t,`${n}/${i}`,r);if(s===pk){r.length=o,r.push(`${n}/${i}`);return}a.push(s)}),a}if(i instanceof YD){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t=i.def.valueType,a=e,o={};for(let e of Object.keys(a)){let i=r.length,s=vk(a[e],t,`${n}/${e}`,r);if(s===pk){r.length=i,r.push(`${n}/${e}`);continue}o[e]=s}return o}if(i instanceof GD){let t=i.options,a=hk(i);if(a!==void 0){if(typeof e!=`object`||!e||Array.isArray(e))return e;let i=e[a];for(let o of t){let t=mk(o);if(!(t instanceof WD))continue;let s=t.shape;if(_k(s[a])===i)return vk(e,o,n,r)}return pk}let o=t.filter(e=>mk(e)instanceof WD),s=typeof e==`object`&&!!e&&!Array.isArray(e);if(o.length>1&&s)return e;for(let i of t){let t=mk(i);if(t instanceof HD&&Array.isArray(e)||t instanceof WD&&s)return vk(e,i,n,r)}return e}return e}function yk(e,t){let n=[],r=vk(e,t,``,n);if(r===pk)throw Error(`Internal error: the stripper found the whole value unrecognisable, which the schemas are not supposed to allow — schema/stripper mismatch.`);return{value:r,stripped:n}}var bk=new Set(Object.values(L));function xk(e){return bk.has(e.type)}var Sk=new Map(pS.options.map(e=>{let t=e.shape;return[String(gk(t.type)),e]})),Ck=()=>typeof process<`u`&&!!{}.SUPPRESS_TRANSFORMATION_WARNINGS;function wk(e){Ck()||console.warn(`[ag-ui][enforce] ${e}`)}var Tk=e=>t=>{let n=MO(e);return t.pipe(xd(e=>{if(!xk(e))return wk(`Dropping unrecognised event '${String(e.type)}': no middleware translated it and the protocol does not describe it.`),n?.event(`ENFORCE`,`Unrecognised event dropped:`,e,{type:e.type}),Lu;let t=Sk.get(e.type);if(t===void 0)throw Error(`No validator for recognised event type '${String(e.type)}'`);let{value:r,stripped:i}=yk(e,t);for(let t of i)wk(`Removed unrecognised material at '${t}' on ${String(e.type)}. Nothing handled it; see the repo-root DEPRECATIONS.md if it is a retired shape.`);return gd(t.parse(r))}))};function Ek(e){let{value:t,stripped:n}=yk(Yc(e,`RunAgentInput`),qx);for(let e of n)wk(`Removed unrecognised material at '${e}' from the outgoing input.`);return qx.parse(t)}var Dk=class{runNext(e,t){return t.run(e).pipe(fk(!1))}runNextWithState(e,t){let n=wO(e.messages||[]),r=wO(e.state===void 0?{}:e.state),i=new Iu;return LO(e,i,t,[]).subscribe({next:e=>{e.messages!==void 0&&(n=e.messages),e.state!==void 0&&(r=e.state)},error:()=>{}}),this.runNext(e,t).pipe(Dd(async e=>(i.next(e),await new Promise(e=>setTimeout(e,0)),{event:e,messages:wO(n),state:wO(r)})))}},Ok=class extends Dk{constructor(e){super(),this.fn=e}run(e,t){return this.fn(e,t)}};function kk(e){return e.startsWith(`image/`)?`image`:e.startsWith(`audio/`)?`audio`:e.startsWith(`video/`)?`video`:`document`}function Ak(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`binary`&&`mimeType`in e&&typeof e.mimeType==`string`}function jk(e){let t=kk(e.mimeType);return e.data?{type:t,source:{type:`data`,value:e.data,mimeType:e.mimeType},...e.filename?{metadata:{filename:e.filename}}:{}}:e.url?{type:t,source:{type:`url`,value:e.url,mimeType:e.mimeType},...e.filename?{metadata:{filename:e.filename}}:{}}:((typeof process>`u`||!{}.SUPPRESS_TRANSFORMATION_WARNINGS)&&console.warn(`[ag-ui][compat] A binary content part carries only an id ('${e.id??``}') and cannot be converted to a modern media part; a 1.0 peer will not accept it. Provide data or a url. See the repo-root DEPRECATIONS.md.`),e)}function Mk(e,t,n){if(typeof e!=`object`||!e||!(`type`in e)||e.type!==t.type||!(`source`in e))return!1;let r=e.source;return typeof r!=`object`||!r||!(`type`in r)||r.type!==t.source.type||!(`value`in r)||r.value!==t.source.value||!(`mimeType`in r)||r.mimeType!==t.source.mimeType?!1:!n||`metadata`in e&&typeof e.metadata==`object`&&e.metadata!==null&&`filename`in e.metadata&&e.metadata.filename===n}function Nk(e){let t=e.content;if(!Array.isArray(t))return e;let n=t.flatMap(e=>{if(Ak(e)){let n=jk(e);return n.type!==`binary`&&t.some(t=>Mk(t,n,e.filename))?[]:[n]}return[e]});return{...e,content:n}}var Pk=`THINKING_START`,Fk=`THINKING_END`,Ik=`THINKING_TEXT_MESSAGE_START`,Lk=`THINKING_TEXT_MESSAGE_CONTENT`,Rk=`THINKING_TEXT_MESSAGE_END`;function zk(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Bk={event:[`rawEvent`,`subagentRunId`],[L.RUN_STARTED]:[`parentRunId`,`input`],[L.RUN_FINISHED]:[`result`,`outcome`],[L.RUN_ERROR]:[`usage`],[L.SUBAGENT_FINISHED]:[`result`],[L.TOOL_CALL_START]:[`parentMessageId`],[L.TOOL_CALL_CHUNK]:[`parentMessageId`],[L.TOOL_CALL_RESULT]:[`role`],"RUN_FINISHED.outcome":[`pendingToolCallIds`],"RUN_FINISHED.usage[]":[`provider`,`reasoningTokens`,`cachedInputTokens`,`cacheWriteInputTokens`],RunAgentInput:[`forwardedProps`],Tool:[`parameters`],ResumeEntry:[`payload`],"input content":[`metadata`]},Vk=new Map(Object.entries(Bk).filter(([e])=>Object.values(L).includes(e))),Hk=e=>RO(e,`an absent field`);function Uk(e,t,n,r){if(!zk(e))return e;let i;for(let a of t)e[a]===null&&(r(n===void 0?`${a}: null`:`${n}.${a}: null`),i??={...e},delete i[a]);return i??e}function Wk(e,t,n){if(!zk(e)||!Array.isArray(e[t]))return e;let r=e[t],i=r.map(n);return i.some((e,t)=>e!==r[t])?{...e,[t]:i}:e}function Gk(e,t){return Wk(e,`content`,e=>{if(!zk(e))return e;switch(e.type){case`image`:case`audio`:case`video`:case`document`:return Uk(e,Bk[`input content`],`${e.type} input content`,t);default:return e}})}function Kk(e,t=Hk){let n=Uk(e,Bk.RunAgentInput,`RunAgentInput`,t);return n=Wk(n,`tools`,e=>Uk(e,Bk.Tool,`Tool`,t)),n=Wk(n,`resume`,e=>Uk(e,Bk.ResumeEntry,`ResumeEntry`,t)),Wk(n,`messages`,e=>Gk(e,t))}var qk=class extends Dk{constructor(...e){super(...e),this.currentReasoningId=null,this.currentMessageId=null,this.nullsNoticedThisRun=new Set,this.noticeNullOncePerRun=e=>{this.nullsNoticedThisRun.has(e)||(this.nullsNoticedThisRun.add(e),RO(e,`an absent field`))}}warn(e,t){RO(e,t)}mintedContinuationId(e,t){if(t!==null)return t;let n=TO();return this.warnAside(`Minting a messageId ('${n}') for ${e}: no THINKING opener preceded it, so there was no id to continue. The id is this client's invention, not the producer's, and verification will reject the translated event for naming something nothing opened.`),n}warnAside(e){typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`[ag-ui][compat] ${e} Set SUPPRESS_TRANSFORMATION_WARNINGS=true to silence.`)}run(e,t){return this.currentReasoningId=null,this.currentMessageId=null,this.nullsNoticedThisRun.clear(),e.messages=e.messages.map(Nk),t.run(e).pipe(yd(e=>this.transformEvent(e)))}transformEvent(e){let t=this.noticeNullOncePerRun;e.type===L.RUN_STARTED&&this.nullsNoticedThisRun.clear(),e=Uk(e,Bk.event,void 0,t);let n=Vk.get(e.type);switch(n&&(e=Uk(e,n,e.type,t)),e.type){case Pk:{this.currentReasoningId=TO();let{title:t,...n}=e;return this.warn(Pk,L.REASONING_START),t!==void 0&&this.warnAside(`Dropping ${Pk}.title ${JSON.stringify(t)}: ${L.REASONING_START} has no title field, so the span's label cannot be carried and nothing downstream can recover it.`),{...n,type:L.REASONING_START,messageId:this.currentReasoningId}}case Ik:return this.currentMessageId=TO(),this.warn(Ik,L.REASONING_MESSAGE_START),{...e,type:L.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:`reasoning`};case Lk:{let{delta:t,...n}=e;return this.warn(Lk,L.REASONING_MESSAGE_CONTENT),{...n,type:L.REASONING_MESSAGE_CONTENT,messageId:this.mintedContinuationId(Lk,this.currentMessageId),delta:t}}case Rk:{let t=this.mintedContinuationId(Rk,this.currentMessageId);return this.currentMessageId=null,this.warn(Rk,L.REASONING_MESSAGE_END),{...e,type:L.REASONING_MESSAGE_END,messageId:t}}case Fk:{let t=this.mintedContinuationId(Fk,this.currentReasoningId);return this.currentReasoningId=null,this.warn(Fk,L.REASONING_END),{...e,type:L.REASONING_END,messageId:t}}case L.RUN_FINISHED:{let n=e,r=Uk(n.outcome,Bk[`RUN_FINISHED.outcome`],`RUN_FINISHED.outcome`,t);return Wk(r===n.outcome?n:{...n,outcome:r},`usage`,e=>Uk(e,Bk[`RUN_FINISHED.usage[]`],`RUN_FINISHED.usage[]`,t))}case L.MESSAGES_SNAPSHOT:{let t=e;return Array.isArray(t.messages)?{...t,messages:t.messages.map(e=>this.upgradeInboundMessage(e))}:e}case L.RUN_STARTED:{let n=Kk(e.input,t),r=n===e.input?e:{...e,input:n},i=r;return!i.input||!Array.isArray(i.input.messages)?r:{...i,input:{...i.input,messages:i.input.messages.map(e=>this.upgradeInboundMessage(e))}}}default:return e}}upgradeInboundMessage(e){e=Gk(e,this.noticeNullOncePerRun);let t=e.content;return!Array.isArray(t)||!t.some(e=>typeof e==`object`&&!!e&&e.type===`binary`)?e:(this.warn(`binary input content`,`the modern media content parts`),Nk(e))}},Jk=()=>e=>wd(()=>{let t=new qk;return e.pipe(yd(e=>t.transformEvent(e)))});function Yk(e,t=new Date){return e.expiresAt!==void 0&&new Date(e.expiresAt)<=t}function Xk(){return typeof process<`u`&&!!{}.SUPPRESS_TRANSFORMATION_WARNINGS}function Zk(e){Xk()||console.warn(`[ag-ui][compat] Flattening message content for a <=0.0.39 peer DROPS non-text parts (${e.join(`, `)}). The peer cannot receive them; upgrade it to keep media content. See the repo-root DEPRECATIONS.md.`)}function Qk(e){Xk()||console.warn(`[ag-ui][compat] Not flattening message content for a <=0.0.39 peer: ${e} content part(s) claim type "text" but carry a malformed 'text' value. That is a defect in the message, not media the peer cannot represent, and a downgrade must not repair it — the content is passed on unchanged so the outgoing enforcement boundary reports it. See the repo-root DEPRECATIONS.md.`)}function $k(e){let t=e.content;if(Array.isArray(t)){let n=e=>typeof e==`object`&&!!e&&`type`in e&&e.type===`text`,r=e=>n(e)&&typeof e.text==`string`,i=t.filter(e=>n(e)&&!r(e));if(i.length>0)return Qk(i.length),e;let a=t.filter(e=>!r(e)).map(e=>typeof e==`object`&&e&&`type`in e?String(e.type):typeof e);a.length>0&&Zk(a);let o=t.filter(r).map(e=>e.text).join(``);return{...e,content:o}}return typeof t==`string`?e:t===void 0?{...e,content:``}:e}var eA=class extends Dk{run(e,t){let{parentRunId:n,...r}=e,i={...r,messages:r.messages.map($k)};return this.runNext(i,t)}},tA=`THINKING_START`,nA=`THINKING_END`,rA=`THINKING_TEXT_MESSAGE_START`,iA=`THINKING_TEXT_MESSAGE_CONTENT`,aA=`THINKING_TEXT_MESSAGE_END`,oA=class extends Dk{constructor(...e){super(...e),this.currentReasoningId=null,this.currentMessageId=null}warnAboutTransformation(e,t){typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is converting ${e} to ${t}. To remove this warning, upgrade your AG-UI integration package (e.g. @ag-ui/langgraph). To surpress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){return this.currentReasoningId=null,this.currentMessageId=null,this.runNext(e,t).pipe(yd(e=>this.transformEvent(e)))}transformEvent(e){switch(e.type){case tA:{this.currentReasoningId=TO();let{title:t,...n}=e;return this.warnAboutTransformation(tA,L.REASONING_START),{...n,type:L.REASONING_START,messageId:this.currentReasoningId}}case rA:return this.currentMessageId=TO(),this.warnAboutTransformation(rA,L.REASONING_MESSAGE_START),{...e,type:L.REASONING_MESSAGE_START,messageId:this.currentMessageId,role:`reasoning`};case iA:{let{delta:t,...n}=e;return this.warnAboutTransformation(iA,L.REASONING_MESSAGE_CONTENT),{...n,type:L.REASONING_MESSAGE_CONTENT,messageId:this.currentMessageId??TO(),delta:t}}case aA:{let t=this.currentMessageId??TO();return this.warnAboutTransformation(aA,L.REASONING_MESSAGE_END),{...e,type:L.REASONING_MESSAGE_END,messageId:t}}case nA:{let t=this.currentReasoningId??TO();return this.warnAboutTransformation(nA,L.REASONING_END),{...e,type:L.REASONING_END,messageId:t}}default:return e}}},sA=`SUBAGENT_STARTED`,cA=`SUBAGENT_FINISHED`,lA=`SUBAGENT_ERROR`;function uA(e){if(e&&typeof e==`object`&&`subagentRunId`in e){let{subagentRunId:t,...n}=e;return n}return e}function dA(e){return e.map(e=>uA(e))}var fA=class extends Dk{warnDroppedLifecycleEvent(e){typeof process<`u`&&{}.SUPPRESS_TRANSFORMATION_WARNINGS||console.warn(`AG-UI is dropping ${e} because the target agent predates subagent support. To remove this warning, upgrade your AG-UI integration package. To suppress it, set SUPPRESS_TRANSFORMATION_WARNINGS=true in your .env file.`)}run(e,t){let n={...e,messages:(e.messages??[]).map(e=>uA(e))};return this.runNext(n,t).pipe(Pd(e=>{let t=e.type;(t===sA||t===cA||t===lA)&&this.warnDroppedLifecycleEvent(t)}),Td(e=>{let t=e.type;return t!==sA&&t!==cA&&t!==lA}),yd(e=>{let t=uA(e);if(t.type===L.MESSAGES_SNAPSHOT){let e=t;if(Array.isArray(e.messages))return{...e,messages:dA(e.messages)}}if(t.type===L.RUN_FINISHED){let e=t;if(e.outcome&&Array.isArray(e.outcome.interrupts))return{...e,outcome:{...e.outcome,interrupts:e.outcome.interrupts.map(e=>uA(e))}}}if(t.type===L.RUN_STARTED){let e=t;if(e.input&&Array.isArray(e.input.messages))return{...e,input:{...e.input,messages:dA(e.input.messages)}}}return t}))}},pA=`1.0.2`,mA=!1,hA=new WeakSet,gA=(e,t)=>/^\d+\.\d+$/.test(e)?WT(e,t)>0?`newer`:`not-newer`:`uninterpretable`,_A=e=>{let t=e.protocolVersion;if(t!==void 0&&t!==`1.0`)switch(gA(t,`1.0`)){case`uninterpretable`:console.warn(`[ag-ui] The producer declared protocol version '${t}', which this client cannot interpret.`);return;case`newer`:console.warn(`[ag-ui] The producer speaks protocol ${t}; this client speaks 1.0. Unrecognised material will be stripped with warnings.`);return;case`not-newer`:return}},vA=class e{resolvePeerCeiling(t){if(this.resolvingPeerCeiling)return pA;let n=Object.getOwnPropertyDescriptor(this,`maxVersion`),r=Object.getOwnPropertyDescriptor(this,`maxProtocolVersion`),i=Object.getPrototypeOf(this);for(;i&&i!==e.prototype;)n??=Object.getOwnPropertyDescriptor(i,`maxVersion`),r??=Object.getOwnPropertyDescriptor(i,`maxProtocolVersion`),i=Object.getPrototypeOf(i);if(t===`maxVersion`&&n)return pA;let a=t===`maxProtocolVersion`?n:r;if(!a)return pA;this.resolvingPeerCeiling=!0;try{return a.get?a.get.call(this):a.value}finally{this.resolvingPeerCeiling=!1}}get maxProtocolVersion(){return this.resolvePeerCeiling(`maxProtocolVersion`)}get maxVersion(){return!this.resolvingPeerCeiling&&!mA&&(mA=!0,console.warn(`[ag-ui] AbstractAgent.maxVersion is deprecated — use maxProtocolVersion. Same value; the new name says whose version it is and that it is a ceiling.`)),this.resolvePeerCeiling(`maxVersion`)}get debug(){return this._debug}set debug(e){this._debug=jO(e),this._debugLogger=PO(this._debug)}get debugLogger(){return this._debugLogger}set debugLogger(e){this._debugLogger=typeof e==`boolean`?e?PO(jO(!0)):void 0:e}resolvedCeilingDuringConstruction(){let e=this.maxProtocolVersion;if(typeof e!=`string`||!GT(e))throw new R(`maxProtocolVersion resolved to ${JSON.stringify(e)} during construction, which is not a version this client can compare. A ceiling read from an instance field is not available yet — return a literal from the getter.`);return e}constructor({agentId:e,description:t,threadId:n,initialMessages:r,initialState:i,debug:a}={}){this.subscribers=[],this.isRunning=!1,this.pendingInterrupts=[],this.middlewares=[],this.resolvingPeerCeiling=!1,this.agentId=e,this.description=t??``,this.threadId=n??Gc(),this.messages=wO(r??[]),this.state=wO(i??{}),this._debug=jO(a),this._debugLogger=PO(this._debug);let o=this.resolvedCeilingDuringConstruction();WT(o,`0.0.39`)<=0&&this.middlewares.unshift(new eA),WT(o,`0.0.45`)<=0&&this.middlewares.unshift(new oA),WT(o,`0.0.57`)<=0&&this.middlewares.unshift(new fA)}subscribe(e){return this.subscribers.push(e),{unsubscribe:()=>{this.subscribers=this.subscribers.filter(t=>t!==e)}}}use(...e){let t=e.map(e=>typeof e==`function`?new Ok(e):e);return this.middlewares.push(...t),this}async runAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??Gc();let n=this.prepareRunAgentInput(e);this.debugLogger?.lifecycle(`LIFECYCLE`,`Run started:`,{agentId:this.agentId,threadId:this.threadId});let r,i=new Set(this.messages.map(e=>e.id)),a=[{onRunStartedEvent:({event:e})=>_A(e),onRunFinishedEvent:e=>{e.outcome===`success`&&(r=e.result)}},...this.subscribers,t??{}];hA.add(n),await this.onInitialize(n,a),this.activeRunDetach$=new Nu;let o;this.activeRunCompletionPromise=new Promise(e=>{o=e}),await vd(Su(()=>[...this.middlewares,new qk].reduceRight((e,t)=>({run:n=>t.run(n,e),get messages(){return e.messages},get state(){return e.state}}),this).run(n),Tk(this.debugLogger),fk(this.debugLogger),zO(this.debugLogger),e=>e.pipe(Nd(this.activeRunDetach$)),e=>this.applyBeforeSourceError(n,e,a),Ed(e=>(this.debugLogger?.lifecycle(`LIFECYCLE`,`Run errored:`,{agentId:this.agentId,error:e instanceof Error?e.message:String(e)}),this.isRunning=!1,this.onError(n,e,a))),jd(()=>{this.debugLogger?.lifecycle(`LIFECYCLE`,`Run finished:`,{agentId:this.agentId,threadId:this.threadId}),this.isRunning=!1,this.onFinalize(n,a),o?.(),o=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(gd(null)));let s=wO(this.messages).filter(e=>!i.has(e.id));return{result:r,newMessages:s}}finally{this.isRunning=!1}}connect(e){throw new Xc}async connectAgent(e,t){try{this.isRunning=!0,this.agentId=this.agentId??Gc();let n=this.prepareRunAgentInput(e),r,i=new Set(this.messages.map(e=>e.id)),a=[{onRunStartedEvent:({event:e})=>_A(e),onRunFinishedEvent:e=>{e.outcome===`success`&&(r=e.result)}},...this.subscribers,t??{}];await this.onInitialize(n,a),this.activeRunDetach$=new Nu;let o;this.activeRunCompletionPromise=new Promise(e=>{o=e}),await vd(Su(()=>wd(()=>this.connect(n)),e=>Tk(this.debugLogger)(Jk()(e)),fk(this.debugLogger),zO(this.debugLogger),e=>e.pipe(Nd(this.activeRunDetach$)),e=>this.applyBeforeSourceError(n,e,a),Ed(e=>(this.isRunning=!1,e instanceof Xc?Lu:this.onError(n,e,a))),jd(()=>{this.isRunning=!1,this.onFinalize(n,a),o?.(),o=void 0,this.activeRunCompletionPromise=void 0,this.activeRunDetach$=void 0}))(gd(null)),{defaultValue:void 0});let s=wO(this.messages).filter(e=>!i.has(e.id));return{result:r,newMessages:s}}finally{this.isRunning=!1}}abortRun(){}async detachActiveRun(){if(!this.activeRunDetach$)return;let e=this.activeRunCompletionPromise??Promise.resolve();this.activeRunDetach$.next(),this.activeRunDetach$?.complete(),await e}applyBeforeSourceError(e,t,n){return wd(()=>{let r,i=t.pipe(Ed(e=>(r={error:e},Lu)));return this.processApplyEvents(e,this.apply(e,i,n),n).pipe(kd(wd(()=>{let e=r;return e?z(()=>e.error):Lu})))})}apply(e,t,n){return LO(e,t,this,n,this.debugLogger)}processApplyEvents(e,t,n){return t.pipe(Pd(t=>{t.messages&&(this.messages=t.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),t.state!==void 0&&(this.state=t.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}))}prepareRunAgentInput(e){let t=wO(this.messages);for(let e of t)e.subagentRunId===null&&delete e.subagentRunId;let n=t.filter(e=>e.role!==`activity`);return{threadId:this.threadId,runId:e?.runId||Gc(),...WT(this.maxProtocolVersion,pA)>=0&&{protocolVersion:`1.0`},tools:wO(e?.tools??[]),context:wO(e?.context??[]),forwardedProps:wO(e?.forwardedProps??{}),state:wO(this.state),messages:n,...e?.resume===void 0?{}:{resume:wO(e.resume)}}}async onInitialize(e,t){if(hA.has(e)&&this.pendingInterrupts.length>0){let t=new Set((e.resume??[]).map(e=>e.interruptId)),n=this.pendingInterrupts.map(e=>e.id).filter(e=>!t.has(e));if(n.length>0)throw new R(`Thread has ${n.length} pending interrupt(s) not addressed by resume: ${n.join(`, `)}`);for(let t of this.pendingInterrupts)if(Yk(t)&&(e.resume??[]).find(e=>e.interruptId===t.id)?.status!==`cancelled`)throw new R(`Interrupt ${t.id} expired at ${t.expiresAt} and can no longer be answered. Cancel it to continue the thread.`)}let n=await AO(t,this.messages,this.state,(t,n,r)=>t.onRunInitialized?.({messages:n,state:r,agent:this,input:e}));if(n.messages!==void 0||n.state!==void 0){if(n.messages){this.messages=n.messages;for(let e of n.messages)e.subagentRunId===null&&delete e.subagentRunId;e.messages=n.messages.filter(e=>e.role!==`activity`),t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})}n.state!==void 0&&(this.state=n.state,e.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))}}onError(e,t,n){return hd(AO(n,this.messages,this.state,(n,r,i)=>n.onRunFailed?.({error:t,messages:r,state:i,agent:this,input:e}))).pipe(yd(r=>{let i=r;if((i.messages!==void 0||i.state!==void 0)&&(i.messages!==void 0&&(this.messages=i.messages,n.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),i.state!==void 0&&(this.state=i.state,n.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})}))),i.stopPropagation!==!0){let e=String(t);if(t.name!==`AbortError`&&t.message!==`Fetch is aborted`&&t.message!==`signal is aborted without reason`&&t.message!==`component unmounted`&&e!==`component unmounted`)throw console.error(`Agent execution failed:`,t),t}return{}}))}async onFinalize(e,t){let n=await AO(t,this.messages,this.state,(t,n,r)=>t.onRunFinalized?.({messages:n,state:r,agent:this,input:e}));(n.messages!==void 0||n.state!==void 0)&&(n.messages!==void 0&&(this.messages=n.messages,t.forEach(t=>{t.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this,input:e})})),n.state!==void 0&&(this.state=n.state,t.forEach(t=>{t.onStateChanged?.({state:this.state,messages:this.messages,agent:this,input:e})})))}clone(){let e=Object.create(Object.getPrototypeOf(this));return e.agentId=this.agentId,e.description=this.description,e.threadId=this.threadId,e.messages=wO(this.messages),e.state=wO(this.state),e._debug=this._debug,e._debugLogger=this._debugLogger,e.isRunning=this.isRunning,e.subscribers=[...this.subscribers],e.middlewares=[...this.middlewares],e.pendingInterrupts=wO(this.pendingInterrupts),e}addMessage(e){this.messages.push(e),(async()=>{for(let t of this.subscribers)await t.onNewMessage?.({message:e,messages:this.messages,state:this.state,agent:this});if(e.role===`assistant`&&e.toolCalls)for(let t of e.toolCalls)for(let e of this.subscribers)await e.onNewToolCall?.({toolCall:t,messages:this.messages,state:this.state,agent:this});for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}addMessages(e){this.messages.push(...e),(async()=>{for(let t of e){for(let e of this.subscribers)await e.onNewMessage?.({message:t,messages:this.messages,state:this.state,agent:this});if(t.role===`assistant`&&t.toolCalls)for(let e of t.toolCalls)for(let t of this.subscribers)await t.onNewToolCall?.({toolCall:e,messages:this.messages,state:this.state,agent:this})}for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setMessages(e){this.messages=wO(e),(async()=>{for(let e of this.subscribers)await e.onMessagesChanged?.({messages:this.messages,state:this.state,agent:this})})()}setState(e){this.state=wO(e),(async()=>{for(let e of this.subscribers)await e.onStateChanged?.({messages:this.messages,state:this.state,agent:this})})()}legacy_to_be_removed_runAgentBridged(e){this.agentId=this.agentId??Gc();let t=this.prepareRunAgentInput(e);return[...this.middlewares,new qk].reduceRight((e,t)=>({run:n=>t.run(n,e),get messages(){return e.messages},get state(){return e.state}}),this).run(t).pipe(Tk(this.debugLogger),fk(this.debugLogger),zO(this.debugLogger),QO(this.threadId,t.runId,this.agentId),e=>e.pipe(yd(e=>(this.debugLogger?.event(`LEGACY`,`Event:`,e,{type:e.type}),e))))}};function yA(e){if(!Array.isArray(e.messages))return e;let t=!1,n=e.messages.map(e=>{if(e.subagentRunId===null){t=!0;let n={...e};return delete n.subagentRunId,n}return e});return t?{...e,messages:n}:e}var bA=class extends vA{requestInit(e){return{method:`POST`,headers:{...this.headers,"Content-Type":`application/json`,Accept:`text/event-stream`},body:JSON.stringify(yA(e)),signal:this.abortController.signal}}runAgent(e,t){return this.abortController=e?.abortController??new AbortController,super.runAgent(e,t)}abortRun(){this.abortController.abort(),super.abortRun()}constructor(e){super(e),this.abortController=new AbortController,this.url=e.url,this.headers=wO(e.headers??{}),this.fetch=e.fetch??((e,t)=>fetch(e,t))}run(e){return qO(VO(()=>this.fetch(this.url,this.requestInit(Ek(e)))),this.debugLogger)}clone(){let e=super.clone();e.url=this.url,e.headers=wO(this.headers??{}),e.fetch=this.fetch;let t=new AbortController,n=this.abortController.signal;return n.aborted&&t.abort(n.reason),e.abortController=t,e}},xA=M.createContext(void 0),SA=e=>{let t=M.useContext(xA);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},CA=({client:e,children:t})=>(M.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,N.jsx)(xA.Provider,{value:e,children:t})),wA={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},TA=new class{#e=wA;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 EA(e){setTimeout(e,0)}var DA=typeof window>`u`||`Deno`in globalThis;function OA(){}function kA(e,t){return typeof e==`function`?e(t):e}function AA(e){return typeof e==`number`&&e>=0&&e!==1/0}function jA(e,t){return Math.max(e+(t||0)-Date.now(),0)}function MA(e,t){return typeof e==`function`?e(t):e}function NA(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==FA(o,t.options))return!1}else if(!LA(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 PA(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(IA(t.options.mutationKey)!==IA(a))return!1}else if(!LA(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function FA(e,t){return(t?.queryKeyHashFn||IA)(e)}function IA(e){return JSON.stringify(e,(e,t)=>HA(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function LA(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)){if(t.length>e.length)return!1;for(let n=0;n500)return t;let r=VA(e)&&VA(t);if(!r&&!(HA(e)&&HA(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{TA.setTimeout(t,e)})}function GA(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:zA(e,t)}function KA(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function qA(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var JA=Symbol();function YA(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===JA?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function XA(e,t){return typeof e==`function`?e(...t):!!e}function ZA(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 QA=()=>DA,$A=()=>QA(),ej=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(){}},tj=new class extends ej{#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`}},nj=EA;function rj(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=nj,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 ij=rj(),aj=new class extends ej{#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 oj(e){return Math.min(1e3*2**e,3e4)}function sj(e){return(e??`online`)!==`online`||aj.isOnline()}var cj=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function lj(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(OA);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new cj(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>tj.isFocused()&&(e.networkMode===`always`||aj.isOnline())&&e.canRun(),p=()=>sj(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=t=>new Promise(n=>{r=e=>{(c()||t())&&n(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())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(m).catch(r=>{if(c())return;let i=e.retry??($A()?0:3),a=e.retryDelay??oj,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&nf()?void 0:g(f)).then(()=>{t?h(r):_()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g(p).then(_),s)}}var uj=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),AA(this.gcTime)&&(this.#e=TA.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??($A()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(TA.clearTimeout(this.#e),this.#e=void 0)}};function dj(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=>{ZA(e,()=>t.signal,()=>n=!0)},u=YA(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?qA:KA;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?pj:fj,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:fj(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 fj(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 pj(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function mj(e,t){return t?fj(e,t)!=null:!1}function hj(e,t){return!t||!e.getPreviousPageParam?!1:pj(e,t)!=null}var gj=class extends uj{#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=yj(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=yj(this.options);e.data!==void 0&&(this.setState(vj(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=GA(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(OA).catch(OA):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=>MA(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===JA||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>MA(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:!jA(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){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({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=YA(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`?dj(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=lj({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof cj&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.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 cj){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(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,..._j(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...vj(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),ij.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function _j(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:sj(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function vj(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function yj(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 bj=class extends ej{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Sj(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Cj(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Cj(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 MA(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&&!BA(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&wj(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||MA(this.options.enabled,this.#t)!==MA(t.enabled,this.#t)||MA(this.options.staleTime,this.#t)!==MA(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||MA(this.options.enabled,this.#t)!==MA(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return BA(this.getCurrentResult(),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),Reflect.get(e,n))})}trackProp(e){this.#p.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),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(OA)),t}#h(e){return!$A()&&MA(this.options.enabled,this.#t)!==!1&&AA(e)}#g(){this.#b();let e=MA(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=jA(this.#r.dataUpdatedAt,e)+1;this.#u=TA.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return MA(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=TA.setInterval(()=>{(this.options.refetchIntervalInBackground||tj.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(TA.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(TA.clearInterval(this.#d),this.#d=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&&Sj(e,t),o=i&&wj(e,n,t,r);(a||o)&&(l={...l,..._j(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.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=GA(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=GA(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{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&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:Tj(e,t),refetch:this.refetch,isEnabled:MA(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),BA(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);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)})})();ij.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#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()}};function xj(e,t){return MA(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||MA(t.retryOnMount,e)!==!1)}function Sj(e,t){return xj(e,t)||e.state.data!==void 0&&Cj(e,t,t.refetchOnMount)}function Cj(e,t,n){if(MA(t.enabled,e)!==!1&&MA(t.staleTime,e)!==`static`){let r=MA(n,e);return r===`always`||r!==!1&&Tj(e,t)}return!1}function wj(e,t,n,r){return(e!==t||MA(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Tj(e,n)}function Tj(e,t){return MA(t.enabled,e)!==!1&&e.isStaleByTime(MA(t.staleTime,e))}var Ej=class extends bj{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:mj(t,n.data),hasPreviousPage:hj(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}},Dj=class extends uj{#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||Oj(),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.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=lj({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)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),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:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}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.#r===r&&(this.#r=void 0),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),ij.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Oj(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var kj=class extends ej{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new Dj({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=Aj(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=Aj(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=Aj(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=Aj(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){ij.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=>PA(t,e))}findAll(e={}){return this.getAll().filter(t=>PA(e,t))}notify(e){ij.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return ij.batch(()=>Promise.all(e.map(e=>e.continue().catch(OA))))}};function Aj(e){return e.options.scope?.id}var jj=class extends ej{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??FA(r,t),a=this.get(i);return a||(a=new gj({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){this.#e.get(e.queryHash)===e&&(e.destroy(),this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){ij.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=>NA(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>NA(e,t)):t}notify(e){ij.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){ij.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){ij.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},Mj=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new jj,this.#t=e.mutationCache||new kj,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=tj.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=aj.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(MA(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=kA(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return ij.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;ij.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return ij.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=ij.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(OA).catch(OA)}invalidateQueries(e,t={}){return ij.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=ij.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(OA)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(OA)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(MA(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(MA(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(OA).catch(OA)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(OA).catch(OA)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return aj.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(IA(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{LA(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(IA(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{LA(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||=FA(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===JA&&(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()}},Nj=M.createContext(!1),Pj=()=>M.useContext(Nj);Nj.Provider;function Fj(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Ij=M.createContext(Fj()),Lj=()=>M.useContext(Ij),Rj=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?XA(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},zj=e=>{M.useEffect(()=>{e.clearReset()},[e])},Bj=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||XA(n,[e.error,r])),Vj=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))}},Hj=(e,t)=>e?.suspense&&t.isPending,Uj=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function Wj(e,t,n){let r=Pj(),i=Lj(),a=SA(n),o=a.defaultQueryOptions(e),s=a.getQueryCache().get(o.queryHash),c=e.subscribed!==!1;o._optimisticResults=r?`isRestoring`:c?`optimistic`:void 0,Vj(o),Rj(o,i,s),zj(i);let[l]=M.useState(()=>new t(a,o)),u=l.getOptimisticResult(o),d=!r&&c;if(M.useSyncExternalStore(M.useCallback(e=>{let t=d?l.subscribe(ij.batchCalls(e)):OA;return l.updateResult(),t},[l,d]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),M.useEffect(()=>{l.setOptions(o)},[o,l]),Hj(o,u))throw Uj(o,l,i);if(Bj({result:u,errorResetBoundary:i,throwOnError:o.throwOnError,query:s,suspense:o.suspense}))throw u.error;return o.notifyOnChangeProps?u:l.trackResult(u)}function Gj(e,t){return Wj(e,bj,t)}function Kj(e,t){return Wj(e,Ej,t)}var qj=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M228,128a12,12,0,0,1-12,12H69l51.52,51.51a12,12,0,0,1-17,17l-72-72a12,12,0,0,1,0-17l72-72a12,12,0,0,1,17,17L69,116H216A12,12,0,0,1,228,128Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M112,56V200L40,128Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M216,120H120V56a8,8,0,0,0-13.66-5.66l-72,72a8,8,0,0,0,0,11.32l72,72A8,8,0,0,0,120,200V136h96a8,8,0,0,0,0-16ZM104,180.69,51.31,128,104,75.31Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224,128a8,8,0,0,1-8,8H120v64a8,8,0,0,1-13.66,5.66l-72-72a8,8,0,0,1,0-11.32l72-72A8,8,0,0,1,120,56v64h96A8,8,0,0,1,224,128Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M222,128a6,6,0,0,1-6,6H54.49l61.75,61.76a6,6,0,1,1-8.48,8.48l-72-72a6,6,0,0,1,0-8.48l72-72a6,6,0,0,1,8.48,8.48L54.49,122H216A6,6,0,0,1,222,128Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224,128a8,8,0,0,1-8,8H59.31l58.35,58.34a8,8,0,0,1-11.32,11.32l-72-72a8,8,0,0,1,0-11.32l72-72a8,8,0,0,1,11.32,11.32L59.31,120H216A8,8,0,0,1,224,128Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M220,128a4,4,0,0,1-4,4H49.66l65.17,65.17a4,4,0,0,1-5.66,5.66l-72-72a4,4,0,0,1,0-5.66l72-72a4,4,0,0,1,5.66,5.66L49.66,124H216A4,4,0,0,1,220,128Z`}))]]),Jj=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224.49,136.49l-72,72a12,12,0,0,1-17-17L187,140H40a12,12,0,0,1,0-24H187L135.51,64.48a12,12,0,0,1,17-17l72,72A12,12,0,0,1,224.49,136.49Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,128l-72,72V56Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M221.66,122.34l-72-72A8,8,0,0,0,136,56v64H40a8,8,0,0,0,0,16h96v64a8,8,0,0,0,13.66,5.66l72-72A8,8,0,0,0,221.66,122.34ZM152,180.69V75.31L204.69,128Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M221.66,133.66l-72,72A8,8,0,0,1,136,200V136H40a8,8,0,0,1,0-16h96V56a8,8,0,0,1,13.66-5.66l72,72A8,8,0,0,1,221.66,133.66Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M220.24,132.24l-72,72a6,6,0,0,1-8.48-8.48L201.51,134H40a6,6,0,0,1,0-12H201.51L139.76,60.24a6,6,0,0,1,8.48-8.48l72,72A6,6,0,0,1,220.24,132.24Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M221.66,133.66l-72,72a8,8,0,0,1-11.32-11.32L196.69,136H40a8,8,0,0,1,0-16H196.69L138.34,61.66a8,8,0,0,1,11.32-11.32l72,72A8,8,0,0,1,221.66,133.66Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M218.83,130.83l-72,72a4,4,0,0,1-5.66-5.66L206.34,132H40a4,4,0,0,1,0-8H206.34L141.17,58.83a4,4,0,0,1,5.66-5.66l72,72A4,4,0,0,1,218.83,130.83Z`}))]]),Yj=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232,44H160a43.86,43.86,0,0,0-32,13.85A43.86,43.86,0,0,0,96,44H24A12,12,0,0,0,12,56V200a12,12,0,0,0,12,12H96a20,20,0,0,1,20,20,12,12,0,0,0,24,0,20,20,0,0,1,20-20h72a12,12,0,0,0,12-12V56A12,12,0,0,0,232,44ZM96,188H36V68H96a20,20,0,0,1,20,20V192.81A43.79,43.79,0,0,0,96,188Zm124,0H160a43.71,43.71,0,0,0-20,4.83V88a20,20,0,0,1,20-20h60Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232,56V200H160a32,32,0,0,0-32,32,32,32,0,0,0-32-32H24V56H96a32,32,0,0,1,32,32,32,32,0,0,1,32-32Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M232,48H160a40,40,0,0,0-32,16A40,40,0,0,0,96,48H24a8,8,0,0,0-8,8V200a8,8,0,0,0,8,8H96a24,24,0,0,1,24,24,8,8,0,0,0,16,0,24,24,0,0,1,24-24h72a8,8,0,0,0,8-8V56A8,8,0,0,0,232,48ZM96,192H32V64H96a24,24,0,0,1,24,24V200A39.81,39.81,0,0,0,96,192Zm128,0H160a39.81,39.81,0,0,0-24,8V88a24,24,0,0,1,24-24h64Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M240,56V200a8,8,0,0,1-8,8H160a24,24,0,0,0-24,23.94,7.9,7.9,0,0,1-5.12,7.55A8,8,0,0,1,120,232a24,24,0,0,0-24-24H24a8,8,0,0,1-8-8V56a8,8,0,0,1,8-8H88a32,32,0,0,1,32,32v87.73a8.17,8.17,0,0,0,7.47,8.25,8,8,0,0,0,8.53-8V80a32,32,0,0,1,32-32h64A8,8,0,0,1,240,56Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232,50H160a38,38,0,0,0-32,17.55A38,38,0,0,0,96,50H24a6,6,0,0,0-6,6V200a6,6,0,0,0,6,6H96a26,26,0,0,1,26,26,6,6,0,0,0,12,0,26,26,0,0,1,26-26h72a6,6,0,0,0,6-6V56A6,6,0,0,0,232,50ZM96,194H30V62H96a26,26,0,0,1,26,26V204.31A37.86,37.86,0,0,0,96,194Zm130,0H160a37.87,37.87,0,0,0-26,10.32V88a26,26,0,0,1,26-26h66Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232,48H160a40,40,0,0,0-32,16A40,40,0,0,0,96,48H24a8,8,0,0,0-8,8V200a8,8,0,0,0,8,8H96a24,24,0,0,1,24,24,8,8,0,0,0,16,0,24,24,0,0,1,24-24h72a8,8,0,0,0,8-8V56A8,8,0,0,0,232,48ZM96,192H32V64H96a24,24,0,0,1,24,24V200A39.81,39.81,0,0,0,96,192Zm128,0H160a39.81,39.81,0,0,0-24,8V88a24,24,0,0,1,24-24h64Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232,52H160a36,36,0,0,0-32,19.54A36,36,0,0,0,96,52H24a4,4,0,0,0-4,4V200a4,4,0,0,0,4,4H96a28,28,0,0,1,28,28,4,4,0,0,0,8,0,28,28,0,0,1,28-28h72a4,4,0,0,0,4-4V56A4,4,0,0,0,232,52ZM96,196H28V60H96a28,28,0,0,1,28,28V209.4A35.93,35.93,0,0,0,96,196Zm132,0H160a35.94,35.94,0,0,0-28,13.41V88a28,28,0,0,1,28-28h68Z`}))]]),Xj=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M144,128a16,16,0,1,1-16-16A16,16,0,0,1,144,128ZM60,112a16,16,0,1,0,16,16A16,16,0,0,0,60,112Zm136,0a16,16,0,1,0,16,16A16,16,0,0,0,196,112Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M240,96v64a16,16,0,0,1-16,16H32a16,16,0,0,1-16-16V96A16,16,0,0,1,32,80H224A16,16,0,0,1,240,96Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M140,128a12,12,0,1,1-12-12A12,12,0,0,1,140,128Zm56-12a12,12,0,1,0,12,12A12,12,0,0,0,196,116ZM60,116a12,12,0,1,0,12,12A12,12,0,0,0,60,116Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224,80H32A16,16,0,0,0,16,96v64a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V96A16,16,0,0,0,224,80ZM60,140a12,12,0,1,1,12-12A12,12,0,0,1,60,140Zm68,0a12,12,0,1,1,12-12A12,12,0,0,1,128,140Zm68,0a12,12,0,1,1,12-12A12,12,0,0,1,196,140Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M138,128a10,10,0,1,1-10-10A10,10,0,0,1,138,128ZM60,118a10,10,0,1,0,10,10A10,10,0,0,0,60,118Zm136,0a10,10,0,1,0,10,10A10,10,0,0,0,196,118Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M140,128a12,12,0,1,1-12-12A12,12,0,0,1,140,128Zm56-12a12,12,0,1,0,12,12A12,12,0,0,0,196,116ZM60,116a12,12,0,1,0,12,12A12,12,0,0,0,60,116Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M136,128a8,8,0,1,1-8-8A8,8,0,0,1,136,128Zm-76-8a8,8,0,1,0,8,8A8,8,0,0,0,60,120Zm136,0a8,8,0,1,0,8,8A8,8,0,0,0,196,120Z`}))]]),Zj=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232.49,215.51,185,168a92.12,92.12,0,1,0-17,17l47.53,47.54a12,12,0,0,0,17-17ZM44,112a68,68,0,1,1,68,68A68.07,68.07,0,0,1,44,112Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M192,112a80,80,0,1,1-80-80A80,80,0,0,1,192,112Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M229.66,218.34,179.6,168.28a88.21,88.21,0,1,0-11.32,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM40,112a72,72,0,1,1,72,72A72.08,72.08,0,0,1,40,112Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M168,112a56,56,0,1,1-56-56A56,56,0,0,1,168,112Zm61.66,117.66a8,8,0,0,1-11.32,0l-50.06-50.07a88,88,0,1,1,11.32-11.31l50.06,50.06A8,8,0,0,1,229.66,229.66ZM112,184a72,72,0,1,0-72-72A72.08,72.08,0,0,0,112,184Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M228.24,219.76l-51.38-51.38a86.15,86.15,0,1,0-8.48,8.48l51.38,51.38a6,6,0,0,0,8.48-8.48ZM38,112a74,74,0,1,1,74,74A74.09,74.09,0,0,1,38,112Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M229.66,218.34l-50.07-50.06a88.11,88.11,0,1,0-11.31,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM40,112a72,72,0,1,1,72,72A72.08,72.08,0,0,1,40,112Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M226.83,221.17l-52.7-52.7a84.1,84.1,0,1,0-5.66,5.66l52.7,52.7a4,4,0,0,0,5.66-5.66ZM36,112a76,76,0,1,1,76,76A76.08,76.08,0,0,1,36,112Z`}))]]),Qj=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M236.37,139.4a12,12,0,0,0-12-3A84.07,84.07,0,0,1,119.6,31.59a12,12,0,0,0-15-15A108.86,108.86,0,0,0,49.69,55.07,108,108,0,0,0,136,228a107.09,107.09,0,0,0,64.93-21.69,108.86,108.86,0,0,0,38.44-54.94A12,12,0,0,0,236.37,139.4Zm-49.88,47.74A84,84,0,0,1,68.86,69.51,84.93,84.93,0,0,1,92.27,48.29Q92,52.13,92,56A108.12,108.12,0,0,0,200,164q3.87,0,7.71-.27A84.79,84.79,0,0,1,186.49,187.14Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M227.89,147.89A96,96,0,1,1,108.11,28.11,96.09,96.09,0,0,0,227.89,147.89Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M233.54,142.23a8,8,0,0,0-8-2,88.08,88.08,0,0,1-109.8-109.8,8,8,0,0,0-10-10,104.84,104.84,0,0,0-52.91,37A104,104,0,0,0,136,224a103.09,103.09,0,0,0,62.52-20.88,104.84,104.84,0,0,0,37-52.91A8,8,0,0,0,233.54,142.23ZM188.9,190.34A88,88,0,0,1,65.66,67.11a89,89,0,0,1,31.4-26A106,106,0,0,0,96,56,104.11,104.11,0,0,0,200,160a106,106,0,0,0,14.92-1.06A89,89,0,0,1,188.9,190.34Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M235.54,150.21a104.84,104.84,0,0,1-37,52.91A104,104,0,0,1,32,120,103.09,103.09,0,0,1,52.88,57.48a104.84,104.84,0,0,1,52.91-37,8,8,0,0,1,10,10,88.08,88.08,0,0,0,109.8,109.8,8,8,0,0,1,10,10Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M232.13,143.64a6,6,0,0,0-6-1.49A90.07,90.07,0,0,1,113.86,29.85a6,6,0,0,0-7.49-7.48A102.88,102.88,0,0,0,54.48,58.68,102,102,0,0,0,197.32,201.52a102.88,102.88,0,0,0,36.31-51.89A6,6,0,0,0,232.13,143.64Zm-42,48.29a90,90,0,0,1-126-126A90.9,90.9,0,0,1,99.65,37.66,102.06,102.06,0,0,0,218.34,156.35,90.9,90.9,0,0,1,190.1,191.93Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M233.54,142.23a8,8,0,0,0-8-2,88.08,88.08,0,0,1-109.8-109.8,8,8,0,0,0-10-10,104.84,104.84,0,0,0-52.91,37A104,104,0,0,0,136,224a103.09,103.09,0,0,0,62.52-20.88,104.84,104.84,0,0,0,37-52.91A8,8,0,0,0,233.54,142.23ZM188.9,190.34A88,88,0,0,1,65.66,67.11a89,89,0,0,1,31.4-26A106,106,0,0,0,96,56,104.11,104.11,0,0,0,200,160a106,106,0,0,0,14.92-1.06A89,89,0,0,1,188.9,190.34Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M230.72,145.06a4,4,0,0,0-4-1A92.08,92.08,0,0,1,111.94,29.27a4,4,0,0,0-5-5A100.78,100.78,0,0,0,56.08,59.88a100,100,0,0,0,140,140,100.78,100.78,0,0,0,35.59-50.87A4,4,0,0,0,230.72,145.06ZM191.3,193.53A92,92,0,0,1,62.47,64.7a93,93,0,0,1,39.88-30.35,100.09,100.09,0,0,0,119.3,119.3A93,93,0,0,1,191.3,193.53Z`}))]]),$j=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M230.14,70.54,185.46,25.85a20,20,0,0,0-28.29,0L33.86,149.17A19.85,19.85,0,0,0,28,163.31V208a20,20,0,0,0,20,20H92.69a19.86,19.86,0,0,0,14.14-5.86L230.14,98.82a20,20,0,0,0,0-28.28ZM91,204H52V165l84-84,39,39ZM192,103,153,64l18.34-18.34,39,39Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M221.66,90.34,192,120,136,64l29.66-29.66a8,8,0,0,1,11.31,0L221.66,79A8,8,0,0,1,221.66,90.34Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM92.69,208H48V163.31l88-88L180.69,120ZM192,108.68,147.31,64l24-24L216,84.68Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM192,108.68,147.31,64l24-24L216,84.68Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M225.9,74.78,181.21,30.09a14,14,0,0,0-19.8,0L38.1,153.41a13.94,13.94,0,0,0-4.1,9.9V208a14,14,0,0,0,14,14H92.69a13.94,13.94,0,0,0,9.9-4.1L225.9,94.58a14,14,0,0,0,0-19.8ZM94.1,209.41a2,2,0,0,1-1.41.59H48a2,2,0,0,1-2-2V163.31a2,2,0,0,1,.59-1.41L136,72.48,183.51,120ZM217.41,86.1,192,111.51,144.49,64,169.9,38.58a2,2,0,0,1,2.83,0l44.68,44.69a2,2,0,0,1,0,2.83Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M227.31,73.37,182.63,28.68a16,16,0,0,0-22.63,0L36.69,152A15.86,15.86,0,0,0,32,163.31V208a16,16,0,0,0,16,16H92.69A15.86,15.86,0,0,0,104,219.31L227.31,96a16,16,0,0,0,0-22.63ZM92.69,208H48V163.31l88-88L180.69,120ZM192,108.68,147.31,64l24-24L216,84.68Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224.49,76.2,179.8,31.51a12,12,0,0,0-17,0L133.17,61.17h0L39.52,154.83A11.9,11.9,0,0,0,36,163.31V208a12,12,0,0,0,12,12H92.69a12,12,0,0,0,8.48-3.51L224.48,93.17a12,12,0,0,0,0-17Zm-129,134.63A4,4,0,0,1,92.69,212H48a4,4,0,0,1-4-4V163.31a4,4,0,0,1,1.17-2.83L136,69.65,186.34,120ZM218.83,87.51,192,114.34,141.66,64l26.82-26.83a4,4,0,0,1,5.66,0l44.69,44.68a4,4,0,0,1,0,5.66Z`}))]]),eM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M240.49,15.51a12,12,0,0,0-17,0L173.94,65.09l-2.54-2.55a36.05,36.05,0,0,0-50.91,0L100,83l-3.51-3.52a12,12,0,0,0-17,17L83,100,62.54,120.49a36,36,0,0,0,0,50.91l2.55,2.54L15.51,223.51a12,12,0,0,0,17,17l49.57-49.58,2.54,2.55a36.06,36.06,0,0,0,50.91,0L156,173l3.51,3.52a12,12,0,0,0,17-17L173,156l20.49-20.49a36,36,0,0,0,0-50.91l-2.55-2.54,49.58-49.57A12,12,0,0,0,240.49,15.51Zm-121.95,161a12,12,0,0,1-17,0L79.51,154.43a12,12,0,0,1,0-17L100,117l39,39Zm58-57.95h0L156,139l-39-39,20.49-20.49a12,12,0,0,1,17,0l22.06,22.06a12,12,0,0,1,0,17ZM85.27,33.37a12,12,0,0,1,21.46-10.74l8,16A12,12,0,1,1,93.27,49.37Zm-68,57.26a12,12,0,0,1,16.1-5.36l16,8a12,12,0,1,1-10.74,21.46l-16-8A12,12,0,0,1,17.27,90.63Zm221.46,74.74a12,12,0,0,1-16.1,5.36l-16-8a12,12,0,0,1,10.74-21.46l16,8A12,12,0,0,1,238.73,165.37Zm-68,57.26a12,12,0,1,1-21.46,10.74l-8-16a12,12,0,0,1,21.46-10.74Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M185,127,127,185a24,24,0,0,1-33.94,0L71,162.91A24,24,0,0,1,71,129L129,71a24,24,0,0,1,33.94,0L185,93.09A24,24,0,0,1,185,127Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M237.66,18.34a8,8,0,0,0-11.32,0l-52.4,52.41-5.37-5.38a32.05,32.05,0,0,0-45.26,0L100,88.69l-6.34-6.35A8,8,0,0,0,82.34,93.66L88.69,100,65.37,123.31a32,32,0,0,0,0,45.26l5.38,5.37-52.41,52.4a8,8,0,0,0,11.32,11.32l52.4-52.41,5.37,5.38a32.06,32.06,0,0,0,45.26,0L156,167.31l6.34,6.35a8,8,0,0,0,11.32-11.32L167.31,156l23.32-23.31a32,32,0,0,0,0-45.26l-5.38-5.37,52.41-52.4A8,8,0,0,0,237.66,18.34Zm-116.29,161a16,16,0,0,1-22.62,0L76.69,157.25a16,16,0,0,1,0-22.62L100,111.31,144.69,156Zm57.94-57.94h0L156,144.69,111.31,100l23.32-23.31a16,16,0,0,1,22.62,0l22.06,22a16,16,0,0,1,0,22.63ZM88.57,35A8,8,0,0,1,103.43,29l8,20A8,8,0,0,1,96.57,55ZM24.57,93A8,8,0,0,1,35,88.57l20,8A8,8,0,0,1,49,111.43l-20-8A8,8,0,0,1,24.57,93ZM231.43,163a8,8,0,0,1-10.4,4.46l-20-8A8,8,0,1,1,207,144.57l20,8A8,8,0,0,1,231.43,163Zm-64,58.06A8,8,0,0,1,152.57,227l-8-20A8,8,0,0,1,159.43,201Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M88.57,35A8,8,0,0,1,103.43,29l8,20A8,8,0,0,1,96.57,55ZM29,103.43l20,8A8,8,0,1,0,55,96.57l-20-8A8,8,0,0,0,29,103.43ZM227,152.57l-20-8A8,8,0,1,0,201,159.43l20,8A8,8,0,0,0,227,152.57ZM159.43,201A8,8,0,0,0,144.57,207l8,20A8,8,0,1,0,167.43,221ZM237.91,18.52a8,8,0,0,0-11.5-.18L174,70.75l-5.38-5.38a32,32,0,0,0-45.28,0L106.14,82.54a4,4,0,0,0,0,5.66l61.7,61.66a4,4,0,0,0,5.66,0l16.74-16.74a32.76,32.76,0,0,0,9.81-22.52,31.82,31.82,0,0,0-9.37-23.17l-5.38-5.37,52.2-52.17A8.22,8.22,0,0,0,237.91,18.52ZM85.64,90.34a8,8,0,0,0-11.49.18,8.22,8.22,0,0,0,.41,11.37L80.67,108,65.34,123.31A31.82,31.82,0,0,0,56,146.47,32.75,32.75,0,0,0,65.77,169l5,4.94L18.49,226.13a8.21,8.21,0,0,0-.61,11.1,8,8,0,0,0,11.72.43L82,185.25l5.37,5.38a32.1,32.1,0,0,0,45.29,0L148,175.31l6.34,6.35a8,8,0,0,0,11.32-11.32Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M236.24,19.76a6,6,0,0,0-8.48,0L173.94,73.57l-6.79-6.78a30,30,0,0,0-42.42,0L100,91.51l-7.76-7.75a6,6,0,0,0-8.48,8.48L91.51,100,66.79,124.73a30,30,0,0,0,0,42.42l6.78,6.79L19.76,227.76a6,6,0,1,0,8.48,8.48l53.82-53.81,6.79,6.78a30,30,0,0,0,42.42,0L156,164.49l7.76,7.75a6,6,0,0,0,8.48-8.48L164.49,156l24.72-24.73a30,30,0,0,0,0-42.42l-6.78-6.79,53.81-53.82A6,6,0,0,0,236.24,19.76Zm-113.45,161a18,18,0,0,1-25.46,0L75.27,158.67a18,18,0,0,1,0-25.46L100,108.49,147.51,156Zm57.94-57.94L156,147.51,108.49,100l24.72-24.73a18,18,0,0,1,25.46,0l22.06,22.06a18,18,0,0,1,0,25.46ZM90.43,34.23a6,6,0,0,1,11.14-4.46l8,20a6,6,0,1,1-11.14,4.46Zm-64,59.54a6,6,0,0,1,7.8-3.34l20,8a6,6,0,1,1-4.46,11.14l-20-8A6,6,0,0,1,26.43,93.77Zm203.14,68.46a6,6,0,0,1-7.8,3.34l-20-8a6,6,0,0,1,4.46-11.14l20,8A6,6,0,0,1,229.57,162.23Zm-64,59.54a6,6,0,1,1-11.14,4.46l-8-20a6,6,0,0,1,11.14-4.46Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M237.66,18.34a8,8,0,0,0-11.32,0l-52.4,52.41-5.37-5.38a32.05,32.05,0,0,0-45.26,0L100,88.69l-6.34-6.35A8,8,0,0,0,82.34,93.66L88.69,100,65.37,123.31a32,32,0,0,0,0,45.26l5.38,5.37-52.41,52.4a8,8,0,0,0,11.32,11.32l52.4-52.41,5.37,5.38a32,32,0,0,0,45.26,0L156,167.31l6.34,6.35a8,8,0,0,0,11.32-11.32L167.31,156l23.32-23.31a32,32,0,0,0,0-45.26l-5.38-5.37,52.41-52.4A8,8,0,0,0,237.66,18.34Zm-116.29,161a16,16,0,0,1-22.62,0L76.69,157.25a16,16,0,0,1,0-22.62L100,111.31,144.69,156Zm57.94-57.94L156,144.69,111.31,100l23.32-23.31a16,16,0,0,1,22.62,0l22.06,22A16,16,0,0,1,179.31,121.37ZM88.57,35A8,8,0,0,1,103.43,29l8,20A8,8,0,0,1,96.57,55ZM24.57,93A8,8,0,0,1,35,88.57l20,8A8,8,0,0,1,49,111.43l-20-8A8,8,0,0,1,24.57,93ZM231.43,163a8,8,0,0,1-10.4,4.46l-20-8A8,8,0,1,1,207,144.57l20,8A8,8,0,0,1,231.43,163Zm-64,58.06A8,8,0,0,1,152.57,227l-8-20A8,8,0,0,1,159.43,201Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M234.83,21.17a4,4,0,0,0-5.66,0L173.94,76.4l-8.2-8.2a28,28,0,0,0-39.6,0L100,94.34l-9.17-9.17a4,4,0,0,0-5.66,5.66L94.34,100,68.2,126.14a28,28,0,0,0,0,39.6l8.2,8.2L21.17,229.17a4,4,0,0,0,5.66,5.66L82.06,179.6l8.2,8.2a28,28,0,0,0,39.6,0L156,161.66l9.17,9.17a4,4,0,0,0,5.66-5.66L161.66,156l26.14-26.14a28,28,0,0,0,0-39.6l-8.2-8.2,55.23-55.23A4,4,0,0,0,234.83,21.17Zm-110.63,161a20,20,0,0,1-28.28,0L73.86,160.08a20,20,0,0,1,0-28.28L100,105.66,150.34,156Zm57.94-57.94L156,150.34,105.66,100,131.8,73.86a20,20,0,0,1,28.28,0l22.06,22.06A20,20,0,0,1,182.14,124.2ZM92.29,33.49a4,4,0,1,1,7.42-3l8,20a4,4,0,0,1-2.22,5.2A3.91,3.91,0,0,1,104,56a4,4,0,0,1-3.71-2.51Zm-64,61a4,4,0,0,1,5.2-2.22l20,8A4,4,0,0,1,52,108a3.91,3.91,0,0,1-1.49-.29l-20-8A4,4,0,0,1,28.29,94.51Zm199.42,67A4,4,0,0,1,224,164a3.91,3.91,0,0,1-1.49-.29l-20-8a4,4,0,1,1,3-7.42l20,8A4,4,0,0,1,227.71,161.49Zm-64,61a4,4,0,0,1-2.22,5.2A3.91,3.91,0,0,1,160,228a4,4,0,0,1-3.71-2.51l-8-20a4,4,0,0,1,7.42-3Z`}))]]),tM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M228,128a12,12,0,0,1-12,12H140v76a12,12,0,0,1-24,0V140H40a12,12,0,0,1,0-24h76V40a12,12,0,0,1,24,0v76h76A12,12,0,0,1,228,128Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,56V200a16,16,0,0,1-16,16H56a16,16,0,0,1-16-16V56A16,16,0,0,1,56,40H200A16,16,0,0,1,216,56Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M224,128a8,8,0,0,1-8,8H136v80a8,8,0,0,1-16,0V136H40a8,8,0,0,1,0-16h80V40a8,8,0,0,1,16,0v80h80A8,8,0,0,1,224,128Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M208,32H48A16,16,0,0,0,32,48V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V48A16,16,0,0,0,208,32ZM184,136H136v48a8,8,0,0,1-16,0V136H72a8,8,0,0,1,0-16h48V72a8,8,0,0,1,16,0v48h48a8,8,0,0,1,0,16Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M222,128a6,6,0,0,1-6,6H134v82a6,6,0,0,1-12,0V134H40a6,6,0,0,1,0-12h82V40a6,6,0,0,1,12,0v82h82A6,6,0,0,1,222,128Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224,128a8,8,0,0,1-8,8H136v80a8,8,0,0,1-16,0V136H40a8,8,0,0,1,0-16h80V40a8,8,0,0,1,16,0v80h80A8,8,0,0,1,224,128Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M220,128a4,4,0,0,1-4,4H132v84a4,4,0,0,1-8,0V132H40a4,4,0,0,1,0-8h84V40a4,4,0,0,1,8,0v84h84A4,4,0,0,1,220,128Z`}))]]),nM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M124,216a12,12,0,0,1-12,12H48a12,12,0,0,1-12-12V40A12,12,0,0,1,48,28h64a12,12,0,0,1,0,24H60V204h52A12,12,0,0,1,124,216Zm108.49-96.49-40-40a12,12,0,0,0-17,17L195,116H112a12,12,0,0,0,0,24h83l-19.52,19.51a12,12,0,0,0,17,17l40-40A12,12,0,0,0,232.49,119.51Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M224,56V200a16,16,0,0,1-16,16H48V40H208A16,16,0,0,1,224,56Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M120,216a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V40a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H56V208h56A8,8,0,0,1,120,216Zm109.66-93.66-40-40a8,8,0,0,0-11.32,11.32L204.69,120H112a8,8,0,0,0,0,16h92.69l-26.35,26.34a8,8,0,0,0,11.32,11.32l40-40A8,8,0,0,0,229.66,122.34Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M120,216a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V40a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H56V208h56A8,8,0,0,1,120,216Zm109.66-93.66-40-40A8,8,0,0,0,176,88v32H112a8,8,0,0,0,0,16h64v32a8,8,0,0,0,13.66,5.66l40-40A8,8,0,0,0,229.66,122.34Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M118,216a6,6,0,0,1-6,6H48a6,6,0,0,1-6-6V40a6,6,0,0,1,6-6h64a6,6,0,0,1,0,12H54V210h58A6,6,0,0,1,118,216Zm110.24-92.24-40-40a6,6,0,0,0-8.48,8.48L209.51,122H112a6,6,0,0,0,0,12h97.51l-29.75,29.76a6,6,0,1,0,8.48,8.48l40-40A6,6,0,0,0,228.24,123.76Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M120,216a8,8,0,0,1-8,8H48a8,8,0,0,1-8-8V40a8,8,0,0,1,8-8h64a8,8,0,0,1,0,16H56V208h56A8,8,0,0,1,120,216Zm109.66-93.66-40-40a8,8,0,0,0-11.32,11.32L204.69,120H112a8,8,0,0,0,0,16h92.69l-26.35,26.34a8,8,0,0,0,11.32,11.32l40-40A8,8,0,0,0,229.66,122.34Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M116,216a4,4,0,0,1-4,4H48a4,4,0,0,1-4-4V40a4,4,0,0,1,4-4h64a4,4,0,0,1,0,8H52V212h60A4,4,0,0,1,116,216Zm110.83-90.83-40-40a4,4,0,0,0-5.66,5.66L214.34,124H112a4,4,0,0,0,0,8H214.34l-33.17,33.17a4,4,0,0,0,5.66,5.66l40-40A4,4,0,0,0,226.83,125.17Z`}))]]),rM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M199,125.31l-49.88-18.39L130.69,57a19.92,19.92,0,0,0-37.38,0L74.92,106.92,25,125.31a19.92,19.92,0,0,0,0,37.38l49.88,18.39L93.31,231a19.92,19.92,0,0,0,37.38,0l18.39-49.88L199,162.69a19.92,19.92,0,0,0,0-37.38Zm-63.38,35.16a12,12,0,0,0-7.11,7.11L112,212.28l-16.47-44.7a12,12,0,0,0-7.11-7.11L43.72,144l44.7-16.47a12,12,0,0,0,7.11-7.11L112,75.72l16.47,44.7a12,12,0,0,0,7.11,7.11L180.28,144ZM140,40a12,12,0,0,1,12-12h12V16a12,12,0,0,1,24,0V28h12a12,12,0,0,1,0,24H188V64a12,12,0,0,1-24,0V52H152A12,12,0,0,1,140,40ZM252,88a12,12,0,0,1-12,12h-4v4a12,12,0,0,1-24,0v-4h-4a12,12,0,0,1,0-24h4V72a12,12,0,0,1,24,0v4h4A12,12,0,0,1,252,88Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M194.82,151.43l-55.09,20.3-20.3,55.09a7.92,7.92,0,0,1-14.86,0l-20.3-55.09-55.09-20.3a7.92,7.92,0,0,1,0-14.86l55.09-20.3,20.3-55.09a7.92,7.92,0,0,1,14.86,0l20.3,55.09,55.09,20.3A7.92,7.92,0,0,1,194.82,151.43Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M197.58,129.06,146,110l-19-51.62a15.92,15.92,0,0,0-29.88,0L78,110l-51.62,19a15.92,15.92,0,0,0,0,29.88L78,178l19,51.62a15.92,15.92,0,0,0,29.88,0L146,178l51.62-19a15.92,15.92,0,0,0,0-29.88ZM137,164.22a8,8,0,0,0-4.74,4.74L112,223.85,91.78,169A8,8,0,0,0,87,164.22L32.15,144,87,123.78A8,8,0,0,0,91.78,119L112,64.15,132.22,119a8,8,0,0,0,4.74,4.74L191.85,144ZM144,40a8,8,0,0,1,8-8h16V16a8,8,0,0,1,16,0V32h16a8,8,0,0,1,0,16H184V64a8,8,0,0,1-16,0V48H152A8,8,0,0,1,144,40ZM248,88a8,8,0,0,1-8,8h-8v8a8,8,0,0,1-16,0V96h-8a8,8,0,0,1,0-16h8V72a8,8,0,0,1,16,0v8h8A8,8,0,0,1,248,88Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M208,144a15.78,15.78,0,0,1-10.42,14.94L146,178l-19,51.62a15.92,15.92,0,0,1-29.88,0L78,178l-51.62-19a15.92,15.92,0,0,1,0-29.88L78,110l19-51.62a15.92,15.92,0,0,1,29.88,0L146,110l51.62,19A15.78,15.78,0,0,1,208,144ZM152,48h16V64a8,8,0,0,0,16,0V48h16a8,8,0,0,0,0-16H184V16a8,8,0,0,0-16,0V32H152a8,8,0,0,0,0,16Zm88,32h-8V72a8,8,0,0,0-16,0v8h-8a8,8,0,0,0,0,16h8v8a8,8,0,0,0,16,0V96h8a8,8,0,0,0,0-16Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M196.89,130.94,144.4,111.6,125.06,59.11a13.92,13.92,0,0,0-26.12,0L79.6,111.6,27.11,130.94a13.92,13.92,0,0,0,0,26.12L79.6,176.4l19.34,52.49a13.92,13.92,0,0,0,26.12,0L144.4,176.4l52.49-19.34a13.92,13.92,0,0,0,0-26.12Zm-4.15,14.86-55.08,20.3a6,6,0,0,0-3.56,3.56l-20.3,55.08a1.92,1.92,0,0,1-3.6,0L89.9,169.66a6,6,0,0,0-3.56-3.56L31.26,145.8a1.92,1.92,0,0,1,0-3.6l55.08-20.3a6,6,0,0,0,3.56-3.56l20.3-55.08a1.92,1.92,0,0,1,3.6,0l20.3,55.08a6,6,0,0,0,3.56,3.56l55.08,20.3a1.92,1.92,0,0,1,0,3.6ZM146,40a6,6,0,0,1,6-6h18V16a6,6,0,0,1,12,0V34h18a6,6,0,0,1,0,12H182V64a6,6,0,0,1-12,0V46H152A6,6,0,0,1,146,40ZM246,88a6,6,0,0,1-6,6H230v10a6,6,0,0,1-12,0V94H208a6,6,0,0,1,0-12h10V72a6,6,0,0,1,12,0V82h10A6,6,0,0,1,246,88Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M197.58,129.06,146,110l-19-51.62a15.92,15.92,0,0,0-29.88,0L78,110l-51.62,19a15.92,15.92,0,0,0,0,29.88L78,178l19,51.62a15.92,15.92,0,0,0,29.88,0L146,178l51.62-19a15.92,15.92,0,0,0,0-29.88ZM137,164.22a8,8,0,0,0-4.74,4.74L112,223.85,91.78,169A8,8,0,0,0,87,164.22L32.15,144,87,123.78A8,8,0,0,0,91.78,119L112,64.15,132.22,119a8,8,0,0,0,4.74,4.74L191.85,144ZM144,40a8,8,0,0,1,8-8h16V16a8,8,0,0,1,16,0V32h16a8,8,0,0,1,0,16H184V64a8,8,0,0,1-16,0V48H152A8,8,0,0,1,144,40ZM248,88a8,8,0,0,1-8,8h-8v8a8,8,0,0,1-16,0V96h-8a8,8,0,0,1,0-16h8V72a8,8,0,0,1,16,0v8h8A8,8,0,0,1,248,88Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M196.2,132.81l-53.36-19.65L123.19,59.8a11.93,11.93,0,0,0-22.38,0L81.16,113.16,27.8,132.81a11.93,11.93,0,0,0,0,22.38l53.36,19.65,19.65,53.36a11.93,11.93,0,0,0,22.38,0l19.65-53.36,53.36-19.65a11.93,11.93,0,0,0,0-22.38Zm-2.77,14.87L138.35,168a4,4,0,0,0-2.37,2.37l-20.3,55.08a3.92,3.92,0,0,1-7.36,0L88,170.35A4,4,0,0,0,85.65,168l-55.08-20.3a3.92,3.92,0,0,1,0-7.36L85.65,120A4,4,0,0,0,88,117.65l20.3-55.08a3.92,3.92,0,0,1,7.36,0L136,117.65a4,4,0,0,0,2.37,2.37l55.08,20.3a3.92,3.92,0,0,1,0,7.36ZM148,40a4,4,0,0,1,4-4h20V16a4,4,0,0,1,8,0V36h20a4,4,0,0,1,0,8H180V64a4,4,0,0,1-8,0V44H152A4,4,0,0,1,148,40Zm96,48a4,4,0,0,1-4,4H228v12a4,4,0,0,1-8,0V92H208a4,4,0,0,1,0-8h12V72a4,4,0,0,1,8,0V84h12A4,4,0,0,1,244,88Z`}))]]),iM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M116,36V20a12,12,0,0,1,24,0V36a12,12,0,0,1-24,0Zm80,92a68,68,0,1,1-68-68A68.07,68.07,0,0,1,196,128Zm-24,0a44,44,0,1,0-44,44A44.05,44.05,0,0,0,172,128ZM51.51,68.49a12,12,0,1,0,17-17l-12-12a12,12,0,0,0-17,17Zm0,119-12,12a12,12,0,0,0,17,17l12-12a12,12,0,1,0-17-17ZM196,72a12,12,0,0,0,8.49-3.51l12-12a12,12,0,0,0-17-17l-12,12A12,12,0,0,0,196,72Zm8.49,115.51a12,12,0,0,0-17,17l12,12a12,12,0,0,0,17-17ZM48,128a12,12,0,0,0-12-12H20a12,12,0,0,0,0,24H36A12,12,0,0,0,48,128Zm80,80a12,12,0,0,0-12,12v16a12,12,0,0,0,24,0V220A12,12,0,0,0,128,208Zm108-92H220a12,12,0,0,0,0,24h16a12,12,0,0,0,0-24Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M184,128a56,56,0,1,1-56-56A56,56,0,0,1,184,128Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M120,40V16a8,8,0,0,1,16,0V40a8,8,0,0,1-16,0Zm72,88a64,64,0,1,1-64-64A64.07,64.07,0,0,1,192,128Zm-16,0a48,48,0,1,0-48,48A48.05,48.05,0,0,0,176,128ZM58.34,69.66A8,8,0,0,0,69.66,58.34l-16-16A8,8,0,0,0,42.34,53.66Zm0,116.68-16,16a8,8,0,0,0,11.32,11.32l16-16a8,8,0,0,0-11.32-11.32ZM192,72a8,8,0,0,0,5.66-2.34l16-16a8,8,0,0,0-11.32-11.32l-16,16A8,8,0,0,0,192,72Zm5.66,114.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32-11.32ZM48,128a8,8,0,0,0-8-8H16a8,8,0,0,0,0,16H40A8,8,0,0,0,48,128Zm80,80a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V216A8,8,0,0,0,128,208Zm112-88H216a8,8,0,0,0,0,16h24a8,8,0,0,0,0-16Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M120,40V16a8,8,0,0,1,16,0V40a8,8,0,0,1-16,0Zm8,24a64,64,0,1,0,64,64A64.07,64.07,0,0,0,128,64ZM58.34,69.66A8,8,0,0,0,69.66,58.34l-16-16A8,8,0,0,0,42.34,53.66Zm0,116.68-16,16a8,8,0,0,0,11.32,11.32l16-16a8,8,0,0,0-11.32-11.32ZM192,72a8,8,0,0,0,5.66-2.34l16-16a8,8,0,0,0-11.32-11.32l-16,16A8,8,0,0,0,192,72Zm5.66,114.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32-11.32ZM48,128a8,8,0,0,0-8-8H16a8,8,0,0,0,0,16H40A8,8,0,0,0,48,128Zm80,80a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V216A8,8,0,0,0,128,208Zm112-88H216a8,8,0,0,0,0,16h24a8,8,0,0,0,0-16Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M122,40V16a6,6,0,0,1,12,0V40a6,6,0,0,1-12,0Zm68,88a62,62,0,1,1-62-62A62.07,62.07,0,0,1,190,128Zm-12,0a50,50,0,1,0-50,50A50.06,50.06,0,0,0,178,128ZM59.76,68.24a6,6,0,1,0,8.48-8.48l-16-16a6,6,0,0,0-8.48,8.48Zm0,119.52-16,16a6,6,0,1,0,8.48,8.48l16-16a6,6,0,1,0-8.48-8.48ZM192,70a6,6,0,0,0,4.24-1.76l16-16a6,6,0,0,0-8.48-8.48l-16,16A6,6,0,0,0,192,70Zm4.24,117.76a6,6,0,0,0-8.48,8.48l16,16a6,6,0,0,0,8.48-8.48ZM46,128a6,6,0,0,0-6-6H16a6,6,0,0,0,0,12H40A6,6,0,0,0,46,128Zm82,82a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V216A6,6,0,0,0,128,210Zm112-88H216a6,6,0,0,0,0,12h24a6,6,0,0,0,0-12Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M120,40V16a8,8,0,0,1,16,0V40a8,8,0,0,1-16,0Zm72,88a64,64,0,1,1-64-64A64.07,64.07,0,0,1,192,128Zm-16,0a48,48,0,1,0-48,48A48.05,48.05,0,0,0,176,128ZM58.34,69.66A8,8,0,0,0,69.66,58.34l-16-16A8,8,0,0,0,42.34,53.66Zm0,116.68-16,16a8,8,0,0,0,11.32,11.32l16-16a8,8,0,0,0-11.32-11.32ZM192,72a8,8,0,0,0,5.66-2.34l16-16a8,8,0,0,0-11.32-11.32l-16,16A8,8,0,0,0,192,72Zm5.66,114.34a8,8,0,0,0-11.32,11.32l16,16a8,8,0,0,0,11.32-11.32ZM48,128a8,8,0,0,0-8-8H16a8,8,0,0,0,0,16H40A8,8,0,0,0,48,128Zm80,80a8,8,0,0,0-8,8v24a8,8,0,0,0,16,0V216A8,8,0,0,0,128,208Zm112-88H216a8,8,0,0,0,0,16h24a8,8,0,0,0,0-16Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M124,40V16a4,4,0,0,1,8,0V40a4,4,0,0,1-8,0Zm64,88a60,60,0,1,1-60-60A60.07,60.07,0,0,1,188,128Zm-8,0a52,52,0,1,0-52,52A52.06,52.06,0,0,0,180,128ZM61.17,66.83a4,4,0,0,0,5.66-5.66l-16-16a4,4,0,0,0-5.66,5.66Zm0,122.34-16,16a4,4,0,0,0,5.66,5.66l16-16a4,4,0,0,0-5.66-5.66ZM192,68a4,4,0,0,0,2.83-1.17l16-16a4,4,0,1,0-5.66-5.66l-16,16A4,4,0,0,0,192,68Zm2.83,121.17a4,4,0,0,0-5.66,5.66l16,16a4,4,0,0,0,5.66-5.66ZM40,124H16a4,4,0,0,0,0,8H40a4,4,0,0,0,0-8Zm88,88a4,4,0,0,0-4,4v24a4,4,0,0,0,8,0V216A4,4,0,0,0,128,212Zm112-88H216a4,4,0,0,0,0,8h24a4,4,0,0,0,0-8Z`}))]]),aM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,48H180V36A28,28,0,0,0,152,8H104A28,28,0,0,0,76,36V48H40a12,12,0,0,0,0,24h4V208a20,20,0,0,0,20,20H192a20,20,0,0,0,20-20V72h4a12,12,0,0,0,0-24ZM100,36a4,4,0,0,1,4-4h48a4,4,0,0,1,4,4V48H100Zm88,168H68V72H188ZM116,104v64a12,12,0,0,1-24,0V104a12,12,0,0,1,24,0Zm48,0v64a12,12,0,0,1-24,0V104a12,12,0,0,1,24,0Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M200,56V208a8,8,0,0,1-8,8H64a8,8,0,0,1-8-8V56Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM96,40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8v8H96Zm96,168H64V64H192ZM112,104v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM112,168a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm0-120H96V40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,50H174V40a22,22,0,0,0-22-22H104A22,22,0,0,0,82,40V50H40a6,6,0,0,0,0,12H50V208a14,14,0,0,0,14,14H192a14,14,0,0,0,14-14V62h10a6,6,0,0,0,0-12ZM94,40a10,10,0,0,1,10-10h48a10,10,0,0,1,10,10V50H94ZM194,208a2,2,0,0,1-2,2H64a2,2,0,0,1-2-2V62H194ZM110,104v64a6,6,0,0,1-12,0V104a6,6,0,0,1,12,0Zm48,0v64a6,6,0,0,1-12,0V104a6,6,0,0,1,12,0Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,48H176V40a24,24,0,0,0-24-24H104A24,24,0,0,0,80,40v8H40a8,8,0,0,0,0,16h8V208a16,16,0,0,0,16,16H192a16,16,0,0,0,16-16V64h8a8,8,0,0,0,0-16ZM96,40a8,8,0,0,1,8-8h48a8,8,0,0,1,8,8v8H96Zm96,168H64V64H192ZM112,104v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Zm48,0v64a8,8,0,0,1-16,0V104a8,8,0,0,1,16,0Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M216,52H172V40a20,20,0,0,0-20-20H104A20,20,0,0,0,84,40V52H40a4,4,0,0,0,0,8H52V208a12,12,0,0,0,12,12H192a12,12,0,0,0,12-12V60h12a4,4,0,0,0,0-8ZM92,40a12,12,0,0,1,12-12h48a12,12,0,0,1,12,12V52H92ZM196,208a4,4,0,0,1-4,4H64a4,4,0,0,1-4-4V60H196ZM108,104v64a4,4,0,0,1-8,0V104a4,4,0,0,1,8,0Zm48,0v64a4,4,0,0,1-8,0V104a4,4,0,0,1,8,0Z`}))]]),oM=new Map([[`bold`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M256,136a12,12,0,0,1-12,12h-8v8a12,12,0,0,1-24,0v-8h-8a12,12,0,0,1,0-24h8v-8a12,12,0,0,1,24,0v8h8A12,12,0,0,1,256,136Zm-54.81,56.28a12,12,0,1,1-18.38,15.44C169.12,191.42,145,172,108,172c-28.89,0-55.46,12.68-74.81,35.72a12,12,0,0,1-18.38-15.44A124.08,124.08,0,0,1,63.5,156.53a72,72,0,1,1,89,0A124,124,0,0,1,201.19,192.28ZM108,148a48,48,0,1,0-48-48A48.05,48.05,0,0,0,108,148Z`}))],[`duotone`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M168,100a60,60,0,1,1-60-60A60,60,0,0,1,168,100Z`,opacity:`0.2`}),M.createElement(`path`,{d:`M256,136a8,8,0,0,1-8,8H232v16a8,8,0,0,1-16,0V144H200a8,8,0,0,1,0-16h16V112a8,8,0,0,1,16,0v16h16A8,8,0,0,1,256,136Zm-57.87,58.85a8,8,0,0,1-12.26,10.3C165.75,181.19,138.09,168,108,168s-57.75,13.19-77.87,37.15a8,8,0,0,1-12.25-10.3c14.94-17.78,33.52-30.41,54.17-37.17a68,68,0,1,1,71.9,0C164.6,164.44,183.18,177.07,198.13,194.85ZM108,152a52,52,0,1,0-52-52A52.06,52.06,0,0,0,108,152Z`}))],[`fill`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M256,136a8,8,0,0,1-8,8H232v16a8,8,0,0,1-16,0V144H200a8,8,0,0,1,0-16h16V112a8,8,0,0,1,16,0v16h16A8,8,0,0,1,256,136ZM144,157.68a68,68,0,1,0-71.9,0c-20.65,6.76-39.23,19.39-54.17,37.17A8,8,0,0,0,24,208H192a8,8,0,0,0,6.13-13.15C183.18,177.07,164.6,164.44,144,157.68Z`}))],[`light`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M254,136a6,6,0,0,1-6,6H230v18a6,6,0,0,1-12,0V142H200a6,6,0,0,1,0-12h18V112a6,6,0,0,1,12,0v18h18A6,6,0,0,1,254,136Zm-57.41,60.14a6,6,0,1,1-9.18,7.72C166.9,179.45,138.69,166,108,166s-58.89,13.45-79.41,37.86a6,6,0,0,1-9.18-7.72C35.14,177.41,55,164.48,77,158.25a66,66,0,1,1,62,0C161,164.48,180.86,177.41,196.59,196.14ZM108,154a54,54,0,1,0-54-54A54.06,54.06,0,0,0,108,154Z`}))],[`regular`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M256,136a8,8,0,0,1-8,8H232v16a8,8,0,0,1-16,0V144H200a8,8,0,0,1,0-16h16V112a8,8,0,0,1,16,0v16h16A8,8,0,0,1,256,136Zm-57.87,58.85a8,8,0,0,1-12.26,10.3C165.75,181.19,138.09,168,108,168s-57.75,13.19-77.87,37.15a8,8,0,0,1-12.25-10.3c14.94-17.78,33.52-30.41,54.17-37.17a68,68,0,1,1,71.9,0C164.6,164.44,183.18,177.07,198.13,194.85ZM108,152a52,52,0,1,0-52-52A52.06,52.06,0,0,0,108,152Z`}))],[`thin`,M.createElement(M.Fragment,null,M.createElement(`path`,{d:`M252,136a4,4,0,0,1-4,4H228v20a4,4,0,0,1-8,0V140H200a4,4,0,0,1,0-8h20V112a4,4,0,0,1,8,0v20h20A4,4,0,0,1,252,136Zm-56.94,61.43a4,4,0,0,1-6.12,5.14C168,177.7,139.3,164,108,164s-60,13.7-80.94,38.57a4,4,0,1,1-6.12-5.14c16.71-19.9,38.13-33.13,61.89-38.59a64,64,0,1,1,50.34,0C156.93,164.3,178.35,177.53,195.06,197.43ZM108,156a56,56,0,1,0-56-56A56.06,56.06,0,0,0,108,156Z`}))]]),sM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:qj}));sM.displayName=`ArrowLeftIcon`;var cM=sM,lM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:Jj}));lM.displayName=`ArrowRightIcon`;var uM=lM,dM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:Yj}));dM.displayName=`BookOpenIcon`;var fM=dM,pM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:Xj}));pM.displayName=`DotsThreeIcon`;var mM=pM,hM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:Zj}));hM.displayName=`MagnifyingGlassIcon`;var gM=hM,_M=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:Qj}));_M.displayName=`MoonIcon`;var vM=_M,yM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:$j}));yM.displayName=`PencilSimpleIcon`;var bM=yM,xM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:eM}));xM.displayName=`PlugsConnectedIcon`;var SM=xM,CM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:tM}));CM.displayName=`PlusIcon`;var wM=CM,TM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:nM}));TM.displayName=`SignOutIcon`;var EM=TM,DM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:rM}));DM.displayName=`SparkleIcon`;var OM=DM,kM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:iM}));kM.displayName=`SunIcon`;var AM=kM,jM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:aM}));jM.displayName=`TrashIcon`;var MM=jM,NM=M.forwardRef((e,t)=>M.createElement(k,{ref:t,...e,weights:oM}));NM.displayName=`UserPlusIcon`;var PM=NM,FM=class extends Error{status;problems;code;constructor(e,t,n=[],r=``){super(e),this.status=t,this.problems=n,this.code=r}},IM=`fanout:unauthorized`;function LM(){let e=new URLSearchParams(window.location.search).get(`return_to`);if(!e)return``;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin||t.pathname!==`/api/auth/oauth/authorize`?``:`${t.pathname}${t.search}`}function RM(e){return!e||typeof e!=`object`||!(`id`in e)||typeof e.id!=`string`||e.id===``?`none`:`user`}function zM(){window.dispatchEvent(new Event(IM))}async function BM(e,t={}){let n=new Headers(t.headers);n.set(`Fanout-Request`,`1`);let r=await fetch(e,{...t,headers:n,credentials:`same-origin`});if(r.status===401&&zM(),r.status===403){let e=await r.clone().json().catch(()=>({}));throw new FM(e.message??`You do not have permission to perform this action.`,r.status,[],e.code??``)}return r}async function VM(){let e=await BM(`/api/auth/logout`,{method:`POST`});if(!e.ok&&e.status!==401)throw Error(`Sign-out failed — your session is still active.`);e.status!==401&&zM(),window.location.assign(`/`)}var HM=(0,M.createContext)(null);function UM(){let e=(0,M.useContext)(HM);if(!e)throw Error(`Fanout runtime status is unavailable`);return e}var WM=(0,M.createContext)(null);function GM(){let e=(0,M.useContext)(WM);if(!e)throw Error(`Fanout viewer is unavailable`);return e}function KM(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.id!=`string`||t.id===``||t.status!==`active`&&t.status!==`suspended`?null:{id:t.id,email:typeof t.email==`string`?t.email:``,display_name:typeof t.display_name==`string`?t.display_name:``,status:t.status,role:typeof t.role==`string`?t.role:``}}async function qM(e,t){let n=await fetch(e,{method:t===void 0?`GET`:`POST`,headers:t===void 0?void 0:{"Content-Type":`application/json`},body:t===void 0?void 0:JSON.stringify(t),credentials:`same-origin`}),r=await n.json().catch(()=>({}));if(!n.ok)throw Error(r.message??`Request failed (${n.status})`);return r}function JM({children:e,wide:t=!1}){return(0,N.jsx)(u,{mih:`100dvh`,style:{background:`radial-gradient(circle at 50% -12%, var(--mantine-color-brand-light), transparent 38%), linear-gradient(180deg, var(--mantine-color-default-hover), var(--mantine-color-body) 62%)`},children:(0,N.jsx)(je,{mih:`100dvh`,px:`md`,py:48,children:(0,N.jsx)(ve,{size:t?680:480,w:`100%`,children:(0,N.jsx)(Fe,{radius:28,p:{base:24,sm:40},style:{background:`var(--mantine-color-body)`,border:`1px solid var(--mantine-color-default-border)`,boxShadow:`var(--mantine-shadow-xl)`},children:e})})})})}function YM(){return typeof window>`u`?``:new URLSearchParams(window.location.search).get(`setup_token`)??``}function XM(){return typeof window>`u`?``:new URLSearchParams(window.location.search).get(`login_token`)??``}function ZM({children:e}){let t=ze(),[n,r]=(0,M.useState)(null),[i,a]=(0,M.useState)(!1),[o,s]=(0,M.useState)(`none`),[c,l]=(0,M.useState)(null),[d,f]=(0,M.useState)(!1),[p,m]=(0,M.useState)(``),[h,g]=(0,M.useState)(``),[_,v]=(0,M.useState)(YM),[y,b]=(0,M.useState)(XM),[x,S]=(0,M.useState)(``),[C,w]=(0,M.useState)(!1),[T,ee]=(0,M.useState)(0),[E,D]=(0,M.useState)(()=>Date.now()),[O,te]=(0,M.useState)(!1),[re,k]=(0,M.useState)(``),[ie,ae]=(0,M.useState)(null),[se,le]=(0,M.useState)(!1),de=(0,M.useRef)(null),fe=LM(),pe=o===`user`;async function he(){let e=await fetch(`/api/auth/me`,{credentials:`same-origin`});if(!e.ok){s(`none`),l(null);return}let t=await e.json().catch(()=>null);s(RM(t)),l(KM(t))}async function ge(){try{let e=await fetch(`/api/auth/me`,{credentials:`same-origin`});if(!e.ok)return;l(KM(await e.json().catch(()=>null)))}catch{}}(0,M.useEffect)(()=>{let e=new URL(window.location.href);(e.searchParams.has(`setup_token`)||e.searchParams.has(`login_token`))&&(e.searchParams.delete(`setup_token`),e.searchParams.delete(`login_token`),t({href:e.pathname+e.search+e.hash,replace:!0}))},[t]),(0,M.useEffect)(()=>{qM(`/api/auth/status`).then(r).catch(e=>k(String(e))).finally(()=>a(!0)),he().catch(()=>s(`none`)).finally(()=>f(!0));let e=()=>{s(`none`),l(null)};return window.addEventListener(IM,e),()=>window.removeEventListener(IM,e)},[]),(0,M.useEffect)(()=>{d&&o===`none`&&y&&(te(!0),k(``),qM(`/api/auth/link/verify`,{token:y}).then(()=>{s(`user`),ge()}).catch(e=>k(e instanceof Error?e.message:String(e))).finally(()=>{b(``),te(!1)}))},[y,d,o]),(0,M.useEffect)(()=>{pe&&d&&fe&&window.location.replace(fe)},[pe,fe,d]),(0,M.useEffect)(()=>{if(T<=Date.now())return;let e=setInterval(()=>{D(Date.now()),Date.now()>=T&&clearInterval(e)},1e3);return()=>clearInterval(e)},[T]);let _e=Math.max(0,Math.ceil((T-E)/1e3));(0,M.useEffect)(()=>{C&&!O&&re&&de.current?.querySelector(`input`)?.focus()},[O,C,re]);async function ve(e){try{await navigator.clipboard.writeText(e),le(!0)}catch{k(`Clipboard access failed. Select and copy the token manually.`)}}if(ie?.ingest_token)return(0,N.jsx)(JM,{wide:!0,children:(0,N.jsxs)(oe,{gap:`lg`,children:[(0,N.jsx)(ke,{}),(0,N.jsxs)(`div`,{children:[(0,N.jsx)(ue,{c:`brand`,fw:700,size:`xs`,tt:`uppercase`,lts:`0.12em`,children:`Setup complete`}),(0,N.jsx)(xe,{order:1,mt:`xs`,fz:{base:28,sm:32},lh:1.08,children:`Save your ingest token`})]}),(0,N.jsx)(ue,{c:`dimmed`,children:`Fanout shows this token once. Store it with your collector secrets before continuing.`}),(0,N.jsxs)(oe,{gap:`xs`,children:[(0,N.jsx)(ue,{size:`sm`,fw:600,children:`OTLP endpoint`}),(0,N.jsx)(ss,{block:!0,children:ie.suggested_endpoint??window.location.origin})]}),(0,N.jsxs)(oe,{gap:`xs`,children:[(0,N.jsx)(ue,{size:`sm`,fw:600,children:`Header`}),(0,N.jsxs)(ss,{block:!0,children:[ie.ingest_header_name??`Authorization`,`: Bearer `,ie.ingest_token]})]}),re&&(0,N.jsx)(Ce,{color:`bad`,radius:`md`,children:re}),(0,N.jsxs)(ne,{grow:!0,align:`stretch`,children:[(0,N.jsx)(ce,{variant:`light`,radius:`md`,leftSection:se?(0,N.jsx)(me,{size:16,weight:`bold`}):(0,N.jsx)(Ee,{size:16}),onClick:()=>void ve(`${ie.ingest_header_name??`Authorization`}: Bearer ${ie.ingest_token}`),children:se?`Copied`:`Copy header`}),(0,N.jsx)(ce,{radius:`md`,rightSection:(0,N.jsx)(uM,{size:16,weight:`bold`}),onClick:()=>{s(`user`),ae(null),ge()},children:`Continue to Fanout`})]}),(0,N.jsx)(ce,{variant:`subtle`,size:`compact-xs`,onClick:()=>void ve(ie.ingest_token??``),children:`Copy token only`})]})});if(!d||!i||y)return(0,N.jsx)(je,{mih:`100dvh`,children:(0,N.jsx)(Ie,{size:`sm`})});if(!n)return(0,N.jsx)(JM,{children:(0,N.jsxs)(oe,{gap:`lg`,children:[(0,N.jsx)(ke,{}),(0,N.jsx)(xe,{order:1,children:`Fanout is unavailable`}),(0,N.jsx)(Ce,{color:`bad`,radius:`md`,children:re||`Authentication status could not be loaded.`})]})});if(pe&&fe)return null;if(pe)return(0,N.jsx)(HM.Provider,{value:n,children:(0,N.jsx)(WM.Provider,{value:c??{id:``,email:p,display_name:h,status:`active`,role:``},children:e})});if(n&&!n.setup_required&&n.auth_mode===`oidc`){let e=fe?`/api/auth/oidc/start?return_to=${encodeURIComponent(fe)}`:`/api/auth/oidc/start`;return(0,N.jsx)(JM,{children:(0,N.jsxs)(oe,{gap:28,children:[(0,N.jsx)(ke,{}),(0,N.jsxs)(oe,{gap:10,children:[(0,N.jsx)(ue,{c:`brand`,fw:700,size:`xs`,tt:`uppercase`,lts:`0.12em`,children:`Secure workspace`}),(0,N.jsx)(xe,{order:1,fz:{base:28,sm:32},lh:1.08,children:`Sign in`}),(0,N.jsx)(ue,{c:`dimmed`,size:`md`,lh:1.6,children:`Use your organization's identity provider to continue.`})]}),re&&(0,N.jsx)(Ce,{color:`bad`,radius:`md`,children:re}),(0,N.jsx)(ce,{component:`a`,href:e,size:`md`,radius:`md`,rightSection:(0,N.jsx)(uM,{size:17,weight:`bold`}),children:`Continue with SSO`})]})})}async function ye(){te(!0),k(``);try{await qM(`/api/auth/code/send`,{email:p}),w(!0),S(``),ee(Date.now()+3e4),D(Date.now())}catch(e){k(e instanceof Error?e.message:String(e))}finally{te(!1)}}async function A(e){te(!0),k(``);try{await qM(`/api/auth/code/verify`,{email:p,code:e}),s(`user`),w(!1),S(``),ee(0),ge()}catch(e){S(``),k(e instanceof Error?e.message:String(e))}finally{te(!1)}}function j(){w(!1),S(``),k(``)}async function be(e){e.preventDefault(),te(!0),k(``);try{if(n?.setup_required){let e=await qM(`/api/auth/setup`,{email:p,display_name:h,setup_token:_});e.ingest_token?ae(e):(s(`user`),ge())}else if(C){await A(x);return}else{await ye();return}}catch(e){k(e instanceof Error?e.message:String(e))}finally{te(!1)}}let Se=C&&!n?.setup_required,we=n?.setup_required?`Create the first admin`:Se?`Check your email`:n?.self_signup?`Sign in or create an account`:`Sign in`,Te=n?.setup_required?`Use the one-time token printed by the Fanout process.`:n?.smtp_configured?Se?`We sent a code to ${p}.`:n?.self_signup?`Enter your email to sign in or create a viewer account. No password needed.`:`Enter your email and we’ll send a short verification code. No password needed.`:`Email delivery is not configured. Ask the operator to run fanout login-link with your email address.`;return(0,N.jsx)(JM,{children:(0,N.jsxs)(oe,{gap:28,children:[(0,N.jsx)(ke,{}),(0,N.jsxs)(oe,{gap:10,children:[(0,N.jsx)(ue,{c:`brand`,fw:700,size:`xs`,tt:`uppercase`,lts:`0.12em`,children:n?.setup_required?`One-time setup`:`Secure workspace`}),(0,N.jsx)(xe,{order:1,fz:{base:28,sm:32},lh:1.08,children:we}),Te&&(0,N.jsx)(ue,{c:`dimmed`,size:`md`,lh:1.6,maw:390,children:Te})]}),(0,N.jsx)(`form`,{onSubmit:be,children:(0,N.jsxs)(oe,{gap:`md`,children:[(0,N.jsx)(Rc,{label:`Email`,placeholder:`you@company.com`,type:`email`,required:!0,value:p,onChange:e=>m(e.currentTarget.value),disabled:C,variant:`filled`,radius:`md`,size:`md`,autoFocus:!C}),n?.setup_required&&(0,N.jsx)(Rc,{label:`Display name`,placeholder:`Your display name`,value:h,onChange:e=>g(e.currentTarget.value),variant:`filled`,radius:`md`,size:`md`}),n?.setup_required&&(0,N.jsx)(Rc,{label:`Setup token`,placeholder:`from the setup URL printed at startup`,required:!0,value:_,onChange:e=>v(e.currentTarget.value),autoComplete:`one-time-code`,variant:`filled`,radius:`md`,size:`md`}),Se&&(0,N.jsxs)(oe,{gap:`xs`,children:[(0,N.jsx)(ue,{size:`sm`,fw:600,children:`Verification code`}),(0,N.jsx)(u,{ref:de,children:(0,N.jsx)(Lc,{length:6,type:`number`,oneTimeCode:!0,autoFocus:!0,value:x,onChange:S,onComplete:e=>void A(e),disabled:O,error:!!re,size:`md`,radius:`md`,"aria-label":`Verification code`,getInputProps:e=>({"aria-label":`Digit ${e+1}`})})}),(0,N.jsxs)(ne,{justify:`space-between`,gap:`xs`,children:[(0,N.jsxs)(ue,{c:`dimmed`,size:`xs`,children:[`Sent to `,p]}),(0,N.jsx)(ce,{variant:`subtle`,size:`compact-xs`,leftSection:(0,N.jsx)(cM,{size:12,weight:`bold`}),onClick:j,disabled:O,children:`Change email`})]}),(0,N.jsxs)(ne,{justify:`space-between`,gap:`xs`,children:[(0,N.jsx)(ue,{c:`dimmed`,size:`xs`,children:`Codes expire in 5 minutes`}),(0,N.jsx)(ce,{variant:`subtle`,size:`compact-xs`,onClick:()=>void ye(),disabled:O||_e>0,children:_e>0?`Resend in ${_e}s`:`Resend code`})]})]}),re&&(0,N.jsx)(Ce,{color:`bad`,radius:`md`,children:re}),Se?(0,N.jsx)(ce,{type:`submit`,size:`md`,radius:`md`,mt:4,loading:O,disabled:O||x.length<6,rightSection:(0,N.jsx)(uM,{size:17,weight:`bold`}),children:`Verify code`}):(0,N.jsx)(ce,{type:`submit`,size:`md`,radius:`md`,mt:4,loading:O,disabled:!n||!n.setup_required&&!n.smtp_configured,leftSection:n?.setup_required?(0,N.jsx)(PM,{size:17,weight:`bold`}):void 0,rightSection:n?.setup_required?void 0:(0,N.jsx)(uM,{size:17,weight:`bold`}),children:n?.setup_required?`Create admin`:`Send code`})]})})]})})}var QM=[`agent-threads`];async function $M(e){let t=await BM(e);if(!t.ok)throw Error(`Request failed (${t.status})`);return t.json()}var eN=new Set([`create_dashboard`,`edit_dashboard`,`replace_dashboard`,`restore_dashboard_version`]);function tN(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function nN(e){if(typeof e==`string`)try{let t=JSON.parse(e);if(tN(t))return t}catch{}}var rN=e=>Array.isArray(e)&&e.every(e=>typeof e==`string`),iN=e=>typeof e==`number`&&Number.isFinite(e)&&e>=0;function aN(e){return tN(e)&&typeof e.id==`string`&&[`ok`,`empty`,`error`,`invalid`,`not_run`,`partial`,`stale`].includes(String(e.status))&&(e.rows===void 0||iN(e.rows))&&(e.elapsed_ms===void 0||iN(e.elapsed_ms))&&(e.diagnosis===void 0||typeof e.diagnosis==`string`)&&(e.error===void 0||typeof e.error==`string`)}function oN(e){if(!tN(e)||!Number.isInteger(e.base_version)||Number(e.base_version)<0||!Number.isInteger(e.version)||Number(e.version)<1||!Array.isArray(e.changes)||typeof e.layout_changed!=`boolean`||e.dashboard_fields!==void 0&&!rN(e.dashboard_fields)||!e.changes.every(e=>tN(e)&&typeof e.panel_id==`string`&&typeof e.title==`string`&&[`added`,`changed`,`removed`].includes(String(e.kind))&&(e.fields===void 0||rN(e.fields)&&!e.fields.includes(`grid`))&&(e.position_changed===void 0||typeof e.position_changed==`boolean`)))return!1;let t=e.save_check;return tN(t)&&typeof t.checked==`boolean`&&iN(t.elapsed_ms)&&Array.isArray(t.panels)&&t.panels.every(e=>aN(e)&&Number.isInteger(e.rows)&&Number(e.rows)>=0)&&new Set(t.panels.map(e=>e.id)).size===t.panels.length&&(t.reason===void 0||typeof t.reason==`string`)&&(!t.checked||t.panels.every(e=>e.status!==`not_run`&&e.status!==`invalid`))}function sN(e,t,n){let r=-1;n.forEach((n,i)=>{n.role===`tool`&&n.toolCallId===e&&n.content===t&&(r=i)});let i=r<0?n.length:r,a=-1;if(n.slice(0,i).forEach((e,t)=>{e.role===`user`&&(a=t)}),a<0)return null;let o=n.slice(a+1,i).flatMap(e=>e.role===`assistant`?e.toolCalls??[]:[]).filter(t=>t.id===e),s=o.length===1?o[0].function.name:void 0;if(!s||!eN.has(s))return null;let c=nN(t),l=c?.dashboard,u=c?.receipt;return!c||c.error||c.isError||!tN(l)||typeof l.id!=`string`||!l.id||typeof l.name!=`string`||!l.name||!oN(u)||l.version!==u.version||r>=0&&n[r].error?null:{id:l.id,name:l.name,version:u.version,label:s===`create_dashboard`?`Created`:s===`restore_dashboard_version`?`Restored`:`Updated`,receipt:u}}var cN={viz:`chart type`,sql:`SQL`,content:`text`,x_unit:`x-axis unit`,options:`display options`,drill:`drill-down`,click:`click action`,time:`time range`,annotations:`markers`,better:`better direction`,reduce:`summary`,min:`minimum`,max:`maximum`},lN=e=>Object.hasOwn(cN,e)?cN[e]:e.replaceAll(`_`,` `),uN=e=>e.kind===`added`?`+ ${e.title}`:e.kind===`removed`?`− ${e.title}`:`~ ${e.title}${e.fields?.length?`: `+e.fields.map(lN).join(`, `):``}${e.position_changed?` · moved`:``}`;function dN(e){return[...e.changes.map(uN),...e.layout_changed?[`Layout adjusted`]:[],...e.dashboard_fields?.map(e=>`Dashboard: ${lN(e)}`)??[]]}function fN(e,t,n){return e.filter(e=>n.has(e.panel_id)&&!t.some(t=>t.panel_id===e.panel_id&&t.path===e.path))}var pN={schema:`Telemetry`,context:`Context`,draft:`Draft`,validation:`Validation`,preview:`Preview`,save:`Save`},mN=new Set([`get_intelligence_snapshot`,`query_telemetry`,`get_observability_overview`,`get_service_topology`,`get_service_dependencies`,`get_service_performance`,`inspect_trace`,`search_logs`]),hN=(e,t)=>Array.isArray(e)?e.flatMap(e=>tN(e)&&typeof e.path==`string`&&typeof e.message==`string`?[{panel_id:t,path:e.path,message:e.message}]:[]):[],gN=e=>{let t=nN(e)?.error;return tN(t)?t.code:void 0},_N=e=>e.role===`tool`&&gN(e.content)===`interrupted`,vN=e=>![`invalid`,`not_run`].includes(e.status);function yN(e,t){let n=e.findIndex(e=>e.id===t&&e.role===`user`);if(n<0)return null;let r=e.findIndex((e,t)=>t>n&&e.role===`user`),i=e.slice(n+1,r<0?void 0:r),a=new Set(i.flatMap(e=>e.role===`tool`&&gN(e.content)===`answer_only`?[e.toolCallId]:[])),o=i.flatMap((e,t)=>e.role===`assistant`?(e.toolCalls??[]).map(e=>({call:e,index:t})):[]).filter(({call:e})=>!a.has(e.id));if(!o.some(({call:e})=>eN.has(e.function.name)||e.function.name===`preview_panels`))return null;let s={schema:{state:`unobserved`},context:{state:`unobserved`},draft:{state:`unobserved`},validation:{state:`unobserved`},preview:{state:`unobserved`},save:{state:`unobserved`}},c={turn_id:t,stages:s,panel_titles:{},panels:[],problems:[],corrections:[],save_attempts:[],explanations:[],context_counts:{deploys:0,anomalies:0}},l=new Map,u=new Map;for(let{call:e}of o)l.set(e.id,(l.get(e.id)??0)+1);i.forEach((e,t)=>{if(e.role===`tool`){let n=u.get(e.toolCallId)??[];n.push({index:t,message:e}),u.set(e.toolCallId,n)}});let d=new Map,f=new Map,p=[],m,h=!1,g=!1,_=(e,t)=>{for(let n of fN(y.get(e)??[],t,new Set([e])))p.some(e=>e.panel_id===n.panel_id&&e.path===n.path)||p.push(n);y.set(e,t)},v=new Map,y=new Map,b=new Set,x=!1,S=!1;for(let{call:t,index:n}of o){if(l.get(t.id)!==1)continue;let r=t.function.name,i=nN(t.function.arguments),a=(u.get(t.id)??[]).filter(e=>e.index>n),o=a.length===1||eN.has(r)&&a.length>1&&a.slice(0,-1).every(e=>_N(e.message))?a.at(-1).message:void 0,C=o&&nN(o.content),w=!!C&&o?.role===`tool`&&!o.error&&!C.error&&!C.isError,T=o?w?`complete`:`failed`:`incomplete`;if(r===`get_telemetry_schema`&&(s.schema={state:T}),mN.has(r)){let e=o?.role===`tool`&&!o.error&&!C?.error&&!C?.isError&&typeof o.content==`string`&&o.content.length>0;if(s.context={state:o?e?`complete`:`failed`:`incomplete`},w)for(let[e,t]of[[`deploys`,[`deploys`,`deployments`]],[`anomalies`,[`anomalies`]]])for(let n of t)Array.isArray(C[n])&&(c.context_counts[e]+=C[n].length)}if(r===`preview_panels`||r===`create_dashboard`||r===`replace_dashboard`){let e=r===`preview_panels`?i?.panels:tN(i?.dashboard)?i.dashboard.panels:void 0;if(Array.isArray(e)){c.panel_count=e.length,s.draft={state:`complete`};for(let t of e)tN(t)&&typeof t.id==`string`&&typeof t.title==`string`&&t.title.trim()&&f.set(t.id,t.title)}}if(r===`preview_panels`){x=!0;let e=Array.isArray(i?.panels)?i.panels.flatMap(e=>tN(e)&&typeof e.id==`string`?[e.id]:[]):[];for(let t of e)v.set(t,{id:t,status:`not_run`});let t=w&&Array.isArray(C.panels)&&C.panels.every(aN)?C.panels:void 0,n=typeof C?.elapsed_ms==`number`&&C.elapsed_ms>=0?C.elapsed_ms:void 0;if(s.validation={state:t?t.some(e=>e.status===`invalid`||e.status===`not_run`)||hN(C?.problems,`dashboard`).length?`failed`:`complete`:T===`complete`?`failed`:T},s.preview={state:t?t.every(vN)?`complete`:`incomplete`:T===`complete`?`failed`:T,elapsed_ms:n},!t||e.length===0||t.length!==e.length||new Set(t.map(e=>e.id)).size!==e.length||t.some(t=>!e.includes(t.id))){S=e.length===0;for(let t of e)o&&b.add(t);continue}S=!1;for(let t of e)b.delete(t);for(let e of t){let t=hN(e.problems,e.id);if(e.status!==`not_run`)_(e.id,t);else{let n=y.get(e.id)??[];y.set(e.id,[...n,...t.filter(e=>!n.some(t=>t.path===e.path))])}v.set(e.id,e)}c.problems=[...y.values()].flat().concat(hN(C?.problems,`dashboard`))}if(eN.has(r)){let n=o&&sN(t.id,o.content,e),r=!!o&&_N(o),i=!r&&o?.role===`tool`&&(!!o.error||!!C?.error||!!C?.isError);if(g=!!i,h=!!o&&!n&&!i&&!r,s.save={state:n?`complete`:r?`interrupted`:i?`failed`:`incomplete`},n)for(let e of c.save_attempts)e.state===`failed`&&(e.state=`retried`);if(c.save_attempts.push({call_id:t.id,state:s.save.state}),n){m?.id!==n.id&&(m=n,d.clear());for(let e of n.receipt.changes){e.title.trim()&&f.set(e.panel_id,e.title);let t=d.get(e.panel_id);if(t?.kind===`added`&&e.kind===`removed`){d.delete(e.panel_id);continue}if(t?.kind===`added`){d.set(e.panel_id,{panel_id:e.panel_id,title:e.title,kind:`added`});continue}if(e.kind===`removed`){d.set(e.panel_id,e);continue}t&&e.kind===`changed`?d.set(e.panel_id,{...e,fields:[...new Set([...t.fields??[],...e.fields??[]])].sort(),position_changed:t.position_changed||e.position_changed}):d.set(e.panel_id,t?.kind===`removed`&&e.kind===`added`?{...e,kind:`changed`}:e)}let e=C?.dashboard,t=tN(e)?e.spec:void 0;if(tN(t)&&Array.isArray(t.panels))for(let e of t.panels)tN(e)&&typeof e.id==`string`&&typeof e.title==`string`&&e.title.trim()&&f.set(e.id,e.title);let r=c.saved?.id===n.id?c.saved.receipt:void 0;c.saved={...n,label:m.label,receipt:{...n.receipt,base_version:m.receipt.base_version,changes:[...d.values()],layout_changed:m.receipt.base_version!==0&&(n.receipt.layout_changed||!!r?.layout_changed),dashboard_fields:m.receipt.base_version===0?void 0:[...new Set([...r?.dashboard_fields??[],...n.receipt.dashboard_fields??[]])].sort()}},c.panel_count=n.receipt.save_check.panels.length,s.draft={state:`complete`};let i=new Set(n.receipt.save_check.panels.map(e=>e.id));for(let e of n.receipt.save_check.panels)vN(e)&&(_(e.id,[]),b.delete(e.id));p=p.filter(e=>i.has(e.panel_id)),c.problems=[...y.values()].flat().filter(e=>i.has(e.panel_id))}}}if(h)return null;c.panel_titles=Object.fromEntries(f),c.corrections=p.map(e=>({...e,title:f.get(e.panel_id)??e.panel_id}));let C=c.saved?new Set(c.saved.receipt.save_check.panels.map(e=>e.id)):void 0;if(c.panels=[...v.values()].filter(e=>!C||C.has(e.id)),x){let e=S||[...b].some(e=>!C||C.has(e)),t=c.panels.some(e=>e.status===`not_run`),n=c.problems.length>0;s.validation.state=e||n?`failed`:t?`incomplete`:`complete`,s.preview.state=e?`failed`:t||n||c.panels.some(e=>e.status===`invalid`)?`incomplete`:`complete`}let w=c.saved?.receipt.save_check;w&&!w.checked&&c.explanations.push(`Save check incomplete: ${w.reason||`Panels were not checked`}`);for(let e of w?.panels??c.panels)e.status!==`ok`&&c.explanations.push(`${f.get(e.id)??e.id}: ${e.status}${e.error||e.diagnosis?` — ${e.error||e.diagnosis}`:``}`);for(let e of c.problems)c.explanations.push(`${f.get(e.panel_id)??e.panel_id}: ${e.message}`);let T=Object.entries(s).filter(([,e])=>e.state===`incomplete`||e.state===`failed`).map(([e,t])=>`${pN[e]}: ${t.state}`);return T.length&&c.explanations.push(T.join(` · `)),s.save.state===`interrupted`&&c.explanations.push(`Save interrupted · outcome unknown`),g&&c.explanations.push(c.saved?`A later change failed; v${c.saved.version} remains saved`:`Save failed · dashboard was not saved`),c}var bN=(0,M.createContext)(null);function xN(){let e=(0,M.useContext)(bN);if(!e)throw Error(`Fanout app context is unavailable`);return e}var SN=`Build me a dashboard for my services, showing request volume, latency, and errors. Ask me which services to monitor first.`,CN={query_telemetry:{activity:`Querying telemetry…`,title:`Telemetry panels`},get_observability_overview:{activity:`Checking system health…`,title:`System health`},get_service_topology:{activity:`Mapping service dependencies…`,title:`Service map`},get_service_dependencies:{activity:`Tracing service dependencies…`,title:`Service dependencies`},list_panel_exemplars:{activity:`Finding example traces…`,title:`Example traces`},resolve_panel_variables:{activity:`Reading filter choices…`,title:`Filter choices`},query_panel_fragment:{activity:`Refreshing panels…`,title:`Panel refresh`},get_service_performance:{activity:`Reading performance signals…`,title:`Performance`},inspect_trace:{activity:`Inspecting a trace…`,title:`Trace lookup`},search_logs:{activity:`Searching logs…`,title:`Logs`},get_intelligence_snapshot:{activity:`Reviewing detected anomalies…`,title:`Detected anomalies`},get_telemetry_schema:{activity:`Reading what telemetry exists…`,title:`Telemetry discovery`},preview_panels:{activity:`Checking dashboard panels…`,title:`Panel check`},list_dashboards:{activity:`Looking through your dashboards…`,title:`Dashboards`},get_dashboard:{activity:`Opening your dashboard…`,title:`Dashboard`},create_dashboard:{activity:`Building your dashboard…`,title:`Dashboard save`},edit_dashboard:{activity:`Updating your dashboard…`,title:`Dashboard save`},replace_dashboard:{activity:`Redesigning your dashboard…`,title:`Dashboard save`},list_dashboard_versions:{activity:`Reading your dashboard history…`,title:`Dashboard history`},restore_dashboard_version:{activity:`Restoring your dashboard…`,title:`Dashboard`}};function wN(e){return CN[e]?.activity??`Working on it…`}function TN(e){return CN[e]?.title??`Analysis step`}function EN(e){switch(e){case`provider_unavailable`:return`Fanout could not reach the model provider. Please try again.`;case`step_limit`:return`Fanout reached its step limit before finishing. Try a narrower question.`;case`time_limit`:return`Fanout reached its 5-minute time limit. Try a smaller request.`;default:return`Fanout could not complete this analysis. Please try again.`}}function DN(e){let t=(0,M.useRef)(new Map);return(0,M.useMemo)(()=>{let n=new Map,r=new Set,i=e.flatMap((e,t)=>e.role===`user`?[t]:[]);i.forEach((a,o)=>{let s=i[o+1]??e.length,c=e[a],l=e[s-1];r.add(c.id);let u=t.current.get(c.id),d=u&&u.last===l&&u.length===s-a?u.receipt:yN(e.slice(a,s),c.id);oe.msecs?(e.seq=IN(n),e.msecs=t):(e.seq=e.seq+1|0,e.seq===0&&e.msecs++),e}function FN(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=IN(e),r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}function IN(e){return(e[6]&127)<<24|e[7]<<16|e[8]<<8|e[9]}function LN(){return NN()}var RN=[`dashboards`],zN=3e4;async function BN(e,t){let{json:n,...r}=t??{},i=new Headers(r.headers),a=r.body;n!==void 0&&(i.set(`content-type`,`application/json`),a=JSON.stringify(n));let o=await BM(e,{...r,headers:i,body:a}),s=await o.json().catch(()=>({}));if(!o.ok)throw new FM(s.message??`Request failed (${o.status})`,o.status,s.problems??[],s.code??``);return s}var VN=e=>`/api/dashboards/${encodeURIComponent(e)}`,HN=()=>BN(`/api/dashboards`).then(e=>e.dashboards),UN=(e,t)=>BN(VN(e),{signal:t}),WN=(e,t)=>BN(`${VN(e)}/versions`,{signal:t}).then(e=>e.versions),GN=(e,t,n)=>BN(`${VN(e)}/versions/${t}`,{signal:n}),KN=(e,t)=>BN(`${VN(e)}/versions/${t}/restore`,{method:`POST`}),qN=(e,t,n,r)=>BN(VN(e),{method:`PUT`,json:{spec:t,base_version:n,message:r}}),JN=(e,t,n,r)=>BN(VN(e),{method:`PATCH`,json:{operations:t,base_version:n,message:r}}),YN=(e,t)=>BN(`/api/panels/query`,{method:`POST`,json:e,signal:t}).then(e=>e.results),XN=e=>BN(`/api/telemetry/schema`,{signal:e}),ZN=(e,t)=>BN(`/api/annotations`,{method:`POST`,json:e,signal:t}),QN=(e,t)=>BN(`/api/panels/variables/resolve`,{method:`POST`,json:e,signal:t}).then(e=>e.options),$N=(e,t)=>BN(`/api/panels/exemplars`,{method:`POST`,json:e,signal:t});function eP(e,t){let n=new URLSearchParams({namespace:e.namespace??``,from:e.window_from,to:e.window_to,limit:`200`});return BN(`/api/traces/${encodeURIComponent(e.trace_id??``)}?${n}`,{signal:t})}function tP(){let{setColorScheme:e}=Nr(),t=Ir(`light`,{getInitialValueInEffect:!0}),n=t===`dark`?`light`:`dark`,[r,i]=(0,M.useState)(!1);return(0,N.jsx)(St,{label:`Switch to ${n} theme`,opened:r,children:(0,N.jsx)(Di,{variant:`subtle`,color:`gray`,"aria-label":`Switch to ${n} theme`,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),onFocus:()=>i(!0),onBlur:()=>i(!1),onClick:()=>{i(!1),e(n)},children:t===`dark`?(0,N.jsx)(AM,{size:17,weight:`bold`}):(0,N.jsx)(vM,{size:17,weight:`bold`})})})}var nP={home:`https://fanout.run/start/what-fanout-is`,ingest:`https://fanout.run/start/send-telemetry`,connect:`https://fanout.run/guides/connect-over-mcp`};async function rP(e,t){let n=new URLSearchParams({page_size:`30`});e&&n.set(`q`,e),t&&n.set(`cursor`,t);let r=await BM(`/api/agent/threads?${n}`);if(!r.ok)throw Error(`Unable to load chats (${r.status})`);return r.json()}function iP({agentAvailable:e,activeThreadID:t,activeDashboardID:n,autoFocusSearch:r=!1,onNewChat:i,onSelectThread:a,onDeletedThread:o,onSelectDashboard:s,onCreateDashboard:c,onInvestigateService:l,ref:u}){let d=SA(),[f,p]=(0,M.useState)(``),[m]=or(f.trim(),250),[h,g]=(0,M.useState)(null),[_,v]=(0,M.useState)(null),[y,b]=(0,M.useState)(``),[x,S]=(0,M.useState)(``),[w,T]=(0,M.useState)(!1),ee=(0,M.useRef)(null);(0,M.useImperativeHandle)(u,()=>({focusSearch:()=>ee.current?.focus()}),[]),(0,M.useEffect)(()=>{r&&requestAnimationFrame(()=>ee.current?.focus())},[r]);let E=Kj({queryKey:[...QM,m],queryFn:({pageParam:e})=>rP(m,e),initialPageParam:``,getNextPageParam:e=>e.next_cursor??void 0,enabled:e}),D=Gj({queryKey:RN,queryFn:HN,refetchInterval:3e4,staleTime:zN}),O=(0,M.useMemo)(()=>E.data?.pages.flatMap(e=>e.items)??[],[E.data]),te=(0,M.useMemo)(()=>uP(O),[O]),re=Gj({queryKey:[`telemetry-schema`,`1h`],queryFn:()=>$M(`/api/telemetry/schema?window=1h`),enabled:e&&!!m&&!!l,staleTime:6e4}),k=(0,M.useMemo)(()=>{if(!m)return[];let e=m.toLowerCase();return(re.data?.services??[]).map(e=>e.value).filter(t=>t.toLowerCase().includes(e)).slice(0,6)},[re.data,m]),ie=(0,M.useMemo)(()=>{let e=D.data??[],t=m.toLowerCase();return t?e.filter(e=>e.name.toLowerCase().includes(t)):e},[D.data,m]);function ae(e){S(``),b(e.title),g(e)}async function se(){if(h&&y.trim()){T(!0),S(``);try{let e=await BM(`/api/agent/threads/${encodeURIComponent(h.id)}`,{method:`PATCH`,headers:{"Content-Type":`application/json`},body:JSON.stringify({title:y.trim()})});if(!e.ok)throw Error(`Unable to rename chat (${e.status})`);await d.invalidateQueries({queryKey:QM}),g(null)}catch(e){S(e instanceof Error?e.message:`Unable to rename this chat.`)}finally{T(!1)}}}async function le(){if(_){T(!0),S(``);try{let e=await BM(`/api/agent/threads/${encodeURIComponent(_.id)}`,{method:`DELETE`});if(!e.ok)throw Error(`Unable to delete chat (${e.status})`);let t=_.id;v(null),await d.invalidateQueries({queryKey:QM}),await d.invalidateQueries({queryKey:RN}),o(t)}catch(e){S(e instanceof Error?e.message:`Unable to delete this chat.`)}finally{T(!1)}}}return(0,N.jsxs)(oe,{gap:`sm`,h:`100%`,component:`nav`,"aria-label":`Navigation`,children:[e&&(0,N.jsx)(ce,{leftSection:(0,N.jsx)(wM,{size:16,weight:`bold`}),onClick:i,children:`New chat`}),(0,N.jsx)(vt,{type:`auto`,offsetScrollbars:!0,flex:1,mx:-4,px:4,children:(0,N.jsxs)(oe,{gap:`lg`,pb:`sm`,children:[e&&(0,N.jsxs)(oe,{gap:4,children:[(0,N.jsx)(aP,{children:`Chats`}),E.isLoading&&(0,N.jsx)(je,{py:`md`,children:(0,N.jsx)(Ie,{size:`xs`})}),E.isError&&(0,N.jsx)(Ce,{color:`bad`,radius:`md`,p:`xs`,children:`Chats could not be loaded.`}),!E.isLoading&&!E.isError&&O.length===0&&(0,N.jsx)(ue,{c:`dimmed`,size:`sm`,px:`sm`,py:`xs`,children:m?`No matching chats`:`No chats yet`}),te.map(e=>(0,N.jsxs)(oe,{gap:2,children:[te.length>1&&(0,N.jsx)(ue,{c:`dimmed`,size:`xs`,px:`sm`,pt:4,children:e.label}),e.threads.map(e=>(0,N.jsx)(oP,{thread:e,active:e.id===t,onSelect:()=>a(e.id),onRename:()=>ae(e),onDelete:()=>{S(``),v(e)}},e.id))]},e.label)),E.hasNextPage&&(0,N.jsx)(ce,{variant:`subtle`,color:`gray`,size:`compact-sm`,loading:E.isFetchingNextPage,onClick:()=>void E.fetchNextPage(),children:`See all`})]}),e&&m&&l&&re.isLoading&&(0,N.jsx)(je,{py:`md`,children:(0,N.jsx)(Ie,{size:`xs`})}),e&&m&&l&&(re.isSuccess||re.isError)&&(0,N.jsxs)(oe,{gap:4,children:[(0,N.jsx)(aP,{children:`Services`}),re.isError&&(0,N.jsx)(ue,{c:`dimmed`,size:`sm`,px:`sm`,children:`Services could not be searched`}),re.isSuccess&&k.length===0&&(0,N.jsx)(ue,{c:`dimmed`,size:`sm`,px:`sm`,children:`No matching services`}),k.map(e=>(0,N.jsx)(C,{className:`rail-row`,p:`sm`,onClick:()=>l(e),children:(0,N.jsx)(ue,{size:`sm`,fw:500,truncate:!0,children:e})},e))]}),(0,N.jsxs)(oe,{gap:4,children:[(0,N.jsx)(aP,{children:`Dashboards`}),D.isLoading&&(0,N.jsx)(je,{py:`md`,children:(0,N.jsx)(Ie,{size:`xs`})}),D.isError&&(0,N.jsx)(Ce,{color:`bad`,radius:`md`,p:`xs`,children:`Dashboards could not be loaded.`}),!D.isLoading&&!D.isError&&m&&ie.length===0&&(0,N.jsx)(ue,{c:`dimmed`,size:`sm`,px:`sm`,py:`xs`,children:`No matching dashboards`}),ie.map(t=>{let r=t.id===n;return(0,N.jsxs)(oe,{gap:0,children:[(0,N.jsx)(C,{component:`a`,href:`/dashboards/${encodeURIComponent(t.id)}`,className:`rail-row`,"data-active":r||void 0,"aria-current":r?`page`:void 0,p:`sm`,onClick:e=>{e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),s(t.id))},children:(0,N.jsxs)(ne,{justify:`space-between`,gap:`sm`,wrap:`nowrap`,children:[(0,N.jsx)(ue,{size:`sm`,fw:r?600:500,truncate:!0,children:t.name}),t.is_default&&(0,N.jsx)(ts,{size:`xs`,variant:`light`,color:`gray`,children:`Default`})]})}),e&&t.origin&&(0,N.jsx)(C,{component:`a`,href:`/chat/${encodeURIComponent(t.origin.thread_id)}`,"data-request-provenance":!0,px:`sm`,pb:`xs`,onClick:e=>{e.button!==0||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||(e.preventDefault(),a(t.origin.thread_id))},children:(0,N.jsxs)(ue,{size:`xs`,c:`dimmed`,lineClamp:2,children:[`Built from: `,t.origin.request_excerpt]})})]},t.id)}),e&&(0,N.jsx)(ce,{variant:`subtle`,color:`gray`,size:`compact-sm`,justify:`flex-start`,leftSection:(0,N.jsx)(OM,{size:14,weight:`fill`}),onClick:c,children:D.data?.length===0?`New dashboard`:`Create with AI`})]})]})}),(0,N.jsx)(Rc,{ref:ee,value:f,onChange:e=>p(e.currentTarget.value),leftSection:(0,N.jsx)(gM,{size:15}),rightSection:(0,N.jsx)(As,{size:`xs`,children:`⌘K`}),rightSectionWidth:44,placeholder:`Search`,"aria-label":`Search chats, dashboards and services`,size:`sm`}),(0,N.jsx)(jc,{opened:h!==null,onClose:()=>!w&&g(null),title:`Rename chat`,centered:!0,children:(0,N.jsx)(`form`,{onSubmit:e=>{e.preventDefault(),se()},children:(0,N.jsxs)(oe,{children:[(0,N.jsx)(Rc,{label:`Name`,value:y,onChange:e=>b(e.currentTarget.value),maxLength:120,autoFocus:!0}),x&&(0,N.jsx)(Ce,{color:`bad`,children:x}),(0,N.jsxs)(ne,{justify:`flex-end`,children:[(0,N.jsx)(ce,{variant:`default`,onClick:()=>g(null),disabled:w,children:`Cancel`}),(0,N.jsx)(ce,{type:`submit`,loading:w,disabled:!y.trim(),children:`Save`})]})]})})}),(0,N.jsx)(jc,{opened:_!==null,onClose:()=>!w&&v(null),title:`Delete chat?`,centered:!0,children:(0,N.jsxs)(oe,{children:[(0,N.jsxs)(ue,{size:`sm`,children:[`This permanently removes `,(0,N.jsx)(ue,{span:!0,fw:650,children:_?.title}),` and its saved messages.`]}),x&&(0,N.jsx)(Ce,{color:`bad`,children:x}),(0,N.jsxs)(ne,{justify:`flex-end`,children:[(0,N.jsx)(ce,{variant:`default`,onClick:()=>v(null),disabled:w,children:`Cancel`}),(0,N.jsx)(ce,{color:`bad`,loading:w,onClick:()=>void le(),children:`Delete`})]})]})})]})}function aP({children:e}){return(0,N.jsx)(ue,{c:`dimmed`,size:`xs`,fw:700,tt:`uppercase`,lts:`0.08em`,px:`sm`,children:e})}function oP({thread:e,active:t,onSelect:n,onRename:r,onDelete:i}){return(0,N.jsx)(u,{"data-active":t||void 0,className:`rail-row`,children:(0,N.jsxs)(ne,{gap:2,wrap:`nowrap`,children:[(0,N.jsx)(C,{onClick:n,"aria-current":t?`page`:void 0,p:`sm`,flex:1,style:{minWidth:0},children:(0,N.jsxs)(oe,{gap:0,children:[(0,N.jsx)(ue,{size:`sm`,fw:t?600:500,truncate:!0,children:e.title}),(0,N.jsx)(ue,{c:`dimmed`,size:`xs`,children:dP(e.updated_at)})]})}),(0,N.jsxs)(hc,{position:`bottom-end`,withinPortal:!0,children:[(0,N.jsx)(hc.Target,{children:(0,N.jsx)(Di,{className:`rail-row-actions`,variant:`subtle`,color:`gray`,size:`sm`,mr:4,"aria-label":`Actions for ${e.title}`,children:(0,N.jsx)(mM,{size:18,weight:`bold`})})}),(0,N.jsxs)(hc.Dropdown,{children:[(0,N.jsx)(hc.Item,{leftSection:(0,N.jsx)(bM,{size:15}),onClick:r,children:`Rename`}),(0,N.jsx)(hc.Item,{color:`bad`,leftSection:(0,N.jsx)(MM,{size:15}),onClick:i,children:`Delete`})]})]})]})})}function sP(e){return e.includes(`T`)?new Date(e):new Date(`${e.replace(` `,`T`)}Z`)}function cP(e){return new Date(e.getFullYear(),e.getMonth(),e.getDate()).getTime()}var lP=[`Today`,`Yesterday`,`Previous 7 days`,`Older`];function uP(e){let t=cP(new Date),n=new Map;for(let r of e){let e=Math.floor((t-cP(sP(r.updated_at)))/864e5),i=e<=0?`Today`:e===1?`Yesterday`:e<=7?`Previous 7 days`:`Older`,a=n.get(i)??[];a.push(r),n.set(i,a)}return lP.filter(e=>n.has(e)).map(e=>({label:e,threads:n.get(e)}))}function dP(e){let t=sP(e),n=cP(new Date);return Math.floor((n-cP(t))/864e5)<=1?new Intl.DateTimeFormat(void 0,{hour:`numeric`,minute:`2-digit`}).format(t):new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`}).format(t)}function fP({children:e}){let{agentAvailable:t,threadID:n,threadMissing:r,newThread:i,selectThread:a,openChat:o}=xN(),s=ze(),c=Un({select:e=>e.location.pathname}),{dashboardId:l}=hn({strict:!1}),u=c===`/chat`||c.startsWith(`/chat/`),[d,f]=br(!1),[p,m]=(0,M.useState)(!1),[h,g]=(0,M.useState)(``),_=(0,M.useRef)(null),v=ie(`(max-width: 62em)`),y=(0,M.useRef)(v);y.current=v,(0,M.useEffect)(()=>{f.close()},[c]),(0,M.useEffect)(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`&&(e.preventDefault(),y.current?(m(!0),f.open()):_.current?.focusSearch())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let b={agentAvailable:t,activeThreadID:u&&!r&&c!==`/chat`?n:void 0,activeDashboardID:l,onNewChat:i,onSelectThread:a,onDeletedThread:e=>{e===n&&i()},onSelectDashboard:e=>void s({to:`/dashboards/$dashboardId`,params:{dashboardId:e},search:{}}),onCreateDashboard:()=>o(SN),onInvestigateService:e=>o(`Investigate the ${e} service. Explain its errors and latency.`)};return(0,N.jsxs)(Vo,{header:{height:52},navbar:{width:256,breakpoint:`md`,collapsed:{mobile:!0}},padding:0,children:[(0,N.jsx)(Vo.Header,{children:(0,N.jsxs)(ne,{h:`100%`,px:{base:`sm`,sm:`md`},justify:`space-between`,wrap:`nowrap`,children:[(0,N.jsxs)(ne,{gap:`sm`,wrap:`nowrap`,children:[(0,N.jsx)(is,{hiddenFrom:`md`,opened:d,onClick:()=>{m(!1),f.toggle()},size:`sm`,"aria-label":d?`Close navigation`:`Open navigation`}),(0,N.jsx)(ke,{size:`small`})]}),(0,N.jsxs)(ne,{gap:`xs`,wrap:`nowrap`,children:[(0,N.jsx)(St,{label:`Documentation`,children:(0,N.jsx)(Di,{component:`a`,href:nP.home,target:`_blank`,rel:`noopener noreferrer`,variant:`subtle`,color:`gray`,"aria-label":`Documentation`,children:(0,N.jsx)(fM,{size:17,weight:`bold`})})}),(0,N.jsx)(tP,{}),(0,N.jsx)(pP,{onError:g})]})]})}),(0,N.jsx)(Vo.Navbar,{p:`sm`,children:(0,N.jsx)(iP,{ref:_,...b})}),(0,N.jsx)(Ds,{opened:d,onClose:f.close,hiddenFrom:`md`,size:288,padding:`sm`,title:(0,N.jsx)(ke,{size:`small`}),overlayProps:{backgroundOpacity:.24,blur:1},children:(0,N.jsx)(iP,{...b,autoFocusSearch:d&&p})}),(0,N.jsxs)(Vo.Main,{children:[h&&(0,N.jsx)(Ce,{color:`bad`,m:`md`,withCloseButton:!0,onClose:()=>g(``),children:h}),e]})]})}function pP({onError:e}){let t=ze(),n=GM(),r=(n.display_name.trim()||n.email.trim()||`?`).charAt(0).toUpperCase();return(0,N.jsxs)(hc,{position:`bottom-end`,withinPortal:!0,shadow:`md`,children:[(0,N.jsx)(hc.Target,{children:(0,N.jsx)(Di,{variant:`subtle`,color:`gray`,size:`lg`,radius:`xl`,"aria-label":`${r} account menu`,children:(0,N.jsx)(Qo,{size:26,radius:`xl`,color:`brand`,children:r})})}),(0,N.jsxs)(hc.Dropdown,{children:[(0,N.jsx)(hc.Label,{children:n.email||`Signed in`}),(0,N.jsx)(hc.Item,{leftSection:(0,N.jsx)(SM,{size:15}),onClick:()=>void t({to:`/settings`}),children:`Connect telemetry`}),(0,N.jsx)(hc.Divider,{}),(0,N.jsx)(hc.Item,{leftSection:(0,N.jsx)(EM,{size:15}),onClick:()=>void VM().catch(t=>e(t instanceof Error?t.message:`Sign-out failed — your session is still active.`)),children:`Sign out`})]})]})}function mP(){let{agent_available:e}=UM(),t=ze(),n=SA(),{threadId:r}=hn({strict:!1}),[i,a]=(0,M.useState)(LN),o=(0,M.useRef)(new Set),s=r??i,[c,l]=(0,M.useState)([]),[u,d]=(0,M.useState)({}),[f,p]=(0,M.useState)(``),[m,h]=(0,M.useState)(!1),[g,_]=(0,M.useState)(!1),[v,y]=(0,M.useState)(``),[b,x]=(0,M.useState)(!1),S=(0,M.useRef)(!1),[C,w]=(0,M.useState)(``),[T,ee]=(0,M.useState)(``),[E,D]=(0,M.useState)(0),O=(0,M.useRef)(null),te=(0,M.useRef)({}),ne=(0,M.useRef)(null),re=(0,M.useRef)(new Map),k=(0,M.useMemo)(()=>new bA({url:`/api/agent/runs`,threadId:s,fetch:(e,t)=>BM(e,t)}),[s]),ie=!e||f===s;function ae(){re.current.clear(),y(``)}function oe(e){return S.current||e instanceof Error&&e.name===`AbortError`}(0,M.useEffect)(()=>{let t=!0;if(l([]),te.current={},d({}),p(``),h(!1),_(!1),S.current=!1,x(!1),ae(),ee(``),!e){p(s);return}!r||o.current.has(s)?(k.setMessages([]),p(s)):BM(`/api/agent/threads/${encodeURIComponent(s)}`).then(async e=>{if(e.status===404)return null;if(!e.ok)throw Error(`Unable to load thread (${e.status})`);return e.json()}).then(e=>{if(t){if(e===null){h(!0),p(s);return}k.setMessages(e.messages??[]),l(e.messages??[]),p(s)}}).catch(()=>{t&&(O.current=null,ee(`This chat could not be restored. Start a new chat or try again.`))});let i=k.subscribe({onMessagesChanged:({messages:e})=>l([...e]),onRunInitialized:()=>{S.current=!1,x(!1),_(!0),ee(``)},onTextMessageContentEvent:({event:e})=>{e.delta&&y(``)},onToolCallStartEvent:({event:e})=>{re.current.set(e.toolCallId,wN(e.toolCallName)),y(wN(e.toolCallName))},onToolCallResultEvent:({event:e,messages:t})=>{re.current.delete(e.toolCallId),y([...re.current.values()].at(-1)??`Analyzing your system`);let r=sN(e.toolCallId,e.content,t);r&&(n.invalidateQueries({queryKey:RN}),n.invalidateQueries({queryKey:[`dashboard`,r.id]}),n.invalidateQueries({queryKey:[`dashboard-versions`,r.id]}))},onRunErrorEvent:({event:e})=>{e.code===`abort`||S.current?(ee(``),x(!0)):(console.warn(`Agent run error`,e.code),ee(EN(e.code))),_(!1),ae()},onRunFinalized:({messages:e})=>{let t=[...e];l(t),d(e=>{let n={...e};for(let e of t)e.role===`assistant`&&!n[e.id]&&(n[e.id]=Date.now());return n}),_(!1),ae(),o.current.delete(s),n.invalidateQueries({queryKey:QM})},onRunFailed:e=>{oe(e.error)?(ee(``),x(!0)):(console.error(`Agent run failed`,e),ee(EN())),_(!1),ae(),o.current.delete(s),n.invalidateQueries({queryKey:QM})}});return()=>{t=!1,i.unsubscribe(),k.abortRun()}},[k,e,n,E,s]),(0,M.useEffect)(()=>{if(!e)return;let n=e=>{let n=e.target,i=n?.matches(`input, textarea, [contenteditable='true']`);e.key===`/`&&!i&&(e.preventDefault(),r?requestAnimationFrame(()=>ne.current?.focus()):t({to:`/chat`}).then(()=>requestAnimationFrame(()=>ne.current?.focus()))),e.key===`Escape`&&n===ne.current&&(w(``),ne.current?.blur())};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t,r]);async function se(){_(!0),ee(``);try{let{context:e=[],...t}=te.current;await k.runAgent({context:e,forwardedProps:t})}catch(e){oe(e)?(ee(``),x(!0)):(console.error(`Agent run failed`,e),ee(EN())),_(!1),ae(),o.current.delete(s)}}async function ce(n,i){let a=n.trim();if(!e||!a||g||!ie||m)return;te.current={...i},r||(o.current.add(s),t({to:`/chat/$threadId`,params:{threadId:s},replace:!0}));let c={id:LN(),role:`user`,content:a};k.addMessage(c),l([...k.messages]),d(e=>({...e,[c.id]:Date.now()})),w(``),await se()}(0,M.useEffect)(()=>{let e=O.current;ie&&r&&e&&(O.current=null,ce(e.text,e.options))},[ie,r,s]);function le(e){e.preventDefault(),ce(C)}function ue(){S.current=!0,ee(``),x(!0),k.abortRun(),_(!1),ae(),o.current.delete(s)}function de(){!g&&k.messages.some(e=>e.role===`user`)&&se()}function fe(n,r){if(!e)return;let i=LN();o.current.add(i),O.current=n?{text:n,options:{...r}}:null,t({to:`/chat/$threadId`,params:{threadId:i}})}function pe(){k.abortRun(),O.current=null,te.current={},a(LN()),t({to:`/chat`})}function me(e){O.current=null,te.current={},t({to:`/chat/$threadId`,params:{threadId:e}})}function he(){D(e=>e+1)}return(0,N.jsx)(bN.Provider,{value:{agentAvailable:e,threadID:s,threadMissing:m,messages:c,messageTimes:u,ready:ie,running:g,activity:v,stopped:b,input:C,setInput:w,error:T,inputRef:ne,send:ce,submit:le,stop:ue,retry:de,reloadThread:he,openChat:fe,newThread:pe,selectThread:me},children:(0,N.jsx)(fP,{children:(0,N.jsx)(Nn,{})})})}function hP(){let e=(0,M.useMemo)(()=>new Mj,[]);return(0,N.jsx)(CA,{client:e,children:(0,N.jsx)(ZM,{children:(0,N.jsx)(mP,{})})})}var gP=xn({component:hP,notFoundComponent:()=>(0,N.jsx)(Ve,{to:`/`,replace:!0})}),_P=Sn(`/`)({component:Cn(()=>tt(()=>import(`./routes-D2AdaqvY.js`),__vite__mapDeps([0,1,2])),`component`)}),vP=Sn(`/settings`)({component:Cn(()=>tt(()=>import(`./settings-og0efxIm.js`),__vite__mapDeps([3,1,4,5,6])),`component`)}),yP=Sn(`/chat/`)({component:Cn(()=>tt(()=>import(`./chat.index-DOzBCpD0.js`),__vite__mapDeps([7,8,1,4,9,5,10])),`component`)}),bP=Sn(`/chat/$threadId`)({component:Cn(()=>tt(()=>import(`./chat._threadId-DOzBCpD0.js`),__vite__mapDeps([11,8,1,4,9,5,10])),`component`)});function xP(e){try{let t=typeof e==`string`?e:JSON.stringify(e);if(!t||t.length>4096)return;let n=typeof e==`string`?JSON.parse(e):e;if(!n||typeof n!=`object`)return;let r=n;return typeof r.panel_id!=`string`||!/^([a-z][a-z0-9_]{0,39})$/.test(r.panel_id)||r.kind!==`traces`&&r.kind!==`logs`||typeof r.from!=`string`||typeof r.to!=`string`||!Number.isFinite(Date.parse(r.from))||!Number.isFinite(Date.parse(r.to))||Date.parse(r.from)>=Date.parse(r.to)||Date.parse(r.to)-Date.parse(r.from)>2592e6||typeof r.window_from!=`string`||typeof r.window_to!=`string`||!Number.isFinite(Date.parse(r.window_from))||!Number.isFinite(Date.parse(r.window_to))||Date.parse(r.window_from)>=Date.parse(r.window_to)||Date.parse(r.window_to)-Date.parse(r.window_from)>2592e6||Date.parse(r.from)Date.parse(r.window_to)||!r.dimensions||Array.isArray(r.dimensions)||typeof r.dimensions!=`object`||Object.keys(r.dimensions).length>3||Object.values(r.dimensions).some(e=>typeof e!=`string`||e.length>500)||r.trace_id!==void 0&&(typeof r.trace_id!=`string`||r.trace_id.length>128)||r.namespace!==void 0&&(typeof r.namespace!=`string`||r.namespace.length>200)||r.bucket&&(!Number.isFinite(r.bucket.lower)||r.bucket.lower<0||r.bucket.upper!==void 0&&(!Number.isFinite(r.bucket.upper)||r.bucket.upper<=r.bucket.lower))?void 0:{panel_id:r.panel_id,kind:r.kind,from:r.from,to:r.to,window_from:r.window_from,window_to:r.window_to,dimensions:r.dimensions,trace_id:r.trace_id,namespace:r.namespace,bucket:r.bucket}}catch{return}}function SP(e,t,n){if(!e.drill&&e.viz!==`service_map`&&!n.trace_id||t.from_ms===void 0||t.to_ms===void 0)return;let r=t.from_ms,i=t.to_ms;if(n.from!==void 0&&n.to!==void 0&&(r=Math.max(r,Date.parse(n.from)),i=Math.min(i,Date.parse(n.to))),n.time!==void 0&&!n.trace_id){let e=/^(\d+)(s|m|h|d)$/.exec(t.interval??``),a=e?Number(e[1])*{s:1e3,m:6e4,h:36e5,d:864e5}[e[2]]:6e4;r=Math.max(r,n.time),i=Math.min(i,n.time+a)}return xP(JSON.stringify({panel_id:e.id,kind:n.trace_id||e.viz===`service_map`?`traces`:e.drill,from:n.from&&Date.parse(n.from)===r?n.from:new Date(r).toISOString(),to:n.to&&Date.parse(n.to)===i?n.to:new Date(i).toISOString(),window_from:new Date(t.from_ms).toISOString(),window_to:new Date(t.to_ms).toISOString(),dimensions:n.dimensions,trace_id:n.trace_id,namespace:n.namespace,bucket:n.bucket}))}function CP(e){let t=new URLSearchParams;for(let[n,r]of Object.entries(e))for(let e of Array.isArray(r)?r:[r]){if(e===void 0)continue;let r=typeof e==`string`&&/^[{"]/.test(e);t.append(n,r||typeof e==`object`&&e?JSON.stringify(e):String(e))}let n=t.toString();return n?`?${n}`:``}function wP(e){let t=Object.create(null),n=e=>{if(e.startsWith(`{`)||e.startsWith(`"`))try{let t=JSON.parse(e);if(typeof t==`string`)return/^[{"]/.test(t)?t:e;if(typeof t==`object`&&t&&!Array.isArray(t))return t}catch{}return e},r=new URLSearchParams(e);for(let e of new Set(r.keys())){let i=r.getAll(e).map(n);t[e]=i.length===1?i[0]:i}return t}var TP=[`5m`,`15m`,`1h`,`3h`,`6h`,`12h`,`24h`,`2d`,`7d`,`30d`],EP=[`off`,`10s`,`30s`,`1m`,`5m`],DP=e=>{if(typeof e!=`string`||!/^\d{4}-\d{2}-\d{2}[Tt](?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:[Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.test(e)||Number.isNaN(Date.parse(e)))return!1;let[t,n,r]=e.slice(0,10).split(`-`).map(Number),i=new Date(0);return i.setUTCFullYear(t,n-1,r),i.setUTCHours(0,0,0,0),i.getUTCFullYear()===t&&i.getUTCMonth()===n-1&&i.getUTCDate()===r},OP=e=>typeof e==`string`||typeof e==`number`||typeof e==`boolean`?String(e):void 0;function kP(e){let t={};typeof e.range==`string`&&TP.includes(e.range)?t.range=e.range:DP(e.from)&&DP(e.to)&&Date.parse(e.from)typeof e==`string`)&&(i[e]=t)}}else{let t=OP(n);t!==void 0&&(i[e]=t)}}}Object.keys(i).length>0&&(t.vars=i);let a=xP(e.drill);return a&&(t.drill=JSON.stringify(a)),t}function AP(e){let t={};e.drill&&(t.drill=JSON.parse(e.drill)),e.range&&(t.range=e.range),e.from&&e.to&&(t.from=e.from,t.to=e.to),e.compare&&(t.compare=e.compare),e.view&&(t.view=e.view),e.edit&&(t.edit=e.edit);for(let[n,r]of Object.entries(e.vars??{}))t[`var-${n}`]=Array.isArray(r)?{values:r}:r;return t}function jP(e,t){let n=new URL(e);return n.search=CP(AP({...kP(wP(n.search)),drill:JSON.stringify(t)})),n.href}function MP(e,t){let n=e.time.refresh??`30s`;return t.from&&t.to?{from:t.from,to:t.to,refresh:n}:t.range?{range:t.range,refresh:n}:{...e.time,refresh:n}}var NP=Sn(`/dashboards/`)({component:Cn(()=>tt(()=>import(`./dashboards.index-CoF5-Lh4.js`),__vite__mapDeps([12,1,2,13,4,9,5,10,6])),`component`),validateSearch:e=>AP(kP(e))}),PP=Sn(`/dashboards/$dashboardId`)({component:Cn(()=>tt(()=>import(`./dashboards._dashboardId-3NqeTTXq.js`),__vite__mapDeps([14,1,2,13,4,9,5,10,6])),`component`),validateSearch:e=>AP(kP(e))}),FP=_P.update({id:`/`,path:`/`,getParentRoute:()=>gP}),IP=vP.update({id:`/settings`,path:`/settings`,getParentRoute:()=>gP}),LP=yP.update({id:`/chat/`,path:`/chat/`,getParentRoute:()=>gP}),RP=bP.update({id:`/chat/$threadId`,path:`/chat/$threadId`,getParentRoute:()=>gP}),zP=NP.update({id:`/dashboards/`,path:`/dashboards/`,getParentRoute:()=>gP}),BP={IndexRoute:FP,SettingsRoute:IP,ChatThreadIdRoute:RP,DashboardsDashboardIdRoute:PP.update({id:`/dashboards/$dashboardId`,path:`/dashboards/$dashboardId`,getParentRoute:()=>gP}),ChatIndexRoute:LP,DashboardsIndexRoute:zP},VP=zn({routeTree:gP._addFileChildren(BP)._addFileTypes(),parseSearch:wP,stringifySearch:CP,defaultPreload:`intent`,scrollRestoration:!0}),HP=[`#fafafa`,`#e6e4de`,`#bfbdb6`,`#8b8e99`,`#565b69`,`#1d2433`,`#131721`,`#0b0e14`,`#080a10`,`#05070b`],UP=[`#f3ecfd`,`#ece3fb`,`#dcc9f7`,`#d2a6ff`,`#bf94ec`,`#a97ce0`,`#9163d6`,`#7c4dcc`,`#5b32a3`,`#40236f`],WP=[`#eefbe6`,`#dcf7cc`,`#c2f0a6`,`#a5e880`,`#8fe06c`,`#7fd962`,`#66c04b`,`#4f9c3a`,`#3b7a2c`,`#2a5a1f`],GP=[`#fff5e6`,`#ffe9c9`,`#ffd79b`,`#ffc571`,`#ffbc62`,`#ffb454`,`#ef9c33`,`#c87d21`,`#9c5f16`,`#74460f`],KP=[`#fdecee`,`#fbd9dc`,`#f8b6bc`,`#f59099`,`#f37d87`,`#f26d78`,`#e04d5a`,`#c03642`,`#96262f`,`#6f1a21`],qP=[`#e8f6ff`,`#ccebff`,`#a3daff`,`#7dcbff`,`#66c5ff`,`#59c2ff`,`#33a7e6`,`#1e86bd`,`#146694`,`#0d4a6d`],JP={dark:{text:`#bfbdb6`,muted:`#8b8e99`,grid:`#1d2433`,surface:`#131721`,border:`#626777`},light:{text:`#4a5058`,muted:`#6b7280`,grid:`#eceef0`,surface:`#fcfcfc`,border:`#8c939d`}},YP={dark:[`#3987e5`,`#d95926`,`#199e70`,`#9085e9`,`#c98500`,`#d55181`],light:[`#2a78d6`,`#eb6834`,`#1baf7a`,`#4a3aa7`,`#eda100`,`#e87ba4`]},XP={micro:11,small:12,body:14,title:16,section:22,page:32},ZP={display:`"Geist Mono Variable", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace`,body:`"Geist Variable", ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`},QP={brand:UP,ok:WP,warn:GP,bad:KP,info:qP},$P={light:7,dark:5};function eF(e){let t=e.replace(`#`,``),n=t.length===3?[...t].map(e=>e+e).join(``):t,r=e=>{let t=parseInt(n.slice(e,e+2),16)/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4};return .2126*r(0)+.7152*r(2)+.0722*r(4)}function tF(e){let t=eF(e),n=1.05/(t+.05);return(t+.05)/.05>n?`var(--mantine-color-black)`:`var(--mantine-color-white)`}function nF(e){return Object.fromEntries(Object.entries(QP).map(([t,n])=>[`--fanout-color-${t}-contrast`,tF(n[$P[e]])]))}function rF(e){return t=>{let n=t.color??oF.primaryColor,r=e({...t,color:n}),i=t.variant===`filled`||t.variant===void 0;return t.autoContrast===!1||!i||!Object.hasOwn(QP,n)?r:{...r,color:`var(--fanout-color-${n}-contrast)`}}}var iF=.25,aF={xs:9,sm:10,md:11,lg:13,xl:16},oF={primaryColor:`brand`,primaryShade:$P,autoContrast:!0,luminanceThreshold:iF,colors:{dark:HP,brand:UP,ok:WP,warn:GP,bad:KP,info:qP},defaultRadius:`md`,fontFamily:ZP.body,fontFamilyMonospace:ZP.display,headings:{fontFamily:ZP.body,fontWeight:`600`},cursorType:`pointer`,components:{Tabs:{styles:(e,t)=>({tab:lF(t.color,`--tabs-text-color`)})},Pagination:{styles:(e,t)=>({control:lF(t.color,`--pagination-active-color`)})},Badge:{vars:(e,t)=>({root:cF(t.size)})},Menu:{defaultProps:{withInitialFocusPlaceholder:!1}},Drawer:{defaultProps:{closeButtonProps:{"aria-label":`Close`}}},Modal:{defaultProps:{closeButtonProps:{"aria-label":`Close`}}}}},sF=()=>({variables:{"--mantine-color-error":`var(--mantine-color-bad-filled)`},light:{"--mantine-color-dimmed":JP.light.muted,...nF(`light`)},dark:nF(`dark`)});function cF(e){let t=aF[e??`md`];return t===void 0||t>=XP.micro?{}:{"--badge-fz":`${XP.micro/16}rem`}}function lF(e,t){return!e||e===oF.primaryColor?{[t]:`var(--fanout-color-${oF.primaryColor}-contrast)`}:{}}var uF=rF(ee),dF=Xr({...oF,variantColorResolver:uF});(0,Kc.createRoot)(document.getElementById(`root`)).render((0,N.jsx)(M.StrictMode,{children:(0,N.jsx)(Yr,{theme:dF,defaultColorScheme:`auto`,cssVariablesResolver:sF,children:(0,N.jsx)(Hn,{router:VP})})}));export{mM as $,Ir as $t,JN as A,U as At,xN as B,Rc as Bt,RN as C,K as Ct,GN as D,Ub as Dt,eP as E,Ob as Et,QN as F,vy as Ft,eN as G,ss as Gt,_N as H,hc as Ht,KN as I,g_ as It,GM as J,eo as Jt,tN as K,ts as Kt,SN as L,f_ as Lt,$N as M,Sb as Mt,YN as N,Yy as Nt,HN as O,px as Ot,qN as P,wy as Pt,bM as Q,Qr as Qt,TN as R,d_ as Rt,nP as S,q as St,XN as T,fb as Tt,pN as U,As as Ut,dN as V,jc as Vt,nN as W,Ds as Wt,FM as X,yi as Xt,BM as Y,Di as Yt,MM as Z,ci as Zt,TP as _,hb as _t,JP as a,ln as an,OA as at,SP as b,Pb as bt,WP as c,SA as ct,GP as d,db as dt,kr as en,Gj as et,PP as f,Rb as ft,kP as g,Eb as gt,MP as h,G as ht,UP as i,Gn as in,IA as it,ZN as j,Ab as jt,WN as k,Ib as kt,YP as l,Vy as lt,jP as m,_b as mt,eF as n,tr as nn,ij as nt,ZP as o,Qt as on,BA as ot,NP as p,yb as pt,$M as q,Ho as qt,KP as r,Xn as rn,ej as rt,qP as s,tn as sn,XA as st,tF as t,yr as tn,Oj as tt,XP as u,By as ut,EP as v,Mb as vt,UN as w,wb as wt,xP as x,cx as xt,AP as y,Gy as yt,DN as z,Zf as zt}; \ No newline at end of file diff --git a/internal/ui/dist/assets/mcp-app-frame-B4umpmdI.js b/internal/ui/dist/assets/mcp-app-frame-B4umpmdI.js deleted file mode 100644 index b0a6137b..00000000 --- a/internal/ui/dist/assets/mcp-app-frame-B4umpmdI.js +++ /dev/null @@ -1,57 +0,0 @@ -import{i as e,r as t,s as n}from"./useRouter-ByJ6_rwb.js";import{C as r,d as i,f as a,p as o,u as s,y as c}from"./brand-DUaZkIz1.js";import{n as l}from"./chat-CgHTI0Fx.js";import{$ as u,Ct as d,Dt as f,Et as p,Ot as m,St as h,Tt as g,Ut as _,Vt as v,_t as y,at as b,bt as x,ct as S,dt as ee,et as C,ft as w,gt as T,ht as E,it as te,kt as ne,lt as re,mt as ie,nt as D,ot as O,pt as k,rt as ae,st as A,tt as oe,ut as se,vt as ce,wt as le,xt as j,yt as M,z as ue}from"./index-BZ6fASDi.js";var de={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`},fe;fe||={};function pe(e){return m(C,e)}function me(e){return f(u,e)}function he(e){return p(oe,e)}function N(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function P(e,t){if(!Array.isArray(e))return[];let n=new Set(t);return e.filter(e=>{if(typeof e!=`string`||/[\s;'\"]/.test(e))return!1;let t=e.match(/^([a-z]+):\/\/([^/]+)$/i);return!!(t&&n.has(t[1].toLowerCase()))})}function ge(e){let t=N(N(N(e)?.ui)?.csp),n=P(t?.connectDomains,[`http`,`https`,`ws`,`wss`]),r=P(t?.resourceDomains,[`http`,`https`]),i=P(t?.frameDomains,[`http`,`https`]),a=P(t?.baseUriDomains,[`http`,`https`]),o=r.length?` ${r.join(` `)}`:``,s=[`default-src 'none'`,`worker-src blob:`,`script-src 'self' 'unsafe-inline'${o}`,`style-src 'self' 'unsafe-inline'${o}`,`img-src 'self' data:${o}`,`media-src 'self' data:${o}`,`font-src 'self' data:${o}`,`connect-src ${n.length?n.join(` `):`'none'`}`];return i.length&&s.push(`frame-src ${i.join(` `)}`),a.length&&s.push(`base-uri ${a.join(` `)}`),`${s.join(`; `)};`}var _e=Object.create,ve=Object.defineProperty,ye=Object.getOwnPropertyDescriptor,be=Object.getOwnPropertyNames,F=Object.getPrototypeOf,xe=Object.prototype.hasOwnProperty,Se=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ce=(e,t)=>{let n={};for(var r in e)ve(n,r,{get:e[r],enumerable:!0});return t&&ve(n,Symbol.toStringTag,{value:`Module`}),n},we=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=be(t),a=0,o=i.length,s;at[e]).bind(null,s),enumerable:!(r=ye(t,s))||r.enumerable});return e},Te=(e,t,n)=>(n=e==null?{}:_e(F(e)),we(t||!e||!e.__esModule?ve(n,`default`,{value:e,enumerable:!0}):n,e)),Ee=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]),De=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),Oe=new Set([`https://json-schema.org/draft-07/schema`,`http://json-schema.org/draft-07/schema`]),ke=new Set([`https://json-schema.org/draft-06/schema`,`http://json-schema.org/draft-06/schema`]);function Ae(e){return typeof e==`string`&&De.has(e.replace(/#$/,``))}function je(e,t){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let n=e.$schema.replace(/#$/,``);if(Ee.has(n))return`2020-12`;if(De.has(n))return`2019-09`;if(Oe.has(n)||ke.has(n))return`draft-7`;throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var Me=`2025-11-25`,Ne=[Me,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Pe=`io.modelcontextprotocol/related-task`,Fe=`io.modelcontextprotocol/protocolVersion`,Ie=`io.modelcontextprotocol/clientInfo`,Le=`io.modelcontextprotocol/serverInfo`,Re=`io.modelcontextprotocol/clientCapabilities`,ze=`io.modelcontextprotocol/subscriptionId`,Be=`io.modelcontextprotocol/logLevel`,Ve=ee(()=>j([x(),E(),A(),ae(),M(x(),Ve),O(Ve)])),I=M(x(),Ve),He=O(Ve),Ue=j([x(),E().int()]),We=x(),Ge=T({ttl:E().optional()}),Ke=T({taskId:x()}),qe=k({progressToken:Ue.optional(),[Pe]:Ke.optional()}),L=T({_meta:qe.optional()}),Je=L.extend({task:Ge.optional()}),R=T({method:x(),params:L.loose().optional()}),z=T({_meta:qe.optional()}),B=T({method:x(),params:z.loose().optional()}),Ye=k({get[Le](){return H.optional().catch(void 0)}}),V=k({_meta:Ye.optional()}),Xe=j([x(),E().int()]),Ze=T({jsonrpc:w(`2.0`),id:Xe,...R.shape}).strict(),Qe=T({jsonrpc:w(`2.0`),...B.shape}).strict(),$e=T({jsonrpc:w(`2.0`),id:Xe,result:V}).strict(),et=T({jsonrpc:w(`2.0`),id:Xe.optional(),error:T({code:E().int(),message:x(),data:h().optional()})}).strict(),tt=j([Ze,Qe,$e,et]),nt=j([$e,et]),rt=V.strict(),it=z.extend({requestId:Xe.optional(),reason:x().optional()}),at=B.extend({method:w(`notifications/cancelled`),params:it}),ot=T({src:x(),mimeType:x().optional(),sizes:O(x()).optional(),theme:D([`light`,`dark`]).optional()}),st=T({icons:O(ot).optional()}),ct=T({name:x(),title:x().optional()}),H=ct.extend({...ct.shape,...st.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),lt=se(T({applyDefaults:A().optional()}),I),ut=ce(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,se(T({form:lt.optional(),url:I.optional()}),I.optional())),dt=k({list:I.optional(),cancel:I.optional(),requests:k({sampling:k({createMessage:I.optional()}).optional(),elicitation:k({create:I.optional()}).optional()}).optional()}),ft=k({list:I.optional(),cancel:I.optional(),requests:k({tools:k({call:I.optional()}).optional()}).optional()}),pt=T({experimental:M(x(),I).optional(),sampling:T({context:I.optional(),tools:I.optional()}).optional(),elicitation:ut.optional(),roots:T({listChanged:A().optional()}).optional(),tasks:dt.optional(),extensions:M(x(),I).optional()}),mt=L.extend({protocolVersion:x(),capabilities:pt,clientInfo:H}),ht=R.extend({method:w(`initialize`),params:mt}),gt=T({experimental:M(x(),I).optional(),logging:I.optional(),completions:I.optional(),prompts:T({listChanged:A().optional()}).optional(),resources:T({subscribe:A().optional(),listChanged:A().optional()}).optional(),tools:T({listChanged:A().optional()}).optional(),tasks:ft.optional(),extensions:M(x(),I).optional()}),_t=V.extend({protocolVersion:x(),capabilities:gt,serverInfo:H,instructions:x().optional()}),vt=B.extend({method:w(`notifications/initialized`),params:z.optional()}),yt=R.extend({method:w(`server/discover`),params:L.optional()}),bt=V.extend({supportedVersions:O(x()),capabilities:gt,instructions:x().optional()}),xt=R.extend({method:w(`ping`),params:L.optional()}),St=T({progress:E(),total:y(E()),message:y(x())}),Ct=T({...z.shape,...St.shape,progressToken:Ue}),wt=B.extend({method:w(`notifications/progress`),params:Ct}),Tt=L.extend({cursor:We.optional()}),Et=R.extend({params:Tt.optional()}),Dt=V.extend({nextCursor:We.optional()}),Ot=T({uri:x(),mimeType:y(x()),_meta:M(x(),h()).optional()}),kt=Ot.extend({text:x()}),At=x().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),jt=Ot.extend({blob:At}),Mt=D([`user`,`assistant`]),Nt=T({audience:O(Mt).optional(),priority:E().min(0).max(1).optional(),lastModified:pe({offset:!0}).optional()}),Pt=T({...ct.shape,...st.shape,uri:x(),description:y(x()),mimeType:y(x()),size:y(E()),annotations:Nt.optional(),_meta:y(k({}))}),Ft=T({...ct.shape,...st.shape,uriTemplate:x(),description:y(x()),mimeType:y(x()),annotations:Nt.optional(),_meta:y(k({}))}),It=Et.extend({method:w(`resources/list`)}),Lt=Dt.extend({resources:O(Pt)}),U=Et.extend({method:w(`resources/templates/list`)}),W=Dt.extend({resourceTemplates:O(Ft)}),Rt=L.extend({uri:x()}),zt=Rt,Bt=R.extend({method:w(`resources/read`),params:zt}),Vt=V.extend({contents:O(j([kt,jt]))}),Ht=B.extend({method:w(`notifications/resources/list_changed`),params:z.optional()}),Ut=Rt,Wt=R.extend({method:w(`resources/subscribe`),params:Ut}),Gt=Rt,Kt=R.extend({method:w(`resources/unsubscribe`),params:Gt}),qt=T({toolsListChanged:A().optional(),promptsListChanged:A().optional(),resourcesListChanged:A().optional(),resourceSubscriptions:O(x()).optional()}),Jt=L.extend({notifications:qt}),Yt=R.extend({method:w(`subscriptions/listen`),params:Jt}),Xt=z.extend({notifications:qt}),Zt=B.extend({method:w(`notifications/subscriptions/acknowledged`),params:Xt}),Qt=Ye.extend({[ze]:Xe}),$t=V.extend({_meta:Qt}),en=z.extend({uri:x()}),tn=B.extend({method:w(`notifications/resources/updated`),params:en}),G=T({name:x(),description:y(x()),required:y(A())}),nn=T({...ct.shape,...st.shape,description:y(x()),arguments:y(O(G)),_meta:y(k({}))}),rn=Et.extend({method:w(`prompts/list`)}),an=Dt.extend({prompts:O(nn)}),on=L.extend({name:x(),arguments:M(x(),x()).optional()}),sn=R.extend({method:w(`prompts/get`),params:on}),cn=T({type:w(`text`),text:x(),annotations:Nt.optional(),_meta:M(x(),h()).optional()}),K=T({type:w(`image`),data:At,mimeType:x(),annotations:Nt.optional(),_meta:M(x(),h()).optional()}),ln=T({type:w(`audio`),data:At,mimeType:x(),annotations:Nt.optional(),_meta:M(x(),h()).optional()}),un=T({type:w(`tool_use`),name:x(),id:x(),input:M(x(),h()),_meta:M(x(),h()).optional()}),dn=T({type:w(`resource`),resource:j([kt,jt]),annotations:Nt.optional(),_meta:M(x(),h()).optional()}),fn=Pt.extend({type:w(`resource_link`)}),pn=j([cn,K,ln,fn,dn]),mn=T({role:Mt,content:pn}),hn=V.extend({description:x().optional(),messages:O(mn)}),gn=B.extend({method:w(`notifications/prompts/list_changed`),params:z.optional()}),_n=T({title:x().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),vn=T({taskSupport:D([`required`,`optional`,`forbidden`]).optional()}),yn=T({...ct.shape,...st.shape,description:x().optional(),inputSchema:T({type:w(`object`),properties:M(x(),Ve).optional(),required:O(x()).optional()}).catchall(h()),outputSchema:k({$schema:x().optional()}).optional(),annotations:_n.optional(),execution:vn.optional(),_meta:M(x(),h()).optional()}),bn=Et.extend({method:w(`tools/list`)}),xn=Dt.extend({tools:O(yn)}),Sn=V.extend({content:O(pn).default([]),structuredContent:h().optional(),isError:A().optional()}),Cn=Sn.or(V.extend({toolResult:h()})),wn=Je.extend({name:x(),arguments:M(x(),h()).optional()}),Tn=R.extend({method:w(`tools/call`),params:wn}),En=B.extend({method:w(`notifications/tools/list_changed`),params:z.optional()}),Dn=T({autoRefresh:A().default(!0),debounceMs:E().int().nonnegative().default(300)}),On=D([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),kn=L.extend({level:On}),An=R.extend({method:w(`logging/setLevel`),params:kn}),jn=z.extend({level:On,logger:x().optional(),data:h()}),Mn=B.extend({method:w(`notifications/message`),params:jn}),Nn=T({name:x().optional()}),Pn=T({hints:O(Nn).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),Fn=T({mode:D([`auto`,`required`,`none`]).optional()}),In=T({type:w(`tool_result`),toolUseId:x().describe(`The unique identifier for the corresponding tool call.`),content:O(pn),structuredContent:h().optional(),isError:A().optional(),_meta:M(x(),h()).optional()}),Ln=S(`type`,[cn,K,ln]),Rn=S(`type`,[cn,K,ln,un,In]),zn=T({role:Mt,content:j([Rn,O(Rn)]),_meta:M(x(),h()).optional()}),Bn=Je.extend({messages:O(zn),modelPreferences:Pn.optional(),systemPrompt:x().optional(),includeContext:D([`none`,`thisServer`,`allServers`]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:O(x()).optional(),metadata:I.optional(),tools:O(yn).optional(),toolChoice:Fn.optional()}),Vn=R.extend({method:w(`sampling/createMessage`),params:Bn}),Hn=V.extend({model:x(),stopReason:y(D([`endTurn`,`stopSequence`,`maxTokens`]).or(x())),role:Mt,content:Ln}),Un=V.extend({model:x(),stopReason:y(D([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(x())),role:Mt,content:j([Rn,O(Rn)])}),Wn=T({type:w(`boolean`),title:x().optional(),description:x().optional(),default:A().optional()}),Gn=T({type:w(`string`),title:x().optional(),description:x().optional(),minLength:E().optional(),maxLength:E().optional(),format:D([`email`,`uri`,`date`,`date-time`]).optional(),default:x().optional()}),Kn=T({type:D([`number`,`integer`]),title:x().optional(),description:x().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),qn=T({type:w(`string`),title:x().optional(),description:x().optional(),enum:O(x()),default:x().optional()}),Jn=T({type:w(`string`),title:x().optional(),description:x().optional(),oneOf:O(T({const:x(),title:x()})),default:x().optional()}),Yn=T({type:w(`string`),title:x().optional(),description:x().optional(),enum:O(x()),enumNames:O(x()).optional(),default:x().optional()}),Xn=j([qn,Jn]),Zn=T({type:w(`array`),title:x().optional(),description:x().optional(),minItems:E().optional(),maxItems:E().optional(),items:T({type:w(`string`),enum:O(x())}),default:O(x()).optional()}),Qn=T({type:w(`array`),title:x().optional(),description:x().optional(),minItems:E().optional(),maxItems:E().optional(),items:T({anyOf:O(T({const:x(),title:x()}))}),default:O(x()).optional()}),$n=j([Zn,Qn]),er=j([Yn,Xn,$n]),tr=j([er,Wn,Gn,Kn]),nr=Je.extend({mode:w(`form`).optional(),message:x(),requestedSchema:T({type:w(`object`),properties:M(x(),tr),required:O(x()).optional()}).catchall(h())}),rr=Je.extend({mode:w(`url`),message:x(),elicitationId:x(),url:x().url()}),ir=j([nr,rr]),ar=R.extend({method:w(`elicitation/create`),params:ir}),or=z.extend({elicitationId:x()}),sr=B.extend({method:w(`notifications/elicitation/complete`),params:or}),cr=V.extend({action:D([`accept`,`decline`,`cancel`]),content:ce(e=>e===null?void 0:e,M(x(),j([x(),E(),A(),O(x())])).optional())}),lr=T({type:w(`ref/resource`),uri:x()}),ur=T({type:w(`ref/prompt`),name:x()}),dr=L.extend({ref:j([ur,lr]),argument:T({name:x(),value:x()}),context:T({arguments:M(x(),x()).optional()}).optional()}),fr=R.extend({method:w(`completion/complete`),params:dr}),pr=V.extend({completion:k({values:O(x()).max(100),total:y(E().int()),hasMore:y(A())})}),mr=T({uri:x().startsWith(`file://`),name:x().optional(),_meta:M(x(),h()).optional()}),hr=R.extend({method:w(`roots/list`),params:L.optional()}),gr=V.extend({roots:O(mr)}),_r=B.extend({method:w(`notifications/roots/list_changed`),params:z.optional()}),vr=k({ttl:E().optional(),pollInterval:E().optional()}),yr=D([`working`,`input_required`,`completed`,`failed`,`cancelled`]),br=T({taskId:x(),status:yr,ttl:j([E(),ae()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:y(E()),statusMessage:y(x())}),xr=V.extend({task:br}),Sr=z.merge(br),Cr=B.extend({method:w(`notifications/tasks/status`),params:Sr}),wr=R.extend({method:w(`tasks/get`),params:L.extend({taskId:x()})}),Tr=V.merge(br),Er=R.extend({method:w(`tasks/result`),params:L.extend({taskId:x()})}),Dr=V.loose(),Or=Et.extend({method:w(`tasks/list`)}),kr=Dt.extend({tasks:O(br)}),Ar=R.extend({method:w(`tasks/cancel`),params:L.extend({taskId:x()})}),jr=V.merge(br),Mr=j([xt,ht,yt,fr,An,sn,rn,It,U,Bt,Wt,Kt,Yt,Tn,bn]),Nr=j([at,wt,vt,_r]),Pr=j([rt,Hn,Un,cr,gr]),Fr=j([xt,Vn,ar,hr]),Ir=j([at,wt,Mn,tn,Ht,En,gn,Zt,sr]),Lr=j([rt,_t,bt,pr,hn,an,Lt,W,Vt,Sn,xn,$t]),q=d().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:de.custom,message:`URL must be parseable`,fatal:!0}),ne}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),Rr=k({resource:x().url(),authorization_servers:O(q).optional(),jwks_uri:x().url().optional(),scopes_supported:O(x()).optional(),bearer_methods_supported:O(x()).optional(),resource_signing_alg_values_supported:O(x()).optional(),resource_name:x().optional(),resource_documentation:x().optional(),resource_policy_uri:x().url().optional(),resource_tos_uri:x().url().optional(),tls_client_certificate_bound_access_tokens:A().optional(),authorization_details_types_supported:O(x()).optional(),dpop_signing_alg_values_supported:O(x()).optional(),dpop_bound_access_tokens_required:A().optional()}),zr=k({issuer:x(),authorization_endpoint:q,token_endpoint:q,registration_endpoint:q.optional(),scopes_supported:O(x()).optional(),response_types_supported:O(x()),response_modes_supported:O(x()).optional(),grant_types_supported:O(x()).optional(),token_endpoint_auth_methods_supported:O(x()).optional(),token_endpoint_auth_signing_alg_values_supported:O(x()).optional(),service_documentation:q.optional(),revocation_endpoint:q.optional(),revocation_endpoint_auth_methods_supported:O(x()).optional(),revocation_endpoint_auth_signing_alg_values_supported:O(x()).optional(),introspection_endpoint:x().optional(),introspection_endpoint_auth_methods_supported:O(x()).optional(),introspection_endpoint_auth_signing_alg_values_supported:O(x()).optional(),code_challenge_methods_supported:O(x()).optional(),client_id_metadata_document_supported:A().optional(),authorization_response_iss_parameter_supported:A().optional().catch(void 0),dpop_signing_alg_values_supported:O(x()).optional()}),Br=k({issuer:x(),authorization_endpoint:q,token_endpoint:q,userinfo_endpoint:q.optional(),jwks_uri:q,registration_endpoint:q.optional(),scopes_supported:O(x()).optional(),response_types_supported:O(x()),response_modes_supported:O(x()).optional(),grant_types_supported:O(x()).optional(),acr_values_supported:O(x()).optional(),subject_types_supported:O(x()),id_token_signing_alg_values_supported:O(x()),id_token_encryption_alg_values_supported:O(x()).optional(),id_token_encryption_enc_values_supported:O(x()).optional(),userinfo_signing_alg_values_supported:O(x()).optional(),userinfo_encryption_alg_values_supported:O(x()).optional(),userinfo_encryption_enc_values_supported:O(x()).optional(),request_object_signing_alg_values_supported:O(x()).optional(),request_object_encryption_alg_values_supported:O(x()).optional(),request_object_encryption_enc_values_supported:O(x()).optional(),token_endpoint_auth_methods_supported:O(x()).optional(),token_endpoint_auth_signing_alg_values_supported:O(x()).optional(),display_values_supported:O(x()).optional(),claim_types_supported:O(x()).optional(),claims_supported:O(x()).optional(),service_documentation:x().optional(),claims_locales_supported:O(x()).optional(),ui_locales_supported:O(x()).optional(),claims_parameter_supported:A().optional(),request_parameter_supported:A().optional(),request_uri_parameter_supported:A().optional(),require_request_uri_registration:A().optional(),op_policy_uri:q.optional(),op_tos_uri:q.optional(),client_id_metadata_document_supported:A().optional(),authorization_response_iss_parameter_supported:A().optional().catch(void 0)}),Vr=T({...Br.shape,...zr.pick({code_challenge_methods_supported:!0}).shape}),Hr=T({access_token:x(),id_token:x().optional(),token_type:x(),expires_in:he().optional(),scope:x().optional(),refresh_token:x().optional(),issuer:x().optional().catch(void 0)}).strip(),Ur=T({issued_token_type:w(`urn:ietf:params:oauth:token-type:id-jag`),access_token:x(),token_type:x().optional(),expires_in:E().optional(),scope:x().optional()}).strip(),Wr=T({error:x(),error_description:x().optional(),error_uri:x().optional()}),Gr=q.optional().or(w(``).transform(()=>void 0)),Kr=T({redirect_uris:O(q),token_endpoint_auth_method:x().optional(),grant_types:O(x()).optional(),response_types:O(x()).optional(),application_type:x().optional(),client_name:x().optional(),client_uri:q.optional(),logo_uri:Gr,scope:x().optional(),contacts:O(x()).optional(),tos_uri:Gr,policy_uri:x().optional(),jwks_uri:q.optional(),jwks:b().optional(),software_id:x().optional(),software_version:x().optional(),software_statement:x().optional()}).strip(),qr=T({client_id:x(),client_secret:x().optional(),client_id_issued_at:E().optional(),client_secret_expires_at:E().optional(),issuer:x().optional().catch(void 0)}).strip(),Jr=Kr.merge(qr),Yr=T({error:x(),error_description:x().optional()}).strip(),Xr=T({token:x(),token_type_hint:x().optional()}).strip(),Zr=Symbol.for(`mcp.sdk.errorBrands`);function Qr(e,t){let n=new Set,r=t;for(;typeof r==`function`;){let e=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,`mcpBrand`)&&typeof e==`string`&&n.add(e),r=Object.getPrototypeOf(r)}n.size!==0&&Object.defineProperty(e,Zr,{value:n,enumerable:!1,configurable:!0})}function $r(e,t){try{if(typeof t==`object`&&t&&Object.prototype.hasOwnProperty.call(e,`mcpBrand`)&&typeof e.mcpBrand==`string`&&Object.prototype.hasOwnProperty.call(t,Zr)){let n=t[Zr];if(n&&typeof n.has==`function`&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var ei=function(e){return e.InvalidRequest=`invalid_request`,e.InvalidClient=`invalid_client`,e.InvalidGrant=`invalid_grant`,e.UnauthorizedClient=`unauthorized_client`,e.UnsupportedGrantType=`unsupported_grant_type`,e.InvalidScope=`invalid_scope`,e.AccessDenied=`access_denied`,e.ServerError=`server_error`,e.TemporarilyUnavailable=`temporarily_unavailable`,e.UnsupportedResponseType=`unsupported_response_type`,e.UnsupportedTokenType=`unsupported_token_type`,e.InvalidToken=`invalid_token`,e.MethodNotAllowed=`method_not_allowed`,e.TooManyRequests=`too_many_requests`,e.InvalidClientMetadata=`invalid_client_metadata`,e.InvalidRedirectUri=`invalid_redirect_uri`,e.InsufficientScope=`insufficient_scope`,e.InvalidTarget=`invalid_target`,e.InvalidDpopProof=`invalid_dpop_proof`,e.UseDpopNonce=`use_dpop_nonce`,e}({}),ti=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`,Qr(this,new.target)}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},J=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.InvalidResult=`INVALID_RESULT`,e.UnsupportedResultType=`UNSUPPORTED_RESULT_TYPE`,e.InputRequiredRoundsExceeded=`INPUT_REQUIRED_ROUNDS_EXCEEDED`,e.ListPaginationExceeded=`LIST_PAGINATION_EXCEEDED`,e.MethodNotSupportedByProtocolVersion=`METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION`,e.EraNegotiationFailed=`ERA_NEGOTIATION_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({}),Y=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e,t,n,r){super(t,r),this.code=e,this.data=n,this.name=`SdkError`,Qr(this,new.target)}},ni=class extends Y{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkHttpError`})}constructor(e,t,n,r){super(e,t,n,r),this.name=`SdkHttpError`}get status(){return this.data.status}get statusText(){return this.data.statusText}};function ri(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function ii(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function ai({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length=oi}function li(e){return e.filter(e=>!ci(e))}function ui(e){return e.filter(e=>ci(e))}function di(e){let t=e.structuredContent;return t===void 0||typeof t==`object`&&t&&!Array.isArray(t)||(e.content?.some(e=>e.type===`text`)??!1)?e:{...e,content:[...e.content??[],{type:`text`,text:JSON.stringify(t)}]}}var fi=[`task`,`inputRequests`,`requestState`];function pi(e){return typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0||fi.some(t=>t in e)?e:{...e,content:[]}}function mi(){let e=ee(()=>j([x(),E(),A(),ae(),M(x(),e),O(e)])),t=M(x(),e),n=j([x(),E().int()]),r=x(),i=T({ttl:E().optional()}),a=T({taskId:x()}),o=k({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),s=T({_meta:o.optional()}),c=s.extend({task:i.optional()}),l=T({method:x(),params:s.loose().optional()}),u=T({_meta:o.optional()}),d=T({method:x(),params:u.loose().optional()}),f=k({_meta:o.optional()}),p=j([x(),E().int()]),m=f.strict(),g=u.extend({requestId:p.optional(),reason:x().optional()}),_=d.extend({method:w(`notifications/cancelled`),params:g}),v=T({src:x(),mimeType:x().optional(),sizes:O(x()).optional(),theme:D([`light`,`dark`]).optional()}),b=T({icons:O(v).optional()}),C=T({name:x(),title:x().optional()}),te=C.extend({...C.shape,...b.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),ne=se(T({applyDefaults:A().optional()}),t),re=ce(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,se(T({form:ne.optional(),url:t.optional()}),t.optional())),ie=k({list:t.optional(),cancel:t.optional(),requests:k({sampling:k({createMessage:t.optional()}).optional(),elicitation:k({create:t.optional()}).optional()}).optional()}),oe=k({list:t.optional(),cancel:t.optional(),requests:k({tools:k({call:t.optional()}).optional()}).optional()}),le=T({experimental:M(x(),t).optional(),sampling:T({context:t.optional(),tools:t.optional()}).optional(),elicitation:re.optional(),roots:T({listChanged:A().optional()}).optional(),tasks:ie.optional(),extensions:M(x(),t).optional()}),ue=s.extend({protocolVersion:x(),capabilities:le,clientInfo:te}),de=l.extend({method:w(`initialize`),params:ue}),fe=T({experimental:M(x(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:T({listChanged:A().optional()}).optional(),resources:T({subscribe:A().optional(),listChanged:A().optional()}).optional(),tools:T({listChanged:A().optional()}).optional(),tasks:oe.optional(),extensions:M(x(),t).optional()}),me=f.extend({protocolVersion:x(),capabilities:fe,serverInfo:te,instructions:x().optional()}),he=d.extend({method:w(`notifications/initialized`),params:u.optional()}),N=l.extend({method:w(`ping`),params:s.optional()}),P=T({progress:E(),total:y(E()),message:y(x())}),ge=T({...u.shape,...P.shape,progressToken:n}),_e=d.extend({method:w(`notifications/progress`),params:ge}),ve=s.extend({cursor:r.optional()}),ye=l.extend({params:ve.optional()}),be=f.extend({nextCursor:r.optional()}),F=T({uri:x(),mimeType:y(x()),_meta:M(x(),h()).optional()}),xe=F.extend({text:x()}),Se=x().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Ce=F.extend({blob:Se}),we=D([`user`,`assistant`]),Te=T({audience:O(we).optional(),priority:E().min(0).max(1).optional(),lastModified:pe({offset:!0}).optional()}),Ee=T({...C.shape,...b.shape,uri:x(),description:y(x()),mimeType:y(x()),size:y(E()),annotations:Te.optional(),_meta:y(k({}))}),De=T({...C.shape,...b.shape,uriTemplate:x(),description:y(x()),mimeType:y(x()),annotations:Te.optional(),_meta:y(k({}))}),Oe=ye.extend({method:w(`resources/list`)}),ke=be.extend({resources:O(Ee)}),Ae=ye.extend({method:w(`resources/templates/list`)}),je=be.extend({resourceTemplates:O(De)}),Me=s.extend({uri:x()}),Ne=Me,Pe=l.extend({method:w(`resources/read`),params:Ne}),Fe=f.extend({contents:O(j([xe,Ce]))}),Ie=d.extend({method:w(`notifications/resources/list_changed`),params:u.optional()}),Le=Me,Re=l.extend({method:w(`resources/subscribe`),params:Le}),ze=Me,Be=l.extend({method:w(`resources/unsubscribe`),params:ze}),Ve=u.extend({uri:x()}),I=d.extend({method:w(`notifications/resources/updated`),params:Ve}),He=T({name:x(),description:y(x()),required:y(A())}),Ue=T({...C.shape,...b.shape,description:y(x()),arguments:y(O(He)),_meta:y(k({}))}),We=ye.extend({method:w(`prompts/list`)}),Ge=be.extend({prompts:O(Ue)}),Ke=s.extend({name:x(),arguments:M(x(),x()).optional()}),qe=l.extend({method:w(`prompts/get`),params:Ke}),L=T({type:w(`text`),text:x(),annotations:Te.optional(),_meta:M(x(),h()).optional()}),Je=T({type:w(`image`),data:Se,mimeType:x(),annotations:Te.optional(),_meta:M(x(),h()).optional()}),R=T({type:w(`audio`),data:Se,mimeType:x(),annotations:Te.optional(),_meta:M(x(),h()).optional()}),z=T({type:w(`tool_use`),name:x(),id:x(),input:M(x(),h()),_meta:M(x(),h()).optional()}),B=T({type:w(`resource`),resource:j([xe,Ce]),annotations:Te.optional(),_meta:M(x(),h()).optional()}),Ye=Ee.extend({type:w(`resource_link`)}),V=j([L,Je,R,Ye,B]),Xe=T({role:we,content:V}),Ze=f.extend({description:x().optional(),messages:O(Xe)}),Qe=d.extend({method:w(`notifications/prompts/list_changed`),params:u.optional()}),$e=T({title:x().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),et=T({taskSupport:D([`required`,`optional`,`forbidden`]).optional()}),tt=T({...C.shape,...b.shape,description:x().optional(),inputSchema:T({type:w(`object`),properties:M(x(),e).optional(),required:O(x()).optional()}).catchall(h()),outputSchema:T({type:w(`object`),properties:M(x(),e).optional(),required:O(x()).optional()}).catchall(h()).optional(),annotations:$e.optional(),execution:et.optional(),_meta:M(x(),h()).optional()}),nt=ye.extend({method:w(`tools/list`)}),rt=be.extend({tools:O(tt)}),it=f.extend({content:O(V),structuredContent:M(x(),h()).optional(),isError:A().optional()}),at=c.extend({name:x(),arguments:M(x(),h()).optional()}),ot=l.extend({method:w(`tools/call`),params:at}),st=d.extend({method:w(`notifications/tools/list_changed`),params:u.optional()}),ct=D([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),H=s.extend({level:ct}),lt=l.extend({method:w(`logging/setLevel`),params:H}),ut=u.extend({level:ct,logger:x().optional(),data:h()}),dt=d.extend({method:w(`notifications/message`),params:ut}),ft=T({name:x().optional()}),pt=T({hints:O(ft).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),mt=T({mode:D([`auto`,`required`,`none`]).optional()}),ht=T({type:w(`tool_result`),toolUseId:x().describe(`The unique identifier for the corresponding tool call.`),content:O(V),structuredContent:T({}).loose().optional(),isError:A().optional(),_meta:M(x(),h()).optional()}),gt=S(`type`,[L,Je,R]),_t=S(`type`,[L,Je,R,z,ht]),vt=T({role:we,content:j([_t,O(_t)]),_meta:M(x(),h()).optional()}),yt=c.extend({messages:O(vt),modelPreferences:pt.optional(),systemPrompt:x().optional(),includeContext:D([`none`,`thisServer`,`allServers`]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:O(x()).optional(),metadata:t.optional(),tools:O(tt).optional(),toolChoice:mt.optional()}),bt=l.extend({method:w(`sampling/createMessage`),params:yt}),xt=f.extend({model:x(),stopReason:y(D([`endTurn`,`stopSequence`,`maxTokens`]).or(x())),role:we,content:gt}),St=f.extend({model:x(),stopReason:y(D([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(x())),role:we,content:j([_t,O(_t)])}),Ct=T({type:w(`boolean`),title:x().optional(),description:x().optional(),default:A().optional()}),wt=T({type:w(`string`),title:x().optional(),description:x().optional(),minLength:E().optional(),maxLength:E().optional(),format:D([`email`,`uri`,`date`,`date-time`]).optional(),default:x().optional()}),Tt=T({type:D([`number`,`integer`]),title:x().optional(),description:x().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),Et=T({type:w(`string`),title:x().optional(),description:x().optional(),enum:O(x()),default:x().optional()}),Dt=T({type:w(`string`),title:x().optional(),description:x().optional(),oneOf:O(T({const:x(),title:x()})),default:x().optional()}),Ot=T({type:w(`string`),title:x().optional(),description:x().optional(),enum:O(x()),enumNames:O(x()).optional(),default:x().optional()}),kt=j([Et,Dt]),At=T({type:w(`array`),title:x().optional(),description:x().optional(),minItems:E().optional(),maxItems:E().optional(),items:T({type:w(`string`),enum:O(x())}),default:O(x()).optional()}),jt=T({type:w(`array`),title:x().optional(),description:x().optional(),minItems:E().optional(),maxItems:E().optional(),items:T({anyOf:O(T({const:x(),title:x()}))}),default:O(x()).optional()}),Mt=j([At,jt]),Nt=j([Ot,kt,Mt]),Pt=j([Nt,Ct,wt,Tt]),Ft=c.extend({mode:w(`form`).optional(),message:x(),requestedSchema:T({type:w(`object`),properties:M(x(),Pt),required:O(x()).optional()}).catchall(h())}),It=c.extend({mode:w(`url`),message:x(),elicitationId:x(),url:x().url()}),Lt=j([Ft,It]),U=l.extend({method:w(`elicitation/create`),params:Lt}),W=u.extend({elicitationId:x()}),Rt=d.extend({method:w(`notifications/elicitation/complete`),params:W}),zt=f.extend({action:D([`accept`,`decline`,`cancel`]),content:ce(e=>e===null?void 0:e,M(x(),j([x(),E(),A(),O(x())])).optional())}),Bt=T({type:w(`ref/resource`),uri:x()}),Vt=T({type:w(`ref/prompt`),name:x()}),Ht=s.extend({ref:j([Vt,Bt]),argument:T({name:x(),value:x()}),context:T({arguments:M(x(),x()).optional()}).optional()}),Ut=l.extend({method:w(`completion/complete`),params:Ht}),Wt=f.extend({completion:k({values:O(x()).max(100),total:y(E().int()),hasMore:y(A())})}),Gt=T({uri:x().startsWith(`file://`),name:x().optional(),_meta:M(x(),h()).optional()}),Kt=l.extend({method:w(`roots/list`),params:s.optional()}),qt=f.extend({roots:O(Gt)}),Jt=d.extend({method:w(`notifications/roots/list_changed`),params:u.optional()}),Yt=k({ttl:E().optional(),pollInterval:E().optional()}),Xt=D([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Zt=T({taskId:x(),status:Xt,ttl:j([E(),ae()]),createdAt:x(),lastUpdatedAt:x(),pollInterval:y(E()),statusMessage:y(x())}),Qt=f.extend({task:Zt}),$t=u.merge(Zt),en=d.extend({method:w(`notifications/tasks/status`),params:$t}),tn=l.extend({method:w(`tasks/get`),params:s.extend({taskId:x()})}),G=f.merge(Zt),nn=l.extend({method:w(`tasks/result`),params:s.extend({taskId:x()})}),rn=f.loose(),an=ye.extend({method:w(`tasks/list`)}),on=be.extend({tasks:O(Zt)}),sn=l.extend({method:w(`tasks/cancel`),params:s.extend({taskId:x()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,TaskMetadataSchema:i,RelatedTaskMetadataSchema:a,RequestMetaSchema:o,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:l,NotificationsParamsSchema:u,NotificationSchema:d,ResultSchema:f,RequestIdSchema:p,EmptyResultSchema:m,CancelledNotificationParamsSchema:g,CancelledNotificationSchema:_,IconSchema:v,IconsSchema:b,BaseMetadataSchema:C,ImplementationSchema:te,ClientTasksCapabilitySchema:ie,ServerTasksCapabilitySchema:oe,ClientCapabilitiesSchema:le,InitializeRequestParamsSchema:ue,InitializeRequestSchema:de,ServerCapabilitiesSchema:fe,InitializeResultSchema:me,InitializedNotificationSchema:he,PingRequestSchema:N,ProgressSchema:P,ProgressNotificationParamsSchema:ge,ProgressNotificationSchema:_e,PaginatedRequestParamsSchema:ve,PaginatedRequestSchema:ye,PaginatedResultSchema:be,ResourceContentsSchema:F,TextResourceContentsSchema:xe,BlobResourceContentsSchema:Ce,RoleSchema:we,AnnotationsSchema:Te,ResourceSchema:Ee,ResourceTemplateSchema:De,ListResourcesRequestSchema:Oe,ListResourcesResultSchema:ke,ListResourceTemplatesRequestSchema:Ae,ListResourceTemplatesResultSchema:je,ResourceRequestParamsSchema:Me,ReadResourceRequestParamsSchema:Ne,ReadResourceRequestSchema:Pe,ReadResourceResultSchema:Fe,ResourceListChangedNotificationSchema:Ie,SubscribeRequestParamsSchema:Le,SubscribeRequestSchema:Re,UnsubscribeRequestParamsSchema:ze,UnsubscribeRequestSchema:Be,ResourceUpdatedNotificationParamsSchema:Ve,ResourceUpdatedNotificationSchema:I,PromptArgumentSchema:He,PromptSchema:Ue,ListPromptsRequestSchema:We,ListPromptsResultSchema:Ge,GetPromptRequestParamsSchema:Ke,GetPromptRequestSchema:qe,TextContentSchema:L,ImageContentSchema:Je,AudioContentSchema:R,ToolUseContentSchema:z,EmbeddedResourceSchema:B,ResourceLinkSchema:Ye,ContentBlockSchema:V,PromptMessageSchema:Xe,GetPromptResultSchema:Ze,PromptListChangedNotificationSchema:Qe,ToolAnnotationsSchema:$e,ToolExecutionSchema:et,ToolSchema:tt,ListToolsRequestSchema:nt,ListToolsResultSchema:rt,CallToolResultSchema:it,CallToolRequestParamsSchema:at,CallToolRequestSchema:ot,ToolListChangedNotificationSchema:st,LoggingLevelSchema:ct,SetLevelRequestParamsSchema:H,SetLevelRequestSchema:lt,LoggingMessageNotificationParamsSchema:ut,LoggingMessageNotificationSchema:dt,ModelHintSchema:ft,ModelPreferencesSchema:pt,ToolChoiceSchema:mt,ToolResultContentSchema:ht,SamplingContentSchema:gt,SamplingMessageContentBlockSchema:_t,SamplingMessageSchema:vt,CreateMessageRequestParamsSchema:yt,CreateMessageRequestSchema:bt,CreateMessageResultSchema:xt,CreateMessageResultWithToolsSchema:St,BooleanSchemaSchema:Ct,StringSchemaSchema:wt,NumberSchemaSchema:Tt,UntitledSingleSelectEnumSchemaSchema:Et,TitledSingleSelectEnumSchemaSchema:Dt,LegacyTitledEnumSchemaSchema:Ot,SingleSelectEnumSchemaSchema:kt,UntitledMultiSelectEnumSchemaSchema:At,TitledMultiSelectEnumSchemaSchema:jt,MultiSelectEnumSchemaSchema:Mt,EnumSchemaSchema:Nt,PrimitiveSchemaDefinitionSchema:Pt,ElicitRequestFormParamsSchema:Ft,ElicitRequestURLParamsSchema:It,ElicitRequestParamsSchema:Lt,ElicitRequestSchema:U,ElicitationCompleteNotificationParamsSchema:W,ElicitationCompleteNotificationSchema:Rt,ElicitResultSchema:zt,ResourceTemplateReferenceSchema:Bt,PromptReferenceSchema:Vt,CompleteRequestParamsSchema:Ht,CompleteRequestSchema:Ut,CompleteResultSchema:Wt,RootSchema:Gt,ListRootsRequestSchema:Kt,ListRootsResultSchema:qt,RootsListChangedNotificationSchema:Jt,TaskCreationParamsSchema:Yt,TaskStatusSchema:Xt,TaskSchema:Zt,CreateTaskResultSchema:Qt,TaskStatusNotificationParamsSchema:$t,TaskStatusNotificationSchema:en,GetTaskRequestSchema:tn,GetTaskResultSchema:G,GetTaskPayloadRequestSchema:nn,GetTaskPayloadResultSchema:rn,ListTasksRequestSchema:an,ListTasksResultSchema:on,CancelTaskRequestSchema:sn,CancelTaskResultSchema:f.merge(Zt),ClientRequestSchema:j([N,de,Ut,lt,qe,We,Oe,Ae,Pe,Re,Be,ot,nt,tn,nn,an,sn]),ClientNotificationSchema:j([_,_e,he,Jt,en]),ClientResultSchema:j([m,xt,St,zt,qt,G,on,Qt]),ServerRequestSchema:j([N,bt,U,Kt,tn,nn,an,sn]),ServerNotificationSchema:j([_,_e,dt,I,Ie,st,Qe,en,Rt]),ServerResultSchema:j([m,me,Wt,Ze,Ge,ke,je,Fe,it,rt,G,on,Qt]),CallToolResultWireSchema:h().superRefine((e,t)=>{if(typeof e==`object`&&e&&!Array.isArray(e)&&e.content===void 0){for(let n of fi)if(n in e){t.addIssue({code:`custom`,message:`content is required when the body carries '${n}' — another result family cannot default into an empty tools/call success`});return}}}).transform(pi).pipe(it)}}var hi;function gi(){return hi??=mi()}function _i(e){return e.type!==`object`}var vi=new Set([`const`,`enum`,`default`,`examples`]),yi=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`,`dependencies`]);function bi(e){return e!==void 0&&!(typeof e==`string`&&e.startsWith(`#`))}function xi(e){let t=typeof e.$schema==`string`?e.$schema:void 0;if(bi(e.$id))return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:e},required:[`result`]};let n=Ae(e.$schema)&&e.$recursiveAnchor!==!0,r=(e,t)=>{if(Array.isArray(e))return e.map(e=>r(e,!1));if(typeof e!=`object`||!e||!t&&bi(e.$id))return e;let i={},a=!1;for(let[o,s]of Object.entries(e))t?i[o]=r(s,!1):(o===`$ref`||o===`$dynamicRef`)&&typeof s==`string`?i[o]=s===`#`?`#/properties/result`:s.startsWith(`#/`)?`#/properties/result${s.slice(1)}`:s:o===`$recursiveRef`&&s===`#`&&n?a=!0:i[o]=vi.has(o)?s:yi.has(o)?r(s,!0):r(s,!1);return a&&(`$ref`in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:`#/properties/result`}]:i.$ref=`#/properties/result`),i};return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:r(e,!1)},required:[`result`]}}var Si={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ci={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},wi={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ti;function Ei(){if(Ti)return Ti;let e=gi();return Ti={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Ti}function Di(e){return Object.prototype.hasOwnProperty.call(Si,e)}function Oi(e){return Object.prototype.hasOwnProperty.call(Ci,e)}function ki(e){return Object.prototype.hasOwnProperty.call(wi,e)}function Ai(e){return ki(e)?Ei().resultSchemas[e]:void 0}function ji(e){return Di(e)?Ei().requestSchemas[e]:void 0}function Mi(e){return Oi(e)?Ei().notificationSchemas[e]:void 0}Object.keys(Si),Object.keys(Ci);function Ni(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pi(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}var Fi={ok:!1,reason:`not-in-era`};function Ii(e){return Ni(e)&&Ni(e.outputSchema)&&_i(e.outputSchema)}function Li(e){return e}var Ri={era:`2025-11-25`,hasRequestMethod:Di,hasNotificationMethod:Oi,validateRequest:(e,t)=>Pi(ji(e),t),validateResult:(e,t)=>Pi(Ai(e),t),validateNotification:(e,t)=>Pi(Mi(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Fi,validateInputResponse:()=>Fi,samplingResultVariant:((e,t)=>{let n=gi();return Pi(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>void 0,validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let n=di(e),r=n.structuredContent;if(r===void 0)return n;let i=typeof r!=`object`||!r||Array.isArray(r),a=t!==void 0&&_i(t);return!i&&!a?n:{...n,structuredContent:{result:r}}},decodeResult(e,t){if(Ni(t)&&`resultType`in t){let e={...t};return delete e.resultType,{kind:`complete`,result:Li(e)}}return{kind:`complete`,result:Li(t)}},encodeResult(e,t){if(e!==`tools/list`)return t;let n=t.tools;return!Array.isArray(n)||!n.some(e=>Ii(e))?t:{...t,tools:n.map(e=>Ii(e)?{...e,outputSchema:xi(e.outputSchema)}:e)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>void 0};function zi(){let e=ee(()=>j([x(),E(),A(),ae(),M(x(),e),O(e)])),t=M(x(),e),n=j([x(),E().int()]),r=x(),i=j([x(),E().int()]),a=D([`user`,`assistant`]),o=D([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),s=x().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),c=T({ttl:E().optional()}),l=T({taskId:x()}),u=k({progressToken:n.optional(),"io.modelcontextprotocol/related-task":l.optional()}),d=T({_meta:u.optional()}),f=d.extend({task:c.optional()}),p=T({_meta:u.optional()}),m=T({method:x(),params:p.loose().optional()}),g=T({src:x(),mimeType:x().optional(),sizes:O(x()).optional(),theme:D([`light`,`dark`]).optional()}),_=T({icons:O(g).optional()}),v=T({name:x(),title:x().optional()}),b=v.extend({...v.shape,..._.shape,version:x(),websiteUrl:x().optional(),description:x().optional()}),S=se(T({applyDefaults:A().optional()}),t),C=ce(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,se(T({form:S.optional(),url:t.optional()}),t.optional())),te=k({list:t.optional(),cancel:t.optional(),requests:k({sampling:k({createMessage:t.optional()}).optional(),elicitation:k({create:t.optional()}).optional()}).optional()}),ne=k({list:t.optional(),cancel:t.optional(),requests:k({tools:k({call:t.optional()}).optional()}).optional()}),re=T({experimental:M(x(),t).optional(),sampling:T({context:t.optional(),tools:t.optional()}).optional(),elicitation:C.optional(),roots:T({listChanged:A().optional()}).optional(),tasks:te.optional(),extensions:M(x(),t).optional()}),ie=T({experimental:M(x(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:T({listChanged:A().optional()}).optional(),resources:T({subscribe:A().optional(),listChanged:A().optional()}).optional(),tools:T({listChanged:A().optional()}).optional(),tasks:ne.optional(),extensions:M(x(),t).optional()}),oe=T({progress:E(),total:y(E()),message:y(x())}),le=T({...p.shape,...oe.shape,progressToken:n}),ue=m.extend({method:w(`notifications/progress`),params:le}),de=p.extend({level:o,logger:x().optional(),data:h()}),fe=m.extend({method:w(`notifications/message`),params:de}),me=T({uri:x(),mimeType:y(x()),_meta:M(x(),h()).optional()}),he=me.extend({text:x()}),N=me.extend({blob:s}),P=T({audience:O(a).optional(),priority:E().min(0).max(1).optional(),lastModified:pe({offset:!0}).optional()}),ge=T({...v.shape,..._.shape,uri:x(),description:y(x()),mimeType:y(x()),size:y(E()),annotations:P.optional(),_meta:y(k({}))}),_e=T({...v.shape,..._.shape,uriTemplate:x(),description:y(x()),mimeType:y(x()),annotations:P.optional(),_meta:y(k({}))}),ve=m.extend({method:w(`notifications/resources/list_changed`),params:p.optional()}),ye=p.extend({uri:x()}),be=m.extend({method:w(`notifications/resources/updated`),params:ye}),F=T({name:x(),description:y(x()),required:y(A())}),xe=T({...v.shape,..._.shape,description:y(x()),arguments:y(O(F)),_meta:y(k({}))}),Se=m.extend({method:w(`notifications/prompts/list_changed`),params:p.optional()}),Ce=T({type:w(`text`),text:x(),annotations:P.optional(),_meta:M(x(),h()).optional()}),we=T({type:w(`image`),data:s,mimeType:x(),annotations:P.optional(),_meta:M(x(),h()).optional()}),Te=T({type:w(`audio`),data:s,mimeType:x(),annotations:P.optional(),_meta:M(x(),h()).optional()}),Ee=T({type:w(`tool_use`),name:x(),id:x(),input:M(x(),h()),_meta:M(x(),h()).optional()}),De=T({type:w(`resource`),resource:j([he,N]),annotations:P.optional(),_meta:M(x(),h()).optional()}),Oe=ge.extend({type:w(`resource_link`)}),ke=j([Ce,we,Te,Oe,De]),Ae=T({role:a,content:ke}),je=T({title:x().optional(),readOnlyHint:A().optional(),destructiveHint:A().optional(),idempotentHint:A().optional(),openWorldHint:A().optional()}),Me=m.extend({method:w(`notifications/tools/list_changed`),params:p.optional()}),Ne=T({name:x().optional()}),Pe=T({hints:O(Ne).optional(),costPriority:E().min(0).max(1).optional(),speedPriority:E().min(0).max(1).optional(),intelligencePriority:E().min(0).max(1).optional()}),ze=T({mode:D([`auto`,`required`,`none`]).optional()}),Ve=T({type:w(`boolean`),title:x().optional(),description:x().optional(),default:A().optional()}),I=T({type:w(`string`),title:x().optional(),description:x().optional(),minLength:E().optional(),maxLength:E().optional(),format:D([`email`,`uri`,`date`,`date-time`]).optional(),default:x().optional()}),He=T({type:D([`number`,`integer`]),title:x().optional(),description:x().optional(),minimum:E().optional(),maximum:E().optional(),default:E().optional()}),Ue=T({type:w(`string`),title:x().optional(),description:x().optional(),enum:O(x()),default:x().optional()}),We=T({type:w(`string`),title:x().optional(),description:x().optional(),oneOf:O(T({const:x(),title:x()})),default:x().optional()}),Ge=T({type:w(`string`),title:x().optional(),description:x().optional(),enum:O(x()),enumNames:O(x()).optional(),default:x().optional()}),Ke=j([Ue,We]),qe=T({type:w(`array`),title:x().optional(),description:x().optional(),minItems:E().optional(),maxItems:E().optional(),items:T({type:w(`string`),enum:O(x())}),default:O(x()).optional()}),L=T({type:w(`array`),title:x().optional(),description:x().optional(),minItems:E().optional(),maxItems:E().optional(),items:T({anyOf:O(T({const:x(),title:x()}))}),default:O(x()).optional()}),Je=j([qe,L]),R=j([Ge,Ke,Je]),z=j([R,Ve,I,He]),B=f.extend({mode:w(`form`).optional(),message:x(),requestedSchema:T({type:w(`object`),properties:M(x(),z),required:O(x()).optional()}).catchall(h())}),Ye=T({type:w(`ref/resource`),uri:x()}),V=T({type:w(`ref/prompt`),name:x()}),Xe=T({uri:x().startsWith(`file://`),name:x().optional(),_meta:M(x(),h()).optional()}),Ze=re.shape,Qe=T({experimental:Ze.experimental,sampling:Ze.sampling,elicitation:Ze.elicitation,roots:Ze.roots,extensions:Ze.extensions}),$e=ie.shape,et=T({experimental:$e.experimental,logging:$e.logging,completions:$e.completions,prompts:$e.prompts,resources:$e.resources,tools:$e.tools,extensions:$e.extensions}),tt=k({progressToken:n.optional(),[Fe]:x(),[Ie]:b.optional(),[Re]:Qe,[Be]:o.optional()}),nt=T({...v.shape,..._.shape,description:x().optional(),inputSchema:k({$schema:x().optional(),type:w(`object`)}),outputSchema:k({$schema:x().optional()}).optional(),annotations:je.optional(),_meta:M(x(),h()).optional()}),rt=T({type:w(`tool_result`),toolUseId:x(),content:O(ke),structuredContent:h().optional(),isError:A().optional(),_meta:M(x(),h()).optional()}),it=j([Ce,we,Te,Ee,rt]),at=T({role:a,content:j([it,O(it)]),_meta:M(x(),h()).optional()}),ot=x(),st=k({[Le]:b.optional().catch(void 0)}),ct=st.optional();function H(e){return k({_meta:ct,resultType:ot.default(`complete`),...e})}let lt=H({}),ut=H({nextCursor:r.optional()}),dt=H({content:O(ke),structuredContent:h().optional(),isError:A().optional()}),ft=H({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`]),tools:O(nt),nextCursor:r.optional()}),pt=H({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`]),prompts:O(xe),nextCursor:r.optional()}),mt=H({description:x().optional(),messages:O(Ae)}),ht=H({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`]),resources:O(ge),nextCursor:r.optional()}),gt=H({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`]),resourceTemplates:O(_e),nextCursor:r.optional()}),_t=H({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`]),contents:O(j([he,N]))}),vt=H({completion:T({values:O(x()).max(100),total:E().int().optional(),hasMore:A().optional()}).loose()}),yt=H({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`])}),bt=H({ttlMs:E().int().min(0).catch(0),cacheScope:D([`public`,`private`]).catch(`private`),supportedVersions:O(x()),capabilities:et,instructions:x().optional()}),xt=T({messages:O(at),modelPreferences:Pe.optional(),systemPrompt:x().optional(),includeContext:D([`none`,`thisServer`,`allServers`]).optional(),temperature:E().optional(),maxTokens:E().int(),stopSequences:O(x()).optional(),metadata:t.optional(),tools:O(nt).optional(),toolChoice:ze.optional()}),St=T({method:w(`sampling/createMessage`),params:xt}),Ct=T({method:w(`roots/list`),params:T({_meta:M(x(),h()).optional()}).optional()}),wt=T({...at.shape,model:x(),stopReason:x().optional()}),Tt=T({roots:O(Xe)}),Et=T({action:D([`accept`,`decline`,`cancel`]),content:M(x(),j([x(),E(),A(),O(x())])).optional()}),Dt=T({mode:w(`url`),message:x(),url:x().url()}),Ot=j([B,Dt]),kt=T({method:w(`elicitation/create`),params:Ot}),At=j([St,Ct,kt]),jt=j([wt,Tt,Et]),Mt=M(x(),At),Nt=M(x(),jt),Pt=H({inputRequests:Mt.optional(),requestState:x().optional()}),Ft={inputResponses:Nt.optional(),requestState:x().optional()},It=T({_meta:tt,...Ft}),Lt=k({progressToken:n.optional()});function U(e,t){return T({method:w(e),params:T({_meta:tt,...t})})}function W(e,t){return T({method:w(e),params:T({_meta:Lt.optional(),...t}).optional()})}let Rt={name:x(),arguments:M(x(),h()).optional(),...Ft},zt={cursor:r.optional()},Bt=U(`tools/call`,Rt),Vt=U(`tools/list`,zt),Ht=U(`prompts/list`,zt),Ut=U(`prompts/get`,{name:x(),arguments:M(x(),x()).optional(),...Ft}),Wt=U(`resources/list`,zt),Gt=U(`resources/templates/list`,zt),Kt=U(`resources/read`,{uri:x(),...Ft}),qt={ref:j([V,Ye]),argument:T({name:x(),value:x()}),context:T({arguments:M(x(),x()).optional()}).optional()},Jt=U(`completion/complete`,qt),Yt=U(`server/discover`,{}),Xt=T({toolsListChanged:A().optional(),promptsListChanged:A().optional(),resourcesListChanged:A().optional(),resourceSubscriptions:O(x()).optional()}),Zt={notifications:Xt},Qt=U(`subscriptions/listen`,Zt),$t=st.extend({"io.modelcontextprotocol/subscriptionId":i}),en=k({_meta:$t,resultType:ot.default(`complete`)}),tn={"tools/call":W(`tools/call`,Rt),"tools/list":W(`tools/list`,zt),"prompts/get":W(`prompts/get`,{name:x(),arguments:M(x(),x()).optional()}),"prompts/list":W(`prompts/list`,zt),"resources/list":W(`resources/list`,zt),"resources/templates/list":W(`resources/templates/list`,zt),"resources/read":W(`resources/read`,{uri:x()}),"completion/complete":W(`completion/complete`,qt),"server/discover":W(`server/discover`,{}),"subscriptions/listen":W(`subscriptions/listen`,Zt)};function G(e){return k({_meta:ct,...e})}let nn={"tools/call":G({content:O(ke),structuredContent:h().optional(),isError:A().optional()}),"tools/list":G({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`]),tools:O(nt),nextCursor:r.optional()}),"prompts/get":G({description:x().optional(),messages:O(Ae)}),"prompts/list":G({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`]),prompts:O(xe),nextCursor:r.optional()}),"resources/list":G({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`]),resources:O(ge),nextCursor:r.optional()}),"resources/templates/list":G({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`]),resourceTemplates:O(_e),nextCursor:r.optional()}),"resources/read":G({ttlMs:E().int().min(0),cacheScope:D([`public`,`private`]),contents:O(j([he,N]))}),"completion/complete":G({completion:T({values:O(x()).max(100),total:E().int().optional(),hasMore:A().optional()}).loose()}),"server/discover":G({ttlMs:E().int().min(0).catch(0),cacheScope:D([`public`,`private`]).catch(`private`),supportedVersions:O(x()),capabilities:et,instructions:x().optional()}),"subscriptions/listen":G({})},rn=k({"io.modelcontextprotocol/subscriptionId":i.optional()}),an=T({method:w(`notifications/subscriptions/acknowledged`),params:T({_meta:rn.optional(),notifications:Xt})}),on=T({_meta:rn.optional(),requestId:i,reason:x().optional()}),sn=T({method:w(`notifications/cancelled`),params:on}),cn={"notifications/cancelled":sn,"notifications/progress":ue,"notifications/message":fe,"notifications/resources/updated":be,"notifications/resources/list_changed":ve,"notifications/tools/list_changed":Me,"notifications/prompts/list_changed":Se,"notifications/subscriptions/acknowledged":an},K=e=>T({jsonrpc:w(`2.0`),id:j([x(),E().int()]),result:e}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,RequestIdSchema:i,RoleSchema:a,LoggingLevelSchema:o,TaskMetadataSchema:c,RelatedTaskMetadataSchema:l,RequestMetaSchema:u,BaseRequestParamsSchema:d,TaskAugmentedRequestParamsSchema:f,NotificationsParamsSchema:p,NotificationSchema:m,IconSchema:g,IconsSchema:_,BaseMetadataSchema:v,ImplementationSchema:b,ClientTasksCapabilitySchema:te,ServerTasksCapabilitySchema:ne,ClientCapabilitiesSchema:re,ServerCapabilitiesSchema:ie,ProgressSchema:oe,ProgressNotificationParamsSchema:le,ProgressNotificationSchema:ue,LoggingMessageNotificationParamsSchema:de,LoggingMessageNotificationSchema:fe,ResourceContentsSchema:me,TextResourceContentsSchema:he,BlobResourceContentsSchema:N,AnnotationsSchema:P,ResourceSchema:ge,ResourceTemplateSchema:_e,ResourceListChangedNotificationSchema:ve,ResourceUpdatedNotificationParamsSchema:ye,ResourceUpdatedNotificationSchema:be,PromptArgumentSchema:F,PromptSchema:xe,PromptListChangedNotificationSchema:Se,TextContentSchema:Ce,ImageContentSchema:we,AudioContentSchema:Te,ToolUseContentSchema:Ee,EmbeddedResourceSchema:De,ResourceLinkSchema:Oe,ContentBlockSchema:ke,PromptMessageSchema:Ae,ToolAnnotationsSchema:je,ToolListChangedNotificationSchema:Me,ModelHintSchema:Ne,ModelPreferencesSchema:Pe,ToolChoiceSchema:ze,BooleanSchemaSchema:Ve,StringSchemaSchema:I,NumberSchemaSchema:He,UntitledSingleSelectEnumSchemaSchema:Ue,TitledSingleSelectEnumSchemaSchema:We,LegacyTitledEnumSchemaSchema:Ge,SingleSelectEnumSchemaSchema:Ke,UntitledMultiSelectEnumSchemaSchema:qe,TitledMultiSelectEnumSchemaSchema:L,MultiSelectEnumSchemaSchema:Je,EnumSchemaSchema:R,PrimitiveSchemaDefinitionSchema:z,ElicitRequestFormParamsSchema:B,ResourceTemplateReferenceSchema:Ye,PromptReferenceSchema:V,RootSchema:Xe,ClientCapabilities2026Schema:Qe,ServerCapabilities2026Schema:et,RequestMetaEnvelopeSchema:tt,ToolSchema:nt,ToolResultContentSchema:rt,SamplingMessageContentBlockSchema:it,SamplingMessageSchema:at,ResultTypeSchema:ot,ResultMetaSchema:st,ResultSchema:lt,PaginatedResultSchema:ut,CallToolResultSchema:dt,ListToolsResultSchema:ft,ListPromptsResultSchema:pt,GetPromptResultSchema:mt,ListResourcesResultSchema:ht,ListResourceTemplatesResultSchema:gt,ReadResourceResultSchema:_t,CompleteResultSchema:vt,CacheableResultSchema:yt,DiscoverResultSchema:bt,CreateMessageRequestParamsSchema:xt,CreateMessageRequestSchema:St,ListRootsRequestSchema:Ct,CreateMessageResultSchema:wt,ListRootsResultSchema:Tt,ElicitResultSchema:Et,ElicitRequestURLParamsSchema:Dt,ElicitRequestParamsSchema:Ot,ElicitRequestSchema:kt,InputRequestSchema:At,InputResponseSchema:jt,InputRequestsSchema:Mt,InputResponsesSchema:Nt,InputRequiredResultSchema:Pt,InputResponseRequestParamsSchema:It,CallToolRequestSchema:Bt,ListToolsRequestSchema:Vt,ListPromptsRequestSchema:Ht,GetPromptRequestSchema:Ut,ListResourcesRequestSchema:Wt,ListResourceTemplatesRequestSchema:Gt,ReadResourceRequestSchema:Kt,CompleteRequestSchema:Jt,DiscoverRequestSchema:Yt,SubscriptionFilterSchema:Xt,SubscriptionsListenRequestSchema:Qt,SubscriptionsListenResultMetaSchema:$t,SubscriptionsListenResultSchema:en,dispatchRequestSchemas:tn,dispatchResultSchemas:nn,NotificationMetaSchema:rn,SubscriptionsAcknowledgedNotificationSchema:an,CancelledNotificationParamsSchema:on,CancelledNotificationSchema:sn,notificationSchemas2026:cn,JSONRPCResultResponseSchema:K(lt),CallToolResultResponseSchema:K(j([dt,Pt])),ListToolsResultResponseSchema:K(ft),ListPromptsResultResponseSchema:K(pt),GetPromptResultResponseSchema:K(j([mt,Pt])),ListResourcesResultResponseSchema:K(ht),ListResourceTemplatesResultResponseSchema:K(gt),ReadResourceResultResponseSchema:K(j([_t,Pt])),CompleteResultResponseSchema:K(vt),DiscoverResultResponseSchema:K(bt),SubscriptionsListenResultResponseSchema:K(en)}}var Bi;function Vi(){return Bi??=zi()}var Hi=[`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`resources/read`,`server/discover`];function Ui(e){return Hi.includes(e)}var Wi=Symbol(`modelcontextprotocol.resultCacheHintFallback`);function Gi(e){return e[Wi]}function Ki(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function qi(e){return e===`public`||e===`private`}var X=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.MissingRequiredClientCapability=-32021]=`MissingRequiredClientCapability`,e[e.UnsupportedProtocolVersion=-32022]=`UnsupportedProtocolVersion`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({}),Z=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ProtocolError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`,Qr(this,new.target)}static fromError(t,n,r){if(t===X.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Yi(e.elicitations,n)}if(t===X.UnsupportedProtocolVersion&&r){let e=r;if(Array.isArray(e.supported)&&typeof e.requested==`string`)return new Xi({supported:e.supported,requested:e.requested},n)}if(t===X.InvalidParams||t===X.ResourceNotFound){let e=r;if(typeof e?.uri==`string`&&(t===X.ResourceNotFound||Object.keys(e).length===1))return new Ji(e.uri,n)}if(t===X.MissingRequiredClientCapability&&r){let e=r;if(e.requiredCapabilities!==null&&typeof e.requiredCapabilities==`object`&&!Array.isArray(e.requiredCapabilities))return new Zi({requiredCapabilities:e.requiredCapabilities},n)}return new e(t,n,r)}},Ji=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ResourceNotFoundError`})}constructor(e,t=`Resource not found: ${e}`){super(X.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Yi=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UrlElicitationRequiredError`})}constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(X.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Xi=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnsupportedProtocolVersionError`})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(X.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Zi=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.MissingRequiredClientCapabilityError`})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(`, `)}`){super(X.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},Qi=0,$i=`private`,ea=[`tools/call`,`prompts/get`,`resources/read`];function ta(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:`complete`};if(n===`complete`||ea.includes(e))return t;throw new Z(X.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function na(e,t){let n=Gi(t);if(t.resultType!==`complete`||!Ui(e))return n===void 0?t:sa(t);let r=t,i=Ki(r.ttlMs)?r.ttlMs:aa(n),a=qi(r.cacheScope)?r.cacheScope:oa(n),o={...r,ttlMs:i,cacheScope:a};return delete o[Wi],o}function ra(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ia(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[Le]:t}}:!ra(n)||n[`io.modelcontextprotocol/serverInfo`]!==void 0?e:{...e,_meta:{...n,[Le]:t}}}function aa(e){return e!==void 0&&Ki(e.ttlMs)?e.ttlMs:Qi}function oa(e){return e!==void 0&&qi(e.cacheScope)?e.cacheScope:$i}function sa(e){let t={...e};return delete t[Wi],t}var ca=[`elicitation/create`,`sampling/createMessage`,`roots/list`],la;function ua(){if(la)return la;let e=Vi();return la={request:{"elicitation/create":T({method:w(`elicitation/create`),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":T({method:w(`sampling/createMessage`),params:e.CreateMessageRequestParamsSchema}),"roots/list":T({method:w(`roots/list`),params:k({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},la}function da(e){return ca.includes(e)}function fa(e){return da(e)?ua().request[e]:void 0}function pa(e){return da(e)?ua().response[e]:void 0}var ma={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},ha={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function ga(e){return Object.prototype.hasOwnProperty.call(ma,e)}function _a(e){return Object.prototype.hasOwnProperty.call(ha,e)}function va(e){return Object.prototype.hasOwnProperty.call(ma,e)}function ya(e){return ga(e)?Vi().dispatchRequestSchemas[e]:void 0}function ba(e){return va(e)?Vi().dispatchResultSchemas[e]:void 0}function xa(e){return _a(e)?Vi().notificationSchemas2026[e]:void 0}Object.keys(ma),Object.keys(ha);function Sa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ca(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}var wa={ok:!1,reason:`not-in-era`},Ta=[Fe,Re];function Ea(e,t){let n=t,r=!1,i=()=>(r||=(n={...n},!0),n),a=t.tools;e===`tools/list`&&Array.isArray(a)&&a.some(e=>Sa(e)&&`execution`in e)&&(i().tools=a.map(e=>{if(!Sa(e)||!(`execution`in e))return e;let t={...e};return delete t.execution,t}));let o=t.capabilities;if(Sa(o)&&`tasks`in o){let e={...o};delete e.tasks,i().capabilities=e}return n}var Da={era:`2026-07-28`,hasRequestMethod:ga,hasNotificationMethod:_a,hasInputRequestMethod:e=>fa(e)!==void 0,validateRequest:(e,t)=>Ca(ya(e),t),validateResult:(e,t)=>Ca(ba(e),t),validateNotification:(e,t)=>Ca(xa(e),t),validateInputRequest:(e,t)=>Ca(fa(e),t),validateInputResponse:(e,t)=>Ca(pa(e),t),samplingResultVariant:()=>wa,outboundEnvelope(e){return{[Fe]:e.protocolVersion,[Ie]:e.clientInfo,[Re]:e.clientCapabilities,...e.logLevel!==void 0&&{"io.modelcontextprotocol/logLevel":e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of Ta)n in e||t.push({key:n,problem:`missing`});let n=Vi().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let e of n.error.issues){let n=e.path.map(String),r=n.length>0?n.join(`.`):`_meta`;n.length===1&&t.some(e=>e.key===r&&e.problem===`missing`)||t.push({key:r,problem:e.message})}return t},projectCallToolResult:e=>di(e),inputRequestSchema:fa,decodeResult(e,t){if(!Sa(t))return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:`missing-resultType`})};if(typeof n!=`string`)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n===`input_required`){let n=t.inputRequests,r=Sa(n)?n:{},i=t.requestState,a=t._meta===void 0?void 0:Vi().ResultMetaSchema.safeParse(t._meta),o=a?.success?a.data:void 0;return Object.keys(r).length===0&&typeof i!=`string`?{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:`input-required-missing-both`})}:{kind:`input_required`,inputRequests:r,...typeof i==`string`&&{requestState:i},...o!==void 0&&{_meta:o}}}if(n!==`complete`)return{kind:`invalid`,error:new Y(J.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let r=ka(),i=Object.hasOwn(r,e)?r[e]:void 0;if(i!==void 0){let n=i.safeParse(t);if(!n.success)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: ${n.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:`complete`,result:a}},encodeResult(e,t,n){return ia(na(e,ta(e,Ea(e,t))),n)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return`Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)`;let t=Vi().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(e=>e.message).join(`; `)}`}},Oa;function ka(){if(Oa)return Oa;let e=Vi();return Oa={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Oa}var Aa=`2026-07-28`;function ja(e){return e!==void 0&&ci(e)?Da:Ri}function Ma(e){return e.revision===void 0?e.era===`modern`?Da.era:Ri.era:ja(e.revision).era}function Na(e){return Ia.some(t=>t.hasRequestMethod(e))}function Pa(e){return Ia.some(t=>t.hasNotificationMethod(e))}function Fa(e){return e===`tasks/get`||e===`tasks/cancel`}var Ia=[Ri,Da],La=Ce({AnnotationsSchema:()=>Nt,AudioContentSchema:()=>ln,BaseMetadataSchema:()=>ct,BaseRequestParamsSchema:()=>L,BlobResourceContentsSchema:()=>jt,BooleanSchemaSchema:()=>Wn,CallToolRequestParamsSchema:()=>wn,CallToolRequestSchema:()=>Tn,CallToolResultSchema:()=>Sn,CancelTaskRequestSchema:()=>Ar,CancelTaskResultSchema:()=>jr,CancelledNotificationParamsSchema:()=>it,CancelledNotificationSchema:()=>at,ClientCapabilitiesSchema:()=>pt,ClientNotificationSchema:()=>Nr,ClientRequestSchema:()=>Mr,ClientResultSchema:()=>Pr,ClientTasksCapabilitySchema:()=>dt,CompatibilityCallToolResultSchema:()=>Cn,CompleteRequestParamsSchema:()=>dr,CompleteRequestSchema:()=>fr,CompleteResultSchema:()=>pr,ContentBlockSchema:()=>pn,CreateMessageRequestParamsSchema:()=>Bn,CreateMessageRequestSchema:()=>Vn,CreateMessageResultSchema:()=>Hn,CreateMessageResultWithToolsSchema:()=>Un,CreateTaskResultSchema:()=>xr,CursorSchema:()=>We,DiscoverRequestSchema:()=>yt,DiscoverResultSchema:()=>bt,ElicitRequestFormParamsSchema:()=>nr,ElicitRequestParamsSchema:()=>ir,ElicitRequestSchema:()=>ar,ElicitRequestURLParamsSchema:()=>rr,ElicitResultSchema:()=>cr,ElicitationCompleteNotificationParamsSchema:()=>or,ElicitationCompleteNotificationSchema:()=>sr,EmbeddedResourceSchema:()=>dn,EmptyResultSchema:()=>rt,EnumSchemaSchema:()=>er,GetPromptRequestParamsSchema:()=>on,GetPromptRequestSchema:()=>sn,GetPromptResultSchema:()=>hn,GetTaskPayloadRequestSchema:()=>Er,GetTaskPayloadResultSchema:()=>Dr,GetTaskRequestSchema:()=>wr,GetTaskResultSchema:()=>Tr,IconSchema:()=>ot,IconsSchema:()=>st,ImageContentSchema:()=>K,ImplementationSchema:()=>H,InitializeRequestParamsSchema:()=>mt,InitializeRequestSchema:()=>ht,InitializeResultSchema:()=>_t,InitializedNotificationSchema:()=>vt,JSONArraySchema:()=>He,JSONObjectSchema:()=>I,JSONRPCErrorResponseSchema:()=>et,JSONRPCMessageSchema:()=>tt,JSONRPCNotificationSchema:()=>Qe,JSONRPCRequestSchema:()=>Ze,JSONRPCResponseSchema:()=>nt,JSONRPCResultResponseSchema:()=>$e,JSONValueSchema:()=>Ve,LegacyTitledEnumSchemaSchema:()=>Yn,ListChangedOptionsBaseSchema:()=>Dn,ListPromptsRequestSchema:()=>rn,ListPromptsResultSchema:()=>an,ListResourceTemplatesRequestSchema:()=>U,ListResourceTemplatesResultSchema:()=>W,ListResourcesRequestSchema:()=>It,ListResourcesResultSchema:()=>Lt,ListRootsRequestSchema:()=>hr,ListRootsResultSchema:()=>gr,ListTasksRequestSchema:()=>Or,ListTasksResultSchema:()=>kr,ListToolsRequestSchema:()=>bn,ListToolsResultSchema:()=>xn,LoggingLevelSchema:()=>On,LoggingMessageNotificationParamsSchema:()=>jn,LoggingMessageNotificationSchema:()=>Mn,ModelHintSchema:()=>Nn,ModelPreferencesSchema:()=>Pn,MultiSelectEnumSchemaSchema:()=>$n,NotificationSchema:()=>B,NotificationsParamsSchema:()=>z,NumberSchemaSchema:()=>Kn,PaginatedRequestParamsSchema:()=>Tt,PaginatedRequestSchema:()=>Et,PaginatedResultSchema:()=>Dt,PingRequestSchema:()=>xt,PrimitiveSchemaDefinitionSchema:()=>tr,ProgressNotificationParamsSchema:()=>Ct,ProgressNotificationSchema:()=>wt,ProgressSchema:()=>St,ProgressTokenSchema:()=>Ue,PromptArgumentSchema:()=>G,PromptListChangedNotificationSchema:()=>gn,PromptMessageSchema:()=>mn,PromptReferenceSchema:()=>ur,PromptSchema:()=>nn,ReadResourceRequestParamsSchema:()=>zt,ReadResourceRequestSchema:()=>Bt,ReadResourceResultSchema:()=>Vt,RelatedTaskMetadataSchema:()=>Ke,RequestIdSchema:()=>Xe,RequestMetaSchema:()=>qe,RequestSchema:()=>R,ResourceContentsSchema:()=>Ot,ResourceLinkSchema:()=>fn,ResourceListChangedNotificationSchema:()=>Ht,ResourceRequestParamsSchema:()=>Rt,ResourceSchema:()=>Pt,ResourceTemplateReferenceSchema:()=>lr,ResourceTemplateSchema:()=>Ft,ResourceUpdatedNotificationParamsSchema:()=>en,ResourceUpdatedNotificationSchema:()=>tn,ResultMetaObjectSchema:()=>Ye,ResultSchema:()=>V,RoleSchema:()=>Mt,RootSchema:()=>mr,RootsListChangedNotificationSchema:()=>_r,SamplingContentSchema:()=>Ln,SamplingMessageContentBlockSchema:()=>Rn,SamplingMessageSchema:()=>zn,ServerCapabilitiesSchema:()=>gt,ServerNotificationSchema:()=>Ir,ServerRequestSchema:()=>Fr,ServerResultSchema:()=>Lr,ServerTasksCapabilitySchema:()=>ft,SetLevelRequestParamsSchema:()=>kn,SetLevelRequestSchema:()=>An,SingleSelectEnumSchemaSchema:()=>Xn,StringSchemaSchema:()=>Gn,SubscribeRequestParamsSchema:()=>Ut,SubscribeRequestSchema:()=>Wt,SubscriptionFilterSchema:()=>qt,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Xt,SubscriptionsAcknowledgedNotificationSchema:()=>Zt,SubscriptionsListenRequestParamsSchema:()=>Jt,SubscriptionsListenRequestSchema:()=>Yt,SubscriptionsListenResultMetaSchema:()=>Qt,SubscriptionsListenResultSchema:()=>$t,TaskAugmentedRequestParamsSchema:()=>Je,TaskCreationParamsSchema:()=>vr,TaskMetadataSchema:()=>Ge,TaskSchema:()=>br,TaskStatusNotificationParamsSchema:()=>Sr,TaskStatusNotificationSchema:()=>Cr,TaskStatusSchema:()=>yr,TextContentSchema:()=>cn,TextResourceContentsSchema:()=>kt,TitledMultiSelectEnumSchemaSchema:()=>Qn,TitledSingleSelectEnumSchemaSchema:()=>Jn,ToolAnnotationsSchema:()=>_n,ToolChoiceSchema:()=>Fn,ToolExecutionSchema:()=>vn,ToolListChangedNotificationSchema:()=>En,ToolResultContentSchema:()=>In,ToolSchema:()=>yn,ToolUseContentSchema:()=>un,UnsubscribeRequestParamsSchema:()=>Gt,UnsubscribeRequestSchema:()=>Kt,UntitledMultiSelectEnumSchemaSchema:()=>Zn,UntitledSingleSelectEnumSchemaSchema:()=>qn}),Ra=e=>Ze.safeParse(e).success,za=e=>Qe.safeParse(e).success,Ba=e=>$e.safeParse(e).success,Va=e=>et.safeParse(e).success,Ha=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.resultType===`input_required`,Ua=e=>ht.safeParse(e).success,Wa=e=>vt.safeParse(e).success,Ga=`Mcp-Param-`,Ka=`x-mcp-header`,qa=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Ja=new Set([`string`,`integer`,`boolean`,`number`]);function Ya(e){let t=[],n=new Map,r=(e,i,a)=>{if(typeof e!=`object`||!e)return;let o=e;if(Ka in o){if(!a||i.length===0)return`${Qa(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let e=o[Ka];if(typeof e!=`string`||e.length===0)return`${Qa(i)}: x-mcp-header MUST be a non-empty string`;if(!qa.test(e))return`${Qa(i)}: x-mcp-header '${e}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let r=typeof o.type==`string`?o.type:void 0;if(r===void 0||!Ja.has(r))return`${Qa(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${r??``}`;let s=e.toLowerCase(),c=n.get(s);if(c!==void 0)return`x-mcp-header '${e}' is not case-insensitively unique (also declared as '${c}')`;n.set(s,e),t.push({path:i,headerName:e,type:r})}let s=o.properties;if(typeof s==`object`&&s)for(let[e,t]of Object.entries(s)){let n=r(t,[...i,e],a);if(n!==void 0)return n}for(let e of Xa){let t=o[e];if(t===void 0)continue;let n=Array.isArray(t)?t:typeof t==`object`&&t&&Za.has(e)?Object.values(t):[t];for(let t of n){let n=r(t,[...i,`<${e}>`],!1);if(n!==void 0)return n}}},i=r(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}var Xa=[`items`,`prefixItems`,`contains`,`additionalProperties`,`unevaluatedProperties`,`unevaluatedItems`,`propertyNames`,`patternProperties`,`dependentSchemas`,`oneOf`,`anyOf`,`allOf`,`not`,`if`,`then`,`else`,`$defs`,`definitions`],Za=new Set([`patternProperties`,`dependentSchemas`,`$defs`,`definitions`]);function Qa(e){return e.length===0?``:e.join(`.`)}var $a=`=?base64?`,eo=`?=`;function to(e){if(typeof e==`string`)return e;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function no(e){if(e.length===0||e.startsWith($a)&&e.endsWith(eo)||e!==e.trim())return!0;for(let t=0;t=32&&n<=126))return!0}return!1}function ro(e){let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCodePoint(e);return btoa(n)}function io(e){return no(e)?`${$a}${ro(e)}${eo}`:e}function ao(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function oo(e,t){let n={};for(let r of e){let e=ao(t,r.path);if(e==null)continue;let i=to(e);i!==void 0&&(n[`${Ga}${r.headerName}`]=io(i))}return n}X.InvalidRequest,X.UnsupportedProtocolVersion,X.InvalidParams,X.MethodNotFound,X.InvalidParams,X.MissingRequiredClientCapability,X.ParseError,X.InvalidRequest,X.MethodNotFound,X.UnsupportedProtocolVersion,X.MissingRequiredClientCapability;var so={"tools/call":`name`,"prompts/get":`name`,"resources/read":`uri`,"tasks/get":`taskId`,"tasks/update":`taskId`,"tasks/cancel":`taskId`};function co(e,t){let n=Object.hasOwn(so,e)?so[e]:void 0;if(n===void 0)return;let r=lo(t)?t[n]:void 0;return{field:n,value:typeof r==`string`?r:void 0}}function lo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function uo(e,t){return le(e,t)}function fo(e){return new Set(e.flatMap(e=>Object.keys(e.shape)))}function po(e){if(e==null)return!1;let t=typeof e;return t!==`object`&&t!==`function`||!(`~standard`in e)?!1:typeof e[`~standard`]?.validate==`function`}var mo=!1,ho=`draft-2020-12`;function go(e,t=`input`){let n=e[`~standard`],r;if(n.jsonSchema)r=n.jsonSchema[t]({target:ho});else if(n.vendor===`zod`){if(!(`_zod`in e))throw Error(`Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().`);mo||(mo=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),r=g(e,{target:ho,io:t})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t===`output`)return r.type===void 0&&_o(r)?{type:`object`,...r}:r;if(r.type!==void 0&&r.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(r.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...r}}function _o(e){if(`properties`in e||`patternProperties`in e||`additionalProperties`in e||`required`in e)return!0;for(let t of[`oneOf`,`anyOf`,`allOf`]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(e=>typeof e==`object`&&!!e&&(e.type===`object`||_o(e)))}return!1}function vo(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function yo(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>vo(e)).join(`, `)}:{success:!0,data:n.value}}function bo(e){let t=g(e,{target:ho,io:`input`});return typeof t.pattern==`string`?t.pattern:void 0}var xo=/\\\.\\d\{(\d+)\}/;function So(e){let t=xo.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(e=>[!1,!0].flatMap(t=>n.map(n=>pe({local:e,offset:t,precision:n}))))}function Co(e,t){let n;switch(e){case`email`:n=[re()];break;case`uri`:n=[d()];break;case`date`:n=[me()];break;case`date-time`:n=So(t)}return new Set(n.map(e=>bo(e)).filter(e=>e!==void 0))}function wo(e,t,n){return n!==`zod`||Co(e,t).has(t)}function To(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Eo(e){try{return go(e,`input`)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Z(X.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}var Do=new Set([`$comment`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function Oo(e){return Do.has(e)||e.startsWith(`x-`)}var ko=new Set([`$schema`,...Object.keys(nr.shape.requestedSchema.shape)]),Ao={string:fo([Gn,qn,Jn,Yn]),number:fo([Kn]),integer:fo([Kn]),boolean:fo([Wn]),array:fo([Zn,Qn])},jo=new Set(Gn.shape.format.unwrap().options);function Mo(e,t,n,r){if(!To(e))return e;let i=typeof e.type==`string`&&Object.hasOwn(Ao,e.type)?Ao[e.type]:void 0;if(i===void 0)return e;let a={};for(let[o,s]of Object.entries(e))i.has(o)||Oo(o)?a[o]=s:o===`pattern`&&e.type===`string`&&typeof e.format==`string`?jo.has(e.format)?(typeof s!=`string`||!wo(e.format,s,n))&&r.push(`${t}.${o}`):a[o]=s:r.push(`${t}.${o}`);return a}function No(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))i===`properties`&&To(a)?n[i]=Object.fromEntries(Object.entries(a).map(([e,n])=>[e,Mo(n,`properties.${e}`,t,r)])):ko.has(i)?n[i]=a:Oo(i)||r.push(i);if(r.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(`, `)}`);return n}function Po(e,t){if(!To(e.properties))return t;let n=Object.entries(e.properties).filter(([,e])=>!uo(tr,e).success).map(([e])=>`properties.${e}`);return n.length>0?n.join(`, `):t}function Fo(e,t,n=``){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,r)=>Fo(e,t[r],`${n}[${r}]`)):!To(e)||!To(t)?[]:Object.entries(e).flatMap(([e,r])=>{let i=n?`${n}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?Fo(r,t[e],i):Oo(e)?[]:[i]})}function Io(e){if(!po(e.requestedSchema))return{...e,mode:`form`,requestedSchema:e.requestedSchema};let t=e.requestedSchema[`~standard`].vendor,n=No(Eo(e.requestedSchema),t),r=uo(nr.shape.requestedSchema,n);if(!r.success)throw new Z(X.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Po(n,r.error.message)}`);let i=Fo(n,r.data);if(i.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(`, `)}`);let a=(r.data.required??[]).filter(e=>!Object.prototype.hasOwnProperty.call(r.data.properties,e));if(a.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(`, `)}`);return{...e,mode:`form`,requestedSchema:r.data}}function Lo(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState==`string`;if(!t&&!n)throw TypeError(`inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)`);return{resultType:`input_required`,...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}Object.assign(Lo,{elicit(e){try{return{method:`elicitation/create`,params:Io(e)}}catch(e){throw e instanceof Z?TypeError(e.message,{cause:e}):e}},elicitUrl(e){return{method:`elicitation/create`,params:{...e,mode:`url`}}},createMessage(e){return{method:`sampling/createMessage`,params:e}},listRoots(){return{method:`roots/list`}}});var Ro=!0,zo=10,Bo=250;function Vo(e){return{autoFulfill:e?.autoFulfill??Ro,maxRounds:e?.maxRounds??zo}}function Ho(e,t,n){let r=t!==void 0&&Object.keys(t).length>0;return!r&&n===void 0?e:{...e,...r&&{inputResponses:t},...n!==void 0&&{requestState:n}}}function Uo(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Wo(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason instanceof Y?t.reason:new Y(J.RequestTimeout,String(t.reason)));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason instanceof Y?t.reason:new Y(J.RequestTimeout,String(t?.reason)))};t?.addEventListener(`abort`,a,{once:!0})})}function Go(e){let t=new AbortController,n=()=>t.abort(e?.reason);return e?.addEventListener(`abort`,n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:e=>t.abort(e),dispose:()=>e?.removeEventListener(`abort`,n)}}async function Ko(e){let{config:t,method:n,originalParams:r,requestOptions:i,hooks:a,signal:o}=e,s=e.flowStartedAt??Date.now(),c=e.firstPayload,l=0;for(;;){if(l+=1,l>t.maxRounds)throw new Y(J.InputRequiredRoundsExceeded,Uo(n,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:c.inputRequests,...c.requestState!==void 0&&{requestState:c.requestState}}});i.onprogress?.({progress:l,message:`Fulfilling input required by '${n}' (round ${l})`});let e=Object.entries(c.inputRequests??{}),u;if(e.length>0){let t=Go(o);try{let n=await Promise.all(e.map(async([e,n])=>{try{return[e,await a.dispatchInputRequest(e,n,t.signal)]}catch(e){throw t.abort(e),e}}));u=Object.fromEntries(n)}finally{t.dispose()}}else await Wo(Bo,o);let d={...i.timeout!==void 0&&{timeout:i.timeout}};if(i.maxTotalTimeout!==void 0){let e=Date.now()-s,t=i.maxTotalTimeout-e;if(t<=0)throw new Y(J.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:i.maxTotalTimeout,totalElapsed:e});d.maxTotalTimeout=t}let f=await a.retry(Ho(r,u,c.requestState),d);if(Ha(f)){c={inputRequests:f.inputRequests??{},...f.requestState!==void 0&&{requestState:f.requestState}};continue}return f}}var qo=`AnnotationsSchema.AudioContentSchema.BaseMetadataSchema.BlobResourceContentsSchema.BooleanSchemaSchema.CallToolRequestSchema.CallToolRequestParamsSchema.CallToolResultSchema.CancelledNotificationSchema.CancelledNotificationParamsSchema.CancelTaskRequestSchema.CancelTaskResultSchema.ClientCapabilitiesSchema.ClientNotificationSchema.ClientRequestSchema.ClientResultSchema.CompatibilityCallToolResultSchema.CompleteRequestSchema.CompleteRequestParamsSchema.CompleteResultSchema.ContentBlockSchema.CreateMessageRequestSchema.CreateMessageRequestParamsSchema.CreateMessageResultSchema.CreateMessageResultWithToolsSchema.CreateTaskResultSchema.CursorSchema.DiscoverRequestSchema.DiscoverResultSchema.ElicitationCompleteNotificationSchema.ElicitationCompleteNotificationParamsSchema.ElicitRequestSchema.ElicitRequestFormParamsSchema.ElicitRequestParamsSchema.ElicitRequestURLParamsSchema.ElicitResultSchema.EmbeddedResourceSchema.EmptyResultSchema.EnumSchemaSchema.GetPromptRequestSchema.GetPromptRequestParamsSchema.GetPromptResultSchema.GetTaskPayloadRequestSchema.GetTaskPayloadResultSchema.GetTaskRequestSchema.GetTaskResultSchema.IconSchema.IconsSchema.ImageContentSchema.ImplementationSchema.InitializedNotificationSchema.InitializeRequestSchema.InitializeRequestParamsSchema.InitializeResultSchema.JSONArraySchema.JSONObjectSchema.JSONRPCErrorResponseSchema.JSONRPCMessageSchema.JSONRPCNotificationSchema.JSONRPCRequestSchema.JSONRPCResponseSchema.JSONRPCResultResponseSchema.JSONValueSchema.LegacyTitledEnumSchemaSchema.ListPromptsRequestSchema.ListPromptsResultSchema.ListResourcesRequestSchema.ListResourcesResultSchema.ListResourceTemplatesRequestSchema.ListResourceTemplatesResultSchema.ListRootsRequestSchema.ListRootsResultSchema.ListTasksRequestSchema.ListTasksResultSchema.ListToolsRequestSchema.ListToolsResultSchema.LoggingLevelSchema.LoggingMessageNotificationSchema.LoggingMessageNotificationParamsSchema.ModelHintSchema.ModelPreferencesSchema.MultiSelectEnumSchemaSchema.NotificationSchema.NumberSchemaSchema.PaginatedRequestSchema.PaginatedRequestParamsSchema.PaginatedResultSchema.PingRequestSchema.PrimitiveSchemaDefinitionSchema.ProgressSchema.ProgressNotificationSchema.ProgressNotificationParamsSchema.ProgressTokenSchema.PromptSchema.PromptArgumentSchema.PromptListChangedNotificationSchema.PromptMessageSchema.PromptReferenceSchema.ReadResourceRequestSchema.ReadResourceRequestParamsSchema.ReadResourceResultSchema.RelatedTaskMetadataSchema.RequestSchema.RequestIdSchema.RequestMetaSchema.ResourceSchema.ResourceContentsSchema.ResourceLinkSchema.ResourceListChangedNotificationSchema.ResourceRequestParamsSchema.ResourceTemplateSchema.ResourceTemplateReferenceSchema.ResourceUpdatedNotificationSchema.ResourceUpdatedNotificationParamsSchema.ResultMetaObjectSchema.ResultSchema.RoleSchema.RootSchema.RootsListChangedNotificationSchema.SamplingContentSchema.SamplingMessageSchema.SamplingMessageContentBlockSchema.ServerCapabilitiesSchema.ServerNotificationSchema.ServerRequestSchema.ServerResultSchema.SetLevelRequestSchema.SetLevelRequestParamsSchema.SingleSelectEnumSchemaSchema.StringSchemaSchema.SubscribeRequestSchema.SubscribeRequestParamsSchema.SubscriptionFilterSchema.SubscriptionsAcknowledgedNotificationSchema.SubscriptionsAcknowledgedNotificationParamsSchema.SubscriptionsListenRequestSchema.SubscriptionsListenRequestParamsSchema.SubscriptionsListenResultSchema.SubscriptionsListenResultMetaSchema.TaskAugmentedRequestParamsSchema.TaskCreationParamsSchema.TaskMetadataSchema.TaskSchema.TaskStatusSchema.TaskStatusNotificationSchema.TaskStatusNotificationParamsSchema.TextContentSchema.TextResourceContentsSchema.TitledMultiSelectEnumSchemaSchema.TitledSingleSelectEnumSchemaSchema.ToolSchema.ToolAnnotationsSchema.ToolChoiceSchema.ToolExecutionSchema.ToolListChangedNotificationSchema.ToolResultContentSchema.ToolUseContentSchema.UnsubscribeRequestSchema.UnsubscribeRequestParamsSchema.UntitledMultiSelectEnumSchemaSchema.UntitledSingleSelectEnumSchemaSchema`.split(`.`),Jo={IdJagTokenExchangeResponseSchema:Ur,OAuthClientInformationFullSchema:Jr,OAuthClientInformationSchema:qr,OAuthClientMetadataSchema:Kr,OAuthClientRegistrationErrorSchema:Yr,OAuthErrorResponseSchema:Wr,OAuthMetadataSchema:zr,OAuthProtectedResourceMetadataSchema:Rr,OAuthTokenRevocationRequestSchema:Xr,OAuthTokensSchema:Hr,OpenIdProviderDiscoveryMetadataSchema:Vr,OpenIdProviderMetadataSchema:Br},Yo={},Xo={};function Zo(e,t){let n=e.slice(0,-6);Yo[n]=t,Xo[n]=e=>t.safeParse(e).success}for(let e of qo)Zo(e,La[e]);for(let[e,t]of Object.entries(Jo))Zo(e,t);Object.freeze(Yo);var Qo=Object.freeze(Xo);function $o(e){switch(e){case`initialize`:case`notifications/initialized`:return ja(void 0);case`server/discover`:return ja(Aa);default:return}}var es=[Fe,Ie,Re,Be],ts=[`inputResponses`,`requestState`];function ns(e,t){let n=e.params;if(!ss(n))return{message:e,lifted:{}};let r=n._meta,i=ss(r)?es.filter(e=>e in r):[],a=t===`request`?ts.filter(e=>e in n):[];if(i.length===0&&a.length===0)return{message:e,lifted:{}};let o={},s={...n};if(i.length>0&&ss(r)){let e={},t={...r};for(let n of i)e[n]=r[n],delete t[n];o.envelope=e,Object.keys(t).length>0?s._meta=t:delete s._meta}for(let e of a)e===`inputResponses`&&(o.inputResponses=s[e]),e===`requestState`&&(o.requestState=s[e]),delete s[e];return{message:{...e,params:s},lifted:o}}function rs(e,t){let n=e.validateResult(t,void 0);if(n.ok||n.reason!==`not-in-era`)return{"~standard":{version:1,vendor:`mcp-wire-codec`,validate(n){let r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason===`invalid`?r.message:`not-in-era: ${t}`}]}}}}}function is(e){return()=>e}var as=is(void 0),os=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Ne,this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new Y(J.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Y(J.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),Ba(e)||Va(e)?this._onresponse(e):Ra(e)?this._onrequest(e,t):za(e)?this._onnotification(e,t):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new Y(J.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=ns(e,`notification`),r=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`)return;if(t?.classification!==void 0){let e=Ma(t.classification);if(e!==r.era){this._onerror(Error(`Era mismatch on inbound notification '${n.method}': classified as ${e} but this instance serves ${r.era}`));return}}if(Pa(n.method)&&!r.hasNotificationMethod(n.method))return;let i=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;(i!==void 0||a!==void 0)&&Promise.resolve().then(()=>i===void 0?a(n):i(n,r)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let{message:n,lifted:r}=ns(e,`request`),i=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,o=(e,t,r)=>{let i={jsonrpc:`2.0`,id:n.id,error:{code:e,message:t,...r!==void 0&&{data:r}}};a?.send(i).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))};if(t?.classification!==void 0){let e=Ma(t.classification);if(e!==i.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${e} but this instance serves ${i.era}`));let r=t.classification.revision??e;o(X.UnsupportedProtocolVersion,`Unsupported protocol version: ${r}`,{supported:this._supportedProtocolVersions,requested:r});return}}if(Na(n.method)&&!i.hasRequestMethod(n.method)&&!(Fa(n.method)&&this._customSchemaRequestMethods.has(n.method))){o(X.MethodNotFound,`Method not found`);return}let s=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(s===void 0){o(X.MethodNotFound,`Method not found`);return}let c=i.checkInboundEnvelope(r);if(c!==void 0){o(X.InvalidParams,c);return}let l=(e,t)=>this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,{...t,relatedRequestId:n.id}),u=(e,t,r)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(e.method),e,t,{...r,relatedRequestId:n.id}),d=new AbortController;this._requestHandlerAbortControllers.set(n.id,d);let f=r.inputResponses===void 0?void 0:us(r.inputResponses),p={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...r.envelope!==void 0&&{envelope:r.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:r.requestState===void 0?as:is(r.requestState),signal:d.signal,send:((e,t,n)=>{let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),po(t))return u(e,t,n);let i=rs(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return u(e,i,t)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},m=this.buildContext(p,t);Promise.resolve().then(()=>s(n,m)).then(async e=>{if(d.signal.aborted)return;let t;try{t=i.encodeResult(n.method,e,this._outboundServerInfo())}catch(e){this._onerror(Error(`Failed to encode result for ${n.method}: ${e}`)),o(X.InternalError,`Internal error`);return}let r={result:t,jsonrpc:`2.0`,id:n.id};await a?.send(r)},async e=>{if(d.signal.aborted)return;let t=Number.isSafeInteger(e.code)?e.code:X.InternalError,r={jsonrpc:`2.0`,id:n.id,error:{code:i.encodeErrorCode(t),message:e.message??`Internal error`,...e.data!==void 0&&{data:e.data}}};await a?.send(r)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===d&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Ba(e)?n(e):n(Z.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let r=this._resolveOutboundCodec(e.method);if(po(t))return Fa(e.method)||this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n);this._assertOutboundRequestInEra(r,e.method);let i=rs(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,e,i,t)}_negotiatedWireCodec(){return ja(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=$o(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Na(t)&&!e.hasRequestMethod(t))throw new Y(J.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let r=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n)}_requestWithSchemaViaCodec(e,t,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s}=r??{},c=Date.now(),l,u;return new Promise((d,f)=>{let p=e=>{f(e)};if(!this._transport){p(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(e){p(e);return}if(r?.signal?.aborted){let e=r.signal.reason;throw e instanceof Y?e:new Y(J.RequestTimeout,String(e))}let m=e.era===`2026-07-28`&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;u=h;let g={...t,jsonrpc:`2.0`,id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let _=this._envelopeOutbound(g),v=!1,y=e=>{v||(this._progressHandlers.delete(h),m===void 0?t.method!==`initialize`&&this._transport?.send(this._envelopeOutbound({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:h,reason:String(e)}}),{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))):m.abort(),f(e instanceof Y?e:new Y(J.RequestTimeout,String(e))))};this._responseHandlers.set(h,i=>{if(r?.signal?.aborted)return;if(v=!0,i instanceof Error)return f(i);let a;try{a=e.decodeResult(t.method,i.result)}catch(e){return f(e instanceof Error?e:Error(String(e)))}if(a.kind===`invalid`)return f(a.error);if(a.kind===`input_required`){if(r?.allowInputRequired===!0)return d(gs(a));let i={codec:e,request:t,resultSchema:n,options:r,flowStartedAt:c,retry:(r,i)=>this._requestWithSchemaViaCodec(e,r===void 0?{method:t.method}:{method:t.method,params:r},n,i)};return d(this._resolveNonCompleteResult(a,i))}let o=a.result;yo(n,o).then(e=>{e.success?d(e.data):f(new Y(J.InvalidResult,`Invalid result for ${t.method}: ${e.error}`))},f)}),l=()=>y(r?.signal?.reason),r?.signal?.addEventListener(`abort`,l,{once:!0});let b=r?.timeout??6e4;this._setupTimeout(h,b,r?.maxTotalTimeout,()=>y(new Y(J.RequestTimeout,`Request timed out`,{timeout:b})),r?.resetTimeoutOnProgress??!1),this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s,requestSignal:m?.signal}).catch(e=>{this._progressHandlers.delete(h),f(e)})}).finally(()=>{l&&r?.signal?.removeEventListener(`abort`,l),u!==void 0&&(this._responseHandlers.delete(u),this._cleanupTimeout(u))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new Y(J.NotConnected,`Not connected`);if(Pa(t.method)&&!e.hasNotificationMethod(t.method))throw new Y(J.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let r=this._envelopeOutbound({jsonrpc:`2.0`,...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&n?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(r,n).catch(e=>this._onerror(e))});return}await this._transport.send(r,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let r;if(typeof t==`function`){if(!Na(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(n,r)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason===`not-in-era`&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason===`not-in-era`?new Z(X.InternalError,`No wire schema for ${e} in the resolved era`):Error(a.message);return Promise.resolve(t(a.value,r))}}else if(n)r=async(r,i)=>{let a=await yo(t.params,{...r.params});if(!a.success)throw new Z(X.InvalidParams,`Invalid params for ${e}: ${a.error}`);return n(a.data,i)};else throw TypeError(`setRequestHandler: handler is required`);typeof t==`function`?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,r))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t==`function`){if(!Pa(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{let i=r.validateNotification(e,n);if(!i.ok)throw i.reason===`not-in-era`?new Z(X.InternalError,`No wire schema for ${e} in the resolved era`):Error(i.message);return Promise.resolve(t(i.value))});return}if(!n)throw TypeError(`setNotificationHandler: handler is required`);this._notificationHandlers.set(e,async r=>{let i=await yo(t.params,{...r.params});if(!i.success)throw new Z(X.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await n(i.data,r)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ss(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cs(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=ss(a)&&ss(i)?{...a,...i}:i}return n}function ls(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function us(e){let t={},n=[];if(!ls(e))return{accepted:t,droppedKeys:n};for(let[r,i]of Object.entries(e)){if(!ls(i)||`method`in i||`result`in i){n.push(r);continue}t[r]=i}return{accepted:t,droppedKeys:n}}function ds(e){throw new Y(J.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function fs(e,t,n,r,i){return{sessionId:i,mcpReq:{id:e,method:t,_meta:n?._meta,requestState:is(void 0),signal:r,send:(()=>ds(`send`)),notify:()=>ds(`notify`)}}}async function ps(e,t,n,r,i){if(!ls(r)||typeof r.method!=`string`)throw new Y(J.InvalidResult,`Invalid input request '${n}': each inputRequests entry must be an embedded request object with a method`,{key:n});let a=r.method;if(!t.hasInputRequestMethod(a))throw new Y(J.InvalidResult,`Invalid input request '${n}': '${a}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:n,method:a});let o=e.getRequestHandler(a);if(o===void 0)throw new Y(J.CapabilityNotSupported,`Cannot fulfil input request '${n}': no handler is registered for '${a}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:n,method:a});let s=ls(r.params)?r.params:void 0;return await o({jsonrpc:`2.0`,id:n,method:a,...s!==void 0&&{params:s}},e.buildContext(fs(n,a,s,i,e.sessionId)))}function ms(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function hs(e,t,n,r){let{codec:i,request:a,options:o,flowStartedAt:s}=r,c={inputRequests:n.inputRequests,...n.requestState!==void 0&&{requestState:n.requestState}},l={dispatchInputRequest:(t,n,r)=>ps(e,i,t,n,r),retry:(e,t)=>r.retry(e,ms(o,t))};return Ko({config:t,method:a.method,originalParams:a.params,firstPayload:c,flowStartedAt:s,signal:o?.signal,requestOptions:{...o?.timeout!==void 0&&{timeout:o.timeout},...o?.maxTotalTimeout!==void 0&&{maxTotalTimeout:o.maxTotalTimeout},...o?.onprogress!==void 0&&{onprogress:o.onprogress}},hooks:l})}function gs(e){return{resultType:`input_required`,inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}var _s=Te(Se((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(e){if(!e)throw TypeError(`argument string is required`);var i=typeof e==`object`?a(e):e;if(typeof i!=`string`)throw TypeError(`argument string is required to be a string`);var s=i.indexOf(`;`),c=s===-1?i.trim():i.slice(0,s).trim();if(!r.test(c))throw TypeError(`invalid media type`);var l=new o(c.toLowerCase());if(s!==-1){var u,d,f;for(t.lastIndex=s;d=t.exec(i);){if(d.index!==s)throw TypeError(`invalid parameter format`);s+=d[0].length,u=d[1].toLowerCase(),f=d[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf(`\\`)!==-1&&(f=f.replace(n,`$1`))),l.parameters[u]=f}if(s!==i.length)throw TypeError(`invalid parameter format`)}return l}function a(e){var t;if(typeof e.getHeader==`function`?t=e.getHeader(`content-type`):typeof e.headers==`object`&&(t=e.headers&&e.headers[`content-type`]),typeof t!=`string`)throw TypeError(`content-type header is missing from object`);return t}function o(e){this.parameters=Object.create(null),this.type=e}}))(),1);function vs(e){if(e)try{return _s.parse(e).type}catch{let t=(e.split(`;`,1)[0]??``).trim().toLowerCase();return t===``||e.slice(t.length).includes(`,`)?void 0:t}}function ys(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function bs(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...ys(t.headers),...ys(r.headers)}:t.headers}):e}var xs=new Set([301,302,303,307,308]),Ss=5;function Cs(e,t){return e.protocol===t.protocol&&e.host===t.host||e.protocol===`http:`&&t.protocol===`https:`&&e.hostname===t.hostname&&!e.port&&!t.port}function ws(e,t){let n=xs.has(t.status)?t.headers?.get(`location`):void 0;if(n)try{return new URL(n,e)}catch{return}}var Ts=new WeakSet;function Es(e){let t=(t,n)=>e(t,n);return Ts.add(t),t}function Ds(e){return Ts.has(e)?e:async(t,n)=>{if(n?.redirect===`error`||n?.redirect===`manual`)return e(t,n);let r=(n?.method??`GET`).toUpperCase(),i=t;for(let t=0;;t++){let a=await e(i,{...n,redirect:`manual`}),o=ws(i,a);if(!o||t===Ss)return a;let s=new URL(i),c=r===`GET`||a.status===307||a.status===308,l=!(o.username||o.password)||o.username===s.username&&o.password===s.password;if(!c||!l||!Cs(s,o))return a;await a.text?.().catch(()=>{}),i=o}}}function Os(e,t){if(t.type===`opaqueredirect`)return`Redirect not followed: this runtime does not expose where it points`;let n=ws(t.url||e,t);if(n)return n.username=n.password=n.search=n.hash=``,n.protocol===`http:`&&new URL(t.url||e).protocol===`https:`?(n.protocol=`https:`,`Redirect from https to plain http not followed; try ${n.href} as the endpoint`):`Redirect to ${n.href} not followed; use that URL as the endpoint if it is the intended server`}function ks(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r1?t[a.href]=e:(a.hash=``,r===``?n=a:Is(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(Ps[i])continue;let a=`${r}/${As(i)}`,o=e[i];if(Array.isArray(o)){if(Ms[i]){let e=o.length;for(let r=0;r%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Us=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Ws=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Gs=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Ks=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,qs=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Js=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},Ys=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Xs=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Zs=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Qs(e){return e.test.bind(e)}var $s={date:tc,time:nc.bind(void 0,!1),"date-time":ic,duration:Zs,uri:sc,"uri-reference":Qs(Vs),"uri-template":Qs(Hs),url:Qs(Us),email:Js,hostname:Qs(Bs),ipv4:Qs(Ys),ipv6:Qs(Xs),regex:lc,uuid:Qs(Ws),"json-pointer":Qs(Gs),"json-pointer-uri-fragment":Qs(Ks),"relative-json-pointer":Qs(qs)};function ec(e){return e%4==0&&(e%100!=0||e%400==0)}function tc(e){let t=e.match(Ls);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&ec(n)?29:Rs[r])}function nc(e,t){let n=t.match(zs);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}var rc=/t|\s/i;function ic(e){let t=e.split(rc);return t.length==2&&tc(t[0])&&nc(!0,t[1])}var ac=/\/|:/,oc=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function sc(e){return ac.test(e)&&oc.test(e)}var cc=/[^\\]\\Z/;function lc(e){if(cc.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function uc(e){let t=0,n=e.length,r=0,i;for(;r=55296&&i<=56319&&rks(e,t))||F.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||F.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;Q(e,v,n,r,i,a,o,t).valid&&F.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let xe=[];if(y!==void 0){let t=`${s}/anyOf`,l=F.length,u=!1;for(let s=0;s{let u=Object.create(c),d=Q(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return F.push(...d.errors),d.valid&&xe.push(u),d.valid}).length;u===1?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...xe),S!==void 0){let t=`${s}/if`;if(Q(e,S,n,r,i,a,o,t,c).valid){if(ee!==void 0){let l=Q(e,ee,n,r,i,a,o,`${s}/then`,c);l.valid||F.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(C!==void 0){let l=Q(e,C,n,r,i,a,o,`${s}/else`,c);l.valid||F.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||F.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(re!==void 0&&t.lengthie&&F.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${ie} properties.`}),D!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${As(s)}`,c=Q(s,D,n,r,i,a,e,t);c.valid||F.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(O!==void 0){let t=`${s}/dependantRequired`;for(let n in O)if(n in e){let r=O[n];for(let i of r)i in e||F.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(k!==void 0)for(let t in k){let l=`${s}/dependentSchemas`;if(t in e){let s=Q(e,k[t],n,r,i,a,o,`${l}/${As(t)}`,c);s.valid||F.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ae!==void 0){let t=`${s}/dependencies`;for(let s in ae)if(s in e){let c=ae[s];if(Array.isArray(c))for(let n of c)n in e||F.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=Q(e,c,n,r,i,a,o,`${t}/${As(s)}`);l.valid||F.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(T!==void 0){let t=`${s}/properties`;for(let s in T){if(!(s in e))continue;let d=`${o}/${As(s)}`,f=Q(e[s],T[s],n,r,i,a,d,`${t}/${As(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,F.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&E!==void 0){let t=`${s}/patternProperties`;for(let s in E){let d=new RegExp(s,`u`),f=E[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${As(p)}`,h=Q(e[p],f,n,r,i,a,m,`${t}/${As(s)}`);h.valid?c[p]=l[p]=!0:(u=i,F.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&te!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${As(s)}`,f=Q(e[s],te,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,F.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ne!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${As(s)}`,u=Q(e[s],ne,n,r,i,a,l,t);u.valid?c[s]=!0:F.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){de!==void 0&&e.length>de&&F.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${de}).`}),ue!==void 0&&e.length=(j||0)&&(F.length=u),j===void 0&&M===void 0&&d===0?F.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):j!==void 0&&dM&&F.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${M} items matching schema. ${d} items were found.`})}}if(!u&&ce!==void 0){let u=`${s}/unevaluatedItems`;for(;l=me||e>me)&&F.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${N?`or equal to `:``} ${me}.`})):(pe!==void 0&&eme&&F.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${me}.`}),he!==void 0&&e<=he&&F.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${he}.`}),N!==void 0&&e>=N&&F.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${N}.`})),P!==void 0){let t=e%P;Math.abs(0-t)>=1.1920929e-7&&Math.abs(P-t)>=1.1920929e-7&&F.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${P}.`})}}else if(u===`string`){let t=ge===void 0&&_e===void 0?0:uc(e);ge!==void 0&&t_e&&F.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${_e}).`}),ve!==void 0&&!new RegExp(ve,`u`).test(e)&&F.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),w!==void 0&&$s[w]&&!$s[w](e)&&F.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${w}".`})}return{valid:F.length===0,errors:F}}var dc=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Is(e)}validate(e){return Q(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Is(e,this.lookup)}},fc=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=je(e,`pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.`);return t===`draft-7`?`7`:t}getValidator(e){let t=new dc(e,this.draft??this._draftFor(e),this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}},pc=globalThis.crypto;async function mc(e){return(await pc).getRandomValues(new Uint8Array(e))}async function hc(e){let t=``;for(;t.length128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await gc(e);return{code_verifier:t,code_challenge:await _c(t)}}var yc=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},bc=10,xc=13,Sc=32;function Cc(e){}function wc(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Cc,onError:n=Cc,onRetry:r=Cc,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(` -`)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new yc(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(` -`,n);for(;r!==-1;){if(n===r){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0,n=r+1,r=e.indexOf(` -`,n);continue}let i=e.charCodeAt(n);if(Tc(e,n,i)){let i=e.charCodeAt(n+5)===Sc?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===bc){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(` -`,n);continue}u=d===0?a:`${u} -${a}`,d++}else Ec(e,n,i)?f=e.slice(e.charCodeAt(n+6)===Sc?n+7:n+6,r)||void 0:_(e,n,r);n=r+1,r=e.indexOf(` -`,n)}return e.slice(n)}for(;n20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function b(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:b}}function Tc(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Ec(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Dc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:r}={}){let i;super({start(a){i=wc({onEvent:e=>{a.enqueue(e)},onError(t){typeof e==`function`&&e(t),(e===`terminate`||t.type===`max-buffer-size-exceeded`)&&a.error(t)},onRetry:t,onComment:n,maxBufferSize:r})},transform(e){i.feed(e)}})}},Oc=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthClientFlowError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e){super(e),this.name=new.target.name,Qr(this,new.target)}},kc=class extends Oc{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.IssuerMismatchError`})}kind;expected;received;constructor(e,t,n){super(`Issuer mismatch in ${e===`metadata`?`authorization server metadata (RFC 8414 §3.3)`:`authorization response (RFC 9207)`}: expected ${JSON.stringify(t)}, received ${JSON.stringify(n)}`),this.kind=e,this.expected=t,this.received=n}},Ac=class extends Oc{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.RegistrationRejectedError`})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},jc=class extends Oc{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.InsecureTokenEndpointError`})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},Mc=class extends Oc{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.AuthorizationServerMismatchError`})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`),this.recordedIssuer=e,this.currentIssuer=t}},Nc=class extends Oc{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.InsufficientScopeError`})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:``}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function Pc(e,t,n){if(e)return typeof e.issuer==`string`?Fc(e.issuer,t)?e:void 0:(n?.canPersistStamp!==!1&&console.warn(`[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.`),e.issuer===void 0?e:{...e,issuer:void 0})}function Fc(e,t){return e===t||e.endsWith(`/`)&&e.slice(0,-1)===t||t.endsWith(`/`)&&t.slice(0,-1)===e}function Ic(e){if(e==null)return!1;let t=e;return typeof t.tokens==`function`&&typeof t.clientInformation==`function`}async function Lc(e,t,n){let{resourceMetadataUrl:r,scope:i}=dl(t.response);if(await al(e,{serverUrl:t.serverUrl,resourceMetadataUrl:r,scope:i,fetchFn:t.fetchFn,...n})!==`AUTHORIZED`)throw new zc}function Rc(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async n=>Lc(e,n,t)}}var zc=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnauthorizedError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e){super(e??`Unauthorized`),this.name=`UnauthorizedError`,Qr(this,new.target)}};function Bc(e){return e?.authorization_response_iss_parameter_supported===!0}function Vc({iss:e,expectedIssuer:t,issParameterSupported:n}){if(t!==void 0){if(e===void 0){if(n)throw new kc(`authorization_response`,t,void 0);return}if(e!==t)throw new kc(`authorization_response`,t,e)}}function Hc(...e){let t=new Set;for(let n of e)if(n)for(let e of n.split(/\s+/))e&&t.add(e);return t.size>0?[...t].join(` `):void 0}function Uc(e,t){if(!e)return!1;let n=new Set((t??``).split(/\s+/).filter(Boolean));for(let t of e.split(/\s+/))if(t&&!n.has(t))return!0;return!1}async function Wc(e,t,n,r,i){if(typeof e==`string`)return{authorizationCode:e,iss:t};let a=e.get(`iss`)??void 0,o=e.get(`code`);if(o)return{authorizationCode:o,iss:a};let s=(await n.discoveryState?.())?.authorizationServerMetadata;if(!s)try{s=(await xl(r,i)).authorizationServerMetadata}catch{s=void 0}if(!s)throw new zc(`Authorization callback failed and the issuer could not be verified`);Vc({iss:a,expectedIssuer:s.issuer,issParameterSupported:Bc(s)});let c=e.get(`error`);throw c?new ti(c,e.get(`error_description`)??c,e.get(`error_uri`)??void 0):new zc("Authorization callback contained neither `code` nor `error`")}function Gc(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var Kc=`code`,qc=`S256`;function Jc(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Gc(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Yc(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Xc(i,a,n);return;case`client_secret_post`:Zc(i,a,r);return;case`none`:Qc(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Xc(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Zc(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Qc(e,t){t.set(`client_id`,e)}function $c(e){return e===`localhost`||e.endsWith(`.localhost`)||e===`127.0.0.1`||e===`[::1]`||e===`::1`}function el(e){let t=new URL(String(e));if(t.protocol!==`https:`&&!$c(t.hostname))throw new jc(t.href);return t}function tl(e){for(let t of e??[]){let e;try{e=new URL(t)}catch{continue}if(e.protocol!==`http:`&&e.protocol!==`https:`||$c(e.hostname))return`native`}return`web`}function nl(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:[`authorization_code`,`refresh_token`]),application_type:t.application_type??tl(t.redirect_uris)}}async function rl(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let e=Wr.parse(JSON.parse(n));return ti.fromResponse(e)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new ti(ei.ServerError,r)}}function il(e,t,n){let r=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${n} (provider implements no invalidateCredentials())`:`invalidating the stored ${n} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${r}. Cause: ${JSON.stringify(t.message)}`)}async function al(e,t){try{return await sl(e,t)}catch(n){if(n instanceof ti){if(n.code===ei.InvalidClient||n.code===ei.UnauthorizedClient)return il(e,n,`client credentials and tokens`),await e.invalidateCredentials?.(`client`),await e.invalidateCredentials?.(`tokens`),await sl(e,t);if(n.code===ei.InvalidGrant||n.code===ei.InvalidDpopProof)return il(e,n,`tokens`),await e.invalidateCredentials?.(`tokens`),await sl(e,t)}throw n}}function ol(e){let{requestedScope:t,resourceMetadata:n,authServerMetadata:r,clientMetadata:i}=e,a=t||n?.scopes_supported?.join(` `)||i.scope;return a&&r?.scopes_supported?.includes(`offline_access`)&&!a.split(` `).includes(`offline_access`)&&i.grant_types?.includes(`refresh_token`)&&(a=`${a} offline_access`),a}async function sl(e,{serverUrl:t,authorizationCode:n,iss:r,scope:i,resourceMetadataUrl:a,fetchFn:o,skipIssuerMetadataValidation:s,forceReauthorization:c}){let l=nl(e),u=await e.discoveryState?.(),d,f,p,m,h=a;if(!h&&u?.resourceMetadataUrl&&(h=new URL(u.resourceMetadataUrl)),u?.authorizationServerUrl){if(f=u.authorizationServerUrl,d=u.resourceMetadata,p=u.authorizationServerMetadata??await bl(f,{fetchFn:o,skipIssuerValidation:s}),!d)try{d=await pl(t,{resourceMetadataUrl:h},o)}catch(e){if(e instanceof TypeError)throw e}(p!==u.authorizationServerMetadata||d!==u.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:p})}else{let e=await xl(t,{resourceMetadataUrl:h,fetchFn:o,skipIssuerMetadataValidation:s});f=e.authorizationServerUrl,p=e.authorizationServerMetadata,d=e.resourceMetadata,m={authorizationServerUrl:String(f),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:p}}let g=p?.issuer??String(f),_={issuer:g};if(await e.saveAuthorizationServerUrl?.(g),n!==void 0){let t=u?.authorizationServerMetadata?.issuer??u?.authorizationServerUrl;if(t===void 0){if(e.saveDiscoveryState!==void 0)throw new Mc(`discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier`,g);console.warn(`[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.`)}else if(!Fc(t,g))throw new Mc(t,g)}m&&await e.saveDiscoveryState?.(m);let v=await ll(t,e,d),y=v&&d&&!e.validateResourceURL?d.resource:v;y&&await e.saveResourceUrl?.(Sl(y));let b=ol({requestedScope:i,resourceMetadata:d,authServerMetadata:p,clientMetadata:e.clientMetadata}),x=await Promise.resolve(e.clientInformation(_)),S=Pc(x,g,{canPersistStamp:e.saveClientInformation!==void 0});if(S===void 0&&x?.issuer&&e.saveClientInformation===void 0)throw new Mc(x.issuer,g);if(S&&S.issuer===void 0&&(S={...S,issuer:g},await e.saveClientInformation?.(S,_)),!S){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=p?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!cl(r))throw new ti(ei.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)S={client_id:r,issuer:g},await e.saveClientInformation?.(S,_);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);S={...await Ol(f,{metadata:p,clientMetadata:l,scope:b,fetchFn:o}),issuer:g},await e.saveClientInformation(S,_)}}let ee=!e.redirectUrl;if(n!==void 0||ee){n!==void 0&&Vc({iss:r,expectedIssuer:p?.issuer,issParameterSupported:Bc(p)});let t=await Dl(e,f,{metadata:p,resource:y,authorizationCode:n,iss:r,scope:b,fetchFn:o});return await e.saveTokens({...t,issuer:g},_),`AUTHORIZED`}let C=Pc(await e.tokens(_),g);if(C&&C.issuer===void 0&&(C={...C,issuer:g},await e.saveTokens(C,_)),C?.refresh_token&&!c){let t;try{t=await El(f,{metadata:p,clientInformation:S,refreshToken:C.refresh_token,resource:y,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:o})}catch(e){if(e instanceof jc)throw e;if(!(e instanceof ti)||e.code===ei.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(e instanceof Error?e.message:String(e))}`);else throw e}if(t)return await e.saveTokens({...t,issuer:g},_),`AUTHORIZED`}let w=e.state?await e.state():void 0,{authorizationUrl:T,codeVerifier:E}=await Cl(f,{metadata:p,clientInformation:S,state:w,redirectUrl:e.redirectUrl,scope:b,resource:y});return await e.saveCodeVerifier(E),await e.redirectToAuthorization(T),`REDIRECT`}function cl(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function ll(e,t,n){let r=ri(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ai({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}var ul=new Set([`bearer`,`dpop`]);function dl(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(!n||!ul.has(n.toLowerCase())||!r)return{};let i=fl(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=fl(e,`scope`)||void 0,s=fl(e,`error`)||void 0,c=fl(e,`error_description`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s,errorDescription:c}}function fl(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),i=n.match(r);if(i){let e=i[1]||i[2];if(e)return e}return null}async function pl(e,t,n=fetch){let r=await vl(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.text?.().catch(()=>{}),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.text?.().catch(()=>{}),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Rr.parse(await r.json())}async function ml(e,t,n=fetch){let r=Ds(n);try{return await r(e,{headers:t})}catch(n){if(!(n instanceof TypeError))throw n;if(t)try{return await r(e,{})}catch(e){if(!(e instanceof TypeError))throw e;return}return}}function hl(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function gl(e,t,n=fetch){return await ml(e,{"MCP-Protocol-Version":t},n)}function _l(e,t){return e?t===`/`?!1:!e.ok&&e.status<500||e.status===502:!0}async function vl(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=hl(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await gl(o,a,n);return!r?.metadataUrl&&_l(s,i.pathname)&&(s=await gl(new URL(`/.well-known/${t}`,i),a,n)),s}function yl(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`},{url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function bl(e,{fetchFn:t=fetch,protocolVersion:n=Me,skipIssuerValidation:r=!1}={}){let i={"MCP-Protocol-Version":n,Accept:`application/json`},a=yl(e);for(let{url:n,type:o}of a){let a=await ml(n,i,t);if(!a)continue;if(!a.ok){if(await a.text?.().catch(()=>{}),a.status<500||a.status===502)continue;throw Error(`HTTP ${a.status} trying to load ${o===`oauth`?`OAuth`:`OpenID provider`} metadata from ${n}`)}let s=o===`oauth`?zr.parse(await a.json()):Vr.parse(await a.json());if(!r){let t=typeof e==`string`?e:e.href;if(!(s.issuer===t||t.endsWith(`/`)&&s.issuer===t.slice(0,-1)))throw new kc(`metadata`,t,s.issuer)}return s}}async function xl(e,t){let n,r;try{n=await pl(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch(e){if(e instanceof TypeError)throw e}r||=String(new URL(`/`,e));let i=await bl(r,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}function Sl(e){return typeof e==`string`?e:e.href}async function Cl(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Kc))throw Error(`Incompatible auth server: does not support response type ${Kc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(qc))throw Error(`Incompatible auth server: does not support code challenge method ${qc}`)}else s=new URL(`/authorize`,e);let c=await vc(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Kc),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,qc),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.split(` `).includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,Sl(o)),{authorizationUrl:s,codeVerifier:l}}function wl(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function Tl(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,dpop:o,fetchFn:s}){let c=el(t?.token_endpoint??new URL(`/token`,e)),l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,Sl(a)),!i&&r&&Yc(Jc(r,t?.token_endpoint_auth_methods_supported??[]),r,l,n);let u=async()=>{let e=new Headers(l);return i&&await i(e,n,c,t),o&&e.set(`DPoP`,await o.buildProof({htm:`POST`,htu:c})),Ds(s??fetch)(c,{method:`POST`,headers:e,body:n})},d=await u();if(o&&d.status===400&&(await d.clone().json().catch(()=>{}))?.error===ei.UseDpopNonce&&(o.observeNonce(d,c),d=await u()),o?.observeNonce(d,c),!d.ok)throw await rl(d);let f=await d.json();try{return Hr.parse(ii(f))}catch(e){throw typeof f==`object`&&f&&`error`in f?await rl(JSON.stringify(f)):e}}async function El(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,dpop:o,fetchFn:s}){return{refresh_token:r,...await Tl(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,dpop:o,fetchFn:s})}}async function Dl(e,t,{metadata:n,resource:r,authorizationCode:i,iss:a,scope:o,fetchFn:s}={}){i!==void 0&&Vc({iss:a,expectedIssuer:n?.issuer,issParameterSupported:Bc(n)});let c=n?.issuer??String(t),l=async()=>{let t=await e.clientInformation({issuer:c}),n=Pc(t,c,{canPersistStamp:!1});if(t&&n===void 0)throw new Mc(String(t.issuer),c);return n},u=await l(),d=o??e.clientMetadata.scope,f;if(e.prepareTokenRequest&&(f=await e.prepareTokenRequest(d)),!f){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);f=wl(i,await e.codeVerifier(),e.redirectUrl)}return u??=await l(),Tl(t,{metadata:n,tokenRequestParams:f,clientInformation:u,addClientAuthentication:e.addClientAuthentication,resource:r,dpop:await e.dpop?.(),fetchFn:s})}async function Ol(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o={...n,...r===void 0?{}:{scope:r}},s=await Ds(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(o)});if(!s.ok)throw new Ac({status:s.status,body:await s.text(),submittedMetadata:o});return Jr.parse(ii(await s.json()))}var kl=new Set([`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`server/discover`]),Al=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(jl(e))}set(e,t){let n=jl(e),r=kl.has(e.method),i=!this._entries.has(n);if(!r&&i&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let e of this._entries.keys())if(!kl.has(e.slice(0,e.indexOf(`\0`)))){this._entries.delete(e),this._cappedSize--;break}}let a=++this._stamp;return this._entries.set(n,{...t,stamp:a}),i&&!r&&this._cappedSize++,a}delete(e){this._entries.delete(jl(e))&&!kl.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,n=kl.has(e);for(let e of this._entries.keys())e.startsWith(t)&&(this._entries.delete(e),n||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};function jl(e){return`${e.method}\0${JSON.stringify([e.partition??``,e.params??``])}`}function Ml(e,t){return t===void 0?e:`${e}\0${t}`}var Nl=864e5,Pl=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity=``;constructor(e,t,n=()=>{},r=``,i=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=n,this._cachePartition=r,this._now=i}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e===`public`?``:this._cachePartition])}async _probe(e,t){let n={method:e,params:t??``},r=this._partitionFor(`private`),i=await this._store.get({...n,partition:r});if(i!==void 0)return i;let a=this._partitionFor(`public`);if(a===r)return;let o=await this._store.get({...n,partition:a});return o?.scope===`public`?o:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,``)}async _deleteBoth(e,t){let n=this._partitionFor(`private`),r=this._partitionFor(`public`);try{await this._store.delete({method:e,params:t,partition:n})}catch(e){this._reportError(e)}if(r!==n)try{await this._store.delete({method:e,params:t,partition:r})}catch(e){this._reportError(e)}}async evictKey(e,t){let n=Ml(e,t),r=this._evictionGeneration.get(n);r!==void 0&&this._evictionGeneration.set(n,r+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let n=Ml(e,t),r=this._evictionGeneration.get(n)??0;return this._evictionGeneration.set(n,r),r}async write(e,t,n,r){if((this._evictionGeneration.get(Ml(e,r?.params))??0)!==n)return;let i=r?.params??``,a=this._partitionFor(`private`),o=this._partitionFor(`public`),s=(r?.scope??`private`)===`public`?o:a;try{await this._store.set({method:e,params:i,partition:s},{value:Fl(t),expiresAt:r?.expiresAt,scope:r?.scope})}catch(e){this._reportError(e)}if(o!==a)try{await this._store.delete({method:e,params:i,partition:s===a?o:a})}catch(e){this._reportError(e)}}async read(e,t){let n=await this._probe(e,t);if(n?.expiresAt!==void 0&&n.expiresAt>this.now())try{let e=JSON.parse(n.value);if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`cached document is not an object`);return{value:e}}catch(n){this._reportError(n),await this._deleteBoth(e,t??``);return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=``}async toolDefinition(e){let t=await this._probe(`tools/list`);if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let e=this._decodeListTools(t),n=new Map;if(e!==void 0)for(let t of e.tools)n.set(t.name,t);this._toolIndex={stamp:t.stamp,byName:n}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let n=await this._probe(`tools/list`);if(n===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==n.stamp){let e=this._decodeListTools(n)??{tools:[]},r=new Map;for(let n of e.tools){let e=t(n);e!==void 0&&r.set(n.name,e)}this._toolOutputValidatorIndex={stamp:n.stamp,byName:r}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(e=>typeof e==`object`&&!!e))throw TypeError(`cached tools/list document has a malformed tools array`);return t}catch(e){this._reportError(e);return}}};function Fl(e){let t;try{t=JSON.stringify(e)}catch(e){throw TypeError(`cache value is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`)}if(typeof t!=`string`)throw TypeError(`cache value is not JSON-serializable: it has no JSON representation`);return t}var Il=Symbol.for(`mcp.authSeamEscape`);function Ll(e){if(typeof e==`object`&&e||typeof e==`function`)try{Object.defineProperty(e,Il,{value:!0,configurable:!0})}catch{}return e}function Rl(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&e[Il]===!0}var zl=-32022,Bl=new Set([-32001,-32020,-32021]);function Vl(e,t){switch(e.kind){case`result`:return Hl(e.result,t);case`rpc-error`:return Ul(e,t);case`http-error`:return Wl(e,t);case`network-error`:return Gl(e.error,t);case`unusable-reply`:return{kind:`error`,error:new Y(J.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${ql(e.error)})`,{cause:e.error},{cause:e.error})};case`auth-required`:return{kind:`error`,error:e.error};case`closed`:return t.transportKind===`stdio`?{kind:`legacy`}:Gl(Error(`Connection closed during the version negotiation probe`),t);case`timeout`:return t.transportKind===`stdio`?{kind:`legacy`}:{kind:`error`,error:new Y(J.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function Hl(e,t){let n=ja(Aa).validateResult(`server/discover`,e);if(!n.ok)return{kind:`legacy`};let r=n.value.supportedVersions,i=t.clientModernVersions.find(e=>r.includes(e));return i===void 0?t.fallbackAvailable?{kind:`legacy`}:{kind:`error`,error:new Xi({supported:[...r],requested:t.requestedVersion})}:{kind:`modern`,version:i,discover:n.value}}function Ul(e,t){let{code:n,message:r,data:i}=e;if(n===zl){let e=Jl(i);if(e===void 0)return{kind:`legacy`};let n=new Xi({supported:e,requested:Yl(i)??t.requestedVersion},r),a=ui(e),o=t.clientModernVersions.find(e=>a.includes(e));return o===void 0?a.length>0?{kind:`error`,error:n}:t.fallbackAvailable?{kind:`legacy`}:{kind:`error`,error:n}:{kind:`corrective`,version:o,error:n}}return Bl.has(n),{kind:`legacy`}}function Wl(e,t){if(e.status===401||e.status===403){let t=e.status===403;return{kind:`error`,error:new ni(t?J.ClientHttpForbidden:J.ClientHttpAuthentication,`Version negotiation failed: ${t?`the server denied access (HTTP 403)`:`the server requires authorization (HTTP 401)`}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:`error`,error:new ni(J.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let n=Xl(e.body);return n===void 0?{kind:`legacy`}:Ul(n,t)}function Gl(e,t){return t.environment===`browser`&&Kl(e)?{kind:`legacy`}:{kind:`error`,error:new Y(J.EraNegotiationFailed,`Version negotiation probe failed: ${ql(e)}`,{cause:e},{cause:e})}}function Kl(e){return e instanceof TypeError||e instanceof Error&&e.name===`TypeError`}function ql(e){return e instanceof Error?e.message:String(e)}function Jl(e){if(typeof e!=`object`||!e)return;let t=e.supported;if(Array.isArray(t)&&t.length!==0&&t.every(e=>typeof e==`string`))return t}function Yl(e){if(typeof e!=`object`||!e)return;let t=e.requested;return typeof t==`string`?t:void 0}function Xl(e){if(e===void 0||e===``)return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let n=t.error;if(typeof n!=`object`||!n)return;let{code:r,message:i,data:a}=n;if(typeof r==`number`)return{code:r,message:typeof i==`string`?i:``,data:a}}var Zl=`legacy`;function Ql(e,t){let n=e?.mode??Zl;if(n===`legacy`)return{kind:`legacy`};let r=e?.probe??{};if(typeof n==`object`){if(!ci(n.pin))throw TypeError(`versionNegotiation: { pin: '${n.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:`pin`,version:n.pin,probe:r}}let i=t?ui(t):[];return{kind:`auto`,modernVersions:i.length>0?i:[...si],fallbackAvailable:!t||li(t).length>0,probe:r}}function $l(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?`browser`:`node`}function eu(e){return`stderr`in e&&`pid`in e?`stdio`:`http`}var tu=class e{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(e){this._transport=e,this._savedOnMessage=e.onmessage,this._savedOnError=e.onerror,this._savedOnClose=e.onclose}static async open(t){let n=new e(t);t.onmessage=e=>{let t=n._pending;if(t!==void 0&&(Ba(e)||Va(e))&&e.id===t.id){n._pending=void 0,Ba(e)?t.resolve({kind:`response`,result:e.result}):t.resolve({kind:`response`,error:e.error});return}},t.onerror=e=>{n._savedOnError?.(e)},t.onclose=()=>{let e=n._pending;e!==void 0&&(n._pending=void 0,e.resolve({kind:`closed`})),n._closeDelivered=!0,n._savedOnClose?.()};try{await t.start()}catch(e){throw n.detach(),e}return n}async exchange(e,t){let n=`server-discover-probe-${++this._probeCounter}`;return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,clearTimeout(o),this._pending?.id===n&&(this._pending=void 0),r(e))},o=setTimeout(()=>a({kind:`timeout`}),t);this._pending={id:n,resolve:a},this._transport.send(e(n)).catch(e=>a({kind:`send-error`,error:e}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let e=this._savedOnClose,t=this._transport,n=!1,r=()=>{if(!n){n=!0;return}e()};t.onclose=r,nu.set(t,()=>{t.onclose===r&&(t.onclose=e)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let e=this._transport,t=e.start,n=!0;e.start=async function(){if(n){n=!1,e.start=t;return}return t.call(e)}}},nu=new WeakMap;function ru(e){let t=nu.get(e);nu.delete(e),t?.()}function iu(e,t,n,r){return{jsonrpc:`2.0`,id:e,method:`server/discover`,params:{_meta:ja(t).outboundEnvelope({protocolVersion:t,clientInfo:n,clientCapabilities:r})}}}function au(e){return e instanceof Y&&e.code===J.ClientHttpUnexpectedContent||e instanceof Error&&e.name===`SyntaxError`}function ou(e,t){switch(e.kind){case`response`:return e.error===void 0?{kind:`result`,result:e.result}:{kind:`rpc-error`,...e.error};case`send-error`:{let t=e.error;if(Rl(t)||t instanceof zc||t instanceof Error&&t.name===`UnauthorizedError`)return{kind:`auth-required`,error:t};if(t instanceof ni){let e=t.data?.text;return{kind:`http-error`,status:t.data.status,body:typeof e==`string`?e:void 0,statusText:t.data.statusText}}return au(t)?{kind:`unusable-reply`,error:t}:{kind:`network-error`,error:t}}case`closed`:return{kind:`closed`};case`timeout`:return{kind:`timeout`,timeoutMs:t}}}async function su(e,t){let n=e.probe.timeoutMs??t.defaultTimeoutMs,r=Math.max(0,e.probe.maxRetries??0),i=e.kind===`pin`?[e.version]:e.modernVersions,a=e.kind===`auto`&&e.fallbackAvailable,o=await tu.open(t.transport),s=async()=>{let s=i[0],c=!1,l=r;for(;;){let r=await o.exchange(e=>iu(e,s,t.clientInfo,t.capabilities),n);if(r.kind===`timeout`&&l>0){l--;continue}let u=ou(r,n),d=Vl(u,{clientModernVersions:i,requestedVersion:s,fallbackAvailable:a,environment:t.environment,transportKind:t.transportKind});switch(d.kind){case`modern`:return{era:`modern`,version:d.version,discover:d.discover};case`corrective`:if(c)throw d.error;c=!0,s=d.version;continue;case`legacy`:{let n=u.kind===`closed`?`the connection closed during the server/discover probe`:void 0;if(e.kind===`pin`)throw new Y(J.EraNegotiationFailed,n===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${n} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new Y(J.EraNegotiationFailed,n===void 0?`Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to`:`Version negotiation failed: ${n} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(n!==void 0&&t.disposableProbe!==!0)throw new Y(J.EraNegotiationFailed,`Version negotiation failed: ${n} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:`legacy`}}case`error`:throw d.error}}},c;try{c=await s()}catch(e){throw o.detach(),e}return o.release(),c}function cu(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,`_dispose`))return;let n=e._serverParams;return typeof n==`object`&&n&&typeof n.command==`string`?n:void 0}async function lu(e,t,n,r){let i=t.constructor,a=new i({...n,stderr:`ignore`}),o=t.close,s=!1,c,l=new Promise((e,t)=>{c=()=>t(uu())});t.close=async function(){return s=!0,c?.(),o.call(t)};let u;try{let t=su(e,{...r,transport:a,transportKind:`stdio`,disposableProbe:!0});t.catch(()=>{}),u=await Promise.race([t,l])}finally{await du(a),t.close=o}if(s)throw uu();return u}function uu(){return new Y(J.EraNegotiationFailed,`Version negotiation failed: the transport was closed during the server/discover probe`)}async function du(e){try{let t=e._dispose;await(typeof t==`function`?t.call(e):e.close())}catch{}}function fu(e){let t=e._meta?.[Le];return Qo.Implementation(t)?t:void 0}function pu(e,t){if(e&&typeof t==`object`&&t){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&pu(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&pu(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&pu(n,t)}}function mu(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}function hu(e){if(typeof e==`object`&&e&&(e.kind===`legacy`&&!(`supportedVersions`in e)&&!(`discover`in e)||e.kind===`modern`&&bt.safeParse(e.discover).success))return e;throw new Y(J.EraNegotiationFailed,`connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }`)}var gu={"notifications/tools/list_changed":[`tools/list`],"notifications/prompts/list_changed":[`prompts/list`],"notifications/resources/list_changed":[`resources/list`,`resources/templates/list`]},_u=64,vu=class extends os{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new Y(J.ConnectionClosed,`subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset`);for(let t of this._listenState.values())t.settle({cause:`remote`,error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new fc,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=Vo(t?.inputRequired),this._cache=new Pl(t?.responseCacheStore??new Al,t?.responseCacheStore!==void 0,e=>this._reportStoreError(e),t?.cachePartition??``),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??_u,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&ci(this._negotiatedProtocolVersion)&&Ra(e))return`drop`}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?hs({getRequestHandler:e=>this._getRequestHandler(e),buildContext:e=>this.buildContext(e,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new Y(J.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:`input_required`,method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,`notifications/tools/list_changed`,e.tools,async()=>(await this.listTools(void 0,{cacheMode:`refresh`})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,`notifications/prompts/list_changed`,e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:`refresh`})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,`notifications/resources/list_changed`,e.resources,async()=>(await this.listResources(void 0,{cacheMode:`refresh`})).resources)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=cs(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error(`Cannot configure version negotiation after connecting to transport`);this._versionNegotiation=e}_wrapHandler(e,t){return e===`elicitation/create`?async(e,n)=>{let r=ja(this._negotiatedProtocolVersion),i=r.validateRequest(`elicitation/create`,e);if(!i.ok&&i.reason===`not-in-era`&&(i=r.validateInputRequest(`elicitation/create`,e)),!i.ok)throw new Z(i.reason===`not-in-era`?X.InternalError:X.InvalidParams,i.reason===`not-in-era`?`No wire schema for elicitation/create in the resolved era`:`Invalid elicitation request: ${i.message}`);let{params:a}=i.value;a.mode=a.mode??`form`;let{supportsFormMode:o,supportsUrlMode:s}=mu(this._capabilities.elicitation);if(a.mode===`form`&&!o)throw new Z(X.InvalidParams,`Client does not support form-mode elicitation requests`);if(a.mode===`url`&&!s)throw new Z(X.InvalidParams,`Client does not support URL-mode elicitation requests`);let c=await t(e,n),l=r.validateResult(`elicitation/create`,c);if(!l.ok&&l.reason===`not-in-era`&&(l=r.validateInputResponse(`elicitation/create`,c)),!l.ok)throw new Z(l.reason===`not-in-era`?X.InternalError:X.InvalidParams,l.reason===`not-in-era`?`No wire schema for elicitation/create in the resolved era`:`Invalid elicitation result: ${l.message}`);let u=l.value,d=a.mode===`form`?a.requestedSchema:void 0;if(a.mode===`form`&&u.action===`accept`&&u.content&&d&&this._capabilities.elicitation?.form?.applyDefaults)try{pu(d,u.content)}catch{}return u}:e===`sampling/createMessage`?async(e,n)=>{let r=ja(this._negotiatedProtocolVersion),i=r.validateRequest(`sampling/createMessage`,e);if(!i.ok&&i.reason===`not-in-era`&&(i=r.validateInputRequest(`sampling/createMessage`,e)),!i.ok)throw new Z(i.reason===`not-in-era`?X.InternalError:X.InvalidParams,i.reason===`not-in-era`?`No wire schema for sampling/createMessage in the resolved era`:`Invalid sampling request: ${i.message}`);let{params:a}=i.value,o=await t(e,n),s=!!(a.tools||a.toolChoice),c=r.samplingResultVariant(s,o);if(!c.ok&&c.reason===`not-in-era`&&(c=r.validateInputResponse(`sampling/createMessage`,o)),!c.ok)throw new Z(c.reason===`not-in-era`?X.InternalError:X.InvalidParams,c.reason===`not-in-era`?`No result schema for sampling/createMessage in the resolved era`:`Invalid sampling result: ${c.message}`);return c.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Y(J.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,hu(t.prior),t);let n=Ql(this._versionNegotiation,this._supportedProtocolVersionsOption);return n.kind===`legacy`?this._connectPlainLegacy(e,t):this._connectNegotiated(e,n,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let t=this._negotiatedProtocolVersion;t!==void 0&&e.setProtocolVersion?.(t);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let n=li(this._supportedProtocolVersions);try{let r=n[0];if(r===void 0)throw new Y(J.EraNegotiationFailed,`Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version`);let i=await this.request({method:`initialize`,params:{protocolVersion:r,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(i===void 0)throw Error(`Server sent invalid initialize result: ${i}`);if(!n.includes(i.protocolVersion))throw Error(`Server's protocol version is not supported: ${i.protocolVersion}`);this._serverCapabilities=i.capabilities,this._serverVersion=i.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(i.protocolVersion),this._instructions=i.instructions,await this.notification({method:`notifications/initialized`}),this._negotiatedProtocolVersion=i.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(e){throw this.close(),e}}async _connectNegotiated(e,t,n){if(e.sessionId!==void 0){await super.connect(e);let t=this._negotiatedProtocolVersion;t!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(t);return}this._resetConnectionState();let r;try{let i=eu(e),a={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:$l(),defaultTimeoutMs:n?.timeout??6e4},o=i===`stdio`?cu(e):void 0;r=o===void 0?await su(t,{...a,transport:e,transportKind:i}):await lu(t,e,o,a)}catch(t){throw await e.close().catch(()=>{}),ru(e),t}if(ru(e),await super.connect(e),r.era===`legacy`){await this._legacyHandshake(e,n);return}if(this._serverCapabilities=r.discover.capabilities,this._serverVersion=fu(r.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=r.discover.instructions,this._discoverResult=r.discover,this._negotiatedProtocolVersion=r.version,e.setProtocolVersion&&e.setProtocolVersion(r.version),this._listChangedConfig){let e=this._listChangedConfig,t=this._serverCapabilities,r={...e.tools&&t?.tools?.listChanged&&{tools:e.tools},...e.prompts&&t?.prompts?.listChanged&&{prompts:e.prompts},...e.resources&&t?.resources?.listChanged&&{resources:e.resources}},i=!0;try{this._setupListChangedHandlers(r)}catch(e){i=!1,this.onerror?.(e instanceof Error?e:Error(String(e)))}let a=i?{...r.tools&&{toolsListChanged:!0},...r.prompts&&{promptsListChanged:!0},...r.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(a).length>0){let e=new AbortController,t=()=>e.abort(n?.signal?.reason);n?.signal?.aborted&&t(),n?.signal?.addEventListener(`abort`,t);try{this._autoOpenedSubscription=await this.listen(a,{timeout:n?.timeout,signal:e.signal})}catch(e){if(n?.signal?.aborted)throw await this.close().catch(()=>{}),e;this.onerror?.(e instanceof Error?e:Error(String(e)))}finally{n?.signal?.removeEventListener(`abort`,t)}}}}async _connectFromPrior(e,t,n){if(t.kind===`legacy`)return this._connectPlainLegacy(e,n);let r=t.discover;this._resetConnectionState();let i=this._supportedProtocolVersionsOption,a=(i&&ui(i).length>0?ui(i):si).find(e=>r.supportedVersions.includes(e));if(a===void 0)throw new Y(J.EraNegotiationFailed,`connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.`);if(await super.connect(e),this._discoverResult=r,this._serverCapabilities=r.capabilities,this._serverVersion=fu(r),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=r.instructions,this._negotiatedProtocolVersion=a,e.setProtocolVersion?.(a),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t===void 0?e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`:`${t.name}@${t.version}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return ci(e)?`modern`:`legacy`}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw new Y(J.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw new Y(J.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw new Y(J.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw new Y(J.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw new Y(J.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw new Y(J.CapabilityNotSupported,`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if(e===`notifications/roots/list_changed`&&!this._capabilities.roots?.listChanged)throw new Y(J.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw new Y(J.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw new Y(J.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw new Y(J.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`)}}async ping(e){return this.request({method:`ping`},e)}async discover(e){let t=await this._requestWithSchema({method:`server/discover`},bt,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:`completion/complete`,params:e},t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug(`Client.listPrompts() called but server does not advertise prompts capability - returning empty list`),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:`prompts/list`,params:e},t);let n=await this._serveFromCache(`prompts/list`,void 0,t);return n===void 0?this._listAllPages(`prompts/list`,e,t,e=>e.prompts):n}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug(`Client.listResources() called but server does not advertise resources capability - returning empty list`),{resources:[]};if(e?.cursor!==void 0)return this.request({method:`resources/list`,params:e},t);let n=await this._serveFromCache(`resources/list`,void 0,t);return n===void 0?this._listAllPages(`resources/list`,e,t,e=>e.resources):n}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug(`Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list`),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:`resources/templates/list`,params:e},t);let n=await this._serveFromCache(`resources/templates/list`,void 0,t);return n===void 0?this._listAllPages(`resources/templates/list`,e,t,e=>e.resourceTemplates):n}async _listAllPages(e,t,n,r,i){let a=n?.cacheMode===`bypass`,o=this._cache.captureGeneration(e),s=await this.request({method:e,...t&&{params:{...t}}},n),c=s.nextCursor,l=s,u=1;for(;c!==void 0;){if(this._listMaxPages!==0&&u>=this._listMaxPages)throw new Y(J.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let i=await this.request({method:e,params:{...t,cursor:c}},n);if(i.nextCursor===c&&JSON.stringify(r(i))===JSON.stringify(r(l)))break;r(s).push(...r(i)),l=i,c=i.nextCursor,u++}return delete s.nextCursor,i?.(s),a||await this._cache.write(e,s,o,this._freshness(s)),s}_freshness(e,t){let n=e,r=typeof n.ttlMs==`number`?n.ttlMs:this._defaultCacheTtlMs,i=n.cacheScope===`public`?`public`:`private`;return{expiresAt:this._cache.now()+Math.min(Math.max(0,r),Nl),scope:i,params:t}}async _serveFromCache(e,t,n){if(n?.cacheMode===`bypass`||n?.cacheMode===`refresh`)return;let r=await this._cache.read(e,t).catch(e=>void this._reportStoreError(e));if(r!==void 0){if(n?.signal?.aborted){let e=n.signal.reason;throw e instanceof Y?e:new Y(J.RequestTimeout,String(e))}return r.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(e){return{ok:!1,compileError:e}}}async _resolveXMcpHeaderScan(e,t){let n=t??await this._cache.toolDefinition(e);return n===void 0?void 0:Ya(n.inputSchema)}async readResource(e,t){let n=await this._serveFromCache(`resources/read`,e.uri,t);if(n!==void 0)return n;let r=this._cache.captureGeneration(`resources/read`,e.uri),i=await this.request({method:`resources/read`,params:e},t);if(t?.cacheMode!==`bypass`){let n=this._freshness(i,e.uri);n.expiresAt>this._cache.now()?await this._cache.write(`resources/read`,i,r,n):t?.cacheMode===`refresh`&&await this._cache.evictKey(`resources/read`,e.uri)}return i}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},t)}async listen(e,t){if(this.transport===void 0)throw new Y(J.NotConnected,`Not connected`);let n=this._negotiatedProtocolVersion;if(n===void 0||!ci(n))throw new Y(J.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${n??`none`}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:`subscriptions/listen`,protocolVersion:n});if(t?.signal?.aborted){let e=t.signal.reason;throw e instanceof Y?e:new Y(J.RequestTimeout,String(e))}let r=new AbortController,i=`listen:${this._nextListenId++}`,a=`opening`,o,s,c,l,u=new Promise((e,t)=>{c=e,l=t}),d,f=new Promise(e=>{d=e}),p=e=>{if(a===`closed`)return;let n=a===`opening`;if(o!==void 0&&(clearTimeout(o),o=void 0),`ack`in e){a=`open`,c(e.ack);return}a=`closed`,s!==void 0&&t?.signal?.removeEventListener(`abort`,s),this._listenState.delete(i),r.abort(),d(e.cause),n&&l(e.error??new Y(J.ConnectionClosed,`subscriptions/listen closed before the server acknowledged`))},m=async()=>{r.abort(),await this.notification({method:`notifications/cancelled`,params:{requestId:i}}).catch(()=>{})},h=async()=>{a!==`closed`&&(p({cause:`local`}),await m())};this._listenState.set(i,{settle:p});let g=t?.timeout??6e4;if(o=setTimeout(()=>{p({cause:`remote`,error:new Y(J.RequestTimeout,`subscriptions/listen ack timed out`,{timeout:g})}),m().catch(()=>{})},g),t?.signal){let e=t.signal;s=()=>{if(a===`closed`)return;let t=e.reason;p({cause:`local`,error:t instanceof Error?t:Error(String(t??`Aborted`))}),m().catch(()=>{})},e.addEventListener(`abort`,s,{once:!0})}let _={jsonrpc:`2.0`,id:i,method:`subscriptions/listen`,params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},v=e=>{p({cause:`remote`,error:e instanceof Error?e:Error(String(e))})};try{this.transport.send(_,{requestSignal:r.signal,onRequestStreamEnd:()=>p({cause:`remote`,error:Error(`subscriptions/listen: stream ended`)})}).catch(v)}catch(e){v(e)}return{honoredFilter:await u,close:h,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let n=Object.hasOwn(gu,e.method)?gu[e.method]:void 0;if(e.method===`notifications/resources/updated`){let t=e.params?.uri;typeof t==`string`&&this._cache.evictKey(`resources/read`,t)}else if(n!==void 0)for(let e of n)this._cache.evict(e);if(e.method===`notifications/subscriptions/acknowledged`){let t=e.params?._meta?.[ze],n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){let t=this._wireCodec().validateNotification(`notifications/subscriptions/acknowledged`,e);n.settle({ack:t.ok?t.value.params.notifications:{}});return}}if(e.method===`notifications/cancelled`){let t=e.params?.requestId,n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){n.settle({cause:`remote`,error:Error(`subscriptions/listen: server cancelled the subscription`)});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){Va(e)?n.settle({cause:`remote`,error:Z.fromError(e.error.code,e.error.message,e.error.data)}):n.settle({cause:`graceful`,error:new Y(J.ConnectionClosed,`subscriptions/listen: server closed the subscription gracefully before acknowledging`)});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new Y(J.ConnectionClosed,`Connection closed`);for(let t of this._listenState.values())t.settle({cause:`remote`,error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let n=this.getProtocolEra()===`modern`&&$l()!==`browser`,r=async()=>{if(!n)return t;let r;try{r=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(e){this._reportStoreError(e)}if(!r?.valid||r.declarations.length===0)return t;let i=oo(r.declarations,e.arguments);return Object.keys(i).length===0?t:{...t,headers:{...t?.headers,...i}}},i=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,e=>this._compileOutputValidator(e)).catch(e=>void this._reportStoreError(e)):this._compileOutputValidator(t.toolDefinition),a=()=>{if(i===void 0||i.ok)return;let t=i.compileError,n=(t instanceof Error?t.message:String(t)).slice(0,200);throw new Z(X.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${n}`)};a();let o;try{o=await this.request({method:`tools/call`,params:e},await r())}catch(s){let c=s instanceof Z&&s.code===-32020;if(!n||!c||t?.toolDefinition!==void 0)throw s;let l={signal:t?.signal,timeout:t?.timeout,cacheMode:`refresh`};await this._cache.evict(`tools/list`),await this.listTools(void 0,l).catch(e=>this._reportStoreError(e)),i=await this._cache.outputValidator(e.name,e=>this._compileOutputValidator(e)).catch(e=>void this._reportStoreError(e)),a(),o=await this.request({method:`tools/call`,params:e},await r())}let s=i!==void 0&&i.ok?i.validator:void 0;if(s){if(o.structuredContent===void 0&&!o.isError)throw new Z(X.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent!==void 0&&!o.isError)try{let e=s(o.structuredContent);if(!e.valid)throw new Z(X.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Z?e:new Z(X.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug(`Client.listTools() called but server does not advertise tools capability - returning empty list`),{tools:[]};if(e?.cursor!==void 0){let n=await this.request({method:`tools/list`,params:e},t);return this._excludeInvalidXMcpHeaderTools(n),n}let n=await this._serveFromCache(`tools/list`,void 0,t);return n===void 0?this._listAllPages(`tools/list`,e,t,e=>e.tools,e=>this._excludeInvalidXMcpHeaderTools(e)):n}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!==`modern`||!this.transport||eu(this.transport)===`stdio`)return;let t=e.tools.filter(e=>{let t=Ya(e.inputSchema);return t.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${e.name}' from tools/list: invalid x-mcp-header declaration — ${t.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,n,r){let i=uo(Dn,n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{s(null,await r())}catch(e){s(e instanceof Error?e:Error(String(e)),null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}};function yu(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function bu(e){if(e.status!==401)return!1;let t=e.headers.get(`www-authenticate`)??``;return yu(t)&&/use_dpop_nonce/i.test(t)}var xu=(e,t)=>n=>{let r=typeof e==`function`?e:()=>e;return async(e,i)=>{let a=(i?.method??`GET`).toUpperCase(),o=new URL(e.toString()),s=await r();if(!s)return n(e,i);let c=async()=>{let r=await t();if(!r)return n(e,i);let c=new Headers(i?.headers),l=await s.buildProof({htm:a,htu:o,accessToken:r});return c.set(`Authorization`,`DPoP ${r}`),c.set(`DPoP`,l),n(e,{...i,headers:c})},l=await c();return bu(l)&&l.headers.has(`dpop-nonce`)&&(s.observeNonce(l,o),await l.text?.().catch(()=>{}),l=await c()),s.observeNonce(l,o),l}},Su=e=>xu(async()=>{try{return await e.dpop?.()}catch(e){throw Ll(e)}},async()=>{let t;try{t=await e.tokens()}catch(e){throw Ll(e)}return t?.token_type?.toLowerCase()===`dpop`?t.access_token:void 0});(class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SseError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n,Qr(this,new.target)}});var Cu=1,wu={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Tu=new Set([`authorization`,`dpop`,`content-type`,`mcp-protocol-version`,`mcp-method`,`mcp-name`,`mcp-session-id`]);function Eu(e,t){if(typeof AbortSignal.any==`function`)return AbortSignal.any([e,t]);let n=new AbortController;if(e.aborted)return n.abort(e.reason),n.signal;if(t.aborted)return n.abort(t.reason),n.signal;let r=()=>{e.removeEventListener(`abort`,i),t.removeEventListener(`abort`,a)};function i(){r(),n.abort(e.reason)}function a(){r(),n.abort(t.reason)}return e.addEventListener(`abort`,i,{once:!0}),t.addEventListener(`abort`,a,{once:!0}),n.signal}var Du=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Ic(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=Rc(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop&&(this._fetch=Su(t.authProvider)(t.fetch??fetch))):this._authProvider=t?.authProvider,this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=bs(t?.fetch,t?.requestInit),this._redirectPolicy===`follow`&&(this._fetchWithInit=Es(this._fetchWithInit)),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??wu,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??`reauthorize`,this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Cu)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(e){throw Ll(e)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope===`throw`||!this._oauthProvider)throw new Nc({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new ni(J.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??`Forbidden`,text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let n=await this._oauthProvider.tokens(),r=Hc(this._scope,n?.scope,e.scope);this._scope=r;let i=Uc(r,n?.scope);return al(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:r,forceReauthorization:i,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy===`follow`?e:Ds(e)}_unfollowedRedirect(e,t){let n=this._redirectPolicy===`follow`?void 0:Os(e,t);return n&&`${n} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(e){throw Ll(e)}return t&&e.set(`Authorization`,`Bearer ${t}`),this._sessionId&&e.set(`mcp-session-id`,this._sessionId),this._protocolVersion&&e.set(`mcp-protocol-version`,this._protocolVersion),e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Ra(t))return;let n=t.params?._meta?.[Fe];if(typeof n!=`string`)return;e.set(`mcp-protocol-version`,n),e.set(`mcp-method`,t.method);let r=co(t.method,t.params);r?.value!==void 0&&e.set(`mcp-name`,io(r.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Ra(e))return!1;let t=e.params?._meta?.[Fe];return typeof t==`string`&&ci(t)}async _startOrAuthSse(e,t=!1,n=0){let{resumptionToken:r,requestSignal:i}=e,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0;try{let a=await this._commonHeaders(),o=[...a.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`text/event-stream`];a.set(`accept`,[...new Set(o)].join(`, `)),r&&a.set(`last-event-id`,r);let s=this._abortController?.signal,c=i!==void 0&&s!==void 0?Eu(s,i):i??s,l=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:`GET`,headers:a,signal:c});if(!l.ok){if(l.status===401&&this._authProvider){if(l.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=dl(l);this._resourceMetadataUrl=e,this._scope=Hc(this._scope,t)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:l,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw Ll(e)}return await l.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,n)}throw await l.text?.().catch(()=>{}),Ll(t?new ni(J.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:l.statusText}):new zc)}if(l.status===403){let{resourceMetadataUrl:r,scope:i,error:a,errorDescription:o}=dl(l);if(a===`insufficient_scope`){let a=await l.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:i,resourceMetadataUrl:r,errorDescription:o,statusText:l.statusText,text:a},n)!==`AUTHORIZED`)throw Ll(new zc);return this._startOrAuthSse(e,t,n+1)}}if(await l.text?.().catch(()=>{}),l.status===405){e.onRequestStreamEnd?.();return}let r=this._unfollowedRedirect(this._url,l)??l.statusText;throw new ni(J.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${r}`,{status:l.status,statusText:l.statusText})}this._handleSseStream(l.body,e,!0)}catch(e){throw a()||this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`)),e.onRequestStreamEnd?.();return}let r=this._getNextReconnectionDelay(t),i=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(n=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`));try{this._scheduleReconnection(e,t+1)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}})};if(this._reconnectionScheduler){let e=this._reconnectionScheduler(i,r,t);this._cancelReconnection=typeof e==`function`?e:void 0}else{let e=setTimeout(i,r);this._cancelReconnection=()=>clearTimeout(e)}}_handleSseStream(e,t,n){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o}=t,s=()=>this._abortController?.signal.aborted===!0||a?.aborted===!0,c,l=!1,u=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Dc({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(c=e.id,l=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=tt.parse(JSON.parse(e.data));(Ba(t)||Va(t))&&(u=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||l)&&!u&&this._abortController&&!s()?this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o},0):s()||o?.()}catch(e){if(s())return;if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||l)&&!u&&this._abortController&&!s())try{this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`)),o?.()}else o?.()}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new zc(`finishAuth requires an OAuthClientProvider`);let{authorizationCode:n,iss:r}=await Wc(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await al(this._oauthProvider,{serverUrl:this._url,authorizationCode:n,iss:r,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!==`AUTHORIZED`)throw new zc(`Failed to authorize`)}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,n,r=0){try{let{resumptionToken:i,onresumptiontoken:a}=t||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:Ra(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(e=>this.onerror?.(e));return}let o=await this._commonHeaders();this._applyBodyDerivedHeaders(o,e);let s=Array.isArray(e)?e.some(e=>Ua(e)):Ua(e);if(s&&o.delete(`mcp-session-id`),t?.headers!==void 0)for(let[e,n]of Object.entries(t.headers))Tu.has(e.toLowerCase())||o.set(e,n);o.set(`content-type`,`application/json`);let c=[...o.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`application/json`,`text/event-stream`];o.set(`accept`,[...new Set(c)].join(`, `));let l=this._abortController?.signal,u=t?.requestSignal!==void 0&&l!==void 0?Eu(l,t.requestSignal):t?.requestSignal??l,d={...this._requestInit,method:`POST`,headers:o,body:JSON.stringify(e),signal:u},f=await this._redirects(this._fetch??fetch)(this._url,d);if(s&&f.ok&&(this._sessionId=f.headers.get(`mcp-session-id`)||void 0),!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=dl(f);this._resourceMetadataUrl=e,this._scope=Hc(this._scope,t)}if(this._authProvider.onUnauthorized&&!n){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw Ll(e)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,r)}throw await f.text?.().catch(()=>{}),Ll(n?new ni(J.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:f.statusText}):new zc)}let i=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:a,scope:o,error:s,errorDescription:c}=dl(f);if(s===`insufficient_scope`){if(await this._stepUpAuthorize({scope:o,resourceMetadataUrl:a,errorDescription:c,statusText:f.statusText,text:i},r)!==`AUTHORIZED`)throw Ll(new zc);return this._send(e,t,n,r+1)}}if(f.status===400&&typeof i==`string`&&this._isModernEnvelopedRequest(e))try{let t=tt.parse(JSON.parse(i)),n=(Array.isArray(e)?e:[e]).filter(e=>Ra(e));if(Va(t)&&n.some(e=>e.id===t.id)){this.onmessage?.(t);return}}catch{}let a=this._unfollowedRedirect(this._url,f)??i;throw new ni(J.ClientHttpNotImplemented,`Error POSTing to endpoint: ${a}`,{status:f.status,statusText:f.statusText,text:i})}if(f.status===202){await f.text?.().catch(()=>{}),Wa(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let p=(Array.isArray(e)?e:[e]).some(e=>`method`in e&&`id`in e&&e.id!==void 0),m=f.headers.get(`content-type`),h=vs(m);if(p){if(h===`text/event-stream`)this._handleSseStream(f.body,{onresumptiontoken:a,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(h===`application/json`){let e=await f.json(),t=Array.isArray(e)?e.map(e=>tt.parse(e)):[tt.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await f.text?.().catch(()=>{}),new Y(J.ClientHttpUnexpectedContent,`Unexpected content type: ${m}`,{contentType:m})}else await f.text?.().catch(()=>{})}catch(e){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await this._redirects(this._fetch??fetch)(this._url,t);if(await n.text?.().catch(()=>{}),!n.ok&&n.status!==405)throw new ni(J.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,n)??n.statusText}`,{status:n.status,statusText:n.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}},Ou=class{_eventSlots=new Map;setHandler(e,t){let n=this._ensureEventSlot(e);n.onHandler&&t&&console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`),n.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let n=this._eventSlots.get(e);if(!n)return;let r=n.listeners.indexOf(t);r!==-1&&n.listeners.splice(r,1)}dispatch(e,t){let n=this._eventSlots.get(e);if(n){n.onHandler?.(t);for(let e of[...n.listeners])e(t)}}_ensureEventSlot(e){let t=this._eventSlots.get(e);return t||(t={listeners:[]},this._eventSlots.set(e,t)),t}},ku=class{_methods=new Set;claim(e,t){if(this._methods.has(e))throw Error(`Handler for "${e}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(e)}replace(e){this._methods.add(e)}release(e){this._methods.delete(e)}has(e){return this._methods.has(e)}},Au=new Set;function ju(e,t){let[n,r]=t,i=n?.shape;if(typeof i?.method?.value!=`string`)return;let a=i.method.value,o=e===`request`?`setRequestHandler`:`setNotificationHandler`;Au.has(o)||(Au.add(o),console.warn(`[ext-apps] ${o}(Schema, handler) is deprecated; use ${o}("${a}", { params: Schema.shape.params }, handler).`));let s=r;return[a,{params:i.params},e===`request`?(e,t)=>s({method:a,params:e},Mu(t)):e=>s({method:a,params:e})]}function Mu(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var Nu=`2026-01-26`,Pu=j([w(`light`),w(`dark`)]).describe(`Color theme preference for the host environment.`),Fu=j([w(`inline`),w(`fullscreen`),w(`pip`)]).describe(`Display mode for UI presentation.`),Iu=j([w(`--color-background-primary`),w(`--color-background-secondary`),w(`--color-background-tertiary`),w(`--color-background-inverse`),w(`--color-background-ghost`),w(`--color-background-info`),w(`--color-background-danger`),w(`--color-background-success`),w(`--color-background-warning`),w(`--color-background-disabled`),w(`--color-text-primary`),w(`--color-text-secondary`),w(`--color-text-tertiary`),w(`--color-text-inverse`),w(`--color-text-ghost`),w(`--color-text-info`),w(`--color-text-danger`),w(`--color-text-success`),w(`--color-text-warning`),w(`--color-text-disabled`),w(`--color-border-primary`),w(`--color-border-secondary`),w(`--color-border-tertiary`),w(`--color-border-inverse`),w(`--color-border-ghost`),w(`--color-border-info`),w(`--color-border-danger`),w(`--color-border-success`),w(`--color-border-warning`),w(`--color-border-disabled`),w(`--color-ring-primary`),w(`--color-ring-secondary`),w(`--color-ring-inverse`),w(`--color-ring-info`),w(`--color-ring-danger`),w(`--color-ring-success`),w(`--color-ring-warning`),w(`--font-sans`),w(`--font-mono`),w(`--font-weight-normal`),w(`--font-weight-medium`),w(`--font-weight-semibold`),w(`--font-weight-bold`),w(`--font-text-xs-size`),w(`--font-text-sm-size`),w(`--font-text-md-size`),w(`--font-text-lg-size`),w(`--font-heading-xs-size`),w(`--font-heading-sm-size`),w(`--font-heading-md-size`),w(`--font-heading-lg-size`),w(`--font-heading-xl-size`),w(`--font-heading-2xl-size`),w(`--font-heading-3xl-size`),w(`--font-text-xs-line-height`),w(`--font-text-sm-line-height`),w(`--font-text-md-line-height`),w(`--font-text-lg-line-height`),w(`--font-heading-xs-line-height`),w(`--font-heading-sm-line-height`),w(`--font-heading-md-line-height`),w(`--font-heading-lg-line-height`),w(`--font-heading-xl-line-height`),w(`--font-heading-2xl-line-height`),w(`--font-heading-3xl-line-height`),w(`--border-radius-xs`),w(`--border-radius-sm`),w(`--border-radius-md`),w(`--border-radius-lg`),w(`--border-radius-xl`),w(`--border-radius-full`),w(`--border-width-regular`),w(`--shadow-hairline`),w(`--shadow-sm`),w(`--shadow-md`),w(`--shadow-lg`)]).describe(`CSS variable keys available to MCP apps for theming.`),Lu=M(Iu.describe(`Style variables for theming MCP apps. - -Individual style keys are optional - hosts may provide any subset of these values. -Values are strings containing CSS values (colors, sizes, font stacks, etc.). - -Note: This type uses \`Record\` rather than \`Partial>\` -for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),j([x(),te()]).describe(`Style variables for theming MCP apps. - -Individual style keys are optional - hosts may provide any subset of these values. -Values are strings containing CSS values (colors, sizes, font stacks, etc.). - -Note: This type uses \`Record\` rather than \`Partial>\` -for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps. - -Individual style keys are optional - hosts may provide any subset of these values. -Values are strings containing CSS values (colors, sizes, font stacks, etc.). - -Note: This type uses \`Record\` rather than \`Partial>\` -for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Ru=T({method:w(`ui/open-link`),params:T({url:x().describe(`URL to open in the host's browser`)})}),zu=T({isError:A().optional().describe(`True if the host failed to open the URL (e.g., due to security policy).`)}).passthrough(),Bu=T({isError:A().optional().describe(`True if the download failed (e.g., user cancelled or host denied).`)}).passthrough(),Vu=T({isError:A().optional().describe(`True if the host rejected or failed to deliver the message.`)}).passthrough(),Hu=T({method:w(`ui/notifications/sandbox-proxy-ready`),params:T({})}),Uu=T({connectDomains:O(x()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket). - -- Maps to CSP \`connect-src\` directive -- Empty or omitted → no network connections (secure default)`),resourceDomains:O(x()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:O(x()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:O(x()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Wu=T({camera:T({}).optional().describe(`Request camera access. - -Maps to Permission Policy \`camera\` feature.`),microphone:T({}).optional().describe(`Request microphone access. - -Maps to Permission Policy \`microphone\` feature.`),geolocation:T({}).optional().describe(`Request geolocation access. - -Maps to Permission Policy \`geolocation\` feature.`),clipboardWrite:T({}).optional().describe(`Request clipboard write access. - -Maps to Permission Policy \`clipboard-write\` feature.`)}),Gu=T({method:w(`ui/notifications/size-changed`),params:T({width:E().optional().describe(`New width in pixels.`),height:E().optional().describe(`New height in pixels.`)})});T({method:w(`ui/notifications/tool-input`),params:T({arguments:M(x(),h().describe(`Complete tool call arguments as key-value pairs.`)).optional().describe(`Complete tool call arguments as key-value pairs.`)})}),T({method:w(`ui/notifications/tool-input-partial`),params:T({arguments:M(x(),h().describe(`Partial tool call arguments (incomplete, may change).`)).optional().describe(`Partial tool call arguments (incomplete, may change).`)})}),T({method:w(`ui/notifications/tool-cancelled`),params:T({reason:x().optional().describe(`Optional reason for the cancellation (e.g., "user action", "timeout").`)})});var Ku=T({fonts:x().optional()}),qu=T({variables:Lu.optional().describe(`CSS variables for theming the app.`),css:Ku.optional().describe(`CSS blocks that apps can inject.`)});T({method:w(`ui/resource-teardown`),params:T({})});var Ju=M(x(),h()),Yu=T({text:T({}).optional().describe(`Host supports text content blocks.`),image:T({}).optional().describe(`Host supports image content blocks.`),audio:T({}).optional().describe(`Host supports audio content blocks.`),resource:T({}).optional().describe(`Host supports resource content blocks.`),resourceLink:T({}).optional().describe(`Host supports resource link content blocks.`),structuredContent:T({}).optional().describe(`Host supports structured content.`)}),Xu=T({method:w(`ui/notifications/request-teardown`),params:T({}).optional()}),Zu=T({experimental:M(x(),M(x(),b()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),openLinks:T({}).optional().describe(`Host supports opening external URLs.`),downloadFile:T({}).optional().describe(`Host supports file downloads via ui/download-file.`),serverTools:T({listChanged:A().optional().describe(`Host supports tools/list_changed notifications.`)}).optional().describe(`Host can proxy tool calls to the MCP server.`),serverResources:T({listChanged:A().optional().describe(`Host supports resources/list_changed notifications.`)}).optional().describe(`Host can proxy resource reads to the MCP server.`),logging:T({}).optional().describe(`Host accepts log messages.`),sandbox:T({permissions:Wu.optional().describe(`Permissions granted by the host (camera, microphone, geolocation).`),csp:Uu.optional().describe(`CSP domains approved by the host.`)}).optional().describe(`Sandbox configuration applied by the host.`),updateModelContext:Yu.optional().describe(`Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.`),message:Yu.optional().describe(`Host supports receiving content messages (ui/message) from the view.`),sampling:T({tools:T({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),Qu=T({experimental:M(x(),M(x(),b()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),tools:T({listChanged:A().optional().describe(`App supports tools/list_changed notifications.`)}).optional().describe(`App exposes MCP-style tools that the host can call.`),availableDisplayModes:O(Fu).optional().describe(`Display modes the app supports.`)}),$u=T({method:w(`ui/notifications/initialized`),params:T({}).optional()});T({csp:Uu.optional().describe(`Content Security Policy configuration for UI resources.`),permissions:Wu.optional().describe(`Sandbox permissions requested by the UI resource.`),domain:x().optional().describe(`Dedicated origin for view sandbox. - -Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists. - -**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include: -- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`) -- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`) - -If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:A().optional().describe(`Visual boundary preference - true if view prefers a visible border. - -Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary. - -- \`true\`: request visible border + background -- \`false\`: request no visible border + background -- omitted: host decides border`)});var ed=T({method:w(`ui/request-display-mode`),params:T({mode:Fu.describe(`The display mode being requested.`)})}),td=T({mode:Fu.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),nd=j([w(`model`),w(`app`)]).describe(`Tool visibility scope - who can access the tool.`);T({resourceUri:x().optional(),visibility:O(nd).optional().describe(`Who can access this tool. Default: ["model", "app"] -- "model": Tool visible to and callable by the agent -- "app": Tool callable by the app from this server only`),csp:ie().optional(),permissions:ie().optional()}),T({mimeTypes:O(x()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});var rd=T({method:w(`ui/download-file`),params:T({contents:O(j([dn,fn])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),id=T({method:w(`ui/message`),params:T({role:w(`user`).describe(`Message role, currently only "user" is supported.`),content:O(pn).describe(`Message content blocks (text, image, etc.).`)})});T({method:w(`ui/notifications/sandbox-resource-ready`),params:T({html:x().describe(`HTML content to load into the inner iframe.`),sandbox:x().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:Uu.optional().describe(`CSP configuration from resource metadata.`),permissions:Wu.optional().describe(`Sandbox permissions from resource metadata.`)})}),T({method:w(`ui/notifications/tool-result`),params:Sn.describe(`Standard MCP tool execution result.`)});var ad=T({toolInfo:T({id:Xe.optional().describe(`JSON-RPC id of the tools/call request.`),tool:yn.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:Pu.optional().describe(`Current color theme preference.`),styles:qu.optional().describe(`Style configuration for theming the app.`),displayMode:Fu.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:O(Fu).optional().describe(`Display modes the host supports.`),containerDimensions:j([T({height:E().describe(`Fixed container height in pixels.`)}),T({maxHeight:j([E(),te()]).optional().describe(`Maximum container height in pixels.`)})]).and(j([T({width:E().describe(`Fixed container width in pixels.`)}),T({maxWidth:j([E(),te()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other -container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:x().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:x().optional().describe(`User's timezone in IANA format.`),userAgent:x().optional().describe(`Host application identifier.`),platform:j([w(`web`),w(`desktop`),w(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:T({touch:A().optional().describe(`Whether the device supports touch input.`),hover:A().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:T({top:E().describe(`Top safe area inset in pixels.`),right:E().describe(`Right safe area inset in pixels.`),bottom:E().describe(`Bottom safe area inset in pixels.`),left:E().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough();T({method:w(`ui/notifications/host-context-changed`),params:ad.describe(`Partial context update containing only changed fields.`)});var od=T({method:w(`ui/update-model-context`),params:T({content:O(pn).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:M(x(),h().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),sd=T({method:w(`ui/initialize`),params:T({appInfo:H.describe(`App identification (name and version).`),appCapabilities:Qu.describe(`Features and capabilities this app provides.`),protocolVersion:x().describe(`Protocol version this app supports.`)})}),cd=T({protocolVersion:x().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:H.describe(`Host application identification and version.`),hostCapabilities:Zu.describe(`Features and capabilities provided by the host.`),hostContext:ad.describe(`Rich context about the host environment.`)}).passthrough(),ld=class{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=e=>{if(t&&e.source!==this.eventSource){console.debug(`Ignoring message from unknown source`,e);return}let n=tt.safeParse(e.data);n.success?(console.debug(`Parsed message`,n.data),this.onmessage?.(n.data)):e.data?.jsonrpc===`2.0`?(console.error(`Failed to parse message`,n.error.message,e),this.onerror?.(Error(`Invalid JSON-RPC message received: `+n.error.message))):console.debug(`Ignoring non-JSON-RPC message`,n.error.message,e)}}async start(){window.addEventListener(`message`,this.messageListener)}async send(e,t){e.method!==`ui/notifications/tool-input-partial`&&console.debug(`Sending message`,e),this.eventTarget.postMessage(e,`*`)}async close(){window.removeEventListener(`message`,this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion},ud=[Nu],dd=class extends os{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Ou;_methods=new ku;setRequestHandler=(...e)=>{let[t,...n]=ju(`request`,e)??e;this._methods.claim(t,`setRequestHandler`),super.setRequestHandler.call(this,t,...n)};setNotificationHandler=(...e)=>{let[t,...n]=ju(`notification`,e)??e;this._methods.claim(t,`setNotificationHandler`),super.setNotificationHandler.call(this,t,...n)};removeRequestHandler=e=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=e=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let n=super._wrapHandler(e,t);return e===`ui/initialize`||e===`ping`?n:async(t,r)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),n(t,r))}eventSchemas={sizechange:Gu,sandboxready:Hu,initialized:$u,requestteardown:Xu,loggingmessage:Mn};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let n=t=>{e===`initialized`&&(this._initializedReceived=!0),this._events.dispatch(e,t)};e===`loggingmessage`?this.setNotificationHandler(`notifications/message`,e=>{n(e.params)}):this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},e=>n(e)),this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,n){t&&n&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,n,r){super(r),this._client=e,this._hostInfo=t,this._hostCapabilities=n,this._methods.replace(`notifications/cancelled`),this._methods.replace(`notifications/progress`),this._ensureEventSlot(`initialized`),this._hostContext=r?.hostContext||{},this.replaceRequestHandler(`ui/initialize`,{params:sd.shape.params,result:cd},e=>this._onAppsInitialize(e)),this.replaceRequestHandler(`ping`,(e,t)=>(this.onping?.(e.params,t),{})),this.replaceRequestHandler(`ui/request-display-mode`,{params:ed.shape.params,result:td},()=>({mode:this._hostContext.displayMode??`inline`}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler(`sizechange`)}set onsizechange(e){this.setEventHandler(`sizechange`,e)}get onsandboxready(){return this.getEventHandler(`sandboxready`)}set onsandboxready(e){this.setEventHandler(`sandboxready`,e)}get oninitialized(){return this.getEventHandler(`initialized`)}set oninitialized(e){this.setEventHandler(`initialized`,e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced(`onmessage`,this._onmessage,e),this._onmessage=e,this.replaceRequestHandler(`ui/message`,{params:id.shape.params,result:Vu},async(e,t)=>{if(!this._onmessage)throw Error(`No onmessage handler set`);return this._onmessage(e,t)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced(`onopenlink`,this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler(`ui/open-link`,{params:Ru.shape.params,result:zu},async(e,t)=>{if(!this._onopenlink)throw Error(`No onopenlink handler set`);return this._onopenlink(e,t)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced(`ondownloadfile`,this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler(`ui/download-file`,{params:rd.shape.params,result:Bu},async(e,t)=>{if(!this._ondownloadfile)throw Error(`No ondownloadfile handler set`);return this._ondownloadfile(e,t)})}get onrequestteardown(){return this.getEventHandler(`requestteardown`)}set onrequestteardown(e){this.setEventHandler(`requestteardown`,e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced(`onrequestdisplaymode`,this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler(`ui/request-display-mode`,{params:ed.shape.params,result:td},async(e,t)=>{if(!this._onrequestdisplaymode)throw Error(`No onrequestdisplaymode handler set`);return this._onrequestdisplaymode(e,t)})}get onloggingmessage(){return this.getEventHandler(`loggingmessage`)}set onloggingmessage(e){this.setEventHandler(`loggingmessage`,e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced(`onupdatemodelcontext`,this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler(`ui/update-model-context`,{params:od.shape.params,result:rt},async(e,t)=>{if(!this._onupdatemodelcontext)throw Error(`No onupdatemodelcontext handler set`);return this._onupdatemodelcontext(e,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(`tools/call`,async(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced(`oncreatesamplingmessage`,this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler(`sampling/createMessage`,async(e,t)=>{if(!this._oncreatesamplingmessage)throw Error(`No oncreatesamplingmessage handler set`);return this._oncreatesamplingmessage(e.params,t)})}sendToolListChanged(e={}){return this.notification({method:`notifications/tools/list_changed`,params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced(`onlistresources`,this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler(`resources/list`,async(e,t)=>{if(!this._onlistresources)throw Error(`No onlistresources handler set`);return this._onlistresources(e.params,t)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced(`onlistresourcetemplates`,this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler(`resources/templates/list`,async(e,t)=>{if(!this._onlistresourcetemplates)throw Error(`No onlistresourcetemplates handler set`);return this._onlistresourcetemplates(e.params,t)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced(`onreadresource`,this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler(`resources/read`,async(e,t)=>{if(!this._onreadresource)throw Error(`No onreadresource handler set`);return this._onreadresource(e.params,t)})}sendResourceListChanged(e={}){return this.notification({method:`notifications/resources/list_changed`,params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced(`onlistprompts`,this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler(`prompts/list`,async(e,t)=>{if(!this._onlistprompts)throw Error(`No onlistprompts handler set`);return this._onlistprompts(e.params,t)})}sendPromptListChanged(e={}){return this.notification({method:`notifications/prompts/list_changed`,params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;return this._appInfo!==void 0&&console.warn(`[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.`),this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:ud.includes(t)?t:Nu,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},n=!1;for(let r of Object.keys(e)){let i=this._hostContext[r],a=e[r];fd(i,a)||(t[r]=a,n=!0)}n&&(this._hostContext=e,this.sendHostContextChange(t))}sendHostContextChange(e){return this.notification({method:`ui/notifications/host-context-changed`,params:e})}sendToolInput(e){return this.notification({method:`ui/notifications/tool-input`,params:e})}sendToolInputPartial(e){return this.notification({method:`ui/notifications/tool-input-partial`,params:e})}sendToolResult(e){return this.notification({method:`ui/notifications/tool-result`,params:e})}sendToolCancelled(e){return this.notification({method:`ui/notifications/tool-cancelled`,params:e})}sendSandboxResourceReady(e){return this.notification({method:`ui/notifications/sandbox-resource-ready`,params:e})}teardownResource(e,t){return this.request({method:`ui/resource-teardown`,params:e},Ju,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:`tools/call`,params:e},t)}listTools(e,t){return this.request({method:`tools/list`,params:e},t)}async connect(e){if(this.transport)throw Error(`AppBridge is already connected. Call close() before connecting again.`);if(this._initializedReceived=!1,this._client){let e=this._client.getServerCapabilities();if(!e)throw Error(`Client server capabilities not available`);e.tools&&(this.oncalltool=async(e,t)=>this._client.request({method:`tools/call`,params:e},{signal:t.mcpReq.signal}),e.tools.listChanged&&this._client.setNotificationHandler(`notifications/tools/list_changed`,e=>this.sendToolListChanged(e.params))),e.resources&&(this.onlistresources=async(e,t)=>this._client.request({method:`resources/list`,params:e},{signal:t.mcpReq.signal}),this.onlistresourcetemplates=async(e,t)=>this._client.request({method:`resources/templates/list`,params:e},{signal:t.mcpReq.signal}),this.onreadresource=async(e,t)=>this._client.request({method:`resources/read`,params:e},{signal:t.mcpReq.signal}),e.resources.listChanged&&this._client.setNotificationHandler(`notifications/resources/list_changed`,e=>this.sendResourceListChanged(e.params))),e.prompts&&(this.onlistprompts=async(e,t)=>this._client.request({method:`prompts/list`,params:e},{signal:t.mcpReq.signal}),e.prompts.listChanged&&this._client.setNotificationHandler(`notifications/prompts/list_changed`,e=>this.sendPromptListChanged(e.params)))}return super.connect(e)}};function fd(e,t){return JSON.stringify(e)===JSON.stringify(t)}var $=n(e(),1),pd=t(),md=`text/html;profile=mcp-app`,hd=`io.modelcontextprotocol/ui`,gd=3,_d=5,vd=2e3,yd=[`inline`,`fullscreen`],bd=class extends Error{},xd=null,Sd=null;async function Cd(){let e=new Du(new URL(`/api/mcp`,location.origin),{fetch:(e,t)=>ue(e,t)}),t=new vu({name:`fanout-browser`,version:`0.2.0`},{supportedProtocolVersions:[`2026-07-28`],versionNegotiation:{mode:{pin:`2026-07-28`}},capabilities:{extensions:{[hd]:{mimeTypes:[md]}}}});try{await t.connect(e);let n={client:t,tools:t.listTools(),references:0,closed:!1,closeListeners:new Set};return n.tools.catch(()=>void 0),t.onclose=()=>Td(n,!1),t.onerror=()=>Td(n,!0),n}catch(t){throw await e.close().catch(()=>void 0),t}}async function wd(){for(let e=0;e{Sd===e&&!t.closed&&(xd=t)}).catch(()=>{Sd===e&&(Sd=null)})}let e=Sd;if(!e)continue;let t=await e;if(t.closed){Sd===e&&(Sd=null);continue}return t.closeTimer&&=(clearTimeout(t.closeTimer),void 0),t.references+=1,t}throw Error(`MCP connection closed during setup`)}function Td(e,t){if(!e.closed){e.closed=!0,e.closeTimer&&clearTimeout(e.closeTimer),e.closeTimer=void 0,xd===e&&(xd=null),Sd=null;for(let t of[...e.closeListeners])t();t&&e.client.close().catch(()=>void 0)}}function Ed(e){e.references=Math.max(0,e.references-1),!(e.closed||e.references||e.closeTimer)&&(e.closeTimer=setTimeout(()=>{e.closeTimer=void 0,!(e.references||xd!==e)&&(e.closed=!0,xd=null,Sd=null,e.client.close().catch(()=>void 0))},0))}function Dd(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}var Od=new Map;async function kd(e,t){let n=Od.get(t);if(n&&n.expires>Date.now())return n.pending;let r={pending:Promise.resolve({text:``}),expires:1/0};return r.pending=e.readResource({uri:t}).then(e=>{let n=e.contents[0];if(e.contents.length!==1||!n||!(`text`in n)||!n.text)throw new bd(`MCP App resource has no HTML content`);if(n.uri!==t)throw new bd(`MCP App resource URI does not match the requested URI`);if(n.mimeType!==md)throw new bd(`MCP App resource has an unsupported MIME type`);let i=Dd(e)?.ttlMs;return r.expires=Date.now()+(typeof i==`number`&&i>0?i:3e5),{text:n.text,_meta:n._meta}}).catch(e=>{throw Od.get(t)===r&&Od.delete(t),e}),Od.set(t,r),r.pending}function Ad(e,t){let n=``;return/]*)?>/i.test(e)?e.replace(/]*)?>/i,e=>`${e}${n}`):/]*)?>/i.test(e)?e.replace(/]*)?>/i,e=>`${e}${n}`):`${n}${e}`}function jd({content:e}){let t=l(e);return t?(0,pd.jsx)(Md,{content:t}):(0,pd.jsx)(o,{color:`bad`,m:`md`,children:`This view could not be loaded. Please try again.`})}function Md({content:e}){let t=(0,$.useRef)(null),n=(0,$.useRef)(null),l=(0,$.useRef)(null),u=(0,$.useRef)(null),[d,f]=(0,$.useState)(``),[p,m]=(0,$.useState)(`inline`),h=(0,$.useRef)(null),g=(0,$.useRef)(p);g.current=p;let y=e=>{m(e),u.current?.setHostContext({theme:te.current,displayMode:e,availableDisplayModes:yd}),e===`inline`&&document.activeElement!==t.current&&t.current?.focus()};(0,$.useEffect)(()=>{if(p!==`fullscreen`)return;h.current?.focus();let e=document.body.style.overflow;document.body.style.overflow=`hidden`;let n=e=>{e.key===`Escape`&&(e.preventDefault(),y(`inline`))},r=e=>{t.current?.parentElement?.contains(e.target)||h.current?.focus()};return window.addEventListener(`keydown`,n),document.addEventListener(`focusin`,r),()=>{document.body.style.overflow=e,window.removeEventListener(`keydown`,n),document.removeEventListener(`focusin`,r)}},[p]);let[b,x]=(0,$.useState)(240),[S,ee]=(0,$.useState)(``),[C,w]=(0,$.useState)(0),T=(0,$.useRef)(0),E=_(`light`),te=(0,$.useRef)(E);te.current=E,(0,$.useEffect)(()=>{u.current?.setHostContext({theme:E,displayMode:g.current,availableDisplayModes:yd})},[E]),(0,$.useEffect)(()=>{T.current=0},[e.resource_uri]),(0,$.useEffect)(()=>{let t=!1,r;m(`inline`),f(``),ee(``);let i=()=>{let e=T.current+1;if(e>_d)return;T.current=e;let t=e===1?0:Math.min(750*2**(e-2),6e3);t===0?w(e=>e+1):r=setTimeout(()=>w(e=>e+1),t)},a=()=>i();async function o(){try{let r=await wd();if(t){Ed(r);return}l.current=r,r.closeListeners.add(a),n.current=r.client;let i=await kd(r.client,e.resource_uri);await r.tools,t||(T.current=0,f(Ad(i.text,i._meta)))}catch(e){console.error(`MCP app resource load failed`,e),t||(ee(`This view could not be loaded. Please try again.`),T.current>0&&!(e instanceof bd)&&i())}}return o(),()=>{t=!0,r&&clearTimeout(r);let e=u.current?.teardownResource({}).catch(()=>void 0)??Promise.resolve(),i=l.current;i&&(i.closeListeners.delete(a),e.finally(()=>Ed(i))),u.current=null,n.current=null,l.current=null}},[e.resource_uri,C]);async function ne(){let r=t.current,i=n.current;if(r?.contentWindow&&d&&i&&!u.current)try{let t=new dd(null,{name:`Fanout`,version:`0.2.0`},{serverTools:{},logging:{}},{hostContext:{theme:te.current,displayMode:`inline`,availableDisplayModes:yd}}),n=l.current;if(!n)throw Error(`MCP connection unavailable`);t.oncalltool=async(e,t)=>{let r=Dd(Dd((await n.tools).tools.find(t=>t.name===e.name)?._meta)?.ui)?.visibility;if(!Array.isArray(r)||!r.includes(`app`)||/^(?:create|edit|replace|restore|delete)_/.test(e.name))throw Error(`This tool is unavailable in the app`);return i.callTool(e,{signal:t.mcpReq.signal})},t.onrequestdisplaymode=async({mode:e})=>e!==`inline`&&e!==`fullscreen`?{mode:g.current}:(y(e),{mode:e}),u.current=t,t.onsizechange=({height:e})=>{e&&x(Math.min(vd,Math.max(240,Math.round(e))))},t.onmessage=async()=>({isError:!0}),t.oninitialized=async()=>{await t.sendToolInput({arguments:e.tool_input??{}}),await t.sendToolResult({content:[{type:`text`,text:JSON.stringify(e.tool_result??{})}],structuredContent:e.tool_result,isError:e.is_error})},await t.connect(new ld(r.contentWindow,r.contentWindow))}catch(e){console.error(`MCP app bridge connect failed`,e),ee(`This view could not be loaded. Please try again.`)}}return S?(0,pd.jsx)(o,{color:`bad`,m:`md`,children:S}):d?(0,pd.jsx)(v,{active:p===`fullscreen`,children:(0,pd.jsxs)(r,{"data-app-fullscreen":p===`fullscreen`?``:void 0,role:p===`fullscreen`?`dialog`:void 0,"aria-modal":p===`fullscreen`||void 0,"aria-label":p===`fullscreen`?`Fanout analysis view`:void 0,bg:`var(--mantine-color-body)`,style:p===`fullscreen`?{position:`fixed`,inset:0,zIndex:1e3,display:`flex`,flexDirection:`column`}:void 0,children:[p===`fullscreen`&&(0,pd.jsx)(r,{p:`xs`,ta:`right`,children:(0,pd.jsx)(i,{ref:h,"data-autofocus":!0,size:`compact-sm`,variant:`default`,"aria-label":`Close analysis view`,onClick:()=>y(`inline`),children:`Close`})}),(0,pd.jsx)(r,{component:`iframe`,tabIndex:0,ref:t,title:`Fanout analysis view`,sandbox:`allow-scripts`,scrolling:`auto`,srcDoc:d,w:`100%`,bd:0,bg:`var(--mantine-color-body)`,style:{display:`block`,height:p===`fullscreen`?`100%`:b,...p===`fullscreen`?{flex:`1 1 0`,minHeight:0}:{}},onLoad:()=>void ne()})]})}):(0,pd.jsxs)(s,{mih:180,p:`xl`,children:[(0,pd.jsx)(c,{size:`sm`}),(0,pd.jsx)(a,{c:`dimmed`,size:`sm`,ml:`sm`,children:`Preparing view…`})]})}export{jd as default}; \ No newline at end of file diff --git a/internal/ui/dist/assets/mcp-app-frame-BNA4_n4D.js b/internal/ui/dist/assets/mcp-app-frame-BNA4_n4D.js new file mode 100644 index 00000000..4ab68994 --- /dev/null +++ b/internal/ui/dist/assets/mcp-app-frame-BNA4_n4D.js @@ -0,0 +1,57 @@ +import{i as e,r as t,s as n}from"./useRouter-ByJ6_rwb.js";import{C as r,d as i,f as a,p as o,u as s,y as c}from"./brand-DUaZkIz1.js";import{n as l}from"./chat-D9q4mn0t.js";import{$t as u,At as d,Ct as f,Dt as p,Et as m,Ft as h,It as g,Lt as _,Mt as v,Nt as y,Ot as b,Pt as ee,Rt as x,St as S,Tt as C,Y as w,Zt as T,_t as E,bt as te,dt as ne,ft as D,gt as O,ht as re,jt as k,kt as A,lt as ie,mt as ae,pt as oe,ut as se,vt as ce,wt as le,xt as ue,yt as de,zt as fe}from"./index-m8tRkNwz.js";var pe={invalid_type:`invalid_type`,too_big:`too_big`,too_small:`too_small`,invalid_format:`invalid_format`,not_multiple_of:`not_multiple_of`,unrecognized_keys:`unrecognized_keys`,invalid_union:`invalid_union`,invalid_key:`invalid_key`,invalid_element:`invalid_element`,invalid_value:`invalid_value`,custom:`custom`},me;me||={};function he(e){return x(se,e)}function ge(e){return _(ie,e)}function _e(e){return g(ne,e)}function j(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}function M(e,t){if(!Array.isArray(e))return[];let n=new Set(t);return e.filter(e=>{if(typeof e!=`string`||/[\s;'\"]/.test(e))return!1;let t=e.match(/^([a-z]+):\/\/([^/]+)$/i);return!!(t&&n.has(t[1].toLowerCase()))})}function ve(e){let t=j(j(j(e)?.ui)?.csp),n=M(t?.connectDomains,[`http`,`https`,`ws`,`wss`]),r=M(t?.resourceDomains,[`http`,`https`]),i=M(t?.frameDomains,[`http`,`https`]),a=M(t?.baseUriDomains,[`http`,`https`]),o=r.length?` ${r.join(` `)}`:``,s=[`default-src 'none'`,`worker-src blob:`,`script-src 'self' 'unsafe-inline'${o}`,`style-src 'self' 'unsafe-inline'${o}`,`img-src 'self' data:${o}`,`media-src 'self' data:${o}`,`font-src 'self' data:${o}`,`connect-src ${n.length?n.join(` `):`'none'`}`];return i.length&&s.push(`frame-src ${i.join(` `)}`),a.length&&s.push(`base-uri ${a.join(` `)}`),`${s.join(`; `)};`}var ye=Object.create,be=Object.defineProperty,N=Object.getOwnPropertyDescriptor,xe=Object.getOwnPropertyNames,P=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty,Ce=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),we=(e,t)=>{let n={};for(var r in e)be(n,r,{get:e[r],enumerable:!0});return t&&be(n,Symbol.toStringTag,{value:`Module`}),n},Te=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=xe(t),a=0,o=i.length,s;at[e]).bind(null,s),enumerable:!(r=N(t,s))||r.enumerable});return e},Ee=(e,t,n)=>(n=e==null?{}:ye(P(e)),Te(t||!e||!e.__esModule?be(n,`default`,{value:e,enumerable:!0}):n,e)),De=new Set([`https://json-schema.org/draft/2020-12/schema`,`http://json-schema.org/draft/2020-12/schema`]),Oe=new Set([`https://json-schema.org/draft/2019-09/schema`,`http://json-schema.org/draft/2019-09/schema`]),ke=new Set([`https://json-schema.org/draft-07/schema`,`http://json-schema.org/draft-07/schema`]),Ae=new Set([`https://json-schema.org/draft-06/schema`,`http://json-schema.org/draft-06/schema`]);function je(e){return typeof e==`string`&&Oe.has(e.replace(/#$/,``))}function Me(e,t){if(!(`$schema`in e)||typeof e.$schema!=`string`)return`2020-12`;let n=e.$schema.replace(/#$/,``);if(De.has(n))return`2020-12`;if(Oe.has(n))return`2019-09`;if(ke.has(n)||Ae.has(n))return`draft-7`;throw Error(`JSON Schema declares an unsupported dialect ("$schema": "${e.$schema.slice(0,200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${t}`)}var Ne=`2025-11-25`,Pe=[Ne,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Fe=`io.modelcontextprotocol/related-task`,Ie=`io.modelcontextprotocol/protocolVersion`,Le=`io.modelcontextprotocol/clientInfo`,Re=`io.modelcontextprotocol/serverInfo`,ze=`io.modelcontextprotocol/clientCapabilities`,Be=`io.modelcontextprotocol/subscriptionId`,Ve=`io.modelcontextprotocol/logLevel`,He=ue(()=>k([d(),C(),E(),oe(),A(d(),He),O(He)])),F=A(d(),He),Ue=O(He),We=k([d(),C().int()]),Ge=d(),Ke=m({ttl:C().optional()}),qe=m({taskId:d()}),Je=f({progressToken:We.optional(),[Fe]:qe.optional()}),I=m({_meta:Je.optional()}),Ye=I.extend({task:Ke.optional()}),L=m({method:d(),params:I.loose().optional()}),R=m({_meta:Je.optional()}),z=m({method:d(),params:R.loose().optional()}),Xe=f({get[Re](){return H.optional().catch(void 0)}}),B=f({_meta:Xe.optional()}),Ze=k([d(),C().int()]),Qe=m({jsonrpc:S(`2.0`),id:Ze,...L.shape}).strict(),$e=m({jsonrpc:S(`2.0`),...z.shape}).strict(),V=m({jsonrpc:S(`2.0`),id:Ze,result:B}).strict(),et=m({jsonrpc:S(`2.0`),id:Ze.optional(),error:m({code:C().int(),message:d(),data:v().optional()})}).strict(),tt=k([Qe,$e,V,et]),nt=k([V,et]),rt=B.strict(),it=R.extend({requestId:Ze.optional(),reason:d().optional()}),at=z.extend({method:S(`notifications/cancelled`),params:it}),ot=m({src:d(),mimeType:d().optional(),sizes:O(d()).optional(),theme:D([`light`,`dark`]).optional()}),st=m({icons:O(ot).optional()}),ct=m({name:d(),title:d().optional()}),H=ct.extend({...ct.shape,...st.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),lt=te(m({applyDefaults:E().optional()}),F),ut=b(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,te(m({form:lt.optional(),url:F.optional()}),F.optional())),dt=f({list:F.optional(),cancel:F.optional(),requests:f({sampling:f({createMessage:F.optional()}).optional(),elicitation:f({create:F.optional()}).optional()}).optional()}),ft=f({list:F.optional(),cancel:F.optional(),requests:f({tools:f({call:F.optional()}).optional()}).optional()}),pt=m({experimental:A(d(),F).optional(),sampling:m({context:F.optional(),tools:F.optional()}).optional(),elicitation:ut.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:dt.optional(),extensions:A(d(),F).optional()}),mt=I.extend({protocolVersion:d(),capabilities:pt,clientInfo:H}),ht=L.extend({method:S(`initialize`),params:mt}),gt=m({experimental:A(d(),F).optional(),logging:F.optional(),completions:F.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:ft.optional(),extensions:A(d(),F).optional()}),_t=B.extend({protocolVersion:d(),capabilities:gt,serverInfo:H,instructions:d().optional()}),vt=z.extend({method:S(`notifications/initialized`),params:R.optional()}),yt=L.extend({method:S(`server/discover`),params:I.optional()}),bt=B.extend({supportedVersions:O(d()),capabilities:gt,instructions:d().optional()}),xt=L.extend({method:S(`ping`),params:I.optional()}),St=m({progress:C(),total:p(C()),message:p(d())}),Ct=m({...R.shape,...St.shape,progressToken:We}),wt=z.extend({method:S(`notifications/progress`),params:Ct}),Tt=I.extend({cursor:Ge.optional()}),Et=L.extend({params:Tt.optional()}),Dt=B.extend({nextCursor:Ge.optional()}),Ot=m({uri:d(),mimeType:p(d()),_meta:A(d(),v()).optional()}),kt=Ot.extend({text:d()}),At=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),jt=Ot.extend({blob:At}),Mt=D([`user`,`assistant`]),Nt=m({audience:O(Mt).optional(),priority:C().min(0).max(1).optional(),lastModified:he({offset:!0}).optional()}),Pt=m({...ct.shape,...st.shape,uri:d(),description:p(d()),mimeType:p(d()),size:p(C()),annotations:Nt.optional(),_meta:p(f({}))}),Ft=m({...ct.shape,...st.shape,uriTemplate:d(),description:p(d()),mimeType:p(d()),annotations:Nt.optional(),_meta:p(f({}))}),It=Et.extend({method:S(`resources/list`)}),Lt=Dt.extend({resources:O(Pt)}),U=Et.extend({method:S(`resources/templates/list`)}),W=Dt.extend({resourceTemplates:O(Ft)}),Rt=I.extend({uri:d()}),zt=Rt,Bt=L.extend({method:S(`resources/read`),params:zt}),Vt=B.extend({contents:O(k([kt,jt]))}),Ht=z.extend({method:S(`notifications/resources/list_changed`),params:R.optional()}),Ut=Rt,Wt=L.extend({method:S(`resources/subscribe`),params:Ut}),Gt=Rt,Kt=L.extend({method:S(`resources/unsubscribe`),params:Gt}),qt=m({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:O(d()).optional()}),Jt=I.extend({notifications:qt}),Yt=L.extend({method:S(`subscriptions/listen`),params:Jt}),Xt=R.extend({notifications:qt}),Zt=z.extend({method:S(`notifications/subscriptions/acknowledged`),params:Xt}),Qt=Xe.extend({[Be]:Ze}),$t=B.extend({_meta:Qt}),en=R.extend({uri:d()}),tn=z.extend({method:S(`notifications/resources/updated`),params:en}),G=m({name:d(),description:p(d()),required:p(E())}),nn=m({...ct.shape,...st.shape,description:p(d()),arguments:p(O(G)),_meta:p(f({}))}),rn=Et.extend({method:S(`prompts/list`)}),an=Dt.extend({prompts:O(nn)}),on=I.extend({name:d(),arguments:A(d(),d()).optional()}),sn=L.extend({method:S(`prompts/get`),params:on}),cn=m({type:S(`text`),text:d(),annotations:Nt.optional(),_meta:A(d(),v()).optional()}),K=m({type:S(`image`),data:At,mimeType:d(),annotations:Nt.optional(),_meta:A(d(),v()).optional()}),ln=m({type:S(`audio`),data:At,mimeType:d(),annotations:Nt.optional(),_meta:A(d(),v()).optional()}),un=m({type:S(`tool_use`),name:d(),id:d(),input:A(d(),v()),_meta:A(d(),v()).optional()}),dn=m({type:S(`resource`),resource:k([kt,jt]),annotations:Nt.optional(),_meta:A(d(),v()).optional()}),fn=Pt.extend({type:S(`resource_link`)}),pn=k([cn,K,ln,fn,dn]),mn=m({role:Mt,content:pn}),hn=B.extend({description:d().optional(),messages:O(mn)}),gn=z.extend({method:S(`notifications/prompts/list_changed`),params:R.optional()}),_n=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),vn=m({taskSupport:D([`required`,`optional`,`forbidden`]).optional()}),yn=m({...ct.shape,...st.shape,description:d().optional(),inputSchema:m({type:S(`object`),properties:A(d(),He).optional(),required:O(d()).optional()}).catchall(v()),outputSchema:f({$schema:d().optional()}).optional(),annotations:_n.optional(),execution:vn.optional(),_meta:A(d(),v()).optional()}),bn=Et.extend({method:S(`tools/list`)}),xn=Dt.extend({tools:O(yn)}),Sn=B.extend({content:O(pn).default([]),structuredContent:v().optional(),isError:E().optional()}),Cn=Sn.or(B.extend({toolResult:v()})),wn=Ye.extend({name:d(),arguments:A(d(),v()).optional()}),Tn=L.extend({method:S(`tools/call`),params:wn}),En=z.extend({method:S(`notifications/tools/list_changed`),params:R.optional()}),Dn=m({autoRefresh:E().default(!0),debounceMs:C().int().nonnegative().default(300)}),On=D([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),kn=I.extend({level:On}),An=L.extend({method:S(`logging/setLevel`),params:kn}),jn=R.extend({level:On,logger:d().optional(),data:v()}),Mn=z.extend({method:S(`notifications/message`),params:jn}),Nn=m({name:d().optional()}),Pn=m({hints:O(Nn).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),Fn=m({mode:D([`auto`,`required`,`none`]).optional()}),In=m({type:S(`tool_result`),toolUseId:d().describe(`The unique identifier for the corresponding tool call.`),content:O(pn),structuredContent:v().optional(),isError:E().optional(),_meta:A(d(),v()).optional()}),Ln=ce(`type`,[cn,K,ln]),Rn=ce(`type`,[cn,K,ln,un,In]),zn=m({role:Mt,content:k([Rn,O(Rn)]),_meta:A(d(),v()).optional()}),Bn=Ye.extend({messages:O(zn),modelPreferences:Pn.optional(),systemPrompt:d().optional(),includeContext:D([`none`,`thisServer`,`allServers`]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:O(d()).optional(),metadata:F.optional(),tools:O(yn).optional(),toolChoice:Fn.optional()}),Vn=L.extend({method:S(`sampling/createMessage`),params:Bn}),Hn=B.extend({model:d(),stopReason:p(D([`endTurn`,`stopSequence`,`maxTokens`]).or(d())),role:Mt,content:Ln}),Un=B.extend({model:d(),stopReason:p(D([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(d())),role:Mt,content:k([Rn,O(Rn)])}),Wn=m({type:S(`boolean`),title:d().optional(),description:d().optional(),default:E().optional()}),Gn=m({type:S(`string`),title:d().optional(),description:d().optional(),minLength:C().optional(),maxLength:C().optional(),format:D([`email`,`uri`,`date`,`date-time`]).optional(),default:d().optional()}),Kn=m({type:D([`number`,`integer`]),title:d().optional(),description:d().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),qn=m({type:S(`string`),title:d().optional(),description:d().optional(),enum:O(d()),default:d().optional()}),Jn=m({type:S(`string`),title:d().optional(),description:d().optional(),oneOf:O(m({const:d(),title:d()})),default:d().optional()}),Yn=m({type:S(`string`),title:d().optional(),description:d().optional(),enum:O(d()),enumNames:O(d()).optional(),default:d().optional()}),Xn=k([qn,Jn]),Zn=m({type:S(`array`),title:d().optional(),description:d().optional(),minItems:C().optional(),maxItems:C().optional(),items:m({type:S(`string`),enum:O(d())}),default:O(d()).optional()}),Qn=m({type:S(`array`),title:d().optional(),description:d().optional(),minItems:C().optional(),maxItems:C().optional(),items:m({anyOf:O(m({const:d(),title:d()}))}),default:O(d()).optional()}),$n=k([Zn,Qn]),er=k([Yn,Xn,$n]),tr=k([er,Wn,Gn,Kn]),nr=Ye.extend({mode:S(`form`).optional(),message:d(),requestedSchema:m({type:S(`object`),properties:A(d(),tr),required:O(d()).optional()}).catchall(v())}),rr=Ye.extend({mode:S(`url`),message:d(),elicitationId:d(),url:d().url()}),ir=k([nr,rr]),ar=L.extend({method:S(`elicitation/create`),params:ir}),or=R.extend({elicitationId:d()}),sr=z.extend({method:S(`notifications/elicitation/complete`),params:or}),cr=B.extend({action:D([`accept`,`decline`,`cancel`]),content:b(e=>e===null?void 0:e,A(d(),k([d(),C(),E(),O(d())])).optional())}),lr=m({type:S(`ref/resource`),uri:d()}),ur=m({type:S(`ref/prompt`),name:d()}),dr=I.extend({ref:k([ur,lr]),argument:m({name:d(),value:d()}),context:m({arguments:A(d(),d()).optional()}).optional()}),fr=L.extend({method:S(`completion/complete`),params:dr}),pr=B.extend({completion:f({values:O(d()).max(100),total:p(C().int()),hasMore:p(E())})}),mr=m({uri:d().startsWith(`file://`),name:d().optional(),_meta:A(d(),v()).optional()}),hr=L.extend({method:S(`roots/list`),params:I.optional()}),gr=B.extend({roots:O(mr)}),_r=z.extend({method:S(`notifications/roots/list_changed`),params:R.optional()}),vr=f({ttl:C().optional(),pollInterval:C().optional()}),yr=D([`working`,`input_required`,`completed`,`failed`,`cancelled`]),br=m({taskId:d(),status:yr,ttl:k([C(),oe()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:p(C()),statusMessage:p(d())}),xr=B.extend({task:br}),Sr=R.merge(br),Cr=z.extend({method:S(`notifications/tasks/status`),params:Sr}),wr=L.extend({method:S(`tasks/get`),params:I.extend({taskId:d()})}),Tr=B.merge(br),Er=L.extend({method:S(`tasks/result`),params:I.extend({taskId:d()})}),Dr=B.loose(),Or=Et.extend({method:S(`tasks/list`)}),kr=Dt.extend({tasks:O(br)}),Ar=L.extend({method:S(`tasks/cancel`),params:I.extend({taskId:d()})}),jr=B.merge(br),Mr=k([xt,ht,yt,fr,An,sn,rn,It,U,Bt,Wt,Kt,Yt,Tn,bn]),Nr=k([at,wt,vt,_r]),Pr=k([rt,Hn,Un,cr,gr]),Fr=k([xt,Vn,ar,hr]),Ir=k([at,wt,Mn,tn,Ht,En,gn,Zt,sr]),Lr=k([rt,_t,bt,pr,hn,an,Lt,W,Vt,Sn,xn,$t]),q=y().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:pe.custom,message:`URL must be parseable`,fatal:!0}),fe}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),Rr=f({resource:d().url(),authorization_servers:O(q).optional(),jwks_uri:d().url().optional(),scopes_supported:O(d()).optional(),bearer_methods_supported:O(d()).optional(),resource_signing_alg_values_supported:O(d()).optional(),resource_name:d().optional(),resource_documentation:d().optional(),resource_policy_uri:d().url().optional(),resource_tos_uri:d().url().optional(),tls_client_certificate_bound_access_tokens:E().optional(),authorization_details_types_supported:O(d()).optional(),dpop_signing_alg_values_supported:O(d()).optional(),dpop_bound_access_tokens_required:E().optional()}),zr=f({issuer:d(),authorization_endpoint:q,token_endpoint:q,registration_endpoint:q.optional(),scopes_supported:O(d()).optional(),response_types_supported:O(d()),response_modes_supported:O(d()).optional(),grant_types_supported:O(d()).optional(),token_endpoint_auth_methods_supported:O(d()).optional(),token_endpoint_auth_signing_alg_values_supported:O(d()).optional(),service_documentation:q.optional(),revocation_endpoint:q.optional(),revocation_endpoint_auth_methods_supported:O(d()).optional(),revocation_endpoint_auth_signing_alg_values_supported:O(d()).optional(),introspection_endpoint:d().optional(),introspection_endpoint_auth_methods_supported:O(d()).optional(),introspection_endpoint_auth_signing_alg_values_supported:O(d()).optional(),code_challenge_methods_supported:O(d()).optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0),dpop_signing_alg_values_supported:O(d()).optional()}),Br=f({issuer:d(),authorization_endpoint:q,token_endpoint:q,userinfo_endpoint:q.optional(),jwks_uri:q,registration_endpoint:q.optional(),scopes_supported:O(d()).optional(),response_types_supported:O(d()),response_modes_supported:O(d()).optional(),grant_types_supported:O(d()).optional(),acr_values_supported:O(d()).optional(),subject_types_supported:O(d()),id_token_signing_alg_values_supported:O(d()),id_token_encryption_alg_values_supported:O(d()).optional(),id_token_encryption_enc_values_supported:O(d()).optional(),userinfo_signing_alg_values_supported:O(d()).optional(),userinfo_encryption_alg_values_supported:O(d()).optional(),userinfo_encryption_enc_values_supported:O(d()).optional(),request_object_signing_alg_values_supported:O(d()).optional(),request_object_encryption_alg_values_supported:O(d()).optional(),request_object_encryption_enc_values_supported:O(d()).optional(),token_endpoint_auth_methods_supported:O(d()).optional(),token_endpoint_auth_signing_alg_values_supported:O(d()).optional(),display_values_supported:O(d()).optional(),claim_types_supported:O(d()).optional(),claims_supported:O(d()).optional(),service_documentation:d().optional(),claims_locales_supported:O(d()).optional(),ui_locales_supported:O(d()).optional(),claims_parameter_supported:E().optional(),request_parameter_supported:E().optional(),request_uri_parameter_supported:E().optional(),require_request_uri_registration:E().optional(),op_policy_uri:q.optional(),op_tos_uri:q.optional(),client_id_metadata_document_supported:E().optional(),authorization_response_iss_parameter_supported:E().optional().catch(void 0)}),Vr=m({...Br.shape,...zr.pick({code_challenge_methods_supported:!0}).shape}),Hr=m({access_token:d(),id_token:d().optional(),token_type:d(),expires_in:_e().optional(),scope:d().optional(),refresh_token:d().optional(),issuer:d().optional().catch(void 0)}).strip(),Ur=m({issued_token_type:S(`urn:ietf:params:oauth:token-type:id-jag`),access_token:d(),token_type:d().optional(),expires_in:C().optional(),scope:d().optional()}).strip(),Wr=m({error:d(),error_description:d().optional(),error_uri:d().optional()}),Gr=q.optional().or(S(``).transform(()=>void 0)),Kr=m({redirect_uris:O(q),token_endpoint_auth_method:d().optional(),grant_types:O(d()).optional(),response_types:O(d()).optional(),application_type:d().optional(),client_name:d().optional(),client_uri:q.optional(),logo_uri:Gr,scope:d().optional(),contacts:O(d()).optional(),tos_uri:Gr,policy_uri:d().optional(),jwks_uri:q.optional(),jwks:re().optional(),software_id:d().optional(),software_version:d().optional(),software_statement:d().optional()}).strip(),qr=m({client_id:d(),client_secret:d().optional(),client_id_issued_at:C().optional(),client_secret_expires_at:C().optional(),issuer:d().optional().catch(void 0)}).strip(),Jr=Kr.merge(qr),Yr=m({error:d(),error_description:d().optional()}).strip(),Xr=m({token:d(),token_type_hint:d().optional()}).strip(),Zr=Symbol.for(`mcp.sdk.errorBrands`);function Qr(e,t){let n=new Set,r=t;for(;typeof r==`function`;){let e=r.mcpBrand;Object.prototype.hasOwnProperty.call(r,`mcpBrand`)&&typeof e==`string`&&n.add(e),r=Object.getPrototypeOf(r)}n.size!==0&&Object.defineProperty(e,Zr,{value:n,enumerable:!1,configurable:!0})}function $r(e,t){try{if(typeof t==`object`&&t&&Object.prototype.hasOwnProperty.call(e,`mcpBrand`)&&typeof e.mcpBrand==`string`&&Object.prototype.hasOwnProperty.call(t,Zr)){let n=t[Zr];if(n&&typeof n.has==`function`&&n.has(e.mcpBrand))return!0}}catch{}return Function.prototype[Symbol.hasInstance].call(e,t)}var ei=function(e){return e.InvalidRequest=`invalid_request`,e.InvalidClient=`invalid_client`,e.InvalidGrant=`invalid_grant`,e.UnauthorizedClient=`unauthorized_client`,e.UnsupportedGrantType=`unsupported_grant_type`,e.InvalidScope=`invalid_scope`,e.AccessDenied=`access_denied`,e.ServerError=`server_error`,e.TemporarilyUnavailable=`temporarily_unavailable`,e.UnsupportedResponseType=`unsupported_response_type`,e.UnsupportedTokenType=`unsupported_token_type`,e.InvalidToken=`invalid_token`,e.MethodNotAllowed=`method_not_allowed`,e.TooManyRequests=`too_many_requests`,e.InvalidClientMetadata=`invalid_client_metadata`,e.InvalidRedirectUri=`invalid_redirect_uri`,e.InsufficientScope=`insufficient_scope`,e.InvalidTarget=`invalid_target`,e.InvalidDpopProof=`invalid_dpop_proof`,e.UseDpopNonce=`use_dpop_nonce`,e}({}),ti=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`,Qr(this,new.target)}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},J=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.InvalidResult=`INVALID_RESULT`,e.UnsupportedResultType=`UNSUPPORTED_RESULT_TYPE`,e.InputRequiredRoundsExceeded=`INPUT_REQUIRED_ROUNDS_EXCEEDED`,e.ListPaginationExceeded=`LIST_PAGINATION_EXCEEDED`,e.MethodNotSupportedByProtocolVersion=`METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION`,e.EraNegotiationFailed=`ERA_NEGOTIATION_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({}),Y=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e,t,n,r){super(t,r),this.code=e,this.data=n,this.name=`SdkError`,Qr(this,new.target)}},ni=class extends Y{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SdkHttpError`})}constructor(e,t,n,r){super(e,t,n,r),this.name=`SdkHttpError`}get status(){return this.data.status}get statusText(){return this.data.statusText}};function ri(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function ii(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={...e};return delete t.issuer,t}function ai({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length=oi}function li(e){return e.filter(e=>!ci(e))}function ui(e){return e.filter(e=>ci(e))}function di(e){let t=e.structuredContent;return t===void 0||typeof t==`object`&&t&&!Array.isArray(t)||(e.content?.some(e=>e.type===`text`)??!1)?e:{...e,content:[...e.content??[],{type:`text`,text:JSON.stringify(t)}]}}var fi=[`task`,`inputRequests`,`requestState`];function pi(e){return typeof e!=`object`||!e||Array.isArray(e)||e.content!==void 0||fi.some(t=>t in e)?e:{...e,content:[]}}function mi(){let e=ue(()=>k([d(),C(),E(),oe(),A(d(),e),O(e)])),t=A(d(),e),n=k([d(),C().int()]),r=d(),i=m({ttl:C().optional()}),a=m({taskId:d()}),o=f({progressToken:n.optional(),"io.modelcontextprotocol/related-task":a.optional()}),s=m({_meta:o.optional()}),c=s.extend({task:i.optional()}),l=m({method:d(),params:s.loose().optional()}),u=m({_meta:o.optional()}),h=m({method:d(),params:u.loose().optional()}),g=f({_meta:o.optional()}),_=k([d(),C().int()]),y=g.strict(),ee=u.extend({requestId:_.optional(),reason:d().optional()}),x=h.extend({method:S(`notifications/cancelled`),params:ee}),w=m({src:d(),mimeType:d().optional(),sizes:O(d()).optional(),theme:D([`light`,`dark`]).optional()}),T=m({icons:O(w).optional()}),ne=m({name:d(),title:d().optional()}),re=ne.extend({...ne.shape,...T.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),ie=te(m({applyDefaults:E().optional()}),t),ae=b(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,te(m({form:ie.optional(),url:t.optional()}),t.optional())),se=f({list:t.optional(),cancel:t.optional(),requests:f({sampling:f({createMessage:t.optional()}).optional(),elicitation:f({create:t.optional()}).optional()}).optional()}),le=f({list:t.optional(),cancel:t.optional(),requests:f({tools:f({call:t.optional()}).optional()}).optional()}),de=m({experimental:A(d(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:ae.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:se.optional(),extensions:A(d(),t).optional()}),fe=s.extend({protocolVersion:d(),capabilities:de,clientInfo:re}),pe=l.extend({method:S(`initialize`),params:fe}),me=m({experimental:A(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:le.optional(),extensions:A(d(),t).optional()}),ge=g.extend({protocolVersion:d(),capabilities:me,serverInfo:re,instructions:d().optional()}),_e=h.extend({method:S(`notifications/initialized`),params:u.optional()}),j=l.extend({method:S(`ping`),params:s.optional()}),M=m({progress:C(),total:p(C()),message:p(d())}),ve=m({...u.shape,...M.shape,progressToken:n}),ye=h.extend({method:S(`notifications/progress`),params:ve}),be=s.extend({cursor:r.optional()}),N=l.extend({params:be.optional()}),xe=g.extend({nextCursor:r.optional()}),P=m({uri:d(),mimeType:p(d()),_meta:A(d(),v()).optional()}),Se=P.extend({text:d()}),Ce=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),we=P.extend({blob:Ce}),Te=D([`user`,`assistant`]),Ee=m({audience:O(Te).optional(),priority:C().min(0).max(1).optional(),lastModified:he({offset:!0}).optional()}),De=m({...ne.shape,...T.shape,uri:d(),description:p(d()),mimeType:p(d()),size:p(C()),annotations:Ee.optional(),_meta:p(f({}))}),Oe=m({...ne.shape,...T.shape,uriTemplate:d(),description:p(d()),mimeType:p(d()),annotations:Ee.optional(),_meta:p(f({}))}),ke=N.extend({method:S(`resources/list`)}),Ae=xe.extend({resources:O(De)}),je=N.extend({method:S(`resources/templates/list`)}),Me=xe.extend({resourceTemplates:O(Oe)}),Ne=s.extend({uri:d()}),Pe=Ne,Fe=l.extend({method:S(`resources/read`),params:Pe}),Ie=g.extend({contents:O(k([Se,we]))}),Le=h.extend({method:S(`notifications/resources/list_changed`),params:u.optional()}),Re=Ne,ze=l.extend({method:S(`resources/subscribe`),params:Re}),Be=Ne,Ve=l.extend({method:S(`resources/unsubscribe`),params:Be}),He=u.extend({uri:d()}),F=h.extend({method:S(`notifications/resources/updated`),params:He}),Ue=m({name:d(),description:p(d()),required:p(E())}),We=m({...ne.shape,...T.shape,description:p(d()),arguments:p(O(Ue)),_meta:p(f({}))}),Ge=N.extend({method:S(`prompts/list`)}),Ke=xe.extend({prompts:O(We)}),qe=s.extend({name:d(),arguments:A(d(),d()).optional()}),Je=l.extend({method:S(`prompts/get`),params:qe}),I=m({type:S(`text`),text:d(),annotations:Ee.optional(),_meta:A(d(),v()).optional()}),Ye=m({type:S(`image`),data:Ce,mimeType:d(),annotations:Ee.optional(),_meta:A(d(),v()).optional()}),L=m({type:S(`audio`),data:Ce,mimeType:d(),annotations:Ee.optional(),_meta:A(d(),v()).optional()}),R=m({type:S(`tool_use`),name:d(),id:d(),input:A(d(),v()),_meta:A(d(),v()).optional()}),z=m({type:S(`resource`),resource:k([Se,we]),annotations:Ee.optional(),_meta:A(d(),v()).optional()}),Xe=De.extend({type:S(`resource_link`)}),B=k([I,Ye,L,Xe,z]),Ze=m({role:Te,content:B}),Qe=g.extend({description:d().optional(),messages:O(Ze)}),$e=h.extend({method:S(`notifications/prompts/list_changed`),params:u.optional()}),V=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),et=m({taskSupport:D([`required`,`optional`,`forbidden`]).optional()}),tt=m({...ne.shape,...T.shape,description:d().optional(),inputSchema:m({type:S(`object`),properties:A(d(),e).optional(),required:O(d()).optional()}).catchall(v()),outputSchema:m({type:S(`object`),properties:A(d(),e).optional(),required:O(d()).optional()}).catchall(v()).optional(),annotations:V.optional(),execution:et.optional(),_meta:A(d(),v()).optional()}),nt=N.extend({method:S(`tools/list`)}),rt=xe.extend({tools:O(tt)}),it=g.extend({content:O(B),structuredContent:A(d(),v()).optional(),isError:E().optional()}),at=c.extend({name:d(),arguments:A(d(),v()).optional()}),ot=l.extend({method:S(`tools/call`),params:at}),st=h.extend({method:S(`notifications/tools/list_changed`),params:u.optional()}),ct=D([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),H=s.extend({level:ct}),lt=l.extend({method:S(`logging/setLevel`),params:H}),ut=u.extend({level:ct,logger:d().optional(),data:v()}),dt=h.extend({method:S(`notifications/message`),params:ut}),ft=m({name:d().optional()}),pt=m({hints:O(ft).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),mt=m({mode:D([`auto`,`required`,`none`]).optional()}),ht=m({type:S(`tool_result`),toolUseId:d().describe(`The unique identifier for the corresponding tool call.`),content:O(B),structuredContent:m({}).loose().optional(),isError:E().optional(),_meta:A(d(),v()).optional()}),gt=ce(`type`,[I,Ye,L]),_t=ce(`type`,[I,Ye,L,R,ht]),vt=m({role:Te,content:k([_t,O(_t)]),_meta:A(d(),v()).optional()}),yt=c.extend({messages:O(vt),modelPreferences:pt.optional(),systemPrompt:d().optional(),includeContext:D([`none`,`thisServer`,`allServers`]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:O(d()).optional(),metadata:t.optional(),tools:O(tt).optional(),toolChoice:mt.optional()}),bt=l.extend({method:S(`sampling/createMessage`),params:yt}),xt=g.extend({model:d(),stopReason:p(D([`endTurn`,`stopSequence`,`maxTokens`]).or(d())),role:Te,content:gt}),St=g.extend({model:d(),stopReason:p(D([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(d())),role:Te,content:k([_t,O(_t)])}),Ct=m({type:S(`boolean`),title:d().optional(),description:d().optional(),default:E().optional()}),wt=m({type:S(`string`),title:d().optional(),description:d().optional(),minLength:C().optional(),maxLength:C().optional(),format:D([`email`,`uri`,`date`,`date-time`]).optional(),default:d().optional()}),Tt=m({type:D([`number`,`integer`]),title:d().optional(),description:d().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),Et=m({type:S(`string`),title:d().optional(),description:d().optional(),enum:O(d()),default:d().optional()}),Dt=m({type:S(`string`),title:d().optional(),description:d().optional(),oneOf:O(m({const:d(),title:d()})),default:d().optional()}),Ot=m({type:S(`string`),title:d().optional(),description:d().optional(),enum:O(d()),enumNames:O(d()).optional(),default:d().optional()}),kt=k([Et,Dt]),At=m({type:S(`array`),title:d().optional(),description:d().optional(),minItems:C().optional(),maxItems:C().optional(),items:m({type:S(`string`),enum:O(d())}),default:O(d()).optional()}),jt=m({type:S(`array`),title:d().optional(),description:d().optional(),minItems:C().optional(),maxItems:C().optional(),items:m({anyOf:O(m({const:d(),title:d()}))}),default:O(d()).optional()}),Mt=k([At,jt]),Nt=k([Ot,kt,Mt]),Pt=k([Nt,Ct,wt,Tt]),Ft=c.extend({mode:S(`form`).optional(),message:d(),requestedSchema:m({type:S(`object`),properties:A(d(),Pt),required:O(d()).optional()}).catchall(v())}),It=c.extend({mode:S(`url`),message:d(),elicitationId:d(),url:d().url()}),Lt=k([Ft,It]),U=l.extend({method:S(`elicitation/create`),params:Lt}),W=u.extend({elicitationId:d()}),Rt=h.extend({method:S(`notifications/elicitation/complete`),params:W}),zt=g.extend({action:D([`accept`,`decline`,`cancel`]),content:b(e=>e===null?void 0:e,A(d(),k([d(),C(),E(),O(d())])).optional())}),Bt=m({type:S(`ref/resource`),uri:d()}),Vt=m({type:S(`ref/prompt`),name:d()}),Ht=s.extend({ref:k([Vt,Bt]),argument:m({name:d(),value:d()}),context:m({arguments:A(d(),d()).optional()}).optional()}),Ut=l.extend({method:S(`completion/complete`),params:Ht}),Wt=g.extend({completion:f({values:O(d()).max(100),total:p(C().int()),hasMore:p(E())})}),Gt=m({uri:d().startsWith(`file://`),name:d().optional(),_meta:A(d(),v()).optional()}),Kt=l.extend({method:S(`roots/list`),params:s.optional()}),qt=g.extend({roots:O(Gt)}),Jt=h.extend({method:S(`notifications/roots/list_changed`),params:u.optional()}),Yt=f({ttl:C().optional(),pollInterval:C().optional()}),Xt=D([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Zt=m({taskId:d(),status:Xt,ttl:k([C(),oe()]),createdAt:d(),lastUpdatedAt:d(),pollInterval:p(C()),statusMessage:p(d())}),Qt=g.extend({task:Zt}),$t=u.merge(Zt),en=h.extend({method:S(`notifications/tasks/status`),params:$t}),tn=l.extend({method:S(`tasks/get`),params:s.extend({taskId:d()})}),G=g.merge(Zt),nn=l.extend({method:S(`tasks/result`),params:s.extend({taskId:d()})}),rn=g.loose(),an=N.extend({method:S(`tasks/list`)}),on=xe.extend({tasks:O(Zt)}),sn=l.extend({method:S(`tasks/cancel`),params:s.extend({taskId:d()})});return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,TaskMetadataSchema:i,RelatedTaskMetadataSchema:a,RequestMetaSchema:o,BaseRequestParamsSchema:s,TaskAugmentedRequestParamsSchema:c,RequestSchema:l,NotificationsParamsSchema:u,NotificationSchema:h,ResultSchema:g,RequestIdSchema:_,EmptyResultSchema:y,CancelledNotificationParamsSchema:ee,CancelledNotificationSchema:x,IconSchema:w,IconsSchema:T,BaseMetadataSchema:ne,ImplementationSchema:re,ClientTasksCapabilitySchema:se,ServerTasksCapabilitySchema:le,ClientCapabilitiesSchema:de,InitializeRequestParamsSchema:fe,InitializeRequestSchema:pe,ServerCapabilitiesSchema:me,InitializeResultSchema:ge,InitializedNotificationSchema:_e,PingRequestSchema:j,ProgressSchema:M,ProgressNotificationParamsSchema:ve,ProgressNotificationSchema:ye,PaginatedRequestParamsSchema:be,PaginatedRequestSchema:N,PaginatedResultSchema:xe,ResourceContentsSchema:P,TextResourceContentsSchema:Se,BlobResourceContentsSchema:we,RoleSchema:Te,AnnotationsSchema:Ee,ResourceSchema:De,ResourceTemplateSchema:Oe,ListResourcesRequestSchema:ke,ListResourcesResultSchema:Ae,ListResourceTemplatesRequestSchema:je,ListResourceTemplatesResultSchema:Me,ResourceRequestParamsSchema:Ne,ReadResourceRequestParamsSchema:Pe,ReadResourceRequestSchema:Fe,ReadResourceResultSchema:Ie,ResourceListChangedNotificationSchema:Le,SubscribeRequestParamsSchema:Re,SubscribeRequestSchema:ze,UnsubscribeRequestParamsSchema:Be,UnsubscribeRequestSchema:Ve,ResourceUpdatedNotificationParamsSchema:He,ResourceUpdatedNotificationSchema:F,PromptArgumentSchema:Ue,PromptSchema:We,ListPromptsRequestSchema:Ge,ListPromptsResultSchema:Ke,GetPromptRequestParamsSchema:qe,GetPromptRequestSchema:Je,TextContentSchema:I,ImageContentSchema:Ye,AudioContentSchema:L,ToolUseContentSchema:R,EmbeddedResourceSchema:z,ResourceLinkSchema:Xe,ContentBlockSchema:B,PromptMessageSchema:Ze,GetPromptResultSchema:Qe,PromptListChangedNotificationSchema:$e,ToolAnnotationsSchema:V,ToolExecutionSchema:et,ToolSchema:tt,ListToolsRequestSchema:nt,ListToolsResultSchema:rt,CallToolResultSchema:it,CallToolRequestParamsSchema:at,CallToolRequestSchema:ot,ToolListChangedNotificationSchema:st,LoggingLevelSchema:ct,SetLevelRequestParamsSchema:H,SetLevelRequestSchema:lt,LoggingMessageNotificationParamsSchema:ut,LoggingMessageNotificationSchema:dt,ModelHintSchema:ft,ModelPreferencesSchema:pt,ToolChoiceSchema:mt,ToolResultContentSchema:ht,SamplingContentSchema:gt,SamplingMessageContentBlockSchema:_t,SamplingMessageSchema:vt,CreateMessageRequestParamsSchema:yt,CreateMessageRequestSchema:bt,CreateMessageResultSchema:xt,CreateMessageResultWithToolsSchema:St,BooleanSchemaSchema:Ct,StringSchemaSchema:wt,NumberSchemaSchema:Tt,UntitledSingleSelectEnumSchemaSchema:Et,TitledSingleSelectEnumSchemaSchema:Dt,LegacyTitledEnumSchemaSchema:Ot,SingleSelectEnumSchemaSchema:kt,UntitledMultiSelectEnumSchemaSchema:At,TitledMultiSelectEnumSchemaSchema:jt,MultiSelectEnumSchemaSchema:Mt,EnumSchemaSchema:Nt,PrimitiveSchemaDefinitionSchema:Pt,ElicitRequestFormParamsSchema:Ft,ElicitRequestURLParamsSchema:It,ElicitRequestParamsSchema:Lt,ElicitRequestSchema:U,ElicitationCompleteNotificationParamsSchema:W,ElicitationCompleteNotificationSchema:Rt,ElicitResultSchema:zt,ResourceTemplateReferenceSchema:Bt,PromptReferenceSchema:Vt,CompleteRequestParamsSchema:Ht,CompleteRequestSchema:Ut,CompleteResultSchema:Wt,RootSchema:Gt,ListRootsRequestSchema:Kt,ListRootsResultSchema:qt,RootsListChangedNotificationSchema:Jt,TaskCreationParamsSchema:Yt,TaskStatusSchema:Xt,TaskSchema:Zt,CreateTaskResultSchema:Qt,TaskStatusNotificationParamsSchema:$t,TaskStatusNotificationSchema:en,GetTaskRequestSchema:tn,GetTaskResultSchema:G,GetTaskPayloadRequestSchema:nn,GetTaskPayloadResultSchema:rn,ListTasksRequestSchema:an,ListTasksResultSchema:on,CancelTaskRequestSchema:sn,CancelTaskResultSchema:g.merge(Zt),ClientRequestSchema:k([j,pe,Ut,lt,Je,Ge,ke,je,Fe,ze,Ve,ot,nt,tn,nn,an,sn]),ClientNotificationSchema:k([x,ye,_e,Jt,en]),ClientResultSchema:k([y,xt,St,zt,qt,G,on,Qt]),ServerRequestSchema:k([j,bt,U,Kt,tn,nn,an,sn]),ServerNotificationSchema:k([x,ye,dt,F,Le,st,$e,en,Rt]),ServerResultSchema:k([y,ge,Wt,Qe,Ke,Ae,Me,Ie,it,rt,G,on,Qt]),CallToolResultWireSchema:v().superRefine((e,t)=>{if(typeof e==`object`&&e&&!Array.isArray(e)&&e.content===void 0){for(let n of fi)if(n in e){t.addIssue({code:`custom`,message:`content is required when the body carries '${n}' — another result family cannot default into an empty tools/call success`});return}}}).transform(pi).pipe(it)}}var hi;function gi(){return hi??=mi()}function _i(e){return e.type!==`object`}var vi=new Set([`const`,`enum`,`default`,`examples`]),yi=new Set([`properties`,`patternProperties`,`$defs`,`definitions`,`dependentSchemas`,`dependencies`]);function bi(e){return e!==void 0&&!(typeof e==`string`&&e.startsWith(`#`))}function xi(e){let t=typeof e.$schema==`string`?e.$schema:void 0;if(bi(e.$id))return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:e},required:[`result`]};let n=je(e.$schema)&&e.$recursiveAnchor!==!0,r=(e,t)=>{if(Array.isArray(e))return e.map(e=>r(e,!1));if(typeof e!=`object`||!e||!t&&bi(e.$id))return e;let i={},a=!1;for(let[o,s]of Object.entries(e))t?i[o]=r(s,!1):(o===`$ref`||o===`$dynamicRef`)&&typeof s==`string`?i[o]=s===`#`?`#/properties/result`:s.startsWith(`#/`)?`#/properties/result${s.slice(1)}`:s:o===`$recursiveRef`&&s===`#`&&n?a=!0:i[o]=vi.has(o)?s:yi.has(o)?r(s,!0):r(s,!1);return a&&(`$ref`in i?i.allOf=[...Array.isArray(i.allOf)?i.allOf:[],{$ref:`#/properties/result`}]:i.$ref=`#/properties/result`),i};return{...t!==void 0&&{$schema:t},type:`object`,properties:{result:r(e,!1)},required:[`result`]}}var Si={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"tasks/get":null,"tasks/result":null,"tasks/list":null,"tasks/cancel":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ci={"notifications/cancelled":null,"notifications/progress":null,"notifications/initialized":null,"notifications/roots/list_changed":null,"notifications/tasks/status":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/elicitation/complete":null},wi={ping:null,initialize:null,"completion/complete":null,"logging/setLevel":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"resources/subscribe":null,"resources/unsubscribe":null,"tools/call":null,"tools/list":null,"sampling/createMessage":null,"elicitation/create":null,"roots/list":null},Ti;function Ei(){if(Ti)return Ti;let e=gi();return Ti={requestSchemas:{ping:e.PingRequestSchema,initialize:e.InitializeRequestSchema,"completion/complete":e.CompleteRequestSchema,"logging/setLevel":e.SetLevelRequestSchema,"prompts/get":e.GetPromptRequestSchema,"prompts/list":e.ListPromptsRequestSchema,"resources/list":e.ListResourcesRequestSchema,"resources/templates/list":e.ListResourceTemplatesRequestSchema,"resources/read":e.ReadResourceRequestSchema,"resources/subscribe":e.SubscribeRequestSchema,"resources/unsubscribe":e.UnsubscribeRequestSchema,"tools/call":e.CallToolRequestSchema,"tools/list":e.ListToolsRequestSchema,"tasks/get":e.GetTaskRequestSchema,"tasks/result":e.GetTaskPayloadRequestSchema,"tasks/list":e.ListTasksRequestSchema,"tasks/cancel":e.CancelTaskRequestSchema,"sampling/createMessage":e.CreateMessageRequestSchema,"elicitation/create":e.ElicitRequestSchema,"roots/list":e.ListRootsRequestSchema},notificationSchemas:{"notifications/cancelled":e.CancelledNotificationSchema,"notifications/progress":e.ProgressNotificationSchema,"notifications/initialized":e.InitializedNotificationSchema,"notifications/roots/list_changed":e.RootsListChangedNotificationSchema,"notifications/tasks/status":e.TaskStatusNotificationSchema,"notifications/message":e.LoggingMessageNotificationSchema,"notifications/resources/updated":e.ResourceUpdatedNotificationSchema,"notifications/resources/list_changed":e.ResourceListChangedNotificationSchema,"notifications/tools/list_changed":e.ToolListChangedNotificationSchema,"notifications/prompts/list_changed":e.PromptListChangedNotificationSchema,"notifications/elicitation/complete":e.ElicitationCompleteNotificationSchema},resultSchemas:{ping:e.EmptyResultSchema,initialize:e.InitializeResultSchema,"completion/complete":e.CompleteResultSchema,"logging/setLevel":e.EmptyResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"resources/subscribe":e.EmptyResultSchema,"resources/unsubscribe":e.EmptyResultSchema,"tools/call":e.CallToolResultWireSchema,"tools/list":e.ListToolsResultSchema,"sampling/createMessage":e.CreateMessageResultWithToolsSchema,"elicitation/create":e.ElicitResultSchema,"roots/list":e.ListRootsResultSchema}},Ti}function Di(e){return Object.prototype.hasOwnProperty.call(Si,e)}function Oi(e){return Object.prototype.hasOwnProperty.call(Ci,e)}function ki(e){return Object.prototype.hasOwnProperty.call(wi,e)}function Ai(e){return ki(e)?Ei().resultSchemas[e]:void 0}function ji(e){return Di(e)?Ei().requestSchemas[e]:void 0}function Mi(e){return Oi(e)?Ei().notificationSchemas[e]:void 0}Object.keys(Si),Object.keys(Ci);function Ni(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Pi(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}var Fi={ok:!1,reason:`not-in-era`};function Ii(e){return Ni(e)&&Ni(e.outputSchema)&&_i(e.outputSchema)}function Li(e){return e}var Ri={era:`2025-11-25`,hasRequestMethod:Di,hasNotificationMethod:Oi,validateRequest:(e,t)=>Pi(ji(e),t),validateResult:(e,t)=>Pi(Ai(e),t),validateNotification:(e,t)=>Pi(Mi(e),t),hasInputRequestMethod:()=>!1,validateInputRequest:()=>Fi,validateInputResponse:()=>Fi,samplingResultVariant:((e,t)=>{let n=gi();return Pi(e?n.CreateMessageResultWithToolsSchema:n.CreateMessageResultSchema,t)}),outboundEnvelope:e=>void 0,validateEnvelopeMeta:e=>[],projectCallToolResult(e,t){let n=di(e),r=n.structuredContent;if(r===void 0)return n;let i=typeof r!=`object`||!r||Array.isArray(r),a=t!==void 0&&_i(t);return!i&&!a?n:{...n,structuredContent:{result:r}}},decodeResult(e,t){if(Ni(t)&&`resultType`in t){let e={...t};return delete e.resultType,{kind:`complete`,result:Li(e)}}return{kind:`complete`,result:Li(t)}},encodeResult(e,t){if(e!==`tools/list`)return t;let n=t.tools;return!Array.isArray(n)||!n.some(e=>Ii(e))?t:{...t,tools:n.map(e=>Ii(e)?{...e,outputSchema:xi(e.outputSchema)}:e)}},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope:e=>void 0};function zi(){let e=ue(()=>k([d(),C(),E(),oe(),A(d(),e),O(e)])),t=A(d(),e),n=k([d(),C().int()]),r=d(),i=k([d(),C().int()]),a=D([`user`,`assistant`]),o=D([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),s=d().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),c=m({ttl:C().optional()}),l=m({taskId:d()}),u=f({progressToken:n.optional(),"io.modelcontextprotocol/related-task":l.optional()}),h=m({_meta:u.optional()}),g=h.extend({task:c.optional()}),_=m({_meta:u.optional()}),y=m({method:d(),params:_.loose().optional()}),ee=m({src:d(),mimeType:d().optional(),sizes:O(d()).optional(),theme:D([`light`,`dark`]).optional()}),x=m({icons:O(ee).optional()}),w=m({name:d(),title:d().optional()}),T=w.extend({...w.shape,...x.shape,version:d(),websiteUrl:d().optional(),description:d().optional()}),ne=te(m({applyDefaults:E().optional()}),t),re=b(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,te(m({form:ne.optional(),url:t.optional()}),t.optional())),ie=f({list:t.optional(),cancel:t.optional(),requests:f({sampling:f({createMessage:t.optional()}).optional(),elicitation:f({create:t.optional()}).optional()}).optional()}),ae=f({list:t.optional(),cancel:t.optional(),requests:f({tools:f({call:t.optional()}).optional()}).optional()}),se=m({experimental:A(d(),t).optional(),sampling:m({context:t.optional(),tools:t.optional()}).optional(),elicitation:re.optional(),roots:m({listChanged:E().optional()}).optional(),tasks:ie.optional(),extensions:A(d(),t).optional()}),ce=m({experimental:A(d(),t).optional(),logging:t.optional(),completions:t.optional(),prompts:m({listChanged:E().optional()}).optional(),resources:m({subscribe:E().optional(),listChanged:E().optional()}).optional(),tools:m({listChanged:E().optional()}).optional(),tasks:ae.optional(),extensions:A(d(),t).optional()}),le=m({progress:C(),total:p(C()),message:p(d())}),de=m({..._.shape,...le.shape,progressToken:n}),fe=y.extend({method:S(`notifications/progress`),params:de}),pe=_.extend({level:o,logger:d().optional(),data:v()}),me=y.extend({method:S(`notifications/message`),params:pe}),ge=m({uri:d(),mimeType:p(d()),_meta:A(d(),v()).optional()}),_e=ge.extend({text:d()}),j=ge.extend({blob:s}),M=m({audience:O(a).optional(),priority:C().min(0).max(1).optional(),lastModified:he({offset:!0}).optional()}),ve=m({...w.shape,...x.shape,uri:d(),description:p(d()),mimeType:p(d()),size:p(C()),annotations:M.optional(),_meta:p(f({}))}),ye=m({...w.shape,...x.shape,uriTemplate:d(),description:p(d()),mimeType:p(d()),annotations:M.optional(),_meta:p(f({}))}),be=y.extend({method:S(`notifications/resources/list_changed`),params:_.optional()}),N=_.extend({uri:d()}),xe=y.extend({method:S(`notifications/resources/updated`),params:N}),P=m({name:d(),description:p(d()),required:p(E())}),Se=m({...w.shape,...x.shape,description:p(d()),arguments:p(O(P)),_meta:p(f({}))}),Ce=y.extend({method:S(`notifications/prompts/list_changed`),params:_.optional()}),we=m({type:S(`text`),text:d(),annotations:M.optional(),_meta:A(d(),v()).optional()}),Te=m({type:S(`image`),data:s,mimeType:d(),annotations:M.optional(),_meta:A(d(),v()).optional()}),Ee=m({type:S(`audio`),data:s,mimeType:d(),annotations:M.optional(),_meta:A(d(),v()).optional()}),De=m({type:S(`tool_use`),name:d(),id:d(),input:A(d(),v()),_meta:A(d(),v()).optional()}),Oe=m({type:S(`resource`),resource:k([_e,j]),annotations:M.optional(),_meta:A(d(),v()).optional()}),ke=ve.extend({type:S(`resource_link`)}),Ae=k([we,Te,Ee,ke,Oe]),je=m({role:a,content:Ae}),Me=m({title:d().optional(),readOnlyHint:E().optional(),destructiveHint:E().optional(),idempotentHint:E().optional(),openWorldHint:E().optional()}),Ne=y.extend({method:S(`notifications/tools/list_changed`),params:_.optional()}),Pe=m({name:d().optional()}),Fe=m({hints:O(Pe).optional(),costPriority:C().min(0).max(1).optional(),speedPriority:C().min(0).max(1).optional(),intelligencePriority:C().min(0).max(1).optional()}),Be=m({mode:D([`auto`,`required`,`none`]).optional()}),He=m({type:S(`boolean`),title:d().optional(),description:d().optional(),default:E().optional()}),F=m({type:S(`string`),title:d().optional(),description:d().optional(),minLength:C().optional(),maxLength:C().optional(),format:D([`email`,`uri`,`date`,`date-time`]).optional(),default:d().optional()}),Ue=m({type:D([`number`,`integer`]),title:d().optional(),description:d().optional(),minimum:C().optional(),maximum:C().optional(),default:C().optional()}),We=m({type:S(`string`),title:d().optional(),description:d().optional(),enum:O(d()),default:d().optional()}),Ge=m({type:S(`string`),title:d().optional(),description:d().optional(),oneOf:O(m({const:d(),title:d()})),default:d().optional()}),Ke=m({type:S(`string`),title:d().optional(),description:d().optional(),enum:O(d()),enumNames:O(d()).optional(),default:d().optional()}),qe=k([We,Ge]),Je=m({type:S(`array`),title:d().optional(),description:d().optional(),minItems:C().optional(),maxItems:C().optional(),items:m({type:S(`string`),enum:O(d())}),default:O(d()).optional()}),I=m({type:S(`array`),title:d().optional(),description:d().optional(),minItems:C().optional(),maxItems:C().optional(),items:m({anyOf:O(m({const:d(),title:d()}))}),default:O(d()).optional()}),Ye=k([Je,I]),L=k([Ke,qe,Ye]),R=k([L,He,F,Ue]),z=g.extend({mode:S(`form`).optional(),message:d(),requestedSchema:m({type:S(`object`),properties:A(d(),R),required:O(d()).optional()}).catchall(v())}),Xe=m({type:S(`ref/resource`),uri:d()}),B=m({type:S(`ref/prompt`),name:d()}),Ze=m({uri:d().startsWith(`file://`),name:d().optional(),_meta:A(d(),v()).optional()}),Qe=se.shape,$e=m({experimental:Qe.experimental,sampling:Qe.sampling,elicitation:Qe.elicitation,roots:Qe.roots,extensions:Qe.extensions}),V=ce.shape,et=m({experimental:V.experimental,logging:V.logging,completions:V.completions,prompts:V.prompts,resources:V.resources,tools:V.tools,extensions:V.extensions}),tt=f({progressToken:n.optional(),[Ie]:d(),[Le]:T.optional(),[ze]:$e,[Ve]:o.optional()}),nt=m({...w.shape,...x.shape,description:d().optional(),inputSchema:f({$schema:d().optional(),type:S(`object`)}),outputSchema:f({$schema:d().optional()}).optional(),annotations:Me.optional(),_meta:A(d(),v()).optional()}),rt=m({type:S(`tool_result`),toolUseId:d(),content:O(Ae),structuredContent:v().optional(),isError:E().optional(),_meta:A(d(),v()).optional()}),it=k([we,Te,Ee,De,rt]),at=m({role:a,content:k([it,O(it)]),_meta:A(d(),v()).optional()}),ot=d(),st=f({[Re]:T.optional().catch(void 0)}),ct=st.optional();function H(e){return f({_meta:ct,resultType:ot.default(`complete`),...e})}let lt=H({}),ut=H({nextCursor:r.optional()}),dt=H({content:O(Ae),structuredContent:v().optional(),isError:E().optional()}),ft=H({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`]),tools:O(nt),nextCursor:r.optional()}),pt=H({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`]),prompts:O(Se),nextCursor:r.optional()}),mt=H({description:d().optional(),messages:O(je)}),ht=H({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`]),resources:O(ve),nextCursor:r.optional()}),gt=H({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`]),resourceTemplates:O(ye),nextCursor:r.optional()}),_t=H({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`]),contents:O(k([_e,j]))}),vt=H({completion:m({values:O(d()).max(100),total:C().int().optional(),hasMore:E().optional()}).loose()}),yt=H({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`])}),bt=H({ttlMs:C().int().min(0).catch(0),cacheScope:D([`public`,`private`]).catch(`private`),supportedVersions:O(d()),capabilities:et,instructions:d().optional()}),xt=m({messages:O(at),modelPreferences:Fe.optional(),systemPrompt:d().optional(),includeContext:D([`none`,`thisServer`,`allServers`]).optional(),temperature:C().optional(),maxTokens:C().int(),stopSequences:O(d()).optional(),metadata:t.optional(),tools:O(nt).optional(),toolChoice:Be.optional()}),St=m({method:S(`sampling/createMessage`),params:xt}),Ct=m({method:S(`roots/list`),params:m({_meta:A(d(),v()).optional()}).optional()}),wt=m({...at.shape,model:d(),stopReason:d().optional()}),Tt=m({roots:O(Ze)}),Et=m({action:D([`accept`,`decline`,`cancel`]),content:A(d(),k([d(),C(),E(),O(d())])).optional()}),Dt=m({mode:S(`url`),message:d(),url:d().url()}),Ot=k([z,Dt]),kt=m({method:S(`elicitation/create`),params:Ot}),At=k([St,Ct,kt]),jt=k([wt,Tt,Et]),Mt=A(d(),At),Nt=A(d(),jt),Pt=H({inputRequests:Mt.optional(),requestState:d().optional()}),Ft={inputResponses:Nt.optional(),requestState:d().optional()},It=m({_meta:tt,...Ft}),Lt=f({progressToken:n.optional()});function U(e,t){return m({method:S(e),params:m({_meta:tt,...t})})}function W(e,t){return m({method:S(e),params:m({_meta:Lt.optional(),...t}).optional()})}let Rt={name:d(),arguments:A(d(),v()).optional(),...Ft},zt={cursor:r.optional()},Bt=U(`tools/call`,Rt),Vt=U(`tools/list`,zt),Ht=U(`prompts/list`,zt),Ut=U(`prompts/get`,{name:d(),arguments:A(d(),d()).optional(),...Ft}),Wt=U(`resources/list`,zt),Gt=U(`resources/templates/list`,zt),Kt=U(`resources/read`,{uri:d(),...Ft}),qt={ref:k([B,Xe]),argument:m({name:d(),value:d()}),context:m({arguments:A(d(),d()).optional()}).optional()},Jt=U(`completion/complete`,qt),Yt=U(`server/discover`,{}),Xt=m({toolsListChanged:E().optional(),promptsListChanged:E().optional(),resourcesListChanged:E().optional(),resourceSubscriptions:O(d()).optional()}),Zt={notifications:Xt},Qt=U(`subscriptions/listen`,Zt),$t=st.extend({"io.modelcontextprotocol/subscriptionId":i}),en=f({_meta:$t,resultType:ot.default(`complete`)}),tn={"tools/call":W(`tools/call`,Rt),"tools/list":W(`tools/list`,zt),"prompts/get":W(`prompts/get`,{name:d(),arguments:A(d(),d()).optional()}),"prompts/list":W(`prompts/list`,zt),"resources/list":W(`resources/list`,zt),"resources/templates/list":W(`resources/templates/list`,zt),"resources/read":W(`resources/read`,{uri:d()}),"completion/complete":W(`completion/complete`,qt),"server/discover":W(`server/discover`,{}),"subscriptions/listen":W(`subscriptions/listen`,Zt)};function G(e){return f({_meta:ct,...e})}let nn={"tools/call":G({content:O(Ae),structuredContent:v().optional(),isError:E().optional()}),"tools/list":G({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`]),tools:O(nt),nextCursor:r.optional()}),"prompts/get":G({description:d().optional(),messages:O(je)}),"prompts/list":G({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`]),prompts:O(Se),nextCursor:r.optional()}),"resources/list":G({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`]),resources:O(ve),nextCursor:r.optional()}),"resources/templates/list":G({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`]),resourceTemplates:O(ye),nextCursor:r.optional()}),"resources/read":G({ttlMs:C().int().min(0),cacheScope:D([`public`,`private`]),contents:O(k([_e,j]))}),"completion/complete":G({completion:m({values:O(d()).max(100),total:C().int().optional(),hasMore:E().optional()}).loose()}),"server/discover":G({ttlMs:C().int().min(0).catch(0),cacheScope:D([`public`,`private`]).catch(`private`),supportedVersions:O(d()),capabilities:et,instructions:d().optional()}),"subscriptions/listen":G({})},rn=f({"io.modelcontextprotocol/subscriptionId":i.optional()}),an=m({method:S(`notifications/subscriptions/acknowledged`),params:m({_meta:rn.optional(),notifications:Xt})}),on=m({_meta:rn.optional(),requestId:i,reason:d().optional()}),sn=m({method:S(`notifications/cancelled`),params:on}),cn={"notifications/cancelled":sn,"notifications/progress":fe,"notifications/message":me,"notifications/resources/updated":xe,"notifications/resources/list_changed":be,"notifications/tools/list_changed":Ne,"notifications/prompts/list_changed":Ce,"notifications/subscriptions/acknowledged":an},K=e=>m({jsonrpc:S(`2.0`),id:k([d(),C().int()]),result:e}).strict();return{JSONValueSchema:e,JSONObjectSchema:t,ProgressTokenSchema:n,CursorSchema:r,RequestIdSchema:i,RoleSchema:a,LoggingLevelSchema:o,TaskMetadataSchema:c,RelatedTaskMetadataSchema:l,RequestMetaSchema:u,BaseRequestParamsSchema:h,TaskAugmentedRequestParamsSchema:g,NotificationsParamsSchema:_,NotificationSchema:y,IconSchema:ee,IconsSchema:x,BaseMetadataSchema:w,ImplementationSchema:T,ClientTasksCapabilitySchema:ie,ServerTasksCapabilitySchema:ae,ClientCapabilitiesSchema:se,ServerCapabilitiesSchema:ce,ProgressSchema:le,ProgressNotificationParamsSchema:de,ProgressNotificationSchema:fe,LoggingMessageNotificationParamsSchema:pe,LoggingMessageNotificationSchema:me,ResourceContentsSchema:ge,TextResourceContentsSchema:_e,BlobResourceContentsSchema:j,AnnotationsSchema:M,ResourceSchema:ve,ResourceTemplateSchema:ye,ResourceListChangedNotificationSchema:be,ResourceUpdatedNotificationParamsSchema:N,ResourceUpdatedNotificationSchema:xe,PromptArgumentSchema:P,PromptSchema:Se,PromptListChangedNotificationSchema:Ce,TextContentSchema:we,ImageContentSchema:Te,AudioContentSchema:Ee,ToolUseContentSchema:De,EmbeddedResourceSchema:Oe,ResourceLinkSchema:ke,ContentBlockSchema:Ae,PromptMessageSchema:je,ToolAnnotationsSchema:Me,ToolListChangedNotificationSchema:Ne,ModelHintSchema:Pe,ModelPreferencesSchema:Fe,ToolChoiceSchema:Be,BooleanSchemaSchema:He,StringSchemaSchema:F,NumberSchemaSchema:Ue,UntitledSingleSelectEnumSchemaSchema:We,TitledSingleSelectEnumSchemaSchema:Ge,LegacyTitledEnumSchemaSchema:Ke,SingleSelectEnumSchemaSchema:qe,UntitledMultiSelectEnumSchemaSchema:Je,TitledMultiSelectEnumSchemaSchema:I,MultiSelectEnumSchemaSchema:Ye,EnumSchemaSchema:L,PrimitiveSchemaDefinitionSchema:R,ElicitRequestFormParamsSchema:z,ResourceTemplateReferenceSchema:Xe,PromptReferenceSchema:B,RootSchema:Ze,ClientCapabilities2026Schema:$e,ServerCapabilities2026Schema:et,RequestMetaEnvelopeSchema:tt,ToolSchema:nt,ToolResultContentSchema:rt,SamplingMessageContentBlockSchema:it,SamplingMessageSchema:at,ResultTypeSchema:ot,ResultMetaSchema:st,ResultSchema:lt,PaginatedResultSchema:ut,CallToolResultSchema:dt,ListToolsResultSchema:ft,ListPromptsResultSchema:pt,GetPromptResultSchema:mt,ListResourcesResultSchema:ht,ListResourceTemplatesResultSchema:gt,ReadResourceResultSchema:_t,CompleteResultSchema:vt,CacheableResultSchema:yt,DiscoverResultSchema:bt,CreateMessageRequestParamsSchema:xt,CreateMessageRequestSchema:St,ListRootsRequestSchema:Ct,CreateMessageResultSchema:wt,ListRootsResultSchema:Tt,ElicitResultSchema:Et,ElicitRequestURLParamsSchema:Dt,ElicitRequestParamsSchema:Ot,ElicitRequestSchema:kt,InputRequestSchema:At,InputResponseSchema:jt,InputRequestsSchema:Mt,InputResponsesSchema:Nt,InputRequiredResultSchema:Pt,InputResponseRequestParamsSchema:It,CallToolRequestSchema:Bt,ListToolsRequestSchema:Vt,ListPromptsRequestSchema:Ht,GetPromptRequestSchema:Ut,ListResourcesRequestSchema:Wt,ListResourceTemplatesRequestSchema:Gt,ReadResourceRequestSchema:Kt,CompleteRequestSchema:Jt,DiscoverRequestSchema:Yt,SubscriptionFilterSchema:Xt,SubscriptionsListenRequestSchema:Qt,SubscriptionsListenResultMetaSchema:$t,SubscriptionsListenResultSchema:en,dispatchRequestSchemas:tn,dispatchResultSchemas:nn,NotificationMetaSchema:rn,SubscriptionsAcknowledgedNotificationSchema:an,CancelledNotificationParamsSchema:on,CancelledNotificationSchema:sn,notificationSchemas2026:cn,JSONRPCResultResponseSchema:K(lt),CallToolResultResponseSchema:K(k([dt,Pt])),ListToolsResultResponseSchema:K(ft),ListPromptsResultResponseSchema:K(pt),GetPromptResultResponseSchema:K(k([mt,Pt])),ListResourcesResultResponseSchema:K(ht),ListResourceTemplatesResultResponseSchema:K(gt),ReadResourceResultResponseSchema:K(k([_t,Pt])),CompleteResultResponseSchema:K(vt),DiscoverResultResponseSchema:K(bt),SubscriptionsListenResultResponseSchema:K(en)}}var Bi;function Vi(){return Bi??=zi()}var Hi=[`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`resources/read`,`server/discover`];function Ui(e){return Hi.includes(e)}var Wi=Symbol(`modelcontextprotocol.resultCacheHintFallback`);function Gi(e){return e[Wi]}function Ki(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function qi(e){return e===`public`||e===`private`}var X=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.MissingRequiredClientCapability=-32021]=`MissingRequiredClientCapability`,e[e.UnsupportedProtocolVersion=-32022]=`UnsupportedProtocolVersion`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({}),Z=class e extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ProtocolError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`,Qr(this,new.target)}static fromError(t,n,r){if(t===X.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Yi(e.elicitations,n)}if(t===X.UnsupportedProtocolVersion&&r){let e=r;if(Array.isArray(e.supported)&&typeof e.requested==`string`)return new Xi({supported:e.supported,requested:e.requested},n)}if(t===X.InvalidParams||t===X.ResourceNotFound){let e=r;if(typeof e?.uri==`string`&&(t===X.ResourceNotFound||Object.keys(e).length===1))return new Ji(e.uri,n)}if(t===X.MissingRequiredClientCapability&&r){let e=r;if(e.requiredCapabilities!==null&&typeof e.requiredCapabilities==`object`&&!Array.isArray(e.requiredCapabilities))return new Zi({requiredCapabilities:e.requiredCapabilities},n)}return new e(t,n,r)}},Ji=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.ResourceNotFoundError`})}constructor(e,t=`Resource not found: ${e}`){super(X.InvalidParams,t,{uri:e})}get uri(){return this.data.uri}},Yi=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UrlElicitationRequiredError`})}constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(X.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Xi=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnsupportedProtocolVersionError`})}constructor(e,t=`Unsupported protocol version: ${e.requested}`){super(X.UnsupportedProtocolVersion,t,e)}get supported(){return this.data.supported}get requested(){return this.data.requested}},Zi=class extends Z{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.MissingRequiredClientCapabilityError`})}constructor(e,t=`Missing required client capabilities: ${Object.keys(e.requiredCapabilities).join(`, `)}`){super(X.MissingRequiredClientCapability,t,e)}get requiredCapabilities(){return this.data.requiredCapabilities}},Qi=0,$i=`private`,ea=[`tools/call`,`prompts/get`,`resources/read`];function ta(e,t){let n=t.resultType;if(n===void 0)return{...t,resultType:`complete`};if(n===`complete`||ea.includes(e))return t;throw new Z(X.InternalError,`Handler for ${e} returned resultType '${String(n)}', but results of ${e} only support 'complete' on protocol revision 2026-07-28`)}function na(e,t){let n=Gi(t);if(t.resultType!==`complete`||!Ui(e))return n===void 0?t:sa(t);let r=t,i=Ki(r.ttlMs)?r.ttlMs:aa(n),a=qi(r.cacheScope)?r.cacheScope:oa(n),o={...r,ttlMs:i,cacheScope:a};return delete o[Wi],o}function ra(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ia(e,t){if(t===void 0)return e;let n=e._meta;return n===void 0?{...e,_meta:{[Re]:t}}:!ra(n)||n[`io.modelcontextprotocol/serverInfo`]!==void 0?e:{...e,_meta:{...n,[Re]:t}}}function aa(e){return e!==void 0&&Ki(e.ttlMs)?e.ttlMs:Qi}function oa(e){return e!==void 0&&qi(e.cacheScope)?e.cacheScope:$i}function sa(e){let t={...e};return delete t[Wi],t}var ca=[`elicitation/create`,`sampling/createMessage`,`roots/list`],la;function ua(){if(la)return la;let e=Vi();return la={request:{"elicitation/create":m({method:S(`elicitation/create`),params:e.ElicitRequestParamsSchema}),"sampling/createMessage":m({method:S(`sampling/createMessage`),params:e.CreateMessageRequestParamsSchema}),"roots/list":m({method:S(`roots/list`),params:f({}).optional()})},response:{"elicitation/create":e.ElicitResultSchema,"sampling/createMessage":e.CreateMessageResultSchema,"roots/list":e.ListRootsResultSchema}},la}function da(e){return ca.includes(e)}function fa(e){return da(e)?ua().request[e]:void 0}function pa(e){return da(e)?ua().response[e]:void 0}var ma={"tools/call":null,"tools/list":null,"prompts/get":null,"prompts/list":null,"resources/list":null,"resources/templates/list":null,"resources/read":null,"completion/complete":null,"server/discover":null,"subscriptions/listen":null},ha={"notifications/cancelled":null,"notifications/progress":null,"notifications/message":null,"notifications/resources/updated":null,"notifications/resources/list_changed":null,"notifications/tools/list_changed":null,"notifications/prompts/list_changed":null,"notifications/subscriptions/acknowledged":null};function ga(e){return Object.prototype.hasOwnProperty.call(ma,e)}function _a(e){return Object.prototype.hasOwnProperty.call(ha,e)}function va(e){return Object.prototype.hasOwnProperty.call(ma,e)}function ya(e){return ga(e)?Vi().dispatchRequestSchemas[e]:void 0}function ba(e){return va(e)?Vi().dispatchResultSchemas[e]:void 0}function xa(e){return _a(e)?Vi().notificationSchemas2026[e]:void 0}Object.keys(ma),Object.keys(ha);function Sa(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ca(e,t){if(e===void 0)return{ok:!1,reason:`not-in-era`};let n=e.safeParse(t);return n.success?{ok:!0,value:n.data}:{ok:!1,reason:`invalid`,message:String(n.error)}}var wa={ok:!1,reason:`not-in-era`},Ta=[Ie,ze];function Ea(e,t){let n=t,r=!1,i=()=>(r||=(n={...n},!0),n),a=t.tools;e===`tools/list`&&Array.isArray(a)&&a.some(e=>Sa(e)&&`execution`in e)&&(i().tools=a.map(e=>{if(!Sa(e)||!(`execution`in e))return e;let t={...e};return delete t.execution,t}));let o=t.capabilities;if(Sa(o)&&`tasks`in o){let e={...o};delete e.tasks,i().capabilities=e}return n}var Da={era:`2026-07-28`,hasRequestMethod:ga,hasNotificationMethod:_a,hasInputRequestMethod:e=>fa(e)!==void 0,validateRequest:(e,t)=>Ca(ya(e),t),validateResult:(e,t)=>Ca(ba(e),t),validateNotification:(e,t)=>Ca(xa(e),t),validateInputRequest:(e,t)=>Ca(fa(e),t),validateInputResponse:(e,t)=>Ca(pa(e),t),samplingResultVariant:()=>wa,outboundEnvelope(e){return{[Ie]:e.protocolVersion,[Le]:e.clientInfo,[ze]:e.clientCapabilities,...e.logLevel!==void 0&&{"io.modelcontextprotocol/logLevel":e.logLevel}}},validateEnvelopeMeta(e){let t=[];for(let n of Ta)n in e||t.push({key:n,problem:`missing`});let n=Vi().RequestMetaEnvelopeSchema.safeParse(e);if(!n.success)for(let e of n.error.issues){let n=e.path.map(String),r=n.length>0?n.join(`.`):`_meta`;n.length===1&&t.some(e=>e.key===r&&e.problem===`missing`)||t.push({key:r,problem:e.message})}return t},projectCallToolResult:e=>di(e),inputRequestSchema:fa,decodeResult(e,t){if(!Sa(t))return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: not an object`,{method:e})};let n=t.resultType;if(n===void 0)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`,{method:e,violation:`missing-resultType`})};if(typeof n!=`string`)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: non-string resultType`,{method:e,resultType:n})};if(n===`input_required`){let n=t.inputRequests,r=Sa(n)?n:{},i=t.requestState,a=t._meta===void 0?void 0:Vi().ResultMetaSchema.safeParse(t._meta),o=a?.success?a.data:void 0;return Object.keys(r).length===0&&typeof i!=`string`?{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`,{method:e,violation:`input-required-missing-both`})}:{kind:`input_required`,inputRequests:r,...typeof i==`string`&&{requestState:i},...o!==void 0&&{_meta:o}}}if(n!==`complete`)return{kind:`invalid`,error:new Y(J.UnsupportedResultType,`Unsupported result type '${n}' for ${e}`,{resultType:n,method:e})};let r=ka(),i=Object.hasOwn(r,e)?r[e]:void 0;if(i!==void 0){let n=i.safeParse(t);if(!n.success)return{kind:`invalid`,error:new Y(J.InvalidResult,`Invalid result for ${e}: ${n.error}`,{method:e})}}let a={...t};return delete a.resultType,{kind:`complete`,result:a}},encodeResult(e,t,n){return ia(na(e,ta(e,Ea(e,t))),n)},encodeErrorCode:e=>e===-32002?-32602:e,checkInboundEnvelope(e){if(e.envelope===void 0)return`Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)`;let t=Vi().RequestMetaEnvelopeSchema.safeParse(e.envelope);if(!t.success)return`Invalid _meta envelope for protocol revision 2026-07-28: ${t.error.issues.map(e=>e.message).join(`; `)}`}},Oa;function ka(){if(Oa)return Oa;let e=Vi();return Oa={"tools/call":e.CallToolResultSchema,"tools/list":e.ListToolsResultSchema,"prompts/get":e.GetPromptResultSchema,"prompts/list":e.ListPromptsResultSchema,"resources/list":e.ListResourcesResultSchema,"resources/templates/list":e.ListResourceTemplatesResultSchema,"resources/read":e.ReadResourceResultSchema,"completion/complete":e.CompleteResultSchema,"server/discover":e.DiscoverResultSchema},Oa}var Aa=`2026-07-28`;function ja(e){return e!==void 0&&ci(e)?Da:Ri}function Ma(e){return e.revision===void 0?e.era===`modern`?Da.era:Ri.era:ja(e.revision).era}function Na(e){return Ia.some(t=>t.hasRequestMethod(e))}function Pa(e){return Ia.some(t=>t.hasNotificationMethod(e))}function Fa(e){return e===`tasks/get`||e===`tasks/cancel`}var Ia=[Ri,Da],La=we({AnnotationsSchema:()=>Nt,AudioContentSchema:()=>ln,BaseMetadataSchema:()=>ct,BaseRequestParamsSchema:()=>I,BlobResourceContentsSchema:()=>jt,BooleanSchemaSchema:()=>Wn,CallToolRequestParamsSchema:()=>wn,CallToolRequestSchema:()=>Tn,CallToolResultSchema:()=>Sn,CancelTaskRequestSchema:()=>Ar,CancelTaskResultSchema:()=>jr,CancelledNotificationParamsSchema:()=>it,CancelledNotificationSchema:()=>at,ClientCapabilitiesSchema:()=>pt,ClientNotificationSchema:()=>Nr,ClientRequestSchema:()=>Mr,ClientResultSchema:()=>Pr,ClientTasksCapabilitySchema:()=>dt,CompatibilityCallToolResultSchema:()=>Cn,CompleteRequestParamsSchema:()=>dr,CompleteRequestSchema:()=>fr,CompleteResultSchema:()=>pr,ContentBlockSchema:()=>pn,CreateMessageRequestParamsSchema:()=>Bn,CreateMessageRequestSchema:()=>Vn,CreateMessageResultSchema:()=>Hn,CreateMessageResultWithToolsSchema:()=>Un,CreateTaskResultSchema:()=>xr,CursorSchema:()=>Ge,DiscoverRequestSchema:()=>yt,DiscoverResultSchema:()=>bt,ElicitRequestFormParamsSchema:()=>nr,ElicitRequestParamsSchema:()=>ir,ElicitRequestSchema:()=>ar,ElicitRequestURLParamsSchema:()=>rr,ElicitResultSchema:()=>cr,ElicitationCompleteNotificationParamsSchema:()=>or,ElicitationCompleteNotificationSchema:()=>sr,EmbeddedResourceSchema:()=>dn,EmptyResultSchema:()=>rt,EnumSchemaSchema:()=>er,GetPromptRequestParamsSchema:()=>on,GetPromptRequestSchema:()=>sn,GetPromptResultSchema:()=>hn,GetTaskPayloadRequestSchema:()=>Er,GetTaskPayloadResultSchema:()=>Dr,GetTaskRequestSchema:()=>wr,GetTaskResultSchema:()=>Tr,IconSchema:()=>ot,IconsSchema:()=>st,ImageContentSchema:()=>K,ImplementationSchema:()=>H,InitializeRequestParamsSchema:()=>mt,InitializeRequestSchema:()=>ht,InitializeResultSchema:()=>_t,InitializedNotificationSchema:()=>vt,JSONArraySchema:()=>Ue,JSONObjectSchema:()=>F,JSONRPCErrorResponseSchema:()=>et,JSONRPCMessageSchema:()=>tt,JSONRPCNotificationSchema:()=>$e,JSONRPCRequestSchema:()=>Qe,JSONRPCResponseSchema:()=>nt,JSONRPCResultResponseSchema:()=>V,JSONValueSchema:()=>He,LegacyTitledEnumSchemaSchema:()=>Yn,ListChangedOptionsBaseSchema:()=>Dn,ListPromptsRequestSchema:()=>rn,ListPromptsResultSchema:()=>an,ListResourceTemplatesRequestSchema:()=>U,ListResourceTemplatesResultSchema:()=>W,ListResourcesRequestSchema:()=>It,ListResourcesResultSchema:()=>Lt,ListRootsRequestSchema:()=>hr,ListRootsResultSchema:()=>gr,ListTasksRequestSchema:()=>Or,ListTasksResultSchema:()=>kr,ListToolsRequestSchema:()=>bn,ListToolsResultSchema:()=>xn,LoggingLevelSchema:()=>On,LoggingMessageNotificationParamsSchema:()=>jn,LoggingMessageNotificationSchema:()=>Mn,ModelHintSchema:()=>Nn,ModelPreferencesSchema:()=>Pn,MultiSelectEnumSchemaSchema:()=>$n,NotificationSchema:()=>z,NotificationsParamsSchema:()=>R,NumberSchemaSchema:()=>Kn,PaginatedRequestParamsSchema:()=>Tt,PaginatedRequestSchema:()=>Et,PaginatedResultSchema:()=>Dt,PingRequestSchema:()=>xt,PrimitiveSchemaDefinitionSchema:()=>tr,ProgressNotificationParamsSchema:()=>Ct,ProgressNotificationSchema:()=>wt,ProgressSchema:()=>St,ProgressTokenSchema:()=>We,PromptArgumentSchema:()=>G,PromptListChangedNotificationSchema:()=>gn,PromptMessageSchema:()=>mn,PromptReferenceSchema:()=>ur,PromptSchema:()=>nn,ReadResourceRequestParamsSchema:()=>zt,ReadResourceRequestSchema:()=>Bt,ReadResourceResultSchema:()=>Vt,RelatedTaskMetadataSchema:()=>qe,RequestIdSchema:()=>Ze,RequestMetaSchema:()=>Je,RequestSchema:()=>L,ResourceContentsSchema:()=>Ot,ResourceLinkSchema:()=>fn,ResourceListChangedNotificationSchema:()=>Ht,ResourceRequestParamsSchema:()=>Rt,ResourceSchema:()=>Pt,ResourceTemplateReferenceSchema:()=>lr,ResourceTemplateSchema:()=>Ft,ResourceUpdatedNotificationParamsSchema:()=>en,ResourceUpdatedNotificationSchema:()=>tn,ResultMetaObjectSchema:()=>Xe,ResultSchema:()=>B,RoleSchema:()=>Mt,RootSchema:()=>mr,RootsListChangedNotificationSchema:()=>_r,SamplingContentSchema:()=>Ln,SamplingMessageContentBlockSchema:()=>Rn,SamplingMessageSchema:()=>zn,ServerCapabilitiesSchema:()=>gt,ServerNotificationSchema:()=>Ir,ServerRequestSchema:()=>Fr,ServerResultSchema:()=>Lr,ServerTasksCapabilitySchema:()=>ft,SetLevelRequestParamsSchema:()=>kn,SetLevelRequestSchema:()=>An,SingleSelectEnumSchemaSchema:()=>Xn,StringSchemaSchema:()=>Gn,SubscribeRequestParamsSchema:()=>Ut,SubscribeRequestSchema:()=>Wt,SubscriptionFilterSchema:()=>qt,SubscriptionsAcknowledgedNotificationParamsSchema:()=>Xt,SubscriptionsAcknowledgedNotificationSchema:()=>Zt,SubscriptionsListenRequestParamsSchema:()=>Jt,SubscriptionsListenRequestSchema:()=>Yt,SubscriptionsListenResultMetaSchema:()=>Qt,SubscriptionsListenResultSchema:()=>$t,TaskAugmentedRequestParamsSchema:()=>Ye,TaskCreationParamsSchema:()=>vr,TaskMetadataSchema:()=>Ke,TaskSchema:()=>br,TaskStatusNotificationParamsSchema:()=>Sr,TaskStatusNotificationSchema:()=>Cr,TaskStatusSchema:()=>yr,TextContentSchema:()=>cn,TextResourceContentsSchema:()=>kt,TitledMultiSelectEnumSchemaSchema:()=>Qn,TitledSingleSelectEnumSchemaSchema:()=>Jn,ToolAnnotationsSchema:()=>_n,ToolChoiceSchema:()=>Fn,ToolExecutionSchema:()=>vn,ToolListChangedNotificationSchema:()=>En,ToolResultContentSchema:()=>In,ToolSchema:()=>yn,ToolUseContentSchema:()=>un,UnsubscribeRequestParamsSchema:()=>Gt,UnsubscribeRequestSchema:()=>Kt,UntitledMultiSelectEnumSchemaSchema:()=>Zn,UntitledSingleSelectEnumSchemaSchema:()=>qn}),Ra=e=>Qe.safeParse(e).success,za=e=>$e.safeParse(e).success,Ba=e=>V.safeParse(e).success,Va=e=>et.safeParse(e).success,Ha=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&e.resultType===`input_required`,Ua=e=>ht.safeParse(e).success,Wa=e=>vt.safeParse(e).success,Ga=`Mcp-Param-`,Ka=`x-mcp-header`,qa=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,Ja=new Set([`string`,`integer`,`boolean`,`number`]);function Ya(e){let t=[],n=new Map,r=(e,i,a)=>{if(typeof e!=`object`||!e)return;let o=e;if(Ka in o){if(!a||i.length===0)return`${Qa(i)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;let e=o[Ka];if(typeof e!=`string`||e.length===0)return`${Qa(i)}: x-mcp-header MUST be a non-empty string`;if(!qa.test(e))return`${Qa(i)}: x-mcp-header '${e}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;let r=typeof o.type==`string`?o.type:void 0;if(r===void 0||!Ja.has(r))return`${Qa(i)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${r??``}`;let s=e.toLowerCase(),c=n.get(s);if(c!==void 0)return`x-mcp-header '${e}' is not case-insensitively unique (also declared as '${c}')`;n.set(s,e),t.push({path:i,headerName:e,type:r})}let s=o.properties;if(typeof s==`object`&&s)for(let[e,t]of Object.entries(s)){let n=r(t,[...i,e],a);if(n!==void 0)return n}for(let e of Xa){let t=o[e];if(t===void 0)continue;let n=Array.isArray(t)?t:typeof t==`object`&&t&&Za.has(e)?Object.values(t):[t];for(let t of n){let n=r(t,[...i,`<${e}>`],!1);if(n!==void 0)return n}}},i=r(e,[],!0);return i===void 0?{valid:!0,declarations:t}:{valid:!1,reason:i}}var Xa=[`items`,`prefixItems`,`contains`,`additionalProperties`,`unevaluatedProperties`,`unevaluatedItems`,`propertyNames`,`patternProperties`,`dependentSchemas`,`oneOf`,`anyOf`,`allOf`,`not`,`if`,`then`,`else`,`$defs`,`definitions`],Za=new Set([`patternProperties`,`dependentSchemas`,`$defs`,`definitions`]);function Qa(e){return e.length===0?``:e.join(`.`)}var $a=`=?base64?`,eo=`?=`;function to(e){if(typeof e==`string`)return e;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return!Number.isFinite(e)||Number.isInteger(e)&&!Number.isSafeInteger(e)?void 0:String(e)}function no(e){if(e.length===0||e.startsWith($a)&&e.endsWith(eo)||e!==e.trim())return!0;for(let t=0;t=32&&n<=126))return!0}return!1}function ro(e){let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCodePoint(e);return btoa(n)}function io(e){return no(e)?`${$a}${ro(e)}${eo}`:e}function ao(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}function oo(e,t){let n={};for(let r of e){let e=ao(t,r.path);if(e==null)continue;let i=to(e);i!==void 0&&(n[`${Ga}${r.headerName}`]=io(i))}return n}X.InvalidRequest,X.UnsupportedProtocolVersion,X.InvalidParams,X.MethodNotFound,X.InvalidParams,X.MissingRequiredClientCapability,X.ParseError,X.InvalidRequest,X.MethodNotFound,X.UnsupportedProtocolVersion,X.MissingRequiredClientCapability;var so={"tools/call":`name`,"prompts/get":`name`,"resources/read":`uri`,"tasks/get":`taskId`,"tasks/update":`taskId`,"tasks/cancel":`taskId`};function co(e,t){let n=Object.hasOwn(so,e)?so[e]:void 0;if(n===void 0)return;let r=lo(t)?t[n]:void 0;return{field:n,value:typeof r==`string`?r:void 0}}function lo(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function uo(e,t){return ee(e,t)}function fo(e){return new Set(e.flatMap(e=>Object.keys(e.shape)))}function po(e){if(e==null)return!1;let t=typeof e;return t!==`object`&&t!==`function`||!(`~standard`in e)?!1:typeof e[`~standard`]?.validate==`function`}var mo=!1,ho=`draft-2020-12`;function go(e,t=`input`){let n=e[`~standard`],r;if(n.jsonSchema)r=n.jsonSchema[t]({target:ho});else if(n.vendor===`zod`){if(!(`_zod`in e))throw Error(`Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema().`);mo||(mo=!0,console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning.")),r=h(e,{target:ho,io:t})}else throw Error(`Schema library "${n.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`);if(t===`output`)return r.type===void 0&&_o(r)?{type:`object`,...r}:r;if(r.type!==void 0&&r.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(r.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...r}}function _o(e){if(`properties`in e||`patternProperties`in e||`additionalProperties`in e||`required`in e)return!0;for(let t of[`oneOf`,`anyOf`,`allOf`]){let n=e[t];if(Array.isArray(n)&&n.length>0)return n.every(e=>typeof e==`object`&&!!e&&(e.type===`object`||_o(e)))}return!1}function vo(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function yo(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>vo(e)).join(`, `)}:{success:!0,data:n.value}}function bo(e){let t=h(e,{target:ho,io:`input`});return typeof t.pattern==`string`?t.pattern:void 0}var xo=/\\\.\\d\{(\d+)\}/;function So(e){let t=xo.exec(e),n=[void 0,-1,0];return t&&n.push(Number(t[1])),[!1,!0].flatMap(e=>[!1,!0].flatMap(t=>n.map(n=>he({local:e,offset:t,precision:n}))))}function Co(e,t){let n;switch(e){case`email`:n=[de()];break;case`uri`:n=[y()];break;case`date`:n=[ge()];break;case`date-time`:n=So(t)}return new Set(n.map(e=>bo(e)).filter(e=>e!==void 0))}function wo(e,t,n){return n!==`zod`||Co(e,t).has(t)}function To(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Eo(e){try{return go(e,`input`)}catch(e){let t=e instanceof Error?e.message:String(e);throw new Z(X.InvalidParams,`Elicitation requestedSchema must describe an object with flat primitive properties: ${t}`)}}var Do=new Set([`$comment`,`deprecated`,`description`,`examples`,`readOnly`,`title`,`writeOnly`]);function Oo(e){return Do.has(e)||e.startsWith(`x-`)}var ko=new Set([`$schema`,...Object.keys(nr.shape.requestedSchema.shape)]),Ao={string:fo([Gn,qn,Jn,Yn]),number:fo([Kn]),integer:fo([Kn]),boolean:fo([Wn]),array:fo([Zn,Qn])},jo=new Set(Gn.shape.format.unwrap().options);function Mo(e,t,n,r){if(!To(e))return e;let i=typeof e.type==`string`&&Object.hasOwn(Ao,e.type)?Ao[e.type]:void 0;if(i===void 0)return e;let a={};for(let[o,s]of Object.entries(e))i.has(o)||Oo(o)?a[o]=s:o===`pattern`&&e.type===`string`&&typeof e.format==`string`?jo.has(e.format)?(typeof s!=`string`||!wo(e.format,s,n))&&r.push(`${t}.${o}`):a[o]=s:r.push(`${t}.${o}`);return a}function No(e,t){let n={},r=[];for(let[i,a]of Object.entries(e))i===`properties`&&To(a)?n[i]=Object.fromEntries(Object.entries(a).map(([e,n])=>[e,Mo(n,`properties.${e}`,t,r)])):ko.has(i)?n[i]=a:Oo(i)||r.push(i);if(r.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${r.join(`, `)}`);return n}function Po(e,t){if(!To(e.properties))return t;let n=Object.entries(e.properties).filter(([,e])=>!uo(tr,e).success).map(([e])=>`properties.${e}`);return n.length>0?n.join(`, `):t}function Fo(e,t,n=``){return Array.isArray(e)&&Array.isArray(t)?e.flatMap((e,r)=>Fo(e,t[r],`${n}[${r}]`)):!To(e)||!To(t)?[]:Object.entries(e).flatMap(([e,r])=>{let i=n?`${n}.${e}`:e;return Object.prototype.hasOwnProperty.call(t,e)?Fo(r,t[e],i):Oo(e)?[]:[i]})}function Io(e){if(!po(e.requestedSchema))return{...e,mode:`form`,requestedSchema:e.requestedSchema};let t=e.requestedSchema[`~standard`].vendor,n=No(Eo(e.requestedSchema),t),r=uo(nr.shape.requestedSchema,n);if(!r.success)throw new Z(X.InvalidParams,`Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${Po(n,r.error.message)}`);let i=Fo(n,r.data);if(i.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${i.join(`, `)}`);let a=(r.data.required??[]).filter(e=>!Object.prototype.hasOwnProperty.call(r.data.properties,e));if(a.length>0)throw new Z(X.InvalidParams,`Elicitation requestedSchema lists required properties that are not defined in properties: ${a.join(`, `)}`);return{...e,mode:`form`,requestedSchema:r.data}}function Lo(e){let t=e.inputRequests!==void 0&&Object.keys(e.inputRequests).length>0,n=typeof e.requestState==`string`;if(!t&&!n)throw TypeError(`inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)`);return{resultType:`input_required`,...e.inputRequests!==void 0&&{inputRequests:e.inputRequests},...e.requestState!==void 0&&{requestState:e.requestState}}}Object.assign(Lo,{elicit(e){try{return{method:`elicitation/create`,params:Io(e)}}catch(e){throw e instanceof Z?TypeError(e.message,{cause:e}):e}},elicitUrl(e){return{method:`elicitation/create`,params:{...e,mode:`url`}}},createMessage(e){return{method:`sampling/createMessage`,params:e}},listRoots(){return{method:`roots/list`}}});var Ro=!0,zo=10,Bo=250;function Vo(e){return{autoFulfill:e?.autoFulfill??Ro,maxRounds:e?.maxRounds??zo}}function Ho(e,t,n){let r=t!==void 0&&Object.keys(t).length>0;return!r&&n===void 0?e:{...e,...r&&{inputResponses:t},...n!==void 0&&{requestState:n}}}function Uo(e,t){return`Multi-round-trip request '${e}' still required input after ${t} rounds (inputRequired.maxRounds)`}function Wo(e,t){return new Promise((n,r)=>{if(t?.aborted){r(t.reason instanceof Y?t.reason:new Y(J.RequestTimeout,String(t.reason)));return}let i=setTimeout(()=>{t?.removeEventListener(`abort`,a),n()},e),a=()=>{clearTimeout(i),r(t?.reason instanceof Y?t.reason:new Y(J.RequestTimeout,String(t?.reason)))};t?.addEventListener(`abort`,a,{once:!0})})}function Go(e){let t=new AbortController,n=()=>t.abort(e?.reason);return e?.addEventListener(`abort`,n,{once:!0}),e?.aborted&&t.abort(e.reason),{signal:t.signal,abort:e=>t.abort(e),dispose:()=>e?.removeEventListener(`abort`,n)}}async function Ko(e){let{config:t,method:n,originalParams:r,requestOptions:i,hooks:a,signal:o}=e,s=e.flowStartedAt??Date.now(),c=e.firstPayload,l=0;for(;;){if(l+=1,l>t.maxRounds)throw new Y(J.InputRequiredRoundsExceeded,Uo(n,t.maxRounds),{rounds:t.maxRounds,lastResult:{inputRequests:c.inputRequests,...c.requestState!==void 0&&{requestState:c.requestState}}});i.onprogress?.({progress:l,message:`Fulfilling input required by '${n}' (round ${l})`});let e=Object.entries(c.inputRequests??{}),u;if(e.length>0){let t=Go(o);try{let n=await Promise.all(e.map(async([e,n])=>{try{return[e,await a.dispatchInputRequest(e,n,t.signal)]}catch(e){throw t.abort(e),e}}));u=Object.fromEntries(n)}finally{t.dispose()}}else await Wo(Bo,o);let d={...i.timeout!==void 0&&{timeout:i.timeout}};if(i.maxTotalTimeout!==void 0){let e=Date.now()-s,t=i.maxTotalTimeout-e;if(t<=0)throw new Y(J.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:i.maxTotalTimeout,totalElapsed:e});d.maxTotalTimeout=t}let f=await a.retry(Ho(r,u,c.requestState),d);if(Ha(f)){c={inputRequests:f.inputRequests??{},...f.requestState!==void 0&&{requestState:f.requestState}};continue}return f}}var qo=`AnnotationsSchema.AudioContentSchema.BaseMetadataSchema.BlobResourceContentsSchema.BooleanSchemaSchema.CallToolRequestSchema.CallToolRequestParamsSchema.CallToolResultSchema.CancelledNotificationSchema.CancelledNotificationParamsSchema.CancelTaskRequestSchema.CancelTaskResultSchema.ClientCapabilitiesSchema.ClientNotificationSchema.ClientRequestSchema.ClientResultSchema.CompatibilityCallToolResultSchema.CompleteRequestSchema.CompleteRequestParamsSchema.CompleteResultSchema.ContentBlockSchema.CreateMessageRequestSchema.CreateMessageRequestParamsSchema.CreateMessageResultSchema.CreateMessageResultWithToolsSchema.CreateTaskResultSchema.CursorSchema.DiscoverRequestSchema.DiscoverResultSchema.ElicitationCompleteNotificationSchema.ElicitationCompleteNotificationParamsSchema.ElicitRequestSchema.ElicitRequestFormParamsSchema.ElicitRequestParamsSchema.ElicitRequestURLParamsSchema.ElicitResultSchema.EmbeddedResourceSchema.EmptyResultSchema.EnumSchemaSchema.GetPromptRequestSchema.GetPromptRequestParamsSchema.GetPromptResultSchema.GetTaskPayloadRequestSchema.GetTaskPayloadResultSchema.GetTaskRequestSchema.GetTaskResultSchema.IconSchema.IconsSchema.ImageContentSchema.ImplementationSchema.InitializedNotificationSchema.InitializeRequestSchema.InitializeRequestParamsSchema.InitializeResultSchema.JSONArraySchema.JSONObjectSchema.JSONRPCErrorResponseSchema.JSONRPCMessageSchema.JSONRPCNotificationSchema.JSONRPCRequestSchema.JSONRPCResponseSchema.JSONRPCResultResponseSchema.JSONValueSchema.LegacyTitledEnumSchemaSchema.ListPromptsRequestSchema.ListPromptsResultSchema.ListResourcesRequestSchema.ListResourcesResultSchema.ListResourceTemplatesRequestSchema.ListResourceTemplatesResultSchema.ListRootsRequestSchema.ListRootsResultSchema.ListTasksRequestSchema.ListTasksResultSchema.ListToolsRequestSchema.ListToolsResultSchema.LoggingLevelSchema.LoggingMessageNotificationSchema.LoggingMessageNotificationParamsSchema.ModelHintSchema.ModelPreferencesSchema.MultiSelectEnumSchemaSchema.NotificationSchema.NumberSchemaSchema.PaginatedRequestSchema.PaginatedRequestParamsSchema.PaginatedResultSchema.PingRequestSchema.PrimitiveSchemaDefinitionSchema.ProgressSchema.ProgressNotificationSchema.ProgressNotificationParamsSchema.ProgressTokenSchema.PromptSchema.PromptArgumentSchema.PromptListChangedNotificationSchema.PromptMessageSchema.PromptReferenceSchema.ReadResourceRequestSchema.ReadResourceRequestParamsSchema.ReadResourceResultSchema.RelatedTaskMetadataSchema.RequestSchema.RequestIdSchema.RequestMetaSchema.ResourceSchema.ResourceContentsSchema.ResourceLinkSchema.ResourceListChangedNotificationSchema.ResourceRequestParamsSchema.ResourceTemplateSchema.ResourceTemplateReferenceSchema.ResourceUpdatedNotificationSchema.ResourceUpdatedNotificationParamsSchema.ResultMetaObjectSchema.ResultSchema.RoleSchema.RootSchema.RootsListChangedNotificationSchema.SamplingContentSchema.SamplingMessageSchema.SamplingMessageContentBlockSchema.ServerCapabilitiesSchema.ServerNotificationSchema.ServerRequestSchema.ServerResultSchema.SetLevelRequestSchema.SetLevelRequestParamsSchema.SingleSelectEnumSchemaSchema.StringSchemaSchema.SubscribeRequestSchema.SubscribeRequestParamsSchema.SubscriptionFilterSchema.SubscriptionsAcknowledgedNotificationSchema.SubscriptionsAcknowledgedNotificationParamsSchema.SubscriptionsListenRequestSchema.SubscriptionsListenRequestParamsSchema.SubscriptionsListenResultSchema.SubscriptionsListenResultMetaSchema.TaskAugmentedRequestParamsSchema.TaskCreationParamsSchema.TaskMetadataSchema.TaskSchema.TaskStatusSchema.TaskStatusNotificationSchema.TaskStatusNotificationParamsSchema.TextContentSchema.TextResourceContentsSchema.TitledMultiSelectEnumSchemaSchema.TitledSingleSelectEnumSchemaSchema.ToolSchema.ToolAnnotationsSchema.ToolChoiceSchema.ToolExecutionSchema.ToolListChangedNotificationSchema.ToolResultContentSchema.ToolUseContentSchema.UnsubscribeRequestSchema.UnsubscribeRequestParamsSchema.UntitledMultiSelectEnumSchemaSchema.UntitledSingleSelectEnumSchemaSchema`.split(`.`),Jo={IdJagTokenExchangeResponseSchema:Ur,OAuthClientInformationFullSchema:Jr,OAuthClientInformationSchema:qr,OAuthClientMetadataSchema:Kr,OAuthClientRegistrationErrorSchema:Yr,OAuthErrorResponseSchema:Wr,OAuthMetadataSchema:zr,OAuthProtectedResourceMetadataSchema:Rr,OAuthTokenRevocationRequestSchema:Xr,OAuthTokensSchema:Hr,OpenIdProviderDiscoveryMetadataSchema:Vr,OpenIdProviderMetadataSchema:Br},Yo={},Xo={};function Zo(e,t){let n=e.slice(0,-6);Yo[n]=t,Xo[n]=e=>t.safeParse(e).success}for(let e of qo)Zo(e,La[e]);for(let[e,t]of Object.entries(Jo))Zo(e,t);Object.freeze(Yo);var Qo=Object.freeze(Xo);function $o(e){switch(e){case`initialize`:case`notifications/initialized`:return ja(void 0);case`server/discover`:return ja(Aa);default:return}}var es=[Ie,Le,ze,Ve],ts=[`inputResponses`,`requestState`];function ns(e,t){let n=e.params;if(!ss(n))return{message:e,lifted:{}};let r=n._meta,i=ss(r)?es.filter(e=>e in r):[],a=t===`request`?ts.filter(e=>e in n):[];if(i.length===0&&a.length===0)return{message:e,lifted:{}};let o={},s={...n};if(i.length>0&&ss(r)){let e={},t={...r};for(let n of i)e[n]=r[n],delete t[n];o.envelope=e,Object.keys(t).length>0?s._meta=t:delete s._meta}for(let e of a)e===`inputResponses`&&(o.inputResponses=s[e]),e===`requestState`&&(o.requestState=s[e]),delete s[e];return{message:{...e,params:s},lifted:o}}function rs(e,t){let n=e.validateResult(t,void 0);if(n.ok||n.reason!==`not-in-era`)return{"~standard":{version:1,vendor:`mcp-wire-codec`,validate(n){let r=e.validateResult(t,n);return r.ok?{value:r.value}:{issues:[{message:r.reason===`invalid`?r.message:`not-in-era: ${t}`}]}}}}}function is(e){return()=>e}var as=is(void 0),os=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_customSchemaRequestMethods=new Set;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_negotiatedProtocolVersion;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??Pe,this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}_shouldDropInbound(e){}_outboundMetaEnvelope(){}_envelopeOutbound(e){let t=this._outboundMetaEnvelope();if(t===void 0)return e;let n=e.params??{};return{...e,params:{...n,_meta:{...t,...n._meta}}}}_resolveNonCompleteResult(e,t){return Promise.reject(new Y(J.UnsupportedResultType,`Unsupported result type '${e.kind}' for ${t.request.method}`,{resultType:e.kind,method:t.request.method}))}_getRequestHandler(e){return this._requestHandlers.get(e)}async _oncancel(e){e.params.requestId!==void 0&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Y(J.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),Ba(e)||Va(e)?this._onresponse(e):Ra(e)?this._onrequest(e,t):za(e)?this._onnotification(e,t):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new Y(J.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e,t){let{message:n}=ns(e,`notification`),r=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`)return;if(t?.classification!==void 0){let e=Ma(t.classification);if(e!==r.era){this._onerror(Error(`Era mismatch on inbound notification '${n.method}': classified as ${e} but this instance serves ${r.era}`));return}}if(Pa(n.method)&&!r.hasNotificationMethod(n.method))return;let i=this._notificationHandlers.get(n.method),a=this.fallbackNotificationHandler;(i!==void 0||a!==void 0)&&Promise.resolve().then(()=>i===void 0?a(n):i(n,r)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let{message:n,lifted:r}=ns(e,`request`),i=this._negotiatedWireCodec();if(t?.classification===void 0&&this._shouldDropInbound(e)===`drop`){this._onerror(Error(`Dropped inbound request '${e.method}': not servable on this connection's protocol era`));return}let a=this._transport,o=(e,t,r)=>{let i={jsonrpc:`2.0`,id:n.id,error:{code:e,message:t,...r!==void 0&&{data:r}}};a?.send(i).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))};if(t?.classification!==void 0){let e=Ma(t.classification);if(e!==i.era){this._onerror(Error(`Era mismatch on inbound request '${n.method}': classified as ${e} but this instance serves ${i.era}`));let r=t.classification.revision??e;o(X.UnsupportedProtocolVersion,`Unsupported protocol version: ${r}`,{supported:this._supportedProtocolVersions,requested:r});return}}if(Na(n.method)&&!i.hasRequestMethod(n.method)&&!(Fa(n.method)&&this._customSchemaRequestMethods.has(n.method))){o(X.MethodNotFound,`Method not found`);return}let s=this._requestHandlers.get(n.method)??this.fallbackRequestHandler;if(s===void 0){o(X.MethodNotFound,`Method not found`);return}let c=i.checkInboundEnvelope(r);if(c!==void 0){o(X.InvalidParams,c);return}let l=(e,t)=>this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,{...t,relatedRequestId:n.id}),u=(e,t,r)=>this._requestWithSchemaViaCodec(this._resolveOutboundCodec(e.method),e,t,{...r,relatedRequestId:n.id}),d=new AbortController;this._requestHandlerAbortControllers.set(n.id,d);let f=r.inputResponses===void 0?void 0:us(r.inputResponses),p={sessionId:a?.sessionId,mcpReq:{id:n.id,method:n.method,_meta:n.params?._meta,...r.envelope!==void 0&&{envelope:r.envelope},...f!==void 0&&{inputResponses:f.accepted},...f!==void 0&&f.droppedKeys.length>0&&{droppedInputResponseKeys:f.droppedKeys},requestState:r.requestState===void 0?as:is(r.requestState),signal:d.signal,send:((e,t,n)=>{let r=this._resolveOutboundCodec(e.method);if(this._assertOutboundRequestInEra(r,e.method),po(t))return u(e,t,n);let i=rs(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`);return u(e,i,t)}),notify:l},http:t?.authInfo?{authInfo:t.authInfo}:void 0},m=this.buildContext(p,t);Promise.resolve().then(()=>s(n,m)).then(async e=>{if(d.signal.aborted)return;let t;try{t=i.encodeResult(n.method,e,this._outboundServerInfo())}catch(e){this._onerror(Error(`Failed to encode result for ${n.method}: ${e}`)),o(X.InternalError,`Internal error`);return}let r={result:t,jsonrpc:`2.0`,id:n.id};await a?.send(r)},async e=>{if(d.signal.aborted)return;let t=Number.isSafeInteger(e.code)?e.code:X.InternalError,r={jsonrpc:`2.0`,id:n.id,error:{code:i.encodeErrorCode(t),message:e.message??`Internal error`,...e.data!==void 0&&{data:e.data}}};await a?.send(r)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(n.id)===d&&this._requestHandlerAbortControllers.delete(n.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._responseHandlers.get(t);if(n===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),this._progressHandlers.delete(t),Ba(e)?n(e):n(Z.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t,n){let r=this._resolveOutboundCodec(e.method);if(po(t))return Fa(e.method)||this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n);this._assertOutboundRequestInEra(r,e.method);let i=rs(r,e.method);if(i===void 0)throw TypeError(`'${e.method}' is not a spec method; pass a result schema as the second argument to request().`);return this._requestWithSchemaViaCodec(r,e,i,t)}_negotiatedWireCodec(){return ja(this._negotiatedProtocolVersion)}_wireCodec(){return this._negotiatedWireCodec()}_resolveOutboundCodec(e){if(this._negotiatedProtocolVersion===void 0){let t=$o(e);if(t)return t}return this._negotiatedWireCodec()}_assertOutboundRequestInEra(e,t){if(Na(t)&&!e.hasRequestMethod(t))throw new Y(J.MethodNotSupportedByProtocolVersion,`Method '${t}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t,era:e.era})}_requestWithSchema(e,t,n){let r=this._resolveOutboundCodec(e.method);return this._assertOutboundRequestInEra(r,e.method),this._requestWithSchemaViaCodec(r,e,t,n)}_requestWithSchemaViaCodec(e,t,n,r){let{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s}=r??{},c=Date.now(),l,u;return new Promise((d,f)=>{let p=e=>{f(e)};if(!this._transport){p(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method)}catch(e){p(e);return}if(r?.signal?.aborted){let e=r.signal.reason;throw e instanceof Y?e:new Y(J.RequestTimeout,String(e))}let m=e.era===`2026-07-28`&&this._transport.hasPerRequestStream===!0?new AbortController:void 0,h=this._requestMessageId++;u=h;let g={...t,jsonrpc:`2.0`,id:h};r?.onprogress&&(this._progressHandlers.set(h,r.onprogress),g.params={...t.params,_meta:{...t.params?._meta,progressToken:h}});let _=this._envelopeOutbound(g),v=!1,y=e=>{v||(this._progressHandlers.delete(h),m===void 0?t.method!==`initialize`&&this._transport?.send(this._envelopeOutbound({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:h,reason:String(e)}}),{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))):m.abort(),f(e instanceof Y?e:new Y(J.RequestTimeout,String(e))))};this._responseHandlers.set(h,i=>{if(r?.signal?.aborted)return;if(v=!0,i instanceof Error)return f(i);let a;try{a=e.decodeResult(t.method,i.result)}catch(e){return f(e instanceof Error?e:Error(String(e)))}if(a.kind===`invalid`)return f(a.error);if(a.kind===`input_required`){if(r?.allowInputRequired===!0)return d(gs(a));let i={codec:e,request:t,resultSchema:n,options:r,flowStartedAt:c,retry:(r,i)=>this._requestWithSchemaViaCodec(e,r===void 0?{method:t.method}:{method:t.method,params:r},n,i)};return d(this._resolveNonCompleteResult(a,i))}let o=a.result;yo(n,o).then(e=>{e.success?d(e.data):f(new Y(J.InvalidResult,`Invalid result for ${t.method}: ${e.error}`))},f)}),l=()=>y(r?.signal?.reason),r?.signal?.addEventListener(`abort`,l,{once:!0});let b=r?.timeout??6e4;this._setupTimeout(h,b,r?.maxTotalTimeout,()=>y(new Y(J.RequestTimeout,`Request timed out`,{timeout:b})),r?.resetTimeoutOnProgress??!1),this._transport.send(_,{relatedRequestId:i,resumptionToken:a,onresumptiontoken:o,headers:s,requestSignal:m?.signal}).catch(e=>{this._progressHandlers.delete(h),f(e)})}).finally(()=>{l&&r?.signal?.removeEventListener(`abort`,l),u!==void 0&&(this._responseHandlers.delete(u),this._cleanupTimeout(u))})}async notification(e,t){return await this._notificationViaCodec(this._resolveOutboundCodec(e.method),e,t)}async _notificationViaCodec(e,t,n){if(!this._transport)throw new Y(J.NotConnected,`Not connected`);if(Pa(t.method)&&!e.hasNotificationMethod(t.method))throw new Y(J.MethodNotSupportedByProtocolVersion,`Notification '${t.method}' is not supported by the negotiated protocol version (wire era ${e.era})`,{method:t.method,era:e.era});this.assertNotificationCapability(t.method);let r=this._envelopeOutbound({jsonrpc:`2.0`,...t});if((this._options?.debouncedNotificationMethods??[]).includes(t.method)&&!t.params&&n?.relatedRequestId===void 0){if(this._pendingDebouncedNotifications.has(t.method))return;this._pendingDebouncedNotifications.add(t.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(t.method),this._transport&&this._transport?.send(r,n).catch(e=>this._onerror(e))});return}await this._transport.send(r,n)}setRequestHandler(e,t,n){this.assertRequestHandlerCapability(e);let r;if(typeof t==`function`){if(!Na(e))throw TypeError(`'${e}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`);r=(n,r)=>{let i=this._negotiatedWireCodec(),a=i.validateRequest(e,n);if(!a.ok&&a.reason===`not-in-era`&&(a=i.validateInputRequest(e,n)),!a.ok)throw a.reason===`not-in-era`?new Z(X.InternalError,`No wire schema for ${e} in the resolved era`):Error(a.message);return Promise.resolve(t(a.value,r))}}else if(n)r=async(r,i)=>{let a=await yo(t.params,{...r.params});if(!a.success)throw new Z(X.InvalidParams,`Invalid params for ${e}: ${a.error}`);return n(a.data,i)};else throw TypeError(`setRequestHandler: handler is required`);typeof t==`function`?this._customSchemaRequestMethods.delete(e):this._customSchemaRequestMethods.add(e),this._requestHandlers.set(e,this._wrapHandler(e,r))}_wrapHandler(e,t){return t}_outboundServerInfo(){}removeRequestHandler(e){this._requestHandlers.delete(e),this._customSchemaRequestMethods.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t,n){if(typeof t==`function`){if(!Pa(e))throw TypeError(`'${e}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`);this._notificationHandlers.set(e,(n,r)=>{let i=r.validateNotification(e,n);if(!i.ok)throw i.reason===`not-in-era`?new Z(X.InternalError,`No wire schema for ${e} in the resolved era`):Error(i.message);return Promise.resolve(t(i.value))});return}if(!n)throw TypeError(`setNotificationHandler: handler is required`);this._notificationHandlers.set(e,async r=>{let i=await yo(t.params,{...r.params});if(!i.success)throw new Z(X.InvalidParams,`Invalid params for notification ${e}: ${i.error}`);await n(i.data,r)})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function ss(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function cs(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=ss(a)&&ss(i)?{...a,...i}:i}return n}function ls(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function us(e){let t={},n=[];if(!ls(e))return{accepted:t,droppedKeys:n};for(let[r,i]of Object.entries(e)){if(!ls(i)||`method`in i||`result`in i){n.push(r);continue}t[r]=i}return{accepted:t,droppedKeys:n}}function ds(e){throw new Y(J.SendFailed,`ctx.mcpReq.${e} is not available while fulfilling an embedded input request: the request is fulfilled locally and has no related peer request`)}function fs(e,t,n,r,i){return{sessionId:i,mcpReq:{id:e,method:t,_meta:n?._meta,requestState:is(void 0),signal:r,send:(()=>ds(`send`)),notify:()=>ds(`notify`)}}}async function ps(e,t,n,r,i){if(!ls(r)||typeof r.method!=`string`)throw new Y(J.InvalidResult,`Invalid input request '${n}': each inputRequests entry must be an embedded request object with a method`,{key:n});let a=r.method;if(!t.hasInputRequestMethod(a))throw new Y(J.InvalidResult,`Invalid input request '${n}': '${a}' is not an embedded request the ${t.era} revision defines (expected elicitation/create, sampling/createMessage, or roots/list)`,{key:n,method:a});let o=e.getRequestHandler(a);if(o===void 0)throw new Y(J.CapabilityNotSupported,`Cannot fulfil input request '${n}': no handler is registered for '${a}' on this client. Declare the corresponding capability and register a handler, or handle input_required results manually.`,{key:n,method:a});let s=ls(r.params)?r.params:void 0;return await o({jsonrpc:`2.0`,id:n,method:a,...s!==void 0&&{params:s}},e.buildContext(fs(n,a,s,i,e.sessionId)))}function ms(e,t){return{...e?.signal!==void 0&&{signal:e.signal},...e?.onprogress!==void 0&&{onprogress:e.onprogress},...e?.resetTimeoutOnProgress!==void 0&&{resetTimeoutOnProgress:e.resetTimeoutOnProgress},...e?.headers!==void 0&&{headers:e.headers},...t.timeout!==void 0&&{timeout:t.timeout},...t.maxTotalTimeout!==void 0&&{maxTotalTimeout:t.maxTotalTimeout},allowInputRequired:!0}}function hs(e,t,n,r){let{codec:i,request:a,options:o,flowStartedAt:s}=r,c={inputRequests:n.inputRequests,...n.requestState!==void 0&&{requestState:n.requestState}},l={dispatchInputRequest:(t,n,r)=>ps(e,i,t,n,r),retry:(e,t)=>r.retry(e,ms(o,t))};return Ko({config:t,method:a.method,originalParams:a.params,firstPayload:c,flowStartedAt:s,signal:o?.signal,requestOptions:{...o?.timeout!==void 0&&{timeout:o.timeout},...o?.maxTotalTimeout!==void 0&&{maxTotalTimeout:o.maxTotalTimeout},...o?.onprogress!==void 0&&{onprogress:o.onprogress}},hooks:l})}function gs(e){return{resultType:`input_required`,inputRequests:e.inputRequests,...e.requestState!==void 0&&{requestState:e.requestState},...e._meta!==void 0&&{_meta:e._meta}}}var _s=Ee(Ce((e=>{var t=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,n=/\\([\u000b\u0020-\u00ff])/g,r=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;e.parse=i;function i(e){if(!e)throw TypeError(`argument string is required`);var i=typeof e==`object`?a(e):e;if(typeof i!=`string`)throw TypeError(`argument string is required to be a string`);var s=i.indexOf(`;`),c=s===-1?i.trim():i.slice(0,s).trim();if(!r.test(c))throw TypeError(`invalid media type`);var l=new o(c.toLowerCase());if(s!==-1){var u,d,f;for(t.lastIndex=s;d=t.exec(i);){if(d.index!==s)throw TypeError(`invalid parameter format`);s+=d[0].length,u=d[1].toLowerCase(),f=d[2],f.charCodeAt(0)===34&&(f=f.slice(1,-1),f.indexOf(`\\`)!==-1&&(f=f.replace(n,`$1`))),l.parameters[u]=f}if(s!==i.length)throw TypeError(`invalid parameter format`)}return l}function a(e){var t;if(typeof e.getHeader==`function`?t=e.getHeader(`content-type`):typeof e.headers==`object`&&(t=e.headers&&e.headers[`content-type`]),typeof t!=`string`)throw TypeError(`content-type header is missing from object`);return t}function o(e){this.parameters=Object.create(null),this.type=e}}))(),1);function vs(e){if(e)try{return _s.parse(e).type}catch{let t=(e.split(`;`,1)[0]??``).trim().toLowerCase();return t===``||e.slice(t.length).includes(`,`)?void 0:t}}function ys(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function bs(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...ys(t.headers),...ys(r.headers)}:t.headers}):e}var xs=new Set([301,302,303,307,308]),Ss=5;function Cs(e,t){return e.protocol===t.protocol&&e.host===t.host||e.protocol===`http:`&&t.protocol===`https:`&&e.hostname===t.hostname&&!e.port&&!t.port}function ws(e,t){let n=xs.has(t.status)?t.headers?.get(`location`):void 0;if(n)try{return new URL(n,e)}catch{return}}var Ts=new WeakSet;function Es(e){let t=(t,n)=>e(t,n);return Ts.add(t),t}function Ds(e){return Ts.has(e)?e:async(t,n)=>{if(n?.redirect===`error`||n?.redirect===`manual`)return e(t,n);let r=(n?.method??`GET`).toUpperCase(),i=t;for(let t=0;;t++){let a=await e(i,{...n,redirect:`manual`}),o=ws(i,a);if(!o||t===Ss)return a;let s=new URL(i),c=r===`GET`||a.status===307||a.status===308,l=!(o.username||o.password)||o.username===s.username&&o.password===s.password;if(!c||!l||!Cs(s,o))return a;await a.text?.().catch(()=>{}),i=o}}}function Os(e,t){if(t.type===`opaqueredirect`)return`Redirect not followed: this runtime does not expose where it points`;let n=ws(t.url||e,t);if(n)return n.username=n.password=n.search=n.hash=``,n.protocol===`http:`&&new URL(t.url||e).protocol===`https:`?(n.protocol=`https:`,`Redirect from https to plain http not followed; try ${n.href} as the endpoint`):`Redirect to ${n.href} not followed; use that URL as the endpoint if it is the intended server`}function ks(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r1?t[a.href]=e:(a.hash=``,r===``?n=a:Is(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(Ps[i])continue;let a=`${r}/${As(i)}`,o=e[i];if(Array.isArray(o)){if(Ms[i]){let e=o.length;for(let r=0;r%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Us=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Ws=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Gs=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Ks=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,qs=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Js=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},Ys=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Xs=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Zs=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e));function Qs(e){return e.test.bind(e)}var $s={date:tc,time:nc.bind(void 0,!1),"date-time":ic,duration:Zs,uri:sc,"uri-reference":Qs(Vs),"uri-template":Qs(Hs),url:Qs(Us),email:Js,hostname:Qs(Bs),ipv4:Qs(Ys),ipv6:Qs(Xs),regex:lc,uuid:Qs(Ws),"json-pointer":Qs(Gs),"json-pointer-uri-fragment":Qs(Ks),"relative-json-pointer":Qs(qs)};function ec(e){return e%4==0&&(e%100!=0||e%400==0)}function tc(e){let t=e.match(Ls);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&ec(n)?29:Rs[r])}function nc(e,t){let n=t.match(zs);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}var rc=/t|\s/i;function ic(e){let t=e.split(rc);return t.length==2&&tc(t[0])&&nc(!0,t[1])}var ac=/\/|:/,oc=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function sc(e){return ac.test(e)&&oc.test(e)}var cc=/[^\\]\\Z/;function lc(e){if(cc.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}function uc(e){let t=0,n=e.length,r=0,i;for(;r=55296&&i<=56319&&rks(e,t))||P.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||P.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;Q(e,v,n,r,i,a,o,t).valid&&P.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Se=[];if(y!==void 0){let t=`${s}/anyOf`,l=P.length,u=!1;for(let s=0;s{let u=Object.create(c),d=Q(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return P.push(...d.errors),d.valid&&Se.push(u),d.valid}).length;u===1?P.length=l:P.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Se),x!==void 0){let t=`${s}/if`;if(Q(e,x,n,r,i,a,o,t,c).valid){if(S!==void 0){let l=Q(e,S,n,r,i,a,o,`${s}/then`,c);l.valid||P.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(C!==void 0){let l=Q(e,C,n,r,i,a,o,`${s}/else`,c);l.valid||P.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||P.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(D!==void 0&&t.lengthO&&P.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${O} properties.`}),re!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${As(s)}`,c=Q(s,re,n,r,i,a,e,t);c.valid||P.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(k!==void 0){let t=`${s}/dependantRequired`;for(let n in k)if(n in e){let r=k[n];for(let i of r)i in e||P.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(A!==void 0)for(let t in A){let l=`${s}/dependentSchemas`;if(t in e){let s=Q(e,A[t],n,r,i,a,o,`${l}/${As(t)}`,c);s.valid||P.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(ie!==void 0){let t=`${s}/dependencies`;for(let s in ie)if(s in e){let c=ie[s];if(Array.isArray(c))for(let n of c)n in e||P.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=Q(e,c,n,r,i,a,o,`${t}/${As(s)}`);l.valid||P.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(T!==void 0){let t=`${s}/properties`;for(let s in T){if(!(s in e))continue;let d=`${o}/${As(s)}`,f=Q(e[s],T[s],n,r,i,a,d,`${t}/${As(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,P.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&E!==void 0){let t=`${s}/patternProperties`;for(let s in E){let d=new RegExp(s,`u`),f=E[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${As(p)}`,h=Q(e[p],f,n,r,i,a,m,`${t}/${As(s)}`);h.valid?c[p]=l[p]=!0:(u=i,P.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&te!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${As(s)}`,f=Q(e[s],te,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,P.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&ne!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${As(s)}`,u=Q(e[s],ne,n,r,i,a,l,t);u.valid?c[s]=!0:P.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){pe!==void 0&&e.length>pe&&P.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${pe}).`}),fe!==void 0&&e.length=(ue||0)&&(P.length=u),ue===void 0&&de===void 0&&d===0?P.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):ue!==void 0&&dde&&P.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${de} items matching schema. ${d} items were found.`})}}if(!u&&ce!==void 0){let u=`${s}/unevaluatedItems`;for(;l=ge||e>ge)&&P.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${j?`or equal to `:``} ${ge}.`})):(he!==void 0&&ege&&P.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${ge}.`}),_e!==void 0&&e<=_e&&P.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${_e}.`}),j!==void 0&&e>=j&&P.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${j}.`})),M!==void 0){let t=e%M;Math.abs(0-t)>=1.1920929e-7&&Math.abs(M-t)>=1.1920929e-7&&P.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${M}.`})}}else if(u===`string`){let t=ve===void 0&&ye===void 0?0:uc(e);ve!==void 0&&tye&&P.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${ye}).`}),be!==void 0&&!new RegExp(be,`u`).test(e)&&P.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),w!==void 0&&$s[w]&&!$s[w](e)&&P.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${w}".`})}return{valid:P.length===0,errors:P}}var dc=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Is(e)}validate(e){return Q(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Is(e,this.lookup)}},fc=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft}_draftFor(e){let t=Me(e,`pass an explicit { draft } to CfWorkerJsonSchemaValidator to validate other dialects.`);return t===`draft-7`?`7`:t}getValidator(e){let t=new dc(e,this.draft??this._draftFor(e),this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}},pc=globalThis.crypto;async function mc(e){return(await pc).getRandomValues(new Uint8Array(e))}async function hc(e){let t=``;for(;t.length128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await gc(e);return{code_verifier:t,code_challenge:await _c(t)}}var yc=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},bc=10,xc=13,Sc=32;function Cc(e){}function wc(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Cc,onError:n=Cc,onRetry:r=Cc,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(` +`)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new yc(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(` +`,n);for(;r!==-1;){if(n===r){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0,n=r+1,r=e.indexOf(` +`,n);continue}let i=e.charCodeAt(n);if(Tc(e,n,i)){let i=e.charCodeAt(n+5)===Sc?n+6:n+5,a=e.slice(i,r);if(d===0&&e.charCodeAt(r+1)===bc){t({id:l,event:f,data:a}),l=void 0,u=``,f=void 0,n=r+2,r=e.indexOf(` +`,n);continue}u=d===0?a:`${u} +${a}`,d++}else Ec(e,n,i)?f=e.slice(e.charCodeAt(n+6)===Sc?n+7:n+6,r)||void 0:_(e,n,r);n=r+1,r=e.indexOf(` +`,n)}return e.slice(n)}for(;n20?`${e.slice(0,20)}\u2026`:e}"`,{type:`unknown-field`,field:e,value:t,line:i}))}}function y(){d>0&&t({id:l,event:f,data:u}),l=void 0,u=``,d=0,f=void 0}function b(e={}){if(e.consume&&o.length>0){let e=o.join(``);_(e,0,e.length)}c=!0,l=void 0,u=``,d=0,f=void 0,o.length=0,s=0,p=!1}return{feed:m,reset:b}}function Tc(e,t,n){return n===100&&e.charCodeAt(t+1)===97&&e.charCodeAt(t+2)===116&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===58}function Ec(e,t,n){return n===101&&e.charCodeAt(t+1)===118&&e.charCodeAt(t+2)===101&&e.charCodeAt(t+3)===110&&e.charCodeAt(t+4)===116&&e.charCodeAt(t+5)===58}var Dc=class extends TransformStream{constructor({onError:e,onRetry:t,onComment:n,maxBufferSize:r}={}){let i;super({start(a){i=wc({onEvent:e=>{a.enqueue(e)},onError(t){typeof e==`function`&&e(t),(e===`terminate`||t.type===`max-buffer-size-exceeded`)&&a.error(t)},onRetry:t,onComment:n,maxBufferSize:r})},transform(e){i.feed(e)}})}},Oc=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.OAuthClientFlowError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e){super(e),this.name=new.target.name,Qr(this,new.target)}},kc=class extends Oc{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.IssuerMismatchError`})}kind;expected;received;constructor(e,t,n){super(`Issuer mismatch in ${e===`metadata`?`authorization server metadata (RFC 8414 §3.3)`:`authorization response (RFC 9207)`}: expected ${JSON.stringify(t)}, received ${JSON.stringify(n)}`),this.kind=e,this.expected=t,this.received=n}},Ac=class extends Oc{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.RegistrationRejectedError`})}status;body;submittedMetadata;constructor(e){super(`Dynamic Client Registration rejected (HTTP ${e.status}): ${e.body}`),this.status=e.status,this.body=e.body,this.submittedMetadata=e.submittedMetadata}},jc=class extends Oc{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.InsecureTokenEndpointError`})}tokenEndpoint;constructor(e){super(`Refusing to send credentials to non-https token endpoint '${e}'. OAuth token requests MUST use TLS (localhost / *.localhost / 127.0.0.1 / ::1 are exempt).`),this.tokenEndpoint=e}},Mc=class extends Oc{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.AuthorizationServerMismatchError`})}constructor(e,t){super(`Authorization server mismatch: credentials are bound to ${JSON.stringify(e)} but this call resolved ${JSON.stringify(t)}; refusing to present them to a different authorization server`),this.recordedIssuer=e,this.currentIssuer=t}},Nc=class extends Oc{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.InsufficientScopeError`})}requiredScope;resourceMetadataUrl;errorDescription;constructor(e){super(`Insufficient scope${e.requiredScope?`: required "${e.requiredScope}"`:``}`),this.requiredScope=e.requiredScope,this.resourceMetadataUrl=e.resourceMetadataUrl,this.errorDescription=e.errorDescription}};function Pc(e,t,n){if(e)return typeof e.issuer==`string`?Fc(e.issuer,t)?e:void 0:(n?.canPersistStamp!==!1&&console.warn(`[mcp-sdk] SEP-2352: stored OAuth credential has no 'issuer' stamp (pre-upgrade storage or provider not round-tripping the value). SEP-2352 isolation is inactive for this read; ensure your provider round-trips the issuer field.`),e.issuer===void 0?e:{...e,issuer:void 0})}function Fc(e,t){return e===t||e.endsWith(`/`)&&e.slice(0,-1)===t||t.endsWith(`/`)&&t.slice(0,-1)===e}function Ic(e){if(e==null)return!1;let t=e;return typeof t.tokens==`function`&&typeof t.clientInformation==`function`}async function Lc(e,t,n){let{resourceMetadataUrl:r,scope:i}=dl(t.response);if(await al(e,{serverUrl:t.serverUrl,resourceMetadataUrl:r,scope:i,fetchFn:t.fetchFn,...n})!==`AUTHORIZED`)throw new zc}function Rc(e,t){return{token:async()=>(await e.tokens())?.access_token,onUnauthorized:async n=>Lc(e,n,t)}}var zc=class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.UnauthorizedError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e){super(e??`Unauthorized`),this.name=`UnauthorizedError`,Qr(this,new.target)}};function Bc(e){return e?.authorization_response_iss_parameter_supported===!0}function Vc({iss:e,expectedIssuer:t,issParameterSupported:n}){if(t!==void 0){if(e===void 0){if(n)throw new kc(`authorization_response`,t,void 0);return}if(e!==t)throw new kc(`authorization_response`,t,e)}}function Hc(...e){let t=new Set;for(let n of e)if(n)for(let e of n.split(/\s+/))e&&t.add(e);return t.size>0?[...t].join(` `):void 0}function Uc(e,t){if(!e)return!1;let n=new Set((t??``).split(/\s+/).filter(Boolean));for(let t of e.split(/\s+/))if(t&&!n.has(t))return!0;return!1}async function Wc(e,t,n,r,i){if(typeof e==`string`)return{authorizationCode:e,iss:t};let a=e.get(`iss`)??void 0,o=e.get(`code`);if(o)return{authorizationCode:o,iss:a};let s=(await n.discoveryState?.())?.authorizationServerMetadata;if(!s)try{s=(await xl(r,i)).authorizationServerMetadata}catch{s=void 0}if(!s)throw new zc(`Authorization callback failed and the issuer could not be verified`);Vc({iss:a,expectedIssuer:s.issuer,issParameterSupported:Bc(s)});let c=e.get(`error`);throw c?new ti(c,e.get(`error_description`)??c,e.get(`error_uri`)??void 0):new zc("Authorization callback contained neither `code` nor `error`")}function Gc(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var Kc=`code`,qc=`S256`;function Jc(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&Gc(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function Yc(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:Xc(i,a,n);return;case`client_secret_post`:Zc(i,a,r);return;case`none`:Qc(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function Xc(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function Zc(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function Qc(e,t){t.set(`client_id`,e)}function $c(e){return e===`localhost`||e.endsWith(`.localhost`)||e===`127.0.0.1`||e===`[::1]`||e===`::1`}function el(e){let t=new URL(String(e));if(t.protocol!==`https:`&&!$c(t.hostname))throw new jc(t.href);return t}function tl(e){for(let t of e??[]){let e;try{e=new URL(t)}catch{continue}if(e.protocol!==`http:`&&e.protocol!==`https:`||$c(e.hostname))return`native`}return`web`}function nl(e){let t=e.clientMetadata;return{...t,grant_types:t.grant_types??(e.redirectUrl===void 0?void 0:[`authorization_code`,`refresh_token`]),application_type:t.application_type??tl(t.redirect_uris)}}async function rl(e){let t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let e=Wr.parse(JSON.parse(n));return ti.fromResponse(e)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new ti(ei.ServerError,r)}}function il(e,t,n){let r=e.invalidateCredentials===void 0?`retrying authorization without discarding the stored ${n} (provider implements no invalidateCredentials())`:`invalidating the stored ${n} and retrying authorization`;console.warn(`[mcp-sdk] OAuth ${JSON.stringify(t.code)} — ${r}. Cause: ${JSON.stringify(t.message)}`)}async function al(e,t){try{return await sl(e,t)}catch(n){if(n instanceof ti){if(n.code===ei.InvalidClient||n.code===ei.UnauthorizedClient)return il(e,n,`client credentials and tokens`),await e.invalidateCredentials?.(`client`),await e.invalidateCredentials?.(`tokens`),await sl(e,t);if(n.code===ei.InvalidGrant||n.code===ei.InvalidDpopProof)return il(e,n,`tokens`),await e.invalidateCredentials?.(`tokens`),await sl(e,t)}throw n}}function ol(e){let{requestedScope:t,resourceMetadata:n,authServerMetadata:r,clientMetadata:i}=e,a=t||n?.scopes_supported?.join(` `)||i.scope;return a&&r?.scopes_supported?.includes(`offline_access`)&&!a.split(` `).includes(`offline_access`)&&i.grant_types?.includes(`refresh_token`)&&(a=`${a} offline_access`),a}async function sl(e,{serverUrl:t,authorizationCode:n,iss:r,scope:i,resourceMetadataUrl:a,fetchFn:o,skipIssuerMetadataValidation:s,forceReauthorization:c}){let l=nl(e),u=await e.discoveryState?.(),d,f,p,m,h=a;if(!h&&u?.resourceMetadataUrl&&(h=new URL(u.resourceMetadataUrl)),u?.authorizationServerUrl){if(f=u.authorizationServerUrl,d=u.resourceMetadata,p=u.authorizationServerMetadata??await bl(f,{fetchFn:o,skipIssuerValidation:s}),!d)try{d=await pl(t,{resourceMetadataUrl:h},o)}catch(e){if(e instanceof TypeError)throw e}(p!==u.authorizationServerMetadata||d!==u.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(f),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:p})}else{let e=await xl(t,{resourceMetadataUrl:h,fetchFn:o,skipIssuerMetadataValidation:s});f=e.authorizationServerUrl,p=e.authorizationServerMetadata,d=e.resourceMetadata,m={authorizationServerUrl:String(f),resourceMetadataUrl:h?.toString(),resourceMetadata:d,authorizationServerMetadata:p}}let g=p?.issuer??String(f),_={issuer:g};if(await e.saveAuthorizationServerUrl?.(g),n!==void 0){let t=u?.authorizationServerMetadata?.issuer??u?.authorizationServerUrl;if(t===void 0){if(e.saveDiscoveryState!==void 0)throw new Mc(`discoveryState was not available on the callback leg; ensure your provider persists discoveryState alongside codeVerifier`,g);console.warn(`[mcp-sdk] OAuthClientProvider does not implement saveDiscoveryState()/discoveryState(); the SEP-2352 callback-leg authorization-server binding cannot be checked. Implement discoveryState (persist alongside codeVerifier) — see docs/migration/upgrade-to-v2.md §SEP-2352.`)}else if(!Fc(t,g))throw new Mc(t,g)}m&&await e.saveDiscoveryState?.(m);let v=await ll(t,e,d),y=v&&d&&!e.validateResourceURL?d.resource:v;y&&await e.saveResourceUrl?.(Sl(y));let b=ol({requestedScope:i,resourceMetadata:d,authServerMetadata:p,clientMetadata:e.clientMetadata}),ee=await Promise.resolve(e.clientInformation(_)),x=Pc(ee,g,{canPersistStamp:e.saveClientInformation!==void 0});if(x===void 0&&ee?.issuer&&e.saveClientInformation===void 0)throw new Mc(ee.issuer,g);if(x&&x.issuer===void 0&&(x={...x,issuer:g},await e.saveClientInformation?.(x,_)),!x){if(n!==void 0)throw Error(`Existing OAuth client information is required when exchanging an authorization code`);let t=p?.client_id_metadata_document_supported===!0,r=e.clientMetadataUrl;if(r&&!cl(r))throw new ti(ei.InvalidClientMetadata,`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${r}`);if(t&&r)x={client_id:r,issuer:g},await e.saveClientInformation?.(x,_);else{if(!e.saveClientInformation)throw Error(`OAuth client information must be saveable for dynamic registration`);x={...await Ol(f,{metadata:p,clientMetadata:l,scope:b,fetchFn:o}),issuer:g},await e.saveClientInformation(x,_)}}let S=!e.redirectUrl;if(n!==void 0||S){n!==void 0&&Vc({iss:r,expectedIssuer:p?.issuer,issParameterSupported:Bc(p)});let t=await Dl(e,f,{metadata:p,resource:y,authorizationCode:n,iss:r,scope:b,fetchFn:o});return await e.saveTokens({...t,issuer:g},_),`AUTHORIZED`}let C=Pc(await e.tokens(_),g);if(C&&C.issuer===void 0&&(C={...C,issuer:g},await e.saveTokens(C,_)),C?.refresh_token&&!c){let t;try{t=await El(f,{metadata:p,clientInformation:x,refreshToken:C.refresh_token,resource:y,addClientAuthentication:e.addClientAuthentication,dpop:await e.dpop?.(),fetchFn:o})}catch(e){if(e instanceof jc)throw e;if(!(e instanceof ti)||e.code===ei.ServerError)console.warn(`[mcp-sdk] Could not refresh OAuth tokens; falling back to a new authorization request. Cause: ${JSON.stringify(e instanceof Error?e.message:String(e))}`);else throw e}if(t)return await e.saveTokens({...t,issuer:g},_),`AUTHORIZED`}let w=e.state?await e.state():void 0,{authorizationUrl:T,codeVerifier:E}=await Cl(f,{metadata:p,clientInformation:x,state:w,redirectUrl:e.redirectUrl,scope:b,resource:y});return await e.saveCodeVerifier(E),await e.redirectToAuthorization(T),`REDIRECT`}function cl(e){if(!e)return!1;try{let t=new URL(e);return t.protocol===`https:`&&t.pathname!==`/`}catch{return!1}}async function ll(e,t,n){let r=ri(e);if(t.validateResourceURL)return await t.validateResourceURL(r,n?.resource);if(n){if(!ai({requestedResource:r,configuredResource:n.resource}))throw Error(`Protected resource ${n.resource} does not match expected ${r} (or origin)`);return new URL(n.resource)}}var ul=new Set([`bearer`,`dpop`]);function dl(e){let t=e.headers.get(`WWW-Authenticate`);if(!t)return{};let[n,r]=t.split(` `);if(!n||!ul.has(n.toLowerCase())||!r)return{};let i=fl(e,`resource_metadata`)||void 0,a;if(i)try{a=new URL(i)}catch{}let o=fl(e,`scope`)||void 0,s=fl(e,`error`)||void 0,c=fl(e,`error_description`)||void 0;return{resourceMetadataUrl:a,scope:o,error:s,errorDescription:c}}function fl(e,t){let n=e.headers.get(`WWW-Authenticate`);if(!n)return null;let r=new RegExp(String.raw`${t}=(?:"([^"]+)"|([^\s,]+))`),i=n.match(r);if(i){let e=i[1]||i[2];if(e)return e}return null}async function pl(e,t,n=fetch){let r=await vl(e,`oauth-protected-resource`,n,{protocolVersion:t?.protocolVersion,metadataUrl:t?.resourceMetadataUrl});if(!r||r.status===404)throw await r?.text?.().catch(()=>{}),Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);if(!r.ok)throw await r.text?.().catch(()=>{}),Error(`HTTP ${r.status} trying to load well-known OAuth protected resource metadata.`);return Rr.parse(await r.json())}async function ml(e,t,n=fetch){let r=Ds(n);try{return await r(e,{headers:t})}catch(n){if(!(n instanceof TypeError))throw n;if(t)try{return await r(e,{})}catch(e){if(!(e instanceof TypeError))throw e;return}return}}function hl(e,t=``,n={}){return t.endsWith(`/`)&&(t=t.slice(0,-1)),n.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}async function gl(e,t,n=fetch){return await ml(e,{"MCP-Protocol-Version":t},n)}function _l(e,t){return e?t===`/`?!1:!e.ok&&e.status<500||e.status===502:!0}async function vl(e,t,n,r){let i=new URL(e),a=r?.protocolVersion??`2025-11-25`,o;if(r?.metadataUrl)o=new URL(r.metadataUrl);else{let e=hl(t,i.pathname);o=new URL(e,r?.metadataServerUrl??i),o.search=i.search}let s=await gl(o,a,n);return!r?.metadataUrl&&_l(s,i.pathname)&&(s=await gl(new URL(`/.well-known/${t}`,i),a,n)),s}function yl(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`},{url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`},{url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function bl(e,{fetchFn:t=fetch,protocolVersion:n=Ne,skipIssuerValidation:r=!1}={}){let i={"MCP-Protocol-Version":n,Accept:`application/json`},a=yl(e);for(let{url:n,type:o}of a){let a=await ml(n,i,t);if(!a)continue;if(!a.ok){if(await a.text?.().catch(()=>{}),a.status<500||a.status===502)continue;throw Error(`HTTP ${a.status} trying to load ${o===`oauth`?`OAuth`:`OpenID provider`} metadata from ${n}`)}let s=o===`oauth`?zr.parse(await a.json()):Vr.parse(await a.json());if(!r){let t=typeof e==`string`?e:e.href;if(!(s.issuer===t||t.endsWith(`/`)&&s.issuer===t.slice(0,-1)))throw new kc(`metadata`,t,s.issuer)}return s}}async function xl(e,t){let n,r;try{n=await pl(e,{resourceMetadataUrl:t?.resourceMetadataUrl},t?.fetchFn),n.authorization_servers&&n.authorization_servers.length>0&&(r=n.authorization_servers[0])}catch(e){if(e instanceof TypeError)throw e}r||=String(new URL(`/`,e));let i=await bl(r,{fetchFn:t?.fetchFn,skipIssuerValidation:t?.skipIssuerMetadataValidation});return{authorizationServerUrl:r,authorizationServerMetadata:i,resourceMetadata:n}}function Sl(e){return typeof e==`string`?e:e.href}async function Cl(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Kc))throw Error(`Incompatible auth server: does not support response type ${Kc}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(qc))throw Error(`Incompatible auth server: does not support code challenge method ${qc}`)}else s=new URL(`/authorize`,e);let c=await vc(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,Kc),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,qc),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.split(` `).includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,Sl(o)),{authorizationUrl:s,codeVerifier:l}}function wl(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function Tl(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,dpop:o,fetchFn:s}){let c=el(t?.token_endpoint??new URL(`/token`,e)),l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,Sl(a)),!i&&r&&Yc(Jc(r,t?.token_endpoint_auth_methods_supported??[]),r,l,n);let u=async()=>{let e=new Headers(l);return i&&await i(e,n,c,t),o&&e.set(`DPoP`,await o.buildProof({htm:`POST`,htu:c})),Ds(s??fetch)(c,{method:`POST`,headers:e,body:n})},d=await u();if(o&&d.status===400&&(await d.clone().json().catch(()=>{}))?.error===ei.UseDpopNonce&&(o.observeNonce(d,c),d=await u()),o?.observeNonce(d,c),!d.ok)throw await rl(d);let f=await d.json();try{return Hr.parse(ii(f))}catch(e){throw typeof f==`object`&&f&&`error`in f?await rl(JSON.stringify(f)):e}}async function El(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,dpop:o,fetchFn:s}){return{refresh_token:r,...await Tl(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,dpop:o,fetchFn:s})}}async function Dl(e,t,{metadata:n,resource:r,authorizationCode:i,iss:a,scope:o,fetchFn:s}={}){i!==void 0&&Vc({iss:a,expectedIssuer:n?.issuer,issParameterSupported:Bc(n)});let c=n?.issuer??String(t),l=async()=>{let t=await e.clientInformation({issuer:c}),n=Pc(t,c,{canPersistStamp:!1});if(t&&n===void 0)throw new Mc(String(t.issuer),c);return n},u=await l(),d=o??e.clientMetadata.scope,f;if(e.prepareTokenRequest&&(f=await e.prepareTokenRequest(d)),!f){if(!i)throw Error(`Either provider.prepareTokenRequest() or authorizationCode is required`);if(!e.redirectUrl)throw Error(`redirectUrl is required for authorization_code flow`);f=wl(i,await e.codeVerifier(),e.redirectUrl)}return u??=await l(),Tl(t,{metadata:n,tokenRequestParams:f,clientInformation:u,addClientAuthentication:e.addClientAuthentication,resource:r,dpop:await e.dpop?.(),fetchFn:s})}async function Ol(e,{metadata:t,clientMetadata:n,scope:r,fetchFn:i}){let a;if(t){if(!t.registration_endpoint)throw Error(`Incompatible auth server: does not support dynamic client registration`);a=new URL(t.registration_endpoint)}else a=new URL(`/register`,e);let o={...n,...r===void 0?{}:{scope:r}},s=await Ds(i??fetch)(a,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(o)});if(!s.ok)throw new Ac({status:s.status,body:await s.text(),submittedMetadata:o});return Jr.parse(ii(await s.json()))}var kl=new Set([`tools/list`,`prompts/list`,`resources/list`,`resources/templates/list`,`server/discover`]),Al=class{_entries=new Map;_maxEntries;_stamp=0;_cappedSize=0;constructor(e){this._maxEntries=e?.maxEntries??512}get size(){return this._entries.size}get(e){return this._entries.get(jl(e))}set(e,t){let n=jl(e),r=kl.has(e.method),i=!this._entries.has(n);if(!r&&i&&this._maxEntries>0&&this._cappedSize>=this._maxEntries){for(let e of this._entries.keys())if(!kl.has(e.slice(0,e.indexOf(`\0`)))){this._entries.delete(e),this._cappedSize--;break}}let a=++this._stamp;return this._entries.set(n,{...t,stamp:a}),i&&!r&&this._cappedSize++,a}delete(e){this._entries.delete(jl(e))&&!kl.has(e.method)&&this._cappedSize--}evict(e){let t=`${e}\0`,n=kl.has(e);for(let e of this._entries.keys())e.startsWith(t)&&(this._entries.delete(e),n||this._cappedSize--)}clear(){this._entries.clear(),this._cappedSize=0}};function jl(e){return`${e.method}\0${JSON.stringify([e.partition??``,e.params??``])}`}function Ml(e,t){return t===void 0?e:`${e}\0${t}`}var Nl=864e5,Pl=class{_evictionGeneration=new Map;_toolIndex;_toolOutputValidatorIndex;_serverIdentity=``;constructor(e,t,n=()=>{},r=``,i=Date.now){this._store=e,this._isUserSupplied=t,this._reportError=n,this._cachePartition=r,this._now=i}now(){return this._now()}setServerIdentity(e){this._serverIdentity=e}_partitionFor(e){return JSON.stringify([this._serverIdentity,e===`public`?``:this._cachePartition])}async _probe(e,t){let n={method:e,params:t??``},r=this._partitionFor(`private`),i=await this._store.get({...n,partition:r});if(i!==void 0)return i;let a=this._partitionFor(`public`);if(a===r)return;let o=await this._store.get({...n,partition:a});return o?.scope===`public`?o:void 0}async evict(e){this._evictionGeneration.set(e,(this._evictionGeneration.get(e)??0)+1),await this._deleteBoth(e,``)}async _deleteBoth(e,t){let n=this._partitionFor(`private`),r=this._partitionFor(`public`);try{await this._store.delete({method:e,params:t,partition:n})}catch(e){this._reportError(e)}if(r!==n)try{await this._store.delete({method:e,params:t,partition:r})}catch(e){this._reportError(e)}}async evictKey(e,t){let n=Ml(e,t),r=this._evictionGeneration.get(n);r!==void 0&&this._evictionGeneration.set(n,r+1),await this._deleteBoth(e,t)}captureGeneration(e,t){let n=Ml(e,t),r=this._evictionGeneration.get(n)??0;return this._evictionGeneration.set(n,r),r}async write(e,t,n,r){if((this._evictionGeneration.get(Ml(e,r?.params))??0)!==n)return;let i=r?.params??``,a=this._partitionFor(`private`),o=this._partitionFor(`public`),s=(r?.scope??`private`)===`public`?o:a;try{await this._store.set({method:e,params:i,partition:s},{value:Fl(t),expiresAt:r?.expiresAt,scope:r?.scope})}catch(e){this._reportError(e)}if(o!==a)try{await this._store.delete({method:e,params:i,partition:s===a?o:a})}catch(e){this._reportError(e)}}async read(e,t){let n=await this._probe(e,t);if(n?.expiresAt!==void 0&&n.expiresAt>this.now())try{let e=JSON.parse(n.value);if(typeof e!=`object`||!e||Array.isArray(e))throw TypeError(`cached document is not an object`);return{value:e}}catch(n){this._reportError(n),await this._deleteBoth(e,t??``);return}}resetForReconnect(){this._isUserSupplied||this._store.clear(),this._evictionGeneration.clear(),this._toolIndex=void 0,this._toolOutputValidatorIndex=void 0,this._serverIdentity=``}async toolDefinition(e){let t=await this._probe(`tools/list`);if(t===void 0){this._toolIndex=void 0;return}if(this._toolIndex?.stamp!==t.stamp){let e=this._decodeListTools(t),n=new Map;if(e!==void 0)for(let t of e.tools)n.set(t.name,t);this._toolIndex={stamp:t.stamp,byName:n}}return this._toolIndex.byName.get(e)}async outputValidator(e,t){let n=await this._probe(`tools/list`);if(n===void 0){this._toolOutputValidatorIndex=void 0;return}if(this._toolOutputValidatorIndex?.stamp!==n.stamp){let e=this._decodeListTools(n)??{tools:[]},r=new Map;for(let n of e.tools){let e=t(n);e!==void 0&&r.set(n.name,e)}this._toolOutputValidatorIndex={stamp:n.stamp,byName:r}}return this._toolOutputValidatorIndex.byName.get(e)}_decodeListTools(e){try{let t=JSON.parse(e.value);if(!Array.isArray(t?.tools)||!t.tools.every(e=>typeof e==`object`&&!!e))throw TypeError(`cached tools/list document has a malformed tools array`);return t}catch(e){this._reportError(e);return}}};function Fl(e){let t;try{t=JSON.stringify(e)}catch(e){throw TypeError(`cache value is not JSON-serializable: ${e instanceof Error?e.message:String(e)}`)}if(typeof t!=`string`)throw TypeError(`cache value is not JSON-serializable: it has no JSON representation`);return t}var Il=Symbol.for(`mcp.authSeamEscape`);function Ll(e){if(typeof e==`object`&&e||typeof e==`function`)try{Object.defineProperty(e,Il,{value:!0,configurable:!0})}catch{}return e}function Rl(e){return(typeof e==`object`&&!!e||typeof e==`function`)&&e[Il]===!0}var zl=-32022,Bl=new Set([-32001,-32020,-32021]);function Vl(e,t){switch(e.kind){case`result`:return Hl(e.result,t);case`rpc-error`:return Ul(e,t);case`http-error`:return Wl(e,t);case`network-error`:return Gl(e.error,t);case`unusable-reply`:return{kind:`error`,error:new Y(J.EraNegotiationFailed,`Version negotiation probe failed: the server answered with an unusable reply (${ql(e.error)})`,{cause:e.error},{cause:e.error})};case`auth-required`:return{kind:`error`,error:e.error};case`closed`:return t.transportKind===`stdio`?{kind:`legacy`}:Gl(Error(`Connection closed during the version negotiation probe`),t);case`timeout`:return t.transportKind===`stdio`?{kind:`legacy`}:{kind:`error`,error:new Y(J.RequestTimeout,`Version negotiation probe timed out after ${e.timeoutMs}ms`,{timeout:e.timeoutMs})}}}function Hl(e,t){let n=ja(Aa).validateResult(`server/discover`,e);if(!n.ok)return{kind:`legacy`};let r=n.value.supportedVersions,i=t.clientModernVersions.find(e=>r.includes(e));return i===void 0?t.fallbackAvailable?{kind:`legacy`}:{kind:`error`,error:new Xi({supported:[...r],requested:t.requestedVersion})}:{kind:`modern`,version:i,discover:n.value}}function Ul(e,t){let{code:n,message:r,data:i}=e;if(n===zl){let e=Jl(i);if(e===void 0)return{kind:`legacy`};let n=new Xi({supported:e,requested:Yl(i)??t.requestedVersion},r),a=ui(e),o=t.clientModernVersions.find(e=>a.includes(e));return o===void 0?a.length>0?{kind:`error`,error:n}:t.fallbackAvailable?{kind:`legacy`}:{kind:`error`,error:n}:{kind:`corrective`,version:o,error:n}}return Bl.has(n),{kind:`legacy`}}function Wl(e,t){if(e.status===401||e.status===403){let t=e.status===403;return{kind:`error`,error:new ni(t?J.ClientHttpForbidden:J.ClientHttpAuthentication,`Version negotiation failed: ${t?`the server denied access (HTTP 403)`:`the server requires authorization (HTTP 401)`}`,{status:e.status,statusText:e.statusText,text:e.body})}}if(e.status>=500)return{kind:`error`,error:new ni(J.EraNegotiationFailed,`Version negotiation failed: the server answered the probe with HTTP ${e.status}`,{status:e.status,statusText:e.statusText,text:e.body})};let n=Xl(e.body);return n===void 0?{kind:`legacy`}:Ul(n,t)}function Gl(e,t){return t.environment===`browser`&&Kl(e)?{kind:`legacy`}:{kind:`error`,error:new Y(J.EraNegotiationFailed,`Version negotiation probe failed: ${ql(e)}`,{cause:e},{cause:e})}}function Kl(e){return e instanceof TypeError||e instanceof Error&&e.name===`TypeError`}function ql(e){return e instanceof Error?e.message:String(e)}function Jl(e){if(typeof e!=`object`||!e)return;let t=e.supported;if(Array.isArray(t)&&t.length!==0&&t.every(e=>typeof e==`string`))return t}function Yl(e){if(typeof e!=`object`||!e)return;let t=e.requested;return typeof t==`string`?t:void 0}function Xl(e){if(e===void 0||e===``)return;let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t)return;let n=t.error;if(typeof n!=`object`||!n)return;let{code:r,message:i,data:a}=n;if(typeof r==`number`)return{code:r,message:typeof i==`string`?i:``,data:a}}var Zl=`legacy`;function Ql(e,t){let n=e?.mode??Zl;if(n===`legacy`)return{kind:`legacy`};let r=e?.probe??{};if(typeof n==`object`){if(!ci(n.pin))throw TypeError(`versionNegotiation: { pin: '${n.pin}' } is not a modern protocol revision — pinning is for 2026-07-28 and later; omit versionNegotiation (or use mode: 'legacy') for 2025-era servers.`);return{kind:`pin`,version:n.pin,probe:r}}let i=t?ui(t):[];return{kind:`auto`,modernVersions:i.length>0?i:[...si],fallbackAvailable:!t||li(t).length>0,probe:r}}function $l(){let e=globalThis;return e.window!==void 0&&e.document!==void 0?`browser`:`node`}function eu(e){return`stderr`in e&&`pid`in e?`stdio`:`http`}var tu=class e{_pending;_probeCounter=0;_savedOnMessage;_savedOnError;_savedOnClose;_closeDelivered=!1;constructor(e){this._transport=e,this._savedOnMessage=e.onmessage,this._savedOnError=e.onerror,this._savedOnClose=e.onclose}static async open(t){let n=new e(t);t.onmessage=e=>{let t=n._pending;if(t!==void 0&&(Ba(e)||Va(e))&&e.id===t.id){n._pending=void 0,Ba(e)?t.resolve({kind:`response`,result:e.result}):t.resolve({kind:`response`,error:e.error});return}},t.onerror=e=>{n._savedOnError?.(e)},t.onclose=()=>{let e=n._pending;e!==void 0&&(n._pending=void 0,e.resolve({kind:`closed`})),n._closeDelivered=!0,n._savedOnClose?.()};try{await t.start()}catch(e){throw n.detach(),e}return n}async exchange(e,t){let n=`server-discover-probe-${++this._probeCounter}`;return new Promise(r=>{let i=!1,a=e=>{i||(i=!0,clearTimeout(o),this._pending?.id===n&&(this._pending=void 0),r(e))},o=setTimeout(()=>a({kind:`timeout`}),t);this._pending={id:n,resolve:a},this._transport.send(e(n)).catch(e=>a({kind:`send-error`,error:e}))})}detach(){if(this._pending=void 0,this._transport.onmessage=this._savedOnMessage,this._transport.onerror=this._savedOnError,this._closeDelivered&&this._savedOnClose!==void 0){let e=this._savedOnClose,t=this._transport,n=!1,r=()=>{if(!n){n=!0;return}e()};t.onclose=r,nu.set(t,()=>{t.onclose===r&&(t.onclose=e)})}else this._transport.onclose=this._savedOnClose}release(){this.detach();let e=this._transport,t=e.start,n=!0;e.start=async function(){if(n){n=!1,e.start=t;return}return t.call(e)}}},nu=new WeakMap;function ru(e){let t=nu.get(e);nu.delete(e),t?.()}function iu(e,t,n,r){return{jsonrpc:`2.0`,id:e,method:`server/discover`,params:{_meta:ja(t).outboundEnvelope({protocolVersion:t,clientInfo:n,clientCapabilities:r})}}}function au(e){return e instanceof Y&&e.code===J.ClientHttpUnexpectedContent||e instanceof Error&&e.name===`SyntaxError`}function ou(e,t){switch(e.kind){case`response`:return e.error===void 0?{kind:`result`,result:e.result}:{kind:`rpc-error`,...e.error};case`send-error`:{let t=e.error;if(Rl(t)||t instanceof zc||t instanceof Error&&t.name===`UnauthorizedError`)return{kind:`auth-required`,error:t};if(t instanceof ni){let e=t.data?.text;return{kind:`http-error`,status:t.data.status,body:typeof e==`string`?e:void 0,statusText:t.data.statusText}}return au(t)?{kind:`unusable-reply`,error:t}:{kind:`network-error`,error:t}}case`closed`:return{kind:`closed`};case`timeout`:return{kind:`timeout`,timeoutMs:t}}}async function su(e,t){let n=e.probe.timeoutMs??t.defaultTimeoutMs,r=Math.max(0,e.probe.maxRetries??0),i=e.kind===`pin`?[e.version]:e.modernVersions,a=e.kind===`auto`&&e.fallbackAvailable,o=await tu.open(t.transport),s=async()=>{let s=i[0],c=!1,l=r;for(;;){let r=await o.exchange(e=>iu(e,s,t.clientInfo,t.capabilities),n);if(r.kind===`timeout`&&l>0){l--;continue}let u=ou(r,n),d=Vl(u,{clientModernVersions:i,requestedVersion:s,fallbackAvailable:a,environment:t.environment,transportKind:t.transportKind});switch(d.kind){case`modern`:return{era:`modern`,version:d.version,discover:d.discover};case`corrective`:if(c)throw d.error;c=!0,s=d.version;continue;case`legacy`:{let n=u.kind===`closed`?`the connection closed during the server/discover probe`:void 0;if(e.kind===`pin`)throw new Y(J.EraNegotiationFailed,n===void 0?`Version negotiation failed: the server did not offer pinned protocol version ${e.version} via server/discover (no fallback in pin mode)`:`Version negotiation failed: ${n} before the server offered pinned protocol version ${e.version} (no fallback in pin mode)`);if(!e.fallbackAvailable)throw new Y(J.EraNegotiationFailed,n===void 0?`Version negotiation failed: the server gave no modern evidence and this client supports no pre-2026-07-28 protocol version to fall back to`:`Version negotiation failed: ${n} and this client supports no pre-2026-07-28 protocol version to fall back to`);if(n!==void 0&&t.disposableProbe!==!0)throw new Y(J.EraNegotiationFailed,`Version negotiation failed: ${n} (this transport probed in place — the disposable sibling probe requires the SDK's base StdioClientTransport)`);return{era:`legacy`}}case`error`:throw d.error}}},c;try{c=await s()}catch(e){throw o.detach(),e}return o.release(),c}function cu(e){let t=Object.getPrototypeOf(e);if(t===null||!Object.prototype.hasOwnProperty.call(t,`_dispose`))return;let n=e._serverParams;return typeof n==`object`&&n&&typeof n.command==`string`?n:void 0}async function lu(e,t,n,r){let i=t.constructor,a=new i({...n,stderr:`ignore`}),o=t.close,s=!1,c,l=new Promise((e,t)=>{c=()=>t(uu())});t.close=async function(){return s=!0,c?.(),o.call(t)};let u;try{let t=su(e,{...r,transport:a,transportKind:`stdio`,disposableProbe:!0});t.catch(()=>{}),u=await Promise.race([t,l])}finally{await du(a),t.close=o}if(s)throw uu();return u}function uu(){return new Y(J.EraNegotiationFailed,`Version negotiation failed: the transport was closed during the server/discover probe`)}async function du(e){try{let t=e._dispose;await(typeof t==`function`?t.call(e):e.close())}catch{}}function fu(e){let t=e._meta?.[Re];return Qo.Implementation(t)?t:void 0}function pu(e,t){if(e&&typeof t==`object`&&t){if(e.type===`object`&&e.properties&&typeof e.properties==`object`){let n=t,r=e.properties;for(let e of Object.keys(r)){let t=r[e];n[e]===void 0&&Object.prototype.hasOwnProperty.call(t,`default`)&&(n[e]=t.default),n[e]!==void 0&&pu(t,n[e])}}if(Array.isArray(e.anyOf))for(let n of e.anyOf)typeof n!=`boolean`&&pu(n,t);if(Array.isArray(e.oneOf))for(let n of e.oneOf)typeof n!=`boolean`&&pu(n,t)}}function mu(e){if(!e)return{supportsFormMode:!1,supportsUrlMode:!1};let t=e.form!==void 0,n=e.url!==void 0;return{supportsFormMode:t||!t&&!n,supportsUrlMode:n}}function hu(e){if(typeof e==`object`&&e&&(e.kind===`legacy`&&!(`supportedVersions`in e)&&!(`discover`in e)||e.kind===`modern`&&bt.safeParse(e.discover).success))return e;throw new Y(J.EraNegotiationFailed,`connect({ prior }): unrecognized prior — expected { kind: 'modern', discover } or { kind: 'legacy' }`)}var gu={"notifications/tools/list_changed":[`tools/list`],"notifications/prompts/list_changed":[`prompts/list`],"notifications/resources/list_changed":[`resources/list`,`resources/templates/list`]},_u=64,vu=class extends os{_serverCapabilities;_serverVersion;_capabilities;_instructions;_jsonSchemaValidator;_cache;_defaultCacheTtlMs;_listMaxPages;_listChangedDebounceTimers=new Map;_listChangedConfig;_enforceStrictCapabilities;_versionNegotiation;_supportedProtocolVersionsOption;_inputRequiredDriverConfig;_listenState=new Map;_nextListenId=0;_autoOpenedSubscription;_discoverResult;_resetConnectionState(){if(this._negotiatedProtocolVersion=void 0,this._serverCapabilities=void 0,this._serverVersion=void 0,this._instructions=void 0,this._discoverResult=void 0,this._autoOpenedSubscription=void 0,this._listenState.size>0){let e=new Y(J.ConnectionClosed,`subscriptions/listen: client reconnected or closed; subscription state from the previous connection was reset`);for(let t of this._listenState.values())t.settle({cause:`remote`,error:e})}this._listenState.clear();for(let e of this._listChangedDebounceTimers.values())clearTimeout(e);this._listChangedDebounceTimers.clear(),this._cache.resetForReconnect()}async close(){try{await super.close()}finally{this._resetConnectionState()}}constructor(e,t){super(t),this._clientInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new fc,this._enforceStrictCapabilities=t?.enforceStrictCapabilities??!1,this._versionNegotiation=t?.versionNegotiation,this._supportedProtocolVersionsOption=t?.supportedProtocolVersions,this._inputRequiredDriverConfig=Vo(t?.inputRequired),this._cache=new Pl(t?.responseCacheStore??new Al,t?.responseCacheStore!==void 0,e=>this._reportStoreError(e),t?.cachePartition??``),this._defaultCacheTtlMs=t?.defaultCacheTtlMs??0,this._listMaxPages=t?.listMaxPages??_u,t?.listChanged&&(this._listChangedConfig=t.listChanged)}buildContext(e,t){return e}_shouldDropInbound(e){if(this._negotiatedProtocolVersion!==void 0&&ci(this._negotiatedProtocolVersion)&&Ra(e))return`drop`}_outboundMetaEnvelope(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return this._wireCodec().outboundEnvelope({protocolVersion:e,clientInfo:this._clientInfo,clientCapabilities:this._capabilities})}_resolveNonCompleteResult(e,t){return this._inputRequiredDriverConfig.autoFulfill?hs({getRequestHandler:e=>this._getRequestHandler(e),buildContext:e=>this.buildContext(e,void 0),sessionId:this.transport?.sessionId},this._inputRequiredDriverConfig,e,t):Promise.reject(new Y(J.UnsupportedResultType,`Unsupported result type 'input_required' for ${t.request.method}: multi-round-trip auto-fulfilment is not enabled on this instance — pass allowInputRequired: true to handle it manually, or enable inputRequired.autoFulfill`,{resultType:`input_required`,method:t.request.method}))}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler(`tools`,`notifications/tools/list_changed`,e.tools,async()=>(await this.listTools(void 0,{cacheMode:`refresh`})).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler(`prompts`,`notifications/prompts/list_changed`,e.prompts,async()=>(await this.listPrompts(void 0,{cacheMode:`refresh`})).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler(`resources`,`notifications/resources/list_changed`,e.resources,async()=>(await this.listResources(void 0,{cacheMode:`refresh`})).resources)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=cs(this._capabilities,e)}setVersionNegotiation(e){if(this.transport)throw Error(`Cannot configure version negotiation after connecting to transport`);this._versionNegotiation=e}_wrapHandler(e,t){return e===`elicitation/create`?async(e,n)=>{let r=ja(this._negotiatedProtocolVersion),i=r.validateRequest(`elicitation/create`,e);if(!i.ok&&i.reason===`not-in-era`&&(i=r.validateInputRequest(`elicitation/create`,e)),!i.ok)throw new Z(i.reason===`not-in-era`?X.InternalError:X.InvalidParams,i.reason===`not-in-era`?`No wire schema for elicitation/create in the resolved era`:`Invalid elicitation request: ${i.message}`);let{params:a}=i.value;a.mode=a.mode??`form`;let{supportsFormMode:o,supportsUrlMode:s}=mu(this._capabilities.elicitation);if(a.mode===`form`&&!o)throw new Z(X.InvalidParams,`Client does not support form-mode elicitation requests`);if(a.mode===`url`&&!s)throw new Z(X.InvalidParams,`Client does not support URL-mode elicitation requests`);let c=await t(e,n),l=r.validateResult(`elicitation/create`,c);if(!l.ok&&l.reason===`not-in-era`&&(l=r.validateInputResponse(`elicitation/create`,c)),!l.ok)throw new Z(l.reason===`not-in-era`?X.InternalError:X.InvalidParams,l.reason===`not-in-era`?`No wire schema for elicitation/create in the resolved era`:`Invalid elicitation result: ${l.message}`);let u=l.value,d=a.mode===`form`?a.requestedSchema:void 0;if(a.mode===`form`&&u.action===`accept`&&u.content&&d&&this._capabilities.elicitation?.form?.applyDefaults)try{pu(d,u.content)}catch{}return u}:e===`sampling/createMessage`?async(e,n)=>{let r=ja(this._negotiatedProtocolVersion),i=r.validateRequest(`sampling/createMessage`,e);if(!i.ok&&i.reason===`not-in-era`&&(i=r.validateInputRequest(`sampling/createMessage`,e)),!i.ok)throw new Z(i.reason===`not-in-era`?X.InternalError:X.InvalidParams,i.reason===`not-in-era`?`No wire schema for sampling/createMessage in the resolved era`:`Invalid sampling request: ${i.message}`);let{params:a}=i.value,o=await t(e,n),s=!!(a.tools||a.toolChoice),c=r.samplingResultVariant(s,o);if(!c.ok&&c.reason===`not-in-era`&&(c=r.validateInputResponse(`sampling/createMessage`,o)),!c.ok)throw new Z(c.reason===`not-in-era`?X.InternalError:X.InvalidParams,c.reason===`not-in-era`?`No result schema for sampling/createMessage in the resolved era`:`Invalid sampling result: ${c.message}`);return c.value}:t}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Y(J.CapabilityNotSupported,`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(t?.prior!=null)return this._connectFromPrior(e,hu(t.prior),t);let n=Ql(this._versionNegotiation,this._supportedProtocolVersionsOption);return n.kind===`legacy`?this._connectPlainLegacy(e,t):this._connectNegotiated(e,n,t)}async _connectPlainLegacy(e,t){if(await super.connect(e),e.sessionId!==void 0){let t=this._negotiatedProtocolVersion;t!==void 0&&e.setProtocolVersion?.(t);return}this._resetConnectionState(),await this._legacyHandshake(e,t)}async _legacyHandshake(e,t){let n=li(this._supportedProtocolVersions);try{let r=n[0];if(r===void 0)throw new Y(J.EraNegotiationFailed,`Cannot run the initialize handshake: supportedProtocolVersions contains no pre-2026-07-28 protocol version`);let i=await this.request({method:`initialize`,params:{protocolVersion:r,capabilities:this._capabilities,clientInfo:this._clientInfo}},t);if(i===void 0)throw Error(`Server sent invalid initialize result: ${i}`);if(!n.includes(i.protocolVersion))throw Error(`Server's protocol version is not supported: ${i.protocolVersion}`);this._serverCapabilities=i.capabilities,this._serverVersion=i.serverInfo,this._cache.setServerIdentity(this._deriveServerIdentity(e)),e.setProtocolVersion&&e.setProtocolVersion(i.protocolVersion),this._instructions=i.instructions,await this.notification({method:`notifications/initialized`}),this._negotiatedProtocolVersion=i.protocolVersion,this._listChangedConfig&&this._setupListChangedHandlers(this._listChangedConfig)}catch(e){throw this.close(),e}}async _connectNegotiated(e,t,n){if(e.sessionId!==void 0){await super.connect(e);let t=this._negotiatedProtocolVersion;t!==void 0&&e.setProtocolVersion&&e.setProtocolVersion(t);return}this._resetConnectionState();let r;try{let i=eu(e),a={clientInfo:this._clientInfo,capabilities:this._capabilities,environment:$l(),defaultTimeoutMs:n?.timeout??6e4},o=i===`stdio`?cu(e):void 0;r=o===void 0?await su(t,{...a,transport:e,transportKind:i}):await lu(t,e,o,a)}catch(t){throw await e.close().catch(()=>{}),ru(e),t}if(ru(e),await super.connect(e),r.era===`legacy`){await this._legacyHandshake(e,n);return}if(this._serverCapabilities=r.discover.capabilities,this._serverVersion=fu(r.discover),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=r.discover.instructions,this._discoverResult=r.discover,this._negotiatedProtocolVersion=r.version,e.setProtocolVersion&&e.setProtocolVersion(r.version),this._listChangedConfig){let e=this._listChangedConfig,t=this._serverCapabilities,r={...e.tools&&t?.tools?.listChanged&&{tools:e.tools},...e.prompts&&t?.prompts?.listChanged&&{prompts:e.prompts},...e.resources&&t?.resources?.listChanged&&{resources:e.resources}},i=!0;try{this._setupListChangedHandlers(r)}catch(e){i=!1,this.onerror?.(e instanceof Error?e:Error(String(e)))}let a=i?{...r.tools&&{toolsListChanged:!0},...r.prompts&&{promptsListChanged:!0},...r.resources&&{resourcesListChanged:!0}}:{};if(Object.keys(a).length>0){let e=new AbortController,t=()=>e.abort(n?.signal?.reason);n?.signal?.aborted&&t(),n?.signal?.addEventListener(`abort`,t);try{this._autoOpenedSubscription=await this.listen(a,{timeout:n?.timeout,signal:e.signal})}catch(e){if(n?.signal?.aborted)throw await this.close().catch(()=>{}),e;this.onerror?.(e instanceof Error?e:Error(String(e)))}finally{n?.signal?.removeEventListener(`abort`,t)}}}}async _connectFromPrior(e,t,n){if(t.kind===`legacy`)return this._connectPlainLegacy(e,n);let r=t.discover;this._resetConnectionState();let i=this._supportedProtocolVersionsOption,a=(i&&ui(i).length>0?ui(i):si).find(e=>r.supportedVersions.includes(e));if(a===void 0)throw new Y(J.EraNegotiationFailed,`connect({ prior }) with a modern verdict requires a 2026-07-28+ mutual protocol version; the supplied DiscoverResult and this client's supportedProtocolVersions have no modern overlap. For a server known to be legacy, pass prior: { kind: 'legacy' } to skip the probe and initialize directly, or use versionNegotiation: { mode: 'auto' } to re-probe with legacy fallback.`);if(await super.connect(e),this._discoverResult=r,this._serverCapabilities=r.capabilities,this._serverVersion=fu(r),this._cache.setServerIdentity(this._deriveServerIdentity(e)),this._instructions=r.instructions,this._negotiatedProtocolVersion=a,e.setProtocolVersion?.(a),this._listChangedConfig)try{this._setupListChangedHandlers(this._listChangedConfig)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}_deriveServerIdentity(e){let t=this._serverVersion;return t===void 0?e.sessionId??`anonymous:${Date.now()}-${Math.random().toString(36).slice(2)}`:`${t.name}@${t.version}`}getNegotiatedProtocolVersion(){return this._negotiatedProtocolVersion}getProtocolEra(){let e=this._negotiatedProtocolVersion;if(e!==void 0)return ci(e)?`modern`:`legacy`}getInstructions(){return this._instructions}getDiscoverResult(){return this._discoverResult}assertCapabilityForMethod(e){switch(e){case`logging/setLevel`:if(!this._serverCapabilities?.logging)throw new Y(J.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._serverCapabilities?.prompts)throw new Y(J.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:case`resources/subscribe`:case`resources/unsubscribe`:if(!this._serverCapabilities?.resources)throw new Y(J.CapabilityNotSupported,`Server does not support resources (required for ${e})`);if(e===`resources/subscribe`&&!this._serverCapabilities.resources.subscribe)throw new Y(J.CapabilityNotSupported,`Server does not support resource subscriptions (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._serverCapabilities?.tools)throw new Y(J.CapabilityNotSupported,`Server does not support tools (required for ${e})`);break;case`completion/complete`:if(!this._serverCapabilities?.completions)throw new Y(J.CapabilityNotSupported,`Server does not support completions (required for ${e})`)}}assertNotificationCapability(e){if(e===`notifications/roots/list_changed`&&!this._capabilities.roots?.listChanged)throw new Y(J.CapabilityNotSupported,`Client does not support roots list changed notifications (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case`sampling/createMessage`:if(!this._capabilities.sampling)throw new Y(J.CapabilityNotSupported,`Client does not support sampling capability (required for ${e})`);break;case`elicitation/create`:if(!this._capabilities.elicitation)throw new Y(J.CapabilityNotSupported,`Client does not support elicitation capability (required for ${e})`);break;case`roots/list`:if(!this._capabilities.roots)throw new Y(J.CapabilityNotSupported,`Client does not support roots capability (required for ${e})`)}}async ping(e){return this.request({method:`ping`},e)}async discover(e){let t=await this._requestWithSchema({method:`server/discover`},bt,e);return this._discoverResult=t,t}async complete(e,t){return this.request({method:`completion/complete`,params:e},t)}async setLoggingLevel(e,t){return this.request({method:`logging/setLevel`,params:{level:e}},t)}async getPrompt(e,t){return this.request({method:`prompts/get`,params:e},t)}async listPrompts(e,t){if(!this._serverCapabilities?.prompts&&!this._enforceStrictCapabilities)return console.debug(`Client.listPrompts() called but server does not advertise prompts capability - returning empty list`),{prompts:[]};if(e?.cursor!==void 0)return this.request({method:`prompts/list`,params:e},t);let n=await this._serveFromCache(`prompts/list`,void 0,t);return n===void 0?this._listAllPages(`prompts/list`,e,t,e=>e.prompts):n}async listResources(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug(`Client.listResources() called but server does not advertise resources capability - returning empty list`),{resources:[]};if(e?.cursor!==void 0)return this.request({method:`resources/list`,params:e},t);let n=await this._serveFromCache(`resources/list`,void 0,t);return n===void 0?this._listAllPages(`resources/list`,e,t,e=>e.resources):n}async listResourceTemplates(e,t){if(!this._serverCapabilities?.resources&&!this._enforceStrictCapabilities)return console.debug(`Client.listResourceTemplates() called but server does not advertise resources capability - returning empty list`),{resourceTemplates:[]};if(e?.cursor!==void 0)return this.request({method:`resources/templates/list`,params:e},t);let n=await this._serveFromCache(`resources/templates/list`,void 0,t);return n===void 0?this._listAllPages(`resources/templates/list`,e,t,e=>e.resourceTemplates):n}async _listAllPages(e,t,n,r,i){let a=n?.cacheMode===`bypass`,o=this._cache.captureGeneration(e),s=await this.request({method:e,...t&&{params:{...t}}},n),c=s.nextCursor,l=s,u=1;for(;c!==void 0;){if(this._listMaxPages!==0&&u>=this._listMaxPages)throw new Y(J.ListPaginationExceeded,`${e}: exceeded listMaxPages (${this._listMaxPages}); server pagination did not terminate`,{method:e,listMaxPages:this._listMaxPages});let i=await this.request({method:e,params:{...t,cursor:c}},n);if(i.nextCursor===c&&JSON.stringify(r(i))===JSON.stringify(r(l)))break;r(s).push(...r(i)),l=i,c=i.nextCursor,u++}return delete s.nextCursor,i?.(s),a||await this._cache.write(e,s,o,this._freshness(s)),s}_freshness(e,t){let n=e,r=typeof n.ttlMs==`number`?n.ttlMs:this._defaultCacheTtlMs,i=n.cacheScope===`public`?`public`:`private`;return{expiresAt:this._cache.now()+Math.min(Math.max(0,r),Nl),scope:i,params:t}}async _serveFromCache(e,t,n){if(n?.cacheMode===`bypass`||n?.cacheMode===`refresh`)return;let r=await this._cache.read(e,t).catch(e=>void this._reportStoreError(e));if(r!==void 0){if(n?.signal?.aborted){let e=n.signal.reason;throw e instanceof Y?e:new Y(J.RequestTimeout,String(e))}return r.value}}_reportStoreError(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}_compileOutputValidator(e){if(e.outputSchema)try{return{ok:!0,validator:this._jsonSchemaValidator.getValidator(e.outputSchema)}}catch(e){return{ok:!1,compileError:e}}}async _resolveXMcpHeaderScan(e,t){let n=t??await this._cache.toolDefinition(e);return n===void 0?void 0:Ya(n.inputSchema)}async readResource(e,t){let n=await this._serveFromCache(`resources/read`,e.uri,t);if(n!==void 0)return n;let r=this._cache.captureGeneration(`resources/read`,e.uri),i=await this.request({method:`resources/read`,params:e},t);if(t?.cacheMode!==`bypass`){let n=this._freshness(i,e.uri);n.expiresAt>this._cache.now()?await this._cache.write(`resources/read`,i,r,n):t?.cacheMode===`refresh`&&await this._cache.evictKey(`resources/read`,e.uri)}return i}async subscribeResource(e,t){return this.request({method:`resources/subscribe`,params:e},t)}async unsubscribeResource(e,t){return this.request({method:`resources/unsubscribe`,params:e},t)}async listen(e,t){if(this.transport===void 0)throw new Y(J.NotConnected,`Not connected`);let n=this._negotiatedProtocolVersion;if(n===void 0||!ci(n))throw new Y(J.MethodNotSupportedByProtocolVersion,`subscriptions/listen requires a 2026-07-28-era connection (negotiated: ${n??`none`}). On a 2025-era connection, change notifications are delivered unsolicited: use ClientOptions.listChanged and resources/subscribe instead.`,{method:`subscriptions/listen`,protocolVersion:n});if(t?.signal?.aborted){let e=t.signal.reason;throw e instanceof Y?e:new Y(J.RequestTimeout,String(e))}let r=new AbortController,i=`listen:${this._nextListenId++}`,a=`opening`,o,s,c,l,u=new Promise((e,t)=>{c=e,l=t}),d,f=new Promise(e=>{d=e}),p=e=>{if(a===`closed`)return;let n=a===`opening`;if(o!==void 0&&(clearTimeout(o),o=void 0),`ack`in e){a=`open`,c(e.ack);return}a=`closed`,s!==void 0&&t?.signal?.removeEventListener(`abort`,s),this._listenState.delete(i),r.abort(),d(e.cause),n&&l(e.error??new Y(J.ConnectionClosed,`subscriptions/listen closed before the server acknowledged`))},m=async()=>{r.abort(),await this.notification({method:`notifications/cancelled`,params:{requestId:i}}).catch(()=>{})},h=async()=>{a!==`closed`&&(p({cause:`local`}),await m())};this._listenState.set(i,{settle:p});let g=t?.timeout??6e4;if(o=setTimeout(()=>{p({cause:`remote`,error:new Y(J.RequestTimeout,`subscriptions/listen ack timed out`,{timeout:g})}),m().catch(()=>{})},g),t?.signal){let e=t.signal;s=()=>{if(a===`closed`)return;let t=e.reason;p({cause:`local`,error:t instanceof Error?t:Error(String(t??`Aborted`))}),m().catch(()=>{})},e.addEventListener(`abort`,s,{once:!0})}let _={jsonrpc:`2.0`,id:i,method:`subscriptions/listen`,params:{_meta:{...this._outboundMetaEnvelope()},notifications:e}},v=e=>{p({cause:`remote`,error:e instanceof Error?e:Error(String(e))})};try{this.transport.send(_,{requestSignal:r.signal,onRequestStreamEnd:()=>p({cause:`remote`,error:Error(`subscriptions/listen: stream ended`)})}).catch(v)}catch(e){v(e)}return{honoredFilter:await u,close:h,closed:f}}get autoOpenedSubscription(){return this._autoOpenedSubscription}_onnotification(e,t){let n=Object.hasOwn(gu,e.method)?gu[e.method]:void 0;if(e.method===`notifications/resources/updated`){let t=e.params?.uri;typeof t==`string`&&this._cache.evictKey(`resources/read`,t)}else if(n!==void 0)for(let e of n)this._cache.evict(e);if(e.method===`notifications/subscriptions/acknowledged`){let t=e.params?._meta?.[Be],n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){let t=this._wireCodec().validateNotification(`notifications/subscriptions/acknowledged`,e);n.settle({ack:t.ok?t.value.params.notifications:{}});return}}if(e.method===`notifications/cancelled`){let t=e.params?.requestId,n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){n.settle({cause:`remote`,error:Error(`subscriptions/listen: server cancelled the subscription`)});return}}super._onnotification(e,t)}_onresponse(e){let t=e.id,n=typeof t==`string`?this._listenState.get(t):void 0;if(n!==void 0){Va(e)?n.settle({cause:`remote`,error:Z.fromError(e.error.code,e.error.message,e.error.data)}):n.settle({cause:`graceful`,error:new Y(J.ConnectionClosed,`subscriptions/listen: server closed the subscription gracefully before acknowledging`)});return}super._onresponse(e)}_onclose(){if(this._listenState.size>0){let e=new Y(J.ConnectionClosed,`Connection closed`);for(let t of this._listenState.values())t.settle({cause:`remote`,error:e});this._listenState.clear()}super._onclose()}async callTool(e,t){let n=this.getProtocolEra()===`modern`&&$l()!==`browser`,r=async()=>{if(!n)return t;let r;try{r=await this._resolveXMcpHeaderScan(e.name,t?.toolDefinition)}catch(e){this._reportStoreError(e)}if(!r?.valid||r.declarations.length===0)return t;let i=oo(r.declarations,e.arguments);return Object.keys(i).length===0?t:{...t,headers:{...t?.headers,...i}}},i=t?.toolDefinition===void 0?await this._cache.outputValidator(e.name,e=>this._compileOutputValidator(e)).catch(e=>void this._reportStoreError(e)):this._compileOutputValidator(t.toolDefinition),a=()=>{if(i===void 0||i.ok)return;let t=i.compileError,n=(t instanceof Error?t.message:String(t)).slice(0,200);throw new Z(X.InvalidParams,`Tool '${e.name}' has an invalid outputSchema: ${n}`)};a();let o;try{o=await this.request({method:`tools/call`,params:e},await r())}catch(s){let c=s instanceof Z&&s.code===-32020;if(!n||!c||t?.toolDefinition!==void 0)throw s;let l={signal:t?.signal,timeout:t?.timeout,cacheMode:`refresh`};await this._cache.evict(`tools/list`),await this.listTools(void 0,l).catch(e=>this._reportStoreError(e)),i=await this._cache.outputValidator(e.name,e=>this._compileOutputValidator(e)).catch(e=>void this._reportStoreError(e)),a(),o=await this.request({method:`tools/call`,params:e},await r())}let s=i!==void 0&&i.ok?i.validator:void 0;if(s){if(o.structuredContent===void 0&&!o.isError)throw new Z(X.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(o.structuredContent!==void 0&&!o.isError)try{let e=s(o.structuredContent);if(!e.valid)throw new Z(X.InvalidParams,`Structured content does not match the tool's output schema: ${e.errorMessage}`)}catch(e){throw e instanceof Z?e:new Z(X.InvalidParams,`Failed to validate structured content: ${e instanceof Error?e.message:String(e)}`)}}return o}async listTools(e,t){if(!this._serverCapabilities?.tools&&!this._enforceStrictCapabilities)return console.debug(`Client.listTools() called but server does not advertise tools capability - returning empty list`),{tools:[]};if(e?.cursor!==void 0){let n=await this.request({method:`tools/list`,params:e},t);return this._excludeInvalidXMcpHeaderTools(n),n}let n=await this._serveFromCache(`tools/list`,void 0,t);return n===void 0?this._listAllPages(`tools/list`,e,t,e=>e.tools,e=>this._excludeInvalidXMcpHeaderTools(e)):n}_excludeInvalidXMcpHeaderTools(e){if(this.getProtocolEra()!==`modern`||!this.transport||eu(this.transport)===`stdio`)return;let t=e.tools.filter(e=>{let t=Ya(e.inputSchema);return t.valid?!0:(console.warn(`[mcp-sdk] excluding tool '${e.name}' from tools/list: invalid x-mcp-header declaration — ${t.reason}`),!1)});t.length!==e.tools.length&&(e.tools=t)}_setupListChangedHandler(e,t,n,r){let i=uo(Dn,n);if(!i.success)throw Error(`Invalid ${e} listChanged options: ${i.error.message}`);if(typeof n.onChanged!=`function`)throw TypeError(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:o}=i.data,{onChanged:s}=n,c=async()=>{if(!a){s(null,null);return}try{s(null,await r())}catch(e){s(e instanceof Error?e:Error(String(e)),null)}};this.setNotificationHandler(t,()=>{if(o){let t=this._listChangedDebounceTimers.get(e);t&&clearTimeout(t);let n=setTimeout(c,o);this._listChangedDebounceTimers.set(e,n)}else c()})}async sendRootsListChanged(){return this.notification({method:`notifications/roots/list_changed`})}};function yu(e){return/(?:^|,)\s*dpop(?:\s|$|,)/i.test(e)}function bu(e){if(e.status!==401)return!1;let t=e.headers.get(`www-authenticate`)??``;return yu(t)&&/use_dpop_nonce/i.test(t)}var xu=(e,t)=>n=>{let r=typeof e==`function`?e:()=>e;return async(e,i)=>{let a=(i?.method??`GET`).toUpperCase(),o=new URL(e.toString()),s=await r();if(!s)return n(e,i);let c=async()=>{let r=await t();if(!r)return n(e,i);let c=new Headers(i?.headers),l=await s.buildProof({htm:a,htu:o,accessToken:r});return c.set(`Authorization`,`DPoP ${r}`),c.set(`DPoP`,l),n(e,{...i,headers:c})},l=await c();return bu(l)&&l.headers.has(`dpop-nonce`)&&(s.observeNonce(l,o),await l.text?.().catch(()=>{}),l=await c()),s.observeNonce(l,o),l}},Su=e=>xu(async()=>{try{return await e.dpop?.()}catch(e){throw Ll(e)}},async()=>{let t;try{t=await e.tokens()}catch(e){throw Ll(e)}return t?.token_type?.toLowerCase()===`dpop`?t.access_token:void 0});(class extends Error{static{Object.defineProperty(this,"mcpBrand",{value:`mcp.SseError`})}static[Symbol.hasInstance](e){return $r(this,e)}static isInstance(e){if(typeof this!=`function`)throw TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");return $r(this,e)}constructor(e,t,n){super(`SSE error: ${t}`),this.code=e,this.event=n,Qr(this,new.target)}});var Cu=1,wu={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},Tu=new Set([`authorization`,`dpop`,`content-type`,`mcp-protocol-version`,`mcp-method`,`mcp-name`,`mcp-session-id`]);function Eu(e,t){if(typeof AbortSignal.any==`function`)return AbortSignal.any([e,t]);let n=new AbortController;if(e.aborted)return n.abort(e.reason),n.signal;if(t.aborted)return n.abort(t.reason),n.signal;let r=()=>{e.removeEventListener(`abort`,i),t.removeEventListener(`abort`,a)};function i(){r(),n.abort(e.reason)}function a(){r(),n.abort(t.reason)}return e.addEventListener(`abort`,i,{once:!0}),t.addEventListener(`abort`,a,{once:!0}),n.signal}var Du=class{_abortController;_url;_resourceMetadataUrl;_scope;_requestInit;_authProvider;_oauthProvider;_skipIssuerMetadataValidation;_fetch;_fetchWithInit;_redirectPolicy;_sessionId;_reconnectionOptions;_protocolVersion;_onInsufficientScope;_maxStepUpRetries;_serverRetryMs;_reconnectionScheduler;_cancelReconnection;onclose;onerror;onmessage;hasPerRequestStream=!0;constructor(e,t){this._url=e,this._resourceMetadataUrl=void 0,this._scope=void 0,this._requestInit=t?.requestInit,this._skipIssuerMetadataValidation=t?.skipIssuerMetadataValidation,this._fetch=t?.fetch,Ic(t?.authProvider)?(this._oauthProvider=t.authProvider,this._authProvider=Rc(t.authProvider,{skipIssuerMetadataValidation:t.skipIssuerMetadataValidation}),t.authProvider.dpop&&(this._fetch=Su(t.authProvider)(t.fetch??fetch))):this._authProvider=t?.authProvider,this._redirectPolicy=t?.redirectPolicy,this._fetchWithInit=bs(t?.fetch,t?.requestInit),this._redirectPolicy===`follow`&&(this._fetchWithInit=Es(this._fetchWithInit)),this._sessionId=t?.sessionId,this._protocolVersion=t?.protocolVersion,this._reconnectionOptions=t?.reconnectionOptions??wu,this._reconnectionScheduler=t?.reconnectionScheduler,this._onInsufficientScope=t?.onInsufficientScope??`reauthorize`,this._maxStepUpRetries=Math.max(0,t?.maxStepUpRetries??Cu)}async _stepUpAuthorize(e,t){try{return await this._stepUpAuthorizeInner(e,t)}catch(e){throw Ll(e)}}async _stepUpAuthorizeInner(e,t){if(this._onInsufficientScope===`throw`||!this._oauthProvider)throw new Nc({requiredScope:e.scope,resourceMetadataUrl:e.resourceMetadataUrl,errorDescription:e.errorDescription});if(t>=this._maxStepUpRetries)throw new ni(J.ClientHttpForbidden,`Server returned 403 insufficient_scope after step-up re-authorization (retry limit ${this._maxStepUpRetries} reached)`,{status:403,statusText:e.statusText??`Forbidden`,text:e.text});e.resourceMetadataUrl&&(this._resourceMetadataUrl=e.resourceMetadataUrl);let n=await this._oauthProvider.tokens(),r=Hc(this._scope,n?.scope,e.scope);this._scope=r;let i=Uc(r,n?.scope);return al(this._oauthProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:r,forceReauthorization:i,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})}_redirects(e){return this._redirectPolicy===`follow`?e:Ds(e)}_unfollowedRedirect(e,t){let n=this._redirectPolicy===`follow`?void 0:Os(e,t);return n&&`${n} (redirectPolicy: 'same-origin')`}async _commonHeaders(){let e=new Headers(this._requestInit?.headers||void 0),t;try{t=await this._authProvider?.token()}catch(e){throw Ll(e)}return t&&e.set(`Authorization`,`Bearer ${t}`),this._sessionId&&e.set(`mcp-session-id`,this._sessionId),this._protocolVersion&&e.set(`mcp-protocol-version`,this._protocolVersion),e}_applyBodyDerivedHeaders(e,t){if(Array.isArray(t)||!Ra(t))return;let n=t.params?._meta?.[Ie];if(typeof n!=`string`)return;e.set(`mcp-protocol-version`,n),e.set(`mcp-method`,t.method);let r=co(t.method,t.params);r?.value!==void 0&&e.set(`mcp-name`,io(r.value))}_isModernEnvelopedRequest(e){if(Array.isArray(e)||!Ra(e))return!1;let t=e.params?._meta?.[Ie];return typeof t==`string`&&ci(t)}async _startOrAuthSse(e,t=!1,n=0){let{resumptionToken:r,requestSignal:i}=e,a=()=>this._abortController?.signal.aborted===!0||i?.aborted===!0;try{let a=await this._commonHeaders(),o=[...a.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`text/event-stream`];a.set(`accept`,[...new Set(o)].join(`, `)),r&&a.set(`last-event-id`,r);let s=this._abortController?.signal,c=i!==void 0&&s!==void 0?Eu(s,i):i??s,l=await this._redirects(this._fetch??fetch)(this._url,{...this._requestInit,method:`GET`,headers:a,signal:c});if(!l.ok){if(l.status===401&&this._authProvider){if(l.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=dl(l);this._resourceMetadataUrl=e,this._scope=Hc(this._scope,t)}if(this._authProvider.onUnauthorized&&!t){try{await this._authProvider.onUnauthorized({response:l,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw Ll(e)}return await l.text?.().catch(()=>{}),this._startOrAuthSse(e,!0,n)}throw await l.text?.().catch(()=>{}),Ll(t?new ni(J.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:l.statusText}):new zc)}if(l.status===403){let{resourceMetadataUrl:r,scope:i,error:a,errorDescription:o}=dl(l);if(a===`insufficient_scope`){let a=await l.text?.().catch(()=>null);if(await this._stepUpAuthorize({scope:i,resourceMetadataUrl:r,errorDescription:o,statusText:l.statusText,text:a},n)!==`AUTHORIZED`)throw Ll(new zc);return this._startOrAuthSse(e,t,n+1)}}if(await l.text?.().catch(()=>{}),l.status===405){e.onRequestStreamEnd?.();return}let r=this._unfollowedRedirect(this._url,l)??l.statusText;throw new ni(J.ClientHttpFailedToOpenStream,`Failed to open SSE stream: ${r}`,{status:l.status,statusText:l.statusText})}this._handleSseStream(l.body,e,!0)}catch(e){throw a()||this.onerror?.(e),e}}_getNextReconnectionDelay(e){if(this._serverRetryMs!==void 0)return this._serverRetryMs;let t=this._reconnectionOptions.initialReconnectionDelay,n=this._reconnectionOptions.reconnectionDelayGrowFactor,r=this._reconnectionOptions.maxReconnectionDelay;return Math.min(t*n**+e,r)}_scheduleReconnection(e,t=0){let n=this._reconnectionOptions.maxRetries;if(t>=n){this.onerror?.(Error(`Maximum reconnection attempts (${n}) exceeded.`)),e.onRequestStreamEnd?.();return}let r=this._getNextReconnectionDelay(t),i=()=>{this._cancelReconnection=void 0,!(this._abortController?.signal.aborted||e.requestSignal?.aborted)&&this._startOrAuthSse(e).catch(n=>{if(!(this._abortController?.signal.aborted||e.requestSignal?.aborted)){this.onerror?.(Error(`Failed to reconnect SSE stream: ${n instanceof Error?n.message:String(n)}`));try{this._scheduleReconnection(e,t+1)}catch(e){this.onerror?.(e instanceof Error?e:Error(String(e)))}}})};if(this._reconnectionScheduler){let e=this._reconnectionScheduler(i,r,t);this._cancelReconnection=typeof e==`function`?e:void 0}else{let e=setTimeout(i,r);this._cancelReconnection=()=>clearTimeout(e)}}_handleSseStream(e,t,n){if(!e){t.onRequestStreamEnd?.();return}let{onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o}=t,s=()=>this._abortController?.signal.aborted===!0||a?.aborted===!0,c,l=!1,u=!1;(async()=>{try{let t=e.pipeThrough(new TextDecoderStream).pipeThrough(new Dc({onRetry:e=>{this._serverRetryMs=e}})).getReader();for(;;){let{value:e,done:n}=await t.read();if(n)break;if(e.id&&(c=e.id,l=!0,r?.(e.id)),e.data&&(!e.event||e.event===`message`))try{let t=tt.parse(JSON.parse(e.data));(Ba(t)||Va(t))&&(u=!0,i!==void 0&&(t.id=i)),this.onmessage?.(t)}catch(e){this.onerror?.(e)}}(n||l)&&!u&&this._abortController&&!s()?this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o},0):s()||o?.()}catch(e){if(s())return;if(this.onerror?.(Error(`SSE stream disconnected: ${e}`)),(n||l)&&!u&&this._abortController&&!s())try{this._scheduleReconnection({resumptionToken:c,onresumptiontoken:r,replayMessageId:i,requestSignal:a,onRequestStreamEnd:o},0)}catch(e){this.onerror?.(Error(`Failed to reconnect: ${e instanceof Error?e.message:String(e)}`)),o?.()}else o?.()}})()}async start(){if(this._abortController)throw Error(`StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.`);this._abortController=new AbortController}async finishAuth(e,t){if(!this._oauthProvider)throw new zc(`finishAuth requires an OAuthClientProvider`);let{authorizationCode:n,iss:r}=await Wc(e,t,this._oauthProvider,this._url,{fetchFn:this._fetchWithInit,resourceMetadataUrl:this._resourceMetadataUrl});if(await al(this._oauthProvider,{serverUrl:this._url,authorizationCode:n,iss:r,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit,skipIssuerMetadataValidation:this._skipIssuerMetadataValidation})!==`AUTHORIZED`)throw new zc(`Failed to authorize`)}async close(){try{this._cancelReconnection?.()}finally{this._cancelReconnection=void 0,this._abortController?.abort(),this.onclose?.()}}async send(e,t){return this._send(e,t,!1)}async _send(e,t,n,r=0){try{let{resumptionToken:i,onresumptiontoken:a}=t||{};if(i){this._startOrAuthSse({resumptionToken:i,replayMessageId:Ra(e)?e.id:void 0,requestSignal:t?.requestSignal}).catch(e=>this.onerror?.(e));return}let o=await this._commonHeaders();this._applyBodyDerivedHeaders(o,e);let s=Array.isArray(e)?e.some(e=>Ua(e)):Ua(e);if(s&&o.delete(`mcp-session-id`),t?.headers!==void 0)for(let[e,n]of Object.entries(t.headers))Tu.has(e.toLowerCase())||o.set(e,n);o.set(`content-type`,`application/json`);let c=[...o.get(`accept`)?.split(`,`).map(e=>e.trim().toLowerCase())??[],`application/json`,`text/event-stream`];o.set(`accept`,[...new Set(c)].join(`, `));let l=this._abortController?.signal,u=t?.requestSignal!==void 0&&l!==void 0?Eu(l,t.requestSignal):t?.requestSignal??l,d={...this._requestInit,method:`POST`,headers:o,body:JSON.stringify(e),signal:u},f=await this._redirects(this._fetch??fetch)(this._url,d);if(s&&f.ok&&(this._sessionId=f.headers.get(`mcp-session-id`)||void 0),!f.ok){if(f.status===401&&this._authProvider){if(f.headers.has(`www-authenticate`)){let{resourceMetadataUrl:e,scope:t}=dl(f);this._resourceMetadataUrl=e,this._scope=Hc(this._scope,t)}if(this._authProvider.onUnauthorized&&!n){try{await this._authProvider.onUnauthorized({response:f,serverUrl:this._url,fetchFn:this._fetchWithInit})}catch(e){throw Ll(e)}return await f.text?.().catch(()=>{}),this._send(e,t,!0,r)}throw await f.text?.().catch(()=>{}),Ll(n?new ni(J.ClientHttpAuthentication,`Server returned 401 after re-authentication`,{status:401,statusText:f.statusText}):new zc)}let i=await f.text?.().catch(()=>null);if(f.status===403){let{resourceMetadataUrl:a,scope:o,error:s,errorDescription:c}=dl(f);if(s===`insufficient_scope`){if(await this._stepUpAuthorize({scope:o,resourceMetadataUrl:a,errorDescription:c,statusText:f.statusText,text:i},r)!==`AUTHORIZED`)throw Ll(new zc);return this._send(e,t,n,r+1)}}if(f.status===400&&typeof i==`string`&&this._isModernEnvelopedRequest(e))try{let t=tt.parse(JSON.parse(i)),n=(Array.isArray(e)?e:[e]).filter(e=>Ra(e));if(Va(t)&&n.some(e=>e.id===t.id)){this.onmessage?.(t);return}}catch{}let a=this._unfollowedRedirect(this._url,f)??i;throw new ni(J.ClientHttpNotImplemented,`Error POSTing to endpoint: ${a}`,{status:f.status,statusText:f.statusText,text:i})}if(f.status===202){await f.text?.().catch(()=>{}),Wa(e)&&this._startOrAuthSse({resumptionToken:void 0}).catch(e=>this.onerror?.(e));return}let p=(Array.isArray(e)?e:[e]).some(e=>`method`in e&&`id`in e&&e.id!==void 0),m=f.headers.get(`content-type`),h=vs(m);if(p){if(h===`text/event-stream`)this._handleSseStream(f.body,{onresumptiontoken:a,requestSignal:t?.requestSignal,onRequestStreamEnd:t?.onRequestStreamEnd},!1);else if(h===`application/json`){let e=await f.json(),t=Array.isArray(e)?e.map(e=>tt.parse(e)):[tt.parse(e)];for(let e of t)this.onmessage?.(e)}else throw await f.text?.().catch(()=>{}),new Y(J.ClientHttpUnexpectedContent,`Unexpected content type: ${m}`,{contentType:m})}else await f.text?.().catch(()=>{})}catch(e){throw t?.requestSignal?.aborted!==!0&&this.onerror?.(e),e}}get sessionId(){return this._sessionId}async terminateSession(){if(this._sessionId)try{let e=await this._commonHeaders(),t={...this._requestInit,method:`DELETE`,headers:e,signal:this._abortController?.signal},n=await this._redirects(this._fetch??fetch)(this._url,t);if(await n.text?.().catch(()=>{}),!n.ok&&n.status!==405)throw new ni(J.ClientHttpFailedToTerminateSession,`Failed to terminate session: ${this._unfollowedRedirect(this._url,n)??n.statusText}`,{status:n.status,statusText:n.statusText});this._sessionId=void 0}catch(e){throw this.onerror?.(e),e}}setProtocolVersion(e){this._protocolVersion=e}get protocolVersion(){return this._protocolVersion}async resumeStream(e,t){await this._startOrAuthSse({resumptionToken:e,onresumptiontoken:t?.onresumptiontoken})}},Ou=class{_eventSlots=new Map;setHandler(e,t){let n=this._ensureEventSlot(e);n.onHandler&&t&&console.warn(`[MCP Apps] on${String(e)} handler replaced. Use addEventListener("${String(e)}", …) to add multiple listeners without replacing.`),n.onHandler=t}getHandler(e){return this._eventSlots.get(e)?.onHandler}addEventListener(e,t){this._ensureEventSlot(e).listeners.push(t)}removeEventListener(e,t){let n=this._eventSlots.get(e);if(!n)return;let r=n.listeners.indexOf(t);r!==-1&&n.listeners.splice(r,1)}dispatch(e,t){let n=this._eventSlots.get(e);if(n){n.onHandler?.(t);for(let e of[...n.listeners])e(t)}}_ensureEventSlot(e){let t=this._eventSlots.get(e);return t||(t={listeners:[]},this._eventSlots.set(e,t)),t}},ku=class{_methods=new Set;claim(e,t){if(this._methods.has(e))throw Error(`Handler for "${e}" already registered (via ${t}). Use addEventListener() to attach multiple listeners, or the on* setter for replace semantics.`);this._methods.add(e)}replace(e){this._methods.add(e)}release(e){this._methods.delete(e)}has(e){return this._methods.has(e)}},Au=new Set;function ju(e,t){let[n,r]=t,i=n?.shape;if(typeof i?.method?.value!=`string`)return;let a=i.method.value,o=e===`request`?`setRequestHandler`:`setNotificationHandler`;Au.has(o)||(Au.add(o),console.warn(`[ext-apps] ${o}(Schema, handler) is deprecated; use ${o}("${a}", { params: Schema.shape.params }, handler).`));let s=r;return[a,{params:i.params},e===`request`?(e,t)=>s({method:a,params:e},Mu(t)):e=>s({method:a,params:e})]}function Mu(e){return{signal:e.mcpReq.signal,requestId:e.mcpReq.id,sessionId:e.sessionId,_meta:e.mcpReq._meta,sendRequest:e.mcpReq.send,sendNotification:e.mcpReq.notify,authInfo:e.http?.authInfo}}var Nu=`2026-01-26`,Pu=k([S(`light`),S(`dark`)]).describe(`Color theme preference for the host environment.`),Fu=k([S(`inline`),S(`fullscreen`),S(`pip`)]).describe(`Display mode for UI presentation.`),Iu=k([S(`--color-background-primary`),S(`--color-background-secondary`),S(`--color-background-tertiary`),S(`--color-background-inverse`),S(`--color-background-ghost`),S(`--color-background-info`),S(`--color-background-danger`),S(`--color-background-success`),S(`--color-background-warning`),S(`--color-background-disabled`),S(`--color-text-primary`),S(`--color-text-secondary`),S(`--color-text-tertiary`),S(`--color-text-inverse`),S(`--color-text-ghost`),S(`--color-text-info`),S(`--color-text-danger`),S(`--color-text-success`),S(`--color-text-warning`),S(`--color-text-disabled`),S(`--color-border-primary`),S(`--color-border-secondary`),S(`--color-border-tertiary`),S(`--color-border-inverse`),S(`--color-border-ghost`),S(`--color-border-info`),S(`--color-border-danger`),S(`--color-border-success`),S(`--color-border-warning`),S(`--color-border-disabled`),S(`--color-ring-primary`),S(`--color-ring-secondary`),S(`--color-ring-inverse`),S(`--color-ring-info`),S(`--color-ring-danger`),S(`--color-ring-success`),S(`--color-ring-warning`),S(`--font-sans`),S(`--font-mono`),S(`--font-weight-normal`),S(`--font-weight-medium`),S(`--font-weight-semibold`),S(`--font-weight-bold`),S(`--font-text-xs-size`),S(`--font-text-sm-size`),S(`--font-text-md-size`),S(`--font-text-lg-size`),S(`--font-heading-xs-size`),S(`--font-heading-sm-size`),S(`--font-heading-md-size`),S(`--font-heading-lg-size`),S(`--font-heading-xl-size`),S(`--font-heading-2xl-size`),S(`--font-heading-3xl-size`),S(`--font-text-xs-line-height`),S(`--font-text-sm-line-height`),S(`--font-text-md-line-height`),S(`--font-text-lg-line-height`),S(`--font-heading-xs-line-height`),S(`--font-heading-sm-line-height`),S(`--font-heading-md-line-height`),S(`--font-heading-lg-line-height`),S(`--font-heading-xl-line-height`),S(`--font-heading-2xl-line-height`),S(`--font-heading-3xl-line-height`),S(`--border-radius-xs`),S(`--border-radius-sm`),S(`--border-radius-md`),S(`--border-radius-lg`),S(`--border-radius-xl`),S(`--border-radius-full`),S(`--border-width-regular`),S(`--shadow-hairline`),S(`--shadow-sm`),S(`--shadow-md`),S(`--shadow-lg`)]).describe(`CSS variable keys available to MCP apps for theming.`),Lu=A(Iu.describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),k([d(),ae()]).describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`)).describe(`Style variables for theming MCP apps. + +Individual style keys are optional - hosts may provide any subset of these values. +Values are strings containing CSS values (colors, sizes, font stacks, etc.). + +Note: This type uses \`Record\` rather than \`Partial>\` +for compatibility with Zod schema generation. Both are functionally equivalent for validation.`),Ru=m({method:S(`ui/open-link`),params:m({url:d().describe(`URL to open in the host's browser`)})}),zu=m({isError:E().optional().describe(`True if the host failed to open the URL (e.g., due to security policy).`)}).passthrough(),Bu=m({isError:E().optional().describe(`True if the download failed (e.g., user cancelled or host denied).`)}).passthrough(),Vu=m({isError:E().optional().describe(`True if the host rejected or failed to deliver the message.`)}).passthrough(),Hu=m({method:S(`ui/notifications/sandbox-proxy-ready`),params:m({})}),Uu=m({connectDomains:O(d()).optional().describe(`Origins for network requests (fetch/XHR/WebSocket). + +- Maps to CSP \`connect-src\` directive +- Empty or omitted → no network connections (secure default)`),resourceDomains:O(d()).optional().describe("Origins for static resources (images, scripts, stylesheets, fonts, media).\n\n- Maps to CSP `img-src`, `script-src`, `style-src`, `font-src`, `media-src` directives\n- Wildcard subdomains supported: `https://*.example.com`\n- Empty or omitted → no network resources (secure default)"),frameDomains:O(d()).optional().describe("Origins for nested iframes.\n\n- Maps to CSP `frame-src` directive\n- Empty or omitted → no nested iframes allowed (`frame-src 'none'`)"),baseUriDomains:O(d()).optional().describe("Allowed base URIs for the document.\n\n- Maps to CSP `base-uri` directive\n- Empty or omitted → only same origin allowed (`base-uri 'self'`)")}),Wu=m({camera:m({}).optional().describe(`Request camera access. + +Maps to Permission Policy \`camera\` feature.`),microphone:m({}).optional().describe(`Request microphone access. + +Maps to Permission Policy \`microphone\` feature.`),geolocation:m({}).optional().describe(`Request geolocation access. + +Maps to Permission Policy \`geolocation\` feature.`),clipboardWrite:m({}).optional().describe(`Request clipboard write access. + +Maps to Permission Policy \`clipboard-write\` feature.`)}),Gu=m({method:S(`ui/notifications/size-changed`),params:m({width:C().optional().describe(`New width in pixels.`),height:C().optional().describe(`New height in pixels.`)})});m({method:S(`ui/notifications/tool-input`),params:m({arguments:A(d(),v().describe(`Complete tool call arguments as key-value pairs.`)).optional().describe(`Complete tool call arguments as key-value pairs.`)})}),m({method:S(`ui/notifications/tool-input-partial`),params:m({arguments:A(d(),v().describe(`Partial tool call arguments (incomplete, may change).`)).optional().describe(`Partial tool call arguments (incomplete, may change).`)})}),m({method:S(`ui/notifications/tool-cancelled`),params:m({reason:d().optional().describe(`Optional reason for the cancellation (e.g., "user action", "timeout").`)})});var Ku=m({fonts:d().optional()}),qu=m({variables:Lu.optional().describe(`CSS variables for theming the app.`),css:Ku.optional().describe(`CSS blocks that apps can inject.`)});m({method:S(`ui/resource-teardown`),params:m({})});var Ju=A(d(),v()),Yu=m({text:m({}).optional().describe(`Host supports text content blocks.`),image:m({}).optional().describe(`Host supports image content blocks.`),audio:m({}).optional().describe(`Host supports audio content blocks.`),resource:m({}).optional().describe(`Host supports resource content blocks.`),resourceLink:m({}).optional().describe(`Host supports resource link content blocks.`),structuredContent:m({}).optional().describe(`Host supports structured content.`)}),Xu=m({method:S(`ui/notifications/request-teardown`),params:m({}).optional()}),Zu=m({experimental:A(d(),A(d(),re()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),openLinks:m({}).optional().describe(`Host supports opening external URLs.`),downloadFile:m({}).optional().describe(`Host supports file downloads via ui/download-file.`),serverTools:m({listChanged:E().optional().describe(`Host supports tools/list_changed notifications.`)}).optional().describe(`Host can proxy tool calls to the MCP server.`),serverResources:m({listChanged:E().optional().describe(`Host supports resources/list_changed notifications.`)}).optional().describe(`Host can proxy resource reads to the MCP server.`),logging:m({}).optional().describe(`Host accepts log messages.`),sandbox:m({permissions:Wu.optional().describe(`Permissions granted by the host (camera, microphone, geolocation).`),csp:Uu.optional().describe(`CSP domains approved by the host.`)}).optional().describe(`Sandbox configuration applied by the host.`),updateModelContext:Yu.optional().describe(`Host accepts context updates (ui/update-model-context) to be included in the model's context for future turns.`),message:Yu.optional().describe(`Host supports receiving content messages (ui/message) from the view.`),sampling:m({tools:m({}).optional().describe("Host supports tool use via `tools` and `toolChoice` parameters.")}).optional().describe("Host supports LLM sampling (sampling/createMessage) from the view.\nMirrors the MCP `ClientCapabilities.sampling` shape so hosts can pass it through.")}),Qu=m({experimental:A(d(),A(d(),re()).describe(`Experimental features keyed by identifier.`)).optional().describe(`Experimental features keyed by identifier.`),tools:m({listChanged:E().optional().describe(`App supports tools/list_changed notifications.`)}).optional().describe(`App exposes MCP-style tools that the host can call.`),availableDisplayModes:O(Fu).optional().describe(`Display modes the app supports.`)}),$u=m({method:S(`ui/notifications/initialized`),params:m({}).optional()});m({csp:Uu.optional().describe(`Content Security Policy configuration for UI resources.`),permissions:Wu.optional().describe(`Sandbox permissions requested by the UI resource.`),domain:d().optional().describe(`Dedicated origin for view sandbox. + +Useful when views need stable, dedicated origins for OAuth callbacks, CORS policies, or API key allowlists. + +**Host-dependent:** The format and validation rules for this field are determined by each host. Servers MUST consult host-specific documentation for the expected domain format. Common patterns include: +- Hash-based subdomains (e.g., \`{hash}.claudemcpcontent.com\`) +- URL-derived subdomains (e.g., \`www-example-com.oaiusercontent.com\`) + +If omitted, host uses default sandbox origin (typically per-conversation).`),prefersBorder:E().optional().describe(`Visual boundary preference - true if view prefers a visible border. + +Boolean requesting whether a visible border and background is provided by the host. Specifying an explicit value for this is recommended because hosts' defaults may vary. + +- \`true\`: request visible border + background +- \`false\`: request no visible border + background +- omitted: host decides border`)});var ed=m({method:S(`ui/request-display-mode`),params:m({mode:Fu.describe(`The display mode being requested.`)})}),td=m({mode:Fu.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),nd=k([S(`model`),S(`app`)]).describe(`Tool visibility scope - who can access the tool.`);m({resourceUri:d().optional(),visibility:O(nd).optional().describe(`Who can access this tool. Default: ["model", "app"] +- "model": Tool visible to and callable by the agent +- "app": Tool callable by the app from this server only`),csp:le().optional(),permissions:le().optional()}),m({mimeTypes:O(d()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')});var rd=m({method:S(`ui/download-file`),params:m({contents:O(k([dn,fn])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),id=m({method:S(`ui/message`),params:m({role:S(`user`).describe(`Message role, currently only "user" is supported.`),content:O(pn).describe(`Message content blocks (text, image, etc.).`)})});m({method:S(`ui/notifications/sandbox-resource-ready`),params:m({html:d().describe(`HTML content to load into the inner iframe.`),sandbox:d().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:Uu.optional().describe(`CSP configuration from resource metadata.`),permissions:Wu.optional().describe(`Sandbox permissions from resource metadata.`)})}),m({method:S(`ui/notifications/tool-result`),params:Sn.describe(`Standard MCP tool execution result.`)});var ad=m({toolInfo:m({id:Ze.optional().describe(`JSON-RPC id of the tools/call request.`),tool:yn.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:Pu.optional().describe(`Current color theme preference.`),styles:qu.optional().describe(`Style configuration for theming the app.`),displayMode:Fu.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:O(Fu).optional().describe(`Display modes the host supports.`),containerDimensions:k([m({height:C().describe(`Fixed container height in pixels.`)}),m({maxHeight:k([C(),ae()]).optional().describe(`Maximum container height in pixels.`)})]).and(k([m({width:C().describe(`Fixed container width in pixels.`)}),m({maxWidth:k([C(),ae()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other +container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:d().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:d().optional().describe(`User's timezone in IANA format.`),userAgent:d().optional().describe(`Host application identifier.`),platform:k([S(`web`),S(`desktop`),S(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:m({touch:E().optional().describe(`Whether the device supports touch input.`),hover:E().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:m({top:C().describe(`Top safe area inset in pixels.`),right:C().describe(`Right safe area inset in pixels.`),bottom:C().describe(`Bottom safe area inset in pixels.`),left:C().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough();m({method:S(`ui/notifications/host-context-changed`),params:ad.describe(`Partial context update containing only changed fields.`)});var od=m({method:S(`ui/update-model-context`),params:m({content:O(pn).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:A(d(),v().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),sd=m({method:S(`ui/initialize`),params:m({appInfo:H.describe(`App identification (name and version).`),appCapabilities:Qu.describe(`Features and capabilities this app provides.`),protocolVersion:d().describe(`Protocol version this app supports.`)})}),cd=m({protocolVersion:d().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:H.describe(`Host application identification and version.`),hostCapabilities:Zu.describe(`Features and capabilities provided by the host.`),hostContext:ad.describe(`Rich context about the host environment.`)}).passthrough(),ld=class{eventTarget;eventSource;messageListener;constructor(e=window.parent,t){this.eventTarget=e,this.eventSource=t,this.messageListener=e=>{if(t&&e.source!==this.eventSource){console.debug(`Ignoring message from unknown source`,e);return}let n=tt.safeParse(e.data);n.success?(console.debug(`Parsed message`,n.data),this.onmessage?.(n.data)):e.data?.jsonrpc===`2.0`?(console.error(`Failed to parse message`,n.error.message,e),this.onerror?.(Error(`Invalid JSON-RPC message received: `+n.error.message))):console.debug(`Ignoring non-JSON-RPC message`,n.error.message,e)}}async start(){window.addEventListener(`message`,this.messageListener)}async send(e,t){e.method!==`ui/notifications/tool-input-partial`&&console.debug(`Sending message`,e),this.eventTarget.postMessage(e,`*`)}async close(){window.removeEventListener(`message`,this.messageListener),this.onclose?.()}onclose;onerror;onmessage;sessionId;setProtocolVersion},ud=[Nu],dd=class extends os{_client;_hostInfo;_hostCapabilities;_appCapabilities;_hostContext={};_appInfo;_initializedReceived=!1;_registeredEvents=new Set;_events=new Ou;_methods=new ku;setRequestHandler=(...e)=>{let[t,...n]=ju(`request`,e)??e;this._methods.claim(t,`setRequestHandler`),super.setRequestHandler.call(this,t,...n)};setNotificationHandler=(...e)=>{let[t,...n]=ju(`notification`,e)??e;this._methods.claim(t,`setNotificationHandler`),super.setNotificationHandler.call(this,t,...n)};removeRequestHandler=e=>{this._methods.release(e),super.removeRequestHandler(e)};removeNotificationHandler=e=>{this._methods.release(e),super.removeNotificationHandler(e)};replaceRequestHandler=(e,...t)=>{this._methods.replace(e),super.setRequestHandler.call(this,e,...t)};_wrapHandler(e,t){let n=super._wrapHandler(e,t);return e===`ui/initialize`||e===`ping`?n:async(t,r)=>(this._initializedReceived||console.warn(`[ext-apps] AppBridge received '${e}' before ui/notifications/initialized. The View is calling host methods before completing the handshake; it should await app.connect() first.`),n(t,r))}eventSchemas={sizechange:Gu,sandboxready:Hu,initialized:$u,requestteardown:Xu,loggingmessage:Mn};setEventHandler(e,t){this._ensureEventSlot(e),this._events.setHandler(e,t)}getEventHandler(e){return this._events.getHandler(e)}addEventListener(e,t){this._ensureEventSlot(e),this._events.addEventListener(e,t)}removeEventListener(e,t){this._events.removeEventListener(e,t)}_ensureEventSlot(e){if(this._registeredEvents.has(e))return;let t=this.eventSchemas[e];if(!t)throw Error(`Unknown event: ${String(e)}`);let n=t=>{e===`initialized`&&(this._initializedReceived=!0),this._events.dispatch(e,t)};e===`loggingmessage`?this.setNotificationHandler(`notifications/message`,e=>{n(e.params)}):this.setNotificationHandler(t.shape.method.value,{params:t.shape.params},e=>n(e)),this._registeredEvents.add(e)}warnIfRequestHandlerReplaced(e,t,n){t&&n&&console.warn(`[MCP Apps] ${e} handler replaced. Previous handler will no longer be called.`)}constructor(e,t,n,r){super(r),this._client=e,this._hostInfo=t,this._hostCapabilities=n,this._methods.replace(`notifications/cancelled`),this._methods.replace(`notifications/progress`),this._ensureEventSlot(`initialized`),this._hostContext=r?.hostContext||{},this.replaceRequestHandler(`ui/initialize`,{params:sd.shape.params,result:cd},e=>this._onAppsInitialize(e)),this.replaceRequestHandler(`ping`,(e,t)=>(this.onping?.(e.params,t),{})),this.replaceRequestHandler(`ui/request-display-mode`,{params:ed.shape.params,result:td},()=>({mode:this._hostContext.displayMode??`inline`}))}buildContext(e){return e}assertCapabilityForMethod(e){}assertRequestHandlerCapability(e){}assertNotificationCapability(e){}getAppCapabilities(){return this._appCapabilities}getAppVersion(){return this._appInfo}onping;get onsizechange(){return this.getEventHandler(`sizechange`)}set onsizechange(e){this.setEventHandler(`sizechange`,e)}get onsandboxready(){return this.getEventHandler(`sandboxready`)}set onsandboxready(e){this.setEventHandler(`sandboxready`,e)}get oninitialized(){return this.getEventHandler(`initialized`)}set oninitialized(e){this.setEventHandler(`initialized`,e)}_onmessage;get onmessage(){return this._onmessage}set onmessage(e){this.warnIfRequestHandlerReplaced(`onmessage`,this._onmessage,e),this._onmessage=e,this.replaceRequestHandler(`ui/message`,{params:id.shape.params,result:Vu},async(e,t)=>{if(!this._onmessage)throw Error(`No onmessage handler set`);return this._onmessage(e,t)})}_onopenlink;get onopenlink(){return this._onopenlink}set onopenlink(e){this.warnIfRequestHandlerReplaced(`onopenlink`,this._onopenlink,e),this._onopenlink=e,this.replaceRequestHandler(`ui/open-link`,{params:Ru.shape.params,result:zu},async(e,t)=>{if(!this._onopenlink)throw Error(`No onopenlink handler set`);return this._onopenlink(e,t)})}_ondownloadfile;get ondownloadfile(){return this._ondownloadfile}set ondownloadfile(e){this.warnIfRequestHandlerReplaced(`ondownloadfile`,this._ondownloadfile,e),this._ondownloadfile=e,this.replaceRequestHandler(`ui/download-file`,{params:rd.shape.params,result:Bu},async(e,t)=>{if(!this._ondownloadfile)throw Error(`No ondownloadfile handler set`);return this._ondownloadfile(e,t)})}get onrequestteardown(){return this.getEventHandler(`requestteardown`)}set onrequestteardown(e){this.setEventHandler(`requestteardown`,e)}_onrequestdisplaymode;get onrequestdisplaymode(){return this._onrequestdisplaymode}set onrequestdisplaymode(e){this.warnIfRequestHandlerReplaced(`onrequestdisplaymode`,this._onrequestdisplaymode,e),this._onrequestdisplaymode=e,this.replaceRequestHandler(`ui/request-display-mode`,{params:ed.shape.params,result:td},async(e,t)=>{if(!this._onrequestdisplaymode)throw Error(`No onrequestdisplaymode handler set`);return this._onrequestdisplaymode(e,t)})}get onloggingmessage(){return this.getEventHandler(`loggingmessage`)}set onloggingmessage(e){this.setEventHandler(`loggingmessage`,e)}_onupdatemodelcontext;get onupdatemodelcontext(){return this._onupdatemodelcontext}set onupdatemodelcontext(e){this.warnIfRequestHandlerReplaced(`onupdatemodelcontext`,this._onupdatemodelcontext,e),this._onupdatemodelcontext=e,this.replaceRequestHandler(`ui/update-model-context`,{params:od.shape.params,result:rt},async(e,t)=>{if(!this._onupdatemodelcontext)throw Error(`No onupdatemodelcontext handler set`);return this._onupdatemodelcontext(e,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(`tools/call`,async(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_oncreatesamplingmessage;get oncreatesamplingmessage(){return this._oncreatesamplingmessage}set oncreatesamplingmessage(e){this.warnIfRequestHandlerReplaced(`oncreatesamplingmessage`,this._oncreatesamplingmessage,e),this._oncreatesamplingmessage=e,this.replaceRequestHandler(`sampling/createMessage`,async(e,t)=>{if(!this._oncreatesamplingmessage)throw Error(`No oncreatesamplingmessage handler set`);return this._oncreatesamplingmessage(e.params,t)})}sendToolListChanged(e={}){return this.notification({method:`notifications/tools/list_changed`,params:e})}_onlistresources;get onlistresources(){return this._onlistresources}set onlistresources(e){this.warnIfRequestHandlerReplaced(`onlistresources`,this._onlistresources,e),this._onlistresources=e,this.replaceRequestHandler(`resources/list`,async(e,t)=>{if(!this._onlistresources)throw Error(`No onlistresources handler set`);return this._onlistresources(e.params,t)})}_onlistresourcetemplates;get onlistresourcetemplates(){return this._onlistresourcetemplates}set onlistresourcetemplates(e){this.warnIfRequestHandlerReplaced(`onlistresourcetemplates`,this._onlistresourcetemplates,e),this._onlistresourcetemplates=e,this.replaceRequestHandler(`resources/templates/list`,async(e,t)=>{if(!this._onlistresourcetemplates)throw Error(`No onlistresourcetemplates handler set`);return this._onlistresourcetemplates(e.params,t)})}_onreadresource;get onreadresource(){return this._onreadresource}set onreadresource(e){this.warnIfRequestHandlerReplaced(`onreadresource`,this._onreadresource,e),this._onreadresource=e,this.replaceRequestHandler(`resources/read`,async(e,t)=>{if(!this._onreadresource)throw Error(`No onreadresource handler set`);return this._onreadresource(e.params,t)})}sendResourceListChanged(e={}){return this.notification({method:`notifications/resources/list_changed`,params:e})}_onlistprompts;get onlistprompts(){return this._onlistprompts}set onlistprompts(e){this.warnIfRequestHandlerReplaced(`onlistprompts`,this._onlistprompts,e),this._onlistprompts=e,this.replaceRequestHandler(`prompts/list`,async(e,t)=>{if(!this._onlistprompts)throw Error(`No onlistprompts handler set`);return this._onlistprompts(e.params,t)})}sendPromptListChanged(e={}){return this.notification({method:`notifications/prompts/list_changed`,params:e})}getCapabilities(){return this._hostCapabilities}async _onAppsInitialize(e){let t=e.protocolVersion;return this._appInfo!==void 0&&console.warn(`[ext-apps] AppBridge received a second ui/initialize. The View may be double-mounting (e.g. React StrictMode in dev) without closing the previous App instance. Responding normally; the latest appInfo/appCapabilities replace the previous values.`),this._appCapabilities=e.appCapabilities,this._appInfo=e.appInfo,{protocolVersion:ud.includes(t)?t:Nu,hostCapabilities:this.getCapabilities(),hostInfo:this._hostInfo,hostContext:this._hostContext}}setHostContext(e){let t={},n=!1;for(let r of Object.keys(e)){let i=this._hostContext[r],a=e[r];fd(i,a)||(t[r]=a,n=!0)}n&&(this._hostContext=e,this.sendHostContextChange(t))}sendHostContextChange(e){return this.notification({method:`ui/notifications/host-context-changed`,params:e})}sendToolInput(e){return this.notification({method:`ui/notifications/tool-input`,params:e})}sendToolInputPartial(e){return this.notification({method:`ui/notifications/tool-input-partial`,params:e})}sendToolResult(e){return this.notification({method:`ui/notifications/tool-result`,params:e})}sendToolCancelled(e){return this.notification({method:`ui/notifications/tool-cancelled`,params:e})}sendSandboxResourceReady(e){return this.notification({method:`ui/notifications/sandbox-resource-ready`,params:e})}teardownResource(e,t){return this.request({method:`ui/resource-teardown`,params:e},Ju,t)}sendResourceTeardown=this.teardownResource;callTool(e,t){return this.request({method:`tools/call`,params:e},t)}listTools(e,t){return this.request({method:`tools/list`,params:e},t)}async connect(e){if(this.transport)throw Error(`AppBridge is already connected. Call close() before connecting again.`);if(this._initializedReceived=!1,this._client){let e=this._client.getServerCapabilities();if(!e)throw Error(`Client server capabilities not available`);e.tools&&(this.oncalltool=async(e,t)=>this._client.request({method:`tools/call`,params:e},{signal:t.mcpReq.signal}),e.tools.listChanged&&this._client.setNotificationHandler(`notifications/tools/list_changed`,e=>this.sendToolListChanged(e.params))),e.resources&&(this.onlistresources=async(e,t)=>this._client.request({method:`resources/list`,params:e},{signal:t.mcpReq.signal}),this.onlistresourcetemplates=async(e,t)=>this._client.request({method:`resources/templates/list`,params:e},{signal:t.mcpReq.signal}),this.onreadresource=async(e,t)=>this._client.request({method:`resources/read`,params:e},{signal:t.mcpReq.signal}),e.resources.listChanged&&this._client.setNotificationHandler(`notifications/resources/list_changed`,e=>this.sendResourceListChanged(e.params))),e.prompts&&(this.onlistprompts=async(e,t)=>this._client.request({method:`prompts/list`,params:e},{signal:t.mcpReq.signal}),e.prompts.listChanged&&this._client.setNotificationHandler(`notifications/prompts/list_changed`,e=>this.sendPromptListChanged(e.params)))}return super.connect(e)}};function fd(e,t){return JSON.stringify(e)===JSON.stringify(t)}var $=n(e(),1),pd=t(),md=`text/html;profile=mcp-app`,hd=`io.modelcontextprotocol/ui`,gd=3,_d=5,vd=2e3,yd=[`inline`,`fullscreen`],bd=class extends Error{},xd=null,Sd=null;async function Cd(){let e=new Du(new URL(`/api/mcp`,location.origin),{fetch:(e,t)=>w(e,t)}),t=new vu({name:`fanout-browser`,version:`0.2.0`},{supportedProtocolVersions:[`2026-07-28`],versionNegotiation:{mode:{pin:`2026-07-28`}},capabilities:{extensions:{[hd]:{mimeTypes:[md]}}}});try{await t.connect(e);let n={client:t,tools:t.listTools(),references:0,closed:!1,closeListeners:new Set};return n.tools.catch(()=>void 0),t.onclose=()=>Td(n,!1),t.onerror=()=>Td(n,!0),n}catch(t){throw await e.close().catch(()=>void 0),t}}async function wd(){for(let e=0;e{Sd===e&&!t.closed&&(xd=t)}).catch(()=>{Sd===e&&(Sd=null)})}let e=Sd;if(!e)continue;let t=await e;if(t.closed){Sd===e&&(Sd=null);continue}return t.closeTimer&&=(clearTimeout(t.closeTimer),void 0),t.references+=1,t}throw Error(`MCP connection closed during setup`)}function Td(e,t){if(!e.closed){e.closed=!0,e.closeTimer&&clearTimeout(e.closeTimer),e.closeTimer=void 0,xd===e&&(xd=null),Sd=null;for(let t of[...e.closeListeners])t();t&&e.client.close().catch(()=>void 0)}}function Ed(e){e.references=Math.max(0,e.references-1),!(e.closed||e.references||e.closeTimer)&&(e.closeTimer=setTimeout(()=>{e.closeTimer=void 0,!(e.references||xd!==e)&&(e.closed=!0,xd=null,Sd=null,e.client.close().catch(()=>void 0))},0))}function Dd(e){return typeof e==`object`&&e&&!Array.isArray(e)?e:void 0}var Od=new Map;async function kd(e,t){let n=Od.get(t);if(n&&n.expires>Date.now())return n.pending;let r={pending:Promise.resolve({text:``}),expires:1/0};return r.pending=e.readResource({uri:t}).then(e=>{let n=e.contents[0];if(e.contents.length!==1||!n||!(`text`in n)||!n.text)throw new bd(`MCP App resource has no HTML content`);if(n.uri!==t)throw new bd(`MCP App resource URI does not match the requested URI`);if(n.mimeType!==md)throw new bd(`MCP App resource has an unsupported MIME type`);let i=Dd(e)?.ttlMs;return r.expires=Date.now()+(typeof i==`number`&&i>0?i:3e5),{text:n.text,_meta:n._meta}}).catch(e=>{throw Od.get(t)===r&&Od.delete(t),e}),Od.set(t,r),r.pending}function Ad(e,t){let n=``;return/]*)?>/i.test(e)?e.replace(/]*)?>/i,e=>`${e}${n}`):/]*)?>/i.test(e)?e.replace(/]*)?>/i,e=>`${e}${n}`):`${n}${e}`}function jd({content:e}){let t=l(e);return t?(0,pd.jsx)(Md,{content:t}):(0,pd.jsx)(o,{color:`bad`,m:`md`,children:`This view could not be loaded. Please try again.`})}function Md({content:e}){let t=(0,$.useRef)(null),n=(0,$.useRef)(null),l=(0,$.useRef)(null),d=(0,$.useRef)(null),[f,p]=(0,$.useState)(``),[m,h]=(0,$.useState)(`inline`),g=(0,$.useRef)(null),_=(0,$.useRef)(m);_.current=m;let v=e=>{h(e),d.current?.setHostContext({theme:te.current,displayMode:e,availableDisplayModes:yd}),e===`inline`&&document.activeElement!==t.current&&t.current?.focus()};(0,$.useEffect)(()=>{if(m!==`fullscreen`)return;g.current?.focus();let e=document.body.style.overflow;document.body.style.overflow=`hidden`;let n=e=>{e.key===`Escape`&&(e.preventDefault(),v(`inline`))},r=e=>{t.current?.parentElement?.contains(e.target)||g.current?.focus()};return window.addEventListener(`keydown`,n),document.addEventListener(`focusin`,r),()=>{document.body.style.overflow=e,window.removeEventListener(`keydown`,n),document.removeEventListener(`focusin`,r)}},[m]);let[y,b]=(0,$.useState)(240),[ee,x]=(0,$.useState)(``),[S,C]=(0,$.useState)(0),w=(0,$.useRef)(0),E=u(`light`),te=(0,$.useRef)(E);te.current=E,(0,$.useEffect)(()=>{d.current?.setHostContext({theme:E,displayMode:_.current,availableDisplayModes:yd})},[E]),(0,$.useEffect)(()=>{w.current=0},[e.resource_uri]),(0,$.useEffect)(()=>{let t=!1,r;h(`inline`),p(``),x(``);let i=()=>{let e=w.current+1;if(e>_d)return;w.current=e;let t=e===1?0:Math.min(750*2**(e-2),6e3);t===0?C(e=>e+1):r=setTimeout(()=>C(e=>e+1),t)},a=()=>i();async function o(){try{let r=await wd();if(t){Ed(r);return}l.current=r,r.closeListeners.add(a),n.current=r.client;let i=await kd(r.client,e.resource_uri);await r.tools,t||(w.current=0,p(Ad(i.text,i._meta)))}catch(e){console.error(`MCP app resource load failed`,e),t||(x(`This view could not be loaded. Please try again.`),w.current>0&&!(e instanceof bd)&&i())}}return o(),()=>{t=!0,r&&clearTimeout(r);let e=d.current?.teardownResource({}).catch(()=>void 0)??Promise.resolve(),i=l.current;i&&(i.closeListeners.delete(a),e.finally(()=>Ed(i))),d.current=null,n.current=null,l.current=null}},[e.resource_uri,S]);async function ne(){let r=t.current,i=n.current;if(r?.contentWindow&&f&&i&&!d.current)try{let t=new dd(null,{name:`Fanout`,version:`0.2.0`},{serverTools:{},logging:{}},{hostContext:{theme:te.current,displayMode:`inline`,availableDisplayModes:yd}}),n=l.current;if(!n)throw Error(`MCP connection unavailable`);t.oncalltool=async(e,t)=>{let r=Dd(Dd((await n.tools).tools.find(t=>t.name===e.name)?._meta)?.ui)?.visibility;if(!Array.isArray(r)||!r.includes(`app`)||/^(?:create|edit|replace|restore|delete)_/.test(e.name))throw Error(`This tool is unavailable in the app`);return i.callTool(e,{signal:t.mcpReq.signal})},t.onrequestdisplaymode=async({mode:e})=>e!==`inline`&&e!==`fullscreen`?{mode:_.current}:(v(e),{mode:e}),d.current=t,t.onsizechange=({height:e})=>{e&&b(Math.min(vd,Math.max(240,Math.round(e))))},t.onmessage=async()=>({isError:!0}),t.oninitialized=async()=>{await t.sendToolInput({arguments:e.tool_input??{}}),await t.sendToolResult({content:[{type:`text`,text:JSON.stringify(e.tool_result??{})}],structuredContent:e.tool_result,isError:e.is_error})},await t.connect(new ld(r.contentWindow,r.contentWindow))}catch(e){console.error(`MCP app bridge connect failed`,e),x(`This view could not be loaded. Please try again.`)}}return ee?(0,pd.jsx)(o,{color:`bad`,m:`md`,children:ee}):f?(0,pd.jsx)(T,{active:m===`fullscreen`,children:(0,pd.jsxs)(r,{"data-app-fullscreen":m===`fullscreen`?``:void 0,role:m===`fullscreen`?`dialog`:void 0,"aria-modal":m===`fullscreen`||void 0,"aria-label":m===`fullscreen`?`Fanout analysis view`:void 0,bg:`var(--mantine-color-body)`,style:m===`fullscreen`?{position:`fixed`,inset:0,zIndex:1e3,display:`flex`,flexDirection:`column`}:void 0,children:[m===`fullscreen`&&(0,pd.jsx)(r,{p:`xs`,ta:`right`,children:(0,pd.jsx)(i,{ref:g,"data-autofocus":!0,size:`compact-sm`,variant:`default`,"aria-label":`Close analysis view`,onClick:()=>v(`inline`),children:`Close`})}),(0,pd.jsx)(r,{component:`iframe`,tabIndex:0,ref:t,title:`Fanout analysis view`,sandbox:`allow-scripts`,scrolling:`auto`,srcDoc:f,w:`100%`,bd:0,bg:`var(--mantine-color-body)`,style:{display:`block`,height:m===`fullscreen`?`100%`:y,...m===`fullscreen`?{flex:`1 1 0`,minHeight:0}:{}},onLoad:()=>void ne()})]})}):(0,pd.jsxs)(s,{mih:180,p:`xl`,children:[(0,pd.jsx)(c,{size:`sm`}),(0,pd.jsx)(a,{c:`dimmed`,size:`sm`,ml:`sm`,children:`Preparing view…`})]})}export{jd as default}; \ No newline at end of file diff --git a/internal/ui/dist/assets/page-6_nmYeSY.js b/internal/ui/dist/assets/page-DWbtzTMF.js similarity index 53% rename from internal/ui/dist/assets/page-6_nmYeSY.js rename to internal/ui/dist/assets/page-DWbtzTMF.js index da75331b..5244d236 100644 --- a/internal/ui/dist/assets/page-6_nmYeSY.js +++ b/internal/ui/dist/assets/page-DWbtzTMF.js @@ -1,18 +1,18 @@ -const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/panel-sql-editor-CC0YOP-x.js","assets/useRouter-ByJ6_rwb.js","assets/brand-DUaZkIz1.js","assets/index-BZ6fASDi.js","assets/useNavigate-B1zgPEUp.js","assets/preload-helper-EHBQhIeL.js","assets/Tooltip-B3r3s_B9.js","assets/index-ADB9ThEc.css"])))=>i.map(i=>d[i]); -import{a as e,i as t,o as n,r,s as i}from"./useRouter-ByJ6_rwb.js";import{A as a,C as o,D as s,E as c,K as l,M as u,O as d,P as f,Q as p,S as m,T as h,X as g,Y as _,Z as v,_ as y,_t as b,a as x,c as S,d as C,dt as w,f as T,ft as E,g as D,gt as O,h as k,j as A,k as j,lt as M,m as N,mt as P,nt as F,o as I,ot as L,p as ee,r as R,s as te,st as ne,tt as re,u as ie,ut as z,v as ae,x as B,y as oe}from"./brand-DUaZkIz1.js";import{c as se,l as ce,t as le}from"./preload-helper-EHBQhIeL.js";import{C as ue,E as de,b as fe,o as pe,t as me,w as he}from"./Tooltip-B3r3s_B9.js";import{a as ge,c as _e,d as ve,i as ye,l as be,n as xe,o as Se,r as Ce,s as we,t as Te,u as Ee}from"./dashboard-change-chips-BODDZoYU.js";import{n as De,r as Oe,t as ke}from"./WarningCircle.es-CClFvSYW.js";import{A as Ae,At as je,B as Me,Bt as Ne,C as Pe,D as Fe,E as Ie,F as Le,Ft as Re,Gt as ze,H as Be,Ht as Ve,I as He,It as Ue,Jt as We,Kt as Ge,Lt as Ke,M as qe,Mt as Je,N as Ye,Nt as Xe,O as Ze,P as Qe,Pt as $e,Q as et,R as tt,Rt as nt,U as rt,Ut as it,V as at,W as ot,Wt as st,Xt as ct,Yt as lt,Zt as ut,_ as dt,a as ft,b as pt,c as mt,d as ht,h as gt,i as _t,j as vt,jt as yt,k as bt,l as xt,m as St,n as Ct,o as wt,qt as Tt,r as Et,s as Dt,t as Ot,u as kt,v as At,w as jt,x as Mt,zt as Nt}from"./index-BZ6fASDi.js";function Pt(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();let n=Ft(e);if(n.length!==Ft(t).length)return!1;for(let r=0;r{if(typeof n!=`string`||n.trim().length===0)throw Error(t);return`${e}-${n}`}}var H=r();function Lt(e){return typeof e==`object`&&e?`base`in e?e.base:void 0:e}function Rt(e,t){if(e===t||Number.isNaN(e)&&Number.isNaN(t))return!0;if(!(e instanceof Object)||!(t instanceof Object))return!1;let n=Object.keys(e),{length:r}=n;if(r!==Object.keys(t).length)return!1;for(let i=0;i{r.current||=window.setTimeout(()=>{i(...e),r.current=null},t)},[t]),o=(0,V.useCallback)(()=>{r.current&&=(window.clearTimeout(r.current),null)},[]);return(0,V.useEffect)(()=>(n.autoInvoke&&a(),o),[o,a]),{start:a,clear:o}}function Ut(e){let t=(0,V.useRef)(void 0);return(0,V.useEffect)(()=>{t.current=e},[e]),t.current}function Wt(e,t,n){let r=(0,V.useRef)(null);(0,V.useEffect)(()=>{r.current&&=(r.current.disconnect(),null);let i=typeof n==`function`?n():n;return i&&(r.current=new MutationObserver(e),r.current.observe(i,t)),()=>{r.current&&=(r.current.disconnect(),null)}},[e,t,n])}function Gt(){let[e,t]=(0,V.useState)(!1);return(0,V.useEffect)(()=>t(!0),[]),e}function Kt(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`}function qt(e,t=document){let n=t.querySelector(e);if(n)return n;let r=t.querySelectorAll(`*`);for(let t=0;t{if(!e||!t||!n.current)return;let r=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=t.offsetWidth===0?1:i.width/t.offsetWidth,o=t.offsetHeight===0?1:i.height/t.offsetHeight,s=window.getComputedStyle(e),c=window.getComputedStyle(t),l=fe(s.borderTopWidth)+fe(c.borderTopWidth),u=fe(s.borderLeftWidth)+fe(c.borderLeftWidth),d={top:(r.top-i.top)/o-l,left:(r.left-i.left)/a-u,width:r.width/a,height:r.height/o};n.current.style.transform=`translateY(${d.top}px) translateX(${d.left}px)`,n.current.style.width=`${d.width}px`,n.current.style.height=`${d.height}px`},p=()=>{window.clearTimeout(o.current),n.current&&(n.current.style.transitionDuration=`0ms`),f(),o.current=window.setTimeout(()=>{n.current&&(n.current.style.transitionDuration=``)},30)},m=(0,V.useRef)(null),h=(0,V.useRef)(null);return(0,V.useEffect)(()=>{if(c&&s.current!==e&&i&&i(),s.current=e,f(),e)return m.current=new ResizeObserver(p),m.current.observe(e),t&&(h.current=new ResizeObserver(p),h.current.observe(t)),()=>{m.current?.disconnect(),h.current?.disconnect()}},[t,e]),(0,V.useEffect)(()=>{if(t){let e=e=>{Zt(e.target,t)&&(p(),d(!1))};return t.addEventListener(`transitionend`,e),()=>{t.removeEventListener(`transitionend`,e)}}},[t]),(0,V.useEffect)(()=>{if(n.current&&a){let e=e=>{e.propertyName===`transform`&&a()};return n.current.addEventListener(`transitionend`,e),()=>{n.current?.removeEventListener(`transitionend`,e)}}},[a]),Ht(()=>{ve()!==`test`&&l(!0)},20,{autoInvoke:!0}),Wt(e=>{e.forEach(e=>{e.type===`attributes`&&e.attributeName===`dir`&&p()})},{attributes:!0,attributeFilter:[`dir`]},()=>document.documentElement),{initialized:c,hidden:u}}var $t={root:`m_96b553a6`},en=g((e,{transitionDuration:t},{shouldReduceMotion:n})=>({root:{"--transition-duration":e.respectReducedMotion&&n?`0ms`:typeof t==`number`?`${t}ms`:t||`150ms`}})),tn=h(e=>{let t=u(`FloatingIndicator`,null,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,target:d,parent:f,transitionDuration:m,mod:h,displayAfterTransitionEnd:g,onTransitionStart:_,onTransitionEnd:v,attributes:y,ref:b,...x}=t,S=p(),C=a({name:`FloatingIndicator`,classes:$t,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:y,vars:l,varsResolver:en,stylesCtx:{shouldReduceMotion:S}}),w=(0,V.useRef)(null),{initialized:T,hidden:E}=Qt({target:d,parent:f,ref:w,displayAfterTransitionEnd:g,onTransitionStart:_,onTransitionEnd:v}),D=re(b,w);return!d||!f?null:(0,H.jsx)(o,{ref:D,mod:[{initialized:T,hidden:E},h],...C(`root`),...x})});tn.displayName=`@mantine/core/FloatingIndicator`,tn.classes=$t,tn.varsResolver=en;var[nn,rn]=de(`Accordion component was not found in the tree`),[an,on]=de(`Accordion.Item component was not found in the tree`),sn={root:`m_9bdbb667`,panel:`m_df78851f`,content:`m_4ba554d4`,itemTitle:`m_8fa820a0`,control:`m_4ba585b8`,"control--default":`m_6939a5e9`,"control--contained":`m_4271d21b`,label:`m_df3ffa0f`,chevron:`m_3f35ae96`,icon:`m_9bd771fe`,item:`m_9bd7b098`,"item--default":`m_fe19b709`,"item--contained":`m_1f921b3b`,"item--filled":`m_2cdf939a`,"item--separated":`m_9f59b069`},cn=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,chevron:s,icon:c,onClick:l,onKeyDown:d,children:f,disabled:p,mod:h,...g}=u(`AccordionControl`,null,e),{value:_}=on(),v=rn(),y=v.isItemActive(_),b=typeof v.order==`number`,x=`h${v.order}`,S=(0,H.jsxs)(m,{...v.getStyles(`control`,{className:n,classNames:t,style:r,styles:i,variant:v.variant}),unstyled:v.unstyled,mod:[`accordion-control`,{active:y,"chevron-position":v.chevronPosition,disabled:p},h],onClick:e=>{l?.(e),v.onChange(_)},type:`button`,disabled:p,"aria-expanded":y,"aria-controls":v.getRegionId(_),id:v.getControlId(_),onKeyDown:Tt({siblingSelector:`[data-accordion-control]`,parentSelector:`[data-accordion]`,activateOnFocus:!1,loop:v.loop,orientation:`vertical`,onKeyDown:d}),...g,children:[(0,H.jsx)(o,{component:`span`,mod:{rotate:!v.disableChevronRotation&&y,position:v.chevronPosition},...v.getStyles(`chevron`,{classNames:t,styles:i}),children:s||v.chevron}),(0,H.jsx)(`span`,{...v.getStyles(`label`,{classNames:t,styles:i}),children:f}),c&&(0,H.jsx)(o,{component:`span`,mod:{"chevron-position":v.chevronPosition},...v.getStyles(`icon`,{classNames:t,styles:i}),children:c})]});return b?(0,H.jsx)(x,{...v.getStyles(`itemTitle`,{classNames:t,styles:i}),children:S}):S});cn.displayName=`@mantine/core/AccordionControl`,cn.classes=sn;var ln=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,value:s,mod:c,...l}=u(`AccordionItem`,null,e),d=rn();return(0,H.jsx)(an,{value:{value:s},children:(0,H.jsx)(o,{mod:[{active:d.isItemActive(s)},c],...d.getStyles(`item`,{className:n,classNames:t,styles:i,style:r,variant:d.variant}),...l})})});ln.displayName=`@mantine/core/AccordionItem`,ln.classes=sn;var un=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,children:o,keepMounted:s,keepMountedMode:c,...l}=u(`AccordionPanel`,null,e),{value:d}=on(),f=rn();return(0,H.jsx)(Ee,{...f.getStyles(`panel`,{className:n,classNames:t,style:r,styles:i}),expanded:f.isItemActive(d),transitionDuration:f.transitionDuration??200,role:`region`,id:f.getRegionId(d),"aria-labelledby":f.getControlId(d),keepMounted:s??f.keepMounted,keepMountedMode:c??f.keepMountedMode,...l,children:(0,H.jsx)(`div`,{...f.getStyles(`content`,{classNames:t,styles:i}),children:o})})});un.displayName=`@mantine/core/AccordionPanel`,un.classes=sn;var dn={multiple:!1,loop:!0,disableChevronRotation:!1,disableCollapse:!1,chevronPosition:`right`,variant:`default`,chevronSize:`auto`,chevronIconSize:16,keepMountedMode:`activity`},fn=g((e,{transitionDuration:t,chevronSize:n,radius:r})=>({root:{"--accordion-transition-duration":t===void 0?void 0:`${t}ms`,"--accordion-chevron-size":n===void 0?void 0:P(n),"--accordion-radius":r===void 0?void 0:ne(r)}})),pn=c(e=>{let t=u(`Accordion`,dn,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,children:d,multiple:f,value:p,defaultValue:m,onChange:h,id:g,loop:_,transitionDuration:v,disableChevronRotation:y,disableCollapse:b,chevronPosition:x,chevronSize:S,order:C,chevron:w,variant:T,radius:E,chevronIconSize:D,attributes:O,keepMounted:k,keepMountedMode:A,...j}=t,M=F(g),[N,P]=ze({value:p,defaultValue:m,finalValue:f?[]:null,onChange:h}),I=e=>Array.isArray(N)?N.includes(e):e===N,L=e=>{if(!Array.isArray(N)&&b&&e===N)return;let t=Array.isArray(N)?N.includes(e)?N.filter(t=>t!==e):[...N,e]:e===N?null:e;P(t)},ee=a({name:`Accordion`,classes:sn,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:O,vars:l,varsResolver:fn});return(0,H.jsx)(nn,{value:{isItemActive:I,onChange:L,getControlId:It(`${M}-control`,`Accordion.Item component was rendered with invalid value or without value`),getRegionId:It(`${M}-panel`,`Accordion.Item component was rendered with invalid value or without value`),chevron:w===null?null:w||(0,H.jsx)(nt,{size:D}),transitionDuration:v,disableChevronRotation:y,chevronPosition:x,order:C,loop:_,getStyles:ee,variant:T,unstyled:c,keepMounted:k,keepMountedMode:A},children:(0,H.jsx)(o,{...ee(`root`),id:M,...j,variant:T,"data-accordion":!0,children:d})})});pn.classes=sn,pn.varsResolver=fn,pn.displayName=`@mantine/core/Accordion`,pn.Item=ln,pn.Panel=un,pn.Control=cn,pn.Chevron=nt;function mn(e){return typeof e==`string`?{value:e,label:e}:typeof e==`object`&&`value`in e&&!(`label`in e)?{value:e.value,label:`${e.value}`,disabled:e.disabled}:typeof e==`object`&&`group`in e?{group:e.group,items:e.items.map(e=>mn(e))}:typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`?{value:e,label:`${e}`}:e}function hn(e){return e?e.map(e=>mn(e)):[]}function gn(e){return e.reduce((e,t)=>`group`in t?{...e,...gn(t.items)}:(e[`${t.value}`]=t,e),{})}var _n={dropdown:`m_88b62a41`,search:`m_985517d8`,options:`m_b2821a6e`,option:`m_92253aa5`,empty:`m_2530cd1d`,header:`m_858f94bd`,footer:`m_82b967cb`,group:`m_254f3e4f`,groupLabel:`m_2bb2e9e5`,chevron:`m_2943220b`,optionsDropdownOption:`m_390b5f4`,optionsDropdownCheckIcon:`m_8ee53fc2`,optionsDropdownCheckPlaceholder:`m_a530ee0a`},vn={error:null},yn=g((e,{size:t,color:n})=>({chevron:{"--combobox-chevron-size":M(t,`combobox-chevron-size`),"--combobox-chevron-color":n?l(n,e):void 0}})),bn=h(e=>{let t=u(`ComboboxChevron`,vn,e),{size:n,error:r,style:i,className:s,classNames:c,styles:l,unstyled:d,vars:f,attributes:p,mod:m,...h}=t,g=a({name:`ComboboxChevron`,classes:_n,props:t,style:i,className:s,classNames:c,styles:l,unstyled:d,vars:f,varsResolver:yn,attributes:p,rootSelector:`chevron`});return(0,H.jsx)(o,{component:`svg`,...h,...g(`chevron`),size:n,viewBox:`0 0 15 15`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,mod:[`combobox-chevron`,{error:r},m],children:(0,H.jsx)(`path`,{d:`M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})});bn.classes=_n,bn.varsResolver=yn,bn.displayName=`@mantine/core/ComboboxChevron`;var[xn,Sn]=de(`Combobox component was not found in tree`);function Cn({onMouseDown:e,onClick:t,onClear:n,...r}){return(0,H.jsx)(k.ClearButton,{tabIndex:-1,"aria-hidden":!0,...r,onMouseDown:t=>{t.preventDefault(),e?.(t)},onClick:e=>{n(),t?.(e)}})}Cn.displayName=`@mantine/core/ComboboxClearButton`;var wn=h(e=>{let{classNames:t,styles:n,className:r,style:i,hidden:a,...o}=u(`ComboboxDropdown`,null,e),s=Sn();return(0,H.jsx)(Ne.Dropdown,{...o,role:`presentation`,"data-hidden":a||void 0,"data-floating-height":s.floatingHeight||void 0,...s.getStyles(`dropdown`,{className:r,style:i,classNames:t,styles:n})})});wn.classes=_n,wn.displayName=`@mantine/core/ComboboxDropdown`;var Tn={refProp:`ref`},En=h(e=>{let{children:t,refProp:n,ref:r}=u(`ComboboxDropdownTarget`,Tn,e);if(Sn(),!w(t))throw Error(`Combobox.DropdownTarget component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);return(0,H.jsx)(Ne.Target,{ref:r,refProp:n,children:t})});En.displayName=`@mantine/core/ComboboxDropdownTarget`;var Dn=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...s}=u(`ComboboxEmpty`,null,e),c=Sn();return(0,H.jsx)(o,{...c.getStyles(`empty`,{className:n,classNames:t,styles:i,style:r}),...s})});Dn.classes=_n,Dn.displayName=`@mantine/core/ComboboxEmpty`;function On({onKeyDown:e,onClick:t,withKeyboardNavigation:n,withAriaAttributes:r,withExpandedAttribute:i,targetType:a,autoComplete:o}){let s=Sn(),[c,l]=(0,V.useState)(null),u=t=>{if(e?.(t),!s.readOnly&&n){if(t.nativeEvent.isComposing)return;if(t.nativeEvent.code===`ArrowDown`&&(t.preventDefault(),s.store.dropdownOpened?l(s.store.selectNextOption()):(s.store.openDropdown(`keyboard`),l(s.store.selectActiveOption()),s.store.updateSelectedOptionIndex(`selected`,{scrollIntoView:!0}))),t.nativeEvent.code===`ArrowUp`&&(t.preventDefault(),s.store.dropdownOpened?l(s.store.selectPreviousOption()):(s.store.openDropdown(`keyboard`),l(s.store.selectActiveOption()),s.store.updateSelectedOptionIndex(`selected`,{scrollIntoView:!0}))),t.nativeEvent.code===`Enter`||t.nativeEvent.code===`NumpadEnter`){if(t.nativeEvent.keyCode===229)return;let e=s.store.getSelectedOptionIndex();s.store.dropdownOpened&&e!==-1?(t.preventDefault(),s.store.clickSelectedOption()):a===`button`&&(t.preventDefault(),s.store.openDropdown(`keyboard`))}t.key===`Escape`&&s.store.closeDropdown(`keyboard`),t.nativeEvent.code===`Space`&&a===`button`&&(t.preventDefault(),s.store.toggleDropdown(`keyboard`))}},d=r?{...i?{role:`combobox`}:{},"aria-haspopup":`listbox`,"aria-expanded":i?!!(s.store.listId&&s.store.dropdownOpened):void 0,"aria-controls":s.store.dropdownOpened&&s.store.listId?s.store.listId:void 0,"aria-activedescendant":s.store.dropdownOpened&&c||void 0,autoComplete:o,"data-expanded":s.store.dropdownOpened||void 0,"data-mantine-stop-propagation":s.store.dropdownOpened||void 0}:{},f=e=>{a===`button`&&e.currentTarget.focus(),t?.(e)};return{...d,onKeyDown:u,onClick:f}}var kn={refProp:`ref`,targetType:`input`,withKeyboardNavigation:!0,withAriaAttributes:!0,withExpandedAttribute:!1,autoComplete:`off`},An=h(e=>{let{children:t,refProp:n,withKeyboardNavigation:r,withAriaAttributes:i,withExpandedAttribute:a,targetType:o,autoComplete:s,ref:c,...l}=u(`ComboboxEventsTarget`,kn,e),d=v(t);if(!d)throw Error(`Combobox.EventsTarget component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let f=Sn(),p=On({targetType:o,withAriaAttributes:i,withKeyboardNavigation:r,withExpandedAttribute:a,onKeyDown:d.props.onKeyDown,onClick:d.props.onClick,autoComplete:s});return(0,V.cloneElement)(d,{...p,...l,[n]:re(c,f.store.targetRef,ue(d))})});An.displayName=`@mantine/core/ComboboxEventsTarget`;var jn=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...s}=u(`ComboboxFooter`,null,e),c=Sn();return(0,H.jsx)(o,{...c.getStyles(`footer`,{className:n,classNames:t,style:r,styles:i}),...s,onMouseDown:e=>{e.preventDefault()}})});jn.classes=_n,jn.displayName=`@mantine/core/ComboboxFooter`;var Mn=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,children:s,label:c,id:l,...d}=u(`ComboboxGroup`,null,e),f=Sn(),p=F(l),m=c!=null&&c!==!1&&c!==``;return(0,H.jsxs)(o,{role:`group`,"aria-labelledby":m?p:void 0,...f.getStyles(`group`,{className:n,classNames:t,style:r,styles:i}),...d,children:[m&&(0,H.jsx)(`div`,{id:p,...f.getStyles(`groupLabel`,{classNames:t,styles:i}),children:c}),s]})});Mn.classes=_n,Mn.displayName=`@mantine/core/ComboboxGroup`;var Nn=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...s}=u(`ComboboxHeader`,null,e),c=Sn();return(0,H.jsx)(o,{...c.getStyles(`header`,{className:n,classNames:t,style:r,styles:i}),...s,onMouseDown:e=>{e.preventDefault()}})});Nn.classes=_n,Nn.displayName=`@mantine/core/ComboboxHeader`;function Pn({value:e,valuesDivider:t=`,`,...n}){return(0,H.jsx)(`input`,{type:`hidden`,value:Array.isArray(e)?e.join(t):e?`${e}`:``,...n})}Pn.displayName=`@mantine/core/ComboboxHiddenInput`;var Fn=h(e=>{let t=u(`ComboboxOption`,null,e),{classNames:n,className:r,style:i,styles:a,vars:s,onClick:c,id:l,active:d,onMouseDown:f,onMouseOver:p,disabled:m,selected:h,mod:g,..._}=t,v=Sn(),y=(0,V.useId)(),b=l||y;return(0,H.jsx)(o,{...v.getStyles(`option`,{className:r,classNames:n,styles:a,style:i}),"aria-disabled":m||void 0,..._,id:b,mod:[`combobox-option`,{"combobox-active":d,"combobox-disabled":m,"combobox-selected":h},g],role:`option`,onClick:e=>{m?e.preventDefault():(v.onOptionSubmit?.(t.value,t),c?.(e))},onMouseDown:e=>{e.preventDefault(),f?.(e)},onMouseOver:e=>{v.resetSelectionOnOptionHover&&v.store.resetSelectedOption(),p?.(e)}})});Fn.classes=_n,Fn.displayName=`@mantine/core/ComboboxOption`;var In=h(e=>{let{classNames:t,className:n,style:r,styles:i,id:a,onMouseDown:s,labelledBy:c,...l}=u(`ComboboxOptions`,null,e),d=Sn(),f=F(a);return(0,V.useEffect)(()=>{d.store.setListId(f)},[f]),(0,H.jsx)(o,{...d.getStyles(`options`,{className:n,style:r,classNames:t,styles:i}),...l,id:f,role:`listbox`,"aria-labelledby":c,onMouseDown:e=>{e.preventDefault(),s?.(e)}})});In.classes=_n,In.displayName=`@mantine/core/ComboboxOptions`;var Ln={withAriaAttributes:!0,withKeyboardNavigation:!0},Rn=h(e=>{let{classNames:t,styles:n,unstyled:r,vars:i,withAriaAttributes:a,onKeyDown:o,onClick:s,withKeyboardNavigation:c,size:l,ref:d,...f}=u(`ComboboxSearch`,Ln,e),p=Sn(),m=p.getStyles(`search`),h=On({targetType:`input`,withAriaAttributes:a,withKeyboardNavigation:c,withExpandedAttribute:!1,onKeyDown:o,onClick:s,autoComplete:`off`});return(0,H.jsx)(k,{ref:re(d,p.store.searchRef),classNames:[{input:m.className},t],styles:[{input:m.style},n],size:l||p.size,...h,...f,__staticSelector:`Combobox`})});Rn.classes=_n,Rn.displayName=`@mantine/core/ComboboxSearch`;var zn={refProp:`ref`,targetType:`input`,withKeyboardNavigation:!0,withAriaAttributes:!0,withExpandedAttribute:!1,autoComplete:`off`},Bn=h(e=>{let{children:t,refProp:n,withKeyboardNavigation:r,withAriaAttributes:i,withExpandedAttribute:a,targetType:o,autoComplete:s,ref:c,...l}=u(`ComboboxTarget`,zn,e),d=v(t);if(!d)throw Error(`Combobox.Target component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let f=Sn(),p=On({targetType:o,withAriaAttributes:i,withKeyboardNavigation:r,withExpandedAttribute:a,onKeyDown:d.props.onKeyDown,onClick:d.props.onClick,autoComplete:s}),m=(0,V.cloneElement)(d,{...p,...l});return(0,H.jsx)(Ne.Target,{refProp:n,ref:re(c,f.store.targetRef),children:m})});Bn.displayName=`@mantine/core/ComboboxTarget`;function Vn(e,t,n){for(let n=e-1;n>=0;--n)if(!t[n].hasAttribute(`data-combobox-disabled`))return n;if(n){for(let e=t.length-1;e>-1;--e)if(!t[e].hasAttribute(`data-combobox-disabled`))return e}return e}function Hn(e,t,n){for(let n=e+1;n{s||(c(!0),i?.(e))},[c,i,s]),_=(0,V.useCallback)((e=`unknown`)=>{s&&(c(!1),r?.(e))},[c,r,s]),v=(0,V.useCallback)((e=`unknown`)=>{s?_(e):g(e)},[_,g,s]),y=(0,V.useCallback)(()=>{let e=Yt(f.current);qt(`#${l.current} [data-combobox-selected]`,e)?.removeAttribute(`data-combobox-selected`)},[]),b=(0,V.useCallback)(e=>{let t=Yt(f.current),n=qt(`#${l.current}`,t),r=n?Jt(`[data-combobox-option]`,n):null;if(!r)return null;let i=e>=r.length?0:e<0?r.length-1:e;return u.current=i,r?.[i]&&!r[i].hasAttribute(`data-combobox-disabled`)?(y(),r[i].setAttribute(`data-combobox-selected`,`true`),r[i].scrollIntoView({block:`nearest`,behavior:o}),r[i].id):null},[o,y]),x=(0,V.useCallback)(()=>{let e=Yt(f.current),t=qt(`#${l.current} [data-combobox-active]`,e);if(t){let n=Jt(`#${l.current} [data-combobox-option]`,e).findIndex(e=>e===t);return b(n)}return b(0)},[b]),S=(0,V.useCallback)(()=>{let e=Yt(f.current),t=Jt(`#${l.current} [data-combobox-option]`,e);return b(Hn(u.current,t,a))},[b,a]),C=(0,V.useCallback)(()=>{let e=Yt(f.current),t=Jt(`#${l.current} [data-combobox-option]`,e);return b(Vn(u.current,t,a))},[b,a]),w=(0,V.useCallback)(()=>{let e=Yt(f.current),t=Jt(`#${l.current} [data-combobox-option]`,e);return b(Un(t))},[b]),T=(0,V.useCallback)((e=`selected`,t)=>{if(typeof e==`number`){u.current=e;let n=Yt(f.current),r=Jt(`#${l.current} [data-combobox-option]`,n);t?.scrollIntoView&&r[e]?.scrollIntoView({block:`nearest`,behavior:o});return}h.current=window.setTimeout(()=>{let n=Yt(f.current),r=Jt(`#${l.current} [data-combobox-option]`,n),i=r.findIndex(t=>t.hasAttribute(`data-combobox-${e}`));u.current=i,t?.scrollIntoView&&r[i]?.scrollIntoView({block:`nearest`,behavior:o})},0)},[]),E=(0,V.useCallback)(()=>{u.current=-1,y()},[y]),D=(0,V.useCallback)(()=>{let e=Yt(f.current);(Jt(`#${l.current} [data-combobox-option]`,e)?.[u.current])?.click()},[]),O=(0,V.useCallback)(e=>{l.current=e},[]),k=(0,V.useCallback)(()=>{p.current=window.setTimeout(()=>d.current?.focus(),0)},[]),A=(0,V.useCallback)(()=>{m.current=window.setTimeout(()=>f.current?.focus(),0)},[]),j=(0,V.useCallback)(()=>u.current,[]);return(0,V.useEffect)(()=>()=>{window.clearTimeout(p.current),window.clearTimeout(m.current),window.clearTimeout(h.current)},[]),{dropdownOpened:s,openDropdown:g,closeDropdown:_,toggleDropdown:v,selectedOptionIndex:u.current,getSelectedOptionIndex:j,selectOption:b,selectFirstOption:w,selectActiveOption:x,selectNextOption:S,selectPreviousOption:C,resetSelectedOption:E,updateSelectedOptionIndex:T,listId:l.current,setListId:O,clickSelectedOption:D,searchRef:d,focusSearchInput:k,targetRef:f,focusTarget:A}}var Gn={keepMounted:!0,keepMountedMode:`display-none`,withinPortal:!0,resetSelectionOnOptionHover:!1,width:`target`,transitionProps:{transition:`fade`,duration:0},size:`sm`},Kn=g((e,{size:t,dropdownPadding:n})=>({options:{"--combobox-option-fz":L(t),"--combobox-option-padding":M(t,`combobox-option-padding`)},dropdown:{"--combobox-padding":n===void 0?void 0:P(n),"--combobox-option-fz":L(t),"--combobox-option-padding":M(t,`combobox-option-padding`)}})),qn=e=>{let t=u(`Combobox`,Gn,e),{classNames:n,styles:r,unstyled:i,children:o,store:s,vars:c,onOptionSubmit:l,onClose:d,size:f,dropdownPadding:p,resetSelectionOnOptionHover:m,__staticSelector:h,readOnly:g,attributes:_,floatingHeight:v,middlewares:y,...b}=t,x=v===`viewport`?{...y,flip:!1,size:{...typeof y?.size==`object`?y.size:{},padding:typeof y?.size==`object`&&y.size.padding!==void 0?y.size.padding:10,apply:({availableHeight:e,availableWidth:t,elements:n,...r})=>{n.floating.style.setProperty(`--combobox-floating-max-height`,`${e}px`);let i=y?.size;typeof i==`object`&&i.apply?i.apply({availableHeight:e,availableWidth:t,elements:n,...r}):i&&Object.assign(n.floating.style,{maxWidth:`${t}px`,maxHeight:`${e}px`})}}}:y,S=Wn(),C=s||S,w=a({name:h||`Combobox`,classes:_n,props:t,classNames:n,styles:r,unstyled:i,attributes:_,vars:c,varsResolver:Kn}),T=()=>{d?.(),C.closeDropdown()};return(0,H.jsx)(xn,{value:{getStyles:w,store:C,onOptionSubmit:l,size:f,resetSelectionOnOptionHover:m,readOnly:g,floatingHeight:v},children:(0,H.jsx)(Ne,{opened:C.dropdownOpened,...b,middlewares:x,onChange:e=>!e&&T(),withRoles:!1,unstyled:i,children:o})})};qn.extend=e=>e,qn.classes=_n,qn.varsResolver=Kn,qn.displayName=`@mantine/core/Combobox`,qn.Target=Bn,qn.Dropdown=wn,qn.Options=In,qn.Option=Fn,qn.Search=Rn,qn.Empty=Dn,qn.Chevron=bn,qn.Footer=jn,qn.Header=Nn,qn.EventsTarget=An,qn.DropdownTarget=En,qn.Group=Mn,qn.ClearButton=Cn,qn.HiddenInput=Pn;function Jn({children:e,role:t}){let n=(0,V.use)(D);return n?(0,H.jsx)(`div`,{role:t,"aria-labelledby":n.labelId,"aria-describedby":n.describedBy,children:e}):(0,H.jsx)(H.Fragment,{children:e})}var Yn={root:`m_5f75b09e`,body:`m_5f6e695e`,labelWrapper:`m_d3ea56bb`,label:`m_8ee546b8`,description:`m_328f68c0`,error:`m_8e8a99cc`},Xn=Yn;function Zn({__staticSelector:e,__stylesApiProps:t,className:n,classNames:r,styles:i,unstyled:s,children:c,label:l,description:u,id:d,disabled:f,error:p,size:m,labelPosition:h=`left`,bodyElement:g=`div`,labelElement:_=`label`,variant:v,style:y,vars:b,mod:x,attributes:S,...C}){let w=a({name:e,props:t,className:n,style:y,classes:Yn,classNames:r,styles:i,unstyled:s,attributes:S}),T=u?`${d}-description`:void 0,E=p&&typeof p!=`boolean`?`${d}-error`:void 0;return(0,H.jsx)(o,{...w(`root`),__vars:{"--label-fz":L(m),"--label-lh":M(m,`label-lh`)},mod:[{"label-position":h},x],variant:v,size:m,...C,children:(0,H.jsxs)(o,{component:g,htmlFor:g===`label`?d:void 0,...w(`body`),children:[c,(0,H.jsxs)(`div`,{...w(`labelWrapper`),"data-disabled":f||void 0,children:[l&&(0,H.jsx)(o,{component:_,htmlFor:_===`label`?d:void 0,...w(`label`),"data-disabled":f||void 0,children:l}),u&&(0,H.jsx)(k.Description,{id:T,size:m,__inheritStyles:!1,...w(`description`),children:u}),p&&typeof p!=`boolean`&&(0,H.jsx)(k.Error,{id:E,size:m,__inheritStyles:!1,...w(`error`),children:p})]})]})})}Zn.displayName=`@mantine/core/InlineInput`;function Qn(e){return`group`in e}function $n({options:e,search:t,limit:n}){let r=t.trim().toLowerCase(),i=[];for(let a=0;a0)return!1;return!0}function tr(e,t=new Set){if(Array.isArray(e))for(let n of e)if(Qn(n))tr(n.items,t);else{if(n.value===void 0)throw Error(`[@mantine/core] Each option must have value property`);if(t.has(n.value))throw Error(`[@mantine/core] Duplicate options are not supported. Option with value "${n.value}" was provided more than once`);t.add(n.value)}}function nr(e,t){return Array.isArray(e)?e.includes(t):e===t}function rr({data:e,withCheckIcon:t,withAlignedLabels:n,value:r,checkIconPosition:i,unstyled:a,renderOption:o}){if(!Qn(e)){let s=nr(r,e.value),c=t&&(s?(0,H.jsx)(Ke,{className:_n.optionsDropdownCheckIcon}):n?(0,H.jsx)(`div`,{className:_n.optionsDropdownCheckPlaceholder}):null),l=(0,H.jsxs)(H.Fragment,{children:[i===`left`&&c,(0,H.jsx)(`span`,{children:e.label}),i===`right`&&c]});return(0,H.jsx)(qn.Option,{value:e.value,disabled:e.disabled,className:_({[_n.optionsDropdownOption]:!a}),"data-reverse":i===`right`||void 0,"data-checked":s||void 0,"aria-selected":s,active:s,children:typeof o==`function`?o({option:e,checked:s}):l})}let s=e.items.map(e=>(0,H.jsx)(rr,{data:e,value:r,unstyled:a,withCheckIcon:t,withAlignedLabels:n,checkIconPosition:i,renderOption:o},`${e.value}`));return(0,H.jsx)(qn.Group,{label:e.group,children:s})}function ir({data:e,hidden:t,hiddenWhenEmpty:n,filter:r,search:i,limit:a,maxDropdownHeight:o,floatingHeight:s,withScrollArea:c=!0,filterOptions:l=!0,withCheckIcon:u=!1,withAlignedLabels:d=!1,value:f,checkIconPosition:p,nothingFoundMessage:m,unstyled:h,labelId:g,renderOption:_,scrollAreaProps:v,"aria-label":y}){let b=Sn();tr(e);let x=typeof i==`string`?(r||$n)({options:e,search:l?i:``,limit:a??1/0}):e,S=er(x),C=x.map((e,t)=>(0,H.jsx)(rr,{data:e,withCheckIcon:u,withAlignedLabels:d,value:f,checkIconPosition:p,unstyled:h,renderOption:_},Qn(e)?`group-${typeof e.group==`string`?e.group:t}`:`${e.value}`));return(0,H.jsx)(qn.Dropdown,{hidden:t||n&&S,"data-composed":!0,children:(0,H.jsxs)(qn.Options,{labelledBy:g,"aria-label":y,children:[c?(0,H.jsx)(pe.Autosize,{mah:(s??b.floatingHeight)===`viewport`?`var(--combobox-floating-options-max-height)`:o??220,type:`scroll`,scrollbarSize:`var(--combobox-padding)`,offsetScrollbars:`y`,...v,children:C}):C,S&&m&&(0,H.jsx)(qn.Empty,{children:m})]})})}function ar(e,t,n,r){if(t===n||r===`before`&&n===t+1||r===`after`&&n===t-1)return e;let i=e.slice(),[a]=i.splice(t,1),o=t{let t=e.lastElementChild;return t?t instanceof HTMLInputElement?t:t.querySelector(`input`):null},sr=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n{let e=i.current;e&&(i.current=null,sr(o.current,e.expectedValue)&&e.container?.querySelector(`[data-mantine-pill-index="${e.index}"]`)?.focus())});let s=(0,V.useCallback)(e=>{a.current=e},[]);return{getPillProps:e=>{if(n)return{draggable:!0,tabIndex:-1,"data-mantine-pill-index":e,"aria-keyshortcuts":`Alt+ArrowLeft Alt+ArrowRight`,onMouseDown:e=>{e.button===0&&e.stopPropagation()},onDragStart:t=>{t.stopPropagation(),t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,String(e)),r.current.draggedIndex=e;let n=t.currentTarget,i=n.getBoundingClientRect(),a=n.cloneNode(!0);a.removeAttribute(`data-dragging`),a.removeAttribute(`data-drag-over`),a.style.position=`fixed`,a.style.top=`-9999px`,a.style.left=`-9999px`,a.style.width=`${i.width}px`,a.style.height=`${i.height}px`,a.style.pointerEvents=`none`,document.body.appendChild(a),t.dataTransfer.setDragImage(a,t.clientX-i.left,t.clientY-i.top),setTimeout(()=>a.parentNode?.removeChild(a),0),requestAnimationFrame(()=>{n.setAttribute(`data-dragging`,`true`)})},onDragOver:t=>{let{draggedIndex:n}=r.current;if(n===null||n===e)return;let i=t.currentTarget,a=i.getBoundingClientRect(),o=t.clientX-a.left,s=(getComputedStyle(i).direction===`rtl`?o>a.width/2:o{let t=e.currentTarget,n=e.relatedTarget;n&&t.contains(n)||(t.removeAttribute(`data-drag-over`),r.current.currentDropTarget===t&&(r.current.currentDropTarget=null))},onDrop:n=>{n.preventDefault(),n.stopPropagation();let i=n.currentTarget,a=i.getAttribute(`data-drag-over`);i.removeAttribute(`data-drag-over`);let{draggedIndex:s}=r.current;if(s!==null&&a&&s!==e){let n=ar(o.current,s,e,a);n!==o.current&&t(n)}r.current.draggedIndex=null,r.current.currentDropTarget=null},onDragEnd:e=>{e.currentTarget.removeAttribute(`data-dragging`);let t=r.current.currentDropTarget;t&&t.removeAttribute(`data-drag-over`),r.current.draggedIndex=null,r.current.currentDropTarget=null},onKeyDown:n=>{if(n.key!==`ArrowLeft`&&n.key!==`ArrowRight`)return;let r=n.currentTarget,a=getComputedStyle(r).direction===`rtl`?n.key===`ArrowLeft`:n.key===`ArrowRight`,s=a?e+1:e-1;if(n.altKey){if(s<0||s>=o.current.length)return;n.preventDefault(),n.stopPropagation();let c=a?`after`:`before`,l=ar(o.current,e,s,c);if(l===o.current)return;i.current={container:r.parentElement,index:s,expectedValue:l},t(l);return}if(s<0)return;let c=r.parentElement;if(c){if(n.preventDefault(),n.stopPropagation(),s>=o.current.length){or(c)?.focus();return}c.querySelector(`[data-mantine-pill-index="${s}"]`)?.focus()}}}},getListProps:()=>n?{ref:s}:{},handleInputKeyDown:e=>{if(!n||e.key!==`ArrowLeft`)return;let t=e.currentTarget;if(!(t.value.length===0||t.selectionStart===0&&t.selectionEnd===0))return;let r=a.current;if(!r)return;let i=r.querySelectorAll(`[data-mantine-pill-index]`);i.length!==0&&(e.preventDefault(),i[i.length-1].focus())}}}function lr({id:e,label:t,labelProps:n,inputWrapperOrder:r}){if(t&&(!r||r.includes(`label`)))return n?.id||`${e}-label`}function ur(e){let t=e.currentTarget;return Yt(t).activeElement!==t}var dr=(0,V.createContext)(null),fr={root:`m_7cda1cd6`,"root--default":`m_44da308b`,"root--contrast":`m_e3a01f8`,label:`m_1e0e6180`,remove:`m_ae386778`,group:`m_1dcfd90b`},pr=(0,V.createContext)(null),mr=g((e,{gap:t},{size:n})=>({group:{"--pg-gap":t===void 0?M(n,`pg-gap`):M(t)}})),hr=h(e=>{let t=u(`PillGroup`,null,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,size:d,disabled:f,attributes:p,...m}=t,h=(0,V.use)(dr)?.size||d||void 0,g=a({name:`PillGroup`,classes:fr,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:p,vars:l,varsResolver:mr,stylesCtx:{size:h},rootSelector:`group`});return(0,H.jsx)(pr,{value:{size:h,disabled:f},children:(0,H.jsx)(o,{size:h,...g(`group`),...m})})});hr.classes=fr,hr.varsResolver=mr,hr.displayName=`@mantine/core/PillGroup`;var gr={variant:`default`},_r=g((e,{radius:t},{size:n})=>({root:{"--pill-fz":M(n,`pill-fz`),"--pill-height":M(n,`pill-height`),"--pill-radius":t===void 0?void 0:ne(t)}})),vr=h(e=>{let t=u(`Pill`,gr,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,variant:d,children:f,withRemoveButton:p,onRemove:m,removeButtonProps:h,radius:g,size:_,disabled:v,mod:y,attributes:b,...x}=t,S=(0,V.use)(pr),C=(0,V.use)(dr),w=_||S?.size||void 0,T=C?.variant===`filled`?`contrast`:d||`default`,E=a({name:`Pill`,classes:fr,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:b,vars:l,varsResolver:_r,stylesCtx:{size:w}});return(0,H.jsxs)(o,{component:`span`,variant:T,size:w,...E(`root`,{variant:T}),mod:[{"with-remove":p&&!v,disabled:v||S?.disabled},y],...x,children:[(0,H.jsx)(`span`,{...E(`label`),children:f}),p&&(0,H.jsx)(ae,{variant:`transparent`,radius:g,tabIndex:-1,"aria-hidden":!0,unstyled:c,...h,...E(`remove`,{className:h?.className,style:h?.style}),onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),h?.onMouseDown?.(e)},onClick:e=>{e.stopPropagation(),m?.(),h?.onClick?.(e)}})]})});vr.classes=fr,vr.varsResolver=_r,vr.displayName=`@mantine/core/Pill`,vr.Group=hr;var yr={field:`m_45c4369d`},br={type:`visible`},xr=h(e=>{let t=u(`PillsInputField`,br,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,type:d,disabled:f,id:p,pointer:m,mod:h,attributes:g,ref:_,...v}=t,y=(0,V.use)(dr),b=(0,V.use)(D),x=a({name:`PillsInputField`,classes:yr,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:g,rootSelector:`field`}),S=f||y?.disabled;return(0,H.jsx)(o,{component:`input`,ref:re(_,y?.fieldRef),"data-type":d,disabled:S,mod:[{disabled:S,pointer:m},h],...x(`field`),...v,id:b?.inputId||p,"aria-invalid":y?.hasError,"aria-describedby":b?.describedBy,type:`text`,onMouseDown:e=>!m&&e.stopPropagation()})});xr.classes=yr,xr.displayName=`@mantine/core/PillsInputField`;var Sr={size:`sm`},Cr=h(e=>{let{children:t,onMouseDown:n,onClick:r,size:i,disabled:a,__staticSelector:o,error:s,variant:c,...l}=u([`Input`,`InputWrapper`,`PillsInput`],Sr,e),d=(0,V.useRef)(null);return(0,H.jsx)(dr,{value:{fieldRef:d,size:i,disabled:a,hasError:!!s,variant:c},children:(0,H.jsx)(N,{size:i,error:s,variant:c,component:`div`,"data-no-overflow":!0,onMouseDown:e=>{e.preventDefault(),n?.(e),d.current?.focus()},onClick:e=>{e.preventDefault(),e.currentTarget.closest(`fieldset`)?.disabled||(d.current?.focus(),r?.(e))},...l,multiline:!0,disabled:a,__staticSelector:o||`PillsInput`,withAria:!1,children:t})})});Cr.displayName=`@mantine/core/PillsInput`,Cr.classes=N.classes,Cr.Field=xr;function wr(e,t){let n=t.trim().toLowerCase();if(n===``)return;let r=Object.values(e).filter(e=>!e.disabled&&e.label.trim().toLowerCase()===n);return r.length===1?r[0]:void 0}function Tr(e){return typeof e==`string`?e.trim().toLowerCase():e}function Er({data:e,value:t}){let n=t.map(Tr);return e.reduce((e,t)=>(Qn(t)?e.push({group:t.group,items:t.items.filter(e=>n.indexOf(Tr(e.value))===-1)}):n.indexOf(Tr(t.value))===-1&&e.push(t),e),[])}var Dr={xs:41,sm:50,md:60,lg:72,xl:89},Or={maxValues:1/0,withCheckIcon:!0,checkIconPosition:`left`,hiddenInputValuesDivider:`,`,clearSearchOnChange:!0,openOnFocus:!0,size:`sm`},kr=c(e=>{let t=u([`Input`,`InputWrapper`,`MultiSelect`],Or,e),{classNames:n,className:r,style:i,styles:o,unstyled:s,vars:c,size:l,value:f,defaultValue:p,onChange:m,onKeyDown:h,variant:g,data:_,dropdownOpened:v,defaultDropdownOpened:y,onDropdownOpen:b,onDropdownClose:x,selectFirstOptionOnChange:S,selectFirstOptionOnDropdownOpen:C,onOptionSubmit:w,comboboxProps:T,filter:E,limit:D,withScrollArea:O,maxDropdownHeight:k,floatingHeight:j,searchValue:M,defaultSearchValue:N,onSearchChange:P,readOnly:I,disabled:L,onFocus:ee,onBlur:R,radius:te,rightSection:ne,rightSectionWidth:re,rightSectionPointerEvents:ie,rightSectionProps:z,leftSection:ae,leftSectionWidth:B,leftSectionPointerEvents:oe,leftSectionProps:se,inputContainer:ce,inputWrapperOrder:le,withAsterisk:ue,labelProps:de,descriptionProps:fe,errorProps:pe,successProps:me,wrapperProps:he,description:ge,label:_e,error:ve,success:ye,maxValues:be,searchable:xe,nothingFoundMessage:Se,withCheckIcon:Ce,withAlignedLabels:we,checkIconPosition:Te,hidePickedOptions:Ee,withErrorStyles:De,withSuccessStyles:Oe,name:ke,form:Ae,id:je,clearable:Me,clearSectionMode:Ne,clearButtonProps:Pe,hiddenInputProps:Fe,placeholder:Ie,hiddenInputValuesDivider:Le,required:Re,mod:Be,renderOption:Ve,renderPill:He,onRemove:Ue,onClear:We,onMaxValues:Ge,scrollAreaProps:Ke,chevronColor:qe,attributes:Je,clearSearchOnChange:Ye,openOnFocus:Xe,loading:Ze,loadingPosition:Qe,withPillsReorder:$e,...et}=t,tt=F(je),nt=lr({id:tt,label:_e,labelProps:de,inputWrapperOrder:le}),rt=hn(_),it=gn(rt),at=(0,V.useRef)({}),ot=Wn({opened:v,defaultOpened:y,onDropdownOpen:()=>{b?.(),C&&ot.selectFirstOption()},onDropdownClose:()=>{x?.(),ot.resetSelectedOption()}}),{styleProps:st,rest:{type:ct,autoComplete:lt,...ut}}=d(et),[dt,ft]=ze({value:f,defaultValue:p,finalValue:[],onChange:m}),{getPillProps:pt,getListProps:mt,handleInputKeyDown:ht}=cr({value:dt,onChange:ft,enabled:$e&&!L&&!I}),[gt,_t]=ze({value:M,defaultValue:N,finalValue:``,onChange:P}),vt=e=>{_t(e),ot.resetSelectedOption()},yt=a({name:`MultiSelect`,classes:{},props:t,classNames:n,styles:o,unstyled:s,attributes:Je}),{resolvedClassNames:bt,resolvedStyles:xt}=A({props:t,styles:o,classNames:n}),St=e=>{h?.(e),!e.defaultPrevented&&(e.key===` `&&!xe&&(e.preventDefault(),ot.toggleDropdown()),e.key===`Backspace`&>.length===0&&dt.length>0&&!I&&(Ue?.(dt[dt.length-1]),ft(dt.slice(0,dt.length-1))),ht(e))},Ct=dt.map((e,t)=>{let n=it[`${e}`]||at.current[`${e}`],r=pt(t);return He?(0,H.jsx)(V.Fragment,{children:He({option:n,value:e,onRemove:()=>{ft(dt.filter(t=>e!==t)),Ue?.(e)},disabled:L,reorderProps:r})},`${e}-${t}`):(0,H.jsx)(vr,{withRemoveButton:!I&&!it[`${e}`]?.disabled,onRemove:()=>{ft(dt.filter(t=>e!==t)),Ue?.(e)},unstyled:s,disabled:L,...yt(`pill`),...r,children:n?.label||e},`${e}-${t}`)});(0,V.useEffect)(()=>{S&&ot.selectFirstOption()},[S,gt]),(0,V.useEffect)(()=>{dt.forEach(e=>{`${e}`in it&&(at.current[`${e}`]=it[`${e}`])})},[it,dt]);let wt=(0,H.jsx)(qn.ClearButton,{...Pe,onClear:()=>{We?.(),ft([]),vt(``)}}),Tt=Er({data:rt,value:dt}),Et=Me&&dt.length>0&&!L&&!I,Dt=Et?{paddingInlineEnd:Dr[l]??Dr.sm}:void 0;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(qn,{store:ot,classNames:bt,styles:xt,unstyled:s,size:l,readOnly:I,__staticSelector:`MultiSelect`,attributes:Je,floatingHeight:j,onOptionSubmit:e=>{w?.(e),Ye&&vt(``),ot.updateSelectedOptionIndex(`selected`),dt.includes(it[`${e}`].value)?(ft(dt.filter(t=>t!==it[`${e}`].value)),Ue?.(it[`${e}`].value)):dt.lengthxe?ot.openDropdown():ot.toggleDropdown(),"data-expanded":ot.dropdownOpened||void 0,id:tt,required:Re,mod:Be,attributes:Je,children:(0,H.jsxs)(vr.Group,{attributes:Je,disabled:L,unstyled:s,...yt(`pillsList`,{style:Dt}),...mt(),children:[Ct,(0,H.jsx)(qn.EventsTarget,{autoComplete:lt,withExpandedAttribute:!0,children:(0,H.jsx)(Cr.Field,{...ut,id:tt,placeholder:Ie,type:!xe&&!Ie?`hidden`:`visible`,...yt(`inputField`),unstyled:s,onFocus:e=>{ee?.(e),Xe&&xe&&ot.openDropdown()},onBlur:e=>{R?.(e),ot.closeDropdown(),vt(``)},onKeyDown:St,value:gt,onChange:e=>{if(ur(e)){if(!I){let t=wr(it,e.currentTarget.value);t&&!dt.includes(t.value)&&dt.length{let{classNames:t,className:n,style:r,styles:i,vars:a,...s}=u(`ProgressLabel`,null,e),c=jr();return(0,H.jsx)(o,{...c.getStyles(`label`,{className:n,style:r,classNames:t,styles:i}),...s})});Nr.classes=Mr,Nr.displayName=`@mantine/core/ProgressLabel`;var Pr=g((e,{size:t,radius:n,transitionDuration:r})=>({root:{"--progress-size":M(t,`progress-size`),"--progress-radius":n===void 0?void 0:ne(n),"--progress-transition-duration":typeof r==`number`?`${r}ms`:void 0}})),Fr=h(e=>{let t=u(`ProgressRoot`,null,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,autoContrast:d,transitionDuration:f,orientation:p,attributes:m,mod:h,...g}=t,_=a({name:`Progress`,classes:Mr,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:m,vars:l,varsResolver:Pr});return(0,H.jsx)(Ar,{value:{getStyles:_,autoContrast:d},children:(0,H.jsx)(o,{mod:[{orientation:p},h],..._(`root`),...g})})});Fr.classes=Mr,Fr.varsResolver=Pr,Fr.displayName=`@mantine/core/ProgressRoot`;var Ir={withAria:!0},Lr=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,value:s,withAria:c,color:d,striped:p,animated:m,mod:h,...g}=u(`ProgressSection`,Ir,e),_=jr(),v=f(),y=c?{role:`progressbar`,"aria-valuemax":100,"aria-valuemin":0,"aria-valuenow":s,"aria-valuetext":`${s}%`}:{};return(0,H.jsx)(o,{..._.getStyles(`section`,{className:n,classNames:t,styles:i,style:r}),...g,...y,mod:[{striped:p||m,animated:m},h],__vars:{"--progress-section-size":`${s}%`,"--progress-section-color":l(d,v),"--progress-label-color":Xt(_.autoContrast,v)?st({color:d,theme:v,autoContrast:_.autoContrast}):void 0}})});Lr.classes=Mr,Lr.displayName=`@mantine/core/ProgressSection`;var Rr=h(e=>{let t=u(`Progress`,null,e),{value:n,classNames:r,styles:i,vars:a,color:o,striped:s,animated:c,"aria-label":l,...d}=t,{resolvedClassNames:f,resolvedStyles:p}=A({classNames:r,styles:i,props:t});return(0,H.jsx)(Fr,{classNames:f,styles:p,vars:a,...d,children:(0,H.jsx)(Lr,{value:n,color:o,striped:s,animated:c,"aria-label":l})})});Rr.classes=Mr,Rr.displayName=`@mantine/core/Progress`,Rr.Section=Lr,Rr.Root=Fr,Rr.Label=Nr;var zr={root:`m_cf365364`,indicator:`m_9e182ccd`,label:`m_1738fcb2`,input:`m_1714d588`,control:`m_69686b9b`,innerLabel:`m_78882f40`},Br={withItemsBorders:!0},Vr=g((e,{radius:t,color:n,transitionDuration:r,size:i,transitionTimingFunction:a})=>({root:{"--sc-radius":t===void 0?void 0:ne(t),"--sc-color":n?l(n,e):void 0,"--sc-shadow":n?void 0:`var(--mantine-shadow-xs)`,"--sc-transition-duration":r===void 0?void 0:`${r}ms`,"--sc-transition-timing-function":a,"--sc-padding":M(i,`sc-padding`),"--sc-font-size":L(i)}})),Hr=c(e=>{let t=u(`SegmentedControl`,Br,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,data:d,value:p,defaultValue:m,onChange:h,size:g,name:_,disabled:v,readOnly:y,fullWidth:b,orientation:x,radius:S,color:C,transitionDuration:w,transitionTimingFunction:T,variant:E,autoContrast:D,withItemsBorders:O,mod:k,attributes:A,ref:j,...M}=t,N=a({name:`SegmentedControl`,props:t,classes:zr,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:A,vars:l,varsResolver:Vr}),P=f(),I=d.map(e=>Kt(e)?{label:`${e}`,value:e}:e),L=Gt(),[ee,R]=(0,V.useState)(0),[te,ne]=(0,V.useState)(null),[ie,z]=(0,V.useState)({}),ae=(e,t)=>{e!==null&&ie[t]!==e&&(ie[t]=e,z({...ie}))},[B,oe]=ze({value:p,defaultValue:m,finalValue:Array.isArray(d)?I.find(e=>!e.disabled)?.value??d[0]?.value??null:null,onChange:h}),se=F(_),ce=I.map(e=>`${e.value}`),le=I.map(e=>(0,V.createElement)(o,{...N(`control`),mod:{active:B===e.value,orientation:x},key:`${e.value}`},(0,V.createElement)(`input`,{...N(`input`),disabled:v||e.disabled,type:`radio`,name:se,value:`${e.value}`,id:`${se}-${e.value}`,checked:B===e.value,onChange:()=>!y&&oe(e.value),"data-focus-ring":P.focusRing,key:`${e.value}-input`}),(0,V.createElement)(o,{component:`label`,...N(`label`),mod:{active:B===e.value&&!(v||e.disabled),disabled:v||e.disabled,"read-only":y},htmlFor:`${se}-${e.value}`,ref:t=>ae(t,`${e.value}`),__vars:{"--sc-label-color":C===void 0?void 0:st({color:C,theme:P,autoContrast:D})},key:`${e.value}-label`},(0,H.jsx)(`span`,{...N(`innerLabel`),children:e.label})))),ue=re(j,ne);return Vt(()=>{R(e=>e+1)},[d.length]),Vt(()=>{z(e=>{let t={};return ce.forEach(n=>{n in e&&(t[n]=e[n])}),Object.keys(t).length===Object.keys(e).length?e:t})},[ce]),d.length===0?null:(0,H.jsxs)(o,{...N(`root`),variant:E,size:g,ref:ue,mod:[{"full-width":b,orientation:x,initialized:L,"with-items-borders":O},k],...M,role:`radiogroup`,"data-disabled":v,children:[B!==void 0&&(0,H.jsx)(tn,{target:ie[`${B}`],parent:te,component:`span`,transitionDuration:`var(--sc-transition-duration)`,...N(`indicator`)},ee),le]})});Hr.classes=zr,Hr.varsResolver=Vr,Hr.displayName=`@mantine/core/SegmentedControl`;var Ur={size:`sm`,withCheckIcon:!0,allowDeselect:!0,checkIconPosition:`left`,openOnFocus:!0},Wr=c(e=>{let t=u([`Input`,`InputWrapper`,`Select`],Ur,e),{classNames:n,styles:r,unstyled:i,vars:a,dropdownOpened:o,defaultDropdownOpened:s,onDropdownClose:c,onDropdownOpen:l,onFocus:d,onBlur:f,onClick:p,onChange:m,data:h,value:g,defaultValue:_,selectFirstOptionOnChange:v,selectFirstOptionOnDropdownOpen:y,onOptionSubmit:b,comboboxProps:x,readOnly:S,disabled:C,filter:w,limit:T,withScrollArea:E,maxDropdownHeight:D,floatingHeight:O,size:k,searchable:j,rightSection:M,checkIconPosition:P,withCheckIcon:I,withAlignedLabels:L,nothingFoundMessage:ee,name:R,form:te,searchValue:ne,defaultSearchValue:re,onSearchChange:ie,allowDeselect:z,error:ae,rightSectionPointerEvents:B,id:oe,clearable:se,clearSectionMode:ce,clearButtonProps:le,hiddenInputProps:ue,renderOption:de,onClear:fe,autoComplete:pe,scrollAreaProps:me,__defaultRightSection:he,__clearSection:ge,__clearable:_e,chevronColor:ve,autoSelectOnBlur:ye,openOnFocus:be,attributes:xe,...Se}=t,Ce=(0,V.useMemo)(()=>hn(h),[h]),we=(0,V.useRef)({}),Te=(0,V.useMemo)(()=>gn(Ce),[Ce]),Ee=F(oe),De=lr({id:Ee,label:Se.label,labelProps:Se.labelProps,inputWrapperOrder:Se.inputWrapperOrder}),[Oe,ke,Ae]=ze({value:g,defaultValue:_,finalValue:null,onChange:m}),je=Oe==null?void 0:`${Oe}`in Te?Te[`${Oe}`]:we.current[`${Oe}`],Me=Ut(je),[Ne,Pe,Fe]=ze({value:ne,defaultValue:re,finalValue:je?je.label:``,onChange:ie}),Ie=Wn({opened:o,defaultOpened:s,onDropdownOpen:()=>{l?.(),y?Ie.selectFirstOption():Ie.updateSelectedOptionIndex(`active`,{scrollIntoView:!0})},onDropdownClose:()=>{c?.(),setTimeout(Ie.resetSelectedOption,0)}}),Le=e=>{Pe(e),Ie.resetSelectedOption()},{resolvedClassNames:Re,resolvedStyles:Be}=A({props:t,styles:r,classNames:n});(0,V.useEffect)(()=>{v&&Ie.selectFirstOption()},[v,Ne]),(0,V.useEffect)(()=>{g===null&&Le(``),g!=null&&je&&(Me?.value!==je.value||Me?.label!==je.label)&&Le(je.label)},[g,je]),(0,V.useEffect)(()=>{!Ae&&!Fe&&Le(Oe==null?``:`${Oe}`in Te?Te[`${Oe}`]?.label:we.current[`${Oe}`]?.label||``)},[Te,Oe]),(0,V.useEffect)(()=>{Oe&&`${Oe}`in Te&&(we.current[`${Oe}`]=Te[`${Oe}`])},[Te,Oe]);let Ve=(0,H.jsx)(qn.ClearButton,{...le,onClear:()=>{ke(null,null),Le(``),fe?.()}}),He=se&&Oe!=null&&!C&&!S;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(qn,{store:Ie,__staticSelector:`Select`,classNames:Re,styles:Be,unstyled:i,readOnly:S,size:k,attributes:xe,floatingHeight:O,keepMounted:ye,onOptionSubmit:e=>{b?.(e);let t=z&&`${Te[e].value}`==`${Oe}`?null:Te[e],n=t?t.value:null;n!==Oe&&ke(n,t),!Ae&&Le(n==null?``:t?.label||``),Ie.closeDropdown()},...x,children:[(0,H.jsx)(qn.Target,{targetType:j?`input`:`button`,autoComplete:pe,withExpandedAttribute:!0,children:(0,H.jsx)(N,{id:Ee,__defaultRightSection:(0,H.jsx)(qn.Chevron,{size:k,error:ae,unstyled:i,color:ve}),__clearSection:Ve,__clearable:He,__clearSectionMode:ce,rightSection:M,rightSectionPointerEvents:B||`none`,...Se,size:k,__staticSelector:`Select`,disabled:C,readOnly:S||!j,value:Ne,onChange:e=>{if(ur(e)){if(!S){let t=wr(Te,e.currentTarget.value);t&&`${t.value}`!=`${Oe}`&&(ke(t.value,t),!Ae&&Le(t.label))}return}Le(e.currentTarget.value),Ie.openDropdown(),v&&Ie.selectFirstOption()},onFocus:e=>{be&&j&&Ie.openDropdown(),d?.(e)},onBlur:e=>{ye&&Ie.clickSelectedOption(),Ie.closeDropdown();let t=Oe!=null&&(`${Oe}`in Te?Te[`${Oe}`]:we.current[`${Oe}`]);Le(t&&t.label||``),f?.(e)},onClick:e=>{j?Ie.openDropdown():Ie.toggleDropdown(),p?.(e)},classNames:Re,styles:Be,unstyled:i,pointer:!j,error:ae,attributes:xe})}),(0,H.jsx)(ir,{data:Ce,hidden:S||C,filter:w,search:Ne,limit:T,hiddenWhenEmpty:!ee,withScrollArea:E,maxDropdownHeight:D,filterOptions:!!j&&je?.label!==Ne,value:Oe,checkIconPosition:P,withCheckIcon:I,withAlignedLabels:L,nothingFoundMessage:ee,unstyled:i,labelId:De,"aria-label":De?void 0:Se[`aria-label`],renderOption:de,scrollAreaProps:me})]}),(0,H.jsx)(qn.HiddenInput,{value:Oe,name:R,form:te,disabled:C,...ue})]})});Wr.classes={...N.classes,...qn.classes},Wr.displayName=`@mantine/core/Select`;function Gr(e){if(e!==void 0)return typeof e==`number`?P(e):e}function Kr({spacing:e,verticalSpacing:t,cols:n,minColWidth:r,autoRows:i,selector:a}){let o=f(),s=t===void 0?e:t,c=r!==void 0,l=E({"--sg-spacing-x":z(Lt(e)),"--sg-spacing-y":z(Lt(s)),"--sg-auto-rows":i,...c?{"--sg-min-col-width":Gr(r)}:{"--sg-cols":Lt(n)?.toString()}}),u=O(o.breakpoints).reduce((t,r)=>(t[r]||(t[r]={}),typeof e==`object`&&e[r]!==void 0&&(t[r][`--sg-spacing-x`]=z(e[r])),typeof s==`object`&&s[r]!==void 0&&(t[r][`--sg-spacing-y`]=z(s[r])),!c&&typeof n==`object`&&n[r]!==void 0&&(t[r][`--sg-cols`]=n[r]),t),{}),d=Ge(O(u),o.breakpoints).filter(e=>O(u[e.value]).length>0).map(e=>({query:`(min-width: ${o.breakpoints[e.value]})`,styles:u[e.value]}));return(0,H.jsx)(j,{styles:l,media:d,selector:a})}function qr(e){return typeof e==`object`&&e?O(e):[]}function Jr(e){return e.sort((e,t)=>We(e)-We(t))}function Yr({spacing:e,verticalSpacing:t,cols:n,minColWidth:r}){return Jr(Array.from(new Set([...qr(e),...qr(t),...r===void 0?qr(n):[]])))}function Xr({spacing:e,verticalSpacing:t,cols:n,minColWidth:r,autoRows:i,selector:a}){let o=t===void 0?e:t,s=r!==void 0,c=E({"--sg-spacing-x":z(Lt(e)),"--sg-spacing-y":z(Lt(o)),"--sg-auto-rows":i,...s?{"--sg-min-col-width":Gr(r)}:{"--sg-cols":Lt(n)?.toString()}}),l=Yr({spacing:e,verticalSpacing:t,cols:n,minColWidth:r}),u=l.reduce((t,r)=>(t[r]||(t[r]={}),typeof e==`object`&&e[r]!==void 0&&(t[r][`--sg-spacing-x`]=z(e[r])),typeof o==`object`&&o[r]!==void 0&&(t[r][`--sg-spacing-y`]=z(o[r])),!s&&typeof n==`object`&&n[r]!==void 0&&(t[r][`--sg-cols`]=n[r]),t),{}),d=l.map(e=>({query:`simple-grid (min-width: ${e})`,styles:u[e]}));return(0,H.jsx)(j,{styles:c,container:d,selector:a})}var Zr={container:`m_925c2d2c`,root:`m_2415a157`},Qr={cols:1,spacing:`md`,type:`media`},$r=h(e=>{let t=u(`SimpleGrid`,Qr,e),{classNames:n,className:r,style:i,styles:c,unstyled:l,vars:d,cols:f,verticalSpacing:p,spacing:m,type:h,minColWidth:g,autoFlow:_,autoRows:v,attributes:y,...b}=t,x=a({name:`SimpleGrid`,classes:Zr,props:t,className:r,style:i,classNames:n,styles:c,unstyled:l,attributes:y,vars:d}),S=s(),C=g===void 0?void 0:_||`auto-fill`;return h===`container`?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Xr,{...t,selector:`.${S}`}),(0,H.jsx)(`div`,{...x(`container`),children:(0,H.jsx)(o,{...x(`root`,{className:S}),...b,"data-auto-cols":C})})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Kr,{...t,selector:`.${S}`}),(0,H.jsx)(o,{...x(`root`,{className:S}),...b,"data-auto-cols":C})]})});$r.classes=Zr,$r.displayName=`@mantine/core/SimpleGrid`;var ei=(0,V.createContext)(null),ti={hiddenInputValuesSeparator:`,`},ni=c((e=>{let{value:t,defaultValue:n,onChange:r,size:i,wrapperProps:a,children:o,readOnly:s,name:c,hiddenInputValuesSeparator:l,hiddenInputProps:d,maxSelectedValues:f,disabled:p,...m}=u(`SwitchGroup`,ti,e),[h,g]=ze({value:t,defaultValue:n,finalValue:[],onChange:r}),_=e=>{let t=e.currentTarget.value;if(s)return;let n=h.includes(t);!n&&f&&h.length>=f||g(n?h.filter(e=>e!==t):[...h,t])},v=e=>{if(p)return!0;if(!f)return!1;let t=h.includes(e),n=h.length>=f;return!t&&n},y=h.join(l);return(0,H.jsx)(ei,{value:{value:h,onChange:_,size:i,isDisabled:v},children:(0,H.jsxs)(k.Wrapper,{size:i,...a,...m,labelElement:`div`,__staticSelector:`SwitchGroup`,children:[(0,H.jsx)(Jn,{role:`group`,children:o}),(0,H.jsx)(`input`,{type:`hidden`,name:c,value:y,...d})]})})}));ni.classes=k.Wrapper.classes,ni.displayName=`@mantine/core/SwitchGroup`;var ri={root:`m_5f93f3bb`,input:`m_926b4011`,track:`m_9307d992`,thumb:`m_93039a1d`,trackLabel:`m_8277e082`},ii={labelPosition:`right`,withThumbIndicator:!0},ai=g((e,{radius:t,color:n,size:r})=>({root:{"--switch-radius":t===void 0?void 0:ne(t),"--switch-height":M(r,`switch-height`),"--switch-width":M(r,`switch-width`),"--switch-thumb-size":M(r,`switch-thumb-size`),"--switch-label-font-size":M(r,`switch-label-font-size`),"--switch-track-label-padding":M(r,`switch-track-label-padding`),"--switch-color":n?l(n,e):void 0}})),oi=h(e=>{let t=u(`Switch`,ii,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,color:f,label:p,offLabel:m,onLabel:h,id:g,size:_,radius:v,wrapperProps:y,thumbIcon:b,checked:x,defaultChecked:S,onChange:C,labelPosition:w,description:T,error:E,disabled:D,variant:O,rootRef:k,mod:A,withThumbIndicator:j,attributes:M,...N}=t,P=(0,V.use)(ei),I=_||P?.size,L=a({name:`Switch`,props:t,classes:ri,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:M,vars:l,varsResolver:ai}),{styleProps:ee,rest:R}=d(N),te=F(g),ne=[T?`${te}-description`:void 0,E&&typeof E!=`boolean`?`${te}-error`:void 0,R[`aria-describedby`]].filter(Boolean).join(` `)||void 0,re={checked:P?.value.includes(R.value)??x,onChange:e=>{P?.onChange(e),C?.(e)}},ie=D||P?.isDisabled?.(R.value),[z,ae]=ze({value:re.checked??x,defaultValue:S,finalValue:!1});return(0,H.jsxs)(Zn,{...L(`root`),__staticSelector:`Switch`,__stylesApiProps:t,id:te,size:I,labelPosition:w,label:p,description:T,error:E,disabled:ie,bodyElement:`label`,labelElement:`span`,classNames:n,styles:s,unstyled:c,"data-checked":re.checked,variant:O,ref:k,mod:A,attributes:M,inert:R.inert,...ee,...y,children:[(0,H.jsx)(`input`,{...R,...re,disabled:ie,checked:z,"data-checked":re.checked,onChange:e=>{re.onChange?.(e),ae(e.currentTarget.checked)},id:te,type:`checkbox`,role:`switch`,inert:R.inert,"aria-describedby":ne,...L(`input`)}),(0,H.jsxs)(o,{"aria-hidden":`true`,component:`span`,mod:{error:E,"label-position":w,"without-labels":!h&&!m},...L(`track`),children:[(0,H.jsx)(o,{component:`span`,mod:{"reduce-motion":!0,"with-thumb-indicator":j&&!b},...L(`thumb`),children:b}),(0,H.jsx)(`span`,{...L(`trackLabel`),children:z?h:m})]})]})});oi.classes={...ri,...Xn},oi.varsResolver=ai,oi.displayName=`@mantine/core/Switch`,oi.Group=ni;var si=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M244,56v48a12,12,0,0,1-12,12H184a12,12,0,1,1,0-24H201.1l-19-17.38c-.13-.12-.26-.24-.38-.37A76,76,0,1,0,127,204h1a75.53,75.53,0,0,0,52.15-20.72,12,12,0,0,1,16.49,17.45A99.45,99.45,0,0,1,128,228h-1.37A100,100,0,1,1,198.51,57.06L220,76.72V56a12,12,0,0,1,24,0Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1-5.66-13.66l17-17-10.55-9.65-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,1,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60l10.93,10L226.34,50.3A8,8,0,0,1,240,56Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M238,56v48a6,6,0,0,1-6,6H184a6,6,0,0,1,0-12h32.55l-30.38-27.8c-.06-.06-.12-.13-.19-.19a82,82,0,1,0-1.7,117.65,6,6,0,0,1,8.24,8.73A93.46,93.46,0,0,1,128,222h-1.28A94,94,0,1,1,194.37,61.4L226,90.35V56a6,6,0,1,1,12,0Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M236,56v48a4,4,0,0,1-4,4H184a4,4,0,0,1,0-8h37.7L187.53,68.69l-.13-.12a84,84,0,1,0-1.75,120.51,4,4,0,0,1,5.5,5.82A91.43,91.43,0,0,1,128,220h-1.26A92,92,0,1,1,193,62.84l35,32.05V56a4,4,0,1,1,8,0Z`}))]]),ci=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M228,128a100,100,0,0,1-98.66,100H128a99.39,99.39,0,0,1-68.62-27.29,12,12,0,0,1,16.48-17.45,76,76,0,1,0-1.57-109c-.13.13-.25.25-.39.37L54.89,92H72a12,12,0,0,1,0,24H24a12,12,0,0,1-12-12V56a12,12,0,0,1,24,0V76.72L57.48,57.06A100,100,0,0,1,228,128Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M224,128a96,96,0,0,1-94.71,96H128A95.38,95.38,0,0,1,62.1,197.8a8,8,0,0,1,11-11.63A80,80,0,1,0,71.43,71.39a3.07,3.07,0,0,1-.26.25L44.59,96H72a8,8,0,0,1,0,16H24a8,8,0,0,1-8-8V56a8,8,0,0,1,16,0V85.8L60.25,60A96,96,0,0,1,224,128Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128a96,96,0,0,1-94.71,96H128A95.38,95.38,0,0,1,62.1,197.8a8,8,0,0,1,11-11.63A80,80,0,1,0,71.43,71.39a3.07,3.07,0,0,1-.26.25L60.63,81.29l17,17A8,8,0,0,1,72,112H24a8,8,0,0,1-8-8V56A8,8,0,0,1,29.66,50.3L49.31,70,60.25,60A96,96,0,0,1,224,128Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M222,128a94,94,0,0,1-92.74,94H128a93.43,93.43,0,0,1-64.5-25.65,6,6,0,1,1,8.24-8.72A82,82,0,1,0,70,70l-.19.19L39.44,98H72a6,6,0,0,1,0,12H24a6,6,0,0,1-6-6V56a6,6,0,0,1,12,0V90.34L61.63,61.4A94,94,0,0,1,222,128Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128a96,96,0,0,1-94.71,96H128A95.38,95.38,0,0,1,62.1,197.8a8,8,0,0,1,11-11.63A80,80,0,1,0,71.43,71.39a3.07,3.07,0,0,1-.26.25L44.59,96H72a8,8,0,0,1,0,16H24a8,8,0,0,1-8-8V56a8,8,0,0,1,16,0V85.8L60.25,60A96,96,0,0,1,224,128Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M220,128a92,92,0,0,1-90.77,92H128a91.47,91.47,0,0,1-63.13-25.1,4,4,0,1,1,5.5-5.82A84,84,0,1,0,68.6,68.57l-.13.12L34.3,100H72a4,4,0,0,1,0,8H24a4,4,0,0,1-4-4V56a4,4,0,0,1,8,0V94.89l35-32A92,92,0,0,1,220,128Z`}))]]),li=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M220,48V96a12,12,0,0,1-24,0V77l-35.51,35.52a12,12,0,0,1-17-17L179,60H160a12,12,0,0,1,0-24h48A12,12,0,0,1,220,48ZM95.51,143.51,60,179V160a12,12,0,0,0-24,0v48a12,12,0,0,0,12,12H96a12,12,0,0,0,0-24H77l35.52-35.51a12,12,0,0,0-17-17ZM208,148a12,12,0,0,0-12,12v19l-35.51-35.52a12,12,0,0,0-17,17L179,196H160a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,208,148ZM77,60H96a12,12,0,0,0,0-24H48A12,12,0,0,0,36,48V96a12,12,0,0,0,24,0V77l35.51,35.52a12,12,0,0,0,17-17Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M208,48V208H48V48Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M216,48V96a8,8,0,0,1-16,0V67.31l-42.34,42.35a8,8,0,0,1-11.32-11.32L188.69,56H160a8,8,0,0,1,0-16h48A8,8,0,0,1,216,48ZM98.34,146.34,56,188.69V160a8,8,0,0,0-16,0v48a8,8,0,0,0,8,8H96a8,8,0,0,0,0-16H67.31l42.35-42.34a8,8,0,0,0-11.32-11.32ZM208,152a8,8,0,0,0-8,8v28.69l-42.34-42.35a8,8,0,0,0-11.32,11.32L188.69,200H160a8,8,0,0,0,0,16h48a8,8,0,0,0,8-8V160A8,8,0,0,0,208,152ZM67.31,56H96a8,8,0,0,0,0-16H48a8,8,0,0,0-8,8V96a8,8,0,0,0,16,0V67.31l42.34,42.35a8,8,0,0,0,11.32-11.32Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M109.66,146.34a8,8,0,0,1,0,11.32L83.31,184l18.35,18.34A8,8,0,0,1,96,216H48a8,8,0,0,1-8-8V160a8,8,0,0,1,13.66-5.66L72,172.69l26.34-26.35A8,8,0,0,1,109.66,146.34ZM83.31,72l18.35-18.34A8,8,0,0,0,96,40H48a8,8,0,0,0-8,8V96a8,8,0,0,0,13.66,5.66L72,83.31l26.34,26.35a8,8,0,0,0,11.32-11.32ZM208,40H160a8,8,0,0,0-5.66,13.66L172.69,72,146.34,98.34a8,8,0,0,0,11.32,11.32L184,83.31l18.34,18.35A8,8,0,0,0,216,96V48A8,8,0,0,0,208,40Zm3.06,112.61a8,8,0,0,0-8.72,1.73L184,172.69l-26.34-26.35a8,8,0,0,0-11.32,11.32L172.69,184l-18.35,18.34A8,8,0,0,0,160,216h48a8,8,0,0,0,8-8V160A8,8,0,0,0,211.06,152.61Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M214,48V96a6,6,0,0,1-12,0V62.48l-45.76,45.76a6,6,0,0,1-8.48-8.48L193.52,54H160a6,6,0,0,1,0-12h48A6,6,0,0,1,214,48ZM99.76,147.76,54,193.52V160a6,6,0,0,0-12,0v48a6,6,0,0,0,6,6H96a6,6,0,0,0,0-12H62.48l45.76-45.76a6,6,0,0,0-8.48-8.48ZM208,154a6,6,0,0,0-6,6v33.52l-45.76-45.76a6,6,0,0,0-8.48,8.48L193.52,202H160a6,6,0,0,0,0,12h48a6,6,0,0,0,6-6V160A6,6,0,0,0,208,154ZM62.48,54H96a6,6,0,0,0,0-12H48a6,6,0,0,0-6,6V96a6,6,0,0,0,12,0V62.48l45.76,45.76a6,6,0,0,0,8.48-8.48Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,48V96a8,8,0,0,1-16,0V67.31l-42.34,42.35a8,8,0,0,1-11.32-11.32L188.69,56H160a8,8,0,0,1,0-16h48A8,8,0,0,1,216,48ZM98.34,146.34,56,188.69V160a8,8,0,0,0-16,0v48a8,8,0,0,0,8,8H96a8,8,0,0,0,0-16H67.31l42.35-42.34a8,8,0,0,0-11.32-11.32ZM208,152a8,8,0,0,0-8,8v28.69l-42.34-42.35a8,8,0,0,0-11.32,11.32L188.69,200H160a8,8,0,0,0,0,16h48a8,8,0,0,0,8-8V160A8,8,0,0,0,208,152ZM67.31,56H96a8,8,0,0,0,0-16H48a8,8,0,0,0-8,8V96a8,8,0,0,0,16,0V67.31l42.34,42.35a8,8,0,0,0,11.32-11.32Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M212,48V96a4,4,0,0,1-8,0V57.66l-49.17,49.17a4,4,0,0,1-5.66-5.66L198.34,52H160a4,4,0,0,1,0-8h48A4,4,0,0,1,212,48ZM101.17,149.17,52,198.34V160a4,4,0,0,0-8,0v48a4,4,0,0,0,4,4H96a4,4,0,0,0,0-8H57.66l49.17-49.17a4,4,0,0,0-5.66-5.66ZM208,156a4,4,0,0,0-4,4v38.34l-49.17-49.17a4,4,0,0,0-5.66,5.66L198.34,204H160a4,4,0,0,0,0,8h48a4,4,0,0,0,4-4V160A4,4,0,0,0,208,156ZM57.66,52H96a4,4,0,0,0,0-8H48a4,4,0,0,0-4,4V96a4,4,0,0,0,8,0V57.66l49.17,49.17a4,4,0,0,0,5.66-5.66Z`}))]]),ui=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216.49,168.49a12,12,0,0,1-17,0L128,97,56.49,168.49a12,12,0,0,1-17-17l80-80a12,12,0,0,1,17,0l80,80A12,12,0,0,1,216.49,168.49Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M208,160H48l80-80Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M213.66,154.34l-80-80a8,8,0,0,0-11.32,0l-80,80A8,8,0,0,0,48,168H208a8,8,0,0,0,5.66-13.66ZM67.31,152,128,91.31,188.69,152Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M215.39,163.06A8,8,0,0,1,208,168H48a8,8,0,0,1-5.66-13.66l80-80a8,8,0,0,1,11.32,0l80,80A8,8,0,0,1,215.39,163.06Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M212.24,164.24a6,6,0,0,1-8.48,0L128,88.49,52.24,164.24a6,6,0,0,1-8.48-8.48l80-80a6,6,0,0,1,8.48,0l80,80A6,6,0,0,1,212.24,164.24Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M213.66,165.66a8,8,0,0,1-11.32,0L128,91.31,53.66,165.66a8,8,0,0,1-11.32-11.32l80-80a8,8,0,0,1,11.32,0l80,80A8,8,0,0,1,213.66,165.66Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M210.83,162.83a4,4,0,0,1-5.66,0L128,85.66,50.83,162.83a4,4,0,0,1-5.66-5.66l80-80a4,4,0,0,1,5.66,0l80,80A4,4,0,0,1,210.83,162.83Z`}))]]),di=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M172,108a12,12,0,0,1-12,12H96a12,12,0,0,1,0-24h64A12,12,0,0,1,172,108Zm-12,28H96a12,12,0,0,0,0,24h64a12,12,0,0,0,0-24Zm76-8A108,108,0,0,1,78.77,224.15L46.34,235A20,20,0,0,1,21,209.66l10.81-32.43A108,108,0,1,1,236,128Zm-24,0A84,84,0,1,0,55.27,170.06a12,12,0,0,1,1,9.81l-9.93,29.79,29.79-9.93a12.1,12.1,0,0,1,3.8-.62,12,12,0,0,1,6,1.62A84,84,0,0,0,212,128Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128A96,96,0,0,1,79.93,211.11h0L42.54,223.58a8,8,0,0,1-10.12-10.12l12.47-37.39h0A96,96,0,1,1,224,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M128,24A104,104,0,0,0,36.18,176.88L24.83,210.93a16,16,0,0,0,20.24,20.24l34.05-11.35A104,104,0,1,0,128,24Zm0,192a87.87,87.87,0,0,1-44.06-11.81,8,8,0,0,0-4-1.08,7.85,7.85,0,0,0-2.53.42L40,216,52.47,178.6a8,8,0,0,0-.66-6.54A88,88,0,1,1,128,216Zm40-104a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,112Zm0,32a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,144Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,24A104,104,0,0,0,36.18,176.88L24.83,210.93a16,16,0,0,0,20.24,20.24l34.05-11.35A104,104,0,1,0,128,24Zm32,128H96a8,8,0,0,1,0-16h64a8,8,0,0,1,0,16Zm0-32H96a8,8,0,0,1,0-16h64a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M166,112a6,6,0,0,1-6,6H96a6,6,0,0,1,0-12h64A6,6,0,0,1,166,112Zm-6,26H96a6,6,0,0,0,0,12h64a6,6,0,0,0,0-12Zm70-10A102,102,0,0,1,79.31,217.65L44.44,229.27a14,14,0,0,1-17.71-17.71l11.62-34.87A102,102,0,1,1,230,128Zm-12,0A90,90,0,1,0,50.08,173.06a6,6,0,0,1,.5,4.91L38.12,215.35a2,2,0,0,0,2.53,2.53L78,205.42a6.2,6.2,0,0,1,1.9-.31,6.09,6.09,0,0,1,3,.81A90,90,0,0,0,218,128Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M168,112a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,112Zm-8,24H96a8,8,0,0,0,0,16h64a8,8,0,0,0,0-16Zm72-8A104,104,0,0,1,79.12,219.82L45.07,231.17a16,16,0,0,1-20.24-20.24l11.35-34.05A104,104,0,1,1,232,128Zm-16,0A88,88,0,1,0,51.81,172.06a8,8,0,0,1,.66,6.54L40,216,77.4,203.53a7.85,7.85,0,0,1,2.53-.42,8,8,0,0,1,4,1.08A88,88,0,0,0,216,128Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M164,112a4,4,0,0,1-4,4H96a4,4,0,0,1,0-8h64A4,4,0,0,1,164,112Zm-4,28H96a4,4,0,0,0,0,8h64a4,4,0,0,0,0-8Zm68-12A100,100,0,0,1,79.5,215.47l-35.69,11.9a12,12,0,0,1-15.18-15.18l11.9-35.69A100,100,0,1,1,228,128Zm-8,0A92,92,0,1,0,48.35,174.07a4,4,0,0,1,.33,3.27L36.22,214.72a4,4,0,0,0,5.06,5.06l37.38-12.46a3.93,3.93,0,0,1,1.27-.21,4.05,4.05,0,0,1,2,.54A92,92,0,0,0,220,128Z`}))]]),fi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,20A108,108,0,1,0,236,128,108.12,108.12,0,0,0,128,20Zm0,192a84,84,0,1,1,84-84A84.09,84.09,0,0,1,128,212Zm68-84a12,12,0,0,1-12,12H128a12,12,0,0,1-12-12V72a12,12,0,0,1,24,0v44h44A12,12,0,0,1,196,128Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm64-88a8,8,0,0,1-8,8H128a8,8,0,0,1-8-8V72a8,8,0,0,1,16,0v48h48A8,8,0,0,1,192,128Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm56,112H128a8,8,0,0,1-8-8V72a8,8,0,0,1,16,0v48h48a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,26A102,102,0,1,0,230,128,102.12,102.12,0,0,0,128,26Zm0,192a90,90,0,1,1,90-90A90.1,90.1,0,0,1,128,218Zm62-90a6,6,0,0,1-6,6H128a6,6,0,0,1-6-6V72a6,6,0,0,1,12,0v50h50A6,6,0,0,1,190,128Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm64-88a8,8,0,0,1-8,8H128a8,8,0,0,1-8-8V72a8,8,0,0,1,16,0v48h48A8,8,0,0,1,192,128Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,28A100,100,0,1,0,228,128,100.11,100.11,0,0,0,128,28Zm0,192a92,92,0,1,1,92-92A92.1,92.1,0,0,1,128,220Zm60-92a4,4,0,0,1-4,4H128a4,4,0,0,1-4-4V72a4,4,0,0,1,8,0v52h52A4,4,0,0,1,188,128Z`}))]]),pi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M140,80v41.21l34.17,20.5a12,12,0,1,1-12.34,20.58l-40-24A12,12,0,0,1,116,128V80a12,12,0,0,1,24,0ZM128,28A99.38,99.38,0,0,0,57.24,57.34c-4.69,4.74-9,9.37-13.24,14V64a12,12,0,0,0-24,0v40a12,12,0,0,0,12,12H72a12,12,0,0,0,0-24H57.77C63,86,68.37,80.22,74.26,74.26a76,76,0,1,1,1.58,109,12,12,0,0,0-16.48,17.46A100,100,0,1,0,128,28Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M136,80v43.47l36.12,21.67a8,8,0,0,1-8.24,13.72l-40-24A8,8,0,0,1,120,128V80a8,8,0,0,1,16,0Zm-8-48A95.44,95.44,0,0,0,60.08,60.15C52.81,67.51,46.35,74.59,40,82V64a8,8,0,0,0-16,0v40a8,8,0,0,0,8,8H72a8,8,0,0,0,0-16H49c7.15-8.42,14.27-16.35,22.39-24.57a80,80,0,1,1,1.66,114.75,8,8,0,1,0-11,11.64A96,96,0,1,0,128,32Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128A96,96,0,0,1,62.11,197.82a8,8,0,1,1,11-11.64A80,80,0,1,0,71.43,71.43C67.9,75,64.58,78.51,61.35,82L77.66,98.34A8,8,0,0,1,72,112H32a8,8,0,0,1-8-8V64a8,8,0,0,1,13.66-5.66L50,70.7c3.22-3.49,6.54-7,10.06-10.55A96,96,0,0,1,224,128ZM128,72a8,8,0,0,0-8,8v48a8,8,0,0,0,3.88,6.86l40,24a8,8,0,1,0,8.24-13.72L136,123.47V80A8,8,0,0,0,128,72Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M134,80v44.6l37.09,22.25a6,6,0,0,1-6.18,10.3l-40-24A6,6,0,0,1,122,128V80a6,6,0,0,1,12,0Zm-6-46A93.4,93.4,0,0,0,61.51,61.56c-8.58,8.68-16,17-23.51,25.8V64a6,6,0,0,0-12,0v40a6,6,0,0,0,6,6H72a6,6,0,0,0,0-12H44.73C52.86,88.29,60.79,79.35,70,70a82,82,0,1,1,1.7,117.62,6,6,0,1,0-8.24,8.72A94,94,0,1,0,128,34Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M136,80v43.47l36.12,21.67a8,8,0,0,1-8.24,13.72l-40-24A8,8,0,0,1,120,128V80a8,8,0,0,1,16,0Zm-8-48A95.44,95.44,0,0,0,60.08,60.15C52.81,67.51,46.35,74.59,40,82V64a8,8,0,0,0-16,0v40a8,8,0,0,0,8,8H72a8,8,0,0,0,0-16H49c7.15-8.42,14.27-16.35,22.39-24.57a80,80,0,1,1,1.66,114.75,8,8,0,1,0-11,11.64A96,96,0,1,0,128,32Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M132,80v45.74l38.06,22.83a4,4,0,0,1-4.12,6.86l-40-24A4,4,0,0,1,124,128V80a4,4,0,0,1,8,0Zm-4-44A91.42,91.42,0,0,0,62.93,63C53.05,73,44.66,82.47,36,92.86V64a4,4,0,0,0-8,0v40a4,4,0,0,0,4,4H72a4,4,0,0,0,0-8H40.47C49.61,89,58.3,79,68.6,68.6a84,84,0,1,1,1.75,120.49,4,4,0,1,0-5.5,5.82A92,92,0,1,0,128,36Z`}))]]),mi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M108,84a16,16,0,1,1,16,16A16,16,0,0,1,108,84Zm128,44A108,108,0,1,1,128,20,108.12,108.12,0,0,1,236,128Zm-24,0a84,84,0,1,0-84,84A84.09,84.09,0,0,0,212,128Zm-72,36.68V132a20,20,0,0,0-20-20,12,12,0,0,0-4,23.32V168a20,20,0,0,0,20,20,12,12,0,0,0,4-23.32Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M144,176a8,8,0,0,1-8,8,16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40A8,8,0,0,1,144,176Zm88-48A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128ZM124,96a12,12,0,1,0-12-12A12,12,0,0,0,124,96Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-4,48a12,12,0,1,1-12,12A12,12,0,0,1,124,72Zm12,112a16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M142,176a6,6,0,0,1-6,6,14,14,0,0,1-14-14V128a2,2,0,0,0-2-2,6,6,0,0,1,0-12,14,14,0,0,1,14,14v40a2,2,0,0,0,2,2A6,6,0,0,1,142,176ZM124,94a10,10,0,1,0-10-10A10,10,0,0,0,124,94Zm106,34A102,102,0,1,1,128,26,102.12,102.12,0,0,1,230,128Zm-12,0a90,90,0,1,0-90,90A90.1,90.1,0,0,0,218,128Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm16-40a8,8,0,0,1-8,8,16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40A8,8,0,0,1,144,176ZM112,84a12,12,0,1,1,12,12A12,12,0,0,1,112,84Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M140,176a4,4,0,0,1-4,4,12,12,0,0,1-12-12V128a4,4,0,0,0-4-4,4,4,0,0,1,0-8,12,12,0,0,1,12,12v40a4,4,0,0,0,4,4A4,4,0,0,1,140,176ZM124,92a8,8,0,1,0-8-8A8,8,0,0,0,124,92Zm104,36A100,100,0,1,1,128,28,100.11,100.11,0,0,1,228,128Zm-8,0a92,92,0,1,0-92,92A92.1,92.1,0,0,0,220,128Z`}))]]),hi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,44H32A20,20,0,0,0,12,64V192a20,20,0,0,0,20,20H224a20,20,0,0,0,20-20V64A20,20,0,0,0,224,44Zm-4,144H36V68H220ZM52,128a12,12,0,0,1,12-12H192a12,12,0,0,1,0,24H64A12,12,0,0,1,52,128Zm0-36A12,12,0,0,1,64,80H192a12,12,0,0,1,0,24H64A12,12,0,0,1,52,92Zm0,72a12,12,0,0,1,12-12h8a12,12,0,0,1,0,24H64A12,12,0,0,1,52,164Zm108,0a12,12,0,0,1-12,12H108a12,12,0,0,1,0-24h40A12,12,0,0,1,160,164Zm44,0a12,12,0,0,1-12,12h-8a12,12,0,0,1,0-24h8A12,12,0,0,1,204,164Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M232,64V192a8,8,0,0,1-8,8H32a8,8,0,0,1-8-8V64a8,8,0,0,1,8-8H224A8,8,0,0,1,232,64Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M224,48H32A16,16,0,0,0,16,64V192a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V64A16,16,0,0,0,224,48Zm0,144H32V64H224V192Zm-16-64a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16H200A8,8,0,0,1,208,128Zm0-32a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16H200A8,8,0,0,1,208,96ZM72,160a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16h8A8,8,0,0,1,72,160Zm96,0a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,160Zm40,0a8,8,0,0,1-8,8h-8a8,8,0,0,1,0-16h8A8,8,0,0,1,208,160Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,48H32A16,16,0,0,0,16,64V192a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V64A16,16,0,0,0,224,48ZM64,168H48a8,8,0,0,1,0-16H64a8,8,0,0,1,0,16Zm96,0H96a8,8,0,0,1,0-16h64a8,8,0,0,1,0,16Zm48,0H192a8,8,0,0,1,0-16h16a8,8,0,0,1,0,16Zm0-32H48a8,8,0,0,1,0-16H208a8,8,0,0,1,0,16Zm0-32H48a8,8,0,0,1,0-16H208a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,50H32A14,14,0,0,0,18,64V192a14,14,0,0,0,14,14H224a14,14,0,0,0,14-14V64A14,14,0,0,0,224,50Zm2,142a2,2,0,0,1-2,2H32a2,2,0,0,1-2-2V64a2,2,0,0,1,2-2H224a2,2,0,0,1,2,2Zm-20-64a6,6,0,0,1-6,6H56a6,6,0,0,1,0-12H200A6,6,0,0,1,206,128Zm0-32a6,6,0,0,1-6,6H56a6,6,0,0,1,0-12H200A6,6,0,0,1,206,96ZM70,160a6,6,0,0,1-6,6H56a6,6,0,0,1,0-12h8A6,6,0,0,1,70,160Zm96,0a6,6,0,0,1-6,6H96a6,6,0,0,1,0-12h64A6,6,0,0,1,166,160Zm40,0a6,6,0,0,1-6,6h-8a6,6,0,0,1,0-12h8A6,6,0,0,1,206,160Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,48H32A16,16,0,0,0,16,64V192a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V64A16,16,0,0,0,224,48Zm0,144H32V64H224V192Zm-16-64a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16H200A8,8,0,0,1,208,128Zm0-32a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16H200A8,8,0,0,1,208,96ZM72,160a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16h8A8,8,0,0,1,72,160Zm96,0a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,160Zm40,0a8,8,0,0,1-8,8h-8a8,8,0,0,1,0-16h8A8,8,0,0,1,208,160Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,52H32A12,12,0,0,0,20,64V192a12,12,0,0,0,12,12H224a12,12,0,0,0,12-12V64A12,12,0,0,0,224,52Zm4,140a4,4,0,0,1-4,4H32a4,4,0,0,1-4-4V64a4,4,0,0,1,4-4H224a4,4,0,0,1,4,4Zm-24-64a4,4,0,0,1-4,4H56a4,4,0,0,1,0-8H200A4,4,0,0,1,204,128Zm0-32a4,4,0,0,1-4,4H56a4,4,0,0,1,0-8H200A4,4,0,0,1,204,96ZM68,160a4,4,0,0,1-4,4H56a4,4,0,0,1,0-8h8A4,4,0,0,1,68,160Zm96,0a4,4,0,0,1-4,4H96a4,4,0,0,1,0-8h64A4,4,0,0,1,164,160Zm40,0a4,4,0,0,1-4,4h-8a4,4,0,0,1,0-8h8A4,4,0,0,1,204,160Z`}))]]),gi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M76,64A12,12,0,0,1,88,52H216a12,12,0,0,1,0,24H88A12,12,0,0,1,76,64Zm140,52H88a12,12,0,0,0,0,24H216a12,12,0,0,0,0-24Zm0,64H88a12,12,0,0,0,0,24H216a12,12,0,0,0,0-24ZM44,112a16,16,0,1,0,16,16A16,16,0,0,0,44,112Zm0-64A16,16,0,1,0,60,64,16,16,0,0,0,44,48Zm0,128a16,16,0,1,0,16,16A16,16,0,0,0,44,176Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,64V192H88V64Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M80,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H88A8,8,0,0,1,80,64Zm136,56H88a8,8,0,1,0,0,16H216a8,8,0,0,0,0-16Zm0,64H88a8,8,0,1,0,0,16H216a8,8,0,0,0,0-16ZM44,52A12,12,0,1,0,56,64,12,12,0,0,0,44,52Zm0,64a12,12,0,1,0,12,12A12,12,0,0,0,44,116Zm0,64a12,12,0,1,0,12,12A12,12,0,0,0,44,180Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M208,32H48A16,16,0,0,0,32,48V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V48A16,16,0,0,0,208,32ZM68,188a12,12,0,1,1,12-12A12,12,0,0,1,68,188Zm0-48a12,12,0,1,1,12-12A12,12,0,0,1,68,140Zm0-48A12,12,0,1,1,80,80,12,12,0,0,1,68,92Zm124,92H104a8,8,0,0,1,0-16h88a8,8,0,0,1,0,16Zm0-48H104a8,8,0,0,1,0-16h88a8,8,0,0,1,0,16Zm0-48H104a8,8,0,0,1,0-16h88a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M82,64a6,6,0,0,1,6-6H216a6,6,0,0,1,0,12H88A6,6,0,0,1,82,64Zm134,58H88a6,6,0,0,0,0,12H216a6,6,0,0,0,0-12Zm0,64H88a6,6,0,0,0,0,12H216a6,6,0,0,0,0-12ZM44,54A10,10,0,1,0,54,64,10,10,0,0,0,44,54Zm0,128a10,10,0,1,0,10,10A10,10,0,0,0,44,182Zm0-64a10,10,0,1,0,10,10A10,10,0,0,0,44,118Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M80,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H88A8,8,0,0,1,80,64Zm136,56H88a8,8,0,0,0,0,16H216a8,8,0,0,0,0-16Zm0,64H88a8,8,0,0,0,0,16H216a8,8,0,0,0,0-16ZM44,52A12,12,0,1,0,56,64,12,12,0,0,0,44,52Zm0,64a12,12,0,1,0,12,12A12,12,0,0,0,44,116Zm0,64a12,12,0,1,0,12,12A12,12,0,0,0,44,180Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M84,64a4,4,0,0,1,4-4H216a4,4,0,0,1,0,8H88A4,4,0,0,1,84,64Zm132,60H88a4,4,0,0,0,0,8H216a4,4,0,0,0,0-8Zm0,64H88a4,4,0,0,0,0,8H216a4,4,0,0,0,0-8ZM44,120a8,8,0,1,0,8,8A8,8,0,0,0,44,120Zm0-64a8,8,0,1,0,8,8A8,8,0,0,0,44,56Zm0,128a8,8,0,1,0,8,8A8,8,0,0,0,44,184Z`}))]]),_i=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M28,64A12,12,0,0,1,40,52H216a12,12,0,0,1,0,24H40A12,12,0,0,1,28,64Zm12,76h64a12,12,0,0,0,0-24H40a12,12,0,0,0,0,24Zm80,40H40a12,12,0,0,0,0,24h80a12,12,0,0,0,0-24Zm120.49,20.49a12,12,0,0,1-17,0l-18.08-18.08a44,44,0,1,1,17-17l18.08,18.07A12,12,0,0,1,240.49,200.49ZM184,164a20,20,0,1,0-20-20A20,20,0,0,0,184,164Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,144a32,32,0,1,1-32-32A32,32,0,0,1,216,144Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M32,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H40A8,8,0,0,1,32,64Zm8,72h72a8,8,0,0,0,0-16H40a8,8,0,0,0,0,16Zm88,48H40a8,8,0,0,0,0,16h88a8,8,0,0,0,0-16Zm109.66,13.66a8,8,0,0,1-11.32,0L206,177.36A40,40,0,1,1,217.36,166l20.3,20.3A8,8,0,0,1,237.66,197.66ZM184,168a24,24,0,1,0-24-24A24,24,0,0,0,184,168Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M32,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H40A8,8,0,0,1,32,64Zm8,72h72a8,8,0,0,0,0-16H40a8,8,0,0,0,0,16Zm88,48H40a8,8,0,0,0,0,16h88a8,8,0,0,0,0-16Zm109.66,2.34L217.36,166A40,40,0,1,0,206,177.36l20.3,20.3a8,8,0,0,0,11.32-11.32Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M34,64a6,6,0,0,1,6-6H216a6,6,0,0,1,0,12H40A6,6,0,0,1,34,64Zm6,70h72a6,6,0,0,0,0-12H40a6,6,0,0,0,0,12Zm88,52H40a6,6,0,0,0,0,12h88a6,6,0,0,0,0-12Zm108.24,10.24a6,6,0,0,1-8.48,0l-21.49-21.48a38.06,38.06,0,1,1,8.49-8.49l21.48,21.49A6,6,0,0,1,236.24,196.24ZM184,170a26,26,0,1,0-26-26A26,26,0,0,0,184,170Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M32,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H40A8,8,0,0,1,32,64Zm8,72h72a8,8,0,0,0,0-16H40a8,8,0,0,0,0,16Zm88,48H40a8,8,0,0,0,0,16h88a8,8,0,0,0,0-16Zm109.66,13.66a8,8,0,0,1-11.32,0L206,177.36A40,40,0,1,1,217.36,166l20.3,20.3A8,8,0,0,1,237.66,197.66ZM184,168a24,24,0,1,0-24-24A24,24,0,0,0,184,168Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M36,64a4,4,0,0,1,4-4H216a4,4,0,0,1,0,8H40A4,4,0,0,1,36,64Zm4,68h72a4,4,0,0,0,0-8H40a4,4,0,0,0,0,8Zm88,56H40a4,4,0,0,0,0,8h88a4,4,0,0,0,0-8Zm106.83,6.83a4,4,0,0,1-5.66,0l-22.72-22.72a36.06,36.06,0,1,1,5.66-5.66l22.72,22.72A4,4,0,0,1,234.83,194.83ZM184,172a28,28,0,1,0-28-28A28,28,0,0,0,184,172Z`}))]]),vi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M156,112a12,12,0,0,1-12,12H80a12,12,0,0,1,0-24h64A12,12,0,0,1,156,112Zm76.49,120.49a12,12,0,0,1-17,0L168,185a92.12,92.12,0,1,1,17-17l47.54,47.53A12,12,0,0,1,232.49,232.49ZM112,180a68,68,0,1,0-68-68A68.08,68.08,0,0,0,112,180Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M192,112a80,80,0,1,1-80-80A80,80,0,0,1,192,112Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M229.66,218.34,179.6,168.28a88.21,88.21,0,1,0-11.32,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM40,112a72,72,0,1,1,72,72A72.08,72.08,0,0,1,40,112Zm112,0a8,8,0,0,1-8,8H80a8,8,0,0,1,0-16h64A8,8,0,0,1,152,112Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M229.66,218.34,179.6,168.28a88.21,88.21,0,1,0-11.32,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM144,120H80a8,8,0,0,1,0-16h64a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M150,112a6,6,0,0,1-6,6H80a6,6,0,0,1,0-12h64A6,6,0,0,1,150,112Zm78.24,116.24a6,6,0,0,1-8.48,0l-51.38-51.38a86.15,86.15,0,1,1,8.48-8.48l51.38,51.38A6,6,0,0,1,228.24,228.24ZM112,186a74,74,0,1,0-74-74A74.09,74.09,0,0,0,112,186Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M152,112a8,8,0,0,1-8,8H80a8,8,0,0,1,0-16h64A8,8,0,0,1,152,112Zm77.66,117.66a8,8,0,0,1-11.32,0l-50.06-50.07a88.11,88.11,0,1,1,11.31-11.31l50.07,50.06A8,8,0,0,1,229.66,229.66ZM112,184a72,72,0,1,0-72-72A72.08,72.08,0,0,0,112,184Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M148,112a4,4,0,0,1-4,4H80a4,4,0,0,1,0-8h64A4,4,0,0,1,148,112Zm78.83,114.83a4,4,0,0,1-5.66,0l-52.7-52.7a84.1,84.1,0,1,1,5.66-5.66l52.7,52.7A4,4,0,0,1,226.83,226.83ZM112,188a76,76,0,1,0-76-76A76.08,76.08,0,0,0,112,188Z`}))]]),yi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M230.47,67.5a12,12,0,0,0-19.26-4.32L172.43,99l-12.68-2.72L157,83.57l35.79-38.78a12,12,0,0,0-4.32-19.26A76.07,76.07,0,0,0,88.41,121.64L30.92,174.18a4.68,4.68,0,0,0-.39.38,36,36,0,0,0,50.91,50.91l.38-.39,52.54-57.49A76.05,76.05,0,0,0,230.47,67.5ZM160,148a51.5,51.5,0,0,1-23.35-5.52,12,12,0,0,0-14.26,2.62L64.31,208.66a12,12,0,0,1-17-17l63.55-58.07a12,12,0,0,0,2.62-14.26A51.5,51.5,0,0,1,108,96a52.06,52.06,0,0,1,52-52h.89L135.17,71.87a12,12,0,0,0-2.91,10.65l5.66,26.35a12,12,0,0,0,9.21,9.21l26.35,5.66a12,12,0,0,0,10.65-2.91L212,95.12c0,.3,0,.59,0,.89A52.06,52.06,0,0,1,160,148Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,96a64,64,0,0,1-94.94,56L73,217A24,24,0,0,1,39,183L104,126.94a64,64,0,0,1,80-90.29L144,80l5.66,26.34L176,112l43.35-40A63.8,63.8,0,0,1,224,96Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M226.76,69a8,8,0,0,0-12.84-2.88l-40.3,37.19-17.23-3.7-3.7-17.23,37.19-40.3A8,8,0,0,0,187,29.24,72,72,0,0,0,88,96,72.34,72.34,0,0,0,94,124.94L33.79,177c-.15.12-.29.26-.43.39a32,32,0,0,0,45.26,45.26c.13-.13.27-.28.39-.42L131.06,162A72,72,0,0,0,232,96,71.56,71.56,0,0,0,226.76,69ZM160,152a56.14,56.14,0,0,1-27.07-7,8,8,0,0,0-9.92,1.77L67.11,211.51a16,16,0,0,1-22.62-22.62L109.18,133a8,8,0,0,0,1.77-9.93,56,56,0,0,1,58.36-82.31l-31.2,33.81a8,8,0,0,0-1.94,7.1L141.83,108a8,8,0,0,0,6.14,6.14l26.35,5.66a8,8,0,0,0,7.1-1.94l33.81-31.2A56.06,56.06,0,0,1,160,152Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M232,96a72,72,0,0,1-100.94,66L79,222.22c-.12.14-.26.29-.39.42a32,32,0,0,1-45.26-45.26c.14-.13.28-.27.43-.39L94,124.94a72.07,72.07,0,0,1,83.54-98.78,8,8,0,0,1,3.93,13.19L144,80l5.66,26.35L176,112l40.65-37.52a8,8,0,0,1,13.19,3.93A72.6,72.6,0,0,1,232,96Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224.91,69.75a6,6,0,0,0-9.63-2.16l-41.07,37.9L154.7,101.3l-4.19-19.51,37.9-41.07a6,6,0,0,0-2.16-9.63,70,70,0,0,0-89.77,94.39l-61.39,53c-.11.09-.21.19-.32.3A30,30,0,0,0,77.2,221.23c.11-.11.21-.21.3-.32l53-61.39a70,70,0,0,0,94.39-89.77ZM160,154a58,58,0,0,1-28-7.22,6,6,0,0,0-7.45,1.33L68.57,212.88a18,18,0,0,1-25.45-25.45l64.76-55.94A6,6,0,0,0,109.2,124a58,58,0,0,1,64-84.53L139.58,75.93a6,6,0,0,0-1.45,5.33l5.65,26.35a6,6,0,0,0,4.61,4.61l26.35,5.65a6,6,0,0,0,5.33-1.45L216.49,82.8A58.06,58.06,0,0,1,160,154Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M226.76,69a8,8,0,0,0-12.84-2.88l-40.3,37.19-17.23-3.7-3.7-17.23,37.19-40.3A8,8,0,0,0,187,29.24,72,72,0,0,0,88,96,72.34,72.34,0,0,0,94,124.94L33.79,177c-.15.12-.29.26-.43.39a32,32,0,0,0,45.26,45.26c.13-.13.27-.28.39-.42L131.06,162A72,72,0,0,0,232,96,71.56,71.56,0,0,0,226.76,69ZM160,152a56.14,56.14,0,0,1-27.07-7,8,8,0,0,0-9.92,1.77L67.11,211.51a16,16,0,0,1-22.62-22.62L109.18,133a8,8,0,0,0,1.77-9.93,56,56,0,0,1,58.36-82.31l-31.2,33.81a8,8,0,0,0-1.94,7.1L141.83,108a8,8,0,0,0,6.14,6.14l26.35,5.66a8,8,0,0,0,7.1-1.94l33.81-31.2A56.06,56.06,0,0,1,160,152Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M223.05,70.5a4,4,0,0,0-6.42-1.44l-41.82,38.6L153,103l-4.68-21.79,38.6-41.82a4,4,0,0,0-1.44-6.43A68,68,0,0,0,98.94,126L36.4,180l-.21.2a28,28,0,0,0,39.6,39.6l.2-.21,54-62.54A68,68,0,0,0,228,96,67.51,67.51,0,0,0,223.05,70.5ZM160,156a60,60,0,0,1-29-7.47,4,4,0,0,0-5,.89L70,214.25A20,20,0,0,1,41.75,186l64.82-56a4,4,0,0,0,.89-5,60,60,0,0,1,69.46-86.59L141.05,77.29a4,4,0,0,0-1,3.55l5.66,26.35a4,4,0,0,0,3.07,3.07l26.35,5.66a4,4,0,0,0,3.55-1l38.87-35.87A60.05,60.05,0,0,1,160,156Z`}))]]),bi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:si}));bi.displayName=`ArrowClockwiseIcon`;var xi=bi,Si=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:ci}));Si.displayName=`ArrowCounterClockwiseIcon`;var Ci=Si,wi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:li}));wi.displayName=`ArrowsOutIcon`;var Ti=wi,Ei=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:ui}));Ei.displayName=`CaretUpIcon`;var Di=Ei,Oi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:di}));Oi.displayName=`ChatCircleTextIcon`;var ki=Oi,Ai=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:fi}));Ai.displayName=`ClockIcon`;var ji=Ai,Mi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:pi}));Mi.displayName=`ClockCounterClockwiseIcon`;var Ni=Mi,Pi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:mi}));Pi.displayName=`InfoIcon`;var Fi=Pi,Ii=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:hi}));Ii.displayName=`KeyboardIcon`;var Li=Ii,Ri=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:gi}));Ri.displayName=`ListBulletsIcon`;var zi=Ri,Bi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:_i}));Bi.displayName=`ListMagnifyingGlassIcon`;var Vi=Bi,Hi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:vi}));Hi.displayName=`MagnifyingGlassMinusIcon`;var Ui=Hi,Wi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:yi}));Wi.displayName=`WrenchIcon`;var Gi=Wi,Ki=i(b(),1),qi=`$__all`;function Ji(e,t,n){if(e.kind===`constant`)return e.value??``;let r=e.kind===`custom`?e.options?.map(e=>({value:e}))??[]:n===null?[]:n,i=t[e.name],a=!e.multi&&Array.isArray(i)&&i.length===0?void 0:i;if(a===`$__all`){if(e.include_all)return qi}else if(a!==void 0){if(e.kind===`text`||r===void 0)return a;let t=new Set(r.map(e=>e.value));if(Array.isArray(a)){if(a.length===0&&e.multi)return[];let n=a.filter(e=>t.has(e));if(n.length>0)return n}else if(t.has(a))return a}return e.default?e.default:e.include_all?qi:r?.[0]?.value??``}var Yi=(e,t)=>e.replace(/\$([a-z][a-z0-9_]*)/g,(e,n)=>{let r=t[n];return r===void 0?e:r===`$__all`?`all`:Array.isArray(r)?r.join(`, `):r});function Xi(e,t,n){let r={};for(let i of e??[]){let e=Ji(i,t,n?.[i.name]);(i.kind!==`query`||e!==``)&&(r[i.name]=e)}return r}function Zi(e){return Array.from({length:e.rows},(t,n)=>Object.fromEntries(e.columns.map((t,r)=>{let i=e.values[r]?.[n]??null;return[t.name,typeof i==`number`&&!Number.isFinite(i)?null:i]})))}function Qi(e,t){return e.viz!==`logs`||!t||t.rows<2?[]:t.columns.flatMap((e,n)=>{if(e.role!==`dimension`||e.type!==`string`||[`body`,`body_template`,`severity`,`status`].includes(e.name)||/(^id$|_id$)/.test(e.name))return[];let r=t.values[n][0];return typeof r==`string`&&r!==``&&t.values[n].slice(0,t.rows).every(e=>e===r)?[{name:e.name,value:r}]:[]})}function $i(e,t){let n=t.frame??{columns:[],values:[],rows:0};return{columns:n.columns.map(e=>e.name),rows:Zi(n),selection:t=>{let n={};for(let r of e.query?.by??[]){let e=r.startsWith(`attributes[`)||r.startsWith(`resource[`)?r.slice(r.indexOf(`'`)+1,r.lastIndexOf(`'`)):r;t[e]!==void 0&&t[e]!==null&&(n[r]=String(t[e]))}return{time:typeof t.time==`number`?t.time:typeof t.start==`number`?t.start:void 0,dimensions:n,trace_id:typeof t.trace_id==`string`?t.trace_id:void 0,namespace:typeof t.namespace==`string`?t.namespace:void 0}}}}function ea(e){return e.replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e])}var ta=e=>e.map(ea).join(`
`);function na(e,t=!1){return n=>{let r=Array.isArray(n)?n:[n];return ta([...r[0]?.axisValueLabel?[r[0].axisValueLabel]:[],...r.map(n=>{let r=n.value,i=Array.isArray(r)?t?r.slice(1):r:[r];return`${n.seriesName??``}${n.name?` · ${n.name}`:``}: ${i.map(t=>typeof t==`number`?e(t,n.seriesName):String(t??`—`)).join(` · `)}`})])}}var ra=e=>/^Other(?: \(\d+\))?$/.test(e??``);function ia(e,t){let n=Math.min(6,Math.max(1,Math.floor(t.options?.top||6))),r=e.filter(e=>!ra(e.name)),i=r.slice(0,n).map(e=>({name:e.name,items:[e]})),a=[...e.filter(e=>ra(e.name)),...r.slice(n)];return a.length&&i.push({name:a.length===1&&ra(a[0].name)?a[0].name:`Other (${a.reduce((e,t)=>e+(ra(t.name)?Number(t.name.match(/\d+/)?.[0]??1):1),0)})`,items:a}),i}function aa(e){let t=e.filter(e=>e!==null);return t.length?t.reduce((e,t)=>e+t,0):null}function oa(e,t){let n=Math.min(6,Math.max(1,Math.floor(t.options?.top||6))),r=e.filter(e=>!ra(e.name));return{shown:[...r.slice(0,n),...e.filter(e=>ra(e.name))],hidden:Math.max(0,r.length-n)}}function sa(e,t){return e>0?[{type:`text`,right:8,bottom:2,silent:!0,style:{text:`${e} more series not shown`,fill:t,fontSize:11}}]:[]}function ca(e,t,n,r,i=`sans-serif`,a){let o=e=>Array.from(e).length>24?`${Array.from(e).slice(0,23).join(``)}…`:e,s=Math.max(1,t-16),c=1,l=0;for(let t of e){let e=15+(a?.(o(t),`12px ${i}`)??Array.from(o(t)).length*7.2);l&&l+10+e>s&&(c++,l=0),l+=(l?10:0)+e}let u=c>2;return{top:n?u?30:c*20+2:12,option:{type:u?`scroll`:`plain`,show:n,top:0,left:0,right:0,padding:0,itemGap:6,icon:`roundRect`,itemWidth:10,itemHeight:10,itemStyle:{borderColor:r,borderWidth:1},textStyle:{color:r,fontSize:12,lineHeight:14},data:e,formatter:o,tooltip:{show:!0,renderMode:`html`,formatter:e=>ea(e.name)}}}}function la(e,t){if(!(!Number.isFinite(e)||!Number.isFinite(t)||e>=t||Math.abs(e)>864e13||Math.abs(t)>864e13))return{from:new Date(Math.floor(e)).toISOString(),to:new Date(Math.ceil(t)).toISOString()}}function ua(e){let t=[e.time?.range?`Range ${e.time.range}`:void 0,e.time?.shift?`Shifted ${e.time.shift}`:void 0].filter(Boolean);return t.length?t.join(` · `):void 0}function da(e,t,n){if(n.interactive===!1||n.data?.value===null)return;let r=n.data?.selection;if(r)return Object.values(r.dimensions).some(ra)?void 0:r;if(ra(n.seriesName)||ra(n.name)||n.value===null||Array.isArray(n.value)&&n.value.at(-1)==null)return;let i=e.query?.by?.[0]??t.frame?.columns.find(e=>e.role===`dimension`)?.name,a=e.viz===`timeseries`?n.seriesName:n.name,o=Array.isArray(n.value)?n.value:[];return{time:e.viz===`timeseries`&&typeof o[0]==`number`?o[0]:void 0,dimensions:i&&a?{[i]:a}:{}}}var fa=new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}),pa=new Intl.NumberFormat(`en`,{maximumFractionDigits:2});function ma(e){return Math.abs(e)<1e-4?e.toExponential(2).replace(/\.?(0+)(?=e)/,``):String(Number(e.toPrecision(3)))}function ha(e,t=pa){return e!==0&&Math.abs(e)<1?ma(e):t.format(e)}function ga(e,t){let n=t===`s`?e*1e3:t===`ns`?e/1e6:e;return e!==0&&n===0?`${ma(e)}${t}`:n!==0&&Math.abs(n)<1?`${ma(n)}ms`:ye(n)}function _a(e){let t=[`B`,`KiB`,`MiB`,`GiB`,`TiB`],n=e,r=0;for(;Math.abs(n)>=1024&&r=1e4?fa:pa);default:return ha(t,Math.abs(t)>=1e4?fa:pa)}}function ya(e){return t=>e===`ms`||e===`s`||e===`ns`?va(e,t).replace(/(\.\d*?)0+([a-z]*)$/,`$1$2`).replace(/\.([a-z]*)$/,`$1`):va(e,t)}function ba(e,t){return ya(e)(t??NaN).replace(/(?<=\d)(ms|ns|s|m|h)\b/g,` $1`)}function xa(e){return Math.max(3,Math.min(10,Math.round(e/70)))-1}function Sa(e,t){let n=t===`ms`?1:t===`s`?1e3:t===`ns`?1e-6:void 0,r=e=>{let t=10**Math.floor(Math.log10(e));return[1,2,5,10].map(e=>e*t).find(t=>t>=e)};if(n===void 0)return r(e);let i=e*n,a=[1,10,100,1e3,1e4,6e4,6e5,36e5,36e6].flatMap(e=>[1,2,5].map(t=>e*t)).sort((e,t)=>e-t);return(i<1?r(i):a.find(e=>e>=i)??r(i/36e5)*36e5)/n}function Ca(e,t,n,r){e=Number.isFinite(e)?Math.min(0,e):0,t=Number.isFinite(t)?Math.max(0,t):1,t===e&&(t=e+1);let i=xa(r),a=Sa(Math.max(t-e,2**-52)/i,n);for(;Math.ceil(t/a)-Math.floor(e/a)>i;)a=Sa(a*1.01,n);return{min:Math.floor(e/a)*a,max:Math.ceil(t/a)*a,interval:a,splitNumber:i,fanout_unit:n}}function wa(e,t){return e.type!==`value`&&e.type!==`log`?e:{...e,...e.type===`value`&&typeof e.min==`number`&&typeof e.max==`number`?Ca(e.min,e.max,typeof e.fanout_unit==`string`?e.fanout_unit:void 0,t):{splitNumber:xa(t)}}}function Ta(e,t,n){let r=e=>va(n,e),i=``;if(n===`ms`||n===`s`||n===`ns`){let a=n===`s`?1e3:n===`ns`?1e-6:1,o=Math.abs((e??t??0)*a),s=o>=6e4?6e4:o>=1e3?1e3:1;i=s===6e4?` min`:s===1e3?` s`:` ms`;let c=s===6e4?1:s===1e3?+(o<1e4):2,l=new Intl.NumberFormat(void 0,{maximumFractionDigits:c});r=e=>l.format(e*a/s)}return t===null&&e!==null?`≥${r(e)}${i}`:(e===null||e===0)&&t!==null?`<${r(t)}${i}`:`${e===null?`−∞`:r(e)}–${t===null?`∞`:r(t)}${i}`}function Ea(e){let t=new Date(e);return t.getHours()===0&&t.getMinutes()===0&&t.getSeconds()===0?t.toLocaleDateString(void 0,{month:`short`,day:`numeric`}):t.toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`})}function Da(e,t=new Date,n){let r=new Date(e);if(!Number.isFinite(r.getTime()))return`—`;let i=new Intl.DateTimeFormat(n,{month:`short`,day:`numeric`,...r.getFullYear()===t.getFullYear()?{}:{year:`numeric`},hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hourCycle:`h23`}).formatToParts(r),a=i.filter(e=>[`month`,`day`,`year`].includes(e.type)).map(e=>e.value),o=i.filter(e=>[`hour`,`minute`,`second`].includes(e.type)).map(e=>e.value);return`${a.join(` `)} ${o.join(`:`)}`}function Oa({panel:e,result:t}){let n=t?.frame;return(0,H.jsxs)(`div`,{"data-panel-data":!0,children:[t?.error&&(0,H.jsx)(T,{"data-panel-error-detail":!0,size:`sm`,role:`status`,style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,userSelect:`text`},children:t.error}),n?(0,H.jsxs)(be,{fz:12,striped:!0,children:[(0,H.jsx)(be.Thead,{children:(0,H.jsx)(be.Tr,{children:n.columns.map(e=>(0,H.jsx)(be.Th,{ff:wt.display,children:e.name},e.name))})}),(0,H.jsx)(be.Tbody,{children:Array.from({length:Math.min(n.rows,500)},(t,r)=>(0,H.jsx)(be.Tr,{children:n.columns.map((t,i)=>{let a=n.values[i][r];return(0,H.jsx)(be.Td,{ff:wt.display,children:a===null?`—`:t.type===`time`?new Date(Number(a)).toISOString():t.role===`measure`?va(t.unit??e.unit,Number(a)):String(a)},t.name)})},r))})]}):(0,H.jsx)(T,{c:`dimmed`,size:`sm`,children:`No data.`}),(0,H.jsxs)(T,{c:`dimmed`,fz:12,mt:8,children:[`Ran in `,t?.elapsed_ms??0,` ms`,t?.interval?`, one point per ${t.interval}`:``,n?`, ${n.rows} rows${n.truncated?` (truncated)`:``}`:``,`.`]}),(t?.sql??e.sql)&&(0,H.jsx)(Re,{block:!0,tabIndex:0,mt:8,children:t?.sql??e.sql})]})}function ka({panel:e,dark:t}){let n=JSON.stringify(e,null,2).split(/("(?:[^"\\]|\\.)*"(?=\s*:)|"(?:[^"\\]|\\.)*"|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?)/g);return(0,H.jsx)(`pre`,{"data-panel-spec":!0,style:{margin:0,fontFamily:wt.display,fontSize:12,color:ft[t?`dark`:`light`].text},children:n.map((e,r)=>{let i=e.startsWith(`"`)&&/^\s*:/.test(n[r+1]??``)?`key`:e.startsWith(`"`)?`string`:/^(true|false|null)$/.test(e)?`literal`:/^-?\d/.test(e)?`number`:`punctuation`,a=i===`key`?_t[t?4:7]:i===`string`?mt[t?4:8]:i===`number`||i===`literal`?Dt[t?4:8]:void 0;return i===`punctuation`?e:(0,H.jsx)(`span`,{"data-json-token":i,style:{color:a},children:e},r)})})}function Aa(e){let t=e.event.data?.selection,n=e.event.value;return JSON.stringify([e.event.seriesName,e.event.name,t?.from??t?.time??(Array.isArray(n)?n[0]:void 0),t?.dimensions,t?.bucket])}function ja(e){let t=new Date().toISOString().slice(0,10),n=e.from.slice(0,10),r=e.to.slice(0,10),i=e=>e.slice(11,-1).replace(/\.000$/,``);return`${(n===t?``:n+` `)+i(e.from)} – ${(r!==n&&r!==t?r+` `:``)+i(e.to)} UTC · ${ye(Date.parse(e.to)-Date.parse(e.from))}`}var Ma={background:`color-mix(in srgb, var(--mantine-color-body) 92%, transparent)`,border:`1px solid var(--mantine-color-default-border)`,borderRadius:`var(--mantine-radius-sm)`,padding:`2px 6px`};function Na(e){return e.replace(`Enter drill`,`↵ drill`).replace(`Shift+←→`,`⇧←→`)}var Pa=(0,V.createContext)(void 0);function Fa({points:e,label:t,summary:n,children:r,onClick:i,canSelect:a,onHighlight:s,onActiveChange:c,onRangePending:l,onRangeChange:u,onRangeBarHeight:d,rangeReset:f,height:p=`100%`,onZoom:m,bounds:h,pointWindow:g}){let[_,v]=(0,V.useState)(!1),[b,x]=(0,V.useState)(``),[S,w]=(0,V.useState)(),[E,D]=(0,V.useState)(null),O=(0,V.useRef)(null),k=(0,V.useRef)(!1);(0,V.useEffect)(()=>{let e=e=>{e.key===`Tab`&&(k.current=!1)};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[]);let A=(0,V.useId)(),j=(0,V.useContext)(Pa),M=(0,V.useRef)(null),N=(0,V.useRef)({onHighlight:s,onActiveChange:c,onRangePending:l,onRangeChange:u,onRangeBarHeight:d});N.current={onHighlight:s,onActiveChange:c,onRangePending:l,onRangeChange:u,onRangeBarHeight:d};let P=(0,V.useMemo)(()=>new Map(e.map(e=>[Aa(e),e])),[e]),F=(0,V.useRef)(void 0),I=e=>g?.(e)?.from??e.event.name??(Array.isArray(e.event.value)?e.event.value[0]:void 0),L=F.current,ee=L?e.filter(e=>e.event.seriesName===L.event.seriesName):e,R=ee.length?ee:e,te=L&&I(L),ne=typeof te==`number`?R.reduce((e,t)=>{let n=I(t),r=e&&I(e);return typeof n==`number`&&(!e||typeof r!=`number`||Math.abs(n-te)I(e)===te),re=S?P.get(S)??ne??R[0]??e[0]:e[0],ie=!!(m&&h&&Number.isFinite(h.from)&&Number.isFinite(h.to)&&h.from[...new Set(e.map(e=>e.event.seriesName))],[e]),ae=(0,V.useMemo)(()=>e.filter(e=>e.event.seriesName===re?.event.seriesName),[e,re?.event.seriesName]),B=re?ae.indexOf(re):-1;(0,V.useEffect)(()=>{re&&(!S||P.has(S)||!ee.length)&&(F.current=re,(!S||!ee.length)&&w(Aa(re))),_&&N.current.onHighlight(re)},[re,S,_]),(0,V.useEffect)(()=>{if(!E)return;let e=Date.parse(E.from),t=Date.parse(E.to);h&&(Number.isFinite(e)&&eh.to)&&D(null)},[h?.from,h?.to,E]),(0,V.useEffect)(()=>{N.current.onRangePending?.(!!E)},[!!E]),(0,V.useEffect)(()=>{N.current.onRangeChange?.(E?{from:Date.parse(E.from),to:Date.parse(E.to)}:void 0)},[E]),(0,V.useEffect)(()=>{D(null)},[f]),(0,V.useEffect)(()=>()=>{N.current.onHighlight(void 0),N.current.onRangePending?.(!1),N.current.onRangeChange?.(void 0)},[]);let oe=(e,t=!1)=>{if(e){if(x(n(e)),t&&ie&&re){let t=E?.anchor??Aa(re),n=P.get(t),r=E?.window??(n&&g?.(n)),i=g?.(e);if(r&&i){let e=Math.max(h.from,Math.min(r.from,i.from)),n=Math.min(h.to,Math.max(r.to,i.to));Number.isFinite(e)&&Number.isFinite(n)&&e{if(!re)return;let n=z[Math.max(0,Math.min(z.length-1,z.indexOf(re.event.seriesName)+t))],r=e.filter(e=>e.event.seriesName===n),i=I(re),a=r.find(e=>I(e)===i),o=typeof i==`number`?r.reduce((e,t)=>{let n=I(t),r=e&&I(e);return typeof n==`number`&&(!e||typeof r!=`number`||Math.abs(n-i){e===`ArrowLeft`||e===`ArrowRight`?oe(ae[Math.max(0,Math.min(ae.length-1,B+(e===`ArrowLeft`?-1:1)))],t):!t&&(e===`ArrowUp`||e===`ArrowDown`)?se(e===`ArrowUp`?-1:1):!t&&(e===`Home`||e===`End`)&&oe(e===`Home`?ae[0]:ae.at(-1))},le=()=>{D(null),O.current?.focus()},ue=ie?`←→ points · ↑↓ series · Enter drill · Shift+←→ range`:`←→ points · ↑↓ series · Enter drill`;return(0,V.useLayoutEffect)(()=>(j?.setHint(_?ue:void 0),()=>j?.setHint(void 0)),[j,_,ue]),(0,V.useLayoutEffect)(()=>{let e=M.current;if(!e)return;N.current.onRangeBarHeight?.(e.getBoundingClientRect().height);let t=new ResizeObserver(([t])=>{if(!t)return;let n=getComputedStyle(e),r=[n.paddingTop,n.paddingBottom,n.borderTopWidth,n.borderBottomWidth].reduce((e,t)=>e+(parseFloat(t)||0),0);N.current.onRangeBarHeight?.(t.borderBoxSize?.[0]?.blockSize??t.contentRect.height+r)});return t.observe(e),()=>{t.disconnect(),N.current.onRangeBarHeight?.(0)}},[!!(E&&ie)]),(0,H.jsxs)(o,{ref:O,"data-chart-plot":!0,tabIndex:0,role:`application`,"aria-roledescription":`chart`,"aria-label":t,"aria-describedby":A,"data-mantine-stop-propagation":E?`true`:void 0,className:`chart-keyboard-point`,style:{position:`relative`,height:p,width:`100%`,flex:`1 1 auto`,minHeight:0,minWidth:0},onPointerDownCapture:e=>{M.current?.contains(e.target)||(k.current=!0,v(!1),_&&N.current.onHighlight(void 0),N.current.onActiveChange?.(!1))},onFocus:e=>{e.target!==e.currentTarget||k.current||(N.current.onActiveChange?.(!0),v(!0))},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(v(!1),D(null),x(``),N.current.onHighlight(void 0),N.current.onActiveChange?.(!1))},onKeyDown:e=>{if(e.defaultPrevented||e.ctrlKey||e.metaKey||e.altKey||e.nativeEvent.isComposing)return;if(e.key===`Escape`&&!e.repeat){E?(e.preventDefault(),e.stopPropagation(),le()):e.target===e.currentTarget&&!e.currentTarget.closest(`[data-panel-fullscreen],[data-fragment-fullscreen]`)&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.blur());return}if(e.target!==e.currentTarget||e.repeat&&![`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`].includes(e.key))return;let t=[`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`,`Home`,`End`].includes(e.key);if(t&&!_&&(k.current=!1,v(!0),N.current.onActiveChange?.(!0),!re)){e.preventDefault();return}e.key===`Enter`&&_&&!e.shiftKey&&re&&i&&(!a||a(re.event))?(e.preventDefault(),i(re.event)):t&&(!e.shiftKey||e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.preventDefault(),ce(e.key,e.shiftKey))},children:[r,(0,H.jsx)(o,{"data-chart-overlay":!0,style:{position:`absolute`,inset:0,zIndex:1,pointerEvents:`none`,overflow:`hidden`},children:E&&ie&&(0,H.jsxs)(y,{ref:M,"data-chart-range-bar":!0,gap:6,style:{...Ma,position:`absolute`,bottom:4,left:4,right:4,maxHeight:`100%`,overflow:`auto`,pointerEvents:`auto`},children:[(0,H.jsx)(T,{"data-chart-range-label":!0,size:`xs`,title:E.from+` – `+E.to,truncate:!0,style:{flex:`1 1 140px`,minWidth:0},children:ja(E)}),(0,H.jsx)(C,{size:`compact-xs`,"data-mantine-stop-propagation":`true`,onClick:()=>{m(Date.parse(E.from),Date.parse(E.to)),le()},children:`Zoom to range`}),(0,H.jsx)(C,{size:`compact-xs`,variant:`subtle`,"data-mantine-stop-propagation":`true`,onClick:le,children:`Cancel`})]})}),(0,H.jsx)(Ve,{id:A,children:ue}),(0,H.jsx)(Ve,{"aria-live":`polite`,"aria-atomic":`true`,children:b})]})}var Ia=new Set([`id`,`http`,`https`,`rpc`,`grpc`,`cpu`,`sql`,`url`,`uri`,`ip`,`io`,`db`,`gc`,`tls`,`api`]),La={ms:`ms`,ns:`ns`,s:`s`,us:`µs`,bytes:`bytes`,percent:`%`,ratio:`ratio`,per_second:`/s`,per_minute:`/min`},Ra={body_template:`message template`,parquet_index:`traces`};function za(e,t){let n=typeof e==`string`?e:e.name,r=t?.options?.columns?.find(e=>e.field===n)?.unit??(typeof e==`string`?void 0:e.unit)??(typeof e!=`string`&&e.role===`measure`?t?.unit:void 0),i=Ra[n]??n;/\b(?:duckdb|parquet|sqlite|variant|timestamptz_ns|timestamp_ns)\b|\btelemetry\./i.test(i)&&(i=`value`),i=i.replace(/^(\w+)\(([^()]*)\)$/,(e,t,n)=>[t,n].filter(Boolean).join(`_`));let a=i.match(/_(ms|ns|us|s|bytes|percent)$/i);a&&(i=i.slice(0,-a[0].length));let o=r??a?.[1]?.toLowerCase();return i=i.split(`_`).map((e,t)=>/^p\d+$/i.test(e)||Ia.has(e.toLowerCase())?e.toUpperCase():t===0?e.charAt(0).toUpperCase()+e.slice(1):e).join(` `),i+(o&&o!==`none`&&o!==`count`?` (${La[o]??o})`:``)}function Ba(e){return e===`healthy`?`ok`:e===`degraded`?`warn`:e===`unknown`?`gray`:`bad`}function Va(e){return ft[e?`dark`:`light`]}function Ha(e){let t=e?5:7;return{ok:mt[t],warn:ht[t],bad:Et[t],info:Dt[t]}}function Ua(e,t){return xt[t?`dark`:`light`][e]??Va(t).muted}function Wa(e){return e===`unhealthy`?`diamond`:e===`degraded`?`roundRect`:`circle`}function Ga(e){return e===`unknown`?`dashed`:`solid`}var Ka=e=>typeof e==`number`&&Number.isFinite(e)?e:null;function qa(e){return e.columns.flatMap((e,t)=>e.role===`measure`?[t]:[])}function Ja(e){let t=e.columns.findIndex(e=>e.role===`time`);if(t<0)return[];let n=e.columns.findIndex(e=>e.role===`dimension`),r=qa(e);if(n>=0&&r.length>0){let i=r[0],a=new Map;for(let r=0;r({name:e.columns[n].name,unit:e.columns[n].unit,points:e.values[t].map((t,r)=>[Number(t),Ka(e.values[n][r])])}))}function Ya(e){let t=e.columns.flatMap((e,t)=>e.role===`dimension`?[t]:[]),n=qa(e);if(t.length===0||n.length===0)return{categories:[],series:[]};let r=t[0],i=[];for(let t=0;t1){let a=t[1],o=n[0],s=new Map;for(let t=0;tnull)),s.get(n)[i.indexOf(String(e.values[r][t]??``))]=Ka(e.values[o][t])}return{categories:i,series:[...s.entries()].map(([t,n])=>({name:t,unit:e.columns[o].unit,values:n}))}}return{categories:i,series:n.map(t=>({name:e.columns[t].name,unit:e.columns[t].unit,values:e.values[t].map(Ka)}))}}function Xa(e,t){let n=e.filter(e=>e!==null);if(n.length===0)return null;switch(t){case`last`:return n[n.length-1];case`min`:return Math.min(...n);case`max`:return Math.max(...n);case`sum`:return n.reduce((e,t)=>e+t,0);default:return n.reduce((e,t)=>e+t,0)/n.length}}function Za(e,t){let n=qa(t)[0];return n===void 0?null:(e.reduce??`window`)===`window`?t.totals?Ka(t.totals[n]):Xa(t.values[n].map(Ka),`mean`):Xa(t.values[n].map(Ka),e.reduce??`mean`)}function Qa(e){let t=qa(e)[0];return t===void 0?[]:e.values[t].map(Ka)}var $a={ok:0,warn:1,bad:2};function eo(e){if(!e?.length)return;let t=[...e].sort((e,t)=>$a[e.status]-$a[t.status]),n=t[0],r=t[t.length-1];return $a[r.status]>$a[n.status]&&r.value!==n.value?r.value>n.value?`lower`:`higher`:`lower`}function to(e,t,n){if(e===null||!t||t.length===0)return null;n??=eo(t);let r=`ok`;for(let i of t)(n===`lower`?e>=i.value:e<=i.value)&&$a[i.status]>$a[r]&&(r=i.status);return r}function no(e,t){let n=Ct(e),r=Ct(t);return(Math.max(n,r)+.05)/(Math.min(n,r)+.05)}function ro(e,t){return`rgba(${[1,3,5].map(t=>parseInt(e.slice(t,t+2),16)).join(`, `)}, ${t})`}function io(e,t){return{color:e,...no(e,t.surface)<3?{borderColor:t.text,borderWidth:1}:{}}}function ao(e,t){return{color:e,...no(e,t.surface)<3?{shadowColor:t.text,shadowBlur:2}:{}}}function oo(e,t){return{ok:mt,warn:ht,bad:Et}[e][t?5:8]}function so(e){let t=Va(e),n=Ha(e);return{dark:e,text:t.text,muted:t.muted,grid:t.grid,surface:t.surface,border:t.border,status:{ok:n.ok,warn:n.warn,bad:n.bad},font:wt.display}}function co(e,t,n){if(!Array.isArray(e.series))return e;let r=e.series,i=Array.isArray(e.yAxis)?e.yAxis:[e.yAxis],a=[],o=r.map((e,o)=>{let s=e.endLabel;if(!s?.show||!Array.isArray(e.data))return e;let c;for(let t=e.data.length-1;t>=0;t--){let n=e.data[t];if(Array.isArray(n)&&typeof n[1]==`number`&&Number.isFinite(n[1])){c=n;break}}let l=i[Number(e.yAxisIndex??0)];if(!c||!l)return{...e,endLabel:{...s,show:!1}};let u=l.type===`log`?Math.log:e=>e,d=l.min??1/0,f=l.max??0;if(l.type===`log`&&(l.min===void 0||l.max===void 0)){for(let t of r)if(Number(t.yAxisIndex??0)===Number(e.yAxisIndex??0)&&Array.isArray(t.data))for(let e of t.data)Array.isArray(e)&&typeof e[1]==`number`&&Number.isFinite(e[1])&&e[1]>0&&(l.min===void 0&&(d=Math.min(d,e[1])),l.max===void 0&&(f=Math.max(f,e[1])))}Number.isFinite(d)||(d=1);let p=u(l.type===`log`?d:l.min??0),m=u(l.type===`log`?Math.max(f,d*1.01):l.max??1),h=n?.(o,c),g=Number.isFinite(h)?h:t.y+t.height*(1-(u(c[1])-p)/(m-p)),_=((s.lineHeight??14)+2)/2,v=[Math.max(t.y+_,Math.min(t.y+t.height-_,g)),...a.flatMap(e=>[e.y-e.half-_,e.y+e.half+_])].filter(e=>Number.isFinite(e)&&e-_>=t.y&&e+_<=t.y+t.height&&a.every(t=>Math.abs(t.y-e)>=t.half+_)).sort((e,t)=>Math.abs(e-g)-Math.abs(t-g))[0];return v===void 0?{...e,endLabel:{...s,show:!1}}:(a.push({y:v,half:_}),{...e,labelLayout:{dy:v-g,hideOverlap:!0}})});return{...e,series:o}}var lo=(e,t,n)=>ra(e)?n.muted:Ua(t,n.dark);function uo(e,t){let n=Ja(e);if(!e.columns.some(e=>e.role===`dimension`))for(let r of n)r.name=za(e.columns.find(e=>e.name===r.name)??r.name,t);return oa(n,t)}function fo(e,t){return{animationDuration:200,textStyle:{fontFamily:e.font,color:e.muted,fontSize:11},grid:{left:8,right:16,top:28,bottom:8,containLabel:!0},tooltip:{trigger:`axis`,formatter:na(e=>va(t,e)),confine:!0,backgroundColor:e.surface,borderColor:e.border,textStyle:{color:e.text,fontSize:12},valueFormatter:e=>va(t,e),axisPointer:{type:`line`,lineStyle:{color:e.border}}},aria:{enabled:!0}}}function po(e,t,n,r){return(e.thresholds??[]).map(i=>({yAxis:i.value,label:{formatter:`${i.label??i.status} ${ya(r??e.unit)(i.value).replace(/(?<=\d)(ms|s|m|h)$/,` $1`)}`,position:i.value<=(n.min+n.max)/2?`insideEndTop`:`insideEndBottom`,distance:8,color:t.muted,textBorderColor:t.surface,textBorderWidth:3,fontSize:12},lineStyle:{color:t.status[i.status],type:[4,3],width:1}}))}function mo(e,t,n,r={width:500,height:248}){let i=t.frame?uo(t.frame,e):{shown:[],hidden:0},a=i.shown,o=a[0]?.unit??e.unit,s=new Set(a.map(e=>e.name)),c=a.find(e=>ra(e.name)),l=t.previous&&t.shift_ms!==void 0?uo(t.previous,e).shown.flatMap(e=>ra(e.name)?c?[e]:[]:s.has(e.name)?[e]:[]):[],u=[...new Set([...a,...l].map(t=>t.unit??e.unit))];u.length===0&&u.push(e.unit);let d=e.options?.style??`line`,f=a.length>=2&&a.length<=6&&i.hidden===0&&d!==`bars`&&d!==`stacked`,p=f?Math.max(40,...a.map(e=>{let t=Array.from(e.name).slice(0,24).join(``);return r.measureText?.(t,`12px ${n.font}`)??Array.from(t).length*7.2}))+12:0,m=f?p+8:0,h=(e.options?.legend??`auto`)!==`hidden`&&a.length>1,g=ca(a.map(e=>e.name),r.width,h,n.text,n.font,r.measureText),_=r.height-g.top-(i.hidden?24:8)-22,v=Math.max(0,Math.floor(_/16)),y=t.shift_ms,b=u.map(t=>{let n=[...a,...l].filter(n=>(n.unit??e.unit)===t).flatMap(e=>e.points.flatMap(([,e])=>e===null?[]:[e]));if(d===`stacked`){let r=new Map;for(let n of a.filter(n=>(n.unit??e.unit)===t))for(let[e,t]of n.points){let n=r.get(e)??{positive:0,negative:0};t!==null&&(t>0?n.positive+=t:n.negative+=t),r.set(e,n)}n.push(...[...r.values()].flatMap(e=>[e.positive,e.negative]))}return Ca(Math.min(0,...n),Math.max(0,...n),t,_)}),x=a.map((t,r)=>{let i=lo(t.name,r,n);return{name:t.name,interactive:!0,yAxisIndex:u.indexOf(t.unit??e.unit),tooltip:{valueFormatter:n=>va(t.unit??e.unit,n)},type:d===`bars`||d===`stacked`?`bar`:`line`,data:t.points,endLabel:f?{show:r0?{symbol:[`none`,`none`],silent:!0,data:po(e,n,b[0],o)}:void 0}}),S=y===void 0?[]:l.map(t=>({name:`${t.name} · previous`,interactive:!1,yAxisIndex:u.indexOf(t.unit??e.unit),tooltip:{valueFormatter:n=>va(t.unit??e.unit,n)},type:`line`,data:t.points.map(([e,t])=>[e+y,t]),showSymbol:!1,silent:!0,z:1,lineStyle:{width:1,type:`dashed`,color:n.muted},itemStyle:{color:n.muted}})),C=u.map((t,r)=>({...e.options?.scale===`log`?{splitNumber:xa(_)}:b[r],type:e.options?.scale===`log`?`log`:`value`,position:r===0?`left`:`right`,offset:Math.max(0,r-1)*56,axisLine:{show:!1},splitLine:{show:r===0,lineStyle:{color:n.grid}},axisLabel:{color:n.muted,fontFamily:n.font,fontSize:11,hideOverlap:!0,formatter:ya(t)}}));return co({...fo(n,o),tooltip:{...fo(n,o).tooltip,formatter:na((t,n)=>va([...a,...l].find(e=>e.name===n||`${e.name} · previous`===n)?.unit??e.unit,t),!0)},legend:g.option,grid:{left:8,right:16+(f?m:0)+Math.max(0,u.length-2)*56,top:g.top,bottom:i.hidden?24:8,containLabel:!0},xAxis:{type:`time`,min:t.from_ms,max:t.to_ms,axisLine:{lineStyle:{color:n.grid}},axisTick:{show:!1},splitLine:{show:!1},axisLabel:{color:n.muted,fontFamily:n.font,fontSize:11,hideOverlap:!0,formatter:Ea}},yAxis:C.length===1?C[0]:C,series:[...x,...S],graphic:sa(i.hidden,n.muted)},{y:g.top,height:_})}function ho(e,t,n){if(n(e)<=t)return e;let r=Array.from(e);for(let e=r.length-1;e>0;e--){let i=Math.floor(e*.45),a=e-i,o=r.slice(0,i).join(``)+`…`+r.slice(-a).join(``);if(n(o)<=t)return o}return`…`}function go(e,t,n,r={width:500,height:248}){let i=Ya(t);if(t.columns.filter(e=>e.role===`dimension`).length<2)for(let n of i.series)n.name=za(t.columns.find(e=>e.name===n.name)??n.name,e);let a=i.categories,{shown:o,hidden:s}=oa(i.series,e),c=t.columns.flatMap((e,t)=>e.role===`dimension`?[t]:[]),l=new Map;for(let n=0;nString(t.values[e][n]??``))),{dimensions:r,...i})}let u=o[0]?.unit??e.unit,d=[...new Set(o.map(t=>t.unit??e.unit))];d.length===0&&d.push(e.unit);let f=o.length>1,p=!!(t.periods?.[`Before deploy`]||t.periods?.[`Since deploy`]),m=e=>r.measureText?.(e,`11px ${n.font}`)??Array.from(e).length*6.6,h=Math.min(r.width*.4,Math.max(40,...a.map(m))),g=ca(o.map(e=>e.name),r.width,f&&e.options?.legend!==`hidden`,n.text,n.font,r.measureText),_=d.map((t,i)=>({...Ca(Math.min(0,...o.filter(n=>(n.unit??e.unit)===t).flatMap(e=>e.values.filter(e=>e!==null))),Math.max(0,...o.filter(n=>(n.unit??e.unit)===t).flatMap(e=>e.values.filter(e=>e!==null))),t,r.width-h-80),type:`value`,position:i===0?`bottom`:`top`,offset:Math.max(0,i-1)*36,splitLine:{show:i===0,lineStyle:{color:n.grid}},axisLabel:{color:n.muted,fontFamily:n.font,fontSize:11,formatter:e=>ba(t,e),hideOverlap:!0}}));return{...fo(n,u),tooltip:{...fo(n,u).tooltip,formatter:na((t,n)=>va(o.find(e=>e.name===n)?.unit??e.unit,t)),axisPointer:{type:`shadow`}},legend:g.option,grid:{left:8,right:56,top:(f?g.top:8)+Math.max(0,d.length-1)*36,bottom:s?24:8,containLabel:!0},yAxis:{type:`category`,inverse:!0,data:a,splitLine:{show:!1},axisLine:{lineStyle:{color:n.grid}},axisTick:{show:!1},axisLabel:{color:n.muted,fontFamily:n.font,fontSize:11,width:h,overflow:`truncate`,formatter:e=>ho(e,h,m)}},xAxis:_.length===1?_[0]:_,series:o.map((t,r)=>({name:t.name,interactive:!0,xAxisIndex:d.indexOf(t.unit??e.unit),tooltip:{valueFormatter:n=>va(t.unit??e.unit,n)},type:`bar`,data:t.values.map((e,n)=>({value:e,selection:l.get(JSON.stringify(c.length>1?[a[n],t.name]:[a[n]]))})),barMaxWidth:p&&t.name===`Before deploy`?7:14,barGap:`20%`,itemStyle:{...io(p?t.name===`Before deploy`?n.muted:Ua(0,n.dark):lo(t.name,r,n),n),borderRadius:[0,4,4,0]},label:{show:p?t.name===`Since deploy`:!f||r===0,position:`right`,color:n.text,fontFamily:n.font,fontSize:11,formatter:({value:n})=>ba(t.unit??e.unit,n)}})),graphic:sa(s,n.muted)}}function _o(e,t,n,r=e.unit,i={width:270,height:140}){let a=e.min??0,o=e.max??100,s=vo(e,a,o,n),c=va(r,t),l=to(t,e.thresholds,e.better),u=l===`bad`?`◆ Bad`:l===`warn`?`■ Warn`:l===`ok`?`● OK`:t===null?`○ Unknown`:void 0,d=e=>`${e}40`,f=i.measureText?.(c,`600 28px ${n.font}`)??c.length*28*.6,p=i.measureText?.(u??``,`11px ${n.font}`)??(u?.length??0)*11*.6,m=i.width{let r=y;return y=e,{type:`rect`,shape:{x:4+r*_,y:g,width:(e-r)*_,height:10,r:[n===0?5:0,n===s.length-1?5:0,n===s.length-1?5:0,n===0?5:0]},style:{fill:d(t)}}}),{id:`gauge-fill`,type:`rect`,shape:{x:4,y:g,width:v*_,height:10,r:5},style:{fill:l?n.status[l]:Ua(0,n.dark)}},{id:`gauge-marker`,type:`rect`,shape:{x:3+v*_,y:g-2,width:2,height:14,r:1},style:{fill:n.text}},{type:`text`,left:4,top:g+12,style:{text:va(r,a),fill:n.muted,fontSize:11,fontFamily:n.font}},{type:`text`,right:4,top:g+12,style:{text:va(r,o),fill:n.muted,fontSize:11,fontFamily:n.font}}]}}function vo(e,t,n,r){let i=n-t||1,a=[t,...(e.thresholds??[]).map(e=>Math.min(n,Math.max(t,e.value))),n].sort((e,t)=>e-t),o=[];for(let t=0;t[(e.end-t)/i,r.status[e.status]])}var yo=function(e,t){return yo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},yo(e,t)};function U(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);yo(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var bo=`12px sans-serif`,xo=20,So=100,Co=`007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N`;function wo(e){var t={};if(typeof JSON>`u`)return t;for(var n=0;n=0)s=o*n.length;else for(var c=0;c=zo&&(Ro=0),Ro++}function Vo(){var e=[...arguments];typeof console<`u`&&console.error.apply(console,e)}function Ho(e){if(typeof e!=`object`||!e)return e;var t=e,n=ko.call(e);if(n===`[object Array]`){if(!xs(e)){t=[];for(var r=0,i=e.length;r`u`&&typeof self<`u`?Ns.worker=!0:!Ns.hasGlobalWindow||`Deno`in window||typeof navigator<`u`&&typeof navigator.userAgent==`string`&&navigator.userAgent.indexOf(`Node.js`)>-1?(Ns.node=!0,Ns.svgSupported=!0):Ps(navigator.userAgent,Ns);function Ps(e,t){var n=t.browser,r=e.match(/Firefox\/([\d.]+)/),i=e.match(/MSIE\s([\d.]+)/)||e.match(/Trident\/.+?rv:(([\d.]+))/),a=e.match(/Edge?\/([\d.]+)/),o=/micromessenger/i.test(e);if(r&&(n.firefox=!0,n.version=r[1]),i&&(n.ie=!0,n.version=i[1]),a&&(n.edge=!0,n.version=a[1],n.newEdge=+a[1].split(`.`)[0]>18),o&&(n.weChat=!0),t.svgSupported=typeof SVGRect<`u`,t.touchEventsSupported=`ontouchstart`in window&&!n.ie&&!n.edge,t.pointerEventsSupported=`onpointerdown`in window&&(n.edge||n.ie&&+n.version>=11),t.domSupported=typeof document<`u`){var s=document.documentElement.style;t.transform3dSupported=(n.ie&&`transition`in s||n.edge||`WebKitCSSMatrix`in window&&`m11`in new WebKitCSSMatrix||`MozPerspective`in s)&&!(`OTransition`in s),t.transformSupported=t.transform3dSupported||n.ie&&+n.version>=9}}var Fs=1e-4,Is=20;function Ls(e){return e.replace(/^\s+|\s+$/g,``)}var Rs=Math.min,zs=Math.max,Bs=Math.abs,Vs=Math.round,Hs=Math.floor,Us=Math.ceil,Ws=Math.pow,Gs=Math.log,Ks=Math.LN10,qs=Math.PI,Js=Math.random;function Ys(e,t,n,r){var i=t[0],a=t[1],o=n[0],s=n[1],c=a-i,l=s-o;if(c===0)return l===0?o:(o+s)/2;if(r){if(c>0){if(e<=i)return o;if(e>=a)return s}else if(e>=i)return o;else if(e<=a)return s}else{if(e===i)return o;if(e===a)return s}return(e-i)/c*l+o}var Xs=Zs;function Zs(e,t,n){switch(e){case`center`:case`middle`:e=`50%`;break;case`left`:case`top`:e=`0%`;break;case`right`:case`bottom`:e=`100%`}return Qs(e,t,n)}function Qs(e,t,n){return Y(e)?$s(e)?parseFloat(e)/100*t+(n||0):parseFloat(e):e==null?NaN:+e}function $s(e){return!!Ls(e).match(/%$/)}function ec(e,t,n){return isNaN(t)?n?``+e:+e:(t=Rs(zs(0,t),Is),e=(+e).toFixed(t),n?e:+e)}function tc(e){return e.sort(function(e,t){return e-t}),e}function nc(e){if(e=+e,isNaN(e))return 0;if(e>1e-14){for(var t=1,n=0;n<15;n++,t*=10)if(Vs(e*t)/t===e)return n}return rc(e)}function rc(e){var t=e.toString().toLowerCase(),n=t.indexOf(`e`),r=n>0?+t.slice(n+1):0,i=n>0?n:t.length,a=t.indexOf(`.`);return zs(0,(a<0?0:i-1-a)-r)}function ic(e,t,n){var r=Bs(e[1]-e[0]);if(!isFinite(r)||r===0)return NaN;var i=Gs(2*Bs(n||1)*Bs(r))/Ks,a=Gs(Bs(t))/Ks,o=zs(0,Us(-i+a));return isFinite(o)||(o=NaN),o}function ac(e,t){var n=zs(nc(e),nc(t)),r=e+t;return n>Is?r:ec(r,n)}var oc=Ws(2,53)-1;function sc(e){var t=qs*2;return(e%t+t)%t}function cc(e){return e>-Fs&&e=10&&t++,t}function pc(e,t){var n=fc(e),r=Ws(10,n),i=e/r;return e=(t===2?1:t?i<1.5?1:i<2.5?2:i<4?3:i<7?5:10:i<1?1:i<2?2:i<3?3:i<5?5:10)*r,ec(e,-n)}function mc(e){e.sort(function(e,t){return s(e,t,0)?-1:1});for(var t=-1/0,n=1,r=0;r0?e.length:0),this.item=null,this.key=NaN,this},e.prototype.next=function(){return(this._step>0?this._idx=this._end)&&(this.item=this._list[this._idx],this.key=this._idx+=this._step,!0)},e})();function ul(){return[1/0,-1/0]}function dl(e,t){hl(t)&&(te[1]&&(e[1]=t))}function fl(e,t){hl(t)&&te[1]&&(e[1]=t)}function ml(e,t){gl(t[0],t[1])&&(t[0]e[1]&&(e[1]=t[1]))}function hl(e){return e!=null&&isFinite(e)}function gl(e,t){return hl(e)&&hl(t)&&e<=t}function _l(e){var t=e[1]-e[0];return isFinite(t)&&t>=0}function vl(e){gl(e[0],e[1])&&e[0]>e[1]&&(e[0]=e[1])}function yl(){var e=`__ec_once_`+bl++;return function(t,n){Z(t,e)||(t[e]=1,n())}}var bl=_c();function xl(e,t,n){var r=Es(),i=0;G(e,function(a){var o=t(a),s=r.get(o)||0;n&&n(a,s),!s&&!n&&(e[i++]=a),r.set(o,s+1)}),n||(e.length=i)}function Sl(e){return e.value+``}function Cl(e){return e+``}function wl(e,t){return X(t,!0)?e.seriesIndex+2:0}function Tl(e,t,n){var r=e.getData().count();return{progressiveRender:n.progressiveEnabled&&t.incrementalPrepareRender&&r>=n.threshold,large:e.get(`large`)&&r>=e.get(`largeThreshold`),modDataCount:e.get(`progressiveChunkMode`)===`mod`?e.getData().count():null}}function El(e){return{overallReset:e}}var Dl=`.`,Ol=`___EC__COMPONENT__CONTAINER___`,kl=`___EC__EXTENDED_CLASS___`;function Al(e){var t={main:``,sub:``};if(e){var n=e.split(Dl);t.main=n[0]||``,t.sub=n[1]||``}return t}function jl(e){_s(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(e),`componentType "`+e+`" illegal`)}function Ml(e){return!!(e&&e[kl])}function Nl(e,t){e.$constructor=e,e.extend=function(e){var t=this,n;return Pl(t)?n=function(e){U(t,e);function t(){return e.apply(this,arguments)||this}return t}(t):(n=function(){(e.$constructor||t).apply(this,arguments)},Jo(n,this)),W(n.prototype,e),n[kl]=!0,n.extend=this.extend,n.superCall=Rl,n.superApply=zl,n.superClass=t,n}}function Pl(e){return rs(e)&&/^class\s/.test(Function.prototype.toString.call(e))}function Fl(e,t){e.extend=t.extend}var Il=Math.round(Math.random()*10);function Ll(e){var t=[`__\0is_clz`,Il++].join(`_`);e.prototype[t]=!0,e.isInstance=function(e){return!!(e&&e[t])}}function Rl(e,t){var n=[...arguments].slice(2);return this.superClass.prototype[t].apply(e,n)}function zl(e,t,n){return this.superClass.prototype[t].apply(e,n)}function Bl(e){var t={};e.registerClass=function(e){var r=e.type||e.prototype.type;if(r){jl(r),e.prototype.type=r;var i=Al(r);if(!i.sub)t[i.main]=e;else if(i.sub!==Ol){var a=n(i);a[i.sub]=e}}return e},e.getClass=function(e,n,r){var i=t[e];if(i&&i[Ol]&&(i=n?i[n]:null),r&&!i)throw Error(n?`Component `+e+`.`+(n||``)+` is used but not imported.`:e+`.type should be specified.`);return i},e.getClassesByMainType=function(e){var n=Al(e),r=[],i=t[n.main];return i&&i[Ol]?G(i,function(e,t){t!==Ol&&r.push(e)}):r.push(i),r},e.hasClass=function(e){return!!t[Al(e).main]},e.getAllClassMainTypes=function(){var e=[];return G(t,function(t,n){e.push(n)}),e},e.hasSubTypes=function(e){var n=t[Al(e).main];return n&&n[Ol]};function n(e){var n=t[e.main];return(!n||!n[Ol])&&(n=t[e.main]={},n[Ol]=!0),n}}function Vl(e,t){for(var n=0;n=0||i&&qo(i,s)<0)){var c=n.getShallow(s,t);c!=null&&(a[e[o][0]]=c)}}return a}}var Hl=Vl([[`fill`,`color`],[`shadowBlur`],[`shadowOffsetX`],[`shadowOffsetY`],[`opacity`],[`shadowColor`]]),Ul=function(){function e(){}return e.prototype.getAreaStyle=function(e,t){return Hl(this,e,t)},e}(),Wl=function(){function e(e){this.value=e}return e}(),Gl=function(){function e(){this._len=0}return e.prototype.insert=function(e){var t=new Wl(e);return this.insertEntry(t),t},e.prototype.insertEntry=function(e){this.head?(this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e):this.head=this.tail=e,this._len++},e.prototype.remove=function(e){var t=e.prev,n=e.next;t?t.next=n:this.head=n,n?n.prev=t:this.tail=t,e.next=e.prev=null,this._len--},e.prototype.len=function(){return this._len},e.prototype.clear=function(){this.head=this.tail=null,this._len=0},e}(),Kl=function(){function e(e){this._list=new Gl,this._maxSize=10,this._map={},this._maxSize=e}return e.prototype.put=function(e,t){var n=this._list,r=this._map,i=null;if(r[e]==null){var a=n.len(),o=this._lastRemovedEntry;if(a>=this._maxSize&&a>0){var s=n.head;n.remove(s),delete r[s.key],i=s.value,this._lastRemovedEntry=s}o?o.value=t:o=new Wl(t),o.key=e,n.insertEntry(o),r[e]=o}return i},e.prototype.get=function(e){var t=this._map[e],n=this._list;if(t!=null)return t!==n.tail&&(n.remove(t),n.insertEntry(t)),t.value},e.prototype.clear=function(){this._list.clear(),this._map={}},e.prototype.len=function(){return this._list.len()},e}(),ql=new Kl(50);function Jl(e){if(typeof e==`string`){var t=ql.get(e);return t&&t.image}return e}function Yl(e,t,n,r,i){if(!e)return t;if(typeof e==`string`){if(t&&t.__zrImageSrc===e||!n)return t;var a=ql.get(e),o={hostEl:n,cb:r,cbPayload:i};return a?(t=a.image,!Zl(t)&&a.pending.push(o)):(t=Eo.loadImage(e,Xl,Xl),t.__zrImageSrc=e,ql.put(e,t.__cachedImgObj={image:t,pending:[o]})),t}return e}function Xl(){var e=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var t=0;tu||d>f||p>m||h>g)return!1;var _=!(u=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height},e.prototype.contain=function(t,n){return e.contain(this,t,n)},e.prototype.clone=function(){return new e(this.x,this.y,this.width,this.height)},e.prototype.copy=function(e){Vu(this,e)},e.prototype.plain=function(){return{x:this.x,y:this.y,width:this.width,height:this.height}},e.prototype.isFinite=function(){return isFinite(this.x)&&isFinite(this.y)&&isFinite(this.width)&&isFinite(this.height)},e.prototype.isZero=function(){return this.width===0||this.height===0},e.create=function(t){return new e(t?t.x:0,t?t.y:0,t?t.width:0,t?t.height:0)},e.copy=function(e,t){return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e},e.applyTransform=function(e,t,n){if(!n){e!==t&&Vu(e,t);return}if(n[1]<1e-5&&n[1]>-1e-5&&n[2]<1e-5&&n[2]>-1e-5){var r=n[0],i=n[3],a=n[4],o=n[5];e.x=t.x*r+a,e.y=t.y*i+o,e.width=t.width*r,e.height=t.height*i,e.width<0&&(e.x+=e.width,e.width=-e.width),e.height<0&&(e.y+=e.height,e.height=-e.height);return}Au.x=Mu.x=t.x,Au.y=Nu.y=t.y,ju.x=Nu.x=t.x+t.width,ju.y=Mu.y=t.y+t.height,Au.transform(n),Nu.transform(n),ju.transform(n),Mu.transform(n),e.x=Tu(Au.x,ju.x,Mu.x,Nu.x),e.y=Tu(Au.y,ju.y,Mu.y,Nu.y);var s=Eu(Au.x,ju.x,Mu.x,Nu.x),c=Eu(Au.y,ju.y,Mu.y,Nu.y);e.width=s-e.x,e.height=c-e.y},e.calculateTransform=function(e,t,n){var r=n.width/t.width,i=n.height/t.height;return e=$l(e||[]),nu(e,e,lu(qu,-t.x,-t.y)),iu(e,e,lu(qu,r,i)),nu(e,e,lu(qu,n.x,n.y)),e},e}(),zu=Ru.create,Bu=Ru.set,Vu=Ru.copy,Hu=Ru.calculateTransform,Uu=Ru.applyTransform,Wu=Ru.contain,Gu=new Ru(0,0,0,0),Ku=new Ru(0,0,0,0),qu=[];function Ju(e,t,n,r,i,a,o,s){var c=Du(t-n),l=Du(r-e),u=Tu(c,l),d=Ou[i],f=Ou[1-i],p=ku[i];t=l||!Pu.bidirectional)&&(Fu[d]=-l,Fu[f]=0,Pu.useDir&&Pu.calcDirMTV())))}function Yu(){var e=0,t=new wu,n=new wu,r={minTv:new wu,maxTv:new wu,useDir:!1,dirMinTv:new wu,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(i,a){r.touchThreshold=0,i&&i.touchThreshold!=null&&(r.touchThreshold=Eu(0,i.touchThreshold)),r.negativeSize=!1,a&&(r.minTv.set(1/0,1/0),r.maxTv.set(0,0),r.useDir=!1,i&&i.direction!=null&&(r.useDir=!0,r.dirMinTv.copy(r.minTv),n.copy(r.minTv),e=i.direction,r.bidirectional=i.bidirectional==null||!!i.bidirectional,r.bidirectional||t.set(Math.cos(e),Math.sin(e))))},calcDirMTV:function(){var a=r.minTv,o=r.dirMinTv,s=a.y*a.y+a.x*a.x,c=Math.sin(e),l=Math.cos(e),u=c*a.y+l*a.x;if(i(u)){i(a.x)&&i(a.y)&&o.set(0,0);return}if(n.x=s*l/u,n.y=s*c/u,i(n.x)&&i(n.y)){o.set(0,0);return}(r.bidirectional||t.dot(n)>0)&&n.len()=ed)){e||=`12px sans-serif`;for(var t=[],n=+new Date,r=0;r<=127;r++)t[r]=Eo.measureText(String.fromCharCode(r),e).width;var i=+new Date-n;return i>16?$u=ed:i>2&&$u++,t}}var $u=0,ed=5;function td(e,t){return e.asciiWidthMapTried||=(e.asciiWidthMap=Qu(e.font),!0),0<=t&&t<=127?e.asciiWidthMap==null?e.asciiCharWidth:e.asciiWidthMap[t]:e.stWideCharWidth}function nd(e,t){var n=e.strWidthCache,r=n.get(t);return r??(r=Eo.measureText(t,e.font).width,n.put(t,r)),r}function rd(e,t,n,r){var i=nd(Xu(t),e),a=sd(t);return new Ru(ad(0,i,n),od(0,a,r),i,a)}function id(e,t,n,r){var i=((e||``)+``).split(` +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/panel-sql-editor-CCiQZRwh.js","assets/useRouter-ByJ6_rwb.js","assets/brand-DUaZkIz1.js","assets/index-m8tRkNwz.js","assets/useNavigate-B1zgPEUp.js","assets/preload-helper-DJZNfKNH.js","assets/Tooltip-B3r3s_B9.js","assets/index-ADB9ThEc.css"])))=>i.map(i=>d[i]); +import{a as e,i as t,o as n,r,s as i}from"./useRouter-ByJ6_rwb.js";import{A as a,C as o,D as s,E as c,K as l,M as u,O as d,P as f,Q as p,S as m,T as h,X as g,Y as _,Z as v,_ as y,_t as b,a as x,c as S,d as C,dt as w,f as T,ft as E,g as D,gt as O,h as k,j as A,k as j,lt as M,m as N,mt as P,nt as F,o as I,ot as L,p as ee,r as te,s as ne,st as re,tt as ie,u as ae,ut as R,v as oe,x as z,y as se}from"./brand-DUaZkIz1.js";import{t as ce}from"./preload-helper-DJZNfKNH.js";import{C as le,E as ue,b as de,o as fe,t as pe,w as me}from"./Tooltip-B3r3s_B9.js";import{a as he,c as ge,d as _e,i as ve,l as B,n as ye,o as be,r as xe,s as Se,t as Ce,u as we}from"./dashboard-change-chips-DKNHrHOk.js";import{n as Te,r as Ee,t as De}from"./WarningCircle.es-CEJpUomm.js";import{$ as Oe,$t as ke,A as Ae,B as je,Bt as Me,C as Ne,D as Pe,E as Fe,F as Ie,Gt as Le,Ht as Re,I as ze,J as Be,Jt as Ve,Kt as He,M as Ue,N as We,O as Ge,P as Ke,Q as qe,Qt as Je,Ut as Ye,V as Xe,Vt as Ze,Wt as Qe,X as $e,Xt as et,Yt as tt,Z as nt,_ as rt,a as it,an as at,b as ot,c as st,ct,d as lt,en as ut,et as dt,h as ft,i as pt,in as mt,j as ht,k as gt,l as _t,m as vt,n as yt,nn as bt,o as xt,on as St,qt as Ct,r as wt,rn as Tt,s as Et,sn as Dt,t as Ot,tn as kt,u as At,v as jt,w as Mt,x as Nt}from"./index-m8tRkNwz.js";function Pt(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();let n=Ft(e);if(n.length!==Ft(t).length)return!1;for(let r=0;r{if(typeof n!=`string`||n.trim().length===0)throw Error(t);return`${e}-${n}`}}var H=r();function Lt(e){return typeof e==`object`&&e?`base`in e?e.base:void 0:e}function Rt(e,t){if(e===t||Number.isNaN(e)&&Number.isNaN(t))return!0;if(!(e instanceof Object)||!(t instanceof Object))return!1;let n=Object.keys(e),{length:r}=n;if(r!==Object.keys(t).length)return!1;for(let i=0;i{r.current||=window.setTimeout(()=>{i(...e),r.current=null},t)},[t]),o=(0,V.useCallback)(()=>{r.current&&=(window.clearTimeout(r.current),null)},[]);return(0,V.useEffect)(()=>(n.autoInvoke&&a(),o),[o,a]),{start:a,clear:o}}function Ut(e){let t=(0,V.useRef)(void 0);return(0,V.useEffect)(()=>{t.current=e},[e]),t.current}function Wt(e,t,n){let r=(0,V.useRef)(null);(0,V.useEffect)(()=>{r.current&&=(r.current.disconnect(),null);let i=typeof n==`function`?n():n;return i&&(r.current=new MutationObserver(e),r.current.observe(i,t)),()=>{r.current&&=(r.current.disconnect(),null)}},[e,t,n])}function Gt(){let[e,t]=(0,V.useState)(!1);return(0,V.useEffect)(()=>t(!0),[]),e}function Kt(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`}function qt(e,t=document){let n=t.querySelector(e);if(n)return n;let r=t.querySelectorAll(`*`);for(let t=0;t{if(!e||!t||!n.current)return;let r=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=t.offsetWidth===0?1:i.width/t.offsetWidth,o=t.offsetHeight===0?1:i.height/t.offsetHeight,s=window.getComputedStyle(e),c=window.getComputedStyle(t),l=de(s.borderTopWidth)+de(c.borderTopWidth),u=de(s.borderLeftWidth)+de(c.borderLeftWidth),d={top:(r.top-i.top)/o-l,left:(r.left-i.left)/a-u,width:r.width/a,height:r.height/o};n.current.style.transform=`translateY(${d.top}px) translateX(${d.left}px)`,n.current.style.width=`${d.width}px`,n.current.style.height=`${d.height}px`},p=()=>{window.clearTimeout(o.current),n.current&&(n.current.style.transitionDuration=`0ms`),f(),o.current=window.setTimeout(()=>{n.current&&(n.current.style.transitionDuration=``)},30)},m=(0,V.useRef)(null),h=(0,V.useRef)(null);return(0,V.useEffect)(()=>{if(c&&s.current!==e&&i&&i(),s.current=e,f(),e)return m.current=new ResizeObserver(p),m.current.observe(e),t&&(h.current=new ResizeObserver(p),h.current.observe(t)),()=>{m.current?.disconnect(),h.current?.disconnect()}},[t,e]),(0,V.useEffect)(()=>{if(t){let e=e=>{Zt(e.target,t)&&(p(),d(!1))};return t.addEventListener(`transitionend`,e),()=>{t.removeEventListener(`transitionend`,e)}}},[t]),(0,V.useEffect)(()=>{if(n.current&&a){let e=e=>{e.propertyName===`transform`&&a()};return n.current.addEventListener(`transitionend`,e),()=>{n.current?.removeEventListener(`transitionend`,e)}}},[a]),Ht(()=>{_e()!==`test`&&l(!0)},20,{autoInvoke:!0}),Wt(e=>{e.forEach(e=>{e.type===`attributes`&&e.attributeName===`dir`&&p()})},{attributes:!0,attributeFilter:[`dir`]},()=>document.documentElement),{initialized:c,hidden:u}}var $t={root:`m_96b553a6`},en=g((e,{transitionDuration:t},{shouldReduceMotion:n})=>({root:{"--transition-duration":e.respectReducedMotion&&n?`0ms`:typeof t==`number`?`${t}ms`:t||`150ms`}})),tn=h(e=>{let t=u(`FloatingIndicator`,null,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,target:d,parent:f,transitionDuration:m,mod:h,displayAfterTransitionEnd:g,onTransitionStart:_,onTransitionEnd:v,attributes:y,ref:b,...x}=t,S=p(),C=a({name:`FloatingIndicator`,classes:$t,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:y,vars:l,varsResolver:en,stylesCtx:{shouldReduceMotion:S}}),w=(0,V.useRef)(null),{initialized:T,hidden:E}=Qt({target:d,parent:f,ref:w,displayAfterTransitionEnd:g,onTransitionStart:_,onTransitionEnd:v}),D=ie(b,w);return!d||!f?null:(0,H.jsx)(o,{ref:D,mod:[{initialized:T,hidden:E},h],...C(`root`),...x})});tn.displayName=`@mantine/core/FloatingIndicator`,tn.classes=$t,tn.varsResolver=en;var[nn,rn]=ue(`Accordion component was not found in the tree`),[an,on]=ue(`Accordion.Item component was not found in the tree`),sn={root:`m_9bdbb667`,panel:`m_df78851f`,content:`m_4ba554d4`,itemTitle:`m_8fa820a0`,control:`m_4ba585b8`,"control--default":`m_6939a5e9`,"control--contained":`m_4271d21b`,label:`m_df3ffa0f`,chevron:`m_3f35ae96`,icon:`m_9bd771fe`,item:`m_9bd7b098`,"item--default":`m_fe19b709`,"item--contained":`m_1f921b3b`,"item--filled":`m_2cdf939a`,"item--separated":`m_9f59b069`},cn=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,chevron:s,icon:c,onClick:l,onKeyDown:d,children:f,disabled:p,mod:h,...g}=u(`AccordionControl`,null,e),{value:_}=on(),v=rn(),y=v.isItemActive(_),b=typeof v.order==`number`,x=`h${v.order}`,S=(0,H.jsxs)(m,{...v.getStyles(`control`,{className:n,classNames:t,style:r,styles:i,variant:v.variant}),unstyled:v.unstyled,mod:[`accordion-control`,{active:y,"chevron-position":v.chevronPosition,disabled:p},h],onClick:e=>{l?.(e),v.onChange(_)},type:`button`,disabled:p,"aria-expanded":y,"aria-controls":v.getRegionId(_),id:v.getControlId(_),onKeyDown:Tt({siblingSelector:`[data-accordion-control]`,parentSelector:`[data-accordion]`,activateOnFocus:!1,loop:v.loop,orientation:`vertical`,onKeyDown:d}),...g,children:[(0,H.jsx)(o,{component:`span`,mod:{rotate:!v.disableChevronRotation&&y,position:v.chevronPosition},...v.getStyles(`chevron`,{classNames:t,styles:i}),children:s||v.chevron}),(0,H.jsx)(`span`,{...v.getStyles(`label`,{classNames:t,styles:i}),children:f}),c&&(0,H.jsx)(o,{component:`span`,mod:{"chevron-position":v.chevronPosition},...v.getStyles(`icon`,{classNames:t,styles:i}),children:c})]});return b?(0,H.jsx)(x,{...v.getStyles(`itemTitle`,{classNames:t,styles:i}),children:S}):S});cn.displayName=`@mantine/core/AccordionControl`,cn.classes=sn;var ln=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,value:s,mod:c,...l}=u(`AccordionItem`,null,e),d=rn();return(0,H.jsx)(an,{value:{value:s},children:(0,H.jsx)(o,{mod:[{active:d.isItemActive(s)},c],...d.getStyles(`item`,{className:n,classNames:t,styles:i,style:r,variant:d.variant}),...l})})});ln.displayName=`@mantine/core/AccordionItem`,ln.classes=sn;var un=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,children:o,keepMounted:s,keepMountedMode:c,...l}=u(`AccordionPanel`,null,e),{value:d}=on(),f=rn();return(0,H.jsx)(we,{...f.getStyles(`panel`,{className:n,classNames:t,style:r,styles:i}),expanded:f.isItemActive(d),transitionDuration:f.transitionDuration??200,role:`region`,id:f.getRegionId(d),"aria-labelledby":f.getControlId(d),keepMounted:s??f.keepMounted,keepMountedMode:c??f.keepMountedMode,...l,children:(0,H.jsx)(`div`,{...f.getStyles(`content`,{classNames:t,styles:i}),children:o})})});un.displayName=`@mantine/core/AccordionPanel`,un.classes=sn;var dn={multiple:!1,loop:!0,disableChevronRotation:!1,disableCollapse:!1,chevronPosition:`right`,variant:`default`,chevronSize:`auto`,chevronIconSize:16,keepMountedMode:`activity`},fn=g((e,{transitionDuration:t,chevronSize:n,radius:r})=>({root:{"--accordion-transition-duration":t===void 0?void 0:`${t}ms`,"--accordion-chevron-size":n===void 0?void 0:P(n),"--accordion-radius":r===void 0?void 0:re(r)}})),pn=c(e=>{let t=u(`Accordion`,dn,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,children:d,multiple:f,value:p,defaultValue:m,onChange:h,id:g,loop:_,transitionDuration:v,disableChevronRotation:y,disableCollapse:b,chevronPosition:x,chevronSize:S,order:C,chevron:w,variant:T,radius:E,chevronIconSize:D,attributes:O,keepMounted:k,keepMountedMode:A,...j}=t,M=F(g),[N,P]=kt({value:p,defaultValue:m,finalValue:f?[]:null,onChange:h}),I=e=>Array.isArray(N)?N.includes(e):e===N,L=e=>{if(!Array.isArray(N)&&b&&e===N)return;let t=Array.isArray(N)?N.includes(e)?N.filter(t=>t!==e):[...N,e]:e===N?null:e;P(t)},ee=a({name:`Accordion`,classes:sn,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:O,vars:l,varsResolver:fn});return(0,H.jsx)(nn,{value:{isItemActive:I,onChange:L,getControlId:It(`${M}-control`,`Accordion.Item component was rendered with invalid value or without value`),getRegionId:It(`${M}-panel`,`Accordion.Item component was rendered with invalid value or without value`),chevron:w===null?null:w||(0,H.jsx)(Ve,{size:D}),transitionDuration:v,disableChevronRotation:y,chevronPosition:x,order:C,loop:_,getStyles:ee,variant:T,unstyled:c,keepMounted:k,keepMountedMode:A},children:(0,H.jsx)(o,{...ee(`root`),id:M,...j,variant:T,"data-accordion":!0,children:d})})});pn.classes=sn,pn.varsResolver=fn,pn.displayName=`@mantine/core/Accordion`,pn.Item=ln,pn.Panel=un,pn.Control=cn,pn.Chevron=Ve;function mn(e){return typeof e==`string`?{value:e,label:e}:typeof e==`object`&&`value`in e&&!(`label`in e)?{value:e.value,label:`${e.value}`,disabled:e.disabled}:typeof e==`object`&&`group`in e?{group:e.group,items:e.items.map(e=>mn(e))}:typeof e==`number`||typeof e==`bigint`||typeof e==`boolean`?{value:e,label:`${e}`}:e}function hn(e){return e?e.map(e=>mn(e)):[]}function gn(e){return e.reduce((e,t)=>`group`in t?{...e,...gn(t.items)}:(e[`${t.value}`]=t,e),{})}var _n={dropdown:`m_88b62a41`,search:`m_985517d8`,options:`m_b2821a6e`,option:`m_92253aa5`,empty:`m_2530cd1d`,header:`m_858f94bd`,footer:`m_82b967cb`,group:`m_254f3e4f`,groupLabel:`m_2bb2e9e5`,chevron:`m_2943220b`,optionsDropdownOption:`m_390b5f4`,optionsDropdownCheckIcon:`m_8ee53fc2`,optionsDropdownCheckPlaceholder:`m_a530ee0a`},vn={error:null},yn=g((e,{size:t,color:n})=>({chevron:{"--combobox-chevron-size":M(t,`combobox-chevron-size`),"--combobox-chevron-color":n?l(n,e):void 0}})),bn=h(e=>{let t=u(`ComboboxChevron`,vn,e),{size:n,error:r,style:i,className:s,classNames:c,styles:l,unstyled:d,vars:f,attributes:p,mod:m,...h}=t,g=a({name:`ComboboxChevron`,classes:_n,props:t,style:i,className:s,classNames:c,styles:l,unstyled:d,vars:f,varsResolver:yn,attributes:p,rootSelector:`chevron`});return(0,H.jsx)(o,{component:`svg`,...h,...g(`chevron`),size:n,viewBox:`0 0 15 15`,fill:`none`,xmlns:`http://www.w3.org/2000/svg`,mod:[`combobox-chevron`,{error:r},m],children:(0,H.jsx)(`path`,{d:`M4.93179 5.43179C4.75605 5.60753 4.75605 5.89245 4.93179 6.06819C5.10753 6.24392 5.39245 6.24392 5.56819 6.06819L7.49999 4.13638L9.43179 6.06819C9.60753 6.24392 9.89245 6.24392 10.0682 6.06819C10.2439 5.89245 10.2439 5.60753 10.0682 5.43179L7.81819 3.18179C7.73379 3.0974 7.61933 3.04999 7.49999 3.04999C7.38064 3.04999 7.26618 3.0974 7.18179 3.18179L4.93179 5.43179ZM10.0682 9.56819C10.2439 9.39245 10.2439 9.10753 10.0682 8.93179C9.89245 8.75606 9.60753 8.75606 9.43179 8.93179L7.49999 10.8636L5.56819 8.93179C5.39245 8.75606 5.10753 8.75606 4.93179 8.93179C4.75605 9.10753 4.75605 9.39245 4.93179 9.56819L7.18179 11.8182C7.35753 11.9939 7.64245 11.9939 7.81819 11.8182L10.0682 9.56819Z`,fill:`currentColor`,fillRule:`evenodd`,clipRule:`evenodd`})})});bn.classes=_n,bn.varsResolver=yn,bn.displayName=`@mantine/core/ComboboxChevron`;var[xn,Sn]=ue(`Combobox component was not found in tree`);function Cn({onMouseDown:e,onClick:t,onClear:n,...r}){return(0,H.jsx)(k.ClearButton,{tabIndex:-1,"aria-hidden":!0,...r,onMouseDown:t=>{t.preventDefault(),e?.(t)},onClick:e=>{n(),t?.(e)}})}Cn.displayName=`@mantine/core/ComboboxClearButton`;var wn=h(e=>{let{classNames:t,styles:n,className:r,style:i,hidden:a,...o}=u(`ComboboxDropdown`,null,e),s=Sn();return(0,H.jsx)(et.Dropdown,{...o,role:`presentation`,"data-hidden":a||void 0,"data-floating-height":s.floatingHeight||void 0,...s.getStyles(`dropdown`,{className:r,style:i,classNames:t,styles:n})})});wn.classes=_n,wn.displayName=`@mantine/core/ComboboxDropdown`;var Tn={refProp:`ref`},En=h(e=>{let{children:t,refProp:n,ref:r}=u(`ComboboxDropdownTarget`,Tn,e);if(Sn(),!w(t))throw Error(`Combobox.DropdownTarget component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);return(0,H.jsx)(et.Target,{ref:r,refProp:n,children:t})});En.displayName=`@mantine/core/ComboboxDropdownTarget`;var Dn=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...s}=u(`ComboboxEmpty`,null,e),c=Sn();return(0,H.jsx)(o,{...c.getStyles(`empty`,{className:n,classNames:t,styles:i,style:r}),...s})});Dn.classes=_n,Dn.displayName=`@mantine/core/ComboboxEmpty`;function On({onKeyDown:e,onClick:t,withKeyboardNavigation:n,withAriaAttributes:r,withExpandedAttribute:i,targetType:a,autoComplete:o}){let s=Sn(),[c,l]=(0,V.useState)(null),u=t=>{if(e?.(t),!s.readOnly&&n){if(t.nativeEvent.isComposing)return;if(t.nativeEvent.code===`ArrowDown`&&(t.preventDefault(),s.store.dropdownOpened?l(s.store.selectNextOption()):(s.store.openDropdown(`keyboard`),l(s.store.selectActiveOption()),s.store.updateSelectedOptionIndex(`selected`,{scrollIntoView:!0}))),t.nativeEvent.code===`ArrowUp`&&(t.preventDefault(),s.store.dropdownOpened?l(s.store.selectPreviousOption()):(s.store.openDropdown(`keyboard`),l(s.store.selectActiveOption()),s.store.updateSelectedOptionIndex(`selected`,{scrollIntoView:!0}))),t.nativeEvent.code===`Enter`||t.nativeEvent.code===`NumpadEnter`){if(t.nativeEvent.keyCode===229)return;let e=s.store.getSelectedOptionIndex();s.store.dropdownOpened&&e!==-1?(t.preventDefault(),s.store.clickSelectedOption()):a===`button`&&(t.preventDefault(),s.store.openDropdown(`keyboard`))}t.key===`Escape`&&s.store.closeDropdown(`keyboard`),t.nativeEvent.code===`Space`&&a===`button`&&(t.preventDefault(),s.store.toggleDropdown(`keyboard`))}},d=r?{...i?{role:`combobox`}:{},"aria-haspopup":`listbox`,"aria-expanded":i?!!(s.store.listId&&s.store.dropdownOpened):void 0,"aria-controls":s.store.dropdownOpened&&s.store.listId?s.store.listId:void 0,"aria-activedescendant":s.store.dropdownOpened&&c||void 0,autoComplete:o,"data-expanded":s.store.dropdownOpened||void 0,"data-mantine-stop-propagation":s.store.dropdownOpened||void 0}:{},f=e=>{a===`button`&&e.currentTarget.focus(),t?.(e)};return{...d,onKeyDown:u,onClick:f}}var kn={refProp:`ref`,targetType:`input`,withKeyboardNavigation:!0,withAriaAttributes:!0,withExpandedAttribute:!1,autoComplete:`off`},An=h(e=>{let{children:t,refProp:n,withKeyboardNavigation:r,withAriaAttributes:i,withExpandedAttribute:a,targetType:o,autoComplete:s,ref:c,...l}=u(`ComboboxEventsTarget`,kn,e),d=v(t);if(!d)throw Error(`Combobox.EventsTarget component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let f=Sn(),p=On({targetType:o,withAriaAttributes:i,withKeyboardNavigation:r,withExpandedAttribute:a,onKeyDown:d.props.onKeyDown,onClick:d.props.onClick,autoComplete:s});return(0,V.cloneElement)(d,{...p,...l,[n]:ie(c,f.store.targetRef,le(d))})});An.displayName=`@mantine/core/ComboboxEventsTarget`;var jn=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...s}=u(`ComboboxFooter`,null,e),c=Sn();return(0,H.jsx)(o,{...c.getStyles(`footer`,{className:n,classNames:t,style:r,styles:i}),...s,onMouseDown:e=>{e.preventDefault()}})});jn.classes=_n,jn.displayName=`@mantine/core/ComboboxFooter`;var Mn=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,children:s,label:c,id:l,...d}=u(`ComboboxGroup`,null,e),f=Sn(),p=F(l),m=c!=null&&c!==!1&&c!==``;return(0,H.jsxs)(o,{role:`group`,"aria-labelledby":m?p:void 0,...f.getStyles(`group`,{className:n,classNames:t,style:r,styles:i}),...d,children:[m&&(0,H.jsx)(`div`,{id:p,...f.getStyles(`groupLabel`,{classNames:t,styles:i}),children:c}),s]})});Mn.classes=_n,Mn.displayName=`@mantine/core/ComboboxGroup`;var Nn=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,...s}=u(`ComboboxHeader`,null,e),c=Sn();return(0,H.jsx)(o,{...c.getStyles(`header`,{className:n,classNames:t,style:r,styles:i}),...s,onMouseDown:e=>{e.preventDefault()}})});Nn.classes=_n,Nn.displayName=`@mantine/core/ComboboxHeader`;function Pn({value:e,valuesDivider:t=`,`,...n}){return(0,H.jsx)(`input`,{type:`hidden`,value:Array.isArray(e)?e.join(t):e?`${e}`:``,...n})}Pn.displayName=`@mantine/core/ComboboxHiddenInput`;var Fn=h(e=>{let t=u(`ComboboxOption`,null,e),{classNames:n,className:r,style:i,styles:a,vars:s,onClick:c,id:l,active:d,onMouseDown:f,onMouseOver:p,disabled:m,selected:h,mod:g,..._}=t,v=Sn(),y=(0,V.useId)(),b=l||y;return(0,H.jsx)(o,{...v.getStyles(`option`,{className:r,classNames:n,styles:a,style:i}),"aria-disabled":m||void 0,..._,id:b,mod:[`combobox-option`,{"combobox-active":d,"combobox-disabled":m,"combobox-selected":h},g],role:`option`,onClick:e=>{m?e.preventDefault():(v.onOptionSubmit?.(t.value,t),c?.(e))},onMouseDown:e=>{e.preventDefault(),f?.(e)},onMouseOver:e=>{v.resetSelectionOnOptionHover&&v.store.resetSelectedOption(),p?.(e)}})});Fn.classes=_n,Fn.displayName=`@mantine/core/ComboboxOption`;var In=h(e=>{let{classNames:t,className:n,style:r,styles:i,id:a,onMouseDown:s,labelledBy:c,...l}=u(`ComboboxOptions`,null,e),d=Sn(),f=F(a);return(0,V.useEffect)(()=>{d.store.setListId(f)},[f]),(0,H.jsx)(o,{...d.getStyles(`options`,{className:n,style:r,classNames:t,styles:i}),...l,id:f,role:`listbox`,"aria-labelledby":c,onMouseDown:e=>{e.preventDefault(),s?.(e)}})});In.classes=_n,In.displayName=`@mantine/core/ComboboxOptions`;var Ln={withAriaAttributes:!0,withKeyboardNavigation:!0},Rn=h(e=>{let{classNames:t,styles:n,unstyled:r,vars:i,withAriaAttributes:a,onKeyDown:o,onClick:s,withKeyboardNavigation:c,size:l,ref:d,...f}=u(`ComboboxSearch`,Ln,e),p=Sn(),m=p.getStyles(`search`),h=On({targetType:`input`,withAriaAttributes:a,withKeyboardNavigation:c,withExpandedAttribute:!1,onKeyDown:o,onClick:s,autoComplete:`off`});return(0,H.jsx)(k,{ref:ie(d,p.store.searchRef),classNames:[{input:m.className},t],styles:[{input:m.style},n],size:l||p.size,...h,...f,__staticSelector:`Combobox`})});Rn.classes=_n,Rn.displayName=`@mantine/core/ComboboxSearch`;var zn={refProp:`ref`,targetType:`input`,withKeyboardNavigation:!0,withAriaAttributes:!0,withExpandedAttribute:!1,autoComplete:`off`},Bn=h(e=>{let{children:t,refProp:n,withKeyboardNavigation:r,withAriaAttributes:i,withExpandedAttribute:a,targetType:o,autoComplete:s,ref:c,...l}=u(`ComboboxTarget`,zn,e),d=v(t);if(!d)throw Error(`Combobox.Target component children should be an element or a component that accepts ref. Fragments, strings, numbers and other primitive values are not supported`);let f=Sn(),p=On({targetType:o,withAriaAttributes:i,withKeyboardNavigation:r,withExpandedAttribute:a,onKeyDown:d.props.onKeyDown,onClick:d.props.onClick,autoComplete:s}),m=(0,V.cloneElement)(d,{...p,...l});return(0,H.jsx)(et.Target,{refProp:n,ref:ie(c,f.store.targetRef),children:m})});Bn.displayName=`@mantine/core/ComboboxTarget`;function Vn(e,t,n){for(let n=e-1;n>=0;--n)if(!t[n].hasAttribute(`data-combobox-disabled`))return n;if(n){for(let e=t.length-1;e>-1;--e)if(!t[e].hasAttribute(`data-combobox-disabled`))return e}return e}function Hn(e,t,n){for(let n=e+1;n{s||(c(!0),i?.(e))},[c,i,s]),_=(0,V.useCallback)((e=`unknown`)=>{s&&(c(!1),r?.(e))},[c,r,s]),v=(0,V.useCallback)((e=`unknown`)=>{s?_(e):g(e)},[_,g,s]),y=(0,V.useCallback)(()=>{let e=Yt(f.current);qt(`#${l.current} [data-combobox-selected]`,e)?.removeAttribute(`data-combobox-selected`)},[]),b=(0,V.useCallback)(e=>{let t=Yt(f.current),n=qt(`#${l.current}`,t),r=n?Jt(`[data-combobox-option]`,n):null;if(!r)return null;let i=e>=r.length?0:e<0?r.length-1:e;return u.current=i,r?.[i]&&!r[i].hasAttribute(`data-combobox-disabled`)?(y(),r[i].setAttribute(`data-combobox-selected`,`true`),r[i].scrollIntoView({block:`nearest`,behavior:o}),r[i].id):null},[o,y]),x=(0,V.useCallback)(()=>{let e=Yt(f.current),t=qt(`#${l.current} [data-combobox-active]`,e);if(t){let n=Jt(`#${l.current} [data-combobox-option]`,e).findIndex(e=>e===t);return b(n)}return b(0)},[b]),S=(0,V.useCallback)(()=>{let e=Yt(f.current),t=Jt(`#${l.current} [data-combobox-option]`,e);return b(Hn(u.current,t,a))},[b,a]),C=(0,V.useCallback)(()=>{let e=Yt(f.current),t=Jt(`#${l.current} [data-combobox-option]`,e);return b(Vn(u.current,t,a))},[b,a]),w=(0,V.useCallback)(()=>{let e=Yt(f.current),t=Jt(`#${l.current} [data-combobox-option]`,e);return b(Un(t))},[b]),T=(0,V.useCallback)((e=`selected`,t)=>{if(typeof e==`number`){u.current=e;let n=Yt(f.current),r=Jt(`#${l.current} [data-combobox-option]`,n);t?.scrollIntoView&&r[e]?.scrollIntoView({block:`nearest`,behavior:o});return}h.current=window.setTimeout(()=>{let n=Yt(f.current),r=Jt(`#${l.current} [data-combobox-option]`,n),i=r.findIndex(t=>t.hasAttribute(`data-combobox-${e}`));u.current=i,t?.scrollIntoView&&r[i]?.scrollIntoView({block:`nearest`,behavior:o})},0)},[]),E=(0,V.useCallback)(()=>{u.current=-1,y()},[y]),D=(0,V.useCallback)(()=>{let e=Yt(f.current);(Jt(`#${l.current} [data-combobox-option]`,e)?.[u.current])?.click()},[]),O=(0,V.useCallback)(e=>{l.current=e},[]),k=(0,V.useCallback)(()=>{p.current=window.setTimeout(()=>d.current?.focus(),0)},[]),A=(0,V.useCallback)(()=>{m.current=window.setTimeout(()=>f.current?.focus(),0)},[]),j=(0,V.useCallback)(()=>u.current,[]);return(0,V.useEffect)(()=>()=>{window.clearTimeout(p.current),window.clearTimeout(m.current),window.clearTimeout(h.current)},[]),{dropdownOpened:s,openDropdown:g,closeDropdown:_,toggleDropdown:v,selectedOptionIndex:u.current,getSelectedOptionIndex:j,selectOption:b,selectFirstOption:w,selectActiveOption:x,selectNextOption:S,selectPreviousOption:C,resetSelectedOption:E,updateSelectedOptionIndex:T,listId:l.current,setListId:O,clickSelectedOption:D,searchRef:d,focusSearchInput:k,targetRef:f,focusTarget:A}}var Gn={keepMounted:!0,keepMountedMode:`display-none`,withinPortal:!0,resetSelectionOnOptionHover:!1,width:`target`,transitionProps:{transition:`fade`,duration:0},size:`sm`},Kn=g((e,{size:t,dropdownPadding:n})=>({options:{"--combobox-option-fz":L(t),"--combobox-option-padding":M(t,`combobox-option-padding`)},dropdown:{"--combobox-padding":n===void 0?void 0:P(n),"--combobox-option-fz":L(t),"--combobox-option-padding":M(t,`combobox-option-padding`)}})),qn=e=>{let t=u(`Combobox`,Gn,e),{classNames:n,styles:r,unstyled:i,children:o,store:s,vars:c,onOptionSubmit:l,onClose:d,size:f,dropdownPadding:p,resetSelectionOnOptionHover:m,__staticSelector:h,readOnly:g,attributes:_,floatingHeight:v,middlewares:y,...b}=t,x=v===`viewport`?{...y,flip:!1,size:{...typeof y?.size==`object`?y.size:{},padding:typeof y?.size==`object`&&y.size.padding!==void 0?y.size.padding:10,apply:({availableHeight:e,availableWidth:t,elements:n,...r})=>{n.floating.style.setProperty(`--combobox-floating-max-height`,`${e}px`);let i=y?.size;typeof i==`object`&&i.apply?i.apply({availableHeight:e,availableWidth:t,elements:n,...r}):i&&Object.assign(n.floating.style,{maxWidth:`${t}px`,maxHeight:`${e}px`})}}}:y,S=Wn(),C=s||S,w=a({name:h||`Combobox`,classes:_n,props:t,classNames:n,styles:r,unstyled:i,attributes:_,vars:c,varsResolver:Kn}),T=()=>{d?.(),C.closeDropdown()};return(0,H.jsx)(xn,{value:{getStyles:w,store:C,onOptionSubmit:l,size:f,resetSelectionOnOptionHover:m,readOnly:g,floatingHeight:v},children:(0,H.jsx)(et,{opened:C.dropdownOpened,...b,middlewares:x,onChange:e=>!e&&T(),withRoles:!1,unstyled:i,children:o})})};qn.extend=e=>e,qn.classes=_n,qn.varsResolver=Kn,qn.displayName=`@mantine/core/Combobox`,qn.Target=Bn,qn.Dropdown=wn,qn.Options=In,qn.Option=Fn,qn.Search=Rn,qn.Empty=Dn,qn.Chevron=bn,qn.Footer=jn,qn.Header=Nn,qn.EventsTarget=An,qn.DropdownTarget=En,qn.Group=Mn,qn.ClearButton=Cn,qn.HiddenInput=Pn;function Jn({children:e,role:t}){let n=(0,V.use)(D);return n?(0,H.jsx)(`div`,{role:t,"aria-labelledby":n.labelId,"aria-describedby":n.describedBy,children:e}):(0,H.jsx)(H.Fragment,{children:e})}var Yn={root:`m_5f75b09e`,body:`m_5f6e695e`,labelWrapper:`m_d3ea56bb`,label:`m_8ee546b8`,description:`m_328f68c0`,error:`m_8e8a99cc`},Xn=Yn;function Zn({__staticSelector:e,__stylesApiProps:t,className:n,classNames:r,styles:i,unstyled:s,children:c,label:l,description:u,id:d,disabled:f,error:p,size:m,labelPosition:h=`left`,bodyElement:g=`div`,labelElement:_=`label`,variant:v,style:y,vars:b,mod:x,attributes:S,...C}){let w=a({name:e,props:t,className:n,style:y,classes:Yn,classNames:r,styles:i,unstyled:s,attributes:S}),T=u?`${d}-description`:void 0,E=p&&typeof p!=`boolean`?`${d}-error`:void 0;return(0,H.jsx)(o,{...w(`root`),__vars:{"--label-fz":L(m),"--label-lh":M(m,`label-lh`)},mod:[{"label-position":h},x],variant:v,size:m,...C,children:(0,H.jsxs)(o,{component:g,htmlFor:g===`label`?d:void 0,...w(`body`),children:[c,(0,H.jsxs)(`div`,{...w(`labelWrapper`),"data-disabled":f||void 0,children:[l&&(0,H.jsx)(o,{component:_,htmlFor:_===`label`?d:void 0,...w(`label`),"data-disabled":f||void 0,children:l}),u&&(0,H.jsx)(k.Description,{id:T,size:m,__inheritStyles:!1,...w(`description`),children:u}),p&&typeof p!=`boolean`&&(0,H.jsx)(k.Error,{id:E,size:m,__inheritStyles:!1,...w(`error`),children:p})]})]})})}Zn.displayName=`@mantine/core/InlineInput`;function Qn(e){return`group`in e}function $n({options:e,search:t,limit:n}){let r=t.trim().toLowerCase(),i=[];for(let a=0;a0)return!1;return!0}function tr(e,t=new Set){if(Array.isArray(e))for(let n of e)if(Qn(n))tr(n.items,t);else{if(n.value===void 0)throw Error(`[@mantine/core] Each option must have value property`);if(t.has(n.value))throw Error(`[@mantine/core] Duplicate options are not supported. Option with value "${n.value}" was provided more than once`);t.add(n.value)}}function nr(e,t){return Array.isArray(e)?e.includes(t):e===t}function rr({data:e,withCheckIcon:t,withAlignedLabels:n,value:r,checkIconPosition:i,unstyled:a,renderOption:o}){if(!Qn(e)){let s=nr(r,e.value),c=t&&(s?(0,H.jsx)(Ct,{className:_n.optionsDropdownCheckIcon}):n?(0,H.jsx)(`div`,{className:_n.optionsDropdownCheckPlaceholder}):null),l=(0,H.jsxs)(H.Fragment,{children:[i===`left`&&c,(0,H.jsx)(`span`,{children:e.label}),i===`right`&&c]});return(0,H.jsx)(qn.Option,{value:e.value,disabled:e.disabled,className:_({[_n.optionsDropdownOption]:!a}),"data-reverse":i===`right`||void 0,"data-checked":s||void 0,"aria-selected":s,active:s,children:typeof o==`function`?o({option:e,checked:s}):l})}let s=e.items.map(e=>(0,H.jsx)(rr,{data:e,value:r,unstyled:a,withCheckIcon:t,withAlignedLabels:n,checkIconPosition:i,renderOption:o},`${e.value}`));return(0,H.jsx)(qn.Group,{label:e.group,children:s})}function ir({data:e,hidden:t,hiddenWhenEmpty:n,filter:r,search:i,limit:a,maxDropdownHeight:o,floatingHeight:s,withScrollArea:c=!0,filterOptions:l=!0,withCheckIcon:u=!1,withAlignedLabels:d=!1,value:f,checkIconPosition:p,nothingFoundMessage:m,unstyled:h,labelId:g,renderOption:_,scrollAreaProps:v,"aria-label":y}){let b=Sn();tr(e);let x=typeof i==`string`?(r||$n)({options:e,search:l?i:``,limit:a??1/0}):e,S=er(x),C=x.map((e,t)=>(0,H.jsx)(rr,{data:e,withCheckIcon:u,withAlignedLabels:d,value:f,checkIconPosition:p,unstyled:h,renderOption:_},Qn(e)?`group-${typeof e.group==`string`?e.group:t}`:`${e.value}`));return(0,H.jsx)(qn.Dropdown,{hidden:t||n&&S,"data-composed":!0,children:(0,H.jsxs)(qn.Options,{labelledBy:g,"aria-label":y,children:[c?(0,H.jsx)(fe.Autosize,{mah:(s??b.floatingHeight)===`viewport`?`var(--combobox-floating-options-max-height)`:o??220,type:`scroll`,scrollbarSize:`var(--combobox-padding)`,offsetScrollbars:`y`,...v,children:C}):C,S&&m&&(0,H.jsx)(qn.Empty,{children:m})]})})}function ar(e,t,n,r){if(t===n||r===`before`&&n===t+1||r===`after`&&n===t-1)return e;let i=e.slice(),[a]=i.splice(t,1),o=t{let t=e.lastElementChild;return t?t instanceof HTMLInputElement?t:t.querySelector(`input`):null},sr=(e,t)=>{if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n{let e=i.current;e&&(i.current=null,sr(o.current,e.expectedValue)&&e.container?.querySelector(`[data-mantine-pill-index="${e.index}"]`)?.focus())});let s=(0,V.useCallback)(e=>{a.current=e},[]);return{getPillProps:e=>{if(n)return{draggable:!0,tabIndex:-1,"data-mantine-pill-index":e,"aria-keyshortcuts":`Alt+ArrowLeft Alt+ArrowRight`,onMouseDown:e=>{e.button===0&&e.stopPropagation()},onDragStart:t=>{t.stopPropagation(),t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,String(e)),r.current.draggedIndex=e;let n=t.currentTarget,i=n.getBoundingClientRect(),a=n.cloneNode(!0);a.removeAttribute(`data-dragging`),a.removeAttribute(`data-drag-over`),a.style.position=`fixed`,a.style.top=`-9999px`,a.style.left=`-9999px`,a.style.width=`${i.width}px`,a.style.height=`${i.height}px`,a.style.pointerEvents=`none`,document.body.appendChild(a),t.dataTransfer.setDragImage(a,t.clientX-i.left,t.clientY-i.top),setTimeout(()=>a.parentNode?.removeChild(a),0),requestAnimationFrame(()=>{n.setAttribute(`data-dragging`,`true`)})},onDragOver:t=>{let{draggedIndex:n}=r.current;if(n===null||n===e)return;let i=t.currentTarget,a=i.getBoundingClientRect(),o=t.clientX-a.left,s=(getComputedStyle(i).direction===`rtl`?o>a.width/2:o{let t=e.currentTarget,n=e.relatedTarget;n&&t.contains(n)||(t.removeAttribute(`data-drag-over`),r.current.currentDropTarget===t&&(r.current.currentDropTarget=null))},onDrop:n=>{n.preventDefault(),n.stopPropagation();let i=n.currentTarget,a=i.getAttribute(`data-drag-over`);i.removeAttribute(`data-drag-over`);let{draggedIndex:s}=r.current;if(s!==null&&a&&s!==e){let n=ar(o.current,s,e,a);n!==o.current&&t(n)}r.current.draggedIndex=null,r.current.currentDropTarget=null},onDragEnd:e=>{e.currentTarget.removeAttribute(`data-dragging`);let t=r.current.currentDropTarget;t&&t.removeAttribute(`data-drag-over`),r.current.draggedIndex=null,r.current.currentDropTarget=null},onKeyDown:n=>{if(n.key!==`ArrowLeft`&&n.key!==`ArrowRight`)return;let r=n.currentTarget,a=getComputedStyle(r).direction===`rtl`?n.key===`ArrowLeft`:n.key===`ArrowRight`,s=a?e+1:e-1;if(n.altKey){if(s<0||s>=o.current.length)return;n.preventDefault(),n.stopPropagation();let c=a?`after`:`before`,l=ar(o.current,e,s,c);if(l===o.current)return;i.current={container:r.parentElement,index:s,expectedValue:l},t(l);return}if(s<0)return;let c=r.parentElement;if(c){if(n.preventDefault(),n.stopPropagation(),s>=o.current.length){or(c)?.focus();return}c.querySelector(`[data-mantine-pill-index="${s}"]`)?.focus()}}}},getListProps:()=>n?{ref:s}:{},handleInputKeyDown:e=>{if(!n||e.key!==`ArrowLeft`)return;let t=e.currentTarget;if(!(t.value.length===0||t.selectionStart===0&&t.selectionEnd===0))return;let r=a.current;if(!r)return;let i=r.querySelectorAll(`[data-mantine-pill-index]`);i.length!==0&&(e.preventDefault(),i[i.length-1].focus())}}}function lr({id:e,label:t,labelProps:n,inputWrapperOrder:r}){if(t&&(!r||r.includes(`label`)))return n?.id||`${e}-label`}function ur(e){let t=e.currentTarget;return Yt(t).activeElement!==t}var dr=(0,V.createContext)(null),fr={root:`m_7cda1cd6`,"root--default":`m_44da308b`,"root--contrast":`m_e3a01f8`,label:`m_1e0e6180`,remove:`m_ae386778`,group:`m_1dcfd90b`},pr=(0,V.createContext)(null),mr=g((e,{gap:t},{size:n})=>({group:{"--pg-gap":t===void 0?M(n,`pg-gap`):M(t)}})),hr=h(e=>{let t=u(`PillGroup`,null,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,size:d,disabled:f,attributes:p,...m}=t,h=(0,V.use)(dr)?.size||d||void 0,g=a({name:`PillGroup`,classes:fr,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:p,vars:l,varsResolver:mr,stylesCtx:{size:h},rootSelector:`group`});return(0,H.jsx)(pr,{value:{size:h,disabled:f},children:(0,H.jsx)(o,{size:h,...g(`group`),...m})})});hr.classes=fr,hr.varsResolver=mr,hr.displayName=`@mantine/core/PillGroup`;var gr={variant:`default`},_r=g((e,{radius:t},{size:n})=>({root:{"--pill-fz":M(n,`pill-fz`),"--pill-height":M(n,`pill-height`),"--pill-radius":t===void 0?void 0:re(t)}})),vr=h(e=>{let t=u(`Pill`,gr,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,variant:d,children:f,withRemoveButton:p,onRemove:m,removeButtonProps:h,radius:g,size:_,disabled:v,mod:y,attributes:b,...x}=t,S=(0,V.use)(pr),C=(0,V.use)(dr),w=_||S?.size||void 0,T=C?.variant===`filled`?`contrast`:d||`default`,E=a({name:`Pill`,classes:fr,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:b,vars:l,varsResolver:_r,stylesCtx:{size:w}});return(0,H.jsxs)(o,{component:`span`,variant:T,size:w,...E(`root`,{variant:T}),mod:[{"with-remove":p&&!v,disabled:v||S?.disabled},y],...x,children:[(0,H.jsx)(`span`,{...E(`label`),children:f}),p&&(0,H.jsx)(oe,{variant:`transparent`,radius:g,tabIndex:-1,"aria-hidden":!0,unstyled:c,...h,...E(`remove`,{className:h?.className,style:h?.style}),onMouseDown:e=>{e.preventDefault(),e.stopPropagation(),h?.onMouseDown?.(e)},onClick:e=>{e.stopPropagation(),m?.(),h?.onClick?.(e)}})]})});vr.classes=fr,vr.varsResolver=_r,vr.displayName=`@mantine/core/Pill`,vr.Group=hr;var yr={field:`m_45c4369d`},br={type:`visible`},xr=h(e=>{let t=u(`PillsInputField`,br,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,type:d,disabled:f,id:p,pointer:m,mod:h,attributes:g,ref:_,...v}=t,y=(0,V.use)(dr),b=(0,V.use)(D),x=a({name:`PillsInputField`,classes:yr,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:g,rootSelector:`field`}),S=f||y?.disabled;return(0,H.jsx)(o,{component:`input`,ref:ie(_,y?.fieldRef),"data-type":d,disabled:S,mod:[{disabled:S,pointer:m},h],...x(`field`),...v,id:b?.inputId||p,"aria-invalid":y?.hasError,"aria-describedby":b?.describedBy,type:`text`,onMouseDown:e=>!m&&e.stopPropagation()})});xr.classes=yr,xr.displayName=`@mantine/core/PillsInputField`;var Sr={size:`sm`},Cr=h(e=>{let{children:t,onMouseDown:n,onClick:r,size:i,disabled:a,__staticSelector:o,error:s,variant:c,...l}=u([`Input`,`InputWrapper`,`PillsInput`],Sr,e),d=(0,V.useRef)(null);return(0,H.jsx)(dr,{value:{fieldRef:d,size:i,disabled:a,hasError:!!s,variant:c},children:(0,H.jsx)(N,{size:i,error:s,variant:c,component:`div`,"data-no-overflow":!0,onMouseDown:e=>{e.preventDefault(),n?.(e),d.current?.focus()},onClick:e=>{e.preventDefault(),e.currentTarget.closest(`fieldset`)?.disabled||(d.current?.focus(),r?.(e))},...l,multiline:!0,disabled:a,__staticSelector:o||`PillsInput`,withAria:!1,children:t})})});Cr.displayName=`@mantine/core/PillsInput`,Cr.classes=N.classes,Cr.Field=xr;function wr(e,t){let n=t.trim().toLowerCase();if(n===``)return;let r=Object.values(e).filter(e=>!e.disabled&&e.label.trim().toLowerCase()===n);return r.length===1?r[0]:void 0}function Tr(e){return typeof e==`string`?e.trim().toLowerCase():e}function Er({data:e,value:t}){let n=t.map(Tr);return e.reduce((e,t)=>(Qn(t)?e.push({group:t.group,items:t.items.filter(e=>n.indexOf(Tr(e.value))===-1)}):n.indexOf(Tr(t.value))===-1&&e.push(t),e),[])}var Dr={xs:41,sm:50,md:60,lg:72,xl:89},Or={maxValues:1/0,withCheckIcon:!0,checkIconPosition:`left`,hiddenInputValuesDivider:`,`,clearSearchOnChange:!0,openOnFocus:!0,size:`sm`},kr=c(e=>{let t=u([`Input`,`InputWrapper`,`MultiSelect`],Or,e),{classNames:n,className:r,style:i,styles:o,unstyled:s,vars:c,size:l,value:f,defaultValue:p,onChange:m,onKeyDown:h,variant:g,data:_,dropdownOpened:v,defaultDropdownOpened:y,onDropdownOpen:b,onDropdownClose:x,selectFirstOptionOnChange:S,selectFirstOptionOnDropdownOpen:C,onOptionSubmit:w,comboboxProps:T,filter:E,limit:D,withScrollArea:O,maxDropdownHeight:k,floatingHeight:j,searchValue:M,defaultSearchValue:N,onSearchChange:P,readOnly:I,disabled:L,onFocus:ee,onBlur:te,radius:ne,rightSection:re,rightSectionWidth:ie,rightSectionPointerEvents:ae,rightSectionProps:R,leftSection:oe,leftSectionWidth:z,leftSectionPointerEvents:se,leftSectionProps:ce,inputContainer:le,inputWrapperOrder:ue,withAsterisk:de,labelProps:fe,descriptionProps:pe,errorProps:me,successProps:he,wrapperProps:ge,description:_e,label:ve,error:B,success:ye,maxValues:be,searchable:xe,nothingFoundMessage:Se,withCheckIcon:Ce,withAlignedLabels:we,checkIconPosition:Te,hidePickedOptions:Ee,withErrorStyles:De,withSuccessStyles:Oe,name:ke,form:Ae,id:je,clearable:Me,clearSectionMode:Ne,clearButtonProps:Pe,hiddenInputProps:Fe,placeholder:Ie,hiddenInputValuesDivider:Le,required:Re,mod:ze,renderOption:Be,renderPill:Ve,onRemove:He,onClear:Ue,onMaxValues:We,scrollAreaProps:Ge,chevronColor:Ke,attributes:qe,clearSearchOnChange:Je,openOnFocus:Ye,loading:Xe,loadingPosition:Ze,withPillsReorder:Qe,...$e}=t,et=F(je),tt=lr({id:et,label:ve,labelProps:fe,inputWrapperOrder:ue}),nt=hn(_),rt=gn(nt),it=(0,V.useRef)({}),at=Wn({opened:v,defaultOpened:y,onDropdownOpen:()=>{b?.(),C&&at.selectFirstOption()},onDropdownClose:()=>{x?.(),at.resetSelectedOption()}}),{styleProps:ot,rest:{type:st,autoComplete:ct,...lt}}=d($e),[ut,dt]=kt({value:f,defaultValue:p,finalValue:[],onChange:m}),{getPillProps:ft,getListProps:pt,handleInputKeyDown:mt}=cr({value:ut,onChange:dt,enabled:Qe&&!L&&!I}),[ht,gt]=kt({value:M,defaultValue:N,finalValue:``,onChange:P}),_t=e=>{gt(e),at.resetSelectedOption()},vt=a({name:`MultiSelect`,classes:{},props:t,classNames:n,styles:o,unstyled:s,attributes:qe}),{resolvedClassNames:yt,resolvedStyles:bt}=A({props:t,styles:o,classNames:n}),xt=e=>{h?.(e),!e.defaultPrevented&&(e.key===` `&&!xe&&(e.preventDefault(),at.toggleDropdown()),e.key===`Backspace`&&ht.length===0&&ut.length>0&&!I&&(He?.(ut[ut.length-1]),dt(ut.slice(0,ut.length-1))),mt(e))},St=ut.map((e,t)=>{let n=rt[`${e}`]||it.current[`${e}`],r=ft(t);return Ve?(0,H.jsx)(V.Fragment,{children:Ve({option:n,value:e,onRemove:()=>{dt(ut.filter(t=>e!==t)),He?.(e)},disabled:L,reorderProps:r})},`${e}-${t}`):(0,H.jsx)(vr,{withRemoveButton:!I&&!rt[`${e}`]?.disabled,onRemove:()=>{dt(ut.filter(t=>e!==t)),He?.(e)},unstyled:s,disabled:L,...vt(`pill`),...r,children:n?.label||e},`${e}-${t}`)});(0,V.useEffect)(()=>{S&&at.selectFirstOption()},[S,ht]),(0,V.useEffect)(()=>{ut.forEach(e=>{`${e}`in rt&&(it.current[`${e}`]=rt[`${e}`])})},[rt,ut]);let Ct=(0,H.jsx)(qn.ClearButton,{...Pe,onClear:()=>{Ue?.(),dt([]),_t(``)}}),wt=Er({data:nt,value:ut}),Tt=Me&&ut.length>0&&!L&&!I,Et=Tt?{paddingInlineEnd:Dr[l]??Dr.sm}:void 0;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(qn,{store:at,classNames:yt,styles:bt,unstyled:s,size:l,readOnly:I,__staticSelector:`MultiSelect`,attributes:qe,floatingHeight:j,onOptionSubmit:e=>{w?.(e),Je&&_t(``),at.updateSelectedOptionIndex(`selected`),ut.includes(rt[`${e}`].value)?(dt(ut.filter(t=>t!==rt[`${e}`].value)),He?.(rt[`${e}`].value)):ut.lengthxe?at.openDropdown():at.toggleDropdown(),"data-expanded":at.dropdownOpened||void 0,id:et,required:Re,mod:ze,attributes:qe,children:(0,H.jsxs)(vr.Group,{attributes:qe,disabled:L,unstyled:s,...vt(`pillsList`,{style:Et}),...pt(),children:[St,(0,H.jsx)(qn.EventsTarget,{autoComplete:ct,withExpandedAttribute:!0,children:(0,H.jsx)(Cr.Field,{...lt,id:et,placeholder:Ie,type:!xe&&!Ie?`hidden`:`visible`,...vt(`inputField`),unstyled:s,onFocus:e=>{ee?.(e),Ye&&xe&&at.openDropdown()},onBlur:e=>{te?.(e),at.closeDropdown(),_t(``)},onKeyDown:xt,value:ht,onChange:e=>{if(ur(e)){if(!I){let t=wr(rt,e.currentTarget.value);t&&!ut.includes(t.value)&&ut.length{let{classNames:t,className:n,style:r,styles:i,vars:a,...s}=u(`ProgressLabel`,null,e),c=jr();return(0,H.jsx)(o,{...c.getStyles(`label`,{className:n,style:r,classNames:t,styles:i}),...s})});Nr.classes=Mr,Nr.displayName=`@mantine/core/ProgressLabel`;var Pr=g((e,{size:t,radius:n,transitionDuration:r})=>({root:{"--progress-size":M(t,`progress-size`),"--progress-radius":n===void 0?void 0:re(n),"--progress-transition-duration":typeof r==`number`?`${r}ms`:void 0}})),Fr=h(e=>{let t=u(`ProgressRoot`,null,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,autoContrast:d,transitionDuration:f,orientation:p,attributes:m,mod:h,...g}=t,_=a({name:`Progress`,classes:Mr,props:t,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:m,vars:l,varsResolver:Pr});return(0,H.jsx)(Ar,{value:{getStyles:_,autoContrast:d},children:(0,H.jsx)(o,{mod:[{orientation:p},h],..._(`root`),...g})})});Fr.classes=Mr,Fr.varsResolver=Pr,Fr.displayName=`@mantine/core/ProgressRoot`;var Ir={withAria:!0},Lr=h(e=>{let{classNames:t,className:n,style:r,styles:i,vars:a,value:s,withAria:c,color:d,striped:p,animated:m,mod:h,...g}=u(`ProgressSection`,Ir,e),_=jr(),v=f(),y=c?{role:`progressbar`,"aria-valuemax":100,"aria-valuemin":0,"aria-valuenow":s,"aria-valuetext":`${s}%`}:{};return(0,H.jsx)(o,{..._.getStyles(`section`,{className:n,classNames:t,styles:i,style:r}),...g,...y,mod:[{striped:p||m,animated:m},h],__vars:{"--progress-section-size":`${s}%`,"--progress-section-color":l(d,v),"--progress-label-color":Xt(_.autoContrast,v)?ut({color:d,theme:v,autoContrast:_.autoContrast}):void 0}})});Lr.classes=Mr,Lr.displayName=`@mantine/core/ProgressSection`;var Rr=h(e=>{let t=u(`Progress`,null,e),{value:n,classNames:r,styles:i,vars:a,color:o,striped:s,animated:c,"aria-label":l,...d}=t,{resolvedClassNames:f,resolvedStyles:p}=A({classNames:r,styles:i,props:t});return(0,H.jsx)(Fr,{classNames:f,styles:p,vars:a,...d,children:(0,H.jsx)(Lr,{value:n,color:o,striped:s,animated:c,"aria-label":l})})});Rr.classes=Mr,Rr.displayName=`@mantine/core/Progress`,Rr.Section=Lr,Rr.Root=Fr,Rr.Label=Nr;var zr={root:`m_cf365364`,indicator:`m_9e182ccd`,label:`m_1738fcb2`,input:`m_1714d588`,control:`m_69686b9b`,innerLabel:`m_78882f40`},Br={withItemsBorders:!0},Vr=g((e,{radius:t,color:n,transitionDuration:r,size:i,transitionTimingFunction:a})=>({root:{"--sc-radius":t===void 0?void 0:re(t),"--sc-color":n?l(n,e):void 0,"--sc-shadow":n?void 0:`var(--mantine-shadow-xs)`,"--sc-transition-duration":r===void 0?void 0:`${r}ms`,"--sc-transition-timing-function":a,"--sc-padding":M(i,`sc-padding`),"--sc-font-size":L(i)}})),Hr=c(e=>{let t=u(`SegmentedControl`,Br,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,data:d,value:p,defaultValue:m,onChange:h,size:g,name:_,disabled:v,readOnly:y,fullWidth:b,orientation:x,radius:S,color:C,transitionDuration:w,transitionTimingFunction:T,variant:E,autoContrast:D,withItemsBorders:O,mod:k,attributes:A,ref:j,...M}=t,N=a({name:`SegmentedControl`,props:t,classes:zr,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:A,vars:l,varsResolver:Vr}),P=f(),I=d.map(e=>Kt(e)?{label:`${e}`,value:e}:e),L=Gt(),[ee,te]=(0,V.useState)(0),[ne,re]=(0,V.useState)(null),[ae,R]=(0,V.useState)({}),oe=(e,t)=>{e!==null&&ae[t]!==e&&(ae[t]=e,R({...ae}))},[z,se]=kt({value:p,defaultValue:m,finalValue:Array.isArray(d)?I.find(e=>!e.disabled)?.value??d[0]?.value??null:null,onChange:h}),ce=F(_),le=I.map(e=>`${e.value}`),ue=I.map(e=>(0,V.createElement)(o,{...N(`control`),mod:{active:z===e.value,orientation:x},key:`${e.value}`},(0,V.createElement)(`input`,{...N(`input`),disabled:v||e.disabled,type:`radio`,name:ce,value:`${e.value}`,id:`${ce}-${e.value}`,checked:z===e.value,onChange:()=>!y&&se(e.value),"data-focus-ring":P.focusRing,key:`${e.value}-input`}),(0,V.createElement)(o,{component:`label`,...N(`label`),mod:{active:z===e.value&&!(v||e.disabled),disabled:v||e.disabled,"read-only":y},htmlFor:`${ce}-${e.value}`,ref:t=>oe(t,`${e.value}`),__vars:{"--sc-label-color":C===void 0?void 0:ut({color:C,theme:P,autoContrast:D})},key:`${e.value}-label`},(0,H.jsx)(`span`,{...N(`innerLabel`),children:e.label})))),de=ie(j,re);return Vt(()=>{te(e=>e+1)},[d.length]),Vt(()=>{R(e=>{let t={};return le.forEach(n=>{n in e&&(t[n]=e[n])}),Object.keys(t).length===Object.keys(e).length?e:t})},[le]),d.length===0?null:(0,H.jsxs)(o,{...N(`root`),variant:E,size:g,ref:de,mod:[{"full-width":b,orientation:x,initialized:L,"with-items-borders":O},k],...M,role:`radiogroup`,"data-disabled":v,children:[z!==void 0&&(0,H.jsx)(tn,{target:ae[`${z}`],parent:ne,component:`span`,transitionDuration:`var(--sc-transition-duration)`,...N(`indicator`)},ee),ue]})});Hr.classes=zr,Hr.varsResolver=Vr,Hr.displayName=`@mantine/core/SegmentedControl`;var Ur={size:`sm`,withCheckIcon:!0,allowDeselect:!0,checkIconPosition:`left`,openOnFocus:!0},Wr=c(e=>{let t=u([`Input`,`InputWrapper`,`Select`],Ur,e),{classNames:n,styles:r,unstyled:i,vars:a,dropdownOpened:o,defaultDropdownOpened:s,onDropdownClose:c,onDropdownOpen:l,onFocus:d,onBlur:f,onClick:p,onChange:m,data:h,value:g,defaultValue:_,selectFirstOptionOnChange:v,selectFirstOptionOnDropdownOpen:y,onOptionSubmit:b,comboboxProps:x,readOnly:S,disabled:C,filter:w,limit:T,withScrollArea:E,maxDropdownHeight:D,floatingHeight:O,size:k,searchable:j,rightSection:M,checkIconPosition:P,withCheckIcon:I,withAlignedLabels:L,nothingFoundMessage:ee,name:te,form:ne,searchValue:re,defaultSearchValue:ie,onSearchChange:ae,allowDeselect:R,error:oe,rightSectionPointerEvents:z,id:se,clearable:ce,clearSectionMode:le,clearButtonProps:ue,hiddenInputProps:de,renderOption:fe,onClear:pe,autoComplete:me,scrollAreaProps:he,__defaultRightSection:ge,__clearSection:_e,__clearable:ve,chevronColor:B,autoSelectOnBlur:ye,openOnFocus:be,attributes:xe,...Se}=t,Ce=(0,V.useMemo)(()=>hn(h),[h]),we=(0,V.useRef)({}),Te=(0,V.useMemo)(()=>gn(Ce),[Ce]),Ee=F(se),De=lr({id:Ee,label:Se.label,labelProps:Se.labelProps,inputWrapperOrder:Se.inputWrapperOrder}),[Oe,ke,Ae]=kt({value:g,defaultValue:_,finalValue:null,onChange:m}),je=Oe==null?void 0:`${Oe}`in Te?Te[`${Oe}`]:we.current[`${Oe}`],Me=Ut(je),[Ne,Pe,Fe]=kt({value:re,defaultValue:ie,finalValue:je?je.label:``,onChange:ae}),Ie=Wn({opened:o,defaultOpened:s,onDropdownOpen:()=>{l?.(),y?Ie.selectFirstOption():Ie.updateSelectedOptionIndex(`active`,{scrollIntoView:!0})},onDropdownClose:()=>{c?.(),setTimeout(Ie.resetSelectedOption,0)}}),Le=e=>{Pe(e),Ie.resetSelectedOption()},{resolvedClassNames:Re,resolvedStyles:ze}=A({props:t,styles:r,classNames:n});(0,V.useEffect)(()=>{v&&Ie.selectFirstOption()},[v,Ne]),(0,V.useEffect)(()=>{g===null&&Le(``),g!=null&&je&&(Me?.value!==je.value||Me?.label!==je.label)&&Le(je.label)},[g,je]),(0,V.useEffect)(()=>{!Ae&&!Fe&&Le(Oe==null?``:`${Oe}`in Te?Te[`${Oe}`]?.label:we.current[`${Oe}`]?.label||``)},[Te,Oe]),(0,V.useEffect)(()=>{Oe&&`${Oe}`in Te&&(we.current[`${Oe}`]=Te[`${Oe}`])},[Te,Oe]);let Be=(0,H.jsx)(qn.ClearButton,{...ue,onClear:()=>{ke(null,null),Le(``),pe?.()}}),Ve=ce&&Oe!=null&&!C&&!S;return(0,H.jsxs)(H.Fragment,{children:[(0,H.jsxs)(qn,{store:Ie,__staticSelector:`Select`,classNames:Re,styles:ze,unstyled:i,readOnly:S,size:k,attributes:xe,floatingHeight:O,keepMounted:ye,onOptionSubmit:e=>{b?.(e);let t=R&&`${Te[e].value}`==`${Oe}`?null:Te[e],n=t?t.value:null;n!==Oe&&ke(n,t),!Ae&&Le(n==null?``:t?.label||``),Ie.closeDropdown()},...x,children:[(0,H.jsx)(qn.Target,{targetType:j?`input`:`button`,autoComplete:me,withExpandedAttribute:!0,children:(0,H.jsx)(N,{id:Ee,__defaultRightSection:(0,H.jsx)(qn.Chevron,{size:k,error:oe,unstyled:i,color:B}),__clearSection:Be,__clearable:Ve,__clearSectionMode:le,rightSection:M,rightSectionPointerEvents:z||`none`,...Se,size:k,__staticSelector:`Select`,disabled:C,readOnly:S||!j,value:Ne,onChange:e=>{if(ur(e)){if(!S){let t=wr(Te,e.currentTarget.value);t&&`${t.value}`!=`${Oe}`&&(ke(t.value,t),!Ae&&Le(t.label))}return}Le(e.currentTarget.value),Ie.openDropdown(),v&&Ie.selectFirstOption()},onFocus:e=>{be&&j&&Ie.openDropdown(),d?.(e)},onBlur:e=>{ye&&Ie.clickSelectedOption(),Ie.closeDropdown();let t=Oe!=null&&(`${Oe}`in Te?Te[`${Oe}`]:we.current[`${Oe}`]);Le(t&&t.label||``),f?.(e)},onClick:e=>{j?Ie.openDropdown():Ie.toggleDropdown(),p?.(e)},classNames:Re,styles:ze,unstyled:i,pointer:!j,error:oe,attributes:xe})}),(0,H.jsx)(ir,{data:Ce,hidden:S||C,filter:w,search:Ne,limit:T,hiddenWhenEmpty:!ee,withScrollArea:E,maxDropdownHeight:D,filterOptions:!!j&&je?.label!==Ne,value:Oe,checkIconPosition:P,withCheckIcon:I,withAlignedLabels:L,nothingFoundMessage:ee,unstyled:i,labelId:De,"aria-label":De?void 0:Se[`aria-label`],renderOption:fe,scrollAreaProps:he})]}),(0,H.jsx)(qn.HiddenInput,{value:Oe,name:te,form:ne,disabled:C,...de})]})});Wr.classes={...N.classes,...qn.classes},Wr.displayName=`@mantine/core/Select`;function Gr(e){if(e!==void 0)return typeof e==`number`?P(e):e}function Kr({spacing:e,verticalSpacing:t,cols:n,minColWidth:r,autoRows:i,selector:a}){let o=f(),s=t===void 0?e:t,c=r!==void 0,l=E({"--sg-spacing-x":R(Lt(e)),"--sg-spacing-y":R(Lt(s)),"--sg-auto-rows":i,...c?{"--sg-min-col-width":Gr(r)}:{"--sg-cols":Lt(n)?.toString()}}),u=O(o.breakpoints).reduce((t,r)=>(t[r]||(t[r]={}),typeof e==`object`&&e[r]!==void 0&&(t[r][`--sg-spacing-x`]=R(e[r])),typeof s==`object`&&s[r]!==void 0&&(t[r][`--sg-spacing-y`]=R(s[r])),!c&&typeof n==`object`&&n[r]!==void 0&&(t[r][`--sg-cols`]=n[r]),t),{}),d=bt(O(u),o.breakpoints).filter(e=>O(u[e.value]).length>0).map(e=>({query:`(min-width: ${o.breakpoints[e.value]})`,styles:u[e.value]}));return(0,H.jsx)(j,{styles:l,media:d,selector:a})}function qr(e){return typeof e==`object`&&e?O(e):[]}function Jr(e){return e.sort((e,t)=>mt(e)-mt(t))}function Yr({spacing:e,verticalSpacing:t,cols:n,minColWidth:r}){return Jr(Array.from(new Set([...qr(e),...qr(t),...r===void 0?qr(n):[]])))}function Xr({spacing:e,verticalSpacing:t,cols:n,minColWidth:r,autoRows:i,selector:a}){let o=t===void 0?e:t,s=r!==void 0,c=E({"--sg-spacing-x":R(Lt(e)),"--sg-spacing-y":R(Lt(o)),"--sg-auto-rows":i,...s?{"--sg-min-col-width":Gr(r)}:{"--sg-cols":Lt(n)?.toString()}}),l=Yr({spacing:e,verticalSpacing:t,cols:n,minColWidth:r}),u=l.reduce((t,r)=>(t[r]||(t[r]={}),typeof e==`object`&&e[r]!==void 0&&(t[r][`--sg-spacing-x`]=R(e[r])),typeof o==`object`&&o[r]!==void 0&&(t[r][`--sg-spacing-y`]=R(o[r])),!s&&typeof n==`object`&&n[r]!==void 0&&(t[r][`--sg-cols`]=n[r]),t),{}),d=l.map(e=>({query:`simple-grid (min-width: ${e})`,styles:u[e]}));return(0,H.jsx)(j,{styles:c,container:d,selector:a})}var Zr={container:`m_925c2d2c`,root:`m_2415a157`},Qr={cols:1,spacing:`md`,type:`media`},$r=h(e=>{let t=u(`SimpleGrid`,Qr,e),{classNames:n,className:r,style:i,styles:c,unstyled:l,vars:d,cols:f,verticalSpacing:p,spacing:m,type:h,minColWidth:g,autoFlow:_,autoRows:v,attributes:y,...b}=t,x=a({name:`SimpleGrid`,classes:Zr,props:t,className:r,style:i,classNames:n,styles:c,unstyled:l,attributes:y,vars:d}),S=s(),C=g===void 0?void 0:_||`auto-fill`;return h===`container`?(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Xr,{...t,selector:`.${S}`}),(0,H.jsx)(`div`,{...x(`container`),children:(0,H.jsx)(o,{...x(`root`,{className:S}),...b,"data-auto-cols":C})})]}):(0,H.jsxs)(H.Fragment,{children:[(0,H.jsx)(Kr,{...t,selector:`.${S}`}),(0,H.jsx)(o,{...x(`root`,{className:S}),...b,"data-auto-cols":C})]})});$r.classes=Zr,$r.displayName=`@mantine/core/SimpleGrid`;var ei=(0,V.createContext)(null),ti={hiddenInputValuesSeparator:`,`},ni=c((e=>{let{value:t,defaultValue:n,onChange:r,size:i,wrapperProps:a,children:o,readOnly:s,name:c,hiddenInputValuesSeparator:l,hiddenInputProps:d,maxSelectedValues:f,disabled:p,...m}=u(`SwitchGroup`,ti,e),[h,g]=kt({value:t,defaultValue:n,finalValue:[],onChange:r}),_=e=>{let t=e.currentTarget.value;if(s)return;let n=h.includes(t);!n&&f&&h.length>=f||g(n?h.filter(e=>e!==t):[...h,t])},v=e=>{if(p)return!0;if(!f)return!1;let t=h.includes(e),n=h.length>=f;return!t&&n},y=h.join(l);return(0,H.jsx)(ei,{value:{value:h,onChange:_,size:i,isDisabled:v},children:(0,H.jsxs)(k.Wrapper,{size:i,...a,...m,labelElement:`div`,__staticSelector:`SwitchGroup`,children:[(0,H.jsx)(Jn,{role:`group`,children:o}),(0,H.jsx)(`input`,{type:`hidden`,name:c,value:y,...d})]})})}));ni.classes=k.Wrapper.classes,ni.displayName=`@mantine/core/SwitchGroup`;var ri={root:`m_5f93f3bb`,input:`m_926b4011`,track:`m_9307d992`,thumb:`m_93039a1d`,trackLabel:`m_8277e082`},ii={labelPosition:`right`,withThumbIndicator:!0},ai=g((e,{radius:t,color:n,size:r})=>({root:{"--switch-radius":t===void 0?void 0:re(t),"--switch-height":M(r,`switch-height`),"--switch-width":M(r,`switch-width`),"--switch-thumb-size":M(r,`switch-thumb-size`),"--switch-label-font-size":M(r,`switch-label-font-size`),"--switch-track-label-padding":M(r,`switch-track-label-padding`),"--switch-color":n?l(n,e):void 0}})),oi=h(e=>{let t=u(`Switch`,ii,e),{classNames:n,className:r,style:i,styles:s,unstyled:c,vars:l,color:f,label:p,offLabel:m,onLabel:h,id:g,size:_,radius:v,wrapperProps:y,thumbIcon:b,checked:x,defaultChecked:S,onChange:C,labelPosition:w,description:T,error:E,disabled:D,variant:O,rootRef:k,mod:A,withThumbIndicator:j,attributes:M,...N}=t,P=(0,V.use)(ei),I=_||P?.size,L=a({name:`Switch`,props:t,classes:ri,className:r,style:i,classNames:n,styles:s,unstyled:c,attributes:M,vars:l,varsResolver:ai}),{styleProps:ee,rest:te}=d(N),ne=F(g),re=[T?`${ne}-description`:void 0,E&&typeof E!=`boolean`?`${ne}-error`:void 0,te[`aria-describedby`]].filter(Boolean).join(` `)||void 0,ie={checked:P?.value.includes(te.value)??x,onChange:e=>{P?.onChange(e),C?.(e)}},ae=D||P?.isDisabled?.(te.value),[R,oe]=kt({value:ie.checked??x,defaultValue:S,finalValue:!1});return(0,H.jsxs)(Zn,{...L(`root`),__staticSelector:`Switch`,__stylesApiProps:t,id:ne,size:I,labelPosition:w,label:p,description:T,error:E,disabled:ae,bodyElement:`label`,labelElement:`span`,classNames:n,styles:s,unstyled:c,"data-checked":ie.checked,variant:O,ref:k,mod:A,attributes:M,inert:te.inert,...ee,...y,children:[(0,H.jsx)(`input`,{...te,...ie,disabled:ae,checked:R,"data-checked":ie.checked,onChange:e=>{ie.onChange?.(e),oe(e.currentTarget.checked)},id:ne,type:`checkbox`,role:`switch`,inert:te.inert,"aria-describedby":re,...L(`input`)}),(0,H.jsxs)(o,{"aria-hidden":`true`,component:`span`,mod:{error:E,"label-position":w,"without-labels":!h&&!m},...L(`track`),children:[(0,H.jsx)(o,{component:`span`,mod:{"reduce-motion":!0,"with-thumb-indicator":j&&!b},...L(`thumb`),children:b}),(0,H.jsx)(`span`,{...L(`trackLabel`),children:R?h:m})]})]})});oi.classes={...ri,...Xn},oi.varsResolver=ai,oi.displayName=`@mantine/core/Switch`,oi.Group=ni;var si=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M244,56v48a12,12,0,0,1-12,12H184a12,12,0,1,1,0-24H201.1l-19-17.38c-.13-.12-.26-.24-.38-.37A76,76,0,1,0,127,204h1a75.53,75.53,0,0,0,52.15-20.72,12,12,0,0,1,16.49,17.45A99.45,99.45,0,0,1,128,228h-1.37A100,100,0,1,1,198.51,57.06L220,76.72V56a12,12,0,0,1,24,0Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1-5.66-13.66l17-17-10.55-9.65-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,1,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60l10.93,10L226.34,50.3A8,8,0,0,1,240,56Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M238,56v48a6,6,0,0,1-6,6H184a6,6,0,0,1,0-12h32.55l-30.38-27.8c-.06-.06-.12-.13-.19-.19a82,82,0,1,0-1.7,117.65,6,6,0,0,1,8.24,8.73A93.46,93.46,0,0,1,128,222h-1.28A94,94,0,1,1,194.37,61.4L226,90.35V56a6,6,0,1,1,12,0Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M240,56v48a8,8,0,0,1-8,8H184a8,8,0,0,1,0-16H211.4L184.81,71.64l-.25-.24a80,80,0,1,0-1.67,114.78,8,8,0,0,1,11,11.63A95.44,95.44,0,0,1,128,224h-1.32A96,96,0,1,1,195.75,60L224,85.8V56a8,8,0,1,1,16,0Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M236,56v48a4,4,0,0,1-4,4H184a4,4,0,0,1,0-8h37.7L187.53,68.69l-.13-.12a84,84,0,1,0-1.75,120.51,4,4,0,0,1,5.5,5.82A91.43,91.43,0,0,1,128,220h-1.26A92,92,0,1,1,193,62.84l35,32.05V56a4,4,0,1,1,8,0Z`}))]]),ci=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M228,128a100,100,0,0,1-98.66,100H128a99.39,99.39,0,0,1-68.62-27.29,12,12,0,0,1,16.48-17.45,76,76,0,1,0-1.57-109c-.13.13-.25.25-.39.37L54.89,92H72a12,12,0,0,1,0,24H24a12,12,0,0,1-12-12V56a12,12,0,0,1,24,0V76.72L57.48,57.06A100,100,0,0,1,228,128Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M224,128a96,96,0,0,1-94.71,96H128A95.38,95.38,0,0,1,62.1,197.8a8,8,0,0,1,11-11.63A80,80,0,1,0,71.43,71.39a3.07,3.07,0,0,1-.26.25L44.59,96H72a8,8,0,0,1,0,16H24a8,8,0,0,1-8-8V56a8,8,0,0,1,16,0V85.8L60.25,60A96,96,0,0,1,224,128Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128a96,96,0,0,1-94.71,96H128A95.38,95.38,0,0,1,62.1,197.8a8,8,0,0,1,11-11.63A80,80,0,1,0,71.43,71.39a3.07,3.07,0,0,1-.26.25L60.63,81.29l17,17A8,8,0,0,1,72,112H24a8,8,0,0,1-8-8V56A8,8,0,0,1,29.66,50.3L49.31,70,60.25,60A96,96,0,0,1,224,128Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M222,128a94,94,0,0,1-92.74,94H128a93.43,93.43,0,0,1-64.5-25.65,6,6,0,1,1,8.24-8.72A82,82,0,1,0,70,70l-.19.19L39.44,98H72a6,6,0,0,1,0,12H24a6,6,0,0,1-6-6V56a6,6,0,0,1,12,0V90.34L61.63,61.4A94,94,0,0,1,222,128Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128a96,96,0,0,1-94.71,96H128A95.38,95.38,0,0,1,62.1,197.8a8,8,0,0,1,11-11.63A80,80,0,1,0,71.43,71.39a3.07,3.07,0,0,1-.26.25L44.59,96H72a8,8,0,0,1,0,16H24a8,8,0,0,1-8-8V56a8,8,0,0,1,16,0V85.8L60.25,60A96,96,0,0,1,224,128Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M220,128a92,92,0,0,1-90.77,92H128a91.47,91.47,0,0,1-63.13-25.1,4,4,0,1,1,5.5-5.82A84,84,0,1,0,68.6,68.57l-.13.12L34.3,100H72a4,4,0,0,1,0,8H24a4,4,0,0,1-4-4V56a4,4,0,0,1,8,0V94.89l35-32A92,92,0,0,1,220,128Z`}))]]),li=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M220,48V96a12,12,0,0,1-24,0V77l-35.51,35.52a12,12,0,0,1-17-17L179,60H160a12,12,0,0,1,0-24h48A12,12,0,0,1,220,48ZM95.51,143.51,60,179V160a12,12,0,0,0-24,0v48a12,12,0,0,0,12,12H96a12,12,0,0,0,0-24H77l35.52-35.51a12,12,0,0,0-17-17ZM208,148a12,12,0,0,0-12,12v19l-35.51-35.52a12,12,0,0,0-17,17L179,196H160a12,12,0,0,0,0,24h48a12,12,0,0,0,12-12V160A12,12,0,0,0,208,148ZM77,60H96a12,12,0,0,0,0-24H48A12,12,0,0,0,36,48V96a12,12,0,0,0,24,0V77l35.51,35.52a12,12,0,0,0,17-17Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M208,48V208H48V48Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M216,48V96a8,8,0,0,1-16,0V67.31l-42.34,42.35a8,8,0,0,1-11.32-11.32L188.69,56H160a8,8,0,0,1,0-16h48A8,8,0,0,1,216,48ZM98.34,146.34,56,188.69V160a8,8,0,0,0-16,0v48a8,8,0,0,0,8,8H96a8,8,0,0,0,0-16H67.31l42.35-42.34a8,8,0,0,0-11.32-11.32ZM208,152a8,8,0,0,0-8,8v28.69l-42.34-42.35a8,8,0,0,0-11.32,11.32L188.69,200H160a8,8,0,0,0,0,16h48a8,8,0,0,0,8-8V160A8,8,0,0,0,208,152ZM67.31,56H96a8,8,0,0,0,0-16H48a8,8,0,0,0-8,8V96a8,8,0,0,0,16,0V67.31l42.34,42.35a8,8,0,0,0,11.32-11.32Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M109.66,146.34a8,8,0,0,1,0,11.32L83.31,184l18.35,18.34A8,8,0,0,1,96,216H48a8,8,0,0,1-8-8V160a8,8,0,0,1,13.66-5.66L72,172.69l26.34-26.35A8,8,0,0,1,109.66,146.34ZM83.31,72l18.35-18.34A8,8,0,0,0,96,40H48a8,8,0,0,0-8,8V96a8,8,0,0,0,13.66,5.66L72,83.31l26.34,26.35a8,8,0,0,0,11.32-11.32ZM208,40H160a8,8,0,0,0-5.66,13.66L172.69,72,146.34,98.34a8,8,0,0,0,11.32,11.32L184,83.31l18.34,18.35A8,8,0,0,0,216,96V48A8,8,0,0,0,208,40Zm3.06,112.61a8,8,0,0,0-8.72,1.73L184,172.69l-26.34-26.35a8,8,0,0,0-11.32,11.32L172.69,184l-18.35,18.34A8,8,0,0,0,160,216h48a8,8,0,0,0,8-8V160A8,8,0,0,0,211.06,152.61Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M214,48V96a6,6,0,0,1-12,0V62.48l-45.76,45.76a6,6,0,0,1-8.48-8.48L193.52,54H160a6,6,0,0,1,0-12h48A6,6,0,0,1,214,48ZM99.76,147.76,54,193.52V160a6,6,0,0,0-12,0v48a6,6,0,0,0,6,6H96a6,6,0,0,0,0-12H62.48l45.76-45.76a6,6,0,0,0-8.48-8.48ZM208,154a6,6,0,0,0-6,6v33.52l-45.76-45.76a6,6,0,0,0-8.48,8.48L193.52,202H160a6,6,0,0,0,0,12h48a6,6,0,0,0,6-6V160A6,6,0,0,0,208,154ZM62.48,54H96a6,6,0,0,0,0-12H48a6,6,0,0,0-6,6V96a6,6,0,0,0,12,0V62.48l45.76,45.76a6,6,0,0,0,8.48-8.48Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,48V96a8,8,0,0,1-16,0V67.31l-42.34,42.35a8,8,0,0,1-11.32-11.32L188.69,56H160a8,8,0,0,1,0-16h48A8,8,0,0,1,216,48ZM98.34,146.34,56,188.69V160a8,8,0,0,0-16,0v48a8,8,0,0,0,8,8H96a8,8,0,0,0,0-16H67.31l42.35-42.34a8,8,0,0,0-11.32-11.32ZM208,152a8,8,0,0,0-8,8v28.69l-42.34-42.35a8,8,0,0,0-11.32,11.32L188.69,200H160a8,8,0,0,0,0,16h48a8,8,0,0,0,8-8V160A8,8,0,0,0,208,152ZM67.31,56H96a8,8,0,0,0,0-16H48a8,8,0,0,0-8,8V96a8,8,0,0,0,16,0V67.31l42.34,42.35a8,8,0,0,0,11.32-11.32Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M212,48V96a4,4,0,0,1-8,0V57.66l-49.17,49.17a4,4,0,0,1-5.66-5.66L198.34,52H160a4,4,0,0,1,0-8h48A4,4,0,0,1,212,48ZM101.17,149.17,52,198.34V160a4,4,0,0,0-8,0v48a4,4,0,0,0,4,4H96a4,4,0,0,0,0-8H57.66l49.17-49.17a4,4,0,0,0-5.66-5.66ZM208,156a4,4,0,0,0-4,4v38.34l-49.17-49.17a4,4,0,0,0-5.66,5.66L198.34,204H160a4,4,0,0,0,0,8h48a4,4,0,0,0,4-4V160A4,4,0,0,0,208,156ZM57.66,52H96a4,4,0,0,0,0-8H48a4,4,0,0,0-4,4V96a4,4,0,0,0,8,0V57.66l49.17,49.17a4,4,0,0,0,5.66-5.66Z`}))]]),ui=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216.49,168.49a12,12,0,0,1-17,0L128,97,56.49,168.49a12,12,0,0,1-17-17l80-80a12,12,0,0,1,17,0l80,80A12,12,0,0,1,216.49,168.49Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M208,160H48l80-80Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M213.66,154.34l-80-80a8,8,0,0,0-11.32,0l-80,80A8,8,0,0,0,48,168H208a8,8,0,0,0,5.66-13.66ZM67.31,152,128,91.31,188.69,152Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M215.39,163.06A8,8,0,0,1,208,168H48a8,8,0,0,1-5.66-13.66l80-80a8,8,0,0,1,11.32,0l80,80A8,8,0,0,1,215.39,163.06Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M212.24,164.24a6,6,0,0,1-8.48,0L128,88.49,52.24,164.24a6,6,0,0,1-8.48-8.48l80-80a6,6,0,0,1,8.48,0l80,80A6,6,0,0,1,212.24,164.24Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M213.66,165.66a8,8,0,0,1-11.32,0L128,91.31,53.66,165.66a8,8,0,0,1-11.32-11.32l80-80a8,8,0,0,1,11.32,0l80,80A8,8,0,0,1,213.66,165.66Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M210.83,162.83a4,4,0,0,1-5.66,0L128,85.66,50.83,162.83a4,4,0,0,1-5.66-5.66l80-80a4,4,0,0,1,5.66,0l80,80A4,4,0,0,1,210.83,162.83Z`}))]]),di=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M172,108a12,12,0,0,1-12,12H96a12,12,0,0,1,0-24h64A12,12,0,0,1,172,108Zm-12,28H96a12,12,0,0,0,0,24h64a12,12,0,0,0,0-24Zm76-8A108,108,0,0,1,78.77,224.15L46.34,235A20,20,0,0,1,21,209.66l10.81-32.43A108,108,0,1,1,236,128Zm-24,0A84,84,0,1,0,55.27,170.06a12,12,0,0,1,1,9.81l-9.93,29.79,29.79-9.93a12.1,12.1,0,0,1,3.8-.62,12,12,0,0,1,6,1.62A84,84,0,0,0,212,128Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128A96,96,0,0,1,79.93,211.11h0L42.54,223.58a8,8,0,0,1-10.12-10.12l12.47-37.39h0A96,96,0,1,1,224,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M128,24A104,104,0,0,0,36.18,176.88L24.83,210.93a16,16,0,0,0,20.24,20.24l34.05-11.35A104,104,0,1,0,128,24Zm0,192a87.87,87.87,0,0,1-44.06-11.81,8,8,0,0,0-4-1.08,7.85,7.85,0,0,0-2.53.42L40,216,52.47,178.6a8,8,0,0,0-.66-6.54A88,88,0,1,1,128,216Zm40-104a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,112Zm0,32a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,144Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,24A104,104,0,0,0,36.18,176.88L24.83,210.93a16,16,0,0,0,20.24,20.24l34.05-11.35A104,104,0,1,0,128,24Zm32,128H96a8,8,0,0,1,0-16h64a8,8,0,0,1,0,16Zm0-32H96a8,8,0,0,1,0-16h64a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M166,112a6,6,0,0,1-6,6H96a6,6,0,0,1,0-12h64A6,6,0,0,1,166,112Zm-6,26H96a6,6,0,0,0,0,12h64a6,6,0,0,0,0-12Zm70-10A102,102,0,0,1,79.31,217.65L44.44,229.27a14,14,0,0,1-17.71-17.71l11.62-34.87A102,102,0,1,1,230,128Zm-12,0A90,90,0,1,0,50.08,173.06a6,6,0,0,1,.5,4.91L38.12,215.35a2,2,0,0,0,2.53,2.53L78,205.42a6.2,6.2,0,0,1,1.9-.31,6.09,6.09,0,0,1,3,.81A90,90,0,0,0,218,128Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M168,112a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,112Zm-8,24H96a8,8,0,0,0,0,16h64a8,8,0,0,0,0-16Zm72-8A104,104,0,0,1,79.12,219.82L45.07,231.17a16,16,0,0,1-20.24-20.24l11.35-34.05A104,104,0,1,1,232,128Zm-16,0A88,88,0,1,0,51.81,172.06a8,8,0,0,1,.66,6.54L40,216,77.4,203.53a7.85,7.85,0,0,1,2.53-.42,8,8,0,0,1,4,1.08A88,88,0,0,0,216,128Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M164,112a4,4,0,0,1-4,4H96a4,4,0,0,1,0-8h64A4,4,0,0,1,164,112Zm-4,28H96a4,4,0,0,0,0,8h64a4,4,0,0,0,0-8Zm68-12A100,100,0,0,1,79.5,215.47l-35.69,11.9a12,12,0,0,1-15.18-15.18l11.9-35.69A100,100,0,1,1,228,128Zm-8,0A92,92,0,1,0,48.35,174.07a4,4,0,0,1,.33,3.27L36.22,214.72a4,4,0,0,0,5.06,5.06l37.38-12.46a3.93,3.93,0,0,1,1.27-.21,4.05,4.05,0,0,1,2,.54A92,92,0,0,0,220,128Z`}))]]),fi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,20A108,108,0,1,0,236,128,108.12,108.12,0,0,0,128,20Zm0,192a84,84,0,1,1,84-84A84.09,84.09,0,0,1,128,212Zm68-84a12,12,0,0,1-12,12H128a12,12,0,0,1-12-12V72a12,12,0,0,1,24,0v44h44A12,12,0,0,1,196,128Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm64-88a8,8,0,0,1-8,8H128a8,8,0,0,1-8-8V72a8,8,0,0,1,16,0v48h48A8,8,0,0,1,192,128Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm56,112H128a8,8,0,0,1-8-8V72a8,8,0,0,1,16,0v48h48a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,26A102,102,0,1,0,230,128,102.12,102.12,0,0,0,128,26Zm0,192a90,90,0,1,1,90-90A90.1,90.1,0,0,1,128,218Zm62-90a6,6,0,0,1-6,6H128a6,6,0,0,1-6-6V72a6,6,0,0,1,12,0v50h50A6,6,0,0,1,190,128Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm64-88a8,8,0,0,1-8,8H128a8,8,0,0,1-8-8V72a8,8,0,0,1,16,0v48h48A8,8,0,0,1,192,128Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,28A100,100,0,1,0,228,128,100.11,100.11,0,0,0,128,28Zm0,192a92,92,0,1,1,92-92A92.1,92.1,0,0,1,128,220Zm60-92a4,4,0,0,1-4,4H128a4,4,0,0,1-4-4V72a4,4,0,0,1,8,0v52h52A4,4,0,0,1,188,128Z`}))]]),pi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M140,80v41.21l34.17,20.5a12,12,0,1,1-12.34,20.58l-40-24A12,12,0,0,1,116,128V80a12,12,0,0,1,24,0ZM128,28A99.38,99.38,0,0,0,57.24,57.34c-4.69,4.74-9,9.37-13.24,14V64a12,12,0,0,0-24,0v40a12,12,0,0,0,12,12H72a12,12,0,0,0,0-24H57.77C63,86,68.37,80.22,74.26,74.26a76,76,0,1,1,1.58,109,12,12,0,0,0-16.48,17.46A100,100,0,1,0,128,28Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,128a88,88,0,1,1-88-88A88,88,0,0,1,216,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M136,80v43.47l36.12,21.67a8,8,0,0,1-8.24,13.72l-40-24A8,8,0,0,1,120,128V80a8,8,0,0,1,16,0Zm-8-48A95.44,95.44,0,0,0,60.08,60.15C52.81,67.51,46.35,74.59,40,82V64a8,8,0,0,0-16,0v40a8,8,0,0,0,8,8H72a8,8,0,0,0,0-16H49c7.15-8.42,14.27-16.35,22.39-24.57a80,80,0,1,1,1.66,114.75,8,8,0,1,0-11,11.64A96,96,0,1,0,128,32Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128A96,96,0,0,1,62.11,197.82a8,8,0,1,1,11-11.64A80,80,0,1,0,71.43,71.43C67.9,75,64.58,78.51,61.35,82L77.66,98.34A8,8,0,0,1,72,112H32a8,8,0,0,1-8-8V64a8,8,0,0,1,13.66-5.66L50,70.7c3.22-3.49,6.54-7,10.06-10.55A96,96,0,0,1,224,128ZM128,72a8,8,0,0,0-8,8v48a8,8,0,0,0,3.88,6.86l40,24a8,8,0,1,0,8.24-13.72L136,123.47V80A8,8,0,0,0,128,72Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M134,80v44.6l37.09,22.25a6,6,0,0,1-6.18,10.3l-40-24A6,6,0,0,1,122,128V80a6,6,0,0,1,12,0Zm-6-46A93.4,93.4,0,0,0,61.51,61.56c-8.58,8.68-16,17-23.51,25.8V64a6,6,0,0,0-12,0v40a6,6,0,0,0,6,6H72a6,6,0,0,0,0-12H44.73C52.86,88.29,60.79,79.35,70,70a82,82,0,1,1,1.7,117.62,6,6,0,1,0-8.24,8.72A94,94,0,1,0,128,34Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M136,80v43.47l36.12,21.67a8,8,0,0,1-8.24,13.72l-40-24A8,8,0,0,1,120,128V80a8,8,0,0,1,16,0Zm-8-48A95.44,95.44,0,0,0,60.08,60.15C52.81,67.51,46.35,74.59,40,82V64a8,8,0,0,0-16,0v40a8,8,0,0,0,8,8H72a8,8,0,0,0,0-16H49c7.15-8.42,14.27-16.35,22.39-24.57a80,80,0,1,1,1.66,114.75,8,8,0,1,0-11,11.64A96,96,0,1,0,128,32Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M132,80v45.74l38.06,22.83a4,4,0,0,1-4.12,6.86l-40-24A4,4,0,0,1,124,128V80a4,4,0,0,1,8,0Zm-4-44A91.42,91.42,0,0,0,62.93,63C53.05,73,44.66,82.47,36,92.86V64a4,4,0,0,0-8,0v40a4,4,0,0,0,4,4H72a4,4,0,0,0,0-8H40.47C49.61,89,58.3,79,68.6,68.6a84,84,0,1,1,1.75,120.49,4,4,0,1,0-5.5,5.82A92,92,0,1,0,128,36Z`}))]]),mi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M108,84a16,16,0,1,1,16,16A16,16,0,0,1,108,84Zm128,44A108,108,0,1,1,128,20,108.12,108.12,0,0,1,236,128Zm-24,0a84,84,0,1,0-84,84A84.09,84.09,0,0,0,212,128Zm-72,36.68V132a20,20,0,0,0-20-20,12,12,0,0,0-4,23.32V168a20,20,0,0,0,20,20,12,12,0,0,0,4-23.32Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,128a96,96,0,1,1-96-96A96,96,0,0,1,224,128Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M144,176a8,8,0,0,1-8,8,16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40A8,8,0,0,1,144,176Zm88-48A104,104,0,1,1,128,24,104.11,104.11,0,0,1,232,128Zm-16,0a88,88,0,1,0-88,88A88.1,88.1,0,0,0,216,128ZM124,96a12,12,0,1,0-12-12A12,12,0,0,0,124,96Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm-4,48a12,12,0,1,1-12,12A12,12,0,0,1,124,72Zm12,112a16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M142,176a6,6,0,0,1-6,6,14,14,0,0,1-14-14V128a2,2,0,0,0-2-2,6,6,0,0,1,0-12,14,14,0,0,1,14,14v40a2,2,0,0,0,2,2A6,6,0,0,1,142,176ZM124,94a10,10,0,1,0-10-10A10,10,0,0,0,124,94Zm106,34A102,102,0,1,1,128,26,102.12,102.12,0,0,1,230,128Zm-12,0a90,90,0,1,0-90,90A90.1,90.1,0,0,0,218,128Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M128,24A104,104,0,1,0,232,128,104.11,104.11,0,0,0,128,24Zm0,192a88,88,0,1,1,88-88A88.1,88.1,0,0,1,128,216Zm16-40a8,8,0,0,1-8,8,16,16,0,0,1-16-16V128a8,8,0,0,1,0-16,16,16,0,0,1,16,16v40A8,8,0,0,1,144,176ZM112,84a12,12,0,1,1,12,12A12,12,0,0,1,112,84Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M140,176a4,4,0,0,1-4,4,12,12,0,0,1-12-12V128a4,4,0,0,0-4-4,4,4,0,0,1,0-8,12,12,0,0,1,12,12v40a4,4,0,0,0,4,4A4,4,0,0,1,140,176ZM124,92a8,8,0,1,0-8-8A8,8,0,0,0,124,92Zm104,36A100,100,0,1,1,128,28,100.11,100.11,0,0,1,228,128Zm-8,0a92,92,0,1,0-92,92A92.1,92.1,0,0,0,220,128Z`}))]]),hi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,44H32A20,20,0,0,0,12,64V192a20,20,0,0,0,20,20H224a20,20,0,0,0,20-20V64A20,20,0,0,0,224,44Zm-4,144H36V68H220ZM52,128a12,12,0,0,1,12-12H192a12,12,0,0,1,0,24H64A12,12,0,0,1,52,128Zm0-36A12,12,0,0,1,64,80H192a12,12,0,0,1,0,24H64A12,12,0,0,1,52,92Zm0,72a12,12,0,0,1,12-12h8a12,12,0,0,1,0,24H64A12,12,0,0,1,52,164Zm108,0a12,12,0,0,1-12,12H108a12,12,0,0,1,0-24h40A12,12,0,0,1,160,164Zm44,0a12,12,0,0,1-12,12h-8a12,12,0,0,1,0-24h8A12,12,0,0,1,204,164Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M232,64V192a8,8,0,0,1-8,8H32a8,8,0,0,1-8-8V64a8,8,0,0,1,8-8H224A8,8,0,0,1,232,64Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M224,48H32A16,16,0,0,0,16,64V192a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V64A16,16,0,0,0,224,48Zm0,144H32V64H224V192Zm-16-64a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16H200A8,8,0,0,1,208,128Zm0-32a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16H200A8,8,0,0,1,208,96ZM72,160a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16h8A8,8,0,0,1,72,160Zm96,0a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,160Zm40,0a8,8,0,0,1-8,8h-8a8,8,0,0,1,0-16h8A8,8,0,0,1,208,160Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,48H32A16,16,0,0,0,16,64V192a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V64A16,16,0,0,0,224,48ZM64,168H48a8,8,0,0,1,0-16H64a8,8,0,0,1,0,16Zm96,0H96a8,8,0,0,1,0-16h64a8,8,0,0,1,0,16Zm48,0H192a8,8,0,0,1,0-16h16a8,8,0,0,1,0,16Zm0-32H48a8,8,0,0,1,0-16H208a8,8,0,0,1,0,16Zm0-32H48a8,8,0,0,1,0-16H208a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,50H32A14,14,0,0,0,18,64V192a14,14,0,0,0,14,14H224a14,14,0,0,0,14-14V64A14,14,0,0,0,224,50Zm2,142a2,2,0,0,1-2,2H32a2,2,0,0,1-2-2V64a2,2,0,0,1,2-2H224a2,2,0,0,1,2,2Zm-20-64a6,6,0,0,1-6,6H56a6,6,0,0,1,0-12H200A6,6,0,0,1,206,128Zm0-32a6,6,0,0,1-6,6H56a6,6,0,0,1,0-12H200A6,6,0,0,1,206,96ZM70,160a6,6,0,0,1-6,6H56a6,6,0,0,1,0-12h8A6,6,0,0,1,70,160Zm96,0a6,6,0,0,1-6,6H96a6,6,0,0,1,0-12h64A6,6,0,0,1,166,160Zm40,0a6,6,0,0,1-6,6h-8a6,6,0,0,1,0-12h8A6,6,0,0,1,206,160Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,48H32A16,16,0,0,0,16,64V192a16,16,0,0,0,16,16H224a16,16,0,0,0,16-16V64A16,16,0,0,0,224,48Zm0,144H32V64H224V192Zm-16-64a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16H200A8,8,0,0,1,208,128Zm0-32a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16H200A8,8,0,0,1,208,96ZM72,160a8,8,0,0,1-8,8H56a8,8,0,0,1,0-16h8A8,8,0,0,1,72,160Zm96,0a8,8,0,0,1-8,8H96a8,8,0,0,1,0-16h64A8,8,0,0,1,168,160Zm40,0a8,8,0,0,1-8,8h-8a8,8,0,0,1,0-16h8A8,8,0,0,1,208,160Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,52H32A12,12,0,0,0,20,64V192a12,12,0,0,0,12,12H224a12,12,0,0,0,12-12V64A12,12,0,0,0,224,52Zm4,140a4,4,0,0,1-4,4H32a4,4,0,0,1-4-4V64a4,4,0,0,1,4-4H224a4,4,0,0,1,4,4Zm-24-64a4,4,0,0,1-4,4H56a4,4,0,0,1,0-8H200A4,4,0,0,1,204,128Zm0-32a4,4,0,0,1-4,4H56a4,4,0,0,1,0-8H200A4,4,0,0,1,204,96ZM68,160a4,4,0,0,1-4,4H56a4,4,0,0,1,0-8h8A4,4,0,0,1,68,160Zm96,0a4,4,0,0,1-4,4H96a4,4,0,0,1,0-8h64A4,4,0,0,1,164,160Zm40,0a4,4,0,0,1-4,4h-8a4,4,0,0,1,0-8h8A4,4,0,0,1,204,160Z`}))]]),gi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M76,64A12,12,0,0,1,88,52H216a12,12,0,0,1,0,24H88A12,12,0,0,1,76,64Zm140,52H88a12,12,0,0,0,0,24H216a12,12,0,0,0,0-24Zm0,64H88a12,12,0,0,0,0,24H216a12,12,0,0,0,0-24ZM44,112a16,16,0,1,0,16,16A16,16,0,0,0,44,112Zm0-64A16,16,0,1,0,60,64,16,16,0,0,0,44,48Zm0,128a16,16,0,1,0,16,16A16,16,0,0,0,44,176Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,64V192H88V64Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M80,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H88A8,8,0,0,1,80,64Zm136,56H88a8,8,0,1,0,0,16H216a8,8,0,0,0,0-16Zm0,64H88a8,8,0,1,0,0,16H216a8,8,0,0,0,0-16ZM44,52A12,12,0,1,0,56,64,12,12,0,0,0,44,52Zm0,64a12,12,0,1,0,12,12A12,12,0,0,0,44,116Zm0,64a12,12,0,1,0,12,12A12,12,0,0,0,44,180Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M208,32H48A16,16,0,0,0,32,48V208a16,16,0,0,0,16,16H208a16,16,0,0,0,16-16V48A16,16,0,0,0,208,32ZM68,188a12,12,0,1,1,12-12A12,12,0,0,1,68,188Zm0-48a12,12,0,1,1,12-12A12,12,0,0,1,68,140Zm0-48A12,12,0,1,1,80,80,12,12,0,0,1,68,92Zm124,92H104a8,8,0,0,1,0-16h88a8,8,0,0,1,0,16Zm0-48H104a8,8,0,0,1,0-16h88a8,8,0,0,1,0,16Zm0-48H104a8,8,0,0,1,0-16h88a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M82,64a6,6,0,0,1,6-6H216a6,6,0,0,1,0,12H88A6,6,0,0,1,82,64Zm134,58H88a6,6,0,0,0,0,12H216a6,6,0,0,0,0-12Zm0,64H88a6,6,0,0,0,0,12H216a6,6,0,0,0,0-12ZM44,54A10,10,0,1,0,54,64,10,10,0,0,0,44,54Zm0,128a10,10,0,1,0,10,10A10,10,0,0,0,44,182Zm0-64a10,10,0,1,0,10,10A10,10,0,0,0,44,118Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M80,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H88A8,8,0,0,1,80,64Zm136,56H88a8,8,0,0,0,0,16H216a8,8,0,0,0,0-16Zm0,64H88a8,8,0,0,0,0,16H216a8,8,0,0,0,0-16ZM44,52A12,12,0,1,0,56,64,12,12,0,0,0,44,52Zm0,64a12,12,0,1,0,12,12A12,12,0,0,0,44,116Zm0,64a12,12,0,1,0,12,12A12,12,0,0,0,44,180Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M84,64a4,4,0,0,1,4-4H216a4,4,0,0,1,0,8H88A4,4,0,0,1,84,64Zm132,60H88a4,4,0,0,0,0,8H216a4,4,0,0,0,0-8Zm0,64H88a4,4,0,0,0,0,8H216a4,4,0,0,0,0-8ZM44,120a8,8,0,1,0,8,8A8,8,0,0,0,44,120Zm0-64a8,8,0,1,0,8,8A8,8,0,0,0,44,56Zm0,128a8,8,0,1,0,8,8A8,8,0,0,0,44,184Z`}))]]),_i=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M28,64A12,12,0,0,1,40,52H216a12,12,0,0,1,0,24H40A12,12,0,0,1,28,64Zm12,76h64a12,12,0,0,0,0-24H40a12,12,0,0,0,0,24Zm80,40H40a12,12,0,0,0,0,24h80a12,12,0,0,0,0-24Zm120.49,20.49a12,12,0,0,1-17,0l-18.08-18.08a44,44,0,1,1,17-17l18.08,18.07A12,12,0,0,1,240.49,200.49ZM184,164a20,20,0,1,0-20-20A20,20,0,0,0,184,164Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M216,144a32,32,0,1,1-32-32A32,32,0,0,1,216,144Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M32,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H40A8,8,0,0,1,32,64Zm8,72h72a8,8,0,0,0,0-16H40a8,8,0,0,0,0,16Zm88,48H40a8,8,0,0,0,0,16h88a8,8,0,0,0,0-16Zm109.66,13.66a8,8,0,0,1-11.32,0L206,177.36A40,40,0,1,1,217.36,166l20.3,20.3A8,8,0,0,1,237.66,197.66ZM184,168a24,24,0,1,0-24-24A24,24,0,0,0,184,168Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M32,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H40A8,8,0,0,1,32,64Zm8,72h72a8,8,0,0,0,0-16H40a8,8,0,0,0,0,16Zm88,48H40a8,8,0,0,0,0,16h88a8,8,0,0,0,0-16Zm109.66,2.34L217.36,166A40,40,0,1,0,206,177.36l20.3,20.3a8,8,0,0,0,11.32-11.32Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M34,64a6,6,0,0,1,6-6H216a6,6,0,0,1,0,12H40A6,6,0,0,1,34,64Zm6,70h72a6,6,0,0,0,0-12H40a6,6,0,0,0,0,12Zm88,52H40a6,6,0,0,0,0,12h88a6,6,0,0,0,0-12Zm108.24,10.24a6,6,0,0,1-8.48,0l-21.49-21.48a38.06,38.06,0,1,1,8.49-8.49l21.48,21.49A6,6,0,0,1,236.24,196.24ZM184,170a26,26,0,1,0-26-26A26,26,0,0,0,184,170Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M32,64a8,8,0,0,1,8-8H216a8,8,0,0,1,0,16H40A8,8,0,0,1,32,64Zm8,72h72a8,8,0,0,0,0-16H40a8,8,0,0,0,0,16Zm88,48H40a8,8,0,0,0,0,16h88a8,8,0,0,0,0-16Zm109.66,13.66a8,8,0,0,1-11.32,0L206,177.36A40,40,0,1,1,217.36,166l20.3,20.3A8,8,0,0,1,237.66,197.66ZM184,168a24,24,0,1,0-24-24A24,24,0,0,0,184,168Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M36,64a4,4,0,0,1,4-4H216a4,4,0,0,1,0,8H40A4,4,0,0,1,36,64Zm4,68h72a4,4,0,0,0,0-8H40a4,4,0,0,0,0,8Zm88,56H40a4,4,0,0,0,0,8h88a4,4,0,0,0,0-8Zm106.83,6.83a4,4,0,0,1-5.66,0l-22.72-22.72a36.06,36.06,0,1,1,5.66-5.66l22.72,22.72A4,4,0,0,1,234.83,194.83ZM184,172a28,28,0,1,0-28-28A28,28,0,0,0,184,172Z`}))]]),vi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M156,112a12,12,0,0,1-12,12H80a12,12,0,0,1,0-24h64A12,12,0,0,1,156,112Zm76.49,120.49a12,12,0,0,1-17,0L168,185a92.12,92.12,0,1,1,17-17l47.54,47.53A12,12,0,0,1,232.49,232.49ZM112,180a68,68,0,1,0-68-68A68.08,68.08,0,0,0,112,180Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M192,112a80,80,0,1,1-80-80A80,80,0,0,1,192,112Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M229.66,218.34,179.6,168.28a88.21,88.21,0,1,0-11.32,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM40,112a72,72,0,1,1,72,72A72.08,72.08,0,0,1,40,112Zm112,0a8,8,0,0,1-8,8H80a8,8,0,0,1,0-16h64A8,8,0,0,1,152,112Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M229.66,218.34,179.6,168.28a88.21,88.21,0,1,0-11.32,11.31l50.06,50.07a8,8,0,0,0,11.32-11.32ZM144,120H80a8,8,0,0,1,0-16h64a8,8,0,0,1,0,16Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M150,112a6,6,0,0,1-6,6H80a6,6,0,0,1,0-12h64A6,6,0,0,1,150,112Zm78.24,116.24a6,6,0,0,1-8.48,0l-51.38-51.38a86.15,86.15,0,1,1,8.48-8.48l51.38,51.38A6,6,0,0,1,228.24,228.24ZM112,186a74,74,0,1,0-74-74A74.09,74.09,0,0,0,112,186Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M152,112a8,8,0,0,1-8,8H80a8,8,0,0,1,0-16h64A8,8,0,0,1,152,112Zm77.66,117.66a8,8,0,0,1-11.32,0l-50.06-50.07a88.11,88.11,0,1,1,11.31-11.31l50.07,50.06A8,8,0,0,1,229.66,229.66ZM112,184a72,72,0,1,0-72-72A72.08,72.08,0,0,0,112,184Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M148,112a4,4,0,0,1-4,4H80a4,4,0,0,1,0-8h64A4,4,0,0,1,148,112Zm78.83,114.83a4,4,0,0,1-5.66,0l-52.7-52.7a84.1,84.1,0,1,1,5.66-5.66l52.7,52.7A4,4,0,0,1,226.83,226.83ZM112,188a76,76,0,1,0-76-76A76.08,76.08,0,0,0,112,188Z`}))]]),yi=new Map([[`bold`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M230.47,67.5a12,12,0,0,0-19.26-4.32L172.43,99l-12.68-2.72L157,83.57l35.79-38.78a12,12,0,0,0-4.32-19.26A76.07,76.07,0,0,0,88.41,121.64L30.92,174.18a4.68,4.68,0,0,0-.39.38,36,36,0,0,0,50.91,50.91l.38-.39,52.54-57.49A76.05,76.05,0,0,0,230.47,67.5ZM160,148a51.5,51.5,0,0,1-23.35-5.52,12,12,0,0,0-14.26,2.62L64.31,208.66a12,12,0,0,1-17-17l63.55-58.07a12,12,0,0,0,2.62-14.26A51.5,51.5,0,0,1,108,96a52.06,52.06,0,0,1,52-52h.89L135.17,71.87a12,12,0,0,0-2.91,10.65l5.66,26.35a12,12,0,0,0,9.21,9.21l26.35,5.66a12,12,0,0,0,10.65-2.91L212,95.12c0,.3,0,.59,0,.89A52.06,52.06,0,0,1,160,148Z`}))],[`duotone`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224,96a64,64,0,0,1-94.94,56L73,217A24,24,0,0,1,39,183L104,126.94a64,64,0,0,1,80-90.29L144,80l5.66,26.34L176,112l43.35-40A63.8,63.8,0,0,1,224,96Z`,opacity:`0.2`}),V.createElement(`path`,{d:`M226.76,69a8,8,0,0,0-12.84-2.88l-40.3,37.19-17.23-3.7-3.7-17.23,37.19-40.3A8,8,0,0,0,187,29.24,72,72,0,0,0,88,96,72.34,72.34,0,0,0,94,124.94L33.79,177c-.15.12-.29.26-.43.39a32,32,0,0,0,45.26,45.26c.13-.13.27-.28.39-.42L131.06,162A72,72,0,0,0,232,96,71.56,71.56,0,0,0,226.76,69ZM160,152a56.14,56.14,0,0,1-27.07-7,8,8,0,0,0-9.92,1.77L67.11,211.51a16,16,0,0,1-22.62-22.62L109.18,133a8,8,0,0,0,1.77-9.93,56,56,0,0,1,58.36-82.31l-31.2,33.81a8,8,0,0,0-1.94,7.1L141.83,108a8,8,0,0,0,6.14,6.14l26.35,5.66a8,8,0,0,0,7.1-1.94l33.81-31.2A56.06,56.06,0,0,1,160,152Z`}))],[`fill`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M232,96a72,72,0,0,1-100.94,66L79,222.22c-.12.14-.26.29-.39.42a32,32,0,0,1-45.26-45.26c.14-.13.28-.27.43-.39L94,124.94a72.07,72.07,0,0,1,83.54-98.78,8,8,0,0,1,3.93,13.19L144,80l5.66,26.35L176,112l40.65-37.52a8,8,0,0,1,13.19,3.93A72.6,72.6,0,0,1,232,96Z`}))],[`light`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M224.91,69.75a6,6,0,0,0-9.63-2.16l-41.07,37.9L154.7,101.3l-4.19-19.51,37.9-41.07a6,6,0,0,0-2.16-9.63,70,70,0,0,0-89.77,94.39l-61.39,53c-.11.09-.21.19-.32.3A30,30,0,0,0,77.2,221.23c.11-.11.21-.21.3-.32l53-61.39a70,70,0,0,0,94.39-89.77ZM160,154a58,58,0,0,1-28-7.22,6,6,0,0,0-7.45,1.33L68.57,212.88a18,18,0,0,1-25.45-25.45l64.76-55.94A6,6,0,0,0,109.2,124a58,58,0,0,1,64-84.53L139.58,75.93a6,6,0,0,0-1.45,5.33l5.65,26.35a6,6,0,0,0,4.61,4.61l26.35,5.65a6,6,0,0,0,5.33-1.45L216.49,82.8A58.06,58.06,0,0,1,160,154Z`}))],[`regular`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M226.76,69a8,8,0,0,0-12.84-2.88l-40.3,37.19-17.23-3.7-3.7-17.23,37.19-40.3A8,8,0,0,0,187,29.24,72,72,0,0,0,88,96,72.34,72.34,0,0,0,94,124.94L33.79,177c-.15.12-.29.26-.43.39a32,32,0,0,0,45.26,45.26c.13-.13.27-.28.39-.42L131.06,162A72,72,0,0,0,232,96,71.56,71.56,0,0,0,226.76,69ZM160,152a56.14,56.14,0,0,1-27.07-7,8,8,0,0,0-9.92,1.77L67.11,211.51a16,16,0,0,1-22.62-22.62L109.18,133a8,8,0,0,0,1.77-9.93,56,56,0,0,1,58.36-82.31l-31.2,33.81a8,8,0,0,0-1.94,7.1L141.83,108a8,8,0,0,0,6.14,6.14l26.35,5.66a8,8,0,0,0,7.1-1.94l33.81-31.2A56.06,56.06,0,0,1,160,152Z`}))],[`thin`,V.createElement(V.Fragment,null,V.createElement(`path`,{d:`M223.05,70.5a4,4,0,0,0-6.42-1.44l-41.82,38.6L153,103l-4.68-21.79,38.6-41.82a4,4,0,0,0-1.44-6.43A68,68,0,0,0,98.94,126L36.4,180l-.21.2a28,28,0,0,0,39.6,39.6l.2-.21,54-62.54A68,68,0,0,0,228,96,67.51,67.51,0,0,0,223.05,70.5ZM160,156a60,60,0,0,1-29-7.47,4,4,0,0,0-5,.89L70,214.25A20,20,0,0,1,41.75,186l64.82-56a4,4,0,0,0,.89-5,60,60,0,0,1,69.46-86.59L141.05,77.29a4,4,0,0,0-1,3.55l5.66,26.35a4,4,0,0,0,3.07,3.07l26.35,5.66a4,4,0,0,0,3.55-1l38.87-35.87A60.05,60.05,0,0,1,160,156Z`}))]]),bi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:si}));bi.displayName=`ArrowClockwiseIcon`;var xi=bi,Si=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:ci}));Si.displayName=`ArrowCounterClockwiseIcon`;var Ci=Si,wi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:li}));wi.displayName=`ArrowsOutIcon`;var Ti=wi,Ei=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:ui}));Ei.displayName=`CaretUpIcon`;var Di=Ei,Oi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:di}));Oi.displayName=`ChatCircleTextIcon`;var ki=Oi,Ai=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:fi}));Ai.displayName=`ClockIcon`;var ji=Ai,Mi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:pi}));Mi.displayName=`ClockCounterClockwiseIcon`;var Ni=Mi,Pi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:mi}));Pi.displayName=`InfoIcon`;var Fi=Pi,Ii=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:hi}));Ii.displayName=`KeyboardIcon`;var Li=Ii,Ri=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:gi}));Ri.displayName=`ListBulletsIcon`;var zi=Ri,Bi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:_i}));Bi.displayName=`ListMagnifyingGlassIcon`;var Vi=Bi,Hi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:vi}));Hi.displayName=`MagnifyingGlassMinusIcon`;var Ui=Hi,Wi=V.forwardRef((e,t)=>V.createElement(x,{ref:t,...e,weights:yi}));Wi.displayName=`WrenchIcon`;var Gi=Wi,Ki=i(b(),1),qi=`$__all`;function Ji(e,t,n){if(e.kind===`constant`)return e.value??``;let r=e.kind===`custom`?e.options?.map(e=>({value:e}))??[]:n===null?[]:n,i=t[e.name],a=!e.multi&&Array.isArray(i)&&i.length===0?void 0:i;if(a===`$__all`){if(e.include_all)return qi}else if(a!==void 0){if(e.kind===`text`||r===void 0)return a;let t=new Set(r.map(e=>e.value));if(Array.isArray(a)){if(a.length===0&&e.multi)return[];let n=a.filter(e=>t.has(e));if(n.length>0)return n}else if(t.has(a))return a}return e.default?e.default:e.include_all?qi:r?.[0]?.value??``}var Yi=(e,t)=>e.replace(/\$([a-z][a-z0-9_]*)/g,(e,n)=>{let r=t[n];return r===void 0?e:r===`$__all`?`all`:Array.isArray(r)?r.join(`, `):r});function Xi(e,t,n){let r={};for(let i of e??[]){let e=Ji(i,t,n?.[i.name]);(i.kind!==`query`||e!==``)&&(r[i.name]=e)}return r}function Zi(e){return Array.from({length:e.rows},(t,n)=>Object.fromEntries(e.columns.map((t,r)=>{let i=e.values[r]?.[n]??null;return[t.name,typeof i==`number`&&!Number.isFinite(i)?null:i]})))}function Qi(e,t){return e.viz!==`logs`||!t||t.rows<2?[]:t.columns.flatMap((e,n)=>{if(e.role!==`dimension`||e.type!==`string`||[`body`,`body_template`,`severity`,`status`].includes(e.name)||/(^id$|_id$)/.test(e.name))return[];let r=t.values[n][0];return typeof r==`string`&&r!==``&&t.values[n].slice(0,t.rows).every(e=>e===r)?[{name:e.name,value:r}]:[]})}function $i(e,t){let n=t.frame??{columns:[],values:[],rows:0};return{columns:n.columns.map(e=>e.name),rows:Zi(n),selection:t=>{let n={};for(let r of e.query?.by??[]){let e=r.startsWith(`attributes[`)||r.startsWith(`resource[`)?r.slice(r.indexOf(`'`)+1,r.lastIndexOf(`'`)):r;t[e]!==void 0&&t[e]!==null&&(n[r]=String(t[e]))}return{time:typeof t.time==`number`?t.time:typeof t.start==`number`?t.start:void 0,dimensions:n,trace_id:typeof t.trace_id==`string`?t.trace_id:void 0,namespace:typeof t.namespace==`string`?t.namespace:void 0}}}}function ea(e){return e.replace(/[&<>"']/g,e=>({"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`})[e])}var ta=e=>e.map(ea).join(`
`);function na(e,t=!1){return n=>{let r=Array.isArray(n)?n:[n];return ta([...r[0]?.axisValueLabel?[r[0].axisValueLabel]:[],...r.map(n=>{let r=n.value,i=Array.isArray(r)?t?r.slice(1):r:[r];return`${n.seriesName??``}${n.name?` · ${n.name}`:``}: ${i.map(t=>typeof t==`number`?e(t,n.seriesName):String(t??`—`)).join(` · `)}`})])}}var ra=e=>/^Other(?: \(\d+\))?$/.test(e??``);function ia(e,t){let n=Math.min(6,Math.max(1,Math.floor(t.options?.top||6))),r=e.filter(e=>!ra(e.name)),i=r.slice(0,n).map(e=>({name:e.name,items:[e]})),a=[...e.filter(e=>ra(e.name)),...r.slice(n)];return a.length&&i.push({name:a.length===1&&ra(a[0].name)?a[0].name:`Other (${a.reduce((e,t)=>e+(ra(t.name)?Number(t.name.match(/\d+/)?.[0]??1):1),0)})`,items:a}),i}function aa(e){let t=e.filter(e=>e!==null);return t.length?t.reduce((e,t)=>e+t,0):null}function oa(e,t){let n=Math.min(6,Math.max(1,Math.floor(t.options?.top||6))),r=e.filter(e=>!ra(e.name));return{shown:[...r.slice(0,n),...e.filter(e=>ra(e.name))],hidden:Math.max(0,r.length-n)}}function sa(e,t){return e>0?[{type:`text`,right:8,bottom:2,silent:!0,style:{text:`${e} more series not shown`,fill:t,fontSize:11}}]:[]}function ca(e,t,n,r,i=`sans-serif`,a){let o=e=>Array.from(e).length>24?`${Array.from(e).slice(0,23).join(``)}…`:e,s=Math.max(1,t-16),c=1,l=0;for(let t of e){let e=15+(a?.(o(t),`12px ${i}`)??Array.from(o(t)).length*7.2);l&&l+10+e>s&&(c++,l=0),l+=(l?10:0)+e}let u=c>2;return{top:n?u?30:c*20+2:12,option:{type:u?`scroll`:`plain`,show:n,top:0,left:0,right:0,padding:0,itemGap:6,icon:`roundRect`,itemWidth:10,itemHeight:10,itemStyle:{borderColor:r,borderWidth:1},textStyle:{color:r,fontSize:12,lineHeight:14},data:e,formatter:o,tooltip:{show:!0,renderMode:`html`,formatter:e=>ea(e.name)}}}}function la(e,t){if(!(!Number.isFinite(e)||!Number.isFinite(t)||e>=t||Math.abs(e)>864e13||Math.abs(t)>864e13))return{from:new Date(Math.floor(e)).toISOString(),to:new Date(Math.ceil(t)).toISOString()}}function ua(e){let t=[e.time?.range?`Range ${e.time.range}`:void 0,e.time?.shift?`Shifted ${e.time.shift}`:void 0].filter(Boolean);return t.length?t.join(` · `):void 0}function da(e,t,n){if(n.interactive===!1||n.data?.value===null)return;let r=n.data?.selection;if(r)return Object.values(r.dimensions).some(ra)?void 0:r;if(ra(n.seriesName)||ra(n.name)||n.value===null||Array.isArray(n.value)&&n.value.at(-1)==null)return;let i=e.query?.by?.[0]??t.frame?.columns.find(e=>e.role===`dimension`)?.name,a=e.viz===`timeseries`?n.seriesName:n.name,o=Array.isArray(n.value)?n.value:[];return{time:e.viz===`timeseries`&&typeof o[0]==`number`?o[0]:void 0,dimensions:i&&a?{[i]:a}:{}}}var fa=new Intl.NumberFormat(`en`,{notation:`compact`,maximumFractionDigits:1}),pa=new Intl.NumberFormat(`en`,{maximumFractionDigits:2});function ma(e){return Math.abs(e)<1e-4?e.toExponential(2).replace(/\.?(0+)(?=e)/,``):String(Number(e.toPrecision(3)))}function ha(e,t=pa){return e!==0&&Math.abs(e)<1?ma(e):t.format(e)}function ga(e,t){let n=t===`s`?e*1e3:t===`ns`?e/1e6:e;return e!==0&&n===0?`${ma(e)}${t}`:n!==0&&Math.abs(n)<1?`${ma(n)}ms`:ve(n)}function _a(e){let t=[`B`,`KiB`,`MiB`,`GiB`,`TiB`],n=e,r=0;for(;Math.abs(n)>=1024&&r=1e4?fa:pa);default:return ha(t,Math.abs(t)>=1e4?fa:pa)}}function ya(e){return t=>e===`ms`||e===`s`||e===`ns`?va(e,t).replace(/(\.\d*?)0+([a-z]*)$/,`$1$2`).replace(/\.([a-z]*)$/,`$1`):va(e,t)}function ba(e,t){return ya(e)(t??NaN).replace(/(?<=\d)(ms|ns|s|m|h)\b/g,` $1`)}function xa(e){return Math.max(3,Math.min(10,Math.round(e/70)))-1}function Sa(e,t){let n=t===`ms`?1:t===`s`?1e3:t===`ns`?1e-6:void 0,r=e=>{let t=10**Math.floor(Math.log10(e));return[1,2,5,10].map(e=>e*t).find(t=>t>=e)};if(n===void 0)return r(e);let i=e*n,a=[1,10,100,1e3,1e4,6e4,6e5,36e5,36e6].flatMap(e=>[1,2,5].map(t=>e*t)).sort((e,t)=>e-t);return(i<1?r(i):a.find(e=>e>=i)??r(i/36e5)*36e5)/n}function Ca(e,t,n,r){e=Number.isFinite(e)?Math.min(0,e):0,t=Number.isFinite(t)?Math.max(0,t):1,t===e&&(t=e+1);let i=xa(r),a=Sa(Math.max(t-e,2**-52)/i,n);for(;Math.ceil(t/a)-Math.floor(e/a)>i;)a=Sa(a*1.01,n);return{min:Math.floor(e/a)*a,max:Math.ceil(t/a)*a,interval:a,splitNumber:i,fanout_unit:n}}function wa(e,t){return e.type!==`value`&&e.type!==`log`?e:{...e,...e.type===`value`&&typeof e.min==`number`&&typeof e.max==`number`?Ca(e.min,e.max,typeof e.fanout_unit==`string`?e.fanout_unit:void 0,t):{splitNumber:xa(t)}}}function Ta(e,t,n){let r=e=>va(n,e),i=``;if(n===`ms`||n===`s`||n===`ns`){let a=n===`s`?1e3:n===`ns`?1e-6:1,o=Math.abs((e??t??0)*a),s=o>=6e4?6e4:o>=1e3?1e3:1;i=s===6e4?` min`:s===1e3?` s`:` ms`;let c=s===6e4?1:s===1e3?+(o<1e4):2,l=new Intl.NumberFormat(void 0,{maximumFractionDigits:c});r=e=>l.format(e*a/s)}return t===null&&e!==null?`≥${r(e)}${i}`:(e===null||e===0)&&t!==null?`<${r(t)}${i}`:`${e===null?`−∞`:r(e)}–${t===null?`∞`:r(t)}${i}`}function Ea(e){let t=new Date(e);return t.getHours()===0&&t.getMinutes()===0&&t.getSeconds()===0?t.toLocaleDateString(void 0,{month:`short`,day:`numeric`}):t.toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`,hourCycle:`h23`})}function Da(e,t=new Date,n){let r=new Date(e);if(!Number.isFinite(r.getTime()))return`—`;let i=new Intl.DateTimeFormat(n,{month:`short`,day:`numeric`,...r.getFullYear()===t.getFullYear()?{}:{year:`numeric`},hour:`2-digit`,minute:`2-digit`,second:`2-digit`,hourCycle:`h23`}).formatToParts(r),a=i.filter(e=>[`month`,`day`,`year`].includes(e.type)).map(e=>e.value),o=i.filter(e=>[`hour`,`minute`,`second`].includes(e.type)).map(e=>e.value);return`${a.join(` `)} ${o.join(`:`)}`}function Oa({panel:e,result:t}){let n=t?.frame;return(0,H.jsxs)(`div`,{"data-panel-data":!0,children:[t?.error&&(0,H.jsx)(T,{"data-panel-error-detail":!0,size:`sm`,role:`status`,style:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,userSelect:`text`},children:t.error}),n?(0,H.jsxs)(B,{fz:12,striped:!0,children:[(0,H.jsx)(B.Thead,{children:(0,H.jsx)(B.Tr,{children:n.columns.map(e=>(0,H.jsx)(B.Th,{ff:xt.display,children:e.name},e.name))})}),(0,H.jsx)(B.Tbody,{children:Array.from({length:Math.min(n.rows,500)},(t,r)=>(0,H.jsx)(B.Tr,{children:n.columns.map((t,i)=>{let a=n.values[i][r];return(0,H.jsx)(B.Td,{ff:xt.display,children:a===null?`—`:t.type===`time`?new Date(Number(a)).toISOString():t.role===`measure`?va(t.unit??e.unit,Number(a)):String(a)},t.name)})},r))})]}):(0,H.jsx)(T,{c:`dimmed`,size:`sm`,children:`No data.`}),(0,H.jsxs)(T,{c:`dimmed`,fz:12,mt:8,children:[`Ran in `,t?.elapsed_ms??0,` ms`,t?.interval?`, one point per ${t.interval}`:``,n?`, ${n.rows} rows${n.truncated?` (truncated)`:``}`:``,`.`]}),(t?.sql??e.sql)&&(0,H.jsx)(Le,{block:!0,tabIndex:0,mt:8,children:t?.sql??e.sql})]})}function ka({panel:e,dark:t}){let n=JSON.stringify(e,null,2).split(/("(?:[^"\\]|\\.)*"(?=\s*:)|"(?:[^"\\]|\\.)*"|\b(?:true|false|null)\b|-?\d+(?:\.\d+)?)/g);return(0,H.jsx)(`pre`,{"data-panel-spec":!0,style:{margin:0,fontFamily:xt.display,fontSize:12,color:it[t?`dark`:`light`].text},children:n.map((e,r)=>{let i=e.startsWith(`"`)&&/^\s*:/.test(n[r+1]??``)?`key`:e.startsWith(`"`)?`string`:/^(true|false|null)$/.test(e)?`literal`:/^-?\d/.test(e)?`number`:`punctuation`,a=i===`key`?pt[t?4:7]:i===`string`?st[t?4:8]:i===`number`||i===`literal`?Et[t?4:8]:void 0;return i===`punctuation`?e:(0,H.jsx)(`span`,{"data-json-token":i,style:{color:a},children:e},r)})})}function Aa(e){let t=e.event.data?.selection,n=e.event.value;return JSON.stringify([e.event.seriesName,e.event.name,t?.from??t?.time??(Array.isArray(n)?n[0]:void 0),t?.dimensions,t?.bucket])}function ja(e){let t=new Date().toISOString().slice(0,10),n=e.from.slice(0,10),r=e.to.slice(0,10),i=e=>e.slice(11,-1).replace(/\.000$/,``);return`${(n===t?``:n+` `)+i(e.from)} – ${(r!==n&&r!==t?r+` `:``)+i(e.to)} UTC · ${ve(Date.parse(e.to)-Date.parse(e.from))}`}var Ma={background:`color-mix(in srgb, var(--mantine-color-body) 92%, transparent)`,border:`1px solid var(--mantine-color-default-border)`,borderRadius:`var(--mantine-radius-sm)`,padding:`2px 6px`};function Na(e){return e.replace(`Enter drill`,`↵ drill`).replace(`Shift+←→`,`⇧←→`)}var Pa=(0,V.createContext)(void 0);function Fa({points:e,label:t,summary:n,children:r,onClick:i,canSelect:a,onHighlight:s,onActiveChange:c,onRangePending:l,onRangeChange:u,onRangeBarHeight:d,rangeReset:f,height:p=`100%`,onZoom:m,bounds:h,pointWindow:g}){let[_,v]=(0,V.useState)(!1),[b,x]=(0,V.useState)(``),[S,w]=(0,V.useState)(),[E,D]=(0,V.useState)(null),O=(0,V.useRef)(null),k=(0,V.useRef)(!1);(0,V.useEffect)(()=>{let e=e=>{e.key===`Tab`&&(k.current=!1)};return document.addEventListener(`keydown`,e,!0),()=>document.removeEventListener(`keydown`,e,!0)},[]);let A=(0,V.useId)(),j=(0,V.useContext)(Pa),M=(0,V.useRef)(null),N=(0,V.useRef)({onHighlight:s,onActiveChange:c,onRangePending:l,onRangeChange:u,onRangeBarHeight:d});N.current={onHighlight:s,onActiveChange:c,onRangePending:l,onRangeChange:u,onRangeBarHeight:d};let P=(0,V.useMemo)(()=>new Map(e.map(e=>[Aa(e),e])),[e]),F=(0,V.useRef)(void 0),I=e=>g?.(e)?.from??e.event.name??(Array.isArray(e.event.value)?e.event.value[0]:void 0),L=F.current,ee=L?e.filter(e=>e.event.seriesName===L.event.seriesName):e,te=ee.length?ee:e,ne=L&&I(L),re=typeof ne==`number`?te.reduce((e,t)=>{let n=I(t),r=e&&I(e);return typeof n==`number`&&(!e||typeof r!=`number`||Math.abs(n-ne)I(e)===ne),ie=S?P.get(S)??re??te[0]??e[0]:e[0],ae=!!(m&&h&&Number.isFinite(h.from)&&Number.isFinite(h.to)&&h.from[...new Set(e.map(e=>e.event.seriesName))],[e]),oe=(0,V.useMemo)(()=>e.filter(e=>e.event.seriesName===ie?.event.seriesName),[e,ie?.event.seriesName]),z=ie?oe.indexOf(ie):-1;(0,V.useEffect)(()=>{ie&&(!S||P.has(S)||!ee.length)&&(F.current=ie,(!S||!ee.length)&&w(Aa(ie))),_&&N.current.onHighlight(ie)},[ie,S,_]),(0,V.useEffect)(()=>{if(!E)return;let e=Date.parse(E.from),t=Date.parse(E.to);h&&(Number.isFinite(e)&&eh.to)&&D(null)},[h?.from,h?.to,E]),(0,V.useEffect)(()=>{N.current.onRangePending?.(!!E)},[!!E]),(0,V.useEffect)(()=>{N.current.onRangeChange?.(E?{from:Date.parse(E.from),to:Date.parse(E.to)}:void 0)},[E]),(0,V.useEffect)(()=>{D(null)},[f]),(0,V.useEffect)(()=>()=>{N.current.onHighlight(void 0),N.current.onRangePending?.(!1),N.current.onRangeChange?.(void 0)},[]);let se=(e,t=!1)=>{if(e){if(x(n(e)),t&&ae&&ie){let t=E?.anchor??Aa(ie),n=P.get(t),r=E?.window??(n&&g?.(n)),i=g?.(e);if(r&&i){let e=Math.max(h.from,Math.min(r.from,i.from)),n=Math.min(h.to,Math.max(r.to,i.to));Number.isFinite(e)&&Number.isFinite(n)&&e{if(!ie)return;let n=R[Math.max(0,Math.min(R.length-1,R.indexOf(ie.event.seriesName)+t))],r=e.filter(e=>e.event.seriesName===n),i=I(ie),a=r.find(e=>I(e)===i),o=typeof i==`number`?r.reduce((e,t)=>{let n=I(t),r=e&&I(e);return typeof n==`number`&&(!e||typeof r!=`number`||Math.abs(n-i){e===`ArrowLeft`||e===`ArrowRight`?se(oe[Math.max(0,Math.min(oe.length-1,z+(e===`ArrowLeft`?-1:1)))],t):!t&&(e===`ArrowUp`||e===`ArrowDown`)?ce(e===`ArrowUp`?-1:1):!t&&(e===`Home`||e===`End`)&&se(e===`Home`?oe[0]:oe.at(-1))},ue=()=>{D(null),O.current?.focus()},de=ae?`←→ points · ↑↓ series · Enter drill · Shift+←→ range`:`←→ points · ↑↓ series · Enter drill`;return(0,V.useLayoutEffect)(()=>(j?.setHint(_?de:void 0),()=>j?.setHint(void 0)),[j,_,de]),(0,V.useLayoutEffect)(()=>{let e=M.current;if(!e)return;N.current.onRangeBarHeight?.(e.getBoundingClientRect().height);let t=new ResizeObserver(([t])=>{if(!t)return;let n=getComputedStyle(e),r=[n.paddingTop,n.paddingBottom,n.borderTopWidth,n.borderBottomWidth].reduce((e,t)=>e+(parseFloat(t)||0),0);N.current.onRangeBarHeight?.(t.borderBoxSize?.[0]?.blockSize??t.contentRect.height+r)});return t.observe(e),()=>{t.disconnect(),N.current.onRangeBarHeight?.(0)}},[!!(E&&ae)]),(0,H.jsxs)(o,{ref:O,"data-chart-plot":!0,tabIndex:0,role:`application`,"aria-roledescription":`chart`,"aria-label":t,"aria-describedby":A,"data-mantine-stop-propagation":E?`true`:void 0,className:`chart-keyboard-point`,style:{position:`relative`,height:p,width:`100%`,flex:`1 1 auto`,minHeight:0,minWidth:0},onPointerDownCapture:e=>{M.current?.contains(e.target)||(k.current=!0,v(!1),_&&N.current.onHighlight(void 0),N.current.onActiveChange?.(!1))},onFocus:e=>{e.target!==e.currentTarget||k.current||(N.current.onActiveChange?.(!0),v(!0))},onBlur:e=>{e.currentTarget.contains(e.relatedTarget)||(v(!1),D(null),x(``),N.current.onHighlight(void 0),N.current.onActiveChange?.(!1))},onKeyDown:e=>{if(e.defaultPrevented||e.ctrlKey||e.metaKey||e.altKey||e.nativeEvent.isComposing)return;if(e.key===`Escape`&&!e.repeat){E?(e.preventDefault(),e.stopPropagation(),ue()):e.target===e.currentTarget&&!e.currentTarget.closest(`[data-panel-fullscreen],[data-fragment-fullscreen]`)&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.blur());return}if(e.target!==e.currentTarget||e.repeat&&![`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`].includes(e.key))return;let t=[`ArrowLeft`,`ArrowRight`,`ArrowUp`,`ArrowDown`,`Home`,`End`].includes(e.key);if(t&&!_&&(k.current=!1,v(!0),N.current.onActiveChange?.(!0),!ie)){e.preventDefault();return}e.key===`Enter`&&_&&!e.shiftKey&&ie&&i&&(!a||a(ie.event))?(e.preventDefault(),i(ie.event)):t&&(!e.shiftKey||e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.preventDefault(),le(e.key,e.shiftKey))},children:[r,(0,H.jsx)(o,{"data-chart-overlay":!0,style:{position:`absolute`,inset:0,zIndex:1,pointerEvents:`none`,overflow:`hidden`},children:E&&ae&&(0,H.jsxs)(y,{ref:M,"data-chart-range-bar":!0,gap:6,style:{...Ma,position:`absolute`,bottom:4,left:4,right:4,maxHeight:`100%`,overflow:`auto`,pointerEvents:`auto`},children:[(0,H.jsx)(T,{"data-chart-range-label":!0,size:`xs`,title:E.from+` – `+E.to,truncate:!0,style:{flex:`1 1 140px`,minWidth:0},children:ja(E)}),(0,H.jsx)(C,{size:`compact-xs`,"data-mantine-stop-propagation":`true`,onClick:()=>{m(Date.parse(E.from),Date.parse(E.to)),ue()},children:`Zoom to range`}),(0,H.jsx)(C,{size:`compact-xs`,variant:`subtle`,"data-mantine-stop-propagation":`true`,onClick:ue,children:`Cancel`})]})}),(0,H.jsx)(Je,{id:A,children:de}),(0,H.jsx)(Je,{"aria-live":`polite`,"aria-atomic":`true`,children:b})]})}var Ia=new Set([`id`,`http`,`https`,`rpc`,`grpc`,`cpu`,`sql`,`url`,`uri`,`ip`,`io`,`db`,`gc`,`tls`,`api`]),La={ms:`ms`,ns:`ns`,s:`s`,us:`µs`,bytes:`bytes`,percent:`%`,ratio:`ratio`,per_second:`/s`,per_minute:`/min`},Ra={body_template:`message template`,parquet_index:`traces`};function za(e,t){let n=typeof e==`string`?e:e.name,r=t?.options?.columns?.find(e=>e.field===n)?.unit??(typeof e==`string`?void 0:e.unit)??(typeof e!=`string`&&e.role===`measure`?t?.unit:void 0),i=Ra[n]??n;/\b(?:duckdb|parquet|sqlite|variant|timestamptz_ns|timestamp_ns)\b|\btelemetry\./i.test(i)&&(i=`value`),i=i.replace(/^(\w+)\(([^()]*)\)$/,(e,t,n)=>[t,n].filter(Boolean).join(`_`));let a=i.match(/_(ms|ns|us|s|bytes|percent)$/i);a&&(i=i.slice(0,-a[0].length));let o=r??a?.[1]?.toLowerCase();return i=i.split(`_`).map((e,t)=>/^p\d+$/i.test(e)||Ia.has(e.toLowerCase())?e.toUpperCase():t===0?e.charAt(0).toUpperCase()+e.slice(1):e).join(` `),i+(o&&o!==`none`&&o!==`count`?` (${La[o]??o})`:``)}function Ba(e){return e===`healthy`?`ok`:e===`degraded`?`warn`:e===`unknown`?`gray`:`bad`}function Va(e){return it[e?`dark`:`light`]}function Ha(e){let t=e?5:7;return{ok:st[t],warn:lt[t],bad:wt[t],info:Et[t]}}function Ua(e,t){return _t[t?`dark`:`light`][e]??Va(t).muted}function Wa(e){return e===`unhealthy`?`diamond`:e===`degraded`?`roundRect`:`circle`}function Ga(e){return e===`unknown`?`dashed`:`solid`}var Ka=e=>typeof e==`number`&&Number.isFinite(e)?e:null;function qa(e){return e.columns.flatMap((e,t)=>e.role===`measure`?[t]:[])}function Ja(e){let t=e.columns.findIndex(e=>e.role===`time`);if(t<0)return[];let n=e.columns.findIndex(e=>e.role===`dimension`),r=qa(e);if(n>=0&&r.length>0){let i=r[0],a=new Map;for(let r=0;r({name:e.columns[n].name,unit:e.columns[n].unit,points:e.values[t].map((t,r)=>[Number(t),Ka(e.values[n][r])])}))}function Ya(e){let t=e.columns.flatMap((e,t)=>e.role===`dimension`?[t]:[]),n=qa(e);if(t.length===0||n.length===0)return{categories:[],series:[]};let r=t[0],i=[];for(let t=0;t1){let a=t[1],o=n[0],s=new Map;for(let t=0;tnull)),s.get(n)[i.indexOf(String(e.values[r][t]??``))]=Ka(e.values[o][t])}return{categories:i,series:[...s.entries()].map(([t,n])=>({name:t,unit:e.columns[o].unit,values:n}))}}return{categories:i,series:n.map(t=>({name:e.columns[t].name,unit:e.columns[t].unit,values:e.values[t].map(Ka)}))}}function Xa(e,t){let n=e.filter(e=>e!==null);if(n.length===0)return null;switch(t){case`last`:return n[n.length-1];case`min`:return Math.min(...n);case`max`:return Math.max(...n);case`sum`:return n.reduce((e,t)=>e+t,0);default:return n.reduce((e,t)=>e+t,0)/n.length}}function Za(e,t){let n=qa(t)[0];return n===void 0?null:(e.reduce??`window`)===`window`?t.totals?Ka(t.totals[n]):Xa(t.values[n].map(Ka),`mean`):Xa(t.values[n].map(Ka),e.reduce??`mean`)}function Qa(e){let t=qa(e)[0];return t===void 0?[]:e.values[t].map(Ka)}var $a={ok:0,warn:1,bad:2};function eo(e){if(!e?.length)return;let t=[...e].sort((e,t)=>$a[e.status]-$a[t.status]),n=t[0],r=t[t.length-1];return $a[r.status]>$a[n.status]&&r.value!==n.value?r.value>n.value?`lower`:`higher`:`lower`}function to(e,t,n){if(e===null||!t||t.length===0)return null;n??=eo(t);let r=`ok`;for(let i of t)(n===`lower`?e>=i.value:e<=i.value)&&$a[i.status]>$a[r]&&(r=i.status);return r}function no(e,t){let n=yt(e),r=yt(t);return(Math.max(n,r)+.05)/(Math.min(n,r)+.05)}function ro(e,t){return`rgba(${[1,3,5].map(t=>parseInt(e.slice(t,t+2),16)).join(`, `)}, ${t})`}function io(e,t){return{color:e,...no(e,t.surface)<3?{borderColor:t.text,borderWidth:1}:{}}}function ao(e,t){return{color:e,...no(e,t.surface)<3?{shadowColor:t.text,shadowBlur:2}:{}}}function oo(e,t){return{ok:st,warn:lt,bad:wt}[e][t?5:8]}function so(e){let t=Va(e),n=Ha(e);return{dark:e,text:t.text,muted:t.muted,grid:t.grid,surface:t.surface,border:t.border,status:{ok:n.ok,warn:n.warn,bad:n.bad},font:xt.display}}function co(e,t,n){if(!Array.isArray(e.series))return e;let r=e.series,i=Array.isArray(e.yAxis)?e.yAxis:[e.yAxis],a=[],o=r.map((e,o)=>{let s=e.endLabel;if(!s?.show||!Array.isArray(e.data))return e;let c;for(let t=e.data.length-1;t>=0;t--){let n=e.data[t];if(Array.isArray(n)&&typeof n[1]==`number`&&Number.isFinite(n[1])){c=n;break}}let l=i[Number(e.yAxisIndex??0)];if(!c||!l)return{...e,endLabel:{...s,show:!1}};let u=l.type===`log`?Math.log:e=>e,d=l.min??1/0,f=l.max??0;if(l.type===`log`&&(l.min===void 0||l.max===void 0)){for(let t of r)if(Number(t.yAxisIndex??0)===Number(e.yAxisIndex??0)&&Array.isArray(t.data))for(let e of t.data)Array.isArray(e)&&typeof e[1]==`number`&&Number.isFinite(e[1])&&e[1]>0&&(l.min===void 0&&(d=Math.min(d,e[1])),l.max===void 0&&(f=Math.max(f,e[1])))}Number.isFinite(d)||(d=1);let p=u(l.type===`log`?d:l.min??0),m=u(l.type===`log`?Math.max(f,d*1.01):l.max??1),h=n?.(o,c),g=Number.isFinite(h)?h:t.y+t.height*(1-(u(c[1])-p)/(m-p)),_=((s.lineHeight??14)+2)/2,v=[Math.max(t.y+_,Math.min(t.y+t.height-_,g)),...a.flatMap(e=>[e.y-e.half-_,e.y+e.half+_])].filter(e=>Number.isFinite(e)&&e-_>=t.y&&e+_<=t.y+t.height&&a.every(t=>Math.abs(t.y-e)>=t.half+_)).sort((e,t)=>Math.abs(e-g)-Math.abs(t-g))[0];return v===void 0?{...e,endLabel:{...s,show:!1}}:(a.push({y:v,half:_}),{...e,labelLayout:{dy:v-g,hideOverlap:!0}})});return{...e,series:o}}var lo=(e,t,n)=>ra(e)?n.muted:Ua(t,n.dark);function uo(e,t){let n=Ja(e);if(!e.columns.some(e=>e.role===`dimension`))for(let r of n)r.name=za(e.columns.find(e=>e.name===r.name)??r.name,t);return oa(n,t)}function fo(e,t){return{animationDuration:200,textStyle:{fontFamily:e.font,color:e.muted,fontSize:11},grid:{left:8,right:16,top:28,bottom:8,containLabel:!0},tooltip:{trigger:`axis`,formatter:na(e=>va(t,e)),confine:!0,backgroundColor:e.surface,borderColor:e.border,textStyle:{color:e.text,fontSize:12},valueFormatter:e=>va(t,e),axisPointer:{type:`line`,lineStyle:{color:e.border}}},aria:{enabled:!0}}}function po(e,t,n,r){return(e.thresholds??[]).map(i=>({yAxis:i.value,label:{formatter:`${i.label??i.status} ${ya(r??e.unit)(i.value).replace(/(?<=\d)(ms|s|m|h)$/,` $1`)}`,position:i.value<=(n.min+n.max)/2?`insideEndTop`:`insideEndBottom`,distance:8,color:t.muted,textBorderColor:t.surface,textBorderWidth:3,fontSize:12},lineStyle:{color:t.status[i.status],type:[4,3],width:1}}))}function mo(e,t,n,r={width:500,height:248}){let i=t.frame?uo(t.frame,e):{shown:[],hidden:0},a=i.shown,o=a[0]?.unit??e.unit,s=new Set(a.map(e=>e.name)),c=a.find(e=>ra(e.name)),l=t.previous&&t.shift_ms!==void 0?uo(t.previous,e).shown.flatMap(e=>ra(e.name)?c?[e]:[]:s.has(e.name)?[e]:[]):[],u=[...new Set([...a,...l].map(t=>t.unit??e.unit))];u.length===0&&u.push(e.unit);let d=e.options?.style??`line`,f=a.length>=2&&a.length<=6&&i.hidden===0&&d!==`bars`&&d!==`stacked`,p=f?Math.max(40,...a.map(e=>{let t=Array.from(e.name).slice(0,24).join(``);return r.measureText?.(t,`12px ${n.font}`)??Array.from(t).length*7.2}))+12:0,m=f?p+8:0,h=(e.options?.legend??`auto`)!==`hidden`&&a.length>1,g=ca(a.map(e=>e.name),r.width,h,n.text,n.font,r.measureText),_=r.height-g.top-(i.hidden?24:8)-22,v=Math.max(0,Math.floor(_/16)),y=t.shift_ms,b=u.map(t=>{let n=[...a,...l].filter(n=>(n.unit??e.unit)===t).flatMap(e=>e.points.flatMap(([,e])=>e===null?[]:[e]));if(d===`stacked`){let r=new Map;for(let n of a.filter(n=>(n.unit??e.unit)===t))for(let[e,t]of n.points){let n=r.get(e)??{positive:0,negative:0};t!==null&&(t>0?n.positive+=t:n.negative+=t),r.set(e,n)}n.push(...[...r.values()].flatMap(e=>[e.positive,e.negative]))}return Ca(Math.min(0,...n),Math.max(0,...n),t,_)}),x=a.map((t,r)=>{let i=lo(t.name,r,n);return{name:t.name,interactive:!0,yAxisIndex:u.indexOf(t.unit??e.unit),tooltip:{valueFormatter:n=>va(t.unit??e.unit,n)},type:d===`bars`||d===`stacked`?`bar`:`line`,data:t.points,endLabel:f?{show:r0?{symbol:[`none`,`none`],silent:!0,data:po(e,n,b[0],o)}:void 0}}),S=y===void 0?[]:l.map(t=>({name:`${t.name} · previous`,interactive:!1,yAxisIndex:u.indexOf(t.unit??e.unit),tooltip:{valueFormatter:n=>va(t.unit??e.unit,n)},type:`line`,data:t.points.map(([e,t])=>[e+y,t]),showSymbol:!1,silent:!0,z:1,lineStyle:{width:1,type:`dashed`,color:n.muted},itemStyle:{color:n.muted}})),C=u.map((t,r)=>({...e.options?.scale===`log`?{splitNumber:xa(_)}:b[r],type:e.options?.scale===`log`?`log`:`value`,position:r===0?`left`:`right`,offset:Math.max(0,r-1)*56,axisLine:{show:!1},splitLine:{show:r===0,lineStyle:{color:n.grid}},axisLabel:{color:n.muted,fontFamily:n.font,fontSize:11,hideOverlap:!0,formatter:ya(t)}}));return co({...fo(n,o),tooltip:{...fo(n,o).tooltip,formatter:na((t,n)=>va([...a,...l].find(e=>e.name===n||`${e.name} · previous`===n)?.unit??e.unit,t),!0)},legend:g.option,grid:{left:8,right:16+(f?m:0)+Math.max(0,u.length-2)*56,top:g.top,bottom:i.hidden?24:8,containLabel:!0},xAxis:{type:`time`,min:t.from_ms,max:t.to_ms,axisLine:{lineStyle:{color:n.grid}},axisTick:{show:!1},splitLine:{show:!1},axisLabel:{color:n.muted,fontFamily:n.font,fontSize:11,hideOverlap:!0,formatter:Ea}},yAxis:C.length===1?C[0]:C,series:[...x,...S],graphic:sa(i.hidden,n.muted)},{y:g.top,height:_})}function ho(e,t,n){if(n(e)<=t)return e;let r=Array.from(e);for(let e=r.length-1;e>0;e--){let i=Math.floor(e*.45),a=e-i,o=r.slice(0,i).join(``)+`…`+r.slice(-a).join(``);if(n(o)<=t)return o}return`…`}function go(e,t,n,r={width:500,height:248}){let i=Ya(t);if(t.columns.filter(e=>e.role===`dimension`).length<2)for(let n of i.series)n.name=za(t.columns.find(e=>e.name===n.name)??n.name,e);let a=i.categories,{shown:o,hidden:s}=oa(i.series,e),c=t.columns.flatMap((e,t)=>e.role===`dimension`?[t]:[]),l=new Map;for(let n=0;nString(t.values[e][n]??``))),{dimensions:r,...i})}let u=o[0]?.unit??e.unit,d=[...new Set(o.map(t=>t.unit??e.unit))];d.length===0&&d.push(e.unit);let f=o.length>1,p=!!(t.periods?.[`Before deploy`]||t.periods?.[`Since deploy`]),m=e=>r.measureText?.(e,`11px ${n.font}`)??Array.from(e).length*6.6,h=Math.min(r.width*.4,Math.max(40,...a.map(m))),g=ca(o.map(e=>e.name),r.width,f&&e.options?.legend!==`hidden`,n.text,n.font,r.measureText),_=d.map((t,i)=>({...Ca(Math.min(0,...o.filter(n=>(n.unit??e.unit)===t).flatMap(e=>e.values.filter(e=>e!==null))),Math.max(0,...o.filter(n=>(n.unit??e.unit)===t).flatMap(e=>e.values.filter(e=>e!==null))),t,r.width-h-80),type:`value`,position:i===0?`bottom`:`top`,offset:Math.max(0,i-1)*36,splitLine:{show:i===0,lineStyle:{color:n.grid}},axisLabel:{color:n.muted,fontFamily:n.font,fontSize:11,formatter:e=>ba(t,e),hideOverlap:!0}}));return{...fo(n,u),tooltip:{...fo(n,u).tooltip,formatter:na((t,n)=>va(o.find(e=>e.name===n)?.unit??e.unit,t)),axisPointer:{type:`shadow`}},legend:g.option,grid:{left:8,right:56,top:(f?g.top:8)+Math.max(0,d.length-1)*36,bottom:s?24:8,containLabel:!0},yAxis:{type:`category`,inverse:!0,data:a,splitLine:{show:!1},axisLine:{lineStyle:{color:n.grid}},axisTick:{show:!1},axisLabel:{color:n.muted,fontFamily:n.font,fontSize:11,width:h,overflow:`truncate`,formatter:e=>ho(e,h,m)}},xAxis:_.length===1?_[0]:_,series:o.map((t,r)=>({name:t.name,interactive:!0,xAxisIndex:d.indexOf(t.unit??e.unit),tooltip:{valueFormatter:n=>va(t.unit??e.unit,n)},type:`bar`,data:t.values.map((e,n)=>({value:e,selection:l.get(JSON.stringify(c.length>1?[a[n],t.name]:[a[n]]))})),barMaxWidth:p&&t.name===`Before deploy`?7:14,barGap:`20%`,itemStyle:{...io(p?t.name===`Before deploy`?n.muted:Ua(0,n.dark):lo(t.name,r,n),n),borderRadius:[0,4,4,0]},label:{show:p?t.name===`Since deploy`:!f||r===0,position:`right`,color:n.text,fontFamily:n.font,fontSize:11,formatter:({value:n})=>ba(t.unit??e.unit,n)}})),graphic:sa(s,n.muted)}}function _o(e,t,n,r=e.unit,i={width:270,height:140}){let a=e.min??0,o=e.max??100,s=vo(e,a,o,n),c=va(r,t),l=to(t,e.thresholds,e.better),u=l===`bad`?`◆ Bad`:l===`warn`?`■ Warn`:l===`ok`?`● OK`:t===null?`○ Unknown`:void 0,d=e=>`${e}40`,f=i.measureText?.(c,`600 28px ${n.font}`)??c.length*28*.6,p=i.measureText?.(u??``,`11px ${n.font}`)??(u?.length??0)*11*.6,m=i.width{let r=y;return y=e,{type:`rect`,shape:{x:4+r*_,y:g,width:(e-r)*_,height:10,r:[n===0?5:0,n===s.length-1?5:0,n===s.length-1?5:0,n===0?5:0]},style:{fill:d(t)}}}),{id:`gauge-fill`,type:`rect`,shape:{x:4,y:g,width:v*_,height:10,r:5},style:{fill:l?n.status[l]:Ua(0,n.dark)}},{id:`gauge-marker`,type:`rect`,shape:{x:3+v*_,y:g-2,width:2,height:14,r:1},style:{fill:n.text}},{type:`text`,left:4,top:g+12,style:{text:va(r,a),fill:n.muted,fontSize:11,fontFamily:n.font}},{type:`text`,right:4,top:g+12,style:{text:va(r,o),fill:n.muted,fontSize:11,fontFamily:n.font}}]}}function vo(e,t,n,r){let i=n-t||1,a=[t,...(e.thresholds??[]).map(e=>Math.min(n,Math.max(t,e.value))),n].sort((e,t)=>e-t),o=[];for(let t=0;t[(e.end-t)/i,r.status[e.status]])}var yo=function(e,t){return yo=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},yo(e,t)};function U(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);yo(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}var bo=`12px sans-serif`,xo=20,So=100,Co=`007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N`;function wo(e){var t={};if(typeof JSON>`u`)return t;for(var n=0;n=0)s=o*n.length;else for(var c=0;c=zo&&(Ro=0),Ro++}function Vo(){var e=[...arguments];typeof console<`u`&&console.error.apply(console,e)}function Ho(e){if(typeof e!=`object`||!e)return e;var t=e,n=ko.call(e);if(n===`[object Array]`){if(!xs(e)){t=[];for(var r=0,i=e.length;r`u`&&typeof self<`u`?Ns.worker=!0:!Ns.hasGlobalWindow||`Deno`in window||typeof navigator<`u`&&typeof navigator.userAgent==`string`&&navigator.userAgent.indexOf(`Node.js`)>-1?(Ns.node=!0,Ns.svgSupported=!0):Ps(navigator.userAgent,Ns);function Ps(e,t){var n=t.browser,r=e.match(/Firefox\/([\d.]+)/),i=e.match(/MSIE\s([\d.]+)/)||e.match(/Trident\/.+?rv:(([\d.]+))/),a=e.match(/Edge?\/([\d.]+)/),o=/micromessenger/i.test(e);if(r&&(n.firefox=!0,n.version=r[1]),i&&(n.ie=!0,n.version=i[1]),a&&(n.edge=!0,n.version=a[1],n.newEdge=+a[1].split(`.`)[0]>18),o&&(n.weChat=!0),t.svgSupported=typeof SVGRect<`u`,t.touchEventsSupported=`ontouchstart`in window&&!n.ie&&!n.edge,t.pointerEventsSupported=`onpointerdown`in window&&(n.edge||n.ie&&+n.version>=11),t.domSupported=typeof document<`u`){var s=document.documentElement.style;t.transform3dSupported=(n.ie&&`transition`in s||n.edge||`WebKitCSSMatrix`in window&&`m11`in new WebKitCSSMatrix||`MozPerspective`in s)&&!(`OTransition`in s),t.transformSupported=t.transform3dSupported||n.ie&&+n.version>=9}}var Fs=1e-4,Is=20;function Ls(e){return e.replace(/^\s+|\s+$/g,``)}var Rs=Math.min,zs=Math.max,Bs=Math.abs,Vs=Math.round,Hs=Math.floor,Us=Math.ceil,Ws=Math.pow,Gs=Math.log,Ks=Math.LN10,qs=Math.PI,Js=Math.random;function Ys(e,t,n,r){var i=t[0],a=t[1],o=n[0],s=n[1],c=a-i,l=s-o;if(c===0)return l===0?o:(o+s)/2;if(r){if(c>0){if(e<=i)return o;if(e>=a)return s}else if(e>=i)return o;else if(e<=a)return s}else{if(e===i)return o;if(e===a)return s}return(e-i)/c*l+o}var Xs=Zs;function Zs(e,t,n){switch(e){case`center`:case`middle`:e=`50%`;break;case`left`:case`top`:e=`0%`;break;case`right`:case`bottom`:e=`100%`}return Qs(e,t,n)}function Qs(e,t,n){return Y(e)?$s(e)?parseFloat(e)/100*t+(n||0):parseFloat(e):e==null?NaN:+e}function $s(e){return!!Ls(e).match(/%$/)}function ec(e,t,n){return isNaN(t)?n?``+e:+e:(t=Rs(zs(0,t),Is),e=(+e).toFixed(t),n?e:+e)}function tc(e){return e.sort(function(e,t){return e-t}),e}function nc(e){if(e=+e,isNaN(e))return 0;if(e>1e-14){for(var t=1,n=0;n<15;n++,t*=10)if(Vs(e*t)/t===e)return n}return rc(e)}function rc(e){var t=e.toString().toLowerCase(),n=t.indexOf(`e`),r=n>0?+t.slice(n+1):0,i=n>0?n:t.length,a=t.indexOf(`.`);return zs(0,(a<0?0:i-1-a)-r)}function ic(e,t,n){var r=Bs(e[1]-e[0]);if(!isFinite(r)||r===0)return NaN;var i=Gs(2*Bs(n||1)*Bs(r))/Ks,a=Gs(Bs(t))/Ks,o=zs(0,Us(-i+a));return isFinite(o)||(o=NaN),o}function ac(e,t){var n=zs(nc(e),nc(t)),r=e+t;return n>Is?r:ec(r,n)}var oc=Ws(2,53)-1;function sc(e){var t=qs*2;return(e%t+t)%t}function cc(e){return e>-Fs&&e=10&&t++,t}function pc(e,t){var n=fc(e),r=Ws(10,n),i=e/r;return e=(t===2?1:t?i<1.5?1:i<2.5?2:i<4?3:i<7?5:10:i<1?1:i<2?2:i<3?3:i<5?5:10)*r,ec(e,-n)}function mc(e){e.sort(function(e,t){return s(e,t,0)?-1:1});for(var t=-1/0,n=1,r=0;r0?e.length:0),this.item=null,this.key=NaN,this},e.prototype.next=function(){return(this._step>0?this._idx=this._end)&&(this.item=this._list[this._idx],this.key=this._idx+=this._step,!0)},e})();function ul(){return[1/0,-1/0]}function dl(e,t){hl(t)&&(te[1]&&(e[1]=t))}function fl(e,t){hl(t)&&te[1]&&(e[1]=t)}function ml(e,t){gl(t[0],t[1])&&(t[0]e[1]&&(e[1]=t[1]))}function hl(e){return e!=null&&isFinite(e)}function gl(e,t){return hl(e)&&hl(t)&&e<=t}function _l(e){var t=e[1]-e[0];return isFinite(t)&&t>=0}function vl(e){gl(e[0],e[1])&&e[0]>e[1]&&(e[0]=e[1])}function yl(){var e=`__ec_once_`+bl++;return function(t,n){Z(t,e)||(t[e]=1,n())}}var bl=_c();function xl(e,t,n){var r=Es(),i=0;G(e,function(a){var o=t(a),s=r.get(o)||0;n&&n(a,s),!s&&!n&&(e[i++]=a),r.set(o,s+1)}),n||(e.length=i)}function Sl(e){return e.value+``}function Cl(e){return e+``}function wl(e,t){return X(t,!0)?e.seriesIndex+2:0}function Tl(e,t,n){var r=e.getData().count();return{progressiveRender:n.progressiveEnabled&&t.incrementalPrepareRender&&r>=n.threshold,large:e.get(`large`)&&r>=e.get(`largeThreshold`),modDataCount:e.get(`progressiveChunkMode`)===`mod`?e.getData().count():null}}function El(e){return{overallReset:e}}var Dl=`.`,Ol=`___EC__COMPONENT__CONTAINER___`,kl=`___EC__EXTENDED_CLASS___`;function Al(e){var t={main:``,sub:``};if(e){var n=e.split(Dl);t.main=n[0]||``,t.sub=n[1]||``}return t}function jl(e){_s(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(e),`componentType "`+e+`" illegal`)}function Ml(e){return!!(e&&e[kl])}function Nl(e,t){e.$constructor=e,e.extend=function(e){var t=this,n;return Pl(t)?n=function(e){U(t,e);function t(){return e.apply(this,arguments)||this}return t}(t):(n=function(){(e.$constructor||t).apply(this,arguments)},Jo(n,this)),W(n.prototype,e),n[kl]=!0,n.extend=this.extend,n.superCall=Rl,n.superApply=zl,n.superClass=t,n}}function Pl(e){return rs(e)&&/^class\s/.test(Function.prototype.toString.call(e))}function Fl(e,t){e.extend=t.extend}var Il=Math.round(Math.random()*10);function Ll(e){var t=[`__\0is_clz`,Il++].join(`_`);e.prototype[t]=!0,e.isInstance=function(e){return!!(e&&e[t])}}function Rl(e,t){var n=[...arguments].slice(2);return this.superClass.prototype[t].apply(e,n)}function zl(e,t,n){return this.superClass.prototype[t].apply(e,n)}function Bl(e){var t={};e.registerClass=function(e){var r=e.type||e.prototype.type;if(r){jl(r),e.prototype.type=r;var i=Al(r);if(!i.sub)t[i.main]=e;else if(i.sub!==Ol){var a=n(i);a[i.sub]=e}}return e},e.getClass=function(e,n,r){var i=t[e];if(i&&i[Ol]&&(i=n?i[n]:null),r&&!i)throw Error(n?`Component `+e+`.`+(n||``)+` is used but not imported.`:e+`.type should be specified.`);return i},e.getClassesByMainType=function(e){var n=Al(e),r=[],i=t[n.main];return i&&i[Ol]?G(i,function(e,t){t!==Ol&&r.push(e)}):r.push(i),r},e.hasClass=function(e){return!!t[Al(e).main]},e.getAllClassMainTypes=function(){var e=[];return G(t,function(t,n){e.push(n)}),e},e.hasSubTypes=function(e){var n=t[Al(e).main];return n&&n[Ol]};function n(e){var n=t[e.main];return(!n||!n[Ol])&&(n=t[e.main]={},n[Ol]=!0),n}}function Vl(e,t){for(var n=0;n=0||i&&qo(i,s)<0)){var c=n.getShallow(s,t);c!=null&&(a[e[o][0]]=c)}}return a}}var Hl=Vl([[`fill`,`color`],[`shadowBlur`],[`shadowOffsetX`],[`shadowOffsetY`],[`opacity`],[`shadowColor`]]),Ul=function(){function e(){}return e.prototype.getAreaStyle=function(e,t){return Hl(this,e,t)},e}(),Wl=function(){function e(e){this.value=e}return e}(),Gl=function(){function e(){this._len=0}return e.prototype.insert=function(e){var t=new Wl(e);return this.insertEntry(t),t},e.prototype.insertEntry=function(e){this.head?(this.tail.next=e,e.prev=this.tail,e.next=null,this.tail=e):this.head=this.tail=e,this._len++},e.prototype.remove=function(e){var t=e.prev,n=e.next;t?t.next=n:this.head=n,n?n.prev=t:this.tail=t,e.next=e.prev=null,this._len--},e.prototype.len=function(){return this._len},e.prototype.clear=function(){this.head=this.tail=null,this._len=0},e}(),Kl=function(){function e(e){this._list=new Gl,this._maxSize=10,this._map={},this._maxSize=e}return e.prototype.put=function(e,t){var n=this._list,r=this._map,i=null;if(r[e]==null){var a=n.len(),o=this._lastRemovedEntry;if(a>=this._maxSize&&a>0){var s=n.head;n.remove(s),delete r[s.key],i=s.value,this._lastRemovedEntry=s}o?o.value=t:o=new Wl(t),o.key=e,n.insertEntry(o),r[e]=o}return i},e.prototype.get=function(e){var t=this._map[e],n=this._list;if(t!=null)return t!==n.tail&&(n.remove(t),n.insertEntry(t)),t.value},e.prototype.clear=function(){this._list.clear(),this._map={}},e.prototype.len=function(){return this._list.len()},e}(),ql=new Kl(50);function Jl(e){if(typeof e==`string`){var t=ql.get(e);return t&&t.image}return e}function Yl(e,t,n,r,i){if(!e)return t;if(typeof e==`string`){if(t&&t.__zrImageSrc===e||!n)return t;var a=ql.get(e),o={hostEl:n,cb:r,cbPayload:i};return a?(t=a.image,!Zl(t)&&a.pending.push(o)):(t=Eo.loadImage(e,Xl,Xl),t.__zrImageSrc=e,ql.put(e,t.__cachedImgObj={image:t,pending:[o]})),t}return e}function Xl(){var e=this.__cachedImgObj;this.onload=this.onerror=this.__cachedImgObj=null;for(var t=0;tu||d>f||p>m||h>g)return!1;var _=!(u=e.x&&t<=e.x+e.width&&n>=e.y&&n<=e.y+e.height},e.prototype.contain=function(t,n){return e.contain(this,t,n)},e.prototype.clone=function(){return new e(this.x,this.y,this.width,this.height)},e.prototype.copy=function(e){Vu(this,e)},e.prototype.plain=function(){return{x:this.x,y:this.y,width:this.width,height:this.height}},e.prototype.isFinite=function(){return isFinite(this.x)&&isFinite(this.y)&&isFinite(this.width)&&isFinite(this.height)},e.prototype.isZero=function(){return this.width===0||this.height===0},e.create=function(t){return new e(t?t.x:0,t?t.y:0,t?t.width:0,t?t.height:0)},e.copy=function(e,t){return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e},e.applyTransform=function(e,t,n){if(!n){e!==t&&Vu(e,t);return}if(n[1]<1e-5&&n[1]>-1e-5&&n[2]<1e-5&&n[2]>-1e-5){var r=n[0],i=n[3],a=n[4],o=n[5];e.x=t.x*r+a,e.y=t.y*i+o,e.width=t.width*r,e.height=t.height*i,e.width<0&&(e.x+=e.width,e.width=-e.width),e.height<0&&(e.y+=e.height,e.height=-e.height);return}Au.x=Mu.x=t.x,Au.y=Nu.y=t.y,ju.x=Nu.x=t.x+t.width,ju.y=Mu.y=t.y+t.height,Au.transform(n),Nu.transform(n),ju.transform(n),Mu.transform(n),e.x=Tu(Au.x,ju.x,Mu.x,Nu.x),e.y=Tu(Au.y,ju.y,Mu.y,Nu.y);var s=Eu(Au.x,ju.x,Mu.x,Nu.x),c=Eu(Au.y,ju.y,Mu.y,Nu.y);e.width=s-e.x,e.height=c-e.y},e.calculateTransform=function(e,t,n){var r=n.width/t.width,i=n.height/t.height;return e=$l(e||[]),nu(e,e,lu(qu,-t.x,-t.y)),iu(e,e,lu(qu,r,i)),nu(e,e,lu(qu,n.x,n.y)),e},e}(),zu=Ru.create,Bu=Ru.set,Vu=Ru.copy,Hu=Ru.calculateTransform,Uu=Ru.applyTransform,Wu=Ru.contain,Gu=new Ru(0,0,0,0),Ku=new Ru(0,0,0,0),qu=[];function Ju(e,t,n,r,i,a,o,s){var c=Du(t-n),l=Du(r-e),u=Tu(c,l),d=Ou[i],f=Ou[1-i],p=ku[i];t=l||!Pu.bidirectional)&&(Fu[d]=-l,Fu[f]=0,Pu.useDir&&Pu.calcDirMTV())))}function Yu(){var e=0,t=new wu,n=new wu,r={minTv:new wu,maxTv:new wu,useDir:!1,dirMinTv:new wu,touchThreshold:0,bidirectional:!0,negativeSize:!1,reset:function(i,a){r.touchThreshold=0,i&&i.touchThreshold!=null&&(r.touchThreshold=Eu(0,i.touchThreshold)),r.negativeSize=!1,a&&(r.minTv.set(1/0,1/0),r.maxTv.set(0,0),r.useDir=!1,i&&i.direction!=null&&(r.useDir=!0,r.dirMinTv.copy(r.minTv),n.copy(r.minTv),e=i.direction,r.bidirectional=i.bidirectional==null||!!i.bidirectional,r.bidirectional||t.set(Math.cos(e),Math.sin(e))))},calcDirMTV:function(){var a=r.minTv,o=r.dirMinTv,s=a.y*a.y+a.x*a.x,c=Math.sin(e),l=Math.cos(e),u=c*a.y+l*a.x;if(i(u)){i(a.x)&&i(a.y)&&o.set(0,0);return}if(n.x=s*l/u,n.y=s*c/u,i(n.x)&&i(n.y)){o.set(0,0);return}(r.bidirectional||t.dot(n)>0)&&n.len()=ed)){e||=`12px sans-serif`;for(var t=[],n=+new Date,r=0;r<=127;r++)t[r]=Eo.measureText(String.fromCharCode(r),e).width;var i=+new Date-n;return i>16?$u=ed:i>2&&$u++,t}}var $u=0,ed=5;function td(e,t){return e.asciiWidthMapTried||=(e.asciiWidthMap=Qu(e.font),!0),0<=t&&t<=127?e.asciiWidthMap==null?e.asciiCharWidth:e.asciiWidthMap[t]:e.stWideCharWidth}function nd(e,t){var n=e.strWidthCache,r=n.get(t);return r??(r=Eo.measureText(t,e.font).width,n.put(t,r)),r}function rd(e,t,n,r){var i=nd(Xu(t),e),a=sd(t);return new Ru(ad(0,i,n),od(0,a,r),i,a)}function id(e,t,n,r){var i=((e||``)+``).split(` `);if(i.length===1)return rd(i[0],t,n,r);for(var a=new Ru(0,0,0,0),o=0;o=0?parseFloat(e)/100*t:parseFloat(e):e}function ld(e,t,n){var r=t.position||`inside`,i=t.distance==null?5:t.distance,a=n.height,o=n.width,s=a/2,c=n.x,l=n.y,u=`left`,d=`top`;if(r instanceof Array)c+=cd(r[0],n.width),l+=cd(r[1],n.height),u=null,d=null;else switch(r){case`left`:c-=i,l+=s,u=`right`,d=`middle`;break;case`right`:c+=i+o,l+=s,d=`middle`;break;case`top`:c+=o/2,l-=i,u=`center`,d=`bottom`;break;case`bottom`:c+=o/2,l+=a+i,u=`center`;break;case`inside`:c+=o/2,l+=s,u=`center`,d=`middle`;break;case`insideLeft`:c+=i,l+=s,d=`middle`;break;case`insideRight`:c+=o-i,l+=s,u=`right`,d=`middle`;break;case`insideTop`:c+=o/2,l+=i,u=`center`;break;case`insideBottom`:c+=o/2,l+=a-i,u=`center`,d=`bottom`;break;case`insideTopLeft`:c+=i,l+=i;break;case`insideTopRight`:c+=o-i,l+=i,u=`right`;break;case`insideBottomLeft`:c+=i,l+=a-i,d=`bottom`;break;case`insideBottomRight`:c+=o-i,l+=a-i,u=`right`,d=`bottom`}return e||={},e.x=c,e.y=l,e.align=u,e.verticalAlign=d,e}var ud=/\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;function dd(e,t,n,r,i,a){if(!n){e.text=``,e.isTruncated=!1;return}var o=(t+``).split(` `);a=fd(n,r,i,a);for(var s=!1,c={},l=0,u=o.length;l=s;l++)c-=s;var u=nd(o,n);return u>c&&(n=``,u=0),c=e-u,i.ellipsis=n,i.ellipsisWidth=u,i.contentWidth=c,i.containerWidth=e,i}function pd(e,t,n){var r=n.containerWidth,i=n.contentWidth,a=n.fontMeasureInfo;if(!r){e.textLine=``,e.isTruncated=!1;return}var o=nd(a,t);if(o<=r){e.textLine=t,e.isTruncated=!1;return}for(var s=0;;s++){if(o<=i||s>=n.maxIterations){t+=n.ellipsis;break}var c=s===0?md(t,i,a):o>0?Math.floor(t.length*i/o):0;t=t.substr(0,c),o=nd(a,t)}t===``&&(t=n.placeholder),e.textLine=t,e.isTruncated=!0}function md(e,t,n){for(var r=0,i=0,a=e.length;ig&&p){var y=Math.floor(g/f);m||=_.length>y,_=_.slice(0,y),v=_.length*f}if(i&&u&&h!=null)for(var b=fd(h,l,t.ellipsis,{minChar:t.truncateMinChar,placeholder:t.placeholder}),x={},S=0;S<_.length;S++)pd(x,_[S],b),_[S]=x.textLine,m||=x.isTruncated;for(var C=g,w=0,T=Xu(l),S=0;S<_.length;S++)w=Math.max(nd(T,_[S]),w);h??=w;var E=h;return C+=c,E+=s,{lines:_,height:g,outerWidth:E,outerHeight:C,lineHeight:f,calculatedLineHeight:d,contentWidth:w,contentHeight:v,width:h,isTruncated:m}}var gd=function(){function e(){}return e}(),_d=function(){function e(e){this.tokens=[],e&&(this.tokens=e)}return e}(),vd=function(){function e(){this.width=0,this.height=0,this.contentWidth=0,this.contentHeight=0,this.outerWidth=0,this.outerHeight=0,this.lines=[],this.isTruncated=!1}return e}();function yd(e,t,n,r,i){var a=new vd,o=Od(e);if(!o)return a;var s=t.padding,c=s?s[1]+s[3]:0,l=s?s[0]+s[2]:0,u=t.width;u==null&&n!=null&&(u=n-c);var d=t.height;d==null&&r!=null&&(d=r-l);for(var f=t.overflow,p=(f===`break`||f===`breakAll`)&&u!=null?{width:u,accumWidth:0,breakAll:f===`breakAll`}:null,m=ud.lastIndex=0,h;(h=ud.exec(o))!=null;){var g=h.index;g>m&&bd(a,o.substring(m,g),t,p),bd(a,h[2],t,p,h[1]),m=ud.lastIndex}md){var F=a.lines.length;O>0?(T.tokens=T.tokens.slice(0,O),C(T,D,E),a.lines=a.lines.slice(0,w+1)):a.lines=a.lines.slice(0,w),a.isTruncated=a.isTruncated||a.lines.length0&&m+r.accumWidth>r.width&&(u=t.split(` +`):[],v=_.length*f;if(g??=v,v>g&&p){var y=Math.floor(g/f);m||=_.length>y,_=_.slice(0,y),v=_.length*f}if(i&&u&&h!=null)for(var b=fd(h,l,t.ellipsis,{minChar:t.truncateMinChar,placeholder:t.placeholder}),x={},S=0;S<_.length;S++)pd(x,_[S],b),_[S]=x.textLine,m||=x.isTruncated;for(var C=g,w=0,T=Xu(l),S=0;S<_.length;S++)w=Math.max(nd(T,_[S]),w);h??=w;var E=h;return C+=c,E+=s,{lines:_,height:g,outerWidth:E,outerHeight:C,lineHeight:f,calculatedLineHeight:d,contentWidth:w,contentHeight:v,width:h,isTruncated:m}}var gd=function(){function e(){}return e}(),_d=function(){function e(e){this.tokens=[],e&&(this.tokens=e)}return e}(),vd=function(){function e(){this.width=0,this.height=0,this.contentWidth=0,this.contentHeight=0,this.outerWidth=0,this.outerHeight=0,this.lines=[],this.isTruncated=!1}return e}();function yd(e,t,n,r,i){var a=new vd,o=Od(e);if(!o)return a;var s=t.padding,c=s?s[1]+s[3]:0,l=s?s[0]+s[2]:0,u=t.width;u==null&&n!=null&&(u=n-c);var d=t.height;d==null&&r!=null&&(d=r-l);for(var f=t.overflow,p=(f===`break`||f===`breakAll`)&&u!=null?{width:u,accumWidth:0,breakAll:f===`breakAll`}:null,m=ud.lastIndex=0,h;(h=ud.exec(o))!=null;){var g=h.index;g>m&&bd(a,o.substring(m,g),t,p),bd(a,h[2],t,p,h[1]),m=ud.lastIndex}md){var F=a.lines.length;O>0?(T.tokens=T.tokens.slice(0,O),C(T,D,E),a.lines=a.lines.slice(0,w+1)):a.lines=a.lines.slice(0,w),a.isTruncated=a.isTruncated||a.lines.length0&&m+r.accumWidth>r.width&&(u=t.split(` `),l=!0),r.accumWidth=m}else{var h=wd(t,c,r.width,r.breakAll,r.accumWidth);r.accumWidth=h.accumWidth+p,d=h.linesWidths,u=h.lines}}u||=t.split(` `);for(var g=Xu(c),_=0;_=32&&t<=591||t>=880&&t<=4351||t>=4608&&t<=5119||t>=7680&&t<=8303}var Sd=Zo(`,&?/;] `.split(``),function(e,t){return e[t]=!0,e},{});function Cd(e){return!xd(e)||!!Sd[e]}function wd(e,t,n,r,i){for(var a=[],o=[],s=``,c=``,l=0,u=0,d=Xu(t),f=0;fn:i+u+m>n){u?(s||c)&&(h?(s||(s=c,c=``,l=0,u=l),a.push(s),o.push(u-l),c+=p,l+=m,s=``,u=l):(c&&(s+=c,c=``,l=0),a.push(s),o.push(u),s=p,u=m)):h?(a.push(c),o.push(l),c=p,l=m):(a.push(p),o.push(m));continue}u+=m,h?(c+=p,l+=m):(c&&(s+=c,c=``,l=0),s+=p)}return c&&(s+=c),s&&(a.push(s),o.push(u)),a.length===1&&(u+=i),{accumWidth:u,lines:a,linesWidths:o}}function Td(e,t,n,r,i,a){if(e.baseX=n,e.baseY=r,e.outerWidth=e.outerHeight=null,t){var o=t.width*2,s=t.height*2;Ru.set(Ed,ad(n,o,i),od(r,s,a),o,s),Ru.intersect(t,Ed,null,Dd);var c=Dd.outIntersectRect;e.outerWidth=c.width,e.outerHeight=c.height,e.baseX=ad(c.x,c.width,i,!0),e.baseY=od(c.y,c.height,a,!0)}}var Ed=new Ru(0,0,0,0),Dd={outIntersectRect:{},clamp:!0};function Od(e){return e==null?e=``:e+=``}function kd(e){var t=Od(e.text),n=e.font;return Ad(e,nd(Xu(n),t),sd(n),null)}function Ad(e,t,n,r){var i=new Ru(ad(e.x||0,t,e.textAlign),od(e.y||0,n,e.textBaseline),t,n),a=r??(jd(e)?e.lineWidth:0);return a>0&&(i.x-=a/2,i.y-=a/2,i.width+=a,i.height+=a),i}function jd(e){var t=e.stroke;return t!=null&&t!==`none`&&e.lineWidth>0}var Md=$l,Nd=5e-5;function Pd(e){return e>Nd||e<-Nd}var Fd=[],Id=[],Ld=Ql(),Rd=Math.abs,zd=function(){function e(){}return e.prototype.getLocalTransform=function(e){return Bd(this,e)},e.prototype.setPosition=function(e){this.x=e[0],this.y=e[1]},e.prototype.setScale=function(e){this.scaleX=e[0],this.scaleY=e[1]},e.prototype.setSkew=function(e){this.skewX=e[0],this.skewY=e[1]},e.prototype.setOrigin=function(e){this.originX=e[0],this.originY=e[1]},e.prototype.needLocalTransform=function(){return Pd(this.rotation)||Pd(this.x)||Pd(this.y)||Pd(this.scaleX-1)||Pd(this.scaleY-1)||Pd(this.skewX)||Pd(this.skewY)},e.prototype.updateTransform=function(){var e=this.parent&&this.parent.transform,t=this.needLocalTransform(),n=this.transform;if(!(t||e)){n&&(Md(n),this.invTransform=null);return}n||=Ql(),t?this.getLocalTransform(n):Md(n),e&&(t?tu(n,e,n):eu(n,e)),this.transform=n,this._resolveGlobalScaleRatio(n),this.invTransform=this.invTransform||Ql(),au(this.invTransform,n)},e.prototype._resolveGlobalScaleRatio=function(e){var t=this.globalScaleRatio;if(t!=null&&t!==1){this.getGlobalScale(Fd);var n=Fd[0]<0?-1:1,r=Fd[1]<0?-1:1,i=((Fd[0]-n)*t+n)/Fd[0]||0,a=((Fd[1]-r)*t+r)/Fd[1]||0;e[0]*=i,e[1]*=i,e[2]*=a,e[3]*=a}},e.prototype.getComputedTransform=function(){for(var e=this,t=[];e;)t.push(e),e=e.parent;for(;e=t.pop();)e.updateTransform();return this.transform},e.prototype.setLocalTransform=function(e){if(e){var t=e[0]*e[0]+e[1]*e[1],n=e[2]*e[2]+e[3]*e[3],r=Math.atan2(e[1],e[0]),i=Math.PI/2+r-Math.atan2(e[3],e[2]);n=Math.sqrt(n)*Math.cos(i),t=Math.sqrt(t),this.skewX=i,this.skewY=0,this.rotation=-r,this.x=+e[4],this.y=+e[5],this.scaleX=t,this.scaleY=n,this.originX=0,this.originY=0}},e.prototype.decomposeTransform=function(){if(this.transform){var e=this.parent,t=this.transform;e&&e.transform&&(e.invTransform=e.invTransform||Ql(),tu(Id,e.invTransform,t),t=Id);var n=this.originX,r=this.originY;(n||r)&&(Ld[4]=n,Ld[5]=r,tu(Id,t,Ld),Id[4]-=n,Id[5]-=r,t=Id),this.setLocalTransform(t)}},e.prototype.getGlobalScale=function(e){var t=this.transform;return e||=[],t?(e[0]=Math.sqrt(t[0]*t[0]+t[1]*t[1]),e[1]=Math.sqrt(t[2]*t[2]+t[3]*t[3]),t[0]<0&&(e[0]=-e[0]),t[3]<0&&(e[1]=-e[1]),e):(e[0]=1,e[1]=1,e)},e.prototype.transformCoordToLocal=function(e,t){var n=[e,t],r=this.invTransform;return r&&xu(n,n,r),n},e.prototype.transformCoordToGlobal=function(e,t){var n=[e,t],r=this.transform;return r&&xu(n,n,r),n},e.prototype.getLineScale=function(){var e=this.transform;return e&&Rd(e[0]-1)>1e-10&&Rd(e[3]-1)>1e-10?Math.sqrt(Rd(e[0]*e[3]-e[2]*e[1])):1},e.prototype.copyTransform=function(e){Ud(this,e)},e.getLocalTransform=function(e,t){t||=[];var n=e.originX||0,r=e.originY||0,i=e.scaleX,a=e.scaleY,o=e.anchorX,s=e.anchorY,c=e.rotation||0,l=e.x,u=e.y,d=e.skewX?Math.tan(e.skewX):0,f=e.skewY?Math.tan(-e.skewY):0;if(n||r||o||s){var p=n+o,m=r+s;t[4]=-p*i-d*m*a,t[5]=-m*a-f*p*i}else t[4]=t[5]=0;return t[0]=i,t[3]=a,t[1]=f*i,t[2]=d*a,c&&ru(t,t,c),t[4]+=n+l,t[5]+=r+u,t},e.initDefaultProps=(function(){var t=e.prototype;t.scaleX=t.scaleY=t.globalScaleRatio=1,t.x=t.y=t.originX=t.originY=t.skewX=t.skewY=t.rotation=t.anchorX=t.anchorY=0})(),e}(),Bd=zd.getLocalTransform;function Vd(){return new zd}var Hd=[`x`,`y`,`originX`,`originY`,`anchorX`,`anchorY`,`rotation`,`scaleX`,`scaleY`,`skewX`,`skewY`];function Ud(e,t){return Go(e,t,Hd)}var Wd={linear:function(e){return e},quadraticIn:function(e){return e*e},quadraticOut:function(e){return e*(2-e)},quadraticInOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)},cubicIn:function(e){return e*e*e},cubicOut:function(e){return--e*e*e+1},cubicInOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)},quarticIn:function(e){return e*e*e*e},quarticOut:function(e){return 1- --e*e*e*e},quarticInOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)},quinticIn:function(e){return e*e*e*e*e},quinticOut:function(e){return--e*e*e*e*e+1},quinticInOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)},sinusoidalIn:function(e){return 1-Math.cos(e*Math.PI/2)},sinusoidalOut:function(e){return Math.sin(e*Math.PI/2)},sinusoidalInOut:function(e){return .5*(1-Math.cos(Math.PI*e))},exponentialIn:function(e){return e===0?0:1024**(e-1)},exponentialOut:function(e){return e===1?1:1-2**(-10*e)},exponentialInOut:function(e){return e===0?0:e===1?1:(e*=2)<1?.5*1024**(e-1):.5*(-(2**(-10*(e-1)))+2)},circularIn:function(e){return 1-Math.sqrt(1-e*e)},circularOut:function(e){return Math.sqrt(1- --e*e)},circularInOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)},elasticIn:function(e){var t,n=.1,r=.4;return e===0?0:e===1?1:(!n||n<1?(n=1,t=r/4):t=r*Math.asin(1/n)/(2*Math.PI),-(n*2**(10*--e)*Math.sin((e-t)*(2*Math.PI)/r)))},elasticOut:function(e){var t,n=.1,r=.4;return e===0?0:e===1?1:(!n||n<1?(n=1,t=r/4):t=r*Math.asin(1/n)/(2*Math.PI),n*2**(-10*e)*Math.sin((e-t)*(2*Math.PI)/r)+1)},elasticInOut:function(e){var t,n=.1,r=.4;return e===0?0:e===1?1:(!n||n<1?(n=1,t=r/4):t=r*Math.asin(1/n)/(2*Math.PI),(e*=2)<1?-.5*(n*2**(10*--e)*Math.sin((e-t)*(2*Math.PI)/r)):n*2**(-10*--e)*Math.sin((e-t)*(2*Math.PI)/r)*.5+1)},backIn:function(e){var t=1.70158;return e*e*((t+1)*e-t)},backOut:function(e){var t=1.70158;return--e*e*((t+1)*e+t)+1},backInOut:function(e){var t=2.5949095;return(e*=2)<1?.5*(e*e*((t+1)*e-t)):.5*((e-=2)*e*((t+1)*e+t)+2)},bounceIn:function(e){return 1-Wd.bounceOut(1-e)},bounceOut:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},bounceInOut:function(e){return e<.5?Wd.bounceIn(e*2)*.5:Wd.bounceOut(e*2-1)*.5+.5}},Gd=Math.pow,Kd=Math.sqrt,qd=1e-8,Jd=1e-4,Yd=Kd(3),Xd=1/3,Zd=ou(),Qd=ou(),$d=ou();function ef(e){return e>-qd&&eqd||e<-qd}function nf(e,t,n,r,i){var a=1-i;return a*a*(a*e+3*i*t)+i*i*(i*r+3*a*n)}function rf(e,t,n,r,i){var a=1-i;return 3*(((t-e)*a+2*(n-t)*i)*a+(r-n)*i*i)}function af(e,t,n,r,i,a){var o=r+3*(t-n)-e,s=3*(n-t*2+e),c=3*(t-e),l=e-i,u=s*s-3*o*c,d=s*c-9*o*l,f=c*c-3*s*l,p=0;if(ef(u)&&ef(d)){if(ef(s))a[0]=0;else{var m=-c/s;m>=0&&m<=1&&(a[p++]=m)}}else{var h=d*d-4*u*f;if(ef(h)){var g=d/u,m=-s/o+g,_=-g/2;m>=0&&m<=1&&(a[p++]=m),_>=0&&_<=1&&(a[p++]=_)}else if(h>0){var v=Kd(h),y=u*s+1.5*o*(-d+v),b=u*s+1.5*o*(-d-v);y=y<0?-Gd(-y,Xd):Gd(y,Xd),b=b<0?-Gd(-b,Xd):Gd(b,Xd);var m=(-s-(y+b))/(3*o);m>=0&&m<=1&&(a[p++]=m)}else{var x=(2*u*s-3*o*d)/(2*Kd(u*u*u)),S=Math.acos(x)/3,C=Kd(u),w=Math.cos(S),m=(-s-2*C*w)/(3*o),_=(-s+C*(w+Yd*Math.sin(S)))/(3*o),T=(-s+C*(w-Yd*Math.sin(S)))/(3*o);m>=0&&m<=1&&(a[p++]=m),_>=0&&_<=1&&(a[p++]=_),T>=0&&T<=1&&(a[p++]=T)}}return p}function of(e,t,n,r,i){var a=6*n-12*t+6*e,o=9*t+3*r-3*e-9*n,s=3*t-3*e,c=0;if(ef(o)){if(tf(a)){var l=-s/a;l>=0&&l<=1&&(i[c++]=l)}}else{var u=a*a-4*o*s;if(ef(u))i[0]=-a/(2*o);else if(u>0){var d=Kd(u),l=(-a+d)/(2*o),f=(-a-d)/(2*o);l>=0&&l<=1&&(i[c++]=l),f>=0&&f<=1&&(i[c++]=f)}}return c}function sf(e,t,n,r,i,a){var o=(t-e)*i+e,s=(n-t)*i+t,c=(r-n)*i+n,l=(s-o)*i+o,u=(c-s)*i+s,d=(u-l)*i+l;a[0]=e,a[1]=o,a[2]=l,a[3]=d,a[4]=d,a[5]=u,a[6]=c,a[7]=r}function cf(e,t,n,r,i,a,o,s,c,l,u){var d,f=.005,p=1/0,m,h,g,_;Zd[0]=c,Zd[1]=l;for(var v=0;v<1;v+=.05)Qd[0]=nf(e,n,i,o,v),Qd[1]=nf(t,r,a,s,v),g=yu(Zd,Qd),g=0&&g=0&&l<=1&&(i[c++]=l)}}else{var u=o*o-4*a*s;if(ef(u)){var l=-o/(2*a);l>=0&&l<=1&&(i[c++]=l)}else if(u>0){var d=Kd(u),l=(-o+d)/(2*a),f=(-o-d)/(2*a);l>=0&&l<=1&&(i[c++]=l),f>=0&&f<=1&&(i[c++]=f)}}return c}function pf(e,t,n){var r=e+n-2*t;return r===0?.5:(e-t)/r}function mf(e,t,n,r,i){var a=(t-e)*r+e,o=(n-t)*r+t,s=(o-a)*r+a;i[0]=e,i[1]=a,i[2]=s,i[3]=s,i[4]=o,i[5]=n}function hf(e,t,n,r,i,a,o,s,c){var l,u=.005,d=1/0;Zd[0]=o,Zd[1]=s;for(var f=0;f<1;f+=.05){Qd[0]=uf(e,n,i,f),Qd[1]=uf(t,r,a,f);var p=yu(Zd,Qd);p=0&&p=1?1:af(0,r,a,1,e,s)&&nf(0,i,o,1,s[0])}}}var yf=function(){function e(e){this._inited=!1,this._startTime=0,this._pausedTime=0,this._paused=!1,this._life=e.life||1e3,this._delay=e.delay||0,this.loop=e.loop||!1,this.onframe=e.onframe||As,this.ondestroy=e.ondestroy||As,this.onrestart=e.onrestart||As,e.easing&&this.setEasing(e.easing)}return e.prototype.step=function(e,t){if(this._inited||=(this._startTime=e+this._delay,!0),this._paused){this._pausedTime+=t;return}var n=this._life,r=e-this._startTime-this._pausedTime,i=r/n;i<0&&(i=0),i=Math.min(i,1);var a=this.easingFunc,o=a?a(i):i;if(this.onframe(o),i===1){if(this.loop){var s=r%n;this._startTime=e-s,this._pausedTime=0,this.onrestart()}else return!0}return!1},e.prototype.pause=function(){this._paused=!0},e.prototype.resume=function(){this._paused=!1},e.prototype.setEasing=function(e){this.easing=e,this.easingFunc=rs(e)?e:Wd[e]||vf(e)},e}(),bf={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function xf(e){return e=Math.round(e),e<0?0:e>255?255:e}function Sf(e){return e=Math.round(e),e<0?0:e>360?360:e}function Cf(e){return e<0?0:e>1?1:e}function wf(e){var t=e;return t.length&&t.charAt(t.length-1)===`%`?xf(parseFloat(t)/100*255):xf(parseInt(t,10))}function Tf(e){var t=e;return t.length&&t.charAt(t.length-1)===`%`?Cf(parseFloat(t)/100):Cf(parseFloat(t))}function Ef(e,t,n){return n<0?n+=1:n>1&&--n,n*6<1?e+(t-e)*n*6:n*2<1?t:n*3<2?e+(t-e)*(2/3-n)*6:e}function Df(e,t,n){return e+(t-e)*n}function Of(e,t,n,r,i){return e[0]=t,e[1]=n,e[2]=r,e[3]=i,e}function kf(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}var Af=new Kl(20),jf=null;function Mf(e,t){jf&&kf(jf,t),jf=Af.put(e,jf||t.slice())}function Nf(e,t){if(e){t||=[];var n=Af.get(e);if(n)return kf(t,n);e+=``;var r=e.replace(/ /g,``).toLowerCase();if(r in bf)return kf(t,bf[r]),Mf(e,t),t;var i=r.length;if(r.charAt(0)===`#`){if(i===4||i===5){var a=parseInt(r.slice(1,4),16);if(!(a>=0&&a<=4095)){Of(t,0,0,0,1);return}return Of(t,(a&3840)>>4|(a&3840)>>8,a&240|(a&240)>>4,a&15|(a&15)<<4,i===5?parseInt(r.slice(4),16)/15:1),Mf(e,t),t}if(i===7||i===9){var a=parseInt(r.slice(1,7),16);if(!(a>=0&&a<=16777215)){Of(t,0,0,0,1);return}return Of(t,(a&16711680)>>16,(a&65280)>>8,a&255,i===9?parseInt(r.slice(7),16)/255:1),Mf(e,t),t}return}var o=r.indexOf(`(`),s=r.indexOf(`)`);if(o!==-1&&s+1===i){var c=r.substr(0,o),l=r.substr(o+1,s-(o+1)).split(`,`),u=1;switch(c){case`rgba`:if(l.length!==4)return l.length===3?Of(t,+l[0],+l[1],+l[2],1):Of(t,0,0,0,1);u=Tf(l.pop());case`rgb`:if(l.length>=3)return Of(t,wf(l[0]),wf(l[1]),wf(l[2]),l.length===3?u:Tf(l[3])),Mf(e,t),t;Of(t,0,0,0,1);return;case`hsla`:if(l.length!==4){Of(t,0,0,0,1);return}return l[3]=Tf(l[3]),Pf(l,t),Mf(e,t),t;case`hsl`:if(l.length!==3){Of(t,0,0,0,1);return}return Pf(l,t),Mf(e,t),t;default:return}}Of(t,0,0,0,1)}}function Pf(e,t){var n=(parseFloat(e[0])%360+360)%360/360,r=Tf(e[1]),i=Tf(e[2]),a=i<=.5?i*(r+1):i+r-i*r,o=i*2-a;return t||=[],Of(t,xf(Ef(o,a,n+1/3)*255),xf(Ef(o,a,n)*255),xf(Ef(o,a,n-1/3)*255),1),e.length===4&&(t[3]=e[3]),t}function Ff(e){if(e){var t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s=(a+i)/2,c,l;if(o===0)c=0,l=0;else{l=s<.5?o/(a+i):o/(2-a-i);var u=((a-t)/6+o/2)/o,d=((a-n)/6+o/2)/o,f=((a-r)/6+o/2)/o;t===a?c=f-d:n===a?c=1/3+u-f:r===a&&(c=2/3+d-u),c<0&&(c+=1),c>1&&--c}var p=[c*360,l,s];return e[3]!=null&&p.push(e[3]),p}}function If(e,t){var n=Nf(e);if(n){for(var r=0;r<3;r++)t<0?n[r]=n[r]*(1-t)|0:n[r]=(255-n[r])*t+n[r]|0,n[r]>255?n[r]=255:n[r]<0&&(n[r]=0);return Vf(n,n.length===4?`rgba`:`rgb`)}}function Lf(e,t,n){if(t&&t.length&&e>=0&&e<=1){n||=[];var r=e*(t.length-1),i=Math.floor(r),a=Math.ceil(r),o=t[i],s=t[a],c=r-i;return n[0]=xf(Df(o[0],s[0],c)),n[1]=xf(Df(o[1],s[1],c)),n[2]=xf(Df(o[2],s[2],c)),n[3]=Cf(Df(o[3],s[3],c)),n}}function Rf(e,t,n){if(t&&t.length&&e>=0&&e<=1){var r=e*(t.length-1),i=Math.floor(r),a=Math.ceil(r),o=Nf(t[i]),s=Nf(t[a]),c=r-i,l=Vf([xf(Df(o[0],s[0],c)),xf(Df(o[1],s[1],c)),xf(Df(o[2],s[2],c)),Cf(Df(o[3],s[3],c))],`rgba`);return n?{color:l,leftIndex:i,rightIndex:a,value:r}:l}}function zf(e,t,n,r){var i=Nf(e);if(e)return i=Ff(i),t!=null&&(i[0]=Sf(rs(t)?t(i[0]):t)),n!=null&&(i[1]=Tf(rs(n)?n(i[1]):n)),r!=null&&(i[2]=Tf(rs(r)?r(i[2]):r)),Vf(Pf(i),`rgba`)}function Bf(e,t){var n=Nf(e);if(n&&t!=null)return n[3]=Cf(t),Vf(n,`rgba`)}function Vf(e,t){if(e&&e.length){var n=e[0]+`,`+e[1]+`,`+e[2];return(t===`rgba`||t===`hsva`||t===`hsla`)&&(n+=`,`+e[3]),t+`(`+n+`)`}}function Hf(e,t){var n=Nf(e);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*t:0}var Uf=new Kl(100);function Wf(e){if(Y(e)){var t=Uf.get(e);return t||(t=If(e,-.1),Uf.put(e,t)),t}if(us(e)){var n=W({},e);return n.colorStops=K(e.colorStops,function(e){return{offset:e.offset,color:If(e.color,-.1)}}),n}return e}function Gf(e){return e.type===`linear`}function Kf(e){return e.type===`radial`}(function(){return typeof Buffer<`u`&&typeof Buffer.from==`function`?function(e){return Buffer.from(e).toString(`base64`)}:typeof btoa==`function`&&typeof unescape==`function`&&typeof encodeURIComponent==`function`?function(e){return btoa(unescape(encodeURIComponent(e)))}:function(e){return null}})();var qf=Array.prototype.slice;function Jf(e,t,n){return(t-e)*n+e}function Yf(e,t,n,r){for(var i=t.length,a=0;ar?t:e,a=Math.min(n,r),o=i[a-1]||{color:[0,0,0,0],offset:0},s=a;so)r.length=o;else for(var s=a;s=1},e.prototype.getAdditiveTrack=function(){return this._additiveTrack},e.prototype.addKeyframe=function(e,t,n){this._needsSort=!0;var r=this.keyframes,i=r.length,a=!1,o=up,s=t;if(Xo(t)){var c=rp(t);o=c,(c===1&&!as(t[0])||c===2&&!as(t[0][0]))&&(a=!0)}else if(as(t)&&!fs(t))o=ip;else if(Y(t)){if(!isNaN(+t))o=ip;else{var l=Nf(t);l&&(s=l,o=sp)}}else if(us(t)){var u=W({},s);u.colorStops=K(t.colorStops,function(e){return{offset:e.offset,color:Nf(e.color)}}),Gf(t)?o=cp:Kf(t)&&(o=lp),s=u}i===0?this.valType=o:(o!==this.valType||o===up)&&(a=!0),this.discrete=this.discrete||a;var d={time:e,value:s,rawValue:t,percent:0};return n&&(d.easing=n,d.easingFunc=rs(n)?n:Wd[n]||vf(n)),r.push(d),d},e.prototype.prepare=function(e,t){var n=this.keyframes;this._needsSort&&n.sort(function(e,t){return e.time-t.time});for(var r=this.valType,i=n.length,a=n[i-1],o=this.discrete,s=fp(r),c=dp(r),l=0;l=0&&!(a[l].percent<=t);l--);l=d(l,o-2)}else{for(l=u;lt);l++);l=d(l-1,o-2)}p=a[l+1],f=a[l]}if(f&&p){this._lastFr=l,this._lastFrP=t;var m=p.percent-f.percent,h=m===0?1:d((t-f.percent)/m,1);p.easingFunc&&(h=p.easingFunc(h));var g=n?this._additiveValue:c?pp:e[s];if((fp(i)||c)&&!g&&(g=this._additiveValue=[]),this.discrete)e[s]=h<1?f.rawValue:p.rawValue;else if(fp(i))i===ap?Yf(g,f[r],p[r],h):Xf(g,f[r],p[r],h);else if(dp(i)){var _=f[r],v=p[r],y=i===cp;e[s]={type:y?`linear`:`radial`,x:Jf(_.x,v.x,h),y:Jf(_.y,v.y,h),colorStops:K(_.colorStops,function(e,t){var n=v.colorStops[t];return{offset:Jf(e.offset,n.offset,h),color:np(Yf([],e.color,n.color,h))}}),global:v.global},y?(e[s].x2=Jf(_.x2,v.x2,h),e[s].y2=Jf(_.y2,v.y2,h)):e[s].r=Jf(_.r,v.r,h)}else if(c)Yf(g,f[r],p[r],h),n||(e[s]=np(g));else{var b=Jf(f[r],p[r],h);n?this._additiveValue=b:e[s]=b}n&&this._addToTarget(e)}}},e.prototype._addToTarget=function(e){var t=this.valType,n=this.propName,r=this._additiveValue;t===ip?e[n]=e[n]+r:t===sp?(Nf(e[n],pp),Zf(pp,pp,r,1),e[n]=np(pp)):t===ap?Zf(e[n],e[n],r,1):t===op&&Qf(e[n],e[n],r,1)},e}(),hp=function(){function e(e,t,n,r){if(this._tracks={},this._trackKeys=[],this._maxTime=0,this._started=0,this._clip=null,this._target=e,this._loop=t,t&&r){Vo(`Can' use additive animation on looped animation.`);return}this._additiveAnimators=r,this._allowDiscrete=n}return e.prototype.getMaxTime=function(){return this._maxTime},e.prototype.getDelay=function(){return this._delay},e.prototype.getLoop=function(){return this._loop},e.prototype.getTarget=function(){return this._target},e.prototype.changeTarget=function(e){this._target=e},e.prototype.when=function(e,t,n){return this.whenWithKeys(e,t,es(t),n)},e.prototype.whenWithKeys=function(e,t,n,r){for(var i=this._tracks,a=0;a0&&s.addKeyframe(0,tp(c),r),this._trackKeys.push(o)}s.addKeyframe(e,tp(t[o]),r)}return this._maxTime=Math.max(this._maxTime,e),this},e.prototype.pause=function(){this._clip.pause(),this._paused=!0},e.prototype.resume=function(){this._clip.resume(),this._paused=!1},e.prototype.isPaused=function(){return!!this._paused},e.prototype.duration=function(e){return this._maxTime=e,this._force=!0,this},e.prototype._doneCallback=function(){this._setTracksFinished(),this._clip=null;var e=this._doneCbs;if(e)for(var t=e.length,n=0;n0)){this._started=1;for(var t=this,n=[],r=this._maxTime||0,i=0;i1){var o=a.pop();i.addKeyframe(o.time,e[r]),i.prepare(this._maxTime,i.getAdditiveTrack())}}}},e}(),gp=function(){function e(e){e&&(this._$eventProcessor=e)}return e.prototype.on=function(e,t,n,r){this._$handlers||={};var i=this._$handlers;if(typeof t==`function`&&(r=n,n=t,t=null),!n||!e)return this;var a=this._$eventProcessor;t!=null&&a&&a.normalizeQuery&&(t=a.normalizeQuery(t)),i[e]||(i[e]=[]);for(var o=0;o=0:n.inside,y=void 0,b=void 0,x=void 0;v&&this.canBeInsideText()?(y=n.insideFill,b=n.insideStroke,(y==null||y===`auto`)&&(y=this.getInsideTextFill()),(b==null||b===`auto`)&&(b=this.getInsideTextStroke(y),x=!0)):(y=n.outsideFill,b=n.outsideStroke,(y==null||y===`auto`)&&(y=this.getOutsideFill()),(b==null||b===`auto`)&&(b=this.getOutsideStroke(y),x=!0)),y||=`#000`,(y!==g.fill||b!==g.stroke||x!==g.autoStroke||a!==g.align||o!==g.verticalAlign)&&(s=!0,g.fill=y,g.stroke=b,g.autoStroke=x,g.align=a,g.verticalAlign=o,t.setDefaultTextStyle(g)),t.__dirty|=1,s&&t.dirtyStyle(!0)}},e.prototype.canBeInsideText=function(){return!0},e.prototype.getInsideTextFill=function(){return`#fff`},e.prototype.getInsideTextStroke=function(e){return`#000`},e.prototype.getOutsideFill=function(){return this.__zr&&this.__zr.isDarkMode()?xp:bp},e.prototype.getOutsideStroke=function(e){var t=this.__zr&&this.__zr.getBackgroundColor(),n=typeof t==`string`&&Nf(t);n||=[255,255,255,1];for(var r=n[3],i=this.__zr.isDarkMode(),a=0;a<3;a++)n[a]=n[a]*r+(i?0:255)*(1-r);return n[3]=1,Vf(n,`rgba`)},e.prototype.traverse=function(e,t){},e.prototype.attrKV=function(e,t){e===`textConfig`?this.setTextConfig(t):e===`textContent`?this.setTextContent(t):e===`clipPath`?this.setClipPath(t):e===`extra`?(this.extra=this.extra||{},W(this.extra,t)):this[e]=t},e.prototype.hide=function(){this.ignore=!0,this.markRedraw()},e.prototype.show=function(){this.ignore=!1,this.markRedraw()},e.prototype.attr=function(e,t){if(typeof e==`string`)this.attrKV(e,t);else if(os(e))for(var n=es(e),r=0;r0},e.prototype.getState=function(e){return this.states[e]},e.prototype.ensureState=function(e){var t=this.states;return t[e]||(t[e]={}),t[e]},e.prototype.clearStates=function(e){this.useState(Cp,!1,e)},e.prototype.useState=function(e,t,n,r){var i=e===Cp;if(this.hasState()||!i){var a=this.currentStates,o=this.stateTransition;if(!(qo(a,e)>=0&&(t||a.length===1))){var s;if(this.stateProxy&&!i&&(s=this.stateProxy(e)),s||=this.states&&this.states[e],!s&&!i){Vo(`State `+e+` not exists.`);return}i||this.saveCurrentToNormalState(s);var c=this._textContent,l=Lp(this,c,s,r);l&&!this.__inHover&&(this.__inHover=l),this._applyStateObj(e,s,this._normalState,t,zp(this,n,o),o);var u=this._textGuide;return c&&c.useState(e,t,n,!!l),u&&u.useState(e,t,n,!!l),i?(this.currentStates=[],this._normalState={}):t?this.currentStates.push(e):this.currentStates=[e],this._updateAnimationTargets(),this.markRedraw(),!l&&this.__inHover&&(this.__inHover=0,this.__dirty&=-2),s}}},e.prototype.useStates=function(e,t,n){if(!e.length)this.clearStates();else{var r=[],i=this.currentStates,a=e.length,o=a===i.length;if(o){for(var s=0;s=0){var n=this.currentStates.slice();n.splice(t,1),this.useStates(n)}},e.prototype.replaceState=function(e,t,n){var r=this.currentStates.slice(),i=qo(r,e),a=qo(r,t)>=0;i>=0?a?r.splice(i,1):r[i]=t:n&&!a&&r.push(t),this.useStates(r)},e.prototype.toggleState=function(e,t){t?this.useState(e,!0):this.removeState(e)},e.prototype._mergeStates=function(e){for(var t={},n,r=0;r=0&&t.splice(n,1)}),this.animators.push(e),n&&n.animation.addAnimator(e),n&&n.wakeUp()},e.prototype.updateDuringAnimation=function(e){this.markRedraw()},e.prototype.stopAnimation=function(e,t){for(var n=this.animators,r=n.length,i=[],a=0;a0&&n.during&&a[0].during(function(e,t){n.during(t)});for(var f=0;f0||i.force&&!o.length){var C=void 0,w=void 0,T=void 0;if(s){w={},f&&(C={});for(var b=0;b0}var Bp=`__zr_style_`+Math.round(Math.random()*10),Vp={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:`#000`,opacity:1,blend:`source-over`},Hp={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};Vp[Bp]=!0;var Up=[`z`,`z2`,`invisible`],Wp=[`invisible`],Gp=function(e){U(t,e);function t(t){return e.call(this,t)||this}return t.prototype._init=function(t){for(var n=es(t),r=0;r1e-4){s[0]=e-n,s[1]=t-r,c[0]=e+n,c[1]=t+r;return}if(em[0]=Qp(i)*n+e,em[1]=Zp(i)*r+t,tm[0]=Qp(a)*n+e,tm[1]=Zp(a)*r+t,l(s,em,tm),u(c,em,tm),i%=$p,i<0&&(i+=$p),a%=$p,a<0&&(a+=$p),i>a&&!o?a+=$p:ii&&(nm[0]=Qp(p)*n+e,nm[1]=Zp(p)*r+t,l(s,nm,s),u(c,nm,c))}var lm={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},um=[],dm=[],fm=[],pm=[],mm=[],hm=[],gm=Math.min,_m=Math.max,vm=Math.cos,ym=Math.sin,bm=Math.abs,xm=Math.PI,Sm=xm*2,Cm=typeof Float32Array<`u`,wm=[];function Tm(e){return Math.round(e/xm*1e8)/1e8%2*xm}function Em(e,t){var n=Tm(e[0]);n<0&&(n+=Sm);var r=n-e[0],i=e[1];i+=r,!t&&i-n>=Sm?i=n+Sm:t&&n-i>=Sm?i=n-Sm:!t&&n>i?i=n+(Sm-Tm(n-i)):t&&n0&&(this._ux=bm(n/vp/e)||0,this._uy=bm(n/vp/t)||0)},e.prototype.setDPR=function(e){this.dpr=e},e.prototype.setContext=function(e){this._ctx=e},e.prototype.getContext=function(){return this._ctx},e.prototype.beginPath=function(){return this._ctx&&this._ctx.beginPath(),this.reset(),this},e.prototype.reset=function(){this._saveData&&(this._len=0),this._pathSegLen&&(this._pathSegLen=null,this._pathLen=0),this._version++},e.prototype.moveTo=function(e,t){return this._drawPendingPt(),this.addData(lm.M,e,t),this._ctx&&this._ctx.moveTo(e,t),this._x0=e,this._y0=t,this._xi=e,this._yi=t,this},e.prototype.lineTo=function(e,t){var n=bm(e-this._xi),r=bm(t-this._yi),i=n>this._ux||r>this._uy;if(this.addData(lm.L,e,t),this._ctx&&i&&this._ctx.lineTo(e,t),i)this._xi=e,this._yi=t,this._pendingPtDist=0;else{var a=n*n+r*r;a>this._pendingPtDist&&(this._pendingPtX=e,this._pendingPtY=t,this._pendingPtDist=a)}return this},e.prototype.bezierCurveTo=function(e,t,n,r,i,a){return this._drawPendingPt(),this.addData(lm.C,e,t,n,r,i,a),this._ctx&&this._ctx.bezierCurveTo(e,t,n,r,i,a),this._xi=i,this._yi=a,this},e.prototype.quadraticCurveTo=function(e,t,n,r){return this._drawPendingPt(),this.addData(lm.Q,e,t,n,r),this._ctx&&this._ctx.quadraticCurveTo(e,t,n,r),this._xi=n,this._yi=r,this},e.prototype.arc=function(e,t,n,r,i,a){this._drawPendingPt(),wm[0]=r,wm[1]=i,Em(wm,a),r=wm[0],i=wm[1];var o=i-r;return this.addData(lm.A,e,t,n,n,r,o,0,+!a),this._ctx&&this._ctx.arc(e,t,n,r,i,a),this._xi=vm(i)*n+e,this._yi=ym(i)*n+t,this},e.prototype.arcTo=function(e,t,n,r,i){return this._drawPendingPt(),this._ctx&&this._ctx.arcTo(e,t,n,r,i),this},e.prototype.rect=function(e,t,n,r){return this._drawPendingPt(),this._ctx&&this._ctx.rect(e,t,n,r),this.addData(lm.R,e,t,n,r),this},e.prototype.closePath=function(){this._drawPendingPt(),this.addData(lm.Z);var e=this._ctx,t=this._x0,n=this._y0;return e&&e.closePath(),this._xi=t,this._yi=n,this},e.prototype.fill=function(e){e&&e.fill(),this.toStatic()},e.prototype.stroke=function(e){e&&e.stroke(),this.toStatic()},e.prototype.len=function(){return this._len},e.prototype.setData=function(e){if(this._saveData){var t=e.length;!(this.data&&this.data.length===t)&&Cm&&(this.data=new Float32Array(t));for(var n=0;n0&&a))for(var o=0;ol.length&&(this._expandData(),l=this.data);for(var u=0;u0&&(this._ctx&&this._ctx.lineTo(this._pendingPtX,this._pendingPtY),this._pendingPtDist=0)},e.prototype._expandData=function(){if(!(this.data instanceof Array)){for(var e=[],t=0;t11&&(this.data=new Float32Array(e)))}},e.prototype.getBoundingRect=function(){fm[0]=fm[1]=mm[0]=mm[1]=Number.MAX_VALUE,pm[0]=pm[1]=hm[0]=hm[1]=-Number.MAX_VALUE;for(var e=this.data,t=0,n=0,r=0,i=0,a=0;an||bm(v)>r||d===t-1)&&(m=Math.sqrt(_*_+v*v),i=h,a=g);break;case lm.C:var y=e[d++],b=e[d++],h=e[d++],g=e[d++],x=e[d++],S=e[d++];m=lf(i,a,y,b,h,g,x,S,10),i=x,a=S;break;case lm.Q:var y=e[d++],b=e[d++],h=e[d++],g=e[d++];m=gf(i,a,y,b,h,g,10),i=h,a=g;break;case lm.A:var C=e[d++],w=e[d++],T=e[d++],E=e[d++],D=e[d++],O=e[d++],k=O+D;d+=1,p&&(o=vm(D)*T+C,s=ym(D)*E+w),m=_m(T,E)*gm(Sm,Math.abs(O)),i=vm(k)*T+C,a=ym(k)*E+w;break;case lm.R:o=i=e[d++],s=a=e[d++];var A=e[d++],j=e[d++];m=A*2+j*2;break;case lm.Z:var _=o-i,v=s-a;m=Math.sqrt(_*_+v*v),i=o,a=s}m>=0&&(c[u++]=m,l+=m)}return this._pathLen=l,l},e.prototype.rebuildPath=function(e,t){var n=this.data,r=this._ux,i=this._uy,a=this._len,o,s,c,l,u,d,f=t<1,p,m,h=0,g=0,_,v=0,y,b;if(!(f&&(this._pathSegLen||this._calculateLength(),p=this._pathSegLen,m=this._pathLen,_=t*m,!_)))lo:for(var x=0;x0&&(e.lineTo(y,b),v=0),S){case lm.M:o=c=n[x++],s=l=n[x++],e.moveTo(c,l);break;case lm.L:u=n[x++],d=n[x++];var w=bm(u-c),T=bm(d-l);if(w>r||T>i){if(f){var E=p[g++];if(h+E>_){var D=(_-h)/E;e.lineTo(c*(1-D)+u*D,l*(1-D)+d*D);break lo}h+=E}e.lineTo(u,d),c=u,l=d,v=0}else{var O=w*w+T*T;O>v&&(y=u,b=d,v=O)}break;case lm.C:var k=n[x++],A=n[x++],j=n[x++],M=n[x++],N=n[x++],P=n[x++];if(f){var E=p[g++];if(h+E>_){var D=(_-h)/E;sf(c,k,j,N,D,um),sf(l,A,M,P,D,dm),e.bezierCurveTo(um[1],dm[1],um[2],dm[2],um[3],dm[3]);break lo}h+=E}e.bezierCurveTo(k,A,j,M,N,P),c=N,l=P;break;case lm.Q:var k=n[x++],A=n[x++],j=n[x++],M=n[x++];if(f){var E=p[g++];if(h+E>_){var D=(_-h)/E;mf(c,k,j,D,um),mf(l,A,M,D,dm),e.quadraticCurveTo(um[1],dm[1],um[2],dm[2]);break lo}h+=E}e.quadraticCurveTo(k,A,j,M),c=j,l=M;break;case lm.A:var F=n[x++],I=n[x++],L=n[x++],ee=n[x++],R=n[x++],te=n[x++],ne=n[x++],re=!n[x++],ie=L>ee?L:ee,z=bm(L-ee)>.001,ae=R+te,B=!1;if(f){var E=p[g++];h+E>_&&(ae=R+te*(_-h)/E,B=!0),h+=E}if(z&&e.ellipse?e.ellipse(F,I,L,ee,ne,R,ae,re):e.arc(F,I,ie,R,ae,re),B)break lo;C&&(o=vm(R)*L+F,s=ym(R)*ee+I),c=vm(ae)*L+F,l=ym(ae)*ee+I;break;case lm.R:o=c=n[x],s=l=n[x+1],u=n[x++],d=n[x++];var oe=n[x++],se=n[x++];if(f){var E=p[g++];if(h+E>_){var ce=_-h;e.moveTo(u,d),e.lineTo(u+gm(ce,oe),d),ce-=oe,ce>0&&e.lineTo(u+oe,d+gm(ce,se)),ce-=se,ce>0&&e.lineTo(u+_m(oe-ce,0),d+se),ce-=oe,ce>0&&e.lineTo(u,d+_m(se-ce,0));break lo}h+=E}e.rect(u,d,oe,se);break;case lm.Z:if(f){var E=p[g++];if(h+E>_){var D=(_-h)/E;e.lineTo(c*(1-D)+o*D,l*(1-D)+s*D);break lo}h+=E}e.closePath(),c=o,l=s}}},e.prototype.clone=function(){var t=new e,n=this.data;return t.data=n.slice?n.slice():Array.prototype.slice.call(n),t._len=this._len,t},e.prototype.canSave=function(){return!!this._saveData},e.CMD=lm,e.initDefaultProps=(function(){var t=e.prototype;t._saveData=!0,t._ux=0,t._uy=0,t._pendingPtDist=0,t._version=0})(),e}();function Om(e,t,n,r,i,a,o){if(i===0)return!1;var s=i,c=0,l=e;if(o>t+s&&o>r+s||oe+s&&a>n+s||at+d&&u>r+d&&u>a+d&&u>s+d||ue+d&&l>n+d&&l>i+d&&l>o+d||lt+l&&c>r+l&&c>a+l||ce+l&&s>n+l&&s>i+l||sn||u+li&&(i+=Nm);var f=Math.atan2(c,s);return f<0&&(f+=Nm),f>=r&&f<=i||f+Nm>=r&&f+Nm<=i}function Fm(e,t,n,r,i,a){if(a>t&&a>r||ai?s:0}var Im=Dm.CMD,Lm=Math.PI*2,Rm=1e-4;function zm(e,t){return Math.abs(e-t)t&&l>r&&l>a&&l>s||l1&&Hm(),p=nf(t,r,a,s,Vm[0]),f>1&&(m=nf(t,r,a,s,Vm[1]))),f===2?gt&&s>r&&s>a||s=0&&l<=1){for(var u=0,d=uf(t,r,a,l),f=0;fn||s<-n)return 0;var c=Math.sqrt(n*n-s*s);Bm[0]=-c,Bm[1]=c;var l=Math.abs(r-i);if(l<1e-4)return 0;if(l>=Lm-1e-4){r=0,i=Lm;var u=a?1:-1;return o>=Bm[0]+e&&o<=Bm[1]+e?u:0}if(r>i){var d=r;r=i,i=d}r<0&&(r+=Lm,i+=Lm);for(var f=0,p=0;p<2;p++){var m=Bm[p];if(m+e>o){var h=Math.atan2(s,m),u=a?1:-1;h<0&&(h=Lm+h),(h>=r&&h<=i||h+Lm>=r&&h+Lm<=i)&&(h>Math.PI/2&&h1&&(n||(s+=Fm(c,l,u,d,r,i))),g&&(c=a[m],l=a[m+1],u=c,d=l),h){case Im.M:u=a[m++],d=a[m++],c=u,l=d;break;case Im.L:if(n){if(Om(c,l,a[m],a[m+1],t,r,i))return!0}else s+=Fm(c,l,a[m],a[m+1],r,i)||0;c=a[m++],l=a[m++];break;case Im.C:if(n){if(km(c,l,a[m++],a[m++],a[m++],a[m++],a[m],a[m+1],t,r,i))return!0}else s+=Um(c,l,a[m++],a[m++],a[m++],a[m++],a[m],a[m+1],r,i)||0;c=a[m++],l=a[m++];break;case Im.Q:if(n){if(Am(c,l,a[m++],a[m++],a[m],a[m+1],t,r,i))return!0}else s+=Wm(c,l,a[m++],a[m++],a[m],a[m+1],r,i)||0;c=a[m++],l=a[m++];break;case Im.A:var _=a[m++],v=a[m++],y=a[m++],b=a[m++],x=a[m++],S=a[m++];m+=1;var C=!!(1-a[m++]);f=Math.cos(x)*y+_,p=Math.sin(x)*b+v,g?(u=f,d=p):s+=Fm(c,l,f,p,r,i);var w=(r-_)*b/y+_;if(n){if(Pm(_,v,b,x,x+S,C,t,w,i))return!0}else s+=Gm(_,v,b,x,x+S,C,w,i);c=Math.cos(x+S)*y+_,l=Math.sin(x+S)*b+v;break;case Im.R:u=c=a[m++],d=l=a[m++];var T=a[m++],E=a[m++];if(f=u+T,p=d+E,n){if(Om(u,d,f,d,t,r,i)||Om(f,d,f,p,t,r,i)||Om(f,p,u,p,t,r,i)||Om(u,p,u,d,t,r,i))return!0}else s+=Fm(f,d,f,p,r,i),s+=Fm(u,p,u,d,r,i);break;case Im.Z:if(n){if(Om(c,l,u,d,t,r,i))return!0}else s+=Fm(c,l,u,d,r,i);c=u,l=d}}return!n&&!zm(l,d)&&(s+=Fm(c,l,u,d,r,i)||0),s!==0}function qm(e,t,n){return Km(e,0,!1,t,n)}function Jm(e,t,n,r){return Km(e,t,!0,n,r)}var Ym=Ko({fill:`#000`,stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:`butt`,miterLimit:10,strokeNoScale:!1,strokeFirst:!1},Vp),Xm={style:Ko({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},Hp.style)},Zm=Hd.concat([`invisible`,`culling`,`z`,`z2`,`zlevel`,`parent`]),Qm=function(e){U(t,e);function t(t){return e.call(this,t)||this}return t.prototype.update=function(){var n=this;e.prototype.update.call(this);var r=this.style;if(r.decal){var i=this._decalEl=this._decalEl||new t;i.buildPath===t.prototype.buildPath&&(i.buildPath=function(e){n.buildPath(e,n.shape)}),i.silent=!0;var a=i.style;for(var o in r)a[o]!==r[o]&&(a[o]=r[o]);a.fill=r.fill?r.decal:null,a.decal=null,a.shadowColor=null,r.strokeFirst&&(a.stroke=null);for(var s=0;s.5?bp:t>.2?Sp:xp}if(e)return xp}return bp},t.prototype.getInsideTextStroke=function(e){var t=this.style.fill;if(Y(t)){var n=this.__zr;if(!!(n&&n.isDarkMode())==Hf(e,0)<.4)return t}},t.prototype.buildPath=function(e,t,n){},t.prototype.pathUpdated=function(){this.__dirty&=-5},t.prototype.getUpdatedPathProxy=function(e){return!this.path&&this.createPathProxy(),this.path.beginPath(),this.buildPath(this.path,this.shape,e),this.path},t.prototype.createPathProxy=function(){this.path=new Dm(!1)},t.prototype.hasStroke=function(){var e=this.style,t=e.stroke;return!(t==null||t===`none`||!(e.lineWidth>0))},t.prototype.hasFill=function(){var e=this.style.fill;return e!=null&&e!==`none`},t.prototype.getBoundingRect=function(){var e=this._rect,t=this.style,n=!e;if(n){var r=!1;this.path||(r=!0,this.createPathProxy());var i=this.path;(r||this.__dirty&4)&&(i.beginPath(),this.buildPath(i,this.shape,!1),this.pathUpdated()),e=i.getBoundingRect()}if(this._rect=e,this.hasStroke()&&this.path&&this.path.len()>0){var a=this._rectStroke||=e.clone();if(this.__dirty||n){a.copy(e);var o=t.strokeNoScale?this.getLineScale():1,s=t.lineWidth;if(!this.hasFill()){var c=this.strokeContainThreshold;s=Math.max(s,c??4)}o>1e-10&&(a.width+=s/o,a.height+=s/o,a.x-=s/o/2,a.y-=s/o/2)}return a}return e},t.prototype.contain=function(e,t){var n=this.transformCoordToLocal(e,t),r=this.getBoundingRect(),i=this.style;if(e=n[0],t=n[1],r.contain(e,t)){var a=this.path;if(this.hasStroke()){var o=i.lineWidth,s=i.strokeNoScale?this.getLineScale():1;if(s>1e-10&&(this.hasFill()||(o=Math.max(o,this.strokeContainThreshold)),Jm(a,o/s,e,t)))return!0}if(this.hasFill())return qm(a,e,t)}return!1},t.prototype.dirtyShape=function(){this.__dirty|=4,this._rect&&=null,this._decalEl&&this._decalEl.dirtyShape(),this.markRedraw()},t.prototype.dirty=function(){this.dirtyStyle(),this.dirtyShape()},t.prototype.animateShape=function(e){return this.animate(`shape`,e)},t.prototype.updateDuringAnimation=function(e){e===`style`?this.dirtyStyle():e===`shape`?this.dirtyShape():this.markRedraw()},t.prototype.attrKV=function(t,n){t===`shape`?this.setShape(n):e.prototype.attrKV.call(this,t,n)},t.prototype.setShape=function(e,t){var n=this.shape;return n||=this.shape={},typeof e==`string`?n[e]=t:W(n,e),this.dirtyShape(),this},t.prototype.shapeChanged=function(){return!!(this.__dirty&4)},t.prototype.createStyle=function(e){return Os(Ym,e)},t.prototype._innerSaveToNormal=function(t){e.prototype._innerSaveToNormal.call(this,t);var n=this._normalState;t.shape&&!n.shape&&(n.shape=W({},this.shape))},t.prototype._applyStateObj=function(t,n,r,i,a,o){if(e.prototype._applyStateObj.call(this,t,n,r,i,a,o),this.__inHover!==1){var s=!(n&&i),c;if(n&&n.shape?a?i?c=n.shape:(c=W({},r.shape),W(c,n.shape)):(c=W({},i?this.shape:r.shape),W(c,n.shape)):s&&(c=r.shape),c){if(a){this.shape=W({},this.shape);for(var l={},u=es(c),d=0;di&&(d=s+c,s*=i/d,c*=i/d),l+u>i&&(d=l+u,l*=i/d,u*=i/d),c+l>a&&(d=c+l,c*=a/d,l*=a/d),s+u>a&&(d=s+u,s*=a/d,u*=a/d),e.moveTo(n+s,r),e.lineTo(n+i-c,r),c!==0&&e.arc(n+i-c,r+c,c,-Math.PI/2,0),e.lineTo(n+i,r+a-l),l!==0&&e.arc(n+i-l,r+a-l,l,0,Math.PI/2),e.lineTo(n+u,r+a),u!==0&&e.arc(n+u,r+a-u,u,Math.PI/2,Math.PI),e.lineTo(n,r+s),s!==0&&e.arc(n+s,r+s,s,Math.PI,Math.PI*1.5),e.closePath()}var oh=Math.round;function sh(e,t,n){if(t){var r=t.x1,i=t.x2,a=t.y1,o=t.y2;e.x1=r,e.x2=i,e.y1=a,e.y2=o;var s=n&&n.lineWidth;return s?(oh(r*2)===oh(i*2)&&(e.x1=e.x2=lh(r,s,!0)),oh(a*2)===oh(o*2)&&(e.y1=e.y2=lh(a,s,!0)),e):e}}function ch(e,t,n){if(t){var r=t.x,i=t.y,a=t.width,o=t.height;e.x=r,e.y=i,e.width=a,e.height=o;var s=n&&n.lineWidth;return s?(e.x=lh(r,s,!0),e.y=lh(i,s,!0),e.width=Math.max(lh(r+a,s,!1)-e.x,a===0?0:1),e.height=Math.max(lh(i+o,s,!1)-e.y,o===0?0:1),e):e}}function lh(e,t,n){if(!t)return e;var r=oh(e*2);return(r+oh(t))%2==0?r/2:(r+(n?1:-1))/2}var uh=function(){function e(){this.x=0,this.y=0,this.width=0,this.height=0}return e}(),dh={},fh=function(e){U(t,e);function t(t){return e.call(this,t)||this}return t.prototype.getDefaultShape=function(){return new uh},t.prototype.buildPath=function(e,t){var n,r,i,a;if(this.subPixelOptimize){var o=ch(dh,t,this.style);n=o.x,r=o.y,i=o.width,a=o.height,o.r=t.r,t=o}else n=t.x,r=t.y,i=t.width,a=t.height;t.r?ah(e,t):e.rect(n,r,i,a)},t.prototype.isZeroArea=function(){return!this.shape.width||!this.shape.height},t}(Qm);fh.prototype.type=`rect`;var ph={fill:`#000`},mh=2,hh={},gh={style:Ko({fill:!0,stroke:!0,fillOpacity:!0,strokeOpacity:!0,lineWidth:!0,fontSize:!0,lineHeight:!0,width:!0,height:!0,textShadowColor:!0,textShadowBlur:!0,textShadowOffsetX:!0,textShadowOffsetY:!0,backgroundColor:!0,padding:!0,borderColor:!0,borderWidth:!0,borderRadius:!0},Hp.style)},_h=function(e){U(t,e);function t(t){var n=e.call(this)||this;return n.type=`text`,n._children=[],n._defaultStyle=ph,n.attr(t),n}return t.prototype.childrenRef=function(){return this._children},t.prototype.update=function(){e.prototype.update.call(this),this.styleChanged()&&this._updateSubTexts();for(var t=0;t0,T=0;T=0&&(D=y[E],D.align===`right`);)this._placeToken(D,e,x,m,T,`right`,g),S-=D.width,T-=D.width,E--;for(w+=(s-(w-p)-(h-T)-S)/2;C<=E;)D=y[C],this._placeToken(D,e,x,m,w+D.width/2,`center`,g),w+=D.width,C++;m+=x}},t.prototype._placeToken=function(e,t,n,r,i,a,o){var s=t.rich[e.styleName]||{};s.text=e.text;var c=e.verticalAlign,l=r+n/2;c===`top`?l=r+e.height/2:c===`bottom`&&(l=r+n-e.height/2),!e.isLineHolder&&Ah(s)&&this._renderBackground(s,t,a===`right`?i-e.width:a===`center`?i-e.width/2:i,l-e.height/2,e.width,e.height);var u=!!s.backgroundColor,d=e.textPadding;d&&(i=Oh(i,a,d),l-=e.height/2-d[0]-e.innerHeight/2);var f=this._getOrCreateChild(eh),p=f.createStyle();f.useStyle(p);var m=this._defaultStyle,h=!1,g=0,_=!1,v=Dh(`fill`in s?s.fill:`fill`in t?t.fill:(h=!0,m.fill)),y=Eh(`stroke`in s?s.stroke:`stroke`in t?t.stroke:!u&&!o&&(!m.autoStroke||h)?(g=mh,_=!0,m.stroke):null),b=s.textShadowBlur>0||t.textShadowBlur>0;p.text=e.text,p.x=i,p.y=l,b&&(p.shadowBlur=s.textShadowBlur||t.textShadowBlur||0,p.shadowColor=s.textShadowColor||t.textShadowColor||`transparent`,p.shadowOffsetX=s.textShadowOffsetX||t.textShadowOffsetX||0,p.shadowOffsetY=s.textShadowOffsetY||t.textShadowOffsetY||0),p.textAlign=a,p.textBaseline=`middle`,p.font=e.font||`12px sans-serif`,p.opacity=ms(s.opacity,t.opacity,1),Sh(p,s),y&&(p.lineWidth=ms(s.lineWidth,t.lineWidth,g),p.lineDash=X(s.lineDash,t.lineDash),p.lineDashOffset=t.lineDashOffset||0,p.stroke=y),v&&(p.fill=v),f.setBoundingRect(Ad(p,e.contentWidth,e.contentHeight,_?0:null))},t.prototype._renderBackground=function(e,t,n,r,i,a){var o=e.backgroundColor,s=e.borderWidth,c=e.borderColor,l=o&&o.image,u=o&&!l,d=e.borderRadius,f=this,p,m;if(u||e.lineHeight||s&&c){p=this._getOrCreateChild(fh),p.useStyle(p.createStyle()),p.style.fill=null;var h=p.shape;h.x=n,h.y=r,h.width=i,h.height=a,h.r=d,p.dirtyShape()}if(u){var g=p.style;g.fill=o||null,g.fillOpacity=X(e.fillOpacity,1)}else if(l){m=this._getOrCreateChild(ih),m.onload=function(){f.dirtyStyle()};var _=m.style;_.image=o.image,_.x=n,_.y=r,_.width=i,_.height=a}if(s&&c){var g=p.style;g.lineWidth=s,g.stroke=c,g.strokeOpacity=X(e.strokeOpacity,1),g.lineDash=e.borderDash,g.lineDashOffset=e.borderDashOffset||0,p.strokeContainThreshold=0,p.hasFill()&&p.hasStroke()&&(g.strokeFirst=!0,g.lineWidth*=2)}var v=(p||m).style;v.shadowBlur=e.shadowBlur||0,v.shadowColor=e.shadowColor||`transparent`,v.shadowOffsetX=e.shadowOffsetX||0,v.shadowOffsetY=e.shadowOffsetY||0,v.opacity=ms(e.opacity,t.opacity,1)},t.makeFont=function(e){var t=``;return Ch(e)&&(t=[e.fontStyle,e.fontWeight,xh(e.fontSize),e.fontFamily||`sans-serif`].join(` `)),t&&vs(t)||e.textFont||e.font},t}(Gp),vh={left:!0,right:1,center:1},yh={top:1,bottom:1,middle:1},bh=[`fontStyle`,`fontWeight`,`fontSize`,`fontFamily`];function xh(e){return typeof e==`string`&&(e.indexOf(`px`)!==-1||e.indexOf(`rem`)!==-1||e.indexOf(`em`)!==-1)?e:isNaN(+e)?`12px`:e+`px`}function Sh(e,t){for(var n=0;n=0,a=!1;if(e instanceof Qm){var o=Kh(e),s=i&&o.selectFill||o.normalFill,c=i&&o.selectStroke||o.normalStroke;if(ng(s)||ng(c)){r||={};var l=r.style||{};l.fill===`inherit`?(a=!0,r=W({},r),l=W({},l),l.fill=s):!ng(l.fill)&&ng(s)?(a=!0,r=W({},r),l=W({},l),l.fill=Wf(s)):!ng(l.stroke)&&ng(c)&&(a||(r=W({},r),l=W({},l)),l.stroke=Wf(c)),r.style=l}}if(r&&r.z2==null){a||(r=W({},r));var u=e.z2EmphasisLift;r.z2=e.z2+(u??10)}return r}function hg(e,t,n){if(n&&n.z2==null){n=W({},n);var r=e.z2SelectLift;n.z2=e.z2+(r??9)}return n}function gg(e,t,n){var r=qo(e.currentStates,t)>=0,i=e.style.opacity,a=r?null:pg(e,[`opacity`],t,{opacity:1});n||={};var o=n.style||{};return o.opacity??(n=W({},n),o=W({opacity:r?i:a.opacity*.1},o),n.style=o),n}function _g(e,t){var n=this.states[e];if(this.style){if(e===`emphasis`)return mg(this,e,t,n);if(e===`blur`)return gg(this,e,n);if(e===`select`)return hg(this,e,n)}return n}function vg(e){e.stateProxy=_g;var t=e.getTextContent(),n=e.getTextGuideLine();t&&(t.stateProxy=_g),n&&(n.stateProxy=_g)}function yg(e,t){!Dg(e,t)&&!e.__highByOuter&&dg(e,ig)}function bg(e,t){!Dg(e,t)&&!e.__highByOuter&&dg(e,ag)}function xg(e,t){e.__highByOuter|=1<<(t||0),dg(e,ig)}function Sg(e,t){!(e.__highByOuter&=~(1<<(t||0)))&&dg(e,ag)}function Cg(e){dg(e,og)}function wg(e){dg(e,sg)}function Tg(e){dg(e,cg)}function Eg(e){dg(e,lg)}function Dg(e,t){return e.__highDownSilentOnTouch&&t.zrByTouch}function Og(e){var t=e.getModel(),n=[],r=[];t.eachComponent(function(t,i){var a=qh(i),o=Uh(e,i),s=t===`series`;!s&&r.push(o),a.isBlured&&(o.group.traverse(function(e){sg(e)}),s&&n.push(i)),a.isBlured=!1}),G(r,function(e){e&&e.toggleBlurSeries&&e.toggleBlurSeries(n,!1,t)})}function kg(e,t,n,r){var i=r.getModel();n||=`coordinateSystem`;function a(e,t){for(var n=0;n0){var a={dataIndex:i,seriesIndex:e.seriesIndex};r!=null&&(a.dataType=r),t.push(a)}})}),t}function Rg(e,t,n){Gg(e,!0),dg(e,vg),Vg(e,t,n)}function zg(e){Gg(e,!1)}function Bg(e,t,n,r){r?zg(e):Rg(e,t,n)}function Vg(e,t,n){var r=jh(e);t==null?r.focus&&=null:(r.focus=t,r.blurScope=n)}var Hg=[`emphasis`,`blur`,`select`],Ug={itemStyle:`getItemStyle`,lineStyle:`getLineStyle`,areaStyle:`getAreaStyle`};function Wg(e,t,n,r){n||=`itemStyle`;for(var i=0;i1&&(o*=n_(m),s*=n_(m));var h=(i===a?-1:1)*n_((o*o*(s*s)-o*o*(p*p)-s*s*(f*f))/(o*o*(p*p)+s*s*(f*f)))||0,g=h*o*p/s,_=h*-s*f/o,v=(e+n)/2+i_(d)*g-r_(d)*_,y=(t+r)/2+r_(d)*g+i_(d)*_,b=c_([1,0],[(f-g)/o,(p-_)/s]),x=[(f-g)/o,(p-_)/s],S=[(-1*f-g)/o,(-1*p-_)/s],C=c_(x,S);if(s_(x,S)<=-1&&(C=a_),s_(x,S)>=1&&(C=0),C<0){var w=Math.round(C/a_*1e6)/1e6;C=a_*2+w%2*a_}u.addData(l,v,y,o,s,b,C,d,a)}var u_=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,d_=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;function f_(e){var t=new Dm;if(!e)return t;var n=0,r=0,i=n,a=r,o,s=Dm.CMD,c=e.match(u_);if(!c)return t;for(var l=0;l=0&&(n.splice(r,0,e),this._doAdd(e))}return this},t.prototype.replace=function(e,t){var n=qo(this._children,e);return n>=0&&this.replaceAt(t,n),this},t.prototype.replaceAt=function(e,t){var n=this._children,r=n[t];if(e&&e!==this&&e.parent!==this&&e!==r){n[t]=e,r.parent=null;var i=this.__zr;i&&r.removeSelfFromZr(i),this._doAdd(e)}return this},t.prototype._doAdd=function(e){e.parent&&e.parent.remove(e),e.parent=this;var t=this.__zr;t&&t!==e.__zr&&e.addSelfToZr(t),t&&t.refresh()},t.prototype.remove=function(e){var t=this.__zr,n=this._children,r=qo(n,e);return r<0?this:(n.splice(r,1),e.parent=null,t&&e.removeSelfFromZr(t),t&&t.refresh(),this)},t.prototype.removeAll=function(){for(var e=this._children,t=this.__zr,n=0;nA*A+j*j&&(w=E,T=D),{cx:w,cy:T,x0:-u,y0:-d,x1:w*(i/x-1),y1:T*(i/x-1)}}function L_(e){var t;if(J(e)){var n=e.length;if(!n)return e;t=n===1?[e[0],e[0],0,0]:n===2?[e[0],e[0],e[1],e[1]]:n===3?e.concat(e[2]):e}else t=[e,e,e,e];return t}function R_(e,t){var n,r=M_(t.r,0),i=M_(t.r0||0,0),a=r>0;if(a||i>0){if(a||(r=i,i=0),i>r){var o=r;r=i,i=o}var s=t.startAngle,c=t.endAngle;if(!(isNaN(s)||isNaN(c))){var l=t.cx,u=t.cy,d=!!t.clockwise,f=A_(c-s),p=f>T_&&f%T_;if(p>P_&&(f=p),!(r>P_))e.moveTo(l,u);else if(f>T_-P_)e.moveTo(l+r*D_(s),u+r*E_(s)),e.arc(l,u,r,s,c,!d),i>P_&&(e.moveTo(l+i*D_(c),u+i*E_(c)),e.arc(l,u,i,c,s,d));else{var m=void 0,h=void 0,g=void 0,_=void 0,v=void 0,y=void 0,b=void 0,x=void 0,S=void 0,C=void 0,w=void 0,T=void 0,E=void 0,D=void 0,O=void 0,k=void 0,A=r*D_(s),j=r*E_(s),M=i*D_(c),N=i*E_(c),P=f>P_;if(P){var F=t.cornerRadius;F&&(n=L_(F),m=n[0],h=n[1],g=n[2],_=n[3]);var I=A_(r-i)/2;if(v=N_(I,g),y=N_(I,_),b=N_(I,m),x=N_(I,h),w=S=M_(v,y),T=C=M_(b,x),(S>P_||C>P_)&&(E=r*D_(c),D=r*E_(c),O=i*D_(s),k=i*E_(s),fP_){var z=N_(g,w),ae=N_(_,w),B=I_(O,k,A,j,r,z,d),oe=I_(E,D,M,N,r,ae,d);e.moveTo(l+B.cx+B.x0,u+B.cy+B.y0),w0&&e.arc(l+B.cx,u+B.cy,z,k_(B.y0,B.x0),k_(B.y1,B.x1),!d),e.arc(l,u,r,k_(B.cy+B.y1,B.cx+B.x1),k_(oe.cy+oe.y1,oe.cx+oe.x1),!d),ae>0&&e.arc(l+oe.cx,u+oe.cy,ae,k_(oe.y1,oe.x1),k_(oe.y0,oe.x0),!d))}else e.moveTo(l+A,u+j),e.arc(l,u,r,s,c,!d);if(!(i>P_)||!P)e.lineTo(l+M,u+N);else if(T>P_){var z=N_(m,T),ae=N_(h,T),B=I_(M,N,E,D,i,-ae,d),oe=I_(A,j,O,k,i,-z,d);e.lineTo(l+B.cx+B.x0,u+B.cy+B.y0),T0&&e.arc(l+B.cx,u+B.cy,ae,k_(B.y0,B.x0),k_(B.y1,B.x1),!d),e.arc(l,u,i,k_(B.cy+B.y1,B.cx+B.x1),k_(oe.cy+oe.y1,oe.cx+oe.x1),d),z>0&&e.arc(l+oe.cx,u+oe.cy,z,k_(oe.y1,oe.x1),k_(oe.y0,oe.x0),!d))}else e.lineTo(l+M,u+N),e.arc(l,u,i,c,s,d)}e.closePath()}}}var z_=function(){function e(){this.cx=0,this.cy=0,this.r0=0,this.r=0,this.startAngle=0,this.endAngle=Math.PI*2,this.clockwise=!0,this.cornerRadius=0}return e}(),B_=function(e){U(t,e);function t(t){return e.call(this,t)||this}return t.prototype.getDefaultShape=function(){return new z_},t.prototype.buildPath=function(e,t){R_(e,t)},t.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},t}(Qm);B_.prototype.type=`sector`;var V_=function(){function e(){this.cx=0,this.cy=0,this.r=0,this.r0=0}return e}(),H_=function(e){U(t,e);function t(t){return e.call(this,t)||this}return t.prototype.getDefaultShape=function(){return new V_},t.prototype.buildPath=function(e,t){var n=t.cx,r=t.cy,i=Math.PI*2;e.moveTo(n+t.r,r),e.arc(n,r,t.r,0,i,!1),e.moveTo(n+t.r0,r),e.arc(n,r,t.r0,0,i,!0)},t}(Qm);H_.prototype.type=`ring`;function U_(e,t,n,r){var i=[],a=[],o=[],s=[],c,l,u,d;if(r){u=[1/0,1/0],d=[-1/0,-1/0];for(var f=0,p=e.length;f=2){if(r){var a=U_(i,r,n,t.smoothConstraint);e.moveTo(i[0][0],i[0][1]);for(var o=i.length,s=0;s<(n?o:o-1);s++){var c=a[s*2],l=a[s*2+1],u=i[(s+1)%o];e.bezierCurveTo(c[0],c[1],l[0],l[1],u[0],u[1])}}else{e.moveTo(i[0][0],i[0][1]);for(var s=1,d=i.length;sfv[1]){if(i=!1,pv.negativeSize||n)return i;var s=uv(fv[0]-dv[1]),c=uv(dv[0]-fv[1]);cv(s,c)>hv.len()&&(s=c||!pv.bidirectional)&&(wu.scale(mv,o,-c*r),pv.useDir&&pv.calcDirMTV()))}}return i},e.prototype._getProjMinMaxOnAxis=function(e,t,n){for(var r=this._axes[e],i=this._origin,a=t[0].dot(r)+i[e],o=a,s=a,c=1;c0){var d=u.duration,f=u.delay,p=u.easing,m={duration:d,delay:f||0,easing:p,done:a,force:!!a||!!o,setToFinal:!l,scope:e,during:o};s?t.animateFrom(n,m):t.animateTo(n,m)}else t.stopAnimation(),!s&&t.attr(n),o&&o(1),a&&a()}function Sv(e,t,n,r,i,a){xv(`update`,e,t,n,r,i,a)}function Cv(e,t,n,r,i,a){xv(`enter`,e,t,n,r,i,a)}function wv(e){if(!e.__zr)return!0;for(var t=0;trv,BezierCurve:()=>tv,BoundingRect:()=>Ru,Circle:()=>x_,CompoundPath:()=>iv,Ellipse:()=>C_,Group:()=>y_,HOVER_LAYER_FOR_INCREMENTAL:()=>2,HOVER_LAYER_FROM_THRESHOLD:()=>1,HOVER_LAYER_NO:()=>0,Image:()=>ih,IncrementalDisplayable:()=>vv,Line:()=>Z_,LinearGradient:()=>ov,OrientedBoundingRect:()=>gv,Path:()=>Qm,Point:()=>wu,Polygon:()=>K_,Polyline:()=>J_,RadialGradient:()=>sv,Rect:()=>fh,Ring:()=>H_,Sector:()=>B_,Text:()=>_h,WH:()=>Mv,XY:()=>jv,applyTransform:()=>qv,calcZ2Range:()=>gy,clipPointsByRect:()=>Qv,clipRectByRect:()=>$v,createIcon:()=>ey,decomposeTransform:()=>by,ensureCopyRect:()=>py,ensureCopyTransform:()=>my,expandOrShrinkRect:()=>ay,extendPath:()=>Fv,extendShape:()=>Nv,getCurrentCanvasPainter:()=>Sy,getShapeClass:()=>Lv,getTransform:()=>Kv,groupTransition:()=>Zv,initProps:()=>Cv,isBoundingRectAxisAligned:()=>dy,isElementRemoved:()=>wv,lineLineIntersect:()=>ny,linePolygonIntersect:()=>ty,makeImage:()=>zv,makePath:()=>Rv,mergePath:()=>Vv,payloadDisableAnimation:()=>yy,registerShape:()=>Iv,removeElement:()=>Tv,removeElementWithFadeOut:()=>Dv,resizePath:()=>Hv,retrieveZInfo:()=>hy,setTooltipConfig:()=>cy,subPixelOptimize:()=>Gv,subPixelOptimizeLine:()=>Uv,subPixelOptimizeRect:()=>Wv,transformDirection:()=>Jv,traverseElements:()=>uy,traverseUpdateZ:()=>_y,updateProps:()=>Sv}),Av={},jv=[`x`,`y`],Mv=[`width`,`height`];function Nv(e){return Qm.extend(e)}var Pv=__;function Fv(e,t){return Pv(e,t)}function Iv(e,t){Av[e]=t}function Lv(e){if(Av.hasOwnProperty(e))return Av[e]}function Rv(e,t,n,r){var i=g_(e,t);return n&&(r===`center`&&(n=Bv(n,i.getBoundingRect())),Hv(i,n)),i}function zv(e,t,n){var r=new ih({style:{image:e,x:t.x,y:t.y,width:t.width,height:t.height},onload:function(e){if(n===`center`){var i={width:e.width,height:e.height};r.setStyle(Bv(t,i))}}});return r}function Bv(e,t){var n=t.width/t.height,r=e.height*n,i;r<=e.width?i=e.height:(r=e.width,i=r/n);var a=e.x+e.width/2,o=e.y+e.height/2;return{x:a-r/2,y:o-i/2,width:r,height:i}}var Vv=v_;function Hv(e,t){if(e.applyTransform){var n=e.getBoundingRect().calculateTransform(t);e.applyTransform(n)}}function Uv(e,t){return sh(e,e,{lineWidth:t}),e}function Wv(e,t){return ch(e,e,t),e}var Gv=lh;function Kv(e,t){for(var n=$l([]);e&&e!==t;)tu(n,e.getLocalTransform(),n),e=e.parent;return n}function qv(e,t,n){return t&&!Xo(t)&&(t=zd.getLocalTransform(t)),n&&(t=au([],t)),xu([],e,t)}function Jv(e,t,n){var r=t[4]===0||t[5]===0||t[0]===0?1:Bs(2*t[4]/t[0]),i=t[4]===0||t[5]===0||t[2]===0?1:Bs(2*t[4]/t[2]),a=[e===`left`?-r:e===`right`?r:0,e===`top`?-i:e===`bottom`?i:0];return a=qv(a,t,n),Bs(a[0])>Bs(a[1])?a[0]>0?`right`:`left`:a[1]>0?`bottom`:`top`}function Yv(e){return!e.isGroup}function Xv(e){return e.shape!=null}function Zv(e,t,n){if(!e||!t)return;function r(e){var t={};return e.traverse(function(e){Yv(e)&&e.anid&&(t[e.anid]=e)}),t}function i(e){var t={x:e.x,y:e.y,rotation:e.rotation};return Xv(e)&&(t.shape=Ho(e.shape)),t}var a=r(e);t.traverse(function(e){if(Yv(e)&&e.anid){var t=a[e.anid];if(t){var r=i(e);e.attr(i(t)),Sv(e,r,n,jh(e).dataIndex)}}})}function Qv(e,t){return K(e,function(e){var n=e[0];n=zs(n,t.x),n=Rs(n,t.x+t.width);var r=e[1];return r=zs(r,t.y),r=Rs(r,t.y+t.height),[n,r]})}function $v(e,t){var n=zs(e.x,t.x),r=Rs(e.x+e.width,t.x+t.width),i=zs(e.y,t.y),a=Rs(e.y+e.height,t.y+t.height);if(r>=n&&a>=i)return{x:n,y:i,width:r-n,height:a-i}}function ey(e,t,n){var r=W({rectHover:!0},t),i=r.style={strokeNoScale:!0};if(n||={x:-1,y:-1,width:2,height:2},e)return e.indexOf(`image://`)===0?(i.image=e.slice(8),Ko(i,n),new ih(r)):Rv(e.replace(`path://`,``),r,n,`center`)}function ty(e,t,n,r,i){for(var a=0,o=i[i.length-1];a1)return!1;var g=ry(p,m,u,d)/f;return!(g<0||g>1)}function ry(e,t,n,r){return e*r-n*t}function iy(e){return e<=1e-6&&e>=-1e-6}function ay(e,t,n,r,i){return t==null?e:(as(t)?oy[0]=oy[1]=oy[2]=oy[3]=t:(oy[0]=t[0],oy[1]=t[1],oy[2]=t[2],oy[3]=t[3]),r&&(oy[0]=zs(0,oy[0]),oy[1]=zs(0,oy[1]),oy[2]=zs(0,oy[2]),oy[3]=zs(0,oy[3])),n&&(oy[0]=-oy[0],oy[1]=-oy[1],oy[2]=-oy[2],oy[3]=-oy[3]),sy(e,oy,`x`,`width`,3,1,i&&i[0]||0),sy(e,oy,`y`,`height`,0,2,i&&i[1]||0),e)}var oy=[0,0,0,0];function sy(e,t,n,r,i,a,o){var s=t[a]+t[i],c=e[r];e[r]+=s,o=zs(0,Rs(o,c)),e[r]=0?-t[i]:t[a]>=0?c+t[a]:Bs(s)>1e-8?(c-o)*t[i]/s:0):e[n]-=t[i]}function cy(e){var t=e.itemTooltipOption,n=e.componentModel,r=e.itemName,i=Y(t)?{formatter:t}:t,a=n.mainType,o=n.componentIndex,s={componentType:a,name:r,$vars:[`name`]};s[a+`Index`]=o;var c=e.formatterParamsExtra;c&&G(es(c),function(e){Z(s,e)||(s[e]=c[e],s.$vars.push(e))});var l=jh(e.el);l.componentMainType=a,l.componentIndex=o,l.tooltipConfig={name:r,option:Ko({content:r,encodeHTMLContent:!0,formatterParams:s},i)}}function ly(e,t){var n;e.isGroup&&(n=t(e)),n||e.traverse(t)}function uy(e,t){if(e){if(J(e))for(var n=0;nt&&(t=r),rt&&(n=t=0),{min:n,max:t}}function _y(e,t,n){vy(e,t,n,-1/0)}function vy(e,t,n,r){if(e.ignoreModelZ)return r;var i=e.getTextContent(),a=e.getTextGuideLine();if(e.isGroup)for(var o=e.childrenRef(),s=0;s=0&&n.push(e)}),n}}function nb(e,t){return Uo(Uo({},e,!0),t,!0)}var rb=Math.log(2);function ib(e,t,n,r,i,a){var o=r+`-`+i,s=e.length;if(a.hasOwnProperty(o))return a[o];if(t===1){var c=Math.round(Math.log((1<>1)%2;s.cssText=[`position: absolute`,`visibility: hidden`,`padding: 0`,`margin: 0`,`border-width: 0`,`user-select: none`,`width:0`,`height:0`,r[c]+`:0`,i[l]+`:0`,r[1-c]+`:auto`,i[1-l]+`:auto`,``].join(`!important;`),e.appendChild(o),n.push(o)}return t.clearMarkers=function(){G(n,function(e){e.parentNode&&e.parentNode.removeChild(e)})},n}function fb(e,t,n){for(var r=n?`invTrans`:`trans`,i=t[r],a=t.srcCoords,o=[],s=[],c=!0,l=0;l<4;l++){var u=e[l].getBoundingClientRect(),d=2*l,f=u.left,p=u.top;o.push(f,p),c=c&&a&&f===a[d]&&p===a[d+1],s.push(e[l].offsetLeft,e[l].offsetTop)}return c&&i?i:(t.srcCoords=o,t[r]=n?ab(s,o):ab(o,s))}function pb(e){return e.nodeName.toUpperCase()===`CANVAS`}var mb=/([&<>"'])/g,hb={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};function gb(e){return e==null?``:(e+``).replace(mb,function(e,t){return hb[t]})}var _b={time:{month:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],monthAbbr:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],dayOfWeek:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],dayOfWeekAbbr:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},legend:{selector:{all:`All`,inverse:`Inv`}},toolbox:{brush:{title:{rect:`Box Select`,polygon:`Lasso Select`,lineX:`Horizontally Select`,lineY:`Vertically Select`,keep:`Keep Selections`,clear:`Clear Selections`}},dataView:{title:`Data View`,lang:[`Data View`,`Close`,`Refresh`]},dataZoom:{title:{zoom:`Zoom`,back:`Zoom Reset`}},magicType:{title:{line:`Switch to Line Chart`,bar:`Switch to Bar Chart`,stack:`Stack`,tiled:`Tile`}},restore:{title:`Restore`},saveAsImage:{title:`Save as Image`,lang:[`Right Click to Save Image`]}},series:{typeNames:{pie:`Pie chart`,bar:`Bar chart`,line:`Line chart`,scatter:`Scatter plot`,effectScatter:`Ripple scatter plot`,radar:`Radar chart`,tree:`Tree`,treemap:`Treemap`,boxplot:`Boxplot`,candlestick:`Candlestick`,k:`K line chart`,heatmap:`Heat map`,map:`Map`,parallel:`Parallel coordinate map`,lines:`Line graph`,graph:`Relationship graph`,sankey:`Sankey diagram`,funnel:`Funnel chart`,gauge:`Gauge`,pictorialBar:`Pictorial bar`,themeRiver:`Theme River Map`,sunburst:`Sunburst`,custom:`Custom chart`,chart:`Chart`}},aria:{general:{withTitle:`This is a chart about "{title}"`,withoutTitle:`This is a chart`},series:{single:{prefix:``,withName:` with type {seriesType} named {seriesName}.`,withoutName:` with type {seriesType}.`},multiple:{prefix:`. It consists of {seriesCount} series count.`,withName:` The {seriesId} series is a {seriesType} representing {seriesName}.`,withoutName:` The {seriesId} series is a {seriesType}.`,separator:{middle:``,end:``}}},data:{allData:`The data is as follows: `,partialData:`The first {displayCnt} items are: `,withName:`the data for {name} is {value}`,withoutName:`{value}`,separator:{middle:`, `,end:`. `}}}},vb={time:{month:[`一月`,`二月`,`三月`,`四月`,`五月`,`六月`,`七月`,`八月`,`九月`,`十月`,`十一月`,`十二月`],monthAbbr:[`1月`,`2月`,`3月`,`4月`,`5月`,`6月`,`7月`,`8月`,`9月`,`10月`,`11月`,`12月`],dayOfWeek:[`星期日`,`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`],dayOfWeekAbbr:[`日`,`一`,`二`,`三`,`四`,`五`,`六`]},legend:{selector:{all:`全选`,inverse:`反选`}},toolbox:{brush:{title:{rect:`矩形选择`,polygon:`圈选`,lineX:`横向选择`,lineY:`纵向选择`,keep:`保持选择`,clear:`清除选择`}},dataView:{title:`数据视图`,lang:[`数据视图`,`关闭`,`刷新`]},dataZoom:{title:{zoom:`区域缩放`,back:`区域缩放还原`}},magicType:{title:{line:`切换为折线图`,bar:`切换为柱状图`,stack:`切换为堆叠`,tiled:`切换为平铺`}},restore:{title:`还原`},saveAsImage:{title:`保存为图片`,lang:[`右键另存为图片`]}},series:{typeNames:{pie:`饼图`,bar:`柱状图`,line:`折线图`,scatter:`散点图`,effectScatter:`涟漪散点图`,radar:`雷达图`,tree:`树图`,treemap:`矩形树图`,boxplot:`箱型图`,candlestick:`K线图`,k:`K线图`,heatmap:`热力图`,map:`地图`,parallel:`平行坐标图`,lines:`线图`,graph:`关系图`,sankey:`桑基图`,funnel:`漏斗图`,gauge:`仪表盘图`,pictorialBar:`象形柱图`,themeRiver:`主题河流图`,sunburst:`旭日图`,custom:`自定义图表`,chart:`图表`}},aria:{general:{withTitle:`这是一个关于“{title}”的图表。`,withoutTitle:`这是一个图表,`},series:{single:{prefix:``,withName:`图表类型是{seriesType},表示{seriesName}。`,withoutName:`图表类型是{seriesType}。`},multiple:{prefix:`它由{seriesCount}个图表系列组成。`,withName:`第{seriesId}个系列是一个表示{seriesName}的{seriesType},`,withoutName:`第{seriesId}个系列是一个{seriesType},`,separator:{middle:`;`,end:`。`}}},data:{allData:`其数据是——`,partialData:`其中,前{displayCnt}项是——`,withName:`{name}的数据是{value}`,withoutName:`{value}`,separator:{middle:`,`,end:``}}}},yb=`ZH`,bb=`EN`,xb=bb,Sb={},Cb={},wb=Ns.domSupported?function(){return(document.documentElement.lang||navigator.language||navigator.browserLanguage||xb).toUpperCase().indexOf(yb)>-1?yb:xb}():xb;function Tb(e,t){e=e.toUpperCase(),Cb[e]=new Zy(t),Sb[e]=t}function Eb(e){if(Y(e)){var t=Sb[e.toUpperCase()]||{};return e===yb||e===bb?Ho(t):Uo(Ho(t),Ho(Sb[xb]),!1)}return Uo(Ho(e),Ho(Sb[xb]),!1)}function Db(e){return Cb[e]}function Ob(){return Cb[xb]}Tb(bb,_b),Tb(yb,vb);var kb=null;function Ab(){return kb}function jb(e,t){var n=Ab(),r=t.breakOption,i=t.breakParsed;return!i&&n&&(i=n.parseAxisBreakOption(r,e)),i}function Mb(e){var t=e.brk;return t?t.breaks:[]}function Nb(e){var t=e.brk;return t?t.hasBreaks():!1}var Pb=1e3,Fb=Pb*60,Ib=Fb*60,Lb=Ib*24,Rb=Lb*365,zb={year:/({yyyy}|{yy})/,month:/({MMMM}|{MMM}|{MM}|{M})/,day:/({dd}|{d})/,hour:/({HH}|{H}|{hh}|{h})/,minute:/({mm}|{m})/,second:/({ss}|{s})/,millisecond:/({SSS}|{S})/},Bb={year:`{yyyy}`,month:`{MMM}`,day:`{d}`,hour:`{HH}:{mm}`,minute:`{HH}:{mm}`,second:`{HH}:{mm}:{ss}`,millisecond:`{HH}:{mm}:{ss} {SSS}`},Vb=`{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}`,Hb=`{yyyy}-{MM}-{dd}`,Ub={year:`{yyyy}`,month:`{yyyy}-{MM}`,day:Hb,hour:Hb+` `+Bb.hour,minute:Hb+` `+Bb.minute,second:Hb+` `+Bb.second,millisecond:Vb},Wb=[`year`,`month`,`day`,`hour`,`minute`,`second`,`millisecond`],Gb=[`year`,`half-year`,`quarter`,`month`,`week`,`half-week`,`day`,`half-day`,`quarter-day`,`hour`,`minute`,`second`,`millisecond`];function Kb(e){return!Y(e)&&!rs(e)?qb(e):e}function qb(e){e||={};var t={},n=!0;return G(Wb,function(t){n&&=e[t]==null}),G(Wb,function(r,i){var a=e[r];t[r]={};for(var o=null,s=i;s>=0;s--){var c=Wb[s],l=os(a)&&!J(a)?a[c]:a,u=void 0;J(l)?(u=l.slice(),o=u[0]||``):Y(l)?(o=l,u=[o]):(o==null?o=Bb[r]:zb[c].test(o)||(o=t[c][c][0]+` `+o),u=[o],n&&(u[1]=`{primary|`+o+`}`)),t[r][c]=u}}),t}function Jb(e,t){return e+=``,`0000`.substr(0,t-e.length)+e}function Yb(e){switch(e){case`half-year`:case`quarter`:return`month`;case`week`:case`half-week`:return`day`;case`half-day`:case`quarter-day`:return`hour`;default:return e}}function Xb(e){return e===Yb(e)}function Zb(e){switch(e){case`year`:case`month`:return`day`;case`millisecond`:return`millisecond`;default:return`second`}}function Qb(e,t,n,r){var i=uc(e),a=i[nx(n)](),o=i[rx(n)]()+1,s=Math.floor((o-1)/3)+1,c=i[ix(n)](),l=i[`get`+(n?`UTC`:``)+`Day`](),u=i[ax(n)](),d=(u-1)%12+1,f=i[ox(n)](),p=i[sx(n)](),m=i[cx(n)](),h=u>=12?`pm`:`am`,g=h.toUpperCase(),_=(r instanceof Zy?r:Db(r||wb)||Ob()).getModel(`time`),v=_.get(`month`),y=_.get(`monthAbbr`),b=_.get(`dayOfWeek`),x=_.get(`dayOfWeekAbbr`);return(t||``).replace(/{a}/g,h+``).replace(/{A}/g,g+``).replace(/{yyyy}/g,a+``).replace(/{yy}/g,Jb(a%100+``,2)).replace(/{Q}/g,s+``).replace(/{MMMM}/g,v[o-1]).replace(/{MMM}/g,y[o-1]).replace(/{MM}/g,Jb(o,2)).replace(/{M}/g,o+``).replace(/{dd}/g,Jb(c,2)).replace(/{d}/g,c+``).replace(/{eeee}/g,b[l]).replace(/{ee}/g,x[l]).replace(/{e}/g,l+``).replace(/{HH}/g,Jb(u,2)).replace(/{H}/g,u+``).replace(/{hh}/g,Jb(d+``,2)).replace(/{h}/g,d+``).replace(/{mm}/g,Jb(f,2)).replace(/{m}/g,f+``).replace(/{ss}/g,Jb(p,2)).replace(/{s}/g,p+``).replace(/{SSS}/g,Jb(m,3)).replace(/{S}/g,m+``)}function $b(e,t,n,r,i){var a=null;if(Y(n))a=n;else if(rs(n)){var o={time:e.time,level:e.time?e.time.level:0},s=Ab();s&&s.makeAxisLabelFormatterParamBreak(o,e.break),a=n(e.value,t,o)}else{var c=e.time;if(c){var l=n[c.lowerTimeUnit][c.upperTimeUnit];a=l[Math.min(c.level,l.length-1)]||``}else{var u=ex(e.value,i);a=n[u][u][0]}}return Qb(new Date(e.value),a,i,r)}function ex(e,t){var n=uc(e),r=n[rx(t)]()+1,i=n[ix(t)](),a=n[ax(t)](),o=n[ox(t)](),s=n[sx(t)](),c=n[cx(t)]()===0,l=c&&s===0,u=l&&o===0,d=u&&a===0,f=d&&i===1;return f&&r===1?`year`:f?`month`:d?`day`:u?`hour`:l?`minute`:c?`second`:`millisecond`}function tx(e,t,n){switch(t){case`year`:e[ux(n)](0);case`month`:e[dx(n)](1);case`day`:e[fx(n)](0);case`hour`:e[px(n)](0);case`minute`:e[mx(n)](0);case`second`:e[hx(n)](0)}return e}function nx(e){return e?`getUTCFullYear`:`getFullYear`}function rx(e){return e?`getUTCMonth`:`getMonth`}function ix(e){return e?`getUTCDate`:`getDate`}function ax(e){return e?`getUTCHours`:`getHours`}function ox(e){return e?`getUTCMinutes`:`getMinutes`}function sx(e){return e?`getUTCSeconds`:`getSeconds`}function cx(e){return e?`getUTCMilliseconds`:`getMilliseconds`}function lx(e){return e?`setUTCFullYear`:`setFullYear`}function ux(e){return e?`setUTCMonth`:`setMonth`}function dx(e){return e?`setUTCDate`:`setDate`}function fx(e){return e?`setUTCHours`:`setHours`}function px(e){return e?`setUTCMinutes`:`setMinutes`}function mx(e){return e?`setUTCSeconds`:`setSeconds`}function hx(e){return e?`setUTCMilliseconds`:`setMilliseconds`}function gx(e){if(!gc(e))return Y(e)?e:`-`;var t=(e+``).split(`.`);return t[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,`$1,`)+(t.length>1?`.`+t[1]:``)}function _x(e,t){return e=(e||``).toLowerCase().replace(/-(.)/g,function(e,t){return t.toUpperCase()}),t&&e&&(e=e.charAt(0).toUpperCase()+e.slice(1)),e}var vx=gs;function yx(e,t,n){var r=`{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}`;function i(e){return e&&vs(e)?e:`-`}function a(e){return bc(e)}var o=t===`time`,s=e instanceof Date;if(o||s){var c=o?uc(e):e;if(!isNaN(+c))return Qb(c,r,n);if(s)return`-`}if(t===`ordinal`)return is(e)?i(e):as(e)&&a(e)?e+``:`-`;var l=hc(e);return a(l)?gx(l):is(e)?i(e):typeof e==`boolean`?e+``:`-`}var bx=[`a`,`b`,`c`,`d`,`e`,`f`,`g`],xx=function(e,t){return`{`+e+(t??``)+`}`};function Sx(e,t,n){J(t)||(t=[t]);var r=t.length;if(!r)return``;for(var i=t[0].$vars||[],a=0;a`:``:{renderMode:a,content:`{`+(n.markerId||`markerX`)+`|} `,style:i===`subItem`?{width:4,height:4,borderRadius:2,backgroundColor:r}:{width:10,height:10,borderRadius:5,backgroundColor:r}}:``}function Tx(e,t){return t||=`transparent`,Y(e)?e:os(e)&&e.colorStops&&(e.colorStops[0]||{}).color||t}var Ex={},Dx={},Ox=function(){function e(){this._normalMasterList=[],this._nonSeriesBoxMasterList=[]}return e.prototype.create=function(e,t){this._nonSeriesBoxMasterList=n(Ex,!0),this._normalMasterList=n(Dx,!1);function n(n,r){var i=[];return G(n,function(n,r){var a=n.create(e,t);i=i.concat(a||[])}),i}},e.prototype.update=function(e,t){G(this._normalMasterList,function(n){n.update&&n.update(e,t)})},e.prototype.getCoordinateSystems=function(){return this._normalMasterList.concat(this._nonSeriesBoxMasterList)},e.register=function(e,t){if(e===`matrix`||e===`calendar`){Ex[e]=t;return}Dx[e]=t},e.get=function(e){return Dx[e]||Ex[e]},e}();function kx(e){return!!Ex[e]}var Ax=Es();function jx(e){var t=e.getShallow(`coord`,!0),n=1;if(t==null){var r=Ax.get(e.type);r&&r.getCoord2&&(n=2,t=r.getCoord2(e))}return{coord:t,from:n}}function Mx(e,t){var n=e.getShallow(`coordinateSystem`),r=e.getShallow(`coordinateSystemUsage`,!0),i=0;if(n){var a=e.mainType===`series`;r??=a?`data`:`box`,r===`data`?(i=1,a||(i=0)):r===`box`&&(i=2,!a&&!kx(n)&&(i=0))}return{coordSysType:n,kind:i}}function Nx(e){var t=e.targetModel,n=e.coordSysType,r=e.coordSysProvider,i=e.isDefaultDataCoordSys;e.allowNotFound;var a=Mx(t,!0),o=a.kind,s=a.coordSysType;if(i&&o!==1&&(o=1,s=n),o===0||s!==n)return 0;var c=r(n,t);return c?(o===1?t.coordinateSystem=c:t.boxCoordinateSystem=c,o):0}var Px=G,Fx=[`left`,`right`,`top`,`bottom`,`width`,`height`],Ix=[[`width`,`left`,`right`],[`height`,`top`,`bottom`]];function Lx(e,t,n,r,i){var a=0,o=0;r??=1/0,i??=1/0;var s=0;t.eachChild(function(c,l){var u=c.getBoundingRect(),d=t.childAt(l+1),f=d&&d.getBoundingRect(),p,m;if(e===`horizontal`){var h=u.width+(f?-f.x+u.x:0);p=a+h,p>r||c.newline?(a=0,p=h,o+=s+n,s=u.height):s=Math.max(s,u.height)}else{var g=u.height+(f?-f.y+u.y:0);m=o+g,m>i||c.newline?(a+=s+n,o=0,m=g,s=u.width):s=Math.max(s,u.width)}c.newline||(c.x=a,c.y=o,c.markRedraw(),e===`horizontal`?a=p+n:o=m+n)})}var Rx=Lx;ns(Lx,`vertical`),ns(Lx,`horizontal`);function zx(e,t){return{left:e.getShallow(`left`,t),top:e.getShallow(`top`,t),right:e.getShallow(`right`,t),bottom:e.getShallow(`bottom`,t),width:e.getShallow(`width`,t),height:e.getShallow(`height`,t)}}function Bx(e,t,n){n=vx(n||0);var r=t.width,i=t.height,a=Xs(e.left,r),o=Xs(e.top,i),s=Xs(e.right,r),c=Xs(e.bottom,i),l=Xs(e.width,r),u=Xs(e.height,i),d=n[2]+n[0],f=n[1]+n[3],p=e.aspect;switch(isNaN(l)&&(l=r-s-f-a),isNaN(u)&&(u=i-c-d-o),p!=null&&(isNaN(l)&&isNaN(u)&&(p>r/i?l=r*.8:u=i*.8),isNaN(l)&&(l=p*u),isNaN(u)&&(u=l/p)),isNaN(a)&&(a=r-s-l-f),isNaN(o)&&(o=i-c-u-d),e.left||e.right){case`center`:a=r/2-l/2-n[3];break;case`right`:a=r-l-f}switch(e.top||e.bottom){case`middle`:case`center`:o=i/2-u/2-n[0];break;case`bottom`:o=i-u-d}a||=0,o||=0,isNaN(l)&&(l=r-f-a-(s||0)),isNaN(u)&&(u=i-d-o-(c||0));var m=new Ru((t.x||0)+a+n[3],(t.y||0)+o+n[0],l,u);return m.margin=n,m}var Vx={rect:1,point:2};function Hx(e,t,n){var r,i,a,o=e.boxCoordinateSystem,s;if(o){var c=jx(e),l=c.coord,u=c.from;if(o.dataToLayout){a=Vx.rect,s=u;var d=o.dataToLayout(l);r=d.contentRect||d.rect}else n&&n.enableLayoutOnlyByCenter&&o.dataToPoint&&(a=Vx.point,s=u,i=o.dataToPoint(l))}return a??=Vx.rect,a===Vx.rect&&(r||={x:0,y:0,width:t.getWidth(),height:t.getHeight()},i=[r.x+r.width/2,r.y+r.height/2]),{type:a,refContainer:r,refPoint:i,boxCoordFrom:s}}function Ux(e,t,n,r,i,a){var o=!i||!i.hv||i.hv[0],s=!i||!i.hv||i.hv[1],c=i&&i.boundingMode||`all`;if(a||=e,a.x=e.x,a.y=e.y,!o&&!s)return!1;var l;if(c===`raw`)l=e.type===`group`?new Ru(0,0,+t.width||0,+t.height||0):e.getBoundingRect();else if(l=e.getBoundingRect(),e.needLocalTransform()){var u=e.getLocalTransform();l=l.clone(),l.applyTransform(u)}var d=Bx(Ko({width:l.width,height:l.height},t),n,r),f=o?d.x-l.x:0,p=s?d.y-l.y:0;return c===`raw`?(a.x=f,a.y=p):(a.x+=f,a.y+=p),a===e&&e.markRedraw(),!0}function Wx(e){var t=e.layoutMode||e.constructor.layoutMode;return os(t)?t:t?{type:t}:null}function Gx(e,t,n){var r=n&&n.ignoreSize;!J(r)&&(r=[r,r]);var i=o(Ix[0],0),a=o(Ix[1],1);c(Ix[0],e,i),c(Ix[1],e,a);function o(n,i){var a={},o=0,c={},l=0,u=2;if(Px(n,function(t){c[t]=e[t]}),Px(n,function(e){Z(t,e)&&(a[e]=c[e]=t[e]),s(a,e)&&o++,s(c,e)&&l++}),r[i])return s(t,n[1])?c[n[2]]=null:s(t,n[2])&&(c[n[1]]=null),c;if(l===u||!o)return c;if(o>=u)return a;for(var d=0;d=0;o--)a=Uo(a,n[o],!0);t.defaultOption=a}return t.defaultOption},t.prototype.getReferringComponents=function(e,t){var n=e+`Index`,r=e+`Id`;return il(this.ecModel,e,{index:this.get(n,!0),id:this.get(r,!0)},t)},t.prototype.getBoxLayoutParams=function(){return zx(this,!1)},t.prototype.getZLevelKey=function(){return``},t.prototype.setZLevel=function(e){this.option.zlevel=e},t.protoInitialize=function(){var e=t.prototype;e.type=`component`,e.id=``,e.name=``,e.mainType=``,e.subType=``,e.componentIndex=0}(),t}(Zy);Fl(Yx,Zy),Bl(Yx),eb(Yx),tb(Yx,Xx);function Xx(e){var t=[];return G(Yx.getClassesByMainType(e),function(e){t=t.concat(e.dependencies||e.prototype.dependencies||[])}),t=K(t,function(e){return Al(e).main}),e!==`dataset`&&qo(t,`dataset`)<=0&&t.unshift(`dataset`),t}var Zx=Qc(),Qx=Qc(),$x=function(){function e(){}return e.prototype.getColorFromPalette=function(e,t,n){var r=Ac(this.get(`color`,!0)),i=this.get(`colorLayer`,!0);return nS(this,Zx,r,i,e,t,n)},e.prototype.clearColorPalette=function(){rS(this,Zx)},e}();function eS(e,t,n,r){return nS(e,Qx,Ac(e.get([`aria`,`decal`,`decals`])),null,t,n,r)}function tS(e,t){for(var n=e.length,r=0;rt)return e[r];return e[n-1]}function nS(e,t,n,r,i,a,o){a||=e;var s=t(a),c=s.paletteIdx||0,l=s.paletteNameMap=s.paletteNameMap||{};if(l.hasOwnProperty(i))return l[i];var u=o==null||!r?n:tS(r,o);if(u||=n,u&&u.length){var d=u[c];return i&&(l[i]=d),s.paletteIdx=(c+1)%u.length,d}}function rS(e,t){t(e).paletteIdx=0,t(e).paletteNameMap={}}var iS={Must:1,Might:2,Not:3},aS=Qc();function oS(e){aS(e).datasetMap=Es()}function sS(e,t,n){var r={},i=cS(t);if(!i||!e)return r;var a=[],o=[],s=t.ecModel,c=aS(s).datasetMap,l=i.uid+`_`+n.seriesLayoutBy,u,d;e=e.slice(),G(e,function(t,n){var i=os(t)?t:e[n]={name:t};i.type===`ordinal`&&u==null&&(u=n,d=m(i)),r[i.name]=[]});var f=c.get(l)||c.set(l,{categoryWayDim:d,valueWayDim:0});G(e,function(e,t){var n=e.name,i=m(e);if(u==null){var s=f.valueWayDim;p(r[n],s,i),p(o,s,i),f.valueWayDim+=i}else if(u===t)p(r[n],0,i),p(a,0,i);else{var s=f.categoryWayDim;p(r[n],s,i),p(o,s,i),f.categoryWayDim+=i}});function p(e,t,n){for(var r=0;rl&&(l=p)}s[0]=c,s[1]=l}},r=function(){return this._data?this._data.length/this._dimSize:0};DS=(e={},e[Fh+`_`+Bh]={pure:!0,appendData:i},e[Fh+`_row`]={pure:!0,appendData:function(){throw Error(`Do not support appendData when set seriesLayoutBy: "row".`)}},e[Ih]={pure:!0,appendData:i},e[Lh]={pure:!0,appendData:function(e){var t=this._data;G(e,function(e,n){for(var r=t[n]||(t[n]=[]),i=0;i<(e||[]).length;i++)r.push(e[i])})}},e[Ph]={appendData:i},e[Rh]={persistent:!1,pure:!0,appendData:function(e){this._data=e},clean:function(){this._offset+=this.count(),this._data=null}},e);function i(e){for(var t=0;t=0&&(s=a.interpolatedValue[c])}return s==null?``:s+``})},e.prototype.getRawValue=function(e,t){return VS(this.getData(t),e)},e.prototype.formatTooltip=function(e,t,n){},e}();function WS(e){var t,n;return os(e)?e.type&&(n=e):t=e,{text:t,frag:n}}function GS(e){return new KS(e)}var KS=function(){function e(e){e||={},this._reset=e.reset,this._plan=e.plan,this._count=e.count,this._onDirty=e.onDirty,this._dirty=!0}return e.prototype.perform=function(e){var t=this._upstream,n=e&&e.skip;if(this._dirty&&t){var r=this.context;r.data=r.outputData=t.context.outputData}this.__pipeline&&(this.__pipeline.currentTask=this);var i;this._plan&&!n&&(i=this._plan(this.context));var a=l(this._modBy),o=this._modDataCount||0,s=l(e&&e.modBy),c=e&&e.modDataCount||0;(a!==s||o!==c)&&(i=`reset`);function l(e){return!(e>=1)&&(e=1),e}var u;(this._dirty||i===`reset`)&&(this._dirty=!1,u=this._doReset(n)),this._modBy=s,this._modDataCount=c;var d=e&&e.step;if(this._dueEnd=t?t._outputDueEnd:this._count?this._count(this.context):1/0,this._progress){var f=this._dueIndex,p=Math.min(d==null?1/0:this._dueIndex+d,this._dueEnd);if(!n&&(u||f1&&r>0?s:o}};return a;function o(){return t=e?null:at},gte:function(e,t){return e>=t}};(function(){function e(e,t){as(t)||Ec(``),this._opFn=YS[e],this._rvalFloat=hc(t)}return e.prototype.evaluate=function(e){return as(e)?this._opFn(e,this._rvalFloat):this._opFn(hc(e),this._rvalFloat)},e})();var XS=function(){function e(e,t){var n=e===`desc`;this._resultLT=n?1:-1,t??=n?`min`:`max`,this._incomparable=t===`min`?-1/0:1/0}return e.prototype.evaluate=function(e,t){var n=as(e)?e:hc(e),r=as(t)?t:hc(t),i=isNaN(n),a=isNaN(r);if(i&&(n=this._incomparable),a&&(r=this._incomparable),i&&a){var o=Y(e),s=Y(t);o&&(n=s?e:0),s&&(r=o?t:0)}return nr?-this._resultLT:0},e}();(function(){function e(e,t){this._rval=t,this._isEQ=e,this._rvalTypeof=typeof t,this._rvalFloat=hc(t)}return e.prototype.evaluate=function(e){var t=e===this._rval;if(!t){var n=typeof e;n!==this._rvalTypeof&&(n===`number`||this._rvalTypeof===`number`)&&(t=hc(e)===this._rvalFloat)}return this._isEQ?t:!t},e})();function ZS(e){var t=``,n=-1/0,r=-1/0,i=1/0,a=1/0;return e&&(e.g!=null&&(t+=`G`+e.g,n=e.g),e.ge!=null&&(t+=`GE`+e.ge,r=e.ge),e.l!=null&&(t+=`L`+e.l,i=e.l),e.le!=null&&(t+=`LE`+e.le,a=e.le)),{key:t,g:n,ge:r,l:i,le:a}}function QS(e,t){return t>e.g&&t>=e.ge&&t`u`?Array:Uint32Array,dC=typeof Uint16Array>`u`?Array:Uint16Array,fC=typeof Int32Array>`u`?Array:Int32Array,pC=typeof Float64Array>`u`?Array:Float64Array,mC={float:pC,int:fC,ordinal:Array,number:Array,time:pC},hC;function gC(e){return e>65535?uC:dC}function _C(e){var t=e.constructor;return t===Array?e.slice():new t(e)}function vC(e,t,n,r,i){var a=mC[n||`float`];if(i){var o=e[t],s=o&&o.length;if(s!==r){for(var c=new a(r),l=0;lh[1]&&(h[1]=m)}return this._rawCount=this._count=s,{start:o,end:s}},e.prototype._initDataFromProvider=function(e,t,n){for(var r=this._provider,i=this._chunks,a=this._dimensions,o=a.length,s=this._rawExtent,c=K(a,function(e){return e.property}),l=0;lg[1]&&(g[1]=h)}}!r.persistent&&r.clean&&r.clean(),this._rawCount=this._count=t,this._extent=[]},e.prototype.count=function(){return this._count},e.prototype.get=function(e,t){if(!(t>=0&&t=0&&t=this._rawCount||e<0)return-1;if(!this._indices)return e;var t=this._indices,n=t[e];if(n!=null&&ne)i=a-1;else return a}return-1},e.prototype.getIndices=function(){var e,t=this._indices;if(t){var n=t.constructor,r=this._count;if(n===Array){e=new n(r);for(var i=0;i=l&&g<=u||isNaN(g))&&(o[s++]=p),p++}f=!0}else if(i===2){for(var m=d[r[0]],_=d[r[1]],v=e[r[1]][0],y=e[r[1]][1],h=0;h=l&&g<=u||isNaN(g))&&(b>=v&&b<=y||isNaN(b))&&(o[s++]=p),p++}f=!0}}if(!f){if(i===1)for(var h=0;h=l&&g<=u||isNaN(g))&&(o[s++]=x)}else for(var h=0;he[w][1])&&(S=!1)}S&&(o[s++]=t.getRawIndex(h))}}return sg[1]&&(g[1]=h)}}}},e.prototype.lttbDownSample=function(e,t){var n=this.clone([e],!0),r=n._chunks[e],i=this.count(),a=0,o=Math.floor(1/t),s=this.getRawIndex(0),c,l,u,d=new(gC(this._rawCount))(Math.min((Math.ceil(i/o)+2)*2,i));d[a++]=s;for(var f=1;fc&&(c=l,u=v)}T>0&&To&&(m=o-l);for(var h=0;hp&&(p=g,f=l+h)}var _=this.getRawIndex(u),v=this.getRawIndex(f);ul-p&&(s=l-p,o.length=s);for(var m=0;mu[1]&&(u[1]=g),d[f++]=_}return i._count=f,i._indices=d,i._updateGetRawIdx(),i},e.prototype.each=function(e,t){if(this._count)for(var n=e.length,r=this._chunks,i=0,a=this.count();id&&(d=p))}return o[c]=[u,d]},e.prototype.getRawDataItem=function(e){var t=this.getRawIndex(e);if(this._provider.persistent)return this._provider.getItem(t);for(var n=[],r=this._chunks,i=0;i=0?this._indices[e]:-1},e.prototype._updateGetRawIdx=function(){this.getRawIndex=this._indices?this._getRawIdx:this._getRawIdxIdentity},e.internalField=function(){function e(e,t,n,r){return JS(e[r],this._dimensions[r])}hC={arrayRows:e,objectRows:function(e,t,n,r){return JS(e[t],this._dimensions[r])},keyedColumns:e,original:function(e,t,n,r){var i=e&&(e.value==null?e:e.value);return JS(i instanceof Array?i[r]:i,this._dimensions[r])},typedArray:function(e,t,n,r){return e[r]}}}(),e}(),bC=function(){function e(e){this._sourceList=[],this._storeList=[],this._upstreamSignList=[],this._versionSignBase=0,this._dirty=!0,this._sourceHost=e}return e.prototype.dirty=function(){this._setLocalSource([],[]),this._storeList=[],this._dirty=!0},e.prototype._setLocalSource=function(e,t){this._sourceList=e,this._upstreamSignList=t,this._versionSignBase++,this._versionSignBase>9e10&&(this._versionSignBase=0)},e.prototype._getVersionSign=function(){return this._sourceHost.uid+`_`+this._versionSignBase},e.prototype.prepareSource=function(){this._isDirty()&&(this._createSource(),this._dirty=!1)},e.prototype._createSource=function(){this._setLocalSource([],[]);var e=this._sourceHost,t=this._getUpstreamSourceManagers(),n=!!t.length,r,i;if(xC(e)){var a=e,o=void 0,s=void 0,c=void 0;if(n){var l=t[0];l.prepareSource(),c=l.getSource(),o=c.data,s=c.sourceFormat,i=[l._getVersionSign()]}else o=a.get(`data`,!0),s=cs(o)?Rh:Ph,i=[];var u=this._getSourceMetaRawOption()||{},d=c&&c.metaRawOption||{},f=X(u.seriesLayoutBy,d.seriesLayoutBy)||null,p=X(u.sourceHeader,d.sourceHeader),m=X(u.dimensions,d.dimensions);r=f!==d.seriesLayoutBy||!!p!=!!d.sourceHeader||m?[mS(o,{seriesLayoutBy:f,sourceHeader:p,dimensions:m},s)]:[]}else{var h=e;if(n){var g=this._applyTransform(t);r=g.sourceList,i=g.upstreamSignList}else r=[mS(h.get(`source`,!0),this._getSourceMetaRawOption(),null)],i=[]}this._setLocalSource(r,i)},e.prototype._applyTransform=function(e){var t=this._sourceHost,n=t.get(`transform`,!0),r=t.get(`fromTransformResult`,!0);r!=null&&e.length!==1&&SC(``);var i,a=[],o=[];return G(e,function(e){e.prepareSource();var t=e.getSource(r||0);r!=null&&!t&&SC(``),a.push(t),o.push(e._getVersionSign())}),n?i=sC(n,a,{datasetIndex:t.componentIndex}):r!=null&&(i=[gS(a[0])]),{sourceList:i,upstreamSignList:o}},e.prototype._isDirty=function(){if(this._dirty)return!0;for(var e=this._getUpstreamSourceManagers(),t=0;tn:i+u+m>n){u?(s||c)&&(h?(s||(s=c,c=``,l=0,u=l),a.push(s),o.push(u-l),c+=p,l+=m,s=``,u=l):(c&&(s+=c,c=``,l=0),a.push(s),o.push(u),s=p,u=m)):h?(a.push(c),o.push(l),c=p,l=m):(a.push(p),o.push(m));continue}u+=m,h?(c+=p,l+=m):(c&&(s+=c,c=``,l=0),s+=p)}return c&&(s+=c),s&&(a.push(s),o.push(u)),a.length===1&&(u+=i),{accumWidth:u,lines:a,linesWidths:o}}function Td(e,t,n,r,i,a){if(e.baseX=n,e.baseY=r,e.outerWidth=e.outerHeight=null,t){var o=t.width*2,s=t.height*2;Ru.set(Ed,ad(n,o,i),od(r,s,a),o,s),Ru.intersect(t,Ed,null,Dd);var c=Dd.outIntersectRect;e.outerWidth=c.width,e.outerHeight=c.height,e.baseX=ad(c.x,c.width,i,!0),e.baseY=od(c.y,c.height,a,!0)}}var Ed=new Ru(0,0,0,0),Dd={outIntersectRect:{},clamp:!0};function Od(e){return e==null?e=``:e+=``}function kd(e){var t=Od(e.text),n=e.font;return Ad(e,nd(Xu(n),t),sd(n),null)}function Ad(e,t,n,r){var i=new Ru(ad(e.x||0,t,e.textAlign),od(e.y||0,n,e.textBaseline),t,n),a=r??(jd(e)?e.lineWidth:0);return a>0&&(i.x-=a/2,i.y-=a/2,i.width+=a,i.height+=a),i}function jd(e){var t=e.stroke;return t!=null&&t!==`none`&&e.lineWidth>0}var Md=$l,Nd=5e-5;function Pd(e){return e>Nd||e<-Nd}var Fd=[],Id=[],Ld=Ql(),Rd=Math.abs,zd=function(){function e(){}return e.prototype.getLocalTransform=function(e){return Bd(this,e)},e.prototype.setPosition=function(e){this.x=e[0],this.y=e[1]},e.prototype.setScale=function(e){this.scaleX=e[0],this.scaleY=e[1]},e.prototype.setSkew=function(e){this.skewX=e[0],this.skewY=e[1]},e.prototype.setOrigin=function(e){this.originX=e[0],this.originY=e[1]},e.prototype.needLocalTransform=function(){return Pd(this.rotation)||Pd(this.x)||Pd(this.y)||Pd(this.scaleX-1)||Pd(this.scaleY-1)||Pd(this.skewX)||Pd(this.skewY)},e.prototype.updateTransform=function(){var e=this.parent&&this.parent.transform,t=this.needLocalTransform(),n=this.transform;if(!(t||e)){n&&(Md(n),this.invTransform=null);return}n||=Ql(),t?this.getLocalTransform(n):Md(n),e&&(t?tu(n,e,n):eu(n,e)),this.transform=n,this._resolveGlobalScaleRatio(n),this.invTransform=this.invTransform||Ql(),au(this.invTransform,n)},e.prototype._resolveGlobalScaleRatio=function(e){var t=this.globalScaleRatio;if(t!=null&&t!==1){this.getGlobalScale(Fd);var n=Fd[0]<0?-1:1,r=Fd[1]<0?-1:1,i=((Fd[0]-n)*t+n)/Fd[0]||0,a=((Fd[1]-r)*t+r)/Fd[1]||0;e[0]*=i,e[1]*=i,e[2]*=a,e[3]*=a}},e.prototype.getComputedTransform=function(){for(var e=this,t=[];e;)t.push(e),e=e.parent;for(;e=t.pop();)e.updateTransform();return this.transform},e.prototype.setLocalTransform=function(e){if(e){var t=e[0]*e[0]+e[1]*e[1],n=e[2]*e[2]+e[3]*e[3],r=Math.atan2(e[1],e[0]),i=Math.PI/2+r-Math.atan2(e[3],e[2]);n=Math.sqrt(n)*Math.cos(i),t=Math.sqrt(t),this.skewX=i,this.skewY=0,this.rotation=-r,this.x=+e[4],this.y=+e[5],this.scaleX=t,this.scaleY=n,this.originX=0,this.originY=0}},e.prototype.decomposeTransform=function(){if(this.transform){var e=this.parent,t=this.transform;e&&e.transform&&(e.invTransform=e.invTransform||Ql(),tu(Id,e.invTransform,t),t=Id);var n=this.originX,r=this.originY;(n||r)&&(Ld[4]=n,Ld[5]=r,tu(Id,t,Ld),Id[4]-=n,Id[5]-=r,t=Id),this.setLocalTransform(t)}},e.prototype.getGlobalScale=function(e){var t=this.transform;return e||=[],t?(e[0]=Math.sqrt(t[0]*t[0]+t[1]*t[1]),e[1]=Math.sqrt(t[2]*t[2]+t[3]*t[3]),t[0]<0&&(e[0]=-e[0]),t[3]<0&&(e[1]=-e[1]),e):(e[0]=1,e[1]=1,e)},e.prototype.transformCoordToLocal=function(e,t){var n=[e,t],r=this.invTransform;return r&&xu(n,n,r),n},e.prototype.transformCoordToGlobal=function(e,t){var n=[e,t],r=this.transform;return r&&xu(n,n,r),n},e.prototype.getLineScale=function(){var e=this.transform;return e&&Rd(e[0]-1)>1e-10&&Rd(e[3]-1)>1e-10?Math.sqrt(Rd(e[0]*e[3]-e[2]*e[1])):1},e.prototype.copyTransform=function(e){Ud(this,e)},e.getLocalTransform=function(e,t){t||=[];var n=e.originX||0,r=e.originY||0,i=e.scaleX,a=e.scaleY,o=e.anchorX,s=e.anchorY,c=e.rotation||0,l=e.x,u=e.y,d=e.skewX?Math.tan(e.skewX):0,f=e.skewY?Math.tan(-e.skewY):0;if(n||r||o||s){var p=n+o,m=r+s;t[4]=-p*i-d*m*a,t[5]=-m*a-f*p*i}else t[4]=t[5]=0;return t[0]=i,t[3]=a,t[1]=f*i,t[2]=d*a,c&&ru(t,t,c),t[4]+=n+l,t[5]+=r+u,t},e.initDefaultProps=(function(){var t=e.prototype;t.scaleX=t.scaleY=t.globalScaleRatio=1,t.x=t.y=t.originX=t.originY=t.skewX=t.skewY=t.rotation=t.anchorX=t.anchorY=0})(),e}(),Bd=zd.getLocalTransform;function Vd(){return new zd}var Hd=[`x`,`y`,`originX`,`originY`,`anchorX`,`anchorY`,`rotation`,`scaleX`,`scaleY`,`skewX`,`skewY`];function Ud(e,t){return Go(e,t,Hd)}var Wd={linear:function(e){return e},quadraticIn:function(e){return e*e},quadraticOut:function(e){return e*(2-e)},quadraticInOut:function(e){return(e*=2)<1?.5*e*e:-.5*(--e*(e-2)-1)},cubicIn:function(e){return e*e*e},cubicOut:function(e){return--e*e*e+1},cubicInOut:function(e){return(e*=2)<1?.5*e*e*e:.5*((e-=2)*e*e+2)},quarticIn:function(e){return e*e*e*e},quarticOut:function(e){return 1- --e*e*e*e},quarticInOut:function(e){return(e*=2)<1?.5*e*e*e*e:-.5*((e-=2)*e*e*e-2)},quinticIn:function(e){return e*e*e*e*e},quinticOut:function(e){return--e*e*e*e*e+1},quinticInOut:function(e){return(e*=2)<1?.5*e*e*e*e*e:.5*((e-=2)*e*e*e*e+2)},sinusoidalIn:function(e){return 1-Math.cos(e*Math.PI/2)},sinusoidalOut:function(e){return Math.sin(e*Math.PI/2)},sinusoidalInOut:function(e){return .5*(1-Math.cos(Math.PI*e))},exponentialIn:function(e){return e===0?0:1024**(e-1)},exponentialOut:function(e){return e===1?1:1-2**(-10*e)},exponentialInOut:function(e){return e===0?0:e===1?1:(e*=2)<1?.5*1024**(e-1):.5*(-(2**(-10*(e-1)))+2)},circularIn:function(e){return 1-Math.sqrt(1-e*e)},circularOut:function(e){return Math.sqrt(1- --e*e)},circularInOut:function(e){return(e*=2)<1?-.5*(Math.sqrt(1-e*e)-1):.5*(Math.sqrt(1-(e-=2)*e)+1)},elasticIn:function(e){var t,n=.1,r=.4;return e===0?0:e===1?1:(!n||n<1?(n=1,t=r/4):t=r*Math.asin(1/n)/(2*Math.PI),-(n*2**(10*--e)*Math.sin((e-t)*(2*Math.PI)/r)))},elasticOut:function(e){var t,n=.1,r=.4;return e===0?0:e===1?1:(!n||n<1?(n=1,t=r/4):t=r*Math.asin(1/n)/(2*Math.PI),n*2**(-10*e)*Math.sin((e-t)*(2*Math.PI)/r)+1)},elasticInOut:function(e){var t,n=.1,r=.4;return e===0?0:e===1?1:(!n||n<1?(n=1,t=r/4):t=r*Math.asin(1/n)/(2*Math.PI),(e*=2)<1?-.5*(n*2**(10*--e)*Math.sin((e-t)*(2*Math.PI)/r)):n*2**(-10*--e)*Math.sin((e-t)*(2*Math.PI)/r)*.5+1)},backIn:function(e){var t=1.70158;return e*e*((t+1)*e-t)},backOut:function(e){var t=1.70158;return--e*e*((t+1)*e+t)+1},backInOut:function(e){var t=2.5949095;return(e*=2)<1?.5*(e*e*((t+1)*e-t)):.5*((e-=2)*e*((t+1)*e+t)+2)},bounceIn:function(e){return 1-Wd.bounceOut(1-e)},bounceOut:function(e){return e<1/2.75?7.5625*e*e:e<2/2.75?7.5625*(e-=1.5/2.75)*e+.75:e<2.5/2.75?7.5625*(e-=2.25/2.75)*e+.9375:7.5625*(e-=2.625/2.75)*e+.984375},bounceInOut:function(e){return e<.5?Wd.bounceIn(e*2)*.5:Wd.bounceOut(e*2-1)*.5+.5}},Gd=Math.pow,Kd=Math.sqrt,qd=1e-8,Jd=1e-4,Yd=Kd(3),Xd=1/3,Zd=ou(),Qd=ou(),$d=ou();function ef(e){return e>-qd&&eqd||e<-qd}function nf(e,t,n,r,i){var a=1-i;return a*a*(a*e+3*i*t)+i*i*(i*r+3*a*n)}function rf(e,t,n,r,i){var a=1-i;return 3*(((t-e)*a+2*(n-t)*i)*a+(r-n)*i*i)}function af(e,t,n,r,i,a){var o=r+3*(t-n)-e,s=3*(n-t*2+e),c=3*(t-e),l=e-i,u=s*s-3*o*c,d=s*c-9*o*l,f=c*c-3*s*l,p=0;if(ef(u)&&ef(d)){if(ef(s))a[0]=0;else{var m=-c/s;m>=0&&m<=1&&(a[p++]=m)}}else{var h=d*d-4*u*f;if(ef(h)){var g=d/u,m=-s/o+g,_=-g/2;m>=0&&m<=1&&(a[p++]=m),_>=0&&_<=1&&(a[p++]=_)}else if(h>0){var v=Kd(h),y=u*s+1.5*o*(-d+v),b=u*s+1.5*o*(-d-v);y=y<0?-Gd(-y,Xd):Gd(y,Xd),b=b<0?-Gd(-b,Xd):Gd(b,Xd);var m=(-s-(y+b))/(3*o);m>=0&&m<=1&&(a[p++]=m)}else{var x=(2*u*s-3*o*d)/(2*Kd(u*u*u)),S=Math.acos(x)/3,C=Kd(u),w=Math.cos(S),m=(-s-2*C*w)/(3*o),_=(-s+C*(w+Yd*Math.sin(S)))/(3*o),T=(-s+C*(w-Yd*Math.sin(S)))/(3*o);m>=0&&m<=1&&(a[p++]=m),_>=0&&_<=1&&(a[p++]=_),T>=0&&T<=1&&(a[p++]=T)}}return p}function of(e,t,n,r,i){var a=6*n-12*t+6*e,o=9*t+3*r-3*e-9*n,s=3*t-3*e,c=0;if(ef(o)){if(tf(a)){var l=-s/a;l>=0&&l<=1&&(i[c++]=l)}}else{var u=a*a-4*o*s;if(ef(u))i[0]=-a/(2*o);else if(u>0){var d=Kd(u),l=(-a+d)/(2*o),f=(-a-d)/(2*o);l>=0&&l<=1&&(i[c++]=l),f>=0&&f<=1&&(i[c++]=f)}}return c}function sf(e,t,n,r,i,a){var o=(t-e)*i+e,s=(n-t)*i+t,c=(r-n)*i+n,l=(s-o)*i+o,u=(c-s)*i+s,d=(u-l)*i+l;a[0]=e,a[1]=o,a[2]=l,a[3]=d,a[4]=d,a[5]=u,a[6]=c,a[7]=r}function cf(e,t,n,r,i,a,o,s,c,l,u){var d,f=.005,p=1/0,m,h,g,_;Zd[0]=c,Zd[1]=l;for(var v=0;v<1;v+=.05)Qd[0]=nf(e,n,i,o,v),Qd[1]=nf(t,r,a,s,v),g=yu(Zd,Qd),g=0&&g=0&&l<=1&&(i[c++]=l)}}else{var u=o*o-4*a*s;if(ef(u)){var l=-o/(2*a);l>=0&&l<=1&&(i[c++]=l)}else if(u>0){var d=Kd(u),l=(-o+d)/(2*a),f=(-o-d)/(2*a);l>=0&&l<=1&&(i[c++]=l),f>=0&&f<=1&&(i[c++]=f)}}return c}function pf(e,t,n){var r=e+n-2*t;return r===0?.5:(e-t)/r}function mf(e,t,n,r,i){var a=(t-e)*r+e,o=(n-t)*r+t,s=(o-a)*r+a;i[0]=e,i[1]=a,i[2]=s,i[3]=s,i[4]=o,i[5]=n}function hf(e,t,n,r,i,a,o,s,c){var l,u=.005,d=1/0;Zd[0]=o,Zd[1]=s;for(var f=0;f<1;f+=.05){Qd[0]=uf(e,n,i,f),Qd[1]=uf(t,r,a,f);var p=yu(Zd,Qd);p=0&&p=1?1:af(0,r,a,1,e,s)&&nf(0,i,o,1,s[0])}}}var yf=function(){function e(e){this._inited=!1,this._startTime=0,this._pausedTime=0,this._paused=!1,this._life=e.life||1e3,this._delay=e.delay||0,this.loop=e.loop||!1,this.onframe=e.onframe||As,this.ondestroy=e.ondestroy||As,this.onrestart=e.onrestart||As,e.easing&&this.setEasing(e.easing)}return e.prototype.step=function(e,t){if(this._inited||=(this._startTime=e+this._delay,!0),this._paused){this._pausedTime+=t;return}var n=this._life,r=e-this._startTime-this._pausedTime,i=r/n;i<0&&(i=0),i=Math.min(i,1);var a=this.easingFunc,o=a?a(i):i;if(this.onframe(o),i===1){if(this.loop){var s=r%n;this._startTime=e-s,this._pausedTime=0,this.onrestart()}else return!0}return!1},e.prototype.pause=function(){this._paused=!0},e.prototype.resume=function(){this._paused=!1},e.prototype.setEasing=function(e){this.easing=e,this.easingFunc=rs(e)?e:Wd[e]||vf(e)},e}(),bf={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function xf(e){return e=Math.round(e),e<0?0:e>255?255:e}function Sf(e){return e=Math.round(e),e<0?0:e>360?360:e}function Cf(e){return e<0?0:e>1?1:e}function wf(e){var t=e;return t.length&&t.charAt(t.length-1)===`%`?xf(parseFloat(t)/100*255):xf(parseInt(t,10))}function Tf(e){var t=e;return t.length&&t.charAt(t.length-1)===`%`?Cf(parseFloat(t)/100):Cf(parseFloat(t))}function Ef(e,t,n){return n<0?n+=1:n>1&&--n,n*6<1?e+(t-e)*n*6:n*2<1?t:n*3<2?e+(t-e)*(2/3-n)*6:e}function Df(e,t,n){return e+(t-e)*n}function Of(e,t,n,r,i){return e[0]=t,e[1]=n,e[2]=r,e[3]=i,e}function kf(e,t){return e[0]=t[0],e[1]=t[1],e[2]=t[2],e[3]=t[3],e}var Af=new Kl(20),jf=null;function Mf(e,t){jf&&kf(jf,t),jf=Af.put(e,jf||t.slice())}function Nf(e,t){if(e){t||=[];var n=Af.get(e);if(n)return kf(t,n);e+=``;var r=e.replace(/ /g,``).toLowerCase();if(r in bf)return kf(t,bf[r]),Mf(e,t),t;var i=r.length;if(r.charAt(0)===`#`){if(i===4||i===5){var a=parseInt(r.slice(1,4),16);if(!(a>=0&&a<=4095)){Of(t,0,0,0,1);return}return Of(t,(a&3840)>>4|(a&3840)>>8,a&240|(a&240)>>4,a&15|(a&15)<<4,i===5?parseInt(r.slice(4),16)/15:1),Mf(e,t),t}if(i===7||i===9){var a=parseInt(r.slice(1,7),16);if(!(a>=0&&a<=16777215)){Of(t,0,0,0,1);return}return Of(t,(a&16711680)>>16,(a&65280)>>8,a&255,i===9?parseInt(r.slice(7),16)/255:1),Mf(e,t),t}return}var o=r.indexOf(`(`),s=r.indexOf(`)`);if(o!==-1&&s+1===i){var c=r.substr(0,o),l=r.substr(o+1,s-(o+1)).split(`,`),u=1;switch(c){case`rgba`:if(l.length!==4)return l.length===3?Of(t,+l[0],+l[1],+l[2],1):Of(t,0,0,0,1);u=Tf(l.pop());case`rgb`:if(l.length>=3)return Of(t,wf(l[0]),wf(l[1]),wf(l[2]),l.length===3?u:Tf(l[3])),Mf(e,t),t;Of(t,0,0,0,1);return;case`hsla`:if(l.length!==4){Of(t,0,0,0,1);return}return l[3]=Tf(l[3]),Pf(l,t),Mf(e,t),t;case`hsl`:if(l.length!==3){Of(t,0,0,0,1);return}return Pf(l,t),Mf(e,t),t;default:return}}Of(t,0,0,0,1)}}function Pf(e,t){var n=(parseFloat(e[0])%360+360)%360/360,r=Tf(e[1]),i=Tf(e[2]),a=i<=.5?i*(r+1):i+r-i*r,o=i*2-a;return t||=[],Of(t,xf(Ef(o,a,n+1/3)*255),xf(Ef(o,a,n)*255),xf(Ef(o,a,n-1/3)*255),1),e.length===4&&(t[3]=e[3]),t}function Ff(e){if(e){var t=e[0]/255,n=e[1]/255,r=e[2]/255,i=Math.min(t,n,r),a=Math.max(t,n,r),o=a-i,s=(a+i)/2,c,l;if(o===0)c=0,l=0;else{l=s<.5?o/(a+i):o/(2-a-i);var u=((a-t)/6+o/2)/o,d=((a-n)/6+o/2)/o,f=((a-r)/6+o/2)/o;t===a?c=f-d:n===a?c=1/3+u-f:r===a&&(c=2/3+d-u),c<0&&(c+=1),c>1&&--c}var p=[c*360,l,s];return e[3]!=null&&p.push(e[3]),p}}function If(e,t){var n=Nf(e);if(n){for(var r=0;r<3;r++)t<0?n[r]=n[r]*(1-t)|0:n[r]=(255-n[r])*t+n[r]|0,n[r]>255?n[r]=255:n[r]<0&&(n[r]=0);return Vf(n,n.length===4?`rgba`:`rgb`)}}function Lf(e,t,n){if(t&&t.length&&e>=0&&e<=1){n||=[];var r=e*(t.length-1),i=Math.floor(r),a=Math.ceil(r),o=t[i],s=t[a],c=r-i;return n[0]=xf(Df(o[0],s[0],c)),n[1]=xf(Df(o[1],s[1],c)),n[2]=xf(Df(o[2],s[2],c)),n[3]=Cf(Df(o[3],s[3],c)),n}}function Rf(e,t,n){if(t&&t.length&&e>=0&&e<=1){var r=e*(t.length-1),i=Math.floor(r),a=Math.ceil(r),o=Nf(t[i]),s=Nf(t[a]),c=r-i,l=Vf([xf(Df(o[0],s[0],c)),xf(Df(o[1],s[1],c)),xf(Df(o[2],s[2],c)),Cf(Df(o[3],s[3],c))],`rgba`);return n?{color:l,leftIndex:i,rightIndex:a,value:r}:l}}function zf(e,t,n,r){var i=Nf(e);if(e)return i=Ff(i),t!=null&&(i[0]=Sf(rs(t)?t(i[0]):t)),n!=null&&(i[1]=Tf(rs(n)?n(i[1]):n)),r!=null&&(i[2]=Tf(rs(r)?r(i[2]):r)),Vf(Pf(i),`rgba`)}function Bf(e,t){var n=Nf(e);if(n&&t!=null)return n[3]=Cf(t),Vf(n,`rgba`)}function Vf(e,t){if(e&&e.length){var n=e[0]+`,`+e[1]+`,`+e[2];return(t===`rgba`||t===`hsva`||t===`hsla`)&&(n+=`,`+e[3]),t+`(`+n+`)`}}function Hf(e,t){var n=Nf(e);return n?(.299*n[0]+.587*n[1]+.114*n[2])*n[3]/255+(1-n[3])*t:0}var Uf=new Kl(100);function Wf(e){if(Y(e)){var t=Uf.get(e);return t||(t=If(e,-.1),Uf.put(e,t)),t}if(us(e)){var n=W({},e);return n.colorStops=K(e.colorStops,function(e){return{offset:e.offset,color:If(e.color,-.1)}}),n}return e}function Gf(e){return e.type===`linear`}function Kf(e){return e.type===`radial`}(function(){return typeof Buffer<`u`&&typeof Buffer.from==`function`?function(e){return Buffer.from(e).toString(`base64`)}:typeof btoa==`function`&&typeof unescape==`function`&&typeof encodeURIComponent==`function`?function(e){return btoa(unescape(encodeURIComponent(e)))}:function(e){return null}})();var qf=Array.prototype.slice;function Jf(e,t,n){return(t-e)*n+e}function Yf(e,t,n,r){for(var i=t.length,a=0;ar?t:e,a=Math.min(n,r),o=i[a-1]||{color:[0,0,0,0],offset:0},s=a;so)r.length=o;else for(var s=a;s=1},e.prototype.getAdditiveTrack=function(){return this._additiveTrack},e.prototype.addKeyframe=function(e,t,n){this._needsSort=!0;var r=this.keyframes,i=r.length,a=!1,o=up,s=t;if(Xo(t)){var c=rp(t);o=c,(c===1&&!as(t[0])||c===2&&!as(t[0][0]))&&(a=!0)}else if(as(t)&&!fs(t))o=ip;else if(Y(t)){if(!isNaN(+t))o=ip;else{var l=Nf(t);l&&(s=l,o=sp)}}else if(us(t)){var u=W({},s);u.colorStops=K(t.colorStops,function(e){return{offset:e.offset,color:Nf(e.color)}}),Gf(t)?o=cp:Kf(t)&&(o=lp),s=u}i===0?this.valType=o:(o!==this.valType||o===up)&&(a=!0),this.discrete=this.discrete||a;var d={time:e,value:s,rawValue:t,percent:0};return n&&(d.easing=n,d.easingFunc=rs(n)?n:Wd[n]||vf(n)),r.push(d),d},e.prototype.prepare=function(e,t){var n=this.keyframes;this._needsSort&&n.sort(function(e,t){return e.time-t.time});for(var r=this.valType,i=n.length,a=n[i-1],o=this.discrete,s=fp(r),c=dp(r),l=0;l=0&&!(a[l].percent<=t);l--);l=d(l,o-2)}else{for(l=u;lt);l++);l=d(l-1,o-2)}p=a[l+1],f=a[l]}if(f&&p){this._lastFr=l,this._lastFrP=t;var m=p.percent-f.percent,h=m===0?1:d((t-f.percent)/m,1);p.easingFunc&&(h=p.easingFunc(h));var g=n?this._additiveValue:c?pp:e[s];if((fp(i)||c)&&!g&&(g=this._additiveValue=[]),this.discrete)e[s]=h<1?f.rawValue:p.rawValue;else if(fp(i))i===ap?Yf(g,f[r],p[r],h):Xf(g,f[r],p[r],h);else if(dp(i)){var _=f[r],v=p[r],y=i===cp;e[s]={type:y?`linear`:`radial`,x:Jf(_.x,v.x,h),y:Jf(_.y,v.y,h),colorStops:K(_.colorStops,function(e,t){var n=v.colorStops[t];return{offset:Jf(e.offset,n.offset,h),color:np(Yf([],e.color,n.color,h))}}),global:v.global},y?(e[s].x2=Jf(_.x2,v.x2,h),e[s].y2=Jf(_.y2,v.y2,h)):e[s].r=Jf(_.r,v.r,h)}else if(c)Yf(g,f[r],p[r],h),n||(e[s]=np(g));else{var b=Jf(f[r],p[r],h);n?this._additiveValue=b:e[s]=b}n&&this._addToTarget(e)}}},e.prototype._addToTarget=function(e){var t=this.valType,n=this.propName,r=this._additiveValue;t===ip?e[n]=e[n]+r:t===sp?(Nf(e[n],pp),Zf(pp,pp,r,1),e[n]=np(pp)):t===ap?Zf(e[n],e[n],r,1):t===op&&Qf(e[n],e[n],r,1)},e}(),hp=function(){function e(e,t,n,r){if(this._tracks={},this._trackKeys=[],this._maxTime=0,this._started=0,this._clip=null,this._target=e,this._loop=t,t&&r){Vo(`Can' use additive animation on looped animation.`);return}this._additiveAnimators=r,this._allowDiscrete=n}return e.prototype.getMaxTime=function(){return this._maxTime},e.prototype.getDelay=function(){return this._delay},e.prototype.getLoop=function(){return this._loop},e.prototype.getTarget=function(){return this._target},e.prototype.changeTarget=function(e){this._target=e},e.prototype.when=function(e,t,n){return this.whenWithKeys(e,t,es(t),n)},e.prototype.whenWithKeys=function(e,t,n,r){for(var i=this._tracks,a=0;a0&&s.addKeyframe(0,tp(c),r),this._trackKeys.push(o)}s.addKeyframe(e,tp(t[o]),r)}return this._maxTime=Math.max(this._maxTime,e),this},e.prototype.pause=function(){this._clip.pause(),this._paused=!0},e.prototype.resume=function(){this._clip.resume(),this._paused=!1},e.prototype.isPaused=function(){return!!this._paused},e.prototype.duration=function(e){return this._maxTime=e,this._force=!0,this},e.prototype._doneCallback=function(){this._setTracksFinished(),this._clip=null;var e=this._doneCbs;if(e)for(var t=e.length,n=0;n0)){this._started=1;for(var t=this,n=[],r=this._maxTime||0,i=0;i1){var o=a.pop();i.addKeyframe(o.time,e[r]),i.prepare(this._maxTime,i.getAdditiveTrack())}}}},e}(),gp=function(){function e(e){e&&(this._$eventProcessor=e)}return e.prototype.on=function(e,t,n,r){this._$handlers||={};var i=this._$handlers;if(typeof t==`function`&&(r=n,n=t,t=null),!n||!e)return this;var a=this._$eventProcessor;t!=null&&a&&a.normalizeQuery&&(t=a.normalizeQuery(t)),i[e]||(i[e]=[]);for(var o=0;o=0:n.inside,y=void 0,b=void 0,x=void 0;v&&this.canBeInsideText()?(y=n.insideFill,b=n.insideStroke,(y==null||y===`auto`)&&(y=this.getInsideTextFill()),(b==null||b===`auto`)&&(b=this.getInsideTextStroke(y),x=!0)):(y=n.outsideFill,b=n.outsideStroke,(y==null||y===`auto`)&&(y=this.getOutsideFill()),(b==null||b===`auto`)&&(b=this.getOutsideStroke(y),x=!0)),y||=`#000`,(y!==g.fill||b!==g.stroke||x!==g.autoStroke||a!==g.align||o!==g.verticalAlign)&&(s=!0,g.fill=y,g.stroke=b,g.autoStroke=x,g.align=a,g.verticalAlign=o,t.setDefaultTextStyle(g)),t.__dirty|=1,s&&t.dirtyStyle(!0)}},e.prototype.canBeInsideText=function(){return!0},e.prototype.getInsideTextFill=function(){return`#fff`},e.prototype.getInsideTextStroke=function(e){return`#000`},e.prototype.getOutsideFill=function(){return this.__zr&&this.__zr.isDarkMode()?xp:bp},e.prototype.getOutsideStroke=function(e){var t=this.__zr&&this.__zr.getBackgroundColor(),n=typeof t==`string`&&Nf(t);n||=[255,255,255,1];for(var r=n[3],i=this.__zr.isDarkMode(),a=0;a<3;a++)n[a]=n[a]*r+(i?0:255)*(1-r);return n[3]=1,Vf(n,`rgba`)},e.prototype.traverse=function(e,t){},e.prototype.attrKV=function(e,t){e===`textConfig`?this.setTextConfig(t):e===`textContent`?this.setTextContent(t):e===`clipPath`?this.setClipPath(t):e===`extra`?(this.extra=this.extra||{},W(this.extra,t)):this[e]=t},e.prototype.hide=function(){this.ignore=!0,this.markRedraw()},e.prototype.show=function(){this.ignore=!1,this.markRedraw()},e.prototype.attr=function(e,t){if(typeof e==`string`)this.attrKV(e,t);else if(os(e))for(var n=es(e),r=0;r0},e.prototype.getState=function(e){return this.states[e]},e.prototype.ensureState=function(e){var t=this.states;return t[e]||(t[e]={}),t[e]},e.prototype.clearStates=function(e){this.useState(Cp,!1,e)},e.prototype.useState=function(e,t,n,r){var i=e===Cp;if(this.hasState()||!i){var a=this.currentStates,o=this.stateTransition;if(!(qo(a,e)>=0&&(t||a.length===1))){var s;if(this.stateProxy&&!i&&(s=this.stateProxy(e)),s||=this.states&&this.states[e],!s&&!i){Vo(`State `+e+` not exists.`);return}i||this.saveCurrentToNormalState(s);var c=this._textContent,l=Lp(this,c,s,r);l&&!this.__inHover&&(this.__inHover=l),this._applyStateObj(e,s,this._normalState,t,zp(this,n,o),o);var u=this._textGuide;return c&&c.useState(e,t,n,!!l),u&&u.useState(e,t,n,!!l),i?(this.currentStates=[],this._normalState={}):t?this.currentStates.push(e):this.currentStates=[e],this._updateAnimationTargets(),this.markRedraw(),!l&&this.__inHover&&(this.__inHover=0,this.__dirty&=-2),s}}},e.prototype.useStates=function(e,t,n){if(!e.length)this.clearStates();else{var r=[],i=this.currentStates,a=e.length,o=a===i.length;if(o){for(var s=0;s=0){var n=this.currentStates.slice();n.splice(t,1),this.useStates(n)}},e.prototype.replaceState=function(e,t,n){var r=this.currentStates.slice(),i=qo(r,e),a=qo(r,t)>=0;i>=0?a?r.splice(i,1):r[i]=t:n&&!a&&r.push(t),this.useStates(r)},e.prototype.toggleState=function(e,t){t?this.useState(e,!0):this.removeState(e)},e.prototype._mergeStates=function(e){for(var t={},n,r=0;r=0&&t.splice(n,1)}),this.animators.push(e),n&&n.animation.addAnimator(e),n&&n.wakeUp()},e.prototype.updateDuringAnimation=function(e){this.markRedraw()},e.prototype.stopAnimation=function(e,t){for(var n=this.animators,r=n.length,i=[],a=0;a0&&n.during&&a[0].during(function(e,t){n.during(t)});for(var f=0;f0||i.force&&!o.length){var C=void 0,w=void 0,T=void 0;if(s){w={},f&&(C={});for(var b=0;b0}var Bp=`__zr_style_`+Math.round(Math.random()*10),Vp={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:`#000`,opacity:1,blend:`source-over`},Hp={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};Vp[Bp]=!0;var Up=[`z`,`z2`,`invisible`],Wp=[`invisible`],Gp=function(e){U(t,e);function t(t){return e.call(this,t)||this}return t.prototype._init=function(t){for(var n=es(t),r=0;r1e-4){s[0]=e-n,s[1]=t-r,c[0]=e+n,c[1]=t+r;return}if(em[0]=Qp(i)*n+e,em[1]=Zp(i)*r+t,tm[0]=Qp(a)*n+e,tm[1]=Zp(a)*r+t,l(s,em,tm),u(c,em,tm),i%=$p,i<0&&(i+=$p),a%=$p,a<0&&(a+=$p),i>a&&!o?a+=$p:ii&&(nm[0]=Qp(p)*n+e,nm[1]=Zp(p)*r+t,l(s,nm,s),u(c,nm,c))}var lm={M:1,L:2,C:3,Q:4,A:5,Z:6,R:7},um=[],dm=[],fm=[],pm=[],mm=[],hm=[],gm=Math.min,_m=Math.max,vm=Math.cos,ym=Math.sin,bm=Math.abs,xm=Math.PI,Sm=xm*2,Cm=typeof Float32Array<`u`,wm=[];function Tm(e){return Math.round(e/xm*1e8)/1e8%2*xm}function Em(e,t){var n=Tm(e[0]);n<0&&(n+=Sm);var r=n-e[0],i=e[1];i+=r,!t&&i-n>=Sm?i=n+Sm:t&&n-i>=Sm?i=n-Sm:!t&&n>i?i=n+(Sm-Tm(n-i)):t&&n0&&(this._ux=bm(n/vp/e)||0,this._uy=bm(n/vp/t)||0)},e.prototype.setDPR=function(e){this.dpr=e},e.prototype.setContext=function(e){this._ctx=e},e.prototype.getContext=function(){return this._ctx},e.prototype.beginPath=function(){return this._ctx&&this._ctx.beginPath(),this.reset(),this},e.prototype.reset=function(){this._saveData&&(this._len=0),this._pathSegLen&&(this._pathSegLen=null,this._pathLen=0),this._version++},e.prototype.moveTo=function(e,t){return this._drawPendingPt(),this.addData(lm.M,e,t),this._ctx&&this._ctx.moveTo(e,t),this._x0=e,this._y0=t,this._xi=e,this._yi=t,this},e.prototype.lineTo=function(e,t){var n=bm(e-this._xi),r=bm(t-this._yi),i=n>this._ux||r>this._uy;if(this.addData(lm.L,e,t),this._ctx&&i&&this._ctx.lineTo(e,t),i)this._xi=e,this._yi=t,this._pendingPtDist=0;else{var a=n*n+r*r;a>this._pendingPtDist&&(this._pendingPtX=e,this._pendingPtY=t,this._pendingPtDist=a)}return this},e.prototype.bezierCurveTo=function(e,t,n,r,i,a){return this._drawPendingPt(),this.addData(lm.C,e,t,n,r,i,a),this._ctx&&this._ctx.bezierCurveTo(e,t,n,r,i,a),this._xi=i,this._yi=a,this},e.prototype.quadraticCurveTo=function(e,t,n,r){return this._drawPendingPt(),this.addData(lm.Q,e,t,n,r),this._ctx&&this._ctx.quadraticCurveTo(e,t,n,r),this._xi=n,this._yi=r,this},e.prototype.arc=function(e,t,n,r,i,a){this._drawPendingPt(),wm[0]=r,wm[1]=i,Em(wm,a),r=wm[0],i=wm[1];var o=i-r;return this.addData(lm.A,e,t,n,n,r,o,0,+!a),this._ctx&&this._ctx.arc(e,t,n,r,i,a),this._xi=vm(i)*n+e,this._yi=ym(i)*n+t,this},e.prototype.arcTo=function(e,t,n,r,i){return this._drawPendingPt(),this._ctx&&this._ctx.arcTo(e,t,n,r,i),this},e.prototype.rect=function(e,t,n,r){return this._drawPendingPt(),this._ctx&&this._ctx.rect(e,t,n,r),this.addData(lm.R,e,t,n,r),this},e.prototype.closePath=function(){this._drawPendingPt(),this.addData(lm.Z);var e=this._ctx,t=this._x0,n=this._y0;return e&&e.closePath(),this._xi=t,this._yi=n,this},e.prototype.fill=function(e){e&&e.fill(),this.toStatic()},e.prototype.stroke=function(e){e&&e.stroke(),this.toStatic()},e.prototype.len=function(){return this._len},e.prototype.setData=function(e){if(this._saveData){var t=e.length;!(this.data&&this.data.length===t)&&Cm&&(this.data=new Float32Array(t));for(var n=0;n0&&a))for(var o=0;ol.length&&(this._expandData(),l=this.data);for(var u=0;u0&&(this._ctx&&this._ctx.lineTo(this._pendingPtX,this._pendingPtY),this._pendingPtDist=0)},e.prototype._expandData=function(){if(!(this.data instanceof Array)){for(var e=[],t=0;t11&&(this.data=new Float32Array(e)))}},e.prototype.getBoundingRect=function(){fm[0]=fm[1]=mm[0]=mm[1]=Number.MAX_VALUE,pm[0]=pm[1]=hm[0]=hm[1]=-Number.MAX_VALUE;for(var e=this.data,t=0,n=0,r=0,i=0,a=0;an||bm(v)>r||d===t-1)&&(m=Math.sqrt(_*_+v*v),i=h,a=g);break;case lm.C:var y=e[d++],b=e[d++],h=e[d++],g=e[d++],x=e[d++],S=e[d++];m=lf(i,a,y,b,h,g,x,S,10),i=x,a=S;break;case lm.Q:var y=e[d++],b=e[d++],h=e[d++],g=e[d++];m=gf(i,a,y,b,h,g,10),i=h,a=g;break;case lm.A:var C=e[d++],w=e[d++],T=e[d++],E=e[d++],D=e[d++],O=e[d++],k=O+D;d+=1,p&&(o=vm(D)*T+C,s=ym(D)*E+w),m=_m(T,E)*gm(Sm,Math.abs(O)),i=vm(k)*T+C,a=ym(k)*E+w;break;case lm.R:o=i=e[d++],s=a=e[d++];var A=e[d++],j=e[d++];m=A*2+j*2;break;case lm.Z:var _=o-i,v=s-a;m=Math.sqrt(_*_+v*v),i=o,a=s}m>=0&&(c[u++]=m,l+=m)}return this._pathLen=l,l},e.prototype.rebuildPath=function(e,t){var n=this.data,r=this._ux,i=this._uy,a=this._len,o,s,c,l,u,d,f=t<1,p,m,h=0,g=0,_,v=0,y,b;if(!(f&&(this._pathSegLen||this._calculateLength(),p=this._pathSegLen,m=this._pathLen,_=t*m,!_)))lo:for(var x=0;x0&&(e.lineTo(y,b),v=0),S){case lm.M:o=c=n[x++],s=l=n[x++],e.moveTo(c,l);break;case lm.L:u=n[x++],d=n[x++];var w=bm(u-c),T=bm(d-l);if(w>r||T>i){if(f){var E=p[g++];if(h+E>_){var D=(_-h)/E;e.lineTo(c*(1-D)+u*D,l*(1-D)+d*D);break lo}h+=E}e.lineTo(u,d),c=u,l=d,v=0}else{var O=w*w+T*T;O>v&&(y=u,b=d,v=O)}break;case lm.C:var k=n[x++],A=n[x++],j=n[x++],M=n[x++],N=n[x++],P=n[x++];if(f){var E=p[g++];if(h+E>_){var D=(_-h)/E;sf(c,k,j,N,D,um),sf(l,A,M,P,D,dm),e.bezierCurveTo(um[1],dm[1],um[2],dm[2],um[3],dm[3]);break lo}h+=E}e.bezierCurveTo(k,A,j,M,N,P),c=N,l=P;break;case lm.Q:var k=n[x++],A=n[x++],j=n[x++],M=n[x++];if(f){var E=p[g++];if(h+E>_){var D=(_-h)/E;mf(c,k,j,D,um),mf(l,A,M,D,dm),e.quadraticCurveTo(um[1],dm[1],um[2],dm[2]);break lo}h+=E}e.quadraticCurveTo(k,A,j,M),c=j,l=M;break;case lm.A:var F=n[x++],I=n[x++],L=n[x++],ee=n[x++],te=n[x++],ne=n[x++],re=n[x++],ie=!n[x++],ae=L>ee?L:ee,R=bm(L-ee)>.001,oe=te+ne,z=!1;if(f){var E=p[g++];h+E>_&&(oe=te+ne*(_-h)/E,z=!0),h+=E}if(R&&e.ellipse?e.ellipse(F,I,L,ee,re,te,oe,ie):e.arc(F,I,ae,te,oe,ie),z)break lo;C&&(o=vm(te)*L+F,s=ym(te)*ee+I),c=vm(oe)*L+F,l=ym(oe)*ee+I;break;case lm.R:o=c=n[x],s=l=n[x+1],u=n[x++],d=n[x++];var se=n[x++],ce=n[x++];if(f){var E=p[g++];if(h+E>_){var le=_-h;e.moveTo(u,d),e.lineTo(u+gm(le,se),d),le-=se,le>0&&e.lineTo(u+se,d+gm(le,ce)),le-=ce,le>0&&e.lineTo(u+_m(se-le,0),d+ce),le-=se,le>0&&e.lineTo(u,d+_m(ce-le,0));break lo}h+=E}e.rect(u,d,se,ce);break;case lm.Z:if(f){var E=p[g++];if(h+E>_){var D=(_-h)/E;e.lineTo(c*(1-D)+o*D,l*(1-D)+s*D);break lo}h+=E}e.closePath(),c=o,l=s}}},e.prototype.clone=function(){var t=new e,n=this.data;return t.data=n.slice?n.slice():Array.prototype.slice.call(n),t._len=this._len,t},e.prototype.canSave=function(){return!!this._saveData},e.CMD=lm,e.initDefaultProps=(function(){var t=e.prototype;t._saveData=!0,t._ux=0,t._uy=0,t._pendingPtDist=0,t._version=0})(),e}();function Om(e,t,n,r,i,a,o){if(i===0)return!1;var s=i,c=0,l=e;if(o>t+s&&o>r+s||oe+s&&a>n+s||at+d&&u>r+d&&u>a+d&&u>s+d||ue+d&&l>n+d&&l>i+d&&l>o+d||lt+l&&c>r+l&&c>a+l||ce+l&&s>n+l&&s>i+l||sn||u+li&&(i+=Nm);var f=Math.atan2(c,s);return f<0&&(f+=Nm),f>=r&&f<=i||f+Nm>=r&&f+Nm<=i}function Fm(e,t,n,r,i,a){if(a>t&&a>r||ai?s:0}var Im=Dm.CMD,Lm=Math.PI*2,Rm=1e-4;function zm(e,t){return Math.abs(e-t)t&&l>r&&l>a&&l>s||l1&&Hm(),p=nf(t,r,a,s,Vm[0]),f>1&&(m=nf(t,r,a,s,Vm[1]))),f===2?gt&&s>r&&s>a||s=0&&l<=1){for(var u=0,d=uf(t,r,a,l),f=0;fn||s<-n)return 0;var c=Math.sqrt(n*n-s*s);Bm[0]=-c,Bm[1]=c;var l=Math.abs(r-i);if(l<1e-4)return 0;if(l>=Lm-1e-4){r=0,i=Lm;var u=a?1:-1;return o>=Bm[0]+e&&o<=Bm[1]+e?u:0}if(r>i){var d=r;r=i,i=d}r<0&&(r+=Lm,i+=Lm);for(var f=0,p=0;p<2;p++){var m=Bm[p];if(m+e>o){var h=Math.atan2(s,m),u=a?1:-1;h<0&&(h=Lm+h),(h>=r&&h<=i||h+Lm>=r&&h+Lm<=i)&&(h>Math.PI/2&&h1&&(n||(s+=Fm(c,l,u,d,r,i))),g&&(c=a[m],l=a[m+1],u=c,d=l),h){case Im.M:u=a[m++],d=a[m++],c=u,l=d;break;case Im.L:if(n){if(Om(c,l,a[m],a[m+1],t,r,i))return!0}else s+=Fm(c,l,a[m],a[m+1],r,i)||0;c=a[m++],l=a[m++];break;case Im.C:if(n){if(km(c,l,a[m++],a[m++],a[m++],a[m++],a[m],a[m+1],t,r,i))return!0}else s+=Um(c,l,a[m++],a[m++],a[m++],a[m++],a[m],a[m+1],r,i)||0;c=a[m++],l=a[m++];break;case Im.Q:if(n){if(Am(c,l,a[m++],a[m++],a[m],a[m+1],t,r,i))return!0}else s+=Wm(c,l,a[m++],a[m++],a[m],a[m+1],r,i)||0;c=a[m++],l=a[m++];break;case Im.A:var _=a[m++],v=a[m++],y=a[m++],b=a[m++],x=a[m++],S=a[m++];m+=1;var C=!!(1-a[m++]);f=Math.cos(x)*y+_,p=Math.sin(x)*b+v,g?(u=f,d=p):s+=Fm(c,l,f,p,r,i);var w=(r-_)*b/y+_;if(n){if(Pm(_,v,b,x,x+S,C,t,w,i))return!0}else s+=Gm(_,v,b,x,x+S,C,w,i);c=Math.cos(x+S)*y+_,l=Math.sin(x+S)*b+v;break;case Im.R:u=c=a[m++],d=l=a[m++];var T=a[m++],E=a[m++];if(f=u+T,p=d+E,n){if(Om(u,d,f,d,t,r,i)||Om(f,d,f,p,t,r,i)||Om(f,p,u,p,t,r,i)||Om(u,p,u,d,t,r,i))return!0}else s+=Fm(f,d,f,p,r,i),s+=Fm(u,p,u,d,r,i);break;case Im.Z:if(n){if(Om(c,l,u,d,t,r,i))return!0}else s+=Fm(c,l,u,d,r,i);c=u,l=d}}return!n&&!zm(l,d)&&(s+=Fm(c,l,u,d,r,i)||0),s!==0}function qm(e,t,n){return Km(e,0,!1,t,n)}function Jm(e,t,n,r){return Km(e,t,!0,n,r)}var Ym=Ko({fill:`#000`,stroke:null,strokePercent:1,fillOpacity:1,strokeOpacity:1,lineDashOffset:0,lineWidth:1,lineCap:`butt`,miterLimit:10,strokeNoScale:!1,strokeFirst:!1},Vp),Xm={style:Ko({fill:!0,stroke:!0,strokePercent:!0,fillOpacity:!0,strokeOpacity:!0,lineDashOffset:!0,lineWidth:!0,miterLimit:!0},Hp.style)},Zm=Hd.concat([`invisible`,`culling`,`z`,`z2`,`zlevel`,`parent`]),Qm=function(e){U(t,e);function t(t){return e.call(this,t)||this}return t.prototype.update=function(){var n=this;e.prototype.update.call(this);var r=this.style;if(r.decal){var i=this._decalEl=this._decalEl||new t;i.buildPath===t.prototype.buildPath&&(i.buildPath=function(e){n.buildPath(e,n.shape)}),i.silent=!0;var a=i.style;for(var o in r)a[o]!==r[o]&&(a[o]=r[o]);a.fill=r.fill?r.decal:null,a.decal=null,a.shadowColor=null,r.strokeFirst&&(a.stroke=null);for(var s=0;s.5?bp:t>.2?Sp:xp}if(e)return xp}return bp},t.prototype.getInsideTextStroke=function(e){var t=this.style.fill;if(Y(t)){var n=this.__zr;if(!!(n&&n.isDarkMode())==Hf(e,0)<.4)return t}},t.prototype.buildPath=function(e,t,n){},t.prototype.pathUpdated=function(){this.__dirty&=-5},t.prototype.getUpdatedPathProxy=function(e){return!this.path&&this.createPathProxy(),this.path.beginPath(),this.buildPath(this.path,this.shape,e),this.path},t.prototype.createPathProxy=function(){this.path=new Dm(!1)},t.prototype.hasStroke=function(){var e=this.style,t=e.stroke;return!(t==null||t===`none`||!(e.lineWidth>0))},t.prototype.hasFill=function(){var e=this.style.fill;return e!=null&&e!==`none`},t.prototype.getBoundingRect=function(){var e=this._rect,t=this.style,n=!e;if(n){var r=!1;this.path||(r=!0,this.createPathProxy());var i=this.path;(r||this.__dirty&4)&&(i.beginPath(),this.buildPath(i,this.shape,!1),this.pathUpdated()),e=i.getBoundingRect()}if(this._rect=e,this.hasStroke()&&this.path&&this.path.len()>0){var a=this._rectStroke||=e.clone();if(this.__dirty||n){a.copy(e);var o=t.strokeNoScale?this.getLineScale():1,s=t.lineWidth;if(!this.hasFill()){var c=this.strokeContainThreshold;s=Math.max(s,c??4)}o>1e-10&&(a.width+=s/o,a.height+=s/o,a.x-=s/o/2,a.y-=s/o/2)}return a}return e},t.prototype.contain=function(e,t){var n=this.transformCoordToLocal(e,t),r=this.getBoundingRect(),i=this.style;if(e=n[0],t=n[1],r.contain(e,t)){var a=this.path;if(this.hasStroke()){var o=i.lineWidth,s=i.strokeNoScale?this.getLineScale():1;if(s>1e-10&&(this.hasFill()||(o=Math.max(o,this.strokeContainThreshold)),Jm(a,o/s,e,t)))return!0}if(this.hasFill())return qm(a,e,t)}return!1},t.prototype.dirtyShape=function(){this.__dirty|=4,this._rect&&=null,this._decalEl&&this._decalEl.dirtyShape(),this.markRedraw()},t.prototype.dirty=function(){this.dirtyStyle(),this.dirtyShape()},t.prototype.animateShape=function(e){return this.animate(`shape`,e)},t.prototype.updateDuringAnimation=function(e){e===`style`?this.dirtyStyle():e===`shape`?this.dirtyShape():this.markRedraw()},t.prototype.attrKV=function(t,n){t===`shape`?this.setShape(n):e.prototype.attrKV.call(this,t,n)},t.prototype.setShape=function(e,t){var n=this.shape;return n||=this.shape={},typeof e==`string`?n[e]=t:W(n,e),this.dirtyShape(),this},t.prototype.shapeChanged=function(){return!!(this.__dirty&4)},t.prototype.createStyle=function(e){return Os(Ym,e)},t.prototype._innerSaveToNormal=function(t){e.prototype._innerSaveToNormal.call(this,t);var n=this._normalState;t.shape&&!n.shape&&(n.shape=W({},this.shape))},t.prototype._applyStateObj=function(t,n,r,i,a,o){if(e.prototype._applyStateObj.call(this,t,n,r,i,a,o),this.__inHover!==1){var s=!(n&&i),c;if(n&&n.shape?a?i?c=n.shape:(c=W({},r.shape),W(c,n.shape)):(c=W({},i?this.shape:r.shape),W(c,n.shape)):s&&(c=r.shape),c){if(a){this.shape=W({},this.shape);for(var l={},u=es(c),d=0;di&&(d=s+c,s*=i/d,c*=i/d),l+u>i&&(d=l+u,l*=i/d,u*=i/d),c+l>a&&(d=c+l,c*=a/d,l*=a/d),s+u>a&&(d=s+u,s*=a/d,u*=a/d),e.moveTo(n+s,r),e.lineTo(n+i-c,r),c!==0&&e.arc(n+i-c,r+c,c,-Math.PI/2,0),e.lineTo(n+i,r+a-l),l!==0&&e.arc(n+i-l,r+a-l,l,0,Math.PI/2),e.lineTo(n+u,r+a),u!==0&&e.arc(n+u,r+a-u,u,Math.PI/2,Math.PI),e.lineTo(n,r+s),s!==0&&e.arc(n+s,r+s,s,Math.PI,Math.PI*1.5),e.closePath()}var oh=Math.round;function sh(e,t,n){if(t){var r=t.x1,i=t.x2,a=t.y1,o=t.y2;e.x1=r,e.x2=i,e.y1=a,e.y2=o;var s=n&&n.lineWidth;return s?(oh(r*2)===oh(i*2)&&(e.x1=e.x2=lh(r,s,!0)),oh(a*2)===oh(o*2)&&(e.y1=e.y2=lh(a,s,!0)),e):e}}function ch(e,t,n){if(t){var r=t.x,i=t.y,a=t.width,o=t.height;e.x=r,e.y=i,e.width=a,e.height=o;var s=n&&n.lineWidth;return s?(e.x=lh(r,s,!0),e.y=lh(i,s,!0),e.width=Math.max(lh(r+a,s,!1)-e.x,a===0?0:1),e.height=Math.max(lh(i+o,s,!1)-e.y,o===0?0:1),e):e}}function lh(e,t,n){if(!t)return e;var r=oh(e*2);return(r+oh(t))%2==0?r/2:(r+(n?1:-1))/2}var uh=function(){function e(){this.x=0,this.y=0,this.width=0,this.height=0}return e}(),dh={},fh=function(e){U(t,e);function t(t){return e.call(this,t)||this}return t.prototype.getDefaultShape=function(){return new uh},t.prototype.buildPath=function(e,t){var n,r,i,a;if(this.subPixelOptimize){var o=ch(dh,t,this.style);n=o.x,r=o.y,i=o.width,a=o.height,o.r=t.r,t=o}else n=t.x,r=t.y,i=t.width,a=t.height;t.r?ah(e,t):e.rect(n,r,i,a)},t.prototype.isZeroArea=function(){return!this.shape.width||!this.shape.height},t}(Qm);fh.prototype.type=`rect`;var ph={fill:`#000`},mh=2,hh={},gh={style:Ko({fill:!0,stroke:!0,fillOpacity:!0,strokeOpacity:!0,lineWidth:!0,fontSize:!0,lineHeight:!0,width:!0,height:!0,textShadowColor:!0,textShadowBlur:!0,textShadowOffsetX:!0,textShadowOffsetY:!0,backgroundColor:!0,padding:!0,borderColor:!0,borderWidth:!0,borderRadius:!0},Hp.style)},_h=function(e){U(t,e);function t(t){var n=e.call(this)||this;return n.type=`text`,n._children=[],n._defaultStyle=ph,n.attr(t),n}return t.prototype.childrenRef=function(){return this._children},t.prototype.update=function(){e.prototype.update.call(this),this.styleChanged()&&this._updateSubTexts();for(var t=0;t0,T=0;T=0&&(D=y[E],D.align===`right`);)this._placeToken(D,e,x,m,T,`right`,g),S-=D.width,T-=D.width,E--;for(w+=(s-(w-p)-(h-T)-S)/2;C<=E;)D=y[C],this._placeToken(D,e,x,m,w+D.width/2,`center`,g),w+=D.width,C++;m+=x}},t.prototype._placeToken=function(e,t,n,r,i,a,o){var s=t.rich[e.styleName]||{};s.text=e.text;var c=e.verticalAlign,l=r+n/2;c===`top`?l=r+e.height/2:c===`bottom`&&(l=r+n-e.height/2),!e.isLineHolder&&Ah(s)&&this._renderBackground(s,t,a===`right`?i-e.width:a===`center`?i-e.width/2:i,l-e.height/2,e.width,e.height);var u=!!s.backgroundColor,d=e.textPadding;d&&(i=Oh(i,a,d),l-=e.height/2-d[0]-e.innerHeight/2);var f=this._getOrCreateChild(eh),p=f.createStyle();f.useStyle(p);var m=this._defaultStyle,h=!1,g=0,_=!1,v=Dh(`fill`in s?s.fill:`fill`in t?t.fill:(h=!0,m.fill)),y=Eh(`stroke`in s?s.stroke:`stroke`in t?t.stroke:!u&&!o&&(!m.autoStroke||h)?(g=mh,_=!0,m.stroke):null),b=s.textShadowBlur>0||t.textShadowBlur>0;p.text=e.text,p.x=i,p.y=l,b&&(p.shadowBlur=s.textShadowBlur||t.textShadowBlur||0,p.shadowColor=s.textShadowColor||t.textShadowColor||`transparent`,p.shadowOffsetX=s.textShadowOffsetX||t.textShadowOffsetX||0,p.shadowOffsetY=s.textShadowOffsetY||t.textShadowOffsetY||0),p.textAlign=a,p.textBaseline=`middle`,p.font=e.font||`12px sans-serif`,p.opacity=ms(s.opacity,t.opacity,1),Sh(p,s),y&&(p.lineWidth=ms(s.lineWidth,t.lineWidth,g),p.lineDash=X(s.lineDash,t.lineDash),p.lineDashOffset=t.lineDashOffset||0,p.stroke=y),v&&(p.fill=v),f.setBoundingRect(Ad(p,e.contentWidth,e.contentHeight,_?0:null))},t.prototype._renderBackground=function(e,t,n,r,i,a){var o=e.backgroundColor,s=e.borderWidth,c=e.borderColor,l=o&&o.image,u=o&&!l,d=e.borderRadius,f=this,p,m;if(u||e.lineHeight||s&&c){p=this._getOrCreateChild(fh),p.useStyle(p.createStyle()),p.style.fill=null;var h=p.shape;h.x=n,h.y=r,h.width=i,h.height=a,h.r=d,p.dirtyShape()}if(u){var g=p.style;g.fill=o||null,g.fillOpacity=X(e.fillOpacity,1)}else if(l){m=this._getOrCreateChild(ih),m.onload=function(){f.dirtyStyle()};var _=m.style;_.image=o.image,_.x=n,_.y=r,_.width=i,_.height=a}if(s&&c){var g=p.style;g.lineWidth=s,g.stroke=c,g.strokeOpacity=X(e.strokeOpacity,1),g.lineDash=e.borderDash,g.lineDashOffset=e.borderDashOffset||0,p.strokeContainThreshold=0,p.hasFill()&&p.hasStroke()&&(g.strokeFirst=!0,g.lineWidth*=2)}var v=(p||m).style;v.shadowBlur=e.shadowBlur||0,v.shadowColor=e.shadowColor||`transparent`,v.shadowOffsetX=e.shadowOffsetX||0,v.shadowOffsetY=e.shadowOffsetY||0,v.opacity=ms(e.opacity,t.opacity,1)},t.makeFont=function(e){var t=``;return Ch(e)&&(t=[e.fontStyle,e.fontWeight,xh(e.fontSize),e.fontFamily||`sans-serif`].join(` `)),t&&vs(t)||e.textFont||e.font},t}(Gp),vh={left:!0,right:1,center:1},yh={top:1,bottom:1,middle:1},bh=[`fontStyle`,`fontWeight`,`fontSize`,`fontFamily`];function xh(e){return typeof e==`string`&&(e.indexOf(`px`)!==-1||e.indexOf(`rem`)!==-1||e.indexOf(`em`)!==-1)?e:isNaN(+e)?`12px`:e+`px`}function Sh(e,t){for(var n=0;n=0,a=!1;if(e instanceof Qm){var o=Kh(e),s=i&&o.selectFill||o.normalFill,c=i&&o.selectStroke||o.normalStroke;if(ng(s)||ng(c)){r||={};var l=r.style||{};l.fill===`inherit`?(a=!0,r=W({},r),l=W({},l),l.fill=s):!ng(l.fill)&&ng(s)?(a=!0,r=W({},r),l=W({},l),l.fill=Wf(s)):!ng(l.stroke)&&ng(c)&&(a||(r=W({},r),l=W({},l)),l.stroke=Wf(c)),r.style=l}}if(r&&r.z2==null){a||(r=W({},r));var u=e.z2EmphasisLift;r.z2=e.z2+(u??10)}return r}function hg(e,t,n){if(n&&n.z2==null){n=W({},n);var r=e.z2SelectLift;n.z2=e.z2+(r??9)}return n}function gg(e,t,n){var r=qo(e.currentStates,t)>=0,i=e.style.opacity,a=r?null:pg(e,[`opacity`],t,{opacity:1});n||={};var o=n.style||{};return o.opacity??(n=W({},n),o=W({opacity:r?i:a.opacity*.1},o),n.style=o),n}function _g(e,t){var n=this.states[e];if(this.style){if(e===`emphasis`)return mg(this,e,t,n);if(e===`blur`)return gg(this,e,n);if(e===`select`)return hg(this,e,n)}return n}function vg(e){e.stateProxy=_g;var t=e.getTextContent(),n=e.getTextGuideLine();t&&(t.stateProxy=_g),n&&(n.stateProxy=_g)}function yg(e,t){!Dg(e,t)&&!e.__highByOuter&&dg(e,ig)}function bg(e,t){!Dg(e,t)&&!e.__highByOuter&&dg(e,ag)}function xg(e,t){e.__highByOuter|=1<<(t||0),dg(e,ig)}function Sg(e,t){!(e.__highByOuter&=~(1<<(t||0)))&&dg(e,ag)}function Cg(e){dg(e,og)}function wg(e){dg(e,sg)}function Tg(e){dg(e,cg)}function Eg(e){dg(e,lg)}function Dg(e,t){return e.__highDownSilentOnTouch&&t.zrByTouch}function Og(e){var t=e.getModel(),n=[],r=[];t.eachComponent(function(t,i){var a=qh(i),o=Uh(e,i),s=t===`series`;!s&&r.push(o),a.isBlured&&(o.group.traverse(function(e){sg(e)}),s&&n.push(i)),a.isBlured=!1}),G(r,function(e){e&&e.toggleBlurSeries&&e.toggleBlurSeries(n,!1,t)})}function kg(e,t,n,r){var i=r.getModel();n||=`coordinateSystem`;function a(e,t){for(var n=0;n0){var a={dataIndex:i,seriesIndex:e.seriesIndex};r!=null&&(a.dataType=r),t.push(a)}})}),t}function Rg(e,t,n){Gg(e,!0),dg(e,vg),Vg(e,t,n)}function zg(e){Gg(e,!1)}function Bg(e,t,n,r){r?zg(e):Rg(e,t,n)}function Vg(e,t,n){var r=jh(e);t==null?r.focus&&=null:(r.focus=t,r.blurScope=n)}var Hg=[`emphasis`,`blur`,`select`],Ug={itemStyle:`getItemStyle`,lineStyle:`getLineStyle`,areaStyle:`getAreaStyle`};function Wg(e,t,n,r){n||=`itemStyle`;for(var i=0;i1&&(o*=n_(m),s*=n_(m));var h=(i===a?-1:1)*n_((o*o*(s*s)-o*o*(p*p)-s*s*(f*f))/(o*o*(p*p)+s*s*(f*f)))||0,g=h*o*p/s,_=h*-s*f/o,v=(e+n)/2+i_(d)*g-r_(d)*_,y=(t+r)/2+r_(d)*g+i_(d)*_,b=c_([1,0],[(f-g)/o,(p-_)/s]),x=[(f-g)/o,(p-_)/s],S=[(-1*f-g)/o,(-1*p-_)/s],C=c_(x,S);if(s_(x,S)<=-1&&(C=a_),s_(x,S)>=1&&(C=0),C<0){var w=Math.round(C/a_*1e6)/1e6;C=a_*2+w%2*a_}u.addData(l,v,y,o,s,b,C,d,a)}var u_=/([mlvhzcqtsa])([^mlvhzcqtsa]*)/gi,d_=/-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g;function f_(e){var t=new Dm;if(!e)return t;var n=0,r=0,i=n,a=r,o,s=Dm.CMD,c=e.match(u_);if(!c)return t;for(var l=0;l=0&&(n.splice(r,0,e),this._doAdd(e))}return this},t.prototype.replace=function(e,t){var n=qo(this._children,e);return n>=0&&this.replaceAt(t,n),this},t.prototype.replaceAt=function(e,t){var n=this._children,r=n[t];if(e&&e!==this&&e.parent!==this&&e!==r){n[t]=e,r.parent=null;var i=this.__zr;i&&r.removeSelfFromZr(i),this._doAdd(e)}return this},t.prototype._doAdd=function(e){e.parent&&e.parent.remove(e),e.parent=this;var t=this.__zr;t&&t!==e.__zr&&e.addSelfToZr(t),t&&t.refresh()},t.prototype.remove=function(e){var t=this.__zr,n=this._children,r=qo(n,e);return r<0?this:(n.splice(r,1),e.parent=null,t&&e.removeSelfFromZr(t),t&&t.refresh(),this)},t.prototype.removeAll=function(){for(var e=this._children,t=this.__zr,n=0;nA*A+j*j&&(w=E,T=D),{cx:w,cy:T,x0:-u,y0:-d,x1:w*(i/x-1),y1:T*(i/x-1)}}function L_(e){var t;if(J(e)){var n=e.length;if(!n)return e;t=n===1?[e[0],e[0],0,0]:n===2?[e[0],e[0],e[1],e[1]]:n===3?e.concat(e[2]):e}else t=[e,e,e,e];return t}function R_(e,t){var n,r=M_(t.r,0),i=M_(t.r0||0,0),a=r>0;if(a||i>0){if(a||(r=i,i=0),i>r){var o=r;r=i,i=o}var s=t.startAngle,c=t.endAngle;if(!(isNaN(s)||isNaN(c))){var l=t.cx,u=t.cy,d=!!t.clockwise,f=A_(c-s),p=f>T_&&f%T_;if(p>P_&&(f=p),!(r>P_))e.moveTo(l,u);else if(f>T_-P_)e.moveTo(l+r*D_(s),u+r*E_(s)),e.arc(l,u,r,s,c,!d),i>P_&&(e.moveTo(l+i*D_(c),u+i*E_(c)),e.arc(l,u,i,c,s,d));else{var m=void 0,h=void 0,g=void 0,_=void 0,v=void 0,y=void 0,b=void 0,x=void 0,S=void 0,C=void 0,w=void 0,T=void 0,E=void 0,D=void 0,O=void 0,k=void 0,A=r*D_(s),j=r*E_(s),M=i*D_(c),N=i*E_(c),P=f>P_;if(P){var F=t.cornerRadius;F&&(n=L_(F),m=n[0],h=n[1],g=n[2],_=n[3]);var I=A_(r-i)/2;if(v=N_(I,g),y=N_(I,_),b=N_(I,m),x=N_(I,h),w=S=M_(v,y),T=C=M_(b,x),(S>P_||C>P_)&&(E=r*D_(c),D=r*E_(c),O=i*D_(s),k=i*E_(s),fP_){var R=N_(g,w),oe=N_(_,w),z=I_(O,k,A,j,r,R,d),se=I_(E,D,M,N,r,oe,d);e.moveTo(l+z.cx+z.x0,u+z.cy+z.y0),w0&&e.arc(l+z.cx,u+z.cy,R,k_(z.y0,z.x0),k_(z.y1,z.x1),!d),e.arc(l,u,r,k_(z.cy+z.y1,z.cx+z.x1),k_(se.cy+se.y1,se.cx+se.x1),!d),oe>0&&e.arc(l+se.cx,u+se.cy,oe,k_(se.y1,se.x1),k_(se.y0,se.x0),!d))}else e.moveTo(l+A,u+j),e.arc(l,u,r,s,c,!d);if(!(i>P_)||!P)e.lineTo(l+M,u+N);else if(T>P_){var R=N_(m,T),oe=N_(h,T),z=I_(M,N,E,D,i,-oe,d),se=I_(A,j,O,k,i,-R,d);e.lineTo(l+z.cx+z.x0,u+z.cy+z.y0),T0&&e.arc(l+z.cx,u+z.cy,oe,k_(z.y0,z.x0),k_(z.y1,z.x1),!d),e.arc(l,u,i,k_(z.cy+z.y1,z.cx+z.x1),k_(se.cy+se.y1,se.cx+se.x1),d),R>0&&e.arc(l+se.cx,u+se.cy,R,k_(se.y1,se.x1),k_(se.y0,se.x0),!d))}else e.lineTo(l+M,u+N),e.arc(l,u,i,c,s,d)}e.closePath()}}}var z_=function(){function e(){this.cx=0,this.cy=0,this.r0=0,this.r=0,this.startAngle=0,this.endAngle=Math.PI*2,this.clockwise=!0,this.cornerRadius=0}return e}(),B_=function(e){U(t,e);function t(t){return e.call(this,t)||this}return t.prototype.getDefaultShape=function(){return new z_},t.prototype.buildPath=function(e,t){R_(e,t)},t.prototype.isZeroArea=function(){return this.shape.startAngle===this.shape.endAngle||this.shape.r===this.shape.r0},t}(Qm);B_.prototype.type=`sector`;var V_=function(){function e(){this.cx=0,this.cy=0,this.r=0,this.r0=0}return e}(),H_=function(e){U(t,e);function t(t){return e.call(this,t)||this}return t.prototype.getDefaultShape=function(){return new V_},t.prototype.buildPath=function(e,t){var n=t.cx,r=t.cy,i=Math.PI*2;e.moveTo(n+t.r,r),e.arc(n,r,t.r,0,i,!1),e.moveTo(n+t.r0,r),e.arc(n,r,t.r0,0,i,!0)},t}(Qm);H_.prototype.type=`ring`;function U_(e,t,n,r){var i=[],a=[],o=[],s=[],c,l,u,d;if(r){u=[1/0,1/0],d=[-1/0,-1/0];for(var f=0,p=e.length;f=2){if(r){var a=U_(i,r,n,t.smoothConstraint);e.moveTo(i[0][0],i[0][1]);for(var o=i.length,s=0;s<(n?o:o-1);s++){var c=a[s*2],l=a[s*2+1],u=i[(s+1)%o];e.bezierCurveTo(c[0],c[1],l[0],l[1],u[0],u[1])}}else{e.moveTo(i[0][0],i[0][1]);for(var s=1,d=i.length;sfv[1]){if(i=!1,pv.negativeSize||n)return i;var s=uv(fv[0]-dv[1]),c=uv(dv[0]-fv[1]);cv(s,c)>hv.len()&&(s=c||!pv.bidirectional)&&(wu.scale(mv,o,-c*r),pv.useDir&&pv.calcDirMTV()))}}return i},e.prototype._getProjMinMaxOnAxis=function(e,t,n){for(var r=this._axes[e],i=this._origin,a=t[0].dot(r)+i[e],o=a,s=a,c=1;c0){var d=u.duration,f=u.delay,p=u.easing,m={duration:d,delay:f||0,easing:p,done:a,force:!!a||!!o,setToFinal:!l,scope:e,during:o};s?t.animateFrom(n,m):t.animateTo(n,m)}else t.stopAnimation(),!s&&t.attr(n),o&&o(1),a&&a()}function Sv(e,t,n,r,i,a){xv(`update`,e,t,n,r,i,a)}function Cv(e,t,n,r,i,a){xv(`enter`,e,t,n,r,i,a)}function wv(e){if(!e.__zr)return!0;for(var t=0;trv,BezierCurve:()=>tv,BoundingRect:()=>Ru,Circle:()=>x_,CompoundPath:()=>iv,Ellipse:()=>C_,Group:()=>y_,HOVER_LAYER_FOR_INCREMENTAL:()=>2,HOVER_LAYER_FROM_THRESHOLD:()=>1,HOVER_LAYER_NO:()=>0,Image:()=>ih,IncrementalDisplayable:()=>vv,Line:()=>Z_,LinearGradient:()=>ov,OrientedBoundingRect:()=>gv,Path:()=>Qm,Point:()=>wu,Polygon:()=>K_,Polyline:()=>J_,RadialGradient:()=>sv,Rect:()=>fh,Ring:()=>H_,Sector:()=>B_,Text:()=>_h,WH:()=>Mv,XY:()=>jv,applyTransform:()=>qv,calcZ2Range:()=>gy,clipPointsByRect:()=>Qv,clipRectByRect:()=>$v,createIcon:()=>ey,decomposeTransform:()=>by,ensureCopyRect:()=>py,ensureCopyTransform:()=>my,expandOrShrinkRect:()=>ay,extendPath:()=>Fv,extendShape:()=>Nv,getCurrentCanvasPainter:()=>Sy,getShapeClass:()=>Lv,getTransform:()=>Kv,groupTransition:()=>Zv,initProps:()=>Cv,isBoundingRectAxisAligned:()=>dy,isElementRemoved:()=>wv,lineLineIntersect:()=>ny,linePolygonIntersect:()=>ty,makeImage:()=>zv,makePath:()=>Rv,mergePath:()=>Vv,payloadDisableAnimation:()=>yy,registerShape:()=>Iv,removeElement:()=>Tv,removeElementWithFadeOut:()=>Dv,resizePath:()=>Hv,retrieveZInfo:()=>hy,setTooltipConfig:()=>cy,subPixelOptimize:()=>Gv,subPixelOptimizeLine:()=>Uv,subPixelOptimizeRect:()=>Wv,transformDirection:()=>Jv,traverseElements:()=>uy,traverseUpdateZ:()=>_y,updateProps:()=>Sv}),Av={},jv=[`x`,`y`],Mv=[`width`,`height`];function Nv(e){return Qm.extend(e)}var Pv=__;function Fv(e,t){return Pv(e,t)}function Iv(e,t){Av[e]=t}function Lv(e){if(Av.hasOwnProperty(e))return Av[e]}function Rv(e,t,n,r){var i=g_(e,t);return n&&(r===`center`&&(n=Bv(n,i.getBoundingRect())),Hv(i,n)),i}function zv(e,t,n){var r=new ih({style:{image:e,x:t.x,y:t.y,width:t.width,height:t.height},onload:function(e){if(n===`center`){var i={width:e.width,height:e.height};r.setStyle(Bv(t,i))}}});return r}function Bv(e,t){var n=t.width/t.height,r=e.height*n,i;r<=e.width?i=e.height:(r=e.width,i=r/n);var a=e.x+e.width/2,o=e.y+e.height/2;return{x:a-r/2,y:o-i/2,width:r,height:i}}var Vv=v_;function Hv(e,t){if(e.applyTransform){var n=e.getBoundingRect().calculateTransform(t);e.applyTransform(n)}}function Uv(e,t){return sh(e,e,{lineWidth:t}),e}function Wv(e,t){return ch(e,e,t),e}var Gv=lh;function Kv(e,t){for(var n=$l([]);e&&e!==t;)tu(n,e.getLocalTransform(),n),e=e.parent;return n}function qv(e,t,n){return t&&!Xo(t)&&(t=zd.getLocalTransform(t)),n&&(t=au([],t)),xu([],e,t)}function Jv(e,t,n){var r=t[4]===0||t[5]===0||t[0]===0?1:Bs(2*t[4]/t[0]),i=t[4]===0||t[5]===0||t[2]===0?1:Bs(2*t[4]/t[2]),a=[e===`left`?-r:e===`right`?r:0,e===`top`?-i:e===`bottom`?i:0];return a=qv(a,t,n),Bs(a[0])>Bs(a[1])?a[0]>0?`right`:`left`:a[1]>0?`bottom`:`top`}function Yv(e){return!e.isGroup}function Xv(e){return e.shape!=null}function Zv(e,t,n){if(!e||!t)return;function r(e){var t={};return e.traverse(function(e){Yv(e)&&e.anid&&(t[e.anid]=e)}),t}function i(e){var t={x:e.x,y:e.y,rotation:e.rotation};return Xv(e)&&(t.shape=Ho(e.shape)),t}var a=r(e);t.traverse(function(e){if(Yv(e)&&e.anid){var t=a[e.anid];if(t){var r=i(e);e.attr(i(t)),Sv(e,r,n,jh(e).dataIndex)}}})}function Qv(e,t){return K(e,function(e){var n=e[0];n=zs(n,t.x),n=Rs(n,t.x+t.width);var r=e[1];return r=zs(r,t.y),r=Rs(r,t.y+t.height),[n,r]})}function $v(e,t){var n=zs(e.x,t.x),r=Rs(e.x+e.width,t.x+t.width),i=zs(e.y,t.y),a=Rs(e.y+e.height,t.y+t.height);if(r>=n&&a>=i)return{x:n,y:i,width:r-n,height:a-i}}function ey(e,t,n){var r=W({rectHover:!0},t),i=r.style={strokeNoScale:!0};if(n||={x:-1,y:-1,width:2,height:2},e)return e.indexOf(`image://`)===0?(i.image=e.slice(8),Ko(i,n),new ih(r)):Rv(e.replace(`path://`,``),r,n,`center`)}function ty(e,t,n,r,i){for(var a=0,o=i[i.length-1];a1)return!1;var g=ry(p,m,u,d)/f;return!(g<0||g>1)}function ry(e,t,n,r){return e*r-n*t}function iy(e){return e<=1e-6&&e>=-1e-6}function ay(e,t,n,r,i){return t==null?e:(as(t)?oy[0]=oy[1]=oy[2]=oy[3]=t:(oy[0]=t[0],oy[1]=t[1],oy[2]=t[2],oy[3]=t[3]),r&&(oy[0]=zs(0,oy[0]),oy[1]=zs(0,oy[1]),oy[2]=zs(0,oy[2]),oy[3]=zs(0,oy[3])),n&&(oy[0]=-oy[0],oy[1]=-oy[1],oy[2]=-oy[2],oy[3]=-oy[3]),sy(e,oy,`x`,`width`,3,1,i&&i[0]||0),sy(e,oy,`y`,`height`,0,2,i&&i[1]||0),e)}var oy=[0,0,0,0];function sy(e,t,n,r,i,a,o){var s=t[a]+t[i],c=e[r];e[r]+=s,o=zs(0,Rs(o,c)),e[r]=0?-t[i]:t[a]>=0?c+t[a]:Bs(s)>1e-8?(c-o)*t[i]/s:0):e[n]-=t[i]}function cy(e){var t=e.itemTooltipOption,n=e.componentModel,r=e.itemName,i=Y(t)?{formatter:t}:t,a=n.mainType,o=n.componentIndex,s={componentType:a,name:r,$vars:[`name`]};s[a+`Index`]=o;var c=e.formatterParamsExtra;c&&G(es(c),function(e){Z(s,e)||(s[e]=c[e],s.$vars.push(e))});var l=jh(e.el);l.componentMainType=a,l.componentIndex=o,l.tooltipConfig={name:r,option:Ko({content:r,encodeHTMLContent:!0,formatterParams:s},i)}}function ly(e,t){var n;e.isGroup&&(n=t(e)),n||e.traverse(t)}function uy(e,t){if(e){if(J(e))for(var n=0;nt&&(t=r),rt&&(n=t=0),{min:n,max:t}}function _y(e,t,n){vy(e,t,n,-1/0)}function vy(e,t,n,r){if(e.ignoreModelZ)return r;var i=e.getTextContent(),a=e.getTextGuideLine();if(e.isGroup)for(var o=e.childrenRef(),s=0;s=0&&n.push(e)}),n}}function nb(e,t){return Uo(Uo({},e,!0),t,!0)}var rb=Math.log(2);function ib(e,t,n,r,i,a){var o=r+`-`+i,s=e.length;if(a.hasOwnProperty(o))return a[o];if(t===1){var c=Math.round(Math.log((1<>1)%2;s.cssText=[`position: absolute`,`visibility: hidden`,`padding: 0`,`margin: 0`,`border-width: 0`,`user-select: none`,`width:0`,`height:0`,r[c]+`:0`,i[l]+`:0`,r[1-c]+`:auto`,i[1-l]+`:auto`,``].join(`!important;`),e.appendChild(o),n.push(o)}return t.clearMarkers=function(){G(n,function(e){e.parentNode&&e.parentNode.removeChild(e)})},n}function fb(e,t,n){for(var r=n?`invTrans`:`trans`,i=t[r],a=t.srcCoords,o=[],s=[],c=!0,l=0;l<4;l++){var u=e[l].getBoundingClientRect(),d=2*l,f=u.left,p=u.top;o.push(f,p),c=c&&a&&f===a[d]&&p===a[d+1],s.push(e[l].offsetLeft,e[l].offsetTop)}return c&&i?i:(t.srcCoords=o,t[r]=n?ab(s,o):ab(o,s))}function pb(e){return e.nodeName.toUpperCase()===`CANVAS`}var mb=/([&<>"'])/g,hb={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`};function gb(e){return e==null?``:(e+``).replace(mb,function(e,t){return hb[t]})}var _b={time:{month:[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],monthAbbr:[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],dayOfWeek:[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],dayOfWeekAbbr:[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]},legend:{selector:{all:`All`,inverse:`Inv`}},toolbox:{brush:{title:{rect:`Box Select`,polygon:`Lasso Select`,lineX:`Horizontally Select`,lineY:`Vertically Select`,keep:`Keep Selections`,clear:`Clear Selections`}},dataView:{title:`Data View`,lang:[`Data View`,`Close`,`Refresh`]},dataZoom:{title:{zoom:`Zoom`,back:`Zoom Reset`}},magicType:{title:{line:`Switch to Line Chart`,bar:`Switch to Bar Chart`,stack:`Stack`,tiled:`Tile`}},restore:{title:`Restore`},saveAsImage:{title:`Save as Image`,lang:[`Right Click to Save Image`]}},series:{typeNames:{pie:`Pie chart`,bar:`Bar chart`,line:`Line chart`,scatter:`Scatter plot`,effectScatter:`Ripple scatter plot`,radar:`Radar chart`,tree:`Tree`,treemap:`Treemap`,boxplot:`Boxplot`,candlestick:`Candlestick`,k:`K line chart`,heatmap:`Heat map`,map:`Map`,parallel:`Parallel coordinate map`,lines:`Line graph`,graph:`Relationship graph`,sankey:`Sankey diagram`,funnel:`Funnel chart`,gauge:`Gauge`,pictorialBar:`Pictorial bar`,themeRiver:`Theme River Map`,sunburst:`Sunburst`,custom:`Custom chart`,chart:`Chart`}},aria:{general:{withTitle:`This is a chart about "{title}"`,withoutTitle:`This is a chart`},series:{single:{prefix:``,withName:` with type {seriesType} named {seriesName}.`,withoutName:` with type {seriesType}.`},multiple:{prefix:`. It consists of {seriesCount} series count.`,withName:` The {seriesId} series is a {seriesType} representing {seriesName}.`,withoutName:` The {seriesId} series is a {seriesType}.`,separator:{middle:``,end:``}}},data:{allData:`The data is as follows: `,partialData:`The first {displayCnt} items are: `,withName:`the data for {name} is {value}`,withoutName:`{value}`,separator:{middle:`, `,end:`. `}}}},vb={time:{month:[`一月`,`二月`,`三月`,`四月`,`五月`,`六月`,`七月`,`八月`,`九月`,`十月`,`十一月`,`十二月`],monthAbbr:[`1月`,`2月`,`3月`,`4月`,`5月`,`6月`,`7月`,`8月`,`9月`,`10月`,`11月`,`12月`],dayOfWeek:[`星期日`,`星期一`,`星期二`,`星期三`,`星期四`,`星期五`,`星期六`],dayOfWeekAbbr:[`日`,`一`,`二`,`三`,`四`,`五`,`六`]},legend:{selector:{all:`全选`,inverse:`反选`}},toolbox:{brush:{title:{rect:`矩形选择`,polygon:`圈选`,lineX:`横向选择`,lineY:`纵向选择`,keep:`保持选择`,clear:`清除选择`}},dataView:{title:`数据视图`,lang:[`数据视图`,`关闭`,`刷新`]},dataZoom:{title:{zoom:`区域缩放`,back:`区域缩放还原`}},magicType:{title:{line:`切换为折线图`,bar:`切换为柱状图`,stack:`切换为堆叠`,tiled:`切换为平铺`}},restore:{title:`还原`},saveAsImage:{title:`保存为图片`,lang:[`右键另存为图片`]}},series:{typeNames:{pie:`饼图`,bar:`柱状图`,line:`折线图`,scatter:`散点图`,effectScatter:`涟漪散点图`,radar:`雷达图`,tree:`树图`,treemap:`矩形树图`,boxplot:`箱型图`,candlestick:`K线图`,k:`K线图`,heatmap:`热力图`,map:`地图`,parallel:`平行坐标图`,lines:`线图`,graph:`关系图`,sankey:`桑基图`,funnel:`漏斗图`,gauge:`仪表盘图`,pictorialBar:`象形柱图`,themeRiver:`主题河流图`,sunburst:`旭日图`,custom:`自定义图表`,chart:`图表`}},aria:{general:{withTitle:`这是一个关于“{title}”的图表。`,withoutTitle:`这是一个图表,`},series:{single:{prefix:``,withName:`图表类型是{seriesType},表示{seriesName}。`,withoutName:`图表类型是{seriesType}。`},multiple:{prefix:`它由{seriesCount}个图表系列组成。`,withName:`第{seriesId}个系列是一个表示{seriesName}的{seriesType},`,withoutName:`第{seriesId}个系列是一个{seriesType},`,separator:{middle:`;`,end:`。`}}},data:{allData:`其数据是——`,partialData:`其中,前{displayCnt}项是——`,withName:`{name}的数据是{value}`,withoutName:`{value}`,separator:{middle:`,`,end:``}}}},yb=`ZH`,bb=`EN`,xb=bb,Sb={},Cb={},wb=Ns.domSupported?function(){return(document.documentElement.lang||navigator.language||navigator.browserLanguage||xb).toUpperCase().indexOf(yb)>-1?yb:xb}():xb;function Tb(e,t){e=e.toUpperCase(),Cb[e]=new Zy(t),Sb[e]=t}function Eb(e){if(Y(e)){var t=Sb[e.toUpperCase()]||{};return e===yb||e===bb?Ho(t):Uo(Ho(t),Ho(Sb[xb]),!1)}return Uo(Ho(e),Ho(Sb[xb]),!1)}function Db(e){return Cb[e]}function Ob(){return Cb[xb]}Tb(bb,_b),Tb(yb,vb);var kb=null;function Ab(){return kb}function jb(e,t){var n=Ab(),r=t.breakOption,i=t.breakParsed;return!i&&n&&(i=n.parseAxisBreakOption(r,e)),i}function Mb(e){var t=e.brk;return t?t.breaks:[]}function Nb(e){var t=e.brk;return t?t.hasBreaks():!1}var Pb=1e3,Fb=Pb*60,Ib=Fb*60,Lb=Ib*24,Rb=Lb*365,zb={year:/({yyyy}|{yy})/,month:/({MMMM}|{MMM}|{MM}|{M})/,day:/({dd}|{d})/,hour:/({HH}|{H}|{hh}|{h})/,minute:/({mm}|{m})/,second:/({ss}|{s})/,millisecond:/({SSS}|{S})/},Bb={year:`{yyyy}`,month:`{MMM}`,day:`{d}`,hour:`{HH}:{mm}`,minute:`{HH}:{mm}`,second:`{HH}:{mm}:{ss}`,millisecond:`{HH}:{mm}:{ss} {SSS}`},Vb=`{yyyy}-{MM}-{dd} {HH}:{mm}:{ss} {SSS}`,Hb=`{yyyy}-{MM}-{dd}`,Ub={year:`{yyyy}`,month:`{yyyy}-{MM}`,day:Hb,hour:Hb+` `+Bb.hour,minute:Hb+` `+Bb.minute,second:Hb+` `+Bb.second,millisecond:Vb},Wb=[`year`,`month`,`day`,`hour`,`minute`,`second`,`millisecond`],Gb=[`year`,`half-year`,`quarter`,`month`,`week`,`half-week`,`day`,`half-day`,`quarter-day`,`hour`,`minute`,`second`,`millisecond`];function Kb(e){return!Y(e)&&!rs(e)?qb(e):e}function qb(e){e||={};var t={},n=!0;return G(Wb,function(t){n&&=e[t]==null}),G(Wb,function(r,i){var a=e[r];t[r]={};for(var o=null,s=i;s>=0;s--){var c=Wb[s],l=os(a)&&!J(a)?a[c]:a,u=void 0;J(l)?(u=l.slice(),o=u[0]||``):Y(l)?(o=l,u=[o]):(o==null?o=Bb[r]:zb[c].test(o)||(o=t[c][c][0]+` `+o),u=[o],n&&(u[1]=`{primary|`+o+`}`)),t[r][c]=u}}),t}function Jb(e,t){return e+=``,`0000`.substr(0,t-e.length)+e}function Yb(e){switch(e){case`half-year`:case`quarter`:return`month`;case`week`:case`half-week`:return`day`;case`half-day`:case`quarter-day`:return`hour`;default:return e}}function Xb(e){return e===Yb(e)}function Zb(e){switch(e){case`year`:case`month`:return`day`;case`millisecond`:return`millisecond`;default:return`second`}}function Qb(e,t,n,r){var i=uc(e),a=i[nx(n)](),o=i[rx(n)]()+1,s=Math.floor((o-1)/3)+1,c=i[ix(n)](),l=i[`get`+(n?`UTC`:``)+`Day`](),u=i[ax(n)](),d=(u-1)%12+1,f=i[ox(n)](),p=i[sx(n)](),m=i[cx(n)](),h=u>=12?`pm`:`am`,g=h.toUpperCase(),_=(r instanceof Zy?r:Db(r||wb)||Ob()).getModel(`time`),v=_.get(`month`),y=_.get(`monthAbbr`),b=_.get(`dayOfWeek`),x=_.get(`dayOfWeekAbbr`);return(t||``).replace(/{a}/g,h+``).replace(/{A}/g,g+``).replace(/{yyyy}/g,a+``).replace(/{yy}/g,Jb(a%100+``,2)).replace(/{Q}/g,s+``).replace(/{MMMM}/g,v[o-1]).replace(/{MMM}/g,y[o-1]).replace(/{MM}/g,Jb(o,2)).replace(/{M}/g,o+``).replace(/{dd}/g,Jb(c,2)).replace(/{d}/g,c+``).replace(/{eeee}/g,b[l]).replace(/{ee}/g,x[l]).replace(/{e}/g,l+``).replace(/{HH}/g,Jb(u,2)).replace(/{H}/g,u+``).replace(/{hh}/g,Jb(d+``,2)).replace(/{h}/g,d+``).replace(/{mm}/g,Jb(f,2)).replace(/{m}/g,f+``).replace(/{ss}/g,Jb(p,2)).replace(/{s}/g,p+``).replace(/{SSS}/g,Jb(m,3)).replace(/{S}/g,m+``)}function $b(e,t,n,r,i){var a=null;if(Y(n))a=n;else if(rs(n)){var o={time:e.time,level:e.time?e.time.level:0},s=Ab();s&&s.makeAxisLabelFormatterParamBreak(o,e.break),a=n(e.value,t,o)}else{var c=e.time;if(c){var l=n[c.lowerTimeUnit][c.upperTimeUnit];a=l[Math.min(c.level,l.length-1)]||``}else{var u=ex(e.value,i);a=n[u][u][0]}}return Qb(new Date(e.value),a,i,r)}function ex(e,t){var n=uc(e),r=n[rx(t)]()+1,i=n[ix(t)](),a=n[ax(t)](),o=n[ox(t)](),s=n[sx(t)](),c=n[cx(t)]()===0,l=c&&s===0,u=l&&o===0,d=u&&a===0,f=d&&i===1;return f&&r===1?`year`:f?`month`:d?`day`:u?`hour`:l?`minute`:c?`second`:`millisecond`}function tx(e,t,n){switch(t){case`year`:e[ux(n)](0);case`month`:e[dx(n)](1);case`day`:e[fx(n)](0);case`hour`:e[px(n)](0);case`minute`:e[mx(n)](0);case`second`:e[hx(n)](0)}return e}function nx(e){return e?`getUTCFullYear`:`getFullYear`}function rx(e){return e?`getUTCMonth`:`getMonth`}function ix(e){return e?`getUTCDate`:`getDate`}function ax(e){return e?`getUTCHours`:`getHours`}function ox(e){return e?`getUTCMinutes`:`getMinutes`}function sx(e){return e?`getUTCSeconds`:`getSeconds`}function cx(e){return e?`getUTCMilliseconds`:`getMilliseconds`}function lx(e){return e?`setUTCFullYear`:`setFullYear`}function ux(e){return e?`setUTCMonth`:`setMonth`}function dx(e){return e?`setUTCDate`:`setDate`}function fx(e){return e?`setUTCHours`:`setHours`}function px(e){return e?`setUTCMinutes`:`setMinutes`}function mx(e){return e?`setUTCSeconds`:`setSeconds`}function hx(e){return e?`setUTCMilliseconds`:`setMilliseconds`}function gx(e){if(!gc(e))return Y(e)?e:`-`;var t=(e+``).split(`.`);return t[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,`$1,`)+(t.length>1?`.`+t[1]:``)}function _x(e,t){return e=(e||``).toLowerCase().replace(/-(.)/g,function(e,t){return t.toUpperCase()}),t&&e&&(e=e.charAt(0).toUpperCase()+e.slice(1)),e}var vx=gs;function yx(e,t,n){var r=`{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}`;function i(e){return e&&vs(e)?e:`-`}function a(e){return bc(e)}var o=t===`time`,s=e instanceof Date;if(o||s){var c=o?uc(e):e;if(!isNaN(+c))return Qb(c,r,n);if(s)return`-`}if(t===`ordinal`)return is(e)?i(e):as(e)&&a(e)?e+``:`-`;var l=hc(e);return a(l)?gx(l):is(e)?i(e):typeof e==`boolean`?e+``:`-`}var bx=[`a`,`b`,`c`,`d`,`e`,`f`,`g`],xx=function(e,t){return`{`+e+(t??``)+`}`};function Sx(e,t,n){J(t)||(t=[t]);var r=t.length;if(!r)return``;for(var i=t[0].$vars||[],a=0;a`:``:{renderMode:a,content:`{`+(n.markerId||`markerX`)+`|} `,style:i===`subItem`?{width:4,height:4,borderRadius:2,backgroundColor:r}:{width:10,height:10,borderRadius:5,backgroundColor:r}}:``}function Tx(e,t){return t||=`transparent`,Y(e)?e:os(e)&&e.colorStops&&(e.colorStops[0]||{}).color||t}var Ex={},Dx={},Ox=function(){function e(){this._normalMasterList=[],this._nonSeriesBoxMasterList=[]}return e.prototype.create=function(e,t){this._nonSeriesBoxMasterList=n(Ex,!0),this._normalMasterList=n(Dx,!1);function n(n,r){var i=[];return G(n,function(n,r){var a=n.create(e,t);i=i.concat(a||[])}),i}},e.prototype.update=function(e,t){G(this._normalMasterList,function(n){n.update&&n.update(e,t)})},e.prototype.getCoordinateSystems=function(){return this._normalMasterList.concat(this._nonSeriesBoxMasterList)},e.register=function(e,t){if(e===`matrix`||e===`calendar`){Ex[e]=t;return}Dx[e]=t},e.get=function(e){return Dx[e]||Ex[e]},e}();function kx(e){return!!Ex[e]}var Ax=Es();function jx(e){var t=e.getShallow(`coord`,!0),n=1;if(t==null){var r=Ax.get(e.type);r&&r.getCoord2&&(n=2,t=r.getCoord2(e))}return{coord:t,from:n}}function Mx(e,t){var n=e.getShallow(`coordinateSystem`),r=e.getShallow(`coordinateSystemUsage`,!0),i=0;if(n){var a=e.mainType===`series`;r??=a?`data`:`box`,r===`data`?(i=1,a||(i=0)):r===`box`&&(i=2,!a&&!kx(n)&&(i=0))}return{coordSysType:n,kind:i}}function Nx(e){var t=e.targetModel,n=e.coordSysType,r=e.coordSysProvider,i=e.isDefaultDataCoordSys;e.allowNotFound;var a=Mx(t,!0),o=a.kind,s=a.coordSysType;if(i&&o!==1&&(o=1,s=n),o===0||s!==n)return 0;var c=r(n,t);return c?(o===1?t.coordinateSystem=c:t.boxCoordinateSystem=c,o):0}var Px=G,Fx=[`left`,`right`,`top`,`bottom`,`width`,`height`],Ix=[[`width`,`left`,`right`],[`height`,`top`,`bottom`]];function Lx(e,t,n,r,i){var a=0,o=0;r??=1/0,i??=1/0;var s=0;t.eachChild(function(c,l){var u=c.getBoundingRect(),d=t.childAt(l+1),f=d&&d.getBoundingRect(),p,m;if(e===`horizontal`){var h=u.width+(f?-f.x+u.x:0);p=a+h,p>r||c.newline?(a=0,p=h,o+=s+n,s=u.height):s=Math.max(s,u.height)}else{var g=u.height+(f?-f.y+u.y:0);m=o+g,m>i||c.newline?(a+=s+n,o=0,m=g,s=u.width):s=Math.max(s,u.width)}c.newline||(c.x=a,c.y=o,c.markRedraw(),e===`horizontal`?a=p+n:o=m+n)})}var Rx=Lx;ns(Lx,`vertical`),ns(Lx,`horizontal`);function zx(e,t){return{left:e.getShallow(`left`,t),top:e.getShallow(`top`,t),right:e.getShallow(`right`,t),bottom:e.getShallow(`bottom`,t),width:e.getShallow(`width`,t),height:e.getShallow(`height`,t)}}function Bx(e,t,n){n=vx(n||0);var r=t.width,i=t.height,a=Xs(e.left,r),o=Xs(e.top,i),s=Xs(e.right,r),c=Xs(e.bottom,i),l=Xs(e.width,r),u=Xs(e.height,i),d=n[2]+n[0],f=n[1]+n[3],p=e.aspect;switch(isNaN(l)&&(l=r-s-f-a),isNaN(u)&&(u=i-c-d-o),p!=null&&(isNaN(l)&&isNaN(u)&&(p>r/i?l=r*.8:u=i*.8),isNaN(l)&&(l=p*u),isNaN(u)&&(u=l/p)),isNaN(a)&&(a=r-s-l-f),isNaN(o)&&(o=i-c-u-d),e.left||e.right){case`center`:a=r/2-l/2-n[3];break;case`right`:a=r-l-f}switch(e.top||e.bottom){case`middle`:case`center`:o=i/2-u/2-n[0];break;case`bottom`:o=i-u-d}a||=0,o||=0,isNaN(l)&&(l=r-f-a-(s||0)),isNaN(u)&&(u=i-d-o-(c||0));var m=new Ru((t.x||0)+a+n[3],(t.y||0)+o+n[0],l,u);return m.margin=n,m}var Vx={rect:1,point:2};function Hx(e,t,n){var r,i,a,o=e.boxCoordinateSystem,s;if(o){var c=jx(e),l=c.coord,u=c.from;if(o.dataToLayout){a=Vx.rect,s=u;var d=o.dataToLayout(l);r=d.contentRect||d.rect}else n&&n.enableLayoutOnlyByCenter&&o.dataToPoint&&(a=Vx.point,s=u,i=o.dataToPoint(l))}return a??=Vx.rect,a===Vx.rect&&(r||={x:0,y:0,width:t.getWidth(),height:t.getHeight()},i=[r.x+r.width/2,r.y+r.height/2]),{type:a,refContainer:r,refPoint:i,boxCoordFrom:s}}function Ux(e,t,n,r,i,a){var o=!i||!i.hv||i.hv[0],s=!i||!i.hv||i.hv[1],c=i&&i.boundingMode||`all`;if(a||=e,a.x=e.x,a.y=e.y,!o&&!s)return!1;var l;if(c===`raw`)l=e.type===`group`?new Ru(0,0,+t.width||0,+t.height||0):e.getBoundingRect();else if(l=e.getBoundingRect(),e.needLocalTransform()){var u=e.getLocalTransform();l=l.clone(),l.applyTransform(u)}var d=Bx(Ko({width:l.width,height:l.height},t),n,r),f=o?d.x-l.x:0,p=s?d.y-l.y:0;return c===`raw`?(a.x=f,a.y=p):(a.x+=f,a.y+=p),a===e&&e.markRedraw(),!0}function Wx(e){var t=e.layoutMode||e.constructor.layoutMode;return os(t)?t:t?{type:t}:null}function Gx(e,t,n){var r=n&&n.ignoreSize;!J(r)&&(r=[r,r]);var i=o(Ix[0],0),a=o(Ix[1],1);c(Ix[0],e,i),c(Ix[1],e,a);function o(n,i){var a={},o=0,c={},l=0,u=2;if(Px(n,function(t){c[t]=e[t]}),Px(n,function(e){Z(t,e)&&(a[e]=c[e]=t[e]),s(a,e)&&o++,s(c,e)&&l++}),r[i])return s(t,n[1])?c[n[2]]=null:s(t,n[2])&&(c[n[1]]=null),c;if(l===u||!o)return c;if(o>=u)return a;for(var d=0;d=0;o--)a=Uo(a,n[o],!0);t.defaultOption=a}return t.defaultOption},t.prototype.getReferringComponents=function(e,t){var n=e+`Index`,r=e+`Id`;return il(this.ecModel,e,{index:this.get(n,!0),id:this.get(r,!0)},t)},t.prototype.getBoxLayoutParams=function(){return zx(this,!1)},t.prototype.getZLevelKey=function(){return``},t.prototype.setZLevel=function(e){this.option.zlevel=e},t.protoInitialize=function(){var e=t.prototype;e.type=`component`,e.id=``,e.name=``,e.mainType=``,e.subType=``,e.componentIndex=0}(),t}(Zy);Fl(Yx,Zy),Bl(Yx),eb(Yx),tb(Yx,Xx);function Xx(e){var t=[];return G(Yx.getClassesByMainType(e),function(e){t=t.concat(e.dependencies||e.prototype.dependencies||[])}),t=K(t,function(e){return Al(e).main}),e!==`dataset`&&qo(t,`dataset`)<=0&&t.unshift(`dataset`),t}var Zx=Qc(),Qx=Qc(),$x=function(){function e(){}return e.prototype.getColorFromPalette=function(e,t,n){var r=Ac(this.get(`color`,!0)),i=this.get(`colorLayer`,!0);return nS(this,Zx,r,i,e,t,n)},e.prototype.clearColorPalette=function(){rS(this,Zx)},e}();function eS(e,t,n,r){return nS(e,Qx,Ac(e.get([`aria`,`decal`,`decals`])),null,t,n,r)}function tS(e,t){for(var n=e.length,r=0;rt)return e[r];return e[n-1]}function nS(e,t,n,r,i,a,o){a||=e;var s=t(a),c=s.paletteIdx||0,l=s.paletteNameMap=s.paletteNameMap||{};if(l.hasOwnProperty(i))return l[i];var u=o==null||!r?n:tS(r,o);if(u||=n,u&&u.length){var d=u[c];return i&&(l[i]=d),s.paletteIdx=(c+1)%u.length,d}}function rS(e,t){t(e).paletteIdx=0,t(e).paletteNameMap={}}var iS={Must:1,Might:2,Not:3},aS=Qc();function oS(e){aS(e).datasetMap=Es()}function sS(e,t,n){var r={},i=cS(t);if(!i||!e)return r;var a=[],o=[],s=t.ecModel,c=aS(s).datasetMap,l=i.uid+`_`+n.seriesLayoutBy,u,d;e=e.slice(),G(e,function(t,n){var i=os(t)?t:e[n]={name:t};i.type===`ordinal`&&u==null&&(u=n,d=m(i)),r[i.name]=[]});var f=c.get(l)||c.set(l,{categoryWayDim:d,valueWayDim:0});G(e,function(e,t){var n=e.name,i=m(e);if(u==null){var s=f.valueWayDim;p(r[n],s,i),p(o,s,i),f.valueWayDim+=i}else if(u===t)p(r[n],0,i),p(a,0,i);else{var s=f.categoryWayDim;p(r[n],s,i),p(o,s,i),f.categoryWayDim+=i}});function p(e,t,n){for(var r=0;rl&&(l=p)}s[0]=c,s[1]=l}},r=function(){return this._data?this._data.length/this._dimSize:0};DS=(e={},e[Fh+`_`+Bh]={pure:!0,appendData:i},e[Fh+`_row`]={pure:!0,appendData:function(){throw Error(`Do not support appendData when set seriesLayoutBy: "row".`)}},e[Ih]={pure:!0,appendData:i},e[Lh]={pure:!0,appendData:function(e){var t=this._data;G(e,function(e,n){for(var r=t[n]||(t[n]=[]),i=0;i<(e||[]).length;i++)r.push(e[i])})}},e[Ph]={appendData:i},e[Rh]={persistent:!1,pure:!0,appendData:function(e){this._data=e},clean:function(){this._offset+=this.count(),this._data=null}},e);function i(e){for(var t=0;t=0&&(s=a.interpolatedValue[c])}return s==null?``:s+``})},e.prototype.getRawValue=function(e,t){return VS(this.getData(t),e)},e.prototype.formatTooltip=function(e,t,n){},e}();function WS(e){var t,n;return os(e)?e.type&&(n=e):t=e,{text:t,frag:n}}function GS(e){return new KS(e)}var KS=function(){function e(e){e||={},this._reset=e.reset,this._plan=e.plan,this._count=e.count,this._onDirty=e.onDirty,this._dirty=!0}return e.prototype.perform=function(e){var t=this._upstream,n=e&&e.skip;if(this._dirty&&t){var r=this.context;r.data=r.outputData=t.context.outputData}this.__pipeline&&(this.__pipeline.currentTask=this);var i;this._plan&&!n&&(i=this._plan(this.context));var a=l(this._modBy),o=this._modDataCount||0,s=l(e&&e.modBy),c=e&&e.modDataCount||0;(a!==s||o!==c)&&(i=`reset`);function l(e){return!(e>=1)&&(e=1),e}var u;(this._dirty||i===`reset`)&&(this._dirty=!1,u=this._doReset(n)),this._modBy=s,this._modDataCount=c;var d=e&&e.step;if(this._dueEnd=t?t._outputDueEnd:this._count?this._count(this.context):1/0,this._progress){var f=this._dueIndex,p=Math.min(d==null?1/0:this._dueIndex+d,this._dueEnd);if(!n&&(u||f1&&r>0?s:o}};return a;function o(){return t=e?null:at},gte:function(e,t){return e>=t}};(function(){function e(e,t){as(t)||Ec(``),this._opFn=YS[e],this._rvalFloat=hc(t)}return e.prototype.evaluate=function(e){return as(e)?this._opFn(e,this._rvalFloat):this._opFn(hc(e),this._rvalFloat)},e})();var XS=function(){function e(e,t){var n=e===`desc`;this._resultLT=n?1:-1,t??=n?`min`:`max`,this._incomparable=t===`min`?-1/0:1/0}return e.prototype.evaluate=function(e,t){var n=as(e)?e:hc(e),r=as(t)?t:hc(t),i=isNaN(n),a=isNaN(r);if(i&&(n=this._incomparable),a&&(r=this._incomparable),i&&a){var o=Y(e),s=Y(t);o&&(n=s?e:0),s&&(r=o?t:0)}return nr?-this._resultLT:0},e}();(function(){function e(e,t){this._rval=t,this._isEQ=e,this._rvalTypeof=typeof t,this._rvalFloat=hc(t)}return e.prototype.evaluate=function(e){var t=e===this._rval;if(!t){var n=typeof e;n!==this._rvalTypeof&&(n===`number`||this._rvalTypeof===`number`)&&(t=hc(e)===this._rvalFloat)}return this._isEQ?t:!t},e})();function ZS(e){var t=``,n=-1/0,r=-1/0,i=1/0,a=1/0;return e&&(e.g!=null&&(t+=`G`+e.g,n=e.g),e.ge!=null&&(t+=`GE`+e.ge,r=e.ge),e.l!=null&&(t+=`L`+e.l,i=e.l),e.le!=null&&(t+=`LE`+e.le,a=e.le)),{key:t,g:n,ge:r,l:i,le:a}}function QS(e,t){return t>e.g&&t>=e.ge&&t`u`?Array:Uint32Array,dC=typeof Uint16Array>`u`?Array:Uint16Array,fC=typeof Int32Array>`u`?Array:Int32Array,pC=typeof Float64Array>`u`?Array:Float64Array,mC={float:pC,int:fC,ordinal:Array,number:Array,time:pC},hC;function gC(e){return e>65535?uC:dC}function _C(e){var t=e.constructor;return t===Array?e.slice():new t(e)}function vC(e,t,n,r,i){var a=mC[n||`float`];if(i){var o=e[t],s=o&&o.length;if(s!==r){for(var c=new a(r),l=0;lh[1]&&(h[1]=m)}return this._rawCount=this._count=s,{start:o,end:s}},e.prototype._initDataFromProvider=function(e,t,n){for(var r=this._provider,i=this._chunks,a=this._dimensions,o=a.length,s=this._rawExtent,c=K(a,function(e){return e.property}),l=0;lg[1]&&(g[1]=h)}}!r.persistent&&r.clean&&r.clean(),this._rawCount=this._count=t,this._extent=[]},e.prototype.count=function(){return this._count},e.prototype.get=function(e,t){if(!(t>=0&&t=0&&t=this._rawCount||e<0)return-1;if(!this._indices)return e;var t=this._indices,n=t[e];if(n!=null&&ne)i=a-1;else return a}return-1},e.prototype.getIndices=function(){var e,t=this._indices;if(t){var n=t.constructor,r=this._count;if(n===Array){e=new n(r);for(var i=0;i=l&&g<=u||isNaN(g))&&(o[s++]=p),p++}f=!0}else if(i===2){for(var m=d[r[0]],_=d[r[1]],v=e[r[1]][0],y=e[r[1]][1],h=0;h=l&&g<=u||isNaN(g))&&(b>=v&&b<=y||isNaN(b))&&(o[s++]=p),p++}f=!0}}if(!f){if(i===1)for(var h=0;h=l&&g<=u||isNaN(g))&&(o[s++]=x)}else for(var h=0;he[w][1])&&(S=!1)}S&&(o[s++]=t.getRawIndex(h))}}return sg[1]&&(g[1]=h)}}}},e.prototype.lttbDownSample=function(e,t){var n=this.clone([e],!0),r=n._chunks[e],i=this.count(),a=0,o=Math.floor(1/t),s=this.getRawIndex(0),c,l,u,d=new(gC(this._rawCount))(Math.min((Math.ceil(i/o)+2)*2,i));d[a++]=s;for(var f=1;fc&&(c=l,u=v)}T>0&&To&&(m=o-l);for(var h=0;hp&&(p=g,f=l+h)}var _=this.getRawIndex(u),v=this.getRawIndex(f);ul-p&&(s=l-p,o.length=s);for(var m=0;mu[1]&&(u[1]=g),d[f++]=_}return i._count=f,i._indices=d,i._updateGetRawIdx(),i},e.prototype.each=function(e,t){if(this._count)for(var n=e.length,r=this._chunks,i=0,a=this.count();id&&(d=p))}return o[c]=[u,d]},e.prototype.getRawDataItem=function(e){var t=this.getRawIndex(e);if(this._provider.persistent)return this._provider.getItem(t);for(var n=[],r=this._chunks,i=0;i=0?this._indices[e]:-1},e.prototype._updateGetRawIdx=function(){this.getRawIndex=this._indices?this._getRawIdx:this._getRawIdxIdentity},e.internalField=function(){function e(e,t,n,r){return JS(e[r],this._dimensions[r])}hC={arrayRows:e,objectRows:function(e,t,n,r){return JS(e[t],this._dimensions[r])},keyedColumns:e,original:function(e,t,n,r){var i=e&&(e.value==null?e:e.value);return JS(i instanceof Array?i[r]:i,this._dimensions[r])},typedArray:function(e,t,n,r){return e[r]}}}(),e}(),bC=function(){function e(e){this._sourceList=[],this._storeList=[],this._upstreamSignList=[],this._versionSignBase=0,this._dirty=!0,this._sourceHost=e}return e.prototype.dirty=function(){this._setLocalSource([],[]),this._storeList=[],this._dirty=!0},e.prototype._setLocalSource=function(e,t){this._sourceList=e,this._upstreamSignList=t,this._versionSignBase++,this._versionSignBase>9e10&&(this._versionSignBase=0)},e.prototype._getVersionSign=function(){return this._sourceHost.uid+`_`+this._versionSignBase},e.prototype.prepareSource=function(){this._isDirty()&&(this._createSource(),this._dirty=!1)},e.prototype._createSource=function(){this._setLocalSource([],[]);var e=this._sourceHost,t=this._getUpstreamSourceManagers(),n=!!t.length,r,i;if(xC(e)){var a=e,o=void 0,s=void 0,c=void 0;if(n){var l=t[0];l.prepareSource(),c=l.getSource(),o=c.data,s=c.sourceFormat,i=[l._getVersionSign()]}else o=a.get(`data`,!0),s=cs(o)?Rh:Ph,i=[];var u=this._getSourceMetaRawOption()||{},d=c&&c.metaRawOption||{},f=X(u.seriesLayoutBy,d.seriesLayoutBy)||null,p=X(u.sourceHeader,d.sourceHeader),m=X(u.dimensions,d.dimensions);r=f!==d.seriesLayoutBy||!!p!=!!d.sourceHeader||m?[mS(o,{seriesLayoutBy:f,sourceHeader:p,dimensions:m},s)]:[]}else{var h=e;if(n){var g=this._applyTransform(t);r=g.sourceList,i=g.upstreamSignList}else r=[mS(h.get(`source`,!0),this._getSourceMetaRawOption(),null)],i=[]}this._setLocalSource(r,i)},e.prototype._applyTransform=function(e){var t=this._sourceHost,n=t.get(`transform`,!0),r=t.get(`fromTransformResult`,!0);r!=null&&e.length!==1&&SC(``);var i,a=[],o=[];return G(e,function(e){e.prepareSource();var t=e.getSource(r||0);r!=null&&!t&&SC(``),a.push(t),o.push(e._getVersionSign())}),n?i=sC(n,a,{datasetIndex:t.componentIndex}):r!=null&&(i=[gS(a[0])]),{sourceList:i,upstreamSignList:o}},e.prototype._isDirty=function(){if(this._dirty)return!0;for(var e=this._getUpstreamSourceManagers(),t=0;t1||n>0&&!e.noHeader;return G(e.blocks,function(e){var n=PC(e);n>=t&&(t=n+ +(r&&(!n||MC(e)&&!e.noHeader)))}),t}return 0}function FC(e,t,n,r){var i=t.noHeader,a=RC(PC(t)),o=[],s=t.blocks||[];_s(!s||J(s)),s||=[];var c=e.orderMode;if(t.sortBlocks&&c){s=s.slice();var l={valueAsc:`asc`,valueDesc:`desc`};if(Z(l,c)){var u=new XS(l[c],null);s.sort(function(e,t){return u.evaluate(e.sortParam,t.sortParam)})}else c===`seriesDesc`&&s.reverse()}G(s,function(n,i){var s=t.valueFormatter,c=NC(n)(s?W(W({},e),{valueFormatter:s}):e,n,i>0?a.html:0,r);c!=null&&o.push(c)});var d=e.renderMode===`richText`?o.join(a.richText):zC(r,o.join(``),i?n:a.html);if(i)return d;var f=yx(t.header,`ordinal`,e.useUTC),p=OC(r,e.renderMode).nameStyle,m=DC(r);return e.renderMode===`richText`?HC(e,f,p)+a.richText+d:zC(r,`
`+gb(f)+`
`+d,n)}function IC(e,t,n,r){var i=e.renderMode,a=t.noName,o=t.noValue,s=!t.markerType,c=t.name,l=e.useUTC,u=t.valueFormatter||e.valueFormatter||function(e){return e=J(e)?e:[e],K(e,function(e,t){return yx(e,J(p)?p[t]:p,l)})};if(!(a&&o)){var d=s?``:e.markupStyleCreator.makeTooltipMarker(t.markerType,t.markerColor||Q.color.secondary,i),f=a?``:yx(c,`ordinal`,l),p=t.valueType,m=o?[]:u(t.value,t.rawDataIndex),h=!s||!a,g=!s&&a,_=OC(r,i),v=_.nameStyle,y=_.valueStyle;return i===`richText`?(s?``:d)+(a?``:HC(e,f,v))+(o?``:UC(e,m,h,g,y)):zC(r,(s?``:d)+(a?``:BC(f,!s,v))+(o?``:VC(m,h,g,y)),n)}}function LC(e,t,n,r,i,a){if(e)return NC(e)({useUTC:i,renderMode:n,orderMode:r,markupStyleCreator:t,valueFormatter:e.valueFormatter},e,0,a)}function RC(e){return{html:kC[e],richText:AC[e]}}function zC(e,t,n){var r=`
`,i=`margin: `+n+`px 0 0`,a=DC(e);return`
`+t+r+`
`}function BC(e,t,n){var r=t?`margin-left:2px`:``;return``+gb(e)+``}function VC(e,t,n,r){var i=t?`float:right;margin-left:`+(n?`10px`:`20px`):``;return e=J(e)?e:[e],``+K(e,function(e){return gb(e)}).join(`  `)+``}function HC(e,t,n){return e.markupStyleCreator.wrapRichTextStyle(t,n)}function UC(e,t,n,r,i){var a=[i],o=r?10:20;return n&&a.push({padding:[0,0,0,o],align:`right`}),e.markupStyleCreator.wrapRichTextStyle(J(t)?t.join(` `):t,a)}function WC(e,t){var n=e.getData().getItemVisual(t,`style`)[e.visualDrawType];return Tx(n)}function GC(e,t){return e.get(`padding`)??(t===`richText`?[8,10]:10)}var KC=function(){function e(){this.richTextStyles={},this._nextStyleNameId=_c()}return e.prototype._generateStyleName=function(){return`__EC_aUTo_`+this._nextStyleNameId++},e.prototype.makeTooltipMarker=function(e,t,n){var r=n===`richText`?this._generateStyleName():null,i=Cx({color:t,type:e,renderMode:n,markerId:r});return Y(i)?i:(this.richTextStyles[r]=i.style,i.content)},e.prototype.wrapRichTextStyle=function(e,t){var n={};J(t)?G(t,function(e){return W(n,e)}):W(n,t);var r=this._generateStyleName();return this.richTextStyles[r]=n,`{`+r+`|`+e+`}`},e}();function qC(e){var t=e.series,n=e.dataIndex,r=e.multipleSeries,i=t.getData(),a=i.mapDimensionsAll(`defaultedTooltip`),o=a.length,s=t.getRawValue(n),c=J(s),l=WC(t,n),u,d,f,p;if(o>1||c&&!o){var m=JC(s,t,n,a,l);u=m.inlineValues,d=m.inlineValueTypes,f=m.blocks,p=m.inlineValues[0]}else if(o){var h=i.getDimensionInfo(a[0]);p=u=VS(i,n,a[0]),d=h.type}else p=u=c?s[0]:s;var g=Gc(t),_=g&&t.name||``,v=i.getName(n),y=r?_:v;return jC(`section`,{header:_,noHeader:r||!g,sortParam:p,blocks:[jC(`nameValue`,{markerType:`item`,markerColor:l,name:y,noName:!vs(y),value:u,valueType:d,rawDataIndex:i.getRawIndex(n)})].concat(f||[])})}function JC(e,t,n,r,i){var a=t.getData(),o=Zo(e,function(e,t,n){var r=a.getDimensionInfo(n);return e||=r&&r.tooltip!==!1&&r.displayName!=null},!1),s=[],c=[],l=[];r.length?G(r,function(e){u(VS(a,n,e),e)}):G(e,u);function u(e,t){var n=a.getDimensionInfo(t);n&&n.otherDims.tooltip!==!1&&(o?l.push(jC(`nameValue`,{markerType:`subItem`,markerColor:i,name:n.displayName,value:e,valueType:n.type})):(s.push(e),c.push(n.type)))}return{inlineValues:s,inlineValueTypes:c,blocks:l}}var YC=Qc();function XC(e,t){return e.getName(t)||e.getId(t)}var ZC=function(e){U(t,e);function t(){var t=e!==null&&e.apply(this,arguments)||this;return t._selectedDataIndicesMap={},t}return t.prototype.init=function(e,t,n){this.seriesIndex=this.componentIndex,this.dataTask=GS({count:ew,reset:tw}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(e,n),(YC(this).sourceManager=new bC(this)).prepareSource();var r=this.getInitialData(e,n);rw(r,this),this.dataTask.context.data=r,YC(this).dataBeforeProcessed=r,QC(this),this._initSelectedMapFromData(r)},t.prototype.mergeDefaultAndTheme=function(e,t){var n=Wx(this),r=n?Kx(e):{},i=this.subType;Yx.hasClass(i)&&(i+=`Series`),Uo(e,t.getTheme().get(this.subType)),Uo(e,this.getDefaultOption()),jc(e,`label`,[`show`]),this.fillDataTextStyle(e.data),n&&Gx(e,r,n)},t.prototype.mergeOption=function(e,t){e=Uo(this.option,e,!0),this.fillDataTextStyle(e.data);var n=Wx(this);n&&Gx(this.option,e,n);var r=YC(this).sourceManager;r.dirty(),r.prepareSource();var i=this.getInitialData(e,t);rw(i,this),this.dataTask.dirty(),this.dataTask.context.data=i,YC(this).dataBeforeProcessed=i,QC(this),this._initSelectedMapFromData(i)},t.prototype.fillDataTextStyle=function(e){if(e&&!cs(e))for(var t=[`show`],n=0;n=0&&u<0)&&(l=v,u=_,d=0),_===u&&(c[d++]=m))}return c.length=d,c},t.prototype.formatTooltip=function(e,t,n){return qC({series:this,dataIndex:e,multipleSeries:t})},t.prototype.isAnimationEnabled=function(){var e=this.ecModel;if(Ns.node&&!(e&&e.ssr))return!1;var t=this.getShallow(`animation`);return t&&this.getData().count()>this.getShallow(`animationThreshold`)&&(t=!1),!!t},t.prototype.restoreData=function(){this.dataTask.dirty()},t.prototype.getColorFromPalette=function(e,t,n){var r=this.ecModel,i=$x.prototype.getColorFromPalette.call(this,e,t,n);return i||=r.getColorFromPalette(e,t,n),i},t.prototype.coordDimToDataDim=function(e){return this.getRawData().mapDimensionsAll(e)},t.prototype.getProgressive=function(){return this.get(`progressive`)},t.prototype.getProgressiveThreshold=function(){return this.get(`progressiveThreshold`)},t.prototype.select=function(e,t){this._innerSelect(this.getData(t),e)},t.prototype.unselect=function(e,t){var n=this.option.selectedMap;if(n){var r=this.option.selectedMode,i=this.getData(t);if(r===`series`||n===`all`){this.option.selectedMap={},this._selectedDataIndicesMap={};return}for(var a=0;a=0&&n.push(i)}return n},t.prototype.isSelected=function(e,t){var n=this.option.selectedMap;if(!n)return!1;var r=this.getData(t);return(n===`all`||n[XC(r,e)])&&!r.getItemModel(e).get([`select`,`disabled`])},t.prototype.isUniversalTransitionEnabled=function(){if(this.__universalTransitionEnabled)return!0;var e=this.option.universalTransition;return e?e===!0||e&&e.enabled:!1},t.prototype._innerSelect=function(e,t){var n,r,i=this.option,a=i.selectedMode,o=t.length;if(a&&o){if(a===`series`)i.selectedMap=`all`;else if(a===`multiple`){os(i.selectedMap)||(i.selectedMap={});for(var s=i.selectedMap,c=0;c0&&this._innerSelect(e,t)}},t.registerClass=function(e){return Yx.registerClass(e)},t.protoInitialize=function(){var e=t.prototype;e.type=`series.__base__`,e.seriesIndex=0,e.ignoreStyleOnData=!1,e.hasSymbolVisual=!1,e.defaultSymbol=`circle`,e.visualStyleAccessPath=`itemStyle`,e.visualDrawType=`fill`}(),t}(Yx);Yo(ZC,US),Yo(ZC,$x),Fl(ZC,Yx);function QC(e){var t=e.name;Gc(e)||(e.name=$C(e)||t)}function $C(e){var t=e.getRawData(),n=t.mapDimensionsAll(`seriesName`),r=[];return G(n,function(e){var n=t.getDimensionInfo(e);n.displayName&&r.push(n.displayName)}),r.join(` `)}function ew(e){return e.model.getRawData().count()}function tw(e){var t=e.model;return t.setData(t.getRawData().cloneShallow()),nw}function nw(e,t){t.outputData&&e.end>t.outputData.count()&&t.model.getRawData().cloneShallow(t.outputData)}function rw(e,t){G(Ds(e.CHANGABLE_METHODS,e.DOWNSAMPLE_METHODS),function(n){e.wrapMethod(n,ns(iw,t))})}function iw(e,t){var n=aw(e);return n&&n.setOutputEnd((t||this).count()),t}function aw(e){var t=(e.ecModel||{}).scheduler,n=t&&t.getPipeline(e.uid);if(n){var r=n.currentTask;if(r){var i=r.agentStubMap;i&&(r=i.get(e.uid))}return r}}function ow(e){return e==null?0:e.length||1}function sw(e){return e}var cw=function(){function e(e,t,n,r,i,a){this._old=e,this._new=t,this._oldKeyGetter=n||sw,this._newKeyGetter=r||sw,this.context=i,this._diffModeMultiple=a===`multiple`}return e.prototype.add=function(e){return this._add=e,this},e.prototype.update=function(e){return this._update=e,this},e.prototype.updateManyToOne=function(e){return this._updateManyToOne=e,this},e.prototype.updateOneToMany=function(e){return this._updateOneToMany=e,this},e.prototype.updateManyToMany=function(e){return this._updateManyToMany=e,this},e.prototype.remove=function(e){return this._remove=e,this},e.prototype.execute=function(){this[this._diffModeMultiple?`_executeMultiple`:`_executeOneToOne`]()},e.prototype._executeOneToOne=function(){var e=this._old,t=this._new,n={},r=Array(e.length),i=Array(t.length);this._initIndexMap(e,null,r,`_oldKeyGetter`),this._initIndexMap(t,n,i,`_newKeyGetter`);for(var a=0;a1){var l=s.shift();s.length===1&&(n[o]=s[0]),this._update&&this._update(l,a)}else c===1?(n[o]=null,this._update&&this._update(s,a)):this._remove&&this._remove(a)}this._performRestAdd(i,n)},e.prototype._executeMultiple=function(){var e=this._old,t=this._new,n={},r={},i=[],a=[];this._initIndexMap(e,n,i,`_oldKeyGetter`),this._initIndexMap(t,r,a,`_newKeyGetter`);for(var o=0;o1&&d===1)this._updateManyToOne&&this._updateManyToOne(l,c),r[s]=null;else if(u===1&&d>1)this._updateOneToMany&&this._updateOneToMany(l,c),r[s]=null;else if(u===1&&d===1)this._update&&this._update(l,c),r[s]=null;else if(u>1&&d>1)this._updateManyToMany&&this._updateManyToMany(l,c),r[s]=null;else if(u>1)for(var f=0;f1)for(var o=0;oi&&(i+=lw);var p=Math.atan2(s,o);if(p<0&&(p+=lw),p>=r&&p<=i||p+lw>=r&&p+lw<=i)return c[0]=u,c[1]=d,l-n;var m=n*Math.cos(r)+e,h=n*Math.sin(r)+t,g=n*Math.cos(i)+e,_=n*Math.sin(i)+t,v=(m-o)*(m-o)+(h-s)*(h-s),y=(g-o)*(g-o)+(_-s)*(_-s);return v0){t=t/180*Math.PI,yw.fromArray(e[0]),bw.fromArray(e[1]),xw.fromArray(e[2]),wu.sub(Sw,yw,bw),wu.sub(Cw,xw,bw);var n=Sw.len(),r=Cw.len();if(!(n<.001||r<.001)){Sw.scale(1/n),Cw.scale(1/r);var i=Sw.dot(Cw);if(Math.cos(t)1&&wu.copy(Ew,xw),Ew.toArray(e[1])}}}}function Ow(e,t,n,r){var i=n===`normal`,a=i?e:e.ensureState(n);a.ignore=t;var o=r.get(`smooth`);o=o===!0?.3:Math.max(+o,0)||0,a.shape=a.shape||{},a.shape.smooth=o;var s=r.getModel(`lineStyle`).getLineStyle();i?e.useStyle(s):a.style=s}function kw(e,t){var n=t.smooth,r=t.points;if(r){if(e.moveTo(r[0][0],r[0][1]),n>0&&r.length>=3){var i=_u(r[0],r[1]),a=_u(r[1],r[2]);if(!i||!a){e.lineTo(r[1][0],r[1][1]),e.lineTo(r[2][0],r[2][1]);return}var o=Math.min(i,a)*n,s=bu([],r[1],r[0],o/i),c=bu([],r[1],r[2],o/a),l=bu([],s,c,.5);e.bezierCurveTo(s[0],s[1],s[0],s[1],l[0],l[1]),e.bezierCurveTo(c[0],c[1],c[0],c[1],r[2][0],r[2][1])}else for(var u=1;u0&&i&&S(-d/a,0,a);var g=e[0],_=e[a-1],v,y;b(),v<0&&C(-v,.8),y<0&&C(y,.8),b(),x(v,y,1),x(y,v,-1),b(),v<0&&w(-v),y<0&&w(y);function b(){v=g.rect[o]-n,y=r-_.rect[o]-_.rect[s]}function x(e,t,n){if(e<0){var r=Math.min(t,-e);if(r>0){S(r*n,0,a);var i=r+e;i<0&&C(-i*n,1)}else C(-e*n,1)}}function S(t,n,r){t!==0&&(u=!0);for(var i=n;i0)for(var c=0;c0;c--){var f=r[c-1]*d;S(-f,c,a)}}}function w(e){var t=e<0?-1:1;e=Math.abs(e);for(var n=Math.ceil(e/(a-1)),r=0;r0?S(n,0,r+1):S(-n,a-r-1,a),e-=n,e<=0)return}return u}function Kw(e){for(var t=0;t=0&&n.attr(i.oldLayoutSelect),qo(u,`emphasis`)>=0&&n.attr(i.oldLayoutEmphasis)),Sv(n,c,t,s)}else if(n.attr(c),!Ly(n).valueAnimation){var d=X(n.style.opacity,1);n.style.opacity=0,Cv(n,{style:{opacity:d}},t,s)}if(i.oldLayout=c,n.states.select){var f=i.oldLayoutSelect={};tT(f,c,nT),tT(f,n.states.select,nT)}if(n.states.emphasis){var p=i.oldLayoutEmphasis={};tT(p,c,nT),tT(p,n.states.emphasis,nT)}zy(n,s,l,t,t)}if(r&&!r.ignore&&!r.invisible){var i=eT(r),a=i.oldLayout,m={points:r.shape.points};a?(r.attr({shape:a}),Sv(r,{shape:m},t)):(r.setShape(m),r.style.strokePercent=0,Cv(r,{style:{strokePercent:1}},t)),i.oldLayout=m}},e}(),iT=Qc();function aT(e){e.registerUpdateLifecycle(`series:beforeupdate`,function(e,t,n){var r=iT(t).labelManager;r||=iT(t).labelManager=new rT,r.clearLabels()}),e.registerUpdateLifecycle(`series:layoutlabels`,function(e,t,n){var r=iT(t).labelManager;G(n.updatedSeries,function(e){r.addLabelsOfSeries(t.getViewOfSeriesModel(e))}),r.updateLayoutConfig(t),r.layout(t),r.processLabelsOverall()})}var oT=es({needTransform:1,normalize:1,scale:1,transformIn:1,transformOut:1,contain:1,getExtent:1,getExtentUnsafe:1,setExtent:1,setExtent2:1,getFilter:1,sanitize:1,getDefaultStartValue:1,freeze:1});function sT(e,t,n){var r;e||={};var i=Ab();if(i){var a=i.createBreakScaleMapper(t,n);a.hasBreaks()&&(G(oT,function(t){a[t]&&(e[t]=q(a[t],a))}),r=a)}return r??mT(e,n),{brk:r,mapper:e}}function cT(e,t){G(oT,function(n){e[n]=t[n]})}function lT(e,t){e.freeze=As}function uT(e){return e.getExtentUnsafe(0,2)}function dT(e,t){return e.getExtentUnsafe(1,t)||e.getExtentUnsafe(0,t)}function fT(e){var t=dT(e,3);return t[1]-t[0]}function pT(e){var t=e.getExtentUnsafe(0,3);return t[1]-t[0]}function mT(e,t){var n=e||{},r=[];return n._extents=r,r[0]=t?t.slice():ul(),W(n,hT),n}var hT={needTransform:function(){return!1},normalize:function(e){var t=this._extents[1]||this._extents[0];return t[1]===t[0]?.5:(e-t[0])/(t[1]-t[0])},scale:function(e){var t=this._extents[1]||this._extents[0];return e*(t[1]-t[0])+t[0]},transformIn:function(e){return e},transformOut:function(e){return e},contain:function(e){var t=dT(this,null);return e>=t[0]&&e<=t[1]},getExtent:function(){return this._extents[0].slice()},getExtentUnsafe:function(e){return this._extents[e]},setExtent:function(e,t){gT(this._extents,0,e,t)},setExtent2:function(e,t,n){var r=this._extents;r[e]||(r[e]=r[0].slice()),gT(r,e,t,n)},freeze:function(){}};function gT(e,t,n,r){gl(n,r)&&(e[t][0]=n,e[t][1]=r)}var _T=`expandAxisBreak`,vT=null;function yT(){return vT}var bT=function(){function e(){}return e.prototype.isBlank=function(){return this._isBlank},e.prototype.setBlank=function(e){this._isBlank=e},e}();Bl(bT);var xT=0,ST=function(){function e(e){this.categories=e.categories||[],this._needCollect=e.needCollect,this._deduplication=e.deduplication,this.uid=++xT,this._onCollect=e.onCollect}return e.createByAxisModel=function(t){var n=t.option,r=n.data,i=r&&K(r,CT);return new e({categories:i,needCollect:!i,deduplication:n.dedplication!==!1})},e.prototype.getOrdinal=function(e){return this._getOrCreateMap().get(e)},e.prototype.parseAndCollect=function(e){var t,n=this._needCollect;if(!Y(e)&&!n)return e;if(n&&!this._deduplication)return t=this.categories.length,this.categories[t]=e,this._onCollect&&this._onCollect(e,t),t;var r=this._getOrCreateMap();return t=r.get(e),t??(n?(t=this.categories.length,this.categories[t]=e,r.set(e,t),this._onCollect&&this._onCollect(e,t)):t=NaN),t},e.prototype._getOrCreateMap=function(){return this._map||=Es(this.categories)},e}();function CT(e){return os(e)&&e.value!=null?e.value:e+``}function wT(e){return TT(e)||DT(e)}function TT(e){return e.type===`interval`}function ET(e){return e.type===`time`}function DT(e){return e.type===`log`}function OT(e){return e.type===`ordinal`}function kT(e){var t=fc(e),n=Ws(10,t),r=Vs(e/n);return r?r===2?r=3:r===3?r=5:r*=2:r=1,ec(r*n,-t)}function AT(e){return nc(e)+2}function jT(e,t){return Gs(e)/Gs(t)}function MT(e,t,n){var r=n&&n.lookup;if(r){for(var i=0;i1&&a/o>2&&(i=Math.round(Math.ceil(i/o)*o)),i!==r[0]&&c(r[0],!0,!0);for(var s=i;s<=r[1];s+=o)c(s,!1,s===r[0]||s===r[1]);s-o!==r[1]&&c(r[1],!0,!0);function c(e,t,r){n({value:e,offInterval:t},r)}}var LT=function(e){U(t,e);function t(n){var r=e.call(this)||this;r.type=`ordinal`,r.parse=t.parse,cT(r,t.decoratedMethods);var i=n.ordinalMeta;i||=new ST({}),J(i)&&(i=new ST({categories:K(i,function(e){return os(e)?e.value:e})})),r._ordinalMeta=i;var a=sT(null,null,n.extent||[0,i.categories.length-1]);return r._mapper=a.mapper,lT(r,a.mapper),r}return t.parse=function(e){return e==null?e=NaN:Y(e)?(e=this._ordinalMeta.getOrdinal(e),e??=NaN):e=Vs(e),e},t.prototype.getTicks=function(){var e=[];return IT(this,0,function(t){e.push(t)}),e},t.prototype.getMinorTicks=function(e){},t.prototype.setSortInfo=function(e){if(e==null){this._ordinalNumbersByTick=this._ticksByOrdinalNumber=null;return}for(var t=e.ordinalNumbers,n=this._ordinalNumbersByTick=[],r=this._ticksByOrdinalNumber=[],i=0,a=this._ordinalMeta.categories.length,o=Rs(a,t.length);i=0&&e=0&&e=0&&eo[0]&&mi[1]||!isFinite(p)||!isFinite(i[1]))break}else{if(m>f)break;p=Rs(p,i[1]),m===f&&(p=i[1])}if(l.push({value:p}),p=ec(p+n,a),s){var h=s.calcNiceTickMultiple(p,d);h>=0&&(p=ec(p+h*n,a))}if(l.length>0&&p===l[l.length-1].value)break;if(l.length>u)return[]}var g=l.length?l[l.length-1].value:i[1];return r[1]>g&&l.push({value:e.expandToNicedExtent?ec(g+n,a):r[1]}),c&&o.pruneTicksByBreak(e.pruneByBreak,l,s.breaks,function(e){return e.value},t.interval,r),c&&e.breakTicks!==`none`&&o.addBreaksToTicks(l,s.breaks,r),l},t.prototype.getMinorTicks=function(e){return RT(this,e,Mb(this),this._cfg.interval)},t.prototype.getLabel=function(e,t){if(e==null)return``;var n=t&&t.precision;return n==null?n=nc(e.value)||0:n===`auto`&&(n=this._cfg.intervalPrecision),gx(ec(e.value,n,!0))},t.type=`interval`,t}(bT);bT.registerClass(zT);var BT=function(e,t,n,r){for(;n>>1;e[i][1]16?16:e>7.5?7:e>3.5?4:e>1.5?2:1}function GT(e){var t=30*Lb;return e/=t,e>6?6:e>3?3:e>2?2:1}function KT(e){return e/=Ib,e>12?12:e>6?6:e>3.5?4:e>2?2:1}function qT(e,t){return e/=t?Fb:Pb,e>30?30:e>20?20:e>15?15:e>10?10:e>5?5:e>2?2:1}function JT(e){return zs(pc(e,!0),1)}function YT(e,t,n){var r=Math.max(0,qo(Wb,t)-1);return tx(new Date(e),Wb[r],n).getTime()}function XT(e,t){var n=new Date(0);n[e](1);var r=n.getTime();n[e](1+t);var i=n.getTime()-r;return function(e,t){return Math.max(0,Math.round((t-e)/i))}}function ZT(e,t,n,r,i,a){var o=Gb,s=0;function c(e,t,n,i,o,c,l){for(var u=XT(o,e),d=t,f=new Date(d);d3e3));)if(f[o](f[i]()+e),d=f.getTime(),a){var p=a.calcNiceTickMultiple(d,u);p>0&&(f[o](f[i]()+p*e),d=f.getTime())}l.push({value:d,notAdd:d>r[1]})}function l(e,i,a){var o=[],s=!i.length;if(!UT(Yb(e),r[0],r[1],n)){s&&(i=[{value:YT(r[0],e,n)},{value:r[1]}]);for(var l=0;l=r[0]&&u<=r[1]&&c(f,u,d,p,m,h,o),e===`year`&&a.length>1&&l===0&&a.unshift({value:a[0].value-f})}}for(var l=0;l=r[0]&&v<=r[1]&&f++)}var y=i/t;if(f>y*1.5&&p>y/1.5||(u.push(g),f>y||e===o[m]))break}d=[]}}for(var b=Qo(K(u,function(e){return Qo(e,function(e){return e.value>=r[0]&&e.value<=r[1]&&!e.notAdd})}),function(e){return e.length>0}),x=b.length-1,S=[],m=0;mr[0])&&S.unshift({value:r[0],time:{level:0,upperTimeUnit:O,lowerTimeUnit:O},notNice:!0}),(!D||D.values&&(a=s);var c=HT.length,l=Math.min(BT(HT,a,0,c),c-1),u=HT[l][1],d=HT[Math.max(l-1,0)][0];e.setTimeInterval({approxInterval:a,interval:u,minLevelUnit:d})};bT.registerClass(VT);var $T=0,eE=1,tE=2,nE=function(e){U(t,e);function t(n){var r=e.call(this)||this;r.type=`log`,r.parse=zT.parse,r.base=n.logBase||10;var i=[],a=[],o=r._lookup={from:i,to:a};i[$T]=i[eE]=a[$T]=a[eE]=NaN,cT(r,t.mapperMethods);var s=Ab(),c=n.breakOption,l={lookup:o};return s&&s.parseAxisBreakOptionInwardTransform(c,r,{noNegative:!0},tE,l),r.powStub=new zT({breakParsed:l.original}),r.intervalStub=new zT({breakParsed:l.transformed}),lT(r,r.intervalStub),r}return t.prototype.getTicks=function(e){var t=this.base,n=this.powStub,r=Ab(),i=this.intervalStub,a={lookup:{from:i.getExtent(),to:n.getExtent()}};return K(i.getTicks(e||{}),function(e){var i=e.value,o=MT(i,t,a),s;if(r){var c=r.getTicksBreakOutwardTransform(this,e,Mb(n),this._lookup);c&&(s=c.vBreak,o=c.tickVal)}return{value:o,break:s}},this)},t.prototype.getMinorTicks=function(e){return RT(this,e,Mb(this.powStub),this.intervalStub.getConfig().interval)},t.prototype.getLabel=function(e,t){return this.intervalStub.getLabel(e,t)},t.type=`log`,t.mapperMethods={needTransform:function(){return!0},normalize:function(e){return this.intervalStub.normalize(jT(e,this.base))},scale:function(e){return MT(this.intervalStub.scale(e),this.base,null)},transformIn:function(e,t){return e=jT(e,this.base),t&&t.depth===2?e:this.intervalStub.transformIn(e,t)},transformOut:function(e,t){var n=t?t.depth:null;return rE.depth=n,iE.lookup=this._lookup,MT(n===2?e:this.intervalStub.transformOut(e,rE),this.base,iE)},contain:function(e){return this.powStub.contain(e)},setExtent:function(e,t){this.setExtent2(0,e,t)},setExtent2:function(e,t,n){if(!(!gl(t,n)||t<=0||n<=0)){var r=aE,i=aE;if(e===0){var a=this._lookup;r=a.to,i=a.from}this.powStub.setExtent2(e,r[$T]=t,r[eE]=n);var o=this.base;this.intervalStub.setExtent2(e,i[$T]=jT(t,o),i[eE]=jT(n,o))}},getFilter:function(){return{g:0}},sanitize:function(e,t){return gl(t[0],t[1])&&bc(e)&&e<=0&&(e=t[0]),e},getDefaultStartValue:function(){return 1},getExtent:function(){return this.powStub.getExtent()},getExtentUnsafe:function(e,t){return t===null?this.powStub.getExtentUnsafe(e,null):this.intervalStub.getExtentUnsafe(e,t)}},t}(bT);bT.registerClass(nE);var rE={},iE={},aE=[],oE={value:1,category:1,time:1,log:1},sE=Qc(),cE={float:`f`,int:`i`,ordinal:`o`,number:`n`,time:`t`},lE=function(){function e(e){this.dimensions=e.dimensions,this._dimOmitted=e.dimensionOmitted,this.source=e.source,this._fullDimCount=e.fullDimensionCount,this._updateDimOmitted(e.dimensionOmitted)}return e.prototype.isDimensionOmitted=function(){return this._dimOmitted},e.prototype._updateDimOmitted=function(e){this._dimOmitted=e,e&&(this._dimNameMap||=fE(this.source))},e.prototype.getSourceDimensionIndex=function(e){return X(this._dimNameMap.get(e),-1)},e.prototype.getSourceDimension=function(e){var t=this.source.dimensionsDefine;if(t)return t[e]},e.prototype.makeStoreSchema=function(){for(var e=this._fullDimCount,t=SS(this.source),n=!pE(e),r=``,i=[],a=0,o=0;a30}function mE(e,t,n){n||={};var r=n.byIndex,i=n.stackedCoordDimension,a,o,s;hE(t)?a=t:(o=t.schema,a=o.dimensions,s=t.store);var c=!!(e&&e.get(`stack`)),l,u,d,f,p=!0;function m(e){return e.type!==`ordinal`&&e.type!==`time`}if(G(a,function(e,t){Y(e)&&(a[t]=e={name:e}),m(e)||(p=!1)}),G(a,function(e,t){c&&!e.isExtraCoord&&(!r&&!l&&e.ordinalMeta&&(l=e),!u&&m(e)&&(!p||e.coordDim!==`x`&&e.coordDim!==`angle`)&&(!i||i===e.coordDim)&&(u=e))}),u&&!r&&!l&&(r=!0),u){d=`__\0ecstackresult_`+e.id,f=`__\0ecstackedover_`+e.id,l&&(l.createInvertedIndices=!0);var h=u.coordDim,g=u.type,_=0;G(a,function(e){e.coordDim===h&&_++});var v={name:d,coordDim:h,coordDimIndex:_,type:g,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:a.length},y={name:f,coordDim:f,coordDimIndex:_+1,type:g,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:a.length+1};o?(s&&(v.storeDimIndex=s.ensureCalculationDimension(f,g),y.storeDimIndex=s.ensureCalculationDimension(d,g)),o.appendCalculationDimension(v),o.appendCalculationDimension(y)):(a.push(v),a.push(y))}return{stackedDimension:u&&u.name,stackedByDimension:l&&l.name,isStackedByIndex:r,stackedOverDimension:f,stackResultDimension:d}}function hE(e){return!uE(e.schema)}function gE(e,t){return!!t&&t===e.getCalculationInfo(`stackedDimension`)}function _E(e,t){return gE(e,t)?e.getCalculationInfo(`stackResultDimension`):t}var vE=Qc();function yE(e){var t=e.get(`type`);return(t==null||!Z(oE,t)&&!bT.getClass(t))&&(t=`value`),t}function bE(e,t,n){var r=Ab(),i;switch(r&&(i=jE(e,t,n)),t){case`category`:return new LT({ordinalMeta:e.getOrdinalMeta?e.getOrdinalMeta():e.getCategories(),extent:ul()});case`time`:return new VT({locale:e.ecModel.getLocaleModel(),useUTC:e.ecModel.get(`useUTC`),breakOption:i});case`log`:return new nE({logBase:e.get(`logBase`),breakOption:i});case`value`:return new zT({breakOption:i});default:return new((bT.getClass(t))||zT)({})}}function xE(e,t,n){var r=n?dT(e,null):e.getExtentUnsafe(0,null),i=r[0],a=r[1];return gl(i,a)?i===t||a===t?2:it?1:3:3}function SE(e){vE(e).noOnMyZero=!0}function CE(e){return vE(e).noOnMyZero}function wE(e){var t=e.getLabelModel().get(`formatter`);if(e.type===`time`){var n=Kb(t);return function(t,r){return e.scale.getFormattedLabel(t,r,n)}}if(Y(t))return function(n){var r=e.scale.getLabel(n);return t.replace(`{value}`,r??``)};if(rs(t)){if(e.type===`category`)return function(n,r){return t(TE(e,n),n.value-e.scale.getExtent()[0],null)};var r=Ab();return function(n,i){var a=null;return r&&(a=r.makeAxisLabelFormatterParamBreak(a,n.break)),t(TE(e,n),i,a)}}return function(t){return e.scale.getLabel(t)}}function TE(e,t){var n=e.scale;return OT(n)?n.getLabel(t):t.value}function EE(e){return e.get(`interval`)??`auto`}function DE(e){return e.type===`category`&&EE(e.getLabelModel())===0}function OE(e,t){var n={};return G(e.mapDimensionsAll(t),function(t){n[_E(e,t)]=!0}),es(n)}function kE(e){return e===`middle`||e===`center`}function AE(e){return e.getShallow(`show`)}function jE(e,t,n){var r=e.get(`breaks`,!0);if(r!=null)return!Ab()||!n||!ME(t)?void 0:r}function ME(e){return e!==`category`}function NE(e,t,n,r,i,a){var o=DT(e),s=o?e.intervalStub:e;if(s.setExtent(r[0],r[1]),o){var c=e.powStub,l={depth:2},u=e.transformOut(r[0],l),d=e.transformOut(r[1],l),f=PT(n,r);t[0]&&!f[0]&&(u=i[0]),t[1]&&!f[1]&&(d=i[1]),c.setExtent(u,d)}s.setConfig(a)}function PE(e,t){return OT(e)?e.getRawOrdinalNumber(t.value):t.value}function FE(e,t){return OT(e)&&!!t.get(`boundaryGap`)}var IE=function(){function e(e){this.type=`cartesian`,this._dimList=[],this._axes={},this.name=e||``}return e.prototype.getAxis=function(e){return this._axes[e]},e.prototype.getAxes=function(){return K(this._dimList,function(e){return this._axes[e]},this)},e.prototype.getAxesByScale=function(e){return e=e.toLowerCase(),Qo(this.getAxes(),function(t){return t.scale.type===e})},e.prototype.addAxis=function(e){var t=e.dim;this._axes[t]=e,this._dimList.push(t)},e}(),LE={left:0,right:0,top:0,bottom:0},RE=[`25%`,`25%`],zE=`cartesian2d`,BE=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.mergeDefaultAndTheme=function(t,n){var r=Kx(t.outerBounds);e.prototype.mergeDefaultAndTheme.apply(this,arguments),r&&t.outerBounds&&Gx(t.outerBounds,r)},t.prototype.mergeOption=function(t,n){e.prototype.mergeOption.apply(this,arguments),this.option.outerBounds&&t.outerBounds&&Gx(this.option.outerBounds,t.outerBounds)},t.type=`grid`,t.dependencies=[`xAxis`,`yAxis`],t.layoutMode=`box`,t.defaultOption={show:!1,z:0,left:`15%`,top:65,right:`10%`,bottom:80,containLabel:!1,outerBoundsMode:`auto`,outerBounds:LE,outerBoundsContain:`all`,outerBoundsClampWidth:RE[0],outerBoundsClampHeight:RE[1],backgroundColor:Q.color.transparent,borderWidth:1,borderColor:Q.color.neutral30},t}(Yx),VE=[`x`,`y`];function HE(e){return(e.type===`interval`||e.type===`time`)&&!Nb(e)}var UE=function(e){U(t,e);function t(){var t=e!==null&&e.apply(this,arguments)||this;return t.type=zE,t.dimensions=VE,t}return t.prototype.calcAffineTransform=function(){this._transform=this._invTransform=null;var e=this.getAxis(`x`).scale,t=this.getAxis(`y`).scale;if(HE(e)&&HE(t)){var n=dT(e,null),r=dT(t,null),i=this.dataToPoint([n[0],r[0]]),a=this.dataToPoint([n[1],r[1]]),o=n[1]-n[0],s=r[1]-r[0];if(o&&s){var c=(a[0]-i[0])/o,l=(a[1]-i[1])/s,u=i[0]-n[0]*c,d=i[1]-r[0]*l,f=this._transform=[c,0,0,l,u,d];this._invTransform=au([],f)}}},t.prototype.getBaseAxis=function(){return this.getAxesByScale(`ordinal`)[0]||this.getAxesByScale(`time`)[0]||this.getAxis(`x`)},t.prototype.containPoint=function(e){var t=this.getAxis(`x`),n=this.getAxis(`y`);return t.contain(t.toLocalCoord(e[0]))&&n.contain(n.toLocalCoord(e[1]))},t.prototype.containData=function(e){return this.getAxis(`x`).containData(e[0])&&this.getAxis(`y`).containData(e[1])},t.prototype.containZone=function(e,t){var n=this.dataToPoint(e),r=this.dataToPoint(t),i=this.getArea(),a=new Ru(n[0],n[1],r[0]-n[0],r[1]-n[1]);return i.intersect(a)},t.prototype.dataToPoint=function(e,t,n){n||=[];var r=e[0],i=e[1];if(this._transform&&r!=null&&isFinite(r)&&i!=null&&isFinite(i))return xu(n,e,this._transform);var a=this.getAxis(`x`),o=this.getAxis(`y`);return n[0]=a.toGlobalCoord(a.dataToCoord(r,t)),n[1]=o.toGlobalCoord(o.dataToCoord(i,t)),n},t.prototype.clampData=function(e,t){var n=this.getAxis(`x`).scale,r=this.getAxis(`y`).scale,i=n.getExtent(),a=r.getExtent(),o=n.parse(e[0]),s=r.parse(e[1]);return t||=[],t[0]=Math.min(Math.max(Math.min(i[0],i[1]),o),Math.max(i[0],i[1])),t[1]=Math.min(Math.max(Math.min(a[0],a[1]),s),Math.max(a[0],a[1])),t},t.prototype.pointToData=function(e,t,n){if(n||=[],this._invTransform)return xu(n,e,this._invTransform);var r=this.getAxis(`x`),i=this.getAxis(`y`);return n[0]=r.coordToData(r.toLocalCoord(e[0]),t),n[1]=i.coordToData(i.toLocalCoord(e[1]),t),n},t.prototype.getOtherAxis=function(e){return this.getAxis(e.dim===`x`?`y`:`x`)},t.prototype.getArea=function(e){e||=0;var t=this.getAxis(`x`).getGlobalExtent(),n=this.getAxis(`y`).getGlobalExtent(),r=Math.min(t[0],t[1])-e,i=Math.min(n[0],n[1])-e;return new Ru(r,i,Math.max(t[0],t[1])-r+e,Math.max(n[0],n[1])-i+e)},t}(IE),WE=Qc(),GE=Qc(),KE={estimate:1,determine:2};function qE(e){return{out:{noPxChangeTryDetermine:[]},kind:e}}function JE(e,t){var n=e.getLabelModel().get(`customValues`);if(n){var r=e.scale;return{labels:K(XE(n,r),function(t,n){return{formattedLabel:wE(e)(t,n),rawLabel:r.getLabel(t),tick:t}})}}return e.type===`category`?ZE(e,t):eD(e)}function YE(e,t,n){var r=e.scale,i=e.getTickModel().get(`customValues`);return i?{ticks:XE(i,r)}:e.type===`category`?$E(e,t):{ticks:r.getTicks(n)}}function XE(e,t){var n=t.getExtent(),r=[];return G(e,function(e){e=t.parse(e),e>=n[0]&&e<=n[1]&&r.push(e)}),xl(r,Cl,null),tc(r),K(r,function(e){return{value:e}})}function ZE(e,t){var n=e.getLabelModel(),r=QE(e,n,t);return!n.get(`show`)||e.scale.isBlank()?{labels:[]}:r}function QE(e,t,n){var r=nD(e),i=EE(t),a=n.kind===KE.estimate;if(!a){var o=iD(r,i);if(o)return o}var s,c;rs(i)?s=dD(e,i,!1):(c=i===`auto`?oD(e,n):i,s=dD(e,c,!1));var l={labels:s,labelCategoryInterval:c};return a?n.out.noPxChangeTryDetermine.push(function(){return aD(r,i,l),!0}):aD(r,i,l),l}function $E(e,t){var n=tD(e),r=EE(t),i=iD(n,r);if(i)return i;var a,o;if((!t.get(`show`)||e.scale.isBlank())&&(a=[]),rs(r))a=dD(e,r,!0);else if(r===`auto`){var s=QE(e,e.getLabelModel(),qE(KE.determine));o=s.labelCategoryInterval,a=K(s.labels,function(e){return e.tick})}else o=r,a=dD(e,o,!0);return aD(n,r,{ticks:a,tickCategoryInterval:o})}function eD(e){var t=e.scale.getTicks(),n=wE(e);return{labels:K(t,function(t,r){return{formattedLabel:n(t,r),rawLabel:e.scale.getLabel(t),tick:t}})}}var tD=rD(`axisTick`),nD=rD(`axisLabel`);function rD(e){return function(t){return GE(t)[e]||(GE(t)[e]={list:[]})}}function iD(e,t){for(var n=0;nu&&(l=Math.max(1,Math.floor(c/u)));for(var d=s[0],f=e.dataToCoord(d+1)-e.dataToCoord(d),p=Math.abs(f*Math.cos(a)),m=Math.abs(f*Math.sin(a)),h=0,g=0;d<=s[1];d+=l){var _=0,v=0,y=id(i({value:d}),r.font,`center`,`top`);_=y.width*1.3,v=y.height*1.3,h=Math.max(h,_,7),g=Math.max(g,v,7)}var b=h/p,x=g/m;isNaN(b)&&(b=1/0),isNaN(x)&&(x=1/0);var S=Math.max(0,Math.floor(Math.min(b,x)));return n===KE.estimate?(t.out.noPxChangeTryDetermine.push(q(cD,null,e,S,c)),S):lD(e,S,c)??S}function cD(e,t,n){return lD(e,t,n)==null}function lD(e,t,n){var r=WE(e.model),i=e.getExtent(),a=r.lastAutoInterval,o=r.lastTickCount;if(a!=null&&o!=null&&Math.abs(a-t)<=1&&Math.abs(o-n)<=1&&a>t&&r.axisExtent0===i[0]&&r.axisExtent1===i[1])return a;r.lastTickCount=n,r.lastAutoInterval=t,r.axisExtent0=i[0],r.axisExtent1=i[1]}function uD(e){var t=e.getLabelModel();return{axisRotate:e.getRotate?e.getRotate():e.isHorizontal&&!e.isHorizontal()?90:0,labelRotate:t.get(`rotate`)||0,font:t.getFont()}}function dD(e,t,n){var r=wE(e),i=e.scale,a=[],o=rs(t);return IT(i,o?0:t,function(e,s){var c=i.getLabel(e);if(o){var l=!!t(e.value,c);if(e.offInterval=!l,!l&&!s)return}a.push(n?e:{formattedLabel:r(e),rawLabel:c,tick:e})}),a}var fD=Qc();function pD(e){fD(e).prepare={}}function mD(e){fD(e).fullUpdate={}}function hD(e){return fD(e).prepare}function gD(e){return fD(e).fullUpdate}var _D=yl(),vD=Qc(),yD=Qc();function bD(e,t){var n=e.model,r=vD(gD(n.ecModel)).keyed,i=r&&r.get(t);return i&&i.get(n.uid)}function xD(e,t){return wD(bD(e,t))}function SD(e,t){var n=[];return CD(e.model.ecModel,function(e){for(var r=0;r0?(t>o&&(o=t),a=!1):t===-2&&(a=!0))}),bc(n)&&n>0&&bc(o)?(e.w=r/n*o,e.w2=o):a&&(e.w=r*LD,e.w2=e.w*n/r)}var VD=[0,1],HD=function(){function e(e,t,n){this.onBand=!1,this.inverse=!1,this.dim=e,this.scale=t,this._extent=n||[0,0]}return e.prototype.contain=function(e){var t=this._extent,n=Math.min(t[0],t[1]),r=Math.max(t[0],t[1]);return e>=n&&e<=r},e.prototype.containData=function(e){return this.scale.contain(this.scale.parse(e))},e.prototype.getExtent=function(){return this._extent.slice()},e.prototype.setExtent=function(e,t){var n=this._extent;n[0]=e,n[1]=t},e.prototype.dataToCoord=function(e,t){var n=this.scale;return e=n.normalize(n.parse(e)),Ys(e,VD,UD(this),t)},e.prototype.coordToData=function(e,t){var n=Ys(e,UD(this),VD,t);return this.scale.scale(n)},e.prototype.pointToData=function(e,t){},e.prototype.getTicksCoords=function(e){e||={};var t=e.tickModel||this.getTickModel(),n=K(YE(this,t,{breakTicks:e.breakTicks,pruneByBreak:e.pruneByBreak}).ticks,function(e){return{coord:this.dataToCoord(PE(this.scale,e)),tick:e}},this),r=t.get(`alignWithLabel`),i=WD(this,n,r);return K(n,function(e){return{coord:e.coord,tickValue:e.tick.value,onBand:i}})},e.prototype.getMinorTicksCoords=function(){if(OT(this.scale))return[];var e=this.model.getModel(`minorTick`).get(`splitNumber`);return e>0&&e<100||(e=5),K(this.scale.getMinorTicks(e),function(e){return K(e,function(e){return{coord:this.dataToCoord(e),tickValue:e}},this)},this)},e.prototype.getViewLabels=function(e){return e||=qE(KE.determine),JE(this,e).labels},e.prototype.getLabelModel=function(){return this.model.getModel(`axisLabel`)},e.prototype.getTickModel=function(){return this.model.getModel(`axisTick`)},e.prototype.getBandWidth=function(){return RD(this,{min:1}).w},e.prototype.calculateCategoryInterval=function(e){return e||=qE(KE.determine),sD(this,e)},e}();function UD(e){var t=e.getExtent();if(e.onBand){var n=(t[1]-t[0])/e.scale.count()/2;t[0]+=n,t[1]-=n}return t}function WD(e,t,n){var r=t.length;if(!e.onBand||n||!r)return!1;var i=RD(e).w;if(!i)return!1;G(t,function(e){e.coord-=i/2});var a=e.scale.getExtent(),o=t[r-1];return o.tick.offInterval&&t.pop(),t.push({coord:o.coord+i,tick:{value:a[1]+1}}),!0}var GD=function(e){U(t,e);function t(t,n,r,i,a){var o=e.call(this,t,n,r)||this;return o.index=0,o.type=i||`value`,o.position=a||`bottom`,o}return t.prototype.isHorizontal=function(){var e=this.position;return e===`top`||e===`bottom`},t.prototype.getGlobalExtent=function(e){var t=this.getExtent();return t[0]=this.toGlobalCoord(t[0]),t[1]=this.toGlobalCoord(t[1]),e&&t[0]>t[1]&&t.reverse(),t},t.prototype.pointToData=function(e,t){return this.coordToData(this.toLocalCoord(e[this.dim===`x`?0:1]),t)},t.prototype.setCategorySortInfo=function(e){if(this.type!==`category`)return!1;this.model.option.categorySortInfo=e,this.scale.setSortInfo(e)},t}(HD),KD=Qm.extend({type:`triangle`,shape:{cx:0,cy:0,width:0,height:0},buildPath:function(e,t){var n=t.cx,r=t.cy,i=t.width/2,a=t.height/2;e.moveTo(n,r-a),e.lineTo(n+i,r+a),e.lineTo(n-i,r+a),e.closePath()}}),qD={line:Z_,rect:fh,roundRect:fh,square:fh,circle:x_,diamond:Qm.extend({type:`diamond`,shape:{cx:0,cy:0,width:0,height:0},buildPath:function(e,t){var n=t.cx,r=t.cy,i=t.width/2,a=t.height/2;e.moveTo(n,r-a),e.lineTo(n+i,r),e.lineTo(n,r+a),e.lineTo(n-i,r),e.closePath()}}),pin:Qm.extend({type:`pin`,shape:{x:0,y:0,width:0,height:0},buildPath:function(e,t){var n=t.x,r=t.y,i=t.width/5*3,a=Math.max(i,t.height),o=i/2,s=o*o/(a-o),c=r-a+o+s,l=Math.asin(s/o),u=Math.cos(l)*o,d=Math.sin(l),f=Math.cos(l),p=o*.6,m=o*.7;e.moveTo(n-u,c+s),e.arc(n,c,o,Math.PI-l,Math.PI*2+l),e.bezierCurveTo(n+u-d*p,c+s+f*p,n,r-m,n,r),e.bezierCurveTo(n,r-m,n-u+d*p,c+s+f*p,n-u,c+s),e.closePath()}}),arrow:Qm.extend({type:`arrow`,shape:{x:0,y:0,width:0,height:0},buildPath:function(e,t){var n=t.height,r=t.width,i=t.x,a=t.y,o=r/3*2;e.moveTo(i,a),e.lineTo(i+o,a+n),e.lineTo(i,a+n/4*3),e.lineTo(i-o,a+n),e.lineTo(i,a),e.closePath()}}),triangle:KD},JD={line:function(e,t,n,r,i){i.x1=e,i.y1=t+r/2,i.x2=e+n,i.y2=t+r/2},rect:function(e,t,n,r,i){i.x=e,i.y=t,i.width=n,i.height=r},roundRect:function(e,t,n,r,i){i.x=e,i.y=t,i.width=n,i.height=r,i.r=Math.min(n,r)/4},square:function(e,t,n,r,i){var a=Math.min(n,r);i.x=e,i.y=t,i.width=a,i.height=a},circle:function(e,t,n,r,i){i.cx=e+n/2,i.cy=t+r/2,i.r=Math.min(n,r)/2},diamond:function(e,t,n,r,i){i.cx=e+n/2,i.cy=t+r/2,i.width=n,i.height=r},pin:function(e,t,n,r,i){i.x=e+n/2,i.y=t+r/2,i.width=n,i.height=r},arrow:function(e,t,n,r,i){i.x=e+n/2,i.y=t+r/2,i.width=n,i.height=r},triangle:function(e,t,n,r,i){i.cx=e+n/2,i.cy=t+r/2,i.width=n,i.height=r}},YD={};G(qD,function(e,t){YD[t]=new e});var XD=Qm.extend({type:`symbol`,shape:{symbolType:``,x:0,y:0,width:0,height:0},calculateTextPosition:function(e,t,n){var r=ld(e,t,n),i=this.shape;return i&&i.symbolType===`pin`&&t.position===`inside`&&(r.y=n.y+n.height*.4),r},buildPath:function(e,t,n){var r=t.symbolType;if(r!==`none`){var i=YD[r];i||=(r=`rect`,YD[r]),JD[r](t.x,t.y,t.width,t.height,i.shape),i.buildPath(e,i.shape,n)}}});function ZD(e,t){if(this.type!==`image`){var n=this.style;this.__isEmptyBrush?(n.stroke=e,n.fill=t||Q.color.neutral00,n.lineWidth=2):this.shape.symbolType===`line`?n.stroke=e:n.fill=e,this.markRedraw()}}function QD(e,t,n,r,i,a,o){var s=e.indexOf(`empty`)===0;s&&(e=e.substr(5,1).toLowerCase()+e.substr(6));var c=e.indexOf(`image://`)===0?zv(e.slice(8),new Ru(t,n,r,i),o?`center`:`cover`):e.indexOf(`path://`)===0?Rv(e.slice(7),{},new Ru(t,n,r,i),o?`center`:`cover`):new XD({shape:{symbolType:e,x:t,y:n,width:r,height:i}});return c.__isEmptyBrush=s,c.setColor=ZD,a&&c.setColor(a),c}function $D(e){return J(e)||(e=[+e,+e]),[e[0]||0,e[1]||0]}function eO(e,t){if(e!=null)return J(e)||(e=[e,e]),[Xs(e[0],t[0])||0,Xs(X(e[1],e[0]),t[1])||0]}var tO=Math.PI,nO=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],rO=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],iO=Qc(),aO=Qc(),oO=function(){function e(e){this.recordMap={},this.resolveAxisNameOverlap=e}return e.prototype.ensureRecord=function(e){var t=e.axis.dim,n=e.componentIndex,r=this.recordMap,i=r[t]||(r[t]=[]);return i[n]||(i[n]={ready:{}})},e}();function sO(e,t,n,r){var i=n.axis,a=t.ensureRecord(n),o=[],s,c=jO(e.axisName)&&kE(e.nameLocation);G(r,function(e){var t=Rw(e);if(t&&!t.label.ignore){o.push(t);var n=a.transGroup;c&&(n.transform?au(cO,n.transform):$l(cO),t.transform&&tu(cO,cO,t.transform),Ru.copy(lO,t.localRect),lO.applyTransform(cO),s?s.union(lO):Ru.copy(s=new Ru(0,0,0,0),lO))}});var l=Math.abs(a.dirVec.x)>.1?`x`:`y`,u=a.transGroup[l];if(o.sort(function(e,t){return Math.abs(e.label[l]-u)-Math.abs(t.label[l]-u)}),c&&s){var d=i.getExtent(),f=Math.min(d[0],d[1]),p=Math.max(d[0],d[1])-f;s.union(new Ru(f,0,p,1))}a.stOccupiedRect=s,a.labelInfoList=o}var cO=Ql(),lO=new Ru(0,0,0,0),uO=function(e,t,n,r,i,a){if(kE(e.nameLocation)){var o=a.stOccupiedRect;o&&dO(Vw({},o,a.transGroup.transform),r,i)}else fO(a.labelInfoList,a.dirVec,r,i)};function dO(e,t,n){var r=new wu;Jw(e,t,r,{direction:Math.atan2(n.y,n.x),bidirectional:!1,touchThreshold:.05})&&Hw(t,r)}function fO(e,t,n,r){for(var i=wu.dot(r,t)>=0,a=0,o=e.length;a0?`top`:`bottom`,i=`center`):cc(r-tO)?(a=n>0?`bottom`:`top`,i=`center`):(a=`middle`,i=r>0&&r0?`right`:`left`:n>0?`left`:`right`),{rotation:r,textAlign:i,textVerticalAlign:a}},e.makeAxisEventDataBase=function(e){var t={componentType:e.mainType,componentIndex:e.componentIndex};return t[e.mainType+`Index`]=e.componentIndex,t},e.isLabelSilent=function(e){var t=e.get(`tooltip`);return e.get(`silent`)||!(e.get(`triggerEvent`)||t&&t.show)},e}(),mO=[`axisLine`,`axisTickLabelEstimate`,`axisTickLabelDetermine`,`axisName`],hO={axisLine:function(e,t,n,r,i,a,o){var s=r.get([`axisLine`,`show`]);if(s===`auto`&&(s=!0,e.raw.axisLineAutoShow!=null&&(s=!!e.raw.axisLineAutoShow)),s){var c=r.axis.getExtent(),l=a.transform,u=[c[0],0],d=[c[1],0],f=u[0]>d[0];l&&(xu(u,u,l),xu(d,d,l));var p=W({lineCap:`round`},r.getModel([`axisLine`,`lineStyle`]).getLineStyle()),m={strokeContainThreshold:e.raw.strokeContainThreshold||5,silent:!0,z2:1,style:p};if(r.get([`axisLine`,`breakLine`])&&Nb(r.axis.scale))yT().buildAxisBreakLine(r,i,a,m);else{var h=new Z_(W({shape:{x1:u[0],y1:u[1],x2:d[0],y2:d[1]}},m));Uv(h.shape,h.style.lineWidth),h.anid=`line`,i.add(h)}var g=r.get([`axisLine`,`symbol`]);if(g!=null){var _=r.get([`axisLine`,`symbolSize`]);Y(g)&&(g=[g,g]),(Y(_)||as(_))&&(_=[_,_]);var v=eO(r.get([`axisLine`,`symbolOffset`])||0,_),y=_[0],b=_[1];G([{rotate:e.rotation+Math.PI/2,offset:v[0],r:0},{rotate:e.rotation-Math.PI/2,offset:v[1],r:Math.sqrt((u[0]-d[0])*(u[0]-d[0])+(u[1]-d[1])*(u[1]-d[1]))}],function(t,n){if(g[n]!==`none`&&g[n]!=null){var r=QD(g[n],-y/2,-b/2,y,b,p.stroke,!0),a=t.r+t.offset,o=f?d:u;r.attr({rotation:t.rotate,x:o[0]+a*Math.cos(e.rotation),y:o[1]-a*Math.sin(e.rotation),silent:!0,z2:11}),i.add(r)}})}}},axisTickLabelEstimate:function(e,t,n,r,i,a,o,s){wO(t,i,s)&&gO(e,t,n,r,i,a,o,KE.estimate)},axisTickLabelDetermine:function(e,t,n,r,i,a,o,s){wO(t,i,s)&&gO(e,t,n,r,i,a,o,KE.determine);var c=SO(e,i,a,r);yO(e,t.labelLayoutList,c),CO(e,i,a,r,e.tickDirection)},axisName:function(e,t,n,r,i,a,o,s){var c=n.ensureRecord(r);t.nameEl&&=(i.remove(t.nameEl),c.nameLayout=c.nameLocation=null);var l=e.axisName;if(jO(l)){var u=e.nameLocation,d=e.nameDirection,f=r.getModel(`nameTextStyle`),p=r.get(`nameGap`)||0,m=r.axis.getExtent(),h=r.axis.inverse?-1:1,g=new wu(0,0),_=new wu(0,0);u===`start`?(g.x=m[0]-h*p,_.x=-h):u===`end`?(g.x=m[1]+h*p,_.x=h):(g.x=(m[0]+m[1])/2,g.y=e.labelOffset+d*p,_.y=d);var v=Ql();_.transform(ru(v,v,e.rotation));var y=r.get(`nameRotate`);y!=null&&(y=y*tO/180);var b,x;kE(u)?b=pO.innerTextLayout(e.rotation,y??e.rotation,d):(b=_O(e.rotation,u,y||0,m),x=e.raw.axisNameAvailableWidth,x!=null&&(x=Math.abs(x/Math.sin(b.rotation)),!isFinite(x)&&(x=null)));var S=f.getFont(),C=r.get(`nameTruncate`,!0)||{},w=C.ellipsis,T=ps(e.raw.nameTruncateMaxWidth,C.maxWidth,x),E=s.nameMarginLevel||0,D=new _h({x:g.x,y:g.y,rotation:b.rotation,silent:pO.isLabelSilent(r),style:Oy(f,{text:l,font:S,overflow:`truncate`,width:T,ellipsis:w,fill:f.getTextColor()||r.get([`axisLine`,`lineStyle`,`color`]),align:f.get(`align`)||b.textAlign,verticalAlign:f.get(`verticalAlign`)||b.textVerticalAlign}),z2:1});if(cy({el:D,componentModel:r,itemName:l}),D.__fullText=l,D.anid=`name`,r.get(`triggerEvent`)){var O=pO.makeAxisEventDataBase(r);O.targetType=`axisName`,O.name=l,jh(D).eventData=O}a.add(D),D.updateTransform(),t.nameEl=D;var k=c.nameLayout=Rw({label:D,priority:D.z2,defaultAttr:{ignore:D.ignore},marginDefault:kE(u)?nO[E]:rO[E]});if(c.nameLocation=u,i.add(D),D.decomposeTransform(),e.shouldNameMoveOverlap&&k){var A=n.ensureRecord(r);n.resolveAxisNameOverlap(e,n,r,k,_,A)}}}};function gO(e,t,n,r,i,a,o,s){EO(t)||TO(e,t,i,s,r,o);var c=t.labelLayoutList;OO(e,r,c,a),NO(r,e.rotation,c);var l=e.optionHideOverlap;vO(r,c,l),l&&qw(Qo(c,function(e){return e&&!e.label.ignore})),sO(e,n,r,c)}function _O(e,t,n,r){var i=sc(n-e),a,o,s=r[0]>r[1],c=t===`start`&&!s||t!==`start`&&s;return cc(i-tO/2)?(o=c?`bottom`:`top`,a=`center`):cc(i-tO*1.5)?(o=c?`top`:`bottom`,a=`center`):(o=`middle`,a=itO/2?c?`left`:`right`:c?`right`:`left`),{rotation:i,textAlign:a,textVerticalAlign:o}}function vO(e,t,n){var r=e.axis,i=e.get([`axisLabel`,`customValues`]);if(DE(r))return;function a(e,a,o){var s=Rw(t[a]),c=Rw(t[o]),l=r.scale;if(s&&c){if(e==null){if(!n&&i)return;var u=iO(s.label).labelInfo.tick;if(ET(l)&&u.notNice||OT(l)&&u.offInterval){bO(s.label);return}}if(e===!1||s.suggestIgnore){bO(s.label);return}if(c.suggestIgnore){bO(c.label);return}var d=.1;if(!n){var f=[0,0,0,0];s=Uw({marginForce:f},s),c=Uw({marginForce:f},c)}Jw(s,c,null,{touchThreshold:d})&&bO(e?c.label:s.label)}}var o=e.get([`axisLabel`,`showMinLabel`]),s=e.get([`axisLabel`,`showMaxLabel`]),c=t.length;a(o,0,1),a(s,c-1,c-2)}function yO(e,t,n){e.showMinorTicks||G(t,function(e){if(e&&e.label.ignore)for(var t=0;t0&&u[1]>0&&!d[0]&&(u[0]=0),u[0]<0&&u[1]<0&&!d[1]&&(u[1]=0));var y=!1;u[0]>u[1]&&(u.reverse(),y=!0);var b=WO(e,t.get(`startValue`,!0)),x=b!=null;!bc(b)&&r&&(b=e.getDefaultStartValue?e.getDefaultStartValue():0),bc(b)&&(x||!_||v)&&(bu[1]&&!d[1]&&(u[1]=b,d[1]=!0)),UO(this._i={scale:e,dataMM:l,noZoomEffMM:u,zoomMM:[],fixMM:d,zoomFixMM:[!1,!1],startValue:b,isBlank:g,incl0:v,tggAxInv:y,ctnShp:i},u)}return e.prototype.makeNoZoom=function(){return this._i.noZoomEffMM.slice()},e.prototype.makeFinal=function(){var e=this._i,t=e.zoomMM,n=e.noZoomEffMM,r=e.zoomFixMM,i=e.fixMM,a={fixMM:i,zoomFixMM:r,isBlank:e.isBlank,incl0:e.incl0,tggAxInv:e.tggAxInv,ctnShp:e.ctnShp,effMM:n.slice()},o=a.effMM;return t[0]!=null&&(o[0]=t[0],i[0]=r[0]=!0),t[1]!=null&&(o[1]=t[1],i[1]=r[1]=!0),UO(e,o),a},e.prototype.makeRenderInfo=function(){return{startValue:this._i.startValue}},e.prototype.setZoomMM=function(e,t){this._i.zoomMM[e]=t},e}();function UO(e,t){var n=e.scale,r=e.dataMM;n.sanitize&&(t[0]=n.sanitize(t[0],r),t[1]=n.sanitize(t[1],r),vl(t))}function WO(e,t){return t==null?null:fs(t)?NaN:e.parse(t)}function GO(e,t){var n;if(OT(e))n=[0,0];else{var r=t.get(`boundaryGap`);typeof r==`boolean`&&(r=null),n=J(r)?r:[r,r]}return[KO(n[0]),KO(n[1])]}function KO(e){return cd(typeof e==`boolean`?0:e,1)||0}function qO(e){var t=BO(e.scale);return t.extent||=ul(),t}function JO(e,t){qO(e).dimIdxInCoord=t.get(e.dim)}function YO(e,t){var n=e.scale,r=e.model,i=e.dim;n.rawExtentInfo||XO(n,e,i,r,t)}function XO(e,t,n,r,i){var a=qO(t),o=a.extent,s=!1;TD(t,function(r){if(r.boxCoordinateSystem){var i=jx(r).coord,c=a.dimIdxInCoord;if(c>=0&&J(i)){var l=i[c];l!=null&&!J(l)&&dl(o,e.parse(l))}}else if(r.coordinateSystem){var u=r.getData();if(u){var d=e.getFilter?e.getFilter():null;G(OE(u,n),function(e){ml(o,u.getApproximateExtent(e,d))})}r.__requireStartValue&&r.__requireStartValue(t)&&(s=!0)}});var c=nk(e,t,r);QO(e,new HO(e,r,o,s,c),i),a.extent=null}function ZO(e,t){var n=e.scale;QO(n,new HO(n,e.model,t,!1,!1),VO)}function QO(e,t,n){e.rawExtentInfo=t,t.from=n}function $O(e,t){ek.set(e,t)}var ek=Es();function tk(e,t,n,r,i){e.rawExtentInfo||ZO({scale:e,model:t},i||ul());var a=e.rawExtentInfo.makeFinal(),o=a.effMM;return e.setExtent(o[0],o[1]),e.setBlank(a.isBlank),r&&a.tggAxInv&&n&&!n.get(`legacyMinMaxDontInverseAxis`)&&(r.inverse=!r.inverse),a}function nk(e,t,n){var r=FE(e,n),i=n.get(`containShape`,!0);if(i==null&&!r&&(i=!0),!i)return!1;var a=!1;return kD(t,function(e){a=!!ek.get(e)||a}),a}function rk(e,t,n,r){if(n.ctnShp){var i;if(kD(e,function(t){var n=ek.get(t);if(n){var a=n(e,r);a&&(i||=[0,0],fl(i,a[0]),pl(i,a[1]),SE(e))}}),i){var a=t.getExtent();if(OT(t))e.onBand||t.setExtent2(1,Rs(a[0],a[0]+i[0]),zs(a[1],a[1]+i[1]));else{var o=a.slice();n.zoomFixMM[0]||(o[0]=Rs(o[0],t.transformOut(t.transformIn(o[0],null)+i[0],null))),n.zoomFixMM[1]||(o[1]=zs(o[1],t.transformOut(t.transformIn(o[1],null)+i[1],null))),(o[0]a[1])&&t.setExtent2(1,o[0],o[1])}}}}function ik(e,t){var n=e.scale,r=e.model,i=tk(n,r,r.ecModel,e,null),a=DT(n),o=DT(t)?t.intervalStub:t,s=a?n.intervalStub:n,c=n.base,l=o.getTicks(),u=o.getTicks({expandToNicedExtent:!0}),d=l.length-1,f,p,m;if(d===1)f=p=0,m=1;else if(d===2){var h=Bs(l[0].value-l[1].value),g=Bs(l[1].value-l[2].value);f=p=0,h===g?m=2:(m=1,h=C[1])return!0})):b[1]?(T=C[1],A(function(){if(P(),k=ec(O-E*m,D),j(),w<=C[0])return!0})):A(function(){k=ec(Us(C[0]/E)*E,D),O=ec(Hs(C[1]/E)*E,D);var e=Vs((O-k)/E);if(e<=m){var t=m-e,n=void 0,r=i.incl0||a;if(r&&C[0]===0)n=[0,t];else if(r&&C[1]===0)n=[t,0];else{var o=Hs(t/2);n=t%2==0?[o,o]:w+T=C[1])return!0}})}NE(n,b,S,[w,T],x,{interval:E,intervalCount:m,intervalPrecision:D,niceExtent:[k,O]})}function ak(e,t){var n=DT(e),r=n?e.intervalStub:e,i=t.fixMinMax||[],a=n?e.getExtent():null,o=r.getExtent(),s=NT(o,i,t.rawExtentResult);r.setExtent(s[0],s[1]),s=r.getExtent();var c=n?sk(r,t):ok(r,t),l=c.intervalPrecision,u=c.interval,d=t.userInterval;d!=null&&(c.interval=d,c.intervalPrecision=AT(d)),i[0]||(s[0]=ec(Hs(s[0]/u)*u,l)),i[1]||(s[1]=ec(Us(s[1]/u)*u,l)),d!=null&&(c.niceExtent=s.slice()),NE(e,i,o,s,a,c)}function ok(e,t){var n=FT(t.splitNumber,5),r=pT(e),i=t.minInterval,a=t.maxInterval,o=pc(r/n,!0);i!=null&&oa&&(o=a);var s=AT(o),c=e.getExtent(),l=[ec(Us(c[0]/o)*o,s),ec(Hs(c[1]/o)*o,s)];return{interval:o,intervalPrecision:s,niceExtent:l}}function sk(e,t){var n=FT(t.splitNumber,10),r=e.getExtent(),i=pT(e),a=zs(dc(i),1);n/i*a<=.5&&(a*=10);var o=AT(a),s=[ec(Us(r[0]/a)*a,o),ec(Hs(r[1]/a)*a,o)];return{intervalPrecision:o,interval:a,niceExtent:s}}function ck(e){var t=e.scale,n=e.model,r=n.axis,i=n.ecModel;lk(t,n,r,i,null)}function lk(e,t,n,r,i){var a=tk(e,t,r,n,i),o=TT(e)||ET(e);uk(e,{splitNumber:t.get(`splitNumber`),fixMinMax:a.fixMM,userInterval:t.get(`interval`),minInterval:o?t.get(`minInterval`):null,maxInterval:o?t.get(`maxInterval`):null,rawExtentResult:a}),n&&r&&rk(n,e,a,r)}function uk(e,t){dk[e.type](e,t)}var dk={interval:ak,log:ak,time:QT,ordinal:As},fk=[[3,1],[0,2]],pk=function(){function e(e,t,n){this.type=`grid`,this._coordsMap={},this._coordsList=[],this._axesMap={},this._axesList=[],this.axisPointerEnabled=!0,this.dimensions=VE,this._initCartesian(e,t,n),this.model=e}return e.prototype.getRect=function(){return this._rect},e.prototype.update=function(e,t){var n=this._axesMap;G(this._axesList,function(e){YO(e,1);var t=e.scale;OT(t)&&t.setSortInfo(e.model.get(`categorySortInfo`))});function r(e){for(var t=es(e),n=[],r=t.length-1;r>=0;r--){var i=e[+t[r]];i.__alignTo?n.push(i):ck(i)}G(n,function(e){vk(e,e.__alignTo)?ck(e):ik(e,e.__alignTo.scale)})}r(n.x),r(n.y);var i={};G(n.x,function(e){hk(n,`y`,e,i)}),G(n.y,function(e){hk(n,`x`,e,i)}),this.resize(this.model,t)},e.prototype.resize=function(e,t,n){var r=Hx(e,t),i=this._rect=Bx(e.getBoxLayoutParams(),r.refContainer),a=this._axesMap,o=this._coordsList,s=e.get(`containLabel`);if(bk(a,i),!n){var c=wk(i,o,a,s,t),l=void 0;if(s)Sk?(Sk(this._axesList,i),bk(a,i)):l=Ck(i.clone(),`axisLabel`,null,i,a,c,r);else{var u=Ek(e,i,r),d=u.outerBoundsRect,f=u.parsedOuterBoundsContain,p=u.outerBoundsClamp;d&&(l=Ck(d,f,p,i,a,c,r))}Tk(i,a,KE.determine,null,l,r),G(this._coordsList,function(e){e.calcAffineTransform()})}},e.prototype.getAxis=function(e,t){var n=this._axesMap[e];if(n!=null)return n[t||0]},e.prototype.getAxes=function(){return this._axesList.slice()},e.prototype.getCartesian=function(e,t){if(e!=null&&t!=null){var n=`x`+e+`y`+t;return this._coordsMap[n]}os(e)&&(t=e.yAxisIndex,e=e.xAxisIndex);for(var r=0,i=this._coordsList;r=0;i--){var a=e[+t[i]];wT(a.scale)&&jE(a.model,a.type,!0)==null&&(a.model.get(`alignTicks`)&&a.model.get(`interval`)==null?r.push(a):n=a)}n||=r.pop(),n&&G(r,function(e){e.__alignTo=n})}function vk(e,t){return Nb(e.scale)||Nb(t.scale)||t.scale.getTicks().length<2}function yk(e,t){var n=e.getExtent(),r=n[0]+n[1];e.toGlobalCoord=e.dim===`x`?function(e){return e+t}:function(e){return r-e+t},e.toLocalCoord=e.dim===`x`?function(e){return e-t}:function(e){return r-e+t}}function bk(e,t){G(e.x,function(e){return xk(e,t.x,t.width)}),G(e.y,function(e){return xk(e,t.y,t.height)})}function xk(e,t,n){var r=[0,n],i=+!!e.inverse;e.setExtent(r[i],r[1-i]),yk(e,t)}var Sk;function Ck(e,t,n,r,i,a,o){Tk(r,i,KE.estimate,t,!1,o);var s=[0,0,0,0];l(0),l(1),u(r,0,NaN),u(r,1,NaN);var c=$o(s,function(e){return e>0})==null;return ay(r,s,!0,!0,n),bk(i,r),c;function l(e){G(i[jv[e]],function(t){if(AE(t.model)){var n=a.ensureRecord(t.model),r=n.labelInfoList;if(r)for(var i=0;i0&&!fs(t)&&t>1e-4&&(e/=t),e}}function wk(e,t,n,r,i){var a=new oO(Dk);return G(n,function(n){return G(n,function(n){if(AE(n.model)){var o=!r;n.axisBuilder=LO(e,t,n.model,i,a,o)}})}),a}function Tk(e,t,n,r,i,a){var o=n===KE.determine;G(t,function(t){return G(t,function(t){AE(t.model)&&(RO(t.axisBuilder,e,t.model),t.axisBuilder.build(o?{axisTickLabelDetermine:!0}:{axisTickLabelEstimate:!0},{noPxChange:i}))})});var s={x:0,y:0};c(0),c(1);function c(t){s[jv[1-t]]=e[Mv[t]]<=a.refContainer[Mv[t]]*.5?0:1-t==1?2:1}G(t,function(e,t){return G(e,function(e){AE(e.model)&&((r===`all`||o)&&e.axisBuilder.build({axisName:!0},{nameMarginLevel:s[t]}),o&&e.axisBuilder.build({axisLine:!0}))})})}function Ek(e,t,n){var r,i=e.get(`outerBoundsMode`,!0);i===`same`?r=t.clone():(i==null||i===`auto`)&&(r=Bx(e.get(`outerBounds`,!0)||LE,n.refContainer));var a=e.get(`outerBoundsContain`,!0),o=a==null||a===`auto`||qo([`all`,`axisLabel`],a)<0?`all`:a,s=[Qs(X(e.get(`outerBoundsClampWidth`,!0),RE[0]),t.width),Qs(X(e.get(`outerBoundsClampHeight`,!0),RE[1]),t.height)];return{outerBoundsRect:r,parsedOuterBoundsContain:o,outerBoundsClamp:s}}var Dk=function(e,t,n,r,i,a){var o=n.axis.dim===`x`?`y`:`x`;uO(e,t,n,r,i,a),kE(e.nameLocation)||G(t.recordMap[o],function(e){e&&e.labelInfoList&&e.dirVec&&fO(e.labelInfoList,e.dirVec,r,i)})},Ok=function(){function e(e,t){this.target=e,this.topTarget=t&&t.topTarget}return e}(),kk=function(){function e(e){this.handler=e,e.on(`mousedown`,this._dragStart,this),e.on(`mousemove`,this._drag,this),e.on(`mouseup`,this._dragEnd,this)}return e.prototype._dragStart=function(e){for(var t=e.target;t&&!t.draggable;)t=t.parent||t.__hostTarget;t&&(this._draggingTarget=t,t.dragging=!0,this._x=e.offsetX,this._y=e.offsetY,this.handler.dispatchToElement(new Ok(t,e),`dragstart`,e.event))},e.prototype._drag=function(e){var t=this._draggingTarget;if(t){var n=e.offsetX,r=e.offsetY,i=n-this._x,a=r-this._y;this._x=n,this._y=r,t.drift(i,a,e),this.handler.dispatchToElement(new Ok(t,e),`drag`,e.event);var o=this.handler.findHover(n,r,t).target,s=this._dropTarget;this._dropTarget=o,t!==o&&(s&&o!==s&&this.handler.dispatchToElement(new Ok(s,e),`dragleave`,e.event),o&&o!==s&&this.handler.dispatchToElement(new Ok(o,e),`dragenter`,e.event))}},e.prototype._dragEnd=function(e){var t=this._draggingTarget;t&&(t.dragging=!1),this.handler.dispatchToElement(new Ok(t,e),`dragend`,e.event),this._dropTarget&&this.handler.dispatchToElement(new Ok(this._dropTarget,e),`drop`,e.event),this._draggingTarget=null,this._dropTarget=null},e}(),Ak=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,jk=[],Mk=Ns.browser.firefox&&+Ns.browser.version.split(`.`)[0]<39;function Nk(e,t,n,r){return n||={},r?Pk(e,t,n):Mk&&t.layerX!=null&&t.layerX!==t.offsetX?(n.zrX=t.layerX,n.zrY=t.layerY):t.offsetX==null?Pk(e,t,n):(n.zrX=t.offsetX,n.zrY=t.offsetY),n}function Pk(e,t,n){if(Ns.domSupported&&e.getBoundingClientRect){var r=t.clientX,i=t.clientY;if(pb(e)){var a=e.getBoundingClientRect();n.zrX=r-a.left,n.zrY=i-a.top;return}if(ub(jk,e,r,i)){n.zrX=jk[0],n.zrY=jk[1];return}}n.zrX=n.zrY=0}function Fk(e){return e||window.event}function Ik(e,t,n){if(t=Fk(t),t.zrX!=null)return t;var r=t.type;if(r&&r.indexOf(`touch`)>=0){var i=r===`touchend`?t.changedTouches[0]:t.targetTouches[0];i&&Nk(e,i,t,n)}else{Nk(e,t,t,n);var a=Lk(t);t.zrDelta=a?a/120:-(t.detail||0)/3}var o=t.button;return t.which==null&&o!==void 0&&Ak.test(t.type)&&(t.which=o&1?1:o&2?3:o&4?2:0),t}function Lk(e){var t=e.wheelDelta;if(t)return t;var n=e.deltaX,r=e.deltaY;if(n==null||r==null)return t;var i=Math.abs(r===0?n:r),a=r>0?-1:r<0?1:n>0?-1:1;return 3*i*a}function Rk(e,t,n,r){e.addEventListener(t,n,r)}function zk(e,t,n,r){e.removeEventListener(t,n,r)}var Bk=function(e){e.preventDefault(),e.stopPropagation(),e.cancelBubble=!0};function Vk(e){return e.which===2||e.which===3}var Hk=function(){function e(){this._track=[]}return e.prototype.recognize=function(e,t,n){return this._doTrack(e,t,n),this._recognize(e)},e.prototype.clear=function(){return this._track.length=0,this},e.prototype._doTrack=function(e,t,n){var r=e.touches;if(r){for(var i={points:[],touches:[],target:t,event:e},a=0,o=r.length;a1&&r&&r.length>1){var a=Uk(r)/Uk(i);!isFinite(a)&&(a=1),t.pinchScale=a;var o=Wk(r);return t.pinchX=o[0],t.pinchY=o[1],{type:`pinch`,target:e[0].target,event:t}}}}},Kk=`silent`;function qk(e,t,n){return{type:e,event:n,target:t.target,topTarget:t.topTarget,cancelBubble:!1,offsetX:n.zrX,offsetY:n.zrY,gestureEvent:n.gestureEvent,pinchX:n.pinchX,pinchY:n.pinchY,pinchScale:n.pinchScale,wheelDelta:n.zrDelta,zrByTouch:n.zrByTouch,which:n.which,stop:Jk}}function Jk(){Bk(this.event)}var Yk=function(e){U(t,e);function t(){var t=e!==null&&e.apply(this,arguments)||this;return t.handler=null,t}return t.prototype.dispose=function(){},t.prototype.setCursor=function(){},t}(gp),Xk=function(){function e(e,t){this.x=e,this.y=t}return e}(),Zk=[`click`,`dblclick`,`mousewheel`,`mouseout`,`mouseup`,`mousedown`,`mousemove`,`contextmenu`],Qk=new Ru(0,0,0,0),$k=function(e){U(t,e);function t(t,n,r,i,a){var o=e.call(this)||this;return o._hovered=new Xk(0,0),o.storage=t,o.painter=n,o.painterRoot=i,o._pointerSize=a,r||=new Yk,o.proxy=null,o.setHandlerProxy(r),o._draggingMgr=new kk(o),o}return t.prototype.setHandlerProxy=function(e){this.proxy&&this.proxy.dispose(),e&&(G(Zk,function(t){e.on&&e.on(t,this[t],this)},this),e.handler=this),this.proxy=e},t.prototype.mousemove=function(e){var t=e.zrX,n=e.zrY,r=nA(this,t,n),i=this._hovered,a=i.target;a&&!a.__zr&&(i=this.findHover(i.x,i.y),a=i.target);var o=this._hovered=r?new Xk(t,n):this.findHover(t,n),s=o.target,c=this.proxy;c.setCursor&&c.setCursor(s?s.cursor:`default`),a&&s!==a&&this.dispatchToElement(i,`mouseout`,e),this.dispatchToElement(o,`mousemove`,e),s&&s!==a&&this.dispatchToElement(o,`mouseover`,e)},t.prototype.mouseout=function(e){var t=e.zrEventControl;t!==`only_globalout`&&this.dispatchToElement(this._hovered,`mouseout`,e),t!==`no_globalout`&&this.trigger(`globalout`,{type:`globalout`,event:e})},t.prototype.resize=function(){this._hovered=new Xk(0,0)},t.prototype.dispatch=function(e,t){var n=this[e];n&&n.call(this,t)},t.prototype.dispose=function(){this.proxy.dispose(),this.storage=null,this.proxy=null,this.painter=null},t.prototype.setCursorStyle=function(e){var t=this.proxy;t.setCursor&&t.setCursor(e)},t.prototype.dispatchToElement=function(e,t,n){e||={};var r=e.target;if(!(r&&r.silent)){for(var i=`on`+t,a=qk(t,e,n);r&&(r[i]&&(a.cancelBubble=!!r[i].call(r,a)),r.trigger(t,a),r=r.__hostTarget?r.__hostTarget:r.parent,!a.cancelBubble););a.cancelBubble||(this.trigger(t,a),this.painter&&this.painter.eachOtherLayer&&this.painter.eachOtherLayer(function(e){typeof e[i]==`function`&&e[i].call(e,a),e.trigger&&e.trigger(t,a)}))}},t.prototype.findHover=function(e,t,n){var r=this.storage.getDisplayList(),i=new Xk(e,t);if(tA(r,i,e,t,n),this._pointerSize&&!i.target){for(var a=[],o=this._pointerSize,s=o/2,c=new Ru(e-s,t-s,o,o),l=r.length-1;l>=0;l--){var u=r[l];u!==n&&!u.ignore&&!u.ignoreCoarsePointer&&(!u.parent||!u.parent.ignoreCoarsePointer)&&(Qk.copy(u.getBoundingRect()),u.transform&&Qk.applyTransform(u.transform),Qk.intersect(c)&&a.push(u))}if(a.length){for(var d=4,f=Math.PI/12,p=Math.PI*2,m=0;m4)return;this._downPoint=null}this.dispatchToElement(a,e,t)}});function eA(e,t,n){if(e[e.rectHover?`rectContain`:`contain`](t,n)){for(var r=e,i=void 0,a=!1;r;){if(r.ignoreClip&&(a=!0),!a){var o=r.getClipPath();if(o&&!o.contain(t,n))return!1}r.silent&&(i=!0);var s=r.__hostTarget;r=s?r.ignoreHostSilent?null:s:r.parent}return!i||Kk}return!1}function tA(e,t,n,r,i){for(var a=e.length-1;a>=0;a--){var o=e[a],s=void 0;if(o!==i&&!o.ignore&&(s=eA(o,n,r))&&(!t.topTarget&&(t.topTarget=o),s!==Kk)){t.target=o;break}}}function nA(e,t,n){var r=e.painter;return t<0||t>r.getWidth()||n<0||n>r.getHeight()}var rA=32,iA=7;function aA(e){for(var t=0;e>=rA;)t|=e&1,e>>=1;return e+t}function oA(e,t,n,r){var i=t+1;if(i===n)return 1;if(r(e[i++],e[t])<0){for(;i=0;)i++;return i-t}function sA(e,t,n){for(n--;t>>1,i(a,e[c])<0?s=c:o=c+1;var l=r-o;switch(l){case 3:e[o+3]=e[o+2];case 2:e[o+2]=e[o+1];case 1:e[o+1]=e[o];break;default:for(;l>0;)e[o+l]=e[o+l-1],l--}e[o]=a}}function lA(e,t,n,r,i,a){var o=0,s=0,c=1;if(a(e,t[n+i])>0){for(s=r-i;c0;)o=c,c=(c<<1)+1,c<=0&&(c=s);c>s&&(c=s),o+=i,c+=i}else{for(s=i+1;cs&&(c=s);var l=o;o=i-c,c=i-l}for(o++;o>>1);a(e,t[n+u])>0?o=u+1:c=u}return c}function uA(e,t,n,r,i,a){var o=0,s=0,c=1;if(a(e,t[n+i])<0){for(s=i+1;cs&&(c=s);var l=o;o=i-c,c=i-l}else{for(s=r-i;c=0;)o=c,c=(c<<1)+1,c<=0&&(c=s);c>s&&(c=s),o+=i,c+=i}for(o++;o>>1);a(e,t[n+u])<0?c=u:o=u+1}return c}function dA(e,t){var n=iA,r,i,a=0,o=[];r=[],i=[];function s(e,t){r[a]=e,i[a]=t,a+=1}function c(){for(;a>1;){var e=a-2;if(e>=1&&i[e-1]<=i[e]+i[e+1]||e>=2&&i[e-2]<=i[e]+i[e-1])i[e-1]i[e+1])break;u(e)}}function l(){for(;a>1;){var e=a-2;e>0&&i[e-1]=iA||m>=iA);if(h)break;f<0&&(f=0),f+=2}if(n=f,n<1&&(n=1),i===1){for(c=0;c=0;c--)e[p+c]=e[f+c];e[d]=o[u];return}for(var m=n;;){var h=0,g=0,_=!1;do if(t(o[u],e[l])<0){if(e[d--]=e[l--],h++,g=0,--i===0){_=!0;break}}else if(e[d--]=o[u--],g++,h=0,--s===1){_=!0;break}while((h|g)=0;c--)e[p+c]=e[f+c];if(i===0){_=!0;break}}if(e[d--]=o[u--],--s===1){_=!0;break}if(g=s-lA(e[l],o,0,s,s-1,t),g!==0){for(d-=g,u-=g,s-=g,p=d+1,f=u+1,c=0;c=iA||g>=iA);if(_)break;m<0&&(m=0),m+=2}if(n=m,n<1&&(n=1),s===1){for(d-=i,l-=i,p=d+1,f=l+1,c=i-1;c>=0;c--)e[p+c]=e[f+c];e[d]=o[u]}else if(s===0)throw Error();else for(f=d-(s-1),c=0;cs&&(c=s),cA(e,n,n+c,n+a,t),a=c}o.pushRun(n,a),o.mergeRuns(),i-=a,n+=a}while(i!==0);o.forceMergeRuns()}}var pA=!1;function mA(){pA||(pA=!0,console.warn(`z / z2 / zlevel of displayable is invalid, which may cause unexpected errors`))}function hA(e,t){return e.zlevel===t.zlevel?e.z===t.z?e.z2-t.z2:e.z-t.z:e.zlevel-t.zlevel}var gA=function(){function e(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=hA}return e.prototype.traverse=function(e,t){for(var n=0;n=0&&this._roots.splice(r,1)},e.prototype.delAllRoots=function(){this._roots=[],this._displayList=[],this._displayListLen=0},e.prototype.getRoots=function(){return this._roots},e.prototype.dispose=function(){this._displayList=null,this._roots=null},e}(),_A=Ns.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(e){return setTimeout(e,16)};function vA(){return new Date().getTime()}var yA=function(e){U(t,e);function t(t){var n=e.call(this)||this;return n._running=!1,n._time=0,n._pausedTime=0,n._pauseStart=0,n._paused=!1,t||={},n.stage=t.stage||{},n}return t.prototype.addClip=function(e){e.animation&&this.removeClip(e),this._head?(this._tail.next=e,e.prev=this._tail,e.next=null,this._tail=e):this._head=this._tail=e,e.animation=this},t.prototype.addAnimator=function(e){e.animation=this;var t=e.getClip();t&&this.addClip(t)},t.prototype.removeClip=function(e){if(e.animation){var t=e.prev,n=e.next;t?t.next=n:this._head=n,n?n.prev=t:this._tail=t,e.next=e.prev=e.animation=null}},t.prototype.removeAnimator=function(e){var t=e.getClip();t&&this.removeClip(t),e.animation=null},t.prototype.update=function(e){for(var t=vA()-this._pausedTime,n=t-this._time,r=this._head;r;){var i=r.next;r.step(t,n)?(r.ondestroy(),this.removeClip(r),r=i):r=i}this._time=t,e||(this.trigger(`frame`,n),this.stage.update&&this.stage.update())},t.prototype._startLoop=function(){var e=this;this._running=!0;function t(){e._running&&(_A(t),!e._paused&&e.update())}_A(t)},t.prototype.start=function(){this._running||(this._time=vA(),this._pausedTime=0,this._startLoop())},t.prototype.stop=function(){this._running=!1},t.prototype.pause=function(){this._paused||=(this._pauseStart=vA(),!0)},t.prototype.resume=function(){this._paused&&=(this._pausedTime+=vA()-this._pauseStart,!1)},t.prototype.clear=function(){for(var e=this._head;e;){var t=e.next;e.prev=e.next=e.animation=null,e=t}this._head=this._tail=null},t.prototype.isFinished=function(){return this._head==null},t.prototype.animate=function(e,t){t||={},this.start();var n=new hp(e,t.loop);return this.addAnimator(n),n},t}(gp),bA=300,xA=Ns.domSupported,SA=(function(){var e=[`click`,`dblclick`,`mousewheel`,`wheel`,`mouseout`,`mouseup`,`mousedown`,`mousemove`,`contextmenu`],t=[`touchstart`,`touchend`,`touchmove`],n={pointerdown:1,pointerup:1,pointermove:1,pointerout:1};return{mouse:e,touch:t,pointer:K(e,function(e){var t=e.replace(`mouse`,`pointer`);return n.hasOwnProperty(t)?t:e})}})(),CA={mouse:[`mousemove`,`mouseup`],pointer:[`pointermove`,`pointerup`]},wA=!1;function TA(e){var t=e.pointerType;return t===`pen`||t===`touch`}function EA(e){e.touching=!0,e.touchTimer!=null&&(clearTimeout(e.touchTimer),e.touchTimer=null),e.touchTimer=setTimeout(function(){e.touching=!1,e.touchTimer=null},700)}function DA(e){e&&(e.zrByTouch=!0)}function OA(e,t){return Ik(e.dom,new AA(e,t),!0)}function kA(e,t){for(var n=t,r=!1;n&&n.nodeType!==9&&!(r=n.domBelongToZr||n!==t&&n===e.painterRoot);)n=n.parentNode;return r}var AA=function(){function e(e,t){this.stopPropagation=As,this.stopImmediatePropagation=As,this.preventDefault=As,this.type=t.type,this.target=this.currentTarget=e.dom,this.pointerType=t.pointerType,this.clientX=t.clientX,this.clientY=t.clientY}return e}(),jA={mousedown:function(e){e=Ik(this.dom,e),this.__mayPointerCapture=[e.zrX,e.zrY],this.trigger(`mousedown`,e)},mousemove:function(e){e=Ik(this.dom,e);var t=this.__mayPointerCapture;t&&(e.zrX!==t[0]||e.zrY!==t[1])&&this.__togglePointerCapture(!0),this.trigger(`mousemove`,e)},mouseup:function(e){e=Ik(this.dom,e),this.__togglePointerCapture(!1),this.trigger(`mouseup`,e)},mouseout:function(e){e=Ik(this.dom,e);var t=e.toElement||e.relatedTarget;kA(this,t)||(this.__pointerCapturing&&(e.zrEventControl=`no_globalout`),this.trigger(`mouseout`,e))},wheel:function(e){wA=!0,e=Ik(this.dom,e),this.trigger(`mousewheel`,e)},mousewheel:function(e){wA||(e=Ik(this.dom,e),this.trigger(`mousewheel`,e))},touchstart:function(e){e=Ik(this.dom,e),DA(e),this.__lastTouchMoment=new Date,this.handler.processGesture(e,`start`),jA.mousemove.call(this,e),jA.mousedown.call(this,e)},touchmove:function(e){e=Ik(this.dom,e),DA(e),this.handler.processGesture(e,`change`),jA.mousemove.call(this,e)},touchend:function(e){e=Ik(this.dom,e),DA(e),this.handler.processGesture(e,`end`),jA.mouseup.call(this,e),+new Date-this.__lastTouchMoment0&&(this._stillFrameAccum++,this._stillFrameAccum>this._sleepAfterStill&&this.animation.stop())},e.prototype.setSleepAfterStill=function(e){this._sleepAfterStill=e},e.prototype.wakeUp=function(){this._disposed||(this.animation.start(),this._stillFrameAccum=0)},e.prototype.refreshHover=function(){this._needsRefreshHover=!0},e.prototype.refreshHoverImmediately=function(){this._disposed||this._refresh({animUpdate:!1,refresh:!1,refreshHover:!0})},e.prototype.resize=function(e){this._disposed||(e||={},this.painter.resize(e.width,e.height),this.handler.resize())},e.prototype.clearAnimation=function(){this._disposed||this.animation.clear()},e.prototype.getWidth=function(){if(!this._disposed)return this.painter.getWidth()},e.prototype.getHeight=function(){if(!this._disposed)return this.painter.getHeight()},e.prototype.setCursorStyle=function(e){this._disposed||this.handler.setCursorStyle(e)},e.prototype.findHover=function(e,t){if(!this._disposed)return this.handler.findHover(e,t)},e.prototype.on=function(e,t,n){return this._disposed||this.handler.on(e,t,n),this},e.prototype.off=function(e,t){this._disposed||this.handler.off(e,t)},e.prototype.trigger=function(e,t){this._disposed||this.handler.trigger(e,t)},e.prototype.clear=function(){if(!this._disposed){for(var e=this.storage.getRoots(),t=0;t=0;o--)r[o]&&!Kc(r[o])?a=!0:(r[o]=null,!a&&i--);r.length=i,e[n]=r}}),delete e[rj],e},t.prototype.setTheme=function(e){this._theme=new Zy(e),this._resetOption(`recreate`,null)},t.prototype.getTheme=function(){return this._theme},t.prototype.getLocaleModel=function(){return this._locale},t.prototype.setUpdatePayload=function(e){this._payload=e},t.prototype.getUpdatePayload=function(){return this._payload},t.prototype.getComponent=function(e,t){var n=this._componentsMap.get(e);if(n){var r=n[t||0];if(r)return r;if(t==null){for(var i=0;i=t:n===`max`?e<=t:e===t}function gj(e,t){return e.join(`,`)===t.join(`,`)}var _j=G,vj=os,yj=[`areaStyle`,`lineStyle`,`nodeStyle`,`linkStyle`,`chordStyle`,`label`,`labelLine`];function bj(e){var t=e&&e.itemStyle;if(t)for(var n=0,r=yj.length;n0?e[n-1].seriesModel:null)}),Uj(e))})}function Uj(e){G(e,function(t,n){var r=[],i=[NaN,NaN],a=[t.stackResultDimension,t.stackedOverDimension],o=t.data,s=t.isStackedByIndex,c=t.seriesModel.get(`stackStrategy`)||`samesign`;o.modify(a,function(a,l,u){var d=o.get(t.stackedDimension,u);if(isNaN(d))return i;var f,p;s?p=o.getRawIndex(u):f=o.get(t.stackedByDimension,u);for(var m=NaN,h=n-1;h>=0;h--){var g=e[h];if(s||(p=g.data.rawIndexOf(g.stackedByDimension,f)),p>=0){var _=g.data.getByRawIndex(g.stackResultDimension,p);if(c===`all`||c===`positive`&&_>0||c===`negative`&&_<0||c===`samesign`&&d>=0&&_>0||c===`samesign`&&d<=0&&_<0){d=ac(d,_),m=_;break}}}return r[0]=d,r[1]=m,r})})}var Wj=function(){function e(){this.group=new y_,this.uid=$y(`viewComponent`)}return e.prototype.init=function(e,t){},e.prototype.render=function(e,t,n,r){},e.prototype.dispose=function(e,t){},e.prototype.updateView=function(e,t,n,r){},e.prototype.updateLayout=function(e,t,n,r){},e.prototype.updateVisual=function(e,t,n,r){},e.prototype.toggleBlurSeries=function(e,t,n){},e.prototype.eachRendered=function(e){var t=this.group;t&&t.traverse(e)},e}();Nl(Wj),Bl(Wj);function Gj(){var e=Qc();return function(t){var n=e(t),r=t.pipelineContext,i=!!n.large,a=!!n.progressiveRender,o=n.large=!!(r&&r.large),s=n.progressiveRender=!!(r&&r.progressiveRender);return(i!==o||a!==s)&&`reset`}}var Kj=Qc(),qj=Gj(),Jj=function(){function e(){this.group=new y_,this.uid=$y(`viewChart`),this.renderTask=GS({plan:Zj,reset:Qj}),this.renderTask.context={view:this}}return e.prototype.init=function(e,t){},e.prototype.render=function(e,t,n,r){},e.prototype.highlight=function(e,t,n,r){var i=e.getData(r&&r.dataType);i&&Xj(i,r,`emphasis`)},e.prototype.downplay=function(e,t,n,r){var i=e.getData(r&&r.dataType);i&&Xj(i,r,`normal`)},e.prototype.remove=function(e,t){this.group.removeAll()},e.prototype.dispose=function(e,t){},e.prototype.updateView=function(e,t,n,r){this.render(e,t,n,r)},e.prototype.updateVisual=function(e,t,n,r){this.render(e,t,n,r)},e.prototype.eachRendered=function(e){uy(this.group,e)},e.markUpdateMethod=function(e,t){Kj(e).updateMethod=t},e.protoInitialize=function(){var t=e.prototype;t.type=`chart`}(),e}();function Yj(e,t,n){e&&Kg(e)&&(t===`emphasis`?xg:Sg)(e,n)}function Xj(e,t,n){var r=Zc(e,t),i=t&&t.highlightKey!=null?qg(t.highlightKey):null;r==null?e.eachItemGraphicEl(function(e){Yj(e,n,i)}):G(Ac(r),function(t){Yj(e.getItemGraphicEl(t),n,i)})}Nl(Jj,[`dispose`]),Bl(Jj);function Zj(e){return qj(e.model)}function Qj(e){var t=e.model,n=e.ecModel,r=e.api,i=e.payload,a=t.pipelineContext.progressiveRender,o=e.view,s=i&&Kj(i).updateMethod,c=a?`incrementalPrepareRender`:s&&o[s]?s:`render`;return c!==`render`&&o[c](t,n,r,i),$j[c]}var $j={incrementalPrepareRender:{progress:function(e,t){t.view.incrementalRender(e,t.model,t.ecModel,t.api,t.payload)}},render:{forceFirstProgress:!0,progress:function(e,t){t.view.render(t.model,t.ecModel,t.api,t.payload)}}},eM=`\0__throttleOriginMethod`,tM=`\0__throttleRate`,nM=`\0__throttleType`;function rM(e,t,n){var r,i=0,a=0,o=null,s,c,l,u;t||=0;function d(){a=new Date().getTime(),o=null,e.apply(c,l||[])}var f=function(){var e=[...arguments];r=new Date().getTime(),c=this,l=e;var f=u||t,p=u||n;u=null,s=r-(p?i:a)-f,clearTimeout(o),p?o=setTimeout(d,f):s>=0?d():o=setTimeout(d,-s),i=r};return f.clear=function(){o&&=(clearTimeout(o),null)},f.debounceNextCall=function(e){u=e},f}function iM(e,t,n,r){var i=e[t];if(i){var a=i[eM]||i,o=i[nM];if(i[tM]!==n||o!==r){if(n==null||!r)return e[t]=a;i=e[t]=rM(a,n,r===`debounce`),i[eM]=a,i[nM]=r,i[tM]=n}return i}}function aM(e,t){var n=e[t];n&&n[eM]&&(n.clear&&n.clear(),e[t]=n[eM])}var oM=Qc(),sM={itemStyle:Vl(Jy,!0),lineStyle:Vl(Gy,!0)},cM={lineStyle:`stroke`,itemStyle:`fill`};function lM(e,t){return e.visualStyleMapper||sM[t]||(console.warn(`Unknown style type '`+t+`'.`),sM.itemStyle)}function uM(e,t){return e.visualDrawType||cM[t]||(console.warn(`Unknown style type '`+t+`'.`),`fill`)}var dM={createOnAllSeries:!0,performRawSeries:!0,reset:function(e,t){var n=e.getData(),r=e.visualStyleAccessPath||`itemStyle`,i=e.getModel(r),a=lM(e,r)(i),o=i.getShallow(`decal`);o&&(n.setVisual(`decal`,o),o.dirty=!0);var s=uM(e,r),c=a[s],l=rs(c)?c:null,u=a.fill===`auto`||a.stroke===`auto`;if(!a[s]||l||u){var d=e.getColorFromPalette(e.name,null,t.getSeriesCount());a[s]||(a[s]=d,n.setVisual(`colorFromPalette`,!0)),a.fill=a.fill===`auto`||rs(a.fill)?d:a.fill,a.stroke=a.stroke===`auto`||rs(a.stroke)?d:a.stroke}if(n.setVisual(`style`,a),n.setVisual(`drawType`,s),!t.isSeriesFiltered(e)&&l)return n.setVisual(`colorFromPalette`,!1),{dataEach:function(t,n){var r=e.getDataParams(n),i=W({},a);i[s]=l(r),t.setItemVisual(n,`style`,i)}}}},fM=new Zy,pM={createOnAllSeries:!0,reset:function(e,t){if(!e.ignoreStyleOnData){var n=e.getData(),r=e.visualStyleAccessPath||`itemStyle`,i=lM(e,r),a=n.getVisual(`drawType`);return{dataEach:n.hasItemOption?function(e,t){var n=e.getRawDataItem(t);if(n&&n[r]){fM.option=n[r];var o=i(fM);W(e.ensureUniqueItemVisual(t,`style`),o),fM.option.decal&&(e.setItemVisual(t,`decal`,fM.option.decal),fM.option.decal.dirty=!0),a in o&&e.setItemVisual(t,`colorFromPalette`,!1)}}:null}}}},mM={performRawSeries:!0,overallReset:function(e){var t=Es();e.eachSeries(function(e){if(!e.isColorBySeries()){var n=e.type+`-`+e.getColorBy();oM(e).scope=t.get(n)||t.set(n,{})}}),e.eachSeries(function(e){if(!e.isColorBySeries()){var t=e.getRawData(),n={},r=e.getData(),i=oM(e).scope,a=uM(e,e.visualStyleAccessPath||`itemStyle`);r.each(function(e){var t=r.getRawIndex(e);n[t]=e}),t.each(function(o){var s=n[o];if(r.getItemVisual(s,`colorFromPalette`)){var c=r.ensureUniqueItemVisual(s,`style`),l=t.getName(o)||o+``,u=t.count();c[a]=e.getColorFromPalette(l,i,u)}})}})}},hM=Math.PI;function gM(e,t){t||={},Ko(t,{text:`loading`,textColor:Q.color.primary,fontSize:12,fontWeight:`normal`,fontStyle:`normal`,fontFamily:`sans-serif`,maskColor:`rgba(255,255,255,0.8)`,showSpinner:!0,color:Q.color.theme[0],spinnerRadius:10,lineWidth:5,zlevel:0});var n=new y_,r=new fh({style:{fill:t.maskColor},zlevel:t.zlevel,z:1e4});n.add(r);var i=new _h({style:{text:t.text,fill:t.textColor,fontSize:t.fontSize,fontWeight:t.fontWeight,fontStyle:t.fontStyle,fontFamily:t.fontFamily},zlevel:t.zlevel,z:10001}),a=new fh({style:{fill:`none`},textContent:i,textConfig:{position:`right`,distance:10},zlevel:t.zlevel,z:10001});n.add(a);var o;return t.showSpinner&&(o=new rv({shape:{startAngle:-hM/2,endAngle:-hM/2+.1,r:t.spinnerRadius},style:{stroke:t.color,lineCap:`round`,lineWidth:t.lineWidth},zlevel:t.zlevel,z:10001}),o.animateShape(!0).when(1e3,{endAngle:hM*3/2}).start(`circularInOut`),o.animateShape(!0).when(1e3,{startAngle:hM*3/2}).delay(300).start(`circularInOut`),n.add(o)),n.resize=function(){var n=i.getBoundingRect().width,s=t.showSpinner?t.spinnerRadius:0,c=(e.getWidth()-s*2-(t.showSpinner&&n?10:0)-n)/2-(t.showSpinner&&n?0:5+n/2)+(t.showSpinner?0:n/2)+(n?0:s),l=e.getHeight()/2;t.showSpinner&&o.setShape({cx:c,cy:l}),a.setShape({x:c-s,y:l-s,width:s*2,height:s*2}),r.setShape({x:0,y:0,width:e.getWidth(),height:e.getHeight()})},n.resize(),n}var _M=function(){function e(e,t,n,r){this._stageTaskMap=Es(),this.ecInstance=e,this.api=t,n=this._dataProcessorHandlers=n.slice(),r=this._visualHandlers=r.slice(),this._allHandlers=n.concat(r)}return e.prototype.restoreData=function(e,t){e.restoreData(t),this._stageTaskMap.each(function(e){var t=e.overallTask;t&&t.dirty()})},e.prototype.getPerformArgs=function(e,t){if(e.__pipeline){var n=this._pipelineMap.get(e.__pipeline.id),r=n.context,i=!t&&n.progressiveEnabled&&(!r||r.progressiveRender)&&e.__idxInPipeline>n.blockIndex?n.step:null,a=r&&r.modDataCount;return{step:i,modBy:a==null?null:Math.ceil(a/i),modDataCount:a}}},e.prototype.getPipeline=function(e){return this._pipelineMap.get(e)},e.prototype.updateStreamModes=function(e,t){var n=this._pipelineMap.get(e.uid);e.pipelineContext=n.context=e.__preparePipelineContext?e.__preparePipelineContext(t,n):Tl(e,t,n)},e.prototype.restorePipelines=function(e,t){var n=this,r=n._pipelineMap=Es();t.eachSeries(function(t){var i=e.painter.type===`canvas`&&t.getProgressive(),a=t.uid;r.set(a,{id:a,head:null,tail:null,threshold:t.getProgressiveThreshold(),progressiveEnabled:i&&!(t.preventIncremental&&t.preventIncremental()),blockIndex:-1,step:Math.round(i||700),count:0}),n._pipe(t,t.dataTask)})},e.prototype.prepareStageTasks=function(){var e=this._stageTaskMap,t=this.api.getModel(),n=this.api;G(this._allHandlers,function(r){var i=e.get(r.uid)||e.set(r.uid,{});_s(!(r.reset&&r.overallReset),``),r.reset&&this._createSeriesStageTask(r,i,t,n),r.overallReset&&this._createOverallStageTask(r,i,t,n)},this)},e.prototype.prepareView=function(e,t,n,r){var i=e.renderTask,a=i.context;a.model=t,a.ecModel=n,a.api=r,i.__block=!e.incrementalPrepareRender,this._pipe(t,i)},e.prototype.performDataProcessorTasks=function(e,t){this._performStageTasks(this._dataProcessorHandlers,e,t,{block:!0})},e.prototype.performVisualTasks=function(e,t,n){this._performStageTasks(this._visualHandlers,e,t,n)},e.prototype._performStageTasks=function(e,t,n,r){r||={};var i=!1,a=this;G(e,function(e,s){if(!(r.visualType&&r.visualType!==e.visualType)){var c=a._stageTaskMap.get(e.uid),l=c.seriesTaskMap,u=c.overallTask;if(u){var d,f=u.agentStubMap;f.each(function(e){o(r,e)&&(e.dirty(),d=!0)}),d&&u.dirty(),a.updatePayload(u,n);var p=a.getPerformArgs(u,r.block);f.each(function(e){e.perform(p)}),u.perform(p)&&(i=!0)}else l&&l.each(function(s,c){o(r,s)&&s.dirty();var l=a.getPerformArgs(s,r.block);l.skip=!e.performRawSeries&&t.isSeriesFiltered(s.context.model),a.updatePayload(s,n),s.perform(l)&&(i=!0)})}});function o(e,t){return e.setDirty&&(!e.dirtyMap||e.dirtyMap.get(t.__pipeline.id))}this.unfinished=i||this.unfinished},e.prototype.performSeriesTasks=function(e){var t;e.eachSeries(function(e){t=e.dataTask.perform()||t}),this.unfinished=t||this.unfinished},e.prototype.plan=function(){this._pipelineMap.each(function(e){var t=e.tail;do{if(t.__block){e.blockIndex=t.__idxInPipeline;break}t=t.getUpstream()}while(t)})},e.prototype.updatePayload=function(e,t){t!==`remain`&&(e.context.payload=t)},e.prototype._createSeriesStageTask=function(e,t,n,r){var i=this,a=t.seriesTaskMap,o=t.seriesTaskMap=Es(),s=e.seriesType,c=e.getTargetSeries;e.createOnAllSeries?n.eachRawSeries(l):s?n.eachRawSeriesByType(s,l):c&&c(n,r).each(l);function l(t){var s=t.uid,c=o.set(s,a&&a.get(s)||GS({plan:SM,reset:CM,count:EM}));c.context={model:t,ecModel:n,api:r,useClearVisual:e.isVisual&&!e.isLayout,plan:e.plan,reset:e.reset,scheduler:i},i._pipe(t,c)}},e.prototype._createOverallStageTask=function(e,t,n,r){var i=this,a=t.overallTask=t.overallTask||GS({reset:vM});a.context={ecModel:n,api:r,overallReset:e.overallReset,scheduler:i};var o=a.agentStubMap,s=a.agentStubMap=Es(),c=e.seriesType,l=e.getTargetSeries,u=e.dirtyOnOverallProgress,d=!1;_s(!e.createOnAllSeries,``),c?n.eachRawSeriesByType(c,f):l?l(n,r).each(f):G(n.getSeries(),f);function f(e){var t=e.uid,n=s.set(t,o&&o.get(t)||(d=!0,GS({reset:yM,onDirty:xM})));n.context={model:e,dirtyOnOverallProgress:u},n.agent=a,n.__block=u,i._pipe(e,n)}d&&a.dirty()},e.prototype._pipe=function(e,t){var n=e.uid,r=this._pipelineMap.get(n);!r.head&&(r.head=t),r.tail&&r.tail.pipe(t),r.tail=t,t.__idxInPipeline=r.count++,t.__pipeline=r},e.wrapStageHandler=function(e,t){return rs(e)&&(e={overallReset:e,seriesType:DM(e)}),e.uid=$y(`stageHandler`),t&&(e.visualType=t),e},e}();function vM(e){e.overallReset(e.ecModel,e.api,e.payload)}function yM(e){return e.dirtyOnOverallProgress&&bM}function bM(){this.agent.dirty(),this.getDownstream().dirty()}function xM(){this.agent&&this.agent.dirty()}function SM(e){return e.plan?e.plan(e.model,e.ecModel,e.api,e.payload):null}function CM(e){e.useClearVisual&&e.data.clearAllVisual();var t=e.resetDefines=Ac(e.reset(e.model,e.ecModel,e.api,e.payload));return t.length>1?K(t,function(e,t){return TM(t)}):wM}var wM=TM(0);function TM(e){return function(t,n){var r=n.data,i=n.resetDefines[e];if(i&&i.dataEach)for(var a=t.start;a0&&u===i.length-l.length){var d=i.slice(0,u);d!==`data`&&(t.mainType=d,t[l.toLowerCase()]=e,s=!0)}}o.hasOwnProperty(i)&&(n[i]=e,s=!0),s||(r[i]=e)})}return{cptQuery:t,dataQuery:n,otherQuery:r}},e.prototype.filter=function(e,t){var n=this.eventInfo;if(!n)return!0;var r=n.targetEl,i=n.packedEvent,a=n.model,o=n.view;if(!a||!o)return!0;var s=t.cptQuery,c=t.dataQuery;return l(s,a,`mainType`)&&l(s,a,`subType`)&&l(s,a,`index`,`componentIndex`)&&l(s,a,`name`)&&l(s,a,`id`)&&l(c,i,`name`)&&l(c,i,`dataIndex`)&&l(c,i,`dataType`)&&(!o.filterForExposedEvent||o.filterForExposedEvent(e,t.otherQuery,r,i));function l(e,t,n,r){return e[n]==null||t[r||n]===e[n]}},e.prototype.afterTrigger=function(){this.eventInfo=null},e}(),LM=[`symbol`,`symbolSize`,`symbolRotate`,`symbolOffset`],RM=LM.concat([`symbolKeepAspect`]),zM={createOnAllSeries:!0,performRawSeries:!0,reset:function(e,t){var n=e.getData();if(e.legendIcon&&n.setVisual(`legendIcon`,e.legendIcon),!e.hasSymbolVisual)return;for(var r={},i={},a=!1,o=0;o=0&&rN(c)?c:.5,e.createRadialGradient(o,s,0,o,s,c)}function oN(e,t,n){for(var r=t.type===`radial`?aN(e,t,n):iN(e,t,n),i=t.colorStops,a=0;a0)?null:e===`dashed`?[4*t,2*t]:e===`dotted`?[t]:as(e)?[e]:J(e)?e:null}function dN(e){var t=e.style,n=t.lineDash&&t.lineWidth>0&&uN(t.lineDash,t.lineWidth),r=t.lineDashOffset;if(n){var i=t.strokeNoScale&&e.getLineScale?e.getLineScale():1;i&&i!==1&&(n=K(n,function(e){return e/i}),r/=i)}return[n,r]}var fN=new Dm(!0);function pN(e){var t=e.stroke;return!(t==null||t===`none`||!(e.lineWidth>0))}function mN(e){return typeof e==`string`&&e!==`none`}function hN(e){var t=e.fill;return t!=null&&t!==`none`}function gN(e,t){if(t.fillOpacity!=null&&t.fillOpacity!==1){var n=e.globalAlpha;e.globalAlpha=t.fillOpacity*t.opacity,e.fill(),e.globalAlpha=n}else e.fill()}function _N(e,t){if(t.strokeOpacity!=null&&t.strokeOpacity!==1){var n=e.globalAlpha;e.globalAlpha=t.strokeOpacity*t.opacity,e.stroke(),e.globalAlpha=n}else e.stroke()}function vN(e,t,n){var r=Yl(t.image,t.__image,n);if(Zl(r)){var i=e.createPattern(r,t.repeat||`repeat`);if(typeof DOMMatrix==`function`&&i&&i.setTransform){var a=new DOMMatrix;a.translateSelf(t.x||0,t.y||0),a.rotateSelf(0,0,(t.rotation||0)*js),a.scaleSelf(t.scaleX||1,t.scaleY||1),i.setTransform(a)}return i}}function yN(e,t,n,r,i){var a,o=pN(n),s=hN(n),c=n.strokePercent,l=c<1,u=!t.path;(!t.silent||l)&&u&&t.createPathProxy();var d=t.path||fN,f=t.__dirty;if(!r){var p=n.fill,m=n.stroke,h=s&&!!p.colorStops,g=o&&!!m.colorStops,_=s&&!!p.image,v=o&&!!m.image,y=void 0,b=void 0,x=void 0,S=void 0,C=void 0;(h||g)&&(C=t.getBoundingRect()),h&&(y=f?oN(e,p,C):t.__canvasFillGradient,t.__canvasFillGradient=y),g&&(b=f?oN(e,m,C):t.__canvasStrokeGradient,t.__canvasStrokeGradient=b),_&&(x=f||!t.__canvasFillPattern?vN(e,p,t):t.__canvasFillPattern,t.__canvasFillPattern=x),v&&(S=f||!t.__canvasStrokePattern?vN(e,m,t):t.__canvasStrokePattern,t.__canvasStrokePattern=S),h?e.fillStyle=y:_&&(x?e.fillStyle=x:s=!1),g?e.strokeStyle=b:v&&(S?e.strokeStyle=S:o=!1)}var w=t.getGlobalScale();d.setScale(w[0],w[1],t.segmentIgnoreThreshold);var T,E;e.setLineDash&&n.lineDash&&(a=dN(t),T=a[0],E=a[1]);var D=!0;(u||f&4)&&(d.setDPR(e.dpr),l?d.setContext(null):(d.setContext(e),D=!1),d.reset(),t.buildPath(d,t.shape,r),d.toStatic(),t.pathUpdated()),D&&d.rebuildPath(e,l?c:1),T&&(e.setLineDash(T),e.lineDashOffset=E),r?(i.batchFill=s,i.batchStroke=o):n.strokeFirst?(o&&_N(e,n),s&&gN(e,n)):(s&&gN(e,n),o&&_N(e,n)),T&&e.setLineDash([])}function bN(e,t,n){var r=t.__image=Yl(n.image,t.__image,t,t.onload);if(r&&Zl(r)){var i=n.x||0,a=n.y||0,o=t.getWidth(),s=t.getHeight(),c=r.width/r.height;if(o==null&&s!=null?o=s*c:s==null&&o!=null?s=o/c:o==null&&s==null&&(o=r.width,s=r.height),n.sWidth&&n.sHeight){var l=n.sx||0,u=n.sy||0;e.drawImage(r,l,u,n.sWidth,n.sHeight,i,a,o,s)}else if(n.sx&&n.sy){var l=n.sx,u=n.sy,d=o-l,f=s-u;e.drawImage(r,l,u,d,f,i,a,o,s)}else e.drawImage(r,i,a,o,s)}}function xN(e,t,n){var r,i=n.text;if(i!=null&&(i+=``),i){e.font=n.font||`12px sans-serif`,e.textAlign=n.textAlign,e.textBaseline=n.textBaseline;var a=void 0,o=void 0;e.setLineDash&&n.lineDash&&(r=dN(t),a=r[0],o=r[1]),a&&(e.setLineDash(a),e.lineDashOffset=o),n.strokeFirst?(pN(n)&&e.strokeText(i,n.x,n.y),hN(n)&&e.fillText(i,n.x,n.y)):(hN(n)&&e.fillText(i,n.x,n.y),pN(n)&&e.strokeText(i,n.x,n.y)),a&&e.setLineDash([])}}var SN=[`shadowBlur`,`shadowOffsetX`,`shadowOffsetY`],CN=[[`lineCap`,`butt`],[`lineJoin`,`miter`],[`miterLimit`,10]];function wN(e,t,n,r,i){var a=!1;if(!r&&(n||={},t===n))return!1;if(r||t.opacity!==n.opacity){FN(e,i),a=!0;var o=Math.max(Math.min(t.opacity,1),0);e.globalAlpha=isNaN(o)?Vp.opacity:o}(r||t.blend!==n.blend)&&(a||=(FN(e,i),!0),e.globalCompositeOperation=t.blend||Vp.blend);for(var s=0;s0&&e.unfinished);e.unfinished||this._zr.flush()}}},t.prototype.getDom=function(){return this._dom},t.prototype.getId=function(){return this.id},t.prototype.getZr=function(){return this._zr},t.prototype.isSSR=function(){return this._ssr},t.prototype.setOption=function(e,t,n){if(!this[hP]){if(this._disposed){this.id;return}var r,i,a;if(os(t)&&(n=t.lazyUpdate,r=t.silent,i=t.replaceMerge,a=t.transition,t=t.notMerge),this[hP]=!0,qP(this),!this._model||t){var o=new fj(this._api),s=this._theme,c=this._model=new aj;c.scheduler=this._scheduler,c.ssr=this._ssr,c.init(null,null,null,s,this._locale,o)}this._model.setOption(e,{replaceMerge:i},tF);var l={seriesTransition:a,optionChanged:!0};if(n)this[_P]={silent:r,updateParams:l},this[hP]=!1,this.getZr().wakeUp();else{try{kP(this),MP.update.call(this,null,l)}catch(e){throw this[_P]=null,this[hP]=!1,e}this._ssr||this._zr.flush(),this[_P]=null,this[hP]=!1,IP.call(this,r),LP.call(this,r)}}},t.prototype.setTheme=function(e,t){if(!this[hP]){if(this._disposed){this.id;return}var n=this._model;if(n){var r=t&&t.silent,i=null;this[_P]&&(r??=this[_P].silent,i=this[_P].updateParams,this[_P]=null),this[hP]=!0,qP(this);try{this._updateTheme(e),n.setTheme(this._theme),kP(this),MP.update.call(this,{type:`setTheme`},i)}catch(e){throw this[hP]=!1,e}this[hP]=!1,IP.call(this,r),LP.call(this,r)}}},t.prototype._updateTheme=function(e){Y(e)&&(e=rF[e]),e&&(e=Ho(e),e&&Bj(e,!0),this._theme=e)},t.prototype.getModel=function(){return this._model},t.prototype.getOption=function(){return this._model&&this._model.getOption()},t.prototype.getWidth=function(){return this._zr.getWidth()},t.prototype.getHeight=function(){return this._zr.getHeight()},t.prototype.getDevicePixelRatio=function(){return this._zr.painter.dpr||Ns.hasGlobalWindow&&window.devicePixelRatio||1},t.prototype.getRenderedCanvas=function(e){return this.renderToCanvas(e)},t.prototype.renderToCanvas=function(e){return e||={},this._zr.painter.getRenderedCanvas({backgroundColor:e.backgroundColor||this._model.get(`backgroundColor`),pixelRatio:e.pixelRatio||this.getDevicePixelRatio()})},t.prototype.renderToSVGString=function(e){return e||={},this._zr.painter.renderToString({useViewBox:e.useViewBox})},t.prototype.getSvgDataURL=function(){var e=this._zr;return G(e.storage.getDisplayList(),function(e){e.stopAnimation(null,!0)}),e.painter.toDataURL()},t.prototype.getDataURL=function(e){if(this._disposed){this.id;return}e||={};var t=e.excludeComponents,n=this._model,r=[],i=this;G(t,function(e){n.eachComponent({mainType:e},function(e){var t=i._componentsMap[e.__viewId];t.group.ignore||(r.push(t),t.group.ignore=!0)})});var a=this._zr.painter.getType()===`svg`?this.getSvgDataURL():this.renderToCanvas(e).toDataURL(`image/`+(e&&e.type||`png`));return G(r,function(e){e.group.ignore=!1}),a},t.prototype.getConnectedDataURL=function(e){if(this._disposed){this.id;return}var t=e.type===`svg`,n=this.group,r=Math.min,i=Math.max,a=1/0;if(oF[n]){var o=a,s=a,c=-a,l=-a,u=[],d=e&&e.pixelRatio||this.getDevicePixelRatio();G(aF,function(a,d){if(a.group===n){var f=t?a.getZr().painter.getSvgDom().innerHTML:a.renderToCanvas(Ho(e)),p=a.getDom().getBoundingClientRect();o=r(p.left,o),s=r(p.top,s),c=i(p.right,c),l=i(p.bottom,l),u.push({dom:f,left:p.left,top:p.top})}}),o*=d,s*=d,c*=d,l*=d;var f=c-o,p=l-s,m=Eo.createCanvas(),h=WA(m,{renderer:t?`svg`:`canvas`});if(h.resize({width:f,height:p}),t){var g=``;return G(u,function(e){var t=e.left-o,n=e.top-s;g+=``+e.dom+``}),h.painter.getSvgRoot().innerHTML=g,e.connectedBackgroundColor&&h.painter.setBackgroundColor(e.connectedBackgroundColor),h.refreshImmediately(),h.painter.toDataURL()}return e.connectedBackgroundColor&&h.add(new fh({shape:{x:0,y:0,width:f,height:p},style:{fill:e.connectedBackgroundColor}})),G(u,function(e){var t=new ih({style:{x:e.left*d-o,y:e.top*d-s,image:e.dom}});h.add(t)}),h.refreshImmediately(),m.toDataURL(`image/`+(e&&e.type||`png`))}return this.getDataURL(e)},t.prototype.convertToPixel=function(e,t,n){return NP(this,`convertToPixel`,e,t,n)},t.prototype.convertToLayout=function(e,t,n){return NP(this,`convertToLayout`,e,t,n)},t.prototype.convertFromPixel=function(e,t,n){return NP(this,`convertFromPixel`,e,t,n)},t.prototype.containPixel=function(e,t){if(this._disposed){this.id;return}var n=this._model,r;return G(el(n,e),function(e,n){n.indexOf(`Models`)>=0&&G(e,function(e){var i=e.coordinateSystem;if(i&&i.containPoint)r||=!!i.containPoint(t);else if(n===`seriesModels`){var a=this._chartsMap[e.__viewId];a&&a.containPoint&&(r||=a.containPoint(t,e))}},this)},this),!!r},t.prototype.getVisual=function(e,t){var n=this._model,r=el(n,e,{defaultMainType:`series`}),i=r.seriesModel.getData(),a=r.hasOwnProperty(`dataIndexInside`)?r.dataIndexInside:r.hasOwnProperty(`dataIndex`)?i.indexOfRawIndex(r.dataIndex):null;return a==null?HM(i,t):VM(i,a,t)},t.prototype.getViewOfComponentModel=function(e){return this._componentsMap[e.__viewId]},t.prototype.getViewOfSeriesModel=function(e){return this._chartsMap[e.__viewId]},t.prototype._initEvents=function(){var e=this;G(XP,function(t){var n=function(n){var r=e.getModel(),i=n.target,a;if(t===`globalout`?a={}:i&&KM(i,function(e){var t=jh(e);if(t&&t.dataIndex!=null){var n=t.dataModel||r.getSeriesByIndex(t.seriesIndex);return a=n&&n.getDataParams(t.dataIndex,t.dataType,i)||{},!0}if(t.eventData)return a=W({},t.eventData),!0},!0),a){var o=a.componentType,s=a.componentIndex;(o===`markLine`||o===`markPoint`||o===`markArea`)&&(o=`series`,s=a.seriesIndex);var c=o&&s!=null&&r.getComponent(o,s),l=c&&e[c.mainType===`series`?`_chartsMap`:`_componentsMap`][c.__viewId];a.event=n,a.type=t,e._$eventProcessor.eventInfo={targetEl:i,packedEvent:a,model:c,view:l},e.trigger(t,a)}};n.zrEventfulCallAtLast=!0,e._zr.on(t,n,e)});var t=this._messageCenter;G($P,function(n,r){t.on(r,function(t){e.trigger(r,t)})}),GM(t,this,this._api)},t.prototype.isDisposed=function(){return this._disposed},t.prototype.clear=function(){if(this._disposed){this.id;return}this.setOption({series:[]},!0)},t.prototype.dispose=function(){if(this._disposed){this.id;return}this._disposed=!0,this.getDom()&&ol(this.getDom(),lF,``);var e=this,t=e._api,n=e._model;G(e._componentsViews,function(e){e.dispose(n,t)}),G(e._chartsViews,function(e){e.dispose(n,t)}),e._zr.dispose(),e._dom=e._model=e._chartsMap=e._componentsMap=e._chartsViews=e._componentsViews=e._scheduler=e._api=e._zr=e._throttledZrFlush=e._theme=e._coordSysMgr=e._messageCenter=null,delete aF[e.id]},t.prototype.resize=function(e){if(!this[hP]){if(this._disposed){this.id;return}this._zr.resize(e);var t=this._model;if(this._loadingFX&&this._loadingFX.resize(),t){var n=t.resetOption(`media`),r=e&&e.silent;this[_P]&&(r??=this[_P].silent,n=!0,this[_P]=null),this[hP]=!0,qP(this);try{n&&kP(this),MP.update.call(this,{type:`resize`,animation:W({duration:0},e&&e.animation)})}catch(e){throw this[hP]=!1,e}this[hP]=!1,IP.call(this,r),LP.call(this,r)}}},t.prototype.showLoading=function(e,t){if(this._disposed){this.id;return}if(os(e)&&(t=e,e=``),e||=`default`,this.hideLoading(),iF[e]){var n=iF[e](this._api,t),r=this._zr;this._loadingFX=n,r.add(n)}},t.prototype.hideLoading=function(){if(this._disposed){this.id;return}this._loadingFX&&this._zr.remove(this._loadingFX),this._loadingFX=null},t.prototype.makeActionFromEvent=function(e){var t=W({},e);return t.type=QP[e.type],t},t.prototype.dispatchAction=function(e,t){if(this._disposed){this.id;return}if(os(t)||(t={silent:!!t}),ZP[e.type]&&this._model){if(this[hP]){this._pendingActions.push(e);return}var n=t.silent;FP.call(this,e,n);var r=t.flush;r?this._zr.flush():r!==!1&&Ns.browser.weChat&&this._throttledZrFlush(),IP.call(this,n),LP.call(this,n)}},t.prototype.updateLabelLayout=function(){qM.trigger(`series:layoutlabels`,this._model,this._api,{updatedSeries:[]})},t.prototype.appendData=function(e){if(this._disposed){this.id;return}var t=e.seriesIndex;this.getModel().getSeriesByIndex(t).appendData(e),this._scheduler.unfinished=!0,this.getZr().wakeUp()},t.internalField=function(){kP=function(e){pD(e._model);var t=e._scheduler;t.restorePipelines(e._zr,e._model),t.prepareStageTasks(),AP(e,!0),AP(e,!1),t.plan()},AP=function(e,t){for(var n=e._model,r=e._scheduler,i=t?e._componentsViews:e._chartsViews,a=t?e._componentsMap:e._chartsMap,o=e._zr,s=e._api,c=0;cX(t.get(`hoverLayerThreshold`),XA.hoverLayerThreshold)&&!Ns.node&&!Ns.worker;(e._usingTHL||a)&&(t.eachSeries(function(t){if(!t.preventUsingHoverLayer){var n=e._chartsMap[t.__viewId];n.__alive&&n.eachRendered(function(e){var t=e.states.emphasis;t&&t.hoverLayer!==2&&(t.hoverLayer=+!!a)})}}),e._usingTHL=a)}}function a(e,t){var n=e.get(`blendMode`)||null;t.eachRendered(function(e){e.isGroup||(e.style.blend=n)})}function o(e,t){if(!e.preventAutoZ){var n=hy(e);t.eachRendered(function(e){return _y(e,n.z,n.zlevel),!0})}}function s(e,t){t.eachRendered(function(e){if(!wv(e)){var t=e.getTextContent(),n=e.getTextGuideLine();e.stateTransition&&=null,t&&t.stateTransition&&(t.stateTransition=null),n&&n.stateTransition&&(n.stateTransition=null),e.hasState()?(e.prevStates=e.currentStates,e.clearStates()):e.prevStates&&=null}})}function c(e,t){var n=e.getModel(`stateAnimation`),i=e.isAnimationEnabled(),a=n.get(`duration`),o=a>0?{duration:a,delay:n.get(`delay`),easing:n.get(`easing`)}:null;t.eachRendered(function(e){if(e.states&&e.states.emphasis){if(wv(e))return;if(e instanceof Qm&&Xg(e),e.__dirty){var t=e.prevStates;t&&e.useStates(t)}if(i){e.stateTransition=o;var n=e.getTextContent(),a=e.getTextGuideLine();n&&(n.stateTransition=o),a&&(a.stateTransition=o)}e.__dirty&&r(e)}})}UP=function(e){return new(function(t){U(n,t);function n(){return t!==null&&t.apply(this,arguments)||this}return n.prototype.getCoordinateSystems=function(){return e._coordSysMgr.getCoordinateSystems()},n.prototype.getComponentByElement=function(t){for(;t;){var n=t.__ecComponentInfo;if(n!=null)return e._model.getComponent(n.mainType,n.index);t=t.parent}},n.prototype.enterEmphasis=function(t,n){xg(t,n),GP(e)},n.prototype.leaveEmphasis=function(t,n){Sg(t,n),GP(e)},n.prototype.enterBlur=function(t){Cg(t),GP(e)},n.prototype.leaveBlur=function(t){wg(t),GP(e)},n.prototype.enterSelect=function(t){Tg(t),GP(e)},n.prototype.leaveSelect=function(t){Eg(t),GP(e)},n.prototype.getModel=function(){return e.getModel()},n.prototype.getViewOfComponentModel=function(t){return e.getViewOfComponentModel(t)},n.prototype.getViewOfSeriesModel=function(t){return e.getViewOfSeriesModel(t)},n.prototype.getECUpdateCycleVersion=function(){return e[gP]},n.prototype.usingTHL=function(){return e._usingTHL},n}(Hh))(e)},WP=function(e){function t(e,t){for(var n=0;n=0)){wF.push(n);var o=_M.wrapStageHandler(n,i);o.__prio=t,o.__raw=n,e.push(o)}}function EF(e,t){iF[e]=t}function DF(e,t,n){var r=XM(`registerMap`);r&&r(e,t,n)}var OF=oC;CF(oP,dM),CF(lP,pM),CF(lP,mM),CF(oP,zM),CF(lP,BM),CF(pP,YN),hF(Bj),gF($N,Vj),EF(`default`,gM),bF({type:Xh,event:Xh,update:Xh},As),bF({type:Zh,event:Zh,update:Zh},As),bF({type:Qh,event:tg,update:Qh,action:As,refineEvent:kF,publishNonRefinedEvent:!0}),bF({type:$h,event:tg,update:$h,action:As,refineEvent:kF,publishNonRefinedEvent:!0}),bF({type:eg,event:tg,update:eg,action:As,refineEvent:kF,publishNonRefinedEvent:!0});function kF(e,t,n,r){return{eventContent:{selected:Lg(n),isFromClick:t.isFromClick||!1}}}mF(`default`,{}),mF(`dark`,FM);var AF=[],jF={registerPreprocessor:hF,registerProcessor:gF,registerPostInit:_F,registerPostUpdate:vF,registerUpdateLifecycle:yF,registerAction:bF,registerCoordinateSystem:xF,registerLayout:SF,registerVisual:CF,registerTransform:OF,registerLoading:EF,registerMap:DF,registerImpl:YM,PRIORITY:mP,ComponentModel:Yx,ComponentView:Wj,SeriesModel:ZC,ChartView:Jj,registerComponentModel:function(e){Yx.registerClass(e)},registerComponentView:function(e){Wj.registerClass(e)},registerSeriesModel:function(e){ZC.registerClass(e)},registerChartView:function(e){Jj.registerClass(e)},registerCustomSeries:function(e,t){QM(e,t)},registerSubTypeDefaulter:function(e,t){Yx.registerSubTypeDefaulter(e,t)},registerPainter:function(e,t){GA(e,t)}};function MF(e){if(J(e)){G(e,function(e){MF(e)});return}qo(AF,e)>=0||(AF.push(e),rs(e)&&(e={install:e}),e.install(jF))}var NF=function(){function e(e,t){this._encode=e,this._schema=t}return e.prototype.get=function(){return{fullDimensions:this._getFullDimensionNames(),encode:this._encode}},e.prototype._getFullDimensionNames=function(){return this._cachedDimNames||=this._schema?this._schema.makeOutputDimensionNames():[],this._cachedDimNames},e}();function PF(e,t){var n={},r=n.encode={},i=Es(),a=[],o=[],s={};G(e.dimensions,function(t){var n=e.getDimensionInfo(t),c=n.coordDim;if(c){var l=n.coordDimIndex;FF(r,c)[l]=t,n.isExtraCoord||(i.set(c,1),LF(n.type)&&(a[0]=t),FF(s,c)[l]=e.getDimensionIndex(n.name)),n.defaultTooltip&&o.push(t)}Nh.each(function(e,t){var i=FF(r,t),a=n.otherDims[t];a!=null&&a!==!1&&(i[a]=n.name)})});var c=[],l={};i.each(function(e,t){var n=r[t];l[t]=n[0],c=c.concat(n)}),n.dataDimsOnCoord=c,n.dataDimIndicesOnCoord=K(c,function(t){return e.getDimensionInfo(t).storeDimIndex}),n.encodeFirstDimNotExtra=l;var u=r.label;u&&u.length&&(a=u.slice());var d=r.tooltip;return d&&d.length?o=d.slice():o.length||(o=a.slice()),r.defaultedLabel=a,r.defaultedTooltip=o,n.userOutput=new NF(s,t),n}function FF(e,t){return e.hasOwnProperty(t)||(e[t]=[]),e[t]}function IF(e){return e===`category`?`ordinal`:e===`time`?`time`:`float`}function LF(e){return e!==`ordinal`&&e!==`time`}var RF=function(){function e(e){this.otherDims={},e!=null&&W(this,e)}return e}(),zF=os,BF=K,VF=typeof Int32Array>`u`?Array:Int32Array,HF=`e\0\0`,UF=-1,WF=[`hasItemOption`,`_nameList`,`_idList`,`_invertedIndicesMap`,`_dimSummary`,`userOutput`,`_rawData`,`_dimValueGetter`,`_nameDimIdx`,`_idDimIdx`,`_nameRepeatCount`],GF=[`_approximateExtent`],KF,qF,JF,YF,XF,ZF,QF,$F=function(){function e(e,t){this.type=`list`,this._dimOmitted=!1,this._nameList=[],this._idList=[],this._visual={},this._layout={},this._itemVisuals=[],this._itemLayouts=[],this._graphicEls=[],this._approximateExtent={},this._calculationInfo={},this.hasItemOption=!1,this.TRANSFERABLE_METHODS=[`cloneShallow`,`downSample`,`minmaxDownSample`,`lttbDownSample`,`map`],this.CHANGABLE_METHODS=[`filterSelf`,`selectRange`],this.DOWNSAMPLE_METHODS=[`downSample`,`minmaxDownSample`,`lttbDownSample`];var n,r=!1;uE(e)?(n=e.dimensions,this._dimOmitted=e.isDimensionOmitted(),this._schema=e):(r=!0,n=e),n||=[`x`,`y`];for(var i={},a=[],o={},s=!1,c={},l=0;l=t)){var n=this._store.getProvider();this._updateOrdinalMeta();var r=this._nameList,i=this._idList;if(n.getSource().sourceFormat===`original`&&!n.pure)for(var a=[],o=e;o0},e.prototype.ensureUniqueItemVisual=function(e,t){var n=this._itemVisuals,r=n[e];r||=n[e]={};var i=r[t];return i??(i=this.getVisual(t),J(i)?i=i.slice():zF(i)&&(i=W({},i)),r[t]=i),i},e.prototype.setItemVisual=function(e,t,n){var r=this._itemVisuals[e]||{};this._itemVisuals[e]=r,zF(t)?W(r,t):r[t]=n},e.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},e.prototype.setLayout=function(e,t){zF(e)?W(this._layout,e):this._layout[e]=t},e.prototype.getLayout=function(e){return this._layout[e]},e.prototype.getItemLayout=function(e){return this._itemLayouts[e]},e.prototype.setItemLayout=function(e,t,n){this._itemLayouts[e]=n?W(this._itemLayouts[e]||{},t):t},e.prototype.clearItemLayouts=function(){this._itemLayouts.length=0},e.prototype.setItemGraphicEl=function(e,t){Mh(this.hostModel&&this.hostModel.seriesIndex,this.dataType,e,t),this._graphicEls[e]=t},e.prototype.getItemGraphicEl=function(e){return this._graphicEls[e]},e.prototype.eachItemGraphicEl=function(e,t){G(this._graphicEls,function(n,r){n&&e&&e.call(t,n,r)})},e.prototype.cloneShallow=function(t){return t||=new e(this._schema?this._schema:BF(this.dimensions,this._getDimInfo,this),this.hostModel),XF(t,this),t._store=this._store,t},e.prototype.wrapMethod=function(e,t){var n=this[e];rs(n)&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(e),this[e]=function(){var e=n.apply(this,arguments);return t.apply(this,[e].concat(hs(arguments)))})},e.internalField=function(){KF=function(e){var t=e._invertedIndicesMap;G(t,function(n,r){var i=e._dimInfos[r],a=i.ordinalMeta,o=e._store;if(a){n=t[r]=new VF(a.categories.length);for(var s=0;s1&&(s+=`__ec__`+l),r[t]=s}}}(),e}();function eI(e,t){pS(e)||(e=hS(e)),t||={};var n=t.coordDimensions||[],r=t.dimensionsDefine||e.dimensionsDefine||[],i=Es(),a=[],o=tI(e,n,r,t.dimensionsCount),s=t.canOmitUnusedDimensions&&pE(o),c=r===e.dimensionsDefine,l=c?fE(e):dE(r),u=t.encodeDefine;!u&&t.encodeDefaulter&&(u=t.encodeDefaulter(e,o));for(var d=Es(u),f=new fC(o),p=0;p0&&(e.name+=t-1)}),new lE({source:e,dimensions:a,fullDimensionCount:o,dimensionOmitted:s})}function tI(e,t,n,r){var i=Math.max(e.dimensionsDetectedCount||1,t.length,n.length,r||0);return G(t,function(e){var t;os(e)&&(t=e.dimsDef)&&(i=Math.max(i,t.length))}),i}function nI(e,t,n){if(n||t.hasKey(e)){for(var r=0;t.hasKey(e+r);)r++;e+=r}return t.set(e,!0),e}var rI=function(){function e(e){this.coordSysDims=[],this.axisMap=Es(),this.categoryAxisMap=Es(),this.coordSysName=e}return e}();function iI(e){var t=e.get(`coordinateSystem`),n=new rI(t),r=aI[t];if(r)return r(e,n,n.axisMap,n.categoryAxisMap),n}var aI={cartesian2d:function(e,t,n,r){var i=e.getReferringComponents(`xAxis`,nl).models[0],a=e.getReferringComponents(`yAxis`,nl).models[0];t.coordSysDims=[`x`,`y`],n.set(`x`,i),n.set(`y`,a),oI(i)&&(r.set(`x`,i),t.firstCategoryDimIndex=0),oI(a)&&(r.set(`y`,a),t.firstCategoryDimIndex??=1)},singleAxis:function(e,t,n,r){var i=e.getReferringComponents(`singleAxis`,nl).models[0];t.coordSysDims=[`single`],n.set(`single`,i),oI(i)&&(r.set(`single`,i),t.firstCategoryDimIndex=0)},polar:function(e,t,n,r){var i=e.getReferringComponents(`polar`,nl).models[0],a=i.findAxisModel(`radiusAxis`),o=i.findAxisModel(`angleAxis`);t.coordSysDims=[`radius`,`angle`],n.set(`radius`,a),n.set(`angle`,o),oI(a)&&(r.set(`radius`,a),t.firstCategoryDimIndex=0),oI(o)&&(r.set(`angle`,o),t.firstCategoryDimIndex??=1)},geo:function(e,t,n,r){t.coordSysDims=[`lng`,`lat`]},parallel:function(e,t,n,r){var i=e.ecModel,a=i.getComponent(`parallel`,e.get(`parallelIndex`)),o=t.coordSysDims=a.dimensions.slice();G(a.parallelAxisIndex,function(e,a){var s=i.getComponent(`parallelAxis`,e),c=o[a];n.set(c,s),oI(s)&&(r.set(c,s),t.firstCategoryDimIndex??=a)})},matrix:function(e,t,n,r){var i=e.getReferringComponents(`matrix`,nl).models[0];t.coordSysDims=[`x`,`y`];var a=i.getDimensionModel(`x`),o=i.getDimensionModel(`y`);n.set(`x`,a),n.set(`y`,o),r.set(`x`,a),r.set(`y`,o)}};function oI(e){return e.get(`type`)===`category`}function sI(e,t){var n=e.get(`coordinateSystem`),r=Ox.get(n),i;return t&&t.coordSysDims&&(i=K(t.coordSysDims,function(e){var n={name:e},r=t.axisMap.get(e);return r&&(n.type=IF(r.get(`type`))),n})),i||=r&&(r.getDimensionsInfo?r.getDimensionsInfo():r.dimensions.slice())||[`x`,`y`],i}function cI(e,t,n){var r,i;return n&&G(e,function(e,a){var o=e.coordDim,s=n.categoryAxisMap.get(o);s&&(r??=a,e.ordinalMeta=s.getOrdinalMeta(),t&&(e.createInvertedIndices=!0)),e.otherDims.itemName!=null&&(i=!0)}),!i&&r!=null&&(e[r].otherDims.itemName=0),r}function lI(e,t,n){n||={};var r=t.getSourceManager(),i,a=!1;e?(a=!0,i=hS(e)):(i=r.getSource(),a=i.sourceFormat===Ph);var o=iI(t),s=sI(t,o),c=n.useEncodeDefaulter,l=rs(c)?c:c?ns(sS,s,t):null,u={coordDimensions:s,generateCoord:n.generateCoord,encodeDefine:t.getEncode(),encodeDefaulter:l,canOmitUnusedDimensions:!a},d=eI(i,u),f=cI(d.dimensions,n.createInvertedIndices,o),p=a?null:r.getSharedDataStore(d),m=mE(t,{schema:d,store:p}),h=new $F(d,t);h.setCalculationInfo(m);var g=f!=null&&uI(i)?function(e,t,n,r){return r===f?n:this.defaultDimValueGetter(e,t,n,r)}:null;return h.hasItemOption=!1,h.initData(a?i:p,null,g),h}function uI(e){if(e.sourceFormat===`original`)return!J(Nc(dI(e.data||[])))}function dI(e){for(var t=0;tthis.getProgressiveThreshold()?this.id:``},t.type=`series.scatter`,t.dependencies=[`grid`,`polar`,`geo`,`singleAxis`,`calendar`,`matrix`],t.defaultOption={coordinateSystem:`cartesian2d`,z:2,legendHoverLink:!0,symbolSize:10,large:!1,largeThreshold:2e3,itemStyle:{opacity:.8},emphasis:{scale:!0},clip:!0,select:{itemStyle:{borderColor:Q.color.primary}},universalTransition:{divideShape:`clone`}},t}(ZC);function pI(e,t){var n=e.mapDimensionsAll(`defaultedLabel`),r=n.length;if(r===1){var i=VS(e,t,n[0]);return i==null?null:i+``}if(r){for(var a=[],o=0;o=0&&r.push(t[a])}return r.join(` `)}var hI=function(e){U(t,e);function t(t,n,r,i){var a=e.call(this)||this;return a.updateData(t,n,r,i),a}return t.prototype._createSymbol=function(e,t,n,r,i,a){this.removeAll();var o=QD(e,-1,-1,2,2,null,a);o.attr({z2:X(i,100),culling:!0,scaleX:r[0]/2,scaleY:r[1]/2}),o.drift=gI,this._symbolType=e,this.add(o)},t.prototype.stopSymbolAnimation=function(e){this.childAt(0).stopAnimation(null,e)},t.prototype.getSymbolType=function(){return this._symbolType},t.prototype.getSymbolPath=function(){return this.childAt(0)},t.prototype.highlight=function(){xg(this.childAt(0))},t.prototype.downplay=function(){Sg(this.childAt(0))},t.prototype.setZ=function(e,t){var n=this.childAt(0);n.zlevel=e,n.z=t},t.prototype.setDraggable=function(e,t){var n=this.childAt(0);n.draggable=e,n.cursor=!t&&e?`move`:n.cursor},t.prototype.updateData=function(e,n,r,i){this.silent=!1;var a=e.getItemVisual(n,`symbol`)||`circle`,o=e.hostModel,s=t.getSymbolSize(e,n),c=t.getSymbolZ2(e,n),l=a!==this._symbolType,u=i&&i.disableAnimation;if(l){var d=e.getItemVisual(n,`symbolKeepAspect`);this._createSymbol(a,e,n,s,c,d)}else{var f=this.childAt(0);f.silent=!1;var p={scaleX:s[0]/2,scaleY:s[1]/2};u?f.attr(p):Sv(f,p,o,n),Ov(f)}if(this._updateCommon(e,n,s,r,i),l){var f=this.childAt(0);if(!u){var p={scaleX:this._sizeX,scaleY:this._sizeY,style:{opacity:f.style.opacity}};f.scaleX=f.scaleY=0,f.style.opacity=0,Cv(f,p,o,n)}}u&&this.childAt(0).stopAnimation(`leave`)},t.prototype._updateCommon=function(e,t,n,r,i){var a=this.childAt(0),o=e.hostModel,s,c,l,u,d,f,p,m,h;if(r&&(s=r.emphasisItemStyle,c=r.blurItemStyle,l=r.selectItemStyle,u=r.focus,d=r.blurScope,p=r.labelStatesModels,m=r.hoverScale,h=r.cursorStyle,f=r.emphasisDisabled),!r||e.hasItemOption){var g=r&&r.itemModel?r.itemModel:e.getItemModel(t),_=g.getModel(`emphasis`);s=_.getModel(`itemStyle`).getItemStyle(),l=g.getModel([`select`,`itemStyle`]).getItemStyle(),c=g.getModel([`blur`,`itemStyle`]).getItemStyle(),u=_.get(`focus`),d=_.get(`blurScope`),f=_.get(`disabled`),p=Dy(g),m=_.getShallow(`scale`),h=g.getShallow(`cursor`)}var v=e.getItemVisual(t,`symbolRotate`);a.attr(`rotation`,(v||0)*Math.PI/180||0);var y=eO(e.getItemVisual(t,`symbolOffset`),n);y&&(a.x=y[0],a.y=y[1]),h&&a.attr(`cursor`,h);var b=e.getItemVisual(t,`style`),x=b.fill;if(a instanceof ih){var S=a.style;a.useStyle(W({image:S.image,x:S.x,y:S.y,width:S.width,height:S.height},b))}else a.__isEmptyBrush?a.useStyle(W({},b)):a.useStyle(b),a.style.decal=null,a.setColor(x,i&&i.symbolInnerColor),a.style.strokeNoScale=!0;var C=e.getItemVisual(t,`liftZ`),w=this._z2;C==null?w!=null&&(a.z2=w,this._z2=null):w??(this._z2=a.z2,a.z2+=C);var T=i&&i.useNameLabel;Ey(a,p,{labelFetcher:o,labelDataIndex:t,defaultText:E,inheritColor:x,defaultOpacity:b.opacity});function E(t){return T?e.getName(t):pI(e,t)}this._sizeX=n[0]/2,this._sizeY=n[1]/2;var D=a.ensureState(`emphasis`);D.style=s,a.ensureState(`select`).style=l,a.ensureState(`blur`).style=c;var O=m==null||m===!0?Math.max(1.1,3/this._sizeY):isFinite(m)&&m>0?+m:1;D.scaleX=this._sizeX*O,D.scaleY=this._sizeY*O,this.setSymbolScale(1),Bg(this,u,d,f)},t.prototype.setSymbolScale=function(e){this.scaleX=this.scaleY=e},t.prototype.fadeOut=function(e,t,n){var r=this.childAt(0),i=jh(this).dataIndex,a=n&&n.animation;if(this.silent=r.silent=!0,n&&n.fadeLabel){var o=r.getTextContent();o&&Tv(o,{style:{opacity:0}},t,{dataIndex:i,removeOpt:a,cb:function(){r.removeTextContent()}})}else r.removeTextContent();Tv(r,{style:{opacity:0},scaleX:0,scaleY:0},t,{dataIndex:i,cb:e,removeOpt:a})},t.getSymbolSize=function(e,t){return $D(e.getItemVisual(t,`symbolSize`))},t.getSymbolZ2=function(e,t){return e.getItemVisual(t,`z2`)},t}(y_);function gI(e,t){this.parent.drift(e,t)}function _I(e,t,n,r){return t&&!isNaN(t[0])&&!isNaN(t[1])&&!(r&&r.isIgnore&&r.isIgnore(n))&&!(r&&r.clipShape&&!r.clipShape.contain(t[0],t[1]))&&e.getItemVisual(n,`symbol`)!==`none`}function vI(e){return e!=null&&!os(e)&&(e={isIgnore:e}),e||{}}function yI(e){var t=e.hostModel,n=t.getModel(`emphasis`);return{emphasisItemStyle:n.getModel(`itemStyle`).getItemStyle(),blurItemStyle:t.getModel([`blur`,`itemStyle`]).getItemStyle(),selectItemStyle:t.getModel([`select`,`itemStyle`]).getItemStyle(),focus:n.get(`focus`),blurScope:n.get(`blurScope`),emphasisDisabled:n.get(`disabled`),hoverScale:n.get(`scale`),labelStatesModels:Dy(t),cursorStyle:t.get(`cursor`)}}function bI(e,t,n,r,i,a,o){var s=new e(t,n,r,i);return s.setPosition(a),t.setItemGraphicEl(n,s),o.add(s),s}var xI=function(){function e(e){this.group=new y_,this._SymbolCtor=e||hI}return e.prototype.updateData=function(e,t){this._progressiveEls=null,t=vI(t);var n=this.group,r=e.hostModel,i=this._data,a=this._SymbolCtor,o=t.disableAnimation,s=this._seriesScope=yI(e),c={disableAnimation:o},l=t.getSymbolPoint||function(t){return e.getItemLayout(t)};i||n.removeAll(),e.diff(i).add(function(r){var i=l(r);_I(e,i,r,t)&&bI(a,e,r,s,c,i,n)}).update(function(u,d){var f=i.getItemGraphicEl(d),p=l(u);if(!_I(e,p,u,t)){n.remove(f);return}var m=e.getItemVisual(u,`symbol`)||`circle`,h=f&&f.getSymbolType&&f.getSymbolType();if(!f||h&&h!==m)n.remove(f),f=new a(e,u,s,c),f.setPosition(p);else{f.updateData(e,u,s,c);var g={x:p[0],y:p[1]};o?f.attr(g):Sv(f,g,r)}n.add(f),e.setItemGraphicEl(u,f)}).remove(function(e){var t=i.getItemGraphicEl(e);t&&t.fadeOut(function(){n.remove(t)},r)}).execute(),this._getSymbolPoint=l,this._data=e},e.prototype.updateLayout=function(e){var t=this._data;if(t)for(var n=this,r=t.getStore(),i=0,a=r.count();i=0;s--){var c=s*2,l=r[c]-a/2,u=r[c+1]-o/2;if(e>=l&&t>=u&&e<=l+a&&t<=u+o)return s}return-1},t.prototype.contain=function(e,t){var n=this.transformCoordToLocal(e,t),r=this.getBoundingRect();return e=n[0],t=n[1],r.contain(e,t)?(this.hoverDataIdx=this.findDataIndex(e,t))>=0:(this.hoverDataIdx=-1,!1)},t.prototype.getBoundingRect=function(){var e=this._rect;if(!e){for(var t=this.shape,n=t.points,r=t.size,i=r[0],a=r[1],o=1/0,s=1/0,c=-1/0,l=-1/0,u=0;u=0&&(c.dataIndex=n+(e.startIndex||0))})},e.prototype.remove=function(){this._clear()},e.prototype._clear=function(){this._newAdded=[],this.group.removeAll()},e}(),EI=typeof Float32Array<`u`?Float32Array:void 0,DI=typeof Float64Array<`u`?Float64Array:void 0;function OI(e){return kI({ctor:EI},e).arr}function kI(e,t){var n=e.arr,r=e.ctor;if(t>oc&&(t=oc),!n||e.typed&&n.length=0||e===t}function ZI(e){var t=QI(e);if(t){var n=t.axisPointerModel,r=t.axis.scale,i=n.option,a=n.get(`status`),o=n.get(`value`);o!=null&&(o=r.parse(o));var s=eL(n);a??(i.status=s?`show`:`hide`);var c=r.getExtent();(o==null||o>c[1])&&(o=c[1]),o-1&&(s.style.stroke=s.style.fill,s.style.fill=Q.color.neutral00,s.style.lineWidth=2),t},t.type=`series.line`,t.dependencies=[`grid`,`polar`],t.defaultOption={z:3,coordinateSystem:`cartesian2d`,legendHoverLink:!0,clip:!0,label:{position:`top`},endLabel:{show:!1,valueAnimation:!0,distance:8},lineStyle:{width:2,type:`solid`},emphasis:{scale:!0},step:!1,smooth:!1,smoothMonotone:null,symbol:`emptyCircle`,symbolSize:6,symbolRotate:null,showSymbol:!0,showAllSymbol:`auto`,connectNulls:!1,sampling:`none`,animationEasing:`linear`,progressive:0,hoverLayerThreshold:1/0,universalTransition:{divideShape:`clone`},triggerLineEvent:!1,triggerEvent:!1},t}(ZC);function _L(e,t,n){var r=e.getBaseAxis(),i=e.getOtherAxis(r),a=vL(i,n),o=r.dim,s=i.dim,c=t.mapDimension(s),l=t.mapDimension(o),u=+(s===`x`||s===`radius`),d=K(e.dimensions,function(e){return t.mapDimension(e)}),f=!1,p=t.getCalculationInfo(`stackResultDimension`);return gE(t,d[0])&&(f=!0,d[0]=p),gE(t,d[1])&&(f=!0,d[1]=p),{dataDimsForPoint:d,valueStart:a,valueAxisDim:s,baseAxisDim:o,stacked:!!f,valueDim:c,baseDim:l,baseDataOffset:u,stackedOverDimension:t.getCalculationInfo(`stackedOverDimension`)}}function vL(e,t){var n=0,r=e.scale.getExtent();return t===`start`?n=r[0]:t===`end`?n=r[1]:as(t)&&!isNaN(t)?n=t:r[0]>0?n=r[0]:r[1]<0&&(n=r[1]),n}function yL(e,t,n,r){var i=NaN;e.stacked&&(i=n.get(n.getCalculationInfo(`stackedOverDimension`),r)),isNaN(i)&&(i=e.valueStart);var a=e.baseDataOffset,o=[];return o[a]=n.get(e.baseDim,r),o[1-a]=i,t.dataToPoint(o)}function bL(e,t){return!isFinite(e)||!isFinite(t)}function xL(e,t){var n=[];return t.diff(e).add(function(e){n.push({cmd:`+`,idx:e})}).update(function(e,t){n.push({cmd:`=`,idx:t,idx1:e})}).remove(function(e){n.push({cmd:`-`,idx:e})}).execute(),n}function SL(e,t,n,r,i,a,o,s){for(var c=xL(e,t),l=[],u=[],d=[],f=[],p=[],m=[],h=[],g=_L(i,t,o),_=e.getLayout(`points`)||[],v=t.getLayout(`points`)||[],y=0;y=i||h<0)break;if(bL(_,v)){if(c){h+=a;continue}break}if(h===n)e[a>0?`moveTo`:`lineTo`](_,v),d=_,f=v;else{var y=_-l,b=v-u;if(y*y+b*b<.5){h+=a;continue}if(o>0){for(var x=h+a,S=t[x*2],C=t[x*2+1];S===_&&C===v&&g=r||bL(S,C))p=_,m=v;else{E=S-l,D=C-u;var A=_-l,j=S-_,M=v-u,N=C-v,P=void 0,F=void 0;if(s===`x`){P=Math.abs(A),F=Math.abs(j);var I=E>0?1:-1;p=_-I*P*o,m=v,O=_+I*F*o,k=v}else if(s===`y`){P=Math.abs(M),F=Math.abs(N);var L=D>0?1:-1;p=_,m=v-L*P*o,O=_,k=v+L*F*o}else P=Math.sqrt(A*A+M*M),F=Math.sqrt(j*j+N*N),T=F/(F+P),p=_-E*o*(1-T),m=v-D*o*(1-T),O=_+E*o*T,k=v+D*o*T,O=CL(O,wL(S,_)),k=CL(k,wL(C,v)),O=wL(O,CL(S,_)),k=wL(k,CL(C,v)),E=O-_,D=k-v,p=_-E*P/F,m=v-D*P/F,p=CL(p,wL(l,_)),m=CL(m,wL(u,v)),p=wL(p,CL(l,_)),m=wL(m,CL(u,v)),E=_-p,D=v-m,O=_+E*F/P,k=v+D*F/P}e.bezierCurveTo(d,f,p,m,_,v),d=O,f=k}else e.lineTo(_,v)}l=_,u=v,h+=a}return g}var EL=function(){function e(){this.smooth=0,this.smoothConstraint=!0}return e}(),DL=function(e){U(t,e);function t(t){var n=e.call(this,t)||this;return n.type=`ec-polyline`,n}return t.prototype.getDefaultStyle=function(){return{stroke:Q.color.neutral99,fill:null}},t.prototype.getDefaultShape=function(){return new EL},t.prototype.buildPath=function(e,t){var n=t.points,r=0,i=n.length/2;if(t.connectNulls){for(;i>0&&bL(n[i*2-2],n[i*2-1]);i--);for(;r=0){var _=o?(d-a)*g+a:(u-i)*g+i;return o?[e,_]:[_,e]}i=u,a=d;break;case r.C:u=n[c++],d=n[c++],f=n[c++],p=n[c++],m=n[c++],h=n[c++];var v=o?af(i,u,f,m,e,s):af(a,d,p,h,e,s);if(v>0)for(var y=0;y=0){var _=o?nf(a,d,p,h,b):nf(i,u,f,m,b);return o?[e,_]:[_,e]}}i=m,a=h}}},t}(Qm),OL=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(EL),kL=function(e){U(t,e);function t(t){var n=e.call(this,t)||this;return n.type=`ec-polygon`,n}return t.prototype.getDefaultShape=function(){return new OL},t.prototype.buildPath=function(e,t){var n=t.points,r=t.stackedOnPoints,i=0,a=n.length/2,o=t.smoothMonotone;if(t.connectNulls){for(;a>0&&bL(n[a*2-2],n[a*2-1]);a--);for(;i=0,a=e.fill||Q.color.neutral99;IL(r,t);var o=r.textFill==null;return i?o&&(r.textFill=n.insideFill||Q.color.neutral00,!r.textStroke&&n.insideStroke&&(r.textStroke=n.insideStroke),!r.textStroke&&(r.textStroke=a),r.textStrokeWidth??=2):(o&&(r.textFill=e.fill||n.outsideFill||Q.color.neutral00),!r.textStroke&&n.outsideStroke&&(r.textStroke=n.outsideStroke)),r.text=t.text,r.rich=t.rich,G(t.rich,function(e){IL(e,e)}),r}function IL(e,t){t&&(Z(t,`fill`)&&(e.textFill=t.fill),Z(t,`stroke`)&&(e.textStroke=t.fill),Z(t,`lineWidth`)&&(e.textStrokeWidth=t.lineWidth),Z(t,`font`)&&(e.font=t.font),Z(t,`fontStyle`)&&(e.fontStyle=t.fontStyle),Z(t,`fontWeight`)&&(e.fontWeight=t.fontWeight),Z(t,`fontSize`)&&(e.fontSize=t.fontSize),Z(t,`fontFamily`)&&(e.fontFamily=t.fontFamily),Z(t,`align`)&&(e.textAlign=t.align),Z(t,`verticalAlign`)&&(e.textVerticalAlign=t.verticalAlign),Z(t,`lineHeight`)&&(e.textLineHeight=t.lineHeight),Z(t,`width`)&&(e.textWidth=t.width),Z(t,`height`)&&(e.textHeight=t.height),Z(t,`backgroundColor`)&&(e.textBackgroundColor=t.backgroundColor),Z(t,`padding`)&&(e.textPadding=t.padding),Z(t,`borderColor`)&&(e.textBorderColor=t.borderColor),Z(t,`borderWidth`)&&(e.textBorderWidth=t.borderWidth),Z(t,`borderRadius`)&&(e.textBorderRadius=t.borderRadius),Z(t,`shadowColor`)&&(e.textBoxShadowColor=t.shadowColor),Z(t,`shadowBlur`)&&(e.textBoxShadowBlur=t.shadowBlur),Z(t,`shadowOffsetX`)&&(e.textBoxShadowOffsetX=t.shadowOffsetX),Z(t,`shadowOffsetY`)&&(e.textBoxShadowOffsetY=t.shadowOffsetY),Z(t,`textShadowColor`)&&(e.textShadowColor=t.textShadowColor),Z(t,`textShadowBlur`)&&(e.textShadowBlur=t.textShadowBlur),Z(t,`textShadowOffsetX`)&&(e.textShadowOffsetX=t.textShadowOffsetX),Z(t,`textShadowOffsetY`)&&(e.textShadowOffsetY=t.textShadowOffsetY))}function LL(e,t){if(e.length===t.length){for(var n=0;nt){a?n.push(o(a,c,t)):i&&n.push(o(i,c,0),o(i,c,t));break}else i&&=(n.push(o(i,c,0)),null),n.push(c),a=c}return n}function WL(e,t,n){var r=e.getVisual(`visualMeta`);if(r&&r.length&&e.count()&&t.type===`cartesian2d`){for(var i,a,o=r.length-1;o>=0;o--){var s=e.getDimensionInfo(r[o].dimension);if(i=s&&s.coordDim,i===`x`||i===`y`){a=r[o];break}}if(a){var c=t.getAxis(i),l=K(a.stops,function(e){return{coord:c.toGlobalCoord(c.dataToCoord(e.value)),color:e.color}}),u=l.length,d=a.outerColors.slice();u&&l[0].coord>l[u-1].coord&&(l.reverse(),d.reverse());var f=UL(l,i===`x`?n.getWidth():n.getHeight()),p=f.length;if(!p&&u)return l[0].coord<0?d[1]?d[1]:l[u-1].color:d[0]?d[0]:l[0].color;var m=10,h=f[0].coord-m,g=f[p-1].coord+m,_=g-h;if(_<.001)return`transparent`;G(f,function(e){e.offset=(e.coord-h)/_}),f.push({offset:p?f[p-1].offset:.5,color:d[1]||`transparent`}),f.unshift({offset:p?f[0].offset:.5,color:d[0]||`transparent`});var v=new ov(0,0,0,0,f,!0);return v[i]=h,v[i+`2`]=g,v}}}function GL(e,t,n){var r=e.get(`showAllSymbol`),i=r===`auto`;if(!r||i){var a=n.getAxesByScale(`ordinal`)[0];if(a&&!(i&&KL(a,t))){var o=t.mapDimension(a.dim),s={};return G(a.getViewLabels(),function(e){e.tick.offInterval||(s[PE(a.scale,e.tick)]=1)}),function(e){return!s.hasOwnProperty(t.get(o,e))}}}}function KL(e,t){var n=e.getExtent(),r=Math.abs(n[1]-n[0])/e.scale.count();isNaN(r)&&(r=0);for(var i=t.count(),a=Math.max(1,Math.round(i/5)),o=0;or)return!1;return!0}function qL(e){for(var t=e.length/2;t>0&&bL(e[t*2-2],e[t*2-1]);t--);return t-1}function JL(e,t){return[e[t*2],e[t*2+1]]}function YL(e,t,n){for(var r=e.length/2,i=n===`x`?0:1,a,o,s=0,c=-1,l=0;l=t||a>=t&&o<=t){c=l;break}s=l,a=o}return{range:[s,c],t:(t-a)/(o-a)}}function XL(e){if(e.get([`endLabel`,`show`]))return!0;for(var t=0;t0&&e.get([`emphasis`,`lineStyle`,`width`])===`bolder`){var M=f.getState(`emphasis`).style;M.lineWidth=+f.style.lineWidth+1}jh(f).seriesIndex=e.seriesIndex,Bg(f,k,A,j);var N=BL(e.get(`smooth`)),P=e.get(`smoothMonotone`);if(f.setShape({smooth:N,smoothMonotone:P,connectNulls:x}),p){var F=a.getCalculationInfo(`stackedOnSeries`),I=0;p.useStyle(Ko(s.getAreaStyle(),{fill:E,opacity:.7,lineJoin:`bevel`,decal:a.getVisual(`style`).decal})),F&&(I=BL(F.get(`smooth`))),p.setShape({smooth:N,stackedOnSmooth:I,smoothMonotone:P,connectNulls:x}),Wg(p,e,`areaStyle`),jh(p).seriesIndex=e.seriesIndex,Bg(p,k,A,j)}var L=this._changePolyState;a.eachItemGraphicEl(function(e){e&&(e.onHoverStateChange=L)}),this._polyline.onHoverStateChange=L,this._data=a,this._coordSys=r,this._stackedOnPoints=y,this._points=c,this._step=w,this._valueOrigin=_;var ee=e.get(`triggerEvent`),R=e.get(`triggerLineEvent`),te=R===!0||ee===!0||ee===`line`,ne=R===!0||ee===!0||ee===`area`;this.packEventData(e,f,te),p&&this.packEventData(e,p,ne)},t.prototype.packEventData=function(e,t,n){jh(t).eventData=n?{componentType:`series`,componentSubType:`line`,componentIndex:e.componentIndex,seriesIndex:e.seriesIndex,seriesName:e.name,seriesType:`line`,selfType:t===this._polygon?`area`:`line`}:null},t.prototype.highlight=function(e,t,n,r){var i=e.getData(),a=Zc(i,r);if(this._changePolyState(`emphasis`),!(a instanceof Array)&&a!=null&&a>=0){var o=i.getLayout(`points`),s=i.getItemGraphicEl(a);if(!s){var c=o[a*2],l=o[a*2+1];if(bL(c,l)||this._clipShapeForSymbol&&!this._clipShapeForSymbol.contain(c,l))return;var u=e.get(`zlevel`)||0,d=e.get(`z`)||0;s=new hI(i,a),s.x=c,s.y=l,s.setZ(u,d);var f=s.getSymbolPath().getTextContent();f&&(f.zlevel=u,f.z=d,f.z2=this._polyline.z2+1),s.__temp=!0,i.setItemGraphicEl(a,s),s.stopSymbolAnimation(!0),this.group.add(s)}s.highlight()}else Jj.prototype.highlight.call(this,e,t,n,r)},t.prototype.downplay=function(e,t,n,r){var i=e.getData(),a=Zc(i,r);if(this._changePolyState(`normal`),a!=null&&a>=0){var o=i.getItemGraphicEl(a);o&&(o.__temp?(i.setItemGraphicEl(a,null),this.group.remove(o)):o.downplay())}else Jj.prototype.downplay.call(this,e,t,n,r)},t.prototype._changePolyState=function(e){var t=this._polygon;fg(this._polyline,e),t&&fg(t,e)},t.prototype._newPolyline=function(e){var t=this._polyline;return t&&this._lineGroup.remove(t),t=new DL({shape:{points:e},segmentIgnoreThreshold:2,z2:10}),this._lineGroup.add(t),this._polyline=t,t},t.prototype._newPolygon=function(e,t){var n=this._polygon;return n&&this._lineGroup.remove(n),n=new kL({shape:{points:e,stackedOnPoints:t},segmentIgnoreThreshold:2}),this._lineGroup.add(n),this._polygon=n,n},t.prototype._initSymbolLabelAnimation=function(e,t,n){var r,i,a=t.getBaseAxis(),o=a.inverse;t.type===`cartesian2d`?(r=a.isHorizontal(),i=!1):t.type===`polar`&&(r=a.dim===`angle`,i=!0);var s=e.hostModel,c=s.get(`animationDuration`);rs(c)&&(c=c(null));var l=s.get(`animationDelay`)||0,u=rs(l)?l(null):l;e.eachItemGraphicEl(function(e,a){var s=e;if(s){var d=[e.x,e.y],f=void 0,p=void 0,m=void 0;if(n){if(i){var h=n,g=t.pointToCoord(d);r?(f=h.startAngle,p=h.endAngle,m=-g[1]/180*Math.PI):(f=h.r0,p=h.r,m=g[0])}else{var _=n;r?(f=_.x,p=_.x+_.width,m=e.x):(f=_.y+_.height,p=_.y,m=e.y)}}var v=p===f?0:(m-f)/(p-f);o&&(v=1-v);var y=rs(l)?l(a):c*v+u,b=s.getSymbolPath(),x=b.getTextContent();s.attr({scaleX:0,scaleY:0}),s.animateTo({scaleX:1,scaleY:1},{duration:200,setToFinal:!0,delay:y}),x&&x.animateFrom({style:{opacity:0}},{duration:300,delay:y}),b.disableLabelAnimation=!0}})},t.prototype._initOrUpdateEndLabel=function(e,t,n){var r=e.getModel(`endLabel`);if(XL(e)){var i=e.getData(),a=this._polyline,o=i.getLayout(`points`);if(!o){a.removeTextContent(),this._endLabel=null;return}var s=this._endLabel;s||(s=this._endLabel=new _h({z2:200}),s.ignoreClip=!0,a.setTextContent(this._endLabel),a.disableLabelAnimation=!0);var c=qL(o);c>=0&&(Ey(a,Dy(e,`endLabel`),{inheritColor:n,labelFetcher:e,labelDataIndex:c,defaultText:function(e,t,n){return n==null?pI(i,e):mI(i,n)},enableTextSetter:!0},QL(r,t)),a.textConfig.position=null)}else this._endLabel&&=(this._polyline.removeTextContent(),null)},t.prototype._endLabelOnDuring=function(e,t,n,r,i,a,o){var s=this._endLabel,c=this._polyline;if(s){e<1&&r.originalX==null&&(r.originalX=s.x,r.originalY=s.y);var l=n.getLayout(`points`),u=n.hostModel,d=u.get(`connectNulls`),f=a.get(`precision`),p=a.get(`distance`)||0,m=o.getBaseAxis(),h=m.isHorizontal(),g=m.inverse,_=t.shape,v=g?h?_.x:_.y+_.height:h?_.x+_.width:_.y,y=(h?p:0)*(g?-1:1),b=(h?0:-p)*(g?-1:1),x=h?`x`:`y`,S=YL(l,v,x),C=S.range,w=C[1]-C[0],T=void 0;if(w>=1){if(w>1&&!d){var E=JL(l,C[0]);s.attr({x:E[0]+y,y:E[1]+b}),i&&(T=u.getRawValue(C[0]))}else{var E=c.getPointOn(v,x);E&&s.attr({x:E[0]+y,y:E[1]+b});var D=u.getRawValue(C[0]),O=u.getRawValue(C[1]);i&&(T=ll(n,f,D,O,S.t))}r.lastFrameIndex=C[0]}else{var k=e===1||r.lastFrameIndex>0?C[0]:0,E=JL(l,k);i&&(T=u.getRawValue(k)),s.attr({x:E[0]+y,y:E[1]+b})}if(i){var A=Ly(s);typeof A.setLabelText==`function`&&A.setLabelText(T)}}},t.prototype._doUpdateAnimation=function(e,t,n,r,i,a,o){var s=this._polyline,c=this._polygon,l=e.hostModel,u=SL(this._data,e,this._stackedOnPoints,t,this._coordSys,n,this._valueOrigin,a),d=u.current,f=u.stackedOnCurrent,p=u.next,m=u.stackedOnNext;if(i&&(f=HL(u.stackedOnCurrent,u.current,n,i,o),d=HL(u.current,null,n,i,o),m=HL(u.stackedOnNext,u.next,n,i,o),p=HL(u.next,null,n,i,o)),zL(d,p)>3e3||c&&zL(f,m)>3e3){s.stopAnimation(),s.setShape({points:p}),c&&(c.stopAnimation(),c.setShape({points:p,stackedOnPoints:m}));return}s.shape.__points=u.current,s.shape.points=d;var h={shape:{points:p}};u.current!==d&&(h.shape.__points=u.next),s.stopAnimation(),Sv(s,h,l),c&&(c.setShape({points:d,stackedOnPoints:f}),c.stopAnimation(),Sv(c,{shape:{stackedOnPoints:m}},l),s.shape.points!==c.shape.points&&(c.shape.points=s.shape.points));for(var g=[],_=u.status,v=0;v<_.length;v++)if(_[v].cmd===`=`){var y=e.getItemGraphicEl(_[v].idx1);y&&g.push({el:y,ptIdx:v})}s.animators&&s.animators.length&&s.animators[0].during(function(){c&&c.dirtyShape();for(var e=s.shape.__points,t=0;tt&&(t=e[n]);return isFinite(t)?t:NaN},min:function(e){for(var t=1/0,n=0;n10&&a.type===`cartesian2d`&&i){var s=a.getBaseAxis(),c=a.getOtherAxis(s),l=s.getExtent(),u=n.getDevicePixelRatio(),d=Math.abs(l[1]-l[0])*(u||1),f=Math.round(o/d);if(isFinite(f)&&f>1){i===`lttb`?e.setData(r.lttbDownSample(r.mapDimension(c.dim),1/f)):i===`minmax`&&e.setData(r.minmaxDownSample(r.mapDimension(c.dim),1/f));var p=void 0;Y(i)?p=eR[i]:rs(i)&&(p=i),p&&e.setData(r.downSample(r.mapDimension(c.dim),1/f,p,tR))}}}}}function rR(e){e.registerChartView($L),e.registerSeriesModel(gL),e.registerLayout(AI(`line`,!0)),e.registerVisual({seriesType:`line`,reset:function(e){var t=e.getData(),n=e.getModel(`lineStyle`).getLineStyle();n&&!n.stroke&&(n.stroke=t.getVisual(`style`).fill),t.setVisual(`legendLineStyle`,n)}}),e.registerProcessor(e.PRIORITY.PROCESSOR.STATISTIC,nR(`line`))}function iR(){jD(`liPosMinGap`,aR)}function aR(e,t,n){var r=Es(),i=n.serUids,a=n.liPosMinGap,o,s=t.axis,c=s.scale,l=c.needTransform(),u=c.getFilter?c.getFilter():null,d=ZS(u);function f(n){DD(e,t.sers,function(e){var t=e.getRawData(),r=t.getDimensionIndex(t.mapDimension(s.dim));r>=0&&n(r,e,t.getStore())})}var p=0;if(f(function(e,t,n){r.set(t.uid,1),(!i||!i.hasKey(t.uid))&&(o=!0),p+=n.count()}),(!i||i.keys().length!==r.keys().length)&&(o=!0),!o&&a!=null){t.liPosMinGap=a;return}kI(oR,p);var m=0;f(function(e,t,n){for(var r=0,i=n.count();r0&&v0?-2:-1,n.serUids=r}var oR=kI({ctor:DI},50);function sR(e){return function(t,n){var r=RD(t,{fromStat:{key:e}});if(bc(r.w2))return[-r.w2/2,r.w2/2]}}function cR(e,t){return e+`|&`+t}function lR(e){return iR(),{liPosMinGap:!OT(e.scale)}}function uR(e,t,n,r){FD(e,{key:t,seriesType:n,coordSysType:r,getMetrics:lR})}function dR(e){return e.scale.rawExtentInfo.makeRenderInfo().startValue}var fR=yl(),pR=`__ec_stack_`;function mR(e){return e.get(`stack`)||pR+e.seriesIndex}function hR(e){if(OT(e.axis.scale)){for(var t=RD(e.axis),n=[],r=0;ro&&(o=a),o!==u&&(t.width=o,n-=o+l*o,r--)}}),u=(n-c)/(r+(r-1)*l),u=zs(u,0);var d=0,f;G(o,function(e){var t=s[e];t.width||=u,f=t,d+=t.width*(1+l)}),f&&(d-=f.width*l);var p={},m=-d/2;return G(o,function(e){var n=s[e];p[e]=p[e]||{bandWidth:t,offset:m,width:n.width},m+=n.width*(1+l)}),p}function yR(e){return{seriesType:e,overallReset:function(t){var n=cR(e,zE);OD(t,n,function(t){var r=gR(t,e);ED(t,n,function(e){var t=r.columnMap[mR(e)];e.getData().setLayout({bandWidth:t.bandWidth,offset:t.offset,size:t.width})})})}}}function bR(e){return{seriesType:e,plan:Gj(),reset:function(e){if(FO(e)){var t=e.getData(),n=e.coordinateSystem,r=n.getBaseAxis(),i=n.getOtherAxis(r),a=t.getDimensionIndex(t.mapDimension(i.dim)),o=t.getDimensionIndex(t.mapDimension(r.dim)),s=e.get(`showBackground`,!0),c=t.mapDimension(i.dim),l=t.getCalculationInfo(`stackResultDimension`),u=gE(t,c)&&!!t.getCalculationInfo(`stackedOnSeries`),d=i.isHorizontal(),f=i.toGlobalCoord(i.dataToCoord(dR(i))),p=xR(e),m=e.get(`barMinHeight`)||0,h=l&&t.getDimensionIndex(l),g=t.getLayout(`size`),_=t.getLayout(`offset`);return{progress:function(e,t){for(var r=e.count,i=p&&OI(r*3),c=p&&s&&OI(r*3),l=p&&OI(r),v=n.master.getRect(),y=d?v.width:v.height,b,x=t.getStore(),S=0;(b=e.next())!=null;){var C=x.get(u?h:a,b),w=x.get(o,b),T=f,E=void 0;u&&(E=+C-x.get(a,b));var D=void 0,O=void 0,k=void 0,A=void 0;if(d){var j=n.dataToPoint([C,w]);u&&(T=n.dataToPoint([E,w])[0]),D=T,O=j[1]+_,k=j[0]-T,A=g,Bs(k)s){u=(p+l)/2;break}f===1&&(d=m-r[0].tickValue)}u??(l?l&&(u=r[r.length-1].coord):u=r[0].coord),a[n]=e.toGlobalCoord(u)}});else{var o=this.getData(),s=o.getLayout(`offset`),c=o.getLayout(`size`),l=+!r.getBaseAxis().isHorizontal();a[l]+=s+c/2}return a}return[NaN,NaN]},t.prototype.__requireStartValue=function(e){return this.getBaseAxis()!==e},t.type=`series.__base_bar__`,t.defaultOption={z:2,coordinateSystem:`cartesian2d`,legendHoverLink:!0,barMinHeight:0,barMinAngle:0,large:!1,largeThreshold:400,progressive:3e3,progressiveChunkMode:`mod`,defaultBarGap:`10%`},t}(ZC);ZC.registerClass(wR);var TR=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.getInitialData=function(){return lI(null,this,{useEncodeDefaulter:!0,createInvertedIndices:!!this.get(`realtimeSort`,!0)||null})},t.prototype.getProgressive=function(){return this.get(`large`)?this.get(`progressive`):!1},t.prototype.__preparePipelineContext=function(e,t){var n=Tl(this,e,t);return n.progressiveRender&&(n.large=!0),n},t.prototype.brushSelector=function(e,t,n){return n.rect(t.getItemLayout(e))},t.type=`series.bar`,t.dependencies=[`grid`,`polar`],t.defaultOption=nb(wR.defaultOption,{clip:!0,roundCap:!1,showBackground:!1,backgroundStyle:{color:`rgba(180, 180, 180, 0.2)`,borderColor:null,borderWidth:0,borderType:`solid`,borderRadius:0,shadowBlur:0,shadowColor:null,shadowOffsetX:0,shadowOffsetY:0,opacity:1},select:{itemStyle:{borderColor:Q.color.primary,borderWidth:2}},realtimeSort:!1}),t}(wR),ER=function(){function e(){this.cx=0,this.cy=0,this.r0=0,this.r=0,this.startAngle=0,this.endAngle=Math.PI*2,this.clockwise=!0}return e}(),DR=function(e){U(t,e);function t(t){var n=e.call(this,t)||this;return n.type=`sausage`,n}return t.prototype.getDefaultShape=function(){return new ER},t.prototype.buildPath=function(e,t){var n=t.cx,r=t.cy,i=Math.max(t.r0||0,0),a=Math.max(t.r,0),o=(a-i)*.5,s=i+o,c=t.startAngle,l=t.endAngle,u=t.clockwise,d=Math.PI*2,f=u?l-cMath.PI/2&&ua)return!0;a=l}return!1},t.prototype._isOrderDifferentInView=function(e,t){for(var n=t.scale,r=n.getExtent(),i=Math.max(0,r[0]),a=Math.min(r[1],n.getOrdinalMeta().categories.length-1);i<=a;++i)if(e.ordinalNumbers[i]!==n.getRawOrdinalNumber(i))return!0},t.prototype._updateSortWithinSameData=function(e,t,n,r){if(this._isOrderChangedWithinSameData(e,t,n)){var i=this._dataSort(e,n,t);this._isOrderDifferentInView(i,n)&&(this._removeOnRenderedListener(r),r.dispatchAction({type:`changeAxisOrder`,componentType:n.dim+`Axis`,axisId:n.index,sortInfo:i}))}},t.prototype._dispatchInitSort=function(e,t,n){var r=t.baseAxis,i=this._dataSort(e,r,function(n){return e.get(e.mapDimension(t.otherAxis.dim),n)});n.dispatchAction({type:`changeAxisOrder`,componentType:r.dim+`Axis`,isInitSort:!0,axisId:r.index,sortInfo:i})},t.prototype.remove=function(e,t){this._clear(this._model),this._removeOnRenderedListener(t)},t.prototype.dispose=function(e,t){this._removeOnRenderedListener(t)},t.prototype._removeOnRenderedListener=function(e){this._onRendered&&=(e.getZr().off(`rendered`,this._onRendered),null)},t.prototype._clear=function(e){var t=this.group,n=this._data;e&&e.isAnimationEnabled()&&n&&!this._isLargeDraw?(this._removeBackground(),this._backgroundEls=[],n.eachItemGraphicEl(function(t){Dv(t,e,jh(t).dataIndex)})):t.removeAll(),this._data=null,this._isFirstFrame=!0},t.prototype._removeBackground=function(){this.group.remove(this._backgroundGroup),this._backgroundGroup=null},t.type=`bar`,t}(Jj),IR={cartesian2d:function(e,t){var n=t.width<0?-1:1,r=t.height<0?-1:1;n<0&&(t.x+=t.width,t.width=-t.width),r<0&&(t.y+=t.height,t.height=-t.height);var i=e.x+e.width,a=e.y+e.height,o=NR(t.x,e.x),s=PR(t.x+t.width,i),c=NR(t.y,e.y),l=PR(t.y+t.height,a),u=si?s:o,t.y=d&&c>a?l:c,t.width=u?0:s-o,t.height=d?0:l-c,n<0&&(t.x+=t.width,t.width=-t.width),r<0&&(t.y+=t.height,t.height=-t.height),u||d},polar:function(e,t){var n=t.r0<=t.r?1:-1;if(n<0){var r=t.r;t.r=t.r0,t.r0=r}var i=PR(t.r,e.r),a=NR(t.r0,e.r0);t.r=i,t.r0=a;var o=i-a<0;if(n<0){var r=t.r;t.r=t.r0,t.r0=r}return o}},LR={cartesian2d:function(e,t,n,r,i,a,o,s,c){var l=new fh({shape:W({},r),z2:1});if(l.__dataIndex=n,l.name=`item`,a){var u=l.shape,d=i?`height`:`width`;u[d]=0}return l},polar:function(e,t,n,r,i,a,o,s,c){var l=!i&&c?DR:B_,u=new l({shape:r,z2:1});if(u.name=`item`,u.calculateTextPosition=OR(KR(i),{isRoundCap:l===DR}),a){var d=u.shape,f=i?`r`:`endAngle`,p={};d[f]=i?r.r0:r.startAngle,p[f]=r[f],(s?Sv:Cv)(u,{shape:p},a)}return u}};function RR(e,t){var n=e.get(`realtimeSort`,!0),r=t.getBaseAxis();if(n&&r.type===`category`&&t.type===`cartesian2d`)return{baseAxis:r,otherAxis:t.getOtherAxis(r)}}function zR(e,t,n,r,i,a,o,s){var c,l;a?(l={x:r.x,width:r.width},c={y:r.y,height:r.height}):(l={y:r.y,height:r.height},c={x:r.x,width:r.width}),s||(o?Sv:Cv)(n,{shape:c},t,i,null);var u=t?e.baseAxis.model:null;(o?Sv:Cv)(n,{shape:l},u,i)}function BR(e,t){for(var n=0;n0?1:-1,o=r.height>0?1:-1;return{x:r.x+a*i/2,y:r.y+o*i/2,width:r.width-a*i,height:r.height-o*i}},polar:function(e,t,n){var r=e.getItemLayout(t);return{cx:r.cx,cy:r.cy,r0:r.r0,r:r.r,startAngle:r.startAngle,endAngle:r.endAngle,clockwise:r.clockwise}}};function GR(e){return e.startAngle!=null&&e.endAngle!=null&&e.startAngle===e.endAngle}function KR(e){return function(e){var t=e?`Arc`:`Angle`;return function(e){switch(e){case`start`:case`insideStart`:case`end`:case`insideEnd`:return e+t;default:return e}}}(e)}function qR(e,t,n,r,i,a,o,s){var c=t.getItemVisual(n,`style`);if(!s){var l=r.get([`itemStyle`,`borderRadius`])||0;e.setShape(`r`,l)}else if(!a.get(`roundCap`)){var u=e.shape;W(u,MR(r.getModel(`itemStyle`),u,!0)),e.setShape(u)}e.useStyle(c);var d=r.getShallow(`cursor`);d&&e.attr(`cursor`,d);var f=s?o?i.r>=i.r0?`endArc`:`startArc`:i.endAngle>=i.startAngle?`endAngle`:`startAngle`:o?nz(i,a.coordinateSystem):rz(i,a.coordinateSystem),p=Dy(r);Ey(e,p,{labelFetcher:a,labelDataIndex:n,defaultText:pI(a.getData(),n),inheritColor:c.fill,defaultOpacity:c.opacity,defaultOutsidePosition:f});var m=e.getTextContent();if(s&&m){var h=r.get([`label`,`position`]);e.textConfig.inside=h===`middle`||null,kR(e,h===`outside`?f:h,KR(o),r.get([`label`,`rotate`]))}Ry(m,p,a.getRawValue(n),function(e){return mI(t,e)});var g=r.getModel([`emphasis`]);Bg(e,g.get(`focus`),g.get(`blurScope`),g.get(`disabled`)),Wg(e,r),GR(i)&&(e.style.fill=`none`,e.style.stroke=`none`,G(e.states,function(e){e.style&&(e.style.fill=e.style.stroke=`none`)}))}function JR(e,t){var n=e.get([`itemStyle`,`borderColor`]);if(!n||n===`none`)return 0;var r=e.get([`itemStyle`,`borderWidth`])||0,i=isNaN(t.width)?Number.MAX_VALUE:Math.abs(t.width),a=isNaN(t.height)?Number.MAX_VALUE:Math.abs(t.height);return Math.min(r,i,a)}var YR=function(){function e(){}return e}(),XR=function(e){U(t,e);function t(t){var n=e.call(this,t)||this;return n.type=`largeBar`,n}return t.prototype.getDefaultShape=function(){return new YR},t.prototype.buildPath=function(e,t){for(var n=t.points,r=this.baseDimIdx,i=1-this.baseDimIdx,a=[],o=[],s=this.barWidth,c=0;c=0?n:null},30,!1);function $R(e,t,n){for(var r=e.baseDimIdx,i=1-r,a=e.shape.points,o=e.largeDataIndices,s=[],c=[],l=e.barWidth,u=0,d=a.length/3;u=s[0]&&t<=s[0]+c[0]&&n>=s[1]&&n<=s[1]+c[1])return o[u]}return-1}function ez(e,t,n){if(AL(n,`cartesian2d`)){var r=t,i=n.getArea();return{x:e?r.x:i.x,y:e?i.y:r.y,width:e?r.width:i.width,height:e?i.height:r.height}}var i=n.getArea(),a=t;return{cx:i.cx,cy:i.cy,r0:e?i.r0:a.r0,r:e?i.r:a.r,startAngle:e?a.startAngle:0,endAngle:e?a.endAngle:Math.PI*2}}function tz(e,t,n){return new(e.type===`polar`?B_:fh)({shape:ez(t,n,e),silent:!0,z2:0})}function nz(e,t){return e.height===0?t.getOtherAxis(t.getBaseAxis()).inverse?`bottom`:`top`:e.height>0?`bottom`:`top`}function rz(e,t){return e.width===0?t.getOtherAxis(t.getBaseAxis()).inverse?`left`:`right`:e.width>=0?`right`:`left`}function iz(e){e.registerChartView(FR),e.registerSeriesModel(TR),e.registerLayout(e.PRIORITY.VISUAL.LAYOUT,yR(`bar`)),e.registerLayout(e.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT,bR(`bar`)),e.registerProcessor(e.PRIORITY.PROCESSOR.STATISTIC,nR(`bar`)),e.registerAction({type:`changeAxisOrder`,event:`changeAxisOrder`,update:`update`},function(e,t){var n=e.componentType||`series`;t.eachComponent({mainType:n,query:e},function(t){e.sortInfo&&t.axis.setCategorySortInfo(e.sortInfo)})}),CR(e)}var az=Qc();function oz(e,t,n){az(e)[t]=n}function sz(e,t,n){var r=az(e);r[t]===n&&(r[t]=null)}function cz(e,t){return!!az(e)[t]}bF({type:`takeGlobalCursor`,event:`globalCursorTaken`,update:`update`},As);var lz={axisPointer:1,tooltip:1,brush:1};function uz(e,t,n){var r=t.getComponentByElement(e.topTarget);if(!r||r===n||lz.hasOwnProperty(r.mainType))return!1;var i=r.coordinateSystem;if(!i||i.model===n)return!1;var a=hy(r),o=hy(n);return!((a.zlevel-o.zlevel||a.z-o.z)<=0)}var dz=function(e){U(t,e);function t(t){var n=e.call(this)||this;n._zr=t;var r=q(n._mousedownHandler,n),i=q(n._mousemoveHandler,n),a=q(n._mouseupHandler,n),o=q(n._mousewheelHandler,n),s=q(n._pinchHandler,n);return n.enable=function(e,n){var c=n.zInfo,l=hy(c.component),u=l.z,d=l.zlevel,f={component:c.component,z:u,zlevel:d,z2:X(c.z2,-1/0)},p=W({},n.triggerInfo);this._opt=Ko(W({},n),{zoomOnMouseWheel:!0,moveOnMouseMove:!0,moveOnMouseWheel:!1,preventDefaultMouseMove:!0,zInfoParsed:f,triggerInfo:p,cursorGrab:`grab`,cursorGrabbing:`grabbing`}),e??=!0,(!this._enabled||this._controlType!==e)&&(this.disable(),this._enabled=!0,(e===!0||e===`move`||e===`pan`)&&(hz(t,`mousedown`,r,f),hz(t,`mousemove`,i,f),hz(t,`mouseup`,a,f)),(e===!0||e===`scale`||e===`zoom`)&&(hz(t,`mousewheel`,o,f),hz(t,`pinch`,s,f)))},n.disable=function(){this._enabled&&(this._enabled=!1,gz(t,`mousedown`,r),gz(t,`mousemove`,i),gz(t,`mouseup`,a),gz(t,`mousewheel`,o),gz(t,`pinch`,s))},n}return t.prototype.isDragging=function(){return this._dragging},t.prototype.isPinching=function(){return this._pinching},t.prototype._checkPointer=function(e,t,n){var r=this._opt,i=r.zInfoParsed;if(uz(e,r.api,i.component))return!1;var a=r.triggerInfo,o=a.roamTrigger,s=!1;return o===`global`&&(s=!0),s||=a.isInSelf(e,t,n),s&&a.isInClip&&!a.isInClip(e,t,n)&&(s=!1),s},t.prototype._decideCursorStyle=function(e,t,n,r){var i=e.target;if(!i&&this._checkPointer(e,t,n))return this._opt.cursorGrab;if(r)return i&&i.cursor||`default`},t.prototype.dispose=function(){this.disable()},t.prototype._mousedownHandler=function(e){if(!(Vk(e)||fz(e))){for(var t=e.target;t;){if(t.draggable)return;t=t.__hostTarget||t.parent}var n=e.offsetX,r=e.offsetY;this._checkPointer(e,n,r)&&(this._x=n,this._y=r,this._dragging=!0)}},t.prototype._mousemoveHandler=function(e){var t=this._zr;if(!(e.gestureEvent===`pinch`||cz(t,`globalPan`)||fz(e))){var n=e.offsetX,r=e.offsetY;if(!this._dragging||!bz(`moveOnMouseMove`,e,this._opt)){var i=this._decideCursorStyle(e,n,r,!1);i&&t.setCursorStyle(i);return}t.setCursorStyle(this._opt.cursorGrabbing);var a=this._x,o=this._y,s=n-a,c=r-o;this._x=n,this._y=r,this._opt.preventDefaultMouseMove&&Bk(e.event),e.__ecRoamConsumed=!0,yz(this,`pan`,`moveOnMouseMove`,e,{dx:s,dy:c,oldX:a,oldY:o,newX:n,newY:r,isAvailableBehavior:null})}},t.prototype._mouseupHandler=function(e){if(!fz(e)){var t=this._zr;if(!Vk(e)){this._dragging=!1;var n=this._decideCursorStyle(e,e.offsetX,e.offsetY,!0);n&&t.setCursorStyle(n)}}},t.prototype._mousewheelHandler=function(e){if(!fz(e)){var t=bz(`zoomOnMouseWheel`,e,this._opt),n=bz(`moveOnMouseWheel`,e,this._opt),r=e.wheelDelta,i=Math.abs(r),a=e.offsetX,o=e.offsetY;if(r!==0&&(t||n)){if(t){var s=i>3?1.4:i>1?1.2:1.1,c=r>0?s:1/s;this._checkTriggerMoveZoom(this,`zoom`,`zoomOnMouseWheel`,e,{scale:c,originX:a,originY:o,isAvailableBehavior:null})}if(n){var l=Math.abs(r),u=(r>0?1:-1)*(l>3?.4:l>1?.15:.05);this._checkTriggerMoveZoom(this,`scrollMove`,`moveOnMouseWheel`,e,{scrollDelta:u,originX:a,originY:o,isAvailableBehavior:null})}}}},t.prototype._pinchHandler=function(e){if(!(cz(this._zr,`globalPan`)||fz(e))){var t=e.pinchScale>1?1.1:1/1.1;this._checkTriggerMoveZoom(this,`zoom`,null,e,{scale:t,originX:e.pinchX,originY:e.pinchY,isAvailableBehavior:null})}},t.prototype._checkTriggerMoveZoom=function(e,t,n,r,i){e._checkPointer(r,i.originX,i.originY)&&(Bk(r.event),r.__ecRoamConsumed=!0,yz(e,t,n,r,i))},t}(gp);function fz(e){return e.__ecRoamConsumed}var pz=Qc();function mz(e){var t=pz(e);return t.roam=t.roam||{},t.uniform=t.uniform||{},t}function hz(e,t,n,r){for(var i=mz(e).roam,a=i[t]=i[t]||[],o=0;o=0;a--)r[a]??(delete n[t[a]],t.pop())}function Rz(e,t){var n=e.visual,r=[];os(n)?Mz(n,function(e){r.push(e)}):n!=null&&r.push(n),!t&&r.length===1&&!{color:1,symbol:1}.hasOwnProperty(e.type)&&(r[1]=r[0]),Kz(e,r)}function zz(e){return{applyVisual:function(t,n,r){var i=this.mapValueToVisual(t);r(`color`,e(n(`color`),i))},_normalizedToVisual:Wz([0,1])}}function Bz(e){var t=this.option.visual;return t[Math.round(Ys(e,[0,1],[0,t.length-1],!0))]||{}}function Vz(e){return function(t,n,r){r(e,this.mapValueToVisual(t))}}function Hz(e){var t=this.option.visual;return t[this.option.loop&&e!==Pz?e%t.length:e]}function Uz(){return this.option.visual[0]}function Wz(e){return{linear:function(t){return Ys(t,e,this.option.visual,!0)},category:Hz,piecewise:function(t,n){var r=Gz.call(this,n);return r??=Ys(t,e,this.option.visual,!0),r},fixed:Uz}}function Gz(e){var t=this.option,n=t.pieceList;if(t.hasSpecialVisual){var r=n[Fz.findPieceIndex(e,n)];if(r&&r.visual)return r.visual[this.type]}}function Kz(e,t){return e.visual=t,e.type===`color`&&(e.parsedVisual=K(t,function(e){return Nf(e)||[0,0,0,1]})),t}var qz={linear:function(e){return Ys(e,this.option.dataExtent,[0,1],!0)},piecewise:function(e){var t=this.option.pieceList,n=Fz.findPieceIndex(e,t,!0);if(n!=null)return Ys(n,[0,t.length-1],[0,1],!0)},category:function(e){return(this.option.categories?this.option.categoryMap[e]:e)??Pz},fixed:As};function Jz(e,t,n){return e?t<=n:t0&&(y[0]=-y[0],y[1]=-y[1]);var x=v[0]<0?-1:1;if(r.__position!==`start`&&r.__position!==`end`){var S=-Math.atan2(v[1],v[0]);l[0].8?`left`:u[0]<-.8?`right`:`center`,p=u[1]>.8?`top`:u[1]<-.8?`bottom`:`middle`;break;case`start`:r.x=-u[0]*h+c[0],r.y=-u[1]*g+c[1],f=u[0]>.8?`right`:u[0]<-.8?`left`:`center`,p=u[1]>.8?`bottom`:u[1]<-.8?`top`:`middle`;break;case`insideStartTop`:case`insideStart`:case`insideStartBottom`:r.x=h*x+c[0],r.y=c[1]+C,f=v[0]<0?`right`:`left`,r.originX=-h*x,r.originY=-C;break;case`insideMiddleTop`:case`insideMiddle`:case`insideMiddleBottom`:case`middle`:r.x=b[0],r.y=b[1]+C,f=`center`,r.originY=-C;break;case`insideEndTop`:case`insideEnd`:case`insideEndBottom`:r.x=-h*x+l[0],r.y=l[1]+C,f=v[0]>=0?`right`:`left`,r.originX=h*x,r.originY=-C}r.scaleX=r.scaleY=i,r.setStyle({verticalAlign:r.__verticalAlign||p,align:r.__align||f})}},t}(y_),sB=function(){function e(e){this.group=new y_,this._LineCtor=e||oB}return e.prototype.updateData=function(e){var t=this;this._progressiveEls=null;var n=this,r=n.group,i=n._lineData;n._lineData=e,i||r.removeAll();var a=lB(e);e.diff(i).add(function(n){t._doAdd(e,n,a)}).update(function(n,r){t._doUpdate(i,e,r,n,a)}).remove(function(e){r.remove(i.getItemGraphicEl(e))}).execute()},e.prototype.updateLayout=function(){var e=this._lineData;e&&e.eachItemGraphicEl(function(t,n){t.updateLayout(e,n)},this)},e.prototype.incrementalPrepareUpdate=function(e){this._seriesScope=lB(e),this._lineData=null,this.group.removeAll()},e.prototype.incrementalUpdate=function(e,t,n){this._progressiveEls=[];function r(e){!e.isGroup&&!cB(e)&&(e.incremental=n,e.ensureState(`emphasis`).hoverLayer=2)}for(var i=e.start;i0}function lB(e){var t=e.hostModel,n=t.getModel(`emphasis`);return{lineStyle:t.getModel(`lineStyle`).getLineStyle(),emphasisLineStyle:n.getModel([`lineStyle`]).getLineStyle(),blurLineStyle:t.getModel([`blur`,`lineStyle`]).getLineStyle(),selectLineStyle:t.getModel([`select`,`lineStyle`]).getLineStyle(),emphasisDisabled:n.get(`disabled`),blurScope:n.get(`blurScope`),focus:n.get(`focus`),labelStatesModels:Dy(t)}}function uB(e){return isNaN(e[0])||isNaN(e[1])}function dB(e){return e&&!uB(e[0])&&!uB(e[1])}function fB(e,t,n,r,i,a){e||=0;var o=ac(n[1],-n[0]);if(i!=null&&(i=mB(i,[0,o])),a!=null&&(a=Math.max(a,i??0)),r===`all`){var s=Math.abs(ac(t[1],-t[0]));s=mB(s,[0,o]),i=a=mB(s,[i,a]),r=0}t[0]=mB(t[0],n),t[1]=mB(t[1],n);var c=pB(t,r);t[r]+=e;var l=i||0,u=n.slice();c.sign<0?u[0]=ac(u[0],l):u[1]=ac(u[1],-l),t[r]=mB(t[r],u);var d=pB(t,r);return i!=null&&(d.sign!==c.sign||d.spana&&(t[1-r]=ac(t[r],d.sign*a)),t}function pB(e,t){var n=e[t]-e[1-t];return{span:Math.abs(n),sign:n>0?-1:n<0?1:t?-1:1}}function mB(e,t){return Math.min(t[1]==null?1/0:t[1],Math.max(t[0]==null?-1/0:t[0],e))}var hB=!0,gB=Math.min,_B=Math.max,vB=Math.pow,yB=1e4,bB=6,xB=6,SB=`globalPan`,CB={w:[0,0],e:[0,1],n:[1,0],s:[1,1]},wB={w:`ew`,e:`ew`,n:`ns`,s:`ns`,ne:`nesw`,sw:`nesw`,nw:`nwse`,se:`nwse`},TB={brushStyle:{lineWidth:2,stroke:Q.color.backgroundTint,fill:Q.color.borderTint},transformable:!0,brushMode:`single`,removeOnClick:!1},EB=0,DB=function(e){U(t,e);function t(t){var n=e.call(this)||this;return n._track=[],n._covers=[],n._handlers={},n._zr=t,n.group=new y_,n._uid=`brushController_`+EB++,G(aV,function(e,t){this._handlers[t]=q(e,this)},n),n}return t.prototype.enableBrush=function(e){return this._brushType&&this._doDisableBrush(),e.brushType&&this._doEnableBrush(e),this},t.prototype._doEnableBrush=function(e){var t=this._zr;this._enableGlobalPan||oz(t,SB,this._uid),G(this._handlers,function(e,n){t.on(n,e)}),this._brushType=e.brushType,this._brushOption=Uo(Ho(TB),e,!0)},t.prototype._doDisableBrush=function(){var e=this._zr;sz(e,SB,this._uid),G(this._handlers,function(t,n){e.off(n,t)}),this._brushType=this._brushOption=null},t.prototype.setPanels=function(e){if(e&&e.length){var t=this._panels={};G(e,function(e){t[e.panelId]=Ho(e)})}else this._panels=null;return this},t.prototype.mount=function(e){e||={},this._enableGlobalPan=e.enableGlobalPan;var t=this.group;return this._zr.add(t),t.attr({x:e.x||0,y:e.y||0,rotation:e.rotation||0,scaleX:e.scaleX||1,scaleY:e.scaleY||1}),this._transform=t.getLocalTransform(),this},t.prototype.updateCovers=function(e){e=K(e,function(e){return Uo(Ho(TB),e,!0)});var t=`\0-brush-index-`,n=this._covers,r=this._covers=[],i=this,a=this._creatingCover;return new cw(n,e,s,o).add(c).update(c).remove(l).execute(),this;function o(e,n){return(e.id==null?t+n:e.id)+`-`+e.brushType}function s(e,t){return o(e.__brushOption,t)}function c(t,o){var s=e[t];o!=null&&n[o]===a?r[t]=n[o]:MB(i,r[t]=o==null?kB(i,OB(i,s)):(n[o].__brushOption=s,n[o]))}function l(e){n[e]!==a&&i.group.remove(n[e])}},t.prototype.unmount=function(){return this.enableBrush(!1),IB(this),this._zr.remove(this.group),this},t.prototype.dispose=function(){this.unmount(),this.off()},t}(gp);function OB(e,t){var n=cV[t.brushType].createCover(e,t);return n.__brushOption=t,jB(n,t),e.group.add(n),n}function kB(e,t){var n=NB(t);return n.endCreating&&(n.endCreating(e,t),jB(t,t.__brushOption)),t}function AB(e,t){var n=t.__brushOption;NB(t).updateCoverShape(e,t,n.range,n)}function jB(e,t){var n=t.z;n??=yB,e.traverse(function(e){e.z=n,e.z2=n})}function MB(e,t){NB(t).updateCommon(e,t),AB(e,t)}function NB(e){return cV[e.__brushOption.brushType]}function PB(e,t,n){var r=e._panels;if(!r)return hB;var i,a=e._transform;return G(r,function(e){e.isTargetByCursor(t,n,a)&&(i=e)}),i}function FB(e,t){var n=e._panels;if(!n)return hB;var r=t.__brushOption.panelId;return r==null?hB:n[r]}function IB(e){var t=e._covers,n=t.length;return G(t,function(t){e.group.remove(t)},e),t.length=0,!!n}function LB(e,t){var n=K(e._covers,function(e){var t=e.__brushOption,n=Ho(t.range);return{brushType:t.brushType,panelId:t.panelId,range:n}});e.trigger(`brush`,{areas:n,isEnd:!!t.isEnd,removeOnClick:!!t.removeOnClick})}function RB(e){var t=e._track;if(!t.length)return!1;var n=t[t.length-1],r=t[0],i=n[0]-r[0],a=n[1]-r[1];return vB(i*i+a*a,.5)>bB}function zB(e){var t=e.length-1;return t<0&&(t=0),[e[0],e[t]]}function BB(e,t,n,r){var i=new y_;return i.add(new fh({name:`main`,style:WB(n),silent:!0,draggable:!0,cursor:`move`,drift:ns(YB,e,t,i,[`n`,`s`,`w`,`e`]),ondragend:ns(LB,t,{isEnd:!0})})),G(r,function(n){i.add(new fh({name:n.join(``),style:{opacity:0},draggable:!0,silent:!0,invisible:!0,drift:ns(YB,e,t,i,n),ondragend:ns(LB,t,{isEnd:!0})}))}),i}function VB(e,t,n,r){var i=r.brushStyle.lineWidth||0,a=_B(i,xB),o=n[0][0],s=n[1][0],c=o-i/2,l=s-i/2,u=n[0][1],d=n[1][1],f=u-a+i/2,p=d-a+i/2,m=u-o,h=d-s,g=m+i,_=h+i;UB(e,t,`main`,o,s,m,h),r.transformable&&(UB(e,t,`w`,c,l,a,_),UB(e,t,`e`,f,l,a,_),UB(e,t,`n`,c,l,g,a),UB(e,t,`s`,c,p,g,a),UB(e,t,`nw`,c,l,a,a),UB(e,t,`ne`,f,l,a,a),UB(e,t,`sw`,c,p,a,a),UB(e,t,`se`,f,p,a,a))}function HB(e,t){var n=t.__brushOption,r=n.transformable,i=t.childAt(0);i.useStyle(WB(n)),i.attr({silent:!r,cursor:r?`move`:`default`}),G([[`w`],[`e`],[`n`],[`s`],[`s`,`e`],[`s`,`w`],[`n`,`e`],[`n`,`w`]],function(n){var i=t.childOfName(n.join(``)),a=n.length===1?qB(e,n[0]):JB(e,n);i&&i.attr({silent:!r,invisible:!r,cursor:r?wB[a]+`-resize`:null})})}function UB(e,t,n,r,i,a,o){var s=t.childOfName(n);s&&s.setShape($B(QB(e,t,[[r,i],[r+a,i+o]])))}function WB(e){return Ko({strokeNoScale:!0},e.brushStyle)}function GB(e,t,n,r){var i=[gB(e,n),gB(t,r)],a=[_B(e,n),_B(t,r)];return[[i[0],a[0]],[i[1],a[1]]]}function KB(e){return Kv(e.group)}function qB(e,t){return{left:`w`,right:`e`,top:`n`,bottom:`s`}[Jv({w:`left`,e:`right`,n:`top`,s:`bottom`}[t],KB(e))]}function JB(e,t){var n=[qB(e,t[0]),qB(e,t[1])];return(n[0]===`e`||n[0]===`w`)&&n.reverse(),n.join(``)}function YB(e,t,n,r,i,a){var o=n.__brushOption,s=e.toRectRange(o.range),c=ZB(t,i,a);G(r,function(e){var t=CB[e];s[t[0]][t[1]]+=c[t[0]]}),o.range=e.fromRectRange(GB(s[0][0],s[1][0],s[0][1],s[1][1])),MB(t,n),LB(t,{isEnd:!1})}function XB(e,t,n,r){var i=t.__brushOption.range,a=ZB(e,n,r);G(i,function(e){e[0]+=a[0],e[1]+=a[1]}),MB(e,t),LB(e,{isEnd:!1})}function ZB(e,t,n){var r=e.group,i=r.transformCoordToLocal(t,n),a=r.transformCoordToLocal(0,0);return[i[0]-a[0],i[1]-a[1]]}function QB(e,t,n){var r=FB(e,t);return r&&r!==hB?r.clipPath(n,e._transform):Ho(n)}function $B(e){var t=gB(e[0][0],e[1][0]),n=gB(e[0][1],e[1][1]),r=_B(e[0][0],e[1][0]),i=_B(e[0][1],e[1][1]);return{x:t,y:n,width:r-t,height:i-n}}function eV(e,t,n){if(e._brushType&&!sV(e,t.offsetX,t.offsetY)){var r=e._zr,i=e._covers,a=PB(e,t,n);if(!e._dragging)for(var o=0;or.getWidth()||n<0||n>r.getHeight()}var cV={lineX:lV(0),lineY:lV(1),rect:{createCover:function(e,t){function n(e){return e}return BB({toRectRange:n,fromRectRange:n},e,t,[[`w`],[`e`],[`n`],[`s`],[`s`,`e`],[`s`,`w`],[`n`,`e`],[`n`,`w`]])},getCreatingRange:function(e){var t=zB(e);return GB(t[1][0],t[1][1],t[0][0],t[0][1])},updateCoverShape:function(e,t,n,r){VB(e,t,n,r)},updateCommon:HB,contain:nV},polygon:{createCover:function(e,t){var n=new y_;return n.add(new J_({name:`main`,style:WB(t),silent:!0})),n},getCreatingRange:function(e){return e},endCreating:function(e,t){t.remove(t.childAt(0)),t.add(new K_({name:`main`,draggable:!0,drift:ns(XB,e,t),ondragend:ns(LB,e,{isEnd:!0})}))},updateCoverShape:function(e,t,n,r){t.childAt(0).setShape({points:QB(e,t,n)})},updateCommon:HB,contain:nV}};function lV(e){return{createCover:function(t,n){return BB({toRectRange:function(t){var n=[t,[0,100]];return e&&n.reverse(),n},fromRectRange:function(t){return t[e]}},t,n,[[[`w`],[`e`]],[[`n`],[`s`]]][e])},getCreatingRange:function(t){var n=zB(t);return[gB(n[0][e],n[1][e]),_B(n[0][e],n[1][e])]},updateCoverShape:function(t,n,r,i){var a,o=FB(t,n);if(o!==hB&&o.getLinearBrushOtherExtent)a=o.getLinearBrushOtherExtent(e);else{var s=t._zr;a=[0,[s.getWidth(),s.getHeight()][1-e]]}var c=[r,a];e&&c.reverse(),VB(t,n,c,i)},updateCommon:HB,contain:nV}}function uV(e){return e=pV(e),function(t){return Qv(t,e)}}function dV(e,t){return e=pV(e),function(n){var r=t??n,i=r?e.width:e.height,a=r?e.x:e.y;return[a,a+(i||0)]}}function fV(e,t,n){var r=pV(e);return function(e,i){return r.contain(i[0],i[1])&&!uz(e,t,n)}}function pV(e){return Ru.create(e)}var mV=256,hV=function(){function e(){this.blurSize=30,this.pointSize=20,this.maxOpacity=1,this.minOpacity=0,this._gradientPixels={inRange:null,outOfRange:null};var e=Eo.createCanvas();this.canvas=e}return e.prototype.update=function(e,t,n,r,i,a){var o=this._getBrush(),s=this._getGradient(i,`inRange`),c=this._getGradient(i,`outOfRange`),l=this.pointSize+this.blurSize,u=this.canvas,d=u.getContext(`2d`),f=e.length;u.width=t,u.height=n;for(var p=0;p0){var E=a(v)?s:c;v>0&&(v=v*w+C),b[x++]=E[T],b[x++]=E[T+1],b[x++]=E[T+2],b[x++]=E[T+3]*v*256}else x+=4}return d.putImageData(y,0,0),u},e.prototype._getBrush=function(){var e=this._brushCanvas||=Eo.createCanvas(),t=this.pointSize+this.blurSize,n=t*2;e.width=n,e.height=n;var r=e.getContext(`2d`);return r.clearRect(0,0,n,n),r.shadowOffsetX=n,r.shadowBlur=this.blurSize,r.shadowColor=Q.color.neutral99,r.beginPath(),r.arc(-t,t,this.pointSize,0,Math.PI*2,!0),r.closePath(),r.fill(),e},e.prototype._getGradient=function(e,t){for(var n=this._gradientPixels,r=n[t]||(n[t]=new Uint8ClampedArray(1024)),i=[0,0,0,0],a=0,o=0;o<256;o++)e[t](o/255,!0,i),r[a++]=i[0],r[a++]=i[1],r[a++]=i[2],r[a++]=i[3];return r},e}();function gV(e,t,n){var r=e[1]-e[0];t=K(t,function(t){return{interval:[(t.interval[0]-e[0])/r,(t.interval[1]-e[0])/r]}});var i=t.length,a=0;return function(e){for(var r=a;r=0;r--){var o=t[r].interval;if(o[0]<=e&&e<=o[1]){a=r;break}}return r>=0&&r=t[0]&&e<=t[1]}}var vV=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.render=function(e,t,n){var r;t.eachComponent(`visualMap`,function(t){t.eachTargetSeries(function(n){n===e&&(r=t)})}),this._progressiveEls=null,this.group.removeAll();var i=e.coordinateSystem;i.type===`cartesian2d`||i.type===`calendar`||i.type===`matrix`?this._renderOnGridLike(e,n,0,e.getData().count()):jL(i)&&this._renderOnGeo(i,e,r,n)},t.prototype.incrementalPrepareRender=function(e,t,n){this.group.removeAll()},t.prototype.incrementalRender=function(e,t,n,r){var i=t.coordinateSystem;i&&(jL(i)?this.render(t,n,r):(this._progressiveEls=[],this._renderOnGridLike(t,r,e.start,e.end,!0)))},t.prototype.eachRendered=function(e){uy(this._progressiveEls||this.group,e)},t.prototype._renderOnGridLike=function(e,t,n,r,i){var a=e.coordinateSystem,o=AL(a,`cartesian2d`),s=AL(a,`matrix`),c,l,u,d;if(o){var f=a.getAxis(`x`),p=a.getAxis(`y`);c=RD(f).w+.5,l=RD(p).w+.5,u=f.scale.getExtent(),d=p.scale.getExtent()}for(var m=this.group,h=e.getData(),g=e.getModel([`emphasis`,`itemStyle`]).getItemStyle(),_=e.getModel([`blur`,`itemStyle`]).getItemStyle(),v=e.getModel([`select`,`itemStyle`]).getItemStyle(),y=e.get([`itemStyle`,`borderRadius`]),b=Dy(e),x=e.getModel(`emphasis`),S=x.get(`focus`),C=x.get(`blurScope`),w=x.get(`disabled`),T=o||s?[h.mapDimension(`x`),h.mapDimension(`y`),h.mapDimension(`value`)]:[h.mapDimension(`time`),h.mapDimension(`value`)],E=n;Eu[1]||Ad[1])continue;var j=a.dataToPoint([k,A]);D=new fh({shape:{x:j[0]-c/2,y:j[1]-l/2,width:c,height:l},style:O})}else if(s){var M=a.dataToLayout([h.get(T[0],E),h.get(T[1],E)]).rect;if(fs(M.x))continue;D=new fh({z2:1,shape:M,style:O})}else{if(isNaN(h.get(T[1],E)))continue;var N=a.dataToLayout([h.get(T[0],E)]),M=N.contentRect||N.rect;if(fs(M.x)||fs(M.y))continue;D=new fh({z2:1,shape:M,style:O})}if(h.hasItemOption){var P=h.getItemModel(E),F=P.getModel(`emphasis`);g=F.getModel(`itemStyle`).getItemStyle(),_=P.getModel([`blur`,`itemStyle`]).getItemStyle(),v=P.getModel([`select`,`itemStyle`]).getItemStyle(),y=P.get([`itemStyle`,`borderRadius`]),S=F.get(`focus`),C=F.get(`blurScope`),w=F.get(`disabled`),b=Dy(P)}D.shape.r=y;var I=e.getRawValue(E),L=`-`;I&&I[2]!=null&&(L=I[2]+``),Ey(D,b,{labelFetcher:e,labelDataIndex:E,defaultOpacity:O.opacity,defaultText:L}),D.ensureState(`emphasis`).style=g,D.ensureState(`blur`).style=_,D.ensureState(`select`).style=v,Bg(D,S,C,w),D.incremental=wl(e,i),i&&(D.states.emphasis.hoverLayer=2),m.add(D),h.setItemGraphicEl(E,D),this._progressiveEls&&this._progressiveEls.push(D)}},t.prototype._renderOnGeo=function(e,t,n,r){var i=n.targetVisuals.inRange,a=n.targetVisuals.outOfRange,o=t.getData(),s=this._hmLayer||this._hmLayer||new hV;s.blurSize=t.get(`blurSize`),s.pointSize=t.get(`pointSize`),s.minOpacity=t.get(`minOpacity`),s.maxOpacity=t.get(`maxOpacity`);var c=e.getViewRect().clone(),l=e.getRoamTransform();c.applyTransform(l);var u=Math.max(c.x,0),d=Math.max(c.y,0),f=Math.min(c.width+c.x,r.getWidth()),p=Math.min(c.height+c.y,r.getHeight()),m=f-u,h=p-d,g=[o.mapDimension(`lng`),o.mapDimension(`lat`),o.mapDimension(`value`)],_=o.mapArray(g,function(t,n,r){var i=e.dataToPoint([t,n]);return i[0]-=u,i[1]-=d,i.push(r),i}),v=n.getExtent(),y=n.type===`visualMap.continuous`?_V(v,n.option.range):gV(v,n.getPieceList(),n.option.selected);s.update(_,m,h,i.color.getNormalizer(),{inRange:i.color.getColorMapper(),outOfRange:a.color.getColorMapper()},y);var b=new ih({style:{width:m,height:h,x:u,y:d,image:s.canvas},silent:!0});this.group.add(b)},t.type=`heatmap`,t}(Jj),yV=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.getInitialData=function(e,t){return lI(null,this,{generateCoord:`value`})},t.prototype.preventIncremental=function(){var e=Ox.get(this.get(`coordinateSystem`));if(e&&e.dimensions)return e.dimensions[0]===`lng`&&e.dimensions[1]===`lat`},t.type=`series.heatmap`,t.dependencies=[`grid`,`geo`,`calendar`,`matrix`],t.defaultOption={coordinateSystem:`cartesian2d`,z:2,geoIndex:0,blurSize:30,pointSize:20,maxOpacity:1,minOpacity:0,select:{itemStyle:{borderColor:Q.color.primary}}},t}(ZC);function bV(e){e.registerChartView(vV),e.registerSeriesModel(yV)}var xV={color:`fill`,borderColor:`stroke`},SV={symbol:1,symbolSize:1,symbolKeepAspect:1,legendIcon:1,visualMeta:1,liftZ:1,decal:1},CV=Qc(),wV=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.optionUpdated=function(){this.currentZLevel=this.get(`zlevel`,!0),this.currentZ=this.get(`z`,!0)},t.prototype.getInitialData=function(e,t){return lI(null,this)},t.prototype.getDataParams=function(t,n,r){var i=e.prototype.getDataParams.call(this,t,n);return r&&(i.info=CV(r).info),i},t.type=`series.custom`,t.dependencies=[`grid`,`polar`,`geo`,`singleAxis`,`calendar`,`matrix`],t.defaultOption={coordinateSystem:`cartesian2d`,z:2,legendHoverLink:!0,clip:!1},t}(ZC);function TV(e,t){return t||=[0,0],K([`x`,`y`],function(n,r){var i=this.getAxis(n),a=t[r],o=e[r]/2;return i.type===`category`?RD(i).w:Math.abs(i.dataToCoord(a-o)-i.dataToCoord(a+o))},this)}function EV(e){var t=e.master.getRect();return{coordSys:{type:`cartesian2d`,x:t.x,y:t.y,width:t.width,height:t.height},api:{coord:function(t){return e.dataToPoint(t)},size:q(TV,e)}}}function DV(e,t){return t||=[0,0],K([0,1],function(n){var r=t[n],i=e[n]/2,a=[],o=[];return a[n]=r-i,o[n]=r+i,a[1-n]=o[1-n]=t[1-n],Math.abs(this.dataToPoint(a)[n]-this.dataToPoint(o)[n])},this)}function OV(e){var t=e.view,n=t.getBoundingRect();return{coordSys:{type:`geo`,x:n.x,y:n.y,width:n.width,height:n.height,zoom:Oz(t)},api:{coord:function(t){return e.dataToPoint(t)},size:q(DV,e)}}}function kV(e,t){var n=this.getAxis(),r=t instanceof Array?t[0]:t,i=(e instanceof Array?e[0]:e)/2;return n.type===`category`?RD(n).w:Math.abs(n.dataToCoord(r-i)-n.dataToCoord(r+i))}function AV(e){var t=e.getRect();return{coordSys:{type:`singleAxis`,x:t.x,y:t.y,width:t.width,height:t.height},api:{coord:function(t){return e.dataToPoint(t)},size:q(kV,e)}}}function jV(e,t){return t||=[0,0],K([`Radius`,`Angle`],function(n,r){var i=`get`+n+`Axis`,a=this[i](),o=t[r],s=e[r]/2,c=a.type===`category`?RD(a).w:Math.abs(a.dataToCoord(o-s)-a.dataToCoord(o+s));return n===`Angle`&&(c=c*Math.PI/180),c},this)}function MV(e){var t=e.getRadiusAxis(),n=e.getAngleAxis(),r=t.getExtent();return r[0]>r[1]&&r.reverse(),{coordSys:{type:`polar`,cx:e.cx,cy:e.cy,r:r[1],r0:r[0]},api:{coord:function(r){var i=t.dataToRadius(r[0]),a=n.dataToAngle(r[1]),o=e.coordToPoint([i,a]);return o.push(i,a*Math.PI/180),o},size:q(jV,e)}}}function NV(e){var t=e.getRect(),n=e.getRangeInfo();return{coordSys:{type:`calendar`,x:t.x,y:t.y,width:t.width,height:t.height,cellWidth:e.getCellWidth(),cellHeight:e.getCellHeight(),rangeInfo:{start:n.start,end:n.end,weeks:n.weeks,dayCount:n.allDay}},api:{coord:function(t,n){return e.dataToPoint(t,n)},layout:function(t,n){return e.dataToLayout(t,n)}}}}function PV(e){var t=e.getRect();return{coordSys:{type:`matrix`,x:t.x,y:t.y,width:t.width,height:t.height},api:{coord:function(t,n){return e.dataToPoint(t,n)},layout:function(t,n){return e.dataToLayout(t,n)}}}}var FV={position:[`x`,`y`],scale:[`scaleX`,`scaleY`],origin:[`originX`,`originY`]},IV=es(FV);Zo(Hd,function(e,t){return e[t]=1,e},{}),Hd.join(`, `);var LV=[``,`style`,`shape`,`extra`],RV=Qc();function zV(e,t,n,r,i){var a=e+`Animation`,o=bv(e,r,i)||{},s=RV(t).userDuring;return o.duration>0&&(o.during=s?q(YV,{el:t,userDuring:s}):null,o.setToFinal=!0,o.scope=e),W(o,n[a]),o}function BV(e,t,n,r){r||={};var i=r.dataIndex,a=r.isInit,o=r.clearStyle,s=n.isAnimationEnabled(),c=RV(e),l=t.style;c.userDuring=t.during;var u={},d={};if($V(e,t,d),e.type===`compound`)for(var f=e.shape.paths,p=t.shape.paths,m=0;m0&&e.animateFrom(g,_)}else GV(e,t,i||0,n,u)}VV(e,t),l?e.dirty():e.markRedraw()}function VV(e,t){for(var n=RV(e).leaveToProps,r=0;r0&&e.animateFrom(i,a)}}function KV(e,t){Z(t,`silent`)&&(e.silent=t.silent),Z(t,`ignore`)&&(e.ignore=t.ignore),e instanceof Gp&&Z(t,`invisible`)&&(e.invisible=t.invisible),e instanceof Qm&&Z(t,`autoBatch`)&&(e.autoBatch=t.autoBatch)}var qV={},JV={setTransform:function(e,t){return qV.el[e]=t,this},getTransform:function(e){return qV.el[e]},setShape:function(e,t){var n=qV.el,r=n.shape||={};return r[e]=t,n.dirtyShape&&n.dirtyShape(),this},getShape:function(e){var t=qV.el.shape;if(t)return t[e]},setStyle:function(e,t){var n=qV.el,r=n.style;return r&&(r[e]=t,n.dirtyStyle&&n.dirtyStyle()),this},getStyle:function(e){var t=qV.el.style;if(t)return t[e]},setExtra:function(e,t){var n=qV.el.extra||(qV.el.extra={});return n[e]=t,this},getExtra:function(e){var t=qV.el.extra;if(t)return t[e]}};function YV(){var e=this,t=e.el;if(t){var n=RV(t).userDuring,r=e.userDuring;if(n!==r){e.el=e.userDuring=null;return}qV.el=t,r(JV)}}function XV(e,t,n,r){var i=n[e];if(i){var a=t[e],o;if(a){var s=n.transition,c=i.transition;if(c){if(!o&&(o=r[e]={}),UV(c))W(o,a);else for(var l=Ac(c),u=0;u=0){!o&&(o=r[e]={});for(var p=es(a),u=0;u=0)){var f=e.getAnimationStyleProps(),p=f?f.style:null;if(p){!a&&(a=r.style={});for(var m=es(n),l=0;l=0?t.getStore().get(i,n):void 0}var a=t.get(r.name,n),o=r&&r.ordinalMeta;return o?o.categories[a]:a}function C(n,r){r??=u;var i=t.getItemVisual(r,`style`),a=i&&i.fill,o=i&&i.opacity,s=y(r,sH).getItemStyle();a!=null&&(s.fill=a),o!=null&&(s.opacity=o);var c={inheritColor:Y(a)?a:Q.color.neutral99},l=b(r,sH),d=Oy(l,null,c,!1,!0);d.text=l.getShallow(`show`)?X(e.getFormattedLabel(r,sH),pI(t,r)):null;var f=ky(l,c,!1);return E(n,s),s=FL(s,d,f),n&&T(s,n),s.legacy=!0,s}function w(n,r){r??=u;var i=y(r,oH).getItemStyle(),a=b(r,oH),o=Oy(a,null,null,!0,!0);o.text=a.getShallow(`show`)?ms(e.getFormattedLabel(r,oH),e.getFormattedLabel(r,sH),pI(t,r)):null;var s=ky(a,null,!0);return E(n,i),i=FL(i,o,s),n&&T(i,n),i.legacy=!0,i}function T(e,t){for(var n in t)Z(t,n)&&(e[n]=t[n])}function E(e,t){e&&(e.textFill&&(t.textFill=e.textFill),e.textPosition&&(t.textPosition=e.textPosition))}function D(e,n){if(n??=u,Z(xV,e)){var r=t.getItemVisual(n,`style`);return r?r[xV[e]]:null}if(Z(SV,e))return t.getItemVisual(n,e)}function O(e){if(o.type===`cartesian2d`)return hR(Ko({axis:o.getBaseAxis()},e))}function k(){return n.getCurrentSeriesIndices()}function A(e){return Iy(e,n)}}function DH(e){var t={};return G(e.dimensions,function(n){var r=e.getDimensionInfo(n);if(!r.isExtraCoord){var i=r.coordDim,a=t[i]=t[i]||[];a[r.coordDimIndex]=e.getDimensionIndex(n)}}),t}function OH(e,t,n,r,i,a,o){if(!r){a.remove(t);return}var s=kH(e,t,n,r,i,a);return s&&o.setItemGraphicEl(n,s),s&&Bg(s,r.focus,r.blurScope,r.emphasisDisabled),s}function kH(e,t,n,r,i,a){var o=-1,s=t;t&&AH(t,r,i)&&(o=qo(a.childrenRef(),t),t=null);var c=!t,l=t;l?l.clearStates():(l=xH(r),s&&yH(s,l)),r.morph===!1?l.disableMorphing=!0:l.disableMorphing&&(l.disableMorphing=!1),r.tooltipDisabled&&(l.tooltipDisabled=!0),hH.normal.cfg=hH.normal.conOpt=hH.emphasis.cfg=hH.emphasis.conOpt=hH.blur.cfg=hH.blur.conOpt=hH.select.cfg=hH.select.conOpt=null,hH.isLegacy=!1,MH(l,n,r,i,c,hH),jH(l,n,r,i,c),SH(e,l,n,r,hH,i,c),Z(r,`info`)&&(CV(l).info=r.info);for(var u=0;u=0?a.replaceAt(l,o):a.add(l),l}function AH(e,t,n){var r=CV(e),i=t.type,a=t.shape,o=t.style;return n.isUniversalTransitionEnabled()||i!=null&&i!==r.customGraphicType||i===`path`&&UH(a)&&HH(a)!==r.customPathData||i===`image`&&Z(o,`image`)&&o.image!==r.customImagePath}function jH(e,t,n,r,i){var a=n.clipPath;if(a===!1)e&&e.getClipPath()&&e.removeClipPath();else if(a){var o=e.getClipPath();o&&AH(o,a,r)&&(o=null),o||(o=xH(a),e.setClipPath(o)),SH(null,o,t,a,null,r,i)}}function MH(e,t,n,r,i,a){if(!(e.isGroup||e.type===`compoundPath`)){NH(n,null,a),NH(n,oH,a);var o=a.normal.conOpt,s=a.emphasis.conOpt,c=a.blur.conOpt,l=a.select.conOpt;if(o!=null||s!=null||l!=null||c!=null){var u=e.getTextContent();if(o===!1)u&&e.removeTextContent();else{o=a.normal.conOpt=o||{type:`text`},u?u.clearStates():(u=xH(o),e.setTextContent(u)),SH(null,u,t,o,null,r,i);for(var d=o&&o.style,f=0;f=u;p--)LH(t,t.childAt(p),i)}}function LH(e,t,n){t&&HV(t,CV(e).option,n)}function RH(e){new cw(e.oldChildren,e.newChildren,zH,zH,e).add(BH).update(BH).remove(VH).execute()}function zH(e,t){return(e&&e.name)??mH+t}function BH(e,t){var n=this.context,r=e==null?null:n.newChildren[e],i=t==null?null:n.oldChildren[t];kH(n.api,i,n.dataIndex,r,n.seriesModel,n.group)}function VH(e){var t=this.context,n=t.oldChildren[e];n&&HV(n,CV(n).option,t.seriesModel)}function HH(e){return e&&(e.pathData||e.d)}function UH(e){return e&&(Z(e,`pathData`)||Z(e,`d`))}function WH(e){e.registerChartView(bH),e.registerSeriesModel(wV)}var GH=Qc(),KH=Ho,qH=q,JH=function(){function e(){this._dragging=!1,this.animationThreshold=15}return e.prototype.render=function(e,t,n,r){var i=t.get(`value`),a=t.get(`status`);if(this._axisModel=e,this._axisPointerModel=t,this._api=n,r||this._lastValue!==i||this._lastStatus!==a){this._lastValue=i,this._lastStatus=a;var o=this._group,s=this._handle;if(!a||a===`hide`){o&&o.hide(),s&&s.hide();return}o&&o.show(),s&&s.show();var c={};this.makeElOption(c,i,e,t,n);var l=c.graphicKey;l!==this._lastGraphicKey&&this.clear(n),this._lastGraphicKey=l;var u=this._moveAnimation=this.determineAnimation(e,t);if(!o)o=this._group=new y_,this.createPointerEl(o,c,e,t),this.createLabelEl(o,c,e,t),n.getZr().add(o);else{var d=ns(YH,t,u);this.updatePointerEl(o,c,d),this.updateLabelEl(o,c,d,t)}$H(o,t,!0),this._renderHandle(i)}},e.prototype.remove=function(e){this.clear(e)},e.prototype.dispose=function(e){this.clear(e)},e.prototype.determineAnimation=function(e,t){var n=t.get(`animation`),r=e.axis,i=r.type===`category`,a=t.get(`snap`);if(!a&&!i)return!1;if(n===`auto`||n==null){var o=this.animationThreshold;if(i&&RD(r).w>o)return!0;if(a){var s=QI(e).seriesDataCount,c=r.getExtent();return Math.abs(c[0]-c[1])/s>o}return!1}return n===!0},e.prototype.makeElOption=function(e,t,n,r,i){},e.prototype.createPointerEl=function(e,t,n,r){var i=t.pointer;if(i){var a=GH(e).pointerEl=new kv[i.type](KH(t.pointer));e.add(a)}},e.prototype.createLabelEl=function(e,t,n,r){if(t.label){var i=GH(e).labelEl=new _h(KH(t.label));e.add(i),ZH(i,r)}},e.prototype.updatePointerEl=function(e,t,n){var r=GH(e).pointerEl;r&&t.pointer&&(r.setStyle(t.pointer.style),n(r,{shape:t.pointer.shape}))},e.prototype.updateLabelEl=function(e,t,n,r){var i=GH(e).labelEl;i&&(i.setStyle(t.label.style),n(i,{x:t.label.x,y:t.label.y}),ZH(i,r))},e.prototype._renderHandle=function(e){if(!this._dragging&&this.updateHandleTransform){var t=this._axisPointerModel,n=this._api.getZr(),r=this._handle,i=t.getModel(`handle`),a=t.get(`status`);if(!i.get(`show`)||!a||a===`hide`){r&&n.remove(r),this._handle=null;return}var o;this._handle||(o=!0,r=this._handle=ey(i.get(`icon`),{cursor:`move`,draggable:!0,onmousemove:function(e){Bk(e.event)},onmousedown:qH(this._onHandleDragMove,this,0,0),drift:qH(this._onHandleDragMove,this),ondragend:qH(this._onHandleDragEnd,this)}),n.add(r)),$H(r,t,!1),r.setStyle(i.getItemStyle(null,[`color`,`borderColor`,`borderWidth`,`opacity`,`shadowColor`,`shadowBlur`,`shadowOffsetX`,`shadowOffsetY`]));var s=i.get(`size`);J(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,iM(this,`_doDispatchAxisPointer`,i.get(`throttle`)||0,`fixRate`),this._moveHandleToValue(e,o)}},e.prototype._moveHandleToValue=function(e,t){YH(this._axisPointerModel,!t&&this._moveAnimation,this._handle,QH(this.getHandleTransform(e,this._axisModel,this._axisPointerModel)))},e.prototype._onHandleDragMove=function(e,t){var n=this._handle;if(n){this._dragging=!0;var r=this.updateHandleTransform(QH(n),[e,t],this._axisModel,this._axisPointerModel);this._payloadInfo=r,n.stopAnimation(),n.attr(QH(r)),GH(n).lastProp=null,this._doDispatchAxisPointer()}},e.prototype._doDispatchAxisPointer=function(){if(this._handle){var e=this._payloadInfo,t=this._axisModel;this._api.dispatchAction({type:`updateAxisPointer`,x:e.cursorPoint[0],y:e.cursorPoint[1],tooltipOption:e.tooltipOption,axesInfo:[{axisDim:t.axis.dim,axisIndex:t.componentIndex}]})}},e.prototype._onHandleDragEnd=function(){if(this._dragging=!1,this._handle){var e=this._axisPointerModel.get(`value`);this._moveHandleToValue(e),this._api.dispatchAction({type:`hideTip`})}},e.prototype.clear=function(e){this._lastValue=null,this._lastStatus=null;var t=e.getZr(),n=this._group,r=this._handle;t&&n&&(this._lastGraphicKey=null,n&&t.remove(n),r&&t.remove(r),this._group=null,this._handle=null,this._payloadInfo=null),aM(this,`_doDispatchAxisPointer`)},e.prototype.doClear=function(){},e.prototype.buildLabel=function(e,t,n){return n||=0,{x:e[n],y:e[1-n],width:t[n],height:t[1-n]}},e}();function YH(e,t,n,r){XH(GH(n).lastProp,r)||(GH(n).lastProp=r,t?Sv(n,r,e):(n.stopAnimation(),n.attr(r)))}function XH(e,t){if(os(e)&&os(t)){var n=!0;return G(t,function(t,r){n&&=XH(e[r],t)}),!!n}return e===t}function ZH(e,t){e[t.get([`label`,`show`])?`show`:`hide`]()}function QH(e){return{x:e.x||0,y:e.y||0,rotation:e.rotation||0}}function $H(e,t,n){var r=t.get(`z`),i=t.get(`zlevel`);e&&e.traverse(function(e){e.type!==`group`&&(r!=null&&(e.z=r),i!=null&&(e.zlevel=i),e.silent=n)})}function eU(e){var t=e.get(`type`),n=e.getModel(t+`Style`),r;return t===`line`?(r=n.getLineStyle(),r.fill=null):t===`shadow`&&(r=n.getAreaStyle(),r.stroke=null),r}function tU(e,t,n,r,i){var a=rU(n.get(`value`),t.axis,t.ecModel,n.get(`seriesDataIndices`),{precision:n.get([`label`,`precision`]),formatter:n.get([`label`,`formatter`])}),o=n.getModel(`label`),s=vx(o.get(`padding`)||0),c=o.getFont(),l=id(a,c),u=i.position,d=l.width+s[1]+s[3],f=l.height+s[0]+s[2],p=i.align;p===`right`&&(u[0]-=d),p===`center`&&(u[0]-=d/2);var m=i.verticalAlign;m===`bottom`&&(u[1]-=f),m===`middle`&&(u[1]-=f/2),nU(u,d,f,r);var h=o.get(`backgroundColor`);(!h||h===`auto`)&&(h=t.get([`axisLine`,`lineStyle`,`color`])),e.label={x:u[0],y:u[1],style:Oy(o,{text:a,font:c,fill:o.getTextColor(),padding:s,backgroundColor:h}),z2:10}}function nU(e,t,n,r){var i=r.getWidth(),a=r.getHeight();e[0]=Math.min(e[0]+t,i)-t,e[1]=Math.min(e[1]+n,a)-n,e[0]=Math.max(e[0],0),e[1]=Math.max(e[1],0)}function rU(e,t,n,r,i){e=t.scale.parse(e);var a=t.scale.getLabel({value:e},{precision:i.precision}),o=i.formatter;if(o){var s={value:TE(t,{value:e}),axisDimension:t.dim,axisIndex:t.index,seriesData:[]};G(r,function(e){var t=n.getSeriesByIndex(e.seriesIndex),r=e.dataIndexInside,i=t&&t.getDataParams(r);i&&s.seriesData.push(i)}),Y(o)?a=o.replace(`{value}`,a):rs(o)&&(a=o(s))}return a}function iU(e,t,n){var r=Ql();return ru(r,r,n.rotation),nu(r,r,n.position),qv([e.dataToCoord(t),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],r)}function aU(e,t,n,r,i,a){var o=pO.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=i.get([`label`,`margin`]),tU(t,r,i,a,{position:iU(r.axis,e,n),align:o.textAlign,verticalAlign:o.textVerticalAlign})}function oU(e,t,n){return n||=0,{x1:e[n],y1:e[1-n],x2:t[n],y2:t[1-n]}}function sU(e,t,n){return n||=0,{x:e[n],y:e[1-n],width:t[n],height:t[1-n]}}function cU(e,t,n){return RD(e,{fromStat:{sers:K(t,function(e){return n.getSeriesByIndex(e.seriesIndex)})},min:1}).w}function lU(e,t,n){return[zs(Rs(t[0],t[1]),e-n/2),Rs(e+n/2,zs(t[0],t[1]))]}var uU=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.makeElOption=function(e,t,n,r,i){var a=n.axis,o=a.grid,s=r.get(`type`),c=a.getGlobalExtent(),l=dU(o,a).getOtherAxis(a).getGlobalExtent(),u=a.toGlobalCoord(a.dataToCoord(t,!0));if(s&&s!==`none`){var d=eU(r),f=fU[s](a,u,c,l,r.get(`seriesDataIndices`),r.ecModel);f.style=d,e.graphicKey=f.type,e.pointer=f}aU(t,e,PO(o.getRect(),n),n,r,i)},t.prototype.getHandleTransform=function(e,t,n){var r=PO(t.axis.grid.getRect(),t,{labelInside:!1});r.labelMargin=n.get([`handle`,`margin`]);var i=iU(t.axis,e,r);return{x:i[0],y:i[1],rotation:r.rotation+(r.labelDirection<0?Math.PI:0)}},t.prototype.updateHandleTransform=function(e,t,n,r){var i=n.axis,a=i.grid,o=i.getGlobalExtent(!0),s=dU(a,i).getOtherAxis(i).getGlobalExtent(),c=i.dim===`x`?0:1,l=[e.x,e.y];l[c]+=t[c],l[c]=Rs(o[1],l[c]),l[c]=zs(o[0],l[c]);var u=(s[1]+s[0])/2,d=[u,u];return d[c]=l[c],{x:l[0],y:l[1],rotation:e.rotation,cursorPoint:d,tooltipOption:[{verticalAlign:`middle`},{align:`center`}][c]}},t}(JH);function dU(e,t){var n={};return n[t.dim+`AxisIndex`]=t.index,e.getCartesian(n)}var fU={line:function(e,t,n,r){return{type:`Line`,subPixelOptimize:!0,shape:oU([t,r[0]],[t,r[1]],pU(e))}},shadow:function(e,t,n,r,i,a){var o=cU(e,i,a),s=r[1]-r[0],c=lU(t,n,o),l=c[0],u=c[1];return{type:`Rect`,shape:sU([l,r[0]],[u-l,s],pU(e))}}};function pU(e){return e.dim===`x`?0:1}var mU=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.type=`axisPointer`,t.defaultOption={show:`auto`,z:50,type:`line`,snap:!1,triggerTooltip:!0,triggerEmphasis:!0,value:null,status:null,link:[],animation:null,animationDurationUpdate:200,lineStyle:{color:Q.color.border,width:1,type:`dashed`},shadowStyle:{color:Q.color.shadowTint},label:{show:!0,formatter:null,precision:`auto`,margin:3,color:Q.color.neutral00,padding:[5,7,5,7],backgroundColor:Q.color.accent60,borderColor:null,borderWidth:0,borderRadius:3},handle:{show:!1,icon:`M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z`,size:45,margin:50,color:Q.color.accent40,throttle:40}},t}(Yx),hU=Qc(),gU=G;function _U(e,t,n){if(!Ns.node){var r=t.getZr();hU(r).records||(hU(r).records={}),vU(r,t);var i=hU(r).records[e]||(hU(r).records[e]={});i.handler=n}}function vU(e,t){if(hU(e).initialized)return;hU(e).initialized=!0,n(`click`,ns(xU,`click`)),n(`mousemove`,ns(xU,`mousemove`)),n(`mousewheel`,ns(xU,`mousewheel`)),n(`globalout`,bU);function n(n,r){e.on(n,function(n){var i=SU(t);gU(hU(e).records,function(e){e&&r(e,n,i.dispatchAction)}),yU(i.pendings,t)})}}function yU(e,t){var n=e.showTip.length,r=e.hideTip.length,i;n?i=e.showTip[n-1]:r&&(i=e.hideTip[r-1]),i&&(i.dispatchAction=null,t.dispatchAction(i))}function bU(e,t,n){e.handler(`leave`,null,n)}function xU(e,t,n,r){t.handler(e,n,r)}function SU(e){var t={showTip:[],hideTip:[]},n=function(r){var i=t[r.type];i?i.push(r):(r.dispatchAction=n,e.dispatchAction(r))};return{dispatchAction:n,pendings:t}}function CU(e,t){if(!Ns.node){var n=t.getZr();(hU(n).records||{})[e]&&(hU(n).records[e]=null)}}var wU=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.render=function(e,t,n){var r=t.getComponent(`tooltip`),i=e.get(`triggerOn`)||r&&r.get(`triggerOn`)||`mousemove|click|mousewheel`;_U(`axisPointer`,n,function(e,t,n){i!==`none`&&(e===`leave`||i.indexOf(e)>=0)&&n({type:`updateAxisPointer`,currTrigger:e,x:t&&t.offsetX,y:t&&t.offsetY})})},t.prototype.remove=function(e,t){CU(`axisPointer`,t)},t.prototype.dispose=function(e,t){CU(`axisPointer`,t)},t.type=`axisPointer`,t}(Wj);function TU(e,t){var n=[],r=e.seriesIndex,i;if(r==null||!(i=t.getSeriesByIndex(r)))return{point:[]};var a=i.getData(),o=Zc(a,e);if(o==null||o<0||J(o))return{point:[]};var s=a.getItemGraphicEl(o),c=i.coordinateSystem;if(i.getTooltipPosition)n=i.getTooltipPosition(o)||[];else if(c&&c.dataToPoint){if(e.isStacked){var l=c.getBaseAxis(),u=c.getOtherAxis(l).dim,d=l.dim,f=+(u===`x`||u===`radius`),p=a.mapDimension(d),m=[];m[f]=a.get(p,o),m[1-f]=a.get(a.getCalculationInfo(`stackResultDimension`),o),n=c.dataToPoint(m)||[]}else n=c.dataToPoint(a.getValues(K(c.dimensions,function(e){return a.mapDimension(e)}),o))||[]}else if(s){var h=s.getBoundingRect().clone();h.applyTransform(s.transform),n=[h.x+h.width/2,h.y+h.height/2]}return{point:n,el:s}}var EU=Qc();function DU(e,t,n){var r=e.currTrigger,i=[e.x,e.y],a=e,o=e.dispatchAction||q(n.dispatchAction,n),s=t.getComponent(`axisPointer`).coordSysAxesInfo;if(s){LU(i)&&(i=TU({seriesIndex:a.seriesIndex,dataIndex:a.dataIndex},t).point);var c=LU(i),l=a.axesInfo,u=s.axesInfo,d=r===`leave`||LU(i),f={},p={},m={list:[],map:{}},h={showPointer:ns(AU,p),showTooltip:ns(jU,m)};G(s.coordSysMap,function(e,t){var n=c||e.containPoint(i);G(s.coordSysAxesInfo[t],function(e,t){var r=e.axis,a=FU(l,e);if(!d&&n&&(!l||a)){var o=a&&a.value;o==null&&!c&&(o=r.pointToData(i)),o!=null&&OU(e,o,h,!1,f)}})});var g={};return G(u,function(e,t){var n=e.linkGroup;n&&!p[t]&&G(n.axesInfo,function(t,r){var i=p[r];if(t!==e&&i){var a=i.value;n.mapper&&(a=e.axis.scale.parse(n.mapper(a,IU(t),IU(e)))),g[e.key]=a}})}),G(g,function(e,t){OU(u[t],e,h,!0,f)}),MU(p,u,f),NU(m,i,e,o),PU(u,o,n),f}}function OU(e,t,n,r,i){var a=e.axis;if(!a.scale.isBlank()&&a.containData(t)){if(!e.involveSeries){n.showPointer(e,t);return}var o=kU(t,e),s=o.payloadBatch,c=o.snapToValue;s[0]&&i.seriesIndex==null&&W(i,s[0]),!r&&e.snap&&a.containData(c)&&c!=null&&(t=c),n.showPointer(e,t,s),n.showTooltip(e,o,c)}}function kU(e,t){var n=t.axis,r=n.dim,i=e,a=[],o=Number.MAX_VALUE,s=-1;return G(t.seriesModels,function(t,c){var l=t.getData().mapDimensionsAll(r),u,d;if(t.getAxisTooltipData){var f=t.getAxisTooltipData(l,e,n);d=f.dataIndices,u=f.nestestValue}else{if(d=t.indicesOfNearest(r,l[0],e,n.type===`category`?.5:null),!d.length)return;u=t.getData().get(l[0],d[0])}if(bc(u)){var p=e-u,m=Math.abs(p);m<=o&&((m=0&&s<0)&&(o=m,s=p,i=u,a.length=0),G(d,function(e){a.push({seriesIndex:t.seriesIndex,dataIndexInside:e,dataIndex:t.getData().getRawIndex(e)})}))}}),{payloadBatch:a,snapToValue:i}}function AU(e,t,n,r){e[t.key]={value:n,payloadBatch:r}}function jU(e,t,n,r){var i=n.payloadBatch,a=t.axis,o=a.model,s=t.axisPointerModel;if(t.triggerTooltip&&i.length){var c=t.coordSys.model,l=tL(c),u=e.map[l];u||(u=e.map[l]={coordSysId:c.id,coordSysIndex:c.componentIndex,coordSysType:c.type,coordSysMainType:c.mainType,dataByAxis:[]},e.list.push(u)),u.dataByAxis.push({axisDim:a.dim,axisIndex:o.componentIndex,axisType:o.type,axisId:o.id,value:r,valueLabelOpt:{precision:s.get([`label`,`precision`]),formatter:s.get([`label`,`formatter`])},seriesDataIndices:i.slice()})}}function MU(e,t,n){var r=n.axesInfo=[];G(t,function(t,n){var i=t.axisPointerModel.option,a=e[n];a?(!t.useHandle&&(i.status=`show`),i.value=a.value,i.seriesDataIndices=(a.payloadBatch||[]).slice()):!t.useHandle&&(i.status=`hide`),i.status===`show`&&r.push({axisDim:t.axis.dim,axisIndex:t.axis.model.componentIndex,value:i.value})})}function NU(e,t,n,r){if(LU(t)||!e.list.length){r({type:`hideTip`});return}var i=((e.list[0].dataByAxis[0]||{}).seriesDataIndices||[])[0]||{};r({type:`showTip`,escapeConnect:!0,x:t[0],y:t[1],tooltipOption:n.tooltipOption,position:n.position,dataIndexInside:i.dataIndexInside,dataIndex:i.dataIndex,seriesIndex:i.seriesIndex,dataByCoordSys:e.list})}function PU(e,t,n){var r=n.getZr(),i=`axisPointerLastHighlights`,a=EU(r)[i]||{},o=EU(r)[i]={};G(e,function(e,t){var n=e.axisPointerModel.option;n.status===`show`&&e.triggerEmphasis&&G(n.seriesDataIndices,function(e){o[e.seriesIndex+`|`+e.dataIndex]=e})});var s=[],c=[];function l(e){return{seriesIndex:e.seriesIndex,dataIndex:e.dataIndex}}G(a,function(e,t){!o[t]&&c.push(l(e))}),G(o,function(e,t){!a[t]&&s.push(l(e))}),c.length&&n.dispatchAction({type:`downplay`,escapeConnect:!0,notBlur:!0,batch:c}),s.length&&n.dispatchAction({type:`highlight`,escapeConnect:!0,notBlur:!0,batch:s})}function FU(e,t){for(var n=0;n<(e||[]).length;n++){var r=e[n];if(t.axis.dim===r.axisDim&&t.axis.model.componentIndex===r.axisIndex)return r}}function IU(e){var t=e.axis.model,n={},r=n.axisDim=e.axis.dim;return n.axisIndex=n[r+`AxisIndex`]=t.componentIndex,n.axisName=n[r+`AxisName`]=t.name,n.axisId=n[r+`AxisId`]=t.id,n}function LU(e){return!e||e[0]==null||isNaN(e[0])||e[1]==null||isNaN(e[1])}function RU(e){rL.registerAxisPointerClass(`CartesianAxisPointer`,uU),e.registerComponentModel(mU),e.registerComponentView(wU),e.registerPreprocessor(function(e){if(e){(!e.axisPointer||e.axisPointer.length===0)&&(e.axisPointer={});var t=e.axisPointer.link;t&&!J(t)&&(e.axisPointer.link=[t])}}),e.registerProcessor(e.PRIORITY.PROCESSOR.STATISTIC,{overallReset:function(e,t){e.getComponent(`axisPointer`).coordSysAxesInfo=GI(e,t)}}),e.registerAction({type:`updateAxisPointer`,event:`updateAxisPointer`,update:`:updateAxisPointer`},DU)}function zU(e){MF(mL),MF(RU)}function BU(e,t){var n=e.existing;if(t.id=e.keyInfo.id,!t.type&&n&&(t.type=n.type),t.parentId==null){var r=t.parentOption;r?t.parentId=r.id:n&&(t.parentId=n.parentId)}t.parentOption=null}function VU(e,t){var n;return G(t,function(t){e[t]!=null&&e[t]!==`auto`&&(n=!0)}),n}function HU(e,t,n){var r=W({},n),i=e[t],a=n.$action||`merge`;a===`merge`?i?(Uo(i,r,!0),Gx(i,r,{ignoreSize:!0}),qx(n,i),GU(n,i),GU(n,i,`shape`),GU(n,i,`style`),GU(n,i,`extra`),n.clipPath=i.clipPath):e[t]=r:a===`replace`?e[t]=r:a===`remove`&&i&&(e[t]=null)}var UU=[`transition`,`enterFrom`,`leaveTo`],WU=UU.concat([`enterAnimation`,`updateAnimation`,`leaveAnimation`]);function GU(e,t,n){if(n&&(!e[n]&&t[n]&&(e[n]={}),e=e[n],t=t[n]),e&&t)for(var r=n?UU:WU,i=0;i=0;c--){var l=n[c],u=Wc(l.id,null),d=u==null?null:i.get(u);if(d){var f=d.parent,h=YU(f),g=f===r?{width:a,height:o}:{width:h.width,height:h.height},_={},v=Ux(d,l,g,null,{hv:l.hv,boundingMode:l.bounding},_);if(!YU(d).isNew&&v){for(var y=l.transition,b={},x=0;x=0)?b[S]=C:d[S]=C}Sv(d,b,e,0)}else d.attr(_)}}},t.prototype._clear=function(){var e=this,t=this._elMap;t.each(function(n){$U(n,YU(n).option,t,e._lastGraphicModel)}),this._elMap=Es()},t.prototype.dispose=function(){this._clear()},t.type=`graphic`,t}(Wj);function ZU(e){var t=new(Z(JU,e)?JU[e]:Lv(e))({});return YU(t).type=e,t}function QU(e,t,n,r){var i=ZU(n);return t.add(i),r.set(e,i),YU(i).id=e,YU(i).isNew=!0,i}function $U(e,t,n,r){e&&e.parent&&(e.type===`group`&&e.traverse(function(e){$U(e,t,n,r)}),HV(e,t,r),n.removeKey(YU(e).id))}function eW(e,t,n,r){e.isGroup||G([[`cursor`,Gp.prototype.cursor],[`zlevel`,r||0],[`z`,n||0],[`z2`,0]],function(n){var r=n[0];Z(t,r)?e[r]=X(t[r],n[1]):e[r]??(e[r]=n[1])}),G(es(t),function(n){if(n.indexOf(`on`)===0){var r=t[n];e[n]=rs(r)?r:null}}),Z(t,`draggable`)&&(e.draggable=t.draggable),t.name!=null&&(e.name=t.name),t.id!=null&&(e.id=t.id)}function tW(e){return e=W({},e),G([`id`,`parentId`,`$action`,`hv`,`bounding`,`textContent`,`clipPath`].concat(Fx),function(t){delete e[t]}),e}function nW(e,t,n){var r=jh(e).eventData;!e.silent&&!e.ignore&&!r&&(r=jh(e).eventData={componentType:`graphic`,componentIndex:t.componentIndex,name:e.name}),r&&(r.info=n.info)}function rW(e){e.registerComponentModel(qU),e.registerComponentView(XU),e.registerPreprocessor(function(e){var t=e.graphic;J(t)?e.graphic=!t[0]||!t[0].elements?[{elements:t}]:[e.graphic[0]]:t&&!t.elements&&(e.graphic=[{elements:[t]}])})}var iW=[`x`,`y`,`radius`,`angle`,`single`],aW=Qc(),oW=[`cartesian2d`,`polar`,`singleAxis`];function sW(e){return qo(oW,e.get(`coordinateSystem`))>=0}function cW(e){return e+`Axis`}function lW(e,t){var n=Es(),r=[],i=Es();e.eachComponent({mainType:`dataZoom`,query:t},function(e){i.get(e.uid)||s(e)});var a;do a=!1,e.eachComponent(`dataZoom`,o);while(a);function o(e){!i.get(e.uid)&&c(e)&&(s(e),a=!0)}function s(e){i.set(e.uid,!0),r.push(e),l(e)}function c(e){var t=!1;return e.eachTargetAxis(function(e,r){var i=n.get(e);i&&i[r]&&(t=!0)}),t}function l(e){e.eachTargetAxis(function(e,t){(n.get(e)||n.set(e,[]))[t]=!0})}return r}function uW(e){var t=e.ecModel,n={infoList:[],infoMap:Es()};return e.eachTargetAxis(function(e,r){var i=t.getComponent(cW(e),r);if(i){var a=i.getCoordSysModel();if(a){var o=a.uid,s=n.infoMap.get(o);s||(s={model:a,axisModels:[]},n.infoList.push(s),n.infoMap.set(o,s)),s.axisModels.push(i)}}}),n}function dW(e){var t=aW(hD(e));return t.axisProxyMap||=Es()}function fW(e){if(e)return dW(e.ecModel).get(e.uid)}function pW(e,t){dW(e.ecModel).set(e.uid,t)}function mW(e,t){var n=t.getAxisModel().axis.__alignTo;return n&&e.getAxisProxy(n.dim,n.model.componentIndex)?fW(n.model):null}var hW=function(){function e(){this.indexList=[],this.indexMap=[]}return e.prototype.add=function(e){this.indexMap[e]||(this.indexList.push(e),this.indexMap[e]=!0)},e}(),gW=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n._autoThrottle=!0,n._noTarget=!0,n._rangePropMode=[`percent`,`percent`],n}return t.prototype.init=function(e,t,n){var r=_W(e);this.settledOption=r,this.mergeDefaultAndTheme(e,n),this._doInit(r)},t.prototype.mergeOption=function(e){var t=_W(e);Uo(this.option,e,!0),Uo(this.settledOption,t,!0),this._doInit(t)},t.prototype._doInit=function(e){var t=this.option;this._setDefaultThrottle(e),this._updateRangeUse(e);var n=this.settledOption;G([[`start`,`startValue`],[`end`,`endValue`]],function(e,r){this._rangePropMode[r]===`value`&&(t[e[0]]=n[e[0]]=null)},this),this._resetTarget()},t.prototype._resetTarget=function(){var e=this.get(`orient`,!0),t=this._targetAxisInfoMap=Es();this._fillSpecifiedTargetAxis(t)?this._orient=e||this._makeAutoOrientByTargetAxis():(this._orient=e||`horizontal`,this._fillAutoTargetAxisByOrient(t,this._orient)),this._noTarget=!0,t.each(function(e){e.indexList.length&&(this._noTarget=!1)},this)},t.prototype._fillSpecifiedTargetAxis=function(e){var t=!1;return G(iW,function(n){var r=this.getReferringComponents(cW(n),rl);if(r.specified){t=!0;var i=new hW;G(r.models,function(e){i.add(e.componentIndex)}),e.set(n,i)}},this),t},t.prototype._fillAutoTargetAxisByOrient=function(e,t){var n=this.ecModel,r=!0;if(r){var i=t===`vertical`?`y`:`x`,a=n.findComponents({mainType:i+`Axis`});o(a,i)}if(r){var a=n.findComponents({mainType:`singleAxis`,filter:function(e){return e.get(`orient`,!0)===t}});o(a,`single`)}function o(t,n){var i=t[0];if(i){var a=new hW;if(a.add(i.componentIndex),e.set(n,a),r=!1,n===`x`||n===`y`){var o=i.getReferringComponents(`grid`,nl).models[0];o&&G(t,function(e){i.componentIndex!==e.componentIndex&&o===e.getReferringComponents(`grid`,nl).models[0]&&a.add(e.componentIndex)})}}}r&&G(iW,function(t){if(r){var i=n.findComponents({mainType:cW(t),filter:function(e){return e.get(`type`,!0)===`category`}});if(i[0]){var a=new hW;a.add(i[0].componentIndex),e.set(t,a),r=!1}}},this)},t.prototype._makeAutoOrientByTargetAxis=function(){var e;return this.eachTargetAxis(function(t){!e&&(e=t)},this),e===`y`?`vertical`:`horizontal`},t.prototype._setDefaultThrottle=function(e){if(e.hasOwnProperty(`throttle`)&&(this._autoThrottle=!1),this._autoThrottle){var t=this.ecModel.option;this.option.throttle=t.animation&&t.animationDurationUpdate>0?100:20}},t.prototype._updateRangeUse=function(e){var t=this._rangePropMode,n=this.get(`rangeMode`);G([[`start`,`startValue`],[`end`,`endValue`]],function(r,i){var a=e[r[0]]!=null,o=e[r[1]]!=null;a&&!o?t[i]=`percent`:!a&&o?t[i]=`value`:n?t[i]=n[i]:a&&(t[i]=`percent`)})},t.prototype.noTarget=function(){return this._noTarget},t.prototype.getFirstTargetAxisModel=function(){var e;return this.eachTargetAxis(function(t,n){e??=this.ecModel.getComponent(cW(t),n)},this),e},t.prototype.eachTargetAxis=function(e,t){this._targetAxisInfoMap.each(function(n,r){G(n.indexList,function(n){e.call(t,r,n)})})},t.prototype.getAxisProxy=function(e,t){return fW(this.getAxisModel(e,t))},t.prototype.getAxisModel=function(e,t){var n=this._targetAxisInfoMap.get(e);if(n&&n.indexMap[t])return this.ecModel.getComponent(cW(e),t)},t.prototype.setRawRange=function(e){var t=this.option,n=this.settledOption;G([[`start`,`startValue`],[`end`,`endValue`]],function(r){(e[r[0]]!=null||e[r[1]]!=null)&&(t[r[0]]=n[r[0]]=e[r[0]],t[r[1]]=n[r[1]]=e[r[1]])},this),this._updateRangeUse(e)},t.prototype.setCalculatedRange=function(e){var t=this.option;G([`start`,`startValue`,`end`,`endValue`],function(n){t[n]=e[n]})},t.prototype.getPercentRange=function(){var e=this.findRepresentativeAxisProxy();if(e)return e.getWindow().percent},t.prototype.getValueRange=function(e,t){if(e==null&&t==null){var n=this.findRepresentativeAxisProxy();if(n)return n.getWindow().value}else return this.getAxisProxy(e,t).getWindow().value},t.prototype.findRepresentativeAxisProxy=function(e){if(e)return fW(e);for(var t,n=this._targetAxisInfoMap.keys(),r=0;ra[1];if(u&&!d&&!f)return!0;u&&(i=!0),d&&(t=!0),f&&(n=!0)}return i&&t&&n})}else G(r,function(n){if(i===`empty`)e.setData(t=t.map(n,function(e){return o(e)?e:NaN}));else{var r={};r[n]=a,t.selectRange(r)}});G(r,function(e){t.setApproximateExtent(a,e)})}});function o(e){return e>=a[0]&&e<=a[1]}},e.prototype._updateMinMaxSpan=function(){var e=this._minMaxSpan={},t=this._dataZoomModel,n=this._extent;G([`min`,`max`],function(r){var i=t.get(r+`Span`),a=t.get(r+`ValueSpan`);a!=null&&(a=this.getAxisModel().axis.scale.parse(a)),a==null?i!=null&&(a=Ys(i,[0,100],n,!0)-n[0]):i=Ys(n[0]+a,n,[0,100],!0),e[r+`Span`]=i,e[r+`ValueSpan`]=a},this)},e}(),SW={dirtyOnOverallProgress:!0,getTargetSeries:function(e){function t(t){e.eachComponent(`dataZoom`,function(n){n.eachTargetAxis(function(r,i){t(r,i,e.getComponent(cW(r),i),n)})})}var n=[];t(function(t,r,i,a){if(!fW(i)){var o=new xW(t,r,a,e);n.push(o),pW(i,o)}});var r=Es();return G(n,function(e){G(e.getTargetSeriesModels(),function(e){r.set(e.uid,e)})}),r},overallReset:function(e,t){e.eachComponent(`dataZoom`,function(e){var n=[];e.eachTargetAxis(function(t,r){var i=e.getAxisProxy(t,r),a=mW(e,i);a?n.push([i,a]):i.reset(e,null)}),G(n,function(t){t[0].reset(e,t[1].getWindow().percentInverted)}),e.eachTargetAxis(function(n,r){e.getAxisProxy(n,r).filterData(e,t)})}),e.eachComponent(`dataZoom`,function(e){var t=e.findRepresentativeAxisProxy();if(t){var n=t.getWindow(),r=n.percent,i=n.value;e.setCalculatedRange({start:r[0],end:r[1],startValue:i[0],endValue:i[1]})}})}};function CW(e){e.registerAction(`dataZoom`,function(e,t){G(lW(t,e),function(t){t.setRawRange({start:e.start,end:e.end,startValue:e.startValue,endValue:e.endValue})})})}var wW=yl();function TW(e){wW(e,function(){e.registerProcessor(e.PRIORITY.PROCESSOR.FILTER,SW),CW(e),e.registerSubTypeDefaulter(`dataZoom`,function(){return`slider`})})}function EW(e){e.registerComponentModel(vW),e.registerComponentView(bW),TW(e)}var DW=function(){function e(){}return e}(),OW={};function kW(e,t){OW[e]=t}function AW(e){return OW[e]}var jW=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.init=function(t,n,r){var i=r.getTheme().get(`toolbox`),a=i?i.feature:null;a&&(this._themeFeatureOption=W({},a),i.feature={}),e.prototype.init.call(this,t,n,r),a&&(i.feature=a)},t.prototype.optionUpdated=function(){G(this.option.feature,function(e,t){var n=this._themeFeatureOption,r=AW(t);r&&(r.getDefaultOption&&(r.defaultOption=r.getDefaultOption(this.ecModel)),n&&n[t]&&(Uo(e,n[t]),n[t]=null),Uo(e,r.defaultOption))},this)},t.type=`toolbox`,t.layoutMode={type:`box`,ignoreSize:!0},t.defaultOption={show:!0,z:6,orient:`horizontal`,left:`right`,top:`top`,backgroundColor:`transparent`,borderColor:Q.color.border,borderRadius:0,borderWidth:0,padding:Q.size.m,itemSize:15,itemGap:Q.size.s,showTitle:!0,iconStyle:{borderColor:Q.color.accent50,color:`none`},emphasis:{iconStyle:{borderColor:Q.color.accent70}},tooltip:{show:!1,position:`bottom`}},t}(Yx);function MW(e,t){var n=vx(t.get(`padding`)),r=t.getItemStyle([`color`,`opacity`]);return r.fill=t.get(`backgroundColor`),new fh({shape:{x:e.x-n[3],y:e.y-n[0],width:e.width+n[1]+n[3],height:e.height+n[0]+n[2],r:t.get(`borderRadius`)},style:r,silent:!0,z2:-1})}var NW=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.render=function(e,t,n,r){var i=this.group;if(i.removeAll(),!e.get(`show`))return;var a=+e.get(`itemSize`),o=e.get(`orient`)===`vertical`,s=e.get(`feature`)||{},c=this._features||=Es(),l=[];G(s,function(e,t){l.push(t)}),new cw(this._featureNames||[],l).add(u).update(u).remove(ns(u,null)).execute(),this._featureNames=Qo(l,function(e){return c.hasKey(e)});function u(i,a){var o=i!=null&&a==null,u=i!=null&&a!=null,f=i==null,p=o||u?l[i]:l[a],m=s[p],h=o||u?new Zy(m,e,t):null,g=h&&h.get(`show`),_;if(o){if(!g)return;if(PW(p))_={onclick:h.option.onclick,featureName:p};else{var v=AW(p);if(!v)return;_=new v}c.set(p,_)}else _=c.get(p);if(f||!g){FW(_)&&_.dispose&&_.dispose(t,n),c.removeKey(p);return}r&&r.newTitle!=null&&r.featureName===p&&(m.title=r.newTitle),o&&(_.uid=$y(`toolbox-feature`)),_.model=h,_.ecModel=t,_.api=n,d(h,_,p),h.setIconStatus=function(e,t){var n=this.option,r=this.iconPaths;n.iconStatus=n.iconStatus||{},n.iconStatus[e]=t,r[e]&&(t===`emphasis`?xg:Sg)(r[e])},FW(_)&&_.render&&_.render(h,t,n,r)}function d(r,s,c){var l=r.getModel(`iconStyle`),u=r.getModel([`emphasis`,`iconStyle`]),d=s instanceof DW&&s.getIcons?s.getIcons():r.get(`icon`),f=r.get(`title`)||{},p,m;Y(d)?(p={},p[c]=d):p=d,Y(f)?(m={},m[c]=f):m=f;var h=r.iconPaths={};G(p,function(c,d){var f=ey(c,{},{x:-a/2,y:-a/2,width:a,height:a});f.setStyle(l.getItemStyle());var p=f.ensureState(`emphasis`);p.style=u.getItemStyle();var g=new _h({style:{text:m[d],align:u.get(`textAlign`),borderRadius:u.get(`textBorderRadius`),padding:u.get(`textPadding`),fill:null,font:Iy({fontStyle:u.get(`textFontStyle`),fontFamily:u.get(`textFontFamily`),fontSize:u.get(`textFontSize`),fontWeight:u.get(`textFontWeight`)},t)},ignore:!0});f.setTextContent(g),cy({el:f,componentModel:e,itemName:d,formatterParamsExtra:{title:m[d]}}),f.__title=m[d],f.on(`mouseover`,function(){var t=u.getItemStyle(),r=o?e.get(`right`)==null&&e.get(`left`)!==`right`?`right`:`left`:e.get(`bottom`)==null&&e.get(`top`)!==`bottom`?`bottom`:`top`;g.setStyle({fill:u.get(`textFill`)||t.fill||t.stroke||Q.color.neutral99,backgroundColor:u.get(`textBackgroundColor`)}),f.setTextConfig({position:u.get(`textPosition`)||r}),g.ignore=!e.get(`showTitle`),n.enterEmphasis(this)}).on(`mouseout`,function(){r.get([`iconStatus`,d])!==`emphasis`&&n.leaveEmphasis(this),g.hide()}),(r.get([`iconStatus`,d])===`emphasis`?xg:Sg)(f),i.add(f),f.on(`click`,q(s.onclick,s,t,n,d)),h[d]=f})}var f=Hx(e,n).refContainer,p=e.getBoxLayoutParams(),m=e.get(`padding`),h=Bx(p,f,m);Rx(e.get(`orient`),i,e.get(`itemGap`),h.width,h.height),Ux(i,p,f,m),i.add(MW(i.getBoundingRect(),e)),o||i.eachChild(function(e){var t=e.__title,r=e.ensureState(`emphasis`),o=r.textConfig||={},s=e.getTextContent(),c=s&&s.ensureState(`emphasis`);if(c&&!rs(c)&&t){var l=c.style||={},u=id(t,_h.makeFont(l)),d=e.x+i.x,f=e.y+i.y+a,p=!1;f+u.height>n.getHeight()&&(o.position=`top`,p=!0);var m=p?-5-u.height:a+10;d+u.width/2>n.getWidth()?(o.position=[`100%`,m],l.align=`right`):d-u.width/2<0&&(o.position=[0,m],l.align=`left`)}})},t.prototype.updateView=function(e,t,n,r){G(this._features,function(e){e&&e instanceof DW&&e.updateView&&e.updateView(e.model,t,n,r)})},t.prototype.dispose=function(e,t){G(this._features,function(n){n&&n instanceof DW&&n.dispose&&n.dispose(e,t)})},t.type=`toolbox`,t}(Wj);function PW(e){return e.indexOf(`my`)===0}function FW(e){return e instanceof DW}var IW=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onclick=function(e,t){var n=this.model,r=n.get(`name`)||e.get(`title.0.text`)||`echarts`,i=t.getZr().painter.getType()===`svg`,a=i?`svg`:n.get(`type`,!0)||`png`,o=t.getConnectedDataURL({type:a,backgroundColor:n.get(`backgroundColor`,!0)||e.get(`backgroundColor`)||Q.color.neutral00,connectedBackgroundColor:n.get(`connectedBackgroundColor`),excludeComponents:n.get(`excludeComponents`),pixelRatio:n.get(`pixelRatio`)}),s=Ns.browser;if(typeof MouseEvent==`function`&&(s.newEdge||!s.ie&&!s.edge)){var c=document.createElement(`a`);c.download=r+`.`+a,c.target=`_blank`,c.href=o;var l=new MouseEvent(`click`,{view:document.defaultView,bubbles:!0,cancelable:!1});c.dispatchEvent(l)}else if(window.navigator.msSaveOrOpenBlob||i){var u=o.split(`,`),d=u[0].indexOf(`base64`)>-1,f=i?decodeURIComponent(u[1]):u[1];d&&(f=window.atob(f));var p=r+`.`+a;if(window.navigator.msSaveOrOpenBlob){for(var m=f.length,h=new Uint8Array(m);m--;)h[m]=f.charCodeAt(m);var g=new Blob([h]);window.navigator.msSaveOrOpenBlob(g,p)}else{var _=document.createElement(`iframe`);document.body.appendChild(_);var v=_.contentWindow,y=v.document;y.open(`image/svg+xml`,`replace`),y.write(f),y.close(),v.focus(),y.execCommand(`SaveAs`,!0,p),document.body.removeChild(_)}}else{var b=n.get(`lang`),x=``,S=window.open();S.document.write(x),S.document.title=r}},t.getDefaultOption=function(e){return{show:!0,icon:`M4.7,22.9L29.3,45.5L54.7,23.4M4.6,43.6L4.6,58L53.8,58L53.8,43.6M29.2,45.1L29.2,0`,title:e.getLocaleModel().get([`toolbox`,`saveAsImage`,`title`]),type:`png`,connectedBackgroundColor:Q.color.neutral00,name:``,excludeComponents:[`toolbox`],lang:e.getLocaleModel().get([`toolbox`,`saveAsImage`,`lang`])}},t}(DW),LW=`__ec_magicType_stack__`,RW=[[`line`,`bar`],[`stack`]],zW=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.getIcons=function(){var e=this.model,t=e.get(`icon`),n={};return G(e.get(`type`),function(e){t[e]&&(n[e]=t[e])}),n},t.getDefaultOption=function(e){return{show:!0,type:[],icon:{line:`M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4`,bar:`M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7`,stack:`M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z`},title:e.getLocaleModel().get([`toolbox`,`magicType`,`title`]),option:{},seriesIndex:{}}},t.prototype.onclick=function(e,t,n){var r=this.model,i=r.get([`seriesIndex`,n]);if(BW[n]){var a={series:[]};G(RW,function(e){qo(e,n)>=0&&G(e,function(e){r.setIconStatus(e,`normal`)})}),r.setIconStatus(n,`emphasis`),e.eachComponent({mainType:`series`,query:i==null?null:{seriesIndex:i}},function(e){var t=e.subType,i=e.id,o=BW[n](t,i,e,r);o&&(Ko(o,e.option),a.series.push(o));var s=e.coordinateSystem;if(s&&s.type===`cartesian2d`&&(n===`line`||n===`bar`)){var c=s.getAxesByScale(`ordinal`)[0];if(c){var l=c.dim+`Axis`,u=e.getReferringComponents(l,nl).models[0].componentIndex;a[l]=a[l]||[];for(var d=0;d<=u;d++)a[l][u]=a[l][u]||{};a[l][u].boundaryGap=n===`bar`}}});var o,s=n;n===`stack`&&(o=Uo({stack:r.option.title.tiled,tiled:r.option.title.stack},r.option.title),r.get([`iconStatus`,n])!==`emphasis`&&(s=`tiled`)),t.dispatchAction({type:`changeMagicType`,currentType:s,newOption:a,newTitle:o,featureName:`magicType`})}},t}(DW),BW={line:function(e,t,n,r){if(e===`bar`)return Uo({id:t,type:`line`,data:n.get(`data`),stack:n.get(`stack`),markPoint:n.get(`markPoint`),markLine:n.get(`markLine`)},r.get([`option`,`line`])||{},!0)},bar:function(e,t,n,r){if(e===`line`)return Uo({id:t,type:`bar`,data:n.get(`data`),stack:n.get(`stack`),markPoint:n.get(`markPoint`),markLine:n.get(`markLine`)},r.get([`option`,`bar`])||{},!0)},stack:function(e,t,n,r){var i=n.get(`stack`)===LW;if(e===`line`||e===`bar`)return r.setIconStatus(`stack`,i?`normal`:`emphasis`),Uo({id:t,stack:i?``:LW},r.get([`option`,`stack`])||{},!0)}};bF({type:`changeMagicType`,event:`magicTypeChanged`,update:`prepareAndUpdate`},function(e,t){t.mergeOption(e.newOption)});var VW=Array(60).join(`-`),HW=` `;function UW(e){var t={},n=[],r=[];return e.eachRawSeries(function(e){var i=e.coordinateSystem;if(i&&(i.type===`cartesian2d`||i.type===`polar`)){var a=i.getBaseAxis();if(a.type===`category`){var o=zO(a);t[o]||(t[o]={categoryAxis:a,valueAxis:i.getOtherAxis(a),series:[]},r.push({axisDim:a.dim,axisIndex:a.index})),t[o].series.push(e)}else n.push(e)}else n.push(e)}),{seriesGroupByCategoryAxis:t,other:n,meta:r}}function WW(e){var t=[];return G(e,function(e,n){var r=e.categoryAxis,i=e.valueAxis.dim,a=[` `].concat(K(e.series,function(e){return e.name})),o=[r.model.getCategories()];G(e.series,function(e){var t=e.getRawData();o.push(e.getRawData().mapArray(t.mapDimension(i),function(e){return e}))});for(var s=[a.join(HW)],c=0;c1||n>0&&!e.noHeader;return G(e.blocks,function(e){var n=PC(e);n>=t&&(t=n+ +(r&&(!n||MC(e)&&!e.noHeader)))}),t}return 0}function FC(e,t,n,r){var i=t.noHeader,a=RC(PC(t)),o=[],s=t.blocks||[];_s(!s||J(s)),s||=[];var c=e.orderMode;if(t.sortBlocks&&c){s=s.slice();var l={valueAsc:`asc`,valueDesc:`desc`};if(Z(l,c)){var u=new XS(l[c],null);s.sort(function(e,t){return u.evaluate(e.sortParam,t.sortParam)})}else c===`seriesDesc`&&s.reverse()}G(s,function(n,i){var s=t.valueFormatter,c=NC(n)(s?W(W({},e),{valueFormatter:s}):e,n,i>0?a.html:0,r);c!=null&&o.push(c)});var d=e.renderMode===`richText`?o.join(a.richText):zC(r,o.join(``),i?n:a.html);if(i)return d;var f=yx(t.header,`ordinal`,e.useUTC),p=OC(r,e.renderMode).nameStyle,m=DC(r);return e.renderMode===`richText`?HC(e,f,p)+a.richText+d:zC(r,`
`+gb(f)+`
`+d,n)}function IC(e,t,n,r){var i=e.renderMode,a=t.noName,o=t.noValue,s=!t.markerType,c=t.name,l=e.useUTC,u=t.valueFormatter||e.valueFormatter||function(e){return e=J(e)?e:[e],K(e,function(e,t){return yx(e,J(p)?p[t]:p,l)})};if(!(a&&o)){var d=s?``:e.markupStyleCreator.makeTooltipMarker(t.markerType,t.markerColor||Q.color.secondary,i),f=a?``:yx(c,`ordinal`,l),p=t.valueType,m=o?[]:u(t.value,t.rawDataIndex),h=!s||!a,g=!s&&a,_=OC(r,i),v=_.nameStyle,y=_.valueStyle;return i===`richText`?(s?``:d)+(a?``:HC(e,f,v))+(o?``:UC(e,m,h,g,y)):zC(r,(s?``:d)+(a?``:BC(f,!s,v))+(o?``:VC(m,h,g,y)),n)}}function LC(e,t,n,r,i,a){if(e)return NC(e)({useUTC:i,renderMode:n,orderMode:r,markupStyleCreator:t,valueFormatter:e.valueFormatter},e,0,a)}function RC(e){return{html:kC[e],richText:AC[e]}}function zC(e,t,n){var r=`
`,i=`margin: `+n+`px 0 0`,a=DC(e);return`
`+t+r+`
`}function BC(e,t,n){var r=t?`margin-left:2px`:``;return``+gb(e)+``}function VC(e,t,n,r){var i=t?`float:right;margin-left:`+(n?`10px`:`20px`):``;return e=J(e)?e:[e],``+K(e,function(e){return gb(e)}).join(`  `)+``}function HC(e,t,n){return e.markupStyleCreator.wrapRichTextStyle(t,n)}function UC(e,t,n,r,i){var a=[i],o=r?10:20;return n&&a.push({padding:[0,0,0,o],align:`right`}),e.markupStyleCreator.wrapRichTextStyle(J(t)?t.join(` `):t,a)}function WC(e,t){var n=e.getData().getItemVisual(t,`style`)[e.visualDrawType];return Tx(n)}function GC(e,t){return e.get(`padding`)??(t===`richText`?[8,10]:10)}var KC=function(){function e(){this.richTextStyles={},this._nextStyleNameId=_c()}return e.prototype._generateStyleName=function(){return`__EC_aUTo_`+this._nextStyleNameId++},e.prototype.makeTooltipMarker=function(e,t,n){var r=n===`richText`?this._generateStyleName():null,i=Cx({color:t,type:e,renderMode:n,markerId:r});return Y(i)?i:(this.richTextStyles[r]=i.style,i.content)},e.prototype.wrapRichTextStyle=function(e,t){var n={};J(t)?G(t,function(e){return W(n,e)}):W(n,t);var r=this._generateStyleName();return this.richTextStyles[r]=n,`{`+r+`|`+e+`}`},e}();function qC(e){var t=e.series,n=e.dataIndex,r=e.multipleSeries,i=t.getData(),a=i.mapDimensionsAll(`defaultedTooltip`),o=a.length,s=t.getRawValue(n),c=J(s),l=WC(t,n),u,d,f,p;if(o>1||c&&!o){var m=JC(s,t,n,a,l);u=m.inlineValues,d=m.inlineValueTypes,f=m.blocks,p=m.inlineValues[0]}else if(o){var h=i.getDimensionInfo(a[0]);p=u=VS(i,n,a[0]),d=h.type}else p=u=c?s[0]:s;var g=Gc(t),_=g&&t.name||``,v=i.getName(n),y=r?_:v;return jC(`section`,{header:_,noHeader:r||!g,sortParam:p,blocks:[jC(`nameValue`,{markerType:`item`,markerColor:l,name:y,noName:!vs(y),value:u,valueType:d,rawDataIndex:i.getRawIndex(n)})].concat(f||[])})}function JC(e,t,n,r,i){var a=t.getData(),o=Zo(e,function(e,t,n){var r=a.getDimensionInfo(n);return e||=r&&r.tooltip!==!1&&r.displayName!=null},!1),s=[],c=[],l=[];r.length?G(r,function(e){u(VS(a,n,e),e)}):G(e,u);function u(e,t){var n=a.getDimensionInfo(t);n&&n.otherDims.tooltip!==!1&&(o?l.push(jC(`nameValue`,{markerType:`subItem`,markerColor:i,name:n.displayName,value:e,valueType:n.type})):(s.push(e),c.push(n.type)))}return{inlineValues:s,inlineValueTypes:c,blocks:l}}var YC=Qc();function XC(e,t){return e.getName(t)||e.getId(t)}var ZC=function(e){U(t,e);function t(){var t=e!==null&&e.apply(this,arguments)||this;return t._selectedDataIndicesMap={},t}return t.prototype.init=function(e,t,n){this.seriesIndex=this.componentIndex,this.dataTask=GS({count:ew,reset:tw}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(e,n),(YC(this).sourceManager=new bC(this)).prepareSource();var r=this.getInitialData(e,n);rw(r,this),this.dataTask.context.data=r,YC(this).dataBeforeProcessed=r,QC(this),this._initSelectedMapFromData(r)},t.prototype.mergeDefaultAndTheme=function(e,t){var n=Wx(this),r=n?Kx(e):{},i=this.subType;Yx.hasClass(i)&&(i+=`Series`),Uo(e,t.getTheme().get(this.subType)),Uo(e,this.getDefaultOption()),jc(e,`label`,[`show`]),this.fillDataTextStyle(e.data),n&&Gx(e,r,n)},t.prototype.mergeOption=function(e,t){e=Uo(this.option,e,!0),this.fillDataTextStyle(e.data);var n=Wx(this);n&&Gx(this.option,e,n);var r=YC(this).sourceManager;r.dirty(),r.prepareSource();var i=this.getInitialData(e,t);rw(i,this),this.dataTask.dirty(),this.dataTask.context.data=i,YC(this).dataBeforeProcessed=i,QC(this),this._initSelectedMapFromData(i)},t.prototype.fillDataTextStyle=function(e){if(e&&!cs(e))for(var t=[`show`],n=0;n=0&&u<0)&&(l=v,u=_,d=0),_===u&&(c[d++]=m))}return c.length=d,c},t.prototype.formatTooltip=function(e,t,n){return qC({series:this,dataIndex:e,multipleSeries:t})},t.prototype.isAnimationEnabled=function(){var e=this.ecModel;if(Ns.node&&!(e&&e.ssr))return!1;var t=this.getShallow(`animation`);return t&&this.getData().count()>this.getShallow(`animationThreshold`)&&(t=!1),!!t},t.prototype.restoreData=function(){this.dataTask.dirty()},t.prototype.getColorFromPalette=function(e,t,n){var r=this.ecModel,i=$x.prototype.getColorFromPalette.call(this,e,t,n);return i||=r.getColorFromPalette(e,t,n),i},t.prototype.coordDimToDataDim=function(e){return this.getRawData().mapDimensionsAll(e)},t.prototype.getProgressive=function(){return this.get(`progressive`)},t.prototype.getProgressiveThreshold=function(){return this.get(`progressiveThreshold`)},t.prototype.select=function(e,t){this._innerSelect(this.getData(t),e)},t.prototype.unselect=function(e,t){var n=this.option.selectedMap;if(n){var r=this.option.selectedMode,i=this.getData(t);if(r===`series`||n===`all`){this.option.selectedMap={},this._selectedDataIndicesMap={};return}for(var a=0;a=0&&n.push(i)}return n},t.prototype.isSelected=function(e,t){var n=this.option.selectedMap;if(!n)return!1;var r=this.getData(t);return(n===`all`||n[XC(r,e)])&&!r.getItemModel(e).get([`select`,`disabled`])},t.prototype.isUniversalTransitionEnabled=function(){if(this.__universalTransitionEnabled)return!0;var e=this.option.universalTransition;return e?e===!0||e&&e.enabled:!1},t.prototype._innerSelect=function(e,t){var n,r,i=this.option,a=i.selectedMode,o=t.length;if(a&&o){if(a===`series`)i.selectedMap=`all`;else if(a===`multiple`){os(i.selectedMap)||(i.selectedMap={});for(var s=i.selectedMap,c=0;c0&&this._innerSelect(e,t)}},t.registerClass=function(e){return Yx.registerClass(e)},t.protoInitialize=function(){var e=t.prototype;e.type=`series.__base__`,e.seriesIndex=0,e.ignoreStyleOnData=!1,e.hasSymbolVisual=!1,e.defaultSymbol=`circle`,e.visualStyleAccessPath=`itemStyle`,e.visualDrawType=`fill`}(),t}(Yx);Yo(ZC,US),Yo(ZC,$x),Fl(ZC,Yx);function QC(e){var t=e.name;Gc(e)||(e.name=$C(e)||t)}function $C(e){var t=e.getRawData(),n=t.mapDimensionsAll(`seriesName`),r=[];return G(n,function(e){var n=t.getDimensionInfo(e);n.displayName&&r.push(n.displayName)}),r.join(` `)}function ew(e){return e.model.getRawData().count()}function tw(e){var t=e.model;return t.setData(t.getRawData().cloneShallow()),nw}function nw(e,t){t.outputData&&e.end>t.outputData.count()&&t.model.getRawData().cloneShallow(t.outputData)}function rw(e,t){G(Ds(e.CHANGABLE_METHODS,e.DOWNSAMPLE_METHODS),function(n){e.wrapMethod(n,ns(iw,t))})}function iw(e,t){var n=aw(e);return n&&n.setOutputEnd((t||this).count()),t}function aw(e){var t=(e.ecModel||{}).scheduler,n=t&&t.getPipeline(e.uid);if(n){var r=n.currentTask;if(r){var i=r.agentStubMap;i&&(r=i.get(e.uid))}return r}}function ow(e){return e==null?0:e.length||1}function sw(e){return e}var cw=function(){function e(e,t,n,r,i,a){this._old=e,this._new=t,this._oldKeyGetter=n||sw,this._newKeyGetter=r||sw,this.context=i,this._diffModeMultiple=a===`multiple`}return e.prototype.add=function(e){return this._add=e,this},e.prototype.update=function(e){return this._update=e,this},e.prototype.updateManyToOne=function(e){return this._updateManyToOne=e,this},e.prototype.updateOneToMany=function(e){return this._updateOneToMany=e,this},e.prototype.updateManyToMany=function(e){return this._updateManyToMany=e,this},e.prototype.remove=function(e){return this._remove=e,this},e.prototype.execute=function(){this[this._diffModeMultiple?`_executeMultiple`:`_executeOneToOne`]()},e.prototype._executeOneToOne=function(){var e=this._old,t=this._new,n={},r=Array(e.length),i=Array(t.length);this._initIndexMap(e,null,r,`_oldKeyGetter`),this._initIndexMap(t,n,i,`_newKeyGetter`);for(var a=0;a1){var l=s.shift();s.length===1&&(n[o]=s[0]),this._update&&this._update(l,a)}else c===1?(n[o]=null,this._update&&this._update(s,a)):this._remove&&this._remove(a)}this._performRestAdd(i,n)},e.prototype._executeMultiple=function(){var e=this._old,t=this._new,n={},r={},i=[],a=[];this._initIndexMap(e,n,i,`_oldKeyGetter`),this._initIndexMap(t,r,a,`_newKeyGetter`);for(var o=0;o1&&d===1)this._updateManyToOne&&this._updateManyToOne(l,c),r[s]=null;else if(u===1&&d>1)this._updateOneToMany&&this._updateOneToMany(l,c),r[s]=null;else if(u===1&&d===1)this._update&&this._update(l,c),r[s]=null;else if(u>1&&d>1)this._updateManyToMany&&this._updateManyToMany(l,c),r[s]=null;else if(u>1)for(var f=0;f1)for(var o=0;oi&&(i+=lw);var p=Math.atan2(s,o);if(p<0&&(p+=lw),p>=r&&p<=i||p+lw>=r&&p+lw<=i)return c[0]=u,c[1]=d,l-n;var m=n*Math.cos(r)+e,h=n*Math.sin(r)+t,g=n*Math.cos(i)+e,_=n*Math.sin(i)+t,v=(m-o)*(m-o)+(h-s)*(h-s),y=(g-o)*(g-o)+(_-s)*(_-s);return v0){t=t/180*Math.PI,yw.fromArray(e[0]),bw.fromArray(e[1]),xw.fromArray(e[2]),wu.sub(Sw,yw,bw),wu.sub(Cw,xw,bw);var n=Sw.len(),r=Cw.len();if(!(n<.001||r<.001)){Sw.scale(1/n),Cw.scale(1/r);var i=Sw.dot(Cw);if(Math.cos(t)1&&wu.copy(Ew,xw),Ew.toArray(e[1])}}}}function Ow(e,t,n,r){var i=n===`normal`,a=i?e:e.ensureState(n);a.ignore=t;var o=r.get(`smooth`);o=o===!0?.3:Math.max(+o,0)||0,a.shape=a.shape||{},a.shape.smooth=o;var s=r.getModel(`lineStyle`).getLineStyle();i?e.useStyle(s):a.style=s}function kw(e,t){var n=t.smooth,r=t.points;if(r){if(e.moveTo(r[0][0],r[0][1]),n>0&&r.length>=3){var i=_u(r[0],r[1]),a=_u(r[1],r[2]);if(!i||!a){e.lineTo(r[1][0],r[1][1]),e.lineTo(r[2][0],r[2][1]);return}var o=Math.min(i,a)*n,s=bu([],r[1],r[0],o/i),c=bu([],r[1],r[2],o/a),l=bu([],s,c,.5);e.bezierCurveTo(s[0],s[1],s[0],s[1],l[0],l[1]),e.bezierCurveTo(c[0],c[1],c[0],c[1],r[2][0],r[2][1])}else for(var u=1;u0&&i&&S(-d/a,0,a);var g=e[0],_=e[a-1],v,y;b(),v<0&&C(-v,.8),y<0&&C(y,.8),b(),x(v,y,1),x(y,v,-1),b(),v<0&&w(-v),y<0&&w(y);function b(){v=g.rect[o]-n,y=r-_.rect[o]-_.rect[s]}function x(e,t,n){if(e<0){var r=Math.min(t,-e);if(r>0){S(r*n,0,a);var i=r+e;i<0&&C(-i*n,1)}else C(-e*n,1)}}function S(t,n,r){t!==0&&(u=!0);for(var i=n;i0)for(var c=0;c0;c--){var f=r[c-1]*d;S(-f,c,a)}}}function w(e){var t=e<0?-1:1;e=Math.abs(e);for(var n=Math.ceil(e/(a-1)),r=0;r0?S(n,0,r+1):S(-n,a-r-1,a),e-=n,e<=0)return}return u}function Kw(e){for(var t=0;t=0&&n.attr(i.oldLayoutSelect),qo(u,`emphasis`)>=0&&n.attr(i.oldLayoutEmphasis)),Sv(n,c,t,s)}else if(n.attr(c),!Ly(n).valueAnimation){var d=X(n.style.opacity,1);n.style.opacity=0,Cv(n,{style:{opacity:d}},t,s)}if(i.oldLayout=c,n.states.select){var f=i.oldLayoutSelect={};tT(f,c,nT),tT(f,n.states.select,nT)}if(n.states.emphasis){var p=i.oldLayoutEmphasis={};tT(p,c,nT),tT(p,n.states.emphasis,nT)}zy(n,s,l,t,t)}if(r&&!r.ignore&&!r.invisible){var i=eT(r),a=i.oldLayout,m={points:r.shape.points};a?(r.attr({shape:a}),Sv(r,{shape:m},t)):(r.setShape(m),r.style.strokePercent=0,Cv(r,{style:{strokePercent:1}},t)),i.oldLayout=m}},e}(),iT=Qc();function aT(e){e.registerUpdateLifecycle(`series:beforeupdate`,function(e,t,n){var r=iT(t).labelManager;r||=iT(t).labelManager=new rT,r.clearLabels()}),e.registerUpdateLifecycle(`series:layoutlabels`,function(e,t,n){var r=iT(t).labelManager;G(n.updatedSeries,function(e){r.addLabelsOfSeries(t.getViewOfSeriesModel(e))}),r.updateLayoutConfig(t),r.layout(t),r.processLabelsOverall()})}var oT=es({needTransform:1,normalize:1,scale:1,transformIn:1,transformOut:1,contain:1,getExtent:1,getExtentUnsafe:1,setExtent:1,setExtent2:1,getFilter:1,sanitize:1,getDefaultStartValue:1,freeze:1});function sT(e,t,n){var r;e||={};var i=Ab();if(i){var a=i.createBreakScaleMapper(t,n);a.hasBreaks()&&(G(oT,function(t){a[t]&&(e[t]=q(a[t],a))}),r=a)}return r??mT(e,n),{brk:r,mapper:e}}function cT(e,t){G(oT,function(n){e[n]=t[n]})}function lT(e,t){e.freeze=As}function uT(e){return e.getExtentUnsafe(0,2)}function dT(e,t){return e.getExtentUnsafe(1,t)||e.getExtentUnsafe(0,t)}function fT(e){var t=dT(e,3);return t[1]-t[0]}function pT(e){var t=e.getExtentUnsafe(0,3);return t[1]-t[0]}function mT(e,t){var n=e||{},r=[];return n._extents=r,r[0]=t?t.slice():ul(),W(n,hT),n}var hT={needTransform:function(){return!1},normalize:function(e){var t=this._extents[1]||this._extents[0];return t[1]===t[0]?.5:(e-t[0])/(t[1]-t[0])},scale:function(e){var t=this._extents[1]||this._extents[0];return e*(t[1]-t[0])+t[0]},transformIn:function(e){return e},transformOut:function(e){return e},contain:function(e){var t=dT(this,null);return e>=t[0]&&e<=t[1]},getExtent:function(){return this._extents[0].slice()},getExtentUnsafe:function(e){return this._extents[e]},setExtent:function(e,t){gT(this._extents,0,e,t)},setExtent2:function(e,t,n){var r=this._extents;r[e]||(r[e]=r[0].slice()),gT(r,e,t,n)},freeze:function(){}};function gT(e,t,n,r){gl(n,r)&&(e[t][0]=n,e[t][1]=r)}var _T=`expandAxisBreak`,vT=null;function yT(){return vT}var bT=function(){function e(){}return e.prototype.isBlank=function(){return this._isBlank},e.prototype.setBlank=function(e){this._isBlank=e},e}();Bl(bT);var xT=0,ST=function(){function e(e){this.categories=e.categories||[],this._needCollect=e.needCollect,this._deduplication=e.deduplication,this.uid=++xT,this._onCollect=e.onCollect}return e.createByAxisModel=function(t){var n=t.option,r=n.data,i=r&&K(r,CT);return new e({categories:i,needCollect:!i,deduplication:n.dedplication!==!1})},e.prototype.getOrdinal=function(e){return this._getOrCreateMap().get(e)},e.prototype.parseAndCollect=function(e){var t,n=this._needCollect;if(!Y(e)&&!n)return e;if(n&&!this._deduplication)return t=this.categories.length,this.categories[t]=e,this._onCollect&&this._onCollect(e,t),t;var r=this._getOrCreateMap();return t=r.get(e),t??(n?(t=this.categories.length,this.categories[t]=e,r.set(e,t),this._onCollect&&this._onCollect(e,t)):t=NaN),t},e.prototype._getOrCreateMap=function(){return this._map||=Es(this.categories)},e}();function CT(e){return os(e)&&e.value!=null?e.value:e+``}function wT(e){return TT(e)||DT(e)}function TT(e){return e.type===`interval`}function ET(e){return e.type===`time`}function DT(e){return e.type===`log`}function OT(e){return e.type===`ordinal`}function kT(e){var t=fc(e),n=Ws(10,t),r=Vs(e/n);return r?r===2?r=3:r===3?r=5:r*=2:r=1,ec(r*n,-t)}function AT(e){return nc(e)+2}function jT(e,t){return Gs(e)/Gs(t)}function MT(e,t,n){var r=n&&n.lookup;if(r){for(var i=0;i1&&a/o>2&&(i=Math.round(Math.ceil(i/o)*o)),i!==r[0]&&c(r[0],!0,!0);for(var s=i;s<=r[1];s+=o)c(s,!1,s===r[0]||s===r[1]);s-o!==r[1]&&c(r[1],!0,!0);function c(e,t,r){n({value:e,offInterval:t},r)}}var LT=function(e){U(t,e);function t(n){var r=e.call(this)||this;r.type=`ordinal`,r.parse=t.parse,cT(r,t.decoratedMethods);var i=n.ordinalMeta;i||=new ST({}),J(i)&&(i=new ST({categories:K(i,function(e){return os(e)?e.value:e})})),r._ordinalMeta=i;var a=sT(null,null,n.extent||[0,i.categories.length-1]);return r._mapper=a.mapper,lT(r,a.mapper),r}return t.parse=function(e){return e==null?e=NaN:Y(e)?(e=this._ordinalMeta.getOrdinal(e),e??=NaN):e=Vs(e),e},t.prototype.getTicks=function(){var e=[];return IT(this,0,function(t){e.push(t)}),e},t.prototype.getMinorTicks=function(e){},t.prototype.setSortInfo=function(e){if(e==null){this._ordinalNumbersByTick=this._ticksByOrdinalNumber=null;return}for(var t=e.ordinalNumbers,n=this._ordinalNumbersByTick=[],r=this._ticksByOrdinalNumber=[],i=0,a=this._ordinalMeta.categories.length,o=Rs(a,t.length);i=0&&e=0&&e=0&&eo[0]&&mi[1]||!isFinite(p)||!isFinite(i[1]))break}else{if(m>f)break;p=Rs(p,i[1]),m===f&&(p=i[1])}if(l.push({value:p}),p=ec(p+n,a),s){var h=s.calcNiceTickMultiple(p,d);h>=0&&(p=ec(p+h*n,a))}if(l.length>0&&p===l[l.length-1].value)break;if(l.length>u)return[]}var g=l.length?l[l.length-1].value:i[1];return r[1]>g&&l.push({value:e.expandToNicedExtent?ec(g+n,a):r[1]}),c&&o.pruneTicksByBreak(e.pruneByBreak,l,s.breaks,function(e){return e.value},t.interval,r),c&&e.breakTicks!==`none`&&o.addBreaksToTicks(l,s.breaks,r),l},t.prototype.getMinorTicks=function(e){return RT(this,e,Mb(this),this._cfg.interval)},t.prototype.getLabel=function(e,t){if(e==null)return``;var n=t&&t.precision;return n==null?n=nc(e.value)||0:n===`auto`&&(n=this._cfg.intervalPrecision),gx(ec(e.value,n,!0))},t.type=`interval`,t}(bT);bT.registerClass(zT);var BT=function(e,t,n,r){for(;n>>1;e[i][1]16?16:e>7.5?7:e>3.5?4:e>1.5?2:1}function GT(e){var t=30*Lb;return e/=t,e>6?6:e>3?3:e>2?2:1}function KT(e){return e/=Ib,e>12?12:e>6?6:e>3.5?4:e>2?2:1}function qT(e,t){return e/=t?Fb:Pb,e>30?30:e>20?20:e>15?15:e>10?10:e>5?5:e>2?2:1}function JT(e){return zs(pc(e,!0),1)}function YT(e,t,n){var r=Math.max(0,qo(Wb,t)-1);return tx(new Date(e),Wb[r],n).getTime()}function XT(e,t){var n=new Date(0);n[e](1);var r=n.getTime();n[e](1+t);var i=n.getTime()-r;return function(e,t){return Math.max(0,Math.round((t-e)/i))}}function ZT(e,t,n,r,i,a){var o=Gb,s=0;function c(e,t,n,i,o,c,l){for(var u=XT(o,e),d=t,f=new Date(d);d3e3));)if(f[o](f[i]()+e),d=f.getTime(),a){var p=a.calcNiceTickMultiple(d,u);p>0&&(f[o](f[i]()+p*e),d=f.getTime())}l.push({value:d,notAdd:d>r[1]})}function l(e,i,a){var o=[],s=!i.length;if(!UT(Yb(e),r[0],r[1],n)){s&&(i=[{value:YT(r[0],e,n)},{value:r[1]}]);for(var l=0;l=r[0]&&u<=r[1]&&c(f,u,d,p,m,h,o),e===`year`&&a.length>1&&l===0&&a.unshift({value:a[0].value-f})}}for(var l=0;l=r[0]&&v<=r[1]&&f++)}var y=i/t;if(f>y*1.5&&p>y/1.5||(u.push(g),f>y||e===o[m]))break}d=[]}}for(var b=Qo(K(u,function(e){return Qo(e,function(e){return e.value>=r[0]&&e.value<=r[1]&&!e.notAdd})}),function(e){return e.length>0}),x=b.length-1,S=[],m=0;mr[0])&&S.unshift({value:r[0],time:{level:0,upperTimeUnit:O,lowerTimeUnit:O},notNice:!0}),(!D||D.values&&(a=s);var c=HT.length,l=Math.min(BT(HT,a,0,c),c-1),u=HT[l][1],d=HT[Math.max(l-1,0)][0];e.setTimeInterval({approxInterval:a,interval:u,minLevelUnit:d})};bT.registerClass(VT);var $T=0,eE=1,tE=2,nE=function(e){U(t,e);function t(n){var r=e.call(this)||this;r.type=`log`,r.parse=zT.parse,r.base=n.logBase||10;var i=[],a=[],o=r._lookup={from:i,to:a};i[$T]=i[eE]=a[$T]=a[eE]=NaN,cT(r,t.mapperMethods);var s=Ab(),c=n.breakOption,l={lookup:o};return s&&s.parseAxisBreakOptionInwardTransform(c,r,{noNegative:!0},tE,l),r.powStub=new zT({breakParsed:l.original}),r.intervalStub=new zT({breakParsed:l.transformed}),lT(r,r.intervalStub),r}return t.prototype.getTicks=function(e){var t=this.base,n=this.powStub,r=Ab(),i=this.intervalStub,a={lookup:{from:i.getExtent(),to:n.getExtent()}};return K(i.getTicks(e||{}),function(e){var i=e.value,o=MT(i,t,a),s;if(r){var c=r.getTicksBreakOutwardTransform(this,e,Mb(n),this._lookup);c&&(s=c.vBreak,o=c.tickVal)}return{value:o,break:s}},this)},t.prototype.getMinorTicks=function(e){return RT(this,e,Mb(this.powStub),this.intervalStub.getConfig().interval)},t.prototype.getLabel=function(e,t){return this.intervalStub.getLabel(e,t)},t.type=`log`,t.mapperMethods={needTransform:function(){return!0},normalize:function(e){return this.intervalStub.normalize(jT(e,this.base))},scale:function(e){return MT(this.intervalStub.scale(e),this.base,null)},transformIn:function(e,t){return e=jT(e,this.base),t&&t.depth===2?e:this.intervalStub.transformIn(e,t)},transformOut:function(e,t){var n=t?t.depth:null;return rE.depth=n,iE.lookup=this._lookup,MT(n===2?e:this.intervalStub.transformOut(e,rE),this.base,iE)},contain:function(e){return this.powStub.contain(e)},setExtent:function(e,t){this.setExtent2(0,e,t)},setExtent2:function(e,t,n){if(!(!gl(t,n)||t<=0||n<=0)){var r=aE,i=aE;if(e===0){var a=this._lookup;r=a.to,i=a.from}this.powStub.setExtent2(e,r[$T]=t,r[eE]=n);var o=this.base;this.intervalStub.setExtent2(e,i[$T]=jT(t,o),i[eE]=jT(n,o))}},getFilter:function(){return{g:0}},sanitize:function(e,t){return gl(t[0],t[1])&&bc(e)&&e<=0&&(e=t[0]),e},getDefaultStartValue:function(){return 1},getExtent:function(){return this.powStub.getExtent()},getExtentUnsafe:function(e,t){return t===null?this.powStub.getExtentUnsafe(e,null):this.intervalStub.getExtentUnsafe(e,t)}},t}(bT);bT.registerClass(nE);var rE={},iE={},aE=[],oE={value:1,category:1,time:1,log:1},sE=Qc(),cE={float:`f`,int:`i`,ordinal:`o`,number:`n`,time:`t`},lE=function(){function e(e){this.dimensions=e.dimensions,this._dimOmitted=e.dimensionOmitted,this.source=e.source,this._fullDimCount=e.fullDimensionCount,this._updateDimOmitted(e.dimensionOmitted)}return e.prototype.isDimensionOmitted=function(){return this._dimOmitted},e.prototype._updateDimOmitted=function(e){this._dimOmitted=e,e&&(this._dimNameMap||=fE(this.source))},e.prototype.getSourceDimensionIndex=function(e){return X(this._dimNameMap.get(e),-1)},e.prototype.getSourceDimension=function(e){var t=this.source.dimensionsDefine;if(t)return t[e]},e.prototype.makeStoreSchema=function(){for(var e=this._fullDimCount,t=SS(this.source),n=!pE(e),r=``,i=[],a=0,o=0;a30}function mE(e,t,n){n||={};var r=n.byIndex,i=n.stackedCoordDimension,a,o,s;hE(t)?a=t:(o=t.schema,a=o.dimensions,s=t.store);var c=!!(e&&e.get(`stack`)),l,u,d,f,p=!0;function m(e){return e.type!==`ordinal`&&e.type!==`time`}if(G(a,function(e,t){Y(e)&&(a[t]=e={name:e}),m(e)||(p=!1)}),G(a,function(e,t){c&&!e.isExtraCoord&&(!r&&!l&&e.ordinalMeta&&(l=e),!u&&m(e)&&(!p||e.coordDim!==`x`&&e.coordDim!==`angle`)&&(!i||i===e.coordDim)&&(u=e))}),u&&!r&&!l&&(r=!0),u){d=`__\0ecstackresult_`+e.id,f=`__\0ecstackedover_`+e.id,l&&(l.createInvertedIndices=!0);var h=u.coordDim,g=u.type,_=0;G(a,function(e){e.coordDim===h&&_++});var v={name:d,coordDim:h,coordDimIndex:_,type:g,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:a.length},y={name:f,coordDim:f,coordDimIndex:_+1,type:g,isExtraCoord:!0,isCalculationCoord:!0,storeDimIndex:a.length+1};o?(s&&(v.storeDimIndex=s.ensureCalculationDimension(f,g),y.storeDimIndex=s.ensureCalculationDimension(d,g)),o.appendCalculationDimension(v),o.appendCalculationDimension(y)):(a.push(v),a.push(y))}return{stackedDimension:u&&u.name,stackedByDimension:l&&l.name,isStackedByIndex:r,stackedOverDimension:f,stackResultDimension:d}}function hE(e){return!uE(e.schema)}function gE(e,t){return!!t&&t===e.getCalculationInfo(`stackedDimension`)}function _E(e,t){return gE(e,t)?e.getCalculationInfo(`stackResultDimension`):t}var vE=Qc();function yE(e){var t=e.get(`type`);return(t==null||!Z(oE,t)&&!bT.getClass(t))&&(t=`value`),t}function bE(e,t,n){var r=Ab(),i;switch(r&&(i=jE(e,t,n)),t){case`category`:return new LT({ordinalMeta:e.getOrdinalMeta?e.getOrdinalMeta():e.getCategories(),extent:ul()});case`time`:return new VT({locale:e.ecModel.getLocaleModel(),useUTC:e.ecModel.get(`useUTC`),breakOption:i});case`log`:return new nE({logBase:e.get(`logBase`),breakOption:i});case`value`:return new zT({breakOption:i});default:return new((bT.getClass(t))||zT)({})}}function xE(e,t,n){var r=n?dT(e,null):e.getExtentUnsafe(0,null),i=r[0],a=r[1];return gl(i,a)?i===t||a===t?2:it?1:3:3}function SE(e){vE(e).noOnMyZero=!0}function CE(e){return vE(e).noOnMyZero}function wE(e){var t=e.getLabelModel().get(`formatter`);if(e.type===`time`){var n=Kb(t);return function(t,r){return e.scale.getFormattedLabel(t,r,n)}}if(Y(t))return function(n){var r=e.scale.getLabel(n);return t.replace(`{value}`,r??``)};if(rs(t)){if(e.type===`category`)return function(n,r){return t(TE(e,n),n.value-e.scale.getExtent()[0],null)};var r=Ab();return function(n,i){var a=null;return r&&(a=r.makeAxisLabelFormatterParamBreak(a,n.break)),t(TE(e,n),i,a)}}return function(t){return e.scale.getLabel(t)}}function TE(e,t){var n=e.scale;return OT(n)?n.getLabel(t):t.value}function EE(e){return e.get(`interval`)??`auto`}function DE(e){return e.type===`category`&&EE(e.getLabelModel())===0}function OE(e,t){var n={};return G(e.mapDimensionsAll(t),function(t){n[_E(e,t)]=!0}),es(n)}function kE(e){return e===`middle`||e===`center`}function AE(e){return e.getShallow(`show`)}function jE(e,t,n){var r=e.get(`breaks`,!0);if(r!=null)return!Ab()||!n||!ME(t)?void 0:r}function ME(e){return e!==`category`}function NE(e,t,n,r,i,a){var o=DT(e),s=o?e.intervalStub:e;if(s.setExtent(r[0],r[1]),o){var c=e.powStub,l={depth:2},u=e.transformOut(r[0],l),d=e.transformOut(r[1],l),f=PT(n,r);t[0]&&!f[0]&&(u=i[0]),t[1]&&!f[1]&&(d=i[1]),c.setExtent(u,d)}s.setConfig(a)}function PE(e,t){return OT(e)?e.getRawOrdinalNumber(t.value):t.value}function FE(e,t){return OT(e)&&!!t.get(`boundaryGap`)}var IE=function(){function e(e){this.type=`cartesian`,this._dimList=[],this._axes={},this.name=e||``}return e.prototype.getAxis=function(e){return this._axes[e]},e.prototype.getAxes=function(){return K(this._dimList,function(e){return this._axes[e]},this)},e.prototype.getAxesByScale=function(e){return e=e.toLowerCase(),Qo(this.getAxes(),function(t){return t.scale.type===e})},e.prototype.addAxis=function(e){var t=e.dim;this._axes[t]=e,this._dimList.push(t)},e}(),LE={left:0,right:0,top:0,bottom:0},RE=[`25%`,`25%`],zE=`cartesian2d`,BE=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.mergeDefaultAndTheme=function(t,n){var r=Kx(t.outerBounds);e.prototype.mergeDefaultAndTheme.apply(this,arguments),r&&t.outerBounds&&Gx(t.outerBounds,r)},t.prototype.mergeOption=function(t,n){e.prototype.mergeOption.apply(this,arguments),this.option.outerBounds&&t.outerBounds&&Gx(this.option.outerBounds,t.outerBounds)},t.type=`grid`,t.dependencies=[`xAxis`,`yAxis`],t.layoutMode=`box`,t.defaultOption={show:!1,z:0,left:`15%`,top:65,right:`10%`,bottom:80,containLabel:!1,outerBoundsMode:`auto`,outerBounds:LE,outerBoundsContain:`all`,outerBoundsClampWidth:RE[0],outerBoundsClampHeight:RE[1],backgroundColor:Q.color.transparent,borderWidth:1,borderColor:Q.color.neutral30},t}(Yx),VE=[`x`,`y`];function HE(e){return(e.type===`interval`||e.type===`time`)&&!Nb(e)}var UE=function(e){U(t,e);function t(){var t=e!==null&&e.apply(this,arguments)||this;return t.type=zE,t.dimensions=VE,t}return t.prototype.calcAffineTransform=function(){this._transform=this._invTransform=null;var e=this.getAxis(`x`).scale,t=this.getAxis(`y`).scale;if(HE(e)&&HE(t)){var n=dT(e,null),r=dT(t,null),i=this.dataToPoint([n[0],r[0]]),a=this.dataToPoint([n[1],r[1]]),o=n[1]-n[0],s=r[1]-r[0];if(o&&s){var c=(a[0]-i[0])/o,l=(a[1]-i[1])/s,u=i[0]-n[0]*c,d=i[1]-r[0]*l,f=this._transform=[c,0,0,l,u,d];this._invTransform=au([],f)}}},t.prototype.getBaseAxis=function(){return this.getAxesByScale(`ordinal`)[0]||this.getAxesByScale(`time`)[0]||this.getAxis(`x`)},t.prototype.containPoint=function(e){var t=this.getAxis(`x`),n=this.getAxis(`y`);return t.contain(t.toLocalCoord(e[0]))&&n.contain(n.toLocalCoord(e[1]))},t.prototype.containData=function(e){return this.getAxis(`x`).containData(e[0])&&this.getAxis(`y`).containData(e[1])},t.prototype.containZone=function(e,t){var n=this.dataToPoint(e),r=this.dataToPoint(t),i=this.getArea(),a=new Ru(n[0],n[1],r[0]-n[0],r[1]-n[1]);return i.intersect(a)},t.prototype.dataToPoint=function(e,t,n){n||=[];var r=e[0],i=e[1];if(this._transform&&r!=null&&isFinite(r)&&i!=null&&isFinite(i))return xu(n,e,this._transform);var a=this.getAxis(`x`),o=this.getAxis(`y`);return n[0]=a.toGlobalCoord(a.dataToCoord(r,t)),n[1]=o.toGlobalCoord(o.dataToCoord(i,t)),n},t.prototype.clampData=function(e,t){var n=this.getAxis(`x`).scale,r=this.getAxis(`y`).scale,i=n.getExtent(),a=r.getExtent(),o=n.parse(e[0]),s=r.parse(e[1]);return t||=[],t[0]=Math.min(Math.max(Math.min(i[0],i[1]),o),Math.max(i[0],i[1])),t[1]=Math.min(Math.max(Math.min(a[0],a[1]),s),Math.max(a[0],a[1])),t},t.prototype.pointToData=function(e,t,n){if(n||=[],this._invTransform)return xu(n,e,this._invTransform);var r=this.getAxis(`x`),i=this.getAxis(`y`);return n[0]=r.coordToData(r.toLocalCoord(e[0]),t),n[1]=i.coordToData(i.toLocalCoord(e[1]),t),n},t.prototype.getOtherAxis=function(e){return this.getAxis(e.dim===`x`?`y`:`x`)},t.prototype.getArea=function(e){e||=0;var t=this.getAxis(`x`).getGlobalExtent(),n=this.getAxis(`y`).getGlobalExtent(),r=Math.min(t[0],t[1])-e,i=Math.min(n[0],n[1])-e;return new Ru(r,i,Math.max(t[0],t[1])-r+e,Math.max(n[0],n[1])-i+e)},t}(IE),WE=Qc(),GE=Qc(),KE={estimate:1,determine:2};function qE(e){return{out:{noPxChangeTryDetermine:[]},kind:e}}function JE(e,t){var n=e.getLabelModel().get(`customValues`);if(n){var r=e.scale;return{labels:K(XE(n,r),function(t,n){return{formattedLabel:wE(e)(t,n),rawLabel:r.getLabel(t),tick:t}})}}return e.type===`category`?ZE(e,t):eD(e)}function YE(e,t,n){var r=e.scale,i=e.getTickModel().get(`customValues`);return i?{ticks:XE(i,r)}:e.type===`category`?$E(e,t):{ticks:r.getTicks(n)}}function XE(e,t){var n=t.getExtent(),r=[];return G(e,function(e){e=t.parse(e),e>=n[0]&&e<=n[1]&&r.push(e)}),xl(r,Cl,null),tc(r),K(r,function(e){return{value:e}})}function ZE(e,t){var n=e.getLabelModel(),r=QE(e,n,t);return!n.get(`show`)||e.scale.isBlank()?{labels:[]}:r}function QE(e,t,n){var r=nD(e),i=EE(t),a=n.kind===KE.estimate;if(!a){var o=iD(r,i);if(o)return o}var s,c;rs(i)?s=dD(e,i,!1):(c=i===`auto`?oD(e,n):i,s=dD(e,c,!1));var l={labels:s,labelCategoryInterval:c};return a?n.out.noPxChangeTryDetermine.push(function(){return aD(r,i,l),!0}):aD(r,i,l),l}function $E(e,t){var n=tD(e),r=EE(t),i=iD(n,r);if(i)return i;var a,o;if((!t.get(`show`)||e.scale.isBlank())&&(a=[]),rs(r))a=dD(e,r,!0);else if(r===`auto`){var s=QE(e,e.getLabelModel(),qE(KE.determine));o=s.labelCategoryInterval,a=K(s.labels,function(e){return e.tick})}else o=r,a=dD(e,o,!0);return aD(n,r,{ticks:a,tickCategoryInterval:o})}function eD(e){var t=e.scale.getTicks(),n=wE(e);return{labels:K(t,function(t,r){return{formattedLabel:n(t,r),rawLabel:e.scale.getLabel(t),tick:t}})}}var tD=rD(`axisTick`),nD=rD(`axisLabel`);function rD(e){return function(t){return GE(t)[e]||(GE(t)[e]={list:[]})}}function iD(e,t){for(var n=0;nu&&(l=Math.max(1,Math.floor(c/u)));for(var d=s[0],f=e.dataToCoord(d+1)-e.dataToCoord(d),p=Math.abs(f*Math.cos(a)),m=Math.abs(f*Math.sin(a)),h=0,g=0;d<=s[1];d+=l){var _=0,v=0,y=id(i({value:d}),r.font,`center`,`top`);_=y.width*1.3,v=y.height*1.3,h=Math.max(h,_,7),g=Math.max(g,v,7)}var b=h/p,x=g/m;isNaN(b)&&(b=1/0),isNaN(x)&&(x=1/0);var S=Math.max(0,Math.floor(Math.min(b,x)));return n===KE.estimate?(t.out.noPxChangeTryDetermine.push(q(cD,null,e,S,c)),S):lD(e,S,c)??S}function cD(e,t,n){return lD(e,t,n)==null}function lD(e,t,n){var r=WE(e.model),i=e.getExtent(),a=r.lastAutoInterval,o=r.lastTickCount;if(a!=null&&o!=null&&Math.abs(a-t)<=1&&Math.abs(o-n)<=1&&a>t&&r.axisExtent0===i[0]&&r.axisExtent1===i[1])return a;r.lastTickCount=n,r.lastAutoInterval=t,r.axisExtent0=i[0],r.axisExtent1=i[1]}function uD(e){var t=e.getLabelModel();return{axisRotate:e.getRotate?e.getRotate():e.isHorizontal&&!e.isHorizontal()?90:0,labelRotate:t.get(`rotate`)||0,font:t.getFont()}}function dD(e,t,n){var r=wE(e),i=e.scale,a=[],o=rs(t);return IT(i,o?0:t,function(e,s){var c=i.getLabel(e);if(o){var l=!!t(e.value,c);if(e.offInterval=!l,!l&&!s)return}a.push(n?e:{formattedLabel:r(e),rawLabel:c,tick:e})}),a}var fD=Qc();function pD(e){fD(e).prepare={}}function mD(e){fD(e).fullUpdate={}}function hD(e){return fD(e).prepare}function gD(e){return fD(e).fullUpdate}var _D=yl(),vD=Qc(),yD=Qc();function bD(e,t){var n=e.model,r=vD(gD(n.ecModel)).keyed,i=r&&r.get(t);return i&&i.get(n.uid)}function xD(e,t){return wD(bD(e,t))}function SD(e,t){var n=[];return CD(e.model.ecModel,function(e){for(var r=0;r0?(t>o&&(o=t),a=!1):t===-2&&(a=!0))}),bc(n)&&n>0&&bc(o)?(e.w=r/n*o,e.w2=o):a&&(e.w=r*LD,e.w2=e.w*n/r)}var VD=[0,1],HD=function(){function e(e,t,n){this.onBand=!1,this.inverse=!1,this.dim=e,this.scale=t,this._extent=n||[0,0]}return e.prototype.contain=function(e){var t=this._extent,n=Math.min(t[0],t[1]),r=Math.max(t[0],t[1]);return e>=n&&e<=r},e.prototype.containData=function(e){return this.scale.contain(this.scale.parse(e))},e.prototype.getExtent=function(){return this._extent.slice()},e.prototype.setExtent=function(e,t){var n=this._extent;n[0]=e,n[1]=t},e.prototype.dataToCoord=function(e,t){var n=this.scale;return e=n.normalize(n.parse(e)),Ys(e,VD,UD(this),t)},e.prototype.coordToData=function(e,t){var n=Ys(e,UD(this),VD,t);return this.scale.scale(n)},e.prototype.pointToData=function(e,t){},e.prototype.getTicksCoords=function(e){e||={};var t=e.tickModel||this.getTickModel(),n=K(YE(this,t,{breakTicks:e.breakTicks,pruneByBreak:e.pruneByBreak}).ticks,function(e){return{coord:this.dataToCoord(PE(this.scale,e)),tick:e}},this),r=t.get(`alignWithLabel`),i=WD(this,n,r);return K(n,function(e){return{coord:e.coord,tickValue:e.tick.value,onBand:i}})},e.prototype.getMinorTicksCoords=function(){if(OT(this.scale))return[];var e=this.model.getModel(`minorTick`).get(`splitNumber`);return e>0&&e<100||(e=5),K(this.scale.getMinorTicks(e),function(e){return K(e,function(e){return{coord:this.dataToCoord(e),tickValue:e}},this)},this)},e.prototype.getViewLabels=function(e){return e||=qE(KE.determine),JE(this,e).labels},e.prototype.getLabelModel=function(){return this.model.getModel(`axisLabel`)},e.prototype.getTickModel=function(){return this.model.getModel(`axisTick`)},e.prototype.getBandWidth=function(){return RD(this,{min:1}).w},e.prototype.calculateCategoryInterval=function(e){return e||=qE(KE.determine),sD(this,e)},e}();function UD(e){var t=e.getExtent();if(e.onBand){var n=(t[1]-t[0])/e.scale.count()/2;t[0]+=n,t[1]-=n}return t}function WD(e,t,n){var r=t.length;if(!e.onBand||n||!r)return!1;var i=RD(e).w;if(!i)return!1;G(t,function(e){e.coord-=i/2});var a=e.scale.getExtent(),o=t[r-1];return o.tick.offInterval&&t.pop(),t.push({coord:o.coord+i,tick:{value:a[1]+1}}),!0}var GD=function(e){U(t,e);function t(t,n,r,i,a){var o=e.call(this,t,n,r)||this;return o.index=0,o.type=i||`value`,o.position=a||`bottom`,o}return t.prototype.isHorizontal=function(){var e=this.position;return e===`top`||e===`bottom`},t.prototype.getGlobalExtent=function(e){var t=this.getExtent();return t[0]=this.toGlobalCoord(t[0]),t[1]=this.toGlobalCoord(t[1]),e&&t[0]>t[1]&&t.reverse(),t},t.prototype.pointToData=function(e,t){return this.coordToData(this.toLocalCoord(e[this.dim===`x`?0:1]),t)},t.prototype.setCategorySortInfo=function(e){if(this.type!==`category`)return!1;this.model.option.categorySortInfo=e,this.scale.setSortInfo(e)},t}(HD),KD=Qm.extend({type:`triangle`,shape:{cx:0,cy:0,width:0,height:0},buildPath:function(e,t){var n=t.cx,r=t.cy,i=t.width/2,a=t.height/2;e.moveTo(n,r-a),e.lineTo(n+i,r+a),e.lineTo(n-i,r+a),e.closePath()}}),qD={line:Z_,rect:fh,roundRect:fh,square:fh,circle:x_,diamond:Qm.extend({type:`diamond`,shape:{cx:0,cy:0,width:0,height:0},buildPath:function(e,t){var n=t.cx,r=t.cy,i=t.width/2,a=t.height/2;e.moveTo(n,r-a),e.lineTo(n+i,r),e.lineTo(n,r+a),e.lineTo(n-i,r),e.closePath()}}),pin:Qm.extend({type:`pin`,shape:{x:0,y:0,width:0,height:0},buildPath:function(e,t){var n=t.x,r=t.y,i=t.width/5*3,a=Math.max(i,t.height),o=i/2,s=o*o/(a-o),c=r-a+o+s,l=Math.asin(s/o),u=Math.cos(l)*o,d=Math.sin(l),f=Math.cos(l),p=o*.6,m=o*.7;e.moveTo(n-u,c+s),e.arc(n,c,o,Math.PI-l,Math.PI*2+l),e.bezierCurveTo(n+u-d*p,c+s+f*p,n,r-m,n,r),e.bezierCurveTo(n,r-m,n-u+d*p,c+s+f*p,n-u,c+s),e.closePath()}}),arrow:Qm.extend({type:`arrow`,shape:{x:0,y:0,width:0,height:0},buildPath:function(e,t){var n=t.height,r=t.width,i=t.x,a=t.y,o=r/3*2;e.moveTo(i,a),e.lineTo(i+o,a+n),e.lineTo(i,a+n/4*3),e.lineTo(i-o,a+n),e.lineTo(i,a),e.closePath()}}),triangle:KD},JD={line:function(e,t,n,r,i){i.x1=e,i.y1=t+r/2,i.x2=e+n,i.y2=t+r/2},rect:function(e,t,n,r,i){i.x=e,i.y=t,i.width=n,i.height=r},roundRect:function(e,t,n,r,i){i.x=e,i.y=t,i.width=n,i.height=r,i.r=Math.min(n,r)/4},square:function(e,t,n,r,i){var a=Math.min(n,r);i.x=e,i.y=t,i.width=a,i.height=a},circle:function(e,t,n,r,i){i.cx=e+n/2,i.cy=t+r/2,i.r=Math.min(n,r)/2},diamond:function(e,t,n,r,i){i.cx=e+n/2,i.cy=t+r/2,i.width=n,i.height=r},pin:function(e,t,n,r,i){i.x=e+n/2,i.y=t+r/2,i.width=n,i.height=r},arrow:function(e,t,n,r,i){i.x=e+n/2,i.y=t+r/2,i.width=n,i.height=r},triangle:function(e,t,n,r,i){i.cx=e+n/2,i.cy=t+r/2,i.width=n,i.height=r}},YD={};G(qD,function(e,t){YD[t]=new e});var XD=Qm.extend({type:`symbol`,shape:{symbolType:``,x:0,y:0,width:0,height:0},calculateTextPosition:function(e,t,n){var r=ld(e,t,n),i=this.shape;return i&&i.symbolType===`pin`&&t.position===`inside`&&(r.y=n.y+n.height*.4),r},buildPath:function(e,t,n){var r=t.symbolType;if(r!==`none`){var i=YD[r];i||=(r=`rect`,YD[r]),JD[r](t.x,t.y,t.width,t.height,i.shape),i.buildPath(e,i.shape,n)}}});function ZD(e,t){if(this.type!==`image`){var n=this.style;this.__isEmptyBrush?(n.stroke=e,n.fill=t||Q.color.neutral00,n.lineWidth=2):this.shape.symbolType===`line`?n.stroke=e:n.fill=e,this.markRedraw()}}function QD(e,t,n,r,i,a,o){var s=e.indexOf(`empty`)===0;s&&(e=e.substr(5,1).toLowerCase()+e.substr(6));var c=e.indexOf(`image://`)===0?zv(e.slice(8),new Ru(t,n,r,i),o?`center`:`cover`):e.indexOf(`path://`)===0?Rv(e.slice(7),{},new Ru(t,n,r,i),o?`center`:`cover`):new XD({shape:{symbolType:e,x:t,y:n,width:r,height:i}});return c.__isEmptyBrush=s,c.setColor=ZD,a&&c.setColor(a),c}function $D(e){return J(e)||(e=[+e,+e]),[e[0]||0,e[1]||0]}function eO(e,t){if(e!=null)return J(e)||(e=[e,e]),[Xs(e[0],t[0])||0,Xs(X(e[1],e[0]),t[1])||0]}var tO=Math.PI,nO=[[1,2,1,2],[5,3,5,3],[8,3,8,3]],rO=[[0,1,0,1],[0,3,0,3],[0,3,0,3]],iO=Qc(),aO=Qc(),oO=function(){function e(e){this.recordMap={},this.resolveAxisNameOverlap=e}return e.prototype.ensureRecord=function(e){var t=e.axis.dim,n=e.componentIndex,r=this.recordMap,i=r[t]||(r[t]=[]);return i[n]||(i[n]={ready:{}})},e}();function sO(e,t,n,r){var i=n.axis,a=t.ensureRecord(n),o=[],s,c=jO(e.axisName)&&kE(e.nameLocation);G(r,function(e){var t=Rw(e);if(t&&!t.label.ignore){o.push(t);var n=a.transGroup;c&&(n.transform?au(cO,n.transform):$l(cO),t.transform&&tu(cO,cO,t.transform),Ru.copy(lO,t.localRect),lO.applyTransform(cO),s?s.union(lO):Ru.copy(s=new Ru(0,0,0,0),lO))}});var l=Math.abs(a.dirVec.x)>.1?`x`:`y`,u=a.transGroup[l];if(o.sort(function(e,t){return Math.abs(e.label[l]-u)-Math.abs(t.label[l]-u)}),c&&s){var d=i.getExtent(),f=Math.min(d[0],d[1]),p=Math.max(d[0],d[1])-f;s.union(new Ru(f,0,p,1))}a.stOccupiedRect=s,a.labelInfoList=o}var cO=Ql(),lO=new Ru(0,0,0,0),uO=function(e,t,n,r,i,a){if(kE(e.nameLocation)){var o=a.stOccupiedRect;o&&dO(Vw({},o,a.transGroup.transform),r,i)}else fO(a.labelInfoList,a.dirVec,r,i)};function dO(e,t,n){var r=new wu;Jw(e,t,r,{direction:Math.atan2(n.y,n.x),bidirectional:!1,touchThreshold:.05})&&Hw(t,r)}function fO(e,t,n,r){for(var i=wu.dot(r,t)>=0,a=0,o=e.length;a0?`top`:`bottom`,i=`center`):cc(r-tO)?(a=n>0?`bottom`:`top`,i=`center`):(a=`middle`,i=r>0&&r0?`right`:`left`:n>0?`left`:`right`),{rotation:r,textAlign:i,textVerticalAlign:a}},e.makeAxisEventDataBase=function(e){var t={componentType:e.mainType,componentIndex:e.componentIndex};return t[e.mainType+`Index`]=e.componentIndex,t},e.isLabelSilent=function(e){var t=e.get(`tooltip`);return e.get(`silent`)||!(e.get(`triggerEvent`)||t&&t.show)},e}(),mO=[`axisLine`,`axisTickLabelEstimate`,`axisTickLabelDetermine`,`axisName`],hO={axisLine:function(e,t,n,r,i,a,o){var s=r.get([`axisLine`,`show`]);if(s===`auto`&&(s=!0,e.raw.axisLineAutoShow!=null&&(s=!!e.raw.axisLineAutoShow)),s){var c=r.axis.getExtent(),l=a.transform,u=[c[0],0],d=[c[1],0],f=u[0]>d[0];l&&(xu(u,u,l),xu(d,d,l));var p=W({lineCap:`round`},r.getModel([`axisLine`,`lineStyle`]).getLineStyle()),m={strokeContainThreshold:e.raw.strokeContainThreshold||5,silent:!0,z2:1,style:p};if(r.get([`axisLine`,`breakLine`])&&Nb(r.axis.scale))yT().buildAxisBreakLine(r,i,a,m);else{var h=new Z_(W({shape:{x1:u[0],y1:u[1],x2:d[0],y2:d[1]}},m));Uv(h.shape,h.style.lineWidth),h.anid=`line`,i.add(h)}var g=r.get([`axisLine`,`symbol`]);if(g!=null){var _=r.get([`axisLine`,`symbolSize`]);Y(g)&&(g=[g,g]),(Y(_)||as(_))&&(_=[_,_]);var v=eO(r.get([`axisLine`,`symbolOffset`])||0,_),y=_[0],b=_[1];G([{rotate:e.rotation+Math.PI/2,offset:v[0],r:0},{rotate:e.rotation-Math.PI/2,offset:v[1],r:Math.sqrt((u[0]-d[0])*(u[0]-d[0])+(u[1]-d[1])*(u[1]-d[1]))}],function(t,n){if(g[n]!==`none`&&g[n]!=null){var r=QD(g[n],-y/2,-b/2,y,b,p.stroke,!0),a=t.r+t.offset,o=f?d:u;r.attr({rotation:t.rotate,x:o[0]+a*Math.cos(e.rotation),y:o[1]-a*Math.sin(e.rotation),silent:!0,z2:11}),i.add(r)}})}}},axisTickLabelEstimate:function(e,t,n,r,i,a,o,s){wO(t,i,s)&&gO(e,t,n,r,i,a,o,KE.estimate)},axisTickLabelDetermine:function(e,t,n,r,i,a,o,s){wO(t,i,s)&&gO(e,t,n,r,i,a,o,KE.determine);var c=SO(e,i,a,r);yO(e,t.labelLayoutList,c),CO(e,i,a,r,e.tickDirection)},axisName:function(e,t,n,r,i,a,o,s){var c=n.ensureRecord(r);t.nameEl&&=(i.remove(t.nameEl),c.nameLayout=c.nameLocation=null);var l=e.axisName;if(jO(l)){var u=e.nameLocation,d=e.nameDirection,f=r.getModel(`nameTextStyle`),p=r.get(`nameGap`)||0,m=r.axis.getExtent(),h=r.axis.inverse?-1:1,g=new wu(0,0),_=new wu(0,0);u===`start`?(g.x=m[0]-h*p,_.x=-h):u===`end`?(g.x=m[1]+h*p,_.x=h):(g.x=(m[0]+m[1])/2,g.y=e.labelOffset+d*p,_.y=d);var v=Ql();_.transform(ru(v,v,e.rotation));var y=r.get(`nameRotate`);y!=null&&(y=y*tO/180);var b,x;kE(u)?b=pO.innerTextLayout(e.rotation,y??e.rotation,d):(b=_O(e.rotation,u,y||0,m),x=e.raw.axisNameAvailableWidth,x!=null&&(x=Math.abs(x/Math.sin(b.rotation)),!isFinite(x)&&(x=null)));var S=f.getFont(),C=r.get(`nameTruncate`,!0)||{},w=C.ellipsis,T=ps(e.raw.nameTruncateMaxWidth,C.maxWidth,x),E=s.nameMarginLevel||0,D=new _h({x:g.x,y:g.y,rotation:b.rotation,silent:pO.isLabelSilent(r),style:Oy(f,{text:l,font:S,overflow:`truncate`,width:T,ellipsis:w,fill:f.getTextColor()||r.get([`axisLine`,`lineStyle`,`color`]),align:f.get(`align`)||b.textAlign,verticalAlign:f.get(`verticalAlign`)||b.textVerticalAlign}),z2:1});if(cy({el:D,componentModel:r,itemName:l}),D.__fullText=l,D.anid=`name`,r.get(`triggerEvent`)){var O=pO.makeAxisEventDataBase(r);O.targetType=`axisName`,O.name=l,jh(D).eventData=O}a.add(D),D.updateTransform(),t.nameEl=D;var k=c.nameLayout=Rw({label:D,priority:D.z2,defaultAttr:{ignore:D.ignore},marginDefault:kE(u)?nO[E]:rO[E]});if(c.nameLocation=u,i.add(D),D.decomposeTransform(),e.shouldNameMoveOverlap&&k){var A=n.ensureRecord(r);n.resolveAxisNameOverlap(e,n,r,k,_,A)}}}};function gO(e,t,n,r,i,a,o,s){EO(t)||TO(e,t,i,s,r,o);var c=t.labelLayoutList;OO(e,r,c,a),NO(r,e.rotation,c);var l=e.optionHideOverlap;vO(r,c,l),l&&qw(Qo(c,function(e){return e&&!e.label.ignore})),sO(e,n,r,c)}function _O(e,t,n,r){var i=sc(n-e),a,o,s=r[0]>r[1],c=t===`start`&&!s||t!==`start`&&s;return cc(i-tO/2)?(o=c?`bottom`:`top`,a=`center`):cc(i-tO*1.5)?(o=c?`top`:`bottom`,a=`center`):(o=`middle`,a=itO/2?c?`left`:`right`:c?`right`:`left`),{rotation:i,textAlign:a,textVerticalAlign:o}}function vO(e,t,n){var r=e.axis,i=e.get([`axisLabel`,`customValues`]);if(DE(r))return;function a(e,a,o){var s=Rw(t[a]),c=Rw(t[o]),l=r.scale;if(s&&c){if(e==null){if(!n&&i)return;var u=iO(s.label).labelInfo.tick;if(ET(l)&&u.notNice||OT(l)&&u.offInterval){bO(s.label);return}}if(e===!1||s.suggestIgnore){bO(s.label);return}if(c.suggestIgnore){bO(c.label);return}var d=.1;if(!n){var f=[0,0,0,0];s=Uw({marginForce:f},s),c=Uw({marginForce:f},c)}Jw(s,c,null,{touchThreshold:d})&&bO(e?c.label:s.label)}}var o=e.get([`axisLabel`,`showMinLabel`]),s=e.get([`axisLabel`,`showMaxLabel`]),c=t.length;a(o,0,1),a(s,c-1,c-2)}function yO(e,t,n){e.showMinorTicks||G(t,function(e){if(e&&e.label.ignore)for(var t=0;t0&&u[1]>0&&!d[0]&&(u[0]=0),u[0]<0&&u[1]<0&&!d[1]&&(u[1]=0));var y=!1;u[0]>u[1]&&(u.reverse(),y=!0);var b=WO(e,t.get(`startValue`,!0)),x=b!=null;!bc(b)&&r&&(b=e.getDefaultStartValue?e.getDefaultStartValue():0),bc(b)&&(x||!_||v)&&(bu[1]&&!d[1]&&(u[1]=b,d[1]=!0)),UO(this._i={scale:e,dataMM:l,noZoomEffMM:u,zoomMM:[],fixMM:d,zoomFixMM:[!1,!1],startValue:b,isBlank:g,incl0:v,tggAxInv:y,ctnShp:i},u)}return e.prototype.makeNoZoom=function(){return this._i.noZoomEffMM.slice()},e.prototype.makeFinal=function(){var e=this._i,t=e.zoomMM,n=e.noZoomEffMM,r=e.zoomFixMM,i=e.fixMM,a={fixMM:i,zoomFixMM:r,isBlank:e.isBlank,incl0:e.incl0,tggAxInv:e.tggAxInv,ctnShp:e.ctnShp,effMM:n.slice()},o=a.effMM;return t[0]!=null&&(o[0]=t[0],i[0]=r[0]=!0),t[1]!=null&&(o[1]=t[1],i[1]=r[1]=!0),UO(e,o),a},e.prototype.makeRenderInfo=function(){return{startValue:this._i.startValue}},e.prototype.setZoomMM=function(e,t){this._i.zoomMM[e]=t},e}();function UO(e,t){var n=e.scale,r=e.dataMM;n.sanitize&&(t[0]=n.sanitize(t[0],r),t[1]=n.sanitize(t[1],r),vl(t))}function WO(e,t){return t==null?null:fs(t)?NaN:e.parse(t)}function GO(e,t){var n;if(OT(e))n=[0,0];else{var r=t.get(`boundaryGap`);typeof r==`boolean`&&(r=null),n=J(r)?r:[r,r]}return[KO(n[0]),KO(n[1])]}function KO(e){return cd(typeof e==`boolean`?0:e,1)||0}function qO(e){var t=BO(e.scale);return t.extent||=ul(),t}function JO(e,t){qO(e).dimIdxInCoord=t.get(e.dim)}function YO(e,t){var n=e.scale,r=e.model,i=e.dim;n.rawExtentInfo||XO(n,e,i,r,t)}function XO(e,t,n,r,i){var a=qO(t),o=a.extent,s=!1;TD(t,function(r){if(r.boxCoordinateSystem){var i=jx(r).coord,c=a.dimIdxInCoord;if(c>=0&&J(i)){var l=i[c];l!=null&&!J(l)&&dl(o,e.parse(l))}}else if(r.coordinateSystem){var u=r.getData();if(u){var d=e.getFilter?e.getFilter():null;G(OE(u,n),function(e){ml(o,u.getApproximateExtent(e,d))})}r.__requireStartValue&&r.__requireStartValue(t)&&(s=!0)}});var c=nk(e,t,r);QO(e,new HO(e,r,o,s,c),i),a.extent=null}function ZO(e,t){var n=e.scale;QO(n,new HO(n,e.model,t,!1,!1),VO)}function QO(e,t,n){e.rawExtentInfo=t,t.from=n}function $O(e,t){ek.set(e,t)}var ek=Es();function tk(e,t,n,r,i){e.rawExtentInfo||ZO({scale:e,model:t},i||ul());var a=e.rawExtentInfo.makeFinal(),o=a.effMM;return e.setExtent(o[0],o[1]),e.setBlank(a.isBlank),r&&a.tggAxInv&&n&&!n.get(`legacyMinMaxDontInverseAxis`)&&(r.inverse=!r.inverse),a}function nk(e,t,n){var r=FE(e,n),i=n.get(`containShape`,!0);if(i==null&&!r&&(i=!0),!i)return!1;var a=!1;return kD(t,function(e){a=!!ek.get(e)||a}),a}function rk(e,t,n,r){if(n.ctnShp){var i;if(kD(e,function(t){var n=ek.get(t);if(n){var a=n(e,r);a&&(i||=[0,0],fl(i,a[0]),pl(i,a[1]),SE(e))}}),i){var a=t.getExtent();if(OT(t))e.onBand||t.setExtent2(1,Rs(a[0],a[0]+i[0]),zs(a[1],a[1]+i[1]));else{var o=a.slice();n.zoomFixMM[0]||(o[0]=Rs(o[0],t.transformOut(t.transformIn(o[0],null)+i[0],null))),n.zoomFixMM[1]||(o[1]=zs(o[1],t.transformOut(t.transformIn(o[1],null)+i[1],null))),(o[0]a[1])&&t.setExtent2(1,o[0],o[1])}}}}function ik(e,t){var n=e.scale,r=e.model,i=tk(n,r,r.ecModel,e,null),a=DT(n),o=DT(t)?t.intervalStub:t,s=a?n.intervalStub:n,c=n.base,l=o.getTicks(),u=o.getTicks({expandToNicedExtent:!0}),d=l.length-1,f,p,m;if(d===1)f=p=0,m=1;else if(d===2){var h=Bs(l[0].value-l[1].value),g=Bs(l[1].value-l[2].value);f=p=0,h===g?m=2:(m=1,h=C[1])return!0})):b[1]?(T=C[1],A(function(){if(P(),k=ec(O-E*m,D),j(),w<=C[0])return!0})):A(function(){k=ec(Us(C[0]/E)*E,D),O=ec(Hs(C[1]/E)*E,D);var e=Vs((O-k)/E);if(e<=m){var t=m-e,n=void 0,r=i.incl0||a;if(r&&C[0]===0)n=[0,t];else if(r&&C[1]===0)n=[t,0];else{var o=Hs(t/2);n=t%2==0?[o,o]:w+T=C[1])return!0}})}NE(n,b,S,[w,T],x,{interval:E,intervalCount:m,intervalPrecision:D,niceExtent:[k,O]})}function ak(e,t){var n=DT(e),r=n?e.intervalStub:e,i=t.fixMinMax||[],a=n?e.getExtent():null,o=r.getExtent(),s=NT(o,i,t.rawExtentResult);r.setExtent(s[0],s[1]),s=r.getExtent();var c=n?sk(r,t):ok(r,t),l=c.intervalPrecision,u=c.interval,d=t.userInterval;d!=null&&(c.interval=d,c.intervalPrecision=AT(d)),i[0]||(s[0]=ec(Hs(s[0]/u)*u,l)),i[1]||(s[1]=ec(Us(s[1]/u)*u,l)),d!=null&&(c.niceExtent=s.slice()),NE(e,i,o,s,a,c)}function ok(e,t){var n=FT(t.splitNumber,5),r=pT(e),i=t.minInterval,a=t.maxInterval,o=pc(r/n,!0);i!=null&&oa&&(o=a);var s=AT(o),c=e.getExtent(),l=[ec(Us(c[0]/o)*o,s),ec(Hs(c[1]/o)*o,s)];return{interval:o,intervalPrecision:s,niceExtent:l}}function sk(e,t){var n=FT(t.splitNumber,10),r=e.getExtent(),i=pT(e),a=zs(dc(i),1);n/i*a<=.5&&(a*=10);var o=AT(a),s=[ec(Us(r[0]/a)*a,o),ec(Hs(r[1]/a)*a,o)];return{intervalPrecision:o,interval:a,niceExtent:s}}function ck(e){var t=e.scale,n=e.model,r=n.axis,i=n.ecModel;lk(t,n,r,i,null)}function lk(e,t,n,r,i){var a=tk(e,t,r,n,i),o=TT(e)||ET(e);uk(e,{splitNumber:t.get(`splitNumber`),fixMinMax:a.fixMM,userInterval:t.get(`interval`),minInterval:o?t.get(`minInterval`):null,maxInterval:o?t.get(`maxInterval`):null,rawExtentResult:a}),n&&r&&rk(n,e,a,r)}function uk(e,t){dk[e.type](e,t)}var dk={interval:ak,log:ak,time:QT,ordinal:As},fk=[[3,1],[0,2]],pk=function(){function e(e,t,n){this.type=`grid`,this._coordsMap={},this._coordsList=[],this._axesMap={},this._axesList=[],this.axisPointerEnabled=!0,this.dimensions=VE,this._initCartesian(e,t,n),this.model=e}return e.prototype.getRect=function(){return this._rect},e.prototype.update=function(e,t){var n=this._axesMap;G(this._axesList,function(e){YO(e,1);var t=e.scale;OT(t)&&t.setSortInfo(e.model.get(`categorySortInfo`))});function r(e){for(var t=es(e),n=[],r=t.length-1;r>=0;r--){var i=e[+t[r]];i.__alignTo?n.push(i):ck(i)}G(n,function(e){vk(e,e.__alignTo)?ck(e):ik(e,e.__alignTo.scale)})}r(n.x),r(n.y);var i={};G(n.x,function(e){hk(n,`y`,e,i)}),G(n.y,function(e){hk(n,`x`,e,i)}),this.resize(this.model,t)},e.prototype.resize=function(e,t,n){var r=Hx(e,t),i=this._rect=Bx(e.getBoxLayoutParams(),r.refContainer),a=this._axesMap,o=this._coordsList,s=e.get(`containLabel`);if(bk(a,i),!n){var c=wk(i,o,a,s,t),l=void 0;if(s)Sk?(Sk(this._axesList,i),bk(a,i)):l=Ck(i.clone(),`axisLabel`,null,i,a,c,r);else{var u=Ek(e,i,r),d=u.outerBoundsRect,f=u.parsedOuterBoundsContain,p=u.outerBoundsClamp;d&&(l=Ck(d,f,p,i,a,c,r))}Tk(i,a,KE.determine,null,l,r),G(this._coordsList,function(e){e.calcAffineTransform()})}},e.prototype.getAxis=function(e,t){var n=this._axesMap[e];if(n!=null)return n[t||0]},e.prototype.getAxes=function(){return this._axesList.slice()},e.prototype.getCartesian=function(e,t){if(e!=null&&t!=null){var n=`x`+e+`y`+t;return this._coordsMap[n]}os(e)&&(t=e.yAxisIndex,e=e.xAxisIndex);for(var r=0,i=this._coordsList;r=0;i--){var a=e[+t[i]];wT(a.scale)&&jE(a.model,a.type,!0)==null&&(a.model.get(`alignTicks`)&&a.model.get(`interval`)==null?r.push(a):n=a)}n||=r.pop(),n&&G(r,function(e){e.__alignTo=n})}function vk(e,t){return Nb(e.scale)||Nb(t.scale)||t.scale.getTicks().length<2}function yk(e,t){var n=e.getExtent(),r=n[0]+n[1];e.toGlobalCoord=e.dim===`x`?function(e){return e+t}:function(e){return r-e+t},e.toLocalCoord=e.dim===`x`?function(e){return e-t}:function(e){return r-e+t}}function bk(e,t){G(e.x,function(e){return xk(e,t.x,t.width)}),G(e.y,function(e){return xk(e,t.y,t.height)})}function xk(e,t,n){var r=[0,n],i=+!!e.inverse;e.setExtent(r[i],r[1-i]),yk(e,t)}var Sk;function Ck(e,t,n,r,i,a,o){Tk(r,i,KE.estimate,t,!1,o);var s=[0,0,0,0];l(0),l(1),u(r,0,NaN),u(r,1,NaN);var c=$o(s,function(e){return e>0})==null;return ay(r,s,!0,!0,n),bk(i,r),c;function l(e){G(i[jv[e]],function(t){if(AE(t.model)){var n=a.ensureRecord(t.model),r=n.labelInfoList;if(r)for(var i=0;i0&&!fs(t)&&t>1e-4&&(e/=t),e}}function wk(e,t,n,r,i){var a=new oO(Dk);return G(n,function(n){return G(n,function(n){if(AE(n.model)){var o=!r;n.axisBuilder=LO(e,t,n.model,i,a,o)}})}),a}function Tk(e,t,n,r,i,a){var o=n===KE.determine;G(t,function(t){return G(t,function(t){AE(t.model)&&(RO(t.axisBuilder,e,t.model),t.axisBuilder.build(o?{axisTickLabelDetermine:!0}:{axisTickLabelEstimate:!0},{noPxChange:i}))})});var s={x:0,y:0};c(0),c(1);function c(t){s[jv[1-t]]=e[Mv[t]]<=a.refContainer[Mv[t]]*.5?0:1-t==1?2:1}G(t,function(e,t){return G(e,function(e){AE(e.model)&&((r===`all`||o)&&e.axisBuilder.build({axisName:!0},{nameMarginLevel:s[t]}),o&&e.axisBuilder.build({axisLine:!0}))})})}function Ek(e,t,n){var r,i=e.get(`outerBoundsMode`,!0);i===`same`?r=t.clone():(i==null||i===`auto`)&&(r=Bx(e.get(`outerBounds`,!0)||LE,n.refContainer));var a=e.get(`outerBoundsContain`,!0),o=a==null||a===`auto`||qo([`all`,`axisLabel`],a)<0?`all`:a,s=[Qs(X(e.get(`outerBoundsClampWidth`,!0),RE[0]),t.width),Qs(X(e.get(`outerBoundsClampHeight`,!0),RE[1]),t.height)];return{outerBoundsRect:r,parsedOuterBoundsContain:o,outerBoundsClamp:s}}var Dk=function(e,t,n,r,i,a){var o=n.axis.dim===`x`?`y`:`x`;uO(e,t,n,r,i,a),kE(e.nameLocation)||G(t.recordMap[o],function(e){e&&e.labelInfoList&&e.dirVec&&fO(e.labelInfoList,e.dirVec,r,i)})},Ok=function(){function e(e,t){this.target=e,this.topTarget=t&&t.topTarget}return e}(),kk=function(){function e(e){this.handler=e,e.on(`mousedown`,this._dragStart,this),e.on(`mousemove`,this._drag,this),e.on(`mouseup`,this._dragEnd,this)}return e.prototype._dragStart=function(e){for(var t=e.target;t&&!t.draggable;)t=t.parent||t.__hostTarget;t&&(this._draggingTarget=t,t.dragging=!0,this._x=e.offsetX,this._y=e.offsetY,this.handler.dispatchToElement(new Ok(t,e),`dragstart`,e.event))},e.prototype._drag=function(e){var t=this._draggingTarget;if(t){var n=e.offsetX,r=e.offsetY,i=n-this._x,a=r-this._y;this._x=n,this._y=r,t.drift(i,a,e),this.handler.dispatchToElement(new Ok(t,e),`drag`,e.event);var o=this.handler.findHover(n,r,t).target,s=this._dropTarget;this._dropTarget=o,t!==o&&(s&&o!==s&&this.handler.dispatchToElement(new Ok(s,e),`dragleave`,e.event),o&&o!==s&&this.handler.dispatchToElement(new Ok(o,e),`dragenter`,e.event))}},e.prototype._dragEnd=function(e){var t=this._draggingTarget;t&&(t.dragging=!1),this.handler.dispatchToElement(new Ok(t,e),`dragend`,e.event),this._dropTarget&&this.handler.dispatchToElement(new Ok(this._dropTarget,e),`drop`,e.event),this._draggingTarget=null,this._dropTarget=null},e}(),Ak=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,jk=[],Mk=Ns.browser.firefox&&+Ns.browser.version.split(`.`)[0]<39;function Nk(e,t,n,r){return n||={},r?Pk(e,t,n):Mk&&t.layerX!=null&&t.layerX!==t.offsetX?(n.zrX=t.layerX,n.zrY=t.layerY):t.offsetX==null?Pk(e,t,n):(n.zrX=t.offsetX,n.zrY=t.offsetY),n}function Pk(e,t,n){if(Ns.domSupported&&e.getBoundingClientRect){var r=t.clientX,i=t.clientY;if(pb(e)){var a=e.getBoundingClientRect();n.zrX=r-a.left,n.zrY=i-a.top;return}if(ub(jk,e,r,i)){n.zrX=jk[0],n.zrY=jk[1];return}}n.zrX=n.zrY=0}function Fk(e){return e||window.event}function Ik(e,t,n){if(t=Fk(t),t.zrX!=null)return t;var r=t.type;if(r&&r.indexOf(`touch`)>=0){var i=r===`touchend`?t.changedTouches[0]:t.targetTouches[0];i&&Nk(e,i,t,n)}else{Nk(e,t,t,n);var a=Lk(t);t.zrDelta=a?a/120:-(t.detail||0)/3}var o=t.button;return t.which==null&&o!==void 0&&Ak.test(t.type)&&(t.which=o&1?1:o&2?3:o&4?2:0),t}function Lk(e){var t=e.wheelDelta;if(t)return t;var n=e.deltaX,r=e.deltaY;if(n==null||r==null)return t;var i=Math.abs(r===0?n:r),a=r>0?-1:r<0?1:n>0?-1:1;return 3*i*a}function Rk(e,t,n,r){e.addEventListener(t,n,r)}function zk(e,t,n,r){e.removeEventListener(t,n,r)}var Bk=function(e){e.preventDefault(),e.stopPropagation(),e.cancelBubble=!0};function Vk(e){return e.which===2||e.which===3}var Hk=function(){function e(){this._track=[]}return e.prototype.recognize=function(e,t,n){return this._doTrack(e,t,n),this._recognize(e)},e.prototype.clear=function(){return this._track.length=0,this},e.prototype._doTrack=function(e,t,n){var r=e.touches;if(r){for(var i={points:[],touches:[],target:t,event:e},a=0,o=r.length;a1&&r&&r.length>1){var a=Uk(r)/Uk(i);!isFinite(a)&&(a=1),t.pinchScale=a;var o=Wk(r);return t.pinchX=o[0],t.pinchY=o[1],{type:`pinch`,target:e[0].target,event:t}}}}},Kk=`silent`;function qk(e,t,n){return{type:e,event:n,target:t.target,topTarget:t.topTarget,cancelBubble:!1,offsetX:n.zrX,offsetY:n.zrY,gestureEvent:n.gestureEvent,pinchX:n.pinchX,pinchY:n.pinchY,pinchScale:n.pinchScale,wheelDelta:n.zrDelta,zrByTouch:n.zrByTouch,which:n.which,stop:Jk}}function Jk(){Bk(this.event)}var Yk=function(e){U(t,e);function t(){var t=e!==null&&e.apply(this,arguments)||this;return t.handler=null,t}return t.prototype.dispose=function(){},t.prototype.setCursor=function(){},t}(gp),Xk=function(){function e(e,t){this.x=e,this.y=t}return e}(),Zk=[`click`,`dblclick`,`mousewheel`,`mouseout`,`mouseup`,`mousedown`,`mousemove`,`contextmenu`],Qk=new Ru(0,0,0,0),$k=function(e){U(t,e);function t(t,n,r,i,a){var o=e.call(this)||this;return o._hovered=new Xk(0,0),o.storage=t,o.painter=n,o.painterRoot=i,o._pointerSize=a,r||=new Yk,o.proxy=null,o.setHandlerProxy(r),o._draggingMgr=new kk(o),o}return t.prototype.setHandlerProxy=function(e){this.proxy&&this.proxy.dispose(),e&&(G(Zk,function(t){e.on&&e.on(t,this[t],this)},this),e.handler=this),this.proxy=e},t.prototype.mousemove=function(e){var t=e.zrX,n=e.zrY,r=nA(this,t,n),i=this._hovered,a=i.target;a&&!a.__zr&&(i=this.findHover(i.x,i.y),a=i.target);var o=this._hovered=r?new Xk(t,n):this.findHover(t,n),s=o.target,c=this.proxy;c.setCursor&&c.setCursor(s?s.cursor:`default`),a&&s!==a&&this.dispatchToElement(i,`mouseout`,e),this.dispatchToElement(o,`mousemove`,e),s&&s!==a&&this.dispatchToElement(o,`mouseover`,e)},t.prototype.mouseout=function(e){var t=e.zrEventControl;t!==`only_globalout`&&this.dispatchToElement(this._hovered,`mouseout`,e),t!==`no_globalout`&&this.trigger(`globalout`,{type:`globalout`,event:e})},t.prototype.resize=function(){this._hovered=new Xk(0,0)},t.prototype.dispatch=function(e,t){var n=this[e];n&&n.call(this,t)},t.prototype.dispose=function(){this.proxy.dispose(),this.storage=null,this.proxy=null,this.painter=null},t.prototype.setCursorStyle=function(e){var t=this.proxy;t.setCursor&&t.setCursor(e)},t.prototype.dispatchToElement=function(e,t,n){e||={};var r=e.target;if(!(r&&r.silent)){for(var i=`on`+t,a=qk(t,e,n);r&&(r[i]&&(a.cancelBubble=!!r[i].call(r,a)),r.trigger(t,a),r=r.__hostTarget?r.__hostTarget:r.parent,!a.cancelBubble););a.cancelBubble||(this.trigger(t,a),this.painter&&this.painter.eachOtherLayer&&this.painter.eachOtherLayer(function(e){typeof e[i]==`function`&&e[i].call(e,a),e.trigger&&e.trigger(t,a)}))}},t.prototype.findHover=function(e,t,n){var r=this.storage.getDisplayList(),i=new Xk(e,t);if(tA(r,i,e,t,n),this._pointerSize&&!i.target){for(var a=[],o=this._pointerSize,s=o/2,c=new Ru(e-s,t-s,o,o),l=r.length-1;l>=0;l--){var u=r[l];u!==n&&!u.ignore&&!u.ignoreCoarsePointer&&(!u.parent||!u.parent.ignoreCoarsePointer)&&(Qk.copy(u.getBoundingRect()),u.transform&&Qk.applyTransform(u.transform),Qk.intersect(c)&&a.push(u))}if(a.length){for(var d=4,f=Math.PI/12,p=Math.PI*2,m=0;m4)return;this._downPoint=null}this.dispatchToElement(a,e,t)}});function eA(e,t,n){if(e[e.rectHover?`rectContain`:`contain`](t,n)){for(var r=e,i=void 0,a=!1;r;){if(r.ignoreClip&&(a=!0),!a){var o=r.getClipPath();if(o&&!o.contain(t,n))return!1}r.silent&&(i=!0);var s=r.__hostTarget;r=s?r.ignoreHostSilent?null:s:r.parent}return!i||Kk}return!1}function tA(e,t,n,r,i){for(var a=e.length-1;a>=0;a--){var o=e[a],s=void 0;if(o!==i&&!o.ignore&&(s=eA(o,n,r))&&(!t.topTarget&&(t.topTarget=o),s!==Kk)){t.target=o;break}}}function nA(e,t,n){var r=e.painter;return t<0||t>r.getWidth()||n<0||n>r.getHeight()}var rA=32,iA=7;function aA(e){for(var t=0;e>=rA;)t|=e&1,e>>=1;return e+t}function oA(e,t,n,r){var i=t+1;if(i===n)return 1;if(r(e[i++],e[t])<0){for(;i=0;)i++;return i-t}function sA(e,t,n){for(n--;t>>1,i(a,e[c])<0?s=c:o=c+1;var l=r-o;switch(l){case 3:e[o+3]=e[o+2];case 2:e[o+2]=e[o+1];case 1:e[o+1]=e[o];break;default:for(;l>0;)e[o+l]=e[o+l-1],l--}e[o]=a}}function lA(e,t,n,r,i,a){var o=0,s=0,c=1;if(a(e,t[n+i])>0){for(s=r-i;c0;)o=c,c=(c<<1)+1,c<=0&&(c=s);c>s&&(c=s),o+=i,c+=i}else{for(s=i+1;cs&&(c=s);var l=o;o=i-c,c=i-l}for(o++;o>>1);a(e,t[n+u])>0?o=u+1:c=u}return c}function uA(e,t,n,r,i,a){var o=0,s=0,c=1;if(a(e,t[n+i])<0){for(s=i+1;cs&&(c=s);var l=o;o=i-c,c=i-l}else{for(s=r-i;c=0;)o=c,c=(c<<1)+1,c<=0&&(c=s);c>s&&(c=s),o+=i,c+=i}for(o++;o>>1);a(e,t[n+u])<0?c=u:o=u+1}return c}function dA(e,t){var n=iA,r,i,a=0,o=[];r=[],i=[];function s(e,t){r[a]=e,i[a]=t,a+=1}function c(){for(;a>1;){var e=a-2;if(e>=1&&i[e-1]<=i[e]+i[e+1]||e>=2&&i[e-2]<=i[e]+i[e-1])i[e-1]i[e+1])break;u(e)}}function l(){for(;a>1;){var e=a-2;e>0&&i[e-1]=iA||m>=iA);if(h)break;f<0&&(f=0),f+=2}if(n=f,n<1&&(n=1),i===1){for(c=0;c=0;c--)e[p+c]=e[f+c];e[d]=o[u];return}for(var m=n;;){var h=0,g=0,_=!1;do if(t(o[u],e[l])<0){if(e[d--]=e[l--],h++,g=0,--i===0){_=!0;break}}else if(e[d--]=o[u--],g++,h=0,--s===1){_=!0;break}while((h|g)=0;c--)e[p+c]=e[f+c];if(i===0){_=!0;break}}if(e[d--]=o[u--],--s===1){_=!0;break}if(g=s-lA(e[l],o,0,s,s-1,t),g!==0){for(d-=g,u-=g,s-=g,p=d+1,f=u+1,c=0;c=iA||g>=iA);if(_)break;m<0&&(m=0),m+=2}if(n=m,n<1&&(n=1),s===1){for(d-=i,l-=i,p=d+1,f=l+1,c=i-1;c>=0;c--)e[p+c]=e[f+c];e[d]=o[u]}else if(s===0)throw Error();else for(f=d-(s-1),c=0;cs&&(c=s),cA(e,n,n+c,n+a,t),a=c}o.pushRun(n,a),o.mergeRuns(),i-=a,n+=a}while(i!==0);o.forceMergeRuns()}}var pA=!1;function mA(){pA||(pA=!0,console.warn(`z / z2 / zlevel of displayable is invalid, which may cause unexpected errors`))}function hA(e,t){return e.zlevel===t.zlevel?e.z===t.z?e.z2-t.z2:e.z-t.z:e.zlevel-t.zlevel}var gA=function(){function e(){this._roots=[],this._displayList=[],this._displayListLen=0,this.displayableSortFunc=hA}return e.prototype.traverse=function(e,t){for(var n=0;n=0&&this._roots.splice(r,1)},e.prototype.delAllRoots=function(){this._roots=[],this._displayList=[],this._displayListLen=0},e.prototype.getRoots=function(){return this._roots},e.prototype.dispose=function(){this._displayList=null,this._roots=null},e}(),_A=Ns.hasGlobalWindow&&(window.requestAnimationFrame&&window.requestAnimationFrame.bind(window)||window.msRequestAnimationFrame&&window.msRequestAnimationFrame.bind(window)||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame)||function(e){return setTimeout(e,16)};function vA(){return new Date().getTime()}var yA=function(e){U(t,e);function t(t){var n=e.call(this)||this;return n._running=!1,n._time=0,n._pausedTime=0,n._pauseStart=0,n._paused=!1,t||={},n.stage=t.stage||{},n}return t.prototype.addClip=function(e){e.animation&&this.removeClip(e),this._head?(this._tail.next=e,e.prev=this._tail,e.next=null,this._tail=e):this._head=this._tail=e,e.animation=this},t.prototype.addAnimator=function(e){e.animation=this;var t=e.getClip();t&&this.addClip(t)},t.prototype.removeClip=function(e){if(e.animation){var t=e.prev,n=e.next;t?t.next=n:this._head=n,n?n.prev=t:this._tail=t,e.next=e.prev=e.animation=null}},t.prototype.removeAnimator=function(e){var t=e.getClip();t&&this.removeClip(t),e.animation=null},t.prototype.update=function(e){for(var t=vA()-this._pausedTime,n=t-this._time,r=this._head;r;){var i=r.next;r.step(t,n)?(r.ondestroy(),this.removeClip(r),r=i):r=i}this._time=t,e||(this.trigger(`frame`,n),this.stage.update&&this.stage.update())},t.prototype._startLoop=function(){var e=this;this._running=!0;function t(){e._running&&(_A(t),!e._paused&&e.update())}_A(t)},t.prototype.start=function(){this._running||(this._time=vA(),this._pausedTime=0,this._startLoop())},t.prototype.stop=function(){this._running=!1},t.prototype.pause=function(){this._paused||=(this._pauseStart=vA(),!0)},t.prototype.resume=function(){this._paused&&=(this._pausedTime+=vA()-this._pauseStart,!1)},t.prototype.clear=function(){for(var e=this._head;e;){var t=e.next;e.prev=e.next=e.animation=null,e=t}this._head=this._tail=null},t.prototype.isFinished=function(){return this._head==null},t.prototype.animate=function(e,t){t||={},this.start();var n=new hp(e,t.loop);return this.addAnimator(n),n},t}(gp),bA=300,xA=Ns.domSupported,SA=(function(){var e=[`click`,`dblclick`,`mousewheel`,`wheel`,`mouseout`,`mouseup`,`mousedown`,`mousemove`,`contextmenu`],t=[`touchstart`,`touchend`,`touchmove`],n={pointerdown:1,pointerup:1,pointermove:1,pointerout:1};return{mouse:e,touch:t,pointer:K(e,function(e){var t=e.replace(`mouse`,`pointer`);return n.hasOwnProperty(t)?t:e})}})(),CA={mouse:[`mousemove`,`mouseup`],pointer:[`pointermove`,`pointerup`]},wA=!1;function TA(e){var t=e.pointerType;return t===`pen`||t===`touch`}function EA(e){e.touching=!0,e.touchTimer!=null&&(clearTimeout(e.touchTimer),e.touchTimer=null),e.touchTimer=setTimeout(function(){e.touching=!1,e.touchTimer=null},700)}function DA(e){e&&(e.zrByTouch=!0)}function OA(e,t){return Ik(e.dom,new AA(e,t),!0)}function kA(e,t){for(var n=t,r=!1;n&&n.nodeType!==9&&!(r=n.domBelongToZr||n!==t&&n===e.painterRoot);)n=n.parentNode;return r}var AA=function(){function e(e,t){this.stopPropagation=As,this.stopImmediatePropagation=As,this.preventDefault=As,this.type=t.type,this.target=this.currentTarget=e.dom,this.pointerType=t.pointerType,this.clientX=t.clientX,this.clientY=t.clientY}return e}(),jA={mousedown:function(e){e=Ik(this.dom,e),this.__mayPointerCapture=[e.zrX,e.zrY],this.trigger(`mousedown`,e)},mousemove:function(e){e=Ik(this.dom,e);var t=this.__mayPointerCapture;t&&(e.zrX!==t[0]||e.zrY!==t[1])&&this.__togglePointerCapture(!0),this.trigger(`mousemove`,e)},mouseup:function(e){e=Ik(this.dom,e),this.__togglePointerCapture(!1),this.trigger(`mouseup`,e)},mouseout:function(e){e=Ik(this.dom,e);var t=e.toElement||e.relatedTarget;kA(this,t)||(this.__pointerCapturing&&(e.zrEventControl=`no_globalout`),this.trigger(`mouseout`,e))},wheel:function(e){wA=!0,e=Ik(this.dom,e),this.trigger(`mousewheel`,e)},mousewheel:function(e){wA||(e=Ik(this.dom,e),this.trigger(`mousewheel`,e))},touchstart:function(e){e=Ik(this.dom,e),DA(e),this.__lastTouchMoment=new Date,this.handler.processGesture(e,`start`),jA.mousemove.call(this,e),jA.mousedown.call(this,e)},touchmove:function(e){e=Ik(this.dom,e),DA(e),this.handler.processGesture(e,`change`),jA.mousemove.call(this,e)},touchend:function(e){e=Ik(this.dom,e),DA(e),this.handler.processGesture(e,`end`),jA.mouseup.call(this,e),+new Date-this.__lastTouchMoment0&&(this._stillFrameAccum++,this._stillFrameAccum>this._sleepAfterStill&&this.animation.stop())},e.prototype.setSleepAfterStill=function(e){this._sleepAfterStill=e},e.prototype.wakeUp=function(){this._disposed||(this.animation.start(),this._stillFrameAccum=0)},e.prototype.refreshHover=function(){this._needsRefreshHover=!0},e.prototype.refreshHoverImmediately=function(){this._disposed||this._refresh({animUpdate:!1,refresh:!1,refreshHover:!0})},e.prototype.resize=function(e){this._disposed||(e||={},this.painter.resize(e.width,e.height),this.handler.resize())},e.prototype.clearAnimation=function(){this._disposed||this.animation.clear()},e.prototype.getWidth=function(){if(!this._disposed)return this.painter.getWidth()},e.prototype.getHeight=function(){if(!this._disposed)return this.painter.getHeight()},e.prototype.setCursorStyle=function(e){this._disposed||this.handler.setCursorStyle(e)},e.prototype.findHover=function(e,t){if(!this._disposed)return this.handler.findHover(e,t)},e.prototype.on=function(e,t,n){return this._disposed||this.handler.on(e,t,n),this},e.prototype.off=function(e,t){this._disposed||this.handler.off(e,t)},e.prototype.trigger=function(e,t){this._disposed||this.handler.trigger(e,t)},e.prototype.clear=function(){if(!this._disposed){for(var e=this.storage.getRoots(),t=0;t=0;o--)r[o]&&!Kc(r[o])?a=!0:(r[o]=null,!a&&i--);r.length=i,e[n]=r}}),delete e[rj],e},t.prototype.setTheme=function(e){this._theme=new Zy(e),this._resetOption(`recreate`,null)},t.prototype.getTheme=function(){return this._theme},t.prototype.getLocaleModel=function(){return this._locale},t.prototype.setUpdatePayload=function(e){this._payload=e},t.prototype.getUpdatePayload=function(){return this._payload},t.prototype.getComponent=function(e,t){var n=this._componentsMap.get(e);if(n){var r=n[t||0];if(r)return r;if(t==null){for(var i=0;i=t:n===`max`?e<=t:e===t}function gj(e,t){return e.join(`,`)===t.join(`,`)}var _j=G,vj=os,yj=[`areaStyle`,`lineStyle`,`nodeStyle`,`linkStyle`,`chordStyle`,`label`,`labelLine`];function bj(e){var t=e&&e.itemStyle;if(t)for(var n=0,r=yj.length;n0?e[n-1].seriesModel:null)}),Uj(e))})}function Uj(e){G(e,function(t,n){var r=[],i=[NaN,NaN],a=[t.stackResultDimension,t.stackedOverDimension],o=t.data,s=t.isStackedByIndex,c=t.seriesModel.get(`stackStrategy`)||`samesign`;o.modify(a,function(a,l,u){var d=o.get(t.stackedDimension,u);if(isNaN(d))return i;var f,p;s?p=o.getRawIndex(u):f=o.get(t.stackedByDimension,u);for(var m=NaN,h=n-1;h>=0;h--){var g=e[h];if(s||(p=g.data.rawIndexOf(g.stackedByDimension,f)),p>=0){var _=g.data.getByRawIndex(g.stackResultDimension,p);if(c===`all`||c===`positive`&&_>0||c===`negative`&&_<0||c===`samesign`&&d>=0&&_>0||c===`samesign`&&d<=0&&_<0){d=ac(d,_),m=_;break}}}return r[0]=d,r[1]=m,r})})}var Wj=function(){function e(){this.group=new y_,this.uid=$y(`viewComponent`)}return e.prototype.init=function(e,t){},e.prototype.render=function(e,t,n,r){},e.prototype.dispose=function(e,t){},e.prototype.updateView=function(e,t,n,r){},e.prototype.updateLayout=function(e,t,n,r){},e.prototype.updateVisual=function(e,t,n,r){},e.prototype.toggleBlurSeries=function(e,t,n){},e.prototype.eachRendered=function(e){var t=this.group;t&&t.traverse(e)},e}();Nl(Wj),Bl(Wj);function Gj(){var e=Qc();return function(t){var n=e(t),r=t.pipelineContext,i=!!n.large,a=!!n.progressiveRender,o=n.large=!!(r&&r.large),s=n.progressiveRender=!!(r&&r.progressiveRender);return(i!==o||a!==s)&&`reset`}}var Kj=Qc(),qj=Gj(),Jj=function(){function e(){this.group=new y_,this.uid=$y(`viewChart`),this.renderTask=GS({plan:Zj,reset:Qj}),this.renderTask.context={view:this}}return e.prototype.init=function(e,t){},e.prototype.render=function(e,t,n,r){},e.prototype.highlight=function(e,t,n,r){var i=e.getData(r&&r.dataType);i&&Xj(i,r,`emphasis`)},e.prototype.downplay=function(e,t,n,r){var i=e.getData(r&&r.dataType);i&&Xj(i,r,`normal`)},e.prototype.remove=function(e,t){this.group.removeAll()},e.prototype.dispose=function(e,t){},e.prototype.updateView=function(e,t,n,r){this.render(e,t,n,r)},e.prototype.updateVisual=function(e,t,n,r){this.render(e,t,n,r)},e.prototype.eachRendered=function(e){uy(this.group,e)},e.markUpdateMethod=function(e,t){Kj(e).updateMethod=t},e.protoInitialize=function(){var t=e.prototype;t.type=`chart`}(),e}();function Yj(e,t,n){e&&Kg(e)&&(t===`emphasis`?xg:Sg)(e,n)}function Xj(e,t,n){var r=Zc(e,t),i=t&&t.highlightKey!=null?qg(t.highlightKey):null;r==null?e.eachItemGraphicEl(function(e){Yj(e,n,i)}):G(Ac(r),function(t){Yj(e.getItemGraphicEl(t),n,i)})}Nl(Jj,[`dispose`]),Bl(Jj);function Zj(e){return qj(e.model)}function Qj(e){var t=e.model,n=e.ecModel,r=e.api,i=e.payload,a=t.pipelineContext.progressiveRender,o=e.view,s=i&&Kj(i).updateMethod,c=a?`incrementalPrepareRender`:s&&o[s]?s:`render`;return c!==`render`&&o[c](t,n,r,i),$j[c]}var $j={incrementalPrepareRender:{progress:function(e,t){t.view.incrementalRender(e,t.model,t.ecModel,t.api,t.payload)}},render:{forceFirstProgress:!0,progress:function(e,t){t.view.render(t.model,t.ecModel,t.api,t.payload)}}},eM=`\0__throttleOriginMethod`,tM=`\0__throttleRate`,nM=`\0__throttleType`;function rM(e,t,n){var r,i=0,a=0,o=null,s,c,l,u;t||=0;function d(){a=new Date().getTime(),o=null,e.apply(c,l||[])}var f=function(){var e=[...arguments];r=new Date().getTime(),c=this,l=e;var f=u||t,p=u||n;u=null,s=r-(p?i:a)-f,clearTimeout(o),p?o=setTimeout(d,f):s>=0?d():o=setTimeout(d,-s),i=r};return f.clear=function(){o&&=(clearTimeout(o),null)},f.debounceNextCall=function(e){u=e},f}function iM(e,t,n,r){var i=e[t];if(i){var a=i[eM]||i,o=i[nM];if(i[tM]!==n||o!==r){if(n==null||!r)return e[t]=a;i=e[t]=rM(a,n,r===`debounce`),i[eM]=a,i[nM]=r,i[tM]=n}return i}}function aM(e,t){var n=e[t];n&&n[eM]&&(n.clear&&n.clear(),e[t]=n[eM])}var oM=Qc(),sM={itemStyle:Vl(Jy,!0),lineStyle:Vl(Gy,!0)},cM={lineStyle:`stroke`,itemStyle:`fill`};function lM(e,t){return e.visualStyleMapper||sM[t]||(console.warn(`Unknown style type '`+t+`'.`),sM.itemStyle)}function uM(e,t){return e.visualDrawType||cM[t]||(console.warn(`Unknown style type '`+t+`'.`),`fill`)}var dM={createOnAllSeries:!0,performRawSeries:!0,reset:function(e,t){var n=e.getData(),r=e.visualStyleAccessPath||`itemStyle`,i=e.getModel(r),a=lM(e,r)(i),o=i.getShallow(`decal`);o&&(n.setVisual(`decal`,o),o.dirty=!0);var s=uM(e,r),c=a[s],l=rs(c)?c:null,u=a.fill===`auto`||a.stroke===`auto`;if(!a[s]||l||u){var d=e.getColorFromPalette(e.name,null,t.getSeriesCount());a[s]||(a[s]=d,n.setVisual(`colorFromPalette`,!0)),a.fill=a.fill===`auto`||rs(a.fill)?d:a.fill,a.stroke=a.stroke===`auto`||rs(a.stroke)?d:a.stroke}if(n.setVisual(`style`,a),n.setVisual(`drawType`,s),!t.isSeriesFiltered(e)&&l)return n.setVisual(`colorFromPalette`,!1),{dataEach:function(t,n){var r=e.getDataParams(n),i=W({},a);i[s]=l(r),t.setItemVisual(n,`style`,i)}}}},fM=new Zy,pM={createOnAllSeries:!0,reset:function(e,t){if(!e.ignoreStyleOnData){var n=e.getData(),r=e.visualStyleAccessPath||`itemStyle`,i=lM(e,r),a=n.getVisual(`drawType`);return{dataEach:n.hasItemOption?function(e,t){var n=e.getRawDataItem(t);if(n&&n[r]){fM.option=n[r];var o=i(fM);W(e.ensureUniqueItemVisual(t,`style`),o),fM.option.decal&&(e.setItemVisual(t,`decal`,fM.option.decal),fM.option.decal.dirty=!0),a in o&&e.setItemVisual(t,`colorFromPalette`,!1)}}:null}}}},mM={performRawSeries:!0,overallReset:function(e){var t=Es();e.eachSeries(function(e){if(!e.isColorBySeries()){var n=e.type+`-`+e.getColorBy();oM(e).scope=t.get(n)||t.set(n,{})}}),e.eachSeries(function(e){if(!e.isColorBySeries()){var t=e.getRawData(),n={},r=e.getData(),i=oM(e).scope,a=uM(e,e.visualStyleAccessPath||`itemStyle`);r.each(function(e){var t=r.getRawIndex(e);n[t]=e}),t.each(function(o){var s=n[o];if(r.getItemVisual(s,`colorFromPalette`)){var c=r.ensureUniqueItemVisual(s,`style`),l=t.getName(o)||o+``,u=t.count();c[a]=e.getColorFromPalette(l,i,u)}})}})}},hM=Math.PI;function gM(e,t){t||={},Ko(t,{text:`loading`,textColor:Q.color.primary,fontSize:12,fontWeight:`normal`,fontStyle:`normal`,fontFamily:`sans-serif`,maskColor:`rgba(255,255,255,0.8)`,showSpinner:!0,color:Q.color.theme[0],spinnerRadius:10,lineWidth:5,zlevel:0});var n=new y_,r=new fh({style:{fill:t.maskColor},zlevel:t.zlevel,z:1e4});n.add(r);var i=new _h({style:{text:t.text,fill:t.textColor,fontSize:t.fontSize,fontWeight:t.fontWeight,fontStyle:t.fontStyle,fontFamily:t.fontFamily},zlevel:t.zlevel,z:10001}),a=new fh({style:{fill:`none`},textContent:i,textConfig:{position:`right`,distance:10},zlevel:t.zlevel,z:10001});n.add(a);var o;return t.showSpinner&&(o=new rv({shape:{startAngle:-hM/2,endAngle:-hM/2+.1,r:t.spinnerRadius},style:{stroke:t.color,lineCap:`round`,lineWidth:t.lineWidth},zlevel:t.zlevel,z:10001}),o.animateShape(!0).when(1e3,{endAngle:hM*3/2}).start(`circularInOut`),o.animateShape(!0).when(1e3,{startAngle:hM*3/2}).delay(300).start(`circularInOut`),n.add(o)),n.resize=function(){var n=i.getBoundingRect().width,s=t.showSpinner?t.spinnerRadius:0,c=(e.getWidth()-s*2-(t.showSpinner&&n?10:0)-n)/2-(t.showSpinner&&n?0:5+n/2)+(t.showSpinner?0:n/2)+(n?0:s),l=e.getHeight()/2;t.showSpinner&&o.setShape({cx:c,cy:l}),a.setShape({x:c-s,y:l-s,width:s*2,height:s*2}),r.setShape({x:0,y:0,width:e.getWidth(),height:e.getHeight()})},n.resize(),n}var _M=function(){function e(e,t,n,r){this._stageTaskMap=Es(),this.ecInstance=e,this.api=t,n=this._dataProcessorHandlers=n.slice(),r=this._visualHandlers=r.slice(),this._allHandlers=n.concat(r)}return e.prototype.restoreData=function(e,t){e.restoreData(t),this._stageTaskMap.each(function(e){var t=e.overallTask;t&&t.dirty()})},e.prototype.getPerformArgs=function(e,t){if(e.__pipeline){var n=this._pipelineMap.get(e.__pipeline.id),r=n.context,i=!t&&n.progressiveEnabled&&(!r||r.progressiveRender)&&e.__idxInPipeline>n.blockIndex?n.step:null,a=r&&r.modDataCount;return{step:i,modBy:a==null?null:Math.ceil(a/i),modDataCount:a}}},e.prototype.getPipeline=function(e){return this._pipelineMap.get(e)},e.prototype.updateStreamModes=function(e,t){var n=this._pipelineMap.get(e.uid);e.pipelineContext=n.context=e.__preparePipelineContext?e.__preparePipelineContext(t,n):Tl(e,t,n)},e.prototype.restorePipelines=function(e,t){var n=this,r=n._pipelineMap=Es();t.eachSeries(function(t){var i=e.painter.type===`canvas`&&t.getProgressive(),a=t.uid;r.set(a,{id:a,head:null,tail:null,threshold:t.getProgressiveThreshold(),progressiveEnabled:i&&!(t.preventIncremental&&t.preventIncremental()),blockIndex:-1,step:Math.round(i||700),count:0}),n._pipe(t,t.dataTask)})},e.prototype.prepareStageTasks=function(){var e=this._stageTaskMap,t=this.api.getModel(),n=this.api;G(this._allHandlers,function(r){var i=e.get(r.uid)||e.set(r.uid,{});_s(!(r.reset&&r.overallReset),``),r.reset&&this._createSeriesStageTask(r,i,t,n),r.overallReset&&this._createOverallStageTask(r,i,t,n)},this)},e.prototype.prepareView=function(e,t,n,r){var i=e.renderTask,a=i.context;a.model=t,a.ecModel=n,a.api=r,i.__block=!e.incrementalPrepareRender,this._pipe(t,i)},e.prototype.performDataProcessorTasks=function(e,t){this._performStageTasks(this._dataProcessorHandlers,e,t,{block:!0})},e.prototype.performVisualTasks=function(e,t,n){this._performStageTasks(this._visualHandlers,e,t,n)},e.prototype._performStageTasks=function(e,t,n,r){r||={};var i=!1,a=this;G(e,function(e,s){if(!(r.visualType&&r.visualType!==e.visualType)){var c=a._stageTaskMap.get(e.uid),l=c.seriesTaskMap,u=c.overallTask;if(u){var d,f=u.agentStubMap;f.each(function(e){o(r,e)&&(e.dirty(),d=!0)}),d&&u.dirty(),a.updatePayload(u,n);var p=a.getPerformArgs(u,r.block);f.each(function(e){e.perform(p)}),u.perform(p)&&(i=!0)}else l&&l.each(function(s,c){o(r,s)&&s.dirty();var l=a.getPerformArgs(s,r.block);l.skip=!e.performRawSeries&&t.isSeriesFiltered(s.context.model),a.updatePayload(s,n),s.perform(l)&&(i=!0)})}});function o(e,t){return e.setDirty&&(!e.dirtyMap||e.dirtyMap.get(t.__pipeline.id))}this.unfinished=i||this.unfinished},e.prototype.performSeriesTasks=function(e){var t;e.eachSeries(function(e){t=e.dataTask.perform()||t}),this.unfinished=t||this.unfinished},e.prototype.plan=function(){this._pipelineMap.each(function(e){var t=e.tail;do{if(t.__block){e.blockIndex=t.__idxInPipeline;break}t=t.getUpstream()}while(t)})},e.prototype.updatePayload=function(e,t){t!==`remain`&&(e.context.payload=t)},e.prototype._createSeriesStageTask=function(e,t,n,r){var i=this,a=t.seriesTaskMap,o=t.seriesTaskMap=Es(),s=e.seriesType,c=e.getTargetSeries;e.createOnAllSeries?n.eachRawSeries(l):s?n.eachRawSeriesByType(s,l):c&&c(n,r).each(l);function l(t){var s=t.uid,c=o.set(s,a&&a.get(s)||GS({plan:SM,reset:CM,count:EM}));c.context={model:t,ecModel:n,api:r,useClearVisual:e.isVisual&&!e.isLayout,plan:e.plan,reset:e.reset,scheduler:i},i._pipe(t,c)}},e.prototype._createOverallStageTask=function(e,t,n,r){var i=this,a=t.overallTask=t.overallTask||GS({reset:vM});a.context={ecModel:n,api:r,overallReset:e.overallReset,scheduler:i};var o=a.agentStubMap,s=a.agentStubMap=Es(),c=e.seriesType,l=e.getTargetSeries,u=e.dirtyOnOverallProgress,d=!1;_s(!e.createOnAllSeries,``),c?n.eachRawSeriesByType(c,f):l?l(n,r).each(f):G(n.getSeries(),f);function f(e){var t=e.uid,n=s.set(t,o&&o.get(t)||(d=!0,GS({reset:yM,onDirty:xM})));n.context={model:e,dirtyOnOverallProgress:u},n.agent=a,n.__block=u,i._pipe(e,n)}d&&a.dirty()},e.prototype._pipe=function(e,t){var n=e.uid,r=this._pipelineMap.get(n);!r.head&&(r.head=t),r.tail&&r.tail.pipe(t),r.tail=t,t.__idxInPipeline=r.count++,t.__pipeline=r},e.wrapStageHandler=function(e,t){return rs(e)&&(e={overallReset:e,seriesType:DM(e)}),e.uid=$y(`stageHandler`),t&&(e.visualType=t),e},e}();function vM(e){e.overallReset(e.ecModel,e.api,e.payload)}function yM(e){return e.dirtyOnOverallProgress&&bM}function bM(){this.agent.dirty(),this.getDownstream().dirty()}function xM(){this.agent&&this.agent.dirty()}function SM(e){return e.plan?e.plan(e.model,e.ecModel,e.api,e.payload):null}function CM(e){e.useClearVisual&&e.data.clearAllVisual();var t=e.resetDefines=Ac(e.reset(e.model,e.ecModel,e.api,e.payload));return t.length>1?K(t,function(e,t){return TM(t)}):wM}var wM=TM(0);function TM(e){return function(t,n){var r=n.data,i=n.resetDefines[e];if(i&&i.dataEach)for(var a=t.start;a0&&u===i.length-l.length){var d=i.slice(0,u);d!==`data`&&(t.mainType=d,t[l.toLowerCase()]=e,s=!0)}}o.hasOwnProperty(i)&&(n[i]=e,s=!0),s||(r[i]=e)})}return{cptQuery:t,dataQuery:n,otherQuery:r}},e.prototype.filter=function(e,t){var n=this.eventInfo;if(!n)return!0;var r=n.targetEl,i=n.packedEvent,a=n.model,o=n.view;if(!a||!o)return!0;var s=t.cptQuery,c=t.dataQuery;return l(s,a,`mainType`)&&l(s,a,`subType`)&&l(s,a,`index`,`componentIndex`)&&l(s,a,`name`)&&l(s,a,`id`)&&l(c,i,`name`)&&l(c,i,`dataIndex`)&&l(c,i,`dataType`)&&(!o.filterForExposedEvent||o.filterForExposedEvent(e,t.otherQuery,r,i));function l(e,t,n,r){return e[n]==null||t[r||n]===e[n]}},e.prototype.afterTrigger=function(){this.eventInfo=null},e}(),LM=[`symbol`,`symbolSize`,`symbolRotate`,`symbolOffset`],RM=LM.concat([`symbolKeepAspect`]),zM={createOnAllSeries:!0,performRawSeries:!0,reset:function(e,t){var n=e.getData();if(e.legendIcon&&n.setVisual(`legendIcon`,e.legendIcon),!e.hasSymbolVisual)return;for(var r={},i={},a=!1,o=0;o=0&&rN(c)?c:.5,e.createRadialGradient(o,s,0,o,s,c)}function oN(e,t,n){for(var r=t.type===`radial`?aN(e,t,n):iN(e,t,n),i=t.colorStops,a=0;a0)?null:e===`dashed`?[4*t,2*t]:e===`dotted`?[t]:as(e)?[e]:J(e)?e:null}function dN(e){var t=e.style,n=t.lineDash&&t.lineWidth>0&&uN(t.lineDash,t.lineWidth),r=t.lineDashOffset;if(n){var i=t.strokeNoScale&&e.getLineScale?e.getLineScale():1;i&&i!==1&&(n=K(n,function(e){return e/i}),r/=i)}return[n,r]}var fN=new Dm(!0);function pN(e){var t=e.stroke;return!(t==null||t===`none`||!(e.lineWidth>0))}function mN(e){return typeof e==`string`&&e!==`none`}function hN(e){var t=e.fill;return t!=null&&t!==`none`}function gN(e,t){if(t.fillOpacity!=null&&t.fillOpacity!==1){var n=e.globalAlpha;e.globalAlpha=t.fillOpacity*t.opacity,e.fill(),e.globalAlpha=n}else e.fill()}function _N(e,t){if(t.strokeOpacity!=null&&t.strokeOpacity!==1){var n=e.globalAlpha;e.globalAlpha=t.strokeOpacity*t.opacity,e.stroke(),e.globalAlpha=n}else e.stroke()}function vN(e,t,n){var r=Yl(t.image,t.__image,n);if(Zl(r)){var i=e.createPattern(r,t.repeat||`repeat`);if(typeof DOMMatrix==`function`&&i&&i.setTransform){var a=new DOMMatrix;a.translateSelf(t.x||0,t.y||0),a.rotateSelf(0,0,(t.rotation||0)*js),a.scaleSelf(t.scaleX||1,t.scaleY||1),i.setTransform(a)}return i}}function yN(e,t,n,r,i){var a,o=pN(n),s=hN(n),c=n.strokePercent,l=c<1,u=!t.path;(!t.silent||l)&&u&&t.createPathProxy();var d=t.path||fN,f=t.__dirty;if(!r){var p=n.fill,m=n.stroke,h=s&&!!p.colorStops,g=o&&!!m.colorStops,_=s&&!!p.image,v=o&&!!m.image,y=void 0,b=void 0,x=void 0,S=void 0,C=void 0;(h||g)&&(C=t.getBoundingRect()),h&&(y=f?oN(e,p,C):t.__canvasFillGradient,t.__canvasFillGradient=y),g&&(b=f?oN(e,m,C):t.__canvasStrokeGradient,t.__canvasStrokeGradient=b),_&&(x=f||!t.__canvasFillPattern?vN(e,p,t):t.__canvasFillPattern,t.__canvasFillPattern=x),v&&(S=f||!t.__canvasStrokePattern?vN(e,m,t):t.__canvasStrokePattern,t.__canvasStrokePattern=S),h?e.fillStyle=y:_&&(x?e.fillStyle=x:s=!1),g?e.strokeStyle=b:v&&(S?e.strokeStyle=S:o=!1)}var w=t.getGlobalScale();d.setScale(w[0],w[1],t.segmentIgnoreThreshold);var T,E;e.setLineDash&&n.lineDash&&(a=dN(t),T=a[0],E=a[1]);var D=!0;(u||f&4)&&(d.setDPR(e.dpr),l?d.setContext(null):(d.setContext(e),D=!1),d.reset(),t.buildPath(d,t.shape,r),d.toStatic(),t.pathUpdated()),D&&d.rebuildPath(e,l?c:1),T&&(e.setLineDash(T),e.lineDashOffset=E),r?(i.batchFill=s,i.batchStroke=o):n.strokeFirst?(o&&_N(e,n),s&&gN(e,n)):(s&&gN(e,n),o&&_N(e,n)),T&&e.setLineDash([])}function bN(e,t,n){var r=t.__image=Yl(n.image,t.__image,t,t.onload);if(r&&Zl(r)){var i=n.x||0,a=n.y||0,o=t.getWidth(),s=t.getHeight(),c=r.width/r.height;if(o==null&&s!=null?o=s*c:s==null&&o!=null?s=o/c:o==null&&s==null&&(o=r.width,s=r.height),n.sWidth&&n.sHeight){var l=n.sx||0,u=n.sy||0;e.drawImage(r,l,u,n.sWidth,n.sHeight,i,a,o,s)}else if(n.sx&&n.sy){var l=n.sx,u=n.sy,d=o-l,f=s-u;e.drawImage(r,l,u,d,f,i,a,o,s)}else e.drawImage(r,i,a,o,s)}}function xN(e,t,n){var r,i=n.text;if(i!=null&&(i+=``),i){e.font=n.font||`12px sans-serif`,e.textAlign=n.textAlign,e.textBaseline=n.textBaseline;var a=void 0,o=void 0;e.setLineDash&&n.lineDash&&(r=dN(t),a=r[0],o=r[1]),a&&(e.setLineDash(a),e.lineDashOffset=o),n.strokeFirst?(pN(n)&&e.strokeText(i,n.x,n.y),hN(n)&&e.fillText(i,n.x,n.y)):(hN(n)&&e.fillText(i,n.x,n.y),pN(n)&&e.strokeText(i,n.x,n.y)),a&&e.setLineDash([])}}var SN=[`shadowBlur`,`shadowOffsetX`,`shadowOffsetY`],CN=[[`lineCap`,`butt`],[`lineJoin`,`miter`],[`miterLimit`,10]];function wN(e,t,n,r,i){var a=!1;if(!r&&(n||={},t===n))return!1;if(r||t.opacity!==n.opacity){FN(e,i),a=!0;var o=Math.max(Math.min(t.opacity,1),0);e.globalAlpha=isNaN(o)?Vp.opacity:o}(r||t.blend!==n.blend)&&(a||=(FN(e,i),!0),e.globalCompositeOperation=t.blend||Vp.blend);for(var s=0;s0&&e.unfinished);e.unfinished||this._zr.flush()}}},t.prototype.getDom=function(){return this._dom},t.prototype.getId=function(){return this.id},t.prototype.getZr=function(){return this._zr},t.prototype.isSSR=function(){return this._ssr},t.prototype.setOption=function(e,t,n){if(!this[hP]){if(this._disposed){this.id;return}var r,i,a;if(os(t)&&(n=t.lazyUpdate,r=t.silent,i=t.replaceMerge,a=t.transition,t=t.notMerge),this[hP]=!0,qP(this),!this._model||t){var o=new fj(this._api),s=this._theme,c=this._model=new aj;c.scheduler=this._scheduler,c.ssr=this._ssr,c.init(null,null,null,s,this._locale,o)}this._model.setOption(e,{replaceMerge:i},tF);var l={seriesTransition:a,optionChanged:!0};if(n)this[_P]={silent:r,updateParams:l},this[hP]=!1,this.getZr().wakeUp();else{try{kP(this),MP.update.call(this,null,l)}catch(e){throw this[_P]=null,this[hP]=!1,e}this._ssr||this._zr.flush(),this[_P]=null,this[hP]=!1,IP.call(this,r),LP.call(this,r)}}},t.prototype.setTheme=function(e,t){if(!this[hP]){if(this._disposed){this.id;return}var n=this._model;if(n){var r=t&&t.silent,i=null;this[_P]&&(r??=this[_P].silent,i=this[_P].updateParams,this[_P]=null),this[hP]=!0,qP(this);try{this._updateTheme(e),n.setTheme(this._theme),kP(this),MP.update.call(this,{type:`setTheme`},i)}catch(e){throw this[hP]=!1,e}this[hP]=!1,IP.call(this,r),LP.call(this,r)}}},t.prototype._updateTheme=function(e){Y(e)&&(e=rF[e]),e&&(e=Ho(e),e&&Bj(e,!0),this._theme=e)},t.prototype.getModel=function(){return this._model},t.prototype.getOption=function(){return this._model&&this._model.getOption()},t.prototype.getWidth=function(){return this._zr.getWidth()},t.prototype.getHeight=function(){return this._zr.getHeight()},t.prototype.getDevicePixelRatio=function(){return this._zr.painter.dpr||Ns.hasGlobalWindow&&window.devicePixelRatio||1},t.prototype.getRenderedCanvas=function(e){return this.renderToCanvas(e)},t.prototype.renderToCanvas=function(e){return e||={},this._zr.painter.getRenderedCanvas({backgroundColor:e.backgroundColor||this._model.get(`backgroundColor`),pixelRatio:e.pixelRatio||this.getDevicePixelRatio()})},t.prototype.renderToSVGString=function(e){return e||={},this._zr.painter.renderToString({useViewBox:e.useViewBox})},t.prototype.getSvgDataURL=function(){var e=this._zr;return G(e.storage.getDisplayList(),function(e){e.stopAnimation(null,!0)}),e.painter.toDataURL()},t.prototype.getDataURL=function(e){if(this._disposed){this.id;return}e||={};var t=e.excludeComponents,n=this._model,r=[],i=this;G(t,function(e){n.eachComponent({mainType:e},function(e){var t=i._componentsMap[e.__viewId];t.group.ignore||(r.push(t),t.group.ignore=!0)})});var a=this._zr.painter.getType()===`svg`?this.getSvgDataURL():this.renderToCanvas(e).toDataURL(`image/`+(e&&e.type||`png`));return G(r,function(e){e.group.ignore=!1}),a},t.prototype.getConnectedDataURL=function(e){if(this._disposed){this.id;return}var t=e.type===`svg`,n=this.group,r=Math.min,i=Math.max,a=1/0;if(oF[n]){var o=a,s=a,c=-a,l=-a,u=[],d=e&&e.pixelRatio||this.getDevicePixelRatio();G(aF,function(a,d){if(a.group===n){var f=t?a.getZr().painter.getSvgDom().innerHTML:a.renderToCanvas(Ho(e)),p=a.getDom().getBoundingClientRect();o=r(p.left,o),s=r(p.top,s),c=i(p.right,c),l=i(p.bottom,l),u.push({dom:f,left:p.left,top:p.top})}}),o*=d,s*=d,c*=d,l*=d;var f=c-o,p=l-s,m=Eo.createCanvas(),h=WA(m,{renderer:t?`svg`:`canvas`});if(h.resize({width:f,height:p}),t){var g=``;return G(u,function(e){var t=e.left-o,n=e.top-s;g+=``+e.dom+``}),h.painter.getSvgRoot().innerHTML=g,e.connectedBackgroundColor&&h.painter.setBackgroundColor(e.connectedBackgroundColor),h.refreshImmediately(),h.painter.toDataURL()}return e.connectedBackgroundColor&&h.add(new fh({shape:{x:0,y:0,width:f,height:p},style:{fill:e.connectedBackgroundColor}})),G(u,function(e){var t=new ih({style:{x:e.left*d-o,y:e.top*d-s,image:e.dom}});h.add(t)}),h.refreshImmediately(),m.toDataURL(`image/`+(e&&e.type||`png`))}return this.getDataURL(e)},t.prototype.convertToPixel=function(e,t,n){return NP(this,`convertToPixel`,e,t,n)},t.prototype.convertToLayout=function(e,t,n){return NP(this,`convertToLayout`,e,t,n)},t.prototype.convertFromPixel=function(e,t,n){return NP(this,`convertFromPixel`,e,t,n)},t.prototype.containPixel=function(e,t){if(this._disposed){this.id;return}var n=this._model,r;return G(el(n,e),function(e,n){n.indexOf(`Models`)>=0&&G(e,function(e){var i=e.coordinateSystem;if(i&&i.containPoint)r||=!!i.containPoint(t);else if(n===`seriesModels`){var a=this._chartsMap[e.__viewId];a&&a.containPoint&&(r||=a.containPoint(t,e))}},this)},this),!!r},t.prototype.getVisual=function(e,t){var n=this._model,r=el(n,e,{defaultMainType:`series`}),i=r.seriesModel.getData(),a=r.hasOwnProperty(`dataIndexInside`)?r.dataIndexInside:r.hasOwnProperty(`dataIndex`)?i.indexOfRawIndex(r.dataIndex):null;return a==null?HM(i,t):VM(i,a,t)},t.prototype.getViewOfComponentModel=function(e){return this._componentsMap[e.__viewId]},t.prototype.getViewOfSeriesModel=function(e){return this._chartsMap[e.__viewId]},t.prototype._initEvents=function(){var e=this;G(XP,function(t){var n=function(n){var r=e.getModel(),i=n.target,a;if(t===`globalout`?a={}:i&&KM(i,function(e){var t=jh(e);if(t&&t.dataIndex!=null){var n=t.dataModel||r.getSeriesByIndex(t.seriesIndex);return a=n&&n.getDataParams(t.dataIndex,t.dataType,i)||{},!0}if(t.eventData)return a=W({},t.eventData),!0},!0),a){var o=a.componentType,s=a.componentIndex;(o===`markLine`||o===`markPoint`||o===`markArea`)&&(o=`series`,s=a.seriesIndex);var c=o&&s!=null&&r.getComponent(o,s),l=c&&e[c.mainType===`series`?`_chartsMap`:`_componentsMap`][c.__viewId];a.event=n,a.type=t,e._$eventProcessor.eventInfo={targetEl:i,packedEvent:a,model:c,view:l},e.trigger(t,a)}};n.zrEventfulCallAtLast=!0,e._zr.on(t,n,e)});var t=this._messageCenter;G($P,function(n,r){t.on(r,function(t){e.trigger(r,t)})}),GM(t,this,this._api)},t.prototype.isDisposed=function(){return this._disposed},t.prototype.clear=function(){if(this._disposed){this.id;return}this.setOption({series:[]},!0)},t.prototype.dispose=function(){if(this._disposed){this.id;return}this._disposed=!0,this.getDom()&&ol(this.getDom(),lF,``);var e=this,t=e._api,n=e._model;G(e._componentsViews,function(e){e.dispose(n,t)}),G(e._chartsViews,function(e){e.dispose(n,t)}),e._zr.dispose(),e._dom=e._model=e._chartsMap=e._componentsMap=e._chartsViews=e._componentsViews=e._scheduler=e._api=e._zr=e._throttledZrFlush=e._theme=e._coordSysMgr=e._messageCenter=null,delete aF[e.id]},t.prototype.resize=function(e){if(!this[hP]){if(this._disposed){this.id;return}this._zr.resize(e);var t=this._model;if(this._loadingFX&&this._loadingFX.resize(),t){var n=t.resetOption(`media`),r=e&&e.silent;this[_P]&&(r??=this[_P].silent,n=!0,this[_P]=null),this[hP]=!0,qP(this);try{n&&kP(this),MP.update.call(this,{type:`resize`,animation:W({duration:0},e&&e.animation)})}catch(e){throw this[hP]=!1,e}this[hP]=!1,IP.call(this,r),LP.call(this,r)}}},t.prototype.showLoading=function(e,t){if(this._disposed){this.id;return}if(os(e)&&(t=e,e=``),e||=`default`,this.hideLoading(),iF[e]){var n=iF[e](this._api,t),r=this._zr;this._loadingFX=n,r.add(n)}},t.prototype.hideLoading=function(){if(this._disposed){this.id;return}this._loadingFX&&this._zr.remove(this._loadingFX),this._loadingFX=null},t.prototype.makeActionFromEvent=function(e){var t=W({},e);return t.type=QP[e.type],t},t.prototype.dispatchAction=function(e,t){if(this._disposed){this.id;return}if(os(t)||(t={silent:!!t}),ZP[e.type]&&this._model){if(this[hP]){this._pendingActions.push(e);return}var n=t.silent;FP.call(this,e,n);var r=t.flush;r?this._zr.flush():r!==!1&&Ns.browser.weChat&&this._throttledZrFlush(),IP.call(this,n),LP.call(this,n)}},t.prototype.updateLabelLayout=function(){qM.trigger(`series:layoutlabels`,this._model,this._api,{updatedSeries:[]})},t.prototype.appendData=function(e){if(this._disposed){this.id;return}var t=e.seriesIndex;this.getModel().getSeriesByIndex(t).appendData(e),this._scheduler.unfinished=!0,this.getZr().wakeUp()},t.internalField=function(){kP=function(e){pD(e._model);var t=e._scheduler;t.restorePipelines(e._zr,e._model),t.prepareStageTasks(),AP(e,!0),AP(e,!1),t.plan()},AP=function(e,t){for(var n=e._model,r=e._scheduler,i=t?e._componentsViews:e._chartsViews,a=t?e._componentsMap:e._chartsMap,o=e._zr,s=e._api,c=0;cX(t.get(`hoverLayerThreshold`),XA.hoverLayerThreshold)&&!Ns.node&&!Ns.worker;(e._usingTHL||a)&&(t.eachSeries(function(t){if(!t.preventUsingHoverLayer){var n=e._chartsMap[t.__viewId];n.__alive&&n.eachRendered(function(e){var t=e.states.emphasis;t&&t.hoverLayer!==2&&(t.hoverLayer=+!!a)})}}),e._usingTHL=a)}}function a(e,t){var n=e.get(`blendMode`)||null;t.eachRendered(function(e){e.isGroup||(e.style.blend=n)})}function o(e,t){if(!e.preventAutoZ){var n=hy(e);t.eachRendered(function(e){return _y(e,n.z,n.zlevel),!0})}}function s(e,t){t.eachRendered(function(e){if(!wv(e)){var t=e.getTextContent(),n=e.getTextGuideLine();e.stateTransition&&=null,t&&t.stateTransition&&(t.stateTransition=null),n&&n.stateTransition&&(n.stateTransition=null),e.hasState()?(e.prevStates=e.currentStates,e.clearStates()):e.prevStates&&=null}})}function c(e,t){var n=e.getModel(`stateAnimation`),i=e.isAnimationEnabled(),a=n.get(`duration`),o=a>0?{duration:a,delay:n.get(`delay`),easing:n.get(`easing`)}:null;t.eachRendered(function(e){if(e.states&&e.states.emphasis){if(wv(e))return;if(e instanceof Qm&&Xg(e),e.__dirty){var t=e.prevStates;t&&e.useStates(t)}if(i){e.stateTransition=o;var n=e.getTextContent(),a=e.getTextGuideLine();n&&(n.stateTransition=o),a&&(a.stateTransition=o)}e.__dirty&&r(e)}})}UP=function(e){return new(function(t){U(n,t);function n(){return t!==null&&t.apply(this,arguments)||this}return n.prototype.getCoordinateSystems=function(){return e._coordSysMgr.getCoordinateSystems()},n.prototype.getComponentByElement=function(t){for(;t;){var n=t.__ecComponentInfo;if(n!=null)return e._model.getComponent(n.mainType,n.index);t=t.parent}},n.prototype.enterEmphasis=function(t,n){xg(t,n),GP(e)},n.prototype.leaveEmphasis=function(t,n){Sg(t,n),GP(e)},n.prototype.enterBlur=function(t){Cg(t),GP(e)},n.prototype.leaveBlur=function(t){wg(t),GP(e)},n.prototype.enterSelect=function(t){Tg(t),GP(e)},n.prototype.leaveSelect=function(t){Eg(t),GP(e)},n.prototype.getModel=function(){return e.getModel()},n.prototype.getViewOfComponentModel=function(t){return e.getViewOfComponentModel(t)},n.prototype.getViewOfSeriesModel=function(t){return e.getViewOfSeriesModel(t)},n.prototype.getECUpdateCycleVersion=function(){return e[gP]},n.prototype.usingTHL=function(){return e._usingTHL},n}(Hh))(e)},WP=function(e){function t(e,t){for(var n=0;n=0)){wF.push(n);var o=_M.wrapStageHandler(n,i);o.__prio=t,o.__raw=n,e.push(o)}}function EF(e,t){iF[e]=t}function DF(e,t,n){var r=XM(`registerMap`);r&&r(e,t,n)}var OF=oC;CF(oP,dM),CF(lP,pM),CF(lP,mM),CF(oP,zM),CF(lP,BM),CF(pP,YN),hF(Bj),gF($N,Vj),EF(`default`,gM),bF({type:Xh,event:Xh,update:Xh},As),bF({type:Zh,event:Zh,update:Zh},As),bF({type:Qh,event:tg,update:Qh,action:As,refineEvent:kF,publishNonRefinedEvent:!0}),bF({type:$h,event:tg,update:$h,action:As,refineEvent:kF,publishNonRefinedEvent:!0}),bF({type:eg,event:tg,update:eg,action:As,refineEvent:kF,publishNonRefinedEvent:!0});function kF(e,t,n,r){return{eventContent:{selected:Lg(n),isFromClick:t.isFromClick||!1}}}mF(`default`,{}),mF(`dark`,FM);var AF=[],jF={registerPreprocessor:hF,registerProcessor:gF,registerPostInit:_F,registerPostUpdate:vF,registerUpdateLifecycle:yF,registerAction:bF,registerCoordinateSystem:xF,registerLayout:SF,registerVisual:CF,registerTransform:OF,registerLoading:EF,registerMap:DF,registerImpl:YM,PRIORITY:mP,ComponentModel:Yx,ComponentView:Wj,SeriesModel:ZC,ChartView:Jj,registerComponentModel:function(e){Yx.registerClass(e)},registerComponentView:function(e){Wj.registerClass(e)},registerSeriesModel:function(e){ZC.registerClass(e)},registerChartView:function(e){Jj.registerClass(e)},registerCustomSeries:function(e,t){QM(e,t)},registerSubTypeDefaulter:function(e,t){Yx.registerSubTypeDefaulter(e,t)},registerPainter:function(e,t){GA(e,t)}};function MF(e){if(J(e)){G(e,function(e){MF(e)});return}qo(AF,e)>=0||(AF.push(e),rs(e)&&(e={install:e}),e.install(jF))}var NF=function(){function e(e,t){this._encode=e,this._schema=t}return e.prototype.get=function(){return{fullDimensions:this._getFullDimensionNames(),encode:this._encode}},e.prototype._getFullDimensionNames=function(){return this._cachedDimNames||=this._schema?this._schema.makeOutputDimensionNames():[],this._cachedDimNames},e}();function PF(e,t){var n={},r=n.encode={},i=Es(),a=[],o=[],s={};G(e.dimensions,function(t){var n=e.getDimensionInfo(t),c=n.coordDim;if(c){var l=n.coordDimIndex;FF(r,c)[l]=t,n.isExtraCoord||(i.set(c,1),LF(n.type)&&(a[0]=t),FF(s,c)[l]=e.getDimensionIndex(n.name)),n.defaultTooltip&&o.push(t)}Nh.each(function(e,t){var i=FF(r,t),a=n.otherDims[t];a!=null&&a!==!1&&(i[a]=n.name)})});var c=[],l={};i.each(function(e,t){var n=r[t];l[t]=n[0],c=c.concat(n)}),n.dataDimsOnCoord=c,n.dataDimIndicesOnCoord=K(c,function(t){return e.getDimensionInfo(t).storeDimIndex}),n.encodeFirstDimNotExtra=l;var u=r.label;u&&u.length&&(a=u.slice());var d=r.tooltip;return d&&d.length?o=d.slice():o.length||(o=a.slice()),r.defaultedLabel=a,r.defaultedTooltip=o,n.userOutput=new NF(s,t),n}function FF(e,t){return e.hasOwnProperty(t)||(e[t]=[]),e[t]}function IF(e){return e===`category`?`ordinal`:e===`time`?`time`:`float`}function LF(e){return e!==`ordinal`&&e!==`time`}var RF=function(){function e(e){this.otherDims={},e!=null&&W(this,e)}return e}(),zF=os,BF=K,VF=typeof Int32Array>`u`?Array:Int32Array,HF=`e\0\0`,UF=-1,WF=[`hasItemOption`,`_nameList`,`_idList`,`_invertedIndicesMap`,`_dimSummary`,`userOutput`,`_rawData`,`_dimValueGetter`,`_nameDimIdx`,`_idDimIdx`,`_nameRepeatCount`],GF=[`_approximateExtent`],KF,qF,JF,YF,XF,ZF,QF,$F=function(){function e(e,t){this.type=`list`,this._dimOmitted=!1,this._nameList=[],this._idList=[],this._visual={},this._layout={},this._itemVisuals=[],this._itemLayouts=[],this._graphicEls=[],this._approximateExtent={},this._calculationInfo={},this.hasItemOption=!1,this.TRANSFERABLE_METHODS=[`cloneShallow`,`downSample`,`minmaxDownSample`,`lttbDownSample`,`map`],this.CHANGABLE_METHODS=[`filterSelf`,`selectRange`],this.DOWNSAMPLE_METHODS=[`downSample`,`minmaxDownSample`,`lttbDownSample`];var n,r=!1;uE(e)?(n=e.dimensions,this._dimOmitted=e.isDimensionOmitted(),this._schema=e):(r=!0,n=e),n||=[`x`,`y`];for(var i={},a=[],o={},s=!1,c={},l=0;l=t)){var n=this._store.getProvider();this._updateOrdinalMeta();var r=this._nameList,i=this._idList;if(n.getSource().sourceFormat===`original`&&!n.pure)for(var a=[],o=e;o0},e.prototype.ensureUniqueItemVisual=function(e,t){var n=this._itemVisuals,r=n[e];r||=n[e]={};var i=r[t];return i??(i=this.getVisual(t),J(i)?i=i.slice():zF(i)&&(i=W({},i)),r[t]=i),i},e.prototype.setItemVisual=function(e,t,n){var r=this._itemVisuals[e]||{};this._itemVisuals[e]=r,zF(t)?W(r,t):r[t]=n},e.prototype.clearAllVisual=function(){this._visual={},this._itemVisuals=[]},e.prototype.setLayout=function(e,t){zF(e)?W(this._layout,e):this._layout[e]=t},e.prototype.getLayout=function(e){return this._layout[e]},e.prototype.getItemLayout=function(e){return this._itemLayouts[e]},e.prototype.setItemLayout=function(e,t,n){this._itemLayouts[e]=n?W(this._itemLayouts[e]||{},t):t},e.prototype.clearItemLayouts=function(){this._itemLayouts.length=0},e.prototype.setItemGraphicEl=function(e,t){Mh(this.hostModel&&this.hostModel.seriesIndex,this.dataType,e,t),this._graphicEls[e]=t},e.prototype.getItemGraphicEl=function(e){return this._graphicEls[e]},e.prototype.eachItemGraphicEl=function(e,t){G(this._graphicEls,function(n,r){n&&e&&e.call(t,n,r)})},e.prototype.cloneShallow=function(t){return t||=new e(this._schema?this._schema:BF(this.dimensions,this._getDimInfo,this),this.hostModel),XF(t,this),t._store=this._store,t},e.prototype.wrapMethod=function(e,t){var n=this[e];rs(n)&&(this.__wrappedMethods=this.__wrappedMethods||[],this.__wrappedMethods.push(e),this[e]=function(){var e=n.apply(this,arguments);return t.apply(this,[e].concat(hs(arguments)))})},e.internalField=function(){KF=function(e){var t=e._invertedIndicesMap;G(t,function(n,r){var i=e._dimInfos[r],a=i.ordinalMeta,o=e._store;if(a){n=t[r]=new VF(a.categories.length);for(var s=0;s1&&(s+=`__ec__`+l),r[t]=s}}}(),e}();function eI(e,t){pS(e)||(e=hS(e)),t||={};var n=t.coordDimensions||[],r=t.dimensionsDefine||e.dimensionsDefine||[],i=Es(),a=[],o=tI(e,n,r,t.dimensionsCount),s=t.canOmitUnusedDimensions&&pE(o),c=r===e.dimensionsDefine,l=c?fE(e):dE(r),u=t.encodeDefine;!u&&t.encodeDefaulter&&(u=t.encodeDefaulter(e,o));for(var d=Es(u),f=new fC(o),p=0;p0&&(e.name+=t-1)}),new lE({source:e,dimensions:a,fullDimensionCount:o,dimensionOmitted:s})}function tI(e,t,n,r){var i=Math.max(e.dimensionsDetectedCount||1,t.length,n.length,r||0);return G(t,function(e){var t;os(e)&&(t=e.dimsDef)&&(i=Math.max(i,t.length))}),i}function nI(e,t,n){if(n||t.hasKey(e)){for(var r=0;t.hasKey(e+r);)r++;e+=r}return t.set(e,!0),e}var rI=function(){function e(e){this.coordSysDims=[],this.axisMap=Es(),this.categoryAxisMap=Es(),this.coordSysName=e}return e}();function iI(e){var t=e.get(`coordinateSystem`),n=new rI(t),r=aI[t];if(r)return r(e,n,n.axisMap,n.categoryAxisMap),n}var aI={cartesian2d:function(e,t,n,r){var i=e.getReferringComponents(`xAxis`,nl).models[0],a=e.getReferringComponents(`yAxis`,nl).models[0];t.coordSysDims=[`x`,`y`],n.set(`x`,i),n.set(`y`,a),oI(i)&&(r.set(`x`,i),t.firstCategoryDimIndex=0),oI(a)&&(r.set(`y`,a),t.firstCategoryDimIndex??=1)},singleAxis:function(e,t,n,r){var i=e.getReferringComponents(`singleAxis`,nl).models[0];t.coordSysDims=[`single`],n.set(`single`,i),oI(i)&&(r.set(`single`,i),t.firstCategoryDimIndex=0)},polar:function(e,t,n,r){var i=e.getReferringComponents(`polar`,nl).models[0],a=i.findAxisModel(`radiusAxis`),o=i.findAxisModel(`angleAxis`);t.coordSysDims=[`radius`,`angle`],n.set(`radius`,a),n.set(`angle`,o),oI(a)&&(r.set(`radius`,a),t.firstCategoryDimIndex=0),oI(o)&&(r.set(`angle`,o),t.firstCategoryDimIndex??=1)},geo:function(e,t,n,r){t.coordSysDims=[`lng`,`lat`]},parallel:function(e,t,n,r){var i=e.ecModel,a=i.getComponent(`parallel`,e.get(`parallelIndex`)),o=t.coordSysDims=a.dimensions.slice();G(a.parallelAxisIndex,function(e,a){var s=i.getComponent(`parallelAxis`,e),c=o[a];n.set(c,s),oI(s)&&(r.set(c,s),t.firstCategoryDimIndex??=a)})},matrix:function(e,t,n,r){var i=e.getReferringComponents(`matrix`,nl).models[0];t.coordSysDims=[`x`,`y`];var a=i.getDimensionModel(`x`),o=i.getDimensionModel(`y`);n.set(`x`,a),n.set(`y`,o),r.set(`x`,a),r.set(`y`,o)}};function oI(e){return e.get(`type`)===`category`}function sI(e,t){var n=e.get(`coordinateSystem`),r=Ox.get(n),i;return t&&t.coordSysDims&&(i=K(t.coordSysDims,function(e){var n={name:e},r=t.axisMap.get(e);return r&&(n.type=IF(r.get(`type`))),n})),i||=r&&(r.getDimensionsInfo?r.getDimensionsInfo():r.dimensions.slice())||[`x`,`y`],i}function cI(e,t,n){var r,i;return n&&G(e,function(e,a){var o=e.coordDim,s=n.categoryAxisMap.get(o);s&&(r??=a,e.ordinalMeta=s.getOrdinalMeta(),t&&(e.createInvertedIndices=!0)),e.otherDims.itemName!=null&&(i=!0)}),!i&&r!=null&&(e[r].otherDims.itemName=0),r}function lI(e,t,n){n||={};var r=t.getSourceManager(),i,a=!1;e?(a=!0,i=hS(e)):(i=r.getSource(),a=i.sourceFormat===Ph);var o=iI(t),s=sI(t,o),c=n.useEncodeDefaulter,l=rs(c)?c:c?ns(sS,s,t):null,u={coordDimensions:s,generateCoord:n.generateCoord,encodeDefine:t.getEncode(),encodeDefaulter:l,canOmitUnusedDimensions:!a},d=eI(i,u),f=cI(d.dimensions,n.createInvertedIndices,o),p=a?null:r.getSharedDataStore(d),m=mE(t,{schema:d,store:p}),h=new $F(d,t);h.setCalculationInfo(m);var g=f!=null&&uI(i)?function(e,t,n,r){return r===f?n:this.defaultDimValueGetter(e,t,n,r)}:null;return h.hasItemOption=!1,h.initData(a?i:p,null,g),h}function uI(e){if(e.sourceFormat===`original`)return!J(Nc(dI(e.data||[])))}function dI(e){for(var t=0;tthis.getProgressiveThreshold()?this.id:``},t.type=`series.scatter`,t.dependencies=[`grid`,`polar`,`geo`,`singleAxis`,`calendar`,`matrix`],t.defaultOption={coordinateSystem:`cartesian2d`,z:2,legendHoverLink:!0,symbolSize:10,large:!1,largeThreshold:2e3,itemStyle:{opacity:.8},emphasis:{scale:!0},clip:!0,select:{itemStyle:{borderColor:Q.color.primary}},universalTransition:{divideShape:`clone`}},t}(ZC);function pI(e,t){var n=e.mapDimensionsAll(`defaultedLabel`),r=n.length;if(r===1){var i=VS(e,t,n[0]);return i==null?null:i+``}if(r){for(var a=[],o=0;o=0&&r.push(t[a])}return r.join(` `)}var hI=function(e){U(t,e);function t(t,n,r,i){var a=e.call(this)||this;return a.updateData(t,n,r,i),a}return t.prototype._createSymbol=function(e,t,n,r,i,a){this.removeAll();var o=QD(e,-1,-1,2,2,null,a);o.attr({z2:X(i,100),culling:!0,scaleX:r[0]/2,scaleY:r[1]/2}),o.drift=gI,this._symbolType=e,this.add(o)},t.prototype.stopSymbolAnimation=function(e){this.childAt(0).stopAnimation(null,e)},t.prototype.getSymbolType=function(){return this._symbolType},t.prototype.getSymbolPath=function(){return this.childAt(0)},t.prototype.highlight=function(){xg(this.childAt(0))},t.prototype.downplay=function(){Sg(this.childAt(0))},t.prototype.setZ=function(e,t){var n=this.childAt(0);n.zlevel=e,n.z=t},t.prototype.setDraggable=function(e,t){var n=this.childAt(0);n.draggable=e,n.cursor=!t&&e?`move`:n.cursor},t.prototype.updateData=function(e,n,r,i){this.silent=!1;var a=e.getItemVisual(n,`symbol`)||`circle`,o=e.hostModel,s=t.getSymbolSize(e,n),c=t.getSymbolZ2(e,n),l=a!==this._symbolType,u=i&&i.disableAnimation;if(l){var d=e.getItemVisual(n,`symbolKeepAspect`);this._createSymbol(a,e,n,s,c,d)}else{var f=this.childAt(0);f.silent=!1;var p={scaleX:s[0]/2,scaleY:s[1]/2};u?f.attr(p):Sv(f,p,o,n),Ov(f)}if(this._updateCommon(e,n,s,r,i),l){var f=this.childAt(0);if(!u){var p={scaleX:this._sizeX,scaleY:this._sizeY,style:{opacity:f.style.opacity}};f.scaleX=f.scaleY=0,f.style.opacity=0,Cv(f,p,o,n)}}u&&this.childAt(0).stopAnimation(`leave`)},t.prototype._updateCommon=function(e,t,n,r,i){var a=this.childAt(0),o=e.hostModel,s,c,l,u,d,f,p,m,h;if(r&&(s=r.emphasisItemStyle,c=r.blurItemStyle,l=r.selectItemStyle,u=r.focus,d=r.blurScope,p=r.labelStatesModels,m=r.hoverScale,h=r.cursorStyle,f=r.emphasisDisabled),!r||e.hasItemOption){var g=r&&r.itemModel?r.itemModel:e.getItemModel(t),_=g.getModel(`emphasis`);s=_.getModel(`itemStyle`).getItemStyle(),l=g.getModel([`select`,`itemStyle`]).getItemStyle(),c=g.getModel([`blur`,`itemStyle`]).getItemStyle(),u=_.get(`focus`),d=_.get(`blurScope`),f=_.get(`disabled`),p=Dy(g),m=_.getShallow(`scale`),h=g.getShallow(`cursor`)}var v=e.getItemVisual(t,`symbolRotate`);a.attr(`rotation`,(v||0)*Math.PI/180||0);var y=eO(e.getItemVisual(t,`symbolOffset`),n);y&&(a.x=y[0],a.y=y[1]),h&&a.attr(`cursor`,h);var b=e.getItemVisual(t,`style`),x=b.fill;if(a instanceof ih){var S=a.style;a.useStyle(W({image:S.image,x:S.x,y:S.y,width:S.width,height:S.height},b))}else a.__isEmptyBrush?a.useStyle(W({},b)):a.useStyle(b),a.style.decal=null,a.setColor(x,i&&i.symbolInnerColor),a.style.strokeNoScale=!0;var C=e.getItemVisual(t,`liftZ`),w=this._z2;C==null?w!=null&&(a.z2=w,this._z2=null):w??(this._z2=a.z2,a.z2+=C);var T=i&&i.useNameLabel;Ey(a,p,{labelFetcher:o,labelDataIndex:t,defaultText:E,inheritColor:x,defaultOpacity:b.opacity});function E(t){return T?e.getName(t):pI(e,t)}this._sizeX=n[0]/2,this._sizeY=n[1]/2;var D=a.ensureState(`emphasis`);D.style=s,a.ensureState(`select`).style=l,a.ensureState(`blur`).style=c;var O=m==null||m===!0?Math.max(1.1,3/this._sizeY):isFinite(m)&&m>0?+m:1;D.scaleX=this._sizeX*O,D.scaleY=this._sizeY*O,this.setSymbolScale(1),Bg(this,u,d,f)},t.prototype.setSymbolScale=function(e){this.scaleX=this.scaleY=e},t.prototype.fadeOut=function(e,t,n){var r=this.childAt(0),i=jh(this).dataIndex,a=n&&n.animation;if(this.silent=r.silent=!0,n&&n.fadeLabel){var o=r.getTextContent();o&&Tv(o,{style:{opacity:0}},t,{dataIndex:i,removeOpt:a,cb:function(){r.removeTextContent()}})}else r.removeTextContent();Tv(r,{style:{opacity:0},scaleX:0,scaleY:0},t,{dataIndex:i,cb:e,removeOpt:a})},t.getSymbolSize=function(e,t){return $D(e.getItemVisual(t,`symbolSize`))},t.getSymbolZ2=function(e,t){return e.getItemVisual(t,`z2`)},t}(y_);function gI(e,t){this.parent.drift(e,t)}function _I(e,t,n,r){return t&&!isNaN(t[0])&&!isNaN(t[1])&&!(r&&r.isIgnore&&r.isIgnore(n))&&!(r&&r.clipShape&&!r.clipShape.contain(t[0],t[1]))&&e.getItemVisual(n,`symbol`)!==`none`}function vI(e){return e!=null&&!os(e)&&(e={isIgnore:e}),e||{}}function yI(e){var t=e.hostModel,n=t.getModel(`emphasis`);return{emphasisItemStyle:n.getModel(`itemStyle`).getItemStyle(),blurItemStyle:t.getModel([`blur`,`itemStyle`]).getItemStyle(),selectItemStyle:t.getModel([`select`,`itemStyle`]).getItemStyle(),focus:n.get(`focus`),blurScope:n.get(`blurScope`),emphasisDisabled:n.get(`disabled`),hoverScale:n.get(`scale`),labelStatesModels:Dy(t),cursorStyle:t.get(`cursor`)}}function bI(e,t,n,r,i,a,o){var s=new e(t,n,r,i);return s.setPosition(a),t.setItemGraphicEl(n,s),o.add(s),s}var xI=function(){function e(e){this.group=new y_,this._SymbolCtor=e||hI}return e.prototype.updateData=function(e,t){this._progressiveEls=null,t=vI(t);var n=this.group,r=e.hostModel,i=this._data,a=this._SymbolCtor,o=t.disableAnimation,s=this._seriesScope=yI(e),c={disableAnimation:o},l=t.getSymbolPoint||function(t){return e.getItemLayout(t)};i||n.removeAll(),e.diff(i).add(function(r){var i=l(r);_I(e,i,r,t)&&bI(a,e,r,s,c,i,n)}).update(function(u,d){var f=i.getItemGraphicEl(d),p=l(u);if(!_I(e,p,u,t)){n.remove(f);return}var m=e.getItemVisual(u,`symbol`)||`circle`,h=f&&f.getSymbolType&&f.getSymbolType();if(!f||h&&h!==m)n.remove(f),f=new a(e,u,s,c),f.setPosition(p);else{f.updateData(e,u,s,c);var g={x:p[0],y:p[1]};o?f.attr(g):Sv(f,g,r)}n.add(f),e.setItemGraphicEl(u,f)}).remove(function(e){var t=i.getItemGraphicEl(e);t&&t.fadeOut(function(){n.remove(t)},r)}).execute(),this._getSymbolPoint=l,this._data=e},e.prototype.updateLayout=function(e){var t=this._data;if(t)for(var n=this,r=t.getStore(),i=0,a=r.count();i=0;s--){var c=s*2,l=r[c]-a/2,u=r[c+1]-o/2;if(e>=l&&t>=u&&e<=l+a&&t<=u+o)return s}return-1},t.prototype.contain=function(e,t){var n=this.transformCoordToLocal(e,t),r=this.getBoundingRect();return e=n[0],t=n[1],r.contain(e,t)?(this.hoverDataIdx=this.findDataIndex(e,t))>=0:(this.hoverDataIdx=-1,!1)},t.prototype.getBoundingRect=function(){var e=this._rect;if(!e){for(var t=this.shape,n=t.points,r=t.size,i=r[0],a=r[1],o=1/0,s=1/0,c=-1/0,l=-1/0,u=0;u=0&&(c.dataIndex=n+(e.startIndex||0))})},e.prototype.remove=function(){this._clear()},e.prototype._clear=function(){this._newAdded=[],this.group.removeAll()},e}(),EI=typeof Float32Array<`u`?Float32Array:void 0,DI=typeof Float64Array<`u`?Float64Array:void 0;function OI(e){return kI({ctor:EI},e).arr}function kI(e,t){var n=e.arr,r=e.ctor;if(t>oc&&(t=oc),!n||e.typed&&n.length=0||e===t}function ZI(e){var t=QI(e);if(t){var n=t.axisPointerModel,r=t.axis.scale,i=n.option,a=n.get(`status`),o=n.get(`value`);o!=null&&(o=r.parse(o));var s=eL(n);a??(i.status=s?`show`:`hide`);var c=r.getExtent();(o==null||o>c[1])&&(o=c[1]),o-1&&(s.style.stroke=s.style.fill,s.style.fill=Q.color.neutral00,s.style.lineWidth=2),t},t.type=`series.line`,t.dependencies=[`grid`,`polar`],t.defaultOption={z:3,coordinateSystem:`cartesian2d`,legendHoverLink:!0,clip:!0,label:{position:`top`},endLabel:{show:!1,valueAnimation:!0,distance:8},lineStyle:{width:2,type:`solid`},emphasis:{scale:!0},step:!1,smooth:!1,smoothMonotone:null,symbol:`emptyCircle`,symbolSize:6,symbolRotate:null,showSymbol:!0,showAllSymbol:`auto`,connectNulls:!1,sampling:`none`,animationEasing:`linear`,progressive:0,hoverLayerThreshold:1/0,universalTransition:{divideShape:`clone`},triggerLineEvent:!1,triggerEvent:!1},t}(ZC);function _L(e,t,n){var r=e.getBaseAxis(),i=e.getOtherAxis(r),a=vL(i,n),o=r.dim,s=i.dim,c=t.mapDimension(s),l=t.mapDimension(o),u=+(s===`x`||s===`radius`),d=K(e.dimensions,function(e){return t.mapDimension(e)}),f=!1,p=t.getCalculationInfo(`stackResultDimension`);return gE(t,d[0])&&(f=!0,d[0]=p),gE(t,d[1])&&(f=!0,d[1]=p),{dataDimsForPoint:d,valueStart:a,valueAxisDim:s,baseAxisDim:o,stacked:!!f,valueDim:c,baseDim:l,baseDataOffset:u,stackedOverDimension:t.getCalculationInfo(`stackedOverDimension`)}}function vL(e,t){var n=0,r=e.scale.getExtent();return t===`start`?n=r[0]:t===`end`?n=r[1]:as(t)&&!isNaN(t)?n=t:r[0]>0?n=r[0]:r[1]<0&&(n=r[1]),n}function yL(e,t,n,r){var i=NaN;e.stacked&&(i=n.get(n.getCalculationInfo(`stackedOverDimension`),r)),isNaN(i)&&(i=e.valueStart);var a=e.baseDataOffset,o=[];return o[a]=n.get(e.baseDim,r),o[1-a]=i,t.dataToPoint(o)}function bL(e,t){return!isFinite(e)||!isFinite(t)}function xL(e,t){var n=[];return t.diff(e).add(function(e){n.push({cmd:`+`,idx:e})}).update(function(e,t){n.push({cmd:`=`,idx:t,idx1:e})}).remove(function(e){n.push({cmd:`-`,idx:e})}).execute(),n}function SL(e,t,n,r,i,a,o,s){for(var c=xL(e,t),l=[],u=[],d=[],f=[],p=[],m=[],h=[],g=_L(i,t,o),_=e.getLayout(`points`)||[],v=t.getLayout(`points`)||[],y=0;y=i||h<0)break;if(bL(_,v)){if(c){h+=a;continue}break}if(h===n)e[a>0?`moveTo`:`lineTo`](_,v),d=_,f=v;else{var y=_-l,b=v-u;if(y*y+b*b<.5){h+=a;continue}if(o>0){for(var x=h+a,S=t[x*2],C=t[x*2+1];S===_&&C===v&&g=r||bL(S,C))p=_,m=v;else{E=S-l,D=C-u;var A=_-l,j=S-_,M=v-u,N=C-v,P=void 0,F=void 0;if(s===`x`){P=Math.abs(A),F=Math.abs(j);var I=E>0?1:-1;p=_-I*P*o,m=v,O=_+I*F*o,k=v}else if(s===`y`){P=Math.abs(M),F=Math.abs(N);var L=D>0?1:-1;p=_,m=v-L*P*o,O=_,k=v+L*F*o}else P=Math.sqrt(A*A+M*M),F=Math.sqrt(j*j+N*N),T=F/(F+P),p=_-E*o*(1-T),m=v-D*o*(1-T),O=_+E*o*T,k=v+D*o*T,O=CL(O,wL(S,_)),k=CL(k,wL(C,v)),O=wL(O,CL(S,_)),k=wL(k,CL(C,v)),E=O-_,D=k-v,p=_-E*P/F,m=v-D*P/F,p=CL(p,wL(l,_)),m=CL(m,wL(u,v)),p=wL(p,CL(l,_)),m=wL(m,CL(u,v)),E=_-p,D=v-m,O=_+E*F/P,k=v+D*F/P}e.bezierCurveTo(d,f,p,m,_,v),d=O,f=k}else e.lineTo(_,v)}l=_,u=v,h+=a}return g}var EL=function(){function e(){this.smooth=0,this.smoothConstraint=!0}return e}(),DL=function(e){U(t,e);function t(t){var n=e.call(this,t)||this;return n.type=`ec-polyline`,n}return t.prototype.getDefaultStyle=function(){return{stroke:Q.color.neutral99,fill:null}},t.prototype.getDefaultShape=function(){return new EL},t.prototype.buildPath=function(e,t){var n=t.points,r=0,i=n.length/2;if(t.connectNulls){for(;i>0&&bL(n[i*2-2],n[i*2-1]);i--);for(;r=0){var _=o?(d-a)*g+a:(u-i)*g+i;return o?[e,_]:[_,e]}i=u,a=d;break;case r.C:u=n[c++],d=n[c++],f=n[c++],p=n[c++],m=n[c++],h=n[c++];var v=o?af(i,u,f,m,e,s):af(a,d,p,h,e,s);if(v>0)for(var y=0;y=0){var _=o?nf(a,d,p,h,b):nf(i,u,f,m,b);return o?[e,_]:[_,e]}}i=m,a=h}}},t}(Qm),OL=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t}(EL),kL=function(e){U(t,e);function t(t){var n=e.call(this,t)||this;return n.type=`ec-polygon`,n}return t.prototype.getDefaultShape=function(){return new OL},t.prototype.buildPath=function(e,t){var n=t.points,r=t.stackedOnPoints,i=0,a=n.length/2,o=t.smoothMonotone;if(t.connectNulls){for(;a>0&&bL(n[a*2-2],n[a*2-1]);a--);for(;i=0,a=e.fill||Q.color.neutral99;IL(r,t);var o=r.textFill==null;return i?o&&(r.textFill=n.insideFill||Q.color.neutral00,!r.textStroke&&n.insideStroke&&(r.textStroke=n.insideStroke),!r.textStroke&&(r.textStroke=a),r.textStrokeWidth??=2):(o&&(r.textFill=e.fill||n.outsideFill||Q.color.neutral00),!r.textStroke&&n.outsideStroke&&(r.textStroke=n.outsideStroke)),r.text=t.text,r.rich=t.rich,G(t.rich,function(e){IL(e,e)}),r}function IL(e,t){t&&(Z(t,`fill`)&&(e.textFill=t.fill),Z(t,`stroke`)&&(e.textStroke=t.fill),Z(t,`lineWidth`)&&(e.textStrokeWidth=t.lineWidth),Z(t,`font`)&&(e.font=t.font),Z(t,`fontStyle`)&&(e.fontStyle=t.fontStyle),Z(t,`fontWeight`)&&(e.fontWeight=t.fontWeight),Z(t,`fontSize`)&&(e.fontSize=t.fontSize),Z(t,`fontFamily`)&&(e.fontFamily=t.fontFamily),Z(t,`align`)&&(e.textAlign=t.align),Z(t,`verticalAlign`)&&(e.textVerticalAlign=t.verticalAlign),Z(t,`lineHeight`)&&(e.textLineHeight=t.lineHeight),Z(t,`width`)&&(e.textWidth=t.width),Z(t,`height`)&&(e.textHeight=t.height),Z(t,`backgroundColor`)&&(e.textBackgroundColor=t.backgroundColor),Z(t,`padding`)&&(e.textPadding=t.padding),Z(t,`borderColor`)&&(e.textBorderColor=t.borderColor),Z(t,`borderWidth`)&&(e.textBorderWidth=t.borderWidth),Z(t,`borderRadius`)&&(e.textBorderRadius=t.borderRadius),Z(t,`shadowColor`)&&(e.textBoxShadowColor=t.shadowColor),Z(t,`shadowBlur`)&&(e.textBoxShadowBlur=t.shadowBlur),Z(t,`shadowOffsetX`)&&(e.textBoxShadowOffsetX=t.shadowOffsetX),Z(t,`shadowOffsetY`)&&(e.textBoxShadowOffsetY=t.shadowOffsetY),Z(t,`textShadowColor`)&&(e.textShadowColor=t.textShadowColor),Z(t,`textShadowBlur`)&&(e.textShadowBlur=t.textShadowBlur),Z(t,`textShadowOffsetX`)&&(e.textShadowOffsetX=t.textShadowOffsetX),Z(t,`textShadowOffsetY`)&&(e.textShadowOffsetY=t.textShadowOffsetY))}function LL(e,t){if(e.length===t.length){for(var n=0;nt){a?n.push(o(a,c,t)):i&&n.push(o(i,c,0),o(i,c,t));break}else i&&=(n.push(o(i,c,0)),null),n.push(c),a=c}return n}function WL(e,t,n){var r=e.getVisual(`visualMeta`);if(r&&r.length&&e.count()&&t.type===`cartesian2d`){for(var i,a,o=r.length-1;o>=0;o--){var s=e.getDimensionInfo(r[o].dimension);if(i=s&&s.coordDim,i===`x`||i===`y`){a=r[o];break}}if(a){var c=t.getAxis(i),l=K(a.stops,function(e){return{coord:c.toGlobalCoord(c.dataToCoord(e.value)),color:e.color}}),u=l.length,d=a.outerColors.slice();u&&l[0].coord>l[u-1].coord&&(l.reverse(),d.reverse());var f=UL(l,i===`x`?n.getWidth():n.getHeight()),p=f.length;if(!p&&u)return l[0].coord<0?d[1]?d[1]:l[u-1].color:d[0]?d[0]:l[0].color;var m=10,h=f[0].coord-m,g=f[p-1].coord+m,_=g-h;if(_<.001)return`transparent`;G(f,function(e){e.offset=(e.coord-h)/_}),f.push({offset:p?f[p-1].offset:.5,color:d[1]||`transparent`}),f.unshift({offset:p?f[0].offset:.5,color:d[0]||`transparent`});var v=new ov(0,0,0,0,f,!0);return v[i]=h,v[i+`2`]=g,v}}}function GL(e,t,n){var r=e.get(`showAllSymbol`),i=r===`auto`;if(!r||i){var a=n.getAxesByScale(`ordinal`)[0];if(a&&!(i&&KL(a,t))){var o=t.mapDimension(a.dim),s={};return G(a.getViewLabels(),function(e){e.tick.offInterval||(s[PE(a.scale,e.tick)]=1)}),function(e){return!s.hasOwnProperty(t.get(o,e))}}}}function KL(e,t){var n=e.getExtent(),r=Math.abs(n[1]-n[0])/e.scale.count();isNaN(r)&&(r=0);for(var i=t.count(),a=Math.max(1,Math.round(i/5)),o=0;or)return!1;return!0}function qL(e){for(var t=e.length/2;t>0&&bL(e[t*2-2],e[t*2-1]);t--);return t-1}function JL(e,t){return[e[t*2],e[t*2+1]]}function YL(e,t,n){for(var r=e.length/2,i=n===`x`?0:1,a,o,s=0,c=-1,l=0;l=t||a>=t&&o<=t){c=l;break}s=l,a=o}return{range:[s,c],t:(t-a)/(o-a)}}function XL(e){if(e.get([`endLabel`,`show`]))return!0;for(var t=0;t0&&e.get([`emphasis`,`lineStyle`,`width`])===`bolder`){var M=f.getState(`emphasis`).style;M.lineWidth=+f.style.lineWidth+1}jh(f).seriesIndex=e.seriesIndex,Bg(f,k,A,j);var N=BL(e.get(`smooth`)),P=e.get(`smoothMonotone`);if(f.setShape({smooth:N,smoothMonotone:P,connectNulls:x}),p){var F=a.getCalculationInfo(`stackedOnSeries`),I=0;p.useStyle(Ko(s.getAreaStyle(),{fill:E,opacity:.7,lineJoin:`bevel`,decal:a.getVisual(`style`).decal})),F&&(I=BL(F.get(`smooth`))),p.setShape({smooth:N,stackedOnSmooth:I,smoothMonotone:P,connectNulls:x}),Wg(p,e,`areaStyle`),jh(p).seriesIndex=e.seriesIndex,Bg(p,k,A,j)}var L=this._changePolyState;a.eachItemGraphicEl(function(e){e&&(e.onHoverStateChange=L)}),this._polyline.onHoverStateChange=L,this._data=a,this._coordSys=r,this._stackedOnPoints=y,this._points=c,this._step=w,this._valueOrigin=_;var ee=e.get(`triggerEvent`),te=e.get(`triggerLineEvent`),ne=te===!0||ee===!0||ee===`line`,re=te===!0||ee===!0||ee===`area`;this.packEventData(e,f,ne),p&&this.packEventData(e,p,re)},t.prototype.packEventData=function(e,t,n){jh(t).eventData=n?{componentType:`series`,componentSubType:`line`,componentIndex:e.componentIndex,seriesIndex:e.seriesIndex,seriesName:e.name,seriesType:`line`,selfType:t===this._polygon?`area`:`line`}:null},t.prototype.highlight=function(e,t,n,r){var i=e.getData(),a=Zc(i,r);if(this._changePolyState(`emphasis`),!(a instanceof Array)&&a!=null&&a>=0){var o=i.getLayout(`points`),s=i.getItemGraphicEl(a);if(!s){var c=o[a*2],l=o[a*2+1];if(bL(c,l)||this._clipShapeForSymbol&&!this._clipShapeForSymbol.contain(c,l))return;var u=e.get(`zlevel`)||0,d=e.get(`z`)||0;s=new hI(i,a),s.x=c,s.y=l,s.setZ(u,d);var f=s.getSymbolPath().getTextContent();f&&(f.zlevel=u,f.z=d,f.z2=this._polyline.z2+1),s.__temp=!0,i.setItemGraphicEl(a,s),s.stopSymbolAnimation(!0),this.group.add(s)}s.highlight()}else Jj.prototype.highlight.call(this,e,t,n,r)},t.prototype.downplay=function(e,t,n,r){var i=e.getData(),a=Zc(i,r);if(this._changePolyState(`normal`),a!=null&&a>=0){var o=i.getItemGraphicEl(a);o&&(o.__temp?(i.setItemGraphicEl(a,null),this.group.remove(o)):o.downplay())}else Jj.prototype.downplay.call(this,e,t,n,r)},t.prototype._changePolyState=function(e){var t=this._polygon;fg(this._polyline,e),t&&fg(t,e)},t.prototype._newPolyline=function(e){var t=this._polyline;return t&&this._lineGroup.remove(t),t=new DL({shape:{points:e},segmentIgnoreThreshold:2,z2:10}),this._lineGroup.add(t),this._polyline=t,t},t.prototype._newPolygon=function(e,t){var n=this._polygon;return n&&this._lineGroup.remove(n),n=new kL({shape:{points:e,stackedOnPoints:t},segmentIgnoreThreshold:2}),this._lineGroup.add(n),this._polygon=n,n},t.prototype._initSymbolLabelAnimation=function(e,t,n){var r,i,a=t.getBaseAxis(),o=a.inverse;t.type===`cartesian2d`?(r=a.isHorizontal(),i=!1):t.type===`polar`&&(r=a.dim===`angle`,i=!0);var s=e.hostModel,c=s.get(`animationDuration`);rs(c)&&(c=c(null));var l=s.get(`animationDelay`)||0,u=rs(l)?l(null):l;e.eachItemGraphicEl(function(e,a){var s=e;if(s){var d=[e.x,e.y],f=void 0,p=void 0,m=void 0;if(n){if(i){var h=n,g=t.pointToCoord(d);r?(f=h.startAngle,p=h.endAngle,m=-g[1]/180*Math.PI):(f=h.r0,p=h.r,m=g[0])}else{var _=n;r?(f=_.x,p=_.x+_.width,m=e.x):(f=_.y+_.height,p=_.y,m=e.y)}}var v=p===f?0:(m-f)/(p-f);o&&(v=1-v);var y=rs(l)?l(a):c*v+u,b=s.getSymbolPath(),x=b.getTextContent();s.attr({scaleX:0,scaleY:0}),s.animateTo({scaleX:1,scaleY:1},{duration:200,setToFinal:!0,delay:y}),x&&x.animateFrom({style:{opacity:0}},{duration:300,delay:y}),b.disableLabelAnimation=!0}})},t.prototype._initOrUpdateEndLabel=function(e,t,n){var r=e.getModel(`endLabel`);if(XL(e)){var i=e.getData(),a=this._polyline,o=i.getLayout(`points`);if(!o){a.removeTextContent(),this._endLabel=null;return}var s=this._endLabel;s||(s=this._endLabel=new _h({z2:200}),s.ignoreClip=!0,a.setTextContent(this._endLabel),a.disableLabelAnimation=!0);var c=qL(o);c>=0&&(Ey(a,Dy(e,`endLabel`),{inheritColor:n,labelFetcher:e,labelDataIndex:c,defaultText:function(e,t,n){return n==null?pI(i,e):mI(i,n)},enableTextSetter:!0},QL(r,t)),a.textConfig.position=null)}else this._endLabel&&=(this._polyline.removeTextContent(),null)},t.prototype._endLabelOnDuring=function(e,t,n,r,i,a,o){var s=this._endLabel,c=this._polyline;if(s){e<1&&r.originalX==null&&(r.originalX=s.x,r.originalY=s.y);var l=n.getLayout(`points`),u=n.hostModel,d=u.get(`connectNulls`),f=a.get(`precision`),p=a.get(`distance`)||0,m=o.getBaseAxis(),h=m.isHorizontal(),g=m.inverse,_=t.shape,v=g?h?_.x:_.y+_.height:h?_.x+_.width:_.y,y=(h?p:0)*(g?-1:1),b=(h?0:-p)*(g?-1:1),x=h?`x`:`y`,S=YL(l,v,x),C=S.range,w=C[1]-C[0],T=void 0;if(w>=1){if(w>1&&!d){var E=JL(l,C[0]);s.attr({x:E[0]+y,y:E[1]+b}),i&&(T=u.getRawValue(C[0]))}else{var E=c.getPointOn(v,x);E&&s.attr({x:E[0]+y,y:E[1]+b});var D=u.getRawValue(C[0]),O=u.getRawValue(C[1]);i&&(T=ll(n,f,D,O,S.t))}r.lastFrameIndex=C[0]}else{var k=e===1||r.lastFrameIndex>0?C[0]:0,E=JL(l,k);i&&(T=u.getRawValue(k)),s.attr({x:E[0]+y,y:E[1]+b})}if(i){var A=Ly(s);typeof A.setLabelText==`function`&&A.setLabelText(T)}}},t.prototype._doUpdateAnimation=function(e,t,n,r,i,a,o){var s=this._polyline,c=this._polygon,l=e.hostModel,u=SL(this._data,e,this._stackedOnPoints,t,this._coordSys,n,this._valueOrigin,a),d=u.current,f=u.stackedOnCurrent,p=u.next,m=u.stackedOnNext;if(i&&(f=HL(u.stackedOnCurrent,u.current,n,i,o),d=HL(u.current,null,n,i,o),m=HL(u.stackedOnNext,u.next,n,i,o),p=HL(u.next,null,n,i,o)),zL(d,p)>3e3||c&&zL(f,m)>3e3){s.stopAnimation(),s.setShape({points:p}),c&&(c.stopAnimation(),c.setShape({points:p,stackedOnPoints:m}));return}s.shape.__points=u.current,s.shape.points=d;var h={shape:{points:p}};u.current!==d&&(h.shape.__points=u.next),s.stopAnimation(),Sv(s,h,l),c&&(c.setShape({points:d,stackedOnPoints:f}),c.stopAnimation(),Sv(c,{shape:{stackedOnPoints:m}},l),s.shape.points!==c.shape.points&&(c.shape.points=s.shape.points));for(var g=[],_=u.status,v=0;v<_.length;v++)if(_[v].cmd===`=`){var y=e.getItemGraphicEl(_[v].idx1);y&&g.push({el:y,ptIdx:v})}s.animators&&s.animators.length&&s.animators[0].during(function(){c&&c.dirtyShape();for(var e=s.shape.__points,t=0;tt&&(t=e[n]);return isFinite(t)?t:NaN},min:function(e){for(var t=1/0,n=0;n10&&a.type===`cartesian2d`&&i){var s=a.getBaseAxis(),c=a.getOtherAxis(s),l=s.getExtent(),u=n.getDevicePixelRatio(),d=Math.abs(l[1]-l[0])*(u||1),f=Math.round(o/d);if(isFinite(f)&&f>1){i===`lttb`?e.setData(r.lttbDownSample(r.mapDimension(c.dim),1/f)):i===`minmax`&&e.setData(r.minmaxDownSample(r.mapDimension(c.dim),1/f));var p=void 0;Y(i)?p=eR[i]:rs(i)&&(p=i),p&&e.setData(r.downSample(r.mapDimension(c.dim),1/f,p,tR))}}}}}function rR(e){e.registerChartView($L),e.registerSeriesModel(gL),e.registerLayout(AI(`line`,!0)),e.registerVisual({seriesType:`line`,reset:function(e){var t=e.getData(),n=e.getModel(`lineStyle`).getLineStyle();n&&!n.stroke&&(n.stroke=t.getVisual(`style`).fill),t.setVisual(`legendLineStyle`,n)}}),e.registerProcessor(e.PRIORITY.PROCESSOR.STATISTIC,nR(`line`))}function iR(){jD(`liPosMinGap`,aR)}function aR(e,t,n){var r=Es(),i=n.serUids,a=n.liPosMinGap,o,s=t.axis,c=s.scale,l=c.needTransform(),u=c.getFilter?c.getFilter():null,d=ZS(u);function f(n){DD(e,t.sers,function(e){var t=e.getRawData(),r=t.getDimensionIndex(t.mapDimension(s.dim));r>=0&&n(r,e,t.getStore())})}var p=0;if(f(function(e,t,n){r.set(t.uid,1),(!i||!i.hasKey(t.uid))&&(o=!0),p+=n.count()}),(!i||i.keys().length!==r.keys().length)&&(o=!0),!o&&a!=null){t.liPosMinGap=a;return}kI(oR,p);var m=0;f(function(e,t,n){for(var r=0,i=n.count();r0&&v0?-2:-1,n.serUids=r}var oR=kI({ctor:DI},50);function sR(e){return function(t,n){var r=RD(t,{fromStat:{key:e}});if(bc(r.w2))return[-r.w2/2,r.w2/2]}}function cR(e,t){return e+`|&`+t}function lR(e){return iR(),{liPosMinGap:!OT(e.scale)}}function uR(e,t,n,r){FD(e,{key:t,seriesType:n,coordSysType:r,getMetrics:lR})}function dR(e){return e.scale.rawExtentInfo.makeRenderInfo().startValue}var fR=yl(),pR=`__ec_stack_`;function mR(e){return e.get(`stack`)||pR+e.seriesIndex}function hR(e){if(OT(e.axis.scale)){for(var t=RD(e.axis),n=[],r=0;ro&&(o=a),o!==u&&(t.width=o,n-=o+l*o,r--)}}),u=(n-c)/(r+(r-1)*l),u=zs(u,0);var d=0,f;G(o,function(e){var t=s[e];t.width||=u,f=t,d+=t.width*(1+l)}),f&&(d-=f.width*l);var p={},m=-d/2;return G(o,function(e){var n=s[e];p[e]=p[e]||{bandWidth:t,offset:m,width:n.width},m+=n.width*(1+l)}),p}function yR(e){return{seriesType:e,overallReset:function(t){var n=cR(e,zE);OD(t,n,function(t){var r=gR(t,e);ED(t,n,function(e){var t=r.columnMap[mR(e)];e.getData().setLayout({bandWidth:t.bandWidth,offset:t.offset,size:t.width})})})}}}function bR(e){return{seriesType:e,plan:Gj(),reset:function(e){if(FO(e)){var t=e.getData(),n=e.coordinateSystem,r=n.getBaseAxis(),i=n.getOtherAxis(r),a=t.getDimensionIndex(t.mapDimension(i.dim)),o=t.getDimensionIndex(t.mapDimension(r.dim)),s=e.get(`showBackground`,!0),c=t.mapDimension(i.dim),l=t.getCalculationInfo(`stackResultDimension`),u=gE(t,c)&&!!t.getCalculationInfo(`stackedOnSeries`),d=i.isHorizontal(),f=i.toGlobalCoord(i.dataToCoord(dR(i))),p=xR(e),m=e.get(`barMinHeight`)||0,h=l&&t.getDimensionIndex(l),g=t.getLayout(`size`),_=t.getLayout(`offset`);return{progress:function(e,t){for(var r=e.count,i=p&&OI(r*3),c=p&&s&&OI(r*3),l=p&&OI(r),v=n.master.getRect(),y=d?v.width:v.height,b,x=t.getStore(),S=0;(b=e.next())!=null;){var C=x.get(u?h:a,b),w=x.get(o,b),T=f,E=void 0;u&&(E=+C-x.get(a,b));var D=void 0,O=void 0,k=void 0,A=void 0;if(d){var j=n.dataToPoint([C,w]);u&&(T=n.dataToPoint([E,w])[0]),D=T,O=j[1]+_,k=j[0]-T,A=g,Bs(k)s){u=(p+l)/2;break}f===1&&(d=m-r[0].tickValue)}u??(l?l&&(u=r[r.length-1].coord):u=r[0].coord),a[n]=e.toGlobalCoord(u)}});else{var o=this.getData(),s=o.getLayout(`offset`),c=o.getLayout(`size`),l=+!r.getBaseAxis().isHorizontal();a[l]+=s+c/2}return a}return[NaN,NaN]},t.prototype.__requireStartValue=function(e){return this.getBaseAxis()!==e},t.type=`series.__base_bar__`,t.defaultOption={z:2,coordinateSystem:`cartesian2d`,legendHoverLink:!0,barMinHeight:0,barMinAngle:0,large:!1,largeThreshold:400,progressive:3e3,progressiveChunkMode:`mod`,defaultBarGap:`10%`},t}(ZC);ZC.registerClass(wR);var TR=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.getInitialData=function(){return lI(null,this,{useEncodeDefaulter:!0,createInvertedIndices:!!this.get(`realtimeSort`,!0)||null})},t.prototype.getProgressive=function(){return this.get(`large`)?this.get(`progressive`):!1},t.prototype.__preparePipelineContext=function(e,t){var n=Tl(this,e,t);return n.progressiveRender&&(n.large=!0),n},t.prototype.brushSelector=function(e,t,n){return n.rect(t.getItemLayout(e))},t.type=`series.bar`,t.dependencies=[`grid`,`polar`],t.defaultOption=nb(wR.defaultOption,{clip:!0,roundCap:!1,showBackground:!1,backgroundStyle:{color:`rgba(180, 180, 180, 0.2)`,borderColor:null,borderWidth:0,borderType:`solid`,borderRadius:0,shadowBlur:0,shadowColor:null,shadowOffsetX:0,shadowOffsetY:0,opacity:1},select:{itemStyle:{borderColor:Q.color.primary,borderWidth:2}},realtimeSort:!1}),t}(wR),ER=function(){function e(){this.cx=0,this.cy=0,this.r0=0,this.r=0,this.startAngle=0,this.endAngle=Math.PI*2,this.clockwise=!0}return e}(),DR=function(e){U(t,e);function t(t){var n=e.call(this,t)||this;return n.type=`sausage`,n}return t.prototype.getDefaultShape=function(){return new ER},t.prototype.buildPath=function(e,t){var n=t.cx,r=t.cy,i=Math.max(t.r0||0,0),a=Math.max(t.r,0),o=(a-i)*.5,s=i+o,c=t.startAngle,l=t.endAngle,u=t.clockwise,d=Math.PI*2,f=u?l-cMath.PI/2&&ua)return!0;a=l}return!1},t.prototype._isOrderDifferentInView=function(e,t){for(var n=t.scale,r=n.getExtent(),i=Math.max(0,r[0]),a=Math.min(r[1],n.getOrdinalMeta().categories.length-1);i<=a;++i)if(e.ordinalNumbers[i]!==n.getRawOrdinalNumber(i))return!0},t.prototype._updateSortWithinSameData=function(e,t,n,r){if(this._isOrderChangedWithinSameData(e,t,n)){var i=this._dataSort(e,n,t);this._isOrderDifferentInView(i,n)&&(this._removeOnRenderedListener(r),r.dispatchAction({type:`changeAxisOrder`,componentType:n.dim+`Axis`,axisId:n.index,sortInfo:i}))}},t.prototype._dispatchInitSort=function(e,t,n){var r=t.baseAxis,i=this._dataSort(e,r,function(n){return e.get(e.mapDimension(t.otherAxis.dim),n)});n.dispatchAction({type:`changeAxisOrder`,componentType:r.dim+`Axis`,isInitSort:!0,axisId:r.index,sortInfo:i})},t.prototype.remove=function(e,t){this._clear(this._model),this._removeOnRenderedListener(t)},t.prototype.dispose=function(e,t){this._removeOnRenderedListener(t)},t.prototype._removeOnRenderedListener=function(e){this._onRendered&&=(e.getZr().off(`rendered`,this._onRendered),null)},t.prototype._clear=function(e){var t=this.group,n=this._data;e&&e.isAnimationEnabled()&&n&&!this._isLargeDraw?(this._removeBackground(),this._backgroundEls=[],n.eachItemGraphicEl(function(t){Dv(t,e,jh(t).dataIndex)})):t.removeAll(),this._data=null,this._isFirstFrame=!0},t.prototype._removeBackground=function(){this.group.remove(this._backgroundGroup),this._backgroundGroup=null},t.type=`bar`,t}(Jj),IR={cartesian2d:function(e,t){var n=t.width<0?-1:1,r=t.height<0?-1:1;n<0&&(t.x+=t.width,t.width=-t.width),r<0&&(t.y+=t.height,t.height=-t.height);var i=e.x+e.width,a=e.y+e.height,o=NR(t.x,e.x),s=PR(t.x+t.width,i),c=NR(t.y,e.y),l=PR(t.y+t.height,a),u=si?s:o,t.y=d&&c>a?l:c,t.width=u?0:s-o,t.height=d?0:l-c,n<0&&(t.x+=t.width,t.width=-t.width),r<0&&(t.y+=t.height,t.height=-t.height),u||d},polar:function(e,t){var n=t.r0<=t.r?1:-1;if(n<0){var r=t.r;t.r=t.r0,t.r0=r}var i=PR(t.r,e.r),a=NR(t.r0,e.r0);t.r=i,t.r0=a;var o=i-a<0;if(n<0){var r=t.r;t.r=t.r0,t.r0=r}return o}},LR={cartesian2d:function(e,t,n,r,i,a,o,s,c){var l=new fh({shape:W({},r),z2:1});if(l.__dataIndex=n,l.name=`item`,a){var u=l.shape,d=i?`height`:`width`;u[d]=0}return l},polar:function(e,t,n,r,i,a,o,s,c){var l=!i&&c?DR:B_,u=new l({shape:r,z2:1});if(u.name=`item`,u.calculateTextPosition=OR(KR(i),{isRoundCap:l===DR}),a){var d=u.shape,f=i?`r`:`endAngle`,p={};d[f]=i?r.r0:r.startAngle,p[f]=r[f],(s?Sv:Cv)(u,{shape:p},a)}return u}};function RR(e,t){var n=e.get(`realtimeSort`,!0),r=t.getBaseAxis();if(n&&r.type===`category`&&t.type===`cartesian2d`)return{baseAxis:r,otherAxis:t.getOtherAxis(r)}}function zR(e,t,n,r,i,a,o,s){var c,l;a?(l={x:r.x,width:r.width},c={y:r.y,height:r.height}):(l={y:r.y,height:r.height},c={x:r.x,width:r.width}),s||(o?Sv:Cv)(n,{shape:c},t,i,null);var u=t?e.baseAxis.model:null;(o?Sv:Cv)(n,{shape:l},u,i)}function BR(e,t){for(var n=0;n0?1:-1,o=r.height>0?1:-1;return{x:r.x+a*i/2,y:r.y+o*i/2,width:r.width-a*i,height:r.height-o*i}},polar:function(e,t,n){var r=e.getItemLayout(t);return{cx:r.cx,cy:r.cy,r0:r.r0,r:r.r,startAngle:r.startAngle,endAngle:r.endAngle,clockwise:r.clockwise}}};function GR(e){return e.startAngle!=null&&e.endAngle!=null&&e.startAngle===e.endAngle}function KR(e){return function(e){var t=e?`Arc`:`Angle`;return function(e){switch(e){case`start`:case`insideStart`:case`end`:case`insideEnd`:return e+t;default:return e}}}(e)}function qR(e,t,n,r,i,a,o,s){var c=t.getItemVisual(n,`style`);if(!s){var l=r.get([`itemStyle`,`borderRadius`])||0;e.setShape(`r`,l)}else if(!a.get(`roundCap`)){var u=e.shape;W(u,MR(r.getModel(`itemStyle`),u,!0)),e.setShape(u)}e.useStyle(c);var d=r.getShallow(`cursor`);d&&e.attr(`cursor`,d);var f=s?o?i.r>=i.r0?`endArc`:`startArc`:i.endAngle>=i.startAngle?`endAngle`:`startAngle`:o?nz(i,a.coordinateSystem):rz(i,a.coordinateSystem),p=Dy(r);Ey(e,p,{labelFetcher:a,labelDataIndex:n,defaultText:pI(a.getData(),n),inheritColor:c.fill,defaultOpacity:c.opacity,defaultOutsidePosition:f});var m=e.getTextContent();if(s&&m){var h=r.get([`label`,`position`]);e.textConfig.inside=h===`middle`||null,kR(e,h===`outside`?f:h,KR(o),r.get([`label`,`rotate`]))}Ry(m,p,a.getRawValue(n),function(e){return mI(t,e)});var g=r.getModel([`emphasis`]);Bg(e,g.get(`focus`),g.get(`blurScope`),g.get(`disabled`)),Wg(e,r),GR(i)&&(e.style.fill=`none`,e.style.stroke=`none`,G(e.states,function(e){e.style&&(e.style.fill=e.style.stroke=`none`)}))}function JR(e,t){var n=e.get([`itemStyle`,`borderColor`]);if(!n||n===`none`)return 0;var r=e.get([`itemStyle`,`borderWidth`])||0,i=isNaN(t.width)?Number.MAX_VALUE:Math.abs(t.width),a=isNaN(t.height)?Number.MAX_VALUE:Math.abs(t.height);return Math.min(r,i,a)}var YR=function(){function e(){}return e}(),XR=function(e){U(t,e);function t(t){var n=e.call(this,t)||this;return n.type=`largeBar`,n}return t.prototype.getDefaultShape=function(){return new YR},t.prototype.buildPath=function(e,t){for(var n=t.points,r=this.baseDimIdx,i=1-this.baseDimIdx,a=[],o=[],s=this.barWidth,c=0;c=0?n:null},30,!1);function $R(e,t,n){for(var r=e.baseDimIdx,i=1-r,a=e.shape.points,o=e.largeDataIndices,s=[],c=[],l=e.barWidth,u=0,d=a.length/3;u=s[0]&&t<=s[0]+c[0]&&n>=s[1]&&n<=s[1]+c[1])return o[u]}return-1}function ez(e,t,n){if(AL(n,`cartesian2d`)){var r=t,i=n.getArea();return{x:e?r.x:i.x,y:e?i.y:r.y,width:e?r.width:i.width,height:e?i.height:r.height}}var i=n.getArea(),a=t;return{cx:i.cx,cy:i.cy,r0:e?i.r0:a.r0,r:e?i.r:a.r,startAngle:e?a.startAngle:0,endAngle:e?a.endAngle:Math.PI*2}}function tz(e,t,n){return new(e.type===`polar`?B_:fh)({shape:ez(t,n,e),silent:!0,z2:0})}function nz(e,t){return e.height===0?t.getOtherAxis(t.getBaseAxis()).inverse?`bottom`:`top`:e.height>0?`bottom`:`top`}function rz(e,t){return e.width===0?t.getOtherAxis(t.getBaseAxis()).inverse?`left`:`right`:e.width>=0?`right`:`left`}function iz(e){e.registerChartView(FR),e.registerSeriesModel(TR),e.registerLayout(e.PRIORITY.VISUAL.LAYOUT,yR(`bar`)),e.registerLayout(e.PRIORITY.VISUAL.PROGRESSIVE_LAYOUT,bR(`bar`)),e.registerProcessor(e.PRIORITY.PROCESSOR.STATISTIC,nR(`bar`)),e.registerAction({type:`changeAxisOrder`,event:`changeAxisOrder`,update:`update`},function(e,t){var n=e.componentType||`series`;t.eachComponent({mainType:n,query:e},function(t){e.sortInfo&&t.axis.setCategorySortInfo(e.sortInfo)})}),CR(e)}var az=Qc();function oz(e,t,n){az(e)[t]=n}function sz(e,t,n){var r=az(e);r[t]===n&&(r[t]=null)}function cz(e,t){return!!az(e)[t]}bF({type:`takeGlobalCursor`,event:`globalCursorTaken`,update:`update`},As);var lz={axisPointer:1,tooltip:1,brush:1};function uz(e,t,n){var r=t.getComponentByElement(e.topTarget);if(!r||r===n||lz.hasOwnProperty(r.mainType))return!1;var i=r.coordinateSystem;if(!i||i.model===n)return!1;var a=hy(r),o=hy(n);return!((a.zlevel-o.zlevel||a.z-o.z)<=0)}var dz=function(e){U(t,e);function t(t){var n=e.call(this)||this;n._zr=t;var r=q(n._mousedownHandler,n),i=q(n._mousemoveHandler,n),a=q(n._mouseupHandler,n),o=q(n._mousewheelHandler,n),s=q(n._pinchHandler,n);return n.enable=function(e,n){var c=n.zInfo,l=hy(c.component),u=l.z,d=l.zlevel,f={component:c.component,z:u,zlevel:d,z2:X(c.z2,-1/0)},p=W({},n.triggerInfo);this._opt=Ko(W({},n),{zoomOnMouseWheel:!0,moveOnMouseMove:!0,moveOnMouseWheel:!1,preventDefaultMouseMove:!0,zInfoParsed:f,triggerInfo:p,cursorGrab:`grab`,cursorGrabbing:`grabbing`}),e??=!0,(!this._enabled||this._controlType!==e)&&(this.disable(),this._enabled=!0,(e===!0||e===`move`||e===`pan`)&&(hz(t,`mousedown`,r,f),hz(t,`mousemove`,i,f),hz(t,`mouseup`,a,f)),(e===!0||e===`scale`||e===`zoom`)&&(hz(t,`mousewheel`,o,f),hz(t,`pinch`,s,f)))},n.disable=function(){this._enabled&&(this._enabled=!1,gz(t,`mousedown`,r),gz(t,`mousemove`,i),gz(t,`mouseup`,a),gz(t,`mousewheel`,o),gz(t,`pinch`,s))},n}return t.prototype.isDragging=function(){return this._dragging},t.prototype.isPinching=function(){return this._pinching},t.prototype._checkPointer=function(e,t,n){var r=this._opt,i=r.zInfoParsed;if(uz(e,r.api,i.component))return!1;var a=r.triggerInfo,o=a.roamTrigger,s=!1;return o===`global`&&(s=!0),s||=a.isInSelf(e,t,n),s&&a.isInClip&&!a.isInClip(e,t,n)&&(s=!1),s},t.prototype._decideCursorStyle=function(e,t,n,r){var i=e.target;if(!i&&this._checkPointer(e,t,n))return this._opt.cursorGrab;if(r)return i&&i.cursor||`default`},t.prototype.dispose=function(){this.disable()},t.prototype._mousedownHandler=function(e){if(!(Vk(e)||fz(e))){for(var t=e.target;t;){if(t.draggable)return;t=t.__hostTarget||t.parent}var n=e.offsetX,r=e.offsetY;this._checkPointer(e,n,r)&&(this._x=n,this._y=r,this._dragging=!0)}},t.prototype._mousemoveHandler=function(e){var t=this._zr;if(!(e.gestureEvent===`pinch`||cz(t,`globalPan`)||fz(e))){var n=e.offsetX,r=e.offsetY;if(!this._dragging||!bz(`moveOnMouseMove`,e,this._opt)){var i=this._decideCursorStyle(e,n,r,!1);i&&t.setCursorStyle(i);return}t.setCursorStyle(this._opt.cursorGrabbing);var a=this._x,o=this._y,s=n-a,c=r-o;this._x=n,this._y=r,this._opt.preventDefaultMouseMove&&Bk(e.event),e.__ecRoamConsumed=!0,yz(this,`pan`,`moveOnMouseMove`,e,{dx:s,dy:c,oldX:a,oldY:o,newX:n,newY:r,isAvailableBehavior:null})}},t.prototype._mouseupHandler=function(e){if(!fz(e)){var t=this._zr;if(!Vk(e)){this._dragging=!1;var n=this._decideCursorStyle(e,e.offsetX,e.offsetY,!0);n&&t.setCursorStyle(n)}}},t.prototype._mousewheelHandler=function(e){if(!fz(e)){var t=bz(`zoomOnMouseWheel`,e,this._opt),n=bz(`moveOnMouseWheel`,e,this._opt),r=e.wheelDelta,i=Math.abs(r),a=e.offsetX,o=e.offsetY;if(r!==0&&(t||n)){if(t){var s=i>3?1.4:i>1?1.2:1.1,c=r>0?s:1/s;this._checkTriggerMoveZoom(this,`zoom`,`zoomOnMouseWheel`,e,{scale:c,originX:a,originY:o,isAvailableBehavior:null})}if(n){var l=Math.abs(r),u=(r>0?1:-1)*(l>3?.4:l>1?.15:.05);this._checkTriggerMoveZoom(this,`scrollMove`,`moveOnMouseWheel`,e,{scrollDelta:u,originX:a,originY:o,isAvailableBehavior:null})}}}},t.prototype._pinchHandler=function(e){if(!(cz(this._zr,`globalPan`)||fz(e))){var t=e.pinchScale>1?1.1:1/1.1;this._checkTriggerMoveZoom(this,`zoom`,null,e,{scale:t,originX:e.pinchX,originY:e.pinchY,isAvailableBehavior:null})}},t.prototype._checkTriggerMoveZoom=function(e,t,n,r,i){e._checkPointer(r,i.originX,i.originY)&&(Bk(r.event),r.__ecRoamConsumed=!0,yz(e,t,n,r,i))},t}(gp);function fz(e){return e.__ecRoamConsumed}var pz=Qc();function mz(e){var t=pz(e);return t.roam=t.roam||{},t.uniform=t.uniform||{},t}function hz(e,t,n,r){for(var i=mz(e).roam,a=i[t]=i[t]||[],o=0;o=0;a--)r[a]??(delete n[t[a]],t.pop())}function Rz(e,t){var n=e.visual,r=[];os(n)?Mz(n,function(e){r.push(e)}):n!=null&&r.push(n),!t&&r.length===1&&!{color:1,symbol:1}.hasOwnProperty(e.type)&&(r[1]=r[0]),Kz(e,r)}function zz(e){return{applyVisual:function(t,n,r){var i=this.mapValueToVisual(t);r(`color`,e(n(`color`),i))},_normalizedToVisual:Wz([0,1])}}function Bz(e){var t=this.option.visual;return t[Math.round(Ys(e,[0,1],[0,t.length-1],!0))]||{}}function Vz(e){return function(t,n,r){r(e,this.mapValueToVisual(t))}}function Hz(e){var t=this.option.visual;return t[this.option.loop&&e!==Pz?e%t.length:e]}function Uz(){return this.option.visual[0]}function Wz(e){return{linear:function(t){return Ys(t,e,this.option.visual,!0)},category:Hz,piecewise:function(t,n){var r=Gz.call(this,n);return r??=Ys(t,e,this.option.visual,!0),r},fixed:Uz}}function Gz(e){var t=this.option,n=t.pieceList;if(t.hasSpecialVisual){var r=n[Fz.findPieceIndex(e,n)];if(r&&r.visual)return r.visual[this.type]}}function Kz(e,t){return e.visual=t,e.type===`color`&&(e.parsedVisual=K(t,function(e){return Nf(e)||[0,0,0,1]})),t}var qz={linear:function(e){return Ys(e,this.option.dataExtent,[0,1],!0)},piecewise:function(e){var t=this.option.pieceList,n=Fz.findPieceIndex(e,t,!0);if(n!=null)return Ys(n,[0,t.length-1],[0,1],!0)},category:function(e){return(this.option.categories?this.option.categoryMap[e]:e)??Pz},fixed:As};function Jz(e,t,n){return e?t<=n:t0&&(y[0]=-y[0],y[1]=-y[1]);var x=v[0]<0?-1:1;if(r.__position!==`start`&&r.__position!==`end`){var S=-Math.atan2(v[1],v[0]);l[0].8?`left`:u[0]<-.8?`right`:`center`,p=u[1]>.8?`top`:u[1]<-.8?`bottom`:`middle`;break;case`start`:r.x=-u[0]*h+c[0],r.y=-u[1]*g+c[1],f=u[0]>.8?`right`:u[0]<-.8?`left`:`center`,p=u[1]>.8?`bottom`:u[1]<-.8?`top`:`middle`;break;case`insideStartTop`:case`insideStart`:case`insideStartBottom`:r.x=h*x+c[0],r.y=c[1]+C,f=v[0]<0?`right`:`left`,r.originX=-h*x,r.originY=-C;break;case`insideMiddleTop`:case`insideMiddle`:case`insideMiddleBottom`:case`middle`:r.x=b[0],r.y=b[1]+C,f=`center`,r.originY=-C;break;case`insideEndTop`:case`insideEnd`:case`insideEndBottom`:r.x=-h*x+l[0],r.y=l[1]+C,f=v[0]>=0?`right`:`left`,r.originX=h*x,r.originY=-C}r.scaleX=r.scaleY=i,r.setStyle({verticalAlign:r.__verticalAlign||p,align:r.__align||f})}},t}(y_),sB=function(){function e(e){this.group=new y_,this._LineCtor=e||oB}return e.prototype.updateData=function(e){var t=this;this._progressiveEls=null;var n=this,r=n.group,i=n._lineData;n._lineData=e,i||r.removeAll();var a=lB(e);e.diff(i).add(function(n){t._doAdd(e,n,a)}).update(function(n,r){t._doUpdate(i,e,r,n,a)}).remove(function(e){r.remove(i.getItemGraphicEl(e))}).execute()},e.prototype.updateLayout=function(){var e=this._lineData;e&&e.eachItemGraphicEl(function(t,n){t.updateLayout(e,n)},this)},e.prototype.incrementalPrepareUpdate=function(e){this._seriesScope=lB(e),this._lineData=null,this.group.removeAll()},e.prototype.incrementalUpdate=function(e,t,n){this._progressiveEls=[];function r(e){!e.isGroup&&!cB(e)&&(e.incremental=n,e.ensureState(`emphasis`).hoverLayer=2)}for(var i=e.start;i0}function lB(e){var t=e.hostModel,n=t.getModel(`emphasis`);return{lineStyle:t.getModel(`lineStyle`).getLineStyle(),emphasisLineStyle:n.getModel([`lineStyle`]).getLineStyle(),blurLineStyle:t.getModel([`blur`,`lineStyle`]).getLineStyle(),selectLineStyle:t.getModel([`select`,`lineStyle`]).getLineStyle(),emphasisDisabled:n.get(`disabled`),blurScope:n.get(`blurScope`),focus:n.get(`focus`),labelStatesModels:Dy(t)}}function uB(e){return isNaN(e[0])||isNaN(e[1])}function dB(e){return e&&!uB(e[0])&&!uB(e[1])}function fB(e,t,n,r,i,a){e||=0;var o=ac(n[1],-n[0]);if(i!=null&&(i=mB(i,[0,o])),a!=null&&(a=Math.max(a,i??0)),r===`all`){var s=Math.abs(ac(t[1],-t[0]));s=mB(s,[0,o]),i=a=mB(s,[i,a]),r=0}t[0]=mB(t[0],n),t[1]=mB(t[1],n);var c=pB(t,r);t[r]+=e;var l=i||0,u=n.slice();c.sign<0?u[0]=ac(u[0],l):u[1]=ac(u[1],-l),t[r]=mB(t[r],u);var d=pB(t,r);return i!=null&&(d.sign!==c.sign||d.spana&&(t[1-r]=ac(t[r],d.sign*a)),t}function pB(e,t){var n=e[t]-e[1-t];return{span:Math.abs(n),sign:n>0?-1:n<0?1:t?-1:1}}function mB(e,t){return Math.min(t[1]==null?1/0:t[1],Math.max(t[0]==null?-1/0:t[0],e))}var hB=!0,gB=Math.min,_B=Math.max,vB=Math.pow,yB=1e4,bB=6,xB=6,SB=`globalPan`,CB={w:[0,0],e:[0,1],n:[1,0],s:[1,1]},wB={w:`ew`,e:`ew`,n:`ns`,s:`ns`,ne:`nesw`,sw:`nesw`,nw:`nwse`,se:`nwse`},TB={brushStyle:{lineWidth:2,stroke:Q.color.backgroundTint,fill:Q.color.borderTint},transformable:!0,brushMode:`single`,removeOnClick:!1},EB=0,DB=function(e){U(t,e);function t(t){var n=e.call(this)||this;return n._track=[],n._covers=[],n._handlers={},n._zr=t,n.group=new y_,n._uid=`brushController_`+EB++,G(aV,function(e,t){this._handlers[t]=q(e,this)},n),n}return t.prototype.enableBrush=function(e){return this._brushType&&this._doDisableBrush(),e.brushType&&this._doEnableBrush(e),this},t.prototype._doEnableBrush=function(e){var t=this._zr;this._enableGlobalPan||oz(t,SB,this._uid),G(this._handlers,function(e,n){t.on(n,e)}),this._brushType=e.brushType,this._brushOption=Uo(Ho(TB),e,!0)},t.prototype._doDisableBrush=function(){var e=this._zr;sz(e,SB,this._uid),G(this._handlers,function(t,n){e.off(n,t)}),this._brushType=this._brushOption=null},t.prototype.setPanels=function(e){if(e&&e.length){var t=this._panels={};G(e,function(e){t[e.panelId]=Ho(e)})}else this._panels=null;return this},t.prototype.mount=function(e){e||={},this._enableGlobalPan=e.enableGlobalPan;var t=this.group;return this._zr.add(t),t.attr({x:e.x||0,y:e.y||0,rotation:e.rotation||0,scaleX:e.scaleX||1,scaleY:e.scaleY||1}),this._transform=t.getLocalTransform(),this},t.prototype.updateCovers=function(e){e=K(e,function(e){return Uo(Ho(TB),e,!0)});var t=`\0-brush-index-`,n=this._covers,r=this._covers=[],i=this,a=this._creatingCover;return new cw(n,e,s,o).add(c).update(c).remove(l).execute(),this;function o(e,n){return(e.id==null?t+n:e.id)+`-`+e.brushType}function s(e,t){return o(e.__brushOption,t)}function c(t,o){var s=e[t];o!=null&&n[o]===a?r[t]=n[o]:MB(i,r[t]=o==null?kB(i,OB(i,s)):(n[o].__brushOption=s,n[o]))}function l(e){n[e]!==a&&i.group.remove(n[e])}},t.prototype.unmount=function(){return this.enableBrush(!1),IB(this),this._zr.remove(this.group),this},t.prototype.dispose=function(){this.unmount(),this.off()},t}(gp);function OB(e,t){var n=cV[t.brushType].createCover(e,t);return n.__brushOption=t,jB(n,t),e.group.add(n),n}function kB(e,t){var n=NB(t);return n.endCreating&&(n.endCreating(e,t),jB(t,t.__brushOption)),t}function AB(e,t){var n=t.__brushOption;NB(t).updateCoverShape(e,t,n.range,n)}function jB(e,t){var n=t.z;n??=yB,e.traverse(function(e){e.z=n,e.z2=n})}function MB(e,t){NB(t).updateCommon(e,t),AB(e,t)}function NB(e){return cV[e.__brushOption.brushType]}function PB(e,t,n){var r=e._panels;if(!r)return hB;var i,a=e._transform;return G(r,function(e){e.isTargetByCursor(t,n,a)&&(i=e)}),i}function FB(e,t){var n=e._panels;if(!n)return hB;var r=t.__brushOption.panelId;return r==null?hB:n[r]}function IB(e){var t=e._covers,n=t.length;return G(t,function(t){e.group.remove(t)},e),t.length=0,!!n}function LB(e,t){var n=K(e._covers,function(e){var t=e.__brushOption,n=Ho(t.range);return{brushType:t.brushType,panelId:t.panelId,range:n}});e.trigger(`brush`,{areas:n,isEnd:!!t.isEnd,removeOnClick:!!t.removeOnClick})}function RB(e){var t=e._track;if(!t.length)return!1;var n=t[t.length-1],r=t[0],i=n[0]-r[0],a=n[1]-r[1];return vB(i*i+a*a,.5)>bB}function zB(e){var t=e.length-1;return t<0&&(t=0),[e[0],e[t]]}function BB(e,t,n,r){var i=new y_;return i.add(new fh({name:`main`,style:WB(n),silent:!0,draggable:!0,cursor:`move`,drift:ns(YB,e,t,i,[`n`,`s`,`w`,`e`]),ondragend:ns(LB,t,{isEnd:!0})})),G(r,function(n){i.add(new fh({name:n.join(``),style:{opacity:0},draggable:!0,silent:!0,invisible:!0,drift:ns(YB,e,t,i,n),ondragend:ns(LB,t,{isEnd:!0})}))}),i}function VB(e,t,n,r){var i=r.brushStyle.lineWidth||0,a=_B(i,xB),o=n[0][0],s=n[1][0],c=o-i/2,l=s-i/2,u=n[0][1],d=n[1][1],f=u-a+i/2,p=d-a+i/2,m=u-o,h=d-s,g=m+i,_=h+i;UB(e,t,`main`,o,s,m,h),r.transformable&&(UB(e,t,`w`,c,l,a,_),UB(e,t,`e`,f,l,a,_),UB(e,t,`n`,c,l,g,a),UB(e,t,`s`,c,p,g,a),UB(e,t,`nw`,c,l,a,a),UB(e,t,`ne`,f,l,a,a),UB(e,t,`sw`,c,p,a,a),UB(e,t,`se`,f,p,a,a))}function HB(e,t){var n=t.__brushOption,r=n.transformable,i=t.childAt(0);i.useStyle(WB(n)),i.attr({silent:!r,cursor:r?`move`:`default`}),G([[`w`],[`e`],[`n`],[`s`],[`s`,`e`],[`s`,`w`],[`n`,`e`],[`n`,`w`]],function(n){var i=t.childOfName(n.join(``)),a=n.length===1?qB(e,n[0]):JB(e,n);i&&i.attr({silent:!r,invisible:!r,cursor:r?wB[a]+`-resize`:null})})}function UB(e,t,n,r,i,a,o){var s=t.childOfName(n);s&&s.setShape($B(QB(e,t,[[r,i],[r+a,i+o]])))}function WB(e){return Ko({strokeNoScale:!0},e.brushStyle)}function GB(e,t,n,r){var i=[gB(e,n),gB(t,r)],a=[_B(e,n),_B(t,r)];return[[i[0],a[0]],[i[1],a[1]]]}function KB(e){return Kv(e.group)}function qB(e,t){return{left:`w`,right:`e`,top:`n`,bottom:`s`}[Jv({w:`left`,e:`right`,n:`top`,s:`bottom`}[t],KB(e))]}function JB(e,t){var n=[qB(e,t[0]),qB(e,t[1])];return(n[0]===`e`||n[0]===`w`)&&n.reverse(),n.join(``)}function YB(e,t,n,r,i,a){var o=n.__brushOption,s=e.toRectRange(o.range),c=ZB(t,i,a);G(r,function(e){var t=CB[e];s[t[0]][t[1]]+=c[t[0]]}),o.range=e.fromRectRange(GB(s[0][0],s[1][0],s[0][1],s[1][1])),MB(t,n),LB(t,{isEnd:!1})}function XB(e,t,n,r){var i=t.__brushOption.range,a=ZB(e,n,r);G(i,function(e){e[0]+=a[0],e[1]+=a[1]}),MB(e,t),LB(e,{isEnd:!1})}function ZB(e,t,n){var r=e.group,i=r.transformCoordToLocal(t,n),a=r.transformCoordToLocal(0,0);return[i[0]-a[0],i[1]-a[1]]}function QB(e,t,n){var r=FB(e,t);return r&&r!==hB?r.clipPath(n,e._transform):Ho(n)}function $B(e){var t=gB(e[0][0],e[1][0]),n=gB(e[0][1],e[1][1]),r=_B(e[0][0],e[1][0]),i=_B(e[0][1],e[1][1]);return{x:t,y:n,width:r-t,height:i-n}}function eV(e,t,n){if(e._brushType&&!sV(e,t.offsetX,t.offsetY)){var r=e._zr,i=e._covers,a=PB(e,t,n);if(!e._dragging)for(var o=0;or.getWidth()||n<0||n>r.getHeight()}var cV={lineX:lV(0),lineY:lV(1),rect:{createCover:function(e,t){function n(e){return e}return BB({toRectRange:n,fromRectRange:n},e,t,[[`w`],[`e`],[`n`],[`s`],[`s`,`e`],[`s`,`w`],[`n`,`e`],[`n`,`w`]])},getCreatingRange:function(e){var t=zB(e);return GB(t[1][0],t[1][1],t[0][0],t[0][1])},updateCoverShape:function(e,t,n,r){VB(e,t,n,r)},updateCommon:HB,contain:nV},polygon:{createCover:function(e,t){var n=new y_;return n.add(new J_({name:`main`,style:WB(t),silent:!0})),n},getCreatingRange:function(e){return e},endCreating:function(e,t){t.remove(t.childAt(0)),t.add(new K_({name:`main`,draggable:!0,drift:ns(XB,e,t),ondragend:ns(LB,e,{isEnd:!0})}))},updateCoverShape:function(e,t,n,r){t.childAt(0).setShape({points:QB(e,t,n)})},updateCommon:HB,contain:nV}};function lV(e){return{createCover:function(t,n){return BB({toRectRange:function(t){var n=[t,[0,100]];return e&&n.reverse(),n},fromRectRange:function(t){return t[e]}},t,n,[[[`w`],[`e`]],[[`n`],[`s`]]][e])},getCreatingRange:function(t){var n=zB(t);return[gB(n[0][e],n[1][e]),_B(n[0][e],n[1][e])]},updateCoverShape:function(t,n,r,i){var a,o=FB(t,n);if(o!==hB&&o.getLinearBrushOtherExtent)a=o.getLinearBrushOtherExtent(e);else{var s=t._zr;a=[0,[s.getWidth(),s.getHeight()][1-e]]}var c=[r,a];e&&c.reverse(),VB(t,n,c,i)},updateCommon:HB,contain:nV}}function uV(e){return e=pV(e),function(t){return Qv(t,e)}}function dV(e,t){return e=pV(e),function(n){var r=t??n,i=r?e.width:e.height,a=r?e.x:e.y;return[a,a+(i||0)]}}function fV(e,t,n){var r=pV(e);return function(e,i){return r.contain(i[0],i[1])&&!uz(e,t,n)}}function pV(e){return Ru.create(e)}var mV=256,hV=function(){function e(){this.blurSize=30,this.pointSize=20,this.maxOpacity=1,this.minOpacity=0,this._gradientPixels={inRange:null,outOfRange:null};var e=Eo.createCanvas();this.canvas=e}return e.prototype.update=function(e,t,n,r,i,a){var o=this._getBrush(),s=this._getGradient(i,`inRange`),c=this._getGradient(i,`outOfRange`),l=this.pointSize+this.blurSize,u=this.canvas,d=u.getContext(`2d`),f=e.length;u.width=t,u.height=n;for(var p=0;p0){var E=a(v)?s:c;v>0&&(v=v*w+C),b[x++]=E[T],b[x++]=E[T+1],b[x++]=E[T+2],b[x++]=E[T+3]*v*256}else x+=4}return d.putImageData(y,0,0),u},e.prototype._getBrush=function(){var e=this._brushCanvas||=Eo.createCanvas(),t=this.pointSize+this.blurSize,n=t*2;e.width=n,e.height=n;var r=e.getContext(`2d`);return r.clearRect(0,0,n,n),r.shadowOffsetX=n,r.shadowBlur=this.blurSize,r.shadowColor=Q.color.neutral99,r.beginPath(),r.arc(-t,t,this.pointSize,0,Math.PI*2,!0),r.closePath(),r.fill(),e},e.prototype._getGradient=function(e,t){for(var n=this._gradientPixels,r=n[t]||(n[t]=new Uint8ClampedArray(1024)),i=[0,0,0,0],a=0,o=0;o<256;o++)e[t](o/255,!0,i),r[a++]=i[0],r[a++]=i[1],r[a++]=i[2],r[a++]=i[3];return r},e}();function gV(e,t,n){var r=e[1]-e[0];t=K(t,function(t){return{interval:[(t.interval[0]-e[0])/r,(t.interval[1]-e[0])/r]}});var i=t.length,a=0;return function(e){for(var r=a;r=0;r--){var o=t[r].interval;if(o[0]<=e&&e<=o[1]){a=r;break}}return r>=0&&r=t[0]&&e<=t[1]}}var vV=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.render=function(e,t,n){var r;t.eachComponent(`visualMap`,function(t){t.eachTargetSeries(function(n){n===e&&(r=t)})}),this._progressiveEls=null,this.group.removeAll();var i=e.coordinateSystem;i.type===`cartesian2d`||i.type===`calendar`||i.type===`matrix`?this._renderOnGridLike(e,n,0,e.getData().count()):jL(i)&&this._renderOnGeo(i,e,r,n)},t.prototype.incrementalPrepareRender=function(e,t,n){this.group.removeAll()},t.prototype.incrementalRender=function(e,t,n,r){var i=t.coordinateSystem;i&&(jL(i)?this.render(t,n,r):(this._progressiveEls=[],this._renderOnGridLike(t,r,e.start,e.end,!0)))},t.prototype.eachRendered=function(e){uy(this._progressiveEls||this.group,e)},t.prototype._renderOnGridLike=function(e,t,n,r,i){var a=e.coordinateSystem,o=AL(a,`cartesian2d`),s=AL(a,`matrix`),c,l,u,d;if(o){var f=a.getAxis(`x`),p=a.getAxis(`y`);c=RD(f).w+.5,l=RD(p).w+.5,u=f.scale.getExtent(),d=p.scale.getExtent()}for(var m=this.group,h=e.getData(),g=e.getModel([`emphasis`,`itemStyle`]).getItemStyle(),_=e.getModel([`blur`,`itemStyle`]).getItemStyle(),v=e.getModel([`select`,`itemStyle`]).getItemStyle(),y=e.get([`itemStyle`,`borderRadius`]),b=Dy(e),x=e.getModel(`emphasis`),S=x.get(`focus`),C=x.get(`blurScope`),w=x.get(`disabled`),T=o||s?[h.mapDimension(`x`),h.mapDimension(`y`),h.mapDimension(`value`)]:[h.mapDimension(`time`),h.mapDimension(`value`)],E=n;Eu[1]||Ad[1])continue;var j=a.dataToPoint([k,A]);D=new fh({shape:{x:j[0]-c/2,y:j[1]-l/2,width:c,height:l},style:O})}else if(s){var M=a.dataToLayout([h.get(T[0],E),h.get(T[1],E)]).rect;if(fs(M.x))continue;D=new fh({z2:1,shape:M,style:O})}else{if(isNaN(h.get(T[1],E)))continue;var N=a.dataToLayout([h.get(T[0],E)]),M=N.contentRect||N.rect;if(fs(M.x)||fs(M.y))continue;D=new fh({z2:1,shape:M,style:O})}if(h.hasItemOption){var P=h.getItemModel(E),F=P.getModel(`emphasis`);g=F.getModel(`itemStyle`).getItemStyle(),_=P.getModel([`blur`,`itemStyle`]).getItemStyle(),v=P.getModel([`select`,`itemStyle`]).getItemStyle(),y=P.get([`itemStyle`,`borderRadius`]),S=F.get(`focus`),C=F.get(`blurScope`),w=F.get(`disabled`),b=Dy(P)}D.shape.r=y;var I=e.getRawValue(E),L=`-`;I&&I[2]!=null&&(L=I[2]+``),Ey(D,b,{labelFetcher:e,labelDataIndex:E,defaultOpacity:O.opacity,defaultText:L}),D.ensureState(`emphasis`).style=g,D.ensureState(`blur`).style=_,D.ensureState(`select`).style=v,Bg(D,S,C,w),D.incremental=wl(e,i),i&&(D.states.emphasis.hoverLayer=2),m.add(D),h.setItemGraphicEl(E,D),this._progressiveEls&&this._progressiveEls.push(D)}},t.prototype._renderOnGeo=function(e,t,n,r){var i=n.targetVisuals.inRange,a=n.targetVisuals.outOfRange,o=t.getData(),s=this._hmLayer||this._hmLayer||new hV;s.blurSize=t.get(`blurSize`),s.pointSize=t.get(`pointSize`),s.minOpacity=t.get(`minOpacity`),s.maxOpacity=t.get(`maxOpacity`);var c=e.getViewRect().clone(),l=e.getRoamTransform();c.applyTransform(l);var u=Math.max(c.x,0),d=Math.max(c.y,0),f=Math.min(c.width+c.x,r.getWidth()),p=Math.min(c.height+c.y,r.getHeight()),m=f-u,h=p-d,g=[o.mapDimension(`lng`),o.mapDimension(`lat`),o.mapDimension(`value`)],_=o.mapArray(g,function(t,n,r){var i=e.dataToPoint([t,n]);return i[0]-=u,i[1]-=d,i.push(r),i}),v=n.getExtent(),y=n.type===`visualMap.continuous`?_V(v,n.option.range):gV(v,n.getPieceList(),n.option.selected);s.update(_,m,h,i.color.getNormalizer(),{inRange:i.color.getColorMapper(),outOfRange:a.color.getColorMapper()},y);var b=new ih({style:{width:m,height:h,x:u,y:d,image:s.canvas},silent:!0});this.group.add(b)},t.type=`heatmap`,t}(Jj),yV=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.getInitialData=function(e,t){return lI(null,this,{generateCoord:`value`})},t.prototype.preventIncremental=function(){var e=Ox.get(this.get(`coordinateSystem`));if(e&&e.dimensions)return e.dimensions[0]===`lng`&&e.dimensions[1]===`lat`},t.type=`series.heatmap`,t.dependencies=[`grid`,`geo`,`calendar`,`matrix`],t.defaultOption={coordinateSystem:`cartesian2d`,z:2,geoIndex:0,blurSize:30,pointSize:20,maxOpacity:1,minOpacity:0,select:{itemStyle:{borderColor:Q.color.primary}}},t}(ZC);function bV(e){e.registerChartView(vV),e.registerSeriesModel(yV)}var xV={color:`fill`,borderColor:`stroke`},SV={symbol:1,symbolSize:1,symbolKeepAspect:1,legendIcon:1,visualMeta:1,liftZ:1,decal:1},CV=Qc(),wV=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.optionUpdated=function(){this.currentZLevel=this.get(`zlevel`,!0),this.currentZ=this.get(`z`,!0)},t.prototype.getInitialData=function(e,t){return lI(null,this)},t.prototype.getDataParams=function(t,n,r){var i=e.prototype.getDataParams.call(this,t,n);return r&&(i.info=CV(r).info),i},t.type=`series.custom`,t.dependencies=[`grid`,`polar`,`geo`,`singleAxis`,`calendar`,`matrix`],t.defaultOption={coordinateSystem:`cartesian2d`,z:2,legendHoverLink:!0,clip:!1},t}(ZC);function TV(e,t){return t||=[0,0],K([`x`,`y`],function(n,r){var i=this.getAxis(n),a=t[r],o=e[r]/2;return i.type===`category`?RD(i).w:Math.abs(i.dataToCoord(a-o)-i.dataToCoord(a+o))},this)}function EV(e){var t=e.master.getRect();return{coordSys:{type:`cartesian2d`,x:t.x,y:t.y,width:t.width,height:t.height},api:{coord:function(t){return e.dataToPoint(t)},size:q(TV,e)}}}function DV(e,t){return t||=[0,0],K([0,1],function(n){var r=t[n],i=e[n]/2,a=[],o=[];return a[n]=r-i,o[n]=r+i,a[1-n]=o[1-n]=t[1-n],Math.abs(this.dataToPoint(a)[n]-this.dataToPoint(o)[n])},this)}function OV(e){var t=e.view,n=t.getBoundingRect();return{coordSys:{type:`geo`,x:n.x,y:n.y,width:n.width,height:n.height,zoom:Oz(t)},api:{coord:function(t){return e.dataToPoint(t)},size:q(DV,e)}}}function kV(e,t){var n=this.getAxis(),r=t instanceof Array?t[0]:t,i=(e instanceof Array?e[0]:e)/2;return n.type===`category`?RD(n).w:Math.abs(n.dataToCoord(r-i)-n.dataToCoord(r+i))}function AV(e){var t=e.getRect();return{coordSys:{type:`singleAxis`,x:t.x,y:t.y,width:t.width,height:t.height},api:{coord:function(t){return e.dataToPoint(t)},size:q(kV,e)}}}function jV(e,t){return t||=[0,0],K([`Radius`,`Angle`],function(n,r){var i=`get`+n+`Axis`,a=this[i](),o=t[r],s=e[r]/2,c=a.type===`category`?RD(a).w:Math.abs(a.dataToCoord(o-s)-a.dataToCoord(o+s));return n===`Angle`&&(c=c*Math.PI/180),c},this)}function MV(e){var t=e.getRadiusAxis(),n=e.getAngleAxis(),r=t.getExtent();return r[0]>r[1]&&r.reverse(),{coordSys:{type:`polar`,cx:e.cx,cy:e.cy,r:r[1],r0:r[0]},api:{coord:function(r){var i=t.dataToRadius(r[0]),a=n.dataToAngle(r[1]),o=e.coordToPoint([i,a]);return o.push(i,a*Math.PI/180),o},size:q(jV,e)}}}function NV(e){var t=e.getRect(),n=e.getRangeInfo();return{coordSys:{type:`calendar`,x:t.x,y:t.y,width:t.width,height:t.height,cellWidth:e.getCellWidth(),cellHeight:e.getCellHeight(),rangeInfo:{start:n.start,end:n.end,weeks:n.weeks,dayCount:n.allDay}},api:{coord:function(t,n){return e.dataToPoint(t,n)},layout:function(t,n){return e.dataToLayout(t,n)}}}}function PV(e){var t=e.getRect();return{coordSys:{type:`matrix`,x:t.x,y:t.y,width:t.width,height:t.height},api:{coord:function(t,n){return e.dataToPoint(t,n)},layout:function(t,n){return e.dataToLayout(t,n)}}}}var FV={position:[`x`,`y`],scale:[`scaleX`,`scaleY`],origin:[`originX`,`originY`]},IV=es(FV);Zo(Hd,function(e,t){return e[t]=1,e},{}),Hd.join(`, `);var LV=[``,`style`,`shape`,`extra`],RV=Qc();function zV(e,t,n,r,i){var a=e+`Animation`,o=bv(e,r,i)||{},s=RV(t).userDuring;return o.duration>0&&(o.during=s?q(YV,{el:t,userDuring:s}):null,o.setToFinal=!0,o.scope=e),W(o,n[a]),o}function BV(e,t,n,r){r||={};var i=r.dataIndex,a=r.isInit,o=r.clearStyle,s=n.isAnimationEnabled(),c=RV(e),l=t.style;c.userDuring=t.during;var u={},d={};if($V(e,t,d),e.type===`compound`)for(var f=e.shape.paths,p=t.shape.paths,m=0;m0&&e.animateFrom(g,_)}else GV(e,t,i||0,n,u)}VV(e,t),l?e.dirty():e.markRedraw()}function VV(e,t){for(var n=RV(e).leaveToProps,r=0;r0&&e.animateFrom(i,a)}}function KV(e,t){Z(t,`silent`)&&(e.silent=t.silent),Z(t,`ignore`)&&(e.ignore=t.ignore),e instanceof Gp&&Z(t,`invisible`)&&(e.invisible=t.invisible),e instanceof Qm&&Z(t,`autoBatch`)&&(e.autoBatch=t.autoBatch)}var qV={},JV={setTransform:function(e,t){return qV.el[e]=t,this},getTransform:function(e){return qV.el[e]},setShape:function(e,t){var n=qV.el,r=n.shape||={};return r[e]=t,n.dirtyShape&&n.dirtyShape(),this},getShape:function(e){var t=qV.el.shape;if(t)return t[e]},setStyle:function(e,t){var n=qV.el,r=n.style;return r&&(r[e]=t,n.dirtyStyle&&n.dirtyStyle()),this},getStyle:function(e){var t=qV.el.style;if(t)return t[e]},setExtra:function(e,t){var n=qV.el.extra||(qV.el.extra={});return n[e]=t,this},getExtra:function(e){var t=qV.el.extra;if(t)return t[e]}};function YV(){var e=this,t=e.el;if(t){var n=RV(t).userDuring,r=e.userDuring;if(n!==r){e.el=e.userDuring=null;return}qV.el=t,r(JV)}}function XV(e,t,n,r){var i=n[e];if(i){var a=t[e],o;if(a){var s=n.transition,c=i.transition;if(c){if(!o&&(o=r[e]={}),UV(c))W(o,a);else for(var l=Ac(c),u=0;u=0){!o&&(o=r[e]={});for(var p=es(a),u=0;u=0)){var f=e.getAnimationStyleProps(),p=f?f.style:null;if(p){!a&&(a=r.style={});for(var m=es(n),l=0;l=0?t.getStore().get(i,n):void 0}var a=t.get(r.name,n),o=r&&r.ordinalMeta;return o?o.categories[a]:a}function C(n,r){r??=u;var i=t.getItemVisual(r,`style`),a=i&&i.fill,o=i&&i.opacity,s=y(r,sH).getItemStyle();a!=null&&(s.fill=a),o!=null&&(s.opacity=o);var c={inheritColor:Y(a)?a:Q.color.neutral99},l=b(r,sH),d=Oy(l,null,c,!1,!0);d.text=l.getShallow(`show`)?X(e.getFormattedLabel(r,sH),pI(t,r)):null;var f=ky(l,c,!1);return E(n,s),s=FL(s,d,f),n&&T(s,n),s.legacy=!0,s}function w(n,r){r??=u;var i=y(r,oH).getItemStyle(),a=b(r,oH),o=Oy(a,null,null,!0,!0);o.text=a.getShallow(`show`)?ms(e.getFormattedLabel(r,oH),e.getFormattedLabel(r,sH),pI(t,r)):null;var s=ky(a,null,!0);return E(n,i),i=FL(i,o,s),n&&T(i,n),i.legacy=!0,i}function T(e,t){for(var n in t)Z(t,n)&&(e[n]=t[n])}function E(e,t){e&&(e.textFill&&(t.textFill=e.textFill),e.textPosition&&(t.textPosition=e.textPosition))}function D(e,n){if(n??=u,Z(xV,e)){var r=t.getItemVisual(n,`style`);return r?r[xV[e]]:null}if(Z(SV,e))return t.getItemVisual(n,e)}function O(e){if(o.type===`cartesian2d`)return hR(Ko({axis:o.getBaseAxis()},e))}function k(){return n.getCurrentSeriesIndices()}function A(e){return Iy(e,n)}}function DH(e){var t={};return G(e.dimensions,function(n){var r=e.getDimensionInfo(n);if(!r.isExtraCoord){var i=r.coordDim,a=t[i]=t[i]||[];a[r.coordDimIndex]=e.getDimensionIndex(n)}}),t}function OH(e,t,n,r,i,a,o){if(!r){a.remove(t);return}var s=kH(e,t,n,r,i,a);return s&&o.setItemGraphicEl(n,s),s&&Bg(s,r.focus,r.blurScope,r.emphasisDisabled),s}function kH(e,t,n,r,i,a){var o=-1,s=t;t&&AH(t,r,i)&&(o=qo(a.childrenRef(),t),t=null);var c=!t,l=t;l?l.clearStates():(l=xH(r),s&&yH(s,l)),r.morph===!1?l.disableMorphing=!0:l.disableMorphing&&(l.disableMorphing=!1),r.tooltipDisabled&&(l.tooltipDisabled=!0),hH.normal.cfg=hH.normal.conOpt=hH.emphasis.cfg=hH.emphasis.conOpt=hH.blur.cfg=hH.blur.conOpt=hH.select.cfg=hH.select.conOpt=null,hH.isLegacy=!1,MH(l,n,r,i,c,hH),jH(l,n,r,i,c),SH(e,l,n,r,hH,i,c),Z(r,`info`)&&(CV(l).info=r.info);for(var u=0;u=0?a.replaceAt(l,o):a.add(l),l}function AH(e,t,n){var r=CV(e),i=t.type,a=t.shape,o=t.style;return n.isUniversalTransitionEnabled()||i!=null&&i!==r.customGraphicType||i===`path`&&UH(a)&&HH(a)!==r.customPathData||i===`image`&&Z(o,`image`)&&o.image!==r.customImagePath}function jH(e,t,n,r,i){var a=n.clipPath;if(a===!1)e&&e.getClipPath()&&e.removeClipPath();else if(a){var o=e.getClipPath();o&&AH(o,a,r)&&(o=null),o||(o=xH(a),e.setClipPath(o)),SH(null,o,t,a,null,r,i)}}function MH(e,t,n,r,i,a){if(!(e.isGroup||e.type===`compoundPath`)){NH(n,null,a),NH(n,oH,a);var o=a.normal.conOpt,s=a.emphasis.conOpt,c=a.blur.conOpt,l=a.select.conOpt;if(o!=null||s!=null||l!=null||c!=null){var u=e.getTextContent();if(o===!1)u&&e.removeTextContent();else{o=a.normal.conOpt=o||{type:`text`},u?u.clearStates():(u=xH(o),e.setTextContent(u)),SH(null,u,t,o,null,r,i);for(var d=o&&o.style,f=0;f=u;p--)LH(t,t.childAt(p),i)}}function LH(e,t,n){t&&HV(t,CV(e).option,n)}function RH(e){new cw(e.oldChildren,e.newChildren,zH,zH,e).add(BH).update(BH).remove(VH).execute()}function zH(e,t){return(e&&e.name)??mH+t}function BH(e,t){var n=this.context,r=e==null?null:n.newChildren[e],i=t==null?null:n.oldChildren[t];kH(n.api,i,n.dataIndex,r,n.seriesModel,n.group)}function VH(e){var t=this.context,n=t.oldChildren[e];n&&HV(n,CV(n).option,t.seriesModel)}function HH(e){return e&&(e.pathData||e.d)}function UH(e){return e&&(Z(e,`pathData`)||Z(e,`d`))}function WH(e){e.registerChartView(bH),e.registerSeriesModel(wV)}var GH=Qc(),KH=Ho,qH=q,JH=function(){function e(){this._dragging=!1,this.animationThreshold=15}return e.prototype.render=function(e,t,n,r){var i=t.get(`value`),a=t.get(`status`);if(this._axisModel=e,this._axisPointerModel=t,this._api=n,r||this._lastValue!==i||this._lastStatus!==a){this._lastValue=i,this._lastStatus=a;var o=this._group,s=this._handle;if(!a||a===`hide`){o&&o.hide(),s&&s.hide();return}o&&o.show(),s&&s.show();var c={};this.makeElOption(c,i,e,t,n);var l=c.graphicKey;l!==this._lastGraphicKey&&this.clear(n),this._lastGraphicKey=l;var u=this._moveAnimation=this.determineAnimation(e,t);if(!o)o=this._group=new y_,this.createPointerEl(o,c,e,t),this.createLabelEl(o,c,e,t),n.getZr().add(o);else{var d=ns(YH,t,u);this.updatePointerEl(o,c,d),this.updateLabelEl(o,c,d,t)}$H(o,t,!0),this._renderHandle(i)}},e.prototype.remove=function(e){this.clear(e)},e.prototype.dispose=function(e){this.clear(e)},e.prototype.determineAnimation=function(e,t){var n=t.get(`animation`),r=e.axis,i=r.type===`category`,a=t.get(`snap`);if(!a&&!i)return!1;if(n===`auto`||n==null){var o=this.animationThreshold;if(i&&RD(r).w>o)return!0;if(a){var s=QI(e).seriesDataCount,c=r.getExtent();return Math.abs(c[0]-c[1])/s>o}return!1}return n===!0},e.prototype.makeElOption=function(e,t,n,r,i){},e.prototype.createPointerEl=function(e,t,n,r){var i=t.pointer;if(i){var a=GH(e).pointerEl=new kv[i.type](KH(t.pointer));e.add(a)}},e.prototype.createLabelEl=function(e,t,n,r){if(t.label){var i=GH(e).labelEl=new _h(KH(t.label));e.add(i),ZH(i,r)}},e.prototype.updatePointerEl=function(e,t,n){var r=GH(e).pointerEl;r&&t.pointer&&(r.setStyle(t.pointer.style),n(r,{shape:t.pointer.shape}))},e.prototype.updateLabelEl=function(e,t,n,r){var i=GH(e).labelEl;i&&(i.setStyle(t.label.style),n(i,{x:t.label.x,y:t.label.y}),ZH(i,r))},e.prototype._renderHandle=function(e){if(!this._dragging&&this.updateHandleTransform){var t=this._axisPointerModel,n=this._api.getZr(),r=this._handle,i=t.getModel(`handle`),a=t.get(`status`);if(!i.get(`show`)||!a||a===`hide`){r&&n.remove(r),this._handle=null;return}var o;this._handle||(o=!0,r=this._handle=ey(i.get(`icon`),{cursor:`move`,draggable:!0,onmousemove:function(e){Bk(e.event)},onmousedown:qH(this._onHandleDragMove,this,0,0),drift:qH(this._onHandleDragMove,this),ondragend:qH(this._onHandleDragEnd,this)}),n.add(r)),$H(r,t,!1),r.setStyle(i.getItemStyle(null,[`color`,`borderColor`,`borderWidth`,`opacity`,`shadowColor`,`shadowBlur`,`shadowOffsetX`,`shadowOffsetY`]));var s=i.get(`size`);J(s)||(s=[s,s]),r.scaleX=s[0]/2,r.scaleY=s[1]/2,iM(this,`_doDispatchAxisPointer`,i.get(`throttle`)||0,`fixRate`),this._moveHandleToValue(e,o)}},e.prototype._moveHandleToValue=function(e,t){YH(this._axisPointerModel,!t&&this._moveAnimation,this._handle,QH(this.getHandleTransform(e,this._axisModel,this._axisPointerModel)))},e.prototype._onHandleDragMove=function(e,t){var n=this._handle;if(n){this._dragging=!0;var r=this.updateHandleTransform(QH(n),[e,t],this._axisModel,this._axisPointerModel);this._payloadInfo=r,n.stopAnimation(),n.attr(QH(r)),GH(n).lastProp=null,this._doDispatchAxisPointer()}},e.prototype._doDispatchAxisPointer=function(){if(this._handle){var e=this._payloadInfo,t=this._axisModel;this._api.dispatchAction({type:`updateAxisPointer`,x:e.cursorPoint[0],y:e.cursorPoint[1],tooltipOption:e.tooltipOption,axesInfo:[{axisDim:t.axis.dim,axisIndex:t.componentIndex}]})}},e.prototype._onHandleDragEnd=function(){if(this._dragging=!1,this._handle){var e=this._axisPointerModel.get(`value`);this._moveHandleToValue(e),this._api.dispatchAction({type:`hideTip`})}},e.prototype.clear=function(e){this._lastValue=null,this._lastStatus=null;var t=e.getZr(),n=this._group,r=this._handle;t&&n&&(this._lastGraphicKey=null,n&&t.remove(n),r&&t.remove(r),this._group=null,this._handle=null,this._payloadInfo=null),aM(this,`_doDispatchAxisPointer`)},e.prototype.doClear=function(){},e.prototype.buildLabel=function(e,t,n){return n||=0,{x:e[n],y:e[1-n],width:t[n],height:t[1-n]}},e}();function YH(e,t,n,r){XH(GH(n).lastProp,r)||(GH(n).lastProp=r,t?Sv(n,r,e):(n.stopAnimation(),n.attr(r)))}function XH(e,t){if(os(e)&&os(t)){var n=!0;return G(t,function(t,r){n&&=XH(e[r],t)}),!!n}return e===t}function ZH(e,t){e[t.get([`label`,`show`])?`show`:`hide`]()}function QH(e){return{x:e.x||0,y:e.y||0,rotation:e.rotation||0}}function $H(e,t,n){var r=t.get(`z`),i=t.get(`zlevel`);e&&e.traverse(function(e){e.type!==`group`&&(r!=null&&(e.z=r),i!=null&&(e.zlevel=i),e.silent=n)})}function eU(e){var t=e.get(`type`),n=e.getModel(t+`Style`),r;return t===`line`?(r=n.getLineStyle(),r.fill=null):t===`shadow`&&(r=n.getAreaStyle(),r.stroke=null),r}function tU(e,t,n,r,i){var a=rU(n.get(`value`),t.axis,t.ecModel,n.get(`seriesDataIndices`),{precision:n.get([`label`,`precision`]),formatter:n.get([`label`,`formatter`])}),o=n.getModel(`label`),s=vx(o.get(`padding`)||0),c=o.getFont(),l=id(a,c),u=i.position,d=l.width+s[1]+s[3],f=l.height+s[0]+s[2],p=i.align;p===`right`&&(u[0]-=d),p===`center`&&(u[0]-=d/2);var m=i.verticalAlign;m===`bottom`&&(u[1]-=f),m===`middle`&&(u[1]-=f/2),nU(u,d,f,r);var h=o.get(`backgroundColor`);(!h||h===`auto`)&&(h=t.get([`axisLine`,`lineStyle`,`color`])),e.label={x:u[0],y:u[1],style:Oy(o,{text:a,font:c,fill:o.getTextColor(),padding:s,backgroundColor:h}),z2:10}}function nU(e,t,n,r){var i=r.getWidth(),a=r.getHeight();e[0]=Math.min(e[0]+t,i)-t,e[1]=Math.min(e[1]+n,a)-n,e[0]=Math.max(e[0],0),e[1]=Math.max(e[1],0)}function rU(e,t,n,r,i){e=t.scale.parse(e);var a=t.scale.getLabel({value:e},{precision:i.precision}),o=i.formatter;if(o){var s={value:TE(t,{value:e}),axisDimension:t.dim,axisIndex:t.index,seriesData:[]};G(r,function(e){var t=n.getSeriesByIndex(e.seriesIndex),r=e.dataIndexInside,i=t&&t.getDataParams(r);i&&s.seriesData.push(i)}),Y(o)?a=o.replace(`{value}`,a):rs(o)&&(a=o(s))}return a}function iU(e,t,n){var r=Ql();return ru(r,r,n.rotation),nu(r,r,n.position),qv([e.dataToCoord(t),(n.labelOffset||0)+(n.labelDirection||1)*(n.labelMargin||0)],r)}function aU(e,t,n,r,i,a){var o=pO.innerTextLayout(n.rotation,0,n.labelDirection);n.labelMargin=i.get([`label`,`margin`]),tU(t,r,i,a,{position:iU(r.axis,e,n),align:o.textAlign,verticalAlign:o.textVerticalAlign})}function oU(e,t,n){return n||=0,{x1:e[n],y1:e[1-n],x2:t[n],y2:t[1-n]}}function sU(e,t,n){return n||=0,{x:e[n],y:e[1-n],width:t[n],height:t[1-n]}}function cU(e,t,n){return RD(e,{fromStat:{sers:K(t,function(e){return n.getSeriesByIndex(e.seriesIndex)})},min:1}).w}function lU(e,t,n){return[zs(Rs(t[0],t[1]),e-n/2),Rs(e+n/2,zs(t[0],t[1]))]}var uU=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.makeElOption=function(e,t,n,r,i){var a=n.axis,o=a.grid,s=r.get(`type`),c=a.getGlobalExtent(),l=dU(o,a).getOtherAxis(a).getGlobalExtent(),u=a.toGlobalCoord(a.dataToCoord(t,!0));if(s&&s!==`none`){var d=eU(r),f=fU[s](a,u,c,l,r.get(`seriesDataIndices`),r.ecModel);f.style=d,e.graphicKey=f.type,e.pointer=f}aU(t,e,PO(o.getRect(),n),n,r,i)},t.prototype.getHandleTransform=function(e,t,n){var r=PO(t.axis.grid.getRect(),t,{labelInside:!1});r.labelMargin=n.get([`handle`,`margin`]);var i=iU(t.axis,e,r);return{x:i[0],y:i[1],rotation:r.rotation+(r.labelDirection<0?Math.PI:0)}},t.prototype.updateHandleTransform=function(e,t,n,r){var i=n.axis,a=i.grid,o=i.getGlobalExtent(!0),s=dU(a,i).getOtherAxis(i).getGlobalExtent(),c=i.dim===`x`?0:1,l=[e.x,e.y];l[c]+=t[c],l[c]=Rs(o[1],l[c]),l[c]=zs(o[0],l[c]);var u=(s[1]+s[0])/2,d=[u,u];return d[c]=l[c],{x:l[0],y:l[1],rotation:e.rotation,cursorPoint:d,tooltipOption:[{verticalAlign:`middle`},{align:`center`}][c]}},t}(JH);function dU(e,t){var n={};return n[t.dim+`AxisIndex`]=t.index,e.getCartesian(n)}var fU={line:function(e,t,n,r){return{type:`Line`,subPixelOptimize:!0,shape:oU([t,r[0]],[t,r[1]],pU(e))}},shadow:function(e,t,n,r,i,a){var o=cU(e,i,a),s=r[1]-r[0],c=lU(t,n,o),l=c[0],u=c[1];return{type:`Rect`,shape:sU([l,r[0]],[u-l,s],pU(e))}}};function pU(e){return e.dim===`x`?0:1}var mU=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.type=`axisPointer`,t.defaultOption={show:`auto`,z:50,type:`line`,snap:!1,triggerTooltip:!0,triggerEmphasis:!0,value:null,status:null,link:[],animation:null,animationDurationUpdate:200,lineStyle:{color:Q.color.border,width:1,type:`dashed`},shadowStyle:{color:Q.color.shadowTint},label:{show:!0,formatter:null,precision:`auto`,margin:3,color:Q.color.neutral00,padding:[5,7,5,7],backgroundColor:Q.color.accent60,borderColor:null,borderWidth:0,borderRadius:3},handle:{show:!1,icon:`M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4h1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7v-1.2h6.6z M13.3,22H6.7v-1.2h6.6z M13.3,19.6H6.7v-1.2h6.6z`,size:45,margin:50,color:Q.color.accent40,throttle:40}},t}(Yx),hU=Qc(),gU=G;function _U(e,t,n){if(!Ns.node){var r=t.getZr();hU(r).records||(hU(r).records={}),vU(r,t);var i=hU(r).records[e]||(hU(r).records[e]={});i.handler=n}}function vU(e,t){if(hU(e).initialized)return;hU(e).initialized=!0,n(`click`,ns(xU,`click`)),n(`mousemove`,ns(xU,`mousemove`)),n(`mousewheel`,ns(xU,`mousewheel`)),n(`globalout`,bU);function n(n,r){e.on(n,function(n){var i=SU(t);gU(hU(e).records,function(e){e&&r(e,n,i.dispatchAction)}),yU(i.pendings,t)})}}function yU(e,t){var n=e.showTip.length,r=e.hideTip.length,i;n?i=e.showTip[n-1]:r&&(i=e.hideTip[r-1]),i&&(i.dispatchAction=null,t.dispatchAction(i))}function bU(e,t,n){e.handler(`leave`,null,n)}function xU(e,t,n,r){t.handler(e,n,r)}function SU(e){var t={showTip:[],hideTip:[]},n=function(r){var i=t[r.type];i?i.push(r):(r.dispatchAction=n,e.dispatchAction(r))};return{dispatchAction:n,pendings:t}}function CU(e,t){if(!Ns.node){var n=t.getZr();(hU(n).records||{})[e]&&(hU(n).records[e]=null)}}var wU=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.render=function(e,t,n){var r=t.getComponent(`tooltip`),i=e.get(`triggerOn`)||r&&r.get(`triggerOn`)||`mousemove|click|mousewheel`;_U(`axisPointer`,n,function(e,t,n){i!==`none`&&(e===`leave`||i.indexOf(e)>=0)&&n({type:`updateAxisPointer`,currTrigger:e,x:t&&t.offsetX,y:t&&t.offsetY})})},t.prototype.remove=function(e,t){CU(`axisPointer`,t)},t.prototype.dispose=function(e,t){CU(`axisPointer`,t)},t.type=`axisPointer`,t}(Wj);function TU(e,t){var n=[],r=e.seriesIndex,i;if(r==null||!(i=t.getSeriesByIndex(r)))return{point:[]};var a=i.getData(),o=Zc(a,e);if(o==null||o<0||J(o))return{point:[]};var s=a.getItemGraphicEl(o),c=i.coordinateSystem;if(i.getTooltipPosition)n=i.getTooltipPosition(o)||[];else if(c&&c.dataToPoint){if(e.isStacked){var l=c.getBaseAxis(),u=c.getOtherAxis(l).dim,d=l.dim,f=+(u===`x`||u===`radius`),p=a.mapDimension(d),m=[];m[f]=a.get(p,o),m[1-f]=a.get(a.getCalculationInfo(`stackResultDimension`),o),n=c.dataToPoint(m)||[]}else n=c.dataToPoint(a.getValues(K(c.dimensions,function(e){return a.mapDimension(e)}),o))||[]}else if(s){var h=s.getBoundingRect().clone();h.applyTransform(s.transform),n=[h.x+h.width/2,h.y+h.height/2]}return{point:n,el:s}}var EU=Qc();function DU(e,t,n){var r=e.currTrigger,i=[e.x,e.y],a=e,o=e.dispatchAction||q(n.dispatchAction,n),s=t.getComponent(`axisPointer`).coordSysAxesInfo;if(s){LU(i)&&(i=TU({seriesIndex:a.seriesIndex,dataIndex:a.dataIndex},t).point);var c=LU(i),l=a.axesInfo,u=s.axesInfo,d=r===`leave`||LU(i),f={},p={},m={list:[],map:{}},h={showPointer:ns(AU,p),showTooltip:ns(jU,m)};G(s.coordSysMap,function(e,t){var n=c||e.containPoint(i);G(s.coordSysAxesInfo[t],function(e,t){var r=e.axis,a=FU(l,e);if(!d&&n&&(!l||a)){var o=a&&a.value;o==null&&!c&&(o=r.pointToData(i)),o!=null&&OU(e,o,h,!1,f)}})});var g={};return G(u,function(e,t){var n=e.linkGroup;n&&!p[t]&&G(n.axesInfo,function(t,r){var i=p[r];if(t!==e&&i){var a=i.value;n.mapper&&(a=e.axis.scale.parse(n.mapper(a,IU(t),IU(e)))),g[e.key]=a}})}),G(g,function(e,t){OU(u[t],e,h,!0,f)}),MU(p,u,f),NU(m,i,e,o),PU(u,o,n),f}}function OU(e,t,n,r,i){var a=e.axis;if(!a.scale.isBlank()&&a.containData(t)){if(!e.involveSeries){n.showPointer(e,t);return}var o=kU(t,e),s=o.payloadBatch,c=o.snapToValue;s[0]&&i.seriesIndex==null&&W(i,s[0]),!r&&e.snap&&a.containData(c)&&c!=null&&(t=c),n.showPointer(e,t,s),n.showTooltip(e,o,c)}}function kU(e,t){var n=t.axis,r=n.dim,i=e,a=[],o=Number.MAX_VALUE,s=-1;return G(t.seriesModels,function(t,c){var l=t.getData().mapDimensionsAll(r),u,d;if(t.getAxisTooltipData){var f=t.getAxisTooltipData(l,e,n);d=f.dataIndices,u=f.nestestValue}else{if(d=t.indicesOfNearest(r,l[0],e,n.type===`category`?.5:null),!d.length)return;u=t.getData().get(l[0],d[0])}if(bc(u)){var p=e-u,m=Math.abs(p);m<=o&&((m=0&&s<0)&&(o=m,s=p,i=u,a.length=0),G(d,function(e){a.push({seriesIndex:t.seriesIndex,dataIndexInside:e,dataIndex:t.getData().getRawIndex(e)})}))}}),{payloadBatch:a,snapToValue:i}}function AU(e,t,n,r){e[t.key]={value:n,payloadBatch:r}}function jU(e,t,n,r){var i=n.payloadBatch,a=t.axis,o=a.model,s=t.axisPointerModel;if(t.triggerTooltip&&i.length){var c=t.coordSys.model,l=tL(c),u=e.map[l];u||(u=e.map[l]={coordSysId:c.id,coordSysIndex:c.componentIndex,coordSysType:c.type,coordSysMainType:c.mainType,dataByAxis:[]},e.list.push(u)),u.dataByAxis.push({axisDim:a.dim,axisIndex:o.componentIndex,axisType:o.type,axisId:o.id,value:r,valueLabelOpt:{precision:s.get([`label`,`precision`]),formatter:s.get([`label`,`formatter`])},seriesDataIndices:i.slice()})}}function MU(e,t,n){var r=n.axesInfo=[];G(t,function(t,n){var i=t.axisPointerModel.option,a=e[n];a?(!t.useHandle&&(i.status=`show`),i.value=a.value,i.seriesDataIndices=(a.payloadBatch||[]).slice()):!t.useHandle&&(i.status=`hide`),i.status===`show`&&r.push({axisDim:t.axis.dim,axisIndex:t.axis.model.componentIndex,value:i.value})})}function NU(e,t,n,r){if(LU(t)||!e.list.length){r({type:`hideTip`});return}var i=((e.list[0].dataByAxis[0]||{}).seriesDataIndices||[])[0]||{};r({type:`showTip`,escapeConnect:!0,x:t[0],y:t[1],tooltipOption:n.tooltipOption,position:n.position,dataIndexInside:i.dataIndexInside,dataIndex:i.dataIndex,seriesIndex:i.seriesIndex,dataByCoordSys:e.list})}function PU(e,t,n){var r=n.getZr(),i=`axisPointerLastHighlights`,a=EU(r)[i]||{},o=EU(r)[i]={};G(e,function(e,t){var n=e.axisPointerModel.option;n.status===`show`&&e.triggerEmphasis&&G(n.seriesDataIndices,function(e){o[e.seriesIndex+`|`+e.dataIndex]=e})});var s=[],c=[];function l(e){return{seriesIndex:e.seriesIndex,dataIndex:e.dataIndex}}G(a,function(e,t){!o[t]&&c.push(l(e))}),G(o,function(e,t){!a[t]&&s.push(l(e))}),c.length&&n.dispatchAction({type:`downplay`,escapeConnect:!0,notBlur:!0,batch:c}),s.length&&n.dispatchAction({type:`highlight`,escapeConnect:!0,notBlur:!0,batch:s})}function FU(e,t){for(var n=0;n<(e||[]).length;n++){var r=e[n];if(t.axis.dim===r.axisDim&&t.axis.model.componentIndex===r.axisIndex)return r}}function IU(e){var t=e.axis.model,n={},r=n.axisDim=e.axis.dim;return n.axisIndex=n[r+`AxisIndex`]=t.componentIndex,n.axisName=n[r+`AxisName`]=t.name,n.axisId=n[r+`AxisId`]=t.id,n}function LU(e){return!e||e[0]==null||isNaN(e[0])||e[1]==null||isNaN(e[1])}function RU(e){rL.registerAxisPointerClass(`CartesianAxisPointer`,uU),e.registerComponentModel(mU),e.registerComponentView(wU),e.registerPreprocessor(function(e){if(e){(!e.axisPointer||e.axisPointer.length===0)&&(e.axisPointer={});var t=e.axisPointer.link;t&&!J(t)&&(e.axisPointer.link=[t])}}),e.registerProcessor(e.PRIORITY.PROCESSOR.STATISTIC,{overallReset:function(e,t){e.getComponent(`axisPointer`).coordSysAxesInfo=GI(e,t)}}),e.registerAction({type:`updateAxisPointer`,event:`updateAxisPointer`,update:`:updateAxisPointer`},DU)}function zU(e){MF(mL),MF(RU)}function BU(e,t){var n=e.existing;if(t.id=e.keyInfo.id,!t.type&&n&&(t.type=n.type),t.parentId==null){var r=t.parentOption;r?t.parentId=r.id:n&&(t.parentId=n.parentId)}t.parentOption=null}function VU(e,t){var n;return G(t,function(t){e[t]!=null&&e[t]!==`auto`&&(n=!0)}),n}function HU(e,t,n){var r=W({},n),i=e[t],a=n.$action||`merge`;a===`merge`?i?(Uo(i,r,!0),Gx(i,r,{ignoreSize:!0}),qx(n,i),GU(n,i),GU(n,i,`shape`),GU(n,i,`style`),GU(n,i,`extra`),n.clipPath=i.clipPath):e[t]=r:a===`replace`?e[t]=r:a===`remove`&&i&&(e[t]=null)}var UU=[`transition`,`enterFrom`,`leaveTo`],WU=UU.concat([`enterAnimation`,`updateAnimation`,`leaveAnimation`]);function GU(e,t,n){if(n&&(!e[n]&&t[n]&&(e[n]={}),e=e[n],t=t[n]),e&&t)for(var r=n?UU:WU,i=0;i=0;c--){var l=n[c],u=Wc(l.id,null),d=u==null?null:i.get(u);if(d){var f=d.parent,h=YU(f),g=f===r?{width:a,height:o}:{width:h.width,height:h.height},_={},v=Ux(d,l,g,null,{hv:l.hv,boundingMode:l.bounding},_);if(!YU(d).isNew&&v){for(var y=l.transition,b={},x=0;x=0)?b[S]=C:d[S]=C}Sv(d,b,e,0)}else d.attr(_)}}},t.prototype._clear=function(){var e=this,t=this._elMap;t.each(function(n){$U(n,YU(n).option,t,e._lastGraphicModel)}),this._elMap=Es()},t.prototype.dispose=function(){this._clear()},t.type=`graphic`,t}(Wj);function ZU(e){var t=new(Z(JU,e)?JU[e]:Lv(e))({});return YU(t).type=e,t}function QU(e,t,n,r){var i=ZU(n);return t.add(i),r.set(e,i),YU(i).id=e,YU(i).isNew=!0,i}function $U(e,t,n,r){e&&e.parent&&(e.type===`group`&&e.traverse(function(e){$U(e,t,n,r)}),HV(e,t,r),n.removeKey(YU(e).id))}function eW(e,t,n,r){e.isGroup||G([[`cursor`,Gp.prototype.cursor],[`zlevel`,r||0],[`z`,n||0],[`z2`,0]],function(n){var r=n[0];Z(t,r)?e[r]=X(t[r],n[1]):e[r]??(e[r]=n[1])}),G(es(t),function(n){if(n.indexOf(`on`)===0){var r=t[n];e[n]=rs(r)?r:null}}),Z(t,`draggable`)&&(e.draggable=t.draggable),t.name!=null&&(e.name=t.name),t.id!=null&&(e.id=t.id)}function tW(e){return e=W({},e),G([`id`,`parentId`,`$action`,`hv`,`bounding`,`textContent`,`clipPath`].concat(Fx),function(t){delete e[t]}),e}function nW(e,t,n){var r=jh(e).eventData;!e.silent&&!e.ignore&&!r&&(r=jh(e).eventData={componentType:`graphic`,componentIndex:t.componentIndex,name:e.name}),r&&(r.info=n.info)}function rW(e){e.registerComponentModel(qU),e.registerComponentView(XU),e.registerPreprocessor(function(e){var t=e.graphic;J(t)?e.graphic=!t[0]||!t[0].elements?[{elements:t}]:[e.graphic[0]]:t&&!t.elements&&(e.graphic=[{elements:[t]}])})}var iW=[`x`,`y`,`radius`,`angle`,`single`],aW=Qc(),oW=[`cartesian2d`,`polar`,`singleAxis`];function sW(e){return qo(oW,e.get(`coordinateSystem`))>=0}function cW(e){return e+`Axis`}function lW(e,t){var n=Es(),r=[],i=Es();e.eachComponent({mainType:`dataZoom`,query:t},function(e){i.get(e.uid)||s(e)});var a;do a=!1,e.eachComponent(`dataZoom`,o);while(a);function o(e){!i.get(e.uid)&&c(e)&&(s(e),a=!0)}function s(e){i.set(e.uid,!0),r.push(e),l(e)}function c(e){var t=!1;return e.eachTargetAxis(function(e,r){var i=n.get(e);i&&i[r]&&(t=!0)}),t}function l(e){e.eachTargetAxis(function(e,t){(n.get(e)||n.set(e,[]))[t]=!0})}return r}function uW(e){var t=e.ecModel,n={infoList:[],infoMap:Es()};return e.eachTargetAxis(function(e,r){var i=t.getComponent(cW(e),r);if(i){var a=i.getCoordSysModel();if(a){var o=a.uid,s=n.infoMap.get(o);s||(s={model:a,axisModels:[]},n.infoList.push(s),n.infoMap.set(o,s)),s.axisModels.push(i)}}}),n}function dW(e){var t=aW(hD(e));return t.axisProxyMap||=Es()}function fW(e){if(e)return dW(e.ecModel).get(e.uid)}function pW(e,t){dW(e.ecModel).set(e.uid,t)}function mW(e,t){var n=t.getAxisModel().axis.__alignTo;return n&&e.getAxisProxy(n.dim,n.model.componentIndex)?fW(n.model):null}var hW=function(){function e(){this.indexList=[],this.indexMap=[]}return e.prototype.add=function(e){this.indexMap[e]||(this.indexList.push(e),this.indexMap[e]=!0)},e}(),gW=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n._autoThrottle=!0,n._noTarget=!0,n._rangePropMode=[`percent`,`percent`],n}return t.prototype.init=function(e,t,n){var r=_W(e);this.settledOption=r,this.mergeDefaultAndTheme(e,n),this._doInit(r)},t.prototype.mergeOption=function(e){var t=_W(e);Uo(this.option,e,!0),Uo(this.settledOption,t,!0),this._doInit(t)},t.prototype._doInit=function(e){var t=this.option;this._setDefaultThrottle(e),this._updateRangeUse(e);var n=this.settledOption;G([[`start`,`startValue`],[`end`,`endValue`]],function(e,r){this._rangePropMode[r]===`value`&&(t[e[0]]=n[e[0]]=null)},this),this._resetTarget()},t.prototype._resetTarget=function(){var e=this.get(`orient`,!0),t=this._targetAxisInfoMap=Es();this._fillSpecifiedTargetAxis(t)?this._orient=e||this._makeAutoOrientByTargetAxis():(this._orient=e||`horizontal`,this._fillAutoTargetAxisByOrient(t,this._orient)),this._noTarget=!0,t.each(function(e){e.indexList.length&&(this._noTarget=!1)},this)},t.prototype._fillSpecifiedTargetAxis=function(e){var t=!1;return G(iW,function(n){var r=this.getReferringComponents(cW(n),rl);if(r.specified){t=!0;var i=new hW;G(r.models,function(e){i.add(e.componentIndex)}),e.set(n,i)}},this),t},t.prototype._fillAutoTargetAxisByOrient=function(e,t){var n=this.ecModel,r=!0;if(r){var i=t===`vertical`?`y`:`x`,a=n.findComponents({mainType:i+`Axis`});o(a,i)}if(r){var a=n.findComponents({mainType:`singleAxis`,filter:function(e){return e.get(`orient`,!0)===t}});o(a,`single`)}function o(t,n){var i=t[0];if(i){var a=new hW;if(a.add(i.componentIndex),e.set(n,a),r=!1,n===`x`||n===`y`){var o=i.getReferringComponents(`grid`,nl).models[0];o&&G(t,function(e){i.componentIndex!==e.componentIndex&&o===e.getReferringComponents(`grid`,nl).models[0]&&a.add(e.componentIndex)})}}}r&&G(iW,function(t){if(r){var i=n.findComponents({mainType:cW(t),filter:function(e){return e.get(`type`,!0)===`category`}});if(i[0]){var a=new hW;a.add(i[0].componentIndex),e.set(t,a),r=!1}}},this)},t.prototype._makeAutoOrientByTargetAxis=function(){var e;return this.eachTargetAxis(function(t){!e&&(e=t)},this),e===`y`?`vertical`:`horizontal`},t.prototype._setDefaultThrottle=function(e){if(e.hasOwnProperty(`throttle`)&&(this._autoThrottle=!1),this._autoThrottle){var t=this.ecModel.option;this.option.throttle=t.animation&&t.animationDurationUpdate>0?100:20}},t.prototype._updateRangeUse=function(e){var t=this._rangePropMode,n=this.get(`rangeMode`);G([[`start`,`startValue`],[`end`,`endValue`]],function(r,i){var a=e[r[0]]!=null,o=e[r[1]]!=null;a&&!o?t[i]=`percent`:!a&&o?t[i]=`value`:n?t[i]=n[i]:a&&(t[i]=`percent`)})},t.prototype.noTarget=function(){return this._noTarget},t.prototype.getFirstTargetAxisModel=function(){var e;return this.eachTargetAxis(function(t,n){e??=this.ecModel.getComponent(cW(t),n)},this),e},t.prototype.eachTargetAxis=function(e,t){this._targetAxisInfoMap.each(function(n,r){G(n.indexList,function(n){e.call(t,r,n)})})},t.prototype.getAxisProxy=function(e,t){return fW(this.getAxisModel(e,t))},t.prototype.getAxisModel=function(e,t){var n=this._targetAxisInfoMap.get(e);if(n&&n.indexMap[t])return this.ecModel.getComponent(cW(e),t)},t.prototype.setRawRange=function(e){var t=this.option,n=this.settledOption;G([[`start`,`startValue`],[`end`,`endValue`]],function(r){(e[r[0]]!=null||e[r[1]]!=null)&&(t[r[0]]=n[r[0]]=e[r[0]],t[r[1]]=n[r[1]]=e[r[1]])},this),this._updateRangeUse(e)},t.prototype.setCalculatedRange=function(e){var t=this.option;G([`start`,`startValue`,`end`,`endValue`],function(n){t[n]=e[n]})},t.prototype.getPercentRange=function(){var e=this.findRepresentativeAxisProxy();if(e)return e.getWindow().percent},t.prototype.getValueRange=function(e,t){if(e==null&&t==null){var n=this.findRepresentativeAxisProxy();if(n)return n.getWindow().value}else return this.getAxisProxy(e,t).getWindow().value},t.prototype.findRepresentativeAxisProxy=function(e){if(e)return fW(e);for(var t,n=this._targetAxisInfoMap.keys(),r=0;ra[1];if(u&&!d&&!f)return!0;u&&(i=!0),d&&(t=!0),f&&(n=!0)}return i&&t&&n})}else G(r,function(n){if(i===`empty`)e.setData(t=t.map(n,function(e){return o(e)?e:NaN}));else{var r={};r[n]=a,t.selectRange(r)}});G(r,function(e){t.setApproximateExtent(a,e)})}});function o(e){return e>=a[0]&&e<=a[1]}},e.prototype._updateMinMaxSpan=function(){var e=this._minMaxSpan={},t=this._dataZoomModel,n=this._extent;G([`min`,`max`],function(r){var i=t.get(r+`Span`),a=t.get(r+`ValueSpan`);a!=null&&(a=this.getAxisModel().axis.scale.parse(a)),a==null?i!=null&&(a=Ys(i,[0,100],n,!0)-n[0]):i=Ys(n[0]+a,n,[0,100],!0),e[r+`Span`]=i,e[r+`ValueSpan`]=a},this)},e}(),SW={dirtyOnOverallProgress:!0,getTargetSeries:function(e){function t(t){e.eachComponent(`dataZoom`,function(n){n.eachTargetAxis(function(r,i){t(r,i,e.getComponent(cW(r),i),n)})})}var n=[];t(function(t,r,i,a){if(!fW(i)){var o=new xW(t,r,a,e);n.push(o),pW(i,o)}});var r=Es();return G(n,function(e){G(e.getTargetSeriesModels(),function(e){r.set(e.uid,e)})}),r},overallReset:function(e,t){e.eachComponent(`dataZoom`,function(e){var n=[];e.eachTargetAxis(function(t,r){var i=e.getAxisProxy(t,r),a=mW(e,i);a?n.push([i,a]):i.reset(e,null)}),G(n,function(t){t[0].reset(e,t[1].getWindow().percentInverted)}),e.eachTargetAxis(function(n,r){e.getAxisProxy(n,r).filterData(e,t)})}),e.eachComponent(`dataZoom`,function(e){var t=e.findRepresentativeAxisProxy();if(t){var n=t.getWindow(),r=n.percent,i=n.value;e.setCalculatedRange({start:r[0],end:r[1],startValue:i[0],endValue:i[1]})}})}};function CW(e){e.registerAction(`dataZoom`,function(e,t){G(lW(t,e),function(t){t.setRawRange({start:e.start,end:e.end,startValue:e.startValue,endValue:e.endValue})})})}var wW=yl();function TW(e){wW(e,function(){e.registerProcessor(e.PRIORITY.PROCESSOR.FILTER,SW),CW(e),e.registerSubTypeDefaulter(`dataZoom`,function(){return`slider`})})}function EW(e){e.registerComponentModel(vW),e.registerComponentView(bW),TW(e)}var DW=function(){function e(){}return e}(),OW={};function kW(e,t){OW[e]=t}function AW(e){return OW[e]}var jW=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.init=function(t,n,r){var i=r.getTheme().get(`toolbox`),a=i?i.feature:null;a&&(this._themeFeatureOption=W({},a),i.feature={}),e.prototype.init.call(this,t,n,r),a&&(i.feature=a)},t.prototype.optionUpdated=function(){G(this.option.feature,function(e,t){var n=this._themeFeatureOption,r=AW(t);r&&(r.getDefaultOption&&(r.defaultOption=r.getDefaultOption(this.ecModel)),n&&n[t]&&(Uo(e,n[t]),n[t]=null),Uo(e,r.defaultOption))},this)},t.type=`toolbox`,t.layoutMode={type:`box`,ignoreSize:!0},t.defaultOption={show:!0,z:6,orient:`horizontal`,left:`right`,top:`top`,backgroundColor:`transparent`,borderColor:Q.color.border,borderRadius:0,borderWidth:0,padding:Q.size.m,itemSize:15,itemGap:Q.size.s,showTitle:!0,iconStyle:{borderColor:Q.color.accent50,color:`none`},emphasis:{iconStyle:{borderColor:Q.color.accent70}},tooltip:{show:!1,position:`bottom`}},t}(Yx);function MW(e,t){var n=vx(t.get(`padding`)),r=t.getItemStyle([`color`,`opacity`]);return r.fill=t.get(`backgroundColor`),new fh({shape:{x:e.x-n[3],y:e.y-n[0],width:e.width+n[1]+n[3],height:e.height+n[0]+n[2],r:t.get(`borderRadius`)},style:r,silent:!0,z2:-1})}var NW=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.render=function(e,t,n,r){var i=this.group;if(i.removeAll(),!e.get(`show`))return;var a=+e.get(`itemSize`),o=e.get(`orient`)===`vertical`,s=e.get(`feature`)||{},c=this._features||=Es(),l=[];G(s,function(e,t){l.push(t)}),new cw(this._featureNames||[],l).add(u).update(u).remove(ns(u,null)).execute(),this._featureNames=Qo(l,function(e){return c.hasKey(e)});function u(i,a){var o=i!=null&&a==null,u=i!=null&&a!=null,f=i==null,p=o||u?l[i]:l[a],m=s[p],h=o||u?new Zy(m,e,t):null,g=h&&h.get(`show`),_;if(o){if(!g)return;if(PW(p))_={onclick:h.option.onclick,featureName:p};else{var v=AW(p);if(!v)return;_=new v}c.set(p,_)}else _=c.get(p);if(f||!g){FW(_)&&_.dispose&&_.dispose(t,n),c.removeKey(p);return}r&&r.newTitle!=null&&r.featureName===p&&(m.title=r.newTitle),o&&(_.uid=$y(`toolbox-feature`)),_.model=h,_.ecModel=t,_.api=n,d(h,_,p),h.setIconStatus=function(e,t){var n=this.option,r=this.iconPaths;n.iconStatus=n.iconStatus||{},n.iconStatus[e]=t,r[e]&&(t===`emphasis`?xg:Sg)(r[e])},FW(_)&&_.render&&_.render(h,t,n,r)}function d(r,s,c){var l=r.getModel(`iconStyle`),u=r.getModel([`emphasis`,`iconStyle`]),d=s instanceof DW&&s.getIcons?s.getIcons():r.get(`icon`),f=r.get(`title`)||{},p,m;Y(d)?(p={},p[c]=d):p=d,Y(f)?(m={},m[c]=f):m=f;var h=r.iconPaths={};G(p,function(c,d){var f=ey(c,{},{x:-a/2,y:-a/2,width:a,height:a});f.setStyle(l.getItemStyle());var p=f.ensureState(`emphasis`);p.style=u.getItemStyle();var g=new _h({style:{text:m[d],align:u.get(`textAlign`),borderRadius:u.get(`textBorderRadius`),padding:u.get(`textPadding`),fill:null,font:Iy({fontStyle:u.get(`textFontStyle`),fontFamily:u.get(`textFontFamily`),fontSize:u.get(`textFontSize`),fontWeight:u.get(`textFontWeight`)},t)},ignore:!0});f.setTextContent(g),cy({el:f,componentModel:e,itemName:d,formatterParamsExtra:{title:m[d]}}),f.__title=m[d],f.on(`mouseover`,function(){var t=u.getItemStyle(),r=o?e.get(`right`)==null&&e.get(`left`)!==`right`?`right`:`left`:e.get(`bottom`)==null&&e.get(`top`)!==`bottom`?`bottom`:`top`;g.setStyle({fill:u.get(`textFill`)||t.fill||t.stroke||Q.color.neutral99,backgroundColor:u.get(`textBackgroundColor`)}),f.setTextConfig({position:u.get(`textPosition`)||r}),g.ignore=!e.get(`showTitle`),n.enterEmphasis(this)}).on(`mouseout`,function(){r.get([`iconStatus`,d])!==`emphasis`&&n.leaveEmphasis(this),g.hide()}),(r.get([`iconStatus`,d])===`emphasis`?xg:Sg)(f),i.add(f),f.on(`click`,q(s.onclick,s,t,n,d)),h[d]=f})}var f=Hx(e,n).refContainer,p=e.getBoxLayoutParams(),m=e.get(`padding`),h=Bx(p,f,m);Rx(e.get(`orient`),i,e.get(`itemGap`),h.width,h.height),Ux(i,p,f,m),i.add(MW(i.getBoundingRect(),e)),o||i.eachChild(function(e){var t=e.__title,r=e.ensureState(`emphasis`),o=r.textConfig||={},s=e.getTextContent(),c=s&&s.ensureState(`emphasis`);if(c&&!rs(c)&&t){var l=c.style||={},u=id(t,_h.makeFont(l)),d=e.x+i.x,f=e.y+i.y+a,p=!1;f+u.height>n.getHeight()&&(o.position=`top`,p=!0);var m=p?-5-u.height:a+10;d+u.width/2>n.getWidth()?(o.position=[`100%`,m],l.align=`right`):d-u.width/2<0&&(o.position=[0,m],l.align=`left`)}})},t.prototype.updateView=function(e,t,n,r){G(this._features,function(e){e&&e instanceof DW&&e.updateView&&e.updateView(e.model,t,n,r)})},t.prototype.dispose=function(e,t){G(this._features,function(n){n&&n instanceof DW&&n.dispose&&n.dispose(e,t)})},t.type=`toolbox`,t}(Wj);function PW(e){return e.indexOf(`my`)===0}function FW(e){return e instanceof DW}var IW=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.onclick=function(e,t){var n=this.model,r=n.get(`name`)||e.get(`title.0.text`)||`echarts`,i=t.getZr().painter.getType()===`svg`,a=i?`svg`:n.get(`type`,!0)||`png`,o=t.getConnectedDataURL({type:a,backgroundColor:n.get(`backgroundColor`,!0)||e.get(`backgroundColor`)||Q.color.neutral00,connectedBackgroundColor:n.get(`connectedBackgroundColor`),excludeComponents:n.get(`excludeComponents`),pixelRatio:n.get(`pixelRatio`)}),s=Ns.browser;if(typeof MouseEvent==`function`&&(s.newEdge||!s.ie&&!s.edge)){var c=document.createElement(`a`);c.download=r+`.`+a,c.target=`_blank`,c.href=o;var l=new MouseEvent(`click`,{view:document.defaultView,bubbles:!0,cancelable:!1});c.dispatchEvent(l)}else if(window.navigator.msSaveOrOpenBlob||i){var u=o.split(`,`),d=u[0].indexOf(`base64`)>-1,f=i?decodeURIComponent(u[1]):u[1];d&&(f=window.atob(f));var p=r+`.`+a;if(window.navigator.msSaveOrOpenBlob){for(var m=f.length,h=new Uint8Array(m);m--;)h[m]=f.charCodeAt(m);var g=new Blob([h]);window.navigator.msSaveOrOpenBlob(g,p)}else{var _=document.createElement(`iframe`);document.body.appendChild(_);var v=_.contentWindow,y=v.document;y.open(`image/svg+xml`,`replace`),y.write(f),y.close(),v.focus(),y.execCommand(`SaveAs`,!0,p),document.body.removeChild(_)}}else{var b=n.get(`lang`),x=``,S=window.open();S.document.write(x),S.document.title=r}},t.getDefaultOption=function(e){return{show:!0,icon:`M4.7,22.9L29.3,45.5L54.7,23.4M4.6,43.6L4.6,58L53.8,58L53.8,43.6M29.2,45.1L29.2,0`,title:e.getLocaleModel().get([`toolbox`,`saveAsImage`,`title`]),type:`png`,connectedBackgroundColor:Q.color.neutral00,name:``,excludeComponents:[`toolbox`],lang:e.getLocaleModel().get([`toolbox`,`saveAsImage`,`lang`])}},t}(DW),LW=`__ec_magicType_stack__`,RW=[[`line`,`bar`],[`stack`]],zW=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.getIcons=function(){var e=this.model,t=e.get(`icon`),n={};return G(e.get(`type`),function(e){t[e]&&(n[e]=t[e])}),n},t.getDefaultOption=function(e){return{show:!0,type:[],icon:{line:`M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4`,bar:`M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7`,stack:`M8.2,38.4l-8.4,4.1l30.6,15.3L60,42.5l-8.1-4.1l-21.5,11L8.2,38.4z M51.9,30l-8.1,4.2l-13.4,6.9l-13.9-6.9L8.2,30l-8.4,4.2l8.4,4.2l22.2,11l21.5-11l8.1-4.2L51.9,30z M51.9,21.7l-8.1,4.2L35.7,30l-5.3,2.8L24.9,30l-8.4-4.1l-8.3-4.2l-8.4,4.2L8.2,30l8.3,4.2l13.9,6.9l13.4-6.9l8.1-4.2l8.1-4.1L51.9,21.7zM30.4,2.2L-0.2,17.5l8.4,4.1l8.3,4.2l8.4,4.2l5.5,2.7l5.3-2.7l8.1-4.2l8.1-4.2l8.1-4.1L30.4,2.2z`},title:e.getLocaleModel().get([`toolbox`,`magicType`,`title`]),option:{},seriesIndex:{}}},t.prototype.onclick=function(e,t,n){var r=this.model,i=r.get([`seriesIndex`,n]);if(BW[n]){var a={series:[]};G(RW,function(e){qo(e,n)>=0&&G(e,function(e){r.setIconStatus(e,`normal`)})}),r.setIconStatus(n,`emphasis`),e.eachComponent({mainType:`series`,query:i==null?null:{seriesIndex:i}},function(e){var t=e.subType,i=e.id,o=BW[n](t,i,e,r);o&&(Ko(o,e.option),a.series.push(o));var s=e.coordinateSystem;if(s&&s.type===`cartesian2d`&&(n===`line`||n===`bar`)){var c=s.getAxesByScale(`ordinal`)[0];if(c){var l=c.dim+`Axis`,u=e.getReferringComponents(l,nl).models[0].componentIndex;a[l]=a[l]||[];for(var d=0;d<=u;d++)a[l][u]=a[l][u]||{};a[l][u].boundaryGap=n===`bar`}}});var o,s=n;n===`stack`&&(o=Uo({stack:r.option.title.tiled,tiled:r.option.title.stack},r.option.title),r.get([`iconStatus`,n])!==`emphasis`&&(s=`tiled`)),t.dispatchAction({type:`changeMagicType`,currentType:s,newOption:a,newTitle:o,featureName:`magicType`})}},t}(DW),BW={line:function(e,t,n,r){if(e===`bar`)return Uo({id:t,type:`line`,data:n.get(`data`),stack:n.get(`stack`),markPoint:n.get(`markPoint`),markLine:n.get(`markLine`)},r.get([`option`,`line`])||{},!0)},bar:function(e,t,n,r){if(e===`line`)return Uo({id:t,type:`bar`,data:n.get(`data`),stack:n.get(`stack`),markPoint:n.get(`markPoint`),markLine:n.get(`markLine`)},r.get([`option`,`bar`])||{},!0)},stack:function(e,t,n,r){var i=n.get(`stack`)===LW;if(e===`line`||e===`bar`)return r.setIconStatus(`stack`,i?`normal`:`emphasis`),Uo({id:t,stack:i?``:LW},r.get([`option`,`stack`])||{},!0)}};bF({type:`changeMagicType`,event:`magicTypeChanged`,update:`prepareAndUpdate`},function(e,t){t.mergeOption(e.newOption)});var VW=Array(60).join(`-`),HW=` `;function UW(e){var t={},n=[],r=[];return e.eachRawSeries(function(e){var i=e.coordinateSystem;if(i&&(i.type===`cartesian2d`||i.type===`polar`)){var a=i.getBaseAxis();if(a.type===`category`){var o=zO(a);t[o]||(t[o]={categoryAxis:a,valueAxis:i.getOtherAxis(a),series:[]},r.push({axisDim:a.dim,axisIndex:a.index})),t[o].series.push(e)}else n.push(e)}else n.push(e)}),{seriesGroupByCategoryAxis:t,other:n,meta:r}}function WW(e){var t=[];return G(e,function(e,n){var r=e.categoryAxis,i=e.valueAxis.dim,a=[` `].concat(K(e.series,function(e){return e.name})),o=[r.model.getCategories()];G(e.series,function(e){var t=e.getRawData();o.push(e.getRawData().mapArray(t.mapDimension(i),function(e){return e}))});for(var s=[a.join(HW)],c=0;c`,m=l.join(p);this._showOrMove(a,function(){this._updateContentNotChangedOnAxis(e,s)?this._updatePosition(a,d,i[0],i[1],this._tooltipContent,s):this._showTooltipContent(a,m,s,Math.random()+``,i[0],i[1],d,null,u)})},t.prototype._showSeriesItemTooltip=function(e,t,n){var r=this._ecModel,i=jh(t),a=i.seriesIndex,o=r.getSeriesByIndex(a),s=i.dataModel||o,c=i.dataIndex,l=i.dataType,u=s.getData(l),d=this._renderMode,f=e.positionDefault,p=tK([u.getItemModel(c),s,o&&(o.coordinateSystem||{}).model],this._tooltipModel,f?{position:f}:null),m=p.get(`trigger`);if(m==null||m===`item`){var h=s.getDataParams(c,l),g=new KC;h.marker=g.makeTooltipMarker(`item`,Tx(h.color),d);var _=WS(s.formatTooltip(c,!1,l)),v=p.get(`order`),y=p.get(`valueFormatter`),b=_.frag,x=b?LC(y?W({valueFormatter:y},b):b,g,d,v,r.get(`useUTC`),p.get(`textStyle`)):_.text,S=`item_`+s.name+`_`+c;this._showOrMove(p,function(){this._showTooltipContent(p,x,h,S,e.offsetX,e.offsetY,e.position,e.target,g)}),n({type:`showTip`,dataIndexInside:c,dataIndex:u.getRawIndex(c),seriesIndex:a,from:this.uid})}},t.prototype._showComponentItemTooltip=function(e,t,n){var r=this._renderMode===`html`,i=jh(t),a=i.tooltipConfig.option||{},o=a.encodeHTMLContent;if(Y(a)){var s=a;a={content:s,formatter:s},o=!0}o&&r&&a.content&&(a=Ho(a),a.content=gb(a.content));var c=[a],l=this._ecModel.getComponent(i.componentMainType,i.componentIndex);l&&c.push(l),c.push({formatter:a.content});var u=e.positionDefault,d=tK(c,this._tooltipModel,u?{position:u}:null),f=d.get(`content`),p=Math.random()+``,m=new KC;this._showOrMove(d,function(){var n=Ho(d.get(`formatterParams`)||{});this._showTooltipContent(d,f,n,p,e.offsetX,e.offsetY,e.position,t,m)}),n({type:`showTip`,from:this.uid})},t.prototype._showTooltipContent=function(e,t,n,r,i,a,o,s,c){if(this._ticket=``,e.get(`showContent`)&&e.get(`show`)){var l=this._tooltipContent;l.setEnterable(e.get(`enterable`));var u=e.get(`formatter`);o||=e.get(`position`);var d=t,f=this._getNearestPoint([i,a],n,e.get(`trigger`),e.get(`borderColor`),e.get(`defaultBorderColor`,!0)).color;if(u){if(Y(u)){var p=e.ecModel.get(`useUTC`),m=J(n)?n[0]:n,h=m&&m.axisType&&m.axisType.indexOf(`time`)>=0;d=u,h&&(d=Qb(m.axisValue,d,p)),d=Sx(d,n,!0)}else if(rs(u)){var g=q(function(t,r){t===this._ticket&&(l.setContent(r,c,e,f,o),this._updatePosition(e,o,i,a,l,n,s))},this);this._ticket=r,d=u(n,r,g)}else d=u}l.setContent(d,c,e,f,o),l.show(e,f),this._updatePosition(e,o,i,a,l,n,s)}},t.prototype._getNearestPoint=function(e,t,n,r,i){if(n===`axis`||J(t))return{color:r||i};if(!J(t))return{color:r||t.color||t.borderColor}},t.prototype._updatePosition=function(e,t,n,r,i,a,o){var s=this._api.getWidth(),c=this._api.getHeight();t||=e.get(`position`);var l=i.getSize(),u=e.get(`align`),d=e.get(`verticalAlign`),f=o&&o.getBoundingRect().clone();if(o&&f.applyTransform(o.transform),rs(t)&&(t=t([n,r],a,i.el,f,{viewSize:[s,c],contentSize:l.slice()})),J(t))n=Xs(t[0],s),r=Xs(t[1],c);else if(os(t)){var p=t;p.width=l[0],p.height=l[1];var m=Bx(p,{width:s,height:c});n=m.x,r=m.y,u=null,d=null}else if(Y(t)&&o){var h=aK(t,f,l,e.get(`borderWidth`));n=h[0],r=h[1]}else{var h=rK(n,r,i,s,c,u?null:20,d?null:20);n=h[0],r=h[1]}if(u&&(n-=oK(u)?l[0]/2:u===`right`?l[0]:0),d&&(r-=oK(d)?l[1]/2:d===`bottom`?l[1]:0),MG(e)){var h=iK(n,r,i,s,c);n=h[0],r=h[1]}i.moveTo(n,r)},t.prototype._updateContentNotChangedOnAxis=function(e,t){var n=this._lastDataByCoordSys,r=this._cbParamsList,i=!!n&&n.length===e.length;return i&&G(n,function(n,a){var o=n.dataByAxis||[],s=(e[a]||{}).dataByAxis||[];i&&=o.length===s.length,i&&G(o,function(e,n){var a=s[n]||{},o=e.seriesDataIndices||[],c=a.seriesDataIndices||[];i=i&&e.value===a.value&&e.axisType===a.axisType&&e.axisId===a.axisId&&o.length===c.length,i&&G(o,function(e,t){var n=c[t];i=i&&e.seriesIndex===n.seriesIndex&&e.dataIndex===n.dataIndex}),r&&G(e.seriesDataIndices,function(e){var n=e.seriesIndex,a=t[n],o=r[n];a&&o&&o.data!==a.data&&(i=!1)})})}),this._lastDataByCoordSys=e,this._cbParamsList=t,!!i},t.prototype._hide=function(e){this._lastDataByCoordSys=null,this._cbParamsList=null,e({type:`hideTip`,from:this.uid})},t.prototype.dispose=function(e,t){!Ns.node&&t.getDom()&&(aM(this,`_updatePosition`),this._tooltipContent.dispose(),CU(`itemTooltip`,t),this._tooltipContent=null,this._tooltipModel=null,this._lastDataByCoordSys=null,this._cbParamsList=null)},t.type=`tooltip`,t}(Wj);function tK(e,t,n){var r=t.ecModel,i;n?(i=new Zy(n,r,r),i=new Zy(t.option,i,r)):i=t;for(var a=e.length-1;a>=0;a--){var o=e[a];o&&(o instanceof Zy&&(o=o.get(`tooltip`,!0)),Y(o)&&(o={formatter:o}),o&&(i=new Zy(o,i,r)))}return i}function nK(e,t){return e.dispatchAction||q(t.dispatchAction,t)}function rK(e,t,n,r,i,a,o){var s=n.getSize(),c=s[0],l=s[1];return a!=null&&(e+c+a+2>r?e-=c+a:e+=a),o!=null&&(t+l+o>i?t-=l+o:t+=o),[e,t]}function iK(e,t,n,r,i){var a=n.getSize(),o=a[0],s=a[1];return e=Math.min(e+o,r)-o,t=Math.min(t+s,i)-s,e=Math.max(e,0),t=Math.max(t,0),[e,t]}function aK(e,t,n,r){var i=n[0],a=n[1],o=Math.ceil(Math.SQRT2*r)+8,s=0,c=0,l=t.width,u=t.height;switch(e){case`inside`:s=t.x+l/2-i/2,c=t.y+u/2-a/2;break;case`top`:s=t.x+l/2-i/2,c=t.y-a-o;break;case`bottom`:s=t.x+l/2-i/2,c=t.y+u+o;break;case`left`:s=t.x-i-o,c=t.y+u/2-a/2;break;case`right`:s=t.x+l+o,c=t.y+u/2-a/2}return[s,c]}function oK(e){return e===`center`||e===`middle`}function sK(e,t,n){var r=tl(e).queryOptionMap,i=r.keys()[0];if(i&&i!==`series`){var a=il(t,i,r.get(i),{useDefault:!1,enableAll:!1,enableNone:!1}).models[0];if(a){var o=n.getViewOfComponentModel(a),s;if(o.group.traverse(function(t){var n=jh(t).tooltipConfig;if(n&&n.name===e.name)return s=t,!0}),s)return{componentMainType:i,componentIndex:a.componentIndex,el:s}}}}function cK(e){MF(RU),e.registerComponentModel(jG),e.registerComponentView(eK),e.registerAction({type:`showTip`,event:`showTip`,update:`tooltip:manuallyShowTip`},As),e.registerAction({type:`hideTip`,event:`hideTip`,update:`tooltip:manuallyHideTip`},As)}var lK=[`rect`,`polygon`,`keep`,`clear`];function uK(e,t){var n=Ac(e?e.brush:[]);if(n.length){var r=[];G(n,function(e){var t=e.hasOwnProperty(`toolbox`)?e.toolbox:[];t instanceof Array&&(r=r.concat(t))});var i=e&&e.toolbox;J(i)&&(i=i[0]),i||(i={feature:{}},e.toolbox=[i]);var a=i.feature||(i.feature={}),o=a.brush||={},s=o.type||=[];s.push.apply(s,r),xl(s,function(e){return e+``},null),t&&!s.length&&s.push.apply(s,lK)}}var dK=G;function fK(e){if(e){for(var t in e)if(e.hasOwnProperty(t))return!0}}function pK(e,t,n){var r={};return dK(t,function(t){var a=r[t]=i();dK(e[t],function(e,r){if(Fz.isValidType(r)){var i={type:r,visual:e};n&&n(i,t),a[r]=new Fz(i),r===`opacity`&&(i=Ho(i),i.type=`colorAlpha`,a.__hidden.__alphaForOpacity=new Fz(i))}})}),r;function i(){var e=function(){};return e.prototype.__hidden=e.prototype,new e}}function mK(e,t,n){var r;G(n,function(e){t.hasOwnProperty(e)&&fK(t[e])&&(r=!0)}),r&&G(n,function(n){t.hasOwnProperty(n)&&fK(t[n])?e[n]=Ho(t[n]):delete e[n]})}function hK(e,t,n,r,i,a){var o={};G(e,function(e){o[e]=Fz.prepareVisualTypes(t[e])});var s;function c(e){return VM(n,s,e)}function l(e,t){UM(n,s,e,t)}a==null?n.each(u):n.each([a],u);function u(e,u){s=a==null?e:u;var d=n.getRawDataItem(s);if(!(d&&d.visualMap===!1))for(var f=r.call(i,e),p=t[f],m=o[f],h=0,g=m.length;ht[0][1]&&(t[0][1]=a[0]),a[1]t[1][1]&&(t[1][1]=a[1])}return t&&MK(t)}};function MK(e){return new Ru(e[0][0],e[1][0],e[0][1]-e[0][0],e[1][1]-e[1][0])}var NK=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.init=function(e,t){this.ecModel=e,this.api=t,this.model,(this._brushController=new DB(t.getZr())).on(`brush`,q(this._onBrush,this)).mount()},t.prototype.render=function(e,t,n,r){this.model=e,this._updateController(e,t,n,r)},t.prototype.updateTransform=function(e,t,n,r){wK(t),this._updateController(e,t,n,r)},t.prototype.updateVisual=function(e,t,n,r){this.updateTransform(e,t,n,r)},t.prototype.updateView=function(e,t,n,r){this._updateController(e,t,n,r)},t.prototype._updateController=function(e,t,n,r){(!r||r.$from!==e.id)&&this._brushController.setPanels(e.brushTargetManager.makePanelOpts(n)).enableBrush(e.brushOption).updateCovers(e.areas.slice())},t.prototype.dispose=function(){this._brushController.dispose()},t.prototype._onBrush=function(e){var t=this.model.id,n=this.model.brushTargetManager.setOutputRanges(e.areas,this.ecModel);(!e.isEnd||e.removeOnClick)&&this.api.dispatchAction({type:`brush`,brushId:t,areas:Ho(n),$from:t}),e.isEnd&&this.api.dispatchAction({type:`brushEnd`,brushId:t,areas:Ho(n),$from:t})},t.type=`brush`,t}(Wj),PK=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n.areas=[],n.brushOption={},n}return t.prototype.optionUpdated=function(e,t){var n=this.option;!t&&mK(n,e,[`inBrush`,`outOfBrush`]);var r=n.inBrush=n.inBrush||{};n.outOfBrush=n.outOfBrush||{color:this.option.defaultOutOfBrushColor},r.hasOwnProperty(`liftZ`)||(r.liftZ=5)},t.prototype.setAreas=function(e){e&&(this.areas=K(e,function(e){return FK(this.option,e)},this))},t.prototype.setBrushOption=function(e){this.brushOption=FK(this.option,e),this.brushType=this.brushOption.brushType},t.type=`brush`,t.dependencies=[`geo`,`grid`,`xAxis`,`yAxis`,`parallel`,`series`],t.defaultOption={seriesIndex:`all`,brushType:`rect`,brushMode:`single`,transformable:!0,brushStyle:{borderWidth:1,color:Q.color.backgroundTint,borderColor:Q.color.borderTint},throttleType:`fixRate`,throttleDelay:0,removeOnClick:!0,z:1e4,defaultOutOfBrushColor:Q.color.disabled},t}(Yx);function FK(e,t){return Uo({brushType:e.brushType,brushMode:e.brushMode,transformable:e.transformable,brushStyle:new Zy(e.brushStyle).getItemStyle(),removeOnClick:e.removeOnClick,z:e.z},t,!0)}var IK=[`rect`,`polygon`,`lineX`,`lineY`,`keep`,`clear`],LK=function(e){U(t,e);function t(){return e!==null&&e.apply(this,arguments)||this}return t.prototype.render=function(e,t,n){var r,i,a;t.eachComponent({mainType:`brush`},function(e){r=e.brushType,i=e.brushOption.brushMode||`single`,a||=!!e.areas.length}),this._brushType=r,this._brushMode=i,G(e.get(`type`,!0),function(t){e.setIconStatus(t,(t===`keep`?i===`multiple`:t===`clear`?a:t===r)?`emphasis`:`normal`)})},t.prototype.updateView=function(e,t,n){this.render(e,t,n)},t.prototype.getIcons=function(){var e=this.model,t=e.get(`icon`,!0),n={};return G(e.get(`type`,!0),function(e){t[e]&&(n[e]=t[e])}),n},t.prototype.onclick=function(e,t,n){var r=this._brushType,i=this._brushMode;n===`clear`?(t.dispatchAction({type:`axisAreaSelect`,intervals:[]}),t.dispatchAction({type:`brush`,command:`clear`,areas:[]})):t.dispatchAction({type:`takeGlobalCursor`,key:`brush`,brushOption:{brushType:n===`keep`?r:r!==n&&n,brushMode:n===`keep`?i===`multiple`?`single`:`multiple`:i}})},t.getDefaultOption=function(e){return{show:!0,type:IK.slice(),icon:{rect:`M7.3,34.7 M0.4,10V-0.2h9.8 M89.6,10V-0.2h-9.8 M0.4,60v10.2h9.8 M89.6,60v10.2h-9.8 M12.3,22.4V10.5h13.1 M33.6,10.5h7.8 M49.1,10.5h7.8 M77.5,22.4V10.5h-13 M12.3,31.1v8.2 M77.7,31.1v8.2 M12.3,47.6v11.9h13.1 M33.6,59.5h7.6 M49.1,59.5 h7.7 M77.5,47.6v11.9h-13`,polygon:`M55.2,34.9c1.7,0,3.1,1.4,3.1,3.1s-1.4,3.1-3.1,3.1 s-3.1-1.4-3.1-3.1S53.5,34.9,55.2,34.9z M50.4,51c1.7,0,3.1,1.4,3.1,3.1c0,1.7-1.4,3.1-3.1,3.1c-1.7,0-3.1-1.4-3.1-3.1 C47.3,52.4,48.7,51,50.4,51z M55.6,37.1l1.5-7.8 M60.1,13.5l1.6-8.7l-7.8,4 M59,19l-1,5.3 M24,16.1l6.4,4.9l6.4-3.3 M48.5,11.6 l-5.9,3.1 M19.1,12.8L9.7,5.1l1.1,7.7 M13.4,29.8l1,7.3l6.6,1.6 M11.6,18.4l1,6.1 M32.8,41.9 M26.6,40.4 M27.3,40.2l6.1,1.6 M49.9,52.1l-5.6-7.6l-4.9-1.2`,lineX:`M15.2,30 M19.7,15.6V1.9H29 M34.8,1.9H40.4 M55.3,15.6V1.9H45.9 M19.7,44.4V58.1H29 M34.8,58.1H40.4 M55.3,44.4 V58.1H45.9 M12.5,20.3l-9.4,9.6l9.6,9.8 M3.1,29.9h16.5 M62.5,20.3l9.4,9.6L62.3,39.7 M71.9,29.9H55.4`,lineY:`M38.8,7.7 M52.7,12h13.2v9 M65.9,26.6V32 M52.7,46.3h13.2v-9 M24.9,12H11.8v9 M11.8,26.6V32 M24.9,46.3H11.8v-9 M48.2,5.1l-9.3-9l-9.4,9.2 M38.9-3.9V12 M48.2,53.3l-9.3,9l-9.4-9.2 M38.9,62.3V46.4`,keep:`M4,10.5V1h10.3 M20.7,1h6.1 M33,1h6.1 M55.4,10.5V1H45.2 M4,17.3v6.6 M55.6,17.3v6.6 M4,30.5V40h10.3 M20.7,40 h6.1 M33,40h6.1 M55.4,30.5V40H45.2 M21,18.9h62.9v48.6H21V18.9z`,clear:`M22,14.7l30.9,31 M52.9,14.7L22,45.7 M4.7,16.8V4.2h13.1 M26,4.2h7.8 M41.6,4.2h7.8 M70.3,16.8V4.2H57.2 M4.7,25.9v8.6 M70.3,25.9v8.6 M4.7,43.2v12.6h13.1 M26,55.8h7.8 M41.6,55.8h7.8 M70.3,43.2v12.6H57.2`},title:e.getLocaleModel().get([`toolbox`,`brush`,`title`])}},t}(DW);function RK(e){e.registerComponentView(NK),e.registerComponentModel(PK),e.registerPreprocessor(uK),e.registerVisual(e.PRIORITY.VISUAL.BRUSH,TK),e.registerAction({type:`brush`,event:`brush`,update:`updateVisual`},function(e,t){t.eachComponent({mainType:`brush`,query:e},function(t){t.setAreas(e.areas)})}),e.registerAction({type:`brushSelect`,event:`brushSelected`,update:`none`},As),e.registerAction({type:`brushEnd`,event:`brushEnd`,update:`none`},As),kW(`brush`,LK)}function zK(e,t){if(!e)return!1;for(var n=J(e)?e:[e],r=0;r=0&&(s[o]=+s[o].toFixed(f)),[s,d]}var KK={min:ns(GK,`min`),max:ns(GK,`max`),average:ns(GK,`average`),median:ns(GK,`median`)};function qK(e,t){if(t){var n=e.getData(),r=e.coordinateSystem,i=r&&r.dimensions;if(!WK(t)&&!J(t.coord)&&J(i)){var a=JK(t,n,r,e);if(t=Ho(t),t.type&&KK[t.type]&&a.baseAxis&&a.valueAxis){var o=qo(i,a.baseAxis.dim),s=qo(i,a.valueAxis.dim),c=KK[t.type](n,a.valueAxis.dim,a.baseDataDim,a.valueDataDim,o,s);t.coord=c[0],t.value=c[1]}else t.coord=[t.xAxis==null?t.radiusAxis:t.xAxis,t.yAxis==null?t.angleAxis:t.yAxis]}if(t.coord==null||!J(i)){t.coord=[];var l=e.getBaseAxis();if(l&&t.type&&KK[t.type]){var u=r.getOtherAxis(l);u&&(t.value=$K(n,n.mapDimension(u.dim),t.type))}}else for(var d=t.coord,f=0;f<2;f++)KK[d[f]]&&(d[f]=$K(n,n.mapDimension(i[f]),d[f]));return t}}function JK(e,t,n,r){var i={};return e.valueIndex!=null||e.valueDim!=null?(i.valueDataDim=e.valueIndex==null?e.valueDim:t.getDimension(e.valueIndex),i.valueAxis=n.getAxis(YK(r,i.valueDataDim)),i.baseAxis=n.getOtherAxis(i.valueAxis),i.baseDataDim=t.mapDimension(i.baseAxis.dim)):(i.baseAxis=r.getBaseAxis(),i.valueAxis=n.getOtherAxis(i.baseAxis),i.baseDataDim=t.mapDimension(i.baseAxis.dim),i.valueDataDim=t.mapDimension(i.valueAxis.dim)),i}function YK(e,t){var n=e.getData().getDimensionInfo(t);return n&&n.coordDim}function XK(e,t){return e&&e.containData&&t.coord&&!UK(t)?e.containData(t.coord):!0}function ZK(e,t,n){return e&&e.containZone&&t.coord&&n.coord&&!UK(t)&&!UK(n)?e.containZone(t.coord,n.coord):!0}function QK(e,t){return e?function(e,n,r,i){return JS(i<2?e.coord&&e.coord[i]:e.value,t[i])}:function(e,n,r,i){return JS(e.value,t[i])}}function $K(e,t,n){if(n===`average`){var r=0,i=0;return e.each(t,function(e,t){isNaN(e)||(r+=e,i++)}),r/i}return n===`median`?e.getMedian(t):e.getDataExtent(t)[+(n===`max`)]}var eq=Qc(),tq=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.init=function(){this.markerGroupMap=Es()},t.prototype.render=function(e,t,n){var r=this,i=this.markerGroupMap;i.each(function(e){eq(e).keep=!1}),t.eachSeries(function(e){var i=HK.getMarkerModelFromSeries(e,r.type);i&&r.renderSeries(e,i,t,n)}),i.each(function(e){!eq(e).keep&&r.group.remove(e.group)}),nq(t,i,this.type)},t.prototype.markKeep=function(e){eq(e).keep=!0},t.prototype.toggleBlurSeries=function(e,t){var n=this;G(e,function(e){var r=HK.getMarkerModelFromSeries(e,n.type);r&&r.getData().eachItemGraphicEl(function(e){e&&(t?Cg(e):wg(e))})})},t.type=`marker`,t}(Wj);function nq(e,t,n){e.eachSeries(function(e){var r=HK.getMarkerModelFromSeries(e,n),i=t.get(e.id);if(r&&i&&i.group){var a=hy(r),o=a.z,s=a.zlevel;_y(i.group,o,s)}})}var rq=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.createMarkerModelFromSeries=function(e,n,r){return new t(e,n,r)},t.type=`markLine`,t.defaultOption={z:5,symbol:[`circle`,`arrow`],symbolSize:[8,16],symbolOffset:0,precision:2,tooltip:{trigger:`item`},label:{show:!0,position:`end`,distance:5},lineStyle:{type:`dashed`},emphasis:{label:{show:!0},lineStyle:{width:3}},animationEasing:`linear`},t}(HK),iq=Qc(),aq=function(e,t,n,r){var i=e.getData(),a;if(J(r))a=r;else{var o=r.type;if(o===`min`||o===`max`||o===`average`||o===`median`||r.xAxis!=null||r.yAxis!=null){var s=void 0,c=void 0;if(r.yAxis!=null||r.xAxis!=null)s=t.getAxis(r.yAxis==null?`x`:`y`),c=ps(r.yAxis,r.xAxis);else{var l=JK(r,i,t,e);s=l.valueAxis,c=$K(i,_E(i,l.valueDataDim),o)}var u=s.dim===`x`?0:1,d=1-u,f=Ho(r),p={coord:[]};f.type=null,f.coord=[],f.coord[d]=-1/0,p.coord[d]=1/0;var m=n.get(`precision`);m>=0&&as(c)&&(c=+c.toFixed(Math.min(m,20))),f.coord[u]=p.coord[u]=c,a=[f,p,{type:o,valueIndex:r.valueIndex,value:c}]}else a=[]}var h=[qK(e,a[0]),qK(e,a[1]),W({},a[2])];return h[2].type=h[2].type||null,Uo(h[2],h[0]),Uo(h[2],h[1]),h};function oq(e){return!isNaN(e)&&!isFinite(e)}function sq(e,t,n,r){var i=1-e,a=r.dimensions[e];return oq(t[i])&&oq(n[i])&&t[e]===n[e]&&r.getAxis(a).containData(t[e])}function cq(e,t){if(e.type===`cartesian2d`){var n=t[0].coord,r=t[1].coord;if(n&&r&&(sq(1,n,r,e)||sq(0,n,r,e)))return!0}return XK(e,t[0])&&XK(e,t[1])}function lq(e,t,n,r,i){var a=r.coordinateSystem,o=e.getItemModel(t),s,c=Xs(o.get(`x`),i.getWidth()),l=Xs(o.get(`y`),i.getHeight());if(!isNaN(c)&&!isNaN(l))s=[c,l];else{if(r.getMarkerPosition)s=r.getMarkerPosition(e.getValues(e.dimensions,t));else{var u=a.dimensions,d=e.get(u[0],t),f=e.get(u[1],t);s=a.dataToPoint([d,f])}if(AL(a,`cartesian2d`)){var p=a.getAxis(`x`),m=a.getAxis(`y`),u=a.dimensions;oq(e.get(u[0],t))?s[0]=p.toGlobalCoord(p.getExtent()[+!n]):oq(e.get(u[1],t))&&(s[1]=m.toGlobalCoord(m.getExtent()[+!n]))}isNaN(c)||(s[0]=c),isNaN(l)||(s[1]=l)}e.setItemLayout(t,s)}var uq=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.updateTransform=function(e,t,n){t.eachSeries(function(e){var t=HK.getMarkerModelFromSeries(e,`markLine`);if(t){var r=t.getData(),i=iq(t).from,a=iq(t).to;i.each(function(t){lq(i,t,!0,e,n),lq(a,t,!1,e,n)}),r.each(function(e){r.setItemLayout(e,[i.getItemLayout(e),a.getItemLayout(e)])}),this.markerGroupMap.get(e.id).updateLayout()}},this)},t.prototype.renderSeries=function(e,t,n,r){var i=e.coordinateSystem,a=e.id,o=e.getData(),s=this.markerGroupMap,c=s.get(a)||s.set(a,new sB);this.group.add(c.group);var l=dq(i,e,t),u=l.from,d=l.to,f=l.line;iq(t).from=u,iq(t).to=d,t.setData(f);var p=t.get(`symbol`),m=t.get(`symbolSize`),h=t.get(`symbolRotate`),g=t.get(`symbolOffset`);J(p)||(p=[p,p]),J(m)||(m=[m,m]),J(h)||(h=[h,h]),J(g)||(g=[g,g]),l.from.each(function(e){_(u,e,!0),_(d,e,!1)}),f.each(function(e){var t=f.getItemModel(e),n=t.getModel(`lineStyle`).getLineStyle();f.setItemLayout(e,[u.getItemLayout(e),d.getItemLayout(e)]);var r=t.get(`z2`);n.stroke??=u.getItemVisual(e,`style`).fill,f.setItemVisual(e,{z2:X(r,0),fromSymbolKeepAspect:u.getItemVisual(e,`symbolKeepAspect`),fromSymbolOffset:u.getItemVisual(e,`symbolOffset`),fromSymbolRotate:u.getItemVisual(e,`symbolRotate`),fromSymbolSize:u.getItemVisual(e,`symbolSize`),fromSymbol:u.getItemVisual(e,`symbol`),toSymbolKeepAspect:d.getItemVisual(e,`symbolKeepAspect`),toSymbolOffset:d.getItemVisual(e,`symbolOffset`),toSymbolRotate:d.getItemVisual(e,`symbolRotate`),toSymbolSize:d.getItemVisual(e,`symbolSize`),toSymbol:d.getItemVisual(e,`symbol`),style:n})}),c.updateData(f),l.line.eachItemGraphicEl(function(e){jh(e).dataModel=t,e.traverse(function(e){jh(e).dataModel=t})});function _(t,n,i){var a=t.getItemModel(n);lq(t,n,i,e,r);var s=a.getModel(`itemStyle`).getItemStyle();s.fill??=HM(o,`color`),t.setItemVisual(n,{symbolKeepAspect:a.get(`symbolKeepAspect`),symbolOffset:X(a.get(`symbolOffset`,!0),g[+!i]),symbolRotate:X(a.get(`symbolRotate`,!0),h[+!i]),symbolSize:X(a.get(`symbolSize`),m[+!i]),symbol:X(a.get(`symbol`,!0),p[+!i]),style:s})}this.markKeep(c),c.group.silent=t.get(`silent`)||e.get(`silent`)},t.type=`markLine`,t}(tq);function dq(e,t,n){var r=e?K(e&&e.dimensions,function(e){var n=t.getData();return W(W({},n.getDimensionInfo(n.mapDimension(e))||{}),{name:e,ordinalMeta:null})}):[{name:`value`,type:`float`}],i=new $F(r,n),a=new $F(r,n),o=new $F([],n),s=K(n.get(`data`),ns(aq,t,e,n));e&&(s=Qo(s,ns(cq,e)));var c=QK(!!e,r);return i.initData(K(s,function(e){return e[0]}),null,c),a.initData(K(s,function(e){return e[1]}),null,c),o.initData(K(s,function(e){return e[2]})),o.hasItemOption=!0,{from:i,to:a,line:o}}function fq(e){e.registerComponentModel(rq),e.registerComponentView(uq),e.registerPreprocessor(function(e){zK(e.series,`markLine`)&&(e.markLine=e.markLine||{})})}var pq=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.createMarkerModelFromSeries=function(e,n,r){return new t(e,n,r)},t.type=`markArea`,t.defaultOption={z:1,tooltip:{trigger:`item`},animation:!1,label:{show:!0,position:`top`},itemStyle:{borderWidth:0},emphasis:{label:{show:!0,position:`top`}}},t}(HK),mq=Qc(),hq=function(e,t,n,r){var i=r[0],a=r[1];if(i&&a){var o=qK(e,i),s=qK(e,a),c=o.coord,l=s.coord;c[0]=ps(c[0],-1/0),c[1]=ps(c[1],-1/0),l[0]=ps(l[0],1/0),l[1]=ps(l[1],1/0);var u=Wo([{},o,s]);return u.coord=[o.coord,s.coord],u.x0=o.x,u.y0=o.y,u.x1=s.x,u.y1=s.y,u}};function gq(e){return!isNaN(e)&&!isFinite(e)}function _q(e,t,n,r){var i=1-e;return gq(t[i])&&gq(n[i])}function vq(e,t){var n=t.coord[0],r=t.coord[1],i={coord:n,x:t.x0,y:t.y0},a={coord:r,x:t.x1,y:t.y1};return AL(e,`cartesian2d`)?n&&r&&(_q(1,n,r,e)||_q(0,n,r,e))?!0:ZK(e,i,a):XK(e,i)||XK(e,a)}function yq(e,t,n,r,i){var a=r.coordinateSystem,o=e.getItemModel(t),s,c=Xs(o.get(n[0]),i.getWidth()),l=Xs(o.get(n[1]),i.getHeight());if(!isNaN(c)&&!isNaN(l))s=[c,l];else{if(r.getMarkerPosition){var u=e.getValues([`x0`,`y0`],t),d=e.getValues([`x1`,`y1`],t),f=a.clampData(u),p=a.clampData(d),m=[];m[0]=n[0]===`x0`?f[0]>p[0]?d[0]:u[0]:f[0]>p[0]?u[0]:d[0],m[1]=n[1]===`y0`?f[1]>p[1]?d[1]:u[1]:f[1]>p[1]?u[1]:d[1],s=r.getMarkerPosition(m,n,!0)}else{var h=e.get(n[0],t),g=e.get(n[1],t),_=[h,g];a.clampData&&a.clampData(_,_),s=a.dataToPoint(_,!0)}if(AL(a,`cartesian2d`)){var v=a.getAxis(`x`),y=a.getAxis(`y`),h=e.get(n[0],t),g=e.get(n[1],t);gq(h)?s[0]=v.toGlobalCoord(v.getExtent()[n[0]===`x0`?0:1]):gq(g)&&(s[1]=y.toGlobalCoord(y.getExtent()[n[1]===`y0`?0:1]))}isNaN(c)||(s[0]=c),isNaN(l)||(s[1]=l)}return s}var bq=[[`x0`,`y0`],[`x1`,`y0`],[`x1`,`y1`],[`x0`,`y1`]],xq=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.updateTransform=function(e,t,n){t.eachSeries(function(e){var t=HK.getMarkerModelFromSeries(e,`markArea`);if(t){var r=t.getData();r.each(function(t){var i=K(bq,function(i){return yq(r,t,i,e,n)});r.setItemLayout(t,i),r.getItemGraphicEl(t).setShape(`points`,i)})}},this)},t.prototype.renderSeries=function(e,t,n,r){var i=e.coordinateSystem,a=e.id,o=e.getData(),s=this.markerGroupMap,c=s.get(a)||s.set(a,{group:new y_});this.group.add(c.group),this.markKeep(c);var l=Sq(i,e,t);t.setData(l),l.each(function(t){var n=K(bq,function(n){return yq(l,t,n,e,r)}),a=i.getAxis(`x`).scale,s=i.getAxis(`y`).scale,c=a.getExtent(),u=s.getExtent(),d=[a.parse(l.get(`x0`,t)),a.parse(l.get(`x1`,t))],f=[s.parse(l.get(`y0`,t)),s.parse(l.get(`y1`,t))];tc(d),tc(f);var p=c[0]>d[1]||c[1]f[1]||u[1]=0},t.prototype.getOrient=function(){return this.get(`orient`)===`vertical`?{index:1,name:`vertical`}:{index:0,name:`horizontal`}},t.type=`legend.plain`,t.dependencies=[`series`],t.defaultOption={z:4,show:!0,orient:`horizontal`,left:`center`,bottom:Q.size.m,align:`auto`,backgroundColor:Q.color.transparent,borderColor:Q.color.border,borderRadius:0,borderWidth:0,padding:5,itemGap:8,itemWidth:25,itemHeight:14,symbolRotate:`inherit`,symbolKeepAspect:!0,inactiveColor:Q.color.disabled,inactiveBorderColor:Q.color.disabled,inactiveBorderWidth:`auto`,itemStyle:{color:`inherit`,opacity:`inherit`,borderColor:`inherit`,borderWidth:`auto`,borderCap:`inherit`,borderJoin:`inherit`,borderDashOffset:`inherit`,borderMiterLimit:`inherit`},lineStyle:{width:`auto`,color:`inherit`,inactiveColor:Q.color.disabled,inactiveWidth:2,opacity:`inherit`,type:`inherit`,cap:`inherit`,join:`inherit`,dashOffset:`inherit`,miterLimit:`inherit`},textStyle:{color:Q.color.secondary},selectedMode:!0,selector:!1,selectorLabel:{show:!0,borderRadius:10,padding:[3,5,3,5],fontSize:12,fontFamily:`sans-serif`,color:Q.color.tertiary,borderWidth:1,borderColor:Q.color.border},emphasis:{selectorLabel:{show:!0,color:Q.color.quaternary}},selectorPosition:`auto`,selectorItemGap:7,selectorButtonGap:10,tooltip:{show:!1},triggerEvent:!1},t}(Yx),Eq=ns,Dq=G,Oq=y_,kq=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n.newlineDisabled=!1,n}return t.prototype.init=function(){this.group.add(this._contentGroup=new Oq),this.group.add(this._selectorGroup=new Oq),this._isFirstRender=!0},t.prototype.getContentGroup=function(){return this._contentGroup},t.prototype.getSelectorGroup=function(){return this._selectorGroup},t.prototype.render=function(e,t,n){var r=this._isFirstRender;if(this._isFirstRender=!1,this.resetInner(),e.get(`show`,!0)){var i=e.get(`align`),a=e.get(`orient`);(!i||i===`auto`)&&(i=e.get(`left`)===`right`&&a===`vertical`?`right`:`left`);var o=e.get(`selector`,!0),s=e.get(`selectorPosition`,!0);o&&(!s||s===`auto`)&&(s=a===`horizontal`?`end`:`start`),this.renderInner(i,e,t,n,o,a,s);var c=Hx(e,n).refContainer,l=e.getBoxLayoutParams(),u=e.get(`padding`),d=Bx(l,c,u),f=this.layoutInner(e,i,d,r,o,s),p=Bx(Ko({width:f.width,height:f.height},l),c,u);this.group.x=p.x-f.x,this.group.y=p.y-f.y,this.group.markRedraw(),this.group.add(this._backgroundEl=MW(f,e))}},t.prototype.resetInner=function(){this.getContentGroup().removeAll(),this._backgroundEl&&this.group.remove(this._backgroundEl),this.getSelectorGroup().removeAll()},t.prototype.renderInner=function(e,t,n,r,i,a,o){var s=this.getContentGroup(),c=Es(),l=t.get(`selectedMode`),u=t.get(`triggerEvent`),d=[];n.eachRawSeries(function(e){!e.get(`legendHoverLink`)&&d.push(e.id)}),Dq(t.getData(),function(i,a){var o=this,f=i.get(`name`);if(!this.newlineDisabled&&(f===``||f===` `)){var p=new Oq;p.newline=!0,s.add(p);return}var m=n.getSeriesByName(f)[0];if(!c.get(f)){if(m){var h=m.getData(),g=h.getVisual(`legendLineStyle`)||{},_=h.getVisual(`legendIcon`),v=h.getVisual(`style`),y=this._createItem(m,f,a,i,t,e,g,v,_,l,r);y.on(`click`,Eq(Mq,f,null,r,d)).on(`mouseover`,Eq(Nq,m.name,null,r,d)).on(`mouseout`,Eq(Pq,m.name,null,r,d)),n.ssr&&y.eachChild(function(e){var t=jh(e);t.seriesIndex=m.seriesIndex,t.dataIndex=a,t.ssrType=`legend`}),u&&y.eachChild(function(e){o.packEventData(e,t,m,a,f)}),c.set(f,!0)}else n.eachRawSeries(function(o){var s=this;if(!c.get(f)&&o.legendVisualProvider){var p=o.legendVisualProvider;if(!p.containName(f))return;var m=p.indexOfName(f),h=p.getItemVisual(m,`style`),g=p.getItemVisual(m,`legendIcon`),_=Nf(h.fill);_&&_[3]===0&&(_[3]=.2,h=W(W({},h),{fill:Vf(_,`rgba`)}));var v=this._createItem(o,f,a,i,t,e,{},h,g,l,r);v.on(`click`,Eq(Mq,null,f,r,d)).on(`mouseover`,Eq(Nq,null,f,r,d)).on(`mouseout`,Eq(Pq,null,f,r,d)),n.ssr&&v.eachChild(function(e){var t=jh(e);t.seriesIndex=o.seriesIndex,t.dataIndex=a,t.ssrType=`legend`}),u&&v.eachChild(function(e){s.packEventData(e,t,o,a,f)}),c.set(f,!0)}},this)}},this),i&&this._createSelector(i,t,r,a,o)},t.prototype.packEventData=function(e,t,n,r,i){var a={componentType:`legend`,componentIndex:t.componentIndex,dataIndex:r,value:i,seriesIndex:n.seriesIndex};jh(e).eventData=a},t.prototype._createSelector=function(e,t,n,r,i){var a=this.getSelectorGroup();Dq(e,function(e){var r=e.type,i=new _h({style:{x:0,y:0,align:`center`,verticalAlign:`middle`},onclick:function(){n.dispatchAction({type:r===`all`?`legendAllSelect`:`legendInverseSelect`,legendId:t.id})}});a.add(i),Ey(i,{normal:t.getModel(`selectorLabel`),emphasis:t.getModel([`emphasis`,`selectorLabel`])},{defaultText:e.title}),Rg(i)})},t.prototype._createItem=function(e,t,n,r,i,a,o,s,c,l,u){var d=e.visualDrawType,f=i.get(`itemWidth`),p=i.get(`itemHeight`),m=i.isSelected(t),h=r.get(`symbolRotate`),g=r.get(`symbolKeepAspect`),_=r.get(`icon`);c=_||c||`roundRect`;var v=Aq(c,r,o,s,d,m,u),y=new Oq,b=r.getModel(`textStyle`);if(rs(e.getLegendIcon)&&(!_||_===`inherit`))y.add(e.getLegendIcon({itemWidth:f,itemHeight:p,icon:c,iconRotate:h,itemStyle:v.itemStyle,lineStyle:v.lineStyle,symbolKeepAspect:g}));else{var x=_===`inherit`&&e.getData().getVisual(`symbol`)?h===`inherit`?e.getData().getVisual(`symbolRotate`):h:0;y.add(jq({itemWidth:f,itemHeight:p,icon:c,iconRotate:x,itemStyle:v.itemStyle,lineStyle:v.lineStyle,symbolKeepAspect:g}))}var S=a===`left`?f+5:-5,C=a,w=i.get(`formatter`),T=t;Y(w)&&w?T=w.replace(`{name}`,t??``):rs(w)&&(T=w(t));var E=m?b.getTextColor():r.get(`inactiveColor`);y.add(new _h({style:Oy(b,{text:T,x:S,y:p/2,fill:E,align:C,verticalAlign:`middle`},{inheritColor:E})}));var D=new fh({shape:y.getBoundingRect(),style:{fill:`transparent`}}),O=r.getModel(`tooltip`);return O.get(`show`)&&cy({el:D,componentModel:i,itemName:t,itemTooltipOption:O.option}),y.add(D),y.eachChild(function(e){e.silent=!0}),D.silent=!l,this.getContentGroup().add(y),Rg(y),y.__legendDataIndex=n,y},t.prototype.layoutInner=function(e,t,n,r,i,a){var o=this.getContentGroup(),s=this.getSelectorGroup();Rx(e.get(`orient`),o,e.get(`itemGap`),n.width,n.height);var c=o.getBoundingRect(),l=[-c.x,-c.y];if(s.markRedraw(),o.markRedraw(),i){Rx(`horizontal`,s,e.get(`selectorItemGap`,!0));var u=s.getBoundingRect(),d=[-u.x,-u.y],f=e.get(`selectorButtonGap`,!0),p=e.getOrient().index,m=p===0?`width`:`height`,h=p===0?`height`:`width`,g=p===0?`y`:`x`;a===`end`?d[p]+=c[m]+f:l[p]+=u[m]+f,d[1-p]+=c[h]/2-u[h]/2,s.x=d[0],s.y=d[1],o.x=l[0],o.y=l[1];var _={x:0,y:0};return _[m]=c[m]+f+u[m],_[h]=Math.max(c[h],u[h]),_[g]=Math.min(0,u[g]+d[1-p]),_}return o.x=l[0],o.y=l[1],this.group.getBoundingRect()},t.prototype.remove=function(){this.getContentGroup().removeAll(),this._isFirstRender=!0},t.type=`legend.plain`,t}(Wj);function Aq(e,t,n,r,i,a,o){function s(e,t){e.lineWidth===`auto`&&(e.lineWidth=t.lineWidth>0?2:0),Dq(e,function(n,r){e[r]===`inherit`&&(e[r]=t[r])})}var c=t.getModel(`itemStyle`),l=c.getItemStyle(),u=e.lastIndexOf(`empty`,0)===0?`fill`:`stroke`,d=c.getShallow(`decal`);l.decal=!d||d===`inherit`?r.decal:UN(d,o),l.fill===`inherit`&&(l.fill=r[i]),l.stroke===`inherit`&&(l.stroke=r[u]),l.opacity===`inherit`&&(l.opacity=(i===`fill`?r:n).opacity),s(l,r);var f=t.getModel(`lineStyle`),p=f.getLineStyle();if(s(p,n),l.fill===`auto`&&(l.fill=r.fill),l.stroke===`auto`&&(l.stroke=r.fill),p.stroke===`auto`&&(p.stroke=r.fill),!a){var m=t.get(`inactiveBorderWidth`),h=l[u];l.lineWidth=m===`auto`?r.lineWidth>0&&h?2:0:l.lineWidth,l.fill=t.get(`inactiveColor`),l.stroke=t.get(`inactiveBorderColor`),p.stroke=f.get(`inactiveColor`),p.lineWidth=f.get(`inactiveWidth`)}return{itemStyle:l,lineStyle:p}}function jq(e){var t=e.icon||`roundRect`,n=QD(t,0,0,e.itemWidth,e.itemHeight,e.itemStyle.fill,e.symbolKeepAspect);return n.setStyle(e.itemStyle),n.rotation=(e.iconRotate||0)*Math.PI/180,n.setOrigin([e.itemWidth/2,e.itemHeight/2]),t.indexOf(`empty`)>-1&&(n.style.stroke=n.style.fill,n.style.fill=Q.color.neutral00,n.style.lineWidth=2),n}function Mq(e,t,n,r){Pq(e,t,n,r),n.dispatchAction({type:`legendToggleSelect`,name:e??t}),Nq(e,t,n,r)}function Nq(e,t,n,r){n.usingTHL()||n.dispatchAction({type:`highlight`,seriesName:e,name:t,excludeSeriesId:r})}function Pq(e,t,n,r){n.usingTHL()||n.dispatchAction({type:`downplay`,seriesName:e,name:t,excludeSeriesId:r})}function Fq(e,t,n){var r=e===`allSelect`||e===`inverseSelect`,i={},a=[];n.eachComponent({mainType:`legend`,query:t},function(n){r?n[e]():n[e](t.name),Iq(n,i),a.push(n.componentIndex)});var o={};return n.eachComponent(`legend`,function(e){G(i,function(t,n){e[t?`select`:`unSelect`](n)}),Iq(e,o)}),r?{selected:o,legendIndex:a}:{name:t.name,selected:o}}function Iq(e,t){var n=t||{};return G(e.getData(),function(t){var r=t.get(`name`);if(r!==` -`&&r!==``){var i=e.isSelected(r);n[r]=Z(n,r)?n[r]&&i:i}}),n}function Lq(e){e.registerAction(`legendToggleSelect`,`legendselectchanged`,ns(Fq,`toggleSelected`)),e.registerAction(`legendAllSelect`,`legendselectall`,ns(Fq,`allSelect`)),e.registerAction(`legendInverseSelect`,`legendinverseselect`,ns(Fq,`inverseSelect`)),e.registerAction(`legendSelect`,`legendselected`,ns(Fq,`select`)),e.registerAction(`legendUnSelect`,`legendunselected`,ns(Fq,`unSelect`))}var Rq=El(zq);function zq(e){var t=e.findComponents({mainType:`legend`});t&&t.length&&e.filterSeries(function(e){for(var n=0;nn[i],m=[-d.x,-d.y];t||(m[r]=c[s]);var h=[0,0],g=[-f.x,-f.y],_=X(e.get(`pageButtonGap`,!0),e.get(`itemGap`,!0));p&&(e.get(`pageButtonPosition`,!0)===`end`?g[r]+=n[i]-f[i]:h[r]+=f[i]+_),g[1-r]+=d[a]/2-f[a]/2,c.setPosition(m),l.setPosition(h),u.setPosition(g);var v={x:0,y:0};if(v[i]=p?n[i]:d[i],v[a]=Math.max(d[a],f[a]),v[o]=Math.min(0,f[o]+g[1-r]),l.__rectSize=n[i],p){var y={x:0,y:0};y[i]=Math.max(n[i]-f[i]-_,0),y[a]=v[a],l.setClipPath(new fh({shape:y})),l.__rectSize=y[i]}else u.eachChild(function(e){e.attr({invisible:!0,silent:!0})});var b=this._getPageInfo(e);return b.pageIndex!=null&&Sv(c,{x:b.contentPosition[0],y:b.contentPosition[1]},p?e:null),this._updatePageInfoView(e,b),v},t.prototype._pageGo=function(e,t,n){var r=this._getPageInfo(t)[e];r!=null&&n.dispatchAction({type:`legendScroll`,scrollDataIndex:r,legendId:t.id})},t.prototype._updatePageInfoView=function(e,t){var n=this._controllerGroup;G([`pagePrev`,`pageNext`],function(r){var i=t[r+`DataIndex`]!=null,a=n.childOfName(r);a&&(a.setStyle(`fill`,i?e.get(`pageIconColor`,!0):e.get(`pageIconInactiveColor`,!0)),a.cursor=i?`pointer`:`default`)});var r=n.childOfName(`pageText`),i=e.get(`pageFormatter`),a=t.pageIndex,o=a==null?0:a+1,s=t.pageCount;r&&i&&r.setStyle(`text`,Y(i)?i.replace(`{current}`,o==null?``:o+``).replace(`{total}`,s==null?``:s+``):i({current:o,total:s}))},t.prototype._getPageInfo=function(e){var t=e.get(`scrollDataIndex`,!0),n=this.getContentGroup(),r=this._containerGroup.__rectSize,i=e.getOrient().index,a=Wq[i],o=Gq[i],s=this._findTargetItemIndex(t),c=n.children(),l=c[s],u=c.length,d=+!!u,f={contentPosition:[n.x,n.y],pageCount:d,pageIndex:d-1,pagePrevDataIndex:null,pageNextDataIndex:null};if(!l)return f;var p=v(l);f.contentPosition[i]=-p.s;for(var m=s+1,h=p,g=p,_=null;m<=u;++m)_=v(c[m]),(!_&&g.e>h.s+r||_&&!y(_,h.s))&&(h=g.i>h.i?g:_,h&&(f.pageNextDataIndex??=h.i,++f.pageCount)),g=_;for(var m=s-1,h=p,g=p,_=null;m>=-1;--m)_=v(c[m]),(!_||!y(g,_.s))&&h.i=t&&e.s<=t+r}},t.prototype._findTargetItemIndex=function(e){if(!this._showController)return 0;var t,n=this.getContentGroup(),r;return n.eachChild(function(n,i){var a=n.__legendDataIndex;r==null&&a!=null&&(r=i),a===e&&(t=i)}),t??r},t.type=`legend.scroll`,t}(kq);function qq(e){e.registerAction(`legendScroll`,`legendscroll`,function(e,t){var n=e.scrollDataIndex;n!=null&&t.eachComponent({mainType:`legend`,subType:`scroll`,query:e},function(e){e.setScrollDataIndex(n)})})}function Jq(e){MF(Bq),e.registerComponentModel(Vq),e.registerComponentView(Kq),qq(e)}function Yq(e){MF(Bq),MF(Jq)}var Xq=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.type=`dataZoom.inside`,t.defaultOption=nb(gW.defaultOption,{disabled:!1,zoomLock:!1,zoomOnMouseWheel:!0,moveOnMouseMove:!0,moveOnMouseWheel:!1,preventDefaultMouseMove:!0}),t}(gW),Zq=Qc();function Qq(e,t,n){Zq(e).coordSysRecordMap.each(function(e){var r=e.dataZoomInfoMap.get(t.uid);r&&(r.getRange=n)})}function $q(e,t){for(var n=Zq(e).coordSysRecordMap,r=n.keys(),i=0;ia[i+r]&&(r=n),o&&=t.get(`preventDefaultMouseMove`,!0),s=X(t.get(`cursorGrab`,!0),s),c=X(t.get(`cursorGrabbing`,!0),c)}),{controlType:r,opt:{zoomOnMouseWheel:!0,moveOnMouseMove:!0,moveOnMouseWheel:!0,preventDefaultMouseMove:!!o,api:n,zInfo:{component:t.model},triggerInfo:{roamTrigger:null,isInSelf:t.containsPoint},cursorGrab:s,cursorGrabbing:c}}}function aJ(e){e.registerUpdateLifecycle(`coordsys:aftercreate`,function(e,t){var n=Zq(t),r=n.coordSysRecordMap||=Es();r.each(function(e){e.dataZoomInfoMap=null}),e.eachComponent({mainType:`dataZoom`,subType:`inside`},function(e){G(uW(e).infoList,function(n){var i=n.model.uid,a=r.get(i)||r.set(i,tJ(t,n.model));(a.dataZoomInfoMap||=Es()).set(e.uid,{dzReferCoordSysInfo:n,model:e,getRange:null})})}),r.each(function(e){var n=e.controller,i,a=e.dataZoomInfoMap;if(a){var o=a.keys()[0];o!=null&&(i=a.get(o))}if(!i){eJ(r,e);return}var s=iJ(a,e,t);n.enable(s.controlType,s.opt),iM(e,`dispatchAction`,i.model.get(`throttle`,!0),`fixRate`)})})}var oJ=function(e){U(t,e);function t(){var t=e!==null&&e.apply(this,arguments)||this;return t.type=`dataZoom.inside`,t}return t.prototype.render=function(t,n,r){if(e.prototype.render.apply(this,arguments),t.noTarget()){this._clear();return}this.range=t.getPercentRange(),Qq(r,t,{pan:q(sJ.pan,this),zoom:q(sJ.zoom,this),scrollMove:q(sJ.scrollMove,this)})},t.prototype.dispose=function(){this._clear(),e.prototype.dispose.apply(this,arguments)},t.prototype._clear=function(){$q(this.api,this.dataZoomModel),this.range=null},t.type=`dataZoom.inside`,t}(yW),sJ={zoom:function(e,t,n,r){var i=this.range,a=i.slice(),o=e.axisModels[0];if(o){var s=lJ[t](null,[r.originX,r.originY],o,n,e),c=(s.signal>0?s.pixelStart+s.pixelLength-s.pixel:s.pixel-s.pixelStart)/s.pixelLength*(a[1]-a[0])+a[0],l=Math.max(1/r.scale,0);a[0]=(a[0]-c)*l+c,a[1]=(a[1]-c)*l+c;var u=this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();if(fB(0,a,[0,100],0,u.minSpan,u.maxSpan),this.range=a,i[0]!==a[0]||i[1]!==a[1])return a}},pan:cJ(function(e,t,n,r,i,a){var o=lJ[r]([a.oldX,a.oldY],[a.newX,a.newY],t,i,n);return o.signal*(e[1]-e[0])*o.pixel/o.pixelLength}),scrollMove:cJ(function(e,t,n,r,i,a){return lJ[r]([0,0],[a.scrollDelta,a.scrollDelta],t,i,n).signal*(e[1]-e[0])*a.scrollDelta})};function cJ(e){return function(t,n,r,i){var a=this.range,o=a.slice(),s=t.axisModels[0];if(s&&(fB(e(o,s,t,n,r,i),o,[0,100],`all`),this.range=o,a[0]!==o[0]||a[1]!==o[1]))return o}}var lJ={grid:function(e,t,n,r,i){var a=n.axis,o={},s=i.model.coordinateSystem.getRect();return e||=[0,0],a.dim===`x`?(o.pixel=t[0]-e[0],o.pixelLength=s.width,o.pixelStart=s.x,o.signal=a.inverse?1:-1):(o.pixel=t[1]-e[1],o.pixelLength=s.height,o.pixelStart=s.y,o.signal=a.inverse?-1:1),o},polar:function(e,t,n,r,i){var a=n.axis,o={},s=i.model.coordinateSystem,c=s.getRadiusAxis().getExtent(),l=s.getAngleAxis().getExtent();return e=e?s.pointToCoord(e):[0,0],t=s.pointToCoord(t),n.mainType===`radiusAxis`?(o.pixel=t[0]-e[0],o.pixelLength=c[1]-c[0],o.pixelStart=c[0],o.signal=a.inverse?1:-1):(o.pixel=t[1]-e[1],o.pixelLength=l[1]-l[0],o.pixelStart=l[0],o.signal=a.inverse?-1:1),o},singleAxis:function(e,t,n,r,i){var a=n.axis,o=i.model.coordinateSystem.getRect(),s={};return e||=[0,0],a.orient===`horizontal`?(s.pixel=t[0]-e[0],s.pixelLength=o.width,s.pixelStart=o.x,s.signal=a.inverse?1:-1):(s.pixel=t[1]-e[1],s.pixelLength=o.height,s.pixelStart=o.y,s.signal=a.inverse?-1:1),s}};function uJ(e){TW(e),e.registerComponentModel(Xq),e.registerComponentView(oJ),aJ(e)}var dJ=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.type=`dataZoom.slider`,t.layoutMode=`box`,t.defaultOption=nb(gW.defaultOption,{show:!0,right:`ph`,top:`ph`,width:`ph`,height:`ph`,left:null,bottom:null,borderColor:Q.color.accent10,borderRadius:0,backgroundColor:Q.color.transparent,dataBackground:{lineStyle:{color:Q.color.accent30,width:.5},areaStyle:{color:Q.color.accent20,opacity:.2}},selectedDataBackground:{lineStyle:{color:Q.color.accent40,width:.5},areaStyle:{color:Q.color.accent20,opacity:.3}},fillerColor:`rgba(135,175,274,0.2)`,handleIcon:`path://M-9.35,34.56V42m0-40V9.5m-2,0h4a2,2,0,0,1,2,2v21a2,2,0,0,1-2,2h-4a2,2,0,0,1-2-2v-21A2,2,0,0,1-11.35,9.5Z`,handleSize:`100%`,handleStyle:{color:Q.color.neutral00,borderColor:Q.color.accent20},moveHandleSize:7,moveHandleIcon:`path://M-320.9-50L-320.9-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-348-41-339-50-320.9-50z M-212.3-50L-212.3-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-239.4-41-230.4-50-212.3-50z M-103.7-50L-103.7-50c18.1,0,27.1,9,27.1,27.1V85.7c0,18.1-9,27.1-27.1,27.1l0,0c-18.1,0-27.1-9-27.1-27.1V-22.9C-130.9-41-121.8-50-103.7-50z`,moveHandleStyle:{color:Q.color.accent40,opacity:.5},showDetail:!0,showDataShadow:`auto`,realtime:!0,zoomLock:!1,textStyle:{color:Q.color.tertiary},brushSelect:!0,brushStyle:{color:Q.color.accent30,opacity:.3},emphasis:{handleLabel:{show:!0},handleStyle:{borderColor:Q.color.accent40},moveHandleStyle:{opacity:.8}},defaultLocationEdgeGap:15}),t}(gW),fJ=fh,pJ=1,mJ=30,hJ=7,gJ=`horizontal`,_J=`vertical`,vJ=5,yJ=[`line`,`bar`,`candlestick`,`scatter`],bJ={easing:`cubicOut`,duration:100,delay:0},xJ=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n._displayables={},n}return t.prototype.init=function(e,t){this.api=t,this._onBrush=q(this._onBrush,this),this._onBrushEnd=q(this._onBrushEnd,this)},t.prototype.render=function(t,n,r,i){if(e.prototype.render.apply(this,arguments),iM(this,`_dispatchZoomAction`,t.get(`throttle`),`fixRate`),this._orient=t.getOrient(),t.get(`show`)===!1){this.group.removeAll();return}if(t.noTarget()){this._clear(),this.group.removeAll();return}(!i||i.type!==`dataZoom`||i.from!==this.uid)&&this._buildView(),this._updateView()},t.prototype.dispose=function(){this._clear(),e.prototype.dispose.apply(this,arguments)},t.prototype._clear=function(){aM(this,`_dispatchZoomAction`);var e=this.api.getZr();e.off(`mousemove`,this._onBrush),e.off(`mouseup`,this._onBrushEnd)},t.prototype._buildView=function(){var e=this.group;e.removeAll(),this._brushing=!1,this._displayables.brushRect=null,this._resetLocation(),this._resetInterval();var t=this._displayables.sliderGroup=new y_;this._renderBackground(),this._renderHandle(),this._renderDataShadow(),e.add(t),this._positionGroup()},t.prototype._resetLocation=function(){var e=this.dataZoomModel,t=this.api,n=e.get(`brushSelect`)?hJ:0,r=Hx(e,t).refContainer,i=this._findCoordRect(),a=e.get(`defaultLocationEdgeGap`,!0)||0,o=this._orient===gJ?{right:r.width-i.x-i.width,top:r.height-mJ-a-n,width:i.width,height:mJ}:{right:a,top:i.y,width:mJ,height:i.height},s=Kx(e.option);G([`right`,`top`,`width`,`height`],function(e){s[e]===`ph`&&(s[e]=o[e])});var c=Bx(s,r);this._location={x:c.x,y:c.y},this._size=[c.width,c.height],this._orient===_J&&this._size.reverse()},t.prototype._positionGroup=function(){var e=this.group,t=this._location,n=this._orient,r=this.dataZoomModel.getFirstTargetAxisModel(),i=r&&r.get(`inverse`),a=this._displayables.sliderGroup,o=(this._dataShadowInfo||{}).otherAxisInverse;a.attr(n===gJ&&!i?{scaleY:o?1:-1,scaleX:1}:n===gJ&&i?{scaleY:o?1:-1,scaleX:-1}:n===_J&&!i?{scaleY:o?-1:1,scaleX:1,rotation:Math.PI/2}:{scaleY:o?-1:1,scaleX:-1,rotation:Math.PI/2});var s=e.getBoundingRect([a]),c=isNaN(s.x)?0:s.x,l=isNaN(s.y)?0:s.y;e.x=t.x-c,e.y=t.y-l,e.markRedraw()},t.prototype._getViewExtent=function(){return[0,this._size[0]]},t.prototype._renderBackground=function(){var e=this.dataZoomModel,t=this._size,n=this._displayables.sliderGroup,r=e.get(`brushSelect`);n.add(new fJ({silent:!0,shape:{x:0,y:0,width:t[0],height:t[1]},style:{fill:e.get(`backgroundColor`)},z2:-40}));var i=new fJ({shape:{x:0,y:0,width:t[0],height:t[1]},style:{fill:`transparent`},z2:0,onclick:q(this._onClickPanel,this)}),a=this.api.getZr();r?(i.on(`mousedown`,this._onBrushStart,this),i.cursor=`crosshair`,a.on(`mousemove`,this._onBrush),a.on(`mouseup`,this._onBrushEnd)):(a.off(`mousemove`,this._onBrush),a.off(`mouseup`,this._onBrushEnd)),n.add(i)},t.prototype._renderDataShadow=function(){var e=this._dataShadowInfo=this._prepareDataShadowInfo();if(this._displayables.dataShadowSegs=[],!e)return;var t=this._size,n=this._shadowSize||[],r=e.series,i=r.getRawData(),a=r.getShadowDim&&r.getShadowDim(),o=a&&i.getDimensionInfo(a)?r.getShadowDim():e.otherDim;if(o==null)return;var s=this._shadowPolygonPts,c=this._shadowPolylinePts;if(i!==this._shadowData||o!==this._shadowDim||t[0]!==n[0]||t[1]!==n[1]){var l=i.getDataExtent(e.thisDim),u=i.getDataExtent(o),d=(u[1]-u[0])*.3;u=[u[0]-d,u[1]+d];var f=[0,t[1]],p=[0,t[0]],m=[[t[0],0],[0,0]],h=[],g=p[1]/Math.max(1,i.count()-1),_=t[0]/(l[1]-l[0]),v=e.thisAxis.type===`time`,y=-g,b=Math.round(i.count()/t[0]),x;i.each([e.thisDim,o],function(e,t,n){if(b>0&&n%b){v||(y+=g);return}y=v?(+e-l[0])*_:y+g;var r=t==null||isNaN(t)||t===``,i=r?0:Ys(t,u,f,!0);r&&!x&&n?(m.push([m[m.length-1][0],0]),h.push([h[h.length-1][0],0])):!r&&x&&(m.push([y,0]),h.push([y,0])),r||(m.push([y,i]),h.push([y,i])),x=r}),s=this._shadowPolygonPts=m,c=this._shadowPolylinePts=h}this._shadowData=i,this._shadowDim=o,this._shadowSize=[t[0],t[1]];var S=this.dataZoomModel;function C(e){var t=S.getModel(e?`selectedDataBackground`:`dataBackground`),n=new y_,r=new K_({shape:{points:s},segmentIgnoreThreshold:1,style:t.getModel(`areaStyle`).getAreaStyle(),silent:!0,z2:-20}),i=new J_({shape:{points:c},segmentIgnoreThreshold:1,style:t.getModel(`lineStyle`).getLineStyle(),silent:!0,z2:-19});return n.add(r),n.add(i),n}for(var w=0;w<3;w++){var T=C(w===1);this._displayables.sliderGroup.add(T),this._displayables.dataShadowSegs.push(T)}},t.prototype._prepareDataShadowInfo=function(){var e=this.dataZoomModel,t=e.get(`showDataShadow`);if(t!==!1){var n,r=this.ecModel;return e.eachTargetAxis(function(i,a){G(e.getAxisProxy(i,a).getTargetSeriesModels(),function(e){if(!n&&!(t!==!0&&qo(yJ,e.get(`type`))<0)){var o=r.getComponent(cW(i),a).axis,s=CJ(i),c,l=e.coordinateSystem;s!=null&&l.getOtherAxis&&(c=l.getOtherAxis(o).inverse),s=e.getData().mapDimension(s),n={thisAxis:o,series:e,thisDim:e.getData().mapDimension(i),otherDim:s,otherAxisInverse:c}}},this)},this),n}},t.prototype._renderHandle=function(){var e=this.group,t=this._displayables,n=t.handles=[null,null],r=t.handleLabels=[null,null],i=this._displayables.sliderGroup,a=this._size,o=this.dataZoomModel,s=this.api,c=o.get(`borderRadius`)||0,l=o.get(`brushSelect`),u=t.filler=new fJ({silent:l,style:{fill:o.get(`fillerColor`)},textConfig:{position:`inside`}});i.add(u),i.add(new fJ({silent:!0,subPixelOptimize:!0,shape:{x:0,y:0,width:a[0],height:a[1],r:c},style:{stroke:o.get(`dataBackgroundColor`)||o.get(`borderColor`),lineWidth:pJ,fill:Q.color.transparent}})),G([0,1],function(t){var a=o.get(`handleIcon`);!YD[a]&&a.indexOf(`path://`)<0&&a.indexOf(`image://`)<0&&(a=`path://`+a);var s=QD(a,-1,0,2,2,null,!0);s.attr({cursor:wJ(this._orient),draggable:!0,drift:q(this._onDragMove,this,t),ondragend:q(this._onDragEnd,this),onmouseover:q(this._onOverDataInfoTriggerArea,this,!0),onmouseout:q(this._onOverDataInfoTriggerArea,this,!1),z2:5});var c=s.getBoundingRect(),l=o.get(`handleSize`);this._handleHeight=Xs(l,this._size[1]),this._handleWidth=c.width/c.height*this._handleHeight,s.setStyle(o.getModel(`handleStyle`).getItemStyle()),s.style.strokeNoScale=!0,s.rectHover=!0,s.ensureState(`emphasis`).style=o.getModel([`emphasis`,`handleStyle`]).getItemStyle(),Rg(s);var u=o.get(`handleColor`);u!=null&&(s.style.fill=u),i.add(n[t]=s);var d=o.getModel(`textStyle`),f=(o.get(`handleLabel`)||{}).show||!1;e.add(r[t]=new _h({silent:!0,invisible:!f,style:Oy(d,{x:0,y:0,text:``,verticalAlign:`middle`,align:`center`,fill:d.getTextColor(),font:d.getFont()}),z2:10}))},this);var d=u;if(l){var f=Xs(o.get(`moveHandleSize`),a[1]),p=t.moveHandle=new fh({style:o.getModel(`moveHandleStyle`).getItemStyle(),silent:!0,shape:{r:[0,0,2,2],y:a[1]-.5,height:f}}),m=f*.8,h=t.moveHandleIcon=QD(o.get(`moveHandleIcon`),-m/2,-m/2,m,m,Q.color.neutral00,!0);h.silent=!0,h.y=a[1]+f/2-.5,p.ensureState(`emphasis`).style=o.getModel([`emphasis`,`moveHandleStyle`]).getItemStyle();var g=Math.min(a[1]/2,Math.max(f,10));d=t.moveZone=new fh({invisible:!0,shape:{y:a[1]-g,height:f+g}}),d.on(`mouseover`,function(){s.enterEmphasis(p)}).on(`mouseout`,function(){s.leaveEmphasis(p)}),i.add(p),i.add(h),i.add(d)}d.attr({draggable:!0,cursor:`grab`,drift:q(this._onActualMoveZoneDrift,this),ondragstart:q(this._onActualMoveZoneDragStart,this),ondragend:q(this._onActualMoveZoneDragEnd,this),onmouseover:q(this._onOverDataInfoTriggerArea,this,!0),onmouseout:q(this._onOverDataInfoTriggerArea,this,!1)})},t.prototype._resetInterval=function(){var e=this._range=this.dataZoomModel.getPercentRange(),t=this._getViewExtent();this._handleEnds=[Ys(e[0],[0,100],t,!0),Ys(e[1],[0,100],t,!0)]},t.prototype._updateInterval=function(e,t){var n=this.dataZoomModel,r=this._handleEnds,i=this._getViewExtent(),a=n.findRepresentativeAxisProxy().getMinMaxSpan(),o=[0,100];fB(t,r,i,n.get(`zoomLock`)?`all`:e,a.minSpan==null?null:Ys(a.minSpan,o,i,!0),a.maxSpan==null?null:Ys(a.maxSpan,o,i,!0));var s=this._range,c=this._range=tc([Ys(r[0],i,o,!0),Ys(r[1],i,o,!0)]);return!s||s[0]!==c[0]||s[1]!==c[1]},t.prototype._updateView=function(e){var t=this._displayables,n=this._handleEnds,r=tc(n.slice()),i=this._size;G([0,1],function(e){var r=t.handles[e],a=this._handleHeight;r.attr({scaleX:a/2,scaleY:a/2,x:n[e]+(e?-1:1),y:i[1]/2-a/2})},this),t.filler.setShape({x:r[0],y:0,width:r[1]-r[0],height:i[1]});var a={x:r[0],width:r[1]-r[0]};t.moveHandle&&(t.moveHandle.setShape(a),t.moveZone.setShape(a),t.moveZone.getBoundingRect(),t.moveHandleIcon&&t.moveHandleIcon.attr(`x`,a.x+a.width/2));for(var o=t.dataShadowSegs,s=[0,r[0],r[1],i[0]],c=0;ct[0]||n[1]<0||n[1]>t[1])){var r=this._handleEnds,i=(r[0]+r[1])/2,a=this._updateInterval(`all`,n[0]-i);this._updateView(),a&&this._dispatchZoomAction(!1)}},t.prototype._onBrushStart=function(e){var t=e.offsetX,n=e.offsetY;this._brushStart=new wu(t,n),this._brushing=!0,this._brushStartTime=+new Date},t.prototype._onBrushEnd=function(e){if(this._brushing){var t=this._displayables.brushRect;if(this._brushing=!1,t){t.attr(`ignore`,!0);var n=t.shape;if(!(+new Date-this._brushStartTime<200&&Math.abs(n.width)<5)){var r=this._getViewExtent(),i=[0,100],a=this._handleEnds=[n.x,n.x+n.width],o=this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();fB(0,a,r,0,o.minSpan==null?null:Ys(o.minSpan,i,r,!0),o.maxSpan==null?null:Ys(o.maxSpan,i,r,!0)),this._range=tc([Ys(a[0],r,i,!0),Ys(a[1],r,i,!0)]),this._updateView(),this._dispatchZoomAction(!1)}}}},t.prototype._onBrush=function(e){this._brushing&&(Bk(e.event),this._updateBrushRect(e.offsetX,e.offsetY))},t.prototype._updateBrushRect=function(e,t){var n=this._displayables,r=this.dataZoomModel,i=n.brushRect;i||(i=n.brushRect=new fJ({silent:!0,style:r.getModel(`brushStyle`).getItemStyle()}),n.sliderGroup.add(i)),i.attr(`ignore`,!1);var a=this._brushStart,o=this._displayables.sliderGroup,s=o.transformCoordToLocal(e,t),c=o.transformCoordToLocal(a.x,a.y),l=this._size;s[0]=Math.max(Math.min(l[0],s[0]),0),i.setShape({x:c[0],y:0,width:s[0]-c[0],height:l[1]})},t.prototype._dispatchZoomAction=function(e){var t=this._range;this.api.dispatchAction({type:`dataZoom`,from:this.uid,dataZoomId:this.dataZoomModel.id,animation:e?bJ:null,start:t[0],end:t[1]})},t.prototype._findCoordRect=function(){var e,t=uW(this.dataZoomModel).infoList;if(!e&&t.length){var n=t[0].model.coordinateSystem;e=n.getRect&&n.getRect()}if(!e){var r=this.api.getWidth(),i=this.api.getHeight();e={x:r*.2,y:i*.2,width:r*.6,height:i*.6}}return e},t.type=`dataZoom.slider`,t}(yW);function SJ(e,t,n,r){var i=e.get(`labelFormatter`),a=e.get(`labelPrecision`);(a==null||a===`auto`)&&(a=n.valuePrecision);var o=n.value[t],s=o==null||isNaN(o)?``:OT(r)||ET(r)?r.getLabel({value:Math.round(o)}):isFinite(a)?ec(o,a,!0):o+``;return rs(i)?i(o,s):Y(i)?i.replace(`{value}`,s):s}function CJ(e){return{x:`y`,y:`x`,radius:`angle`,angle:`radius`}[e]}function wJ(e){return e===`vertical`?`ns-resize`:`ew-resize`}function TJ(e){e.registerComponentModel(dJ),e.registerComponentView(xJ),TW(e)}function EJ(e){MF(uJ),MF(TJ)}var DJ={get:function(e,t,n){var r=Ho((OJ[e]||{})[t]);return n&&J(r)?r[r.length-1]:r}},OJ={color:{active:[`#006edd`,`#e0ffff`],inactive:[Q.color.transparent]},colorHue:{active:[0,360],inactive:[0,0]},colorSaturation:{active:[.3,1],inactive:[0,0]},colorLightness:{active:[.9,.5],inactive:[0,0]},colorAlpha:{active:[.3,1],inactive:[0,0]},opacity:{active:[.3,1],inactive:[0,0]},symbol:{active:[`circle`,`roundRect`,`diamond`],inactive:[`none`]},symbolSize:{active:[10,50],inactive:[0,0]}},kJ=Fz.mapVisual,AJ=Fz.eachVisual,jJ=J,MJ=G,NJ=tc,PJ=Ys,FJ=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n.stateList=[`inRange`,`outOfRange`],n.replacableOptionKeys=[`inRange`,`outOfRange`,`target`,`controller`,`color`],n.layoutMode={type:`box`,ignoreSize:!0},n.dataBound=[-1/0,1/0],n.targetVisuals={},n.controllerVisuals={},n}return t.prototype.init=function(e,t,n){this.mergeDefaultAndTheme(e,n)},t.prototype.optionUpdated=function(e,t){var n=this.option;!t&&mK(n,e,this.replacableOptionKeys),this.textStyleModel=this.getModel(`textStyle`),this.resetItemSize(),this.completeVisualOption()},t.prototype.resetVisual=function(e){var t=this.stateList;e=q(e,this),this.controllerVisuals=pK(this.option.controller,t,e),this.targetVisuals=pK(this.option.target,t,e)},t.prototype.getItemSymbol=function(){return null},t.prototype.getTargetSeriesIndices=function(){var e=this,t=this.option.seriesTargets;if(t){var n=[];return MJ(t,function(t){if(t.seriesIndex!=null)n.push(t.seriesIndex);else if(t.seriesId!=null){var r;e.ecModel.eachSeries(function(e){e.id===t.seriesId&&(r=e)}),r&&n.push(r.componentIndex)}}),n}var r=this.option.seriesId,i=this.option.seriesIndex;i==null&&r==null&&(i=`all`);var a=il(this.ecModel,`series`,{index:i,id:r},{useDefault:!1,enableAll:!0,enableNone:!1}).models;return K(a,function(e){return e.componentIndex})},t.prototype.eachTargetSeries=function(e,t){G(this.getTargetSeriesIndices(),function(n){var r=this.ecModel.getSeriesByIndex(n);r&&e.call(t,r)},this)},t.prototype.isTargetSeries=function(e){var t=!1;return this.eachTargetSeries(function(n){n===e&&(t=!0)}),t},t.prototype.formatValueText=function(e,t,n){var r=this.option,i=r.precision,a=this.dataBound,o=r.formatter,s;n||=[`<`,`>`],J(e)&&(e=e.slice(),s=!0);var c=t?e:s?[l(e[0]),l(e[1])]:l(e);return Y(o)?o.replace(`{value}`,s?c[0]:c).replace(`{value2}`,s?c[1]:c):rs(o)?s?o(e[0],e[1]):o(e):s?e[0]===a[0]?n[0]+` `+c[1]:e[1]===a[1]?n[1]+` `+c[0]:c[0]+` - `+c[1]:c;function l(e){return e===a[0]?`min`:e===a[1]?`max`:(+e).toFixed(Math.min(i,20))}},t.prototype.resetExtent=function(){var e=this.option,t=NJ([e.min,e.max]);this._dataExtent=t},t.prototype.getDimension=function(e){var t=this,n=this.option.seriesTargets;if(n){var r=$o(n,function(n){return n.seriesIndex!=null&&n.seriesIndex===e||n.seriesId!=null&&n.seriesId===t.ecModel.getSeriesByIndex(e).id});if(r)return r.dimension}return this.option.dimension},t.prototype.getDataDimensionIndex=function(e){var t=e.hostModel.seriesIndex,n=this.getDimension(t);if(n!=null)return e.getDimensionIndex(n);for(var r=e.dimensions,i=r.length-1;i>=0;i--){var a=r[i],o=e.getDimensionInfo(a);if(!o.isCalculationCoord)return o.storeDimIndex}},t.prototype.getExtent=function(){return this._dataExtent.slice()},t.prototype.completeVisualOption=function(){var e=this.ecModel,t=this.option,n={inRange:t.inRange,outOfRange:t.outOfRange},r=t.target||={},i=t.controller||={};Uo(r,n),Uo(i,n);var a=this.isCategory();o.call(this,r),o.call(this,i),s.call(this,r,`inRange`,`outOfRange`),c.call(this,i);function o(n){jJ(t.color)&&!n.inRange&&(n.inRange={color:t.color.slice().reverse()}),n.inRange=n.inRange||{color:e.get(`gradientColor`)}}function s(e,t,n){var r=e[t],i=e[n];r&&!i&&(i=e[n]={},MJ(r,function(e,t){if(Fz.isValidType(t)){var n=DJ.get(t,`inactive`,a);n!=null&&(i[t]=n,t===`color`&&!i.hasOwnProperty(`opacity`)&&!i.hasOwnProperty(`colorAlpha`)&&(i.opacity=[0,0]))}}))}function c(e){var t=(e.inRange||{}).symbol||(e.outOfRange||{}).symbol,n=(e.inRange||{}).symbolSize||(e.outOfRange||{}).symbolSize,r=this.get(`inactiveColor`),i=this.getItemSymbol()||`roundRect`;MJ(this.stateList,function(o){var s=this.itemSize,c=e[o];c||=e[o]={color:a?r:[r]},c.symbol??(c.symbol=t&&Ho(t)||(a?i:[i])),c.symbolSize??(c.symbolSize=n&&Ho(n)||(a?s[0]:[s[0],s[0]])),c.symbol=kJ(c.symbol,function(e){return e===`none`?i:e});var l=c.symbolSize;if(l!=null){var u=-1/0;AJ(l,function(e){e>u&&(u=e)}),c.symbolSize=kJ(l,function(e){return PJ(e,[0,u],[0,s[0]],!0)})}},this)}},t.prototype.resetItemSize=function(){this.itemSize=[parseFloat(this.get(`itemWidth`)),parseFloat(this.get(`itemHeight`))]},t.prototype.isCategory=function(){return!!this.option.categories},t.prototype.setSelected=function(e){},t.prototype.getSelected=function(){return null},t.prototype.getValueState=function(e){return null},t.prototype.getVisualMeta=function(e){return null},t.type=`visualMap`,t.dependencies=[`series`],t.defaultOption={show:!0,z:4,min:0,max:200,left:0,right:null,top:null,bottom:0,itemWidth:null,itemHeight:null,inverse:!1,orient:`vertical`,backgroundColor:Q.color.transparent,borderColor:Q.color.borderTint,contentColor:Q.color.theme[0],inactiveColor:Q.color.disabled,borderWidth:0,padding:Q.size.m,textGap:10,precision:0,textStyle:{color:Q.color.secondary}},t}(Yx),IJ=[20,140],LJ=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.optionUpdated=function(t,n){e.prototype.optionUpdated.apply(this,arguments),this.resetExtent(),this.resetVisual(function(e){e.mappingMethod=`linear`,e.dataExtent=this.getExtent()}),this._resetRange()},t.prototype.resetItemSize=function(){e.prototype.resetItemSize.apply(this,arguments);var t=this.itemSize;(t[0]==null||isNaN(t[0]))&&(t[0]=IJ[0]),(t[1]==null||isNaN(t[1]))&&(t[1]=IJ[1])},t.prototype._resetRange=function(){var e=this.getExtent(),t=this.option.range;!t||t.auto?(e.auto=1,this.option.range=e):J(t)&&(t[0]>t[1]&&t.reverse(),t[0]=Math.max(t[0],e[0]),t[1]=Math.min(t[1],e[1]))},t.prototype.completeVisualOption=function(){e.prototype.completeVisualOption.apply(this,arguments),G(this.stateList,function(e){var t=this.option.controller[e].symbolSize;t&&t[0]!==t[1]&&(t[0]=t[1]/3)},this)},t.prototype.setSelected=function(e){this.option.range=e.slice(),this._resetRange()},t.prototype.getSelected=function(){var e=this.getExtent(),t=tc((this.get(`range`)||[]).slice());return t[0]>e[1]&&(t[0]=e[1]),t[1]>e[1]&&(t[1]=e[1]),t[0]=n[1]||e<=t[1])?`inRange`:`outOfRange`},t.prototype.findTargetDataIndices=function(e){var t=[];return this.eachTargetSeries(function(n){var r=[],i=n.getData();i.each(this.getDataDimensionIndex(i),function(t,n){e[0]<=t&&t<=e[1]&&r.push(n)},this),t.push({seriesId:n.id,dataIndex:r})},this),t},t.prototype.getVisualMeta=function(e){var t=RJ(this,`outOfRange`,this.getExtent()),n=RJ(this,`inRange`,this.option.range.slice()),r=[];function i(t,n){r.push({value:t,color:e(t,n)})}for(var a=0,o=0,s=n.length,c=t.length;oe[1])break;r.push({color:this.getControllerVisual(o,`color`,t),offset:a/n})}return r.push({color:this.getControllerVisual(e[1],`color`,t),offset:1}),r},t.prototype._createBarPoints=function(e,t){var n=this.visualMapModel.itemSize;return[[n[0]-t[0],e[0]],[n[0],e[0]],[n[0],e[1]],[n[0]-t[1],e[1]]]},t.prototype._createBarGroup=function(e){var t=this._orient,n=this.visualMapModel.get(`inverse`);return new y_(t===`horizontal`&&!n?{scaleX:e===`bottom`?1:-1,rotation:Math.PI/2}:t===`horizontal`&&n?{scaleX:e===`bottom`?-1:1,rotation:-Math.PI/2}:t===`vertical`&&!n?{scaleX:e===`left`?1:-1,scaleY:-1}:{scaleX:e===`left`?1:-1})},t.prototype._updateHandle=function(e,t){if(this._useHandle){var n=this._shapes,r=this.visualMapModel,i=n.handleThumbs,a=n.handleLabels,o=r.itemSize,s=r.getExtent(),c=this._applyTransform(`left`,n.mainGroup);WJ([0,1],function(l){var u=i[l];u.setStyle(`fill`,t.handlesColor[l]),u.y=e[l];var d=UJ(e[l],[0,o[1]],s,!0),f=this.getControllerVisual(d,`symbolSize`);u.scaleX=u.scaleY=f/o[0],u.x=o[0]-f/2;var p=qv(n.handleLabelPoints[l],Kv(u,this.group));if(this._orient===`horizontal`){var m=c===`left`||c===`top`?(o[0]-f)/2:(o[0]-f)/-2;p[1]+=m}a[l].setStyle({x:p[0],y:p[1],text:r.formatValueText(this._dataInterval[l]),verticalAlign:`middle`,align:this._orient===`vertical`?this._applyTransform(`left`,n.mainGroup):`center`})},this)}},t.prototype._showIndicator=function(e,t,n,r){var i=this.visualMapModel,a=i.getExtent(),o=i.itemSize,s=[0,o[1]],c=this._shapes,l=c.indicator;if(l){l.attr(`invisible`,!1);var u=this.getControllerVisual(e,`color`,{convertOpacityToAlpha:!0}),d=this.getControllerVisual(e,`symbolSize`),f=UJ(e,a,s,!0),p=o[0]-d/2,m={x:l.x,y:l.y};l.y=f,l.x=p;var h=qv(c.indicatorLabelPoint,Kv(l,this.group)),g=c.indicatorLabel;g.attr(`invisible`,!1);var _=this._applyTransform(`left`,c.mainGroup),v=this._orient===`horizontal`;g.setStyle({text:(n||``)+i.formatValueText(t),verticalAlign:v?_:`middle`,align:v?`center`:_});var y={x:p,y:f,style:{fill:u}},b={style:{x:h[0],y:h[1]}};if(i.ecModel.isAnimationEnabled()&&!this._firstShowIndicator){var x={duration:100,easing:`cubicInOut`,additive:!0};l.x=m.x,l.y=m.y,l.animateTo(y,x),g.animateTo(b,x)}else l.attr(y),g.attr(b);this._firstShowIndicator=!1;var S=this._shapes.handleLabels;if(S)for(var C=0;Ci[1]&&(l[1]=1/0),t&&(l[0]===-1/0?this._showIndicator(c,l[1],`< `,o):l[1]===1/0?this._showIndicator(c,l[0],`> `,o):this._showIndicator(c,c,`≈ `,o));var u=this._hoverLinkDataIndices,d=[];(t||QJ(n))&&(d=this._hoverLinkDataIndices=n.findTargetDataIndices(l));var f=Xc(u,d);this._dispatchHighDown(`downplay`,HJ(f[0],n)),this._dispatchHighDown(`highlight`,HJ(f[1],n))}},t.prototype._hoverLinkFromSeriesMouseOver=function(e){var t;if(KM(e.target,function(e){var n=jh(e);if(n.dataIndex!=null)return t=n,!0},!0),t){var n=this.ecModel.getSeriesByIndex(t.seriesIndex),r=this.visualMapModel;if(r.isTargetSeries(n)){var i=n.getData(t.dataType),a=i.getStore().get(r.getDataDimensionIndex(i),t.dataIndex);isNaN(a)||this._showIndicator(a,a)}}},t.prototype._hideIndicator=function(){var e=this._shapes;e.indicator&&e.indicator.attr(`invisible`,!0),e.indicatorLabel&&e.indicatorLabel.attr(`invisible`,!0);var t=this._shapes.handleLabels;if(t)for(var n=0;n=0&&(i.dimension=a,r.push(i))}}),e.getData().setVisual(`visualMeta`,r)}}];function rY(e,t,n,r){for(var i=t.targetVisuals[r],a=Fz.prepareVisualTypes(i),o={color:HM(e.getData(),`color`)},s=0,c=a.length;s0:e.splitNumber>0)||e.calculable)?`continuous`:`piecewise`}),e.registerAction(eY,tY),G(nY,function(t){e.registerVisual(e.PRIORITY.VISUAL.COMPONENT,t)}),e.registerPreprocessor(aY))}function lY(e){e.registerComponentModel(LJ),e.registerComponentView(YJ),cY(e)}var uY=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n._pieceList=[],n}return t.prototype.optionUpdated=function(t,n){e.prototype.optionUpdated.apply(this,arguments),this.resetExtent();var r=this._mode=this._determineMode();this._pieceList=[],dY[this._mode].call(this,this._pieceList),this._resetSelected(t,n);var i=this.option.categories;this.resetVisual(function(e,t){r===`categories`?(e.mappingMethod=`category`,e.categories=Ho(i)):(e.dataExtent=this.getExtent(),e.mappingMethod=`piecewise`,e.pieceList=K(this._pieceList,function(e){return e=Ho(e),t!==`inRange`&&(e.visual=null),e}))})},t.prototype.completeVisualOption=function(){var t=this.option,n={},r=Fz.listVisualTypes(),i=this.isCategory();G(t.pieces,function(e){G(r,function(t){e.hasOwnProperty(t)&&(n[t]=1)})}),G(n,function(e,n){var r=!1;G(this.stateList,function(e){r=r||a(t,e,n)||a(t.target,e,n)},this),!r&&G(this.stateList,function(e){(t[e]||(t[e]={}))[n]=DJ.get(n,e===`inRange`?`active`:`inactive`,i)})},this);function a(e,t,n){return e&&e[t]&&e[t].hasOwnProperty(n)}e.prototype.completeVisualOption.apply(this,arguments)},t.prototype._resetSelected=function(e,t){var n=this.option,r=this._pieceList,i=(t?n:e).selected||{};if(n.selected=i,G(r,function(e,t){var n=this.getSelectedMapKey(e);i.hasOwnProperty(n)||(i[n]=!0)},this),n.selectedMode===`single`){var a=!1;G(r,function(e,t){var n=this.getSelectedMapKey(e);i[n]&&(a?i[n]=!1:a=!0)},this)}},t.prototype.getItemSymbol=function(){return this.get(`itemSymbol`)},t.prototype.getSelectedMapKey=function(e){return this._mode===`categories`?e.value+``:e.index+``},t.prototype.getPieceList=function(){return this._pieceList},t.prototype._determineMode=function(){var e=this.option;return e.pieces&&e.pieces.length>0?`pieces`:this.option.categories?`categories`:`splitNumber`},t.prototype.setSelected=function(e){this.option.selected=Ho(e)},t.prototype.getValueState=function(e){var t=Fz.findPieceIndex(e,this._pieceList);return t==null?`outOfRange`:this.option.selected[this.getSelectedMapKey(this._pieceList[t])]?`inRange`:`outOfRange`},t.prototype.findTargetDataIndices=function(e){var t=[],n=this._pieceList;return this.eachTargetSeries(function(r){var i=[],a=r.getData();a.each(this.getDataDimensionIndex(a),function(t,r){Fz.findPieceIndex(t,n)===e&&i.push(r)},this),t.push({seriesId:r.id,dataIndex:i})},this),t},t.prototype.getRepresentValue=function(e){var t;if(this.isCategory())t=e.value;else if(e.value!=null)t=e.value;else{var n=e.interval||[];t=n[0]===-1/0&&n[1]===1/0?0:(n[0]+n[1])/2}return t},t.prototype.getVisualMeta=function(e){if(this.isCategory())return;var t=[],n=[``,``],r=this;function i(i,a){var o=r.getRepresentValue({interval:i});a||=r.getValueState(o);var s=e(o,a);i[0]===-1/0?n[0]=s:i[1]===1/0?n[1]=s:t.push({value:i[0],color:s},{value:i[1],color:s})}var a=this._pieceList.slice();if(!a.length)a.push({interval:[-1/0,1/0]});else{var o=a[0].interval[0];o!==-1/0&&a.unshift({interval:[-1/0,o]}),o=a[a.length-1].interval[1],o!==1/0&&a.push({interval:[o,1/0]})}var s=-1/0;return G(a,function(e){var t=e.interval;t&&(t[0]>s&&i([s,t[0]],`outOfRange`),i(t.slice()),s=t[1])},this),{stops:t,outerColors:n}},t.type=`visualMap.piecewise`,t.defaultOption=nb(FJ.defaultOption,{selected:null,minOpen:!1,maxOpen:!1,align:`auto`,itemWidth:20,itemHeight:14,itemSymbol:`roundRect`,pieces:null,categories:null,splitNumber:5,selectedMode:`multiple`,itemGap:10,hoverLink:!0}),t}(FJ),dY={splitNumber:function(e){var t=this.option,n=Math.min(t.precision,20),r=this.getExtent(),i=t.splitNumber;i=Math.max(parseInt(i,10),1),t.splitNumber=i;for(var a=(r[1]-r[0])/i;+a.toFixed(n)!==a&&n<5;)n++;t.precision=n,a=+a.toFixed(n),t.minOpen&&e.push({interval:[-1/0,r[0]],close:[0,0]});for(var o=0,s=r[0];o`,`≥`][t[0]]];e.text=e.text||this.formatValueText(e.value==null?e.interval:e.value,!1,n)},this)}};function fY(e,t){var n=e.inverse;(e.orient===`vertical`?!n:n)&&t.reverse()}var pY=function(e){U(t,e);function t(){var n=e!==null&&e.apply(this,arguments)||this;return n.type=t.type,n}return t.prototype.doRender=function(){var e=this.group;e.removeAll();var t=this.visualMapModel,n=t.get(`textGap`),r=t.textStyleModel,i=this._getItemAlign(),a=t.itemSize,o=this._getViewData(),s=o.endsText,c=ps(t.get(`showLabel`,!0),!s),l=!t.get(`selectedMode`);s&&this._renderEndsText(e,s[0],a,c,i),G(o.viewPieceList,function(o){var s=o.piece,u=new y_;u.onclick=q(this._onItemClick,this,s),this._enableHoverLink(u,o.indexInModelPieceList);var d=t.getRepresentValue(s);if(this._createItemSymbol(u,d,[0,0,a[0],a[1]],l),c){var f=this.visualMapModel.getValueState(d),p=r.get(`align`)||i;u.add(new _h({style:Oy(r,{x:p===`right`?-n:a[0]+n,y:a[1]/2,text:s.text,verticalAlign:r.get(`verticalAlign`)||`middle`,align:p,opacity:X(r.get(`opacity`),f===`outOfRange`?.5:1)}),silent:l}))}e.add(u)},this),s&&this._renderEndsText(e,s[1],a,c,i),Rx(t.get(`orient`),e,t.get(`itemGap`)),this.renderBackground(e),this.positionGroup(e)},t.prototype._enableHoverLink=function(e,t){var n=this;e.on(`mouseover`,function(){return r(`highlight`)}).on(`mouseout`,function(){return r(`downplay`)});var r=function(e){var r=n.visualMapModel;r.option.hoverLink&&n.api.dispatchAction({type:e,batch:HJ(r.findTargetDataIndices(t),r)})}},t.prototype._getItemAlign=function(){var e=this.visualMapModel,t=e.option;if(t.orient===`vertical`)return VJ(e,this.api,e.itemSize);var n=t.align;return(!n||n===`auto`)&&(n=`left`),n},t.prototype._renderEndsText=function(e,t,n,r,i){if(t){var a=new y_,o=this.visualMapModel.textStyleModel;a.add(new _h({style:Oy(o,{x:r?i===`right`?n[0]:0:n[0]/2,y:n[1]/2,verticalAlign:`middle`,align:r?i:`center`,text:t})})),e.add(a)}},t.prototype._getViewData=function(){var e=this.visualMapModel,t=K(e.getPieceList(),function(e,t){return{piece:e,indexInModelPieceList:t}}),n=e.get(`text`),r=e.get(`orient`),i=e.get(`inverse`);return(r===`horizontal`?i:!i)?t.reverse():n&&=n.slice().reverse(),{viewPieceList:t,endsText:n}},t.prototype._createItemSymbol=function(e,t,n,r){var i=QD(this.getControllerVisual(t,`symbol`),n[0],n[1],n[2],n[3],this.getControllerVisual(t,`color`));i.silent=r,e.add(i)},t.prototype._onItemClick=function(e){var t=this.visualMapModel,n=t.option,r=n.selectedMode;if(r){var i=Ho(n.selected),a=t.getSelectedMapKey(e);r===`single`||r===!0?(i[a]=!0,G(i,function(e,t){i[t]=t===a})):i[a]=!i[a],this.api.dispatchAction({type:`selectDataRange`,from:this.uid,visualMapId:this.visualMapModel.id,selected:i})}},t.type=`visualMap.piecewise`,t}(zJ);function mY(e){e.registerComponentModel(uY),e.registerComponentView(pY),cY(e)}function hY(e){MF(lY),MF(mY)}var gY={label:{enabled:!0},decal:{show:!1}},_Y=Qc(),vY=Qc(),yY=El(bY);function bY(e,t){var n=e.getModel(`aria`);if(!n.get(`enabled`))return;var r=vY(e).scope||(vY(e).scope={}),i=Ho(gY);Uo(i.label,e.getLocaleModel().get(`aria`),!1),Uo(n.option,i,!1),a(),o();function a(){if(n.getModel(`decal`).get(`show`)){var t=Es();e.eachSeries(function(e){e.isColorBySeries()||(_Y(e).scope=t.get(e.type)||t.set(e.type,{}))}),e.eachSeries(function(t){if(rs(t.enableAriaDecal)){t.enableAriaDecal();return}var n=t.getData();if(t.isColorBySeries()){var i=eS(t.ecModel,t.name,r,e.getSeriesCount()),a=n.getVisual(`decal`);n.setVisual(`decal`,u(a,i))}else{var o=t.getRawData(),s={},c=_Y(t).scope;n.each(function(e){var t=n.getRawIndex(e);s[t]=e});var l=o.count();o.each(function(e){var r=s[e],i=o.getName(e)||e+``,a=eS(t.ecModel,i,c,l),d=n.getItemVisual(r,`decal`);n.setItemVisual(r,`decal`,u(d,a))})}function u(e,t){var n=e?W(W({},t),e):t;return n.dirty=!0,n}})}}function o(){var r=t.getZr().dom;if(r){var i=e.getLocaleModel().get(`aria`),a=n.getModel(`label`);if(a.option=Ko(a.option,i),a.get(`enabled`)){if(r.setAttribute(`role`,`img`),a.get(`description`)){r.setAttribute(`aria-label`,a.get(`description`));return}var o=e.getSeriesCount(),u=a.get([`data`,`maxCount`])||10,d=a.get([`series`,`maxCount`])||10,f=Math.min(o,d),p;if(!(o<1)){var m=c();p=m?s(a.get([`general`,`withTitle`]),{title:m}):a.get([`general`,`withoutTitle`]);var h=[],g=o>1?a.get([`series`,`multiple`,`prefix`]):a.get([`series`,`single`,`prefix`]);p+=s(g,{seriesCount:o}),e.eachSeries(function(e,t){if(t1?a.get([`series`,`multiple`,r]):a.get([`series`,`single`,r]),n=s(n,{seriesId:e.seriesIndex,seriesName:e.get(`name`),seriesType:l(e.subType)});var i=e.getData();if(i.count()>u){var c=a.get([`data`,`partialData`]);n+=s(c,{displayCnt:u})}else n+=a.get([`data`,`allData`]);for(var d=a.get([`data`,`separator`,`middle`]),p=a.get([`data`,`separator`,`end`]),m=a.get([`data`,`excludeDimensionId`]),g=[],_=0;_=a}}}for(var l=TY(this),u=l.startIdx;u=0)&&(a=!0)}),a||i.__dirty){var o=n._opts.useDirtyRect&&!wY(i)?i.createRepaintRects(e,t,n._width,n._height):null,s=n._i.layerStack[0],c=!0;if(i.__dirty){c=!1,i.__dirty=!1;var l=i.zlevel===s.zl&&i.zlevel2===s.zl2?n._backgroundColor:null;i.clear(!1,l,o)}RY(i,function(t){var a=n._paintPerCursor(i,t,e,o,c);r&&=a})}},WY),Ns.wxa&&BY(this._i,function(e){e&&e.ctx&&e.ctx.draw&&e.ctx.draw()}),r},e.prototype._paintPerCursor=function(e,t,n,r,i){var a=e.ctx;if(r){if(!r.length)t.drawIdx=t.endIdx;else for(var o=this.dpr,s=0;s=t.endIdx},e.prototype._paintPerCursorInRect=function(e,t,n,r,i){for(var a={inHover:!1,allClipped:!1,prevEl:null,viewWidth:this._width,viewHeight:this._height,beforeBrushParam:{contentRetained:i}},o=e.ctx,s=wY(e),c=s&&Eo.getTime(),l=t.drawIdx,u=t.notClearIdx,d=u>=0?Math.min(u,l):l;d15){d++;break}}}RN(o,a),t.drawIdx=Math.max(d,l)},e.prototype.getLayer=function(e,t){return this._ensureLayer(e,0,t)},e.prototype._ensureLayer=function(e,t,n){t||=0;var r=this._singleCanvas;r&&!this._needsManuallyCompositing&&(e=OY,t=0);var i=zY(this._i,e)[t];return i||(i=PY(`zr_`+e+`.`+t,this,e,t),this._layerConfig[e]&&Uo(i,this._layerConfig[e],!0),(n||r&&e!==OY)&&(i.virtual=!0),this._insertLayer(i,e,t,!1),i.initContext()),i},e.prototype.insertLayer=function(e,t){this._insertLayer(t,e,0,!1)},e.prototype._insertLayer=function(e,t,n,r){var i=this._i,a=i.layers,o=i.layerStack,s=this._domRoot,c=null;if(!(a[t]&&a[t][n])&&MY(e)){for(var l=o.length,u=0;u0&&(c=zY(i,o[u-1].zl)[o[u-1].zl2]),o.splice(u,0,{zl:t,zl2:n}),zY(i,t)[n]=e,!r&&!e.virtual){if(c){var d=c.dom;d.nextSibling?s.insertBefore(e.dom,d.nextSibling):s.appendChild(e.dom)}else s.firstChild?s.insertBefore(e.dom,s.firstChild):s.appendChild(e.dom)}e.painter||=this}},e.prototype.eachLayer=function(e,t){return BY(this._i,function(n,r){e.call(t,n,r)})},e.prototype.eachBuiltinLayer=function(e,t){return BY(this._i,function(n,r){e.call(t,n,r)},VY)},e.prototype.eachOtherLayer=function(e,t){return BY(this._i,function(n,r){e.call(t,n,r)},HY)},e.prototype.getLayers=function(){var e={};return BY(this._i,function(t,n,r){e[t.id]=t}),e},e.prototype._updateLayerStatus=function(e,t){var n=this;if(n._singleCanvas)for(var r=1;r=0;a--){var o=i.get(r[a]);if(!o.used)t.__dirty=!0,i.removeKey(r[a]),r.splice(a,1);else{var s=o.endIdxNew;(wY(t)?s=0;r--){var i=t[r];if(i.zl===e){var a=n[e][i.zl2];if(a.__builtin__)continue;if(t.splice(r,1),n[e][i.zl2]=void 0,!a.virtual){var o=a.dom.parentNode;o&&o.removeChild(a.dom)}}}},e.prototype.resize=function(e,t){if(this._domRoot.style){var n=this._domRoot;n.style.display=`none`;var r=this._opts,i=this.root;e!=null&&(r.width=e),t!=null&&(r.height=t),e=lN(i,0,r),t=lN(i,1,r),n.style.display=``,(this._width!==e||t!==this._height)&&(n.style.width=e+`px`,n.style.height=t+`px`,BY(this._i,function(n){n.resize(e,t)}),this.refresh({paintAll:!0})),this._width=e,this._height=t}else{if(e==null||t==null)return;this._width=e,this._height=t,this._ensureLayer(OY).resize(e,t)}return this},e.prototype.clearLayer=function(e){G(this._i.layers[e],function(e){e&&!e.__builtin__&&e.clear()})},e.prototype.dispose=function(){this.root.innerHTML=``,this.root=this.storage=this._domRoot=this._i=null},e.prototype.getRenderedCanvas=function(e){if(e||={},this._singleCanvas&&!this._compositeManually)return this._i.layers[OY][0].dom;var t=new EY(`image`,this,e.pixelRatio||this.dpr);t.initContext(),t.clear(!1,e.backgroundColor||this._backgroundColor);var n=t.ctx;if(e.pixelRatio<=this.dpr){this.refresh();var r=t.dom.width,i=t.dom.height;BY(this._i,function(e){e.__builtin__?n.drawImage(e.dom,0,0,r,i):e.renderToCanvas&&(n.save(),e.renderToCanvas(n),n.restore())})}else{for(var a={inHover:!1,viewWidth:this._width,viewHeight:this._height,beforeBrushParam:{}},o=this.storage.getDisplayList(!0),s=0,c=o.length;s{e.data&&e.interactive!==!1&&e.data.forEach((r,i)=>{let a=typeof r==`object`&&r&&!Array.isArray(r)?r:void 0,o=a?.value??r;o!=null&&t.push({series_index:n,data_index:i,label:`${e.name??`Series`} · point ${i+1}`,event:{seriesName:e.name,name:a?.name,value:o,data:r,interactive:e.interactive}})})}),t}MF([aT,KY,rR,iz,WH,bV,hL,zU,rW,Yq,cK,Cq,fq,hY,SY,RK,EJ,AG]);var JY=new Map;function YY({option:e,optionForSize:t,height:n,label:r,onClick:i,onZoom:a,group:o,keyboard:s}){let c=(0,V.useRef)(null),l=(0,V.useRef)(null),[u,d]=(0,V.useState)(e),[f,p]=(0,V.useState)(!1),m=(0,V.useRef)(!1),h=(0,V.useRef)(e),g=(0,V.useRef)(s);g.current=s;let _=(0,V.useRef)(void 0),v=(0,V.useCallback)(e=>{_.current&&l.current?.dispatchAction({type:`downplay`,seriesIndex:_.current.series_index,dataIndex:_.current.data_index}),l.current?.dispatchAction({type:`hideTip`}),_.current=e,e&&(l.current?.dispatchAction({type:`highlight`,seriesIndex:e.series_index,dataIndex:e.data_index}),l.current?.dispatchAction({type:`showTip`,seriesIndex:e.series_index,dataIndex:e.data_index}))},[]),y=Array.isArray(u.series)?u.series:u.series?[u.series]:[],b=Array.isArray(u.xAxis)?u.xAxis[0]:u.xAxis,x=Array.isArray(u.yAxis)?u.yAxis[0]:u.yAxis,S=(0,V.useMemo)(()=>{if(!s||!f)return[];let e=Array.isArray(u.series)?u.series:u.series?[u.series]:[],t=x?.type===`category`&&e[0]?.type!==`custom`?x:b?.type===`category`?b:void 0;return qY(e.map(e=>({...e,interactive:void 0}))).map(n=>{let r=Array.isArray(n.event.value)?n.event.value:[];return{...n,event:{...n.event,interactive:e[n.series_index]?.interactive,name:n.event.name??(e[n.series_index]?.type===`custom`?x?.data?.[Number(r[1])]:t?.data?.[n.data_index])}}}).filter(e=>e.event.value!=null&&(!Array.isArray(e.event.value)||e.event.value.at(-1)!=null))},[u,f]),C=e=>{let t=e.event.data?.selection,n=Array.isArray(e.event.value)?e.event.value:[],r=t?.from?Date.parse(t.from):t?.time??(b?.type===`time`?Number(n[0]):NaN),i=/^(\d+)(ms|s|m|h|d)$/.exec(s?.interval??``),a=i?Number(i[1])*{ms:1,s:1e3,m:6e4,h:36e5,d:864e5}[i[2]]:void 0,o=y[e.series_index]?.data?.[e.data_index+1],c=Array.isArray(o)?o:o?.value,l=typeof c?.[0]==`number`&&c[0]>r?c[0]:void 0,u=a?r+a:l??s?.bounds?.to??r,d=t?.to?Date.parse(t.to):y[e.series_index]?.type===`custom`?Number(n[3]):Math.min(u,s?.bounds?.to??u);return Number.isFinite(r)&&Number.isFinite(d)?{from:r,to:d}:void 0},w=e=>{let t=y[e.series_index],n=Array.isArray(e.event.value)?e.event.value:[e.event.value],r=t?.type===`custom`,i=C(e),a=r?x?.data?.[Number(n[1])]:e.event.name,o=r?n[2]:n.at(-1),s=typeof o==`number`?t?.tooltip?.valueFormatter?.(o)??va(t?.keyboard_unit,o):String(o??`No value`),c=t?.type===`scatter`?`x: ${va(t.keyboard_x_unit,Number(n[0]))} · y: `:``;return[e.event.seriesName??`Series`,a,i?new Date(i.from).toISOString()+(i.to===i.from?``:` – ${new Date(i.to).toISOString()}`):void 0,c+s].filter(Boolean).join(` · `)},T=(0,V.useRef)({}),E=(0,V.useRef)(i);E.current=i;let D=(0,V.useRef)(a);D.current=a;let O=!!a,k=(0,V.useRef)(void 0),A=(0,V.useRef)(0),[j,M]=(0,V.useState)(0),N=(0,V.useCallback)(()=>{let e=k.current;l.current?.dispatchAction({type:`brush`,areas:e?[{brushType:`lineX`,xAxisIndex:0,coordRange:[e.from,e.to]}]:[]},{silent:!0})},[]),P=(0,V.useCallback)(e=>{(k.current?.from!==e?.from||k.current?.to!==e?.to)&&(k.current=e,N())},[N]),F=O?`${r} Brush across the chart to zoom to that range.`:r,I=(0,V.useRef)(()=>void 0),L=(0,V.useCallback)(e=>{e!==A.current&&(A.current=e,I.current())},[]);(0,V.useRef)(null);let ee=(0,V.useRef)(void 0),R=(0,V.useRef)(!1);R.current=!!t,I.current=()=>{ee.current===void 0&&(ee.current=document.createElement(`canvas`).getContext(`2d`));let n=ee.current,r={measureText:n?(e,t)=>(n.font=t,n.measureText(e).width):void 0,width:c.current?.clientWidth??0,height:c.current?.clientHeight??0},i=t&&r.width>0&&r.height>0?t(r):e;if(A.current&&i.grid&&!Array.isArray(i.grid)){let e=i.grid;i={...i,grid:{...e,bottom:(typeof e.bottom==`number`?e.bottom:8)+A.current}}}let a=i.series??[],o=new Set(a.map(e=>e.name)),s=Object.fromEntries(Object.entries(T.current).filter(([e])=>o.has(e)));T.current=s;let u=i.legend;l.current?.setOption({...i,...u?{legend:{...u,selected:{...u.selected,...s}}}:{},...D.current?{toolbox:{show:!1},brush:{xAxisIndex:0,brushMode:`single`,removeOnClick:!0}}:{},aria:{...i.aria,enabled:!0,description:F}},{notMerge:!0});let f=l.current?.getModel?.().getComponent(`grid`)?.coordinateSystem?.getRect(),p=f?.height;if(p&&i.yAxis){let e=Array.isArray(i.yAxis)?i.yAxis:[i.yAxis],t=e.map(e=>wa(e,p));t.some((t,n)=>t.splitNumber!==e[n].splitNumber||t.interval!==e[n].interval)&&(i={...i,yAxis:Array.isArray(i.yAxis)?t:t[0]},l.current?.setOption({yAxis:i.yAxis}))}f&&i.series?.some(e=>e.endLabel?.show)&&(i=co(i,f,(e,t)=>{let n=l.current?.convertToPixel({seriesIndex:e},t);return Array.isArray(n)?n[1]:NaN}),l.current?.setOption({series:i.series})),_.current&&v(_.current),D.current&&l.current?.dispatchAction({type:`takeGlobalCursor`,key:`brush`,brushOption:{brushType:`lineX`,brushMode:`single`}}),D.current&&k.current&&N(),h.current=i,g.current&&m.current&&d(i)},(0,V.useEffect)(()=>{if(!c.current)return;let e=uF(c.current,void 0,{renderer:`canvas`});l.current=e,e.on(`click`,e=>{let t=e,n=h.current.series??[],r=t.seriesIndex===void 0?t.interactive:t.componentType&&t.componentType!==`series`?!1:n[t.seriesIndex]?.interactive;E.current?.({...t,...r===void 0?{}:{interactive:r}})}),e.on(`brushEnd`,t=>{let n=t.areas?.[0]?.coordRange;n?.length===2&&Number.isFinite(n[0])&&Number.isFinite(n[1])&&n[0]e+1)),e.dispatchAction({type:`brush`,areas:[]},{silent:!0}),D.current&&e.dispatchAction({type:`takeGlobalCursor`,key:`brush`,brushOption:{brushType:`lineX`,brushMode:`single`}}))}),e.on(`legendselectchanged`,e=>{T.current={...e.selected}});let t=new ResizeObserver(()=>{e.resize(),R.current&&I.current()});return t.observe(c.current),()=>{t.disconnect(),_.current&&v(void 0),e.dispose(),l.current=null}},[]),(0,V.useEffect)(()=>{I.current()},[e,t,F,O]),(0,V.useEffect)(()=>{let e=l.current;if(e&&o)return e.group=o,JY.set(o,(JY.get(o)??0)+1),dF(o),()=>{e.group=``;let t=(JY.get(o)??1)-1;if(t>0){JY.set(o,t);return}JY.delete(o),fF(o)}},[o]);let te=(0,H.jsx)(`div`,{ref:c,role:`img`,"aria-label":F,"aria-hidden":s?!0:void 0,style:{height:s?`100%`:n,position:s?`absolute`:void 0,inset:s?0:void 0,zIndex:s?0:void 0,flex:`1 1 auto`,minHeight:0,width:`100%`,minWidth:0,cursor:i?`pointer`:void 0}}),ne=Array.isArray(e.series)?e.series:e.series?[e.series]:[],re=r+`: `+ne.length+` series`+(s?.bounds?`; `+new Date(s.bounds.from).toISOString()+` – `+new Date(s.bounds.to).toISOString():``);return s?(0,H.jsx)(Fa,{height:n,rangeReset:j,onRangeChange:P,onRangeBarHeight:L,points:S,label:re,summary:w,onClick:i,canSelect:s.canSelect,onHighlight:v,onZoom:a,bounds:s.bounds,pointWindow:C,onRangePending:s.onRangePending,onActiveChange:e=>{m.current=e,p(e),e&&d(h.current)},children:te}):te}function XY({panel:e,title:t=e.title,result:n,dark:r,height:i,onSelect:a,onPoint:o}){let s=(0,V.useMemo)(()=>t=>go(e,n.frame,so(r),t),[e,n.frame,r]),c=(0,V.useMemo)(()=>s({width:500,height:i}),[s,i]),l=(0,V.useCallback)(t=>!!da(e,n,t),[e,n]);return(0,H.jsx)(YY,{keyboard:{canSelect:l},option:c,optionForSize:s,height:i,label:`${t}: bar chart`,onClick:o||a?t=>{let r=da(e,n,t);if(!r)return;o?.(r);let i=Object.values(r.dimensions)[0];i!==void 0&&a?.(i)}:void 0})}function ZY({panel:e,title:t=e.title,result:n,dark:r,height:i}){let a=Za(e,n.frame),o=n.frame.columns.find(e=>e.role===`measure`)?.unit??e.unit,s=e.better??n.better,c=(0,V.useMemo)(()=>t=>_o({...e,better:s},a,so(r),o,t),[e,s,a,r,o]),l=(0,V.useMemo)(()=>c({width:270,height:i}),[c,i]);return(0,H.jsx)(YY,{option:l,optionForSize:c,height:i,label:`${t}: gauge`})}function QY(e,t){return!t.previous||(e.reduce??`window`)===`window`&&!t.previous.totals?null:Za(e,t.previous)}function $Y({panel:e,result:t,dark:n=!1,compare:r=!0,range:i}){let a=t.frame,s=Za(e,a),c=a.columns.find(e=>e.role===`measure`)?.unit??e.unit,l=e.better??t.better??eo(e.thresholds),u=to(s,e.thresholds,l)??(a.health?.health===`healthy`?`ok`:a.health?.health===`degraded`?`warn`:a.health?.health===`unhealthy`?`bad`:null),d=QY(e,t),f=Qa(a),p=e.thresholds?.find(e=>e.status===u&&s!==null&&(l===`higher`?s<=e.value:s>=e.value))?.label,m=so(n);return(0,H.jsxs)(o,{h:`100%`,style:{display:`flex`,flexDirection:`column`,justifyContent:`space-between`,gap:4},children:[(0,H.jsxs)(y,{justify:`space-between`,align:`flex-start`,wrap:`nowrap`,gap:`xs`,children:[(0,H.jsx)(T,{"data-stat-value":!0,fz:32,fw:700,lh:1.1,lts:`-0.02em`,ff:`var(--mantine-font-family-monospace)`,children:va(c,s)}),u&&(0,H.jsxs)(T,{"data-stat-status":!0,fz:12,fw:500,style:{borderRadius:999,padding:`1px 8px`,whiteSpace:`nowrap`,background:`${m.status[u]}22`,color:m.text},children:[(0,H.jsx)(`span`,{style:{color:m.status[u]},children:u===`bad`?`◆`:u===`warn`?`■`:`●`}),` `,p??(u===`bad`?`Unhealthy`:u===`warn`?`Degraded`:`Healthy`)]})]}),r&&d!==null&&s!==null&&(0,H.jsx)(eX,{dark:n,value:s,previous:d,better:l,unit:c,period:tX(i,t)}),(0,H.jsx)(nX,{points:f,area:!0,dark:n,height:40})]})}function eX({value:e,previous:t,better:n,unit:r,period:i,dark:a}){let o=r===`percent`,s=o?e-t:t===0?e===0?0:1/0:(e-t)/Math.abs(t)*100,c=s>=0,l=s===0||!n?null:c?n===`higher`:n===`lower`,u=Number.isFinite(s)?o?`${c?`+`:`−`}${Math.abs(s).toFixed(1)} pts`:`${c?`+`:`−`}${Math.abs(s).toFixed(0)}%`:`new`;return(0,H.jsxs)(y,{gap:6,children:[(0,H.jsxs)(T,{"data-stat-delta":!0,fz:12,fw:600,style:{color:l===null?`var(--mantine-color-dimmed)`:oo(l?`ok`:`bad`,a)},children:[c?`▲`:`▼`,` `,u]}),(0,H.jsxs)(T,{fz:12,c:`dimmed`,children:[`vs previous `,i]})]})}function tX(e,t){let n=t.from_ms!==void 0&&t.to_ms!==void 0?t.to_ms-t.from_ms:t.shift_ms,r=/^(\d+)(s|m|h|d|w)$/.exec(e??``),i=r?Number(r[1])*{s:1e3,m:6e4,h:36e5,d:864e5,w:6048e5}[r[2]]:n;if(!i)return`period`;let a=i>=6048e5?`week`:i>=864e5?`day`:i>=36e5?`hour`:i>=6e4?`minute`:`second`,o=i/{week:6048e5,day:864e5,hour:36e5,minute:6e4,second:1e3}[a];return o===1?a:`${Number(o.toFixed(2))} ${a}s`}function nX({points:e,area:t=!1,dark:n=!1,height:r=32}){let i=e.filter(e=>e!==null&&Number.isFinite(e));if(i.length<2)return null;let a=Math.min(...i),o=Math.max(...i),s=r,c=t=>t/(e.length-1)*200,l=e=>s-2-(e-a)/(o-a||1)*(s-4),u=e.map((t,n)=>t===null||!Number.isFinite(t)?``:`${n===0||e[n-1]===null||!Number.isFinite(e[n-1])?`M`:`L`}${c(n).toFixed(1)},${l(t).toFixed(1)}`).join(``),d=[];return e.forEach((t,n)=>{if(t!==null&&Number.isFinite(t)){if(!n||e[n-1]===null||!Number.isFinite(e[n-1]))d.push({start:n,end:n,path:`M${c(n).toFixed(1)},${l(t).toFixed(1)}`});else{let e=d.at(-1);e.end=n,e.path+=`L${c(n).toFixed(1)},${l(t).toFixed(1)}`}}}),(0,H.jsxs)(`svg`,{viewBox:`0 0 200 ${s}`,preserveAspectRatio:`none`,width:`100%`,height:s,role:`img`,"aria-label":`Value over this panel's time range`,children:[t&&d.filter(e=>e.end>e.start).map(e=>(0,H.jsx)(`path`,{"data-sparkline-area":!0,d:`${e.path}L${c(e.end)},${s}L${c(e.start)},${s}Z`,fill:Ua(0,n),opacity:.18},e.start)),(0,H.jsx)(`path`,{"data-sparkline-line":!0,d:u,fill:`none`,stroke:t?Ua(0,n):`var(--mantine-primary-color-filled)`,strokeWidth:1.5,vectorEffect:`non-scaling-stroke`})]})}function rX(e){return iX(e)||typeof e==`function`||aX(e)}function iX(e){return typeof e==`function`&&(()=>{let t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function aX(e){return typeof e==`object`&&typeof e.$$typeof==`symbol`&&[`react.memo`,`react.forward_ref`].includes(e.$$typeof.description)}function oX(e,t){return e==null?null:rX(e)?V.createElement(e,t):e}function sX(e){if(`cell`in e&&e.cell){let t=e.cell,n=t.column.columnDef,r=t,i=n;return r.getIsAggregated?.()?oX(i.aggregatedCell??n.cell,t.getContext()):r.getIsPlaceholder?.()?null:oX(n.cell,t.getContext())}return`header`in e&&e.header?oX(e.header.column.columnDef.header,e.header.getContext()):`footer`in e&&e.footer?oX(e.footer.column.columnDef.footer,e.footer.getContext()):null}function cX(e){let t=lt(e.source,e.selector,{compare:Pt});return typeof e.children==`function`?e.children(t):e.children}function lX(e){let t=e;return Object.defineProperty(e,"state",{get(){return e.get()}}),`set`in e&&(t.setState=e.set.bind(e)),t}function uX(e){let{createAtom:t,batch:n}=e,r=t(0);return{createOptionsStore:!1,wrapExternalAtoms:!1,addSubscription:()=>{throw Error(`Feature not supported in current reactivity implementation`)},unmount:()=>{throw Error(`Feature not supported in current reactivity implementation`)},schedule:e.schedule??(e=>queueMicrotask(e)),batch:n,untrack:e=>e(),createReadonlyAtom:(e,n)=>{let i=n?.compare??Object.is,a=!1,o,s=()=>{let t=e();return(!a||!i(o,t))&&(o=t,a=!0),o},c=t(()=>(r.get(),s()),{compare:i});return{get:s,subscribe:c.subscribe.bind(c)}},createWritableAtom:(e,n)=>t(e,{compare:n?.compare}),commit:()=>{r.set(e=>e+1)}}}function dX(e,t=Object.is){let n=!1,r;return{get:e.get,markCommitted:e=>{r=e,n=!0},subscribe:i=>e.subscribe(e=>{(!n||!t(r,e))&&i(e)})}}function fX(){return uX({createAtom:ut,batch:ct})}function pX(e,t){return typeof e==`function`?e(t):e}function mX(e){if(Array.isArray(e))return e.map(mX);if(e&&typeof e==`object`){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n=t===null?gX():{},r=Object.keys(e);for(let t=0;t{(t.options.atoms?.[e]??t.baseAtoms[e]).set(e=>pX(n,e))}}function yX(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bX(e){return Reflect.ownKeys(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}var xX=3;function SX(e,t){return CX(e,t,xX)}function CX(e,t,n){if(Object.is(e,t))return!0;if(n<=0||!yX(e)||!yX(t)||(Array.isArray(e)||Array.isArray(t))&&(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length))return!1;let r=bX(e),i=bX(t);if(r.length!==i.length)return!1;let a=e,o=t;for(let e=0;e{let t=pX(n,e);return r(e,t)?e:t})}function TX(e){return e instanceof Function}function EX(e,t){let n=[],r=e=>{e.forEach(e=>{n.push(e);let i=t(e);i.length&&r(i)})};return r(e),n}var DX=({fn:e,memoDeps:t,onAfterCompare:n,onAfterUpdate:r,onBeforeCompare:i,onBeforeUpdate:a})=>{let o=[],s;return c=>{i?.();let l=t?.(c),u=!l||l.length!==o?.length;if(!u&&l){for(let e=0;e{if(!t){t=!0;return}e()}}function kX({feature:e,fnName:t,objectId:n,onAfterUpdate:r,table:i,...a}){let o={onAfterUpdate:r?()=>{let{schedule:e,untrack:t}=i._reactivity;e(()=>t(()=>r()))}:void 0};return DX({...a,...o})}function AX(e,t=`_`){let[n,r]=e.replace(t,` `).split(` `);return{fnKey:r,fnName:`${n}.${r}`,parentName:n}}function jX(e,t,n){for(let[r,{fn:i,memoDeps:a}]of Object.entries(n)){let{fnKey:n,fnName:o}=AX(r);t[n]=a?kX({memoDeps:a,fn:i,fnName:o,table:t,feature:e}):i}}function MX(e,t,n,r){for(let[i,{fn:a,memoDeps:o}]of Object.entries(r)){let{fnKey:r,fnName:s}=AX(i);if(o){let i=`_memo_${r}`;t[r]=function(...t){if(!this[i]){let t=this;this[i]=kX({memoDeps:e=>o(t,e),fn:(...e)=>a(t,...e),fnName:s,objectId:t.id,table:n,feature:e})}return this[i](...t)}}else t[r]=function(...e){return a(this,...e)}}}function NX(e){return e.row.getValue(e.column.id)}function PX(e){return e.getValue()??e.table.options.renderFallbackValue}function FX(e){return{table:e.table,column:e.column,row:e.row,cell:e,getValue:()=>e.getValue(),renderValue:()=>e.renderValue()}}var IX={assignCellPrototype:(e,t)=>{MX(`coreCellsFeature`,e,t,{cell_getValue:{fn:e=>NX(e)},cell_renderValue:{fn:e=>PX(e)},cell_getContext:{fn:e=>FX(e),memoDeps:e=>[e]}})}};function LX(e){if(!e._columnPrototype){e._columnPrototype={table:e};let t=Object.values(e._features);for(let n=0;n{let n=t;for(let t=0;te[i.accessorKey]}if(!s)throw Error();let l=LX(e),u=Object.create(l);u.accessorFn=c,u.columnDef=i,u.columns=[],u.depth=n,u.id=`${String(s)}`,u.parent=r;let d=e._columnInstanceInitFns;for(let e=0;ee.getFlatColumns())]}function YX(e){if(e.columns.length){let t=e.columns.flatMap(e=>e.getLeafColumns());return VX(e.table,t)}return[e]}function XX(e){return{header:e=>{let t=e.header.column.columnDef;return t.accessorKey?t.accessorKey:t.accessorFn?t.id:null},cell:e=>e.renderValue()?.toString?.()??null,...Object.values(e._features).reduce((e,t)=>Object.assign(e,t.getDefaultColumnDef?.()),{}),...e.options.defaultColumn}}function ZX(e,t,n,r=0){let i=Array(t.length);for(let a=0;ae.getFlatColumns())}function eZ(e){let t=gX(),n=e.getAllFlatColumns();for(let e=0;ee.getLeafColumns()))}function nZ(e){let t=gX(),n=e.getAllLeafColumns();for(let e=0;e{MX(`coreColumnsFeature`,e,t,{column_getFlatColumns:{fn:e=>JX(e),memoDeps:e=>[e.table.options.columns]},column_getLeafColumns:{fn:e=>YX(e),memoDeps:e=>[e.table.atoms.columnOrder?.get(),e.table.atoms.grouping?.get(),e.table.options.columns,e.table.options.groupedColumnMode]}})},constructTableAPIs:e=>{jX(`coreColumnsFeature`,e,{table_getDefaultColumnDef:{fn:()=>XX(e),memoDeps:()=>[e.options.defaultColumn]},table_getAllColumns:{fn:()=>QX(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumns:{fn:()=>$X(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumnsById:{fn:()=>eZ(e),memoDeps:()=>[e.options.columns]},table_getAllLeafColumns:{fn:()=>tZ(e),memoDeps:()=>[e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.options.columns,e.options.groupedColumnMode]},table_getAllLeafColumnsById:{fn:()=>nZ(e),memoDeps:()=>[e.getAllLeafColumns()]},table_getColumn:{fn:t=>rZ(e,t)}})}};function aZ(e){if(!e._headerPrototype){e._headerPrototype={table:e};let t=Object.values(e._features);for(let n=0;n0&&dZ(s,t-1,n,r,i,a)}function fZ(e){for(let t=0;te.id),e)}function vZ(e){return[...e.getHeaderGroups()].reverse()}function yZ(e){let t=e.getHeaderGroups(),n=[];for(let e=0;e{MX(`coreHeadersFeature`,e,t,{header_getLeafHeaders:{fn:e=>hZ(e),memoDeps:e=>[e.column.table.options.columns]},header_getContext:{fn:e=>gZ(e),memoDeps:e=>[e.column.table.options.columns]}})},constructTableAPIs:e=>{jX(`coreHeadersFeature`,e,{table_getHeaderGroups:{fn:()=>_Z(e),memoDeps:()=>[e.options.columns,e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.atoms.columnPinning?.get(),e.atoms.columnVisibility?.get(),e.options.groupedColumnMode]},table_getFooterGroups:{fn:()=>vZ(e),memoDeps:()=>[e.getHeaderGroups()]},table_getFlatHeaders:{fn:()=>yZ(e),memoDeps:()=>[e.getHeaderGroups()]},table_getLeafHeaders:{fn:()=>bZ(e),memoDeps:()=>[e.getHeaderGroups()]}})}};function SZ(e){if(!e._rowPrototype){e._rowPrototype={table:e};let t=Object.values(e._features);for(let n=0;n{let s=SZ(e),c=Object.create(s);c._displayIndexCache=-1,c._uniqueValuesCache=gX(),c._valuesCache=gX(),c.depth=i,c.id=t,c.index=r,c.original=n,c.parentId=o,c.subRows=a??[];let l=e._rowInstanceInitFns;for(let e=0;ekX({feature:`coreRowModelsFeature`,table:e,fnName:`table.getCoreRowModel`,memoDeps:()=>[e.options.data],fn:()=>EZ(e,e.options.data),onAfterUpdate:OX(()=>{WX(e),GX(e),KX(e),qX(e)})})}function TZ(e,t,n,r=0,i){let a=[];for(let o=0;o{jX(`coreRowModelsFeature`,e,{table_getCoreRowModel:{fn:()=>DZ(e)},table_getPreFilteredRowModel:{fn:()=>OZ(e)},table_getFilteredRowModel:{fn:()=>kZ(e)},table_getPreGroupedRowModel:{fn:()=>AZ(e)},table_getGroupedRowModel:{fn:()=>jZ(e)},table_getPreSortedRowModel:{fn:()=>MZ(e)},table_getSortedRowModel:{fn:()=>NZ(e)},table_getPreExpandedRowModel:{fn:()=>PZ(e)},table_getExpandedRowModel:{fn:()=>FZ(e)},table_getPrePaginatedRowModel:{fn:()=>IZ(e)},table_getPaginatedRowModel:{fn:()=>LZ(e)},table_getRowModel:{fn:()=>RZ(e)}})}};function BZ(e){if(!e._cellPrototype){e._cellPrototype={table:e};let t=Object.values(e._features);for(let n=0;ne.subRows)}function JZ(e){let t=e.getCoreRowModel().flatRows,n=0;for(let e=0;e{MX(`coreRowsFeature`,e,t,{row_getDisplayIndex:{fn:e=>HZ(e)},row_getAllCellsByColumnId:{fn:e=>QZ(e),memoDeps:e=>[e.getAllCells()]},row_getAllCells:{fn:e=>ZZ(e),memoDeps:e=>[e.table.getAllLeafColumns()]},row_getLeafRows:{fn:e=>qZ(e),memoDeps:e=>[e.subRows]},row_getParentRow:{fn:e=>YZ(e)},row_getParentRows:{fn:e=>XZ(e)},row_getUniqueValues:{fn:(e,t)=>GZ(e,t)},row_getValue:{fn:(e,t)=>WZ(e,t)},row_renderValue:{fn:(e,t)=>KZ(e,t)}})},constructTableAPIs:e=>{jX(`coreRowsFeature`,e,{table_getRowsInDisplayOrder:{fn:()=>UZ(e),memoDeps:()=>[e.getPrePaginatedRowModel().rows,e.options.paginateExpandedRows,e.options.paginateExpandedRows===!1?e.atoms.expanded?.get():void 0]},table_getRowId:{fn:(t,n,r)=>$Z(t,e,n,r)},table_getRow:{fn:(t,n)=>eQ(e,t,n)},table_getMaxSubRowDepth:{fn:()=>JZ(e),memoDeps:()=>[e.getCoreRowModel()]}})}};function nQ(e,t,n=(e,t)=>e===t){let r=t===void 0?e.options.state:t;e._reactivity.batch(()=>{if(r)for(let t in r){let i=e.baseAtoms[t];if(!i)continue;let a=r[t],o=a===void 0?e.initialState[t]:a;n(e._reactivity.untrack(()=>i.get()),o)||i.set(()=>o)}})}function rQ(e,t,n=(e,t)=>e===t){e._reactivity.batch(()=>{nQ(e,t,n),e._reactivity.commit?.()})}function iQ(e){let t=mX(e.initialState);e._reactivity.batch(()=>{let n=Object.keys(t);for(let r=0;rr):e.options=r,n?.syncExternalState!==!1&&rQ(e,r.state??null)}var sQ={coreCellsFeature:IX,coreColumnsFeature:iZ,coreHeadersFeature:xZ,coreRowModelsFeature:zZ,coreRowsFeature:tQ,coreTablesFeature:{constructTableAPIs:e=>{jX(`coreTablesFeature`,e,{table_reset:{fn:()=>iQ(e)},table_setOptions:{fn:t=>oQ(e,t)}})}}};function cQ(e){return e}function lQ(e,t={}){return Object.values(e).forEach(e=>{t=e.getInitialState?.(t)??t}),mX(t)}function uQ(e){let t=e.features.coreReactivityFeature,{aggregationFns:n,columnMeta:r,coreRowModel:i,expandedRowModel:a,facetedMinMaxValues:o,facetedRowModel:s,facetedUniqueValues:c,filterFns:l,filterMeta:u,filteredRowModel:d,groupedRowModel:f,paginatedRowModel:p,sortFns:m,sortedRowModel:h,tableMeta:g,..._}=e.features,v={_cellInstanceInitFns:[],_columnInstanceInitFns:[],_features:{...sQ,..._},_headerGroupInstanceInitFns:[],_headerInstanceInitFns:[],_reactivity:t,_rowInstanceInitFns:[],_rowModelFns:{aggregationFns:n,filterFns:l,sortFns:m},_rowModels:{},atoms:{},baseAtoms:{}},y=Object.values(v._features),b={...y.reduce((e,t)=>Object.assign(e,t.getDefaultTableOptions?.(v)),{}),...e};if(t.wrapExternalAtoms&&b.atoms)for(let[e,n]of Object.entries(b.atoms)){let r=n,i=t.createWritableAtom(r.get(),{debugName:`externalAtom/${e}`});b.atoms[e]=i;let a=!1,o=r.subscribe(e=>{a||i.set(e)}),s=i.subscribe(e=>{a=!0,r.set(e),a=!1});t.addSubscription(o),t.addSubscription(s)}t.createOptionsStore?(v.optionsStore=t.createWritableAtom(b,{debugName:`table/optionsStore`}),Object.defineProperty(v,"options",{configurable:!0,enumerable:!0,get(){return v.optionsStore.get()},set(e){v.optionsStore.set(()=>e)}})):v.options=b,v.initialState=lQ(v._features,v.options.initialState);let x=Object.keys(v.initialState);for(let e=0;e{let e=v.options,t=e.atoms?.[n],r=t?t.get():v.baseAtoms[n].get();if(t)return r;let i=e.state;if(i&&_X(i,n)){let e=i[n];return e===void 0?v.initialState[n]:e}return r},{debugName:`table/atoms/${n}`})}nQ(v),v.store=lX(t.createReadonlyAtom(()=>{let e={};for(let t=0;t{let i=e.getValue(r),a=n.getValue(r),o=t.resolveDataValue;return o&&(i=o(i),a=o(a)),t.sort(i,a,e,n,r)},e);return t}var pQ=fQ({resolveDataValue:e=>gQ(e).toLowerCase(),sort:(e,t)=>_Q(e,t)}),mQ=fQ({sort:(e,t)=>hQ(e,t)});function hQ(e,t){return e===t?0:e>t?1:-1}function gQ(e){return typeof e==`number`?isNaN(e)||e===1/0||e===-1/0?``:String(e):typeof e==`string`?e:``}function _Q(e,t){let n=0,r=0,i=e.length,a=t.length;for(;n=48&&e<=57}function yQ(e,t,n){let r=t+1;for(;ro)return 1;if(o>a)return-1}return o>s?1:s>o?-1:0}function xQ(e,t,n,r,i,a){let o=t;for(;oi?1:i>t?-1:0}let u=parseInt(e.slice(t,n),10),d=parseInt(r.slice(i,a),10);return u>d?1:d>u?-1:0}function SQ(e,t,n){let r=0;for(let i=t;i1)){r=`alphanumeric`;break}}if(!r&&i&&(r=`text`),r){let e=t?.[r];if(e||r===`alphanumeric`&&(e=t?.text),e)return e}return mQ}function kQ(e){let t=e.table.getFilteredRowModel().flatRows.slice(0,10);for(let n=0;n{let o=a.findIndex(t=>t.id===e.id),s=o===-1?void 0:a[o],c=[],l,u=i?t:r===`desc`,d=!!(a.length&&FQ(e)&&n);return l=d?s?`toggle`:`add`:s?`toggle`:`replace`,l===`toggle`&&(i||r||(l=`remove`)),l===`add`?(c=[...a,{id:e.id,desc:u}],c.splice(0,c.length-(e.table.options.maxMultiSortColCount??2**53-1))):c=l===`toggle`?d?a.map(t=>t.id===e.id?{...t,desc:u}:t):[{id:e.id,desc:u}]:l===`remove`?d?a.filter(t=>t.id!==e.id):[]:[{id:e.id,desc:u}],c})}function MQ(e){return e.columnDef.sortDescFirst??e.table.options.sortDescFirst??kQ(e)===`desc`?`desc`:`asc`}function NQ(e,t){let n=MQ(e),r=IQ(e);return r?r!==n&&(e.table.options.enableSortingRemoval??!0)&&(!t||(e.table.options.enableMultiRemove??!0))?!1:r===`desc`?`asc`:`desc`:n}function PQ(e){return(e.columnDef.enableSorting??!0)&&(e.table.options.enableSorting??!0)&&!!e.accessorFn}function FQ(e){return e.columnDef.enableMultiSort??e.table.options.enableMultiSort??!!e.accessorFn}function IQ(e){let t=e.table.atoms.sorting?.get()?.find(t=>t.id===e.id);return t?t.desc?`desc`:`asc`:!1}function LQ(e){return e.table.atoms.sorting?.get()?.findIndex(t=>t.id===e.id)??-1}function RQ(e){TQ(e.table,t=>t.length?t.filter(t=>t.id!==e.id):[])}function zQ(e){let t=PQ(e);return n=>{t&&jQ(e,void 0,FQ(e)?e.table.options.isMultiSortEvent?.(n):!1)}}var BQ={getInitialState(e){return{sorting:wQ(),...e}},getDefaultColumnDef(){return{sortFn:`auto`,sortUndefined:1}},getDefaultTableOptions(e){return{autoResetSorting:!1,onSortingChange:vX(`sorting`,e),isMultiSortEvent:e=>e.shiftKey}},assignColumnPrototype(e,t){MX(`rowSortingFeature`,e,t,{column_getAutoSortFn:{fn:e=>OQ(e)},column_getAutoSortDir:{fn:e=>kQ(e)},column_getSortFn:{fn:e=>AQ(e)},column_toggleSorting:{fn:(e,t,n)=>jQ(e,t,n)},column_getFirstSortDir:{fn:e=>MQ(e)},column_getNextSortingOrder:{fn:(e,t)=>NQ(e,t)},column_getCanSort:{fn:e=>PQ(e)},column_getCanMultiSort:{fn:e=>FQ(e)},column_getIsSorted:{fn:e=>IQ(e)},column_getSortIndex:{fn:e=>LQ(e)},column_clearSorting:{fn:e=>RQ(e)},column_getToggleSortingHandler:{fn:e=>zQ(e)}})},constructTableAPIs(e){jX(`rowSortingFeature`,e,{table_autoResetSorting:{fn:()=>DQ(e)},table_setSorting:{fn:t=>TQ(e,t)},table_resetSorting:{fn:t=>EQ(e,t)}})}};function VQ(){return e=>{let t=e;return kX({feature:`rowSortingFeature`,table:t,fnName:`table.getSortedRowModel`,memoDeps:()=>[t.atoms.sorting?.get(),t.getPreSortedRowModel()],fn:()=>HQ(t),onAfterUpdate:OX(()=>GX(t))})}}function HQ(e){let t=e.getPreSortedRowModel(),n=e.atoms.sorting?.get();if(!t.rows.length||!n?.length)return t;let r=[],i=n.filter(t=>{let n=e.getColumn(t.id);return n?PQ(n):!1});if(!i.length)return t;let a=[];for(let t=0;t{for(let n=0;n{let t=e.slice();t.sort(o);let n=!1;for(let i=0;i`u`?V.useEffect:V.useLayoutEffect;function WQ(e,t){let[{table:n,rootSource:r}]=(0,V.useState)(()=>{let t=uQ({...e,features:{coreReactivityFeature:fX(),...e.features}});return t.Subscribe=(e=>cX({...e,source:e.source??t.store})),t.FlexRender=sX,{table:t,rootSource:dX(t.store,Pt)}}),i=n;oQ(i,t=>({...t,...e}),{syncExternalState:!1});let a=i.options.state,o=r.get(),s=lt(r,t,{compare:Pt});return UQ(()=>{r.markCommitted(o),rQ(i,a??null,Pt)}),(0,V.useMemo)(()=>({...n,options:e,state:s}),[n,e,s])}function GQ(e,t,n,r,i,a){e.format===`status`&&e.unit&&typeof t==`string`&&t.trim()!==``&&Number.isFinite(Number(t))&&(t=Number(t));let o=t===null?`—`:String(t),s={kind:e.format,text:o};if([`unit`,`bar`,`status`,`sparkline`].includes(e.format)&&(s.text=typeof t==`number`?va(e.unit,t):o),e.format===`bar`&&(s.fraction=typeof t==`number`&&n>0?Math.max(0,Math.min(1,t/n)):0),e.format===`status`&&typeof t==`number`&&(s.status=to(Number.isFinite(t)?t:null,r?.thresholds,r?.better??i)),e.format===`service_link`&&(s.variable=e.variable),e.format===`sparkline`&&a)return s.points=a.slice(0,240),s;if(e.format===`sparkline`)try{let e=JSON.parse(o);Array.isArray(e)?s.points=e.slice(0,240).map(e=>typeof e==`number`&&Number.isFinite(e)?e:null):s.unsupported=`Sparkline requires an array column`}catch{s.unsupported=`Sparkline requires an array column`}return s}function KQ({text:e,template:t=!1,highlight:n=``}){let r=it(`light`)===`dark`,i=_t[r?5:7],a=[1,3,5].map(e=>parseInt(i.slice(e,e+2),16)).join(`, `),o=[];if(n){let t=e.toLowerCase(),r=n.toLowerCase();for(let e=t.indexOf(r);e!==-1;e=t.indexOf(r,e+r.length))o.push(e)}let s=(t,i)=>{let s=[],c=t;for(let l of o){let o=Math.max(t,l),u=Math.min(i,l+n.length);o>=u||(s.push(e.slice(c,o),(0,H.jsx)(`mark`,{"data-highlight-match":!0,style:{background:`rgba(${a}, ${r?.22:.3})`,color:`inherit`,borderRadius:3,padding:`0 2px`},children:e.slice(o,u)},o)),c=u)}return s.push(e.slice(c,i)),s},c=[],l=0;if(t)for(let t of e.matchAll(/<\*>||||