From e98d6858a8ba520859ee43c481d1e6dba27b612e Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Thu, 22 Oct 2026 13:00:35 +0200 Subject: [PATCH 001/203] Stop rebuilding the production image from scratch in CI The image job took ~66 min because CI almost never found a prebuilt image: local sign-off built it emulated (slow, and it crashed the local Docker), and the fourmolu bot ran a different version than laptops, so it rewrote signed-off trees and changed the image's tree fingerprint. When CI did build, the dist-newstyle cache mount died with the runner. - Default the image builder to the native amd64 builder when it exists. - Pin fourmolu in the Makefile for both laptops and the bot; sign-off and ship refuse an unformatted tree. - Carry dist-newstyle across runners via the Actions cache (master saves, PRs restore read-only). --- .github/workflows/fourmolu.yml | 16 +++------------- .github/workflows/production-image.yml | 21 +++++++++++++++++++++ Makefile | 25 ++++++++++++++++++++----- scripts/ci/ci.sh | 10 ++++++---- 4 files changed, 50 insertions(+), 22 deletions(-) diff --git a/.github/workflows/fourmolu.yml b/.github/workflows/fourmolu.yml index bb898dd04..d16db65c7 100644 --- a/.github/workflows/fourmolu.yml +++ b/.github/workflows/fourmolu.yml @@ -18,22 +18,12 @@ jobs: with: token: ${{ secrets.GITHUB_TOKEN }} + # `make fmt` downloads the version the Makefile pins, so laptops and this bot agree. - name: Cache fourmolu - id: cache-fourmolu uses: actions/cache@v5 with: - path: ~/.local/bin/fourmolu - key: fourmolu-0.19.0.0 - - - name: Install fourmolu - if: steps.cache-fourmolu.outputs.cache-hit != 'true' - run: | - mkdir -p ~/.local/bin - curl -sL https://github.com/fourmolu/fourmolu/releases/download/v0.19.0.0/fourmolu-0.19.0.0-linux-x86_64 -o ~/.local/bin/fourmolu - chmod +x ~/.local/bin/fourmolu - - - name: Add fourmolu to PATH - run: echo "$HOME/.local/bin" >> $GITHUB_PATH + path: .ci/fourmolu-* + key: fourmolu-${{ hashFiles('Makefile') }} - name: Format code run: make fmt diff --git a/.github/workflows/production-image.yml b/.github/workflows/production-image.yml index 34103cc0f..d9ea91202 100644 --- a/.github/workflows/production-image.yml +++ b/.github/workflows/production-image.yml @@ -31,6 +31,27 @@ jobs: with: node-version: '22' - uses: docker/setup-buildx-action@v3 + # The Dockerfile's dist-newstyle cache mount dies with each fresh runner, so every + # build recompiled all of monoscope (~57 min). Carry it in the Actions cache: master + # saves, PRs restore master's and stay read-only so they can't evict it. Paths sit + # outside the checkout because release.sh refuses a dirty tree. + - if: github.ref == 'refs/heads/master' + uses: actions/cache@v5 + with: + path: ${{ runner.temp }}/dist-newstyle + key: prod-dist-${{ inputs.revision }} + restore-keys: prod-dist- + - if: github.ref != 'refs/heads/master' + uses: actions/cache/restore@v5 + with: + path: ${{ runner.temp }}/dist-newstyle + key: prod-dist-${{ inputs.revision }} + restore-keys: prod-dist- + - uses: reproducible-containers/buildkit-cache-dance@v3.4.0 + with: + cache-map: '{"${{ runner.temp }}/dist-newstyle": {"target": "/build/dist-newstyle", "id": "monoscope-production-dist-locked-v1"}}' + scratch-dir: ${{ runner.temp }}/cache-dance-scratch + skip-extraction: ${{ github.ref != 'refs/heads/master' }} - uses: docker/login-action@v4 with: registry: ghcr.io diff --git a/Makefile b/Makefile index 8942790b1..5ebdb3fd0 100644 --- a/Makefile +++ b/Makefile @@ -226,8 +226,23 @@ live-test-unit: live-reload-doctests: ghcid --command 'cabal repl lib:monoscope --no-semaphore --with-compiler=$(GHC)' --test ':! cabal test monoscope:doctests --ghc-options="-O0" --test-show-details=streaming' $(RELOAD_ENV) -fmt: - fourmolu --mode inplace $$(find ./src/ ./shared/ ./cli/ -name '*.hs') +# One pinned fourmolu for laptops and the fourmolu workflow: a different version +# reformats nearly every file, so the bot rewrote signed-off trees and the +# prebuilt deploy image (keyed on the tree) never matched. +FOURMOLU_VERSION := 0.19.0.0 +FOURMOLU := .ci/fourmolu-$(FOURMOLU_VERSION) +HS_FILES = $$(find ./src/ ./shared/ ./cli/ -name '*.hs') + +$(FOURMOLU): + @mkdir -p $(@D) + curl -fsSL https://github.com/fourmolu/fourmolu/releases/download/v$(FOURMOLU_VERSION)/fourmolu-$(FOURMOLU_VERSION)-$(OS)-$(shell uname -m) -o $@.tmp + chmod +x $@.tmp && mv $@.tmp $@ + +fmt: $(FOURMOLU) + $(FOURMOLU) --mode inplace $(HS_FILES) + +fmt-check: $(FOURMOLU) + @$(FOURMOLU) --mode check $(HS_FILES) >/dev/null 2>&1 || { echo "── not fourmolu-formatted: run \`make fmt\` and commit (CI would rewrite the tree)"; exit 1; } fix-imports: fix-imports $$(find ./src -name '*.hs') <$$(find ./src -name '*.hs') @@ -442,7 +457,7 @@ ci: # Run local checks, publish passing results, then show what GitHub still needs. # A committed, clean tree also gets its deploy image, built alongside the checks so # `make ship` only has to deploy it. -ci-signoff: +ci-signoff: fmt-check @result=0; image_pid=''; mkdir -p .ci; \ if [ -z "$$(git status --porcelain)" ]; then \ ./scripts/ci/ci.sh image > .ci/image.log 2>&1 & image_pid=$$!; \ @@ -484,7 +499,7 @@ deploy-image: # # make ship # everything # make ship CHECKS="build doctests unit-tests cli-tests" -ship: +ship: fmt-check ./scripts/ci/ci.sh ship $(CHECKS) # Deploy the current master image; rollback requires an explicit target. @@ -541,4 +556,4 @@ builder-rm: .PHONY: ci ci-signoff ci-status ci-shell ci-down ci-clean ci-selftest deploy-image ship kafka-topics deploy-app rollback-app deploy-status builder-setup builder-status builder-rm tf-image -.PHONY: all test fmt lint fix-lint live-reload kill-live-reload live-reload-cli live-reload-doctests live-test-dev tmux-live-test-dev build-chart-cli build-chart-cli-linux tmux-live-reload tmux-live-reload-cli tmux-pin-here tmux-unpin kill-web-components-watch web-components-watch e2e-install test-e2e test-e2e-real test-e2e-ui gen-proto sync-otel-proto update-otel-proto minio-local timefusion-start timefusion-stop test-integration-tf +.PHONY: all test fmt fmt-check lint fix-lint live-reload kill-live-reload live-reload-cli live-reload-doctests live-test-dev tmux-live-test-dev build-chart-cli build-chart-cli-linux tmux-live-reload tmux-live-reload-cli tmux-pin-here tmux-unpin kill-web-components-watch web-components-watch e2e-install test-e2e test-e2e-real test-e2e-ui gen-proto sync-otel-proto update-otel-proto minio-local timefusion-start timefusion-stop test-integration-tf diff --git a/scripts/ci/ci.sh b/scripts/ci/ci.sh index bcb73530f..63c672bcf 100755 --- a/scripts/ci/ci.sh +++ b/scripts/ci/ci.sh @@ -757,10 +757,12 @@ IMAGE=${MONOSCOPE_IMAGE:-ghcr.io/monoscope-tech/monoscope} # the habit this whole file exists to kill. A BUILDER naming a native amd64 # buildx endpoint removes the emulation instead of tolerating it. # -# Deploy images build on this machine by default (Rosetta-emulated on Apple Silicon, with -# BuildKit's cache kept here). MONOSCOPE_BUILDER=monoscope-amd64 opts into the native -# builder `make builder-setup` creates over SSH — that host is production. -BUILDER=${MONOSCOPE_BUILDER:-} +# Deploy images build on the native builder `make builder-setup` creates over SSH when it +# exists (that host is production; the builder container is capped by builder-setup), else +# on this machine. Emulated builds took long enough — and crashed Docker Desktop/OrbStack +# often enough — that sign-off rarely produced an image and CI rebuilt it from scratch +# (~1h). MONOSCOPE_BUILDER= (empty) forces a local build. +BUILDER=${MONOSCOPE_BUILDER-monoscope-amd64} # A TimeFusion image built for this machine's own architecture. `make tf-image` # produces it; cmd_local picks it up on its own. From 524eb1ddf98f7342e72aab72a723e9af5ae83270 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Sun, 25 Oct 2026 04:03:40 +0200 Subject: [PATCH 002/203] Fold Real User Monitoring into the RUM dashboard and the Explorer (#695) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Fold Real User Monitoring into the RUM dashboard and the Explorer sessions view The /rum page duplicated what rum.yaml and the Explorer already do, and the two had drifted: the template filtered on telemetry.sdk.language, which no browser SDK sets, so it showed nothing in production. - rum.yaml carries the page's browser/page-view/error predicates verbatim (so TimeFusion rollups still serve them), route-masked top pages, sessions, errors, a single-scan audience table, and Web Vitals P75 read from histogram buckets in portable SQL (Postgres and TimeFusion), never the export mean. - Tables gain hidden columns and link placeholders for every row field and the dashboard's time range; table cards render their call-to-action link. - /rum opens the dashboard; /rum/sessions opens the Explorer sessions view over browser telemetry, from the sidebar and the dashboard alike. - Deleted the page, its model, caches, CSS, specs and e2e; withSharedCache moves to Pkg.QueryCache for Endpoints. * Keep /rum/dashboard as an alias of the RUM dashboard entrypoint * Read unset dashboard variables as empty; fold the sessions header's service scan into the session grouping An unset {{var-*}} stayed literal in widget queries, so the RUM dashboard's "no application selected" branch never matched and every widget read zero on a first visit. replacePlaceholders now empties an unset dashboard variable. The Explorer sessions view forked a second full-window scan just to count services for its header; aggregating each session's services in the session scan costs ~5% of it (4.0s vs 4.2s on prod demo, 24h), and the page context query no longer needs its own service list. * Let dashboard tables explain themselves on hover Columns gain a header description and a per-cell tooltip templated over the row, both through the body-wide tippy handler long cells already use. The RUM dashboard spells out every Web Vital abbreviation, P75, the known range and its other terms. * Restore what the RUM page showed beyond the dashboard - Web Vitals with nothing in the window get a row saying so instead of vanishing; thresholds and descriptions live in one VALUES table. - Mixed histogram bucket layouts (the browser SDK moving to threshold-aligned buckets) coarsen to the edges every point shares: each point's cumulative count is summed per edge, which is exact there, instead of interleaving bucket counts from different layouts. - Screen recordings whose spans never arrived join the Explorer sessions view again when it is unfiltered or browser-scoped, with their Replay action; they carry no attributes, so any other filter or scope leaves them out. * Load browser SDK 0.13.0 for Monoscope's own telemetry 0.13.0 exports web vitals as DELTA histograms with threshold-aligned buckets, so the RUM dashboard can rate CLS and the other vitals from their P75 bucket. Replaces the vendored 0.11.6 bundle. * Address review: template-only variable clearing, one predicate source, tested redirects - fillQueryTemplate clears unset {{var-*}} in a dashboard query template before substitution, so a substituted (telemetry-controlled) value is never rewritten; replacePlaceholders is back to plain substitution for links and tooltips. It is the one entry point for chart, logs-widget, variable and constant templates. - RUM's predicates are built-in placeholders ({{browser_filter}}, {{pageview_filter}}, {{error_filter}}, {{browser_kql}}) from Pkg.Parser, so rum.yaml, endpoint-stats.yaml and the Explorer link cannot drift; a test pins that the SQL and KQL forms select the same rows. - /rum, /rum/dashboard and /rum/sessions are one route; links shared from the old page (?tab=sessions&session=…) open that session; unknown paths 404. Links keep the window via timeScopedUrl / TimePicker.rangeQuery. - Recording-only sessions are decided inside fetchSessions from the parsed query. - KQL embedded from SQL strips backslashes as well as quotes; cell tooltips carry aria-description. - Tests for every Web Vitals rating branch, the redirects and withSharedCache miss/hit/expiry. * Parse endpoint widgets with the real browser filter in the template test --- e2e/playwright.config.ts | 4 +- e2e/tests/rum-sessions.spec.ts | 893 -------- e2e/tests/sidebar-navigation.spec.ts | 2 +- monoscope.cabal | 28 +- package.yaml | 2 + src/Models/Apis/LogQueries.hs | 109 +- src/Models/Projects/Dashboards.hs | 4 +- src/Models/Telemetry/RUM.hs | 603 ----- src/Pages/BodyWrapper.hs | 4 +- src/Pages/Charts/Charts.hs | 10 +- src/Pages/Components.hs | 15 +- src/Pages/Dashboards.hs | 29 +- src/Pages/Endpoints.hs | 4 +- src/Pages/Issues.hs | 2 +- src/Pages/RealUserMonitoring.hs | 1959 ----------------- src/Pkg/Components/TimePicker.hs | 2 +- src/Pkg/Components/Widget.hs | 53 +- src/Pkg/Parser.hs | 34 +- src/Pkg/QueryCache.hs | 21 +- src/Pkg/TestUtils.hs | 4 - src/System/Config.hs | 12 - src/Utils.hs | 12 + src/Web/Routes.hs | 7 +- static/public/assets/css/tailwind.css | 57 - ...-0.11.6.min.js => monoscope-0.13.0.min.js} | 4 +- static/public/dashboards/endpoint-stats.yaml | 16 +- static/public/dashboards/rum.yaml | 458 ++-- .../integration/Pages/DashboardWidgetsSpec.hs | 103 +- test/integration/Pages/LogExplorer/LogSpec.hs | 12 + test/integration/Pages/QueryCacheSpec.hs | 10 + .../Pages/RealUserMonitoringSpec.hs | 1114 ---------- test/unit/Models/DashboardTemplatesSpec.hs | 15 +- web-components/src/widgets.ts | 3 +- 33 files changed, 655 insertions(+), 4950 deletions(-) delete mode 100644 e2e/tests/rum-sessions.spec.ts delete mode 100644 src/Models/Telemetry/RUM.hs delete mode 100644 src/Pages/RealUserMonitoring.hs rename static/public/assets/deps/monoscope/{monoscope-0.11.6.min.js => monoscope-0.13.0.min.js} (82%) delete mode 100644 test/integration/Pages/RealUserMonitoringSpec.hs diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts index 76aaf3512..2adc7700c 100644 --- a/e2e/playwright.config.ts +++ b/e2e/playwright.config.ts @@ -18,7 +18,7 @@ export default defineConfig({ trace: "on-first-retry", }, projects: [ - { name: "chromium", use: { ...devices["Desktop Chrome"] }, testIgnore: /(container-identity|endpoint-analytics|host-map|infrastructure-time-window|metric-exemplars|metrics-catalog|rum-sessions|tabs)\.spec\.ts$/ }, - { name: "chromium-fixtures", use: { ...devices["Desktop Chrome"] }, testMatch: /(container-identity|endpoint-analytics|host-map|infrastructure-time-window|metric-exemplars|metrics-catalog|rum-sessions|tabs)\.spec\.ts$/, dependencies: ["chromium"], workers: 1 }, + { name: "chromium", use: { ...devices["Desktop Chrome"] }, testIgnore: /(container-identity|endpoint-analytics|host-map|infrastructure-time-window|metric-exemplars|metrics-catalog|tabs)\.spec\.ts$/ }, + { name: "chromium-fixtures", use: { ...devices["Desktop Chrome"] }, testMatch: /(container-identity|endpoint-analytics|host-map|infrastructure-time-window|metric-exemplars|metrics-catalog|tabs)\.spec\.ts$/, dependencies: ["chromium"], workers: 1 }, ], }); diff --git a/e2e/tests/rum-sessions.spec.ts b/e2e/tests/rum-sessions.spec.ts deleted file mode 100644 index 8029f1383..000000000 --- a/e2e/tests/rum-sessions.spec.ts +++ /dev/null @@ -1,893 +0,0 @@ -import { test, expect, type Page } from "@playwright/test"; -import { DEMO_PROJECT, sql } from "./helpers"; - -const fixtureUser = `e2e-session-fixture-${Date.now()}`; -const clearSessions = `DELETE FROM projects.replay_sessions WHERE project_id = '${DEMO_PROJECT}' AND session_id::text LIKE 'ec2e0000-0000-4000-8000-%'`; - -const refreshSessionList = (page: Page) => page.evaluate(() => new Promise(resolve => { - const settled = (event: Event) => { - if ((event.target as HTMLElement).id !== "rum-sessions-list") return; - document.removeEventListener("htmx:after:settle", settled); - resolve(); - }; - document.addEventListener("htmx:after:settle", settled); - window.dispatchEvent(new Event("update-query")); -})); - -// scripts/e2e.sh supplies the isolated server URL; local browser probes use existing data. -test.beforeAll(() => { - if (!process.env.E2E_BASE_URL) return; - sql(`${clearSessions}; - INSERT INTO projects.replay_sessions (session_id, project_id, created_at, last_event_at, event_file_count, user_name, user_id) - SELECT ('ec2e0000-0000-4000-8000-' || lpad(i::text, 12, '0'))::uuid, '${DEMO_PROJECT}', - now() - interval '30 seconds' - i * interval '1 second', now() - i * interval '1 second', - 1, 'Demo shopper ' || lpad(i::text, 8, '0'), '${fixtureUser}' FROM generate_series(1, 200) AS i`); -}); - -test.afterAll(() => { - if (process.env.E2E_BASE_URL) sql(clearSessions); -}); - -test("desktop session list keeps session identities readable", async ({ page }) => { - await page.setViewportSize({ width: 1440, height: 900 }); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=sessions`); - const identity = page.locator(".rum-session-link").first(); - await expect(identity).toBeVisible(); - expect(await identity.evaluate(element => { - const text = document.createRange(); - text.selectNodeContents(element); - return text.getBoundingClientRect().width <= element.getBoundingClientRect().width; - })).toBe(true); -}); - -test("live session refresh preserves keyboard focus and list scroll", async ({ page }) => { - await page.setViewportSize({ width: 1440, height: 900 }); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=sessions${process.env.E2E_BASE_URL ? `&q=${fixtureUser}` : ""}`); - const list = page.locator("#rum-sessions-list"); - const session = list.locator(".rum-session-link").nth(50); - await expect(session).toBeAttached(); - await expect(list.locator('[hx-get*="refresh=1"]')).toHaveCount(0); - if (process.env.E2E_BASE_URL) await expect(list.getByText("200 active now", { exact: true })).toBeVisible(); - await page.evaluate(() => document.fonts.ready); - await session.scrollIntoViewIfNeeded(); - await session.focus(); - const sessionId = await session.getAttribute("data-session-id"); - const scrollTop = await list.evaluate(element => element.scrollTop); - expect(scrollTop).toBeGreaterThan(0); - await refreshSessionList(page); - await expect(list.locator(`.rum-session-link[data-session-id="${sessionId}"]`)).toBeFocused(); - expect(Math.abs(await list.evaluate(element => element.scrollTop) - scrollTop)).toBeLessThanOrEqual(1); -}); - -test("mobile session list keeps the replay workspace within reach", async ({ page }) => { - await page.setViewportSize({ width: 390, height: 844 }); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=sessions`); - const list = page.locator("#rum-sessions-list"); - await expect(list.locator(".rum-session-link").first()).toBeVisible(); - const workspace = page.locator("#rum-replay-workspace"); - await expect.poll(() => workspace.evaluate(element => element.getBoundingClientRect().top)).toBeLessThan(844); - expect(await list.evaluate(element => element.scrollHeight > element.clientHeight)).toBe(true); - await list.locator(".rum-session-link").first().click(); - await expect(workspace.getByRole("link", { name: "Inspect telemetry" })).toBeVisible(); -}); - -test("selecting a session does not wait for a full list response", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=sessions&since=1H&filter=replays&q=${fixtureUser}`); - const list = page.locator("#rum-sessions-list"); - const session = list.locator(".rum-session-link").first(); - await expect(session).toBeVisible(); - await page.locator("[data-time-transport]").getByRole("button", { name: /^Pause live (data|updates)$/ }).click(); - await expect(page.locator("[data-time-transport]")).toHaveAttribute("data-interval", "0"); - const sid = await session.getAttribute("data-session-id"); - await list.evaluate(element => element.setAttribute("data-e2e-preserved", "true")); - let fullListRequests = 0; - let release!: () => void; - const held = new Promise(resolve => { release = resolve; }); - await page.route("**/rum?**", async route => { - const url = new URL(route.request().url()); - if (url.searchParams.get("session") !== sid || url.searchParams.get("panel") !== "sessions") return route.continue(); - fullListRequests++; - const response = await route.fetch(); - await held; - await route.fulfill({ response }); - }); - try { - await session.click(); - await expect(page.locator("#rum-replay-workspace session-replay")).toBeVisible(); - expect(fullListRequests).toBe(0); - await expect(list).toHaveAttribute("data-e2e-preserved", "true"); - await expect(session).toHaveAttribute("aria-current", "true"); - const url = new URL(page.url()); - for (const [key, value] of Object.entries({ session: sid, q: fixtureUser, filter: "replays", since: "1H" })) expect(url.searchParams.get(key)).toBe(value); - for (const key of ["panel", "deferred", "refresh"]) expect(url.searchParams.has(key)).toBe(false); - } finally { - release(); - await page.unrouteAll({ behavior: "wait" }); - } -}); - -test("session search survives filter changes and keeps the replay workspace", async ({ page }) => { - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=sessions`); - const search = page.getByRole("searchbox", { name: "Search sessions" }); - const filters = page.getByRole("navigation", { name: "Filter sessions" }); - await expect(filters).toBeVisible(); - await page.keyboard.press("/"); - await expect(search).toBeFocused(); - const searchResponse = page.waitForResponse(r => { - const url = new URL(r.url()); - return url.pathname.endsWith("/rum") && url.searchParams.get("q") === "e2e-missing-session"; - }); - await search.fill("e2e-missing-session"); - expect((await searchResponse).status()).toBe(200); - await expect(page.getByText("No sessions match this filter", { exact: true })).toBeVisible(); - const workspace = page.locator("#rum-replay-workspace"); - await expect(workspace).toBeVisible(); - await workspace.evaluate(element => element.setAttribute("data-e2e-preserved", "true")); - for (const [label, filter] of [["With errors", "errors"], ["With replay", "replays"], ["All sessions", ""]]) { - const response = page.waitForResponse(r => { - const url = new URL(r.url()); - return url.pathname.endsWith("/rum") && url.searchParams.get("filter") === filter && url.searchParams.get("q") === "e2e-missing-session"; - }); - await filters.getByRole("link", { name: label, exact: true }).click(); - expect((await response).status()).toBe(200); - await expect(filters.getByRole("link", { name: label, exact: true })).toHaveAttribute("aria-current", "page"); - await expect(search).toHaveValue("e2e-missing-session"); - await expect(page.locator("#rum-session-filter")).toHaveValue(filter); - await expect(workspace).toHaveAttribute("data-e2e-preserved", "true"); - const refresh = page.waitForResponse(r => { - const url = new URL(r.url()); - return url.pathname.endsWith("/rum") && url.searchParams.get("panel") === "sessions" - && r.request().headers()["hx-source"] === "div#rum-panel-sessions"; - }); - await refreshSessionList(page); - const refreshedUrl = new URL((await refresh).url()); - expect(refreshedUrl.searchParams.get("q")).toBe("e2e-missing-session"); - expect(refreshedUrl.searchParams.get("filter") ?? "").toBe(filter); - await expect(filters.getByRole("link", { name: label, exact: true })).toHaveAttribute("aria-current", "page"); - await expect(page.getByText("No sessions match this filter", { exact: true })).toBeVisible(); - await expect(workspace).toHaveAttribute("data-e2e-preserved", "true"); - } -}); - -test("page links preserve regex query characters through Explorer preload", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const cleanup = `DELETE FROM otel_logs_and_spans WHERE project_id='${DEMO_PROJECT}' AND resource___deployment___environment___name='e2e-page-links'`; - sql(`${cleanup}; - INSERT INTO otel_logs_and_spans (project_id,summary,name,kind,timestamp,start_time,end_time,duration,attributes,resource, - attributes___url___full,resource___user_agent___original,resource___deployment___environment___name,context___trace_id,context___span_id) - SELECT '${DEMO_PROJECT}',ARRAY['documentLoad'],'documentLoad','span',now(),now(),now()+interval '10 milliseconds',10000000, - jsonb_build_object('url',jsonb_build_object('full',url)), - jsonb_build_object('user_agent',jsonb_build_object('original','Mozilla/5.0'),'deployment',jsonb_build_object('environment',jsonb_build_object('name','e2e-page-links'))), - url,'Mozilla/5.0','e2e-page-links',repeat('f',31)||i::text,repeat('f',15)||i::text - FROM unnest(ARRAY['https://shop.example/cart&ready','https://shop.example/cart&ready?q=x','https://shop.example/cart&ready#section', - 'https://shop.example/cart&ready-later','https://shop.example/Cart&ready','https://shop.example/other/cart&ready','https://shop.example/search?q=/cart&ready']) WITH ORDINALITY AS paths(url,i)`); - try { - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=performance&since=1H&environment=e2e-page-links`); - const link = page.locator("#rum-panel-pages").getByRole("link", { name: "/cart&ready", exact: true }); - await expect(link).toBeVisible(); - const query = new URL((await link.getAttribute("href"))!, page.url()).searchParams.get("query"); - const preload = page.waitForResponse(r => new URL(r.url()).pathname.endsWith("/log_explorer/data")); - await link.click(); - const response = await preload; - expect(new URL(response.url()).searchParams.get("query")).toBe(query); - const events = await response.json(); - expect(events.error).toBeUndefined(); - expect(events.queryResultCount).toBe(3); - await expect(page.locator("#resultTable [data-row-id]")).toHaveCount(3); - } finally { - sql(cleanup); - } -}); - -test("session time changes survive live refresh, search, filters and reload", async ({ page, context }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const cleanup = `DELETE FROM otel_logs_and_spans WHERE project_id='${DEMO_PROJECT}' AND resource___deployment___environment___name='e2e-session-search'`; - sql(`${cleanup}; - INSERT INTO otel_logs_and_spans (project_id,summary,name,kind,timestamp,start_time,end_time,duration,attributes,resource, - attributes___session___id,resource___telemetry___sdk___language,resource___service___name,resource___deployment___environment___name) - SELECT '${DEMO_PROJECT}',ARRAY['documentLoad'],'documentLoad','span',now(),now(),now()+interval '10 milliseconds',10000000, - jsonb_build_object('session',jsonb_build_object('id',sid),'url',jsonb_build_object('path','/scoped-session-proof')), - jsonb_build_object('telemetry',jsonb_build_object('sdk',jsonb_build_object('language','webjs')),'service',jsonb_build_object('name',svc), - 'deployment',jsonb_build_object('environment',jsonb_build_object('name','e2e-session-search'))), - sid,'webjs',svc,'e2e-session-search' - FROM (VALUES ('ec2e0000-0000-4000-8000-000000000001','e2e-session-search'), - ('ec2e0000-0000-4000-8000-000000000002','other-service')) AS scopes(sid,svc)`); - try { - const initialPanel = page.waitForResponse(r => { - const url = new URL(r.url()); - return url.pathname.endsWith("/rum") && url.searchParams.get("panel") === "sessions" - && r.request().headers()["hx-source"] === "div#rum-panel-sessions"; - }); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=sessions&since=1H&environment=e2e-session-search&service_scope=e2e-session-search`); - const initialUrl = new URL((await initialPanel).url()); - expect(initialUrl.searchParams.get("service_scope")).toBe("e2e-session-search"); - await expect(page.locator(".rum-session-link")).toHaveCount(1); - await page.locator(".rum-session-link").click(); - const workspace = page.locator("#rum-replay-workspace"); - await expect(workspace.locator("session-replay")).toBeVisible(); - await page.waitForURL(url => url.searchParams.has("session")); - const session = new URL(page.url()).searchParams.get("session"); - const changedWindow = page.waitForResponse(r => r.request().headers()["hx-source"] === "div#rum-panel-sessions"); - await page.locator("[data-live-range]").click(); - await page.locator('#n-timepicker-popover button[data-value="24H"]').click(); - expect(new URL((await changedWindow).url()).searchParams.get("since")).toBe("24H"); - await expect(page.locator("#n-currentRange")).toHaveText("Last 24 hours"); - await page.getByRole("link", { name: "With replay", exact: true }).click(); - await expect(page.getByRole("link", { name: "With replay", exact: true })).toHaveAttribute("aria-current", "page"); - await page.waitForURL(url => url.searchParams.get("filter") === "replays"); - const query = "e2e missing session + % &"; - const response = page.waitForResponse(r => { - const url = new URL(r.url()); - return url.pathname.endsWith("/rum") && url.searchParams.get("q") === query - && r.request().headers()["hx-source"] === "form#rum-session-search-form"; - }); - await page.getByRole("searchbox", { name: "Search sessions" }).fill(query); - await response; - await expect(page.getByText("No sessions match this filter", { exact: true })).toBeVisible(); - await page.waitForURL(url => url.searchParams.get("q") === query); - await page.getByRole("link", { name: "All sessions", exact: true }).click(); - await expect(page.getByRole("link", { name: "All sessions", exact: true })).toHaveAttribute("aria-current", "page"); - await page.waitForURL(url => !url.searchParams.has("filter")); - const url = new URL(page.url()); - for (const [key, value] of Object.entries({q:query, session, since:"24H", environment:"e2e-session-search", service_scope:"e2e-session-search"})) { - expect(url.searchParams.get(key)).toBe(value); - } - expect(url.searchParams.get("filter") ?? "").toBe(""); - for (const parameter of ["panel", "deferred", "refresh"]) expect(url.searchParams.has(parameter)).toBe(false); - await page.reload(); - await expect(page.getByRole("searchbox", { name: "Search sessions" })).toHaveValue(query); - await expect(page.getByText("No sessions match this filter", { exact: true })).toBeVisible(); - await expect(workspace.locator("session-replay")).toBeVisible(); - const shared = await context.newPage(); - await shared.goto(url.toString()); - await expect(shared.getByRole("searchbox", { name: "Search sessions" })).toHaveValue(query); - await expect(shared.getByText("No sessions match this filter", { exact: true })).toBeVisible(); - await expect(shared.locator("#rum-replay-workspace session-replay")).toBeVisible(); - await page.goBack(); - await expect(page.getByRole("searchbox", { name: "Search sessions" })).toHaveValue(query); - await expect(page.getByRole("link", { name: "With replay", exact: true })).toHaveAttribute("aria-current", "page"); - await page.goBack(); - await expect(page.getByRole("searchbox", { name: "Search sessions" })).toHaveValue(""); - await expect(page.getByRole("link", { name: "All sessions", exact: true })).toHaveAttribute("aria-current", "page"); - await expect(workspace.locator("session-replay")).toBeVisible(); - const historicalResponse = page.waitForResponse(r => r.request().headers()["hx-source"] === "div#rum-panel-sessions"); - await page.getByRole("button", { name: "Previous time window", exact: true }).first().click(); - const historical = new URL(page.url()); - const historicalRequest = new URL((await historicalResponse).url()); - for (const key of ["from", "to"]) { - expect(historical.searchParams.get(key)).toBeTruthy(); - expect(historicalRequest.searchParams.get(key)).toBe(historical.searchParams.get(key)); - } - expect(historicalRequest.searchParams.get("since") ?? "").toBe(""); - await page.getByRole("searchbox", { name: "Search sessions" }).fill("historical missing session"); - await page.waitForURL(url => url.searchParams.get("q") === "historical missing session"); - for (const key of ["from", "to", "session", "environment", "service_scope"]) { - expect(new URL(page.url()).searchParams.get(key)).toBe(historical.searchParams.get(key)); - } - expect(new URL(page.url()).searchParams.get("since") ?? "").toBe(""); - await page.reload(); - await expect(page.getByRole("searchbox", { name: "Search sessions" })).toHaveValue("historical missing session"); - for (const key of ["from", "to"]) expect(new URL(page.url()).searchParams.get(key)).toBe(historical.searchParams.get(key)); - } finally { - sql(cleanup); - } -}); - -test("Overview counts a session once when its events span chart intervals", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const scope = `e2e-overview-session-${Date.now()}`; - const cleanup = `DELETE FROM otel_logs_and_spans WHERE project_id='${DEMO_PROJECT}' AND resource___deployment___environment___name='${scope}'`; - sql(`${cleanup}; - INSERT INTO otel_logs_and_spans (project_id,summary,name,kind,timestamp,start_time,end_time,duration,attributes,resource, - attributes___session___id,resource___telemetry___sdk___language,resource___service___name,resource___deployment___environment___name) - SELECT '${DEMO_PROJECT}',ARRAY['documentLoad'],'documentLoad','span',at,at,at+interval '10 milliseconds',10000000, - jsonb_build_object('session',jsonb_build_object('id','overview-shared-session'),'url',jsonb_build_object('path','/overview-count')), - jsonb_build_object('telemetry',jsonb_build_object('sdk',jsonb_build_object('language','webjs')),'service',jsonb_build_object('name','${scope}'), - 'deployment',jsonb_build_object('environment',jsonb_build_object('name','${scope}'))), - 'overview-shared-session','webjs','${scope}','${scope}' - FROM (VALUES (now()-interval '40 minutes'),(now()-interval '10 minutes')) AS events(at)`); - try { - await page.goto(`/p/${DEMO_PROJECT}/rum?since=1H&environment=${scope}&service_scope=${scope}`); - await expect(page.locator("#rum-stat-pageviewsValue")).toHaveText("2 views"); - await expect(page.locator("#rum-stat-p75Value")).toHaveText("10.0ms"); - await expect(page.locator("#rum-stat-sessionsValue")).toHaveText("1 sessions"); - } finally { - sql(cleanup); - } -}); - -test("Overview does not prewarm hidden Performance panels while visible panels load", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const scope = `e2e-overview-prewarm-${Date.now()}`; - const cleanup = `DELETE FROM otel_logs_and_spans WHERE project_id='${DEMO_PROJECT}' AND resource___service___name='${scope}'; DELETE FROM otel_metrics WHERE project_id='${DEMO_PROJECT}' AND resource___service___name='${scope}'`; - sql(`INSERT INTO otel_logs_and_spans (project_id,summary,name,kind,timestamp,start_time,end_time,duration,attributes,resource, - attributes___url___path,resource___telemetry___sdk___language,resource___service___name) - VALUES('${DEMO_PROJECT}',ARRAY['documentLoad'],'documentLoad','span',now()-interval '10 seconds',now()-interval '10 seconds',now(),10000000, - '{"url":{"path":"/overview-visible"}}',jsonb_build_object('service',jsonb_build_object('name','${scope}')),'/overview-visible','webjs','${scope}'); - INSERT INTO otel_metrics (project_id,id,series_id,timestamp,metric_name,metric_type,metric_unit,value,resource,resource___service___name) - VALUES('${DEMO_PROJECT}',gen_random_uuid(),'${scope}',now()-interval '10 seconds','browser.web_vital.fcp','GAUGE','ms',22.5, - jsonb_build_object('service',jsonb_build_object('name','${scope}')),'${scope}')`); - let release = () => {}; - const held = new Promise(resolve => { release = resolve; }); - const hiddenRequests: string[] = []; - page.on("request", request => { - const params = new URL(request.url()).searchParams; - if (params.get("tab") === "performance" && params.has("panel")) hiddenRequests.push(request.url()); - }); - await page.route("**/rum?**", async route => { - if (new URL(route.request().url()).searchParams.get("panel") !== "pages") return route.continue(); - const response = await route.fetch(); - await held; - await route.fulfill({ response }); - }); - try { - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=overview&since=24H&service_scope=${scope}`); - await expect(page.locator("#rum-stat-pageviewsValue")).toHaveText("1 views"); - await expect(page.locator("#rum-panel-vitals")).toContainText("22.5 ms"); - // Observe the existing eight-second prewarm boundary while a real visible response is held. - await page.evaluate(() => new Promise(resolve => setTimeout(resolve, 8500))); - await expect(page.locator("#rum-panel-pages")).toHaveAttribute("data-deferred-shell", ""); - expect(hiddenRequests).toEqual([]); - release(); - await expect(page.locator("#rum-panel-pages")).toContainText("/overview-visible"); - await page.unrouteAll({ behavior: "wait" }); - await page.getByRole("link", { name: "Performance", exact: true }).click(); - await expect(page.locator("#rum-panel-vitals")).toContainText("22.5 ms"); - } finally { - release(); - try { await page.unrouteAll({ behavior: "wait" }); } finally { sql(cleanup); } - } -}); - -test("Overview keeps its loaded values during refresh after the first browser event arrives", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const scope = `e2e-overview-live-${Date.now()}`; - const cleanup = `DELETE FROM otel_logs_and_spans WHERE project_id='${DEMO_PROJECT}' AND resource___deployment___environment___name='${scope}'`; - let release = () => {}; - const pending = new Promise(resolve => { release = resolve; }); - const refreshPulse = () => page.evaluate(() => new Promise(resolve => { - const panel = document.getElementById("rum-panel-pulse"); - const reloadsPanel = panel?.matches("[hx-get], [data-hx-get]"); - const settled = (event: Event) => { - if ((event.target as HTMLElement).id !== "rum-panel-pulse") return; - document.removeEventListener("htmx:after:settle", settled); - resolve(); - }; - if (reloadsPanel) document.addEventListener("htmx:after:settle", settled); - window.dispatchEvent(new Event("update-query")); - if (!reloadsPanel) resolve(); - })); - try { - await page.goto(`/p/${DEMO_PROJECT}/rum?since=1H&environment=${scope}&service_scope=${scope}`); - await expect(page.getByText(`No browser telemetry for ${scope} in this range`, { exact: true })).toBeVisible(); - sql(`INSERT INTO otel_logs_and_spans (project_id,summary,name,kind,timestamp,start_time,end_time,duration,attributes,resource, - attributes___session___id,resource___telemetry___sdk___language,resource___service___name,resource___deployment___environment___name) - VALUES ('${DEMO_PROJECT}',ARRAY['documentLoad'],'documentLoad','span',now()-interval '10 seconds',now()-interval '10 seconds',now()-interval '10 seconds'+interval '10 milliseconds',10000000, - '{"session":{"id":"overview-first-event"},"url":{"path":"/first-event"}}', - '{"telemetry":{"sdk":{"language":"webjs"}},"service":{"name":"${scope}"},"deployment":{"environment":{"name":"${scope}"}}}', - 'overview-first-event','webjs','${scope}','${scope}')`); - await refreshPulse(); - const value = page.locator("#rum-stat-p75Value"); - await expect(value).toHaveText("10.0ms"); - await page.route("**/widget?**", async route => { - if (route.request().headers()["hx-source"] !== "div#rum-stat-p75_stat") return route.continue(); - const response = await route.fetch(); - await pending; - await route.fulfill({ response }); - }); - const requested = page.waitForRequest(request => request.headers()["hx-source"] === "div#rum-stat-p75_stat"); - const refreshed = refreshPulse(); - await requested; - await refreshed; - await expect(value).toHaveText("10.0ms"); - const recovered = page.waitForResponse(response => response.request().headers()["hx-source"] === "div#rum-stat-p75_stat"); - release(); - expect((await recovered).status()).toBe(200); - await page.unrouteAll({ behavior: "wait" }); - await expect(value).toHaveText("10.0ms"); - } finally { - release(); - await page.unrouteAll({ behavior: "wait" }); - sql(cleanup); - } -}); - -test("Performance and Overview panels use the current picker window", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const scope = `e2e-panel-window-${Date.now()}`; - const cleanup = `DELETE FROM otel_logs_and_spans WHERE project_id='${DEMO_PROJECT}' AND resource___service___name='${scope}'`; - sql(`INSERT INTO otel_logs_and_spans (project_id,summary,name,kind,timestamp,start_time,end_time,duration,attributes,resource, - attributes___url___path,resource___telemetry___sdk___language,resource___service___name,resource___deployment___environment___name) - SELECT '${DEMO_PROJECT}',ARRAY['documentLoad'],'documentLoad','span',at,at,at+interval '10 milliseconds',10000000, - '{"url":{"path":"/picker-window"}}', - jsonb_build_object('telemetry',jsonb_build_object('sdk',jsonb_build_object('language','webjs')), - 'service',jsonb_build_object('name','${scope}'),'deployment',jsonb_build_object('environment',jsonb_build_object('name','${scope}'))), - '/picker-window','webjs','${scope}','${scope}' FROM (VALUES(now()-interval '10 minutes'),(now()-interval '2 hours')) AS events(at)`); - let release = () => {}; - try { - for (const tab of ["performance", "overview"]) { - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=${tab}&since=1H&service_scope=${scope}&environment=${scope}`); - const row = page.locator("#rum-panel-pages tbody tr").filter({ has: page.getByRole("link", { name: "/picker-window", exact: true }) }); - await expect(row.locator("td").nth(1)).toHaveText("1"); - const changed = page.waitForResponse(response => response.request().headers()["hx-source"] === "div#rum-panel-pages"); - await page.locator("[data-live-range]").click(); - await page.locator('#n-timepicker-popover button[data-value="24H"]').click(); - const changedUrl = new URL((await changed).url()); - await expect(row.locator("td").nth(1)).toHaveText("2"); - expect(changedUrl.searchParams.get("since")).toBe("24H"); - for (const key of ["service_scope", "environment"]) expect(changedUrl.searchParams.get(key)).toBe(scope); - const previous = page.waitForResponse(response => response.request().headers()["hx-source"] === "div#rum-panel-pages"); - await page.getByRole("button", { name: "Previous time window", exact: true }).first().click(); - const previousUrl = new URL((await previous).url()); - for (const key of ["from", "to"]) { - expect(previousUrl.searchParams.get(key)).toBeTruthy(); - expect(previousUrl.searchParams.get(key)).toBe(new URL(page.url()).searchParams.get(key)); - } - expect(previousUrl.searchParams.get("since") ?? "").toBe(""); - for (const key of ["service_scope", "environment"]) expect(previousUrl.searchParams.get(key)).toBe(scope); - await expect(row).toHaveCount(0); - } - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=overview&service_scope=${scope}&environment=${scope}`); - const defaultRow = page.locator("#rum-panel-pages tbody tr").filter({ has: page.getByRole("link", { name: "/picker-window", exact: true }) }); - await expect(defaultRow.locator("td").nth(1)).toHaveText("2"); - const defaultRefresh = page.waitForResponse(response => response.request().headers()["hx-source"] === "div#rum-panel-pages"); - await page.evaluate(() => window.dispatchEvent(new Event("update-query"))); - expect(new URL((await defaultRefresh).url()).searchParams.get("since")).toBe("24H"); - await expect(defaultRow.locator("td").nth(1)).toHaveText("2"); - for (const [tab, panel] of [["performance", "pages"], ["sessions", "sessions"]]) { - const pending = new Promise(resolve => { release = resolve; }); - let fetched = () => {}; - const initialFetched = new Promise(resolve => { fetched = resolve; }); - let held = false; - const cancelled: string[] = []; - page.on("requestfailed", request => { - const url = new URL(request.url()); - if (url.searchParams.get("panel") === panel && url.searchParams.get("since") === "1H") cancelled.push(request.url()); - }); - await page.route("**/rum?**", async route => { - if (held || new URL(route.request().url()).searchParams.get("panel") !== panel) return route.continue(); - held = true; - const response = await route.fetch(); - fetched(); - await pending; - await route.fulfill({ response }); - }); - await page.context().clearCookies(); - const scopeParams = tab === "sessions" ? `q=${fixtureUser}` : `service_scope=${scope}&environment=${scope}`; - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=${tab}&since=1H&${scopeParams}`); - await initialFetched; - const responses: number[] = []; - page.on("response", response => { - const url = new URL(response.url()); - if (url.searchParams.get("panel") === panel && url.searchParams.get("since") === "24H") responses.push(response.status()); - }); - await page.locator("[data-live-range]").click(); - await page.locator('#n-timepicker-popover button[data-value="24H"]').click(); - await expect(page.locator("#n-currentRange")).toHaveText("Last 24 hours"); - release(); - if (tab === "performance") await expect(defaultRow.locator("td").nth(1)).toHaveText("2"); - else { - await expect(page.locator(".rum-session-link")).toHaveCount(200); - await expect(page.locator("#rum-replay-workspace")).toBeVisible(); - } - await expect.poll(() => responses).toEqual([200]); - await expect.poll(() => cancelled.length).toBe(1); - await page.unrouteAll({ behavior: "wait" }); - } - } finally { - release(); - await page.unrouteAll({ behavior: "wait" }); - sql(cleanup); - } -}); - -test("failed RUM queries show an error after the panel swap and recover on retry", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const scope = `e2e-panel-failure-${Date.now()}`; - const cleanup = `DELETE FROM otel_metrics WHERE project_id='${DEMO_PROJECT}' AND resource___service___name='${scope}'`; - sql(`INSERT INTO otel_metrics (project_id,id,series_id,timestamp,metric_name,metric_type,metric_unit,value,resource,resource___service___name,attributes) - VALUES ('${DEMO_PROJECT}',gen_random_uuid(),'${scope}',now()-interval '10 seconds','browser.web_vital.fcp','GAUGE','ms',10, - jsonb_build_object('service',jsonb_build_object('name','${scope}')),'${scope}','{"page.url":"/panel-recovery"}')`); - let renamed = false; - try { - sql("ALTER TABLE otel_metrics RENAME TO rum_failed_metrics_fixture"); - renamed = true; - const failed = page.waitForResponse(response => new URL(response.url()).searchParams.get("panel") === "vitals"); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=performance&since=1H&service_scope=${scope}`); - expect((await failed).status()).toBe(200); - const panel = page.locator("#rum-panel-vitals"); - await expect(panel.getByRole("alert")).toContainText("Some RUM data could not be loaded."); - await expect(panel.getByText("No data", { exact: true })).toHaveCount(0); - sql("ALTER TABLE rum_failed_metrics_fixture RENAME TO otel_metrics"); - renamed = false; - const recovered = page.waitForResponse(response => new URL(response.url()).searchParams.get("panel") === "vitals"); - await panel.getByRole("button", { name: "Retry", exact: true }).click(); - expect((await recovered).status()).toBe(200); - await expect(panel.getByRole("alert")).toHaveCount(0); - await expect(panel.getByRole("row").filter({ hasText: "First Contentful Paint" })).toContainText("10.0 ms"); - } finally { - if (renamed) sql("ALTER TABLE rum_failed_metrics_fixture RENAME TO otel_metrics"); - sql(cleanup); - } -}); - -test("mobile vital tables keep measurements and page identities readable", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const scope = `e2e-mobile-vitals-${Date.now()}`; - const cleanup = `DELETE FROM otel_metrics WHERE project_id='${DEMO_PROJECT}' AND resource___service___name='${scope}'`; - sql(`INSERT INTO otel_metrics (project_id,id,series_id,timestamp,start_timestamp,metric_name,metric_type,metric_unit,value,aggregation_temporality,distribution_count,hist_bucket_counts,hist_explicit_bounds,resource,resource___service___name,attributes) - SELECT '${DEMO_PROJECT}',gen_random_uuid(),'${scope}' || name,now()-interval '10 seconds',now()-interval '1 minute', - 'browser.web_vital.' || name,type,unit,value,'DELTA',count,buckets,bounds,jsonb_build_object('service',jsonb_build_object('name','${scope}')),'${scope}', - '{"page.url":"https://shop.example/item/ABCDEF12?variant=long-mobile-page-identity"}' - FROM (VALUES ('lcp','HISTOGRAM','ms',NULL::float8,100::bigint,ARRAY[80,20]::bigint[],ARRAY[100]::float8[]), - ('fcp','GAUGE','ms',22.5,NULL,NULL,NULL),('ttfb','SUM','ms',100,NULL,NULL,NULL)) AS points(name,type,unit,value,count,buckets,bounds)`); - try { - for (const width of [390, 320, 1440]) { - await page.setViewportSize({ width, height: 844 }); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=performance&since=1H&service_scope=${scope}`); - const table = page.getByRole("heading", { name: "Web Vitals field performance", exact: true }).locator("xpath=ancestor::section[1]").getByRole("table"); - await expect(table.getByRole("row")).toHaveCount(6); - await expect(table.getByRole("cell")).toHaveCount(35); - await expect(table).toContainText("Estimated within"); - await expect(table).toContainText("Exact quantile"); - await expect(table).toContainText("Unsupported population"); - for (const theme of ["light", "dark"]) { - await page.evaluate(theme => { if (document.body.dataset.theme !== theme) (window as any).toggleDarkMode(); }, theme); - expect(await table.locator("tbody tr").evaluateAll(rows => rows.every(row => [...row.querySelectorAll("td")].every(cell => { - const bounds = cell.getBoundingClientRect(); - return bounds.width > 0 && bounds.left >= 0 && bounds.right <= window.innerWidth && cell.scrollWidth <= cell.clientWidth; - })))).toBe(true); - await table.locator("tbody tr").first().screenshot({ path: test.info().outputPath(`vitals-${theme}-${width}.png`) }); - const pages = page.getByRole("heading", { name: "Web Vitals by page", exact: true }).locator("xpath=ancestor::section[1]").getByRole("table"); - await expect(pages.getByRole("cell")).toHaveCount(7); - await pages.locator("tbody tr").first().screenshot({ path: test.info().outputPath(`page-vitals-${theme}-${width}.png`) }); - expect(await pages.locator("tbody td").evaluateAll(cells => cells.every((cell, index) => { - const bounds = cell.getBoundingClientRect(); - const text = document.createRange(); - text.selectNodeContents(cell); - return bounds.width > 0 && bounds.left >= 0 && bounds.right <= window.innerWidth && cell.scrollWidth <= cell.clientWidth - && (window.innerWidth >= 640 && index === 0 || [...text.getClientRects()].every(rect => rect.left >= bounds.left - 1 && rect.right <= bounds.right + 1)); - }))).toBe(true); - await expect(pages.getByRole("columnheader")).toHaveCount(7); - await expect(pages.getByRole("columnheader", { name: "Observations", exact: true })).toHaveCount(1); - if (width < 640) { - await expect(pages.getByText("Unsupported population", { exact: true })).toBeVisible(); - await expect(pages.getByText("Exact quantile", { exact: true })).toBeVisible(); - } - const link = pages.getByRole("link", { name: "https://shop.example/item/ABCDEF12?variant=long-mobile-page-identity", exact: true }); - if (width < 640) expect(await link.evaluate(element => element.getBoundingClientRect().height)).toBeGreaterThanOrEqual(44); - const destination = new URL((await link.getAttribute("href"))!, page.url()); - expect(destination.searchParams.get("query")).toContain('attributes.url.full == "https://shop.example/item/ABCDEF12?variant=long-mobile-page-identity"'); - expect(destination.searchParams.get("query")).toContain(`service=="${scope}"`); - expect(destination.searchParams.get("since")).toBe("1H"); - } - await expect(table.getByRole("columnheader", { name: "Coverage", exact: true })).toHaveCount(1); - } - } finally { - sql(cleanup); - } -}); - -test("singleton vital trend keeps the selected time axis", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const scope = `e2e-vital-axis-${Date.now()}`; - const cleanup = `DELETE FROM otel_metrics WHERE project_id='${DEMO_PROJECT}' AND resource___service___name='${scope}'`; - // Keep the short window inside one five-minute bucket even at a wall-clock boundary. - const to = new Date(Math.floor(Date.now() / 300000) * 300000 - 60000); - const from = new Date(to.getTime() - 90 * 60 * 1000); - sql(`INSERT INTO otel_metrics (project_id,id,series_id,timestamp,metric_name,metric_type,metric_unit,value,resource,resource___service___name) - VALUES ('${DEMO_PROJECT}',gen_random_uuid(),'${scope}','${new Date(to.getTime() - 10000).toISOString()}','browser.web_vital.lcp','GAUGE','ms',1200, - jsonb_build_object('service',jsonb_build_object('name','${scope}')),'${scope}')`); - try { - for (const [range, span] of [[{ since: "1H" }, 60 * 60 * 1000], [{ from: from.toISOString(), to: to.toISOString() }, 90 * 60 * 1000], [{ from: new Date(to.getTime() - 30000).toISOString(), to: to.toISOString() }, 30000]] as const) { - await page.goto(`/p/${DEMO_PROJECT}/rum?${new URLSearchParams({ tab: "performance", service_scope: scope, ...range })}`); - const chart = page.locator("#rum-vital-trend-lcp"); - await expect(chart).toBeVisible(); - await chart.scrollIntoViewIfNeeded(); - await expect.poll(() => chart.evaluate(element => { - const instance = (window as any).echarts?.getInstanceByDom(element); - const extent = instance?.getModel().getComponent("xAxis").axis.scale.getExtent(); - return extent ? extent[1] - extent[0] : null; - })).toBe(span); - await expect.poll(() => chart.evaluate(element => { - const instance = (window as any).echarts?.getInstanceByDom(element); - const series = instance?.getModel().getSeriesByIndex(0); - if (!series || series.getData().count() !== 1 || !series.get("showSymbol")) return false; - const datum = instance.getOption().dataset[0].source[1]; - const [x, y] = instance.convertToPixel({ seriesIndex: 0 }, datum); - const plot = instance.getModel().getComponent("grid").coordinateSystem.getRect(); - return datum[1] === 1200 && x >= plot.x && x <= plot.x + plot.width && y >= plot.y && y <= plot.y + plot.height; - })).toBe(true); - } - } finally { - sql(cleanup); - } -}); - -test("explicit RUM window survives reload and shared navigation without since", async ({ page, context }) => { - const to = new Date(); - const from = new Date(to.getTime() - 90 * 60 * 1000); - const params = new URLSearchParams({ tab: "performance", from: from.toISOString(), to: to.toISOString(), environment: "e2e-explicit-window", service_scope: "e2e-explicit-window" }); - const url = `/p/${DEMO_PROJECT}/rum?${params}`; - for (const target of [page, await context.newPage()]) { - const response = await target.goto(url); - const initialRange = (await response!.text()).match(/id="n-currentRange">([^<]*)/)?.[1]; - expect(initialRange).toBeTruthy(); - expect(initialRange).not.toBe("Last 24 hours"); - await expect(target.locator("#n-currentRange")).not.toHaveText("Last 24 hours"); - await target.reload(); - await expect(target.locator("#n-currentRange")).not.toHaveText("Last 24 hours"); - const current = new URL(target.url()); - for (const [key, value] of params) expect(current.searchParams.get(key)).toBe(value); - expect(current.searchParams.has("since")).toBe(false); - } -}); - -test("initial RUM field panel does not depend on application globals", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const scope = `e2e-initial-rum-${Date.now()}`; - const cleanup = `DELETE FROM otel_metrics WHERE project_id='${DEMO_PROJECT}' AND resource___service___name='${scope}'`; - sql(`INSERT INTO otel_metrics (project_id,id,series_id,timestamp,metric_name,metric_type,metric_unit,value,resource,resource___service___name) - SELECT '${DEMO_PROJECT}',gen_random_uuid(),'${scope}',at,'browser.web_vital.fcp','GAUGE','ms',value, - jsonb_build_object('service',jsonb_build_object('name','${scope}')),'${scope}' - FROM (VALUES(now()-interval '10 seconds',22.5),(now()-interval '2 hours',99)) AS points(at,value)`); - let release = () => {}; - const held = new Promise(resolve => { release = resolve; }); - const errors: string[] = []; - page.on("console", message => { if (message.type() === "error") errors.push(message.text()); }); - page.on("pageerror", error => errors.push(error.message)); - await page.route(/\/public\/assets\/(?:js\/main\.|web-components\/dist\/js\/index\.).*\.js$/, async route => { await held; await route.continue(); }); - const responses: string[] = []; - page.on("response", response => { if (new URL(response.url()).searchParams.get("panel") === "vitals" && response.status() === 200) responses.push(response.url()); }); - try { - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=performance&since=24H&since=1H&service_scope=${scope}`, { waitUntil: "commit" }); - const shell = page.locator("#rum-panel-vitals"); - await expect(shell).toBeAttached(); - await expect.poll(() => page.evaluate(() => typeof (window as any).htmx)).toBe("object"); - expect(await page.evaluate(() => typeof (window as any).params)).toBe("undefined"); - await shell.evaluate(element => (window as any).htmx.process(element)); - const table = page.getByRole("heading", { name: "Web Vitals field performance", exact: true }).locator("xpath=ancestor::section[1]").getByRole("table"); - await expect(table).toContainText("22.5 ms", { timeout: 5_000 }); - expect(responses).toHaveLength(1); - const url = new URL(responses[0]); - expect(url.searchParams.getAll("since")).toEqual(["1H"]); - expect(url.searchParams.get("service_scope")).toBe(scope); - expect(errors).toEqual([]); - } finally { - release(); - try { await page.unrouteAll({ behavior: "wait" }); } finally { sql(cleanup); } - await test.info().attach("initial-rum-errors", { body: JSON.stringify(errors), contentType: "application/json" }); - } -}); - - -test("automatic live updates do not cancel the first RUM panel response", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const scope = `e2e-initial-live-${Date.now()}`; - const cleanup = `DELETE FROM otel_metrics WHERE project_id='${DEMO_PROJECT}' AND resource___service___name='${scope}'`; - sql(`INSERT INTO otel_metrics (project_id,id,series_id,timestamp,metric_name,metric_type,metric_unit,value,resource,resource___service___name) - VALUES('${DEMO_PROJECT}',gen_random_uuid(),'${scope}',now()-interval '10 seconds','browser.web_vital.fcp','GAUGE','ms',22.5, - jsonb_build_object('service',jsonb_build_object('name','${scope}')),'${scope}')`); - let release = () => {}; - try { - for (const [tab, panel, scopeParams] of [["performance", "vitals", `service_scope=${scope}`], ["sessions", "sessions", `q=${fixtureUser}`]]) { - const pending = new Promise(resolve => { release = resolve; }); - let fetched = () => {}; - const initialFetched = new Promise(resolve => { fetched = resolve; }); - const requests: string[] = []; - const cancelled: string[] = []; - const trackCancellation = (request: import("@playwright/test").Request) => { - if (new URL(request.url()).searchParams.get("panel") === panel) cancelled.push(request.url()); - }; - page.on("requestfailed", trackCancellation); - await page.route("**/rum?**", async route => { - if (new URL(route.request().url()).searchParams.get("panel") !== panel) return route.continue(); - requests.push(route.request().url()); - if (requests.length !== 1) return route.continue(); - const response = await route.fetch(); - fetched(); - await pending; - await route.fulfill({ response }); - }); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=${tab}&since=24H&${scopeParams}`); - await initialFetched; - await expect(page.locator("[data-time-transport]")).toHaveAttribute("data-interval", "15000"); - await expect(page.locator(`#rum-panel-${panel}`)).toHaveAttribute("data-deferred-shell", ""); - await page.evaluate(() => window.dispatchEvent(new CustomEvent("update-query", { detail: { source: "auto-refresh" } }))); - release(); - if (tab === "performance") await expect(page.locator("#rum-panel-vitals")).toContainText("22.5 ms"); - else await expect(page.locator(".rum-session-link")).toHaveCount(200); - expect(cancelled).toEqual([]); - expect(requests).toHaveLength(1); - const loaded = page.waitForResponse(response => new URL(response.url()).searchParams.get("panel") === panel); - await page.evaluate(() => window.dispatchEvent(new CustomEvent("update-query", { detail: { source: "auto-refresh" } }))); - expect((await loaded).status()).toBe(200); - await page.unrouteAll({ behavior: "wait" }); - page.off("requestfailed", trackCancellation); - } - } finally { - release(); - try { await page.unrouteAll({ behavior: "wait" }); } finally { sql(cleanup); } - } -}); - -test("refreshed vital charts remain registered on their current elements", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires the disposable e2e database"); - const scope = `e2e-vital-registry-${Date.now()}`; - const cleanup = `DELETE FROM otel_metrics WHERE project_id='${DEMO_PROJECT}' AND resource___service___name='${scope}'`; - sql(`INSERT INTO otel_metrics (project_id,id,series_id,timestamp,metric_name,metric_type,metric_unit,value,resource,resource___service___name) - SELECT '${DEMO_PROJECT}',gen_random_uuid(),'${scope}' || name,at,'browser.web_vital.' || name,'GAUGE','ms',value, - jsonb_build_object('service',jsonb_build_object('name','${scope}')),'${scope}' - FROM (VALUES ('fcp',now()-interval '10 minutes',20),('ttfb',now()-interval '10 minutes',100), - ('fcp',now()-interval '2 hours',80),('ttfb',now()-interval '2 hours',500)) AS points(name,at,value)`); - const assertCharts = async (span: number, samples: number) => { - for (const name of ["fcp", "ttfb"]) { - const chart = page.locator(`#rum-vital-trend-${name}`); - await chart.scrollIntoViewIfNeeded(); - await expect.poll(() => chart.evaluate(element => { - const instance = (window as any).echarts?.getInstanceByDom(element); - const extent = instance?.getModel().getComponent("xAxis").axis.scale.getExtent(); - const data = instance?.getOption().dataset[0].source; - return [Boolean(instance && instance.getDom() === element && !instance.isDisposed()), - element.querySelectorAll("canvas").length, extent ? extent[1] - extent[0] : null, - data?.slice(1).map((point: number[]) => point[1]).sort((a: number, b: number) => a - b) ?? []]; - })).toEqual([true, 1, span, (name === "fcp" ? [20, 80] : [100, 500]).slice(0, samples)]); - } - }; - const waitForTrend = () => page.evaluate(() => new Promise(resolve => { - const settled = (event: Event) => { - if ((event.target as HTMLElement).id !== "rum-panel-vital_trend") return; - document.removeEventListener("htmx:after:settle", settled); - resolve(); - }; - document.addEventListener("htmx:after:settle", settled); - })); - try { - await page.setViewportSize({ width: 1440, height: 1000 }); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=performance&since=1H&service_scope=${scope}`); - await expect(page.getByRole("link", { name: "Performance", exact: true })).toHaveAttribute("aria-current", "page"); - await expect(page.getByRole("heading", { name: "Web Vitals over time", exact: true })).toBeVisible(); - await page.locator("[data-time-transport]").getByRole("button", { name: /^Pause live (data|updates)$/ }).click(); - await expect(page.locator("[data-time-transport]")).toHaveAttribute("data-interval", "0"); - await assertCharts(60 * 60 * 1000, 1); - await page.locator("[data-live-range]").click(); - const changed = waitForTrend(); - await page.locator('#n-timepicker-popover button[data-value="24H"]').click(); - await changed; - await expect(page.locator("#n-currentRange")).toHaveText("Last 24 hours"); - await assertCharts(24 * 60 * 60 * 1000, 2); - await page.evaluate(() => { - (window as any).__rumPriorCharts = ["fcp", "ttfb"].map(name => (window as any).echarts.getInstanceByDom(document.getElementById(`rum-vital-trend-${name}`))); - }); - const refreshed = waitForTrend(); - await page.evaluate(() => window.dispatchEvent(new Event("update-query"))); - await refreshed; - await assertCharts(24 * 60 * 60 * 1000, 2); - expect(await page.evaluate(() => ["fcp", "ttfb"].every((name, index) => { - const instance = (window as any).__rumPriorCharts[index]; - return !instance.isDisposed() && (window as any).echarts.getInstanceByDom(document.getElementById(`rum-vital-trend-${name}`)) === instance; - }))).toBe(true); - } finally { - sql(cleanup); - } -}); - -test("automatic session ticks keep an in-flight list request while search replaces it", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires a disposable fixture database"); - await page.setViewportSize({ width: 390, height: 900 }); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=sessions&since=1H`); - const list = page.locator("#rum-sessions-list"); - await expect(list.locator(".rum-session-link").first()).toBeVisible(); - await page.locator('[popovertarget="n-timepicker-popover"]').click(); - await page.locator("[data-mobile-live-toggle]").click(); - await expect(page.locator("[data-time-transport]")).toHaveAttribute("data-interval", "0"); - await page.locator('[popovertarget="n-timepicker-popover"]').click(); - const workspace = page.locator("#rum-replay-workspace"); - await workspace.evaluate(element => element.setAttribute("data-e2e-preserved", "true")); - let release = () => {}; - const held = new Promise(resolve => { release = resolve; }); - let releaseSearch = () => {}; - const heldSearch = new Promise(resolve => { releaseSearch = resolve; }); - const automatic: import("@playwright/test").Request[] = []; - await page.route("**/rum?**", async route => { - const url = new URL(route.request().url()); - if (url.searchParams.get("panel") === "sessions" && route.request().headers()["hx-source"] === "div#rum-panel-sessions") { - automatic.push(route.request()); - if (automatic.length === 1) await held; - } - if (url.searchParams.get("q") === "e2e-missing-session" && route.request().headers()["hx-source"] === "form#rum-session-search-form") await heldSearch; - await route.continue(); - }); - try { - const first = page.waitForRequest(request => new URL(request.url()).searchParams.get("panel") === "sessions"); - await page.evaluate(() => window.dispatchEvent(new CustomEvent("update-query", { detail: { source: "auto-refresh" } }))); - const pending = await first; - await expect(page.locator("#rum-panel-sessions")).toHaveClass(/htmx-request/); - await page.evaluate(() => window.dispatchEvent(new CustomEvent("update-query", { detail: { source: "auto-refresh" } }))); - await page.waitForTimeout(300); // Let an unwanted replacement reach the real HTTP route. - expect(automatic).toHaveLength(1); - expect(pending.failure()).toBeNull(); - const search = page.getByRole("searchbox", { name: "Search sessions" }); - const replaced = page.waitForEvent("requestfailed", request => request === pending); - const searching = page.waitForRequest(request => new URL(request.url()).searchParams.get("q") === "e2e-missing-session"); - const searched = page.waitForResponse(response => new URL(response.url()).searchParams.get("q") === "e2e-missing-session"); - await search.fill("e2e-missing-session"); - const pendingSearch = await searching; - release(); - await replaced; - await expect(page.locator("#rum-session-search-form")).toHaveClass(/htmx-request/); - await page.evaluate(() => window.dispatchEvent(new CustomEvent("update-query", { detail: { source: "auto-refresh" } }))); - await page.waitForTimeout(300); - expect(automatic).toHaveLength(1); - expect(pendingSearch.failure()).toBeNull(); - releaseSearch(); - expect((await searched).status()).toBe(200); - await expect(page.getByText("No sessions match this filter", { exact: true })).toBeVisible(); - await expect(search).toBeFocused(); - await expect(workspace).toHaveAttribute("data-e2e-preserved", "true"); - await expect(page.locator("#rum-session-search-form")).not.toHaveClass(/htmx-request/); - const resumed = page.waitForResponse(response => response.request().headers()["hx-source"] === "div#rum-panel-sessions"); - await page.evaluate(() => window.dispatchEvent(new CustomEvent("update-query", { detail: { source: "auto-refresh" } }))); - expect((await resumed).status()).toBe(200); - expect(automatic).toHaveLength(2); - await expect(search).toHaveValue("e2e-missing-session"); - await expect(workspace).toHaveAttribute("data-e2e-preserved", "true"); - } finally { release(); releaseSearch(); await page.unrouteAll({ behavior: "wait" }); } -}); - -test("manual session replacements keep cancellation attached to the newest request", async ({ page }) => { - test.skip(!process.env.E2E_BASE_URL, "Requires a disposable fixture database"); - await page.setViewportSize({ width: 390, height: 900 }); - await page.goto(`/p/${DEMO_PROJECT}/rum?tab=sessions&since=1H`); - await expect(page.locator(".rum-session-link").first()).toBeVisible(); - await page.locator('[popovertarget="n-timepicker-popover"]').click(); - await page.locator("[data-mobile-live-toggle]").click(); - await expect(page.locator("[data-time-transport]")).toHaveAttribute("data-interval", "0"); - await page.locator('[popovertarget="n-timepicker-popover"]').click(); - let releaseFirst = () => {}; - const firstGate = new Promise(resolve => { releaseFirst = resolve; }); - let releaseSecond = () => {}; - const secondGate = new Promise(resolve => { releaseSecond = resolve; }); - await page.route("**/rum?**", async route => { - const query = new URL(route.request().url()).searchParams.get("q"); - if (query === "e2e-first-pending") await firstGate; - if (query === "e2e-second-pending") await secondGate; - await route.continue(); - }); - try { - const search = page.getByRole("searchbox", { name: "Search sessions" }); - const firstIssued = page.waitForRequest(request => new URL(request.url()).searchParams.get("q") === "e2e-first-pending"); - await search.fill("e2e-first-pending"); - const first = await firstIssued; - const firstCancelled = page.waitForEvent("requestfailed", request => request === first); - const secondIssued = page.waitForRequest(request => new URL(request.url()).searchParams.get("q") === "e2e-second-pending"); - await search.fill("e2e-second-pending"); - const second = await secondIssued; - const secondSettled = Promise.race([ - page.waitForEvent("requestfinished", request => request === second), - page.waitForEvent("requestfailed", request => request === second), - ]); - releaseFirst(); - await firstCancelled; - await expect(page.locator("#rum-session-search-form")).toHaveClass(/htmx-request/); - const latest = page.waitForResponse(response => new URL(response.url()).searchParams.get("q") === fixtureUser); - await search.fill(fixtureUser); - expect((await latest).status()).toBe(200); - await expect(page.locator(".rum-session-link")).toHaveCount(200); - await expect.poll(() => new URL(page.url()).searchParams.get("q")).toBe(fixtureUser); - await expect(search).toBeFocused(); - releaseSecond(); - await secondSettled; - await page.waitForTimeout(300); - await expect(page.locator(".rum-session-link")).toHaveCount(200); - expect(second.failure()).not.toBeNull(); - await expect(search).toHaveValue(fixtureUser); - await expect.poll(() => new URL(page.url()).searchParams.get("q")).toBe(fixtureUser); - await expect(search).toBeFocused(); - } finally { - releaseFirst(); - releaseSecond(); - await page.unrouteAll({ behavior: "wait" }); - } -}); diff --git a/e2e/tests/sidebar-navigation.spec.ts b/e2e/tests/sidebar-navigation.spec.ts index 9c9918a75..9672e9c4d 100644 --- a/e2e/tests/sidebar-navigation.spec.ts +++ b/e2e/tests/sidebar-navigation.spec.ts @@ -16,7 +16,7 @@ const cases = [ ['/manage_billing', '/settings'], ['/dashboards', '/dashboards'], ['/issues', '/issues'], - ['/rum', '/rum'], + ['/rum', '/dashboards'], ['/monitors', '/monitors'], ['/reports', '/reports'], ]; diff --git a/monoscope.cabal b/monoscope.cabal index b45ad3d65..379e44720 100644 --- a/monoscope.cabal +++ b/monoscope.cabal @@ -271,6 +271,28 @@ extra-source-files: test/fixtures/github-app-test.pem test/fixtures/wiki-browser.mjs static/public/assets/web-components/dist/manifest.json + static/public/dashboards/_overview.yaml + static/public/dashboards/apache.yaml + static/public/dashboards/cloudflare.yaml + static/public/dashboards/docker.yaml + static/public/dashboards/elasticsearch.yaml + static/public/dashboards/endpoint-stats.yaml + static/public/dashboards/haproxy.yaml + static/public/dashboards/heroku.yaml + static/public/dashboards/host-prometheus.yaml + static/public/dashboards/http-stats.yaml + static/public/dashboards/kitchensink.yaml + static/public/dashboards/kubernetes.yaml + static/public/dashboards/minio.yaml + static/public/dashboards/mysql.yaml + static/public/dashboards/nginx.yaml + static/public/dashboards/opentelemetry-collector.yaml + static/public/dashboards/opentelemetry-tracing.yaml + static/public/dashboards/postgresql.yaml + static/public/dashboards/rabbitmq.yaml + static/public/dashboards/redis.yaml + static/public/dashboards/rum.yaml + static/public/dashboards/timefusion.yaml source-repository head type: git @@ -328,7 +350,6 @@ library Models.Telemetry.ContainerTypes Models.Telemetry.DeterministicId Models.Telemetry.Report - Models.Telemetry.RUM Models.Telemetry.ServiceGraph Models.Telemetry.Telemetry Opentelemetry.OtlpServer @@ -356,7 +377,6 @@ library Pages.Monitors Pages.Onboarding Pages.Projects - Pages.RealUserMonitoring Pages.Replay Pages.Reports Pages.ServiceMap @@ -798,7 +818,6 @@ test-suite integration-tests Pages.Projects.ProjectsSpec Pages.PrometheusSpec Pages.QueryCacheSpec - Pages.RealUserMonitoringSpec Pages.ReportsSpec Pages.ServiceMapSpec Pages.ShareSpec @@ -974,7 +993,6 @@ test-suite test-dev Models.Telemetry.ContainerTypes Models.Telemetry.DeterministicId Models.Telemetry.Report - Models.Telemetry.RUM Models.Telemetry.ServiceGraph Models.Telemetry.Telemetry Opentelemetry.OtlpServer @@ -1002,7 +1020,6 @@ test-suite test-dev Pages.Monitors Pages.Onboarding Pages.Projects - Pages.RealUserMonitoring Pages.Replay Pages.Reports Pages.ServiceMap @@ -1117,7 +1134,6 @@ test-suite test-dev Pages.Projects.ProjectsSpec Pages.PrometheusSpec Pages.QueryCacheSpec - Pages.RealUserMonitoringSpec Pages.ReportsSpec Pages.ServiceMapSpec Pages.ShareSpec diff --git a/package.yaml b/package.yaml index ede61a6ce..420c91a9f 100644 --- a/package.yaml +++ b/package.yaml @@ -39,6 +39,8 @@ extra-source-files: # Cabal does not track TH addDependentFile; listing it here makes a rebuilt bundle # re-run GHC, which then re-splices viteAssetFile. - static/public/assets/web-components/dist/manifest.json + # Dashboard templates are spliced by TH the same way. + - static/public/dashboards/*.yaml # - static/public/**/*.png # - static/public/**/*.css # - static/public/**/*.ttf diff --git a/src/Models/Apis/LogQueries.hs b/src/Models/Apis/LogQueries.hs index 583449286..2350e554a 100644 --- a/src/Models/Apis/LogQueries.hs +++ b/src/Models/Apis/LogQueries.hs @@ -57,7 +57,6 @@ import Database.PostgreSQL.Simple.ToField (ToField) import Deriving.Aeson qualified as DAE import Deriving.Aeson.Stock qualified as DAE import Effectful -import Effectful.Ki qualified as Ki import Effectful.Labeled (Labeled) import Effectful.Log (Log) import Effectful.Time qualified as Time @@ -73,7 +72,7 @@ import Pkg.Parser.Stats (Section, Sources (..)) import Relude hiding (many, some) import Relude.Extra.Foldable1 (maximum1, minimum1) import System.Logging qualified as Log -import System.Tracing (Tracing, forkWithCtx, withSpan_) +import System.Tracing (Tracing, withSpan_) import Utils (listToIndexHashMap, lookupVecNonEmptyText, replaceAllFormats, truncateHour) import Web.HttpApiData (FromHttpApiData (..)) @@ -482,6 +481,7 @@ data SessionAggRow = SessionAggRow , errorCount :: Int64 , firstSeen :: UTCTime , lastSeen :: UTCTime + , services :: Maybe (V.Vector Text) } deriving stock (Generic, Show) deriving anyclass (HI.DecodeRow) @@ -650,6 +650,11 @@ sessionKeyExpr :: Text sessionKeyExpr = "COALESCE(NULLIF(attributes___session___id, ''), NULLIF(attributes___user___id, ''), NULLIF(attributes___user___email, ''))" +-- | The browser filter, parsed once per process rather than per sessions request. +browserAst :: Either Text [Section] +browserAst = parseQueryToAST browserKql + + -- | Ordering for the Sessions viz. The wire spellings are exactly the values the sort -- dropdown in "Pkg.Components.LogQueryBox" emits and what shared URLs carry. -- @@ -687,7 +692,7 @@ sessionSortLabel ordering = T.toUpper (T.take 1 label) <> T.drop 1 label label = T.replace "_" " " $ display ordering -fetchSessions :: (DB es, IOE :> es, Ki.StructuredConcurrency :> es, Labeled "timefusion" Hasql :> es, Log :> es, Time.Time :> es) => Bool -> Projects.ProjectId -> [Section] -> (Maybe UTCTime, Maybe UTCTime) -> Maybe Text -> Maybe Text -> Maybe SessionSort -> Int -> SessionsRead -> Eff es (Maybe SessionSummary, Int, [SessionRow]) +fetchSessions :: (DB es, IOE :> es, Labeled "timefusion" Hasql :> es, Log :> es, Time.Time :> es) => Bool -> Projects.ProjectId -> [Section] -> (Maybe UTCTime, Maybe UTCTime) -> Maybe Text -> Maybe Text -> Maybe SessionSort -> Int -> SessionsRead -> Eff es (Maybe SessionSummary, Int, [SessionRow]) fetchSessions enableTfReads pid queryAST dateRange environment service sortByM skip readKind = do now <- Time.currentTime let scope = mkScopedQuery pid dateRange environment service @@ -697,52 +702,53 @@ fetchSessions enableTfReads pid queryAST dateRange environment service sortByM s ordering = fromMaybe SortLastSeen sortByM Log.logTrace "fetchSessions: start" $ AE.object ["project_id" AE..= pid, "skip" AE..= skip, "date_range" AE..= show dateRange, "sort_by" AE..= sortByM] - -- One scan of the window keyed by 'sessionKeyExpr' (identity = MAX non-null per session), - -- with only rollup-servable aggregates: a distinct count per group (trace ids, services) - -- forces the raw store — 7s against 0.15s. Sorting, paging and the header happen here. - -- The header's service read (a GROUP BY, since a distinct count leaves the rollups) is - -- independent of the scan and forks beside it; on long-session projects both are raw - -- window scans of several seconds. A failure on either side still fails the request. - (sessions :: [SessionAggRow], serviceRows :: [Maybe Text]) <- Ki.scoped \ks -> do - servicesT <- - forkWithCtx ks - $ if readKind == WithHeader - then - Hasql.withHasqlTimefusion enableTfReads - $ Hasql.interp - $ [HI.sql|SELECT resource___service___name FROM otel_logs_and_spans WHERE |] - <> whereSql - <> [HI.sql| GROUP BY 1|] - else pure [] - sessions <- - Hasql.withHasqlTimefusion enableTfReads - $ Hasql.interp - $ [HI.sql|SELECT |] - <> keySql - <> [HI.sql| AS session_id, - MAX(attributes___user___id), MAX(attributes___user___email), - MAX(COALESCE(NULLIF(attributes___user___full_name, ''), NULLIF(attributes___user___name, ''))), - COUNT(*)::BIGINT, - COUNT(*) FILTER (WHERE |] - <> rawSql severityIsErrorSql - <> [HI.sql|)::BIGINT, - MIN(timestamp), MAX(COALESCE(end_time, timestamp)) - FROM otel_logs_and_spans - WHERE |] - <> whereSql - <> [HI.sql| AND |] - <> keySql - <> [HI.sql| IS NOT NULL - GROUP BY 1|] - (sessions,) <$> Ki.atomically (Ki.await servicesT) + -- One raw scan of the window keyed by 'sessionKeyExpr' (an expression, so no rollup can + -- serve it). Each session's services ride along for ~5% of the scan, which is cheaper than + -- the separate full-window service scan the header used to fork beside it. + telemetry :: [SessionAggRow] <- + Hasql.withHasqlTimefusion enableTfReads + $ Hasql.interp + $ [HI.sql|SELECT |] + <> keySql + <> [HI.sql| AS session_id, + MAX(attributes___user___id), MAX(attributes___user___email), + MAX(COALESCE(NULLIF(attributes___user___full_name, ''), NULLIF(attributes___user___name, ''))), + COUNT(*)::BIGINT, + COUNT(*) FILTER (WHERE |] + <> rawSql severityIsErrorSql + <> [HI.sql|)::BIGINT, + MIN(timestamp), MAX(COALESCE(end_time, timestamp)), + ARRAY_REMOVE(ARRAY_AGG(DISTINCT resource___service___name), NULL) + FROM otel_logs_and_spans + WHERE |] + <> whereSql + <> [HI.sql| AND |] + <> keySql + <> [HI.sql| IS NOT NULL + GROUP BY 1|] + -- A recording whose spans never arrived is still a session a reader can replay. It carries no + -- attributes, so only an unscoped list that is unfiltered or exactly browser-scoped holds it. + let fromT = fromMaybe (addUTCTime (-3600) now) (fst dateRange) + toT = fromMaybe now (snd dateRange) + recordings :: [SessionAggRow] <- + if isNothing environment && isNothing service && (null queryAST || Right queryAST == browserAst) + then + Hasql.interp + [HI.sql| SELECT session_id::text, user_id, user_email, user_name, 0::bigint, 0::bigint, created_at, last_event_at, NULL::text[] + FROM projects.replay_sessions + WHERE project_id = #{pid} AND last_event_at >= #{fromT} AND created_at <= #{toT} + AND (event_file_count > 0 OR cardinality(file_keys) > 0 OR cardinality(shard_keys) > 0) |] + else pure [] + let telemetryIds = S.fromList $ map (.sessionId) telemetry + sessions = telemetry <> filter ((`S.notMember` telemetryIds) . (.sessionId)) recordings Log.logTrace "fetchSessions: query done" $ AE.object ["rows" AE..= length sessions] let durationNs r = round (diffUTCTime r.lastSeen r.firstSeen * 1e9) :: Int64 ordered = sortOn (Down . case ordering of SortLastSeen -> Left . (.lastSeen); SortFirstSeen -> Left . (.firstSeen); SortDuration -> Right . durationNs; SortErrors -> Right . (.errorCount); SortEvents -> Right . (.eventCount)) sessions page = take aggregatePageSize $ drop skip ordered pageIds = map (.sessionId) page - -- First-observed context and the service list for the page only, bounded to the page's own - -- span: a session's rows all lie inside it, and it is a fraction of the window. - context :: [(Text, Maybe Text, Maybe Text, Maybe Text, Maybe (V.Vector Text))] <- + -- First-observed context for the page only, bounded to the page's own span: a session's rows + -- all lie inside it. Ordered first-values for every session in the window cost ~65% more scan. + context :: [(Text, Maybe Text, Maybe Text, Maybe Text)] <- case nonEmpty page of Nothing -> pure [] Just rows -> @@ -755,8 +761,7 @@ fetchSessions enableTfReads pid queryAST dateRange environment service sortByM s (ARRAY_AGG(attributes___user_agent___original ORDER BY timestamp) FILTER (WHERE attributes___user_agent___original IS NOT NULL AND attributes___user_agent___original <> ''))[1], (ARRAY_AGG(COALESCE(NULLIF(status_message, ''), NULLIF(body::text, '')) ORDER BY timestamp) FILTER (WHERE (|] <> rawSql severityIsErrorSql - <> [HI.sql|) AND COALESCE(NULLIF(status_message, ''), NULLIF(body::text, '')) IS NOT NULL))[1], - ARRAY_REMOVE(ARRAY_AGG(DISTINCT resource___service___name), NULL) + <> [HI.sql|) AND COALESCE(NULLIF(status_message, ''), NULLIF(body::text, '')) IS NOT NULL))[1] FROM otel_logs_and_spans WHERE |] <> whereSql @@ -770,16 +775,14 @@ fetchSessions enableTfReads pid queryAST dateRange environment service sortByM s -- lookup over the page's ids only. Non-UUID session keys (sessions derived -- from user id/email) can never have a recording, so they're not even asked for. replayed <- replayedSessionIds pid (mapMaybe UUID.fromText pageIds) - unless (length context == length page) + unless (length context == length (filter ((`S.member` telemetryIds) . (.sessionId)) page)) $ Log.logAttention "fetchSessions: page rows without context" $ AE.object ["project_id" AE..= pid, "page" AE..= length page, "context" AE..= length context] - let contextById = HM.fromList [(sid, (landing, agent, firstError, fromMaybe V.empty services)) | (sid, landing, agent, firstError, services) <- context] + let contextById = HM.fromList [(sid, (landing, agent, firstError)) | (sid, landing, agent, firstError) <- context] durations = V.fromList $ sort $ map durationNs sessions events = V.fromList $ sort $ map (.eventCount) sessions -- Densify the header's over-time buckets across the full picker range so -- empty periods render as blanks. - fromT = fromMaybe (addUTCTime (-3600) now) (fst dateRange) - toT = fromMaybe now (snd dateRange) epochBucket t = floor (utcTimeToPOSIXSeconds t) `div` bucketW pMin = epochBucket fromT pMax = max pMin (epochBucket toT) @@ -790,7 +793,7 @@ fetchSessions enableTfReads pid queryAST dateRange environment service sortByM s { totalSessions = fromIntegral $ length sessions , erroredSessions = fromIntegral $ length $ filter ((> 0) . (.errorCount)) sessions , uniqueUsers = fromIntegral $ length $ ordNub $ mapMaybe (\r -> r.userId <|> r.userEmail) sessions - , uniqueServices = fromIntegral $ length $ catMaybes serviceRows + , uniqueServices = fromIntegral $ length $ ordNub $ concatMap toList $ mapMaybe (.services) sessions , medianDurationNs = percentile 0.5 durations , p95DurationNs = percentile 0.95 durations , medianEvents = percentile 0.5 events @@ -801,8 +804,8 @@ fetchSessions enableTfReads pid queryAST dateRange environment service sortByM s , errored = buckets True } toRow r@SessionAggRow{..} = - let (landingUrl, userAgent, firstError, services) = fromMaybe (Nothing, Nothing, Nothing, V.empty) $ HM.lookup sessionId contextById - in SessionRow{durationNs = durationNs r, hasReplay = maybe False (`S.member` replayed) (UUID.fromText sessionId), ..} + let (landingUrl, userAgent, firstError) = fromMaybe (Nothing, Nothing, Nothing) $ HM.lookup sessionId contextById + in SessionRow{durationNs = durationNs r, services = fold services, hasReplay = maybe False (`S.member` replayed) (UUID.fromText sessionId), ..} pure (summary, length sessions, map toRow page) diff --git a/src/Models/Projects/Dashboards.hs b/src/Models/Projects/Dashboards.hs index 71fe2a91c..92962d8eb 100644 --- a/src/Models/Projects/Dashboards.hs +++ b/src/Models/Projects/Dashboards.hs @@ -74,7 +74,7 @@ import Pkg.Components.Table (SortField (..), SortOrder (..)) import Pkg.Components.TimePicker qualified as TimePicker import Pkg.Components.Widget qualified as Widget import Pkg.DeriveUtils (UUIDId (..), WrappedEnumSC (..), selectFrom) -import Pkg.Parser (replacePlaceholders, variablePresets) +import Pkg.Parser (fillQueryTemplate, variablePresets) import Relude import Servant (FromHttpApiData, ServerError (..), err404) import System.Directory (listDirectory) @@ -295,7 +295,7 @@ replaceDashboardVariables replaceDashboardVariables pid mf mt allParams currentTime x = x & field' @"sql" . _Just . #statement %~ replace & field' @"query" . _Just %~ replace where - replace = replacePlaceholders (variablePresets def pid.toText mf mt allParams currentTime) + replace = fillQueryTemplate (variablePresets def pid.toText mf mt allParams currentTime) -- | Look up a dashboard WITHOUT checking which project owns it. diff --git a/src/Models/Telemetry/RUM.hs b/src/Models/Telemetry/RUM.hs deleted file mode 100644 index 45300e973..000000000 --- a/src/Models/Telemetry/RUM.hs +++ /dev/null @@ -1,603 +0,0 @@ -module Models.Telemetry.RUM ( - RumBucket (..), - RumPage (..), - RumError (..), - RumBreakdown (..), - RumPulse (..), - ReplaySession (..), - RumSession (..), - SessionFilter (..), - ObservationCount, - VitalEstimate (value, bounds), - VitalCoverage (..), - VitalMeasurement (..), - measurementValue, - measurementSamples, - VitalGrouping (..), - VitalPopulation (..), - rumVitalPopulation, - VitalTrendPoint (..), - PageVitalPoint (..), - RumQueryResult (..), - RumQuery (..), - RumCacheKey (..), - rumCacheDbKey, - rumPanelCacheGet, - rumPanelCacheGetStale, - withSharedCache, - rumPanelCacheSet, -) where - -import Data.Aeson qualified as AE -import Data.Effectful.Hasql qualified as Hasql -import Data.Map.Strict qualified as Map -import Data.Time (UTCTime) -import Data.UUID qualified as UUID -import Effectful (Eff, (:>)) -import Effectful.Labeled (Labeled) -import Hasql.Decoders qualified as D -import Hasql.Interpolate qualified as HI -import Models.Projects.Projects qualified as Projects -import Pkg.Components.TimePicker qualified as TimePicker -import Pkg.DeriveUtils (AesonText (..), DB, WrappedEnumSC (..), unAesonText) -import Pkg.Parser (ScopedQuery (..)) -import Relude -import Relude.Extra.Bifunctor (firstF) -import Relude.Extra.Foldable1 (minimum1) -import Utils (toXXHash) - - -data RumBucket = FiveMinutes | OneHour | SixHours - deriving stock (Eq, Generic, Ord, Show) - deriving anyclass (Hashable) - - -data RumPage = RumPage - { path :: Text - , views :: Int64 - , p75LoadMs :: Maybe Double - , lastSeen :: UTCTime - } - deriving stock (Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON, HI.DecodeRow) - - -data RumError = RumError - { timestamp :: UTCTime - , errorType :: Text - , message :: Text - , sessionId :: Maybe Text - , userId :: Maybe Text - , path :: Maybe Text - } - deriving stock (Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON, HI.DecodeRow) - - --- | One user agent's traffic. The user agent string is classified into browser, OS and --- device family in the page layer; the query only groups and counts. -data RumBreakdown = RumBreakdown - { userAgent :: Text - , sessions :: Int64 - , views :: Int64 - , errors :: Int64 - } - deriving stock (Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON, HI.DecodeRow) - - -data ReplaySession = ReplaySession - { id :: UUID.UUID - , startedAt :: UTCTime - , endedAt :: UTCTime - , userId :: Maybe Text - , userName :: Maybe Text - , userEmail :: Maybe Text - } - deriving stock (Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON, HI.DecodeRow) - - -data SessionFilter = AllSessionRows | ErrorSessionRows | ReplaySessionRows - deriving stock (Bounded, Enum, Eq, Generic, Ord, Show) - deriving anyclass (Hashable) - - -data RumSession = RumSession - { id :: Text - , startedAt :: UTCTime - , endedAt :: UTCTime - , events :: Int64 - , errors :: Int64 - , views :: Int64 - , userId :: Maybe Text - , userName :: Maybe Text - , userEmail :: Maybe Text - , service :: Maybe Text - , lastPage :: Maybe Text - , userAgent :: Maybe Text - , hasReplay :: Bool - } - deriving stock (Eq, Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON, HI.DecodeRow) - - --- $setup --- >>> import Data.Aeson qualified as AE --- >>> import Data.Either (isLeft) --- >>> import Relude (LByteString) - - --- | Cache decoding preserves positive observation counts. --- --- >>> let valid = AE.eitherDecode "3" :: Either String ObservationCount --- >>> fmap (\count -> AE.eitherDecode (AE.encode count) == Right count) valid --- Right True --- >>> map (isLeft . (AE.eitherDecode :: LByteString -> Either String ObservationCount)) ["0", "-1"] --- [True,True] -newtype ObservationCount = ObservationCount Natural - deriving stock (Eq, Generic, Show) - deriving newtype (AE.ToJSON) - - -instance AE.FromJSON ObservationCount where - parseJSON = AE.parseJSON >=> maybe (fail "Observation count must be positive") pure . mkObservationCount - - -mkObservationCount :: Natural -> Maybe ObservationCount -mkObservationCount count = ObservationCount count <$ guard (count > 0) - - --- | A cached quantile is finite and nonnegative, and an estimated value lies in its bucket. --- --- >>> let valid = AE.eitherDecode "{\"value\":75,\"bounds\":[0,100]}" :: Either String VitalEstimate --- >>> fmap (\estimate -> AE.eitherDecode (AE.encode estimate) == Right estimate) valid --- Right True --- >>> map (isLeft . (AE.eitherDecode :: LByteString -> Either String VitalEstimate)) ["{\"value\":120,\"bounds\":[0,100]}", "{\"value\":-1,\"bounds\":null}", "{\"value\":1e400,\"bounds\":null}"] --- [True,True,True] -data VitalEstimate = VitalEstimate {value :: Double, bounds :: Maybe (Double, Double)} - deriving stock (Eq, Generic, Show) - deriving anyclass (AE.ToJSON) - - -instance AE.FromJSON VitalEstimate where - parseJSON = AE.genericParseJSON AE.defaultOptions >=> maybe (fail "Invalid vital quantile or bucket range") pure . mkEstimate - - -mkEstimate :: VitalEstimate -> Maybe VitalEstimate -mkEstimate e = e <$ guard (finite e.value && all (\(lo, hi) -> finite lo && finite hi && lo <= e.value && e.value <= hi) e.bounds) - where - finite v = v >= 0 && not (isInfinite v || isNaN v) - - --- | Constructor order is severity, least first: a population with several defects reports its last. -data VitalCoverage = InterruptedSeries | InvalidBuckets | InvalidReset | InvalidValue | MissingBaseline | OverlappingIntervals | UnboundedBucket | UnknownStart | UnknownTemporality | UnsupportedPopulation - deriving stock (Bounded, Enum, Eq, Generic, Read, Show) - deriving (AE.FromJSON, AE.ToJSON, HI.DecodeValue, HI.EncodeValue) via WrappedEnumSC 'Nothing "" VitalCoverage - - --- | SQL rank of a coverage column (NULL for @'complete'@), and the inverse, so @MAX@ picks the --- most severe defect by constructor order rather than by its spelling. -coverageRank, coverageName :: HI.Sql -> HI.Sql -coverageRank col = [HI.sql|CASE (|] <> col <> [HI.sql|)|] <> foldMap (\(rank, issue) -> [HI.sql| WHEN #{issue} THEN #{rank}|]) coverageRanks <> [HI.sql| END|] -coverageName col = [HI.sql|COALESCE(CASE (|] <> col <> [HI.sql|)|] <> foldMap (\(rank, issue) -> [HI.sql| WHEN #{rank} THEN #{issue}|]) coverageRanks <> [HI.sql| END, 'complete')|] - - -coverageRanks :: [(Int64, VitalCoverage)] -coverageRanks = zip [1 ..] [minBound .. maxBound] - - -data VitalMeasurement = Unmeasured | Measured ObservationCount VitalEstimate | Unavailable Natural VitalCoverage - deriving stock (Eq, Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON) - - -measurementValue :: VitalMeasurement -> Maybe Double -measurementValue = \case - Measured _ estimate -> Just estimate.value - Unmeasured -> Nothing - Unavailable _ _ -> Nothing - - -measurementSamples :: VitalMeasurement -> Natural -measurementSamples = \case - Measured (ObservationCount count) _ -> count - Unmeasured -> 0 - Unavailable count _ -> count - - -data VitalGrouping = FieldVital | TrendVital UTCTime | PageVital Text - deriving stock (Eq, Generic, Ord, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON) - - -data VitalPopulation = VitalPopulation - { grouping :: VitalGrouping - , metricName :: Text - , measurement :: VitalMeasurement - } - deriving stock (Eq, Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON) - - -instance HI.DecodeValue VitalPopulation where - decodeValue = - D.refine decode - $ D.record - $ (,,,,,,,) - <$> D.field (D.nullable D.timestamptz) - <*> D.field (D.nullable D.text) - <*> D.field (D.nonNullable D.text) - <*> D.field (D.nonNullable D.int8) - <*> D.field (D.nullable $ HI.decodeValue @VitalCoverage) - <*> D.field (D.nullable D.float8) - <*> D.field (D.nullable D.float8) - <*> D.field (D.nullable D.float8) - where - decode (bucket, page, metric, count, coverage, value, lower, upper) = do - grouping <- case (bucket, page) of - (Nothing, Nothing) -> Right FieldVital - (Just time, Nothing) -> Right (TrendVital time) - (Nothing, Just url) -> Right (PageVital url) - _ -> Left "Invalid vital population grouping" - unless (count >= 0) $ Left "Negative vital observation count" - measurement <- case (coverage, count, value, lower, upper) of - (Just issue, _, Nothing, _, _) -> Right $ Unavailable (fromIntegral count) issue - (Nothing, 0, Nothing, _, _) -> Right Unmeasured - (Nothing, _, Just measured, Nothing, Nothing) -> measuredEstimate count (VitalEstimate measured Nothing) - (Nothing, _, Just measured, Just lo, Just hi) -> measuredEstimate count (VitalEstimate measured (Just (lo, hi))) - _ -> Left "Invalid vital population measurement" - pure VitalPopulation{grouping, metricName = metric, measurement} - measuredEstimate count estimate = do - samples <- maybeToRight "Invalid measured vital population" (mkObservationCount $ fromIntegral count) - Measured samples <$> maybeToRight "Invalid measured vital population" (mkEstimate estimate) - - -data VitalRead = PopulationRead VitalPopulation | EpochRead Text UTCTime - - -data VitalReadKind = Population | Epoch - deriving stock (Read, Show) - deriving (HI.DecodeValue, HI.EncodeValue) via WrappedEnumSC 'Nothing "" VitalReadKind - - -instance HI.DecodeRow VitalRead where - decodeRow = - D.column - $ D.nonNullable - $ D.refine decode - $ D.record - $ (,,,) - <$> D.field (D.nonNullable $ HI.decodeValue @VitalReadKind) - <*> D.field (D.nullable $ HI.decodeValue @VitalPopulation) - <*> D.field (D.nullable D.text) - <*> D.field (D.nullable D.timestamptz) - where - decode (Population, Just population, Nothing, Nothing) = Right $ PopulationRead population - decode (Epoch, Nothing, Just series, Just start) = Right $ EpochRead series start - decode _ = Left "Invalid vital read row" - - -data VitalTrendPoint = VitalTrendPoint - { bucket :: UTCTime - , metricName :: Text - , measurement :: VitalMeasurement - } - deriving stock (Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON) - - -data PageVitalPoint = PageVitalPoint - { page :: Text - , metricName :: Text - , measurement :: VitalMeasurement - } - deriving stock (Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON) - - --- | A histogram contributes observations, not its export mean. All surfaces share the --- same population, with exact scalar quantiles and estimates over common explicit bounds. --- Reports are selected by end time; DELTA populations do not require a known start. -rumVitalPopulation :: (DB es, Labeled "timefusion" Hasql.Hasql :> es) => Bool -> ScopedQuery -> TimePicker.TimeWindow -> RumBucket -> Eff es [VitalPopulation] -rumVitalPopulation useTf scope window bucket = do - let interval :: Text - interval = case bucket of FiveMinutes -> "5 minutes"; OneHour -> "1 hour"; SixHours -> "6 hours" - vitalScope = - let names :: [Text] - names = [prefix <> name | name <- ["lcp", "inp", "cls", "fcp", "ttfb"], prefix <- ["browser.web_vital.", "k6.browser_web_vital_"]] - in [HI.sql|project_id=#{scope.projectId.toText} AND (#{scope.environment}::text IS NULL OR resource___deployment___environment___name = #{scope.environment}) - AND (#{scope.service}::text IS NULL OR resource___service___name = #{scope.service}) AND metric_name = ANY(#{names}::text[]) - AND (starts_with(metric_name,'browser.web_vital.') OR metric_type='GAUGE')|] - columns = - [HI.sql|timestamp,start_timestamp,series_id,metric_type,aggregation_temporality,flags, - CASE WHEN metric_type IN ('GAUGE') THEN value END AS value, - distribution_count,hist_bucket_counts,CASE WHEN hist_explicit_bounds IS NULL AND cardinality(hist_bucket_counts)=1 THEN ARRAY[]::float8[] ELSE hist_explicit_bounds END AS hist_explicit_bounds, - COALESCE(attributes #>> '{page,url}',attributes->>'page.url',attributes->>'url') AS page, - CASE WHEN starts_with(metric_name,'browser.web_vital.') THEN substring(metric_name FROM length('browser.web_vital.')+1) - ELSE substring(metric_name FROM length('k6.browser_web_vital_')+1) END::text AS metric|] - current = [HI.sql|SELECT |] <> columns <> [HI.sql| FROM otel_metrics WHERE |] <> vitalScope <> [HI.sql| AND timestamp>=#{window.fromTime} AND timestamp<=#{window.toTime}|] - withHistory epochs = case nonEmpty epochs of - Nothing -> current - Just selected -> - let oldest = minimum1 $ fmap snd selected - seriesIds :: [Text] - seriesIds = ordNub $ map fst epochs - exactEpochs = mconcat $ intersperse [HI.sql| OR |] [[HI.sql|(series_id::text=#{seriesId} AND start_timestamp=#{start})|] | (seriesId, start) <- epochs] - in current - <> [HI.sql| UNION ALL SELECT |] - <> columns - <> [HI.sql| FROM ( - SELECT *,ROW_NUMBER() OVER(PARTITION BY series_id,CASE WHEN flags & 1!=0 THEN NULL ELSE start_timestamp END ORDER BY timestamp DESC) AS predecessor - FROM otel_metrics WHERE |] - <> vitalScope - <> [HI.sql| AND series_id = ANY(#{seriesIds}::text[])|] - <> [HI.sql| AND timestamp>=#{oldest} AND timestamp<#{window.fromTime} AND (flags & 1!=0 OR |] - <> exactEpochs - <> [HI.sql|)) AS history WHERE predecessor=1|] - -- TimeFusion drops partitions when inheriting a named window with a new order/frame. - readPopulations source discoverEpochs = - Hasql.interpTimefusion useTf - $ [HI.sql|WITH source AS (|] - <> source - <> [HI.sql| -), previous AS ( - SELECT *, LAG(CASE WHEN flags & 1=0 THEN timestamp END) OVER(PARTITION BY series_id,start_timestamp ORDER BY timestamp) AS prior_timestamp, - MAX(CASE WHEN flags & 1!=0 THEN timestamp END) OVER(PARTITION BY series_id ORDER BY timestamp ROWS UNBOUNDED PRECEDING) AS last_marker, - LAG(CASE WHEN flags & 1=0 THEN timestamp END) OVER(PARTITION BY series_id ORDER BY timestamp) AS previous_series_timestamp, - LAG(CASE WHEN flags & 1=0 THEN distribution_count END) OVER(PARTITION BY series_id,start_timestamp ORDER BY timestamp) AS prior_count, - LAG(CASE WHEN flags & 1=0 THEN hist_bucket_counts END) OVER(PARTITION BY series_id,start_timestamp ORDER BY timestamp) AS prior_counts, - LAG(CASE WHEN flags & 1=0 THEN hist_explicit_bounds END) OVER(PARTITION BY series_id,start_timestamp ORDER BY timestamp) AS prior_bounds - FROM source -), points AS ( - SELECT *, time_bucket(#{interval}::interval,timestamp) AS bucket, - CASE WHEN metric_type IN ('GAUGE') AND value IS NOT NULL THEN 1 - WHEN aggregation_temporality='DELTA' THEN distribution_count - WHEN prior_count IS NOT NULL THEN distribution_count-prior_count - WHEN start_timestamp=timestamp THEN 0 - WHEN start_timestamp >= #{window.fromTime} AND start_timestamp < timestamp THEN distribution_count - ELSE 0 END AS observations, - CASE WHEN metric_type='GAUGE' THEN CASE WHEN value>=0 AND value<'Infinity'::float8 THEN 'complete' ELSE #{InvalidValue} END - WHEN metric_type!='HISTOGRAM' THEN #{UnsupportedPopulation} - WHEN distribution_count IS NULL OR hist_bucket_counts IS NULL OR hist_explicit_bounds IS NULL OR cardinality(hist_bucket_counts)!=cardinality(hist_explicit_bounds)+1 OR distribution_count<0 THEN #{InvalidBuckets} - WHEN start_timestamp>timestamp OR (start_timestamp IS NULL AND aggregation_temporality IS DISTINCT FROM 'DELTA') THEN #{UnknownStart} - WHEN aggregation_temporality='DELTA' AND previous_series_timestamp>start_timestamp THEN #{OverlappingIntervals} - WHEN aggregation_temporality='DELTA' THEN 'complete' - WHEN aggregation_temporality IS NULL OR aggregation_temporality!='CUMULATIVE' THEN #{UnknownTemporality} - WHEN last_marker>prior_timestamp OR (prior_timestamp IS NULL AND last_marker>=start_timestamp AND start_timestamp!=timestamp) THEN #{InterruptedSeries} - WHEN prior_count IS NOT NULL AND (distribution_countstart_timestamp THEN #{OverlappingIntervals} - WHEN prior_count IS NOT NULL THEN 'complete' - WHEN start_timestamp=timestamp THEN 'complete' - WHEN start_timestamp<#{window.fromTime} THEN #{MissingBaseline} - ELSE 'complete' END AS coverage - FROM previous WHERE timestamp>=#{window.fromTime} AND flags & 1=0 -), sides AS ( - SELECT points.*,unnest(ARRAY[0,1]) AS side FROM points -), expanded AS ( - SELECT sides.*,CASE WHEN value IS NOT NULL THEN 1 WHEN side=0 THEN distribution_count ELSE prior_count END AS expected_count, - unnest(CASE WHEN value IS NOT NULL THEN ARRAY[value]::float8[] - WHEN side=0 THEN hist_explicit_bounds||ARRAY[NULL]::float8[] ELSE prior_bounds||ARRAY[NULL]::float8[] END) AS bound, - unnest(CASE WHEN value IS NOT NULL THEN ARRAY[1]::bigint[] - WHEN side=0 THEN hist_bucket_counts ELSE prior_counts END) AS amount - FROM sides - WHERE side=0 OR (aggregation_temporality='CUMULATIVE' AND prior_count IS NOT NULL AND value IS NULL) -), indexed AS ( - SELECT *,CASE WHEN value IS NOT NULL THEN 1 ELSE COALESCE(array_position(CASE WHEN side=0 THEN hist_explicit_bounds ELSE prior_bounds END,bound),cardinality(CASE WHEN side=0 THEN hist_explicit_bounds ELSE prior_bounds END)+1) END AS position - FROM expanded -), cumulative AS ( - SELECT *,SUM(amount) OVER(PARTITION BY timestamp,series_id,start_timestamp,side ORDER BY bound NULLS LAST ROWS UNBOUNDED PRECEDING) AS cumulative, - SUM(amount) OVER(PARTITION BY timestamp,series_id,start_timestamp,side) AS bucket_count, - LAG(bound) OVER(PARTITION BY timestamp,series_id,start_timestamp,side ORDER BY position) AS preceding_bound, - ROW_NUMBER() OVER(PARTITION BY timestamp,series_id,start_timestamp,side ORDER BY position) AS bound_ordinal - FROM indexed -), validated AS ( - SELECT *,|] - <> coverageName ([HI.sql|MAX(|] <> coverageRank [HI.sql|CASE WHEN coverage IN (#{UnsupportedPopulation},#{InvalidValue}) THEN coverage WHEN amount IS NULL OR amount<0 OR bucket_count!=expected_count OR expected_count<0 OR (bound IS NOT NULL AND NOT(bound>=0 AND bound<'Infinity'::float8)) OR (bound_ordinal>1 AND bound IS NOT NULL AND (preceding_bound IS NULL OR bound<=preceding_bound)) THEN #{InvalidBuckets} ELSE coverage END|] <> [HI.sql|) OVER(PARTITION BY timestamp,series_id,start_timestamp)|]) - <> [HI.sql| AS point_coverage - FROM cumulative -), paired AS ( - SELECT *, MAX(CASE WHEN side=1 THEN cumulative END) OVER(PARTITION BY timestamp,series_id,start_timestamp,bound) AS prior_cumulative - FROM validated -), selected_raw AS ( - SELECT *,cumulative-COALESCE(prior_cumulative,0) AS cdf, - ROW_NUMBER() OVER(PARTITION BY timestamp,series_id,start_timestamp ORDER BY bound NULLS LAST) AS ordinal - FROM paired WHERE side=0 AND (value IS NOT NULL OR aggregation_temporality='DELTA' OR prior_count IS NULL OR prior_cumulative IS NOT NULL) -), selected AS ( - SELECT *,|] - <> coverageName ([HI.sql|MAX(|] <> coverageRank [HI.sql|CASE WHEN point_coverage='complete' AND (cdf<0 OR cdf [HI.sql|) OVER(PARTITION BY timestamp,series_id,start_timestamp)|]) - <> [HI.sql| AS effective_coverage - FROM (SELECT *,LAG(cdf,1,0) OVER(PARTITION BY timestamp,series_id,start_timestamp ORDER BY bound NULLS LAST) AS LAG_CDF FROM selected_raw) AS ordered -), totals AS ( - SELECT CASE WHEN GROUPING(bucket)=0 THEN 1 WHEN GROUPING(page)=0 THEN 2 ELSE 0 END AS kind, - bucket AS group_bucket,page AS group_page,metric,bound, - SUM(CASE WHEN value IS NULL AND observations>0 AND effective_coverage='complete' THEN cdf ELSE 0 END)::bigint AS histogram_cdf, - COUNT(*) FILTER(WHERE value IS NULL AND observations>0 AND effective_coverage='complete') AS histogram_points_at_bound, - SUM(CASE WHEN value IS NOT NULL AND effective_coverage='complete' THEN observations ELSE 0 END)::bigint AS scalar_observations, - SUM(CASE WHEN ordinal=1 AND effective_coverage='complete' THEN observations ELSE 0 END)::bigint AS observations, - COUNT(*) FILTER(WHERE ordinal=1 AND value IS NULL AND observations>0 AND effective_coverage='complete') AS histogram_points, - MAX(|] - <> coverageRank [HI.sql|effective_coverage|] - <> [HI.sql|) AS coverage - FROM selected GROUP BY GROUPING SETS((metric,bound),(bucket,metric,bound),(page,metric,bound)) -), distribution AS ( - SELECT *,SUM(observations) OVER population AS total, - SUM(histogram_points) OVER population AS total_histogram_points, - |] - <> coverageName [HI.sql|MAX(coverage) OVER population|] - <> [HI.sql| AS population_coverage, - SUM(scalar_observations) OVER scalar_population AS scalar_cdf - FROM totals - WINDOW population AS (PARTITION BY kind,group_bucket,group_page,metric), - scalar_population AS (PARTITION BY kind,group_bucket,group_page,metric ORDER BY bound NULLS LAST ROWS UNBOUNDED PRECEDING) -), common AS ( - SELECT *,CASE WHEN total_histogram_points=0 THEN 1+0.75::float8*(total-1)::float8 ELSE 0.75::float8*total::float8 END AS quantile_position, - MAX(CASE WHEN histogram_points_at_bound=total_histogram_points THEN bound END) OVER preceding_population AS histogram_lower_bound, - MIN(CASE WHEN histogram_points_at_bound=total_histogram_points THEN bound END) OVER following_population AS histogram_upper_bound, - MAX(CASE WHEN histogram_points_at_bound=total_histogram_points THEN histogram_cdf END) OVER cumulative_population AS histogram_lower_cdf, - MIN(CASE WHEN histogram_points_at_bound=total_histogram_points THEN histogram_cdf END) OVER following_population AS histogram_upper_cdf - FROM distribution WHERE total_histogram_points=0 OR histogram_points_at_bound=total_histogram_points OR scalar_observations>0 - WINDOW preceding_population AS (PARTITION BY kind,group_bucket,group_page,metric ORDER BY bound NULLS LAST ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING), - following_population AS (PARTITION BY kind,group_bucket,group_page,metric ORDER BY bound NULLS LAST ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING), - cumulative_population AS (PARTITION BY kind,group_bucket,group_page,metric ORDER BY bound NULLS LAST ROWS UNBOUNDED PRECEDING) -), interpolated AS ( - SELECT *,CASE WHEN histogram_points_at_bound=total_histogram_points THEN histogram_cdf::float8 - WHEN COALESCE(histogram_lower_cdf,0)=histogram_upper_cdf THEN histogram_upper_cdf::float8 - WHEN histogram_upper_bound IS NOT NULL THEN COALESCE(histogram_lower_cdf,0)::float8+ - (histogram_upper_cdf-COALESCE(histogram_lower_cdf,0))::float8*(bound-COALESCE(histogram_lower_bound,0))/(histogram_upper_bound-COALESCE(histogram_lower_bound,0)) END AS histogram_at_bound - FROM common -), combined AS ( - SELECT *,COALESCE(histogram_at_bound,histogram_lower_cdf::float8,0)+scalar_cdf::float8 AS cdf FROM interpolated -), ranked AS ( - SELECT *,CASE WHEN total_histogram_points=0 THEN CEIL(quantile_position) ELSE quantile_position END AS quantile_target, - LAG(bound) OVER population AS lower_bound, - LAG(cdf,1,0) OVER population AS lower_cdf, - LAG(histogram_at_bound,1,0) OVER population AS prior_histogram_cdf, - ROW_NUMBER() OVER population AS quantile_ordinal - FROM combined - WINDOW population AS (PARTITION BY kind,group_bucket,group_page,metric ORDER BY bound NULLS LAST) -), quantiles AS ( - SELECT *,CASE WHEN population_coverage='complete' AND total>0 AND (bound IS NULL OR histogram_at_bound IS NULL) THEN #{UnboundedBucket} - WHEN population_coverage!='complete' THEN population_coverage END AS issue, - CASE WHEN population_coverage!='complete' OR total=0 OR bound IS NULL OR histogram_at_bound IS NULL THEN NULL - WHEN total_histogram_points=0 THEN CASE WHEN lower_cdfcdf-scalar_observations::float8 THEN bound - ELSE COALESCE(lower_bound,0)::float8+(bound-COALESCE(lower_bound,0))::float8* - (quantile_position-lower_cdf::float8)/(histogram_at_bound-prior_histogram_cdf)::float8 END AS p75 - FROM ranked WHERE ((total=0 OR population_coverage!='complete') AND quantile_ordinal=1) - OR (total>0 AND population_coverage='complete' - AND cdf>=quantile_target - AND lower_cdf0 AND total_histogram_points>0 AND (histogram_points_at_bound=total_histogram_points OR COALESCE(histogram_lower_cdf,0)!=histogram_upper_cdf) THEN COALESCE(histogram_lower_bound,0)::float8 END, - CASE WHEN issue IS NULL AND total>0 AND total_histogram_points>0 AND (histogram_points_at_bound=total_histogram_points OR COALESCE(histogram_lower_cdf,0)!=histogram_upper_cdf) THEN histogram_upper_bound::float8 END) AS population,NULL::text AS epoch_series,NULL::timestamptz AS epoch_start -FROM quantiles WHERE kind!=2 OR group_page IS NOT NULL -UNION ALL -SELECT #{Epoch}::text,NULL,series_id::text,start_timestamp FROM ( - SELECT DISTINCT series_id,start_timestamp FROM selected - WHERE #{discoverEpochs} AND metric_type='HISTOGRAM' AND aggregation_temporality='CUMULATIVE' AND start_timestamp<#{window.fromTime} -) AS epochs -) -SELECT ROW(read_kind,population,epoch_series,epoch_start) FROM reads -|] - initial <- readPopulations current True - let epochs = [(series, start) | EpochRead series start <- initial] - populationReads <- if null epochs then pure initial else readPopulations (withHistory epochs) False - let populations = [population | PopulationRead population <- populationReads] - -- Grouped pages are ordered/capped here to avoid native final-sort memory pressure. - let (fieldAndTrend, pageEntries) = partitionWith (\population -> case population.grouping of PageVital url -> Right (url, [population]); FieldVital -> Left population; TrendVital{} -> Left population) populations - pageGroups = Map.fromListWith (<>) pageEntries - orderedPages = sortWith (\(url, rows) -> (Down $ sum $ map (measurementSamples . (.measurement)) rows, url)) $ Map.toList pageGroups - pure - $ sortWith (\population -> (population.grouping, population.metricName)) fieldAndTrend - <> concatMap (sortWith (.metricName) . snd) (take 150 orderedPages) - - --- | The Overview's headline numbers from one scan of the window; a window with no browser telemetry yields no row. -data RumPulse = RumPulse - { sessions :: Int64 - , pageViews :: Int64 - , errors :: Int64 - , p75LoadMs :: Maybe Double - } - deriving stock (Eq, Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON, HI.DecodeRow) - - -data RumQueryResult - = PulseResult (Maybe RumPulse) - | PagesResult [RumPage] - | ErrorsResult [RumError] - | SessionsResult [RumSession] - | SessionDetailResult (Maybe RumSession) - | VitalPopulationResult [VitalPopulation] - | BreakdownResult [RumBreakdown] - deriving stock (Generic, Show) - deriving anyclass (AE.FromJSON, AE.ToJSON) - - -data RumQuery - = PulseQuery - | PagesQuery - | ErrorsQuery - | SessionSearchQuery (Maybe Text) SessionFilter - | SessionDetailQuery Text - | VitalPopulationQuery RumBucket - | BreakdownQuery - deriving stock (Eq, Generic, Ord, Show) - deriving anyclass (Hashable) - - --- | Bumped when a query's cached payload shape or semantics change, so an older replica's --- entry is never decoded here. -queryVersion :: RumQuery -> Word -queryVersion = \case - PulseQuery -> 1 - PagesQuery -> 0 - ErrorsQuery -> 0 - SessionSearchQuery{} -> 2 - SessionDetailQuery{} -> 2 - VitalPopulationQuery{} -> 2 - BreakdownQuery -> 0 - - --- | @service@ is part of the key, not a filter applied after it. Without it a page scoped to --- one service would be served another service's cached rows — the cache would hand back --- exactly the cross-team mixing the scope exists to prevent. -data RumCacheKey = RumCacheKey - { project :: Projects.ProjectId - , query :: RumQuery - , environment :: Maybe Text - , service :: Maybe Text - , from :: Maybe Text - , to :: Maybe Text - , since :: Maybe Text - } - deriving stock (Eq, Generic, Ord, Show) - deriving anyclass (Hashable) - - -rumCacheDbKey :: RumCacheKey -> Text -rumCacheDbKey key = toXXHash $ show key <> ":v" <> show (queryVersion key.query) - - --- | Shared L2 for expensive panel/stats results, keyed by the hashed memory-cache key. --- The in-memory caches are per replica; without this layer every replica paid each cold --- scan once per TTL (the vitals-detail scan alone costs ~25s), and the first visitor --- after every expiry always ate one. Generic over the payload so the API catalog's host --- and endpoint stats share the table with the RUM panels. -rumPanelCacheGet :: (AE.FromJSON a, DB es) => Text -> Eff es (Maybe a) -rumPanelCacheGet key = - fmap (unAesonText . HI.getOneColumn) <$> Hasql.interpOne [HI.sql|SELECT payload FROM rum_panel_cache WHERE cache_key = #{key} AND expires_at > now()|] - - --- | Payload plus staleness: 'True' when the entry is past its freshness expiry but still --- inside the prune horizon ('rumPanelCacheSet' deletes rows expired by over twelve hours). --- The RUM page serves stale entries instantly and revalidates in the background. Twelve --- hours spans the overnight gap, so the morning's first visit paints last night's list and --- refreshes it instead of paying a cold 24h scan. Older entries are treated as absent. -rumPanelCacheGetStale :: (AE.FromJSON a, DB es) => Text -> Eff es (Maybe (a, Bool)) -rumPanelCacheGetStale key = - firstF unAesonText <$> Hasql.interpOne [HI.sql|SELECT payload, expires_at <= now() FROM rum_panel_cache WHERE cache_key = #{key} AND expires_at > now() - interval '12 hours'|] - - --- | Memory-miss path in one step: read the shared table, else compute and publish for --- the fleet. @rawKey@ is hashed, so callers pass a readable @show@n key. -withSharedCache :: (AE.FromJSON a, AE.ToJSON a, DB es) => Text -> Int64 -> Eff es a -> Eff es a -withSharedCache rawKey ttl compute = do - let key = toXXHash rawKey - rumPanelCacheGet key >>= maybe (compute >>= \fresh -> fresh <$ rumPanelCacheSet key ttl fresh) pure - - -rumPanelCacheSet :: (AE.ToJSON a, DB es) => Text -> Int64 -> a -> Eff es () -rumPanelCacheSet key ttlSeconds value = do - let payload = AesonText value - Hasql.interpExecute_ - [HI.sql|INSERT INTO rum_panel_cache (cache_key, payload, expires_at) - VALUES (#{key}, #{payload}, now() + make_interval(secs => #{ttlSeconds}::double precision)) - ON CONFLICT (cache_key) DO UPDATE SET payload = EXCLUDED.payload, expires_at = EXCLUDED.expires_at|] - -- Expired rows are pruned on write: writes are rare (one per cold panel per TTL), and it - -- keeps the table from needing its own cleanup job. - Hasql.interpExecute_ [HI.sql|DELETE FROM rum_panel_cache WHERE expires_at < now() - interval '12 hours'|] diff --git a/src/Pages/BodyWrapper.hs b/src/Pages/BodyWrapper.hs index 7043ed14e..818cfcba7 100644 --- a/src/Pages/BodyWrapper.hs +++ b/src/Pages/BodyWrapper.hs @@ -373,7 +373,7 @@ bodyWrapper bcfg child = do -- Vendored (not unpkg): a third-party CDN must never sit on our critical path — a -- slow or unreachable CDN stalled first paint for every visitor. defer keeps even -- the local copy off the parser. - when browserMonitoring $ script_ [src_ $ assetUrl "/public/assets/deps/monoscope/monoscope-0.11.6.min.js", defer_ ""] ("" :: Text) + when browserMonitoring $ script_ [src_ $ assetUrl "/public/assets/deps/monoscope/monoscope-0.13.0.min.js", defer_ ""] ("" :: Text) -- Hashed URLs for assets the TS bundle references by path (see web-components/src/assets.ts). -- Those references can't carry a compile-time hash of their own, and /public/assets/* is @@ -1214,7 +1214,7 @@ navFlyoutItems :: Text -> Text -> [(Text, Text)] navFlyoutItems pidTxt = \case "Explorer" -> [(label, p path) | (label, path) <- explorerTabs] "Infrastructure" -> [(label, p path) | (label, path) <- infrastructureTabs] - "Real User Monitoring" -> [("Overview", p "/rum"), ("Sessions", p "/rum?tab=sessions"), ("Performance", p "/rum?tab=performance")] + "Real User Monitoring" -> [("Dashboard", p "/rum"), ("Sessions", p "/rum/sessions")] -- API Docs carries no host: it is the whole project's learned spec. The -- per-host and per-endpoint scopes are reached from the catalog rows. "API Catalog" -> [("Incoming", p "/api_catalog?request_type=Incoming"), ("Outgoing", p "/api_catalog?request_type=Outgoing"), ("API Docs", p "/api_catalog/docs?request_type=Incoming")] diff --git a/src/Pages/Charts/Charts.hs b/src/Pages/Charts/Charts.hs index 2170c2c35..0cdaeae2f 100644 --- a/src/Pages/Charts/Charts.hs +++ b/src/Pages/Charts/Charts.hs @@ -44,7 +44,7 @@ import Pages.Charts.Types (DataType (..), MetricsData (..), MetricsStats (..)) import Pkg.Components.TimePicker qualified as Components import Pkg.DeriveUtils (DB) import Pkg.Metrics qualified as Metrics -import Pkg.Parser (BinDensity, QueryComponents (finalSummarizeQuery, whereClause), RangeEnd (..), SqlQueryCfg (..), applyScopedQuery, buildDateRange, buildEnvFilter, buildServiceFilter, defSqlQueryCfg, mkScopedQuery, pSource, queryASTToComponents, replacePlaceholders, variablePresets, variablePresetsKQL) +import Pkg.Parser (BinDensity, QueryComponents (finalSummarizeQuery, whereClause), RangeEnd (..), SqlQueryCfg (..), applyScopedQuery, buildDateRange, buildEnvFilter, buildServiceFilter, defSqlQueryCfg, fillQueryTemplate, mkScopedQuery, pSource, queryASTToComponents, variablePresets, variablePresetsKQL) import Pkg.Parser.Expr (Subject (..)) import Pkg.Parser.Stats (BinFunction (..), ByClauseItem (..), Section (..), Sources (..), SummarizeByClause (..), parseQueryDiagnosed, queryErrorText) import Pkg.QueryCache qualified as QC @@ -163,7 +163,7 @@ queryMetrics dbSource (maybeToMonoid -> respDataType) pidM (Utils.nonEmptyT -> q -- Validated against `source`, not blind: a widget can carry `source=metrics` in the -- request rather than in the query text, and checking those fields against -- otel_logs_and_spans rejects the metrics table's own columns (`metric_name`, `value`). - case first queryErrorText $ parseQueryDiagnosed source $ replacePlaceholders mappngKQL $ maybeToMonoid queryM of + case first queryErrorText $ parseQueryDiagnosed source $ fillQueryTemplate mappngKQL $ maybeToMonoid queryM of Left err -> pure (emptyMetricsFor now fromD toD){error = Just err} Right queryAST -> runQueryAST authCtx dbSource respDataType pid source density environment service (maybe False (T.null . snd) currentRange) queryAST (maybeToMonoid queryM) querySQLM mappngSQL now fromD toD @@ -187,7 +187,7 @@ runQueryAST authCtx dbSource respDataType pid source binDensity environment serv pure (emptyMetricsFor now fromD toD){error = Just message} Just querySQL -> do let tbl = sourceTable source - sqlQuery = replacePlaceholders mappngSQL querySQL + sqlQuery = fillQueryTemplate mappngSQL querySQL convertTimestampsToMs <$> withChartSpan tbl @@ -225,7 +225,7 @@ runRawQuery authCtx dbSource decoder cfg ast kql template mapping liveRange prog M.fromList [("query_ast_filters", rawAstFilters cacheCfg components)] <> variablePresets cfg.binDensity cfg.pid.toText from to [] cfg.currentTime <> mapping - sql = replacePlaceholders canonical template + sql = fillQueryTemplate canonical template fetch = liftIO $ fetchMetricsDataWithProgress progress decoder sql cfg.currentTime from to authCtx dbSource >>= either throwIO pure case (endpoint, from, to) of (Just endpointHash, Just start, Just end) -> @@ -753,7 +753,7 @@ queryMetricsStream dbSource dataTypeM pidM queryM querySQLM sinceM fromM toM sou raw = Utils.nonEmptyT querySQLM parsed = maybe - (first queryErrorText $ parseQueryDiagnosed source $ replacePlaceholders mappingKQL $ maybeToMonoid $ Utils.nonEmptyT queryM) + (first queryErrorText $ parseQueryDiagnosed source $ fillQueryTemplate mappingKQL $ maybeToMonoid $ Utils.nonEmptyT queryM) Left (raw >>= rawSqlScopeError environment service) scope = mkScopedQuery pid (fromD, toD) environment service diff --git a/src/Pages/Components.hs b/src/Pages/Components.hs index 245751361..36225b6a8 100644 --- a/src/Pages/Components.hs +++ b/src/Pages/Components.hs @@ -1,4 +1,4 @@ -module Pages.Components (drawer_, PanelStyle (..), PanelCfg (..), panel_, entityHeader_, detailSection_, pivotLinks_, disclosure_, settingsSection_, settingsH2_, sectionLabel_, fieldLabel_, headerRow_, navBar, brandLogo_, resizer_, resizerWith_, detailTab_, httpTab_, tabPanel_, segmented_, periodToggle_, Deferred (..), RefreshingDeferred (..), withDeferredBody, deferredShell_, lazyPanel_, timeRefreshListener_, timeWindowVals_, drawerLoadingSkeleton_, tableSkeleton_, chartSkeleton_, EmptyStateCfg (..), EmptyStateSize (..), EmptyStateAction (..), emptyState_, callout_, BadgeColor (..), IconBadgeSize (..), iconBadge_, tonePill_, colorChip_, metadataChip_, metaChip_, connectionBadge_, silenceBadge_, statFigure_, factGrid_, kvList_, sparkline_, eventsCountCell_, lastSeenCell_, dateTime, localTimeFmt_, FieldSize (..), FieldCfg (..), formField_, formSelectField_, formCheckbox_, options_, roleOptions_, tagInput_, toggleRow_, searchInput_, copyField_, copyButton_, facetRail_, facetSection_, facetOption_, ModalCfg (..), modalWith_, formActionsModal_, dangerAction_, floatingDialog_, dialogField_, kbdHints_, durationMenu_, primaryButton_, inlineIconBtn_, RowAction (..), rowActions_, externalLink_, installationSettingsLink_, dirtyFormSaveAttr_, resetFormOnSuccessAttr_, detailsClosedBelowAttr_, keyboardActivateAttr_, listboxNavAttr_, copySourceAttr_, filterInputAttr_, TraceFrame (..), stackTrace_, stackFrames_, codeContextUrl, curlCommand, getTargetPage, abbreviateUnit, agoText, durationQuery, untilLabel, paymentPlanPicker) where +module Pages.Components (drawer_, PanelStyle (..), PanelCfg (..), panel_, entityHeader_, detailSection_, pivotLinks_, disclosure_, settingsSection_, settingsH2_, sectionLabel_, fieldLabel_, headerRow_, navBar, brandLogo_, resizer_, resizerWith_, detailTab_, httpTab_, tabPanel_, segmented_, periodToggle_, Deferred (..), RefreshingDeferred (..), withDeferredBody, deferredShell_, lazyPanel_, timeRefreshListener_, drawerLoadingSkeleton_, tableSkeleton_, chartSkeleton_, EmptyStateCfg (..), EmptyStateSize (..), EmptyStateAction (..), emptyState_, callout_, BadgeColor (..), IconBadgeSize (..), iconBadge_, tonePill_, colorChip_, metadataChip_, metaChip_, connectionBadge_, silenceBadge_, statFigure_, factGrid_, kvList_, sparkline_, eventsCountCell_, lastSeenCell_, dateTime, localTimeFmt_, FieldSize (..), FieldCfg (..), formField_, formSelectField_, formCheckbox_, options_, roleOptions_, tagInput_, toggleRow_, searchInput_, copyField_, copyButton_, facetRail_, facetSection_, facetOption_, ModalCfg (..), modalWith_, formActionsModal_, dangerAction_, floatingDialog_, dialogField_, kbdHints_, durationMenu_, primaryButton_, inlineIconBtn_, RowAction (..), rowActions_, externalLink_, installationSettingsLink_, dirtyFormSaveAttr_, resetFormOnSuccessAttr_, detailsClosedBelowAttr_, keyboardActivateAttr_, listboxNavAttr_, copySourceAttr_, filterInputAttr_, TraceFrame (..), stackTrace_, stackFrames_, codeContextUrl, curlCommand, getTargetPage, abbreviateUnit, agoText, durationQuery, untilLabel, paymentPlanPicker) where import Data.Default (Default (..)) import Data.List (elemIndex, findIndex, lookup) @@ -769,16 +769,14 @@ formSelectField_ size lbl name required options = FieldMd -> "select w-full h-12 cursor-pointer" --- | @Collapsible open@ is a details disclosure; @FlushCard@ a bordered card with a header --- strip and an unpadded body, for a table or chart that sits flush. -data PanelStyle = Raised | Collapsible Bool | FlushCard +-- | @Collapsible open@ is a details disclosure. +data PanelStyle = Raised | Collapsible Bool data PanelCfg = PanelCfg { icon :: Maybe Text , subtitle :: Maybe Text , sectionId :: Maybe Text -- id of a collapsible panel's details element - , action :: Maybe (Text, Text) -- (label, url) link at a flush card header's right edge } deriving stock (Generic) deriving anyclass (Default) @@ -786,13 +784,6 @@ data PanelCfg = PanelCfg panel_ :: Monad m => PanelStyle -> PanelCfg -> Text -> HtmlT m () -> HtmlT m () panel_ style cfg title content = case style of - FlushCard -> section_ [class_ "overflow-hidden rounded-lg border border-strokeWeak surface-raised"] do - header_ [class_ "flex items-start justify-between gap-3 border-b border-strokeWeak px-3 py-2.5"] do - div_ [class_ "min-w-0"] do - h2_ [class_ "text-sm font-semibold text-textStrong"] $ toHtml title - whenJust cfg.subtitle $ p_ [class_ "mt-0.5 text-xs text-textWeak"] . toHtml - forM_ cfg.action \(label, url) -> a_ [href_ url, class_ "shrink-0 text-xs font-medium text-textBrand hover:underline"] $ toHtml label - content Raised -> div_ [class_ "surface-raised rounded-2xl p-4 relative"] do span_ [class_ "flex items-center gap-2 text-sm font-semibold text-textStrong mb-3"] do whenJust cfg.icon \ic -> faSprite_ ic "regular" "w-4 h-4 text-iconNeutral" diff --git a/src/Pages/Dashboards.hs b/src/Pages/Dashboards.hs index a1dec0585..ce6f4084c 100644 --- a/src/Pages/Dashboards.hs +++ b/src/Pages/Dashboards.hs @@ -4,6 +4,7 @@ module Pages.Dashboards ( dashboardSettledPostH, dashboardTabRenamePatchH, entrypointRedirectGetH, + rumRedirectH, DashboardGet (..), DashboardSettleSample (..), DashboardNavigation (..), @@ -95,7 +96,6 @@ import Models.Projects.ProjectMembers qualified as ManageMembers import Models.Projects.Projects qualified as Projects import Models.Telemetry.ServiceGraph (ServiceGraph (..), ServiceNode (..), endpointDependencyGraphForRange) import NeatInterpolation -import Network.HTTP.Types.URI qualified as URI import OpenTelemetry.Attributes qualified as OA import Pages.BodyWrapper import Pages.Charts.Charts qualified as Charts @@ -113,7 +113,7 @@ import Pkg.Components.TimePicker qualified as TimePicker import Pkg.Components.Widget qualified as Widget import Pkg.DeriveUtils (UUIDId (..), WrappedEnumSC (..), assetUrl, bulkActionSlug) import Pkg.Metrics qualified as Metrics -import Pkg.Parser (QueryComponents (..), SqlQueryCfg (..), applyScopedQuery, binDensityFor, constantToKQLList, constantToSQLList, defSqlQueryCfg, fixedUTCTime, mkScopedQuery, parseQueryToComponents, replacePlaceholders, variablePresetsKQL) +import Pkg.Parser (QueryComponents (..), SqlQueryCfg (..), applyScopedQuery, binDensityFor, browserKql, constantToKQLList, constantToSQLList, defSqlQueryCfg, fillQueryTemplate, fixedUTCTime, mkScopedQuery, parseQueryToComponents, variablePresetsKQL) import Pkg.Parser.Expr (sqlStringLit) import Pkg.SchemaLearning.Catalog qualified as Catalog import Relude hiding (ask) @@ -951,7 +951,7 @@ processWidget prefill pid now timeRange allParams widgetBase = do -- resolved here or the list searches for the literal "{{var-endpointHash}}". -- Every other type reaches /chart_data, which interpolates at fetch time. resolveLogsQuery - | widgetBase.wType == Widget.WTLogs = fmap (replacePlaceholders (variablePresetsKQL def pid.toText fromD toD allParams now)) + | widgetBase.wType == Widget.WTLogs = fmap (fillQueryTemplate (variablePresetsKQL def pid.toText fromD toD allParams now)) | otherwise = Relude.id widget = widgetBase & #id %~ (<|> (slugify <$> widgetBase.title)) & #_projectId %~ (<|> Just pid) & #rawQuery .~ widgetBase.query & #query %~ resolveLogsQuery @@ -2265,6 +2265,23 @@ entrypointRedirectGetH baseTemplate title tags pid qparams = do pure $ addHeader redirectTo NoContent +-- | @/rum@ (and the older @/rum/dashboard@) opens the RUM dashboard; @/rum/sessions@ opens the +-- Explorer sessions view over browser telemetry, keeping the window. Shared links from the old +-- page (@/rum?tab=sessions&session=…@) land on the same view, narrowed to that session. +rumRedirectH :: Projects.ProjectId -> [Text] -> [(Text, Maybe Text)] -> ATAuthCtx (Headers '[Header "Location" Text] NoContent) +rumRedirectH pid segments params = case (segments, param "tab") of + (["sessions"], _) -> sessions + ([], Just "sessions") -> sessions + ([], _) -> dashboard + (["dashboard"], _) -> dashboard + _ -> throwError err404 + where + param k = join $ lookup k params + dashboard = entrypointRedirectGetH "rum.yaml" "Real User Monitoring" ["rum", "browser", "frontend", "web-vitals"] pid params + query = maybe browserKql (("attributes.session.id == " <>) . kqlQuoted) (param "session") + sessions = pure $ addHeader (timeScopedUrl ("/p/" <> pid.toText <> "/log_explorer") [("viz_type", "sessions"), ("query", query)] (param "from") (param "to") (param "since")) NoContent + + -- | Form data for renaming a dashboard data DashboardRenameForm = DashboardRenameForm { title :: Text @@ -2622,12 +2639,6 @@ activeTabSlugKey :: Text activeTabSlugKey = "activeTabSlug" --- | Percent-encoded query string, prefixed with @?@ when non-empty. --- @[("key", Just "value"), ("empty", Nothing)]@ becomes @"?key=value&empty"@. -queryStringFrom :: [(Text, Maybe Text)] -> Text -queryStringFrom = decodeUtf8 . URI.renderQuery True . map (bimap encodeUtf8 (fmap encodeUtf8)) - - -- | Add variable defaults to params for any variable not already in params. -- This ensures constants can reference variables like {{var-resource}} even when not in URL. -- | Fill in a dashboard's declared variables that the request did not supply. diff --git a/src/Pages/Endpoints.hs b/src/Pages/Endpoints.hs index 13de6864b..7a8f9d9fb 100644 --- a/src/Pages/Endpoints.hs +++ b/src/Pages/Endpoints.hs @@ -15,12 +15,12 @@ import Lucid import Models.Apis.Endpoints qualified as Endpoints import Models.Apis.SchemaCatalog qualified as SchemaCatalog import Models.Projects.Projects qualified as Projects -import Models.Telemetry.RUM qualified as RUMData import Pages.BodyWrapper (BWConfig (..), PageCtx (..), checkFreeTierStatus, mkPageCtx, navTabAttrs) import Pages.Components (RowAction (..), copyButton_, detailTab_, eventsCountCell_, lastSeenCell_, periodToggle_, rowActions_, sparkline_, tabPanel_) import Pkg.Components.Table (BulkAction (..), Column (..), Config (..), EmptyStateAction (..), Features (..), Pagination (..), SearchMode (..), TabFilter (..), TabFilterOpt (..), Table (..), TableHeaderActions (..), TableResponse (..), TableRows (..), ZeroState (..), col, withAttrs, withColHeaderExtra) import Pkg.DeriveUtils (WrappedEnumSC (..), assetUrl, bulkActionSlug) import Pkg.OpenApi qualified as OpenApi +import Pkg.QueryCache qualified as QueryCache import PyF qualified import Relude hiding (ask, asks) import System.Config (AuthContext (..), EnvConfig (..)) @@ -153,7 +153,7 @@ catalogColumns pid baseUrl period = withStatsCache :: (AE.FromJSON v, AE.ToJSON v, Hashable k, Show k) => Cache.Cache k v -> Text -> k -> Endpoints.StatsMode -> (Endpoints.StatsMode -> ATAuthCtx v) -> ATAuthCtx v withStatsCache cache tag key mode fetch = case mode of Endpoints.ShellOnly -> fetch Endpoints.ShellOnly - Endpoints.WithStats -> Cache.fetchWithCache cache key \_ -> RUMData.withSharedCache (tag <> show key) 300 (fetch Endpoints.WithStats) + Endpoints.WithStats -> Cache.fetchWithCache cache key \_ -> QueryCache.withSharedCache (tag <> show key) 300 (fetch Endpoints.WithStats) logExplorerHref :: Projects.ProjectId -> Text -> Text diff --git a/src/Pages/Issues.hs b/src/Pages/Issues.hs index 571ba93e4..b0b521736 100644 --- a/src/Pages/Issues.hs +++ b/src/Pages/Issues.hs @@ -2135,7 +2135,7 @@ aiChatResponse_ pid userQuery explanation widgetsM toolCallsM systemPromptM = dataRows <- obj AE..: "data" :: Parser (V.Vector (V.Vector AE.Value)) count <- obj AE..:? "count" let source = AE.toJSON $ V.cons (AE.toJSON <$> V.fromList headers) (fmap AE.toJSON <$> dataRows) - pure Widget.WidgetDataset{source, rowsPerMin = Nothing, value = count, servedValue = Nothing, from = Nothing, to = Nothing, stats = Nothing} + pure Widget.WidgetDataset{source, rowsPerMin = Nothing, value = count, from = Nothing, to = Nothing, stats = Nothing} -- $setup diff --git a/src/Pages/RealUserMonitoring.hs b/src/Pages/RealUserMonitoring.hs deleted file mode 100644 index 96a402e23..000000000 --- a/src/Pages/RealUserMonitoring.hs +++ /dev/null @@ -1,1959 +0,0 @@ --- | Real User Monitoring projects browser OpenTelemetry and session recordings into one --- investigation surface. The dashboard template is the customizable aggregate view; this page --- owns the user/session workflow that a dashboard cannot express. -module Pages.RealUserMonitoring ( - rumGetH, - rumGetScopedH, - RumGet (..), - RumData (..), - RumSession (..), - RumLinks (..), - SessionFilter (..), - Vital (..), - VitalRating (..), - classifyVital, - pageLabel, - binnedSql, - activitySql, - sessionsSql, - p75Sql, - browserSql, - pageViewSql, - errorSql, -) where - -import Data.Aeson qualified as AE -import Data.Cache qualified as Cache -import Data.Char (isDigit, isLetter, isLower) -import Data.Default (def) -import Data.Effectful.Hasql (Hasql) -import Data.Effectful.Hasql qualified as Hasql -import Data.Fixed (mod') -import Data.List (lookup) -import Data.Map.Strict qualified as M -import Data.Text qualified as T -import Data.Text.Display (Display, display) -import Data.Time (NominalDiffTime, UTCTime, addUTCTime, diffUTCTime) -import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) -import Data.UUID qualified as UUID -import Data.Vector qualified as V -import Effectful (Eff, (:>)) -import Effectful.Concurrent.Async (pooledForConcurrently) -import Effectful.Labeled (Labeled) -import Effectful.Reader.Static qualified as Reader -import Effectful.Time qualified as Time -import Hasql.Interpolate qualified as HI -import Lucid -import Lucid.Aria qualified as Aria -import Lucid.Base (TermRaw (termRaw)) -import Lucid.Htmx (hxGet_, hxIndicator_, hxPushUrl_, hxSelect_, hxSwap_, hxTarget_, hxTrigger_) -import Models.Projects.Projects qualified as Projects -import Models.Telemetry.RUM (PageVitalPoint (..), ReplaySession (..), RumBreakdown (..), RumBucket (..), RumCacheKey (..), RumError (..), RumPage (..), RumPulse (..), RumQuery (..), RumQueryResult (..), RumSession (..), SessionFilter (..), VitalEstimate (..), VitalGrouping (..), VitalMeasurement (..), VitalPopulation (..), VitalTrendPoint (..), rumCacheDbKey, rumPanelCacheGetStale, rumPanelCacheSet) -import Models.Telemetry.RUM qualified as RUM -import Pages.BodyWrapper (BWConfig (..), PageCtx (..), mkPageCtx) -import Pages.Components (Deferred (..), EmptyStateAction (..), EmptyStateCfg (..), EmptyStateSize (..), withDeferredBody) -import Pages.Components qualified as Components -import Pkg.Components.Table qualified as Table -import Pkg.Components.TimePicker qualified as TimePicker -import Pkg.Components.Widget qualified as Widget -import Pkg.DeriveUtils (DB, WrappedEnumSC (..), escapeRegex, rawSql) -import Pkg.ErrorFingerprint (normalizeMessage) -import Pkg.Parser (ScopedQuery (..), applyScopedKqlContext, mkScopedQuery) -import Pkg.QueryCache qualified as QueryCache -import Relude -import Relude.Extra.Foldable1 (maximum1, minimum1) -import System.Clock (TimeSpec (..)) -import System.Config (AuthContext (..), EnvConfig (enableTimefusionReads)) -import System.Logging qualified as Log -import System.Types (ATAuthCtx, RespHeaders, addRespHeaders) -import UnliftIO (tryAny, withRunInIO) -import Utils (TabStrip (..), classifyUserAgent, countNoun, faSprite_, getDurationNSMS, kqlQuoted, navTabStrip_, nonEmptyT, prettyTimeShort, replaceAllFormats, showFFloat', toXXHash) -import Web.HttpApiData (FromHttpApiData (..)) - - -data RumTab = Overview | Sessions | Performance - deriving stock (Bounded, Enum, Eq, Read, Show) - deriving (Display, FromHttpApiData) via WrappedEnumSC 'Nothing "" RumTab - - --- | Accepts both the canonical short values this page links with ("errors", "replays") and --- the tab labels the shared Table's filter tabs put in the URL ("With errors"). -parseSessionFilter :: Maybe Text -> SessionFilter -parseSessionFilter paramM = fromMaybe AllSessionRows $ find matches [minBound .. maxBound] - where - normalized = T.toLower <$> paramM - matches value = normalized `elem` [sessionFilterParam value, Just $ T.toLower $ sessionFilterLabel value] - - -sessionFilterParam :: SessionFilter -> Maybe Text -sessionFilterParam = \case - AllSessionRows -> Nothing - ErrorSessionRows -> Just "errors" - ReplaySessionRows -> Just "replays" - - -data VitalRating = Good | NeedsImprovement | Poor | Unknown - deriving stock (Eq, Show) - - -data Vital = Vital - { name :: Text - , label :: Text - , description :: Text - , measurement :: VitalMeasurement - , unit :: Text - , goodAt :: Double - , poorAt :: Double - } - deriving stock (Show) - - --- | Web Vitals use Google's standard field thresholds. The boundary values are good/needs --- improvement (not poor), which prevents a value exactly at 2.5s or 200ms being overstated. --- --- >>> classifyVital 2500 4000 (Just 2500) --- Good --- >>> classifyVital 2500 4000 (Just 4000) --- NeedsImprovement --- >>> classifyVital 2500 4000 Nothing --- Unknown -classifyVital :: Double -> Double -> Maybe Double -> VitalRating -classifyVital good poor = \case - Nothing -> Unknown - Just value | value <= good -> Good - Just value | value <= poor -> NeedsImprovement - Just _ -> Poor - - --- | Field definitions acquire a measurement from the shared population. -vitalDefinitions :: [Vital] -vitalDefinitions = - [ mk "lcp" "Largest Contentful Paint" "When the main content becomes visible" "ms" 2500 4000 - , mk "inp" "Interaction to Next Paint" "How quickly interactions produce visual feedback" "ms" 200 500 - , mk "cls" "Cumulative Layout Shift" "Visual stability while the page loads" "" 0.1 0.25 - , mk "fcp" "First Contentful Paint" "When the first content appears" "ms" 1800 3000 - , mk "ttfb" "Time to First Byte" "Server and network response before rendering" "ms" 800 1800 - ] - where - mk name label description unit goodAt poorAt = Vital{name, label, description, unit, goodAt, poorAt, measurement = Unmeasured} - - -vitalRating :: Vital -> VitalRating -vitalRating vital = case vital.measurement of - Measured _ estimate -> case estimate.bounds of - Nothing -> classifyVital vital.goodAt vital.poorAt (Just estimate.value) - Just (lower, upper) - | upper <= vital.goodAt -> Good - | lower >= vital.poorAt -> Poor - | lower >= vital.goodAt && upper <= vital.poorAt -> NeedsImprovement - | otherwise -> Unknown - Unmeasured -> Unknown - Unavailable _ _ -> Unknown - - --- | What every RUM read is scoped to. Bundled rather than passed as five positional --- arguments because a filter that reached one panel and not another would render a page --- whose own numbers disagree — the summary counting a service the table below it excludes. -data RumScope = RumScope - { useTf :: Bool - , queryScope :: ScopedQuery - } - - --- | Project, window, environment and service: true of any table. An absent filter matches --- everything, so clearing one is just dropping the query parameter. -scopePredicate :: RumScope -> HI.Sql -scopePredicate scope = - let projectId = scope.queryScope.projectId.toText - (fromTime, toTime) = scope.queryScope.timeRange - environment = scope.queryScope.environment - service = scope.queryScope.service - in [HI.sql|project_id = #{projectId} - AND timestamp >= #{fromTime} AND timestamp <= #{toTime} - AND (#{environment}::text IS NULL OR resource___deployment___environment___name = #{environment}) - AND (#{service}::text IS NULL OR resource___service___name = #{service})|] - - --- | The span tables additionally have to be narrowed to what a browser sent; the metrics table --- identifies its browser data by metric name instead. --- --- Laddered, because no single marker covers real browser telemetry. @telemetry.sdk.language@ --- alone — which every RUM query used to filter on by itself — matches /nothing/ in production: --- the OpenTelemetry browser SDKs leave it unset, so the page was scoped to the empty set while --- three browser applications were reporting. The remaining rungs are what those three actually --- carry: the browser resource detector's user agent, the standard browser instrumentation span --- names, and our own SDK's page-view naming. --- --- @resourceFetch@ is deliberately absent: it is one span per script, stylesheet and image, 40% --- of all browser rows here, and it carries nothing RUM shows — its sessions and users are --- already on the page-level spans beside it. -browserScope :: RumScope -> HI.Sql -browserScope scope = scopePredicate scope <> " AND " <> rawSql browserSql - - --- | The predicates as text, shared by the Hasql queries and the summary widgets' SQL. --- TimeFusion's @rum_*@ rollup measures declare these strings verbatim and serve a widget --- only while its filter matches exactly, so an edit here must be mirrored in TimeFusion's --- @schemas/otel_logs_and_spans.yaml@. -browserSql, pageViewSql, errorSql :: Text -browserSql = - "(resource___telemetry___sdk___language IN ('webjs', 'javascript', 'js') OR resource___user_agent___original IS NOT NULL" - <> " OR name IN ('documentLoad', 'documentFetch') OR " - <> pageViewSql - <> ")" -pageViewSql = "(name LIKE 'Pageview %' OR name = 'documentLoad')" -errorSql = "(status_code = 'ERROR' OR lower(COALESCE(level, '')) = 'error' OR attributes___exception___type IS NOT NULL)" - - --- | The page a browser event was on. Document loads retain the browser's full --- URL; our Pageview events group by path, even when their raw URL has a query. -pagePath :: HI.Sql -pagePath = [HI.sql|COALESCE(NULLIF(CASE WHEN name = 'documentLoad' THEN attributes___url___full END, ''), NULLIF(attributes___url___path, ''), NULLIF(attributes___url___full, ''), replace(name, 'Pageview · ', ''))|] - - --- | What counts as one page view. @documentLoad@ is the OpenTelemetry browser SDK's page-load --- span; @Pageview ·@ is ours. Shared so the summary, the trend, the table and the per-session --- counts cannot disagree about what they are counting. -pageViewPredicate :: HI.Sql -pageViewPredicate = rawSql pageViewSql - - --- | What counts as a browser error. Shared for the same reason as 'pageViewPredicate': the --- summary, the trend, the error list and the per-session counts must agree. -errorPredicate :: HI.Sql -errorPredicate = rawSql errorSql - - --- | Presence plus the four headline numbers from one scan of the window, so every tile --- arrives with the panel (and shares its cache) instead of spinning through its own fetch; --- the two sparkline tiles still fetch their series and refresh the number from it. @HAVING@ turns an empty window into --- no row, so presence is the row's existence. -rumPulse :: (DB es, Labeled "timefusion" Hasql :> es) => RumScope -> Eff es (Maybe RumPulse) -rumPulse scope = - Hasql.withHasqlTimefusion scope.useTf - $ Hasql.interpOne - $ [HI.sql|SELECT COUNT(DISTINCT NULLIF(attributes___session___id, ''))::bigint, - COUNT(*) FILTER (WHERE |] - <> pageViewPredicate - <> [HI.sql|)::bigint, COUNT(*) FILTER (WHERE |] - <> errorPredicate - <> [HI.sql|)::bigint, - (approx_percentile(0.75, percentile_agg(CASE WHEN |] - <> pageViewPredicate - <> [HI.sql| THEN duration END)) / 1000000.0)::float8 - FROM otel_logs_and_spans WHERE |] - <> browserScope scope - <> [HI.sql| HAVING COUNT(*) > 0|] - - -rumPages :: (DB es, Labeled "timefusion" Hasql :> es) => RumScope -> Eff es [RumPage] -rumPages scope = - Hasql.interpTimefusion - scope.useTf - ( [HI.sql| - SELECT - |] - <> pagePath - <> [HI.sql|, - COUNT(*)::bigint, - (approx_percentile(0.75, percentile_agg(duration)) / 1000000.0)::float8, - MAX(timestamp) - FROM otel_logs_and_spans - WHERE |] - -- No 'browserScope' here: both page-view markers are already disjuncts of it, so - -- @browserScope AND pageView@ is just @pageView@ — and the bare two-name predicate - -- is ~25x more selective than the four-branch OR ladder (0.13% vs 3.3% of the - -- window on the demo project), which measured 1.3-2.3x faster over 24h - -- (scripts/local/rum-perf-goal-candidates.sh). - <> scopePredicate scope - <> [HI.sql| AND |] - <> pageViewPredicate - <> [HI.sql| AND duration IS NOT NULL - GROUP BY 1 ORDER BY COUNT(*) DESC LIMIT 20|] - ) - - --- | Recent raw error rows; 'groupErrors' folds them into issues at render time. 400 recent --- rows rather than 20: the panel shows groups, and a flat 20 of a hot error would hide every --- other issue behind twenty copies of the loudest one. -rumErrors :: (DB es, Labeled "timefusion" Hasql :> es) => RumScope -> Eff es [RumError] -rumErrors scope = - Hasql.interpTimefusion - scope.useTf - ( [HI.sql| - SELECT timestamp, - COALESCE(attributes___exception___type, status_message, 'Browser error'), - COALESCE(attributes___exception___message, status_message, name, 'No error message'), - attributes___session___id, - COALESCE(attributes___user___id, attributes___user___email), - |] - <> pagePath - <> [HI.sql| - FROM otel_logs_and_spans - WHERE |] - <> browserScope scope - <> [HI.sql| AND |] - <> errorPredicate - <> [HI.sql| ORDER BY timestamp DESC LIMIT 400|] - ) - - --- | Text is matched against complete sessions before LIMIT, preserving their event totals; --- that path stays raw because page text participates in HAVING. The plain list and exact-id --- reads use a mergeable core, then enrich only the at-most 200 selected ids with the page and --- user-agent expressions. -otelSessionRows :: (DB es, Labeled "timefusion" Hasql :> es) => RumScope -> SessionMatch -> SessionFilter -> Eff es [RumSession] -otelSessionRows scope match sessionFilter = case match of - SessionText (Just query) -> - let needle = searchPattern query - in sessionRows pageAndAgent mempty - $ [HI.sql|COUNT(*) FILTER (WHERE - attributes___session___id ILIKE #{needle} - OR attributes___user___id ILIKE #{needle} - OR attributes___user___full_name ILIKE #{needle} - OR attributes___user___email ILIKE #{needle} - OR resource___service___name ILIKE #{needle} - OR (|] - <> pagePath - <> [HI.sql|) ILIKE #{needle}) > 0|] - SessionText Nothing -> sessionRows nullPageCols mempty "true" >>= enrich - SessionIds ids -> sessionRows nullPageCols [HI.sql| AND attributes___session___id = ANY(#{ids})|] "true" >>= enrich - where - -- Aliased: DataFusion rejects two identically-named NULL projections. - nullPageCols = "NULL::text AS last_page, NULL::text AS user_agent" - pageAndAgent = - [HI.sql|(ARRAY_AGG(|] - <> pagePath - <> [HI.sql| ORDER BY timestamp DESC, id DESC) FILTER (WHERE |] - <> pageViewPredicate - <> [HI.sql|))[1], MAX(COALESCE(NULLIF(attributes___user_agent___original, ''), resource___user_agent___original))|] - sessionRows pageCols extraWhere having = - Hasql.interpTimefusion - scope.useTf - ( [HI.sql| - SELECT attributes___session___id, - MIN(timestamp), MAX(timestamp), COUNT(*)::bigint, - COUNT(*) FILTER (WHERE |] - <> errorPredicate - <> [HI.sql|)::bigint, - COUNT(*) FILTER (WHERE |] - <> pageViewPredicate - <> [HI.sql|)::bigint, - MAX(attributes___user___id), MAX(attributes___user___full_name), MAX(attributes___user___email), - MAX(resource___service___name), |] - <> pageCols - <> [HI.sql|, false AS has_replay - FROM otel_logs_and_spans - WHERE |] - <> browserScope scope - <> [HI.sql| AND attributes___session___id IS NOT NULL AND attributes___session___id <> ''|] - <> extraWhere - <> [HI.sql| GROUP BY attributes___session___id HAVING |] - <> having - <> (if sessionFilter == ErrorSessionRows then [HI.sql| AND COUNT(*) FILTER (WHERE |] <> errorPredicate <> [HI.sql|) > 0|] else mempty) - <> [HI.sql| ORDER BY MAX(timestamp) DESC LIMIT 200|] - ) - enrich [] = pure [] - enrich rows = do - let ids = map (.id) rows - details :: [(Text, Maybe Text, Maybe Text)] <- - Hasql.interpTimefusion - scope.useTf - ( [HI.sql|SELECT attributes___session___id, |] - <> pageAndAgent - <> [HI.sql| FROM otel_logs_and_spans WHERE |] - <> browserScope (spanScope 0 [(row.startedAt, row.endedAt) | row <- rows] scope) - <> [HI.sql| AND attributes___session___id = ANY(#{ids}) GROUP BY attributes___session___id|] - ) - let byId = M.fromList [(sid, (lastPage, userAgent)) | (sid, lastPage, userAgent) <- details] - pure [maybe row (\(lastPage, userAgent) -> row{lastPage, userAgent}) $ M.lookup row.id byId | row <- rows] - - --- | Every follow-up read of sessions already in hand scans only their own span. The newest --- 200 sessions of a 24h window cover ~11h on a busy project, and the enrichment scan costs --- 1.7s over that span against 9.7s over the day (scripts/local/rum-sessions-2026-09-29.md). --- --- >>> import Data.Time (UTCTime (..)) --- >>> let day = UTCTime (toEnum 60000) 0 --- >>> let scope = RumScope True (mkScopedQuery Projects.demoProjectId (Just day, Just (addUTCTime 86400 day)) Nothing Nothing) --- >>> (spanScope 0 [(addUTCTime 100 day, addUTCTime 200 day), (addUTCTime 50 day, addUTCTime 150 day)] scope).queryScope.timeRange == (Just (addUTCTime 50 day), Just (addUTCTime 200 day)) --- True --- >>> (spanScope 900 [] scope).queryScope.timeRange == scope.queryScope.timeRange --- True --- >>> (spanScope 900 [(day, addUTCTime 86400 day)] scope).queryScope.timeRange == scope.queryScope.timeRange --- True -spanScope :: NominalDiffTime -> [(UTCTime, UTCTime)] -> RumScope -> RumScope -spanScope pad spans scope = case nonEmpty spans of - Nothing -> scope - Just found -> - let (from, to) = scope.queryScope.timeRange - clamp bound f x = maybe x (f x) bound - in scope{queryScope = scope.queryScope{timeRange = (Just $ clamp from max $ addUTCTime (-pad) $ minimum1 $ fst <$> found, Just $ clamp to min $ addUTCTime pad $ maximum1 $ snd <$> found)}} - - --- The same lookup mode is used for both stores so recordings can enrich matched --- telemetry, and recording-only identities can discover their associated spans. -data SessionMatch = SessionText (Maybe Text) | SessionIds [Text] - - -searchPattern :: Text -> Text -searchPattern query = "%" <> T.replace "_" "\\_" (T.replace "%" "\\%" (T.replace "\\" "\\\\" query)) <> "%" - - --- | Traffic per user agent string, busiest first. Classification into browser, OS and --- device happens in 'classifyUserAgent': the store only groups, so a new browser release --- needs no query change to show up. -rumBreakdown :: (DB es, Labeled "timefusion" Hasql :> es) => RumScope -> Eff es [RumBreakdown] -rumBreakdown scope = - Hasql.interpTimefusion - scope.useTf - ( [HI.sql| - SELECT COALESCE(NULLIF(attributes___user_agent___original, ''), resource___user_agent___original), - COUNT(DISTINCT NULLIF(attributes___session___id, ''))::bigint, - COUNT(*) FILTER (WHERE |] - <> pageViewPredicate - <> [HI.sql|)::bigint, - COUNT(*) FILTER (WHERE |] - <> errorPredicate - <> [HI.sql|)::bigint - FROM otel_logs_and_spans - WHERE |] - <> browserScope scope - <> [HI.sql| AND COALESCE(NULLIF(attributes___user_agent___original, ''), resource___user_agent___original) IS NOT NULL - GROUP BY 1 ORDER BY 2 DESC LIMIT 100|] - ) - - -replaySessionRows :: DB es => RumScope -> SessionMatch -> Eff es [ReplaySession] -replaySessionRows scope match = - let projectId = scope.queryScope.projectId - (fromTime, toTime) = scope.queryScope.timeRange - in Hasql.interp - ( [HI.sql| - SELECT session_id, created_at, last_event_at, user_id, user_name, user_email - FROM projects.replay_sessions - WHERE project_id = #{projectId} AND last_event_at >= #{fromTime} AND created_at <= #{toTime} - AND (event_file_count > 0 OR cardinality(file_keys) > 0 OR cardinality(shard_keys) > 0) - AND |] - <> matchPredicate - <> [HI.sql| - ORDER BY last_event_at DESC LIMIT 200 - |] - ) - where - matchPredicate = case match of - SessionIds ids -> [HI.sql| CAST(session_id AS TEXT) = ANY(#{ids}) |] - SessionText Nothing -> [HI.sql| true |] - SessionText (Just query) -> - let needle = searchPattern query - in [HI.sql| (CAST(session_id AS TEXT) ILIKE #{needle} - OR user_id ILIKE #{needle} OR user_name ILIKE #{needle} OR user_email ILIKE #{needle}) |] - - -searchSessions :: (DB es, Labeled "timefusion" Hasql :> es) => RumScope -> Maybe Text -> SessionFilter -> Eff es [RumSession] -searchSessions scope query sessionFilter = do - spans <- otelSessionRows scope (SessionText query) sessionFilter - recordings <- if sessionFilter == ErrorSessionRows then pure [] else replaySessionRows scope (SessionText query) - let recordingIds = map (UUID.toText . (.id)) recordings - spanIds = map (.id) spans - -- Cross-enrich by exact id: filtering each store independently otherwise turns a - -- page match into "No replay", or a recording-name match into "No telemetry". - -- Only ids the other store did NOT already return need the extra look-up — a session - -- both searches found carries complete aggregates already (the text predicate is a - -- HAVING filter, not a row filter). On an unfiltered load the sets overlap almost - -- entirely, which skips a second full-window scan of the span table. - newRecordings = filter ((`notElem` spanIds) . UUID.toText . (.id)) recordings - newRecordingIds = map (UUID.toText . (.id)) newRecordings - newSpanIds = filter (`notElem` recordingIds) spanIds - -- A recording's spans sit inside it, give or take the flush lag either side. Only a text - -- search pays for this: on the plain list a recording missing from the newest 200 span - -- sessions almost always has no browser spans at all, and the id lookup across the - -- recordings' combined span (most of the window) cost 34s on TimeFusion for that nothing. - extraSpans <- if null newRecordings || isNothing query then pure [] else otelSessionRows (spanScope recordingPad [(r.startedAt, r.endedAt) | r <- newRecordings] scope) (SessionIds newRecordingIds) sessionFilter - extraRecordings <- if null newSpanIds then pure [] else replaySessionRows scope (SessionIds newSpanIds) - pure $ take 200 $ filter keep $ mergeSessions scope.queryScope (extraSpans <> spans) (recordings <> extraRecordings) - where - keep session = case sessionFilter of - AllSessionRows -> True - ErrorSessionRows -> session.errors > 0 - ReplaySessionRows -> session.hasReplay - - -sessionDetail :: (DB es, Labeled "timefusion" Hasql :> es) => RumScope -> Text -> Eff es (Maybe RumSession) -sessionDetail scope sid = do - recordings <- replaySessionRows scope (SessionIds [sid]) - spans <- otelSessionRows (spanScope recordingPad [(r.startedAt, r.endedAt) | r <- recordings] scope) (SessionIds [sid]) AllSessionRows - pure $ listToMaybe $ mergeSessions scope.queryScope spans recordings - - -recordingPad :: NominalDiffTime -recordingPad = 15 * 60 - - --- | Recordings carry no service or environment attribution. Under either scope they --- may enrich matching telemetry, but cannot introduce recording-only sessions. -mergeSessions :: ScopedQuery -> [RumSession] -> [ReplaySession] -> [RumSession] -mergeSessions scope otel replays = sortWith (Down . (.endedAt)) $ M.elems $ foldl' addReplay (M.fromList [(s.id, s) | s <- otel]) replays - where - addReplay sessions replay = - let sid = UUID.toText replay.id - in if isJust scope.service || isJust scope.environment - then M.adjust (attachReplay replay) sid sessions - else M.alter (Just . maybe (fromReplay replay) (attachReplay replay)) sid sessions - fromReplay replay = - RumSession - { id = UUID.toText replay.id - , startedAt = replay.startedAt - , endedAt = replay.endedAt - , events = 0 - , errors = 0 - , views = 0 - , userId = replay.userId - , userName = replay.userName - , userEmail = replay.userEmail - , service = Nothing - , lastPage = Nothing - , userAgent = Nothing - , hasReplay = True - } - attachReplay replay session = - session - { startedAt = min session.startedAt replay.startedAt - , endedAt = max session.endedAt replay.endedAt - , userId = session.userId <|> replay.userId - , userName = session.userName <|> replay.userName - , userEmail = session.userEmail <|> replay.userEmail - , hasReplay = True - } - - --- | Everything a RUM self-link has to preserve for the page you land on to still be the page --- you were looking at. Passed as one value so a new scope dimension cannot be added to the --- handler and silently forgotten by half the links. -data RumLinks = RumLinks - { queryScope :: ScopedQuery - , window :: TimePicker.TimeWindow - } - - --- | One independently-loaded region of the page. Each panel is a separate scan of the --- window, costing 0.5–4s on its own, and the panels together contend badly enough that six --- concurrently take 10–28s. Loading them as one unit made the whole page wait for the --- slowest; each panel now fetches itself, so a panel appears as soon as /its/ query lands. -data RumPanel = PanelPulse | PanelPages | PanelVitals | PanelVitalTrend | PanelErrors | PanelSessions | PanelSessionDetail | PanelAudience - deriving stock (Eq, Read, Show) - deriving (Display, FromHttpApiData) via WrappedEnumSC 'Nothing "Panel" RumPanel - - --- | Ids are the swap contract: 'deferredShell_' selects @#id@ out of the panel response, so --- the shell and the rendered panel must agree on it. -panelId :: RumPanel -> Text -panelId PanelSessionDetail = "rum-replay-workspace" -panelId panel = "rum-panel-" <> display panel - - -data RumData = RumData - { links :: RumLinks - , tab :: RumTab - , panel :: Maybe RumPanel - -- ^ Which panel this response carries. 'Nothing' is the page skeleton: every panel - -- renders as a shell that fetches itself. - , servedStale :: Bool - -- ^ At least one panel query was served from the stale band of the shared cache. The - -- panel re-fetches itself with @refresh@ so the viewer always converges on fresh data - -- without ever waiting on a cold scan for first paint. - , now :: UTCTime - , pulse :: Maybe RumPulse - , pages :: [RumPage] - , errors :: [RumError] - , sessions :: [RumSession] - , vitals :: [Vital] - , vitalTrend :: [VitalTrendPoint] - , pageVitals :: [PageVitalPoint] - , breakdown :: [RumBreakdown] - , query :: Maybe Text - , sessionFilter :: SessionFilter - , selectedSession :: Maybe Text - , selectedSessionData :: Maybe RumSession - , degradedPanels :: [RumQuery] - } - - -newtype RumGet = RumGet (PageCtx (Deferred RumData)) - - -instance ToHtml RumGet where - toHtml (RumGet (PageCtx _ (DeferredBody loaded))) | isJust loaded.panel = toHtml loaded - toHtml (RumGet page) = toHtml page - toHtmlRaw = toHtml - - -data RumCachePolicy = SkipCache | CachePopulated | CacheEmptySearch - deriving stock (Eq) - - --- | Every RUM panel is a separate scan of a 24-hour window, and a tab click re-runs all of --- them. Holding the page chrome hostage to the slowest one is what makes switching tabs feel --- broken, so the first request renders the tab strip, time picker and a skeleton, and the --- panels arrive on the request the skeleton fires. -rumSkeleton_ :: RumTab -> Html () -rumSkeleton_ Sessions = div_ [class_ "flex flex-col bg-bgBase xl:h-full xl:min-h-0"] do - div_ [class_ "flex shrink-0 items-center border-b border-strokeWeak px-4 py-1 max-md:px-3"] - $ div_ [class_ "h-8 w-full max-w-[22rem] rounded-lg skeleton-shimmer"] "" - sessionsSkeleton_ -rumSkeleton_ _ = div_ [class_ "min-h-full space-y-5 bg-bgBase p-4", role_ "status", Aria.label_ "Loading real user monitoring"] do - div_ [class_ "grid grid-cols-4 gap-px border-y border-strokeWeak bg-bgBase max-md:grid-cols-2"] - $ replicateM_ 4 - $ div_ [class_ "flex flex-col gap-2 px-4 py-3"] do - div_ [class_ "h-6 w-16 rounded skeleton-shimmer"] "" - div_ [class_ "h-3 w-24 rounded skeleton-shimmer"] "" - div_ [class_ "grid grid-cols-[minmax(0,1.65fr)_minmax(18rem,0.75fr)] gap-4 max-xl:grid-cols-1"] do - div_ [class_ "rounded-lg border border-strokeWeak surface-raised p-4"] Components.chartSkeleton_ - div_ [class_ "rounded-lg border border-strokeWeak surface-raised"] $ Components.tableSkeleton_ 5 - div_ [class_ "rounded-lg border border-strokeWeak surface-raised"] $ Components.tableSkeleton_ 6 - - --- | Backwards-compatible programmatic entry point. Browser routes call --- 'rumGetScopedH' so a shared link can name its environment, while existing internal --- callers retain the authenticated session as their environment default. -rumGetH :: Projects.ProjectId -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> ATAuthCtx (RespHeaders RumGet) -rumGetH pid tabM queryM sessionFilterM fromM toM sinceM selectedM serviceM panelM deferredM refreshM = - rumGetScopedH pid tabM queryM sessionFilterM fromM toM sinceM selectedM serviceM panelM deferredM refreshM Nothing - - --- | Route entry point with an explicit environment carried by a shared URL. -rumGetScopedH :: Projects.ProjectId -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> ATAuthCtx (RespHeaders RumGet) -rumGetScopedH pid tabM queryM sessionFilterM fromM toM sinceM selectedM _serviceM panelM deferredM refreshM environmentM = do - (session, _, bw) <- mkPageCtx pid - appCtx <- Reader.ask @AuthContext - now <- Time.currentTime - let tab = fromMaybe Overview $ rightToMaybe . parseUrlPiece =<< tabM - panel = rightToMaybe . parseUrlPiece =<< panelM - sessionFilter = parseSessionFilter sessionFilterM - searchQuery = mfilter (not . T.null) $ T.strip <$> queryM - since = sinceM <|> ("24H" <$ guard (all (isNothing . nonEmptyT) [fromM, toM])) - window = TimePicker.mkTimeWindow now fromM toM since - -- A shared investigation link names its environment explicitly. The sticky selection - -- remains the default for a hand-entered RUM URL, but must not silently rewrite a link - -- that an on-call engineer opened from an alert or issue. - environment = mfilter (not . T.null) environmentM <|> session.environment - serviceFilter = session.service - scope = RumScope{useTf = appCtx.env.enableTimefusionReads, queryScope = mkScopedQuery pid (Just window.fromTime, Just window.toTime) environment serviceFilter} - links = RumLinks{queryScope = scope.queryScope, window} - bucket - | diffUTCTime window.toTime window.fromTime <= 6 * 3600 = FiveMinutes - | diffUTCTime window.toTime window.fromTime <= 3 * 86400 = OneHour - | otherwise = SixHours - cacheKey query = RumCacheKey pid query environment serviceFilter (nonEmptyT fromM) (nonEmptyT toM) window.sinceQuery - panelTtl = TimePicker.cacheTtl window - pulseQ = (cacheKey PulseQuery, panelTtl, PulseResult <$> rumPulse scope, Nothing) - pagesQ = (cacheKey PagesQuery, panelTtl, PagesResult <$> rumPages scope, Nothing) - errorsQ = (cacheKey ErrorsQuery, panelTtl, ErrorsResult <$> rumErrors scope, Nothing) - -- A cold list over a wide window paints the newest three hours first — a 24h scan of the - -- session shape is 7-24s on a busy project against 0.2s for 3h - -- (scripts/local/rum-sessions-2026-09-29.md) — and the stale-serve revalidation then - -- fetches the full range. Only the plain newest-first list qualifies: a text search or a - -- filter must see the whole window or it silently answers "no match". - recent = spanScope 0 [(addUTCTime (-(3 * 3600)) window.toTime, window.toTime)] scope <$ guard (diffUTCTime window.toTime window.fromTime > 6 * 3600) - -- The Overview's recent sessions are the Sessions tab's unfiltered list: one cache entry, one scan. - searchAt s = SessionsResult <$> searchSessions s searchQuery sessionFilter - sessionSearchQ = (cacheKey $ SessionSearchQuery searchQuery sessionFilter, panelTtl, searchAt scope, searchAt <$> (guard (isNothing searchQuery && sessionFilter == AllSessionRows) *> recent)) - sessionDetailQs = [(cacheKey $ SessionDetailQuery sid, panelTtl, SessionDetailResult <$> sessionDetail scope sid, Nothing) | sid <- maybeToList selectedM, not $ T.null sid] - vitalsQ = (cacheKey $ VitalPopulationQuery bucket, panelTtl, VitalPopulationResult <$> RUM.rumVitalPopulation scope.useTf scope.queryScope window bucket, Nothing) - breakdownQ = (cacheKey BreakdownQuery, panelTtl, BreakdownResult <$> rumBreakdown scope, Nothing) - -- Only the requested panel's queries run. The skeleton request runs none at all, so the - -- page chrome is free and each panel pays only for itself. - -- - -- These all used to run together on one request. Measured on the demo project over 24h - -- (scripts/local/rum-perf-2026-08-30.md): panels cost 0.5–4.1s individually but six - -- concurrently take 10–28s — contention eats most of the parallelism, and the page still - -- waited for the slowest. Per-panel fetching trades that for a first paint at the cost - -- of one panel. - panelQueries = case panel of - Just PanelPulse -> [pulseQ] - Just PanelPages -> [pagesQ] - Just PanelVitals -> [vitalsQ] - Just PanelVitalTrend -> [vitalsQ] - Just PanelErrors -> [errorsQ] - Just PanelSessions -> sessionSearchQ : sessionDetailQs - Just PanelSessionDetail -> sessionDetailQs - Just PanelAudience -> [breakdownQ] - Nothing -> [] - -- Concurrent requests share lookup, computation and publication within a replica. - -- Completed entries are shared across replicas through rum_panel_cache. - -- - -- The shared layer also serves STALE populated entries (past expiry, inside the prune horizon): - -- an expired panel answers instantly with its last-known data and the page re-fetches - -- itself with @refresh@, which bypasses the stale band and recomputes. First paint - -- stops waiting on a cold scan after the very first visit. Stale payloads are never - -- copied into the memory cache — its TTL would re-classify them as fresh and suppress - -- the revalidation they exist to trigger. - -- - -- A failed recompute falls back to populated stale data rather than blanking the panel: - -- last-known data plus no revalidation trigger, so the page neither lies forever nor - -- collapses to zero states while the store is down. A payload from an older code - -- shape fails to decode; that is a cache miss, not an error. - runQuery (key, ttl, action, quick) = withRunInIO \unlift -> fmap snd $ QueryCache.coalesceQuery appCtx.rumQueryFlights (key, refresh) $ unlift do - -- First SDK visits remain uncached; an explicit missing search gets a brief fresh-only hit. - let label = rumQueryLabel key.query - policy result - | SessionSearchQuery (Just _) _ <- key.query, SessionsResult [] <- result = CacheEmptySearch - | populated = CachePopulated - | otherwise = SkipCache - where - populated = case result of - PulseResult pulse -> isJust pulse - PagesResult rows -> not $ null rows - ErrorsResult rows -> not $ null rows - SessionsResult rows -> not $ null rows - SessionDetailResult row -> isJust row - VitalPopulationResult rows -> not $ null rows - BreakdownResult rows -> not $ null rows - usable (value, stale) = policy value /= CacheEmptySearch || not (stale || refresh) - l1 <- liftIO $ Cache.lookup appCtx.rumCache key - case l1 of - Just hit | usable (hit, False) -> pure $ Right (hit, False) - _ -> do - let dbKey = rumCacheDbKey key - staleEntryM <- mfilter usable . fromRight Nothing <$> tryAny (rumPanelCacheGetStale dbKey) - outcome <- - tryAny - ( case staleEntryM of - Just (shared, False) -> do - -- Shared empty searches keep their database expiry rather than extend it in L1. - when (policy shared /= CacheEmptySearch) $ liftIO $ Cache.insert' appCtx.rumCache (Just ttl) key shared - pure (shared, False) - Just (shared, True) | not refresh -> pure (shared, True) - -- Never cached: a cached slice would be served as the final answer whenever the - -- full revalidation fails. The revalidation computes and caches the full window. - Nothing | Just partial <- quick, not refresh -> (,True) <$> partial - _ -> do - fresh <- action - when (policy fresh /= SkipCache) do - let lifetime = if policy fresh == CacheEmptySearch then min ttl (TimeSpec 30 0) else ttl - liftIO $ Cache.insert' appCtx.rumCache (Just lifetime) key fresh - either (\err -> Log.logAttention "RUM panel cache write failed" (label, displayException err)) pure =<< tryAny (rumPanelCacheSet dbKey lifetime.sec fresh) - pure (fresh, False) - ) - case outcome of - Right res -> pure $ Right res - Left err -> case staleEntryM of - Just (stale, _) -> Right (stale, False) <$ Log.logAttention "RUM panel query failed; served stale cache" (label, displayException err) - Nothing -> Left key.query <$ Log.logAttention "RUM panel query failed" (label, displayException err) - refresh = isJust refreshM - deferredUrl = rumUrl links ([(key, value) | (key, Just value) <- [("tab", tabM), ("q", queryM), ("filter", sessionFilterM), ("session", selectedM)]] <> [("deferred", "1")]) - body <- withDeferredBody deferredM "rum-page" deferredUrl (rumSkeleton_ tab) do - outcomes <- pooledForConcurrently panelQueries runQuery - let (degradedPanels, served) = partitionEithers outcomes - results = map fst served - servedStale = any snd served - pulse = asum [value | PulseResult value <- results] - pages = fold [value | PagesResult value <- results] - errors = fold [value | ErrorsResult value <- results] - sessions = fold [value | SessionsResult value <- results] - selectedSessionData = asum [value | SessionDetailResult value <- results] - populations = fold [value | VitalPopulationResult value <- results] - fieldMeasurements = M.fromList [(population.metricName, population.measurement) | population <- populations, population.grouping == FieldVital] - vitals = [(vital :: Vital){measurement = M.findWithDefault Unmeasured vital.name fieldMeasurements} | vital <- vitalDefinitions] - vitalTrend = [VitalTrendPoint time population.metricName population.measurement | population <- populations, TrendVital time <- [population.grouping]] - pageVitals = [PageVitalPoint url population.metricName population.measurement | population <- populations, PageVital url <- [population.grouping]] - breakdown = fold [value | BreakdownResult value <- results] - pure RumData{links, tab, panel, servedStale, now, pulse, pages, errors, sessions, vitals, vitalTrend, pageVitals, breakdown, query = queryM, sessionFilter, selectedSession = selectedM, selectedSessionData, degradedPanels} - let conf = - bw - { pageTitle = "Real User Monitoring" - , menuItem = Just "Real User Monitoring" - , navTabs = Just $ rumNavTabs_ links tab - , pageActions = Just $ rumActions_ links - , docsLink = Just "https://monoscope.tech/docs/sdks/browser/" - } - addRespHeaders $ RumGet $ PageCtx conf body - - -rumNavTabs_ :: RumLinks -> RumTab -> Html () -rumNavTabs_ links active = navTabStrip_ NavLinks "Real User Monitoring views" "" [(toHtml $ T.toTitle $ display tab, rumUrl links [("tab", display tab)], tab == active) | tab <- [minBound .. maxBound]] - - -rumActions_ :: RumLinks -> Html () -rumActions_ links = div_ [class_ "inline-flex items-center gap-2", data_ "default-window" "24H"] do - a_ [href_ $ "/p/" <> links.queryScope.projectId.toText <> "/rum/dashboard", class_ "btn btn-sm gap-1.5 max-md:hidden"] do - faSprite_ "chart-line" "regular" "h-3.5 w-3.5" - "Open RUM dashboard" - TimePicker.liveDataControls_ Nothing links.window.currentRange Nothing TimePicker.RefreshOnly - - -instance ToHtml RumData where - toHtml = toHtmlRaw . rumPage_ - toHtmlRaw = toHtml - - --- | A panel slot. On the skeleton response every slot is a shell that fetches only its own --- panel; on a panel response the matching slot carries content and the rest stay shells — --- @hx-select@ discards them, so rendering the surrounding layout costs nothing. --- --- Stale-served content re-fetches itself once, with @refresh@, shortly after landing: the --- viewer sees last-known data instantly and the fresh result swaps in when the recompute --- lands. The refreshed response is fresh by construction (refresh bypasses the stale band), --- so it carries no trigger of its own and the cycle always terminates. --- --- Rendered content also re-fetches itself on the time transport's live tick, which is what --- makes the LIVE badge tell the truth on this page: the panels hold every number on it, and --- nothing else here was listening for the tick. -slot_ :: RumData -> RumPanel -> Html () -> Html () -> Html () -slot_ page panel skeleton content - | page.panel == Just panel = div_ ([id_ $ panelId panel, class_ $ "w-full" <> if panel == PanelSessions then " flex-1 min-h-0" else ""] <> liveAttrs) do - if sessionList || null page.degradedPanels then content else degradedBanner_ page panel - unless sessionList $ panelRevalidation_ page panel - | otherwise = - div_ - ([id_ $ panelId panel, class_ "w-full", data_ "deferred-shell" ""] <> panelSwapAttrs page panel False "load, update-query[event.detail?.source!='auto-refresh'] from:window" (Just "replace")) - skeleton - where - -- One panel's worth of work per tick, swapped in place: the page chrome, the scroll - -- position and any open replay stay exactly as they were, and a tick that lands inside - -- the panel's cache TTL costs a cache read. - -- Automatic ticks leave in-flight work running; manual changes still replace it. - -- Populated summary widgets refresh themselves; replacing their parent resets loaded values. - liveAttrs - | panel == PanelPulse && isJust page.pulse = [] - | otherwise = panelSwapAttrs page panel False "update-query[event.detail?.source!='auto-refresh'||!this.matches('.htmx-request,:has(.htmx-request),#rum-page:has(#rum-session-search-form.htmx-request) #rum-panel-sessions')] from:window" (Just "replace") - -- On the Sessions tab the panel also carries the replay workspace; swapping the whole - -- panel would restart a replay the viewer just opened. Only the list is re-fetched - -- there — a selection made while the refresh is in flight survives. - sessionList = page.tab == Sessions && panel == PanelSessions - - -panelRevalidation_ :: RumData -> RumPanel -> Html () -panelRevalidation_ page panel = - -- A populated pulse is four widgets that fetch and refresh themselves; re-rendering the - -- panel around them only restarts them, which is the spinner flash on first load. - when (page.servedStale && not (panel == PanelPulse && isJust page.pulse)) $ div_ (class_ "hidden" : panelSwapAttrs page panel True "load delay:600ms" ("abort" <$ guard (page.tab == Sessions && panel == PanelSessions || panel == PanelSessionDetail))) mempty - - --- | A rendered session list syncs with the search form that also replaces it; any other --- panel syncs with itself. -panelSwapAttrs :: RumData -> RumPanel -> Bool -> Text -> Maybe Text -> [Attribute] -panelSwapAttrs page panel refresh trigger syncMode = - -- Rendered content morphs, so a live tick patches numbers into the table the viewer is - -- reading instead of rebuilding it under their pointer; only the skeleton is replaced. - [hxGet_ url, hxTrigger_ trigger, hxTarget_ refreshTarget, hxSelect_ refreshTarget, hxSwap_ $ if isJust page.panel then "outerMorph" else "outerHTML"] - <> [term "hx-sync" $ bool ("#" <> panelId panel) "#rum-session-search-form" sessionList <> ":" <> mode | mode <- toList syncMode] - <> [term "hx-include" "#rum-session-search-form" | sessionList] - <> [Components.timeWindowVals_ "24H", term "hx-preload" "false"] - where - sessionList = page.panel == Just panel && page.tab == Sessions && panel == PanelSessions - refreshTarget = if sessionList then "#rum-sessions-list" else "#" <> panelId panel - url = - rumUrl page.links - $ [("tab", display page.tab), ("panel", display panel), ("deferred", "1")] - <> [(key, value) | (key, Just value) <- [("q", page.query), ("filter", sessionFilterParam page.sessionFilter), ("session", page.selectedSession)]] - <> [("refresh", "1") | refresh] - - -rumPage_ :: RumData -> Html () -rumPage_ page | page.panel == Just PanelSessionDetail = sessionWorkspace_ page -rumPage_ page = div_ [id_ "rum-page", class_ $ "bg-bgBase " <> if page.tab == Sessions then "flex flex-col xl:h-full xl:min-h-0 [&>#rum-panel-sessions]:flex-1 [&>#rum-panel-sessions]:min-h-0" else "min-h-full"] do - when (page.tab == Sessions) $ div_ [class_ "flex shrink-0 items-center border-b border-strokeWeak px-4 py-1 max-md:px-3"] $ sessionSearch_ page - case page.tab of - Overview -> overview_ page - Sessions -> sessions_ page - Performance -> performance_ page - - --- | Keep search outside the scrolling list. HTMX replaces only the list, so typing --- never interrupts the recording. The GET form also works without JavaScript. -sessionSearch_ :: RumData -> Html () -sessionSearch_ page = form_ - [ id_ "rum-session-search-form" - , method_ "get" - , action_ route - , hxGet_ route - , hxTrigger_ "input delay:300ms, submit" - , hxTarget_ "#rum-sessions-list" - , hxSelect_ "#rum-sessions-list" - , hxSwap_ "outerMorph" - , term "hx-sync" "this:replace" - , -- hx-replace-url would record the request URL, panel=sessions&deferred=1 included. - term "hx-on::before:request" "event.detail.ctx.replace = this.action + '?' + new URLSearchParams(new FormData(this))" - , term "hx-vals" "{\"panel\":\"sessions\",\"deferred\":\"1\"}" - , class_ "flex min-w-0 flex-[1_1_22rem] items-center gap-2" - ] - do - input_ [type_ "hidden", name_ "tab", value_ "sessions"] - input_ [type_ "hidden", name_ "session", value_ $ fromMaybe "" page.selectedSession] - TimePicker.timeHiddenInputs_ page.links.window.fromQuery page.links.window.toQuery page.links.window.sinceQuery - forM_ page.links.queryScope.environment $ \environment -> input_ [type_ "hidden", name_ "environment", value_ environment] - forM_ page.links.queryScope.service $ \service -> input_ [type_ "hidden", name_ "service_scope", value_ service] - input_ [id_ "rum-session-filter", type_ "hidden", name_ "filter", value_ $ fromMaybe "" $ sessionFilterParam page.sessionFilter] - Components.searchInput_ - "min-w-0 flex-1 border-strokeWeak bg-bgBase shadow-none max-sm:h-11" - "Search sessions by user, session, page, or service" - [ id_ "rum-session-search" - , name_ "q" - , value_ $ fromMaybe "" page.query - , term "aria-keyshortcuts" "/" - , onkeydown_ "if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); this.blur(); }" - , term "_" "on keydown[key == '/' and not ctrlKey and not metaKey and not altKey and not (the event's target matches ) and no and no <[popover]:popover-open/>] from window halt the event then call me.focus() end" - ] - span_ [class_ "flex shrink-0 items-center gap-1 text-xs text-textWeak max-sm:hidden"] do - kbd_ [class_ "kbd kbd-xs"] "/" - "to focus" - where - route = "/p/" <> page.links.queryScope.projectId.toText <> "/rum" - - --- | A service filter that matched nothing is not an uninstrumented project. The unscoped --- empty state pitches installing the browser SDK, which here would tell a user with working --- telemetry to re-instrument a working app. The way out is to widen the scope, so that is --- what this offers. -scopedEmptyState_ :: Text -> Html () -scopedEmptyState_ name = - div_ [class_ "mx-auto flex min-h-[40vh] max-w-2xl flex-col justify-center px-6 py-12"] - $ Components.emptyState_ - def{icon = Just "web", action = ESNone} - ("No browser telemetry for " <> name <> " in this range") - "This service reported no page views, errors or Web Vitals in the selected window. Widen the time range, or choose another service from the global scope picker." - - -rumEmptyState_ :: Projects.ProjectId -> Html () -rumEmptyState_ pid = div_ [class_ "mx-auto flex min-h-[60vh] max-w-2xl flex-col justify-center px-6 py-12"] do - Components.emptyState_ - def - { icon = Just "web" - , action = - ESCustom $ div_ [class_ "flex flex-wrap justify-center gap-2"] do - a_ [href_ "https://monoscope.tech/docs/sdks/browser/", target_ "_blank", rel_ "noopener noreferrer", class_ "btn btn-sm btn-primary"] "Install the browser SDK" - a_ [href_ $ "/p/" <> pid.toText <> "/rum/dashboard", class_ "btn btn-sm"] "Open RUM dashboard" - } - "No browser telemetry yet" - "Install the browser SDK to send page loads, interactions, network spans, errors, and Core Web Vitals through OpenTelemetry. Enable session replay to connect those signals to the user's exact experience." - Components.factGrid_ - "grid-cols-3 bg-bgBase max-sm:grid-cols-1 max-sm:divide-x-0 max-sm:divide-y" - [ ("OpenTelemetry", "Portable traces and metrics") - , ("Web Vitals", "LCP, INP, CLS, FCP, TTFB") - , ("Session Replay", "DOM, console, and network context") - ] - - -overview_ :: RumData -> Html () -overview_ page = div_ [class_ "space-y-2 px-4 pb-4 pt-2 max-md:px-3"] do - slot_ page PanelPulse pulseSkeleton_ $ pulseOrEmpty_ page - div_ [class_ "grid grid-cols-[minmax(0,1.65fr)_minmax(18rem,0.75fr)] gap-4 max-xl:grid-cols-1"] do - div_ [class_ "min-w-0 space-y-2"] do - slot_ page PanelPages (panelSkeleton_ $ Components.tableSkeleton_ 5) $ topPages_ page.links page.pages - slot_ page PanelAudience (panelSkeleton_ $ Components.tableSkeleton_ 3) $ audiencePanel_ page.breakdown - aside_ [class_ "min-w-0 space-y-2"] do - slot_ page PanelVitals (panelSkeleton_ $ Components.tableSkeleton_ 4) $ vitalsPanel_ page.vitals - slot_ page PanelErrors (panelSkeleton_ $ Components.tableSkeleton_ 4) $ recentErrors_ page.links page.errors - slot_ page PanelSessions (panelSkeleton_ $ Components.tableSkeleton_ 6) $ recentSessions_ page - - --- | The onboarding pitch belongs here: this is the panel that knows whether the project has --- any browser telemetry at all. With telemetry present, the numbers and the activity chart --- are the same Widget components dashboards are built from — they fetch their own data --- through the chart pipeline, so they look, behave and cache exactly like every other --- number and chart in the product. -pulseOrEmpty_ :: RumData -> Html () -pulseOrEmpty_ page - | Just pulse <- page.pulse = div_ [class_ "space-y-4"] do - rumStatWidgets_ page.links pulse - rumActivityWidget_ page.links - | otherwise = maybe (rumEmptyState_ page.links.queryScope.projectId) scopedEmptyState_ page.links.queryScope.service - - -pulseSkeleton_ :: Html () -pulseSkeleton_ = div_ [class_ "space-y-4", role_ "status", Aria.label_ "Loading summary"] do - div_ [class_ "grid grid-cols-4 gap-3 max-md:grid-cols-2"] - $ replicateM_ 4 - $ div_ [class_ "flex h-28 flex-col justify-center gap-2 rounded-lg border border-strokeWeak surface-raised px-4"] do - div_ [class_ "h-6 w-16 rounded skeleton-shimmer"] "" - div_ [class_ "h-3 w-24 rounded skeleton-shimmer"] "" - panelSkeleton_ Components.chartSkeleton_ - - -panelSkeleton_ :: Html () -> Html () -panelSkeleton_ = div_ [class_ "rounded-lg border border-strokeWeak surface-raised"] - - -rumStatWidgets_ :: RumLinks -> RumPulse -> Html () -rumStatWidgets_ links pulse = div_ [class_ "grid grid-cols-4 gap-3 max-md:grid-cols-2"] do - statSlot_ - $ served (Just $ fromIntegral pulse.sessions) - $ statWidget "rum-stat-sessions" Widget.WTStat "Sessions" "users" "sessions" sessionsSql - statSlot_ - -- The page-view predicate alone: its two disjuncts are already inside 'browserSql''s - -- OR, so @browserSql AND pageView@ is just @pageView@ — the same subset collapse - -- 'rumPages' applies, and the cheaper predicate plans measurably faster. - $ served (Just $ fromIntegral pulse.pageViews) - $ statWidget "rum-stat-pageviews" Widget.WTTimeseriesStat "Page views" "file-lines" "views" - $ binnedSql "count(*)" pageViewSql - statSlot_ - $ served (Just $ fromIntegral pulse.errors) - $ ( statWidget "rum-stat-errors" Widget.WTTimeseriesStat "Browser errors" "triangle-exclamation" "errors" - $ binnedSql "count(*)" (browserSql <> " AND " <> errorSql) - ) - { Widget.seriesIntent = Just "error" - } - statSlot_ - $ served pulse.p75LoadMs - $ statWidget "rum-stat-p75" Widget.WTStat "P75 page load" "gauge" "ms" p75Sql - where - statSlot_ = div_ [class_ "h-28 min-h-28"] . Widget.widget_ - -- A value rendered with the panel; the widget still refreshes itself on live ticks. - served value widget = widget{Widget.dataset = Just (def :: Widget.WidgetDataset){Widget.source = AE.Null, Widget.servedValue = value}} - statWidget wid wType title icon unit sql = - def - { Widget.wType = wType - , Widget.id = Just wid - , Widget.title = Just title - , Widget.icon = Just icon - , Widget.unit = Just unit - , Widget.sql = Just sql - , Widget.query = Just $ scopedKql links "" - , Widget.summarizeBy = Just Widget.SBSum - , Widget._projectId = Just links.queryScope.projectId - , Widget.standalone = Just True - , Widget.hideSubtitle = Just True - } - - --- | A RUM series as SQL rather than KQL: TimeFusion serves it from the @rum_*@ rollup measures --- only when its filter is exactly the declared predicate, which KQL's lowering never produces --- (@startswith@ becomes a regex, @exception.type != null@ a JSON search). -binnedSql :: Text -> Text -> Text -binnedSql aggregate predicate = - "SELECT extract(epoch from time_bucket('{{rollup_interval}}', timestamp))::integer, 'value', " - <> aggregate - <> "::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND " - <> predicate - <> " GROUP BY time_bucket('{{rollup_interval}}', timestamp) ORDER BY time_bucket('{{rollup_interval}}', timestamp) DESC" - - -sessionsSql :: Text -sessionsSql = - "SELECT distinct_count(approx_count_distinct(attributes___session___id))::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND " - <> browserSql - <> " AND attributes___session___id IS NOT NULL" - - -p75Sql :: Text -p75Sql = - "SELECT (approx_percentile(0.75, percentile_agg(duration)) / 1000000)::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND " - <> pageViewSql - <> " AND duration IS NOT NULL" - - --- | One aggregate unpivoted to (time, series, value): an @iff@ series key is not a rollup --- dimension, while two filtered counts read two rollup measures. A page view that errored --- counts in both series. -activitySql :: Text -activitySql = - "SELECT a.time, s.series, CASE s.series WHEN 'Page views' THEN a.page_views ELSE a.errors END FROM (" - <> "SELECT extract(epoch from time_bucket('{{rollup_interval}}', timestamp))::integer AS time, count(*) FILTER (WHERE " - <> pageViewSql - <> ")::float AS page_views, count(*) FILTER (WHERE " - <> browserSql - <> " AND " - <> errorSql - <> ")::float AS errors FROM otel_logs_and_spans WHERE {{query_ast_filters}} GROUP BY time_bucket('{{rollup_interval}}', timestamp)) a" - <> " CROSS JOIN (VALUES ('Page views'), ('Errors')) AS s(series) ORDER BY a.time DESC" - - -rumActivityWidget_ :: RumLinks -> Html () -rumActivityWidget_ links = - div_ [class_ "h-80 min-h-80"] - $ Widget.widget_ - def - { Widget.wType = Widget.WTTimeseries - , Widget.id = Just "rum-activity" - , Widget.title = Just "Page views and errors" - , Widget.sql = Just activitySql - , Widget.query = Just $ scopedKql links "" - , Widget._projectId = Just links.queryScope.projectId - , Widget.standalone = Just True - , Widget.hideSubtitle = Just True - , Widget.legendPosition = Just "top-right" - , Widget.legendSize = Just Widget.LSXs - , Widget.allowZoom = Just True - } - - --- | Config every embedded RUM table shares. They sit inside a panel that already carries --- the card frame, so the table adds no second surface; fixed layout makes long URLs and --- session ids truncate instead of forcing the panel to scroll sideways. -rumTableConfig :: Text -> Table.Config -rumTableConfig elemId = def{Table.elemID = elemId, Table.renderAsTable = True, Table.noSurface = True, Table.tableClasses = "table table-sm w-full table-fixed"} - - -rightCol :: Text -> (a -> Html ()) -> Table.Column a -rightCol name render = (Table.col name render){Table.align = Just "text-right tabular-nums"} - - -tableZero_ :: Text -> Table.ZeroState -tableZero_ title = Table.ZeroState{icon = "web", title, description = "", action = ESNone} - - -topPages_ :: RumLinks -> [RumPage] -> Html () -topPages_ links pages = rumPanel_ "Top pages" "Traffic and real-user load latency" (Just ("Explore all events", logsUrl links browserPageViewKql)) do - toHtml - Table.Table - { config = rumTableConfig "rumTopPages" - , columns = - [ (Table.col "Page" \page -> a_ [href_ $ logsUrl links (browserPageViewKql <> " and " <> routeKql page.path), class_ "block truncate font-medium text-textBrand"] $ toHtml page.path){Table.attrs = [class_ "w-[46%]"]} - , rightCol "Views" $ toHtml . show . (.views) - , -- A page's P75 judged on the LCP field thresholds (2.5s / 4s), so the colour says - -- at a glance which rows hurt, not just which are busiest. - rightCol "P75 load" \page -> case page.p75LoadMs of - Nothing -> "—" - Just ms -> let style = ratingStyle $ classifyVital 2500 4000 (Just ms) in ratedValue_ style style.label $ toHtml $ getDurationNSMS $ round $ ms * 1e6 - , (rightCol "Last seen" $ Components.localTimeFmt_ "dd MMM HH:mm" . (.lastSeen)){Table.attrs = [class_ "max-sm:hidden"]} - ] - , rows = V.fromList $ sortWith (Down . (.views)) $ map merge $ M.elems $ M.fromListWith (<>) [(pageRoute p.path, pure @NonEmpty p) | p <- pages] - , features = def{Table.zeroState = Just $ tableZero_ "No page views in this time range"} - } - where - browserPageViewKql = browserKql <> " and " <> pageViewKql - -- One row per route; views add up, the worst P75 wins (same worse-wins rule the - -- vitals table applies across emitters), and the route replaces the raw URL. - merge routePages@(newest :| _) = - RumPage - { path = pageRoute newest.path - , views = sum $ (.views) <$> routePages - , p75LoadMs = viaNonEmpty maximum1 $ mapMaybe (.p75LoadMs) $ toList routePages - , lastSeen = maximum1 $ (.lastSeen) <$> routePages - } - - -vitalsPanel_ :: [Vital] -> Html () -vitalsPanel_ vitals = rumPanel_ "Core Web Vitals" "P75 of intervals ending in this range; histogram values are bucket estimates" Nothing do - div_ [class_ "divide-y divide-strokeWeak"] $ forM_ vitals \vital -> do - let rating = vitalRating vital - style = ratingStyle rating - div_ [class_ "px-3 py-3"] do - div_ [class_ "flex items-start justify-between gap-3"] do - div_ [class_ "min-w-0"] do - h3_ [class_ "truncate text-sm font-medium text-textStrong"] $ toHtml vital.label - p_ [class_ "mt-0.5 text-xs text-textWeak"] $ toHtml vital.description - p_ [class_ "mt-0.5 text-xs text-textWeak"] $ toHtml $ measurementNote vital - div_ [class_ "shrink-0 text-right"] do - strong_ [class_ $ "block text-sm font-semibold tabular-nums " <> style.textClass] $ toHtml $ formatVital vital - span_ [class_ "text-xs text-textWeak"] $ toHtml $ observationLabel vital.measurement - div_ [class_ "mt-2 grid grid-cols-3 gap-1", Aria.label_ $ vital.label <> " rating: " <> style.label] - $ forM_ [Good, NeedsImprovement, Poor] \band -> span_ [class_ $ "h-1.5 rounded-full " <> if band == rating then (ratingStyle band).fillClass else "bg-fillWeak", Aria.hidden_ "true"] "" - - --- | One issue: every raw error whose type and normalized message agree. Grouped at render --- time so the cache keeps raw rows; the representative message and page are the newest. -data RumErrorGroup = RumErrorGroup - { errorType :: Text - , message :: Text - , count :: Int - , sessions :: Int - , lastSeen :: UTCTime - , path :: Maybe Text - , sessionId :: Maybe Text - } - - --- | Fold raw error rows (newest first) into issues, loudest first. Messages are grouped --- normalized — UUIDs, numbers and other identifiers masked — so "id=123" and "id=456" --- are one issue, exactly the collapse Sentry and Datadog error tracking perform. -groupErrors :: [RumError] -> [RumErrorGroup] -groupErrors errors = - sortWith (\g -> (Down g.count, Down g.lastSeen)) - $ map summarise - $ M.elems - $ M.fromListWith (flip (<>)) [((e.errorType, normalizeMessage e.message), pure @NonEmpty e) | e <- errors] - where - summarise issue@(latest :| _) = - RumErrorGroup - { errorType = latest.errorType - , message = latest.message - , count = length issue - , sessions = length $ ordNub $ mapMaybe (.sessionId) $ toList issue - , lastSeen = latest.timestamp - , path = asum $ map (.path) $ toList issue - , sessionId = asum $ map (.sessionId) $ toList issue - } - - -recentErrors_ :: RumLinks -> [RumError] -> Html () -recentErrors_ links errors = rumPanel_ "Browser errors" "Grouped by signature; counts and sessions are within this range" (Just ("View errors", logsUrl links (browserKql <> " and status_code == \"ERROR\""))) do - if null errors - then div_ [class_ "flex items-center gap-2 px-3 py-5 text-sm text-textWeak"] $ faSprite_ "circle-check" "regular" "h-4 w-4 text-textSuccess" >> "No browser errors in this range" - else ul_ [class_ "divide-y divide-strokeWeak"] $ forM_ (take 6 $ groupErrors errors) \issue -> li_ [class_ "px-3 py-2.5"] do - div_ [class_ "flex items-start gap-2"] do - faSprite_ "triangle-exclamation" "solid" "mt-0.5 h-3.5 w-3.5 shrink-0 text-iconError" - div_ [class_ "min-w-0 flex-1"] do - div_ [class_ "flex items-center justify-between gap-2"] do - div_ [class_ "flex min-w-0 items-center gap-1.5"] do - strong_ [class_ "truncate text-sm font-medium text-textStrong"] $ toHtml issue.errorType - when (issue.count > 1) $ span_ [class_ "badge badge-sm badge-error badge-outline shrink-0 tabular-nums"] $ toHtml $ "×" <> show issue.count - span_ [class_ "shrink-0 text-xs text-textWeak"] $ Components.localTimeFmt_ "HH:mm" issue.lastSeen - p_ [class_ "mt-0.5 line-clamp-2 text-xs text-textWeak"] $ toHtml issue.message - div_ [class_ "mt-1 flex flex-wrap items-center gap-x-2 text-xs text-textWeak"] do - forM_ issue.path $ span_ [class_ "max-w-56 truncate font-mono"] . toHtml - when (issue.sessions > 0) $ span_ [class_ "tabular-nums"] $ toHtml $ countNoun issue.sessions "session" - forM_ issue.sessionId \sid -> do - a_ [href_ $ sessionsUrl links Nothing AllSessionRows (Just sid), class_ "font-medium text-textBrand hover:underline"] "View session" - a_ [href_ $ sessionLogsUrl links sid, class_ "font-medium text-textBrand hover:underline"] "Telemetry" - - -data AudienceRow = AudienceRow - { name :: Text - , sessions :: Int64 - , views :: Int64 - , errors :: Int64 - } - - --- | Collapse per-user-agent traffic onto one classified dimension. A session using two --- user agent strings would count once per string; families make that vanishingly rare. -audienceBy :: ((Text, Text, Text) -> Text) -> [RumBreakdown] -> [AudienceRow] -audienceBy pick rows = - sortWith (Down . (.sessions)) - $ map (\(name, (sessions, views, errors)) -> AudienceRow{name, sessions, views, errors}) - $ M.toList - $ M.fromListWith - (\(a, b, c) (x, y, z) -> (a + x, b + y, c + z)) - [(pick $ classifyUserAgent row.userAgent, (row.sessions, row.views, row.errors)) | row <- rows] - - --- | Who the traffic is: the first question of "is this bug Safari-only?" and "is mobile --- slower?", which an aggregate summary cannot answer. Every RUM product leads with this. -audiencePanel_ :: [RumBreakdown] -> Html () -audiencePanel_ breakdown = rumPanel_ "Audience" "Sessions by browser, operating system, and device class — errors highlight where failures concentrate" Nothing do - if null breakdown - then Components.emptyState_ def{size = ESCompact} "No user agent data in this time range" "" - else div_ [class_ "grid grid-cols-3 divide-x divide-strokeWeak max-md:grid-cols-1 max-md:divide-x-0 max-md:divide-y"] do - audienceColumn_ "Browser" browserHue $ audienceBy (\(b, _, _) -> b) breakdown - audienceColumn_ "Operating system" osHue $ audienceBy (\(_, os, _) -> os) breakdown - audienceColumn_ "Device" deviceHue $ audienceBy (\(_, _, d) -> d) breakdown - - --- | Fixed hues per family, so the colour becomes the recognition cue: Safari is the same --- colour on the audience bars, the session rows and every future view. -osHue :: Text -> Int -osHue = fromMaybe 261 . (`lookup` [("Windows", 230), ("macOS", 261), ("iOS", 300), ("Android", 200), ("ChromeOS", 215), ("Linux", 320)]) - - -deviceHue :: Text -> Int -deviceHue = fromMaybe 230 . (`lookup` [("Mobile", 200), ("Tablet", 300)]) - - -audienceColumn_ :: Text -> (Text -> Int) -> [AudienceRow] -> Html () -audienceColumn_ title hue rows = div_ [class_ "min-w-0 px-3 py-2.5"] do - h3_ [class_ "text-xs font-medium uppercase tracking-wide text-textWeak"] $ toHtml title - ul_ [class_ "mt-2 space-y-2"] $ forM_ (take 5 rows) \row -> li_ [class_ "min-w-0"] do - div_ [class_ "flex items-baseline justify-between gap-2 text-sm"] do - span_ [class_ "flex min-w-0 items-center gap-1.5"] do - span_ [class_ "rum-chip flex h-4 w-4 shrink-0 items-center justify-center rounded text-2xs font-bold", style_ $ "--hue:" <> show (hue row.name), Aria.hidden_ "true"] $ toHtml $ T.take 1 row.name - span_ [class_ "truncate font-medium text-textStrong"] $ toHtml row.name - span_ [class_ "shrink-0 text-xs tabular-nums text-textWeak"] do - when (row.errors > 0) do - span_ [class_ "font-medium text-textError"] $ toHtml $ countNoun row.errors "error" - " · " - toHtml $ countNoun row.sessions "session" - div_ [class_ "mt-1 h-1.5 w-full overflow-hidden rounded-full bg-fillWeak", Aria.hidden_ "true"] - $ div_ [class_ "rum-bar h-full rounded-full", style_ $ "width:" <> show (share row) <> "%;--hue:" <> show (hue row.name)] "" - where - maxSessions = foldl' max 1 $ map (.sessions) rows - share row = max 2 $ round @Double @Int $ fromIntegral row.sessions / fromIntegral maxSessions * 100 - - -recentSessions_ :: RumData -> Html () -recentSessions_ page = rumPanel_ "Recent sessions" "Open a recording or inspect its correlated telemetry" (Just ("View all sessions", sessionsUrl page.links Nothing AllSessionRows Nothing)) do - when page.servedStale refreshingHint_ - sessionsTable_ False page.now page.links Nothing AllSessionRows Nothing (take 8 page.sessions) - - -refreshingHint_ :: Html () -refreshingHint_ = p_ [class_ "flex items-center gap-2 border-b border-strokeWeak px-3 py-1.5 text-xs text-textWeak", role_ "status"] do - span_ [class_ "loading loading-spinner loading-xs", Aria.hidden_ "true"] "" - "Refreshing the full time range…" - - --- | Mirrors the split layout 'sessions_' renders — list left, replay workspace right — so --- neither the first paint nor the panel shell flashes a different frame than the content --- that replaces it. No fake search bar: the real one is already in the toolbar above. -sessionsSkeleton_ :: Html () -sessionsSkeleton_ = div_ [class_ "grid bg-bgBase xl:h-full xl:min-h-0 xl:grid-cols-[minmax(32rem,35%)_minmax(0,1fr)]", role_ "status", Aria.label_ "Loading sessions"] do - section_ [class_ "min-w-0 overflow-y-auto border-strokeWeak xl:border-e max-xl:max-h-[45svh] max-xl:border-b"] do - div_ [class_ "flex items-center gap-1.5 border-b border-strokeWeak px-3 py-1.5"] - $ replicateM_ 3 - $ div_ [class_ "h-5 w-20 rounded-full skeleton-shimmer"] "" - div_ [class_ "flex flex-col gap-4 p-3"] - $ replicateM_ 8 - $ div_ [class_ "flex items-center gap-2.5"] do - div_ [class_ "h-8 w-8 shrink-0 rounded-full skeleton-shimmer"] "" - div_ [class_ "flex min-w-0 grow flex-col gap-1.5"] do - div_ [class_ "h-3 w-2/5 rounded skeleton-shimmer"] "" - div_ [class_ "h-2.5 w-3/5 rounded skeleton-shimmer"] "" - div_ [class_ "h-3 w-14 shrink-0 rounded skeleton-shimmer"] "" - section_ [class_ "min-w-0 bg-bgBase"] mempty - - -sessions_ :: RumData -> Html () -sessions_ page = slot_ page PanelSessions sessionsSkeleton_ do - div_ [class_ "grid bg-bgBase xl:h-full xl:min-h-0 xl:grid-cols-[minmax(32rem,35%)_minmax(0,1fr)]"] do - section_ [id_ "rum-sessions-list", Aria.label_ "Sessions", tabindex_ "0", class_ "min-w-0 overflow-y-auto overscroll-contain border-strokeWeak xl:min-h-0 xl:border-e max-xl:max-h-[45svh] max-xl:border-b"] do - when page.servedStale refreshingHint_ - if PanelSessions `elem` map queryPanel page.degradedPanels then degradedBanner_ page PanelSessions else sessionsTable_ True page.now page.links page.query page.sessionFilter page.selectedSession page.sessions - panelRevalidation_ page PanelSessions - sessionWorkspace_ page - - -sessionWorkspace_ :: RumData -> Html () -sessionWorkspace_ page = - section_ [id_ "rum-replay-workspace", class_ "min-w-0 bg-bgBase xl:min-h-0 xl:overflow-y-auto xl:overscroll-contain", Aria.label_ "Session details"] do - if PanelSessionDetail `elem` map queryPanel page.degradedPanels then degradedBanner_ page PanelSessionDetail else replayWorkspace_ page.links selected - when (page.panel == Just PanelSessionDetail) $ panelRevalidation_ page PanelSessionDetail - where - selected = page.selectedSessionData <|> (page.selectedSession >>= \sid -> find ((== sid) . (.id)) page.sessions) - - -sessionFilterLabel :: SessionFilter -> Text -sessionFilterLabel = \case - AllSessionRows -> "All sessions" - ErrorSessionRows -> "With errors" - ReplaySessionRows -> "With replay" - - --- | @workspace@ marks the Sessions tab, where the replay panel sits beside the table: there --- a row swaps only that panel instead of re-rendering the page around it, and the shared --- Table contributes the filter tabs and the zero state. The Overview's recent list --- has no panel to swap, so its rows navigate and it carries none of the chrome. -sessionsTable_ :: Bool -> UTCTime -> RumLinks -> Maybe Text -> SessionFilter -> Maybe Text -> [RumSession] -> Html () -sessionsTable_ workspace now links query sessionFilter selectedSession sessions = - toHtml - Table.Table - { config = (rumTableConfig $ bool "rumRecentSessions" "rumSessions" workspace){Table.containerClasses = "w-full mx-auto space-y-0", Table.tableClasses = "table table-sm w-full table-fixed sm:min-w-[28rem]"} - , columns = - [ ( Table.col "Session" \session -> div_ [class_ "flex items-center gap-2.5"] do - sessionAvatar_ session - div_ [class_ "min-w-0 flex-1"] do - div_ [class_ "flex items-center gap-1.5"] do - a_ - ( sessionLinkAttrs session.id - <> [ id_ $ "rum-session-" <> toXXHash session.id - , class_ "rum-session-link block truncate font-medium text-textStrong hover:text-textBrand aria-[current=true]:text-textBrand focus-visible:outline-none" - , data_ "session-id" session.id - , term "aria-current" $ bool "false" "true" (selectedSession == Just session.id) - , Aria.label_ $ bool "Open session for " "Watch replay for " session.hasReplay <> sessionIdentity session - , title_ $ sessionIdentity session - , onkeydown_ "if (event.key === 'Enter') event.stopPropagation()" - ] - -- A shared link lands with its row in view; the list morphs on refresh, so this fires once. - <> [term "_" "init call me.scrollIntoView({block: 'center'})" | selectedSession == Just session.id] - ) - $ toHtml - $ if sessionIdentity session == session.id then "Session " <> T.take 8 session.id else sessionIdentity session - when (isActive now session) - $ span_ [class_ "rum-pulse-dot shrink-0", title_ "Active now", Aria.label_ "Session active now"] "" - div_ [class_ "mt-0.5 flex items-center gap-1.5 text-xs text-textWeak"] do - forM_ (classifyUserAgent <$> session.userAgent) \(browser, os, device) -> do - envChip_ browser - span_ $ toHtml os - faSprite_ (deviceIcon device) "solid" "h-3 w-3 shrink-0 text-iconNeutral" - span_ [class_ "truncate font-mono", title_ session.id] $ toHtml $ T.take 8 session.id - ) - { Table.attrs = [class_ $ bool "w-[38%]" "w-[46%]" workspace <> " px-2 py-2"] - , Table.headerExtra = Just $ span_ [class_ "md:hidden"] "Session" - } - , ( Table.col "Last page" \session -> do - -- Display the distinguishing path; keep the full URL available on hover. - span_ [class_ $ "block text-sm text-textStrong" <> bool "" " truncate" (isJust session.lastPage), title_ $ fromMaybe "" session.lastPage] - $ toHtml - $ maybe (bool "No page views" "Recording only" (replayOnly session)) pageLabel session.lastPage - span_ [class_ "mt-0.5 block text-xs text-textWeak", title_ $ show session.endedAt] - $ toHtml - $ prettyTimeShort now session.endedAt - ) - { Table.attrs = [class_ $ bool "w-[22%]" "w-[20%]" workspace <> " px-2 py-2"] - } - , ( Table.col "Activity" \session -> do - when (session.errors > 0) $ span_ [class_ "mb-1 inline-flex items-center gap-1 rounded-full bg-fillError-weak px-1.5 py-0.5 text-xs font-medium text-textError"] do - faSprite_ "triangle-exclamation" "solid" "h-2.5 w-2.5 shrink-0" - toHtml $ countNoun session.errors "error" - if replayOnly session - then span_ [class_ "text-xs text-textWeak"] "No telemetry" - else div_ [class_ "flex items-center gap-2.5 text-xs tabular-nums"] do - -- sr-only carries the unit so the icon+number readout stays accessible. - span_ [class_ "flex items-center gap-1 text-textStrong", title_ "Page views"] do - faSprite_ "file-lines" "regular" "h-3 w-3 text-iconBrand" - toHtml $ show session.views - span_ [class_ "sr-only"] $ toHtml $ " " <> countNoun session.views "view" - span_ [class_ "flex items-center gap-1 text-textWeak", title_ "Events"] do - faSprite_ "bolt" "regular" "h-3 w-3 text-iconNeutral" - toHtml $ show session.events - span_ [class_ "sr-only"] $ toHtml $ " " <> countNoun session.events "event" - ) - { Table.attrs = [class_ $ bool "w-[22%]" "w-[18%]" workspace <> " px-2 py-2 max-sm:hidden"] - } - , ( Table.col "Duration" \session -> do - span_ [class_ "block text-sm tabular-nums text-textStrong"] $ toHtml $ formatSessionDuration session - if session.hasReplay - then span_ [class_ "mt-0.5 inline-flex items-center gap-1 rounded-full bg-fillSuccess-weak px-1.5 py-0.5 text-xs font-medium text-textSuccess"] do - faSprite_ "circle-play" "regular" "h-2.5 w-2.5 shrink-0" - "Replay" - else span_ [class_ "mt-0.5 block text-xs text-textWeak"] "No replay" - ) - { Table.attrs = [class_ $ bool "w-[18%]" "w-[16%]" workspace <> " max-sm:w-[20%] px-2 py-2.5"] - } - ] - , rows = V.fromList sessions - , features = - def - { Table.rowAttrs = - Just - $ const - [ class_ " cursor-pointer [&:has(a[aria-current=true])]:bg-fillBrand-weak [&:has(a:focus-visible)]:outline-2 [&:has(a:focus-visible)]:-outline-offset-2 [&:has(a:focus-visible)]:outline-strokeFocus" - , onclick_ "if (!event.target.closest('a, button, input, select, textarea') && !window.getSelection()?.toString()) { const link = this.querySelector('.rum-session-link'); if (event.ctrlKey || event.metaKey) window.open(link.href, '_blank', 'noopener'); else link.click(); }" - ] - , Table.header = - guard workspace - $> div_ [class_ "sticky top-0 z-10 flex flex-wrap items-center justify-between gap-2 border-b border-strokeWeak bg-bgBase px-3 py-1"] do - nav_ [class_ "tabs tabs-box tabs-outline tabs-xs items-center", Aria.label_ "Filter sessions"] $ forM_ [minBound .. maxBound] $ \value -> do - let url = sessionsUrl links query value selectedSession - filterValue = fromMaybe "" $ sessionFilterParam value - a_ - [ href_ url - , hxGet_ $ "/p/" <> links.queryScope.projectId.toText <> "/rum" - , term "hx-include" "#rum-session-search-form" - , term "hx-vals" $ "{\"panel\":\"sessions\",\"deferred\":\"1\",\"filter\":\"" <> filterValue <> "\"}" - , hxTarget_ "#rum-sessions-list" - , hxSelect_ "#rum-sessions-list" - , hxSwap_ "outerMorph" - , hxPushUrl_ url - , term "hx-sync" "#rum-session-search-form:replace" - , data_ "filter" filterValue - , term "hx-on::after:request" "if (event.detail.ctx.response.status === 200) document.getElementById('rum-session-filter').value = this.dataset.filter" - , term "aria-current" $ bool "false" "page" (value == sessionFilter) - , class_ $ "tab h-auto! " <> bool "" "tab-active text-textStrong" (value == sessionFilter) - ] - $ toHtml - $ sessionFilterLabel value - span_ [class_ "flex shrink-0 items-center gap-2.5"] do - let activeCount = length $ filter (isActive now) sessions - when (activeCount > 0) - $ span_ [class_ "inline-flex items-center gap-1.5 rounded-full bg-fillSuccess-weak px-2 py-0.5 text-xs font-medium text-textSuccess"] do - span_ [class_ "rum-pulse-dot", Aria.hidden_ "true"] "" - toHtml $ show activeCount <> " active now" - span_ [class_ "text-xs tabular-nums text-textWeak", role_ "status", Aria.live_ "polite"] $ toHtml $ (if length sessions == 200 then "Newest " else "") <> countNoun (length sessions) "session" - , Table.zeroState = Just $ tableZero_ $ bool "No sessions in this time range" "No sessions match this filter" (sessionFilter /= AllSessionRows || maybe False (not . T.null) query) - } - } - where - sessionLinkAttrs sid = - let url = sessionsUrl links query sessionFilter $ Just sid - in href_ url - : if workspace - then - [ hxGet_ $ url <> "&panel=session_detail&deferred=1" - , hxTarget_ "#rum-replay-workspace" - , term "hx-on::after:request" "if (event.detail.ctx.response.status >= 200 && event.detail.ctx.response.status < 300) { document.querySelectorAll('.rum-session-link').forEach(link => link.setAttribute('aria-current', String(link.dataset.sessionId === this.dataset.sessionId))); document.getElementById('rum-session-search').form.elements.session.value = this.dataset.sessionId; }" - , hxSelect_ "#rum-replay-workspace" - , hxSwap_ "outerHTML" - , hxPushUrl_ url - , hxIndicator_ "#rum-replay-workspace" - , term "hx-sync" "#rum-replay-workspace:replace" - ] - else [] - - -replayWorkspace_ :: RumLinks -> Maybe RumSession -> Html () -replayWorkspace_ links = \case - Just session -> div_ [class_ "min-h-full"] do - header_ [class_ "border-b border-strokeWeak bg-bgBase px-4 py-3"] do - div_ [class_ "flex flex-wrap items-center justify-between gap-3"] do - div_ [class_ "flex min-w-0 items-center gap-3"] do - sessionAvatar_ session - div_ [class_ "min-w-0"] do - div_ [class_ "flex items-center gap-2"] do - h2_ [class_ "truncate text-sm font-semibold text-textStrong"] $ toHtml $ sessionIdentity session - forM_ (classifyUserAgent <$> session.userAgent) \(browser, os, device) -> do - envChip_ browser - span_ [class_ "text-xs text-textWeak"] $ toHtml os - faSprite_ (deviceIcon device) "solid" "h-3 w-3 text-iconNeutral" - p_ [class_ "mt-0.5 truncate font-mono text-xs text-textWeak"] $ toHtml session.id - a_ [href_ $ sessionLogsUrl links session.id, class_ "btn btn-sm gap-1.5"] do - faSprite_ "magnifying-glass-chart" "regular" "h-3.5 w-3.5" - "Inspect telemetry" - -- The facts the list row carries, so a shared link answers "how long, how many pages, - -- any errors" before the recording has loaded. Errors are the only tinted value. - dl_ [class_ "mt-2 flex flex-wrap items-baseline gap-x-4 gap-y-1 text-xs tabular-nums"] do - let fact :: Text -> Text -> Maybe Text -> Html () - fact label value hint = div_ [class_ "flex min-w-0 items-baseline gap-1"] do - dt_ [class_ "shrink-0 text-textWeak"] $ toHtml label - dd_ (class_ "truncate font-medium text-textStrong" : [title_ h | Just h <- [hint]]) $ toHtml value - fact "Duration" (formatSessionDuration session) Nothing - if replayOnly session - then div_ do - dt_ [class_ "sr-only"] "Telemetry" - dd_ [class_ "text-textWeak"] "No telemetry" - else do - fact "Page views" (show session.views) Nothing - fact "Events" (show session.events) Nothing - if session.errors > 0 - then div_ do - dt_ [class_ "sr-only"] "Errors" - dd_ [class_ "inline-flex items-center gap-1 rounded-full bg-fillError-weak px-1.5 py-0.5 font-medium text-textError"] do - faSprite_ "triangle-exclamation" "solid" "h-2.5 w-2.5 shrink-0" - toHtml $ countNoun session.errors "error" - else fact "Errors" "0" Nothing - forM_ session.lastPage \url -> fact "Last page" (pageLabel url) (Just url) - forM_ session.service \service -> fact "Service" service (Just service) - if session.hasReplay - then termRaw "session-replay" [id_ "rumSessionReplay", term "initialSession" session.id, term "consoleOpen" "true", term "fullWidth" "true", class_ "block min-h-[34rem] w-full", term "projectId" links.queryScope.projectId.toText, term "containerId" "rum-replay-workspace"] ("" :: Text) - else div_ [class_ "space-y-1 p-4"] do - h3_ [class_ "text-sm font-medium text-textStrong"] "No recording for this session" - p_ [class_ "text-sm text-textWeak"] "Inspect telemetry to follow navigation, network requests, and errors." - Nothing -> - div_ [class_ "flex min-h-[34rem] flex-col items-center justify-center p-8"] - $ Components.emptyState_ def{icon = Just "video"} "Select a session" "Choose a session to inspect its activity or watch an available recording." - - -performance_ :: RumData -> Html () -performance_ page = div_ [class_ "space-y-2 px-4 pb-4 pt-2 max-md:px-3"] do - -- A project that reports no Web Vitals at all gets one explanation, not five "No data" - -- rows plus two more empty panels below them. - let noVitals = all ((== Unmeasured) . (.measurement)) page.vitals - slot_ page PanelVitals (panelSkeleton_ $ Components.tableSkeleton_ 6) - $ if noVitals - then - rumPanel_ "Web Vitals" "P75 of LCP, INP, CLS, FCP and TTFB against Google's thresholds" Nothing - $ Components.emptyState_ - def - { icon = Just "gauge" - , action = ESCustom $ div_ [class_ "flex flex-wrap items-center justify-center gap-3"] do - a_ [href_ $ rumUrl page.links{window = TimePicker.mkTimeWindow page.now Nothing Nothing (Just "7D")} [("tab", "performance")], class_ "btn btn-sm btn-primary"] "Widen to 7 days" - a_ [href_ "https://monoscope.tech/docs/sdks/browser/", target_ "_blank", rel_ "noopener noreferrer", class_ "link text-sm text-textBrand"] "Check the SDK metrics export" - } - "No Web Vitals in this time range" - "Nothing sent a browser.web_vital.* metric for this scope. The browser SDK reports LCP, INP, CLS, FCP and TTFB automatically once its metrics export is on." - else vitalsTable_ page.vitals - slot_ page PanelVitalTrend (panelSkeleton_ Components.chartSkeleton_) $ unless noVitals do - vitalTrendPanel_ page.links.window page.vitalTrend - div_ [class_ "mt-4"] $ pageVitalsTable_ page.links page.pageVitals - div_ [class_ "grid grid-cols-2 gap-4 max-lg:grid-cols-1"] do - slot_ page PanelPages (panelSkeleton_ $ Components.tableSkeleton_ 5) $ topPages_ page.links page.pages - slot_ page PanelErrors (panelSkeleton_ $ Components.tableSkeleton_ 5) $ recentErrors_ page.links page.errors - slot_ page PanelAudience (panelSkeleton_ $ Components.tableSkeleton_ 3) $ audiencePanel_ page.breakdown - - --- | One platform chart per vital, with Google's good/poor marks as the widget's own --- threshold lines. The data uses the shared server-side population because --- histogram-backed vitals are not yet expressible in the widget KQL pipeline (@value@ is --- NULL on histogram datapoints); the dataset is embedded, so the widget renders like every --- other chart in the product without fetching anything of its own. -vitalTrendPanel_ :: TimePicker.TimeWindow -> [VitalTrendPoint] -> Html () -vitalTrendPanel_ window points = rumPanel_ "Web Vitals over time" "P75 of intervals ending in each bucket; unavailable coverage appears as gaps" Nothing do - if null points - then Components.emptyState_ def{size = ESCompact} "No web vital samples in this time range" "" - else div_ [class_ "grid grid-cols-2 gap-3 p-3 max-lg:grid-cols-1"] $ forM_ vitalDefinitions \vital -> do - let series = sortWith fst [(p.bucket, RUM.measurementValue p.measurement) | p <- points, p.metricName == vital.name] - -- Milliseconds, matching what the chart endpoint serves (Charts.convertTimestampsToMs): - -- the axis reads epoch-ms, and seconds silently render as a 1970 timeline. - sourceRows = AE.toJSON (["timestamp", "P75"] :: [Text]) : [AE.toJSON (floor (1000 * utcTimeToPOSIXSeconds (max window.fromTime bucketTime)) :: Int64, value) | (bucketTime, value) <- series] - unless (null series) - $ div_ [class_ "h-52 min-h-52"] - $ Widget.widget_ - def - { Widget.wType = Widget.WTTimeseriesLine - , Widget.id = Just $ "rum-vital-trend-" <> vital.name - , Widget.title = Just vital.label - , Widget.unit = Just vital.unit - , Widget.standalone = Just True - , Widget.hideSubtitle = Just True - , Widget.hideLegend = Just True - , Widget.hideValue = Just True - , Widget.warningThreshold = Just vital.goodAt - , Widget.alertThreshold = Just vital.poorAt - , Widget.showThresholdLines = Just Widget.TLAlways - , Widget.dataset = - Just - (def :: Widget.WidgetDataset) - { Widget.source = AE.toJSON sourceRows - , Widget.from = Just $ floor $ 1000 * utcTimeToPOSIXSeconds window.fromTime - , Widget.to = Just $ floor $ 1000 * utcTimeToPOSIXSeconds window.toTime - } - } - - --- | Path of a page URL for display; the full URL stays in the tooltip. --- --- >>> pageLabel "https://shop.example/cart" --- "/cart" --- >>> pageLabel "https://shop.example" --- "/" --- >>> pageLabel "/checkout" --- "/checkout" -pageLabel :: Text -> Text -pageLabel url - | "://" `T.isInfixOf` url = "/" <> T.intercalate "/" (drop 3 $ T.splitOn "/" url) - | otherwise = url - - --- | Collapse page URLs into routes, the grouping Datadog performs into view names: query --- and fragment dropped, and any path segment 'replaceAllFormats' finds variable content in --- (uuid, number, hash — the masks error grouping uses) becomes @:id@ wholesale, so SKUs --- like @2ZYFJ3GM2N@ don't leave partial-mask confetti. Short segments such as @v2@ stay --- literal. --- --- A wholly id-like segment keeps its inferred type — "/lookup/{uuid}" vs --- "/lookup/{integer}" is the key shape of the endpoint, learned without any route --- template. @:id@ is reserved for SKU-style tokens where no type is detectable. --- --- >>> pageRoute "https://shop.example/cart/checkout/c73bcdcc-2669-4bf6-81d3-e4ae73fb11fd?order=x" --- "/cart/checkout/{uuid}" --- >>> pageRoute "/product/2ZYFJ3GM2N" --- "/product/:id" --- >>> pageRoute "/products/12345" --- "/products/{integer}" --- >>> pageRoute "/api/v2/cart" --- "/api/v2/cart" --- --- Host-style or wordy segments keep their identity even when they contain a digit: --- --- >>> pageRoute "l2.example/cached" --- "l2.example/cached" -pageRoute :: Text -> Text -pageRoute = T.intercalate "/" . map maskSegment . T.splitOn "/" . T.takeWhile (`notElem` ("?#" :: String)) . pageLabel - where - maskSegment seg - | masked `elem` ["{uuid}", "{integer}", "{hex}", "{sha1}", "{sha256}", "{md5}"] = masked - | T.length seg >= 8 && T.any isDigit seg && not (T.any isLower seg) = ":id" - | otherwise = seg - where - masked = replaceAllFormats seg - - --- | Explorer filter for a masked route: exact path match when nothing was masked, else a --- prefix match on the static part before the first mask. --- --- >>> putTextLn (routeKql "/") --- (attributes.url.path == "/" or attributes.url.full matches regex "^([A-Za-z][A-Za-z0-9+.-]*://[^/?#]+/?|/)([?#].*)?$") --- >>> putTextLn (routeKql "/cart") --- (attributes.url.path == "/cart" or attributes.url.full matches regex "^([A-Za-z][A-Za-z0-9+.-]*://[^/?#]+)?/cart([?#].*)?$") --- >>> putTextLn (routeKql "/item/{hex}") --- (attributes.url.path startswith "/item/" or attributes.url.full contains "/item/") -routeKql :: Text -> Text -routeKql route - -- Both spellings, matching 'pagePath': our SDK sets url.path, the browser SDK only url.full. - | prefix == route = "(attributes.url.path == " <> kqlQuoted route <> " or attributes.url.full matches regex " <> kqlQuoted routeRegex <> ")" - | otherwise = "(attributes.url.path startswith " <> kqlQuoted prefix <> " or attributes.url.full contains " <> kqlQuoted prefix <> ")" - where - prefix = fst $ T.breakOn "{" $ fst $ T.breakOn ":id" route - origin = "[A-Za-z][A-Za-z0-9+.-]*://[^/?#]+" - routeRegex = "^" <> (if route == "/" then "(" <> origin <> "/?|/)" else "(" <> origin <> ")?" <> escapeRegex route) <> "([?#].*)?$" - - --- | Traffic-weighted room for improvement, after Sentry's "Opportunity" ranking: sample --- count times how far each vital's P75 sits past its "good" threshold, normalized per --- vital so CLS (unitless) and the millisecond vitals weigh equally. --- --- The invariant this exists for — a quiet page with a poor vital outranks a busy page --- whose vitals are all good: --- --- >>> opportunityScore [(2500, 4000, 2000)] 100000 --- 0.0 --- >>> opportunityScore [(2500, 4000, 4750)] 10 > opportunityScore [(2500, 4000, 2000)] 100000 --- True -opportunityScore :: [(Double, Double, Double)] -> Natural -> Double -opportunityScore vitals sampleTotal = fromIntegral sampleTotal * sum [max 0 ((p75 - goodAt) / (poorAt - goodAt)) | (goodAt, poorAt, p75) <- vitals] - - --- | Sentry's signature vitals view: one row per page, P75 per vital, each judged on its --- own thresholds. Rows lead with the largest 'opportunityScore' (ties broken by traffic), --- so the fix that would move the site-wide experience most is always on top. -pageVitalsTable_ :: RumLinks -> [PageVitalPoint] -> Html () -pageVitalsTable_ links points = rumPanel_ "Web Vitals by page" "Exact page URLs; histogram P75s are estimates within the shown bucket range" Nothing do - toHtml - Table.Table - { config = (rumTableConfig "rumPageVitals"){Table.tableClasses = "table table-sm w-full table-fixed max-sm:[&_thead]:sr-only max-sm:[&_td]:block max-sm:[&_td]:min-w-0 max-sm:[&_td]:border-0 max-sm:[&_td]:py-1 max-sm:[&_td]:text-left"} - , columns = - ( Table.col "Page" \(url, _, _) -> a_ [href_ $ logsUrl links (browserKql <> " and " <> exactPageKql url), class_ "block truncate font-medium text-textBrand max-sm:min-h-11 max-sm:whitespace-normal max-sm:break-all", title_ url, Aria.label_ url] do - toHtml $ pageLabel url - when (pageLabel url /= url) $ span_ [class_ "block truncate text-xs text-textWeak max-sm:whitespace-normal max-sm:break-all"] $ toHtml url - ) - { Table.attrs = [class_ "sm:w-[28%] max-sm:col-span-2"] - } - : [ rightCol (T.toUpper vital.name) \(_, byVital, _) -> do - span_ [class_ "block text-xs text-textWeak sm:hidden", Aria.hidden_ "true"] $ toHtml $ T.toUpper vital.name <> " P75" - vitalCell vital byVital - | vital <- vitalDefinitions - ] - <> [ rightCol "Observations" \(_, _, sampleTotal) -> do - span_ [class_ "block text-xs text-textWeak sm:hidden", Aria.hidden_ "true"] "Observations" - toHtml $ show sampleTotal - ] - , rows = V.fromList pageRows - , features = def{Table.zeroState = Just $ tableZero_ "No page-attributed web vital observations in this time range", Table.rowAttrs = Just $ const [class_ " max-sm:grid max-sm:grid-cols-2 max-sm:gap-x-4 max-sm:border-b max-sm:border-strokeWeak max-sm:py-3 max-sm:last:border-0"]} - } - where - exactPageKql url - | "://" `T.isInfixOf` url = "attributes.url.full == " <> kqlQuoted url - | otherwise = routeKql url - vitalCell :: Vital -> M.Map Text VitalMeasurement -> Html () - vitalCell vital byVital = case M.lookup vital.name byVital of - Nothing -> span_ [class_ "text-textWeak"] "—" - Just measurement -> do - let measured = (vital :: Vital){measurement} - ratedValue_ (ratingStyle $ vitalRating measured) (measurementNote measured) $ toHtml $ formatVital measured - span_ [class_ "block text-xs text-textWeak sm:hidden"] $ toHtml $ measurementNote measured - score byVital = opportunityScore [(v.goodAt, v.poorAt, value) | v <- vitalDefinitions, Just measurement <- [M.lookup v.name byVital], Just value <- [RUM.measurementValue measurement]] - pageRows = - take 12 - $ sortWith - (\(_, byVital, sampleTotal) -> Down (score byVital sampleTotal, sampleTotal)) - [(url, M.fromList [(point.metricName, point.measurement) | point <- cells], sum $ map (RUM.measurementSamples . (.measurement)) cells) | (url, cells) <- M.toList $ M.fromListWith (<>) [(point.page, [point]) | point <- points]] - - -vitalsTable_ :: [Vital] -> Html () -vitalsTable_ vitals = rumPanel_ "Web Vitals field performance" "Intervals ending in this range can include earlier observations. Histogram estimates assume uniform values within a bucket." Nothing do - toHtml - Table.Table - { config = (rumTableConfig "rumVitals"){Table.tableClasses = "table table-sm w-full max-sm:[&_thead]:sr-only max-sm:[&_td]:block max-sm:[&_td]:min-w-0 max-sm:[&_td]:border-0 max-sm:[&_td]:py-1"} - , columns = - [ (Table.col "Metric" \vital -> strong_ [class_ "block text-sm font-medium text-textStrong"] (toHtml vital.label) >> span_ [class_ "text-xs text-textWeak"] (toHtml vital.description)){Table.attrs = [class_ "max-sm:col-span-2"]} - , (rightCol "P75" \vital -> span_ [class_ "mr-2 text-xs text-textWeak sm:hidden", Aria.hidden_ "true"] "P75" >> span_ [class_ $ "font-semibold " <> (ratingStyle $ vitalRating vital).textClass] (toHtml $ formatVital vital)){Table.attrs = [class_ "max-sm:order-1 max-sm:text-left"]} - , threshold "Good" (.goodAt) "max-sm:order-5" - , threshold "Poor" (.poorAt) "max-sm:order-6" - , (Table.col "Assessment" \vital -> let style = ratingStyle $ vitalRating vital in Components.tonePill_ style.tone style.label){Table.attrs = [class_ "max-sm:order-2 max-sm:text-right"]} - , (Table.col "Coverage" $ toHtml . measurementNote){Table.attrs = [class_ "text-xs text-textWeak max-sm:order-4 max-sm:col-span-2"]} - , (rightCol "Observations" $ toHtml . observationLabel . (.measurement)){Table.attrs = [class_ "text-textWeak max-sm:order-3 max-sm:col-span-2 max-sm:text-left"]} - ] - , rows = V.fromList vitals - , features = def{Table.rowAttrs = Just $ const [class_ " max-sm:grid max-sm:grid-cols-2 max-sm:border-b max-sm:border-strokeWeak max-sm:py-3 max-sm:last:border-0"]} - } - where - threshold label at order = (rightCol label \vital -> span_ [class_ "mr-2 text-xs sm:hidden", Aria.hidden_ "true"] (toHtml label) >> toHtml (formatVitalThreshold vital $ at vital)){Table.attrs = [class_ $ "text-textWeak max-sm:text-left " <> order]} - - --- | Every RUM card is the shared 'Components.panel_' flush-card variant. -rumPanel_ :: Text -> Text -> Maybe (Text, Text) -> Html () -> Html () -rumPanel_ title subtitle action = Components.panel_ Components.FlushCard def{Components.subtitle = Just subtitle, Components.action = action} title - - -sessionIdentity :: RumSession -> Text -sessionIdentity session = fromMaybe session.id $ session.userName <|> session.userEmail <|> session.userId - - --- | A recording whose session id never appeared on a span: it has a replay and nothing else. -replayOnly :: RumSession -> Bool -replayOnly session = session.hasReplay && session.events == 0 - - -formatSessionDuration :: RumSession -> Text -formatSessionDuration session - | seconds < 1 = "<1s" - | seconds < 60 = show (round seconds :: Int) <> "s" - | seconds < 3600 = show (floor (seconds / 60) :: Int) <> "m " <> show (round (seconds `mod'` 60) :: Int) <> "s" - | otherwise = show (floor (seconds / 3600) :: Int) <> "h " <> show (floor ((seconds `mod'` 3600) / 60) :: Int) <> "m" - where - seconds = realToFrac (diffUTCTime session.endedAt session.startedAt) :: Double - - --- | A session counts as live while its newest event is fresher than the ingest lag. -isActive :: UTCTime -> RumSession -> Bool -isActive now session = diffUTCTime now session.endedAt < 300 - - --- | Deterministic hue for one identity, so a user's avatar keeps its colour across renders. --- A curated list rather than hash-mod-360: arbitrary hues include the muddy ones. --- --- >>> identityHue "ada@example.com" == identityHue "ada@example.com" --- True -identityHue :: Text -> Int -identityHue ident = hues V.! (T.foldl' (\acc c -> acc * 31 + fromEnum c) 7 ident `mod` V.length hues) - where - hues = V.fromList [261, 205, 162, 120, 69, 21, 350, 300] - - --- | Up to two letters for the avatar: the initials of a name, else the identity's first --- letters. --- --- >>> sessionMonogram' (Just "Ada Lovelace") "x" --- "AL" --- >>> sessionMonogram' Nothing "ada@example.com" --- "AD" -sessionMonogram' :: Maybe Text -> Text -> Text -sessionMonogram' (Just name) _ - | (w1 : w2 : _) <- words name = T.toUpper $ T.take 1 w1 <> T.take 1 w2 -sessionMonogram' _ ident = T.toUpper $ T.take 2 $ T.filter isLetter ident - - --- | Coloured monogram avatar for the session's identity. Anonymous sessions (no name, --- email or id attribute — identity falls back to the session UUID) get a neutral user --- glyph rather than two hex letters pretending to be initials. -sessionAvatar_ :: RumSession -> Html () -sessionAvatar_ session - | anonymous = span_ [class_ "flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-fillWeak text-textWeak", Aria.hidden_ "true"] $ faSprite_ "user" "regular" "h-3.5 w-3.5" - | otherwise = - span_ [class_ "rum-avatar flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-semibold", style_ $ "--hue:" <> show (identityHue ident), Aria.hidden_ "true"] - $ toHtml - $ sessionMonogram' session.userName ident - where - ident = sessionIdentity session - anonymous = ident == session.id - - --- | One coloured letter per browser family, fixed per family so the colour itself becomes --- the recognition cue across rows. -browserHue :: Text -> Int -browserHue = fromMaybe 261 . (`lookup` [("Chrome", 230), ("Safari", 205), ("Firefox", 340), ("Edge", 195), ("Opera", 330), ("Samsung Internet", 280)]) - - -envChip_ :: Text -> Html () -envChip_ browser = span_ [class_ "rum-chip flex h-4 w-4 shrink-0 items-center justify-center rounded text-2xs font-bold", style_ $ "--hue:" <> show (browserHue browser), title_ browser] $ toHtml $ T.take 1 browser - - -deviceIcon :: Text -> Text -deviceIcon = \case - "Mobile" -> "mobile" - "Tablet" -> "mobile" - _ -> "laptop" - - -formatVital :: Vital -> Text -formatVital vital = case vital.measurement of - Unmeasured -> "No data" - Unavailable _ _ -> "Unavailable" - Measured _ estimate -> (if isJust estimate.bounds then "≈ " else "") <> formatVitalThreshold vital estimate.value - - -measurementNote :: Vital -> Text -measurementNote vital = case vital.measurement of - Unmeasured -> "No observations" - Measured _ estimate -> maybe "Exact quantile" (\(lower, upper) -> "Estimated within " <> formatVitalThreshold vital lower <> "–" <> formatVitalThreshold vital upper) estimate.bounds - -- Each note names the export defect and its fix (SDK, collector, or time range). - Unavailable _ issue -> case issue of - RUM.MissingBaseline -> "Cumulative histogram with no earlier export in range; widen the range" - RUM.UnknownStart -> "Cumulative histogram exported without a start time; use delta temporality" - RUM.UnknownTemporality -> "Histogram exported without an aggregation temporality" - RUM.UnsupportedPopulation -> "Unsupported population" - RUM.InvalidValue -> "Observation is negative or infinite" - RUM.InvalidBuckets -> "Histogram bucket counts do not match its bounds" - RUM.InvalidReset -> "Cumulative count went backwards without a new interval" - RUM.OverlappingIntervals -> "Report intervals overlap; the exporter is double-counting" - RUM.UnboundedBucket -> "P75 falls in the histogram's open top bucket; add a higher bound" - RUM.InterruptedSeries -> "Series restarted mid-range without a baseline" - - -observationLabel :: VitalMeasurement -> Text -observationLabel measurement = - countNoun (RUM.measurementSamples measurement) $ case measurement of - Unavailable{} -> "known observation" - _ -> "observation" - - -formatVitalThreshold :: Vital -> Double -> Text -formatVitalThreshold vital value - | vital.unit == "ms" = getDurationNSMS $ round $ value * 1e6 - | otherwise = showFFloat' 3 value - - -data RatingStyle = RatingStyle {label :: Text, textClass :: Text, fillClass :: Text, tone :: Components.BadgeColor} - - --- | A rated number carries its rating as a dot and as text, never as colour alone. -ratedValue_ :: RatingStyle -> Text -> Html () -> Html () -ratedValue_ style title value = span_ [class_ $ "inline-flex items-center gap-1.5 font-medium tabular-nums " <> style.textClass, title_ title] do - span_ [class_ $ "h-2 w-2 shrink-0 rounded-full " <> style.fillClass, Aria.hidden_ "true"] "" - span_ [class_ "sr-only"] $ toHtml $ style.label <> ": " - value - - -ratingStyle :: VitalRating -> RatingStyle -ratingStyle = \case - Good -> RatingStyle "Good" "text-textSuccess" "bg-fillSuccess-strong" Components.SuccessBadge - NeedsImprovement -> RatingStyle "Needs improvement" "text-textWarning" "bg-fillWarning-strong" Components.WarningBadge - Poor -> RatingStyle "Poor" "text-textError" "bg-fillError-strong" Components.ErrorBadge - Unknown -> RatingStyle "Not assessed" "text-textWeak" "bg-fillNeutral-strong" Components.NeutralBadge - - --- | The KQL counterparts of 'browserScope' and 'pageViewPredicate'. A link that filtered on --- @telemetry.sdk.language == "webjs"@ sent the user to an Explorer view of nothing, because no --- browser SDK in production sets it — the same mistake the queries themselves made. -browserKql :: Text -browserKql = "(resource.telemetry.sdk.language == \"webjs\" or resource.user_agent.original != \"\" or name in (\"documentLoad\", \"documentFetch\") or name startswith \"Pageview \")" - - --- | The KQL twin of 'pageViewPredicate'. -pageViewKql :: Text -pageViewKql = "(name == \"documentLoad\" or name startswith \"Pageview \")" - - --- | A first-stage KQL filter carrying the page's investigation boundary. The scope has to --- land before any pipe — or a piped query would append it to the summarize — and must retain --- both the selected environment and service when the reader opens the Explorer. -scopedKql :: RumLinks -> Text -> Text -scopedKql links = applyScopedKqlContext links.queryScope - - --- | A RUM URL carrying the scope the page is under. 'TimePicker.windowUrl' URI-encodes each --- value, so nothing here may encode first: a pre-encoded KQL query arrives at the Log --- Explorer double-escaped (@%2520@ for a space) and parses as one meaningless token. -rumUrl :: RumLinks -> [(Text, Text)] -> Text -rumUrl links extras = - TimePicker.windowUrl - ("/p/" <> links.queryScope.projectId.toText <> "/rum") - ( extras - <> [("environment", environment) | environment <- maybeToList links.queryScope.environment] - <> [("service_scope", service) | service <- maybeToList links.queryScope.service] - ) - links.window - - --- | Log Explorer link for a browser query. The service scope is appended to the KQL rather --- than passed alongside it, so what the Explorer lists is what the panel counted. -logsUrl :: RumLinks -> Text -> Text -logsUrl links query = - TimePicker.windowUrl - ("/p/" <> links.queryScope.projectId.toText <> "/log_explorer") - [("query", scopedKql links query)] - links.window - - --- | Log Explorer link for one session's correlated events. -sessionLogsUrl :: RumLinks -> Text -> Text -sessionLogsUrl links sid = logsUrl links $ "attributes.session.id == " <> kqlQuoted sid - - -sessionsUrl :: RumLinks -> Maybe Text -> SessionFilter -> Maybe Text -> Text -sessionsUrl links query sessionFilter sessionM = - rumUrl links - $ ("tab", "sessions") - : [(key, value) | (key, Just value) <- [("q", query), ("filter", sessionFilterParam sessionFilter), ("session", sessionM)]] - - -degradedBanner_ :: RumData -> RumPanel -> Html () -degradedBanner_ page panel = div_ [role_ "alert", class_ "flex items-start gap-2 border-b border-strokeWarning-strong bg-fillWarning-weak px-4 py-2.5 text-sm text-textStrong"] do - faSprite_ "triangle-exclamation" "solid" "mt-0.5 h-4 w-4 shrink-0 text-iconWarning" - div_ do - strong_ "Some RUM data could not be loaded." - span_ [class_ "ml-1 text-textWeak"] $ toHtml $ "Retry or narrow the time range. Unavailable: " <> T.intercalate ", " (map rumQueryLabel page.degradedPanels) <> "." - button_ ([type_ "button", class_ "btn btn-sm shrink-0"] <> panelSwapAttrs page panel True "click" (Just "replace")) "Retry" - - --- | The panel a degraded query blanks; the inverse of @panelQueries@. -queryPanel :: RumQuery -> RumPanel -queryPanel = \case - PulseQuery -> PanelPulse - PagesQuery -> PanelPages - ErrorsQuery -> PanelErrors - SessionSearchQuery{} -> PanelSessions - SessionDetailQuery{} -> PanelSessionDetail - VitalPopulationQuery{} -> PanelVitals - BreakdownQuery -> PanelAudience - - -rumQueryLabel :: RumQuery -> Text -rumQueryLabel = \case - PulseQuery -> "experience" - PagesQuery -> "pages" - ErrorsQuery -> "errors" - SessionSearchQuery{} -> "sessions" - SessionDetailQuery{} -> "session" - VitalPopulationQuery{} -> "web vitals" - BreakdownQuery -> "audience" diff --git a/src/Pkg/Components/TimePicker.hs b/src/Pkg/Components/TimePicker.hs index ae01bf9d0..ef4c27653 100644 --- a/src/Pkg/Components/TimePicker.hs +++ b/src/Pkg/Components/TimePicker.hs @@ -441,7 +441,7 @@ data TimeWindow = TimeWindow } --- | The default range for 'mkTimeWindow' surfaces (infrastructure, RUM), which +-- | The default range for 'mkTimeWindow' surfaces (infrastructure), which -- refresh live and so open on a tighter window than 'defaultSince'. defaultWindow :: Text defaultWindow = "5M" diff --git a/src/Pkg/Components/Widget.hs b/src/Pkg/Components/Widget.hs index 91d173b76..3faa8d15a 100644 --- a/src/Pkg/Components/Widget.hs +++ b/src/Pkg/Components/Widget.hs @@ -38,8 +38,9 @@ import Models.Projects.Projects qualified as Projects import NeatInterpolation import Pages.Charts.Charts qualified as Charts import Pages.Components (copyButton_, headerRow_) +import Pkg.Components.TimePicker qualified as TimePicker import Pkg.DeriveUtils (JsonValueSchema (..), WrappedEnumSC (..)) -import Pkg.Parser (ToQueryText (..), parseQueryToAST) +import Pkg.Parser (ToQueryText (..), parseQueryToAST, replacePlaceholders) import Pkg.Parser.Expr (Subject (..)) import Pkg.Parser.Stats (BinFunction (..), ByClauseItem (..), Section (..), SummarizeByClause (..)) import Pkg.QueryCache qualified as QC @@ -345,7 +346,6 @@ data WidgetDataset = WidgetDataset { source :: AE.Value , rowsPerMin :: Maybe Double , value :: Maybe Double - , servedValue :: Maybe Double -- Stand-in shown until a timeseries stat's own stats arrive , from :: Maybe Int , to :: Maybe Int , stats :: Maybe Charts.MetricsStats @@ -413,7 +413,6 @@ toWidgetDataset md = { source = AE.toJSON $ V.cons (AE.toJSON <$> md.headers) (AE.toJSON <<$>> md.dataset) , rowsPerMin = md.rowsPerMin , value = Just md.rowsCount - , servedValue = Nothing , from = md.from , to = md.to , stats = md.stats @@ -444,6 +443,9 @@ data TableColumn = TableColumn , progress :: Maybe ProgressScale , progressVariant :: Maybe Text -- "default", "info", "error", etc. , columnType :: Maybe ColumnType -- default CTText + , hidden :: Maybe Bool -- Carried for links (@{{row.}}@) but not rendered + , description :: Maybe Text -- Header tooltip, e.g. what an abbreviation stands for + , tooltip :: Maybe Text -- Cell tooltip; a template over @{{row.}}@ } deriving stock (Generic, Show, THS.Lift) deriving anyclass (Default, FromForm, NFData) @@ -568,7 +570,7 @@ widget_ w' = case w.wType of div_ (class_ "grid-stack grid-stack-preloaded nested-grid flex-1 group-has-[.wgt-collapse:checked]/wgt:hidden" : gridStackAttrs normalizedChildren) $ forM_ normalizedChildren (\wChild -> widget_ (wChild{_isNested = Just True})) WTTable -> wgtCard_ $ renderTable w WTLogs -> wgtCard_ $ renderLogsWidget w - WTServiceMap -> wgtCard_ $ withCardFrame True w ((\c -> (c.title, c.url)) <$> w.cta) $ div_ [class_ "h-full overflow-auto p-3"] $ whenJust w.html toHtmlRaw + WTServiceMap -> wgtCard_ $ withCardFrame True w (ctaAction w) $ div_ [class_ "h-full overflow-auto p-3"] $ whenJust w.html toHtmlRaw WTFlamegraph -> gridItem_ $ div_ [class_ "h-full "] $ div_ [class_ "p-3"] "Flamegraph widget coming soon" _ -> gridItem_ $ div_ [class_ " w-full h-full group/wgt "] $ renderChart w where @@ -1082,6 +1084,11 @@ withCardFrame flexCol widget extraAction body = do body +-- | A template's card link, with its project placeholder resolved. +ctaAction :: Widget -> Maybe (Text, Text) +ctaAction w = (\c -> (c.title, replacePlaceholders (one ("project_id", projectIdText w)) c.url)) <$> w.cta + + renderLogsWidget :: Widget -> Html () renderLogsWidget widget = do let wId = maybeToMonoid widget.id @@ -1145,13 +1152,15 @@ sortableTableHead_ :: Widget -> Maybe Text -> Html () sortableTableHead_ widget selected = thead_ [class_ "sticky top-0 z-10 before:content-[''] before:absolute before:left-0 before:right-0 before:bottom-0 before:h-px before:bg-strokeWeak"] $ tr_ [] - $ forM_ (fold widget.columns) \col -> do + $ forM_ (filter (not . or . (.hidden)) $ fold widget.columns) \col -> do let (direction, ariaSort, glyph) | selected == Just ("+" <> col.field) = ("asc", "ascending", "↑") | selected == Just ("-" <> col.field) = ("desc", "descending", "↓") | otherwise = ("none", "none", "↕") :: (Text, Text, Text) sortable = sortableColumn widget col - th_ [class_ $ "text-left bg-bgRaised sticky top-0 " <> fromMaybe "" col.align, term "aria-sort" ariaSort] + -- A dotted underline marks a header that explains itself on hover. + title = span_ [class_ "underline decoration-dotted decoration-strokeStrong underline-offset-4" | isJust col.description] $ toHtml col.title + th_ ([class_ $ "text-left bg-bgRaised sticky top-0 " <> fromMaybe "" col.align, term "aria-sort" ariaSort] <> foldMap (\d -> [term "data-tippy-content" d, term "aria-description" d]) col.description) $ if sortable then button_ [ type_ "button" @@ -1168,16 +1177,16 @@ sortableTableHead_ widget selected = |] ] $ headerRow_ [] do - toHtml col.title + title span_ [class_ "sort-arrow ml-1 text-iconNeutral"] $ toHtml glyph - else headerRow_ [] $ toHtml col.title + else headerRow_ [] title renderTable :: Widget -> Html () renderTable widget = do let tableId = maybeToMonoid widget.id eagerWidget = widget & #eager ?~ True & #pngUrl .~ Nothing & #html .~ Nothing & #dataset .~ Nothing - withCardFrame True widget Nothing + withCardFrame True widget (ctaAction widget) $ div_ [ class_ "h-full overflow-auto p-3" , hxGet_ $ widgetFetchUrl eagerWidget @@ -1200,7 +1209,7 @@ renderStatContent :: Widget -> Maybe Text -> Html () renderStatContent widget valueM = do let chartId = maybeToMonoid widget.id statContentId = chartId <> "_stat" - hasData = isTrue widget.eager || isJust (widget.dataset >>= \d -> d.value <|> d.servedValue) + hasData = isTrue widget.eager || isJust (widget.dataset >>= (.value)) div_ [ id_ statContentId , class_ $ "stat-widget px-3 flex flex-col " <> bool "py-3 " "py-2 " (isTrue widget._isNested) @@ -1225,7 +1234,7 @@ renderChart widget = do let rateM = widget.dataset >>= (.rowsPerMin) <&> \r -> Utils.prettyPrintCount (round r) <> "/min" chartId = maybeToMonoid widget.id isTimeseriesStat = widget.wType == WTTimeseriesStat - fallback = widget.dataset >>= (\d -> d.servedValue <|> d.value) <&> \value -> formatStatValue value $ fromMaybe "" widget.unit + fallback = widget.dataset >>= (.value) <&> \value -> formatStatValue value $ fromMaybe "" widget.unit valueM = ( do guard isTimeseriesStat @@ -1587,7 +1596,10 @@ renderTableWithDataAndParams :: Widget -> V.Vector (V.Vector Text) -> [(Text, Ma renderTableWithDataAndParams widget dataRows params = do let columns = fromMaybe [] widget.columns tableId = maybeToMonoid widget.id + param k = join $ lookup k params currentVar = widget.onRowClick >>= (.setVariable) >>= \var -> find ((== "var-" <> var) . fst) params >>= snd + -- URL-encoded link substitutions; links into other pages keep the window the table was read over. + linkSubs = M.fromList [("project_id", projectIdText widget), ("time_range", TimePicker.rangeQuery $ TimePicker.TimePicker (param "since") (param "from") (param "to"))] -- Rows navigate server-side to the @navigate_to_tab@ tab, else the widget's own tab -- (or the whole tabless dashboard), with the row's variable set. rowNavAttrs value = fold do @@ -1615,7 +1627,9 @@ renderTableWithDataAndParams widget dataRows params = do ] V.forM_ dataRows \row -> do let firstColValue = memptyIfFalse (not $ null columns) (getRowValue 0 row) - rowValue = maybe firstColValue (\tpl -> foldl' (\t (col, idx) -> T.replace ("{{row." <> col.field <> "}}") (getRowValue idx row) t) tpl (zip columns [0 ..])) (widget.onRowClick >>= (.value)) + rowSubs = M.fromList [("row." <> c.field, getRowValue i row) | (c, i) <- zip columns [0 ..]] + rowValue = maybe firstColValue (replacePlaceholders rowSubs) (widget.onRowClick >>= (.value)) + cellLinkSubs = linkSubs <> fmap toUriStr rowSubs isCurrent = Just rowValue == currentVar tr_ ( [class_ $ "hover" <> memptyIfFalse (isJust widget.onRowClick) " cursor-pointer" <> memptyIfFalse isCurrent " bg-fillBrand-weak font-semibold"] @@ -1623,10 +1637,11 @@ renderTableWithDataAndParams widget dataRows params = do <> rowNavAttrs rowValue ) $ ifor_ columns \idx col -> - td_ [class_ $ cellClass col] + unless (or col.hidden) + $ td_ ([class_ $ cellClass col] <> foldMap (\t -> let tip = replacePlaceholders rowSubs t in [term "data-tippy-content" tip, term "aria-description" tip]) col.tooltip) $ if isJust col.progress then renderProgressCell col (getRowValue idx row) maxValues valueWidths - else renderLongTextOr widget col (getRowValue idx row) + else renderLongTextOr widget cellLinkSubs col (getRowValue idx row) getRowValue :: Int -> V.Vector Text -> Text @@ -1716,8 +1731,8 @@ formatTimestampValue (T.strip -> val) -- Long values get a truncated single-line view with a tippy tooltip (delegated -- body-wide in BodyWrapper) showing the full text on hover. Number/duration -- columns skip the wrapper since they're always short. -renderLongTextOr :: Widget -> TableColumn -> Text -> Html () -renderLongTextOr widget col value +renderLongTextOr :: Widget -> M.Map Text Text -> TableColumn -> Text -> Html () +renderLongTextOr widget linkSubs col value | or col.copyable = div_ [class_ "group flex items-center gap-1 min-w-0"] do shown copyButton_ "btn btn-xs btn-ghost shrink-0 opacity-0 group-hover:opacity-100 focus:opacity-100" "w-3 h-3" "my @data-copy" [data_ "copy" value] @@ -1729,8 +1744,4 @@ renderLongTextOr widget col value formatted = formatColumnValue col value content = if T.isInfixOf "⇒" formatted then renderSummaryTags formatted else toHtml formatted cell = maybe content (\template -> a_ [href_ $ tableLink template, class_ "text-textBrand hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-strokeBrand-strong rounded-sm"] content) col.link - -- Link values are data, not markup. URL-encode the cell substitution before it - -- reaches the href, while project ids are UUIDs controlled by the server. - tableLink template = - T.replace "{{project_id}}" (projectIdText widget) - $ T.replace ("{{row." <> col.field <> "}}") (toUriStr value) template + tableLink = replacePlaceholders linkSubs diff --git a/src/Pkg/Parser.hs b/src/Pkg/Parser.hs index a2ff3b35a..d70cc0616 100644 --- a/src/Pkg/Parser.hs +++ b/src/Pkg/Parser.hs @@ -1,5 +1,5 @@ -- Parser implemented with help and code from: https://markkarpov.com/tutorial/megaparsec.html -module Pkg.Parser (queryASTToComponents, parseQueryToComponents, getProcessedColumns, fixedUTCTime, parseQuery, sectionsToComponents, defSqlQueryCfg, defPid, PageDirection (..), PageCursor (..), ScopedQuery (..), mkScopedQuery, applyScopedQuery, applyScopedKqlContext, SqlQueryCfg (..), RangeEnd (..), QueryComponents (..), buildDateRange, buildGroupBy, buildOrderBy, buildLimit, buildWhereCondition, buildEnvFilter, buildServiceFilter, listToColNames, colsNoAsClause, defaultSelectSqlQuery, pSource, parseQueryToAST, ToQueryText (..), calculateAutoBinWidth, autoBinWidth, BinDensity (..), binDensityFor, replacePlaceholders, variablePresets, variablePresetsKQL, constantToSQLList, constantToKQLList, defaultQueryLimit, intervalSeconds) where +module Pkg.Parser (queryASTToComponents, parseQueryToComponents, getProcessedColumns, fixedUTCTime, parseQuery, sectionsToComponents, defSqlQueryCfg, defPid, PageDirection (..), PageCursor (..), ScopedQuery (..), mkScopedQuery, applyScopedQuery, applyScopedKqlContext, SqlQueryCfg (..), RangeEnd (..), QueryComponents (..), buildDateRange, buildGroupBy, buildOrderBy, buildLimit, buildWhereCondition, buildEnvFilter, buildServiceFilter, listToColNames, colsNoAsClause, defaultSelectSqlQuery, pSource, parseQueryToAST, ToQueryText (..), calculateAutoBinWidth, autoBinWidth, BinDensity (..), binDensityFor, replacePlaceholders, fillQueryTemplate, browserKql, variablePresets, variablePresetsKQL, constantToSQLList, constantToKQLList, defaultQueryLimit, intervalSeconds) where import Control.Error (hush) import Data.Char (isAlphaNum) @@ -932,6 +932,34 @@ replacePlaceholders :: Map.Map Text Text -> Text -> Text replacePlaceholders mappng txt = Map.foldlWithKey' (\t k v -> T.replace ("{{" <> k <> "}}") v t) txt mappng +-- | Fill a dashboard query template. A @{{var-…}}@ the request did not set reads as empty, so +-- @'{{var-x}}' = ''@ means "unfiltered". Unset variables are cleared from the template before +-- substitution, so a substituted value is never rewritten. +-- +-- >>> fillQueryTemplate (Map.fromList [("var-a", "x")]) "'{{var-a}}' '{{var-b}}' {{var-" +-- "'x' '' {{var-" +-- >>> fillQueryTemplate (Map.fromList [("row", "{{var-z}}")]) "{{row}} {{var-y}}" +-- "{{var-z}} " +fillQueryTemplate :: Map.Map Text Text -> Text -> Text +fillQueryTemplate mappng = replacePlaceholders mappng . clearUnset + where + clearUnset t = case T.breakOn "{{var-" t of + (before, rest) | (key, close) <- T.breakOn "}}" (T.drop 2 rest), not (T.null close) -> before <> bool "" ("{{" <> key <> "}}") (Map.member key mappng) <> clearUnset (T.drop 2 close) + _ -> t + + +-- | Real User Monitoring's predicates, as dashboard placeholders. Laddered, because no single +-- marker covers browser telemetry: the OpenTelemetry browser SDKs leave telemetry.sdk.language +-- unset. TimeFusion's @rum_*@ rollup measures declare these strings verbatim and serve a widget +-- only while its filter matches exactly, so an edit here must be mirrored in TimeFusion's +-- @schemas/otel_logs_and_spans.yaml@. +browserSql, pageViewSql, errorSql, browserKql :: Text +browserSql = "(resource___telemetry___sdk___language IN ('webjs', 'javascript', 'js') OR resource___user_agent___original IS NOT NULL OR name IN ('documentLoad', 'documentFetch') OR " <> pageViewSql <> ")" +pageViewSql = "(name LIKE 'Pageview %' OR name = 'documentLoad')" +errorSql = "(status_code = 'ERROR' OR lower(COALESCE(level, '')) = 'error' OR attributes___exception___type IS NOT NULL)" +browserKql = "(resource.telemetry.sdk.language in (\"webjs\", \"javascript\", \"js\") or resource.user_agent.original != null or name in (\"documentLoad\", \"documentFetch\") or name startswith \"Pageview \")" + + variablePresets :: BinDensity -> Text -> Maybe UTCTime -> Maybe UTCTime -> [(Text, Maybe Text)] -> UTCTime -> Map.Map Text Text variablePresets density pid mf mt allParams currentTime = let fmtUTC = maybe "" formatUTC @@ -947,6 +975,10 @@ variablePresets density pid mf mt allParams currentTime = , ("time_filter", clause "timestamp") , ("time_filter_sql_created_at", clause "created_at") , ("rollup_interval", calculateAutoBinWidth density (mf, mt) currentTime) + , ("browser_filter", browserSql) + , ("pageview_filter", pageViewSql) + , ("error_filter", errorSql) + , ("browser_kql", browserKql) ] <> (allParams <&> second maybeToMonoid) diff --git a/src/Pkg/QueryCache.hs b/src/Pkg/QueryCache.hs index d991d3a82..7c8ac963c 100644 --- a/src/Pkg/QueryCache.hs +++ b/src/Pkg/QueryCache.hs @@ -8,6 +8,7 @@ module Pkg.QueryCache ( QueryFlights, newQueryFlights, coalesceQuery, + withSharedCache, cachedRawQuery, lookupRawCache, updateRawCache, @@ -54,7 +55,7 @@ import Hasql.Interpolate qualified as HI import Models.Projects.Projects qualified as Projects import OpenTelemetry.Attributes qualified as OA import Pages.Charts.Types (DataType, MetricsData (..), MetricsStats (..)) -import Pkg.DeriveUtils (AesonText (..), DB) +import Pkg.DeriveUtils (AesonText (..), DB, unAesonText) import Pkg.Metrics qualified as Metrics import Pkg.Parser (RangeEnd (..), SqlQueryCfg (..), autoBinWidth, fixedUTCTime, intervalSeconds) import Pkg.Parser.Expr (ToQueryText (..), display, kqlTimespanToTimeBucket, resolveWildcardTimes) @@ -543,3 +544,21 @@ cleanupExpiredCache = do ) SELECT COUNT(*)::bigint FROM deleted |] + + +-- | Fleet-wide L2 behind a per-replica memory cache (its table keeps the RUM page's historical name): read the shared table, else compute and +-- publish. @rawKey@ is hashed, so callers pass a readable @show@n key. Expired rows are pruned +-- on write, which is rare enough (one per cold key per TTL) to need no cleanup job. +withSharedCache :: (AE.FromJSON a, AE.ToJSON a, DB es) => Text -> Int64 -> Eff es a -> Eff es a +withSharedCache rawKey ttl compute = + Hasql.interpOne [HI.sql|SELECT payload FROM rum_panel_cache WHERE cache_key = #{key} AND expires_at > now()|] >>= maybe publish (pure . unAesonText . HI.getOneColumn) + where + key = toXXHash rawKey + publish = do + fresh <- compute + Hasql.interpExecute_ + [HI.sql|INSERT INTO rum_panel_cache (cache_key, payload, expires_at) + VALUES (#{key}, #{AesonText fresh}, now() + make_interval(secs => #{ttl}::double precision)) + ON CONFLICT (cache_key) DO UPDATE SET payload = EXCLUDED.payload, expires_at = EXCLUDED.expires_at|] + Hasql.interpExecute_ [HI.sql|DELETE FROM rum_panel_cache WHERE expires_at < now() - interval '12 hours'|] + pure fresh diff --git a/src/Pkg/TestUtils.hs b/src/Pkg/TestUtils.hs index 728c1c683..b24376096 100644 --- a/src/Pkg/TestUtils.hs +++ b/src/Pkg/TestUtils.hs @@ -823,8 +823,6 @@ withTestResources f = withSetup $ \pool cstr -> withSharedLogger \logger -> do endpointStatsCache <- newCache (Just $ TimeSpec 300 0) rawQueryFlights <- QueryCache.newQueryFlights infrastructureCache <- newCache (Just $ TimeSpec 15 0) - rumCache <- newCache (Just $ TimeSpec 15 0) - rumQueryFlights <- QueryCache.newQueryFlights codeBlobCache <- newCache (Just $ TimeSpec (15 * 60) 0) repoListCache <- newCache (Just $ TimeSpec (10 * 60) 0) tp <- getGlobalTracerProvider @@ -903,8 +901,6 @@ withTestResources f = withSetup $ \pool cstr -> withSharedLogger \logger -> do endpointStatsCache rawQueryFlights infrastructureCache - rumCache - rumQueryFlights codeBlobCache repoListCache projectKeyCache diff --git a/src/System/Config.hs b/src/System/Config.hs index decbc8e96..8185171f1 100644 --- a/src/System/Config.hs +++ b/src/System/Config.hs @@ -25,7 +25,6 @@ import Log (LogLevel (..), readLogLevelEither, showLogLevel) import Models.Apis.Endpoints qualified as Endpoints import Models.Projects.Projects qualified as Projects import Models.Telemetry.ContainerTypes qualified as Containers -import Models.Telemetry.RUM qualified as RUM import Models.Telemetry.Telemetry qualified as Telemetry import Network.HTTP.Client qualified as HC import Network.HTTP.Client.TLS qualified as HCTLS @@ -435,10 +434,6 @@ data AuthContext = AuthContext -- Completed results live in PostgreSQL's query_cache and are shared by replicas. , infrastructureCache :: Cache Containers.ContainerSnapshotKey (V.Vector Containers.ContainerRow) -- ^ One expensive metrics pivot feeds every infrastructure tab and detail drawer. - , rumCache :: Cache RUM.RumCacheKey RUM.RumQueryResult - -- ^ Briefly reuses RUM panel reads across tab navigation and preloaded requests. - , rumQueryFlights :: QueryCache.QueryFlights (RUM.RumCacheKey, Bool) (Either RUM.RumQuery (RUM.RumQueryResult, Bool)) - -- ^ Shares panel requests within a replica; stale reads and forced refreshes remain separate. , codeBlobCache :: Cache CodeBlobKey ByteString -- ^ Source blobs for stack-trace code context, keyed @(owner, repo, ref, path)@. One git-host -- API call per frame opened otherwise, and a hot issue viewed repeatedly re-fetches every @@ -557,11 +552,6 @@ configToEnv config = do endpointStatsCache <- liftIO $ newCache (Just $ TimeSpec 300 0) rawQueryFlights <- liftIO QueryCache.newQueryFlights infrastructureCache <- liftIO $ newCache (Just $ TimeSpec 15 0) - -- 15s was shorter than the queries it caches: a RUM panel set takes ~28s over a 24h - -- window, so every entry expired before the next request could reach it and the cache - -- never hit. Matches the other telemetry stat caches above. - rumCache <- liftIO $ newCache (Just $ TimeSpec 300 0) - rumQueryFlights <- liftIO QueryCache.newQueryFlights -- 15 min: a mutable ref (a branch name) must not pin a stale blob for long, and the value -- here is collapsing the burst of frames opened while reading ONE issue, not long-term -- storage. A commit-sha ref is immutable and would tolerate far longer, but the key cannot @@ -624,8 +614,6 @@ configToEnv config = do , endpointStatsCache , rawQueryFlights , infrastructureCache - , rumCache - , rumQueryFlights , codeBlobCache , repoListCache , extractionWorker diff --git a/src/Utils.hs b/src/Utils.hs index dd118e89e..dc67fb1d9 100644 --- a/src/Utils.hs +++ b/src/Utils.hs @@ -1,4 +1,5 @@ module Utils ( + queryStringFrom, classifyUserAgent, sinceWindows, onpointerdown_, @@ -131,6 +132,7 @@ import Lucid.Svg qualified as Svg import Models.Projects.Projects qualified as Projects import NeatInterpolation (text) import Network.HTTP.Types (urlEncode) +import Network.HTTP.Types.URI qualified as URI import Network.URI (escapeURIString, isUnescapedInURI) import Numeric (showFFloat, showHex) import Pkg.Icons qualified as Icons @@ -794,6 +796,16 @@ isDemoAndNotSudo :: Projects.ProjectId -> Bool -> Bool isDemoAndNotSudo pid isSudo = pid == Projects.demoProjectId && not isSudo +-- | Percent-encoded query string, prefixed with @?@ when non-empty. +-- +-- >>> queryStringFrom [("key", Just "a b"), ("empty", Nothing)] +-- "?key=a%20b&empty" +-- >>> queryStringFrom [] +-- "" +queryStringFrom :: [(Text, Maybe Text)] -> Text +queryStringFrom = decodeUtf8 . URI.renderQuery True . map (bimap encodeUtf8 (fmap encodeUtf8)) + + toUriStr :: Text -> Text toUriStr s = decodeUtf8 $ urlEncode True (encodeUtf8 s) diff --git a/src/Web/Routes.hs b/src/Web/Routes.hs index bd4f89439..1b6968462 100644 --- a/src/Web/Routes.hs +++ b/src/Web/Routes.hs @@ -75,7 +75,6 @@ import Pages.Projects qualified as CreateProject import Pages.Projects qualified as Integrations import Pages.Projects qualified as ListProjects import Pages.Projects qualified as ManageMembers -import Pages.RealUserMonitoring qualified as RUM import Pages.Replay qualified as Replay import Pages.Reports qualified as Reports import Pages.ServiceMap qualified as ServiceMap @@ -474,7 +473,7 @@ data CookieProtectedRoutes mode = CookieProtectedRoutes , slackIdentityPost :: mode :- "slack" :> "link" :> Capture "linkId" (UUIDId "slack_link") :> ReqBody '[FormUrlEncoded] Slack.SlackLinkForm :> Post '[HTML] (RespHeaders (Html ())) , slackLinkProjectGet :: mode :- "slack" :> "oauth" :> "callback" :> QPT "code" :> QPT "state" :> LocationRedirect BotUtils.BotResponse , endpointDetailsRedirect :: mode :- "p" :> ProjectId :> "endpoints" :> "details" :> AllQueryParams :> LocationRedirect NoContent - , rumDashboardRedirect :: mode :- "p" :> ProjectId :> "rum" :> "dashboard" :> AllQueryParams :> LocationRedirect NoContent + , rumRedirect :: mode :- "p" :> ProjectId :> "rum" :> CaptureAll "view" Text :> AllQueryParams :> LocationRedirect NoContent , dashboardNewGet :: mode :- "p" :> ProjectId :> "dashboards" :> "new" :> Get '[HTML] (RespHeaders Dashboards.DashboardNew) , dashboardsGet :: mode :- "p" :> ProjectId :> "dashboards" :> Capture "dashboard_id" Dashboards.DashboardId :> QPT "file" :> QPT "from" :> QPT "to" :> QPT "since" :> HXRequest :> AllQueryParams :> Get '[HTML] (RespHeaders (PageCtx Dashboards.DashboardGet)) , dashboardsGetList :: mode :- "p" :> ProjectId :> "dashboards" :> QPT "sort" :> QPT "embedded" :> QueryParam "teamId" ApiT.TeamId :> QPT "copy_widget_id" :> QueryParam "source_dashboard_id" Dashboards.DashboardId :> QPT "new" :> RecordParam KeepPrefixExp Dashboards.DashboardFilters :> Get '[HTML] (RespHeaders Dashboards.DashboardsGet) @@ -692,7 +691,6 @@ type TelemetryRoutes = NamedRoutes TelemetryRoutes' type TelemetryRoutes' :: Type -> Type data TelemetryRoutes' mode = TelemetryRoutes' { tracesGet :: mode :- "traces" :> Capture "trace_id" Text :> QPU "timestamp" :> QPT "span_id" :> QPT "nav" :> QPT "embed" :> QueryParam "spans" Int :> Get '[HTML] (RespHeaders Trace.TraceDetailsGet) - , rumGetH :: mode :- "rum" :> QPT "tab" :> QPT "q" :> QPT "filter" :> QPT "from" :> QPT "to" :> QPT "since" :> QPT "session" :> QPT "service" :> QPT "panel" :> QPT "deferred" :> QPT "refresh" :> QPT "environment" :> Get '[HTML] (RespHeaders RUM.RumGet) , metricsOVGetH :: mode :- "metrics" :> QPT "tab" :> QPT "from" :> QPT "to" :> QPT "since" :> QPT "metric_source" :> QPT "metric_prefix" :> QPI "cursor" :> QPT "expand" :> QPT "label" :> QPT "q" :> QueryParam "append" Bool :> Get '[HTML] (RespHeaders Metrics.MetricsOverViewGet) , dataPointCountsGetH :: mode :- "metrics" :> "datapoints" :> "counts" :> QPT "from" :> QPT "to" :> QPT "since" :> Get '[HTML] (RespHeaders (Html ())) , metricDetailsGetH :: mode :- "metrics" :> "details" :> Capture "metric_name" Text :> QPT "from" :> QPT "to" :> QPT "since" :> QPT "metric_source" :> QPT "label" :> Get '[HTML] (RespHeaders (Html ())) @@ -978,7 +976,7 @@ cookieProtectedServer = , slackIdentityPost = Slack.linkIdentityPostH , slackLinkProjectGet = Slack.linkProjectGetH , endpointDetailsRedirect = Dashboards.entrypointRedirectGetH "endpoint-stats.yaml" "Endpoint Analytics" ["endpoints", "http", "events"] - , rumDashboardRedirect = Dashboards.entrypointRedirectGetH "rum.yaml" "Real User Monitoring" ["rum", "browser", "frontend", "web-vitals"] + , rumRedirect = Dashboards.rumRedirectH , dashboardsGet = Dashboards.dashboardGetH , dashboardNewGet = Dashboards.dashboardNewGetH , dashboardsGetList = Dashboards.dashboardsGetH @@ -1173,7 +1171,6 @@ telemetryServer :: Projects.ProjectId -> Servant.ServerT TelemetryRoutes ATAuthC telemetryServer pid = TelemetryRoutes' { tracesGet = Trace.traceH pid - , rumGetH = RUM.rumGetScopedH pid , metricsOVGetH = Metrics.metricsOverViewGetH pid , dataPointCountsGetH = Metrics.dataPointCountsGetH pid , metricDetailsGetH = Metrics.metricDetailsGetH pid diff --git a/static/public/assets/css/tailwind.css b/static/public/assets/css/tailwind.css index aae902117..b5caafa36 100644 --- a/static/public/assets/css/tailwind.css +++ b/static/public/assets/css/tailwind.css @@ -1141,63 +1141,6 @@ body, :host { --skeleton-highlight: color-mix(in oklch, var(--color-fillBrand-strong) 20%, transparent); } - /* RUM identity + environment markers. The hue arrives inline as --hue (hashed from the - identity, or fixed per browser/OS/device family); the classes only set lightness and - chroma, so light and dark themes share the one declaration. */ - .rum-avatar { - --hue: 261; - background: oklch(0.93 0.05 var(--hue)); - color: oklch(0.45 0.14 var(--hue)); - } - [data-theme="dark"] .rum-avatar { - background: oklch(0.36 0.07 var(--hue)); - color: oklch(0.88 0.09 var(--hue)); - } - - .rum-chip { - --hue: 261; - background: oklch(0.92 0.06 var(--hue)); - color: oklch(0.48 0.15 var(--hue)); - } - [data-theme="dark"] .rum-chip { - background: oklch(0.38 0.08 var(--hue)); - color: oklch(0.86 0.1 var(--hue)); - } - - .rum-bar { - --hue: 261; - background: oklch(0.6 0.14 var(--hue) / 0.65); - } - [data-theme="dark"] .rum-bar { - background: oklch(0.68 0.12 var(--hue) / 0.55); - } - - /* Live-session dot: a solid core with a ping ring, matching the pulse affordance used - elsewhere for live updates. */ - .rum-pulse-dot { - position: relative; - display: inline-block; - width: 0.375rem; - height: 0.375rem; - border-radius: 9999px; - background: var(--color-fillSuccess-strong); - } - .rum-pulse-dot::after { - content: ""; - position: absolute; - inset: 0; - border-radius: 9999px; - background: var(--color-fillSuccess-strong); - animation: rum-ping 2s cubic-bezier(0, 0, 0.2, 1) infinite; - } - @keyframes rum-ping { - 0% { transform: scale(1); opacity: 0.7; } - 75%, 100% { transform: scale(2.6); opacity: 0; } - } - @media (prefers-reduced-motion: reduce) { - .rum-pulse-dot::after { animation: none; } - } - .skeleton-wave { animation-delay: calc(var(--row-index) * 0.1s); } diff --git a/static/public/assets/deps/monoscope/monoscope-0.11.6.min.js b/static/public/assets/deps/monoscope/monoscope-0.13.0.min.js similarity index 82% rename from static/public/assets/deps/monoscope/monoscope-0.11.6.min.js rename to static/public/assets/deps/monoscope/monoscope-0.13.0.min.js index b93053fd0..99a9d737b 100644 --- a/static/public/assets/deps/monoscope/monoscope-0.11.6.min.js +++ b/static/public/assets/deps/monoscope/monoscope-0.13.0.min.js @@ -1,7 +1,7 @@ -var Monoscope=function(){"use strict";var e,t=Object.defineProperty,r=(e,r,n)=>((e,r,n)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n)(e,"symbol"!=typeof r?r+"":r,n),n=Object.defineProperty,s=(e,t,r)=>((e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r),i=Object.defineProperty,o=(e,t,r)=>((e,t,r)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);const a={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},l={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},c={};function u(e){if(c[e])return c[e];const t=globalThis[e],r=t.prototype,n=e in a?a[e]:void 0,s=Boolean(n&&n.every(e=>{var t,n;return Boolean(null==(n=null==(t=Object.getOwnPropertyDescriptor(r,e))?void 0:t.get)?void 0:n.toString().includes("[native code]"))})),i=e in l?l[e]:void 0,o=Boolean(i&&i.every(e=>{var t;return"function"==typeof r[e]&&(null==(t=r[e])?void 0:t.toString().includes("[native code]"))}));if(s&&o&&!globalThis.Zone)return c[e]=t.prototype,t.prototype;try{const n=document.createElement("iframe");document.body.appendChild(n);const s=n.contentWindow;if(!s)return t.prototype;const i=s[e].prototype;return document.body.removeChild(n),i?c[e]=i:r}catch{return r}}const h={};function p(e,t,r){var n;const s=`${e}.${String(r)}`;if(h[s])return h[s].call(t);const i=u(e),o=null==(n=Object.getOwnPropertyDescriptor(i,r))?void 0:n.get;return o?(h[s]=o,o.call(t)):t[r]}const d={};function f(e,t,r){const n=`${e}.${String(r)}`;if(d[n])return d[n].bind(t);const s=u(e)[r];return"function"!=typeof s?t[r]:(d[n]=s,s.bind(t))}const m={childNodes:function(e){return p("Node",e,"childNodes")},parentNode:function(e){return p("Node",e,"parentNode")},parentElement:function(e){return p("Node",e,"parentElement")},textContent:function(e){return p("Node",e,"textContent")},contains:function(e,t){return f("Node",e,"contains")(t)},getRootNode:function(e){return f("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?p("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?p("Element",e,"shadowRoot"):null},querySelector:function(e,t){return p("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return p("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return u("MutationObserver").constructor}};let g=class{constructor(){o(this,"idNodeMap",new Map),o(this,"nodeMetaMap",new WeakMap)}getId(e){var t;if(!e)return-1;return(null==(t=this.getMeta(e))?void 0:t.id)??-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){const t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(e=>this.removeNodeFromMap(e))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){const r=t.id;this.idNodeMap.set(r,e),this.nodeMetaMap.set(e,t)}replace(e,t){const r=this.getNode(e);if(r){const e=this.nodeMetaMap.get(r);e&&this.nodeMetaMap.set(t,e)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}};function y(e,t,r){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return!!r&&y(m.parentNode(e),t,r);for(let r=e.classList.length;r--;){const n=e.classList[r];if(t.test(n))return!0}return!!r&&y(m.parentNode(e),t,r)}function w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function v(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var b={exports:{}},_=String,S=function(){return{isColorSupported:!1,reset:_,bold:_,dim:_,italic:_,underline:_,inverse:_,hidden:_,strikethrough:_,black:_,red:_,green:_,yellow:_,blue:_,magenta:_,cyan:_,white:_,gray:_,bgBlack:_,bgRed:_,bgGreen:_,bgYellow:_,bgBlue:_,bgMagenta:_,bgCyan:_,bgWhite:_}};b.exports=S(),b.exports.createColors=S;var C=b.exports;const E=v(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let T=C,k=E,x=class e extends Error{constructor(t,r,n,s,i,o){super(t),this.name="CssSyntaxError",this.reason=t,i&&(this.file=i),s&&(this.source=s),o&&(this.plugin=o),void 0!==r&&void 0!==n&&("number"==typeof r?(this.line=r,this.column=n):(this.line=r.line,this.column=r.column,this.endLine=n.line,this.endColumn=n.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;null==e&&(e=T.isColorSupported),k&&e&&(t=k(t));let r,n,s=t.split(/\r?\n/),i=Math.max(this.line-3,0),o=Math.min(this.line+2,s.length),a=String(o).length;if(e){let{bold:e,gray:t,red:s}=T.createColors(!0);r=t=>e(s(t)),n=e=>t(e)}else r=n=e=>e;return s.slice(i,o).map((e,t)=>{let s=i+1+t,o=" "+(" "+s).slice(-a)+" | ";if(s===this.line){let t=n(o.replace(/\d/g," "))+e.slice(0,this.column-1).replace(/[^\t]/g," ");return r(">")+n(o)+e+"\n "+t+r("^")}return" "+n(o)+e}).join("\n")}toString(){let e=this.showSourceCode();return e&&(e="\n\n"+e+"\n"),this.name+": "+this.message+e}};var O=x;x.default=x;var A={};A.isClean=Symbol("isClean"),A.my=Symbol("my");const I={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let R=class{constructor(e){this.builder=e}atrule(e,t){let r="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(void 0!==e.raws.afterName?r+=e.raws.afterName:n&&(r+=" "),e.nodes)this.block(e,r+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(r+n+s,e)}}beforeAfter(e,t){let r;r="decl"===e.type?this.raw(e,null,"beforeDecl"):"comment"===e.type?this.raw(e,null,"beforeComment"):"before"===t?this.raw(e,null,"beforeRule"):this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&"root"!==n.type;)s+=1,n=n.parent;if(r.includes("\n")){let t=this.raw(e,null,"indent");if(t.length)for(let e=0;e0&&"comment"===e.nodes[t].type;)t-=1;let r=this.raw(e,"semicolon");for(let n=0;n{if(n=e.raws[t],void 0!==n)return!1})}var o;return void 0===n&&(n=I[r]),i.rawCache[r]=n,n}rawBeforeClose(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length>0&&void 0!==e.raws.after)return t=e.raws.after,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let r;return e.walkComments(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeDecl"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeDecl(e,t){let r;return e.walkDecls(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeRule"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeOpen(e){let t;return e.walk(e=>{if("decl"!==e.type&&(t=e.raws.between,void 0!==t))return!1}),t}rawBeforeRule(e){let t;return e.walk(r=>{if(r.nodes&&(r.parent!==e||e.first!==r)&&void 0!==r.raws.before)return t=r.raws.before,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(e=>{if(void 0!==e.raws.between)return t=e.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(e=>{if(e.nodes&&0===e.nodes.length&&(t=e.raws.after,void 0!==t))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(r=>{let n=r.parent;if(n&&n!==e&&n.parent&&n.parent===e&&void 0!==r.raws.before){let e=r.raws.before.split("\n");return t=e[e.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length&&"decl"===e.last.type&&(t=e.raws.semicolon,void 0!==t))return!1}),t}rawValue(e,t){let r=e[t],n=e.raws[t];return n&&n.value===r?n.raw:r}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};var M=R;R.default=R;let N=M;function P(e,t){new N(t).stringify(e)}var L=P;P.default=P;let{isClean:D,my:U}=A,F=O,B=M,j=L;function z(e,t){let r=new e.constructor;for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;if("proxyCache"===n)continue;let s=e[n],i=typeof s;"parent"===n&&"object"===i?t&&(r[n]=t):"source"===n?r[n]=s:Array.isArray(s)?r[n]=s.map(e=>z(e,r)):("object"===i&&null!==s&&(s=z(s)),r[n]=s)}return r}let V=class{constructor(e={}){this.raws={},this[D]=!1,this[U]=!0;for(let t in e)if("nodes"===t){this.nodes=[];for(let r of e[t])"function"==typeof r.clone?this.append(r.clone()):this.append(r)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=z(this);for(let r in e)t[r]=e[r];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:r,start:n}=this.rangeBy(t);return this.source.input.error(e,{column:n.column,line:n.line},{column:r.column,line:r.line},t)}return new F(e)}getProxyProcessor(){return{get:(e,t)=>"proxyOf"===t?e:"root"===t?()=>e.root().toProxy():e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"prop"!==t&&"value"!==t&&"name"!==t&&"params"!==t&&"important"!==t&&"text"!==t||e.markDirty()),!0)}}markDirty(){if(this[D]){this[D]=!1;let e=this;for(;e=e.parent;)e[D]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){let n=(t=this.toString()).indexOf(e.word);-1!==n&&(r=this.positionInside(n,t))}return r}positionInside(e,t){let r=t||this.toString(),n=this.source.start.column,s=this.source.start.line;for(let t=0;t"object"==typeof e&&e.toJSON?e.toJSON(null,t):e);else if("object"==typeof n&&n.toJSON)r[e]=n.toJSON(null,t);else if("source"===e){let i=t.get(n.input);null==i&&(i=s,t.set(n.input,s),s++),r[e]={end:n.end,inputId:i,start:n.start}}else r[e]=n}return n&&(r.inputs=[...t.keys()].map(e=>e.toJSON())),r}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=j){e.stringify&&(e=e.stringify);let t="";return e(this,e=>{t+=e}),t}warn(e,t,r){let n={node:this};for(let e in r)n[e]=r[e];return e.warn(t,n)}get proxyOf(){return this}};var G=V;V.default=V;let H=G,Z=class extends H{constructor(e){e&&void 0!==e.value&&"string"!=typeof e.value&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var $=Z;Z.default=Z;var W={nanoid:(e=21)=>{let t="",r=e;for(;r--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t}};let{SourceMapConsumer:Y,SourceMapGenerator:X}=E,{existsSync:J,readFileSync:K}=E,{dirname:q,join:Q}=E;let ee=class{constructor(e,t){if(!1===t.map)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let r=t.map?t.map.prev:void 0,n=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=q(this.mapFile)),n&&(this.text=n)}consumer(){return this.consumerCache||(this.consumerCache=new Y(this.text)),this.consumerCache}decodeInline(e){if(/^data:application\/json;charset=utf-?8,/.test(e)||/^data:application\/json,/.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(e)||/^data:application\/json;base64,/.test(e))return t=e.substr(RegExp.lastMatch.length),Buffer?Buffer.from(t,"base64").toString():window.atob(t);var t;let r=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+r)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return"object"==typeof e&&("string"==typeof e.mappings||"string"==typeof e._mappings||Array.isArray(e.sections))}loadAnnotation(e){let t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(!t)return;let r=e.lastIndexOf(t.pop()),n=e.indexOf("*/",r);r>-1&&n>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,n)))}loadFile(e){if(this.root=q(e),J(e))return this.mapFile=e,K(e,"utf-8").toString().trim()}loadMap(e,t){if(!1===t)return!1;if(t){if("string"==typeof t)return t;if("function"!=typeof t){if(t instanceof Y)return X.fromSourceMap(t).toString();if(t instanceof X)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}{let r=t(e);if(r){let e=this.loadFile(r);if(!e)throw new Error("Unable to load previous source map: "+r.toString());return e}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let t=this.annotation;return e&&(t=Q(q(e),t)),this.loadFile(t)}}}startWith(e,t){return!!e&&e.substr(0,t.length)===t}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var te=ee;ee.default=ee;let{SourceMapConsumer:re,SourceMapGenerator:ne}=E,{fileURLToPath:se,pathToFileURL:ie}=E,{isAbsolute:oe,resolve:ae}=E,{nanoid:le}=W,ce=E,ue=O,he=te,pe=Symbol("fromOffsetCache"),de=Boolean(re&&ne),fe=Boolean(ae&&oe),me=class{constructor(e,t={}){if(null==e||"object"==typeof e&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!fe||/^\w+:\/\//.test(t.from)||oe(t.from)?this.file=t.from:this.file=ae(t.from)),fe&&de){let e=new he(this.css,t);if(e.text){this.map=e;let t=e.consumer().file;!this.file&&t&&(this.file=this.mapResolve(t))}}this.file||(this.id=""),this.map&&(this.map.file=this.from)}error(e,t,r,n={}){let s,i,o;if(t&&"object"==typeof t){let e=t,n=r;if("number"==typeof e.offset){let n=this.fromOffset(e.offset);t=n.line,r=n.col}else t=e.line,r=e.column;if("number"==typeof n.offset){let e=this.fromOffset(n.offset);i=e.line,o=e.col}else i=n.line,o=n.column}else if(!r){let e=this.fromOffset(t);t=e.line,r=e.col}let a=this.origin(t,r,i,o);return s=a?new ue(e,void 0===a.endLine?a.line:{column:a.column,line:a.line},void 0===a.endLine?a.column:{column:a.endColumn,line:a.endLine},a.source,a.file,n.plugin):new ue(e,void 0===i?t:{column:r,line:t},void 0===i?r:{column:o,line:i},this.css,this.file,n.plugin),s.input={column:r,endColumn:o,endLine:i,line:t,source:this.css},this.file&&(ie&&(s.input.url=ie(this.file).toString()),s.input.file=this.file),s}fromOffset(e){let t,r;if(this[pe])r=this[pe];else{let e=this.css.split("\n");r=new Array(e.length);let t=0;for(let n=0,s=e.length;n=t)n=r.length-1;else{let t,s=r.length-2;for(;n>1),e=r[t+1])){n=t;break}n=t+1}}return{col:e-r[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:ae(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,r,n){if(!this.map)return!1;let s,i,o=this.map.consumer(),a=o.originalPositionFor({column:t,line:e});if(!a.source)return!1;"number"==typeof r&&(s=o.originalPositionFor({column:n,line:r})),i=oe(a.source)?ie(a.source):new URL(a.source,this.map.consumer().sourceRoot||ie(this.map.mapFile));let l={column:a.column,endColumn:s&&s.column,endLine:s&&s.line,line:a.line,url:i.toString()};if("file:"===i.protocol){if(!se)throw new Error("file: protocol is not available in this PostCSS build");l.file=se(i)}let c=o.sourceContentFor(a.source);return c&&(l.source=c),l}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])null!=this[t]&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};var ge=me;me.default=me,ce&&ce.registerInput&&ce.registerInput(me);let{SourceMapConsumer:ye,SourceMapGenerator:we}=E,{dirname:ve,relative:be,resolve:_e,sep:Se}=E,{pathToFileURL:Ce}=E,Ee=ge,Te=Boolean(ye&&we),ke=Boolean(ve&&_e&&be&&Se);var xe=class{constructor(e,t,r,n){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=n,this.originalCSS=n,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let t="\n";this.css.includes("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"}applyPrevMaps(){for(let e of this.previous()){let t,r=this.toUrl(this.path(e.file)),n=e.root||ve(e.file);!1===this.mapOpts.sourcesContent?(t=new ye(e.text),t.sourcesContent&&(t.sourcesContent=null)):t=e.consumer(),this.map.applySourceMap(t,r,this.toUrl(this.path(n)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],"comment"===e.type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),ke&&Te&&this.isMap())return this.generateMap();{let e="";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=we.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new we({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):""});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new we({file:this.outputFile(),ignoreInvalidMapping:!0});let e,t,r=1,n=1,s="",i={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(o,a,l)=>{if(this.css+=o,a&&"end"!==l&&(i.generated.line=r,i.generated.column=n-1,a.source&&a.source.start?(i.source=this.sourcePath(a),i.original.line=a.source.start.line,i.original.column=a.source.start.column-1,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,this.map.addMapping(i))),e=o.match(/\n/g),e?(r+=e.length,t=o.lastIndexOf("\n"),n=o.length-t):n+=o.length,a&&"start"!==l){let e=a.parent||{raws:{}};("decl"===a.type||"atrule"===a.type&&!a.nodes)&&a===e.last&&!e.raws.semicolon||(a.source&&a.source.end?(i.source=this.sourcePath(a),i.original.line=a.source.end.line,i.original.column=a.source.end.column-1,i.generated.line=r,i.generated.column=n-2,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,i.generated.line=r,i.generated.column=n-1,this.map.addMapping(i)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(e=>e.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(e=>e.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(e=>e.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(e){if(this.mapOpts.absolute)return e;if(60===e.charCodeAt(0))return e;if(/^\w+:\/\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let r=this.opts.to?ve(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(r=ve(_e(r,this.mapOpts.annotation)));let n=be(r,e);return this.memoizedPaths.set(e,n),n}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new Ee(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let r=t.source.input.from;if(r&&!e[r]){e[r]=!0;let n=this.usesFileUrls?this.toFileUrl(r):this.toUrl(this.path(r));this.map.setSourceContent(n,t.source.input.css)}}});else if(this.css){let e=this.opts.from?this.toUrl(this.path(this.opts.from)):"";this.map.setSourceContent(e,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(Ce){let t=Ce(e).toString();return this.memoizedFileURLs.set(e,t),t}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;"\\"===Se&&(e=e.replace(/\\/g,"/"));let r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r}};let Oe=G,Ae=class extends Oe{constructor(e){super(e),this.type="comment"}};var Ie=Ae;Ae.default=Ae;let Re,Me,Ne,Pe,{isClean:Le,my:De}=A,Ue=$,Fe=Ie,Be=G;function je(e){return e.map(e=>(e.nodes&&(e.nodes=je(e.nodes)),delete e.source,e))}function ze(e){if(e[Le]=!1,e.proxyOf.nodes)for(let t of e.proxyOf.nodes)ze(t)}let Ve=class e extends Be{append(...e){for(let t of e){let e=this.normalize(t,this.last);for(let t of e)this.proxyOf.nodes.push(t)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t,r,n=this.getIterator();for(;this.indexes[n]"proxyOf"===t?e:e[t]?"each"===t||"string"==typeof t&&t.startsWith("walk")?(...r)=>e[t](...r.map(e=>"function"==typeof e?(t,r)=>e(t.toProxy(),r):e)):"every"===t||"some"===t?r=>e[t]((e,...t)=>r(e.toProxy(),...t)):"root"===t?()=>e.root().toProxy():"nodes"===t?e.nodes.map(e=>e.toProxy()):"first"===t||"last"===t?e[t].toProxy():e[t]:e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"name"!==t&&"params"!==t&&"selector"!==t||e.markDirty()),!0)}}index(e){return"number"==typeof e?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let r,n=this.index(e),s=this.normalize(t,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(let e of s)this.proxyOf.nodes.splice(n+1,0,e);for(let e in this.indexes)r=this.indexes[e],n(t[De]||e.rebuild(t),(t=t.proxyOf).parent&&t.parent.removeChild(t),t[Le]&&ze(t),void 0===t.raws.before&&r&&void 0!==r.raws.before&&(t.raws.before=r.raws.before.replace(/\S/g,"")),t.parent=this.proxyOf,t))}prepend(...e){e=e.reverse();for(let t of e){let e=this.normalize(t,this.first,"prepend").reverse();for(let t of e)this.proxyOf.nodes.unshift(t);for(let t in this.indexes)this.indexes[t]=this.indexes[t]+e.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){let t;e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);for(let r in this.indexes)t=this.indexes[r],t>=e&&(this.indexes[r]=t-1);return this.markDirty(),this}replaceValues(e,t,r){return r||(r=t,t={}),this.walkDecls(n=>{t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,r))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,r)=>{let n;try{n=e(t,r)}catch(e){throw t.addToError(e)}return!1!==n&&t.walk&&(n=t.walk(e)),n})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("atrule"===r.type&&e.test(r.name))return t(r,n)}):this.walk((r,n)=>{if("atrule"===r.type&&r.name===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("atrule"===e.type)return t(e,r)}))}walkComments(e){return this.walk((t,r)=>{if("comment"===t.type)return e(t,r)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("decl"===r.type&&e.test(r.prop))return t(r,n)}):this.walk((r,n)=>{if("decl"===r.type&&r.prop===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("decl"===e.type)return t(e,r)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("rule"===r.type&&e.test(r.selector))return t(r,n)}):this.walk((r,n)=>{if("rule"===r.type&&r.selector===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("rule"===e.type)return t(e,r)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Ve.registerParse=e=>{Re=e},Ve.registerRule=e=>{Me=e},Ve.registerAtRule=e=>{Ne=e},Ve.registerRoot=e=>{Pe=e};var Ge=Ve;Ve.default=Ve,Ve.rebuild=e=>{"atrule"===e.type?Object.setPrototypeOf(e,Ne.prototype):"rule"===e.type?Object.setPrototypeOf(e,Me.prototype):"decl"===e.type?Object.setPrototypeOf(e,Ue.prototype):"comment"===e.type?Object.setPrototypeOf(e,Fe.prototype):"root"===e.type&&Object.setPrototypeOf(e,Pe.prototype),e[De]=!0,e.nodes&&e.nodes.forEach(e=>{Ve.rebuild(e)})};let He,Ze,$e=Ge,We=class extends $e{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new He(new Ze,this,e).stringify()}};We.registerLazyResult=e=>{He=e},We.registerProcessor=e=>{Ze=e};var Ye=We;We.default=We;let Xe={};var Je=function(e){Xe[e]||(Xe[e]=!0,"undefined"!=typeof console&&console.warn&&console.warn(e))};let Ke=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let e=t.node.rangeBy(t);this.line=e.start.line,this.column=e.start.column,this.endLine=e.end.line,this.endColumn=e.end.column}for(let e in t)this[e]=t[e]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var qe=Ke;Ke.default=Ke;let Qe=qe,et=class{constructor(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let r=new Qe(e,t);return this.messages.push(r),r}warnings(){return this.messages.filter(e=>"warning"===e.type)}get content(){return this.css}};var tt=et;et.default=et;const rt="'".charCodeAt(0),nt='"'.charCodeAt(0),st="\\".charCodeAt(0),it="/".charCodeAt(0),ot="\n".charCodeAt(0),at=" ".charCodeAt(0),lt="\f".charCodeAt(0),ct="\t".charCodeAt(0),ut="\r".charCodeAt(0),ht="[".charCodeAt(0),pt="]".charCodeAt(0),dt="(".charCodeAt(0),ft=")".charCodeAt(0),mt="{".charCodeAt(0),gt="}".charCodeAt(0),yt=";".charCodeAt(0),wt="*".charCodeAt(0),vt=":".charCodeAt(0),bt="@".charCodeAt(0),_t=/[\t\n\f\r "#'()/;[\\\]{}]/g,St=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Ct=/.[\r\n"'(/\\]/,Et=/[\da-f]/i;let Tt=Ge,kt=class extends Tt{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};var xt=kt;kt.default=kt,Tt.registerAtRule(kt);let Ot,At,It=Ge,Rt=class extends It{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,r){let n=super.normalize(e);if(t)if("prepend"===r)this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let e of n)e.raws.before=t.raws.before;return n}removeChild(e,t){let r=this.index(e);return!t&&0===r&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[r].raws.before),super.removeChild(e)}toResult(e={}){return new Ot(new At,this,e).stringify()}};Rt.registerLazyResult=e=>{Ot=e},Rt.registerProcessor=e=>{At=e};var Mt=Rt;Rt.default=Rt,It.registerRoot(Rt);let Nt={comma:e=>Nt.split(e,[","],!0),space:e=>Nt.split(e,[" ","\n","\t"]),split(e,t,r){let n=[],s="",i=!1,o=0,a=!1,l="",c=!1;for(let r of e)c?c=!1:"\\"===r?c=!0:a?r===l&&(a=!1):'"'===r||"'"===r?(a=!0,l=r):"("===r?o+=1:")"===r?o>0&&(o-=1):0===o&&t.includes(r)&&(i=!0),i?(""!==s&&n.push(s.trim()),s="",i=!1):s+=r;return(r||""!==s)&&n.push(s.trim()),n}};var Pt=Nt;Nt.default=Nt;let Lt=Ge,Dt=Pt,Ut=class extends Lt{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Dt.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,r=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(r)}};var Ft=Ut;Ut.default=Ut,Lt.registerRule(Ut);let Bt=$,jt=function(e,t={}){let r,n,s,i,o,a,l,c,u,h,p=e.css.valueOf(),d=t.ignoreErrors,f=p.length,m=0,g=[],y=[];function w(t){throw e.error("Unclosed "+t,m)}return{back:function(e){y.push(e)},endOfFile:function(){return 0===y.length&&m>=f},nextToken:function(e){if(y.length)return y.pop();if(m>=f)return;let t=!!e&&e.ignoreUnclosed;switch(r=p.charCodeAt(m),r){case ot:case at:case ct:case ut:case lt:n=m;do{n+=1,r=p.charCodeAt(n)}while(r===at||r===ot||r===ct||r===ut||r===lt);h=["space",p.slice(m,n)],m=n-1;break;case ht:case pt:case mt:case gt:case vt:case yt:case ft:{let e=String.fromCharCode(r);h=[e,e,m];break}case dt:if(c=g.length?g.pop()[1]:"",u=p.charCodeAt(m+1),"url"===c&&u!==rt&&u!==nt&&u!==at&&u!==ot&&u!==ct&&u!==lt&&u!==ut){n=m;do{if(a=!1,n=p.indexOf(")",n+1),-1===n){if(d||t){n=m;break}w("bracket")}for(l=n;p.charCodeAt(l-1)===st;)l-=1,a=!a}while(a);h=["brackets",p.slice(m,n+1),m,n],m=n}else n=p.indexOf(")",m+1),i=p.slice(m,n+1),-1===n||Ct.test(i)?h=["(","(",m]:(h=["brackets",i,m,n],m=n);break;case rt:case nt:s=r===rt?"'":'"',n=m;do{if(a=!1,n=p.indexOf(s,n+1),-1===n){if(d||t){n=m+1;break}w("string")}for(l=n;p.charCodeAt(l-1)===st;)l-=1,a=!a}while(a);h=["string",p.slice(m,n+1),m,n],m=n;break;case bt:_t.lastIndex=m+1,_t.test(p),n=0===_t.lastIndex?p.length-1:_t.lastIndex-2,h=["at-word",p.slice(m,n+1),m,n],m=n;break;case st:for(n=m,o=!0;p.charCodeAt(n+1)===st;)n+=1,o=!o;if(r=p.charCodeAt(n+1),o&&r!==it&&r!==at&&r!==ot&&r!==ct&&r!==ut&&r!==lt&&(n+=1,Et.test(p.charAt(n)))){for(;Et.test(p.charAt(n+1));)n+=1;p.charCodeAt(n+1)===at&&(n+=1)}h=["word",p.slice(m,n+1),m,n],m=n;break;default:r===it&&p.charCodeAt(m+1)===wt?(n=p.indexOf("*/",m+2)+1,0===n&&(d||t?n=p.length:w("comment")),h=["comment",p.slice(m,n+1),m,n],m=n):(St.lastIndex=m+1,St.test(p),n=0===St.lastIndex?p.length-1:St.lastIndex-2,h=["word",p.slice(m,n+1),m,n],g.push(h),m=n)}return m++,h},position:function(){return m}}},zt=Ie,Vt=xt,Gt=Mt,Ht=Ft;const Zt={empty:!0,space:!0};var $t=class{constructor(e){this.input=e,this.root=new Gt,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t,r,n,s=new Vt;s.name=e[1].slice(1),""===s.name&&this.unnamedAtrule(s,e),this.init(s,e[2]);let i=!1,o=!1,a=[],l=[];for(;!this.tokenizer.endOfFile();){if(t=(e=this.tokenizer.nextToken())[0],"("===t||"["===t?l.push("("===t?")":"]"):"{"===t&&l.length>0?l.push("}"):t===l[l.length-1]&&l.pop(),0===l.length){if(";"===t){s.source.end=this.getPosition(e[2]),s.source.end.offset++,this.semicolon=!0;break}if("{"===t){o=!0;break}if("}"===t){if(a.length>0){for(n=a.length-1,r=a[n];r&&"space"===r[0];)r=a[--n];r&&(s.source.end=this.getPosition(r[3]||r[2]),s.source.end.offset++)}this.end(e);break}a.push(e)}else a.push(e);if(this.tokenizer.endOfFile()){i=!0;break}}s.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(s.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(s,"params",a),i&&(e=a[a.length-1],s.source.end=this.getPosition(e[3]||e[2]),s.source.end.offset++,this.spaces=s.raws.between,s.raws.between="")):(s.raws.afterName="",s.params=""),o&&(s.nodes=[],this.current=s)}checkMissedSemicolon(e){let t=this.colon(e);if(!1===t)return;let r,n=0;for(let s=t-1;s>=0&&(r=e[s],"space"===r[0]||(n+=1,2!==n));s--);throw this.input.error("Missed semicolon","word"===r[0]?r[3]+1:r[2])}colon(e){let t,r,n,s=0;for(let[i,o]of e.entries()){if(t=o,r=t[0],"("===r&&(s+=1),")"===r&&(s-=1),0===s&&":"===r){if(n){if("word"===n[0]&&"progid"===n[1])continue;return i}this.doubleColon(t)}n=t}return!1}comment(e){let t=new zt;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let r=e[1].slice(2,-2);if(/^\s*$/.test(r))t.text="",t.raws.left=r,t.raws.right="";else{let e=r.match(/^(\s*)([^]*\S)(\s*)$/);t.text=e[2],t.raws.left=e[1],t.raws.right=e[3]}}createTokenizer(){this.tokenizer=jt(this.input)}decl(e,t){let r=new Bt;this.init(r,e[0][2]);let n,s=e[e.length-1];for(";"===s[0]&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(s[3]||s[2]||function(e){for(let t=e.length-1;t>=0;t--){let r=e[t],n=r[3]||r[2];if(n)return n}}(e)),r.source.end.offset++;"word"!==e[0][0];)1===e.length&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop="";e.length;){let t=e[0][0];if(":"===t||"space"===t||"comment"===t)break;r.prop+=e.shift()[1]}for(r.raws.between="";e.length;){if(n=e.shift(),":"===n[0]){r.raws.between+=n[1];break}"word"===n[0]&&/\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1]}"_"!==r.prop[0]&&"*"!==r.prop[0]||(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));let i,o=[];for(;e.length&&(i=e[0][0],"space"===i||"comment"===i);)o.push(e.shift());this.precheckMissedSemicolon(e);for(let t=e.length-1;t>=0;t--){if(n=e[t],"!important"===n[1].toLowerCase()){r.important=!0;let n=this.stringFrom(e,t);n=this.spacesFromEnd(e)+n," !important"!==n&&(r.raws.important=n);break}if("important"===n[1].toLowerCase()){let n=e.slice(0),s="";for(let e=t;e>0;e--){let t=n[e][0];if(0===s.trim().indexOf("!")&&"space"!==t)break;s=n.pop()[1]+s}0===s.trim().indexOf("!")&&(r.important=!0,r.raws.important=s,e=n)}if("space"!==n[0]&&"comment"!==n[0])break}e.some(e=>"space"!==e[0]&&"comment"!==e[0])&&(r.raws.between+=o.map(e=>e[1]).join(""),o=[]),this.raw(r,"value",o.concat(e),t),r.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new Ht;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let e=this.current.nodes[this.current.nodes.length-1];e&&"rule"===e.type&&!e.raws.ownSemicolon&&(e.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="","comment"!==e.type&&(this.semicolon=!1)}other(e){let t=!1,r=null,n=!1,s=null,i=[],o=e[1].startsWith("--"),a=[],l=e;for(;l;){if(r=l[0],a.push(l),"("===r||"["===r)s||(s=l),i.push("("===r?")":"]");else if(o&&n&&"{"===r)s||(s=l),i.push("}");else if(0===i.length){if(";"===r){if(n)return void this.decl(a,o);break}if("{"===r)return void this.rule(a);if("}"===r){this.tokenizer.back(a.pop()),t=!0;break}":"===r&&(n=!0)}else r===i[i.length-1]&&(i.pop(),0===i.length&&(s=null));l=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),i.length>0&&this.unclosedBracket(s),t&&n){if(!o)for(;a.length&&(l=a[a.length-1][0],"space"===l||"comment"===l);)this.tokenizer.back(a.pop());this.decl(a,o)}else this.unknownWord(a)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e)}this.endFile()}precheckMissedSemicolon(){}raw(e,t,r,n){let s,i,o,a,l=r.length,c="",u=!0;for(let e=0;ee+t[1],"");e.raws[t]={raw:n,value:c}}e[t]=c}rule(e){e.pop();let t=new Ht;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t||"comment"===t);)r=e.pop()[1]+r;return r}spacesAndCommentsFromStart(e){let t,r="";for(;e.length&&(t=e[0][0],"space"===t||"comment"===t);)r+=e.shift()[1];return r}spacesFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t);)r=e.pop()[1]+r;return r}stringFrom(e,t){let r="";for(let n=t;nfr(e)),e}let mr={},gr=class e{constructor(t,r,n){let s;if(this.stringified=!1,this.processed=!1,"object"!=typeof r||null===r||"root"!==r.type&&"document"!==r.type)if(r instanceof e||r instanceof ir)s=fr(r.root),r.map&&(void 0===n.map&&(n.map={}),n.map.inline||(n.map.inline=!1),n.map.prev=r.map);else{let e=or;n.syntax&&(e=n.syntax.parse),n.parser&&(e=n.parser),e.parse&&(e=e.parse);try{s=e(r,n)}catch(e){this.processed=!0,this.error=e}s&&!s[Qt]&&rr.rebuild(s)}else s=fr(r);this.result=new ir(t,s,n),this.helpers={...mr,postcss:mr,result:this.result},this.plugins=this.processor.plugins.map(e=>"object"==typeof e&&e.prepare?{...e,...e.prepare(this.result)}:e)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let r=this.result.lastPlugin;try{if(t&&t.addToError(e),this.error=e,"CssSyntaxError"!==e.name||e.plugin){if(r.postcssVersion&&"production"!==process.env.NODE_ENV){let e=r.postcssPlugin,t=r.postcssVersion,n=this.result.processor.version,s=t.split("."),i=n.split(".");(s[0]!==i[0]||parseInt(s[1])>parseInt(i[1]))&&console.error("Unknown error from PostCSS plugin. Your current PostCSS version is "+n+", but "+e+" uses "+t+". Perhaps this is the source of the error below.")}}else e.plugin=r.postcssPlugin,e.setMessage()}catch(e){console&&console.error&&console.error(e)}return e}prepareVisitors(){this.listeners={};let e=(e,t,r)=>{this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push([e,r])};for(let t of this.plugins)if("object"==typeof t)for(let r in t){if(!cr[r]&&/^[A-Z]/.test(r))throw new Error(`Unknown event ${r} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!ur[r])if("object"==typeof t[r])for(let n in t[r])e(t,"*"===n?r:r+"-"+n.toLowerCase(),t[r][n]);else"function"==typeof t[r]&&e(t,r,t[r])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e0;){let e=this.visitTick(t);if(hr(e))try{await e}catch(e){let r=t[t.length-1].node;throw this.handleError(e,r)}}}if(this.listeners.OnceExit)for(let[t,r]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if("document"===e.type){let t=e.nodes.map(e=>r(e,this.helpers));await Promise.all(t)}else await r(e,this.helpers)}catch(e){throw this.handleError(e)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if("object"==typeof e&&e.Once){if("document"===this.result.root.type){let t=this.result.root.nodes.map(t=>e.Once(t,this.helpers));return hr(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}if("function"==typeof e)return e(this.result.root,this.result)}catch(e){throw this.handleError(e)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=tr;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new er(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){if(hr(this.runOnRoot(e)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[qt];)e[qt]=!0,this.walkSync(e);if(this.listeners.OnceExit)if("document"===e.type)for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this.opts||sr("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[r,n]of e){let e;this.result.lastPlugin=r;try{e=n(t,this.helpers)}catch(e){throw this.handleError(e,t.proxyOf)}if("root"!==t.type&&"document"!==t.type&&!t.parent)return!0;if(hr(e))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:r,visitors:n}=t;if("root"!==r.type&&"document"!==r.type&&!r.parent)return void e.pop();if(n.length>0&&t.visitorIndex{e[qt]||this.walkSync(e)});else{let t=this.listeners[r];if(t&&this.visitSync(t,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};gr.registerPostcss=e=>{mr=e};var yr=gr;gr.default=gr,ar.registerLazyResult(gr),nr.registerLazyResult(gr);let wr=xe,vr=L,br=Je,_r=Kt;const Sr=tt;let Cr=class{constructor(e,t,r){let n;t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;let s=vr;this.result=new Sr(this._processor,n,this._opts),this.result.css=t;let i=this;Object.defineProperty(this.result,"root",{get:()=>i.root});let o=new wr(s,n,this._opts,t);if(o.isMap()){let[e,t]=o.generate();e&&(this.result.css=e),t&&(this.result.map=t)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this._opts||br("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=_r;try{e=t(this._css,this._opts)}catch(e){this.error=e}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}};var Er=Cr;Cr.default=Cr;let Tr=Er,kr=yr,xr=Ye,Or=Mt,Ar=class{constructor(e=[]){this.version="8.4.38",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let r of e)if(!0===r.postcss?r=r():r.postcss&&(r=r.postcss),"object"==typeof r&&Array.isArray(r.plugins))t=t.concat(r.plugins);else if("object"==typeof r&&r.postcssPlugin)t.push(r);else if("function"==typeof r)t.push(r);else{if("object"!=typeof r||!r.parse&&!r.stringify)throw new Error(r+" is not a PostCSS plugin");if("production"!==process.env.NODE_ENV)throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.")}return t}process(e,t={}){return this.plugins.length||t.parser||t.stringifier||t.syntax?new kr(this,e,t):new Tr(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};var Ir=Ar;Ar.default=Ar,Or.registerProcessor(Ar),xr.registerProcessor(Ar);let Rr=$,Mr=te,Nr=Ie,Pr=xt,Lr=ge,Dr=Mt,Ur=Ft;function Fr(e,t){if(Array.isArray(e))return e.map(e=>Fr(e));let{inputs:r,...n}=e;if(r){t=[];for(let e of r){let r={...e,__proto__:Lr.prototype};r.map&&(r.map={...r.map,__proto__:Mr.prototype}),t.push(r)}}if(n.nodes&&(n.nodes=e.nodes.map(e=>Fr(e,t))),n.source){let{inputId:e,...r}=n.source;n.source=r,null!=e&&(n.source.input=t[e])}if("root"===n.type)return new Dr(n);if("decl"===n.type)return new Rr(n);if("rule"===n.type)return new Ur(n);if("comment"===n.type)return new Nr(n);if("atrule"===n.type)return new Pr(n);throw new Error("Unknown node type: "+e.type)}var Br=Fr;Fr.default=Fr;let jr=O,zr=$,Vr=yr,Gr=Ge,Hr=Ir,Zr=L,$r=Br,Wr=Ye,Yr=qe,Xr=Ie,Jr=xt,Kr=tt,qr=ge,Qr=Kt,en=Pt,tn=Ft,rn=Mt,nn=G;function sn(...e){return 1===e.length&&Array.isArray(e[0])&&(e=e[0]),new Hr(e)}sn.plugin=function(e,t){let r,n=!1;function s(...r){console&&console.warn&&!n&&(n=!0,console.warn(e+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226"));let s=t(...r);return s.postcssPlugin=e,s.postcssVersion=(new Hr).version,s}return Object.defineProperty(s,"postcss",{get:()=>(r||(r=s()),r)}),s.process=function(e,t,r){return sn([s(r)]).process(e,t)},s},sn.stringify=Zr,sn.parse=Qr,sn.fromJSON=$r,sn.list=en,sn.comment=e=>new Xr(e),sn.atRule=e=>new Jr(e),sn.decl=e=>new zr(e),sn.rule=e=>new tn(e),sn.root=e=>new rn(e),sn.document=e=>new Wr(e),sn.CssSyntaxError=jr,sn.Declaration=zr,sn.Container=Gr,sn.Processor=Hr,sn.Document=Wr,sn.Comment=Xr,sn.Warning=Yr,sn.AtRule=Jr,sn.Result=Kr,sn.Input=qr,sn.Rule=tn,sn.Root=rn,sn.Node=nn,Vr.registerPostcss(sn);var on=sn;sn.default=sn;const an=w(on);an.stringify,an.fromJSON,an.plugin,an.parse,an.list,an.document,an.comment,an.atRule,an.rule,an.decl,an.root,an.CssSyntaxError,an.Declaration,an.Container,an.Processor,an.Document,an.Comment,an.Warning,an.AtRule,an.Result,an.Input,an.Rule,an.Root,an.Node;var ln=Object.defineProperty,cn=(e,t,r)=>((e,t,r)=>t in e?ln(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);function un(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function hn(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var pn={exports:{}},dn=String,fn=function(){return{isColorSupported:!1,reset:dn,bold:dn,dim:dn,italic:dn,underline:dn,inverse:dn,hidden:dn,strikethrough:dn,black:dn,red:dn,green:dn,yellow:dn,blue:dn,magenta:dn,cyan:dn,white:dn,gray:dn,bgBlack:dn,bgRed:dn,bgGreen:dn,bgYellow:dn,bgBlue:dn,bgMagenta:dn,bgCyan:dn,bgWhite:dn}};pn.exports=fn(),pn.exports.createColors=fn;var mn=pn.exports;const gn=hn(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let yn=mn,wn=gn,vn=class e extends Error{constructor(t,r,n,s,i,o){super(t),this.name="CssSyntaxError",this.reason=t,i&&(this.file=i),s&&(this.source=s),o&&(this.plugin=o),void 0!==r&&void 0!==n&&("number"==typeof r?(this.line=r,this.column=n):(this.line=r.line,this.column=r.column,this.endLine=n.line,this.endColumn=n.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;null==e&&(e=yn.isColorSupported),wn&&e&&(t=wn(t));let r,n,s=t.split(/\r?\n/),i=Math.max(this.line-3,0),o=Math.min(this.line+2,s.length),a=String(o).length;if(e){let{bold:e,gray:t,red:s}=yn.createColors(!0);r=t=>e(s(t)),n=e=>t(e)}else r=n=e=>e;return s.slice(i,o).map((e,t)=>{let s=i+1+t,o=" "+(" "+s).slice(-a)+" | ";if(s===this.line){let t=n(o.replace(/\d/g," "))+e.slice(0,this.column-1).replace(/[^\t]/g," ");return r(">")+n(o)+e+"\n "+t+r("^")}return" "+n(o)+e}).join("\n")}toString(){let e=this.showSourceCode();return e&&(e="\n\n"+e+"\n"),this.name+": "+this.message+e}};var bn=vn;vn.default=vn;var _n={};_n.isClean=Symbol("isClean"),_n.my=Symbol("my");const Sn={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let Cn=class{constructor(e){this.builder=e}atrule(e,t){let r="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(void 0!==e.raws.afterName?r+=e.raws.afterName:n&&(r+=" "),e.nodes)this.block(e,r+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(r+n+s,e)}}beforeAfter(e,t){let r;r="decl"===e.type?this.raw(e,null,"beforeDecl"):"comment"===e.type?this.raw(e,null,"beforeComment"):"before"===t?this.raw(e,null,"beforeRule"):this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&"root"!==n.type;)s+=1,n=n.parent;if(r.includes("\n")){let t=this.raw(e,null,"indent");if(t.length)for(let e=0;e0&&"comment"===e.nodes[t].type;)t-=1;let r=this.raw(e,"semicolon");for(let n=0;n{if(n=e.raws[t],void 0!==n)return!1})}var o;return void 0===n&&(n=Sn[r]),i.rawCache[r]=n,n}rawBeforeClose(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length>0&&void 0!==e.raws.after)return t=e.raws.after,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let r;return e.walkComments(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeDecl"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeDecl(e,t){let r;return e.walkDecls(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeRule"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeOpen(e){let t;return e.walk(e=>{if("decl"!==e.type&&(t=e.raws.between,void 0!==t))return!1}),t}rawBeforeRule(e){let t;return e.walk(r=>{if(r.nodes&&(r.parent!==e||e.first!==r)&&void 0!==r.raws.before)return t=r.raws.before,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(e=>{if(void 0!==e.raws.between)return t=e.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(e=>{if(e.nodes&&0===e.nodes.length&&(t=e.raws.after,void 0!==t))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(r=>{let n=r.parent;if(n&&n!==e&&n.parent&&n.parent===e&&void 0!==r.raws.before){let e=r.raws.before.split("\n");return t=e[e.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length&&"decl"===e.last.type&&(t=e.raws.semicolon,void 0!==t))return!1}),t}rawValue(e,t){let r=e[t],n=e.raws[t];return n&&n.value===r?n.raw:r}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};var En=Cn;Cn.default=Cn;let Tn=En;function kn(e,t){new Tn(t).stringify(e)}var xn=kn;kn.default=kn;let{isClean:On,my:An}=_n,In=bn,Rn=En,Mn=xn;function Nn(e,t){let r=new e.constructor;for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;if("proxyCache"===n)continue;let s=e[n],i=typeof s;"parent"===n&&"object"===i?t&&(r[n]=t):"source"===n?r[n]=s:Array.isArray(s)?r[n]=s.map(e=>Nn(e,r)):("object"===i&&null!==s&&(s=Nn(s)),r[n]=s)}return r}let Pn=class{constructor(e={}){this.raws={},this[On]=!1,this[An]=!0;for(let t in e)if("nodes"===t){this.nodes=[];for(let r of e[t])"function"==typeof r.clone?this.append(r.clone()):this.append(r)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=Nn(this);for(let r in e)t[r]=e[r];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:r,start:n}=this.rangeBy(t);return this.source.input.error(e,{column:n.column,line:n.line},{column:r.column,line:r.line},t)}return new In(e)}getProxyProcessor(){return{get:(e,t)=>"proxyOf"===t?e:"root"===t?()=>e.root().toProxy():e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"prop"!==t&&"value"!==t&&"name"!==t&&"params"!==t&&"important"!==t&&"text"!==t||e.markDirty()),!0)}}markDirty(){if(this[On]){this[On]=!1;let e=this;for(;e=e.parent;)e[On]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){let n=(t=this.toString()).indexOf(e.word);-1!==n&&(r=this.positionInside(n,t))}return r}positionInside(e,t){let r=t||this.toString(),n=this.source.start.column,s=this.source.start.line;for(let t=0;t"object"==typeof e&&e.toJSON?e.toJSON(null,t):e);else if("object"==typeof n&&n.toJSON)r[e]=n.toJSON(null,t);else if("source"===e){let i=t.get(n.input);null==i&&(i=s,t.set(n.input,s),s++),r[e]={end:n.end,inputId:i,start:n.start}}else r[e]=n}return n&&(r.inputs=[...t.keys()].map(e=>e.toJSON())),r}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=Mn){e.stringify&&(e=e.stringify);let t="";return e(this,e=>{t+=e}),t}warn(e,t,r){let n={node:this};for(let e in r)n[e]=r[e];return e.warn(t,n)}get proxyOf(){return this}};var Ln=Pn;Pn.default=Pn;let Dn=Ln,Un=class extends Dn{constructor(e){e&&void 0!==e.value&&"string"!=typeof e.value&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var Fn=Un;Un.default=Un;var Bn={nanoid:(e=21)=>{let t="",r=e;for(;r--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t}};let{SourceMapConsumer:jn,SourceMapGenerator:zn}=gn,{existsSync:Vn,readFileSync:Gn}=gn,{dirname:Hn,join:Zn}=gn;let $n=class{constructor(e,t){if(!1===t.map)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let r=t.map?t.map.prev:void 0,n=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=Hn(this.mapFile)),n&&(this.text=n)}consumer(){return this.consumerCache||(this.consumerCache=new jn(this.text)),this.consumerCache}decodeInline(e){if(/^data:application\/json;charset=utf-?8,/.test(e)||/^data:application\/json,/.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(e)||/^data:application\/json;base64,/.test(e))return t=e.substr(RegExp.lastMatch.length),Buffer?Buffer.from(t,"base64").toString():window.atob(t);var t;let r=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+r)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return"object"==typeof e&&("string"==typeof e.mappings||"string"==typeof e._mappings||Array.isArray(e.sections))}loadAnnotation(e){let t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(!t)return;let r=e.lastIndexOf(t.pop()),n=e.indexOf("*/",r);r>-1&&n>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,n)))}loadFile(e){if(this.root=Hn(e),Vn(e))return this.mapFile=e,Gn(e,"utf-8").toString().trim()}loadMap(e,t){if(!1===t)return!1;if(t){if("string"==typeof t)return t;if("function"!=typeof t){if(t instanceof jn)return zn.fromSourceMap(t).toString();if(t instanceof zn)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}{let r=t(e);if(r){let e=this.loadFile(r);if(!e)throw new Error("Unable to load previous source map: "+r.toString());return e}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let t=this.annotation;return e&&(t=Zn(Hn(e),t)),this.loadFile(t)}}}startWith(e,t){return!!e&&e.substr(0,t.length)===t}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var Wn=$n;$n.default=$n;let{SourceMapConsumer:Yn,SourceMapGenerator:Xn}=gn,{fileURLToPath:Jn,pathToFileURL:Kn}=gn,{isAbsolute:qn,resolve:Qn}=gn,{nanoid:es}=Bn,ts=gn,rs=bn,ns=Wn,ss=Symbol("fromOffsetCache"),is=Boolean(Yn&&Xn),os=Boolean(Qn&&qn),as=class{constructor(e,t={}){if(null==e||"object"==typeof e&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!os||/^\w+:\/\//.test(t.from)||qn(t.from)?this.file=t.from:this.file=Qn(t.from)),os&&is){let e=new ns(this.css,t);if(e.text){this.map=e;let t=e.consumer().file;!this.file&&t&&(this.file=this.mapResolve(t))}}this.file||(this.id=""),this.map&&(this.map.file=this.from)}error(e,t,r,n={}){let s,i,o;if(t&&"object"==typeof t){let e=t,n=r;if("number"==typeof e.offset){let n=this.fromOffset(e.offset);t=n.line,r=n.col}else t=e.line,r=e.column;if("number"==typeof n.offset){let e=this.fromOffset(n.offset);i=e.line,o=e.col}else i=n.line,o=n.column}else if(!r){let e=this.fromOffset(t);t=e.line,r=e.col}let a=this.origin(t,r,i,o);return s=a?new rs(e,void 0===a.endLine?a.line:{column:a.column,line:a.line},void 0===a.endLine?a.column:{column:a.endColumn,line:a.endLine},a.source,a.file,n.plugin):new rs(e,void 0===i?t:{column:r,line:t},void 0===i?r:{column:o,line:i},this.css,this.file,n.plugin),s.input={column:r,endColumn:o,endLine:i,line:t,source:this.css},this.file&&(Kn&&(s.input.url=Kn(this.file).toString()),s.input.file=this.file),s}fromOffset(e){let t,r;if(this[ss])r=this[ss];else{let e=this.css.split("\n");r=new Array(e.length);let t=0;for(let n=0,s=e.length;n=t)n=r.length-1;else{let t,s=r.length-2;for(;n>1),e=r[t+1])){n=t;break}n=t+1}}return{col:e-r[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:Qn(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,r,n){if(!this.map)return!1;let s,i,o=this.map.consumer(),a=o.originalPositionFor({column:t,line:e});if(!a.source)return!1;"number"==typeof r&&(s=o.originalPositionFor({column:n,line:r})),i=qn(a.source)?Kn(a.source):new URL(a.source,this.map.consumer().sourceRoot||Kn(this.map.mapFile));let l={column:a.column,endColumn:s&&s.column,endLine:s&&s.line,line:a.line,url:i.toString()};if("file:"===i.protocol){if(!Jn)throw new Error("file: protocol is not available in this PostCSS build");l.file=Jn(i)}let c=o.sourceContentFor(a.source);return c&&(l.source=c),l}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])null!=this[t]&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};var ls=as;as.default=as,ts&&ts.registerInput&&ts.registerInput(as);let{SourceMapConsumer:cs,SourceMapGenerator:us}=gn,{dirname:hs,relative:ps,resolve:ds,sep:fs}=gn,{pathToFileURL:ms}=gn,gs=ls,ys=Boolean(cs&&us),ws=Boolean(hs&&ds&&ps&&fs);var vs=class{constructor(e,t,r,n){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=n,this.originalCSS=n,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let t="\n";this.css.includes("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"}applyPrevMaps(){for(let e of this.previous()){let t,r=this.toUrl(this.path(e.file)),n=e.root||hs(e.file);!1===this.mapOpts.sourcesContent?(t=new cs(e.text),t.sourcesContent&&(t.sourcesContent=null)):t=e.consumer(),this.map.applySourceMap(t,r,this.toUrl(this.path(n)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],"comment"===e.type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),ws&&ys&&this.isMap())return this.generateMap();{let e="";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=us.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new us({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):""});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new us({file:this.outputFile(),ignoreInvalidMapping:!0});let e,t,r=1,n=1,s="",i={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(o,a,l)=>{if(this.css+=o,a&&"end"!==l&&(i.generated.line=r,i.generated.column=n-1,a.source&&a.source.start?(i.source=this.sourcePath(a),i.original.line=a.source.start.line,i.original.column=a.source.start.column-1,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,this.map.addMapping(i))),e=o.match(/\n/g),e?(r+=e.length,t=o.lastIndexOf("\n"),n=o.length-t):n+=o.length,a&&"start"!==l){let e=a.parent||{raws:{}};("decl"===a.type||"atrule"===a.type&&!a.nodes)&&a===e.last&&!e.raws.semicolon||(a.source&&a.source.end?(i.source=this.sourcePath(a),i.original.line=a.source.end.line,i.original.column=a.source.end.column-1,i.generated.line=r,i.generated.column=n-2,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,i.generated.line=r,i.generated.column=n-1,this.map.addMapping(i)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(e=>e.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(e=>e.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(e=>e.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(e){if(this.mapOpts.absolute)return e;if(60===e.charCodeAt(0))return e;if(/^\w+:\/\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let r=this.opts.to?hs(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(r=hs(ds(r,this.mapOpts.annotation)));let n=ps(r,e);return this.memoizedPaths.set(e,n),n}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new gs(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let r=t.source.input.from;if(r&&!e[r]){e[r]=!0;let n=this.usesFileUrls?this.toFileUrl(r):this.toUrl(this.path(r));this.map.setSourceContent(n,t.source.input.css)}}});else if(this.css){let e=this.opts.from?this.toUrl(this.path(this.opts.from)):"";this.map.setSourceContent(e,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(ms){let t=ms(e).toString();return this.memoizedFileURLs.set(e,t),t}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;"\\"===fs&&(e=e.replace(/\\/g,"/"));let r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r}};let bs=Ln,_s=class extends bs{constructor(e){super(e),this.type="comment"}};var Ss=_s;_s.default=_s;let Cs,Es,Ts,ks,{isClean:xs,my:Os}=_n,As=Fn,Is=Ss,Rs=Ln;function Ms(e){return e.map(e=>(e.nodes&&(e.nodes=Ms(e.nodes)),delete e.source,e))}function Ns(e){if(e[xs]=!1,e.proxyOf.nodes)for(let t of e.proxyOf.nodes)Ns(t)}let Ps=class e extends Rs{append(...e){for(let t of e){let e=this.normalize(t,this.last);for(let t of e)this.proxyOf.nodes.push(t)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t,r,n=this.getIterator();for(;this.indexes[n]"proxyOf"===t?e:e[t]?"each"===t||"string"==typeof t&&t.startsWith("walk")?(...r)=>e[t](...r.map(e=>"function"==typeof e?(t,r)=>e(t.toProxy(),r):e)):"every"===t||"some"===t?r=>e[t]((e,...t)=>r(e.toProxy(),...t)):"root"===t?()=>e.root().toProxy():"nodes"===t?e.nodes.map(e=>e.toProxy()):"first"===t||"last"===t?e[t].toProxy():e[t]:e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"name"!==t&&"params"!==t&&"selector"!==t||e.markDirty()),!0)}}index(e){return"number"==typeof e?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let r,n=this.index(e),s=this.normalize(t,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(let e of s)this.proxyOf.nodes.splice(n+1,0,e);for(let e in this.indexes)r=this.indexes[e],n(t[Os]||e.rebuild(t),(t=t.proxyOf).parent&&t.parent.removeChild(t),t[xs]&&Ns(t),void 0===t.raws.before&&r&&void 0!==r.raws.before&&(t.raws.before=r.raws.before.replace(/\S/g,"")),t.parent=this.proxyOf,t))}prepend(...e){e=e.reverse();for(let t of e){let e=this.normalize(t,this.first,"prepend").reverse();for(let t of e)this.proxyOf.nodes.unshift(t);for(let t in this.indexes)this.indexes[t]=this.indexes[t]+e.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){let t;e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);for(let r in this.indexes)t=this.indexes[r],t>=e&&(this.indexes[r]=t-1);return this.markDirty(),this}replaceValues(e,t,r){return r||(r=t,t={}),this.walkDecls(n=>{t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,r))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,r)=>{let n;try{n=e(t,r)}catch(e){throw t.addToError(e)}return!1!==n&&t.walk&&(n=t.walk(e)),n})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("atrule"===r.type&&e.test(r.name))return t(r,n)}):this.walk((r,n)=>{if("atrule"===r.type&&r.name===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("atrule"===e.type)return t(e,r)}))}walkComments(e){return this.walk((t,r)=>{if("comment"===t.type)return e(t,r)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("decl"===r.type&&e.test(r.prop))return t(r,n)}):this.walk((r,n)=>{if("decl"===r.type&&r.prop===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("decl"===e.type)return t(e,r)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("rule"===r.type&&e.test(r.selector))return t(r,n)}):this.walk((r,n)=>{if("rule"===r.type&&r.selector===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("rule"===e.type)return t(e,r)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Ps.registerParse=e=>{Cs=e},Ps.registerRule=e=>{Es=e},Ps.registerAtRule=e=>{Ts=e},Ps.registerRoot=e=>{ks=e};var Ls=Ps;Ps.default=Ps,Ps.rebuild=e=>{"atrule"===e.type?Object.setPrototypeOf(e,Ts.prototype):"rule"===e.type?Object.setPrototypeOf(e,Es.prototype):"decl"===e.type?Object.setPrototypeOf(e,As.prototype):"comment"===e.type?Object.setPrototypeOf(e,Is.prototype):"root"===e.type&&Object.setPrototypeOf(e,ks.prototype),e[Os]=!0,e.nodes&&e.nodes.forEach(e=>{Ps.rebuild(e)})};let Ds,Us,Fs=Ls,Bs=class extends Fs{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new Ds(new Us,this,e).stringify()}};Bs.registerLazyResult=e=>{Ds=e},Bs.registerProcessor=e=>{Us=e};var js=Bs;Bs.default=Bs;let zs={};var Vs=function(e){zs[e]||(zs[e]=!0,"undefined"!=typeof console&&console.warn&&console.warn(e))};let Gs=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let e=t.node.rangeBy(t);this.line=e.start.line,this.column=e.start.column,this.endLine=e.end.line,this.endColumn=e.end.column}for(let e in t)this[e]=t[e]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var Hs=Gs;Gs.default=Gs;let Zs=Hs,$s=class{constructor(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let r=new Zs(e,t);return this.messages.push(r),r}warnings(){return this.messages.filter(e=>"warning"===e.type)}get content(){return this.css}};var Ws=$s;$s.default=$s;const Ys="'".charCodeAt(0),Xs='"'.charCodeAt(0),Js="\\".charCodeAt(0),Ks="/".charCodeAt(0),qs="\n".charCodeAt(0),Qs=" ".charCodeAt(0),ei="\f".charCodeAt(0),ti="\t".charCodeAt(0),ri="\r".charCodeAt(0),ni="[".charCodeAt(0),si="]".charCodeAt(0),ii="(".charCodeAt(0),oi=")".charCodeAt(0),ai="{".charCodeAt(0),li="}".charCodeAt(0),ci=";".charCodeAt(0),ui="*".charCodeAt(0),hi=":".charCodeAt(0),pi="@".charCodeAt(0),di=/[\t\n\f\r "#'()/;[\\\]{}]/g,fi=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,mi=/.[\r\n"'(/\\]/,gi=/[\da-f]/i;let yi=Ls,wi=class extends yi{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};var vi=wi;wi.default=wi,yi.registerAtRule(wi);let bi,_i,Si=Ls,Ci=class extends Si{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,r){let n=super.normalize(e);if(t)if("prepend"===r)this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let e of n)e.raws.before=t.raws.before;return n}removeChild(e,t){let r=this.index(e);return!t&&0===r&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[r].raws.before),super.removeChild(e)}toResult(e={}){return new bi(new _i,this,e).stringify()}};Ci.registerLazyResult=e=>{bi=e},Ci.registerProcessor=e=>{_i=e};var Ei=Ci;Ci.default=Ci,Si.registerRoot(Ci);let Ti={comma:e=>Ti.split(e,[","],!0),space:e=>Ti.split(e,[" ","\n","\t"]),split(e,t,r){let n=[],s="",i=!1,o=0,a=!1,l="",c=!1;for(let r of e)c?c=!1:"\\"===r?c=!0:a?r===l&&(a=!1):'"'===r||"'"===r?(a=!0,l=r):"("===r?o+=1:")"===r?o>0&&(o-=1):0===o&&t.includes(r)&&(i=!0),i?(""!==s&&n.push(s.trim()),s="",i=!1):s+=r;return(r||""!==s)&&n.push(s.trim()),n}};var ki=Ti;Ti.default=Ti;let xi=Ls,Oi=ki,Ai=class extends xi{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Oi.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,r=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(r)}};var Ii=Ai;Ai.default=Ai,xi.registerRule(Ai);let Ri=Fn,Mi=function(e,t={}){let r,n,s,i,o,a,l,c,u,h,p=e.css.valueOf(),d=t.ignoreErrors,f=p.length,m=0,g=[],y=[];function w(t){throw e.error("Unclosed "+t,m)}return{back:function(e){y.push(e)},endOfFile:function(){return 0===y.length&&m>=f},nextToken:function(e){if(y.length)return y.pop();if(m>=f)return;let t=!!e&&e.ignoreUnclosed;switch(r=p.charCodeAt(m),r){case qs:case Qs:case ti:case ri:case ei:n=m;do{n+=1,r=p.charCodeAt(n)}while(r===Qs||r===qs||r===ti||r===ri||r===ei);h=["space",p.slice(m,n)],m=n-1;break;case ni:case si:case ai:case li:case hi:case ci:case oi:{let e=String.fromCharCode(r);h=[e,e,m];break}case ii:if(c=g.length?g.pop()[1]:"",u=p.charCodeAt(m+1),"url"===c&&u!==Ys&&u!==Xs&&u!==Qs&&u!==qs&&u!==ti&&u!==ei&&u!==ri){n=m;do{if(a=!1,n=p.indexOf(")",n+1),-1===n){if(d||t){n=m;break}w("bracket")}for(l=n;p.charCodeAt(l-1)===Js;)l-=1,a=!a}while(a);h=["brackets",p.slice(m,n+1),m,n],m=n}else n=p.indexOf(")",m+1),i=p.slice(m,n+1),-1===n||mi.test(i)?h=["(","(",m]:(h=["brackets",i,m,n],m=n);break;case Ys:case Xs:s=r===Ys?"'":'"',n=m;do{if(a=!1,n=p.indexOf(s,n+1),-1===n){if(d||t){n=m+1;break}w("string")}for(l=n;p.charCodeAt(l-1)===Js;)l-=1,a=!a}while(a);h=["string",p.slice(m,n+1),m,n],m=n;break;case pi:di.lastIndex=m+1,di.test(p),n=0===di.lastIndex?p.length-1:di.lastIndex-2,h=["at-word",p.slice(m,n+1),m,n],m=n;break;case Js:for(n=m,o=!0;p.charCodeAt(n+1)===Js;)n+=1,o=!o;if(r=p.charCodeAt(n+1),o&&r!==Ks&&r!==Qs&&r!==qs&&r!==ti&&r!==ri&&r!==ei&&(n+=1,gi.test(p.charAt(n)))){for(;gi.test(p.charAt(n+1));)n+=1;p.charCodeAt(n+1)===Qs&&(n+=1)}h=["word",p.slice(m,n+1),m,n],m=n;break;default:r===Ks&&p.charCodeAt(m+1)===ui?(n=p.indexOf("*/",m+2)+1,0===n&&(d||t?n=p.length:w("comment")),h=["comment",p.slice(m,n+1),m,n],m=n):(fi.lastIndex=m+1,fi.test(p),n=0===fi.lastIndex?p.length-1:fi.lastIndex-2,h=["word",p.slice(m,n+1),m,n],g.push(h),m=n)}return m++,h},position:function(){return m}}},Ni=Ss,Pi=vi,Li=Ei,Di=Ii;const Ui={empty:!0,space:!0};var Fi=class{constructor(e){this.input=e,this.root=new Li,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t,r,n,s=new Pi;s.name=e[1].slice(1),""===s.name&&this.unnamedAtrule(s,e),this.init(s,e[2]);let i=!1,o=!1,a=[],l=[];for(;!this.tokenizer.endOfFile();){if(t=(e=this.tokenizer.nextToken())[0],"("===t||"["===t?l.push("("===t?")":"]"):"{"===t&&l.length>0?l.push("}"):t===l[l.length-1]&&l.pop(),0===l.length){if(";"===t){s.source.end=this.getPosition(e[2]),s.source.end.offset++,this.semicolon=!0;break}if("{"===t){o=!0;break}if("}"===t){if(a.length>0){for(n=a.length-1,r=a[n];r&&"space"===r[0];)r=a[--n];r&&(s.source.end=this.getPosition(r[3]||r[2]),s.source.end.offset++)}this.end(e);break}a.push(e)}else a.push(e);if(this.tokenizer.endOfFile()){i=!0;break}}s.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(s.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(s,"params",a),i&&(e=a[a.length-1],s.source.end=this.getPosition(e[3]||e[2]),s.source.end.offset++,this.spaces=s.raws.between,s.raws.between="")):(s.raws.afterName="",s.params=""),o&&(s.nodes=[],this.current=s)}checkMissedSemicolon(e){let t=this.colon(e);if(!1===t)return;let r,n=0;for(let s=t-1;s>=0&&(r=e[s],"space"===r[0]||(n+=1,2!==n));s--);throw this.input.error("Missed semicolon","word"===r[0]?r[3]+1:r[2])}colon(e){let t,r,n,s=0;for(let[i,o]of e.entries()){if(t=o,r=t[0],"("===r&&(s+=1),")"===r&&(s-=1),0===s&&":"===r){if(n){if("word"===n[0]&&"progid"===n[1])continue;return i}this.doubleColon(t)}n=t}return!1}comment(e){let t=new Ni;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let r=e[1].slice(2,-2);if(/^\s*$/.test(r))t.text="",t.raws.left=r,t.raws.right="";else{let e=r.match(/^(\s*)([^]*\S)(\s*)$/);t.text=e[2],t.raws.left=e[1],t.raws.right=e[3]}}createTokenizer(){this.tokenizer=Mi(this.input)}decl(e,t){let r=new Ri;this.init(r,e[0][2]);let n,s=e[e.length-1];for(";"===s[0]&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(s[3]||s[2]||function(e){for(let t=e.length-1;t>=0;t--){let r=e[t],n=r[3]||r[2];if(n)return n}}(e)),r.source.end.offset++;"word"!==e[0][0];)1===e.length&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop="";e.length;){let t=e[0][0];if(":"===t||"space"===t||"comment"===t)break;r.prop+=e.shift()[1]}for(r.raws.between="";e.length;){if(n=e.shift(),":"===n[0]){r.raws.between+=n[1];break}"word"===n[0]&&/\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1]}"_"!==r.prop[0]&&"*"!==r.prop[0]||(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));let i,o=[];for(;e.length&&(i=e[0][0],"space"===i||"comment"===i);)o.push(e.shift());this.precheckMissedSemicolon(e);for(let t=e.length-1;t>=0;t--){if(n=e[t],"!important"===n[1].toLowerCase()){r.important=!0;let n=this.stringFrom(e,t);n=this.spacesFromEnd(e)+n," !important"!==n&&(r.raws.important=n);break}if("important"===n[1].toLowerCase()){let n=e.slice(0),s="";for(let e=t;e>0;e--){let t=n[e][0];if(0===s.trim().indexOf("!")&&"space"!==t)break;s=n.pop()[1]+s}0===s.trim().indexOf("!")&&(r.important=!0,r.raws.important=s,e=n)}if("space"!==n[0]&&"comment"!==n[0])break}e.some(e=>"space"!==e[0]&&"comment"!==e[0])&&(r.raws.between+=o.map(e=>e[1]).join(""),o=[]),this.raw(r,"value",o.concat(e),t),r.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new Di;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let e=this.current.nodes[this.current.nodes.length-1];e&&"rule"===e.type&&!e.raws.ownSemicolon&&(e.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="","comment"!==e.type&&(this.semicolon=!1)}other(e){let t=!1,r=null,n=!1,s=null,i=[],o=e[1].startsWith("--"),a=[],l=e;for(;l;){if(r=l[0],a.push(l),"("===r||"["===r)s||(s=l),i.push("("===r?")":"]");else if(o&&n&&"{"===r)s||(s=l),i.push("}");else if(0===i.length){if(";"===r){if(n)return void this.decl(a,o);break}if("{"===r)return void this.rule(a);if("}"===r){this.tokenizer.back(a.pop()),t=!0;break}":"===r&&(n=!0)}else r===i[i.length-1]&&(i.pop(),0===i.length&&(s=null));l=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),i.length>0&&this.unclosedBracket(s),t&&n){if(!o)for(;a.length&&(l=a[a.length-1][0],"space"===l||"comment"===l);)this.tokenizer.back(a.pop());this.decl(a,o)}else this.unknownWord(a)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e)}this.endFile()}precheckMissedSemicolon(){}raw(e,t,r,n){let s,i,o,a,l=r.length,c="",u=!0;for(let e=0;ee+t[1],"");e.raws[t]={raw:n,value:c}}e[t]=c}rule(e){e.pop();let t=new Di;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t||"comment"===t);)r=e.pop()[1]+r;return r}spacesAndCommentsFromStart(e){let t,r="";for(;e.length&&(t=e[0][0],"space"===t||"comment"===t);)r+=e.shift()[1];return r}spacesFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t);)r=e.pop()[1]+r;return r}stringFrom(e,t){let r="";for(let n=t;noo(e)),e}let ao={},lo=class e{constructor(t,r,n){let s;if(this.stringified=!1,this.processed=!1,"object"!=typeof r||null===r||"root"!==r.type&&"document"!==r.type)if(r instanceof e||r instanceof Ki)s=oo(r.root),r.map&&(void 0===n.map&&(n.map={}),n.map.inline||(n.map.inline=!1),n.map.prev=r.map);else{let e=qi;n.syntax&&(e=n.syntax.parse),n.parser&&(e=n.parser),e.parse&&(e=e.parse);try{s=e(r,n)}catch(e){this.processed=!0,this.error=e}s&&!s[Zi]&&Yi.rebuild(s)}else s=oo(r);this.result=new Ki(t,s,n),this.helpers={...ao,postcss:ao,result:this.result},this.plugins=this.processor.plugins.map(e=>"object"==typeof e&&e.prepare?{...e,...e.prepare(this.result)}:e)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let r=this.result.lastPlugin;try{if(t&&t.addToError(e),this.error=e,"CssSyntaxError"!==e.name||e.plugin){if(r.postcssVersion&&"production"!==process.env.NODE_ENV){let e=r.postcssPlugin,t=r.postcssVersion,n=this.result.processor.version,s=t.split("."),i=n.split(".");(s[0]!==i[0]||parseInt(s[1])>parseInt(i[1]))&&console.error("Unknown error from PostCSS plugin. Your current PostCSS version is "+n+", but "+e+" uses "+t+". Perhaps this is the source of the error below.")}}else e.plugin=r.postcssPlugin,e.setMessage()}catch(e){console&&console.error&&console.error(e)}return e}prepareVisitors(){this.listeners={};let e=(e,t,r)=>{this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push([e,r])};for(let t of this.plugins)if("object"==typeof t)for(let r in t){if(!to[r]&&/^[A-Z]/.test(r))throw new Error(`Unknown event ${r} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!ro[r])if("object"==typeof t[r])for(let n in t[r])e(t,"*"===n?r:r+"-"+n.toLowerCase(),t[r][n]);else"function"==typeof t[r]&&e(t,r,t[r])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e0;){let e=this.visitTick(t);if(no(e))try{await e}catch(e){let r=t[t.length-1].node;throw this.handleError(e,r)}}}if(this.listeners.OnceExit)for(let[t,r]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if("document"===e.type){let t=e.nodes.map(e=>r(e,this.helpers));await Promise.all(t)}else await r(e,this.helpers)}catch(e){throw this.handleError(e)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if("object"==typeof e&&e.Once){if("document"===this.result.root.type){let t=this.result.root.nodes.map(t=>e.Once(t,this.helpers));return no(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}if("function"==typeof e)return e(this.result.root,this.result)}catch(e){throw this.handleError(e)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=Wi;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new $i(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){if(no(this.runOnRoot(e)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[Hi];)e[Hi]=!0,this.walkSync(e);if(this.listeners.OnceExit)if("document"===e.type)for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this.opts||Ji("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[r,n]of e){let e;this.result.lastPlugin=r;try{e=n(t,this.helpers)}catch(e){throw this.handleError(e,t.proxyOf)}if("root"!==t.type&&"document"!==t.type&&!t.parent)return!0;if(no(e))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:r,visitors:n}=t;if("root"!==r.type&&"document"!==r.type&&!r.parent)return void e.pop();if(n.length>0&&t.visitorIndex{e[Hi]||this.walkSync(e)});else{let t=this.listeners[r];if(t&&this.visitSync(t,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};lo.registerPostcss=e=>{ao=e};var co=lo;lo.default=lo,Qi.registerLazyResult(lo),Xi.registerLazyResult(lo);let uo=vs,ho=xn,po=Vs,fo=Gi;const mo=Ws;let go=class{constructor(e,t,r){let n;t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;let s=ho;this.result=new mo(this._processor,n,this._opts),this.result.css=t;let i=this;Object.defineProperty(this.result,"root",{get:()=>i.root});let o=new uo(s,n,this._opts,t);if(o.isMap()){let[e,t]=o.generate();e&&(this.result.css=e),t&&(this.result.map=t)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this._opts||po("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=fo;try{e=t(this._css,this._opts)}catch(e){this.error=e}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}};var yo=go;go.default=go;let wo=yo,vo=co,bo=js,_o=Ei,So=class{constructor(e=[]){this.version="8.4.38",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let r of e)if(!0===r.postcss?r=r():r.postcss&&(r=r.postcss),"object"==typeof r&&Array.isArray(r.plugins))t=t.concat(r.plugins);else if("object"==typeof r&&r.postcssPlugin)t.push(r);else if("function"==typeof r)t.push(r);else{if("object"!=typeof r||!r.parse&&!r.stringify)throw new Error(r+" is not a PostCSS plugin");if("production"!==process.env.NODE_ENV)throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.")}return t}process(e,t={}){return this.plugins.length||t.parser||t.stringifier||t.syntax?new vo(this,e,t):new wo(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};var Co=So;So.default=So,_o.registerProcessor(So),bo.registerProcessor(So);let Eo=Fn,To=Wn,ko=Ss,xo=vi,Oo=ls,Ao=Ei,Io=Ii;function Ro(e,t){if(Array.isArray(e))return e.map(e=>Ro(e));let{inputs:r,...n}=e;if(r){t=[];for(let e of r){let r={...e,__proto__:Oo.prototype};r.map&&(r.map={...r.map,__proto__:To.prototype}),t.push(r)}}if(n.nodes&&(n.nodes=e.nodes.map(e=>Ro(e,t))),n.source){let{inputId:e,...r}=n.source;n.source=r,null!=e&&(n.source.input=t[e])}if("root"===n.type)return new Ao(n);if("decl"===n.type)return new Eo(n);if("rule"===n.type)return new Io(n);if("comment"===n.type)return new ko(n);if("atrule"===n.type)return new xo(n);throw new Error("Unknown node type: "+e.type)}var Mo=Ro;Ro.default=Ro;let No=bn,Po=Fn,Lo=co,Do=Ls,Uo=Co,Fo=xn,Bo=Mo,jo=js,zo=Hs,Vo=Ss,Go=vi,Ho=Ws,Zo=ls,$o=Gi,Wo=ki,Yo=Ii,Xo=Ei,Jo=Ln;function Ko(...e){return 1===e.length&&Array.isArray(e[0])&&(e=e[0]),new Uo(e)}Ko.plugin=function(e,t){let r,n=!1;function s(...r){console&&console.warn&&!n&&(n=!0,console.warn(e+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226"));let s=t(...r);return s.postcssPlugin=e,s.postcssVersion=(new Uo).version,s}return Object.defineProperty(s,"postcss",{get:()=>(r||(r=s()),r)}),s.process=function(e,t,r){return Ko([s(r)]).process(e,t)},s},Ko.stringify=Fo,Ko.parse=$o,Ko.fromJSON=Bo,Ko.list=Wo,Ko.comment=e=>new Vo(e),Ko.atRule=e=>new Go(e),Ko.decl=e=>new Po(e),Ko.rule=e=>new Yo(e),Ko.root=e=>new Xo(e),Ko.document=e=>new jo(e),Ko.CssSyntaxError=No,Ko.Declaration=Po,Ko.Container=Do,Ko.Processor=Uo,Ko.Document=jo,Ko.Comment=Vo,Ko.Warning=zo,Ko.AtRule=Go,Ko.Result=Ho,Ko.Input=Zo,Ko.Rule=Yo,Ko.Root=Xo,Ko.Node=Jo,Lo.registerPostcss(Ko);var qo=Ko;Ko.default=Ko;const Qo=un(qo);Qo.stringify,Qo.fromJSON,Qo.plugin,Qo.parse,Qo.list,Qo.document,Qo.comment,Qo.atRule,Qo.rule,Qo.decl,Qo.root,Qo.CssSyntaxError,Qo.Declaration,Qo.Container,Qo.Processor,Qo.Document,Qo.Comment,Qo.Warning,Qo.AtRule,Qo.Result,Qo.Input,Qo.Rule,Qo.Root,Qo.Node;let ea=class e{constructor(...e){cn(this,"parentElement",null),cn(this,"parentNode",null),cn(this,"ownerDocument"),cn(this,"firstChild",null),cn(this,"lastChild",null),cn(this,"previousSibling",null),cn(this,"nextSibling",null),cn(this,"ELEMENT_NODE",1),cn(this,"TEXT_NODE",3),cn(this,"nodeType"),cn(this,"nodeName"),cn(this,"RRNodeType")}get childNodes(){const e=[];let t=this.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}contains(t){if(!(t instanceof e))return!1;if(t.ownerDocument!==this.ownerDocument)return!1;if(t===this)return!0;for(;t.parentNode;){if(t.parentNode===this)return!0;t=t.parentNode}return!1}appendChild(e){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(e,t){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(e){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}};const ta={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},ra={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},na={};function sa(e){if(na[e])return na[e];const t=globalThis[e],r=t.prototype,n=e in ta?ta[e]:void 0,s=Boolean(n&&n.every(e=>{var t,n;return Boolean(null==(n=null==(t=Object.getOwnPropertyDescriptor(r,e))?void 0:t.get)?void 0:n.toString().includes("[native code]"))})),i=e in ra?ra[e]:void 0,o=Boolean(i&&i.every(e=>{var t;return"function"==typeof r[e]&&(null==(t=r[e])?void 0:t.toString().includes("[native code]"))}));if(s&&o&&!globalThis.Zone)return na[e]=t.prototype,t.prototype;try{const n=document.createElement("iframe");document.body.appendChild(n);const s=n.contentWindow;if(!s)return t.prototype;const i=s[e].prototype;return document.body.removeChild(n),i?na[e]=i:r}catch{return r}}const ia={};function oa(e,t,r){var n;const s=`${e}.${String(r)}`;if(ia[s])return ia[s].call(t);const i=sa(e),o=null==(n=Object.getOwnPropertyDescriptor(i,r))?void 0:n.get;return o?(ia[s]=o,o.call(t)):t[r]}const aa={};function la(e,t,r){const n=`${e}.${String(r)}`;if(aa[n])return aa[n].bind(t);const s=sa(e)[r];return"function"!=typeof s?t[r]:(aa[n]=s,s.bind(t))}const ca={childNodes:function(e){return oa("Node",e,"childNodes")},parentNode:function(e){return oa("Node",e,"parentNode")},parentElement:function(e){return oa("Node",e,"parentElement")},textContent:function(e){return oa("Node",e,"textContent")},contains:function(e,t){return la("Node",e,"contains")(t)},getRootNode:function(e){return la("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?oa("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?oa("Element",e,"shadowRoot"):null},querySelector:function(e,t){return oa("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return oa("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return sa("MutationObserver").constructor}};const ua="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";let ha={map:{},getId:()=>(console.error(ua),-1),getNode:()=>(console.error(ua),null),removeNodeFromMap(){console.error(ua)},has:()=>(console.error(ua),!1),reset(){console.error(ua)}};"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(ha=new Proxy(ha,{get:(e,t,r)=>("map"===t&&console.error(ua),Reflect.get(e,t,r))}));let pa=Date.now;function da(e){if(!e)return null;return e.nodeType===e.ELEMENT_NODE?e:ca.parentElement(e)}/[1-9][0-9]{12}/.test(Date.now().toString())||(pa=()=>(new Date).getTime());function fa(e){var t;let r=null;return"getRootNode"in e&&(null==(t=ca.getRootNode(e))?void 0:t.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&ca.host(ca.getRootNode(e))&&(r=ca.host(ca.getRootNode(e))),r}function ma(e){let t,r=e;for(;t=fa(r);)r=t;return r}function ga(e){const t=e.ownerDocument;if(!t)return!1;const r=ma(e);return ca.contains(t,r)}const ya=Object.freeze(Object.defineProperty({__proto__:null,StyleSheetMirror:class{constructor(){s(this,"id",1),s(this,"styleIDMap",new WeakMap),s(this,"idStyleMap",new Map)}getId(e){return this.styleIDMap.get(e)??-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let r;return r=void 0===t?this.id++:t,this.styleIDMap.set(e,r),this.idStyleMap.set(r,e),r}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}},get _mirror(){return ha},closestElementOfNode:da,getBaseDimension:function e(t,r){var n,s;const i=null==(s=null==(n=t.ownerDocument)?void 0:n.defaultView)?void 0:s.frameElement;if(!i||i===r)return{x:0,y:0,relativeScale:1,absoluteScale:1};const o=i.getBoundingClientRect(),a=e(i,r),l=o.height/i.clientHeight;return{x:o.x*a.relativeScale+a.x,y:o.y*a.relativeScale+a.y,relativeScale:l,absoluteScale:a.absoluteScale*l}},getNestedRule:function e(t,r){const n=t[r[0]];return 1===r.length?n:e(n.cssRules[r[1]].cssRules,r.slice(2))},getPositionsAndIndex:function(e){const t=[...e],r=t.pop();return{positions:t,index:r}},getRootShadowHost:ma,getShadowHost:fa,getWindowHeight:function(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight},getWindowScroll:function(e){var t,r,n,s;const i=e.document;return{left:i.scrollingElement?i.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:i.documentElement.scrollLeft||(null==i?void 0:i.body)&&(null==(t=ca.parentElement(i.body))?void 0:t.scrollLeft)||(null==(r=null==i?void 0:i.body)?void 0:r.scrollLeft)||0,top:i.scrollingElement?i.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==i?void 0:i.documentElement.scrollTop)||(null==i?void 0:i.body)&&(null==(n=ca.parentElement(i.body))?void 0:n.scrollTop)||(null==(s=null==i?void 0:i.body)?void 0:s.scrollTop)||0}},getWindowWidth:function(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth},hasShadowRoot:function(e){return!!e&&(e instanceof ea&&"shadowRoot"in e?Boolean(e.shadowRoot):Boolean(ca.shadowRoot(e)))},hookSetter:function e(t,r,n,s,i=window){const o=i.Object.getOwnPropertyDescriptor(t,r);return i.Object.defineProperty(t,r,s?n:{set(e){setTimeout(()=>{n.set.call(this,e)},0),o&&o.set&&o.set.call(this,e)}}),()=>e(t,r,o||{},!0)},inDom:function(e){const t=e.ownerDocument;return!!t&&(ca.contains(t,e)||ga(e))},isAncestorRemoved:function e(t,r){if(function(e){const t=e&&"host"in e&&"mode"in e&&m.host(e)||null;return Boolean(t&&"shadowRoot"in t&&m.shadowRoot(t)===e)}(t))return!1;const n=r.getId(t);if(!r.has(n))return!0;const s=ca.parentNode(t);return(!s||s.nodeType!==t.DOCUMENT_NODE)&&(!s||e(s,r))},isBlocked:function(e,t,r,n){if(!e)return!1;const s=da(e);if(!s)return!1;try{if("string"==typeof t){if(s.classList.contains(t))return!0;if(n&&null!==s.closest("."+t))return!0}else if(y(s,t,n))return!0}catch(e){}if(r){if(s.matches(r))return!0;if(n&&null!==s.closest(r))return!0}return!1},isIgnored:function(e,t,r){return!("TITLE"!==e.tagName||!r.headTitleMutations)||-2===t.getId(e)},isSerialized:function(e,t){return-1!==t.getId(e)},isSerializedIframe:function(e,t){return Boolean("IFRAME"===e.nodeName&&t.getMeta(e))},isSerializedStylesheet:function(e,t){return Boolean("LINK"===e.nodeName&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&"stylesheet"===e.getAttribute("rel")&&t.getMeta(e))},iterateResolveTree:function e(t,r){r(t.value);for(let n=t.children.length-1;n>=0;n--)e(t.children[n],r)},legacy_isTouchEvent:function(e){return Boolean(e.changedTouches)},get nowTimestamp(){return pa},on:function(e,t,r=document){const n={capture:!0,passive:!0};return r.addEventListener(e,t,n),()=>r.removeEventListener(e,t,n)},patch:function(e,t,r){try{if(!(t in e))return()=>{};const n=e[t],s=r(n);return"function"==typeof s&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__rrweb_original__:{enumerable:!1,value:n}})),e[t]=s,()=>{e[t]=n}}catch{return()=>{}}},polyfill:function(e=window){"NodeList"in e&&!e.NodeList.prototype.forEach&&(e.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in e&&!e.DOMTokenList.prototype.forEach&&(e.DOMTokenList.prototype.forEach=Array.prototype.forEach)},queueToResolveTrees:function(e){const t={},r=(e,r)=>{const n={value:e,parent:r,children:[]};return t[e.node.id]=n,n},n=[];for(const s of e){const{nextId:e,parentId:i}=s;if(e&&e in t){const i=t[e];if(i.parent){const e=i.parent.children.indexOf(i);i.parent.children.splice(e,0,r(s,i.parent))}else{const e=n.indexOf(i);n.splice(e,0,r(s,null))}continue}if(i in t){const e=t[i];e.children.push(r(s,e));continue}n.push(r(s,null))}return n},shadowHostInDom:ga,throttle:function(e,t,r={}){let n=null,s=0;return function(...i){const o=Date.now();s||!1!==r.leading||(s=o);const a=t-(o-s),l=this;a<=0||a>t?(n&&(clearTimeout(n),n=null),s=o,e.apply(l,i)):n||!1===r.trailing||(n=setTimeout(()=>{s=!1===r.leading?0:Date.now(),n=null,e.apply(l,i)},a))}},uniqueTextMutations:function(e){const t=new Set,r=[];for(let n=e.length;n--;){const s=e[n];t.has(s.id)||(r.push(s),t.add(s.id))}return r}},Symbol.toStringTag,{value:"Module"}));for(var wa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",va="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ba=0;ba<64;ba++)va[wa.charCodeAt(ba)]=ba;var _a,Sa,Ca;"undefined"!=typeof window&&window.Blob&&new Blob([(_a="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",Uint8Array.from(atob(_a),e=>e.charCodeAt(0)))],{type:"text/javascript;charset=utf-8"});try{if(2!==Array.from([1],e=>2*e)[0]){const t=document.createElement("iframe");document.body.appendChild(t),Array.from=(null==(e=t.contentWindow)?void 0:e.Array.from)||Array.from,document.body.removeChild(t)}}catch(e){console.debug("Unable to override Array.from",e)}new g,(Ca=Sa||(Sa={}))[Ca.NotStarted=0]="NotStarted",Ca[Ca.Running=1]="Running",Ca[Ca.Stopped=2]="Stopped";class Ea{constructor(e){r(this,"fileName"),r(this,"functionName"),r(this,"lineNumber"),r(this,"columnNumber"),this.fileName=e.fileName||"",this.functionName=e.functionName||"",this.lineNumber=e.lineNumber,this.columnNumber=e.columnNumber}toString(){const e=this.lineNumber||"",t=this.columnNumber||"";return this.functionName?`${this.functionName} (${this.fileName}:${e}:${t})`:`${this.fileName}:${e}:${t}`}}const Ta=/(^|@)\S+:\d+/,ka=/^\s*at .*(\S+:\d+|\(native\))/m,xa=/^(eval@)?(\[native code])?$/,Oa={parse:function(e){return e?void 0!==e.stacktrace||void 0!==e["opera#sourceloc"]?this.parseOpera(e):e.stack&&e.stack.match(ka)?this.parseV8OrIE(e):e.stack?this.parseFFOrSafari(e):(console.warn("[console-record-plugin]: Failed to parse error object:",e),[]):[]},extractLocation:function(e){if(-1===e.indexOf(":"))return[e];const t=/(.+?)(?::(\d+))?(?::(\d+))?$/.exec(e.replace(/[()]/g,""));if(!t)throw new Error(`Cannot parse given url: ${e}`);return[t[1],t[2]||void 0,t[3]||void 0]},parseV8OrIE:function(e){return e.stack.split("\n").filter(function(e){return!!e.match(ka)},this).map(function(e){e.indexOf("(eval ")>-1&&(e=e.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(\),.*$)/g,""));let t=e.replace(/^\s+/,"").replace(/\(eval code/g,"(");const r=t.match(/ (\((.+):(\d+):(\d+)\)$)/);t=r?t.replace(r[0],""):t;const n=t.split(/\s+/).slice(1),s=this.extractLocation(r?r[1]:n.pop()),i=n.join(" ")||void 0,o=["eval",""].indexOf(s[0])>-1?void 0:s[0];return new Ea({functionName:i,fileName:o,lineNumber:s[1],columnNumber:s[2]})},this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter(function(e){return!e.match(xa)},this).map(function(e){if(e.indexOf(" > eval")>-1&&(e=e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===e.indexOf("@")&&-1===e.indexOf(":"))return new Ea({functionName:e});{const t=/((.*".+"[^@]*)?[^@]*)(?:@)/,r=e.match(t),n=r&&r[1]?r[1]:void 0,s=this.extractLocation(e.replace(t,""));return new Ea({functionName:n,fileName:s[0],lineNumber:s[1],columnNumber:s[2]})}},this)},parseOpera:function(e){return!e.stacktrace||e.message.indexOf("\n")>-1&&e.message.split("\n").length>e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){const t=/Line (\d+).*script (?:in )?(\S+)/i,r=e.message.split("\n"),n=[];for(let e=2,s=r.length;e/,"$2").replace(/\([^)]*\)/g,"")||void 0;return new Ea({functionName:n,fileName:r[0],lineNumber:r[1],columnNumber:r[2]})},this)}};function Aa(e){if(!e||!e.outerHTML)return"";let t="";for(;e.parentElement;){let r=e.localName;if(!r)break;r=r.toLowerCase();const n=e.parentElement,s=[];if(n.children&&n.children.length>0)for(let e=0;e1&&(r+=`:eq(${s.indexOf(e)})`),t=r+(t?">"+t:""),e=n}return t}function Ia(e){return"[object Object]"===Object.prototype.toString.call(e)}function Ra(e,t){if(0===t)return!0;const r=Object.keys(e);for(const n of r)if(Ia(e[n])&&Ra(e[n],t-1))return!0;return!1}function Ma(e,t){const r={numOfKeysLimit:50,depthOfLimit:4};Object.assign(r,t);const n=[],s=[];return JSON.stringify(e,function(e,t){if(n.length>0){const r=n.indexOf(this);~r?n.splice(r+1):n.push(this),~r?s.splice(r,1/0,e):s.push(e),~n.indexOf(t)&&(t=n[0]===t?"[Circular ~]":"[Circular ~."+s.slice(0,n.indexOf(t)).join(".")+"]")}else n.push(t);if(null===t)return t;if(void 0===t)return"undefined";if(function(e){if(Ia(e)&&Object.keys(e).length>r.numOfKeysLimit)return!0;if("function"==typeof e)return!0;if(Ia(e)&&Ra(e,r.depthOfLimit))return!0;return!1}(t))return function(e){let t=e.toString();r.stringLengthLimit&&t.length>r.stringLengthLimit&&(t=`${t.slice(0,r.stringLengthLimit)}...`);return t}(t);if("bigint"==typeof t)return t.toString()+"n";if(t instanceof Event){const e={};for(const r in t){const n=t[r];Array.isArray(n)?e[r]=Aa(n.length?n[0]:null):e[r]=n}return e}return t instanceof Node?t instanceof HTMLElement?t?t.outerHTML:"":t.nodeName:t instanceof Error?t.stack?t.stack+"\nEnd of stack for Error object":t.name+": "+t.message:t})}const Na={level:["assert","clear","count","countReset","debug","dir","dirxml","error","group","groupCollapsed","groupEnd","info","log","table","time","timeEnd","timeLog","trace","warn"],lengthThreshold:1e3,logger:"console"};function Pa(e,t,r){const n=r?Object.assign({},Na,r):Na,s=n.logger;if(!s)return()=>{};let i;i="string"==typeof s?t[s]:s;let o=0,a=!1;const l=[];if(n.level.includes("error")){const r=t=>{const r=t.message,s=t.error,i=Oa.parse(s).map(e=>e.toString()),o=[Ma(r,n.stringifyOptions)];e({level:"error",trace:i,payload:o})};t.addEventListener("error",r),l.push(()=>{t.removeEventListener("error",r)});const s=t=>{let r,s;t.reason instanceof Error?(r=t.reason,s=[Ma(`Uncaught (in promise) ${r.name}: ${r.message}`,n.stringifyOptions)]):(r=new Error,s=[Ma("Uncaught (in promise)",n.stringifyOptions),Ma(t.reason,n.stringifyOptions)]);const i=Oa.parse(r).map(e=>e.toString());e({level:"error",trace:i,payload:s})};t.addEventListener("unhandledrejection",s),l.push(()=>{t.removeEventListener("unhandledrejection",s)})}for(const e of n.level)l.push(c(i,e));return()=>{l.forEach(e=>e())};function c(t,r){return t[r]?ya.patch(t,r,t=>(...s)=>{if(t.apply(this,s),!("assert"===r&&s[0]||a)){a=!0;try{const t=Oa.parse(new Error).map(e=>e.toString()).splice(1),i=("assert"===r?s.slice(1):s).map(e=>Ma(e,n.stringifyOptions));o++,o{}}}var La,Da=Object.defineProperty,Ua=(e,t,r)=>((e,t,r)=>t in e?Da(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r),Fa=Object.defineProperty,Ba=(e,t,r)=>((e,t,r)=>t in e?Fa(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r),ja=(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(ja||{});const za={Node:["childNodes","parentNode","parentElement","textContent","ownerDocument"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Va={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Ga={};function Ha(e){if(Ga[e])return Ga[e];const t=globalThis[e],r=t.prototype,n=e in za?za[e]:void 0,s=Boolean(n&&n.every(e=>{var t,n;return Boolean(null==(n=null==(t=Object.getOwnPropertyDescriptor(r,e))?void 0:t.get)?void 0:n.toString().includes("[native code]"))})),i=e in Va?Va[e]:void 0,o=Boolean(i&&i.every(e=>{var t;return"function"==typeof r[e]&&(null==(t=r[e])?void 0:t.toString().includes("[native code]"))}));if(s&&o&&!globalThis.Zone)return Ga[e]=t.prototype,t.prototype;try{const n=document.createElement("iframe");document.body.appendChild(n);const s=n.contentWindow;if(!s)return t.prototype;const i=s[e].prototype;return document.body.removeChild(n),i?Ga[e]=i:r}catch{return r}}const Za={};function $a(e,t,r){var n;const s=`${e}.${String(r)}`;if(Za[s])return Za[s].call(t);const i=Ha(e),o=null==(n=Object.getOwnPropertyDescriptor(i,r))?void 0:n.get;return o?(Za[s]=o,o.call(t)):t[r]}const Wa={};function Ya(e,t,r){const n=`${e}.${String(r)}`;if(Wa[n])return Wa[n].bind(t);const s=Ha(e)[r];return"function"!=typeof s?t[r]:(Wa[n]=s,s.bind(t))}const Xa={ownerDocument:function(e){return $a("Node",e,"ownerDocument")},childNodes:function(e){return $a("Node",e,"childNodes")},parentNode:function(e){return $a("Node",e,"parentNode")},parentElement:function(e){return $a("Node",e,"parentElement")},textContent:function(e){return $a("Node",e,"textContent")},contains:function(e,t){return Ya("Node",e,"contains")(t)},getRootNode:function(e){return Ya("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?$a("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?$a("Element",e,"shadowRoot"):null},querySelector:function(e,t){return $a("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return $a("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return Ha("MutationObserver").constructor},patch:function(e,t,r){try{if(!(t in e))return()=>{};const n=e[t],s=r(n);return"function"==typeof s&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__rrweb_original__:{enumerable:!1,value:n}})),e[t]=s,()=>{e[t]=n}}catch{return()=>{}}}};function Ja(e){return e.nodeType===e.ELEMENT_NODE}function Ka(e){const t=e&&"host"in e&&"mode"in e&&Xa.host(e)||null;return Boolean(t&&"shadowRoot"in t&&Xa.shadowRoot(t)===e)}function qa(e){return"[object ShadowRoot]"===Object.prototype.toString.call(e)}function Qa(e){try{const r=e.rules||e.cssRules;if(!r)return null;let n=e.href;!n&&e.ownerNode&&(n=e.ownerNode.baseURI);const s=Array.from(r,e=>el(e,n)).join("");return(t=s).includes(" background-clip: text;")&&!t.includes(" -webkit-background-clip: text;")&&(t=t.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),t}catch(e){return null}var t}function el(e,t){if(function(e){return"styleSheet"in e}(e)){let t;try{t=Qa(e.styleSheet)||function(e){const{cssText:t}=e;if(t.split('"').length<3)return t;const r=["@import",`url(${JSON.stringify(e.href)})`];return""===e.layerName?r.push("layer"):e.layerName&&r.push(`layer(${e.layerName})`),e.supportsText&&r.push(`supports(${e.supportsText})`),e.media.length&&r.push(e.media.mediaText),r.join(" ")+";"}(e)}catch(r){t=e.cssText}return e.styleSheet.href?hl(t,e.styleSheet.href):t}{let r=e.cssText;return function(e){return"selectorText"in e}(e)&&e.selectorText.includes(":")&&(r=function(e){const t=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return e.replace(t,"$1\\$2")}(r)),t?hl(r,t):r}}class tl{constructor(){Ba(this,"idNodeMap",new Map),Ba(this,"nodeMetaMap",new WeakMap)}getId(e){var t;if(!e)return-1;return(null==(t=this.getMeta(e))?void 0:t.id)??-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){const t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(e=>this.removeNodeFromMap(e))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){const r=t.id;this.idNodeMap.set(r,e),this.nodeMetaMap.set(e,t)}replace(e,t){const r=this.getNode(e);if(r){const e=this.nodeMetaMap.get(r);e&&this.nodeMetaMap.set(t,e)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}}function rl({element:e,maskInputOptions:t,tagName:r,type:n,value:s,maskInputFn:i}){let o=s||"";const a=n&&nl(n);return(t[r.toLowerCase()]||a&&t[a])&&(o=i?i(o,e):"*".repeat(o.length)),o}function nl(e){return e.toLowerCase()}const sl="__rrweb_original__";function il(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?nl(t):null}function ol(e,t){let r;try{r=new URL(e,t??window.location.href)}catch(e){return null}const n=r.pathname.match(/\.([0-9a-z]+)(?:$)/i);return(null==n?void 0:n[1])??null}const al=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,ll=/^(?:[a-z+]+:)?\/\//i,cl=/^www\..*/i,ul=/^(data:)([^,]*),(.*)/i;function hl(e,t){return(e||"").replace(al,(e,r,n,s,i,o)=>{const a=n||i||o,l=r||s||"";if(!a)return e;if(ll.test(a)||cl.test(a))return`url(${l}${a}${l})`;if(ul.test(a))return`url(${l}${a}${l})`;if("/"===a[0])return`url(${l}${function(e){let t="";return t=e.indexOf("//")>-1?e.split("/").slice(0,3).join("/"):e.split("/")[0],t=t.split("?")[0],t}(t)+a}${l})`;const c=t.split("/"),u=a.split("/");c.pop();for(const e of u)"."!==e&&(".."===e?c.pop():c.push(e));return`url(${l}${c.join("/")}${l})`})}function pl(e,t=!1){return t?e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,""):e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"").replace(/0px/g,"0")}function dl(e,t){return function(e,t,r=!1){const n=Array.from(t.childNodes),s=[];let i=0;if(n.length>1&&e&&"string"==typeof e){let t=pl(e,r);const o=t.length/e.length;for(let a=1;a2&&""===p[0]&&""!==n[a-1].textContent)d=t.indexOf(h,1);else if(1===p.length){if(h=h.substring(0,h.length-1),p=t.split(h),p.length<=1)return s.push(e),s;u=c+1}else u===l.length-1&&(d=t.indexOf(h));if(p.length>=2&&u>c){const e=n[a-1].textContent;if(e&&"string"==typeof e){const r=pl(e).length;d=t.indexOf(h,r)}-1===d&&(d=p[0].length)}if(-1!==d){let a=Math.floor(d/o);for(;a>0&&a50*n.length)return s.push(e),s;const l=pl(e.substring(0,a),r);if(l.length===d){s.push(e.substring(0,a)),e=e.substring(a),t=t.substring(d);break}l.length=t.length);){let i=n(vl);if(","===i.slice(-1))i=Sl(e,i.substring(0,i.length-1)),s.push(i);else{let n="";i=Sl(e,i);let o=!1;for(;;){const e=t.charAt(r);if(""===e){s.push((i+n).trim());break}if(o)")"===e&&(o=!1);else{if(","===e){r+=1,s.push((i+n).trim());break}"("===e&&(o=!0)}n+=e,r+=1}}}return s.join(", ")}(e,n):"style"===r?hl(n,El(e)):"object"===t&&"data"===r?Sl(e,n):n:n}function kl(e,t,r){return["video","audio"].includes(e)&&"autoplay"===t}function xl(e,t,r){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return!!r&&xl(Xa.parentNode(e),t,r);for(let r=e.classList.length;r--;){const n=e.classList[r];if(t.test(n))return!0}return!!r&&xl(Xa.parentNode(e),t,r)}function Ol(e,t,r,n){let s;if(Ja(e)){if(s=e,!Xa.childNodes(s).length)return!1}else{if(null===Xa.parentElement(e))return!1;s=Xa.parentElement(e)}try{if("string"==typeof t){if(n){if(s.closest(`.${t}`))return!0}else if(s.classList.contains(t))return!0}else if(xl(s,t,n))return!0;if(r)if(n){if(s.closest(r))return!0}else if(s.matches(r))return!0}catch(e){}return!1}function Al(e,t){const{doc:r,mirror:n,blockClass:s,blockSelector:i,needsMask:o,inlineStylesheet:a,maskInputOptions:l={},maskTextFn:c,maskInputFn:u,dataURLOptions:h={},inlineImages:p,recordCanvas:d,keepIframeSrcFn:f,newlyAddedElement:m=!1,cssCaptured:g=!1}=t,y=function(e,t){if(!t.hasNode(e))return;const r=t.getId(e);return 1===r?void 0:r}(r,n);switch(e.nodeType){case e.DOCUMENT_NODE:return"CSS1Compat"!==e.compatMode?{type:ja.Document,childNodes:[],compatMode:e.compatMode}:{type:ja.Document,childNodes:[]};case e.DOCUMENT_TYPE_NODE:return{type:ja.DocumentType,name:e.name,publicId:e.publicId,systemId:e.systemId,rootId:y};case e.ELEMENT_NODE:return function(e,t){const{doc:r,blockClass:n,blockSelector:s,inlineStylesheet:i,maskInputOptions:o={},maskInputFn:a,dataURLOptions:l={},inlineImages:c,recordCanvas:u,keepIframeSrcFn:h,newlyAddedElement:p=!1,rootId:d}=t,f=function(e,t,r){try{if("string"==typeof t){if(e.classList.contains(t))return!0}else for(let r=e.classList.length;r--;){const n=e.classList[r];if(t.test(n))return!0}if(r)return e.matches(r)}catch(e){}return!1}(e,n,s),m=function(e){if(e instanceof HTMLFormElement)return"form";const t=nl(e.tagName);return ml.test(t)?"div":t}(e);let g={};const y=e.attributes.length;for(let t=0;tt.href===e.href);let n=null;t&&(n=Qa(t)),n&&(delete g.rel,delete g.href,g._cssText=n)}if("style"===m&&e.sheet){let t=Qa(e.sheet);t&&(e.childNodes.length>1&&(t=dl(t,e)),g._cssText=t)}if(["input","textarea","select"].includes(m)){const t=e.value,r=e.checked;"radio"!==g.type&&"checkbox"!==g.type&&"submit"!==g.type&&"button"!==g.type&&t?g.value=rl({element:e,type:il(e),tagName:m,value:t,maskInputOptions:o,maskInputFn:a}):r&&(g.checked=r)}"option"===m&&(e.selected&&!o.select?g.selected=!0:delete g.selected);"dialog"===m&&e.open&&(g.rr_open_mode=e.matches("dialog:modal")?"modal":"non-modal");if("canvas"===m&&u)if("2d"===e.__context)(function(e){const t=e.getContext("2d");if(!t)return!0;for(let r=0;r0!==e))return!1}return!0})(e)||(g.rr_dataURL=e.toDataURL(l.type,l.quality));else if(!("__context"in e)){const t=e.toDataURL(l.type,l.quality),n=r.createElement("canvas");n.width=e.width,n.height=e.height;t!==n.toDataURL(l.type,l.quality)&&(g.rr_dataURL=t)}if("img"===m&&c){yl||(yl=r.createElement("canvas"),wl=yl.getContext("2d"));const t=e,n=t.currentSrc||t.getAttribute("src")||"",s=t.crossOrigin,i=()=>{t.removeEventListener("load",i);try{yl.width=t.naturalWidth,yl.height=t.naturalHeight,wl.drawImage(t,0,0),g.rr_dataURL=yl.toDataURL(l.type,l.quality)}catch(e){if("anonymous"!==t.crossOrigin)return t.crossOrigin="anonymous",void(t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i));console.warn(`Cannot inline img src=${n}! Error: ${e}`)}"anonymous"===t.crossOrigin&&(s?g.crossOrigin=s:t.removeAttribute("crossorigin"))};t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i)}if(["audio","video"].includes(m)){const t=g;t.rr_mediaState=e.paused?"paused":"played",t.rr_mediaCurrentTime=e.currentTime,t.rr_mediaPlaybackRate=e.playbackRate,t.rr_mediaMuted=e.muted,t.rr_mediaLoop=e.loop,t.rr_mediaVolume=e.volume}p||(e.scrollLeft&&(g.rr_scrollLeft=e.scrollLeft),e.scrollTop&&(g.rr_scrollTop=e.scrollTop));if(f){const{width:t,height:r}=e.getBoundingClientRect();g={class:g.class,rr_width:`${t}px`,rr_height:`${r}px`}}"iframe"!==m||h(g.src)||(e.contentDocument||(g.rr_src=g.src),delete g.src);let w;try{customElements.get(m)&&(w=!0)}catch(e){}return{type:ja.Element,tagName:m,attributes:g,childNodes:[],isSVG:Cl(e)||void 0,needBlock:f,rootId:d,isCustom:w}}(e,{doc:r,blockClass:s,blockSelector:i,inlineStylesheet:a,maskInputOptions:l,maskInputFn:u,dataURLOptions:h,inlineImages:p,recordCanvas:d,keepIframeSrcFn:f,newlyAddedElement:m,rootId:y});case e.TEXT_NODE:return function(e,t){const{needsMask:r,maskTextFn:n,rootId:s,cssCaptured:i}=t,o=Xa.parentNode(e),a=o&&o.tagName;let l="";const c="STYLE"===a||void 0,u="SCRIPT"===a||void 0;u?l="SCRIPT_PLACEHOLDER":i||(l=Xa.textContent(e),c&&l&&(l=hl(l,El(t.doc))));!c&&!u&&l&&r&&(l=n?n(l,Xa.parentElement(e)):l.replace(/[\S]/g,"*"));return{type:ja.Text,textContent:l||"",rootId:s}}(e,{doc:r,needsMask:o,maskTextFn:c,rootId:y,cssCaptured:g});case e.CDATA_SECTION_NODE:return{type:ja.CDATA,textContent:"",rootId:y};case e.COMMENT_NODE:return{type:ja.Comment,textContent:Xa.textContent(e)||"",rootId:y};default:return!1}}function Il(e){return null==e?"":e.toLowerCase()}function Rl(e){return!0===e||"all"===e?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===e,headMetaDescKeywords:"all"===e,headTitleMutations:"all"===e}:e||{}}function Ml(e,t){const{doc:r,mirror:n,blockClass:s,blockSelector:i,maskTextClass:o,maskTextSelector:a,skipChild:l=!1,inlineStylesheet:c=!0,maskInputOptions:u={},maskTextFn:h,maskInputFn:p,slimDOMOptions:d,dataURLOptions:f={},inlineImages:m=!1,recordCanvas:g=!1,onSerialize:y,onIframeLoad:w,iframeLoadTimeout:v=5e3,onStylesheetLoad:b,stylesheetLoadTimeout:_=5e3,keepIframeSrcFn:S=()=>!1,newlyAddedElement:C=!1,cssCaptured:E=!1}=t;let{needsMask:T}=t,{preserveWhiteSpace:k=!0}=t;if(!T){T=Ol(e,o,a,void 0===T)}const x=Al(e,{doc:r,mirror:n,blockClass:s,blockSelector:i,needsMask:T,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,dataURLOptions:f,inlineImages:m,recordCanvas:g,keepIframeSrcFn:S,newlyAddedElement:C,cssCaptured:E});if(!x)return console.warn(e,"not serialized"),null;let O;O=n.hasNode(e)?n.getId(e):function(e,t){if(t.comment&&e.type===ja.Comment)return!0;if(e.type===ja.Element){if(t.script&&("script"===e.tagName||"link"===e.tagName&&("preload"===e.attributes.rel&&"script"===e.attributes.as||"modulepreload"===e.attributes.rel)||"link"===e.tagName&&"prefetch"===e.attributes.rel&&"string"==typeof e.attributes.href&&"js"===ol(e.attributes.href)))return!0;if(t.headFavicon&&("link"===e.tagName&&"shortcut icon"===e.attributes.rel||"meta"===e.tagName&&(Il(e.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===Il(e.attributes.name)||"icon"===Il(e.attributes.rel)||"apple-touch-icon"===Il(e.attributes.rel)||"shortcut icon"===Il(e.attributes.rel))))return!0;if("meta"===e.tagName){if(t.headMetaDescKeywords&&Il(e.attributes.name).match(/^description|keywords$/))return!0;if(t.headMetaSocial&&(Il(e.attributes.property).match(/^(og|twitter|fb):/)||Il(e.attributes.name).match(/^(og|twitter):/)||"pinterest"===Il(e.attributes.name)))return!0;if(t.headMetaRobots&&("robots"===Il(e.attributes.name)||"googlebot"===Il(e.attributes.name)||"bingbot"===Il(e.attributes.name)))return!0;if(t.headMetaHttpEquiv&&void 0!==e.attributes["http-equiv"])return!0;if(t.headMetaAuthorship&&("author"===Il(e.attributes.name)||"generator"===Il(e.attributes.name)||"framework"===Il(e.attributes.name)||"publisher"===Il(e.attributes.name)||"progid"===Il(e.attributes.name)||Il(e.attributes.property).match(/^article:/)||Il(e.attributes.property).match(/^product:/)))return!0;if(t.headMetaVerification&&("google-site-verification"===Il(e.attributes.name)||"yandex-verification"===Il(e.attributes.name)||"csrf-token"===Il(e.attributes.name)||"p:domain_verify"===Il(e.attributes.name)||"verify-v1"===Il(e.attributes.name)||"verification"===Il(e.attributes.name)||"shopify-checkout-api-token"===Il(e.attributes.name)))return!0}}return!1}(x,d)||!k&&x.type===ja.Text&&!x.textContent.replace(/^\s+|\s+$/gm,"").length?-2:gl();const A=Object.assign(x,{id:O});if(n.add(e,A),-2===O)return null;y&&y(e);let I=!l;if(A.type===ja.Element){I=I&&!A.needBlock,delete A.needBlock;const t=Xa.shadowRoot(e);t&&qa(t)&&(A.isShadowHost=!0)}if((A.type===ja.Document||A.type===ja.Element)&&I){d.headWhitespace&&A.type===ja.Element&&"head"===A.tagName&&(k=!1);const t={doc:r,mirror:n,blockClass:s,blockSelector:i,needsMask:T,maskTextClass:o,maskTextSelector:a,skipChild:l,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,slimDOMOptions:d,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:k,onSerialize:y,onIframeLoad:w,iframeLoadTimeout:v,onStylesheetLoad:b,stylesheetLoadTimeout:_,keepIframeSrcFn:S,cssCaptured:!1};if(A.type===ja.Element&&"textarea"===A.tagName&&void 0!==A.attributes.value);else{A.type===ja.Element&&void 0!==A.attributes._cssText&&"string"==typeof A.attributes._cssText&&(t.cssCaptured=!0);for(const r of Array.from(Xa.childNodes(e))){const e=Ml(r,t);e&&A.childNodes.push(e)}}let C=null;if(Ja(e)&&(C=Xa.shadowRoot(e)))for(const e of Array.from(Xa.childNodes(C))){const r=Ml(e,t);r&&(qa(C)&&(r.isShadow=!0),A.childNodes.push(r))}}const R=Xa.parentNode(e);return R&&Ka(R)&&qa(R)&&(A.isShadow=!0),A.type===ja.Element&&"iframe"===A.tagName&&function(e,t,r){const n=e.contentWindow;if(!n)return;let s,i=!1;try{s=n.document.readyState}catch(e){return}if("complete"!==s){const n=setTimeout(()=>{i||(t(),i=!0)},r);return void e.addEventListener("load",()=>{clearTimeout(n),i=!0,t()})}const o="about:blank";if(n.location.href!==o||e.src===o||""===e.src)return setTimeout(t,0),e.addEventListener("load",t);e.addEventListener("load",t)}(e,()=>{const t=e.contentDocument;if(t&&w){const r=Ml(t,{doc:t,mirror:n,blockClass:s,blockSelector:i,needsMask:T,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,slimDOMOptions:d,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:k,onSerialize:y,onIframeLoad:w,iframeLoadTimeout:v,onStylesheetLoad:b,stylesheetLoadTimeout:_,keepIframeSrcFn:S});r&&w(e,r)}},v),A.type===ja.Element&&"link"===A.tagName&&"string"==typeof A.attributes.rel&&("stylesheet"===A.attributes.rel||"preload"===A.attributes.rel&&"string"==typeof A.attributes.href&&"css"===ol(A.attributes.href))&&function(e,t,r){let n,s=!1;try{n=e.sheet}catch(e){return}if(n)return;const i=setTimeout(()=>{s||(t(),s=!0)},r);e.addEventListener("load",()=>{clearTimeout(i),s=!0,t()})}(e,()=>{if(b){const t=Ml(e,{doc:r,mirror:n,blockClass:s,blockSelector:i,needsMask:T,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,slimDOMOptions:d,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:k,onSerialize:y,onIframeLoad:w,iframeLoadTimeout:v,onStylesheetLoad:b,stylesheetLoadTimeout:_,keepIframeSrcFn:S});t&&b(e,t)}},_),A}function Nl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Pl(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var Ll={exports:{}},Dl=String,Ul=function(){return{isColorSupported:!1,reset:Dl,bold:Dl,dim:Dl,italic:Dl,underline:Dl,inverse:Dl,hidden:Dl,strikethrough:Dl,black:Dl,red:Dl,green:Dl,yellow:Dl,blue:Dl,magenta:Dl,cyan:Dl,white:Dl,gray:Dl,bgBlack:Dl,bgRed:Dl,bgGreen:Dl,bgYellow:Dl,bgBlue:Dl,bgMagenta:Dl,bgCyan:Dl,bgWhite:Dl}};Ll.exports=Ul(),Ll.exports.createColors=Ul;var Fl=Ll.exports;const Bl=Pl(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let jl=Fl,zl=Bl,Vl=class e extends Error{constructor(t,r,n,s,i,o){super(t),this.name="CssSyntaxError",this.reason=t,i&&(this.file=i),s&&(this.source=s),o&&(this.plugin=o),void 0!==r&&void 0!==n&&("number"==typeof r?(this.line=r,this.column=n):(this.line=r.line,this.column=r.column,this.endLine=n.line,this.endColumn=n.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;null==e&&(e=jl.isColorSupported),zl&&e&&(t=zl(t));let r,n,s=t.split(/\r?\n/),i=Math.max(this.line-3,0),o=Math.min(this.line+2,s.length),a=String(o).length;if(e){let{bold:e,gray:t,red:s}=jl.createColors(!0);r=t=>e(s(t)),n=e=>t(e)}else r=n=e=>e;return s.slice(i,o).map((e,t)=>{let s=i+1+t,o=" "+(" "+s).slice(-a)+" | ";if(s===this.line){let t=n(o.replace(/\d/g," "))+e.slice(0,this.column-1).replace(/[^\t]/g," ");return r(">")+n(o)+e+"\n "+t+r("^")}return" "+n(o)+e}).join("\n")}toString(){let e=this.showSourceCode();return e&&(e="\n\n"+e+"\n"),this.name+": "+this.message+e}};var Gl=Vl;Vl.default=Vl;var Hl={};Hl.isClean=Symbol("isClean"),Hl.my=Symbol("my");const Zl={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let $l=class{constructor(e){this.builder=e}atrule(e,t){let r="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(void 0!==e.raws.afterName?r+=e.raws.afterName:n&&(r+=" "),e.nodes)this.block(e,r+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(r+n+s,e)}}beforeAfter(e,t){let r;r="decl"===e.type?this.raw(e,null,"beforeDecl"):"comment"===e.type?this.raw(e,null,"beforeComment"):"before"===t?this.raw(e,null,"beforeRule"):this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&"root"!==n.type;)s+=1,n=n.parent;if(r.includes("\n")){let t=this.raw(e,null,"indent");if(t.length)for(let e=0;e0&&"comment"===e.nodes[t].type;)t-=1;let r=this.raw(e,"semicolon");for(let n=0;n{if(n=e.raws[t],void 0!==n)return!1})}var o;return void 0===n&&(n=Zl[r]),i.rawCache[r]=n,n}rawBeforeClose(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length>0&&void 0!==e.raws.after)return t=e.raws.after,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let r;return e.walkComments(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeDecl"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeDecl(e,t){let r;return e.walkDecls(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeRule"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeOpen(e){let t;return e.walk(e=>{if("decl"!==e.type&&(t=e.raws.between,void 0!==t))return!1}),t}rawBeforeRule(e){let t;return e.walk(r=>{if(r.nodes&&(r.parent!==e||e.first!==r)&&void 0!==r.raws.before)return t=r.raws.before,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(e=>{if(void 0!==e.raws.between)return t=e.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(e=>{if(e.nodes&&0===e.nodes.length&&(t=e.raws.after,void 0!==t))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(r=>{let n=r.parent;if(n&&n!==e&&n.parent&&n.parent===e&&void 0!==r.raws.before){let e=r.raws.before.split("\n");return t=e[e.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length&&"decl"===e.last.type&&(t=e.raws.semicolon,void 0!==t))return!1}),t}rawValue(e,t){let r=e[t],n=e.raws[t];return n&&n.value===r?n.raw:r}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};var Wl=$l;$l.default=$l;let Yl=Wl;function Xl(e,t){new Yl(t).stringify(e)}var Jl=Xl;Xl.default=Xl;let{isClean:Kl,my:ql}=Hl,Ql=Gl,ec=Wl,tc=Jl;function rc(e,t){let r=new e.constructor;for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;if("proxyCache"===n)continue;let s=e[n],i=typeof s;"parent"===n&&"object"===i?t&&(r[n]=t):"source"===n?r[n]=s:Array.isArray(s)?r[n]=s.map(e=>rc(e,r)):("object"===i&&null!==s&&(s=rc(s)),r[n]=s)}return r}let nc=class{constructor(e={}){this.raws={},this[Kl]=!1,this[ql]=!0;for(let t in e)if("nodes"===t){this.nodes=[];for(let r of e[t])"function"==typeof r.clone?this.append(r.clone()):this.append(r)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=rc(this);for(let r in e)t[r]=e[r];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:r,start:n}=this.rangeBy(t);return this.source.input.error(e,{column:n.column,line:n.line},{column:r.column,line:r.line},t)}return new Ql(e)}getProxyProcessor(){return{get:(e,t)=>"proxyOf"===t?e:"root"===t?()=>e.root().toProxy():e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"prop"!==t&&"value"!==t&&"name"!==t&&"params"!==t&&"important"!==t&&"text"!==t||e.markDirty()),!0)}}markDirty(){if(this[Kl]){this[Kl]=!1;let e=this;for(;e=e.parent;)e[Kl]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){let n=(t=this.toString()).indexOf(e.word);-1!==n&&(r=this.positionInside(n,t))}return r}positionInside(e,t){let r=t||this.toString(),n=this.source.start.column,s=this.source.start.line;for(let t=0;t"object"==typeof e&&e.toJSON?e.toJSON(null,t):e);else if("object"==typeof n&&n.toJSON)r[e]=n.toJSON(null,t);else if("source"===e){let i=t.get(n.input);null==i&&(i=s,t.set(n.input,s),s++),r[e]={end:n.end,inputId:i,start:n.start}}else r[e]=n}return n&&(r.inputs=[...t.keys()].map(e=>e.toJSON())),r}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=tc){e.stringify&&(e=e.stringify);let t="";return e(this,e=>{t+=e}),t}warn(e,t,r){let n={node:this};for(let e in r)n[e]=r[e];return e.warn(t,n)}get proxyOf(){return this}};var sc=nc;nc.default=nc;let ic=sc,oc=class extends ic{constructor(e){e&&void 0!==e.value&&"string"!=typeof e.value&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var ac=oc;oc.default=oc;var lc={nanoid:(e=21)=>{let t="",r=e;for(;r--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t}};let{SourceMapConsumer:cc,SourceMapGenerator:uc}=Bl,{existsSync:hc,readFileSync:pc}=Bl,{dirname:dc,join:fc}=Bl;let mc=class{constructor(e,t){if(!1===t.map)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let r=t.map?t.map.prev:void 0,n=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=dc(this.mapFile)),n&&(this.text=n)}consumer(){return this.consumerCache||(this.consumerCache=new cc(this.text)),this.consumerCache}decodeInline(e){if(/^data:application\/json;charset=utf-?8,/.test(e)||/^data:application\/json,/.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(e)||/^data:application\/json;base64,/.test(e))return t=e.substr(RegExp.lastMatch.length),Buffer?Buffer.from(t,"base64").toString():window.atob(t);var t;let r=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+r)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return"object"==typeof e&&("string"==typeof e.mappings||"string"==typeof e._mappings||Array.isArray(e.sections))}loadAnnotation(e){let t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(!t)return;let r=e.lastIndexOf(t.pop()),n=e.indexOf("*/",r);r>-1&&n>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,n)))}loadFile(e){if(this.root=dc(e),hc(e))return this.mapFile=e,pc(e,"utf-8").toString().trim()}loadMap(e,t){if(!1===t)return!1;if(t){if("string"==typeof t)return t;if("function"!=typeof t){if(t instanceof cc)return uc.fromSourceMap(t).toString();if(t instanceof uc)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}{let r=t(e);if(r){let e=this.loadFile(r);if(!e)throw new Error("Unable to load previous source map: "+r.toString());return e}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let t=this.annotation;return e&&(t=fc(dc(e),t)),this.loadFile(t)}}}startWith(e,t){return!!e&&e.substr(0,t.length)===t}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var gc=mc;mc.default=mc;let{SourceMapConsumer:yc,SourceMapGenerator:wc}=Bl,{fileURLToPath:vc,pathToFileURL:bc}=Bl,{isAbsolute:_c,resolve:Sc}=Bl,{nanoid:Cc}=lc,Ec=Bl,Tc=Gl,kc=gc,xc=Symbol("fromOffsetCache"),Oc=Boolean(yc&&wc),Ac=Boolean(Sc&&_c),Ic=class{constructor(e,t={}){if(null==e||"object"==typeof e&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!Ac||/^\w+:\/\//.test(t.from)||_c(t.from)?this.file=t.from:this.file=Sc(t.from)),Ac&&Oc){let e=new kc(this.css,t);if(e.text){this.map=e;let t=e.consumer().file;!this.file&&t&&(this.file=this.mapResolve(t))}}this.file||(this.id=""),this.map&&(this.map.file=this.from)}error(e,t,r,n={}){let s,i,o;if(t&&"object"==typeof t){let e=t,n=r;if("number"==typeof e.offset){let n=this.fromOffset(e.offset);t=n.line,r=n.col}else t=e.line,r=e.column;if("number"==typeof n.offset){let e=this.fromOffset(n.offset);i=e.line,o=e.col}else i=n.line,o=n.column}else if(!r){let e=this.fromOffset(t);t=e.line,r=e.col}let a=this.origin(t,r,i,o);return s=a?new Tc(e,void 0===a.endLine?a.line:{column:a.column,line:a.line},void 0===a.endLine?a.column:{column:a.endColumn,line:a.endLine},a.source,a.file,n.plugin):new Tc(e,void 0===i?t:{column:r,line:t},void 0===i?r:{column:o,line:i},this.css,this.file,n.plugin),s.input={column:r,endColumn:o,endLine:i,line:t,source:this.css},this.file&&(bc&&(s.input.url=bc(this.file).toString()),s.input.file=this.file),s}fromOffset(e){let t,r;if(this[xc])r=this[xc];else{let e=this.css.split("\n");r=new Array(e.length);let t=0;for(let n=0,s=e.length;n=t)n=r.length-1;else{let t,s=r.length-2;for(;n>1),e=r[t+1])){n=t;break}n=t+1}}return{col:e-r[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:Sc(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,r,n){if(!this.map)return!1;let s,i,o=this.map.consumer(),a=o.originalPositionFor({column:t,line:e});if(!a.source)return!1;"number"==typeof r&&(s=o.originalPositionFor({column:n,line:r})),i=_c(a.source)?bc(a.source):new URL(a.source,this.map.consumer().sourceRoot||bc(this.map.mapFile));let l={column:a.column,endColumn:s&&s.column,endLine:s&&s.line,line:a.line,url:i.toString()};if("file:"===i.protocol){if(!vc)throw new Error("file: protocol is not available in this PostCSS build");l.file=vc(i)}let c=o.sourceContentFor(a.source);return c&&(l.source=c),l}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])null!=this[t]&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};var Rc=Ic;Ic.default=Ic,Ec&&Ec.registerInput&&Ec.registerInput(Ic);let{SourceMapConsumer:Mc,SourceMapGenerator:Nc}=Bl,{dirname:Pc,relative:Lc,resolve:Dc,sep:Uc}=Bl,{pathToFileURL:Fc}=Bl,Bc=Rc,jc=Boolean(Mc&&Nc),zc=Boolean(Pc&&Dc&&Lc&&Uc);var Vc=class{constructor(e,t,r,n){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=n,this.originalCSS=n,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let t="\n";this.css.includes("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"}applyPrevMaps(){for(let e of this.previous()){let t,r=this.toUrl(this.path(e.file)),n=e.root||Pc(e.file);!1===this.mapOpts.sourcesContent?(t=new Mc(e.text),t.sourcesContent&&(t.sourcesContent=null)):t=e.consumer(),this.map.applySourceMap(t,r,this.toUrl(this.path(n)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],"comment"===e.type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),zc&&jc&&this.isMap())return this.generateMap();{let e="";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=Nc.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new Nc({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):""});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new Nc({file:this.outputFile(),ignoreInvalidMapping:!0});let e,t,r=1,n=1,s="",i={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(o,a,l)=>{if(this.css+=o,a&&"end"!==l&&(i.generated.line=r,i.generated.column=n-1,a.source&&a.source.start?(i.source=this.sourcePath(a),i.original.line=a.source.start.line,i.original.column=a.source.start.column-1,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,this.map.addMapping(i))),e=o.match(/\n/g),e?(r+=e.length,t=o.lastIndexOf("\n"),n=o.length-t):n+=o.length,a&&"start"!==l){let e=a.parent||{raws:{}};("decl"===a.type||"atrule"===a.type&&!a.nodes)&&a===e.last&&!e.raws.semicolon||(a.source&&a.source.end?(i.source=this.sourcePath(a),i.original.line=a.source.end.line,i.original.column=a.source.end.column-1,i.generated.line=r,i.generated.column=n-2,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,i.generated.line=r,i.generated.column=n-1,this.map.addMapping(i)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(e=>e.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(e=>e.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(e=>e.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(e){if(this.mapOpts.absolute)return e;if(60===e.charCodeAt(0))return e;if(/^\w+:\/\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let r=this.opts.to?Pc(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(r=Pc(Dc(r,this.mapOpts.annotation)));let n=Lc(r,e);return this.memoizedPaths.set(e,n),n}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new Bc(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let r=t.source.input.from;if(r&&!e[r]){e[r]=!0;let n=this.usesFileUrls?this.toFileUrl(r):this.toUrl(this.path(r));this.map.setSourceContent(n,t.source.input.css)}}});else if(this.css){let e=this.opts.from?this.toUrl(this.path(this.opts.from)):"";this.map.setSourceContent(e,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(Fc){let t=Fc(e).toString();return this.memoizedFileURLs.set(e,t),t}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;"\\"===Uc&&(e=e.replace(/\\/g,"/"));let r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r}};let Gc=sc,Hc=class extends Gc{constructor(e){super(e),this.type="comment"}};var Zc=Hc;Hc.default=Hc;let $c,Wc,Yc,Xc,{isClean:Jc,my:Kc}=Hl,qc=ac,Qc=Zc,eu=sc;function tu(e){return e.map(e=>(e.nodes&&(e.nodes=tu(e.nodes)),delete e.source,e))}function ru(e){if(e[Jc]=!1,e.proxyOf.nodes)for(let t of e.proxyOf.nodes)ru(t)}let nu=class e extends eu{append(...e){for(let t of e){let e=this.normalize(t,this.last);for(let t of e)this.proxyOf.nodes.push(t)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t,r,n=this.getIterator();for(;this.indexes[n]"proxyOf"===t?e:e[t]?"each"===t||"string"==typeof t&&t.startsWith("walk")?(...r)=>e[t](...r.map(e=>"function"==typeof e?(t,r)=>e(t.toProxy(),r):e)):"every"===t||"some"===t?r=>e[t]((e,...t)=>r(e.toProxy(),...t)):"root"===t?()=>e.root().toProxy():"nodes"===t?e.nodes.map(e=>e.toProxy()):"first"===t||"last"===t?e[t].toProxy():e[t]:e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"name"!==t&&"params"!==t&&"selector"!==t||e.markDirty()),!0)}}index(e){return"number"==typeof e?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let r,n=this.index(e),s=this.normalize(t,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(let e of s)this.proxyOf.nodes.splice(n+1,0,e);for(let e in this.indexes)r=this.indexes[e],n(t[Kc]||e.rebuild(t),(t=t.proxyOf).parent&&t.parent.removeChild(t),t[Jc]&&ru(t),void 0===t.raws.before&&r&&void 0!==r.raws.before&&(t.raws.before=r.raws.before.replace(/\S/g,"")),t.parent=this.proxyOf,t))}prepend(...e){e=e.reverse();for(let t of e){let e=this.normalize(t,this.first,"prepend").reverse();for(let t of e)this.proxyOf.nodes.unshift(t);for(let t in this.indexes)this.indexes[t]=this.indexes[t]+e.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){let t;e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);for(let r in this.indexes)t=this.indexes[r],t>=e&&(this.indexes[r]=t-1);return this.markDirty(),this}replaceValues(e,t,r){return r||(r=t,t={}),this.walkDecls(n=>{t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,r))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,r)=>{let n;try{n=e(t,r)}catch(e){throw t.addToError(e)}return!1!==n&&t.walk&&(n=t.walk(e)),n})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("atrule"===r.type&&e.test(r.name))return t(r,n)}):this.walk((r,n)=>{if("atrule"===r.type&&r.name===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("atrule"===e.type)return t(e,r)}))}walkComments(e){return this.walk((t,r)=>{if("comment"===t.type)return e(t,r)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("decl"===r.type&&e.test(r.prop))return t(r,n)}):this.walk((r,n)=>{if("decl"===r.type&&r.prop===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("decl"===e.type)return t(e,r)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("rule"===r.type&&e.test(r.selector))return t(r,n)}):this.walk((r,n)=>{if("rule"===r.type&&r.selector===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("rule"===e.type)return t(e,r)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};nu.registerParse=e=>{$c=e},nu.registerRule=e=>{Wc=e},nu.registerAtRule=e=>{Yc=e},nu.registerRoot=e=>{Xc=e};var su=nu;nu.default=nu,nu.rebuild=e=>{"atrule"===e.type?Object.setPrototypeOf(e,Yc.prototype):"rule"===e.type?Object.setPrototypeOf(e,Wc.prototype):"decl"===e.type?Object.setPrototypeOf(e,qc.prototype):"comment"===e.type?Object.setPrototypeOf(e,Qc.prototype):"root"===e.type&&Object.setPrototypeOf(e,Xc.prototype),e[Kc]=!0,e.nodes&&e.nodes.forEach(e=>{nu.rebuild(e)})};let iu,ou,au=su,lu=class extends au{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new iu(new ou,this,e).stringify()}};lu.registerLazyResult=e=>{iu=e},lu.registerProcessor=e=>{ou=e};var cu=lu;lu.default=lu;let uu={};var hu=function(e){uu[e]||(uu[e]=!0,"undefined"!=typeof console&&console.warn&&console.warn(e))};let pu=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let e=t.node.rangeBy(t);this.line=e.start.line,this.column=e.start.column,this.endLine=e.end.line,this.endColumn=e.end.column}for(let e in t)this[e]=t[e]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var du=pu;pu.default=pu;let fu=du,mu=class{constructor(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let r=new fu(e,t);return this.messages.push(r),r}warnings(){return this.messages.filter(e=>"warning"===e.type)}get content(){return this.css}};var gu=mu;mu.default=mu;const yu="'".charCodeAt(0),wu='"'.charCodeAt(0),vu="\\".charCodeAt(0),bu="/".charCodeAt(0),_u="\n".charCodeAt(0),Su=" ".charCodeAt(0),Cu="\f".charCodeAt(0),Eu="\t".charCodeAt(0),Tu="\r".charCodeAt(0),ku="[".charCodeAt(0),xu="]".charCodeAt(0),Ou="(".charCodeAt(0),Au=")".charCodeAt(0),Iu="{".charCodeAt(0),Ru="}".charCodeAt(0),Mu=";".charCodeAt(0),Nu="*".charCodeAt(0),Pu=":".charCodeAt(0),Lu="@".charCodeAt(0),Du=/[\t\n\f\r "#'()/;[\\\]{}]/g,Uu=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Fu=/.[\r\n"'(/\\]/,Bu=/[\da-f]/i;let ju=su,zu=class extends ju{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};var Vu=zu;zu.default=zu,ju.registerAtRule(zu);let Gu,Hu,Zu=su,$u=class extends Zu{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,r){let n=super.normalize(e);if(t)if("prepend"===r)this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let e of n)e.raws.before=t.raws.before;return n}removeChild(e,t){let r=this.index(e);return!t&&0===r&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[r].raws.before),super.removeChild(e)}toResult(e={}){return new Gu(new Hu,this,e).stringify()}};$u.registerLazyResult=e=>{Gu=e},$u.registerProcessor=e=>{Hu=e};var Wu=$u;$u.default=$u,Zu.registerRoot($u);let Yu={comma:e=>Yu.split(e,[","],!0),space:e=>Yu.split(e,[" ","\n","\t"]),split(e,t,r){let n=[],s="",i=!1,o=0,a=!1,l="",c=!1;for(let r of e)c?c=!1:"\\"===r?c=!0:a?r===l&&(a=!1):'"'===r||"'"===r?(a=!0,l=r):"("===r?o+=1:")"===r?o>0&&(o-=1):0===o&&t.includes(r)&&(i=!0),i?(""!==s&&n.push(s.trim()),s="",i=!1):s+=r;return(r||""!==s)&&n.push(s.trim()),n}};var Xu=Yu;Yu.default=Yu;let Ju=su,Ku=Xu,qu=class extends Ju{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Ku.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,r=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(r)}};var Qu=qu;qu.default=qu,Ju.registerRule(qu);let eh=ac,th=function(e,t={}){let r,n,s,i,o,a,l,c,u,h,p=e.css.valueOf(),d=t.ignoreErrors,f=p.length,m=0,g=[],y=[];function w(t){throw e.error("Unclosed "+t,m)}return{back:function(e){y.push(e)},endOfFile:function(){return 0===y.length&&m>=f},nextToken:function(e){if(y.length)return y.pop();if(m>=f)return;let t=!!e&&e.ignoreUnclosed;switch(r=p.charCodeAt(m),r){case _u:case Su:case Eu:case Tu:case Cu:n=m;do{n+=1,r=p.charCodeAt(n)}while(r===Su||r===_u||r===Eu||r===Tu||r===Cu);h=["space",p.slice(m,n)],m=n-1;break;case ku:case xu:case Iu:case Ru:case Pu:case Mu:case Au:{let e=String.fromCharCode(r);h=[e,e,m];break}case Ou:if(c=g.length?g.pop()[1]:"",u=p.charCodeAt(m+1),"url"===c&&u!==yu&&u!==wu&&u!==Su&&u!==_u&&u!==Eu&&u!==Cu&&u!==Tu){n=m;do{if(a=!1,n=p.indexOf(")",n+1),-1===n){if(d||t){n=m;break}w("bracket")}for(l=n;p.charCodeAt(l-1)===vu;)l-=1,a=!a}while(a);h=["brackets",p.slice(m,n+1),m,n],m=n}else n=p.indexOf(")",m+1),i=p.slice(m,n+1),-1===n||Fu.test(i)?h=["(","(",m]:(h=["brackets",i,m,n],m=n);break;case yu:case wu:s=r===yu?"'":'"',n=m;do{if(a=!1,n=p.indexOf(s,n+1),-1===n){if(d||t){n=m+1;break}w("string")}for(l=n;p.charCodeAt(l-1)===vu;)l-=1,a=!a}while(a);h=["string",p.slice(m,n+1),m,n],m=n;break;case Lu:Du.lastIndex=m+1,Du.test(p),n=0===Du.lastIndex?p.length-1:Du.lastIndex-2,h=["at-word",p.slice(m,n+1),m,n],m=n;break;case vu:for(n=m,o=!0;p.charCodeAt(n+1)===vu;)n+=1,o=!o;if(r=p.charCodeAt(n+1),o&&r!==bu&&r!==Su&&r!==_u&&r!==Eu&&r!==Tu&&r!==Cu&&(n+=1,Bu.test(p.charAt(n)))){for(;Bu.test(p.charAt(n+1));)n+=1;p.charCodeAt(n+1)===Su&&(n+=1)}h=["word",p.slice(m,n+1),m,n],m=n;break;default:r===bu&&p.charCodeAt(m+1)===Nu?(n=p.indexOf("*/",m+2)+1,0===n&&(d||t?n=p.length:w("comment")),h=["comment",p.slice(m,n+1),m,n],m=n):(Uu.lastIndex=m+1,Uu.test(p),n=0===Uu.lastIndex?p.length-1:Uu.lastIndex-2,h=["word",p.slice(m,n+1),m,n],g.push(h),m=n)}return m++,h},position:function(){return m}}},rh=Zc,nh=Vu,sh=Wu,ih=Qu;const oh={empty:!0,space:!0};var ah=class{constructor(e){this.input=e,this.root=new sh,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t,r,n,s=new nh;s.name=e[1].slice(1),""===s.name&&this.unnamedAtrule(s,e),this.init(s,e[2]);let i=!1,o=!1,a=[],l=[];for(;!this.tokenizer.endOfFile();){if(t=(e=this.tokenizer.nextToken())[0],"("===t||"["===t?l.push("("===t?")":"]"):"{"===t&&l.length>0?l.push("}"):t===l[l.length-1]&&l.pop(),0===l.length){if(";"===t){s.source.end=this.getPosition(e[2]),s.source.end.offset++,this.semicolon=!0;break}if("{"===t){o=!0;break}if("}"===t){if(a.length>0){for(n=a.length-1,r=a[n];r&&"space"===r[0];)r=a[--n];r&&(s.source.end=this.getPosition(r[3]||r[2]),s.source.end.offset++)}this.end(e);break}a.push(e)}else a.push(e);if(this.tokenizer.endOfFile()){i=!0;break}}s.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(s.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(s,"params",a),i&&(e=a[a.length-1],s.source.end=this.getPosition(e[3]||e[2]),s.source.end.offset++,this.spaces=s.raws.between,s.raws.between="")):(s.raws.afterName="",s.params=""),o&&(s.nodes=[],this.current=s)}checkMissedSemicolon(e){let t=this.colon(e);if(!1===t)return;let r,n=0;for(let s=t-1;s>=0&&(r=e[s],"space"===r[0]||(n+=1,2!==n));s--);throw this.input.error("Missed semicolon","word"===r[0]?r[3]+1:r[2])}colon(e){let t,r,n,s=0;for(let[i,o]of e.entries()){if(t=o,r=t[0],"("===r&&(s+=1),")"===r&&(s-=1),0===s&&":"===r){if(n){if("word"===n[0]&&"progid"===n[1])continue;return i}this.doubleColon(t)}n=t}return!1}comment(e){let t=new rh;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let r=e[1].slice(2,-2);if(/^\s*$/.test(r))t.text="",t.raws.left=r,t.raws.right="";else{let e=r.match(/^(\s*)([^]*\S)(\s*)$/);t.text=e[2],t.raws.left=e[1],t.raws.right=e[3]}}createTokenizer(){this.tokenizer=th(this.input)}decl(e,t){let r=new eh;this.init(r,e[0][2]);let n,s=e[e.length-1];for(";"===s[0]&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(s[3]||s[2]||function(e){for(let t=e.length-1;t>=0;t--){let r=e[t],n=r[3]||r[2];if(n)return n}}(e)),r.source.end.offset++;"word"!==e[0][0];)1===e.length&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop="";e.length;){let t=e[0][0];if(":"===t||"space"===t||"comment"===t)break;r.prop+=e.shift()[1]}for(r.raws.between="";e.length;){if(n=e.shift(),":"===n[0]){r.raws.between+=n[1];break}"word"===n[0]&&/\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1]}"_"!==r.prop[0]&&"*"!==r.prop[0]||(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));let i,o=[];for(;e.length&&(i=e[0][0],"space"===i||"comment"===i);)o.push(e.shift());this.precheckMissedSemicolon(e);for(let t=e.length-1;t>=0;t--){if(n=e[t],"!important"===n[1].toLowerCase()){r.important=!0;let n=this.stringFrom(e,t);n=this.spacesFromEnd(e)+n," !important"!==n&&(r.raws.important=n);break}if("important"===n[1].toLowerCase()){let n=e.slice(0),s="";for(let e=t;e>0;e--){let t=n[e][0];if(0===s.trim().indexOf("!")&&"space"!==t)break;s=n.pop()[1]+s}0===s.trim().indexOf("!")&&(r.important=!0,r.raws.important=s,e=n)}if("space"!==n[0]&&"comment"!==n[0])break}e.some(e=>"space"!==e[0]&&"comment"!==e[0])&&(r.raws.between+=o.map(e=>e[1]).join(""),o=[]),this.raw(r,"value",o.concat(e),t),r.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new ih;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let e=this.current.nodes[this.current.nodes.length-1];e&&"rule"===e.type&&!e.raws.ownSemicolon&&(e.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="","comment"!==e.type&&(this.semicolon=!1)}other(e){let t=!1,r=null,n=!1,s=null,i=[],o=e[1].startsWith("--"),a=[],l=e;for(;l;){if(r=l[0],a.push(l),"("===r||"["===r)s||(s=l),i.push("("===r?")":"]");else if(o&&n&&"{"===r)s||(s=l),i.push("}");else if(0===i.length){if(";"===r){if(n)return void this.decl(a,o);break}if("{"===r)return void this.rule(a);if("}"===r){this.tokenizer.back(a.pop()),t=!0;break}":"===r&&(n=!0)}else r===i[i.length-1]&&(i.pop(),0===i.length&&(s=null));l=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),i.length>0&&this.unclosedBracket(s),t&&n){if(!o)for(;a.length&&(l=a[a.length-1][0],"space"===l||"comment"===l);)this.tokenizer.back(a.pop());this.decl(a,o)}else this.unknownWord(a)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e)}this.endFile()}precheckMissedSemicolon(){}raw(e,t,r,n){let s,i,o,a,l=r.length,c="",u=!0;for(let e=0;ee+t[1],"");e.raws[t]={raw:n,value:c}}e[t]=c}rule(e){e.pop();let t=new ih;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t||"comment"===t);)r=e.pop()[1]+r;return r}spacesAndCommentsFromStart(e){let t,r="";for(;e.length&&(t=e[0][0],"space"===t||"comment"===t);)r+=e.shift()[1];return r}spacesFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t);)r=e.pop()[1]+r;return r}stringFrom(e,t){let r="";for(let n=t;nAh(e)),e}let Ih={},Rh=class e{constructor(t,r,n){let s;if(this.stringified=!1,this.processed=!1,"object"!=typeof r||null===r||"root"!==r.type&&"document"!==r.type)if(r instanceof e||r instanceof bh)s=Ah(r.root),r.map&&(void 0===n.map&&(n.map={}),n.map.inline||(n.map.inline=!1),n.map.prev=r.map);else{let e=_h;n.syntax&&(e=n.syntax.parse),n.parser&&(e=n.parser),e.parse&&(e=e.parse);try{s=e(r,n)}catch(e){this.processed=!0,this.error=e}s&&!s[fh]&&yh.rebuild(s)}else s=Ah(r);this.result=new bh(t,s,n),this.helpers={...Ih,postcss:Ih,result:this.result},this.plugins=this.processor.plugins.map(e=>"object"==typeof e&&e.prepare?{...e,...e.prepare(this.result)}:e)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let r=this.result.lastPlugin;try{if(t&&t.addToError(e),this.error=e,"CssSyntaxError"!==e.name||e.plugin){if(r.postcssVersion&&"production"!==process.env.NODE_ENV){let e=r.postcssPlugin,t=r.postcssVersion,n=this.result.processor.version,s=t.split("."),i=n.split(".");(s[0]!==i[0]||parseInt(s[1])>parseInt(i[1]))&&console.error("Unknown error from PostCSS plugin. Your current PostCSS version is "+n+", but "+e+" uses "+t+". Perhaps this is the source of the error below.")}}else e.plugin=r.postcssPlugin,e.setMessage()}catch(e){console&&console.error&&console.error(e)}return e}prepareVisitors(){this.listeners={};let e=(e,t,r)=>{this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push([e,r])};for(let t of this.plugins)if("object"==typeof t)for(let r in t){if(!Eh[r]&&/^[A-Z]/.test(r))throw new Error(`Unknown event ${r} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Th[r])if("object"==typeof t[r])for(let n in t[r])e(t,"*"===n?r:r+"-"+n.toLowerCase(),t[r][n]);else"function"==typeof t[r]&&e(t,r,t[r])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e0;){let e=this.visitTick(t);if(kh(e))try{await e}catch(e){let r=t[t.length-1].node;throw this.handleError(e,r)}}}if(this.listeners.OnceExit)for(let[t,r]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if("document"===e.type){let t=e.nodes.map(e=>r(e,this.helpers));await Promise.all(t)}else await r(e,this.helpers)}catch(e){throw this.handleError(e)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if("object"==typeof e&&e.Once){if("document"===this.result.root.type){let t=this.result.root.nodes.map(t=>e.Once(t,this.helpers));return kh(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}if("function"==typeof e)return e(this.result.root,this.result)}catch(e){throw this.handleError(e)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=gh;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new mh(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){if(kh(this.runOnRoot(e)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[dh];)e[dh]=!0,this.walkSync(e);if(this.listeners.OnceExit)if("document"===e.type)for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this.opts||vh("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[r,n]of e){let e;this.result.lastPlugin=r;try{e=n(t,this.helpers)}catch(e){throw this.handleError(e,t.proxyOf)}if("root"!==t.type&&"document"!==t.type&&!t.parent)return!0;if(kh(e))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:r,visitors:n}=t;if("root"!==r.type&&"document"!==r.type&&!r.parent)return void e.pop();if(n.length>0&&t.visitorIndex{e[dh]||this.walkSync(e)});else{let t=this.listeners[r];if(t&&this.visitSync(t,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};Rh.registerPostcss=e=>{Ih=e};var Mh=Rh;Rh.default=Rh,Sh.registerLazyResult(Rh),wh.registerLazyResult(Rh);let Nh=Vc,Ph=Jl,Lh=hu,Dh=ph;const Uh=gu;let Fh=class{constructor(e,t,r){let n;t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;let s=Ph;this.result=new Uh(this._processor,n,this._opts),this.result.css=t;let i=this;Object.defineProperty(this.result,"root",{get:()=>i.root});let o=new Nh(s,n,this._opts,t);if(o.isMap()){let[e,t]=o.generate();e&&(this.result.css=e),t&&(this.result.map=t)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this._opts||Lh("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=Dh;try{e=t(this._css,this._opts)}catch(e){this.error=e}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}};var Bh=Fh;Fh.default=Fh;let jh=Bh,zh=Mh,Vh=cu,Gh=Wu,Hh=class{constructor(e=[]){this.version="8.4.38",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let r of e)if(!0===r.postcss?r=r():r.postcss&&(r=r.postcss),"object"==typeof r&&Array.isArray(r.plugins))t=t.concat(r.plugins);else if("object"==typeof r&&r.postcssPlugin)t.push(r);else if("function"==typeof r)t.push(r);else{if("object"!=typeof r||!r.parse&&!r.stringify)throw new Error(r+" is not a PostCSS plugin");if("production"!==process.env.NODE_ENV)throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.")}return t}process(e,t={}){return this.plugins.length||t.parser||t.stringifier||t.syntax?new zh(this,e,t):new jh(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};var Zh=Hh;Hh.default=Hh,Gh.registerProcessor(Hh),Vh.registerProcessor(Hh);let $h=ac,Wh=gc,Yh=Zc,Xh=Vu,Jh=Rc,Kh=Wu,qh=Qu;function Qh(e,t){if(Array.isArray(e))return e.map(e=>Qh(e));let{inputs:r,...n}=e;if(r){t=[];for(let e of r){let r={...e,__proto__:Jh.prototype};r.map&&(r.map={...r.map,__proto__:Wh.prototype}),t.push(r)}}if(n.nodes&&(n.nodes=e.nodes.map(e=>Qh(e,t))),n.source){let{inputId:e,...r}=n.source;n.source=r,null!=e&&(n.source.input=t[e])}if("root"===n.type)return new Kh(n);if("decl"===n.type)return new $h(n);if("rule"===n.type)return new qh(n);if("comment"===n.type)return new Yh(n);if("atrule"===n.type)return new Xh(n);throw new Error("Unknown node type: "+e.type)}var ep=Qh;Qh.default=Qh;let tp=Gl,rp=ac,np=Mh,sp=su,ip=Zh,op=Jl,ap=ep,lp=cu,cp=du,up=Zc,hp=Vu,pp=gu,dp=Rc,fp=ph,mp=Xu,gp=Qu,yp=Wu,wp=sc;function vp(...e){return 1===e.length&&Array.isArray(e[0])&&(e=e[0]),new ip(e)}vp.plugin=function(e,t){let r,n=!1;function s(...r){console&&console.warn&&!n&&(n=!0,console.warn(e+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226"));let s=t(...r);return s.postcssPlugin=e,s.postcssVersion=(new ip).version,s}return Object.defineProperty(s,"postcss",{get:()=>(r||(r=s()),r)}),s.process=function(e,t,r){return vp([s(r)]).process(e,t)},s},vp.stringify=op,vp.parse=fp,vp.fromJSON=ap,vp.list=mp,vp.comment=e=>new up(e),vp.atRule=e=>new hp(e),vp.decl=e=>new rp(e),vp.rule=e=>new gp(e),vp.root=e=>new yp(e),vp.document=e=>new lp(e),vp.CssSyntaxError=tp,vp.Declaration=rp,vp.Container=sp,vp.Processor=ip,vp.Document=lp,vp.Comment=up,vp.Warning=cp,vp.AtRule=hp,vp.Result=pp,vp.Input=dp,vp.Rule=gp,vp.Root=yp,vp.Node=wp,np.registerPostcss(vp);var bp=vp;vp.default=vp;const _p=Nl(bp);_p.stringify,_p.fromJSON,_p.plugin,_p.parse,_p.list,_p.document,_p.comment,_p.atRule,_p.rule,_p.decl,_p.root,_p.CssSyntaxError,_p.Declaration,_p.Container,_p.Processor,_p.Document,_p.Comment,_p.Warning,_p.AtRule,_p.Result,_p.Input,_p.Rule,_p.Root,_p.Node;var Sp=Object.defineProperty,Cp=(e,t,r)=>((e,t,r)=>t in e?Sp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);function Ep(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Tp(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var kp={exports:{}},xp=String,Op=function(){return{isColorSupported:!1,reset:xp,bold:xp,dim:xp,italic:xp,underline:xp,inverse:xp,hidden:xp,strikethrough:xp,black:xp,red:xp,green:xp,yellow:xp,blue:xp,magenta:xp,cyan:xp,white:xp,gray:xp,bgBlack:xp,bgRed:xp,bgGreen:xp,bgYellow:xp,bgBlue:xp,bgMagenta:xp,bgCyan:xp,bgWhite:xp}};kp.exports=Op(),kp.exports.createColors=Op;var Ap=kp.exports;const Ip=Tp(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let Rp=Ap,Mp=Ip,Np=class e extends Error{constructor(t,r,n,s,i,o){super(t),this.name="CssSyntaxError",this.reason=t,i&&(this.file=i),s&&(this.source=s),o&&(this.plugin=o),void 0!==r&&void 0!==n&&("number"==typeof r?(this.line=r,this.column=n):(this.line=r.line,this.column=r.column,this.endLine=n.line,this.endColumn=n.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;null==e&&(e=Rp.isColorSupported),Mp&&e&&(t=Mp(t));let r,n,s=t.split(/\r?\n/),i=Math.max(this.line-3,0),o=Math.min(this.line+2,s.length),a=String(o).length;if(e){let{bold:e,gray:t,red:s}=Rp.createColors(!0);r=t=>e(s(t)),n=e=>t(e)}else r=n=e=>e;return s.slice(i,o).map((e,t)=>{let s=i+1+t,o=" "+(" "+s).slice(-a)+" | ";if(s===this.line){let t=n(o.replace(/\d/g," "))+e.slice(0,this.column-1).replace(/[^\t]/g," ");return r(">")+n(o)+e+"\n "+t+r("^")}return" "+n(o)+e}).join("\n")}toString(){let e=this.showSourceCode();return e&&(e="\n\n"+e+"\n"),this.name+": "+this.message+e}};var Pp=Np;Np.default=Np;var Lp={};Lp.isClean=Symbol("isClean"),Lp.my=Symbol("my");const Dp={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let Up=class{constructor(e){this.builder=e}atrule(e,t){let r="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(void 0!==e.raws.afterName?r+=e.raws.afterName:n&&(r+=" "),e.nodes)this.block(e,r+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(r+n+s,e)}}beforeAfter(e,t){let r;r="decl"===e.type?this.raw(e,null,"beforeDecl"):"comment"===e.type?this.raw(e,null,"beforeComment"):"before"===t?this.raw(e,null,"beforeRule"):this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&"root"!==n.type;)s+=1,n=n.parent;if(r.includes("\n")){let t=this.raw(e,null,"indent");if(t.length)for(let e=0;e0&&"comment"===e.nodes[t].type;)t-=1;let r=this.raw(e,"semicolon");for(let n=0;n{if(n=e.raws[t],void 0!==n)return!1})}var o;return void 0===n&&(n=Dp[r]),i.rawCache[r]=n,n}rawBeforeClose(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length>0&&void 0!==e.raws.after)return t=e.raws.after,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let r;return e.walkComments(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeDecl"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeDecl(e,t){let r;return e.walkDecls(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeRule"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeOpen(e){let t;return e.walk(e=>{if("decl"!==e.type&&(t=e.raws.between,void 0!==t))return!1}),t}rawBeforeRule(e){let t;return e.walk(r=>{if(r.nodes&&(r.parent!==e||e.first!==r)&&void 0!==r.raws.before)return t=r.raws.before,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(e=>{if(void 0!==e.raws.between)return t=e.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(e=>{if(e.nodes&&0===e.nodes.length&&(t=e.raws.after,void 0!==t))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(r=>{let n=r.parent;if(n&&n!==e&&n.parent&&n.parent===e&&void 0!==r.raws.before){let e=r.raws.before.split("\n");return t=e[e.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length&&"decl"===e.last.type&&(t=e.raws.semicolon,void 0!==t))return!1}),t}rawValue(e,t){let r=e[t],n=e.raws[t];return n&&n.value===r?n.raw:r}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};var Fp=Up;Up.default=Up;let Bp=Fp;function jp(e,t){new Bp(t).stringify(e)}var zp=jp;jp.default=jp;let{isClean:Vp,my:Gp}=Lp,Hp=Pp,Zp=Fp,$p=zp;function Wp(e,t){let r=new e.constructor;for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;if("proxyCache"===n)continue;let s=e[n],i=typeof s;"parent"===n&&"object"===i?t&&(r[n]=t):"source"===n?r[n]=s:Array.isArray(s)?r[n]=s.map(e=>Wp(e,r)):("object"===i&&null!==s&&(s=Wp(s)),r[n]=s)}return r}let Yp=class{constructor(e={}){this.raws={},this[Vp]=!1,this[Gp]=!0;for(let t in e)if("nodes"===t){this.nodes=[];for(let r of e[t])"function"==typeof r.clone?this.append(r.clone()):this.append(r)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=Wp(this);for(let r in e)t[r]=e[r];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:r,start:n}=this.rangeBy(t);return this.source.input.error(e,{column:n.column,line:n.line},{column:r.column,line:r.line},t)}return new Hp(e)}getProxyProcessor(){return{get:(e,t)=>"proxyOf"===t?e:"root"===t?()=>e.root().toProxy():e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"prop"!==t&&"value"!==t&&"name"!==t&&"params"!==t&&"important"!==t&&"text"!==t||e.markDirty()),!0)}}markDirty(){if(this[Vp]){this[Vp]=!1;let e=this;for(;e=e.parent;)e[Vp]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){let n=(t=this.toString()).indexOf(e.word);-1!==n&&(r=this.positionInside(n,t))}return r}positionInside(e,t){let r=t||this.toString(),n=this.source.start.column,s=this.source.start.line;for(let t=0;t"object"==typeof e&&e.toJSON?e.toJSON(null,t):e);else if("object"==typeof n&&n.toJSON)r[e]=n.toJSON(null,t);else if("source"===e){let i=t.get(n.input);null==i&&(i=s,t.set(n.input,s),s++),r[e]={end:n.end,inputId:i,start:n.start}}else r[e]=n}return n&&(r.inputs=[...t.keys()].map(e=>e.toJSON())),r}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=$p){e.stringify&&(e=e.stringify);let t="";return e(this,e=>{t+=e}),t}warn(e,t,r){let n={node:this};for(let e in r)n[e]=r[e];return e.warn(t,n)}get proxyOf(){return this}};var Xp=Yp;Yp.default=Yp;let Jp=Xp,Kp=class extends Jp{constructor(e){e&&void 0!==e.value&&"string"!=typeof e.value&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var qp=Kp;Kp.default=Kp;var Qp={nanoid:(e=21)=>{let t="",r=e;for(;r--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t}};let{SourceMapConsumer:ed,SourceMapGenerator:td}=Ip,{existsSync:rd,readFileSync:nd}=Ip,{dirname:sd,join:id}=Ip;let od=class{constructor(e,t){if(!1===t.map)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let r=t.map?t.map.prev:void 0,n=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=sd(this.mapFile)),n&&(this.text=n)}consumer(){return this.consumerCache||(this.consumerCache=new ed(this.text)),this.consumerCache}decodeInline(e){if(/^data:application\/json;charset=utf-?8,/.test(e)||/^data:application\/json,/.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(e)||/^data:application\/json;base64,/.test(e))return t=e.substr(RegExp.lastMatch.length),Buffer?Buffer.from(t,"base64").toString():window.atob(t);var t;let r=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+r)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return"object"==typeof e&&("string"==typeof e.mappings||"string"==typeof e._mappings||Array.isArray(e.sections))}loadAnnotation(e){let t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(!t)return;let r=e.lastIndexOf(t.pop()),n=e.indexOf("*/",r);r>-1&&n>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,n)))}loadFile(e){if(this.root=sd(e),rd(e))return this.mapFile=e,nd(e,"utf-8").toString().trim()}loadMap(e,t){if(!1===t)return!1;if(t){if("string"==typeof t)return t;if("function"!=typeof t){if(t instanceof ed)return td.fromSourceMap(t).toString();if(t instanceof td)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}{let r=t(e);if(r){let e=this.loadFile(r);if(!e)throw new Error("Unable to load previous source map: "+r.toString());return e}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let t=this.annotation;return e&&(t=id(sd(e),t)),this.loadFile(t)}}}startWith(e,t){return!!e&&e.substr(0,t.length)===t}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var ad=od;od.default=od;let{SourceMapConsumer:ld,SourceMapGenerator:cd}=Ip,{fileURLToPath:ud,pathToFileURL:hd}=Ip,{isAbsolute:pd,resolve:dd}=Ip,{nanoid:fd}=Qp,md=Ip,gd=Pp,yd=ad,wd=Symbol("fromOffsetCache"),vd=Boolean(ld&&cd),bd=Boolean(dd&&pd),_d=class{constructor(e,t={}){if(null==e||"object"==typeof e&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!bd||/^\w+:\/\//.test(t.from)||pd(t.from)?this.file=t.from:this.file=dd(t.from)),bd&&vd){let e=new yd(this.css,t);if(e.text){this.map=e;let t=e.consumer().file;!this.file&&t&&(this.file=this.mapResolve(t))}}this.file||(this.id=""),this.map&&(this.map.file=this.from)}error(e,t,r,n={}){let s,i,o;if(t&&"object"==typeof t){let e=t,n=r;if("number"==typeof e.offset){let n=this.fromOffset(e.offset);t=n.line,r=n.col}else t=e.line,r=e.column;if("number"==typeof n.offset){let e=this.fromOffset(n.offset);i=e.line,o=e.col}else i=n.line,o=n.column}else if(!r){let e=this.fromOffset(t);t=e.line,r=e.col}let a=this.origin(t,r,i,o);return s=a?new gd(e,void 0===a.endLine?a.line:{column:a.column,line:a.line},void 0===a.endLine?a.column:{column:a.endColumn,line:a.endLine},a.source,a.file,n.plugin):new gd(e,void 0===i?t:{column:r,line:t},void 0===i?r:{column:o,line:i},this.css,this.file,n.plugin),s.input={column:r,endColumn:o,endLine:i,line:t,source:this.css},this.file&&(hd&&(s.input.url=hd(this.file).toString()),s.input.file=this.file),s}fromOffset(e){let t,r;if(this[wd])r=this[wd];else{let e=this.css.split("\n");r=new Array(e.length);let t=0;for(let n=0,s=e.length;n=t)n=r.length-1;else{let t,s=r.length-2;for(;n>1),e=r[t+1])){n=t;break}n=t+1}}return{col:e-r[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:dd(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,r,n){if(!this.map)return!1;let s,i,o=this.map.consumer(),a=o.originalPositionFor({column:t,line:e});if(!a.source)return!1;"number"==typeof r&&(s=o.originalPositionFor({column:n,line:r})),i=pd(a.source)?hd(a.source):new URL(a.source,this.map.consumer().sourceRoot||hd(this.map.mapFile));let l={column:a.column,endColumn:s&&s.column,endLine:s&&s.line,line:a.line,url:i.toString()};if("file:"===i.protocol){if(!ud)throw new Error("file: protocol is not available in this PostCSS build");l.file=ud(i)}let c=o.sourceContentFor(a.source);return c&&(l.source=c),l}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])null!=this[t]&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};var Sd=_d;_d.default=_d,md&&md.registerInput&&md.registerInput(_d);let{SourceMapConsumer:Cd,SourceMapGenerator:Ed}=Ip,{dirname:Td,relative:kd,resolve:xd,sep:Od}=Ip,{pathToFileURL:Ad}=Ip,Id=Sd,Rd=Boolean(Cd&&Ed),Md=Boolean(Td&&xd&&kd&&Od);var Nd=class{constructor(e,t,r,n){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=n,this.originalCSS=n,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let t="\n";this.css.includes("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"}applyPrevMaps(){for(let e of this.previous()){let t,r=this.toUrl(this.path(e.file)),n=e.root||Td(e.file);!1===this.mapOpts.sourcesContent?(t=new Cd(e.text),t.sourcesContent&&(t.sourcesContent=null)):t=e.consumer(),this.map.applySourceMap(t,r,this.toUrl(this.path(n)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],"comment"===e.type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),Md&&Rd&&this.isMap())return this.generateMap();{let e="";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=Ed.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new Ed({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):""});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new Ed({file:this.outputFile(),ignoreInvalidMapping:!0});let e,t,r=1,n=1,s="",i={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(o,a,l)=>{if(this.css+=o,a&&"end"!==l&&(i.generated.line=r,i.generated.column=n-1,a.source&&a.source.start?(i.source=this.sourcePath(a),i.original.line=a.source.start.line,i.original.column=a.source.start.column-1,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,this.map.addMapping(i))),e=o.match(/\n/g),e?(r+=e.length,t=o.lastIndexOf("\n"),n=o.length-t):n+=o.length,a&&"start"!==l){let e=a.parent||{raws:{}};("decl"===a.type||"atrule"===a.type&&!a.nodes)&&a===e.last&&!e.raws.semicolon||(a.source&&a.source.end?(i.source=this.sourcePath(a),i.original.line=a.source.end.line,i.original.column=a.source.end.column-1,i.generated.line=r,i.generated.column=n-2,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,i.generated.line=r,i.generated.column=n-1,this.map.addMapping(i)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(e=>e.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(e=>e.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(e=>e.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(e){if(this.mapOpts.absolute)return e;if(60===e.charCodeAt(0))return e;if(/^\w+:\/\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let r=this.opts.to?Td(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(r=Td(xd(r,this.mapOpts.annotation)));let n=kd(r,e);return this.memoizedPaths.set(e,n),n}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new Id(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let r=t.source.input.from;if(r&&!e[r]){e[r]=!0;let n=this.usesFileUrls?this.toFileUrl(r):this.toUrl(this.path(r));this.map.setSourceContent(n,t.source.input.css)}}});else if(this.css){let e=this.opts.from?this.toUrl(this.path(this.opts.from)):"";this.map.setSourceContent(e,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(Ad){let t=Ad(e).toString();return this.memoizedFileURLs.set(e,t),t}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;"\\"===Od&&(e=e.replace(/\\/g,"/"));let r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r}};let Pd=Xp,Ld=class extends Pd{constructor(e){super(e),this.type="comment"}};var Dd=Ld;Ld.default=Ld;let Ud,Fd,Bd,jd,{isClean:zd,my:Vd}=Lp,Gd=qp,Hd=Dd,Zd=Xp;function $d(e){return e.map(e=>(e.nodes&&(e.nodes=$d(e.nodes)),delete e.source,e))}function Wd(e){if(e[zd]=!1,e.proxyOf.nodes)for(let t of e.proxyOf.nodes)Wd(t)}let Yd=class e extends Zd{append(...e){for(let t of e){let e=this.normalize(t,this.last);for(let t of e)this.proxyOf.nodes.push(t)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t,r,n=this.getIterator();for(;this.indexes[n]"proxyOf"===t?e:e[t]?"each"===t||"string"==typeof t&&t.startsWith("walk")?(...r)=>e[t](...r.map(e=>"function"==typeof e?(t,r)=>e(t.toProxy(),r):e)):"every"===t||"some"===t?r=>e[t]((e,...t)=>r(e.toProxy(),...t)):"root"===t?()=>e.root().toProxy():"nodes"===t?e.nodes.map(e=>e.toProxy()):"first"===t||"last"===t?e[t].toProxy():e[t]:e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"name"!==t&&"params"!==t&&"selector"!==t||e.markDirty()),!0)}}index(e){return"number"==typeof e?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let r,n=this.index(e),s=this.normalize(t,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(let e of s)this.proxyOf.nodes.splice(n+1,0,e);for(let e in this.indexes)r=this.indexes[e],n(t[Vd]||e.rebuild(t),(t=t.proxyOf).parent&&t.parent.removeChild(t),t[zd]&&Wd(t),void 0===t.raws.before&&r&&void 0!==r.raws.before&&(t.raws.before=r.raws.before.replace(/\S/g,"")),t.parent=this.proxyOf,t))}prepend(...e){e=e.reverse();for(let t of e){let e=this.normalize(t,this.first,"prepend").reverse();for(let t of e)this.proxyOf.nodes.unshift(t);for(let t in this.indexes)this.indexes[t]=this.indexes[t]+e.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){let t;e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);for(let r in this.indexes)t=this.indexes[r],t>=e&&(this.indexes[r]=t-1);return this.markDirty(),this}replaceValues(e,t,r){return r||(r=t,t={}),this.walkDecls(n=>{t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,r))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,r)=>{let n;try{n=e(t,r)}catch(e){throw t.addToError(e)}return!1!==n&&t.walk&&(n=t.walk(e)),n})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("atrule"===r.type&&e.test(r.name))return t(r,n)}):this.walk((r,n)=>{if("atrule"===r.type&&r.name===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("atrule"===e.type)return t(e,r)}))}walkComments(e){return this.walk((t,r)=>{if("comment"===t.type)return e(t,r)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("decl"===r.type&&e.test(r.prop))return t(r,n)}):this.walk((r,n)=>{if("decl"===r.type&&r.prop===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("decl"===e.type)return t(e,r)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("rule"===r.type&&e.test(r.selector))return t(r,n)}):this.walk((r,n)=>{if("rule"===r.type&&r.selector===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("rule"===e.type)return t(e,r)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Yd.registerParse=e=>{Ud=e},Yd.registerRule=e=>{Fd=e},Yd.registerAtRule=e=>{Bd=e},Yd.registerRoot=e=>{jd=e};var Xd=Yd;Yd.default=Yd,Yd.rebuild=e=>{"atrule"===e.type?Object.setPrototypeOf(e,Bd.prototype):"rule"===e.type?Object.setPrototypeOf(e,Fd.prototype):"decl"===e.type?Object.setPrototypeOf(e,Gd.prototype):"comment"===e.type?Object.setPrototypeOf(e,Hd.prototype):"root"===e.type&&Object.setPrototypeOf(e,jd.prototype),e[Vd]=!0,e.nodes&&e.nodes.forEach(e=>{Yd.rebuild(e)})};let Jd,Kd,qd=Xd,Qd=class extends qd{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new Jd(new Kd,this,e).stringify()}};Qd.registerLazyResult=e=>{Jd=e},Qd.registerProcessor=e=>{Kd=e};var ef=Qd;Qd.default=Qd;let tf={};var rf=function(e){tf[e]||(tf[e]=!0,"undefined"!=typeof console&&console.warn&&console.warn(e))};let nf=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let e=t.node.rangeBy(t);this.line=e.start.line,this.column=e.start.column,this.endLine=e.end.line,this.endColumn=e.end.column}for(let e in t)this[e]=t[e]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var sf=nf;nf.default=nf;let of=sf,af=class{constructor(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let r=new of(e,t);return this.messages.push(r),r}warnings(){return this.messages.filter(e=>"warning"===e.type)}get content(){return this.css}};var lf=af;af.default=af;const cf="'".charCodeAt(0),uf='"'.charCodeAt(0),hf="\\".charCodeAt(0),pf="/".charCodeAt(0),df="\n".charCodeAt(0),ff=" ".charCodeAt(0),mf="\f".charCodeAt(0),gf="\t".charCodeAt(0),yf="\r".charCodeAt(0),wf="[".charCodeAt(0),vf="]".charCodeAt(0),bf="(".charCodeAt(0),_f=")".charCodeAt(0),Sf="{".charCodeAt(0),Cf="}".charCodeAt(0),Ef=";".charCodeAt(0),Tf="*".charCodeAt(0),kf=":".charCodeAt(0),xf="@".charCodeAt(0),Of=/[\t\n\f\r "#'()/;[\\\]{}]/g,Af=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,If=/.[\r\n"'(/\\]/,Rf=/[\da-f]/i;let Mf=Xd,Nf=class extends Mf{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};var Pf=Nf;Nf.default=Nf,Mf.registerAtRule(Nf);let Lf,Df,Uf=Xd,Ff=class extends Uf{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,r){let n=super.normalize(e);if(t)if("prepend"===r)this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let e of n)e.raws.before=t.raws.before;return n}removeChild(e,t){let r=this.index(e);return!t&&0===r&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[r].raws.before),super.removeChild(e)}toResult(e={}){return new Lf(new Df,this,e).stringify()}};Ff.registerLazyResult=e=>{Lf=e},Ff.registerProcessor=e=>{Df=e};var Bf=Ff;Ff.default=Ff,Uf.registerRoot(Ff);let jf={comma:e=>jf.split(e,[","],!0),space:e=>jf.split(e,[" ","\n","\t"]),split(e,t,r){let n=[],s="",i=!1,o=0,a=!1,l="",c=!1;for(let r of e)c?c=!1:"\\"===r?c=!0:a?r===l&&(a=!1):'"'===r||"'"===r?(a=!0,l=r):"("===r?o+=1:")"===r?o>0&&(o-=1):0===o&&t.includes(r)&&(i=!0),i?(""!==s&&n.push(s.trim()),s="",i=!1):s+=r;return(r||""!==s)&&n.push(s.trim()),n}};var zf=jf;jf.default=jf;let Vf=Xd,Gf=zf,Hf=class extends Vf{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Gf.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,r=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(r)}};var Zf=Hf;Hf.default=Hf,Vf.registerRule(Hf);let $f=qp,Wf=function(e,t={}){let r,n,s,i,o,a,l,c,u,h,p=e.css.valueOf(),d=t.ignoreErrors,f=p.length,m=0,g=[],y=[];function w(t){throw e.error("Unclosed "+t,m)}return{back:function(e){y.push(e)},endOfFile:function(){return 0===y.length&&m>=f},nextToken:function(e){if(y.length)return y.pop();if(m>=f)return;let t=!!e&&e.ignoreUnclosed;switch(r=p.charCodeAt(m),r){case df:case ff:case gf:case yf:case mf:n=m;do{n+=1,r=p.charCodeAt(n)}while(r===ff||r===df||r===gf||r===yf||r===mf);h=["space",p.slice(m,n)],m=n-1;break;case wf:case vf:case Sf:case Cf:case kf:case Ef:case _f:{let e=String.fromCharCode(r);h=[e,e,m];break}case bf:if(c=g.length?g.pop()[1]:"",u=p.charCodeAt(m+1),"url"===c&&u!==cf&&u!==uf&&u!==ff&&u!==df&&u!==gf&&u!==mf&&u!==yf){n=m;do{if(a=!1,n=p.indexOf(")",n+1),-1===n){if(d||t){n=m;break}w("bracket")}for(l=n;p.charCodeAt(l-1)===hf;)l-=1,a=!a}while(a);h=["brackets",p.slice(m,n+1),m,n],m=n}else n=p.indexOf(")",m+1),i=p.slice(m,n+1),-1===n||If.test(i)?h=["(","(",m]:(h=["brackets",i,m,n],m=n);break;case cf:case uf:s=r===cf?"'":'"',n=m;do{if(a=!1,n=p.indexOf(s,n+1),-1===n){if(d||t){n=m+1;break}w("string")}for(l=n;p.charCodeAt(l-1)===hf;)l-=1,a=!a}while(a);h=["string",p.slice(m,n+1),m,n],m=n;break;case xf:Of.lastIndex=m+1,Of.test(p),n=0===Of.lastIndex?p.length-1:Of.lastIndex-2,h=["at-word",p.slice(m,n+1),m,n],m=n;break;case hf:for(n=m,o=!0;p.charCodeAt(n+1)===hf;)n+=1,o=!o;if(r=p.charCodeAt(n+1),o&&r!==pf&&r!==ff&&r!==df&&r!==gf&&r!==yf&&r!==mf&&(n+=1,Rf.test(p.charAt(n)))){for(;Rf.test(p.charAt(n+1));)n+=1;p.charCodeAt(n+1)===ff&&(n+=1)}h=["word",p.slice(m,n+1),m,n],m=n;break;default:r===pf&&p.charCodeAt(m+1)===Tf?(n=p.indexOf("*/",m+2)+1,0===n&&(d||t?n=p.length:w("comment")),h=["comment",p.slice(m,n+1),m,n],m=n):(Af.lastIndex=m+1,Af.test(p),n=0===Af.lastIndex?p.length-1:Af.lastIndex-2,h=["word",p.slice(m,n+1),m,n],g.push(h),m=n)}return m++,h},position:function(){return m}}},Yf=Dd,Xf=Pf,Jf=Bf,Kf=Zf;const qf={empty:!0,space:!0};var Qf=class{constructor(e){this.input=e,this.root=new Jf,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t,r,n,s=new Xf;s.name=e[1].slice(1),""===s.name&&this.unnamedAtrule(s,e),this.init(s,e[2]);let i=!1,o=!1,a=[],l=[];for(;!this.tokenizer.endOfFile();){if(t=(e=this.tokenizer.nextToken())[0],"("===t||"["===t?l.push("("===t?")":"]"):"{"===t&&l.length>0?l.push("}"):t===l[l.length-1]&&l.pop(),0===l.length){if(";"===t){s.source.end=this.getPosition(e[2]),s.source.end.offset++,this.semicolon=!0;break}if("{"===t){o=!0;break}if("}"===t){if(a.length>0){for(n=a.length-1,r=a[n];r&&"space"===r[0];)r=a[--n];r&&(s.source.end=this.getPosition(r[3]||r[2]),s.source.end.offset++)}this.end(e);break}a.push(e)}else a.push(e);if(this.tokenizer.endOfFile()){i=!0;break}}s.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(s.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(s,"params",a),i&&(e=a[a.length-1],s.source.end=this.getPosition(e[3]||e[2]),s.source.end.offset++,this.spaces=s.raws.between,s.raws.between="")):(s.raws.afterName="",s.params=""),o&&(s.nodes=[],this.current=s)}checkMissedSemicolon(e){let t=this.colon(e);if(!1===t)return;let r,n=0;for(let s=t-1;s>=0&&(r=e[s],"space"===r[0]||(n+=1,2!==n));s--);throw this.input.error("Missed semicolon","word"===r[0]?r[3]+1:r[2])}colon(e){let t,r,n,s=0;for(let[i,o]of e.entries()){if(t=o,r=t[0],"("===r&&(s+=1),")"===r&&(s-=1),0===s&&":"===r){if(n){if("word"===n[0]&&"progid"===n[1])continue;return i}this.doubleColon(t)}n=t}return!1}comment(e){let t=new Yf;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let r=e[1].slice(2,-2);if(/^\s*$/.test(r))t.text="",t.raws.left=r,t.raws.right="";else{let e=r.match(/^(\s*)([^]*\S)(\s*)$/);t.text=e[2],t.raws.left=e[1],t.raws.right=e[3]}}createTokenizer(){this.tokenizer=Wf(this.input)}decl(e,t){let r=new $f;this.init(r,e[0][2]);let n,s=e[e.length-1];for(";"===s[0]&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(s[3]||s[2]||function(e){for(let t=e.length-1;t>=0;t--){let r=e[t],n=r[3]||r[2];if(n)return n}}(e)),r.source.end.offset++;"word"!==e[0][0];)1===e.length&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop="";e.length;){let t=e[0][0];if(":"===t||"space"===t||"comment"===t)break;r.prop+=e.shift()[1]}for(r.raws.between="";e.length;){if(n=e.shift(),":"===n[0]){r.raws.between+=n[1];break}"word"===n[0]&&/\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1]}"_"!==r.prop[0]&&"*"!==r.prop[0]||(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));let i,o=[];for(;e.length&&(i=e[0][0],"space"===i||"comment"===i);)o.push(e.shift());this.precheckMissedSemicolon(e);for(let t=e.length-1;t>=0;t--){if(n=e[t],"!important"===n[1].toLowerCase()){r.important=!0;let n=this.stringFrom(e,t);n=this.spacesFromEnd(e)+n," !important"!==n&&(r.raws.important=n);break}if("important"===n[1].toLowerCase()){let n=e.slice(0),s="";for(let e=t;e>0;e--){let t=n[e][0];if(0===s.trim().indexOf("!")&&"space"!==t)break;s=n.pop()[1]+s}0===s.trim().indexOf("!")&&(r.important=!0,r.raws.important=s,e=n)}if("space"!==n[0]&&"comment"!==n[0])break}e.some(e=>"space"!==e[0]&&"comment"!==e[0])&&(r.raws.between+=o.map(e=>e[1]).join(""),o=[]),this.raw(r,"value",o.concat(e),t),r.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new Kf;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let e=this.current.nodes[this.current.nodes.length-1];e&&"rule"===e.type&&!e.raws.ownSemicolon&&(e.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="","comment"!==e.type&&(this.semicolon=!1)}other(e){let t=!1,r=null,n=!1,s=null,i=[],o=e[1].startsWith("--"),a=[],l=e;for(;l;){if(r=l[0],a.push(l),"("===r||"["===r)s||(s=l),i.push("("===r?")":"]");else if(o&&n&&"{"===r)s||(s=l),i.push("}");else if(0===i.length){if(";"===r){if(n)return void this.decl(a,o);break}if("{"===r)return void this.rule(a);if("}"===r){this.tokenizer.back(a.pop()),t=!0;break}":"===r&&(n=!0)}else r===i[i.length-1]&&(i.pop(),0===i.length&&(s=null));l=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),i.length>0&&this.unclosedBracket(s),t&&n){if(!o)for(;a.length&&(l=a[a.length-1][0],"space"===l||"comment"===l);)this.tokenizer.back(a.pop());this.decl(a,o)}else this.unknownWord(a)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e)}this.endFile()}precheckMissedSemicolon(){}raw(e,t,r,n){let s,i,o,a,l=r.length,c="",u=!0;for(let e=0;ee+t[1],"");e.raws[t]={raw:n,value:c}}e[t]=c}rule(e){e.pop();let t=new Kf;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t||"comment"===t);)r=e.pop()[1]+r;return r}spacesAndCommentsFromStart(e){let t,r="";for(;e.length&&(t=e[0][0],"space"===t||"comment"===t);)r+=e.shift()[1];return r}spacesFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t);)r=e.pop()[1]+r;return r}stringFrom(e,t){let r="";for(let n=t;n_m(e)),e}let Sm={},Cm=class e{constructor(t,r,n){let s;if(this.stringified=!1,this.processed=!1,"object"!=typeof r||null===r||"root"!==r.type&&"document"!==r.type)if(r instanceof e||r instanceof pm)s=_m(r.root),r.map&&(void 0===n.map&&(n.map={}),n.map.inline||(n.map.inline=!1),n.map.prev=r.map);else{let e=dm;n.syntax&&(e=n.syntax.parse),n.parser&&(e=n.parser),e.parse&&(e=e.parse);try{s=e(r,n)}catch(e){this.processed=!0,this.error=e}s&&!s[om]&&cm.rebuild(s)}else s=_m(r);this.result=new pm(t,s,n),this.helpers={...Sm,postcss:Sm,result:this.result},this.plugins=this.processor.plugins.map(e=>"object"==typeof e&&e.prepare?{...e,...e.prepare(this.result)}:e)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let r=this.result.lastPlugin;try{if(t&&t.addToError(e),this.error=e,"CssSyntaxError"!==e.name||e.plugin){if(r.postcssVersion&&"production"!==process.env.NODE_ENV){let e=r.postcssPlugin,t=r.postcssVersion,n=this.result.processor.version,s=t.split("."),i=n.split(".");(s[0]!==i[0]||parseInt(s[1])>parseInt(i[1]))&&console.error("Unknown error from PostCSS plugin. Your current PostCSS version is "+n+", but "+e+" uses "+t+". Perhaps this is the source of the error below.")}}else e.plugin=r.postcssPlugin,e.setMessage()}catch(e){console&&console.error&&console.error(e)}return e}prepareVisitors(){this.listeners={};let e=(e,t,r)=>{this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push([e,r])};for(let t of this.plugins)if("object"==typeof t)for(let r in t){if(!gm[r]&&/^[A-Z]/.test(r))throw new Error(`Unknown event ${r} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!ym[r])if("object"==typeof t[r])for(let n in t[r])e(t,"*"===n?r:r+"-"+n.toLowerCase(),t[r][n]);else"function"==typeof t[r]&&e(t,r,t[r])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e0;){let e=this.visitTick(t);if(wm(e))try{await e}catch(e){let r=t[t.length-1].node;throw this.handleError(e,r)}}}if(this.listeners.OnceExit)for(let[t,r]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if("document"===e.type){let t=e.nodes.map(e=>r(e,this.helpers));await Promise.all(t)}else await r(e,this.helpers)}catch(e){throw this.handleError(e)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if("object"==typeof e&&e.Once){if("document"===this.result.root.type){let t=this.result.root.nodes.map(t=>e.Once(t,this.helpers));return wm(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}if("function"==typeof e)return e(this.result.root,this.result)}catch(e){throw this.handleError(e)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=lm;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new am(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){if(wm(this.runOnRoot(e)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[im];)e[im]=!0,this.walkSync(e);if(this.listeners.OnceExit)if("document"===e.type)for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this.opts||hm("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[r,n]of e){let e;this.result.lastPlugin=r;try{e=n(t,this.helpers)}catch(e){throw this.handleError(e,t.proxyOf)}if("root"!==t.type&&"document"!==t.type&&!t.parent)return!0;if(wm(e))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:r,visitors:n}=t;if("root"!==r.type&&"document"!==r.type&&!r.parent)return void e.pop();if(n.length>0&&t.visitorIndex{e[im]||this.walkSync(e)});else{let t=this.listeners[r];if(t&&this.visitSync(t,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};Cm.registerPostcss=e=>{Sm=e};var Em=Cm;Cm.default=Cm,fm.registerLazyResult(Cm),um.registerLazyResult(Cm);let Tm=Nd,km=zp,xm=rf,Om=sm;const Am=lf;let Im=class{constructor(e,t,r){let n;t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;let s=km;this.result=new Am(this._processor,n,this._opts),this.result.css=t;let i=this;Object.defineProperty(this.result,"root",{get:()=>i.root});let o=new Tm(s,n,this._opts,t);if(o.isMap()){let[e,t]=o.generate();e&&(this.result.css=e),t&&(this.result.map=t)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this._opts||xm("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=Om;try{e=t(this._css,this._opts)}catch(e){this.error=e}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}};var Rm=Im;Im.default=Im;let Mm=Rm,Nm=Em,Pm=ef,Lm=Bf,Dm=class{constructor(e=[]){this.version="8.4.38",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let r of e)if(!0===r.postcss?r=r():r.postcss&&(r=r.postcss),"object"==typeof r&&Array.isArray(r.plugins))t=t.concat(r.plugins);else if("object"==typeof r&&r.postcssPlugin)t.push(r);else if("function"==typeof r)t.push(r);else{if("object"!=typeof r||!r.parse&&!r.stringify)throw new Error(r+" is not a PostCSS plugin");if("production"!==process.env.NODE_ENV)throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.")}return t}process(e,t={}){return this.plugins.length||t.parser||t.stringifier||t.syntax?new Nm(this,e,t):new Mm(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};var Um=Dm;Dm.default=Dm,Lm.registerProcessor(Dm),Pm.registerProcessor(Dm);let Fm=qp,Bm=ad,jm=Dd,zm=Pf,Vm=Sd,Gm=Bf,Hm=Zf;function Zm(e,t){if(Array.isArray(e))return e.map(e=>Zm(e));let{inputs:r,...n}=e;if(r){t=[];for(let e of r){let r={...e,__proto__:Vm.prototype};r.map&&(r.map={...r.map,__proto__:Bm.prototype}),t.push(r)}}if(n.nodes&&(n.nodes=e.nodes.map(e=>Zm(e,t))),n.source){let{inputId:e,...r}=n.source;n.source=r,null!=e&&(n.source.input=t[e])}if("root"===n.type)return new Gm(n);if("decl"===n.type)return new Fm(n);if("rule"===n.type)return new Hm(n);if("comment"===n.type)return new jm(n);if("atrule"===n.type)return new zm(n);throw new Error("Unknown node type: "+e.type)}var $m=Zm;Zm.default=Zm;let Wm=Pp,Ym=qp,Xm=Em,Jm=Xd,Km=Um,qm=zp,Qm=$m,eg=ef,tg=sf,rg=Dd,ng=Pf,sg=lf,ig=Sd,og=sm,ag=zf,lg=Zf,cg=Bf,ug=Xp;function hg(...e){return 1===e.length&&Array.isArray(e[0])&&(e=e[0]),new Km(e)}hg.plugin=function(e,t){let r,n=!1;function s(...r){console&&console.warn&&!n&&(n=!0,console.warn(e+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226"));let s=t(...r);return s.postcssPlugin=e,s.postcssVersion=(new Km).version,s}return Object.defineProperty(s,"postcss",{get:()=>(r||(r=s()),r)}),s.process=function(e,t,r){return hg([s(r)]).process(e,t)},s},hg.stringify=qm,hg.parse=og,hg.fromJSON=Qm,hg.list=ag,hg.comment=e=>new rg(e),hg.atRule=e=>new ng(e),hg.decl=e=>new Ym(e),hg.rule=e=>new lg(e),hg.root=e=>new cg(e),hg.document=e=>new eg(e),hg.CssSyntaxError=Wm,hg.Declaration=Ym,hg.Container=Jm,hg.Processor=Km,hg.Document=eg,hg.Comment=rg,hg.Warning=tg,hg.AtRule=ng,hg.Result=sg,hg.Input=ig,hg.Rule=lg,hg.Root=cg,hg.Node=ug,Xm.registerPostcss(hg);var pg=hg;hg.default=hg;const dg=Ep(pg);dg.stringify,dg.fromJSON,dg.plugin,dg.parse,dg.list,dg.document,dg.comment,dg.atRule,dg.rule,dg.decl,dg.root,dg.CssSyntaxError,dg.Declaration,dg.Container,dg.Processor,dg.Document,dg.Comment,dg.Warning,dg.AtRule,dg.Result,dg.Input,dg.Rule,dg.Root,dg.Node;class fg{constructor(...e){Cp(this,"parentElement",null),Cp(this,"parentNode",null),Cp(this,"ownerDocument"),Cp(this,"firstChild",null),Cp(this,"lastChild",null),Cp(this,"previousSibling",null),Cp(this,"nextSibling",null),Cp(this,"ELEMENT_NODE",1),Cp(this,"TEXT_NODE",3),Cp(this,"nodeType"),Cp(this,"nodeName"),Cp(this,"RRNodeType")}get childNodes(){const e=[];let t=this.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}contains(e){if(!(e instanceof fg))return!1;if(e.ownerDocument!==this.ownerDocument)return!1;if(e===this)return!0;for(;e.parentNode;){if(e.parentNode===this)return!0;e=e.parentNode}return!1}appendChild(e){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(e,t){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(e){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}}const mg={Node:["childNodes","parentNode","parentElement","textContent","ownerDocument"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},gg={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},yg={};function wg(e){if(yg[e])return yg[e];const t=globalThis[e],r=t.prototype,n=e in mg?mg[e]:void 0,s=Boolean(n&&n.every(e=>{var t,n;return Boolean(null==(n=null==(t=Object.getOwnPropertyDescriptor(r,e))?void 0:t.get)?void 0:n.toString().includes("[native code]"))})),i=e in gg?gg[e]:void 0,o=Boolean(i&&i.every(e=>{var t;return"function"==typeof r[e]&&(null==(t=r[e])?void 0:t.toString().includes("[native code]"))}));if(s&&o&&!globalThis.Zone)return yg[e]=t.prototype,t.prototype;try{const n=document.createElement("iframe");document.body.appendChild(n);const s=n.contentWindow;if(!s)return t.prototype;const i=s[e].prototype;return document.body.removeChild(n),i?yg[e]=i:r}catch{return r}}const vg={};function bg(e,t,r){var n;const s=`${e}.${String(r)}`;if(vg[s])return vg[s].call(t);const i=wg(e),o=null==(n=Object.getOwnPropertyDescriptor(i,r))?void 0:n.get;return o?(vg[s]=o,o.call(t)):t[r]}const _g={};function Sg(e,t,r){const n=`${e}.${String(r)}`;if(_g[n])return _g[n].bind(t);const s=wg(e)[r];return"function"!=typeof s?t[r]:(_g[n]=s,s.bind(t))}function Cg(){return wg("MutationObserver").constructor}function Eg(e,t,r){try{if(!(t in e))return()=>{};const n=e[t],s=r(n);return"function"==typeof s&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__rrweb_original__:{enumerable:!1,value:n}})),e[t]=s,()=>{e[t]=n}}catch{return()=>{}}}const Tg={ownerDocument:function(e){return bg("Node",e,"ownerDocument")},childNodes:function(e){return bg("Node",e,"childNodes")},parentNode:function(e){return bg("Node",e,"parentNode")},parentElement:function(e){return bg("Node",e,"parentElement")},textContent:function(e){return bg("Node",e,"textContent")},contains:function(e,t){return Sg("Node",e,"contains")(t)},getRootNode:function(e){return Sg("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?bg("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?bg("Element",e,"shadowRoot"):null},querySelector:function(e,t){return bg("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return bg("Element",e,"querySelectorAll")(t)},mutationObserver:Cg,patch:Eg};function kg(e,t,r=document){const n={capture:!0,passive:!0};return r.addEventListener(e,t,n),()=>r.removeEventListener(e,t,n)}const xg="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";let Og={map:{},getId:()=>(console.error(xg),-1),getNode:()=>(console.error(xg),null),removeNodeFromMap(){console.error(xg)},has:()=>(console.error(xg),!1),reset(){console.error(xg)}};function Ag(e,t,r={}){let n=null,s=0;return function(...i){const o=Date.now();s||!1!==r.leading||(s=o);const a=t-(o-s),l=this;a<=0||a>t?(n&&(clearTimeout(n),n=null),s=o,e.apply(l,i)):n||!1===r.trailing||(n=setTimeout(()=>{s=!1===r.leading?0:Date.now(),n=null,e.apply(l,i)},a))}}function Ig(e,t,r,n,s=window){const i=s.Object.getOwnPropertyDescriptor(e,t);return s.Object.defineProperty(e,t,n?r:{set(e){setTimeout(()=>{r.set.call(this,e)},0),i&&i.set&&i.set.call(this,e)}}),()=>Ig(e,t,i||{},!0)}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(Og=new Proxy(Og,{get:(e,t,r)=>("map"===t&&console.error(xg),Reflect.get(e,t,r))}));let Rg=Date.now;function Mg(e){var t,r,n,s;const i=e.document;return{left:i.scrollingElement?i.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:i.documentElement.scrollLeft||(null==i?void 0:i.body)&&(null==(t=Tg.parentElement(i.body))?void 0:t.scrollLeft)||(null==(r=null==i?void 0:i.body)?void 0:r.scrollLeft)||0,top:i.scrollingElement?i.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==i?void 0:i.documentElement.scrollTop)||(null==i?void 0:i.body)&&(null==(n=Tg.parentElement(i.body))?void 0:n.scrollTop)||(null==(s=null==i?void 0:i.body)?void 0:s.scrollTop)||0}}function Ng(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Pg(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Lg(e){if(!e)return null;return e.nodeType===e.ELEMENT_NODE?e:Tg.parentElement(e)}function Dg(e,t,r,n){if(!e)return!1;const s=Lg(e);if(!s)return!1;try{if("string"==typeof t){if(s.classList.contains(t))return!0;if(n&&null!==s.closest("."+t))return!0}else if(xl(s,t,n))return!0}catch(e){}if(r){if(s.matches(r))return!0;if(n&&null!==s.closest(r))return!0}return!1}function Ug(e,t,r){return!("TITLE"!==e.tagName||!r.headTitleMutations)||-2===t.getId(e)}function Fg(e,t){if(Ka(e))return!1;const r=t.getId(e);if(!t.has(r))return!0;const n=Tg.parentNode(e);return(!n||n.nodeType!==e.DOCUMENT_NODE)&&(!n||Fg(n,t))}function Bg(e){return Boolean(e.changedTouches)}function jg(e,t){return Boolean("IFRAME"===e.nodeName&&t.getMeta(e))}function zg(e,t){return Boolean("LINK"===e.nodeName&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&"stylesheet"===e.getAttribute("rel")&&t.getMeta(e))}function Vg(e){return!!e&&(e instanceof fg&&"shadowRoot"in e?Boolean(e.shadowRoot):Boolean(Tg.shadowRoot(e)))}/[1-9][0-9]{12}/.test(Date.now().toString())||(Rg=()=>(new Date).getTime());class Gg{constructor(){Ua(this,"id",1),Ua(this,"styleIDMap",new WeakMap),Ua(this,"idStyleMap",new Map)}getId(e){return this.styleIDMap.get(e)??-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let r;return r=void 0===t?this.id++:t,this.styleIDMap.set(e,r),this.idStyleMap.set(r,e),r}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}function Hg(e){var t;let r=null;return"getRootNode"in e&&(null==(t=Tg.getRootNode(e))?void 0:t.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&Tg.host(Tg.getRootNode(e))&&(r=Tg.host(Tg.getRootNode(e))),r}function Zg(e){const t=Tg.ownerDocument(e);if(!t)return!1;const r=function(e){let t,r=e;for(;t=Hg(r);)r=t;return r}(e);return Tg.contains(t,r)}function $g(e){const t=Tg.ownerDocument(e);return!!t&&(Tg.contains(t,e)||Zg(e))}var Wg=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(Wg||{}),Yg=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(Yg||{}),Xg=(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(Xg||{}),Jg=(e=>(e[e.Mouse=0]="Mouse",e[e.Pen=1]="Pen",e[e.Touch=2]="Touch",e))(Jg||{}),Kg=(e=>(e[e["2D"]=0]="2D",e[e.WebGL=1]="WebGL",e[e.WebGL2=2]="WebGL2",e))(Kg||{}),qg=(e=>(e[e.Play=0]="Play",e[e.Pause=1]="Pause",e[e.Seeked=2]="Seeked",e[e.VolumeChange=3]="VolumeChange",e[e.RateChange=4]="RateChange",e))(qg||{}),Qg=(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(Qg||{});function ey(e){return"__ln"in e}class ty{constructor(){Ua(this,"length",0),Ua(this,"head",null),Ua(this,"tail",null)}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let r=0;r`${e}@${t}`;class ny{constructor(){Ua(this,"frozen",!1),Ua(this,"locked",!1),Ua(this,"texts",[]),Ua(this,"attributes",[]),Ua(this,"attributeMap",new WeakMap),Ua(this,"removes",[]),Ua(this,"mapRemoves",[]),Ua(this,"movedMap",{}),Ua(this,"addedSet",new Set),Ua(this,"movedSet",new Set),Ua(this,"droppedSet",new Set),Ua(this,"removesSubTreeCache",new Set),Ua(this,"mutationCb"),Ua(this,"blockClass"),Ua(this,"blockSelector"),Ua(this,"maskTextClass"),Ua(this,"maskTextSelector"),Ua(this,"inlineStylesheet"),Ua(this,"maskInputOptions"),Ua(this,"maskTextFn"),Ua(this,"maskInputFn"),Ua(this,"keepIframeSrcFn"),Ua(this,"recordCanvas"),Ua(this,"inlineImages"),Ua(this,"slimDOMOptions"),Ua(this,"dataURLOptions"),Ua(this,"doc"),Ua(this,"mirror"),Ua(this,"iframeManager"),Ua(this,"stylesheetManager"),Ua(this,"shadowDomManager"),Ua(this,"canvasManager"),Ua(this,"processedNodeManager"),Ua(this,"unattachedDoc"),Ua(this,"processMutations",e=>{e.forEach(this.processMutation),this.emit()}),Ua(this,"emit",()=>{if(this.frozen||this.locked)return;const e=[],t=new Set,r=new ty,n=e=>{let t=e,r=-2;for(;-2===r;)t=t&&t.nextSibling,r=t&&this.mirror.getId(t);return r},s=s=>{const i=Tg.parentNode(s);if(!i||!$g(s))return;let o=!1;if(s.nodeType===Node.TEXT_NODE){const e=i.tagName;if("TEXTAREA"===e)return;"STYLE"===e&&this.addedSet.has(i)&&(o=!0)}const a=Ka(i)?this.mirror.getId(Hg(s)):this.mirror.getId(i),l=n(s);if(-1===a||-1===l)return r.addNode(s);const c=Ml(s,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:e=>{jg(e,this.mirror)&&this.iframeManager.addIframe(e),zg(e,this.mirror)&&this.stylesheetManager.trackLinkElement(e),Vg(s)&&this.shadowDomManager.addShadowRoot(Tg.shadowRoot(s),this.doc)},onIframeLoad:(e,t)=>{this.iframeManager.attachIframe(e,t),this.shadowDomManager.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{this.stylesheetManager.attachLinkElement(e,t)},cssCaptured:o});c&&(e.push({parentId:a,nextId:l,node:c}),t.add(c.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const e of this.movedSet)iy(this.removesSubTreeCache,e,this.mirror)&&!this.movedSet.has(Tg.parentNode(e))||s(e);for(const e of this.addedSet)oy(this.droppedSet,e)||iy(this.removesSubTreeCache,e,this.mirror)?oy(this.movedSet,e)?s(e):this.droppedSet.add(e):s(e);let i=null;for(;r.length;){let e=null;if(i){const t=this.mirror.getId(Tg.parentNode(i.value)),r=n(i.value);-1!==t&&-1!==r&&(e=i)}if(!e){let t=r.tail;for(;t;){const r=t;if(t=t.previous,r){const t=this.mirror.getId(Tg.parentNode(r.value));if(-1===n(r.value))continue;if(-1!==t){e=r;break}{const t=r.value,n=Tg.parentNode(t);if(n&&n.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const t=Tg.host(n);if(-1!==this.mirror.getId(t)){e=r;break}}}}}}if(!e){for(;r.head;)r.removeNode(r.head.value);break}i=e.previous,r.removeNode(e.value),s(e.value)}const o={texts:this.texts.map(e=>{const t=e.node,r=Tg.parentNode(t);return r&&"TEXTAREA"===r.tagName&&this.genTextAreaValueMutation(r),{id:this.mirror.getId(t),value:e.value}}).filter(e=>!t.has(e.id)).filter(e=>this.mirror.has(e.id)),attributes:this.attributes.map(e=>{const{attributes:t}=e;if("string"==typeof t.style){const r=JSON.stringify(e.styleDiff),n=JSON.stringify(e._unchangedStyles);r.length!t.has(e.id)).filter(e=>this.mirror.has(e.id)),removes:this.removes,adds:e};(o.texts.length||o.attributes.length||o.removes.length||o.adds.length)&&(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.removesSubTreeCache=new Set,this.movedMap={},this.mutationCb(o))}),Ua(this,"genTextAreaValueMutation",e=>{let t=this.attributeMap.get(e);t||(t={node:e,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(t),this.attributeMap.set(e,t));const r=Array.from(Tg.childNodes(e),e=>Tg.textContent(e)||"").join("");t.attributes.value=rl({element:e,maskInputOptions:this.maskInputOptions,tagName:e.tagName,type:il(e),value:r,maskInputFn:this.maskInputFn})}),Ua(this,"processMutation",e=>{if(!Ug(e.target,this.mirror,this.slimDOMOptions))switch(e.type){case"characterData":{const t=Tg.textContent(e.target);Dg(e.target,this.blockClass,this.blockSelector,!1)||t===e.oldValue||this.texts.push({value:Ol(e.target,this.maskTextClass,this.maskTextSelector,!0)&&t?this.maskTextFn?this.maskTextFn(t,Lg(e.target)):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{const t=e.target;let r=e.attributeName,n=e.target.getAttribute(r);if("value"===r){const e=il(t);n=rl({element:t,maskInputOptions:this.maskInputOptions,tagName:t.tagName,type:e,value:n,maskInputFn:this.maskInputFn})}if(Dg(e.target,this.blockClass,this.blockSelector,!1)||n===e.oldValue)return;let s=this.attributeMap.get(e.target);if("IFRAME"===t.tagName&&"src"===r&&!this.keepIframeSrcFn(n)){if(t.contentDocument)return;r="rr_src"}if(s||(s={node:e.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(s),this.attributeMap.set(e.target,s)),"type"===r&&"INPUT"===t.tagName&&"password"===(e.oldValue||"").toLowerCase()&&t.setAttribute("data-rr-is-password","true"),!kl(t.tagName,r))if(s.attributes[r]=Tl(this.doc,nl(t.tagName),nl(r),n),"style"===r){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(e){this.unattachedDoc=this.doc}const r=this.unattachedDoc.createElement("span");e.oldValue&&r.setAttribute("style",e.oldValue);for(const e of Array.from(t.style)){const n=t.style.getPropertyValue(e),i=t.style.getPropertyPriority(e);n!==r.style.getPropertyValue(e)||i!==r.style.getPropertyPriority(e)?s.styleDiff[e]=""===i?n:[n,i]:s._unchangedStyles[e]=[n,i]}for(const e of Array.from(r.style))""===t.style.getPropertyValue(e)&&(s.styleDiff[e]=!1)}else"open"===r&&"DIALOG"===t.tagName&&(t.matches("dialog:modal")?s.attributes.rr_open_mode="modal":s.attributes.rr_open_mode="non-modal");break}case"childList":if(Dg(e.target,this.blockClass,this.blockSelector,!0))return;if("TEXTAREA"===e.target.tagName)return void this.genTextAreaValueMutation(e.target);e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const r=this.mirror.getId(t),n=Ka(e.target)?this.mirror.getId(Tg.host(e.target)):this.mirror.getId(e.target);Dg(e.target,this.blockClass,this.blockSelector,!1)||Ug(t,this.mirror,this.slimDOMOptions)||!function(e,t){return-1!==t.getId(e)}(t,this.mirror)||(this.addedSet.has(t)?(sy(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&-1===r||Fg(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[ry(r,n)]?sy(this.movedSet,t):(this.removes.push({parentId:n,id:r,isShadow:!(!Ka(e.target)||!qa(e.target))||void 0}),function(e,t){const r=[e];for(;r.length;){const e=r.pop();t.has(e)||(t.add(e),Tg.childNodes(e).forEach(e=>r.push(e)))}}(t,this.removesSubTreeCache))),this.mapRemoves.push(t))})}}),Ua(this,"genAdds",(e,t)=>{if(!this.processedNodeManager.inOtherBuffer(e,this)&&!this.addedSet.has(e)&&!this.movedSet.has(e)){if(this.mirror.hasNode(e)){if(Ug(e,this.mirror,this.slimDOMOptions))return;this.movedSet.add(e);let r=null;t&&this.mirror.hasNode(t)&&(r=this.mirror.getId(t)),r&&-1!==r&&(this.movedMap[ry(this.mirror.getId(e),r)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);Dg(e,this.blockClass,this.blockSelector,!1)||(Tg.childNodes(e).forEach(e=>this.genAdds(e)),Vg(e)&&Tg.childNodes(Tg.shadowRoot(e)).forEach(t=>{this.processedNodeManager.add(t,this),this.genAdds(t,e)}))}})}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function sy(e,t){e.delete(t),Tg.childNodes(t).forEach(t=>sy(e,t))}function iy(e,t,r){return 0!==e.size&&function(e,t){const r=Tg.parentNode(t);return!!r&&e.has(r)}(e,t)}function oy(e,t){return 0!==e.size&&ay(e,t)}function ay(e,t){const r=Tg.parentNode(t);return!!r&&(!!e.has(r)||ay(e,r))}let ly;const cy=e=>{if(!ly)return e;return(...t)=>{try{return e(...t)}catch(e){if(ly&&!0===ly(e))return;throw e}}},uy=[];function hy(e){try{if("composedPath"in e){const t=e.composedPath();if(t.length)return t[0]}else if("path"in e&&e.path.length)return e.path[0]}catch{}return e&&e.target}function py(e,t){const r=new ny;uy.push(r),r.init(e);const n=new(Cg())(cy(r.processMutations.bind(r)));return n.observe(t,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),n}function dy({mouseInteractionCb:e,doc:t,mirror:r,blockClass:n,blockSelector:s,sampling:i}){if(!1===i.mouseInteraction)return()=>{};const o=!0===i.mouseInteraction||void 0===i.mouseInteraction?{}:i.mouseInteraction,a=[];let l=null;return Object.keys(Xg).filter(e=>Number.isNaN(Number(e))&&!e.endsWith("_Departed")&&!1!==o[e]).forEach(i=>{let o=nl(i);const c=(t=>i=>{const o=hy(i);if(Dg(o,n,s,!0))return;let a=null,c=t;if("pointerType"in i){switch(i.pointerType){case"mouse":a=Jg.Mouse;break;case"touch":a=Jg.Touch;break;case"pen":a=Jg.Pen}a===Jg.Touch?Xg[t]===Xg.MouseDown?c="TouchStart":Xg[t]===Xg.MouseUp&&(c="TouchEnd"):Jg.Pen}else Bg(i)&&(a=Jg.Touch);null!==a?(l=a,(c.startsWith("Touch")&&a===Jg.Touch||c.startsWith("Mouse")&&a===Jg.Mouse)&&(a=null)):Xg[t]===Xg.Click&&(a=l,l=null);const u=Bg(i)?i.changedTouches[0]:i;if(!u)return;const h=r.getId(o),{clientX:p,clientY:d}=u;cy(e)({type:Xg[c],id:h,x:p,y:d,...null!==a&&{pointerType:a}})})(i);if(window.PointerEvent)switch(Xg[i]){case Xg.MouseDown:case Xg.MouseUp:o=o.replace("mouse","pointer");break;case Xg.TouchStart:case Xg.TouchEnd:return}a.push(kg(o,c,t))}),cy(()=>{a.forEach(e=>e())})}function fy({scrollCb:e,doc:t,mirror:r,blockClass:n,blockSelector:s,sampling:i}){return kg("scroll",cy(Ag(cy(i=>{const o=hy(i);if(!o||Dg(o,n,s,!0))return;const a=r.getId(o);if(o===t&&t.defaultView){const r=Mg(t.defaultView);e({id:a,x:r.left,y:r.top})}else e({id:a,x:o.scrollLeft,y:o.scrollTop})}),i.scroll||100)),t)}const my=["INPUT","TEXTAREA","SELECT"],gy=new WeakMap;function yy(e){return function(e,t){if(_y("CSSGroupingRule")&&e.parentRule instanceof CSSGroupingRule||_y("CSSMediaRule")&&e.parentRule instanceof CSSMediaRule||_y("CSSSupportsRule")&&e.parentRule instanceof CSSSupportsRule||_y("CSSConditionRule")&&e.parentRule instanceof CSSConditionRule){const r=Array.from(e.parentRule.cssRules).indexOf(e);t.unshift(r)}else if(e.parentStyleSheet){const r=Array.from(e.parentStyleSheet.cssRules).indexOf(e);t.unshift(r)}return t}(e,[])}function wy(e,t,r){let n,s;return e?(e.ownerNode?n=t.getId(e.ownerNode):s=r.getId(e),{styleId:s,id:n}):{}}function vy({mirror:e,stylesheetManager:t},r){var n,s,i;let o=null;o="#document"===r.nodeName?e.getId(r):e.getId(Tg.host(r));const a="#document"===r.nodeName?null==(n=r.defaultView)?void 0:n.Document:null==(i=null==(s=r.ownerDocument)?void 0:s.defaultView)?void 0:i.ShadowRoot,l=(null==a?void 0:a.prototype)?Object.getOwnPropertyDescriptor(null==a?void 0:a.prototype,"adoptedStyleSheets"):void 0;return null!==o&&-1!==o&&a&&l?(Object.defineProperty(r,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get(){var e;return null==(e=l.get)?void 0:e.call(this)},set(e){var r;const n=null==(r=l.set)?void 0:r.call(this,e);if(null!==o&&-1!==o)try{t.adoptStyleSheets(e,o)}catch(e){}return n}}),cy(()=>{Object.defineProperty(r,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get:l.get,set:l.set})})):()=>{}}function by(e,t={}){const r=e.doc.defaultView;if(!r)return()=>{};let n;!function(e,t){const{mutationCb:r,mousemoveCb:n,mouseInteractionCb:s,scrollCb:i,viewportResizeCb:o,inputCb:a,mediaInteractionCb:l,styleSheetRuleCb:c,styleDeclarationCb:u,canvasMutationCb:h,fontCb:p,selectionCb:d,customElementCb:f}=e;e.mutationCb=(...e)=>{t.mutation&&t.mutation(...e),r(...e)},e.mousemoveCb=(...e)=>{t.mousemove&&t.mousemove(...e),n(...e)},e.mouseInteractionCb=(...e)=>{t.mouseInteraction&&t.mouseInteraction(...e),s(...e)},e.scrollCb=(...e)=>{t.scroll&&t.scroll(...e),i(...e)},e.viewportResizeCb=(...e)=>{t.viewportResize&&t.viewportResize(...e),o(...e)},e.inputCb=(...e)=>{t.input&&t.input(...e),a(...e)},e.mediaInteractionCb=(...e)=>{t.mediaInteaction&&t.mediaInteaction(...e),l(...e)},e.styleSheetRuleCb=(...e)=>{t.styleSheetRule&&t.styleSheetRule(...e),c(...e)},e.styleDeclarationCb=(...e)=>{t.styleDeclaration&&t.styleDeclaration(...e),u(...e)},e.canvasMutationCb=(...e)=>{t.canvasMutation&&t.canvasMutation(...e),h(...e)},e.fontCb=(...e)=>{t.font&&t.font(...e),p(...e)},e.selectionCb=(...e)=>{t.selection&&t.selection(...e),d(...e)},e.customElementCb=(...e)=>{t.customElement&&t.customElement(...e),f(...e)}}(e,t),e.recordDOM&&(n=py(e,e.doc));const s=function({mousemoveCb:e,sampling:t,doc:r,mirror:n}){if(!1===t.mousemove)return()=>{};const s="number"==typeof t.mousemove?t.mousemove:50,i="number"==typeof t.mousemoveCallback?t.mousemoveCallback:500;let o,a=[];const l=Ag(cy(t=>{const r=Date.now()-o;e(a.map(e=>(e.timeOffset-=r,e)),t),a=[],o=null}),i),c=cy(Ag(cy(e=>{const t=hy(e),{clientX:r,clientY:s}=Bg(e)?e.changedTouches[0]:e;o||(o=Rg()),a.push({x:r,y:s,id:n.getId(t),timeOffset:Rg()-o}),l("undefined"!=typeof DragEvent&&e instanceof DragEvent?Yg.Drag:e instanceof MouseEvent?Yg.MouseMove:Yg.TouchMove)}),s,{trailing:!1})),u=[kg("mousemove",c,r),kg("touchmove",c,r),kg("drag",c,r)];return cy(()=>{u.forEach(e=>e())})}(e),i=dy(e),o=fy(e),a=function({viewportResizeCb:e},{win:t}){let r=-1,n=-1;return kg("resize",cy(Ag(cy(()=>{const t=Ng(),s=Pg();r===t&&n===s||(e({width:Number(s),height:Number(t)}),r=t,n=s)}),200)),t)}(e,{win:r}),l=function({inputCb:e,doc:t,mirror:r,blockClass:n,blockSelector:s,ignoreClass:i,ignoreSelector:o,maskInputOptions:a,maskInputFn:l,sampling:c,userTriggeredOnInput:u}){function h(e){let r=hy(e);const c=e.isTrusted,h=r&&r.tagName;if(r&&"OPTION"===h&&(r=Tg.parentElement(r)),!r||!h||my.indexOf(h)<0||Dg(r,n,s,!0))return;if(r.classList.contains(i)||o&&r.matches(o))return;let d=r.value,f=!1;const m=il(r)||"";"radio"===m||"checkbox"===m?f=r.checked:(a[h.toLowerCase()]||a[m])&&(d=rl({element:r,maskInputOptions:a,tagName:h,type:m,value:d,maskInputFn:l})),p(r,u?{text:d,isChecked:f,userTriggered:c}:{text:d,isChecked:f});const g=r.name;"radio"===m&&g&&f&&t.querySelectorAll(`input[type="radio"][name="${g}"]`).forEach(e=>{if(e!==r){const t=e.value;p(e,u?{text:t,isChecked:!f,userTriggered:!1}:{text:t,isChecked:!f})}})}function p(t,n){const s=gy.get(t);if(!s||s.text!==n.text||s.isChecked!==n.isChecked){gy.set(t,n);const s=r.getId(t);cy(e)({...n,id:s})}}const d=("last"===c.input?["change"]:["input","change"]).map(e=>kg(e,cy(h),t)),f=t.defaultView;if(!f)return()=>{d.forEach(e=>e())};const m=f.Object.getOwnPropertyDescriptor(f.HTMLInputElement.prototype,"value"),g=[[f.HTMLInputElement.prototype,"value"],[f.HTMLInputElement.prototype,"checked"],[f.HTMLSelectElement.prototype,"value"],[f.HTMLTextAreaElement.prototype,"value"],[f.HTMLSelectElement.prototype,"selectedIndex"],[f.HTMLOptionElement.prototype,"selected"]];return m&&m.set&&d.push(...g.map(e=>Ig(e[0],e[1],{set(){cy(h)({target:this,isTrusted:!1})}},!1,f))),cy(()=>{d.forEach(e=>e())})}(e),c=function({mediaInteractionCb:e,blockClass:t,blockSelector:r,mirror:n,sampling:s,doc:i}){const o=cy(i=>Ag(cy(s=>{const o=hy(s);if(!o||Dg(o,t,r,!0))return;const{currentTime:a,volume:l,muted:c,playbackRate:u,loop:h}=o;e({type:i,id:n.getId(o),currentTime:a,volume:l,muted:c,playbackRate:u,loop:h})}),s.media||500)),a=[kg("play",o(qg.Play),i),kg("pause",o(qg.Pause),i),kg("seeked",o(qg.Seeked),i),kg("volumechange",o(qg.VolumeChange),i),kg("ratechange",o(qg.RateChange),i)];return cy(()=>{a.forEach(e=>e())})}(e);let u=()=>{},h=()=>{},p=()=>{},d=()=>{};e.recordDOM&&(u=function({styleSheetRuleCb:e,mirror:t,stylesheetManager:r},{win:n}){if(!n.CSSStyleSheet||!n.CSSStyleSheet.prototype)return()=>{};const s=n.CSSStyleSheet.prototype.insertRule;n.CSSStyleSheet.prototype.insertRule=new Proxy(s,{apply:cy((n,s,i)=>{const[o,a]=i,{id:l,styleId:c}=wy(s,t,r.styleMirror);return(l&&-1!==l||c&&-1!==c)&&e({id:l,styleId:c,adds:[{rule:o,index:a}]}),n.apply(s,i)})}),n.CSSStyleSheet.prototype.addRule=function(e,t,r=this.cssRules.length){const s=`${e} { ${t} }`;return n.CSSStyleSheet.prototype.insertRule.apply(this,[s,r])};const i=n.CSSStyleSheet.prototype.deleteRule;let o,a;n.CSSStyleSheet.prototype.deleteRule=new Proxy(i,{apply:cy((n,s,i)=>{const[o]=i,{id:a,styleId:l}=wy(s,t,r.styleMirror);return(a&&-1!==a||l&&-1!==l)&&e({id:a,styleId:l,removes:[{index:o}]}),n.apply(s,i)})}),n.CSSStyleSheet.prototype.removeRule=function(e){return n.CSSStyleSheet.prototype.deleteRule.apply(this,[e])},n.CSSStyleSheet.prototype.replace&&(o=n.CSSStyleSheet.prototype.replace,n.CSSStyleSheet.prototype.replace=new Proxy(o,{apply:cy((n,s,i)=>{const[o]=i,{id:a,styleId:l}=wy(s,t,r.styleMirror);return(a&&-1!==a||l&&-1!==l)&&e({id:a,styleId:l,replace:o}),n.apply(s,i)})})),n.CSSStyleSheet.prototype.replaceSync&&(a=n.CSSStyleSheet.prototype.replaceSync,n.CSSStyleSheet.prototype.replaceSync=new Proxy(a,{apply:cy((n,s,i)=>{const[o]=i,{id:a,styleId:l}=wy(s,t,r.styleMirror);return(a&&-1!==a||l&&-1!==l)&&e({id:a,styleId:l,replaceSync:o}),n.apply(s,i)})}));const l={};Sy("CSSGroupingRule")?l.CSSGroupingRule=n.CSSGroupingRule:(Sy("CSSMediaRule")&&(l.CSSMediaRule=n.CSSMediaRule),Sy("CSSConditionRule")&&(l.CSSConditionRule=n.CSSConditionRule),Sy("CSSSupportsRule")&&(l.CSSSupportsRule=n.CSSSupportsRule));const c={};return Object.entries(l).forEach(([n,s])=>{c[n]={insertRule:s.prototype.insertRule,deleteRule:s.prototype.deleteRule},s.prototype.insertRule=new Proxy(c[n].insertRule,{apply:cy((n,s,i)=>{const[o,a]=i,{id:l,styleId:c}=wy(s.parentStyleSheet,t,r.styleMirror);return(l&&-1!==l||c&&-1!==c)&&e({id:l,styleId:c,adds:[{rule:o,index:[...yy(s),a||0]}]}),n.apply(s,i)})}),s.prototype.deleteRule=new Proxy(c[n].deleteRule,{apply:cy((n,s,i)=>{const[o]=i,{id:a,styleId:l}=wy(s.parentStyleSheet,t,r.styleMirror);return(a&&-1!==a||l&&-1!==l)&&e({id:a,styleId:l,removes:[{index:[...yy(s),o]}]}),n.apply(s,i)})})}),cy(()=>{n.CSSStyleSheet.prototype.insertRule=s,n.CSSStyleSheet.prototype.deleteRule=i,o&&(n.CSSStyleSheet.prototype.replace=o),a&&(n.CSSStyleSheet.prototype.replaceSync=a),Object.entries(l).forEach(([e,t])=>{t.prototype.insertRule=c[e].insertRule,t.prototype.deleteRule=c[e].deleteRule})})}(e,{win:r}),h=vy(e,e.doc),p=function({styleDeclarationCb:e,mirror:t,ignoreCSSAttributes:r,stylesheetManager:n},{win:s}){const i=s.CSSStyleDeclaration.prototype.setProperty;s.CSSStyleDeclaration.prototype.setProperty=new Proxy(i,{apply:cy((s,o,a)=>{var l;const[c,u,h]=a;if(r.has(c))return i.apply(o,[c,u,h]);const{id:p,styleId:d}=wy(null==(l=o.parentRule)?void 0:l.parentStyleSheet,t,n.styleMirror);return(p&&-1!==p||d&&-1!==d)&&e({id:p,styleId:d,set:{property:c,value:u,priority:h},index:yy(o.parentRule)}),s.apply(o,a)})});const o=s.CSSStyleDeclaration.prototype.removeProperty;return s.CSSStyleDeclaration.prototype.removeProperty=new Proxy(o,{apply:cy((s,i,a)=>{var l;const[c]=a;if(r.has(c))return o.apply(i,[c]);const{id:u,styleId:h}=wy(null==(l=i.parentRule)?void 0:l.parentStyleSheet,t,n.styleMirror);return(u&&-1!==u||h&&-1!==h)&&e({id:u,styleId:h,remove:{property:c},index:yy(i.parentRule)}),s.apply(i,a)})}),cy(()=>{s.CSSStyleDeclaration.prototype.setProperty=i,s.CSSStyleDeclaration.prototype.removeProperty=o})}(e,{win:r}),e.collectFonts&&(d=function({fontCb:e,doc:t}){const r=t.defaultView;if(!r)return()=>{};const n=[],s=new WeakMap,i=r.FontFace;r.FontFace=function(e,t,r){const n=new i(e,t,r);return s.set(n,{family:e,buffer:"string"!=typeof t,descriptors:r,fontSource:"string"==typeof t?t:JSON.stringify(Array.from(new Uint8Array(t)))}),n};const o=Eg(t.fonts,"add",function(t){return function(r){return setTimeout(cy(()=>{const t=s.get(r);t&&(e(t),s.delete(r))}),0),t.apply(this,[r])}});return n.push(()=>{r.FontFace=i}),n.push(o),cy(()=>{n.forEach(e=>e())})}(e)));const f=function(e){const{doc:t,mirror:r,blockClass:n,blockSelector:s,selectionCb:i}=e;let o=!0;const a=cy(()=>{const e=t.getSelection();if(!e||o&&(null==e?void 0:e.isCollapsed))return;o=e.isCollapsed||!1;const a=[],l=e.rangeCount||0;for(let t=0;t{}}(e),g=[];for(const t of e.plugins)g.push(t.observer(t.callback,r,t.options));return cy(()=>{uy.forEach(e=>e.reset()),null==n||n.disconnect(),s(),i(),o(),a(),l(),c(),u(),h(),p(),d(),f(),m(),g.forEach(e=>e())})}function _y(e){return void 0!==window[e]}function Sy(e){return Boolean(void 0!==window[e]&&window[e].prototype&&"insertRule"in window[e].prototype&&"deleteRule"in window[e].prototype)}class Cy{constructor(e){Ua(this,"iframeIdToRemoteIdMap",new WeakMap),Ua(this,"iframeRemoteIdToIdMap",new WeakMap),this.generateIdFn=e}getId(e,t,r,n){const s=r||this.getIdToRemoteIdMap(e),i=n||this.getRemoteIdToIdMap(e);let o=s.get(t);return o||(o=this.generateIdFn(),s.set(t,o),i.set(o,t)),o}getIds(e,t){const r=this.getIdToRemoteIdMap(e),n=this.getRemoteIdToIdMap(e);return t.map(t=>this.getId(e,t,r,n))}getRemoteId(e,t,r){const n=r||this.getRemoteIdToIdMap(e);if("number"!=typeof t)return t;const s=n.get(t);return s||-1}getRemoteIds(e,t){const r=this.getRemoteIdToIdMap(e);return t.map(t=>this.getRemoteId(e,t,r))}reset(e){if(!e)return this.iframeIdToRemoteIdMap=new WeakMap,void(this.iframeRemoteIdToIdMap=new WeakMap);this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}}class Ey{constructor(e){Ua(this,"iframes",new WeakMap),Ua(this,"crossOriginIframeMap",new WeakMap),Ua(this,"crossOriginIframeMirror",new Cy(gl)),Ua(this,"crossOriginIframeStyleMirror"),Ua(this,"crossOriginIframeRootIdMap",new WeakMap),Ua(this,"mirror"),Ua(this,"mutationCb"),Ua(this,"wrappedEmit"),Ua(this,"loadListener"),Ua(this,"stylesheetManager"),Ua(this,"recordCrossOriginIframes"),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new Cy(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var r,n;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&(null==(r=e.contentWindow)||r.addEventListener("message",this.handleMessage.bind(this))),null==(n=this.loadListener)||n.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){const t=e;if("rrweb"!==t.data.type||t.origin!==t.data.origin)return;if(!e.source)return;const r=this.crossOriginIframeMap.get(e.source);if(!r)return;const n=this.transformCrossOriginEvent(r,t.data.event);n&&this.wrappedEmit(n,t.data.isCheckout)}transformCrossOriginEvent(e,t){var r;switch(t.type){case Wg.FullSnapshot:{this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);const r=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,r),this.patchRootIdOnNode(t.data.node,r),{timestamp:t.timestamp,type:Wg.IncrementalSnapshot,data:{source:Yg.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case Wg.Meta:case Wg.Load:case Wg.DomContentLoaded:return!1;case Wg.Plugin:return t;case Wg.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case Wg.IncrementalSnapshot:switch(t.data.source){case Yg.Mutation:return t.data.adds.forEach(t=>{this.replaceIds(t,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(t.node,e);const r=this.crossOriginIframeRootIdMap.get(e);r&&this.patchRootIdOnNode(t.node,r)}),t.data.removes.forEach(t=>{this.replaceIds(t,e,["parentId","id"])}),t.data.attributes.forEach(t=>{this.replaceIds(t,e,["id"])}),t.data.texts.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case Yg.Drag:case Yg.TouchMove:case Yg.MouseMove:return t.data.positions.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case Yg.ViewportResize:return!1;case Yg.MediaInteraction:case Yg.MouseInteraction:case Yg.Scroll:case Yg.CanvasMutation:case Yg.Input:return this.replaceIds(t.data,e,["id"]),t;case Yg.StyleSheetRule:case Yg.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case Yg.Font:return t;case Yg.Selection:return t.data.ranges.forEach(t=>{this.replaceIds(t,e,["start","end"])}),t;case Yg.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),null==(r=t.data.styles)||r.forEach(t=>{this.replaceStyleIds(t,e,["styleId"])}),t}}return!1}replace(e,t,r,n){for(const s of n)(Array.isArray(t[s])||"number"==typeof t[s])&&(Array.isArray(t[s])?t[s]=e.getIds(r,t[s]):t[s]=e.getId(r,t[s]));return t}replaceIds(e,t,r){return this.replace(this.crossOriginIframeMirror,e,t,r)}replaceStyleIds(e,t,r){return this.replace(this.crossOriginIframeStyleMirror,e,t,r)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach(e=>{this.replaceIdOnNode(e,t)})}patchRootIdOnNode(e,t){e.type===Qg.Document||e.rootId||(e.rootId=t),"childNodes"in e&&e.childNodes.forEach(e=>{this.patchRootIdOnNode(e,t)})}}class Ty{constructor(e){Ua(this,"shadowDoms",new WeakSet),Ua(this,"mutationCb"),Ua(this,"scrollCb"),Ua(this,"bypassOptions"),Ua(this,"mirror"),Ua(this,"restoreHandlers",[]),this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(e,t){if(!qa(e))return;if(this.shadowDoms.has(e))return;this.shadowDoms.add(e);const r=py({...this.bypassOptions,doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},e);this.restoreHandlers.push(()=>r.disconnect()),this.restoreHandlers.push(fy({...this.bypassOptions,scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(Tg.host(e))),this.restoreHandlers.push(vy({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e))},0)}observeAttachShadow(e){e.contentWindow&&e.contentDocument&&this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)}patchAttachShadow(e,t){const r=this;this.restoreHandlers.push(Eg(e.prototype,"attachShadow",function(e){return function(n){const s=e.call(this,n),i=Tg.shadowRoot(this);return i&&$g(this)&&r.addShadowRoot(i,t),s}}))}reset(){this.restoreHandlers.forEach(e=>{try{e()}catch(e){}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet}}for(var ky="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",xy="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Oy=0;Oy<64;Oy++)xy[ky.charCodeAt(Oy)]=Oy;const Ay=new Map;const Iy=(e,t,r)=>{if(!e||!Ny(e,t)&&"object"!=typeof e)return;const n=function(e,t){let r=Ay.get(e);return r||(r=new Map,Ay.set(e,r)),r.has(t)||r.set(t,[]),r.get(t)}(r,e.constructor.name);let s=n.indexOf(e);return-1===s&&(s=n.length,n.push(e)),s};function Ry(e,t,r){if(e instanceof Array)return e.map(e=>Ry(e,t,r));if(null===e)return e;if(e instanceof Float32Array||e instanceof Float64Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Int8Array||e instanceof Uint8ClampedArray){return{rr_type:e.constructor.name,args:[Object.values(e)]}}if(e instanceof ArrayBuffer){return{rr_type:e.constructor.name,base64:function(e){var t,r=new Uint8Array(e),n=r.length,s="";for(t=0;t>2],s+=ky[(3&r[t])<<4|r[t+1]>>4],s+=ky[(15&r[t+1])<<2|r[t+2]>>6],s+=ky[63&r[t+2]];return n%3==2?s=s.substring(0,s.length-1)+"=":n%3==1&&(s=s.substring(0,s.length-2)+"=="),s}(e)}}if(e instanceof DataView){return{rr_type:e.constructor.name,args:[Ry(e.buffer,t,r),e.byteOffset,e.byteLength]}}if(e instanceof HTMLImageElement){const t=e.constructor.name,{src:r}=e;return{rr_type:t,src:r}}if(e instanceof HTMLCanvasElement){return{rr_type:"HTMLImageElement",src:e.toDataURL()}}if(e instanceof ImageData){return{rr_type:e.constructor.name,args:[Ry(e.data,t,r),e.width,e.height]}}if(Ny(e,t)||"object"==typeof e){return{rr_type:e.constructor.name,index:Iy(e,t,r)}}return e}const My=(e,t,r)=>e.map(e=>Ry(e,t,r)),Ny=(e,t)=>{const r=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(e=>"function"==typeof t[e]);return Boolean(r.find(r=>e instanceof t[r]))};function Py(e,t,r,n){const s=[];try{const i=Eg(e.HTMLCanvasElement.prototype,"getContext",function(e){return function(s,...i){if(!Dg(this,t,r,!0)){const e=function(e){return"experimental-webgl"===e?"webgl":e}(s);if("__context"in this||(this.__context=e),n&&["webgl","webgl2"].includes(e))if(i[0]&&"object"==typeof i[0]){const e=i[0];e.preserveDrawingBuffer||(e.preserveDrawingBuffer=!0)}else i.splice(0,1,{preserveDrawingBuffer:!0})}return e.apply(this,[s,...i])}});s.push(i)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{s.forEach(e=>e())}}function Ly(e,t,r,n,s,i){const o=[],a=Object.getOwnPropertyNames(e);for(const l of a)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(l))try{if("function"!=typeof e[l])continue;const a=Eg(e,l,function(e){return function(...o){const a=e.apply(this,o);if(Iy(a,i,this),"tagName"in this.canvas&&!Dg(this.canvas,n,s,!0)){const e=My(o,i,this),n={type:t,property:l,args:e};r(this.canvas,n)}return a}});o.push(a)}catch{const n=Ig(e,l,{set(e){r(this.canvas,{type:t,property:l,args:[e],setter:!0})}});o.push(n)}return o}const Dy="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",Uy="undefined"!=typeof window&&window.Blob&&new Blob([(e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0)))(Dy)],{type:"text/javascript;charset=utf-8"});function Fy(e){let t;try{if(t=Uy&&(window.URL||window.webkitURL).createObjectURL(Uy),!t)throw"";const r=new Worker(t,{name:null==e?void 0:e.name});return r.addEventListener("error",()=>{(window.URL||window.webkitURL).revokeObjectURL(t)}),r}catch(t){return new Worker("data:text/javascript;base64,"+Dy,{name:null==e?void 0:e.name})}finally{t&&(window.URL||window.webkitURL).revokeObjectURL(t)}}class By{constructor(e){Ua(this,"pendingCanvasMutations",new Map),Ua(this,"rafStamps",{latestId:0,invokeId:null}),Ua(this,"mirror"),Ua(this,"mutationCb"),Ua(this,"resetObservers"),Ua(this,"frozen",!1),Ua(this,"locked",!1),Ua(this,"processMutation",(e,t)=>{!(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId)&&this.rafStamps.invokeId||(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(e)||this.pendingCanvasMutations.set(e,[]),this.pendingCanvasMutations.get(e).push(t)});const{sampling:t="all",win:r,blockClass:n,blockSelector:s,recordCanvas:i,dataURLOptions:o}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,i&&"all"===t&&this.initCanvasMutationObserver(r,n,s),i&&"number"==typeof t&&this.initCanvasFPSObserver(t,r,n,s,{dataURLOptions:o})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,r,n,s){const i=Py(t,r,n,!0),o=new Map,a=new Fy;a.onmessage=e=>{const{id:t}=e.data;if(o.set(t,!1),!("base64"in e.data))return;const{base64:r,type:n,width:s,height:i}=e.data;this.mutationCb({id:t,type:Kg["2D"],commands:[{property:"clearRect",args:[0,0,s,i]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:r}],type:n}]},0,0]}]})};const l=1e3/e;let c,u=0;const h=e=>{u&&e-u{const e=[];return t.document.querySelectorAll("canvas").forEach(t=>{Dg(t,r,n,!0)||e.push(t)}),e})().forEach(async e=>{var t;const r=this.mirror.getId(e);if(o.get(r))return;if(0===e.width||0===e.height)return;if(o.set(r,!0),["webgl","webgl2"].includes(e.__context)){const r=e.getContext(e.__context);!1===(null==(t=null==r?void 0:r.getContextAttributes())?void 0:t.preserveDrawingBuffer)&&r.clear(r.COLOR_BUFFER_BIT)}const n=await createImageBitmap(e);a.postMessage({id:r,bitmap:n,width:e.width,height:e.height,dataURLOptions:s.dataURLOptions},[n])})),c=requestAnimationFrame(h)};c=requestAnimationFrame(h),this.resetObservers=()=>{i(),cancelAnimationFrame(c)}}initCanvasMutationObserver(e,t,r){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const n=Py(e,t,r,!1),s=function(e,t,r,n){const s=[],i=Object.getOwnPropertyNames(t.CanvasRenderingContext2D.prototype);for(const o of i)try{if("function"!=typeof t.CanvasRenderingContext2D.prototype[o])continue;const i=Eg(t.CanvasRenderingContext2D.prototype,o,function(s){return function(...i){return Dg(this.canvas,r,n,!0)||setTimeout(()=>{const r=My(i,t,this);e(this.canvas,{type:Kg["2D"],property:o,args:r})},0),s.apply(this,i)}});s.push(i)}catch{const r=Ig(t.CanvasRenderingContext2D.prototype,o,{set(t){e(this.canvas,{type:Kg["2D"],property:o,args:[t],setter:!0})}});s.push(r)}return()=>{s.forEach(e=>e())}}(this.processMutation.bind(this),e,t,r),i=function(e,t,r,n){const s=[];return s.push(...Ly(t.WebGLRenderingContext.prototype,Kg.WebGL,e,r,n,t)),void 0!==t.WebGL2RenderingContext&&s.push(...Ly(t.WebGL2RenderingContext.prototype,Kg.WebGL2,e,r,n,t)),()=>{s.forEach(e=>e())}}(this.processMutation.bind(this),e,t,r);this.resetObservers=()=>{n(),s(),i()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const r=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,r)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const r=this.pendingCanvasMutations.get(e);if(!r||-1===t)return;const n=r.map(e=>{const{type:t,...r}=e;return r}),{type:s}=r[0];this.mutationCb({id:t,type:s,commands:n}),this.pendingCanvasMutations.delete(e)}}class jy{constructor(e){Ua(this,"trackedLinkElements",new WeakSet),Ua(this,"mutationCb"),Ua(this,"adoptedStyleSheetCb"),Ua(this,"styleMirror",new Gg),this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(0===e.length)return;const r={id:t,styleIds:[]},n=[];for(const t of e){let e;this.styleMirror.has(t)?e=this.styleMirror.getId(t):(e=this.styleMirror.add(t),n.push({styleId:e,rules:Array.from(t.rules||CSSRule,(e,r)=>({rule:el(e,t.href),index:r}))})),r.styleIds.push(e)}n.length>0&&(r.styles=n),this.adoptedStyleSheetCb(r)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}}class zy{constructor(){Ua(this,"nodeMap",new WeakMap),Ua(this,"active",!1)}inOtherBuffer(e,t){const r=this.nodeMap.get(e);return r&&Array.from(r).some(e=>e!==t)}add(e,t){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||new Set).add(t))}destroy(){}}let Vy,Gy,Hy,Zy=!1;try{if(2!==Array.from([1],e=>2*e)[0]){const e=document.createElement("iframe");document.body.appendChild(e),Array.from=(null==(La=e.contentWindow)?void 0:La.Array.from)||Array.from,document.body.removeChild(e)}}catch(e){console.debug("Unable to override Array.from",e)}const $y=new tl;function Wy(e={}){const{emit:t,checkoutEveryNms:r,checkoutEveryNth:n,blockClass:s="rr-block",blockSelector:i=null,ignoreClass:o="rr-ignore",ignoreSelector:a=null,maskTextClass:l="rr-mask",maskTextSelector:c=null,inlineStylesheet:u=!0,maskAllInputs:h,maskInputOptions:p,slimDOMOptions:d,maskInputFn:f,maskTextFn:m,hooks:g,packFn:y,sampling:w={},dataURLOptions:v={},mousemoveWait:b,recordDOM:_=!0,recordCanvas:S=!1,recordCrossOriginIframes:C=!1,recordAfter:E=("DOMContentLoaded"===e.recordAfter?e.recordAfter:"load"),userTriggeredOnInput:T=!1,collectFonts:k=!1,inlineImages:x=!1,plugins:O,keepIframeSrcFn:A=()=>!1,ignoreCSSAttributes:I=new Set([]),errorHandler:R}=e;ly=R;const M=!C||window.parent===window;let N=!1;if(!M)try{window.parent.document&&(N=!1)}catch(e){N=!0}if(M&&!t)throw new Error("emit function is required");if(!M&&!N)return()=>{};void 0!==b&&void 0===w.mousemove&&(w.mousemove=b),$y.reset();const P=!0===h?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==p?p:{password:!0},L=Rl(d);let D;!function(e=window){"NodeList"in e&&!e.NodeList.prototype.forEach&&(e.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in e&&!e.DOMTokenList.prototype.forEach&&(e.DOMTokenList.prototype.forEach=Array.prototype.forEach)}();let U=0;const F=e=>{for(const t of O||[])t.eventProcessor&&(e=t.eventProcessor(e));return y&&!N&&(e=y(e)),e};Vy=(e,s)=>{var i;const o=e;if(o.timestamp=Rg(),!(null==(i=uy[0])?void 0:i.isFrozen())||o.type===Wg.FullSnapshot||o.type===Wg.IncrementalSnapshot&&o.data.source===Yg.Mutation||uy.forEach(e=>e.unfreeze()),M)null==t||t(F(o),s);else if(N){const e={type:"rrweb",event:F(o),origin:window.location.origin,isCheckout:s};window.parent.postMessage(e,"*")}if(o.type===Wg.FullSnapshot)D=o,U=0;else if(o.type===Wg.IncrementalSnapshot){if(o.data.source===Yg.Mutation&&o.data.isAttachIframe)return;U++;const e=n&&U>=n,t=r&&o.timestamp-D.timestamp>r;(e||t)&&Gy(!0)}};const B=e=>{Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.Mutation,...e}})},j=e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.Scroll,...e}}),z=e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.CanvasMutation,...e}}),V=new jy({mutationCb:B,adoptedStyleSheetCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.AdoptedStyleSheet,...e}})}),G=new Ey({mirror:$y,mutationCb:B,stylesheetManager:V,recordCrossOriginIframes:C,wrappedEmit:Vy});for(const e of O||[])e.getMirror&&e.getMirror({nodeMirror:$y,crossOriginIframeMirror:G.crossOriginIframeMirror,crossOriginIframeStyleMirror:G.crossOriginIframeStyleMirror});const H=new zy;Hy=new By({recordCanvas:S,mutationCb:z,win:window,blockClass:s,blockSelector:i,mirror:$y,sampling:w.canvas,dataURLOptions:v});const Z=new Ty({mutationCb:B,scrollCb:j,bypassOptions:{blockClass:s,blockSelector:i,maskTextClass:l,maskTextSelector:c,inlineStylesheet:u,maskInputOptions:P,dataURLOptions:v,maskTextFn:m,maskInputFn:f,recordCanvas:S,inlineImages:x,sampling:w,slimDOMOptions:L,iframeManager:G,stylesheetManager:V,canvasManager:Hy,keepIframeSrcFn:A,processedNodeManager:H},mirror:$y});Gy=(e=!1)=>{if(!_)return;Vy({type:Wg.Meta,data:{href:window.location.href,width:Pg(),height:Ng()}},e),V.reset(),Z.init(),uy.forEach(e=>e.lock());const t=function(e,t){const{mirror:r=new tl,blockClass:n="rr-block",blockSelector:s=null,maskTextClass:i="rr-mask",maskTextSelector:o=null,inlineStylesheet:a=!0,inlineImages:l=!1,recordCanvas:c=!1,maskAllInputs:u=!1,maskTextFn:h,maskInputFn:p,slimDOM:d=!1,dataURLOptions:f,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:w,onStylesheetLoad:v,stylesheetLoadTimeout:b,keepIframeSrcFn:_=()=>!1}=t||{};return Ml(e,{doc:e,mirror:r,blockClass:n,blockSelector:s,maskTextClass:i,maskTextSelector:o,skipChild:!1,inlineStylesheet:a,maskInputOptions:!0===u?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===u?{password:!0}:u,maskTextFn:h,maskInputFn:p,slimDOMOptions:Rl(d),dataURLOptions:f,inlineImages:l,recordCanvas:c,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:w,onStylesheetLoad:v,stylesheetLoadTimeout:b,keepIframeSrcFn:_,newlyAddedElement:!1})}(document,{mirror:$y,blockClass:s,blockSelector:i,maskTextClass:l,maskTextSelector:c,inlineStylesheet:u,maskAllInputs:P,maskTextFn:m,maskInputFn:f,slimDOM:L,dataURLOptions:v,recordCanvas:S,inlineImages:x,onSerialize:e=>{jg(e,$y)&&G.addIframe(e),zg(e,$y)&&V.trackLinkElement(e),Vg(e)&&Z.addShadowRoot(Tg.shadowRoot(e),document)},onIframeLoad:(e,t)=>{G.attachIframe(e,t),Z.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{V.attachLinkElement(e,t)},keepIframeSrcFn:A});if(!t)return console.warn("Failed to snapshot the document");Vy({type:Wg.FullSnapshot,data:{node:t,initialOffset:Mg(window)}},e),uy.forEach(e=>e.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&V.adoptStyleSheets(document.adoptedStyleSheets,$y.getId(document))};try{const e=[],t=e=>{var t;return cy(by)({mutationCb:B,mousemoveCb:(e,t)=>Vy({type:Wg.IncrementalSnapshot,data:{source:t,positions:e}}),mouseInteractionCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.MouseInteraction,...e}}),scrollCb:j,viewportResizeCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.ViewportResize,...e}}),inputCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.Input,...e}}),mediaInteractionCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.MediaInteraction,...e}}),styleSheetRuleCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.StyleSheetRule,...e}}),styleDeclarationCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.StyleDeclaration,...e}}),canvasMutationCb:z,fontCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.Font,...e}}),selectionCb:e=>{Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.Selection,...e}})},customElementCb:e=>{Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.CustomElement,...e}})},blockClass:s,ignoreClass:o,ignoreSelector:a,maskTextClass:l,maskTextSelector:c,maskInputOptions:P,inlineStylesheet:u,sampling:w,recordDOM:_,recordCanvas:S,inlineImages:x,userTriggeredOnInput:T,collectFonts:k,doc:e,maskInputFn:f,maskTextFn:m,keepIframeSrcFn:A,blockSelector:i,slimDOMOptions:L,dataURLOptions:v,mirror:$y,iframeManager:G,stylesheetManager:V,shadowDomManager:Z,processedNodeManager:H,canvasManager:Hy,ignoreCSSAttributes:I,plugins:(null==(t=null==O?void 0:O.filter(e=>e.observer))?void 0:t.map(e=>({observer:e.observer,options:e.options,callback:t=>Vy({type:Wg.Plugin,data:{plugin:e.name,payload:t}})})))||[]},g)};G.addLoadListener(r=>{try{e.push(t(r.contentDocument))}catch(e){console.warn(e)}});const r=()=>{Gy(),e.push(t(document)),Zy=!0};return["interactive","complete"].includes(document.readyState)?r():(e.push(kg("DOMContentLoaded",()=>{Vy({type:Wg.DomContentLoaded,data:{}}),"DOMContentLoaded"===E&&r()})),e.push(kg("load",()=>{Vy({type:Wg.Load,data:{}}),"load"===E&&r()},window))),()=>{e.forEach(e=>{try{e()}catch(e){String(e).toLowerCase().includes("cross-origin")||console.warn(e)}}),H.destroy(),Zy=!1,ly=void 0}}catch(e){console.warn(e)}}var Yy;Wy.addCustomEvent=(e,t)=>{if(!Zy)throw new Error("please add custom event after start recording");Vy({type:Wg.Custom,data:{tag:e,payload:t}})},Wy.freezePage=()=>{uy.forEach(e=>e.freeze())},Wy.takeFullSnapshot=e=>{if(!Zy)throw new Error("please take full snapshot after start recording");Gy(e)},Wy.mirror=$y,function(e){e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped"}(Yy||(Yy={}));const Xy=5e3;class Jy{constructor(e,t,r){this.events=[],this.stopRecording=void 0,this.saveInterval=null,this.isSaving=!1,this.isConfigured=!1,this._enabled=!0,this.userAttributes={},this._listenersAttached=!1,this.handleUnload=()=>this.save(!0),this.handleVisibilityChange=()=>{"hidden"===document.visibilityState&&this.save()},this.sessionId=t,this.tabId=r,this.config=e,this.setupListeners()}setupListeners(){"undefined"==typeof window||this._listenersAttached||(this._listenersAttached=!0,window.addEventListener("beforeunload",this.handleUnload),window.addEventListener("pagehide",this.handleUnload),document.addEventListener("visibilitychange",this.handleVisibilityChange))}removeListeners(){"undefined"!=typeof window&&this._listenersAttached&&(this._listenersAttached=!1,window.removeEventListener("beforeunload",this.handleUnload),window.removeEventListener("pagehide",this.handleUnload),document.removeEventListener("visibilitychange",this.handleVisibilityChange))}trimEvents(){if(this.events.length<=Xy)return;this.config.debug&&console.warn("Event queue exceeded 5000, dropping middle events (preserving snapshots)");const e=this.events.filter(e=>2===e.type),t=this.events.filter(e=>2!==e.type),r=Math.max(0,Xy-e.length);this.events=[...e,...t.slice(-r)],this.events.sort((e,t)=>e.timestamp-t.timestamp)}configure(){if("undefined"==typeof window)return;if(this.isConfigured)return;this.setupListeners();const e=Math.max(0,Math.min(1,this.config.replaySampleRate??1));if(Math.random()>=e)return this._enabled=!1,void(this.config.debug&&console.log("MonoscopeReplay: sampled out"));try{this.stopRecording=Wy({emit:e=>{this._enabled&&(this.events.push(e),this.events.length>=50&&this.save())},blockClass:"rr-block",maskAllInputs:!0,maskInputOptions:{password:!0,email:!0,tel:!0},maskTextClass:"rr-mask",checkoutEveryNms:15e3,sampling:{mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!1,Blur:!1,TouchStart:!0,TouchEnd:!1},mousemove:!0,scroll:150,media:800,input:"last"},plugins:[(t={level:["info","log","warn","error"],lengthThreshold:1e4,stringifyOptions:{stringLengthLimit:1e3,numOfKeysLimit:100,depthOfLimit:2}},{name:"rrweb/console@1",observer:Pa,options:t})]}),this.saveInterval=setInterval(()=>this.save(),2e3),this.isConfigured=!0,this.config.debug&&console.log("MonoscopeReplay configured successfully")}catch(e){console.warn("Monoscope: failed to configure replay",e)}var t}async save(e=!1){if(this.isSaving&&!e)return;if(0===this.events.length)return;this.trimEvents(),this.isSaving=!0;const t=this.config.apiKey||this.config.projectId||"",r=`${this.config.replayEventsBaseUrl||"https://app.monoscope.tech"}/api/v1/rrweb`,n=[...this.events];this.events=[];const s={events:n,sessionId:this.sessionId,tabId:this.tabId,timestamp:(new Date).toISOString(),eventCount:n.length,user:Object.keys(this.userAttributes).length>0?this.userAttributes:void 0},i={"Content-Type":"application/json",Authorization:`Bearer ${t}`};try{if(e&&"undefined"!=typeof navigator&&navigator.sendBeacon){const e=new Blob([JSON.stringify(s)],{type:"application/json"});navigator.sendBeacon(r,e)||fetch(r,{method:"POST",headers:i,body:JSON.stringify(s),keepalive:!0}).catch(()=>{})}else{const e=JSON.stringify(s),t=await fetch(r,{method:"POST",headers:i,body:e,keepalive:e.length<63e3});if(!t.ok){const e=t.status;throw 401===e||403===e?console.warn("[Monoscope] Replay upload authentication failed. Your apiKey may be invalid."):console.warn(`[Monoscope] Replay upload failed (${e}). Check your apiKey and network.`),new Error(`Failed to save replay events: ${e} ${t.statusText}`)}this.config.debug&&console.log(`Successfully saved ${n.length} replay events`)}}catch(e){console.warn("Monoscope: failed to save replay events:",e),this.events=[...n,...this.events],this.trimEvents()}finally{this.isSaving=!1}}stop(){this.save(!0).catch(()=>{}),this.stopRecording&&(this.stopRecording(),this.stopRecording=void 0),this.saveInterval&&(clearInterval(this.saveInterval),this.saveInterval=null),this.removeListeners(),this.isConfigured=!1,this.config.debug&&console.log("MonoscopeReplay stopped")}setEnabled(e){this._enabled=e,e||this.stop()}setUser(e){this.userAttributes={...this.userAttributes,...e}}getEventCount(){return this.events.length}updateSessionId(e){this.sessionId=e}getSessionId(){return this.sessionId}isRecording(){return this.isConfigured&&void 0!==this.stopRecording}}const Ky="1.9.1",qy=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;const Qy=function(e){const t=new Set([e]),r=new Set,n=e.match(qy);if(!n)return()=>!1;const s=+n[1],i=+n[2],o=+n[3];if(null!=n[4])return function(t){return t===e};function a(e){return r.add(e),!1}function l(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;const n=e.match(qy);if(!n)return a(e);const c=+n[1],u=+n[2],h=+n[3];return null!=n[4]||s!==c?a(e):0===s?i===u&&o<=h?l(e):a(e):i<=u?l(e):a(e)}}(Ky),ew=Ky.split(".")[0],tw=Symbol.for(`opentelemetry.js.api.${ew}`),rw="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{};function nw(e,t,r,n=!1){var s;const i=rw[tw]=null!==(s=rw[tw])&&void 0!==s?s:{version:Ky};if(!n&&i[e]){const t=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return r.error(t.stack||t.message),!1}if(i.version!==Ky){const t=new Error(`@opentelemetry/api: Registration of version v${i.version} for ${e} does not match previously registered API v${Ky}`);return r.error(t.stack||t.message),!1}return i[e]=t,r.debug(`@opentelemetry/api: Registered a global for ${e} v${Ky}.`),!0}function sw(e){var t,r;const n=null===(t=rw[tw])||void 0===t?void 0:t.version;if(n&&Qy(n))return null===(r=rw[tw])||void 0===r?void 0:r[e]}function iw(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${Ky}.`);const r=rw[tw];r&&delete r[e]}class ow{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return aw("debug",this._namespace,e)}error(...e){return aw("error",this._namespace,e)}info(...e){return aw("info",this._namespace,e)}warn(...e){return aw("warn",this._namespace,e)}verbose(...e){return aw("verbose",this._namespace,e)}}function aw(e,t,r){const n=sw("diag");if(n)return n[e](t,...r)}var lw;!function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"}(lw||(lw={}));class cw{static instance(){return this._instance||(this._instance=new cw),this._instance}constructor(){function e(e){return function(...t){const r=sw("diag");if(r)return r[e](...t)}}const t=this;t.setLogger=(e,r={logLevel:lw.INFO})=>{var n,s,i;if(e===t){const e=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error(null!==(n=e.stack)&&void 0!==n?n:e.message),!1}"number"==typeof r&&(r={logLevel:r});const o=sw("diag"),a=function(e,t){function r(r,n){const s=t[r];return"function"==typeof s&&e>=n?s.bind(t):function(){}}return elw.ALL&&(e=lw.ALL),t=t||{},{error:r("error",lw.ERROR),warn:r("warn",lw.WARN),info:r("info",lw.INFO),debug:r("debug",lw.DEBUG),verbose:r("verbose",lw.VERBOSE)}}(null!==(s=r.logLevel)&&void 0!==s?s:lw.INFO,e);if(o&&!r.suppressOverrideMessage){const e=null!==(i=(new Error).stack)&&void 0!==i?i:"";o.warn(`Current logger will be overwritten from ${e}`),a.warn(`Current logger will overwrite one already registered from ${e}`)}return nw("diag",a,t,!0)},t.disable=()=>{iw("diag",t)},t.createComponentLogger=e=>new ow(e),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}class uw{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){const t=this._entries.get(e);if(t)return Object.assign({},t)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,t){const r=new uw(this._entries);return r._entries.set(e,t),r}removeEntry(e){const t=new uw(this._entries);return t._entries.delete(e),t}removeEntries(...e){const t=new uw(this._entries);for(const r of e)t._entries.delete(r);return t}clear(){return new uw}}const hw=Symbol("BaggageEntryMetadata"),pw=cw.instance();function dw(e={}){return new uw(new Map(Object.entries(e)))}function fw(e){return Symbol.for(e)}class mw{constructor(e){const t=this;t._currentContext=e?new Map(e):new Map,t.getValue=e=>t._currentContext.get(e),t.setValue=(e,r)=>{const n=new mw(t._currentContext);return n._currentContext.set(e,r),n},t.deleteValue=e=>{const r=new mw(t._currentContext);return r._currentContext.delete(e),r}}}const gw=new mw;class yw{}class ww{addCallback(e){}removeCallback(e){}}const vw=new class{constructor(){}createGauge(e,t){return _w}createHistogram(e,t){return Sw}createCounter(e,t){return bw}createUpDownCounter(e,t){return Cw}createObservableGauge(e,t){return Tw}createObservableCounter(e,t){return Ew}createObservableUpDownCounter(e,t){return kw}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}},bw=new class extends yw{add(e,t){}},_w=new class extends yw{record(e,t){}},Sw=new class extends yw{record(e,t){}},Cw=new class extends yw{add(e,t){}},Ew=new class extends ww{},Tw=new class extends ww{},kw=new class extends ww{};function xw(){return vw}var Ow;!function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"}(Ow||(Ow={}));const Aw={get(e,t){if(null!=e)return e[t]},keys:e=>null==e?[]:Object.keys(e)},Iw={set(e,t,r){null!=e&&(e[t]=r)}};const Rw="context",Mw=new class{active(){return gw}with(e,t,r,...n){return t.call(r,...n)}bind(e,t){return t}enable(){return this}disable(){return this}};class Nw{constructor(){}static getInstance(){return this._instance||(this._instance=new Nw),this._instance}setGlobalContextManager(e){return nw(Rw,e,cw.instance())}active(){return this._getContextManager().active()}with(e,t,r,...n){return this._getContextManager().with(e,t,r,...n)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return sw(Rw)||Mw}disable(){this._getContextManager().disable(),iw(Rw,cw.instance())}}var Pw;!function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"}(Pw||(Pw={}));const Lw="0000000000000000",Dw="00000000000000000000000000000000",Uw={traceId:Dw,spanId:Lw,traceFlags:Pw.NONE};class Fw{constructor(e=Uw){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}const Bw=fw("OpenTelemetry Context Key SPAN");function jw(e){return e.getValue(Bw)||void 0}function zw(){return jw(Nw.getInstance().active())}function Vw(e,t){return e.setValue(Bw,t)}function Gw(e){return e.deleteValue(Bw)}function Hw(e,t){return Vw(e,new Fw(t))}function Zw(e){var t;return null===(t=jw(e))||void 0===t?void 0:t.spanContext()}const $w=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function Ww(e,t){if("string"!=typeof e||e.length!==t)return!1;let r=0;for(let t=0;tc}}var c;return{key:o,value:a,metadata:l}}class Ov{inject(e,t,r){const n=bv.getBaggage(e);if(!n||Tv(e))return;const s=function(e){return e.getAllEntries().map(([e,t])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return void 0!==t.metadata&&(r+=";"+t.metadata.toString()),r})}(n).filter(e=>e.length<=4096).slice(0,180),i=function(e){return e.reduce((e,t)=>{const r=`${e}${""!==e?",":""}${t}`;return r.length>8192?e:r},"")}(s);i.length>0&&r.set(t,kv,i)}extract(e,t,r){const n=r.get(t,kv),s=Array.isArray(n)?n.join(","):n;if(!s)return e;const i={};if(0===s.length)return e;return s.split(",").forEach(e=>{const t=xv(e);if(t){const e={value:t.value};t.metadata&&(e.metadata=t.metadata),i[t.key]=e}}),0===Object.entries(i).length?e:bv.setBaggage(e,bv.createBaggage(i))}fields(){return[kv]}}function Av(e){const t={};if("object"!=typeof e||null==e)return t;for(const r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;if(!Iv(r)){av.warn(`Invalid attribute key: ${r}`);continue}const n=e[r];Rv(n)?Array.isArray(n)?t[r]=n.slice():t[r]=n:av.warn(`Invalid attribute value set for key: ${r}`)}return t}function Iv(e){return"string"==typeof e&&""!==e}function Rv(e){return null==e||(Array.isArray(e)?function(e){let t;for(const r of e){if(null==r)continue;const e=typeof r;if(e!==t){if(!t){if(Mv(e)){t=e;continue}return!1}return!1}}return!0}(e):Mv(typeof e))}function Mv(e){switch(e){case"number":case"boolean":case"string":return!0}return!1}let Nv=e=>{av.error(function(e){return"string"==typeof e?e:JSON.stringify(function(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}(e))}(e))};function Pv(e){try{Nv(e)}catch{}}const Lv="http.url",Dv="error.type",Uv="exception.message",Fv="exception.type",Bv="http.request.method",jv="http.request.method_original",zv="http.response.status_code",Vv="server.address",Gv="server.port",Hv="service.name",Zv="telemetry.sdk.language",$v="webjs",Wv="telemetry.sdk.name",Yv="telemetry.sdk.version",Xv="url.full",Jv="process.runtime.name",Kv={[Wv]:"opentelemetry",[Jv]:"browser",[Zv]:$v,[Yv]:"2.6.1"},qv=performance,Qv=Math.pow(10,6),eb=Math.pow(10,9);function tb(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*Qv)]}function rb(e){return ib(tb(qv.timeOrigin),tb("number"==typeof e?e:qv.now()))}function nb(e){return Array.isArray(e)&&2===e.length&&"number"==typeof e[0]&&"number"==typeof e[1]}function sb(e){return nb(e)||"number"==typeof e||e instanceof Date}function ib(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=eb&&(r[1]-=eb,r[0]+=1),r}var ob;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ob||(ob={}));class ab{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>"function"==typeof e.fields?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,t,r){for(const n of this._propagators)try{n.inject(e,t,r)}catch(e){av.warn(`Failed to inject with ${n.constructor.name}. Err: ${e.message}`)}}extract(e,t,r){return this._propagators.reduce((e,n)=>{try{return n.extract(e,t,r)}catch(e){av.warn(`Failed to extract with ${n.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}const lb="[_0-9a-z-*/]",cb=new RegExp(`^(?:${`[a-z]${lb}{0,255}`}|${`[a-z0-9]${lb}{0,240}@[a-z]${lb}{0,13}`})$`),ub=/^[ -~]{0,255}[!-~]$/,hb=/,|=/;class pb{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){const r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){const t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+"="+this.get(t)),e),[]).join(",")}_parse(e){e.length>512||(this._internalState=e.split(",").reverse().reduce((e,t)=>{const r=t.trim(),n=r.indexOf("=");if(-1!==n){const s=r.slice(0,n),i=r.slice(n+1,t.length);(function(e){return cb.test(e)})(s)&&function(e){return ub.test(e)&&!hb.test(e)}(i)&&e.set(s,i)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const e=new pb;return e._internalState=new Map(this._internalState),e}}const db="traceparent",fb="tracestate",mb=new RegExp("^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$");class gb{inject(e,t,r){const n=Cv.getSpanContext(e);if(!n||Tv(e)||!Xw(n))return;const s=`00-${n.traceId}-${n.spanId}-0${Number(n.traceFlags||Pw.NONE).toString(16)}`;r.set(t,db,s),n.traceState&&r.set(t,fb,n.traceState.serialize())}extract(e,t,r){const n=r.get(t,db);if(!n)return e;const s=Array.isArray(n)?n[0]:n;if("string"!=typeof s)return e;const i=function(e){const t=mb.exec(e);return t?"00"===t[1]&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}:null}(s);if(!i)return e;i.isRemote=!0;const o=r.get(t,fb);if(o){const e=Array.isArray(o)?o.join(","):o;i.traceState=new pb("string"==typeof e?e:void 0)}return Cv.setSpanContext(e,i)}fields(){return[db,fb]}}const yb="[object Null]",wb="[object Undefined]",vb=Function.prototype.toString,bb=vb.call(Object),_b=Object.getPrototypeOf,Sb=Object.prototype,Cb=Sb.hasOwnProperty,Eb=Symbol?Symbol.toStringTag:void 0,Tb=Sb.toString;function kb(e){if(!function(e){return null!=e&&"object"==typeof e}(e)||"[object Object]"!==function(e){if(null==e)return void 0===e?wb:yb;return Eb&&Eb in Object(e)?function(e){const t=Cb.call(e,Eb),r=e[Eb];let n=!1;try{e[Eb]=void 0,n=!0}catch{}const s=Tb.call(e);n&&(t?e[Eb]=r:delete e[Eb]);return s}(e):function(e){return Tb.call(e)}(e)}(e))return!1;const t=_b(e);if(null===t)return!0;const r=Cb.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&vb.call(r)===bb}function xb(e){return Ib(e)?e.slice():e}function Ob(e,t,r=0,n){let s;if(!(r>20)){if(r++,Nb(e)||Nb(t)||Rb(t))s=xb(t);else if(Ib(e)){if(s=e.slice(),Ib(t))for(let e=0,r=t.length;e{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}class Lb{_isCalled=!1;_deferred=new Pb;_callback;_that;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}let Db;function Ub(){if(void 0===Db)try{const e=globalThis.process.argv0;Db=e?`unknown_service:${e}`:"unknown_service"}catch{Db="unknown_service"}return Db}const Fb=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;let Bb=class e{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,r){const n=new e({},r);return n._rawAttributes=zb(t),n._asyncAttributesPending=t.filter(([e,t])=>Fb(t)).length>0,n}constructor(e,t){const r=e.attributes??{};this._rawAttributes=Object.entries(r).map(([e,t])=>(Fb(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=zb(this._rawAttributes),this._schemaUrl=function(e){if("string"==typeof e||void 0===e)return e;return void av.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",e)}(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;eFb(t)?[e,t.catch(t=>{av.debug("promise rejection for resource attribute: %s - %s",e,t)})]:[e,t])}class Vb{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;_attributesCount=0;name;status={code:iv.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_recordEndMetrics;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){const t=Date.now();if(this._spanContext=e.spanContext,this._performanceStartTime=qv.now(),this._performanceOffset=t-(this._performanceStartTime+qv.timeOrigin),this._startTimeProvided=null!=e.startTime,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit??0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,e.links)for(const t of e.links)this.addLink(t);this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,this._recordEndMetrics=e.recordEndMetrics,null!=e.attributes&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,t){if(null==t||this._isSpanEnded())return this;if(0===e.length)return av.warn(`Invalid attribute key: ${e}`),this;if(!Rv(t))return av.warn(`Invalid attribute value set for key: ${e}`),this;const{attributeCountLimit:r}=this._spanLimits,n=!Object.prototype.hasOwnProperty.call(this.attributes,e);return void 0!==r&&this._attributesCount>=r&&n?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(t),n&&this._attributesCount++,this)}setAttributes(e){for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setAttribute(t,e[t]);return this}addEvent(e,t,r){if(this._isSpanEnded())return this;const{eventCountLimit:n}=this._spanLimits;if(0===n)return av.warn("No events allowed."),this._droppedEventsCount++,this;void 0!==n&&this.events.length>=n&&(0===this._droppedEventsCount&&av.debug("Dropping extra events."),this.events.shift(),this._droppedEventsCount++),sb(t)&&(sb(r)||(r=t),t=void 0);const s=Av(t),{attributePerEventCountLimit:i}=this._spanLimits,o={};let a=0,l=0;for(const e in s){if(!Object.prototype.hasOwnProperty.call(s,e))continue;const t=s[e];void 0!==i&&l>=i?a++:(o[e]=this._truncateToSize(t),l++)}return this.events.push({name:e,attributes:o,time:this._getTime(r),droppedAttributesCount:a}),this}addLink(e){if(this._isSpanEnded())return this;const{linkCountLimit:t}=this._spanLimits;if(0===t)return this._droppedLinksCount++,this;void 0!==t&&this.links.length>=t&&(0===this._droppedLinksCount&&av.debug("Dropping extra links."),this.links.shift(),this._droppedLinksCount++);const{attributePerLinkCountLimit:r}=this._spanLimits,n=Av(e.attributes),s={};let i=0,o=0;for(const e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;const t=n[e];void 0!==r&&o>=r?i++:(s[e]=this._truncateToSize(t),o++)}const a={context:e.context};return o>0&&(a.attributes=s),i>0&&(a.droppedAttributesCount=i),this.links.push(a),this}addLinks(e){for(const t of e)this.addLink(t);return this}setStatus(e){if(this._isSpanEnded())return this;if(e.code===iv.UNSET)return this;if(this.status.code===iv.OK)return this;const t={code:e.code};return e.code===iv.ERROR&&("string"==typeof e.message?t.message=e.message:null!=e.message&&av.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`)),this.status=t,this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){this._isSpanEnded()?av.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`):(this.endTime=this._getTime(e),this._duration=function(e,t){let r=t[0]-e[0],n=t[1]-e[1];return n<0&&(r-=1,n+=eb),[r,n]}(this.startTime,this.endTime),this._duration[0]<0&&(av.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&av.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._droppedLinksCount>0&&av.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`),this._spanProcessor.onEnding&&this._spanProcessor.onEnding(this),this._recordEndMetrics?.(),this._ended=!0,this._spanProcessor.onEnd(this))}_getTime(e){if("number"==typeof e&&e<=qv.now())return rb(e+this._performanceOffset);if("number"==typeof e)return tb(e);if(e instanceof Date)return tb(e.getTime());if(nb(e))return e;if(this._startTimeProvided)return tb(Date.now());const t=qv.now()-this._performanceStartTime;return ib(this.startTime,tb(t))}isRecording(){return!1===this._ended}recordException(e,t){const r={};"string"==typeof e?r[Uv]=e:e&&(e.code?r[Fv]=e.code.toString():e.name&&(r[Fv]=e.name),e.message&&(r[Uv]=e.message),e.stack&&(r["exception.stacktrace"]=e.stack)),r[Fv]||r[Uv]?this.addEvent("exception",r,t):av.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){const e=new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);av.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){const t=this._attributeValueLengthLimit;return t<=0?(av.warn(`Attribute value limit must be positive, got ${t}`),e):"string"==typeof e?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(e=>"string"==typeof e?this._truncateToLimitUtil(e,t):e):e}}var Gb,Hb;!function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(Gb||(Gb={}));class Zb{shouldSample(){return{decision:Gb.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class $b{shouldSample(){return{decision:Gb.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class Wb{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||(Pv(new Error("ParentBasedSampler must have a root sampler configured")),this._root=new $b),this._remoteParentSampled=e.remoteParentSampled??new $b,this._remoteParentNotSampled=e.remoteParentNotSampled??new Zb,this._localParentSampled=e.localParentSampled??new $b,this._localParentNotSampled=e.localParentNotSampled??new Zb}shouldSample(e,t,r,n,s,i){const o=Cv.getSpanContext(e);return o&&Xw(o)?o.isRemote?o.traceFlags&Pw.SAMPLED?this._remoteParentSampled.shouldSample(e,t,r,n,s,i):this._remoteParentNotSampled.shouldSample(e,t,r,n,s,i):o.traceFlags&Pw.SAMPLED?this._localParentSampled.shouldSample(e,t,r,n,s,i):this._localParentNotSampled.shouldSample(e,t,r,n,s,i):this._root.shouldSample(e,t,r,n,s,i)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}class Yb{_ratio;_upperBound;constructor(e=0){this._ratio=this._normalize(e),this._upperBound=Math.floor(4294967295*this._ratio)}shouldSample(e,t){return{decision:Yw(t)&&this._accumulate(t)=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let r=0;r>>0}return t}}!function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"}(Hb||(Hb={}));function Xb(){return{sampler:Jb(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function Jb(){const e=Hb.ParentBasedAlwaysOn;switch(e){case Hb.AlwaysOn:return new $b;case Hb.AlwaysOff:return new Zb;case Hb.ParentBasedAlwaysOn:return new Wb({root:new $b});case Hb.ParentBasedAlwaysOff:return new Wb({root:new Zb});case Hb.TraceIdRatio:return new Yb(Kb());case Hb.ParentBasedTraceIdRatio:return new Wb({root:new Yb(Kb())});default:return av.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "${Hb.ParentBasedAlwaysOn}".`),new Wb({root:new $b})}}function Kb(){return av.error("OTEL_TRACES_SAMPLER_ARG is blank, defaulting to 1."),1}const qb=1/0;class Qb{_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,t){this._exporter=e,this._maxExportBatchSize="number"==typeof t?.maxExportBatchSize?t.maxExportBatchSize:512,this._maxQueueSize="number"==typeof t?.maxQueueSize?t.maxQueueSize:2048,this._scheduledDelayMillis="number"==typeof t?.scheduledDelayMillis?t.scheduledDelayMillis:5e3,this._exportTimeoutMillis="number"==typeof t?.exportTimeoutMillis?t.exportTimeoutMillis:3e4,this._shutdownOnce=new Lb(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(av.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||0!==(e.spanContext().traceFlags&Pw.SAMPLED)&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize)return 0===this._droppedSpansCount&&av.debug("maxQueueSize reached, dropping spans"),void this._droppedSpansCount++;this._droppedSpansCount>0&&(av.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{const r=[];for(let e=0,t=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);e{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),0===this._finishedSpans.length?Promise.resolve():new Promise((e,t)=>{const r=setTimeout(()=>{t(new Error("Timeout"))},this._exportTimeoutMillis);ov.with(function(e){return e.setValue(Ev,!0)}(ov.active()),()=>{let n;this._finishedSpans.length<=this._maxExportBatchSize?(n=this._finishedSpans,this._finishedSpans=[]):n=this._finishedSpans.splice(0,this._maxExportBatchSize);const s=()=>this._exporter.export(n,n=>{clearTimeout(r),n.code===ob.SUCCESS?e():t(n.error??new Error("BatchSpanProcessor: span export failed"))});let i=null;for(let e=0,t=n.length;e{Pv(e),t(e)})})})}_maybeStartTimer(){if(this._isExporting)return;const e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,Pv(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();void 0===this._timer&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),"number"!=typeof this._timer&&this._timer.unref())}_clearTimer(){void 0!==this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}class e_ extends Qb{_visibilityChangeListener;_pageHideListener;constructor(e,t){super(e,t),this.onInit(t)}onInit(e){!0!==e?.disableAutoFlushOnDocumentHide&&"undefined"!=typeof document&&(this._visibilityChangeListener=()=>{"hidden"===document.visibilityState&&this.forceFlush().catch(e=>{Pv(e)})},this._pageHideListener=()=>{this.forceFlush().catch(e=>{Pv(e)})},document.addEventListener("visibilitychange",this._visibilityChangeListener),document.addEventListener("pagehide",this._pageHideListener))}onShutdown(){"undefined"!=typeof document&&(this._visibilityChangeListener&&document.removeEventListener("visibilitychange",this._visibilityChangeListener),this._pageHideListener&&document.removeEventListener("pagehide",this._pageHideListener))}}const t_=new Uint8Array(16),r_=new Uint8Array(8),n_=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function s_(e){for(let t=0;t>>0;for(let t=0;t0)return;e[e.length-1]=1}function i_(e){let t="";for(let r=0;r{};const n={[l_]:r};return this.liveSpans.add(1,n),()=>{this.liveSpans.add(-1,n)}}}function u_(e){return e?e.isRemote?"remote":"local":"none"}class h_{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;_tracerMetrics;constructor(e,t,r,n){const s=function(e){const t={sampler:Jb()},r=Xb(),n=Object.assign({},r,t,e);return n.generalLimits=Object.assign({},r.generalLimits,e.generalLimits||{}),n.spanLimits=Object.assign({},r.spanLimits,e.spanLimits||{}),n}(t);this._sampler=s.sampler,this._generalLimits=s.generalLimits,this._spanLimits=s.spanLimits,this._idGenerator=t.idGenerator||new o_,this._resource=r,this._spanProcessor=n,this.instrumentationScope=e;const i=s.meterProvider?s.meterProvider.getMeter("@opentelemetry/sdk-trace","2.6.1"):xw();this._tracerMetrics=new c_(i)}startSpan(e,t={},r=ov.active()){t.root&&(r=Cv.deleteSpan(r));const n=Cv.getSpan(r);if(Tv(r)){av.debug("Instrumentation suppressed, returning Noop Span");return Cv.wrapSpanContext(Uw)}const s=n?.spanContext(),i=this._idGenerator.generateSpanId();let o,a,l;s&&Cv.isSpanContextValid(s)?(a=s.traceId,l=s.traceState,o=s):a=this._idGenerator.generateTraceId();const c=t.kind??sv.INTERNAL,u=(t.links??[]).map(e=>({context:e.context,attributes:Av(e.attributes)})),h=Av(t.attributes),p=this._sampler.shouldSample(r,a,e,c,h,u),d=this._tracerMetrics.startSpan(s,p.decision);l=p.traceState??l;const f={traceId:a,spanId:i,traceFlags:p.decision===nv.RECORD_AND_SAMPLED?Pw.SAMPLED:Pw.NONE,traceState:l};if(p.decision===nv.NOT_RECORD){av.debug("Recording is off, propagating context in a non-recording span");return Cv.wrapSpanContext(f)}const m=Av(Object.assign(h,p.attributes));return new Vb({resource:this._resource,scope:this.instrumentationScope,context:r,spanContext:f,name:e,kind:c,links:u,parentSpanContext:o,attributes:m,startTime:t.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits,recordEndMetrics:d})}startActiveSpan(e,t,r,n){let s,i,o;if(arguments.length<2)return;2===arguments.length?o=t:3===arguments.length?(s=t,o=r):(s=t,i=r,o=n);const a=i??ov.active(),l=this.startSpan(e,s,a),c=Cv.setSpan(a,l);return ov.with(c,o,void 0,l)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class p_{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){const e=[];for(const t of this._spanProcessors)e.push(t.forceFlush());return new Promise(t=>{Promise.all(e).then(()=>{t()}).catch(e=>{Pv(e||new Error("MultiSpanProcessor: forceFlush failed")),t()})})}onStart(e,t){for(const r of this._spanProcessors)r.onStart(e,t)}onEnding(e){for(const t of this._spanProcessors)t.onEnding&&t.onEnding(e)}onEnd(e){for(const t of this._spanProcessors)t.onEnd(e)}shutdown(){const e=[];for(const t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,r)=>{Promise.all(e).then(()=>{t()},r)})}}var d_,f_;!function(e){e[e.resolved=0]="resolved",e[e.timeout=1]="timeout",e[e.error=2]="error",e[e.unresolved=3]="unresolved"}(d_||(d_={}));class m_{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){const t=function(...e){let t=e.shift();const r=new WeakMap;for(;e.length>0;)t=Ob(t,e.shift(),0,r);return t}({},Xb(),function(e){const t=Object.assign({},e.spanLimits);return t.attributeCountLimit=e.spanLimits?.attributeCountLimit??e.generalLimits?.attributeCountLimit??void 0??void 0??128,t.attributeValueLengthLimit=e.spanLimits?.attributeValueLengthLimit??e.generalLimits?.attributeValueLengthLimit??void 0??void 0??qb,Object.assign({},e,{spanLimits:t})}(e));this._resource=t.resource??jb({[Hv]:Ub(),[Zv]:Kv[Zv],[Wv]:Kv[Wv],[Yv]:Kv[Yv]}),this._config=Object.assign({},t,{resource:this._resource});const r=[];e.spanProcessors?.length&&r.push(...e.spanProcessors),this._activeSpanProcessor=new p_(r)}getTracer(e,t,r){const n=`${e}@${t||""}:${r?.schemaUrl||""}`;return this._tracers.has(n)||this._tracers.set(n,new h_({name:e,version:t,schemaUrl:r?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(n)}forceFlush(){const e=this._config.forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(r=>{let n;const s=setTimeout(()=>{r(new Error(`Span processor did not completed within timeout period of ${e} ms`)),n=d_.timeout},e);t.forceFlush().then(()=>{clearTimeout(s),n!==d_.timeout&&(n=d_.resolved,r(n))}).catch(e=>{clearTimeout(s),n=d_.error,r(e)})}));return new Promise((e,r)=>{Promise.all(t).then(t=>{const n=t.filter(e=>e!==d_.resolved);n.length>0?r(n):e()}).catch(e=>r([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}class g_{_enabled=!1;_currentContext=gw;_bindFunction(e=gw,t){const r=this,n=function(...n){return r.with(e,()=>t.apply(this,n))};return Object.defineProperty(n,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),n}active(){return this._currentContext}bind(e,t){return void 0===e&&(e=this.active()),"function"==typeof t?this._bindFunction(e,t):t}disable(){return this._currentContext=gw,this._enabled=!1,this}enable(){return this._enabled||(this._enabled=!0,this._currentContext=gw),this}with(e,t,r,...n){const s=this._currentContext;this._currentContext=e||gw;try{return t.call(r,...n)}finally{this._currentContext=s}}}class y_ extends m_{constructor(e={}){super(e)}register(e={}){var t;Cv.setGlobalTracerProvider(this),null!==(t=e.propagator)&&(void 0!==t?bv.setGlobalPropagator(t):bv.setGlobalPropagator(new ab({propagators:[new gb,new Ov]}))),function(e){if(null!==e){if(void 0===e){const e=new g_;return e.enable(),void ov.setGlobalContextManager(e)}e.enable(),ov.setGlobalContextManager(e)}}(e.contextManager)}}!function(e){e.CONNECT_END="connectEnd",e.CONNECT_START="connectStart",e.DECODED_BODY_SIZE="decodedBodySize",e.DOM_COMPLETE="domComplete",e.DOM_CONTENT_LOADED_EVENT_END="domContentLoadedEventEnd",e.DOM_CONTENT_LOADED_EVENT_START="domContentLoadedEventStart",e.DOM_INTERACTIVE="domInteractive",e.DOMAIN_LOOKUP_END="domainLookupEnd",e.DOMAIN_LOOKUP_START="domainLookupStart",e.ENCODED_BODY_SIZE="encodedBodySize",e.FETCH_START="fetchStart",e.LOAD_EVENT_END="loadEventEnd",e.LOAD_EVENT_START="loadEventStart",e.NAVIGATION_START="navigationStart",e.REDIRECT_END="redirectEnd",e.REDIRECT_START="redirectStart",e.REQUEST_START="requestStart",e.RESPONSE_END="responseEnd",e.RESPONSE_START="responseStart",e.SECURE_CONNECTION_START="secureConnectionStart",e.START_TIME="startTime",e.UNLOAD_EVENT_END="unloadEventEnd",e.UNLOAD_EVENT_START="unloadEventStart"}(f_||(f_={}));function w_(e,t){return t in e}function v_(e,t,r,n=!0){if(w_(r,t)&&"number"==typeof r[t]&&(!n||0!==r[t]))return e.addEvent(t,r[t])}function b_(e,t,r=!1,n,s){void 0===n&&(n=0!==t[f_.START_TIME]),r||(v_(e,f_.FETCH_START,t,n),v_(e,f_.DOMAIN_LOOKUP_START,t,n),v_(e,f_.DOMAIN_LOOKUP_END,t,n),v_(e,f_.CONNECT_START,t,n),v_(e,f_.SECURE_CONNECTION_START,t,n),v_(e,f_.CONNECT_END,t,n),v_(e,f_.REQUEST_START,t,n),v_(e,f_.RESPONSE_START,t,n),v_(e,f_.RESPONSE_END,t,n));{const r=t[f_.ENCODED_BODY_SIZE];void 0!==r&&e.setAttribute("http.response_content_length",r);const n=t[f_.DECODED_BODY_SIZE];void 0!==n&&r!==n&&e.setAttribute("http.response_content_length_uncompressed",n)}}function __(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return"/";const r=function(e){const t=e.nodeType,r=function(e){if(!e.parentNode)return 0;const t=[e.nodeType];e.nodeType===Node.CDATA_SECTION_NODE&&t.push(Node.TEXT_NODE);let r=Array.from(e.parentNode.childNodes);if(r=r.filter(r=>{const n=r.localName;return t.indexOf(r.nodeType)>=0&&n===e.localName}),r.length>=1)return r.indexOf(e)+1;return 0}(e);let n="";if(t===Node.ELEMENT_NODE){const t=e.getAttribute("id");if(t)return`//*[@id="${t}"]`;n=e.localName}else if(t===Node.TEXT_NODE||t===Node.CDATA_SECTION_NODE)n="text()";else{if(t!==Node.COMMENT_NODE)return"";n="comment()"}if(n&&r>1)return`/${n}[${r}]`;return`/${n}`}(e);if(r.indexOf("@id")>0)return r;let n="";return e.parentNode&&(n+=__(e.parentNode)),n+=r,n}let S_=class{emit(e){}};const C_=new S_;const E_=new class{getLogger(e,t,r){return new S_}};let T_=class{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):C_}},k_=class{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new T_(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:E_}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}};const x_="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},O_=Symbol.for("io.opentelemetry.js.api.logs"),A_=x_;const I_=class e{constructor(){this._proxyLoggerProvider=new k_}static getInstance(){return this._instance||(this._instance=new e),this._instance}setGlobalLoggerProvider(e){return A_[O_]?this.getLoggerProvider():(A_[O_]=(t=1,r=e,n=E_,e=>e===t?r:n),this._proxyLoggerProvider.setDelegate(e),e);var t,r,n}getLoggerProvider(){var e,t;return null!==(t=null===(e=A_[O_])||void 0===e?void 0:e.call(A_,1))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete A_[O_],this._proxyLoggerProvider=new k_}}.getInstance();let R_=console.error.bind(console);function M_(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const N_=(e,t,r)=>{if(!e||!e[t])return void R_("no original function "+String(t)+" to wrap");if(!r)return R_("no wrapper function"),void R_((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void R_("original object and wrapper must be functions");const s=r(n,t);return M_(s,"__original",n),M_(s,"__unwrap",()=>{e[t]===s&&M_(e,t,n)}),M_(s,"__wrapped",!0),M_(e,t,s),s},P_=(e,t,r)=>{if(!e)return R_("must provide one or more modules to patch"),void R_((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{N_(e,t,r)})}):R_("must provide one or more functions to wrap on modules")},L_=(e,t)=>{if(!e||!e[t])return R_("no function to unwrap."),void R_((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():R_("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},D_=(e,t)=>{if(!e)return R_("must provide one or more modules to patch"),void R_((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{L_(e,t)})}):R_("must provide one or more functions to unwrap on modules")};let U_=class{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=av.createComponentLogger({namespace:e}),this._tracer=Cv.getTracer(e,t),this._meter=hv.getMeter(e,t),this._logger=I_.getLogger(e,t),this._updateMetricInstruments()}_wrap=N_;_unwrap=L_;_massWrap=P_;_massUnwrap=D_;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}},F_=class extends U_{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}};function B_(e,t,r){let n,s;try{s=e()}catch(e){n=e}finally{return t(n,s),s}}function j_(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var z_,V_;function G_(e,t){let r=z_.OLD;const n=t?.split(",").map(e=>e.trim()).filter(e=>""!==e);for(const t of n??[]){if(t.toLowerCase()===e+"/dup"){r=z_.DUPLICATE;break}t.toLowerCase()===e&&(r=z_.STABLE)}return r}!function(e){e[e.STABLE=1]="STABLE",e[e.OLD=2]="OLD",e[e.DUPLICATE=3]="DUPLICATE"}(z_||(z_={})),function(e){e.DOCUMENT_LOAD="documentLoad",e.DOCUMENT_FETCH="documentFetch",e.RESOURCE_FETCH="resourceFetch"}(V_||(V_={}));var H_;!function(e){e.FIRST_PAINT="firstPaint",e.FIRST_CONTENTFUL_PAINT="firstContentfulPaint"}(H_||(H_={}));const Z_={"first-paint":H_.FIRST_PAINT,"first-contentful-paint":H_.FIRST_CONTENTFUL_PAINT};class $_ extends F_{component="document-load";version="1";moduleName=this.component;constructor(e={}){super("@opentelemetry/instrumentation-document-load","0.48.0",e)}init(){}_onDocumentLoaded(){window.setTimeout(()=>{this._collectPerformance()})}_addResourcesSpans(e){const t=qv.getEntriesByType?.("resource");t&&t.forEach(t=>{this._initResourceSpan(t,e)})}_collectPerformance(){const e=Array.from(document.getElementsByTagName("meta")).find(e=>e.getAttribute("name")===db),t=(()=>{const e={},t=qv.getEntriesByType?.("navigation")[0];if(t)Object.values(f_).forEach(r=>{if(w_(t,r)){const n=t[r];"number"==typeof n&&(e[r]=n)}});else{const t=qv.timing;t&&Object.values(f_).forEach(r=>{if(w_(t,r)){const n=t[r];"number"==typeof n&&(e[r]=n)}})}return e})(),r=e&&e.content||"";ov.with(bv.extract(gw,{traceparent:r}),()=>{const e=this._startSpan(V_.DOCUMENT_LOAD,f_.FETCH_START,t);e&&(ov.with(Cv.setSpan(ov.active(),e),()=>{const e=this._startSpan(V_.DOCUMENT_FETCH,f_.FETCH_START,t);e&&(e.setAttribute(Lv,location.href),ov.with(Cv.setSpan(ov.active(),e),()=>{b_(e,t,this.getConfig().ignoreNetworkEvents),this._addCustomAttributesOnSpan(e,this.getConfig().applyCustomAttributesOnSpan?.documentFetch),this._endSpan(e,f_.RESPONSE_END,t)}))}),e.setAttribute(Lv,location.href),e.setAttribute("http.user_agent",navigator.userAgent),this._addResourcesSpans(e),this.getConfig().ignoreNetworkEvents||(v_(e,f_.FETCH_START,t),v_(e,f_.UNLOAD_EVENT_START,t),v_(e,f_.UNLOAD_EVENT_END,t),v_(e,f_.DOM_INTERACTIVE,t),v_(e,f_.DOM_CONTENT_LOADED_EVENT_START,t),v_(e,f_.DOM_CONTENT_LOADED_EVENT_END,t),v_(e,f_.DOM_COMPLETE,t),v_(e,f_.LOAD_EVENT_START,t),v_(e,f_.LOAD_EVENT_END,t)),this.getConfig().ignorePerformancePaintEvents||(e=>{const t=qv.getEntriesByType?.("paint");t&&t.forEach(({name:t,startTime:r})=>{w_(Z_,t)&&e.addEvent(Z_[t],r)})})(e),this._addCustomAttributesOnSpan(e,this.getConfig().applyCustomAttributesOnSpan?.documentLoad),this._endSpan(e,f_.LOAD_EVENT_END,t))})}_endSpan(e,t,r){e&&(w_(r,t)?e.end(r[t]):e.end())}_initResourceSpan(e,t){const r=this._startSpan(V_.RESOURCE_FETCH,f_.FETCH_START,e,t);r&&(r.setAttribute(Lv,e.name),b_(r,e,this.getConfig().ignoreNetworkEvents),this._addCustomAttributesOnResourceSpan(r,e,this.getConfig().applyCustomAttributesOnSpan?.resourceFetch),this._endSpan(r,f_.RESPONSE_END,e))}_startSpan(e,t,r,n){if(w_(r,t)&&"number"==typeof r[t]){return this.tracer.startSpan(e,{startTime:r[t]},n?Cv.setSpan(ov.active(),n):void 0)}}_waitForPageLoad(){"complete"===window.document.readyState?this._onDocumentLoaded():(this._onDocumentLoaded=this._onDocumentLoaded.bind(this),window.addEventListener("load",this._onDocumentLoaded))}_addCustomAttributesOnSpan(e,t){t&&B_(()=>t(e),e=>{e&&this._diag.error("addCustomAttributesOnSpan",e)})}_addCustomAttributesOnResourceSpan(e,t,r){r&&B_(()=>r(e,t),e=>{e&&this._diag.error("addCustomAttributesOnResourceSpan",e)})}enable(){window.removeEventListener("load",this._onDocumentLoaded),this._waitForPageLoad()}disable(){window.removeEventListener("load",this._onDocumentLoaded)}}const W_="OT_ZONE_CONTEXT";class Y_{_enabled=!1;_bindFunction(e,t){const r=this,n=function(...n){return r.with(e,()=>t.apply(this,n))};return Object.defineProperty(n,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),n}_bindListener(e,t){const r=t;return void 0!==r.__ot_listeners||(r.__ot_listeners={},"function"==typeof r.addEventListener&&(r.addEventListener=this._patchAddEventListener(r,r.addEventListener,e)),"function"==typeof r.removeEventListener&&(r.removeEventListener=this._patchRemoveEventListener(r,r.removeEventListener))),t}_createZone(e,t){return Zone.current.fork({name:e,properties:{[W_]:t}})}_patchAddEventListener(e,t,r){const n=this;return function(s,i,o){void 0===e.__ot_listeners&&(e.__ot_listeners={});let a=e.__ot_listeners[s];void 0===a&&(a=new WeakMap,e.__ot_listeners[s]=a);const l=n.bind(r,i);return a.set(i,l),t.call(this,s,l,o)}}_patchRemoveEventListener(e,t){return function(r,n){if(void 0===e.__ot_listeners||void 0===e.__ot_listeners[r])return t.call(this,r,n);const s=e.__ot_listeners[r],i=s.get(n);return s.delete(n),t.call(this,r,i||n)}}active(){return this._enabled&&Zone.current&&Zone.current.get(W_)||gw}bind(e,t){return"function"==typeof t?this._bindFunction(e,t):("object"==typeof(r=t)&&null!==r&&"addEventListener"in r&&"function"==typeof r.addEventListener&&"removeEventListener"in r&&"function"==typeof r.removeEventListener&&this._bindListener(e,t),t);var r}disable(){return this._enabled=!1,this}enable(){return this._enabled=!0,this}with(e,t,r,...n){let s="otel:with";return t.name&&(s+=`:${t.name}`),this._createZone(s,e).run(t,r,n)}} +var Monoscope=function(){"use strict";var e,t=Object.defineProperty,r=(e,r,n)=>((e,r,n)=>r in e?t(e,r,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[r]=n)(e,"symbol"!=typeof r?r+"":r,n),n=Object.defineProperty,s=(e,t,r)=>((e,t,r)=>t in e?n(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r),i=Object.defineProperty,o=(e,t,r)=>((e,t,r)=>t in e?i(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);const a={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},l={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},c={};function u(e){if(c[e])return c[e];const t=globalThis[e],r=t.prototype,n=e in a?a[e]:void 0,s=Boolean(n&&n.every(e=>{var t,n;return Boolean(null==(n=null==(t=Object.getOwnPropertyDescriptor(r,e))?void 0:t.get)?void 0:n.toString().includes("[native code]"))})),i=e in l?l[e]:void 0,o=Boolean(i&&i.every(e=>{var t;return"function"==typeof r[e]&&(null==(t=r[e])?void 0:t.toString().includes("[native code]"))}));if(s&&o&&!globalThis.Zone)return c[e]=t.prototype,t.prototype;try{const n=document.createElement("iframe");document.body.appendChild(n);const s=n.contentWindow;if(!s)return t.prototype;const i=s[e].prototype;return document.body.removeChild(n),i?c[e]=i:r}catch{return r}}const h={};function p(e,t,r){var n;const s=`${e}.${String(r)}`;if(h[s])return h[s].call(t);const i=u(e),o=null==(n=Object.getOwnPropertyDescriptor(i,r))?void 0:n.get;return o?(h[s]=o,o.call(t)):t[r]}const d={};function f(e,t,r){const n=`${e}.${String(r)}`;if(d[n])return d[n].bind(t);const s=u(e)[r];return"function"!=typeof s?t[r]:(d[n]=s,s.bind(t))}const m={childNodes:function(e){return p("Node",e,"childNodes")},parentNode:function(e){return p("Node",e,"parentNode")},parentElement:function(e){return p("Node",e,"parentElement")},textContent:function(e){return p("Node",e,"textContent")},contains:function(e,t){return f("Node",e,"contains")(t)},getRootNode:function(e){return f("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?p("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?p("Element",e,"shadowRoot"):null},querySelector:function(e,t){return p("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return p("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return u("MutationObserver").constructor}};let g=class{constructor(){o(this,"idNodeMap",new Map),o(this,"nodeMetaMap",new WeakMap)}getId(e){var t;if(!e)return-1;return(null==(t=this.getMeta(e))?void 0:t.id)??-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){const t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(e=>this.removeNodeFromMap(e))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){const r=t.id;this.idNodeMap.set(r,e),this.nodeMetaMap.set(e,t)}replace(e,t){const r=this.getNode(e);if(r){const e=this.nodeMetaMap.get(r);e&&this.nodeMetaMap.set(t,e)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}};function y(e,t,r){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return!!r&&y(m.parentNode(e),t,r);for(let r=e.classList.length;r--;){const n=e.classList[r];if(t.test(n))return!0}return!!r&&y(m.parentNode(e),t,r)}function w(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function v(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var b={exports:{}},_=String,S=function(){return{isColorSupported:!1,reset:_,bold:_,dim:_,italic:_,underline:_,inverse:_,hidden:_,strikethrough:_,black:_,red:_,green:_,yellow:_,blue:_,magenta:_,cyan:_,white:_,gray:_,bgBlack:_,bgRed:_,bgGreen:_,bgYellow:_,bgBlue:_,bgMagenta:_,bgCyan:_,bgWhite:_}};b.exports=S(),b.exports.createColors=S;var C=b.exports;const E=v(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let T=C,k=E,x=class e extends Error{constructor(t,r,n,s,i,o){super(t),this.name="CssSyntaxError",this.reason=t,i&&(this.file=i),s&&(this.source=s),o&&(this.plugin=o),void 0!==r&&void 0!==n&&("number"==typeof r?(this.line=r,this.column=n):(this.line=r.line,this.column=r.column,this.endLine=n.line,this.endColumn=n.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;null==e&&(e=T.isColorSupported),k&&e&&(t=k(t));let r,n,s=t.split(/\r?\n/),i=Math.max(this.line-3,0),o=Math.min(this.line+2,s.length),a=String(o).length;if(e){let{bold:e,gray:t,red:s}=T.createColors(!0);r=t=>e(s(t)),n=e=>t(e)}else r=n=e=>e;return s.slice(i,o).map((e,t)=>{let s=i+1+t,o=" "+(" "+s).slice(-a)+" | ";if(s===this.line){let t=n(o.replace(/\d/g," "))+e.slice(0,this.column-1).replace(/[^\t]/g," ");return r(">")+n(o)+e+"\n "+t+r("^")}return" "+n(o)+e}).join("\n")}toString(){let e=this.showSourceCode();return e&&(e="\n\n"+e+"\n"),this.name+": "+this.message+e}};var O=x;x.default=x;var A={};A.isClean=Symbol("isClean"),A.my=Symbol("my");const I={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let R=class{constructor(e){this.builder=e}atrule(e,t){let r="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(void 0!==e.raws.afterName?r+=e.raws.afterName:n&&(r+=" "),e.nodes)this.block(e,r+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(r+n+s,e)}}beforeAfter(e,t){let r;r="decl"===e.type?this.raw(e,null,"beforeDecl"):"comment"===e.type?this.raw(e,null,"beforeComment"):"before"===t?this.raw(e,null,"beforeRule"):this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&"root"!==n.type;)s+=1,n=n.parent;if(r.includes("\n")){let t=this.raw(e,null,"indent");if(t.length)for(let e=0;e0&&"comment"===e.nodes[t].type;)t-=1;let r=this.raw(e,"semicolon");for(let n=0;n{if(n=e.raws[t],void 0!==n)return!1})}var o;return void 0===n&&(n=I[r]),i.rawCache[r]=n,n}rawBeforeClose(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length>0&&void 0!==e.raws.after)return t=e.raws.after,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let r;return e.walkComments(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeDecl"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeDecl(e,t){let r;return e.walkDecls(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeRule"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeOpen(e){let t;return e.walk(e=>{if("decl"!==e.type&&(t=e.raws.between,void 0!==t))return!1}),t}rawBeforeRule(e){let t;return e.walk(r=>{if(r.nodes&&(r.parent!==e||e.first!==r)&&void 0!==r.raws.before)return t=r.raws.before,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(e=>{if(void 0!==e.raws.between)return t=e.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(e=>{if(e.nodes&&0===e.nodes.length&&(t=e.raws.after,void 0!==t))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(r=>{let n=r.parent;if(n&&n!==e&&n.parent&&n.parent===e&&void 0!==r.raws.before){let e=r.raws.before.split("\n");return t=e[e.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length&&"decl"===e.last.type&&(t=e.raws.semicolon,void 0!==t))return!1}),t}rawValue(e,t){let r=e[t],n=e.raws[t];return n&&n.value===r?n.raw:r}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};var M=R;R.default=R;let N=M;function P(e,t){new N(t).stringify(e)}var L=P;P.default=P;let{isClean:D,my:U}=A,F=O,B=M,j=L;function z(e,t){let r=new e.constructor;for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;if("proxyCache"===n)continue;let s=e[n],i=typeof s;"parent"===n&&"object"===i?t&&(r[n]=t):"source"===n?r[n]=s:Array.isArray(s)?r[n]=s.map(e=>z(e,r)):("object"===i&&null!==s&&(s=z(s)),r[n]=s)}return r}let V=class{constructor(e={}){this.raws={},this[D]=!1,this[U]=!0;for(let t in e)if("nodes"===t){this.nodes=[];for(let r of e[t])"function"==typeof r.clone?this.append(r.clone()):this.append(r)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=z(this);for(let r in e)t[r]=e[r];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:r,start:n}=this.rangeBy(t);return this.source.input.error(e,{column:n.column,line:n.line},{column:r.column,line:r.line},t)}return new F(e)}getProxyProcessor(){return{get:(e,t)=>"proxyOf"===t?e:"root"===t?()=>e.root().toProxy():e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"prop"!==t&&"value"!==t&&"name"!==t&&"params"!==t&&"important"!==t&&"text"!==t||e.markDirty()),!0)}}markDirty(){if(this[D]){this[D]=!1;let e=this;for(;e=e.parent;)e[D]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){let n=(t=this.toString()).indexOf(e.word);-1!==n&&(r=this.positionInside(n,t))}return r}positionInside(e,t){let r=t||this.toString(),n=this.source.start.column,s=this.source.start.line;for(let t=0;t"object"==typeof e&&e.toJSON?e.toJSON(null,t):e);else if("object"==typeof n&&n.toJSON)r[e]=n.toJSON(null,t);else if("source"===e){let i=t.get(n.input);null==i&&(i=s,t.set(n.input,s),s++),r[e]={end:n.end,inputId:i,start:n.start}}else r[e]=n}return n&&(r.inputs=[...t.keys()].map(e=>e.toJSON())),r}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=j){e.stringify&&(e=e.stringify);let t="";return e(this,e=>{t+=e}),t}warn(e,t,r){let n={node:this};for(let e in r)n[e]=r[e];return e.warn(t,n)}get proxyOf(){return this}};var G=V;V.default=V;let H=G,Z=class extends H{constructor(e){e&&void 0!==e.value&&"string"!=typeof e.value&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var $=Z;Z.default=Z;var W={nanoid:(e=21)=>{let t="",r=e;for(;r--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t}};let{SourceMapConsumer:Y,SourceMapGenerator:X}=E,{existsSync:J,readFileSync:K}=E,{dirname:q,join:Q}=E;let ee=class{constructor(e,t){if(!1===t.map)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let r=t.map?t.map.prev:void 0,n=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=q(this.mapFile)),n&&(this.text=n)}consumer(){return this.consumerCache||(this.consumerCache=new Y(this.text)),this.consumerCache}decodeInline(e){if(/^data:application\/json;charset=utf-?8,/.test(e)||/^data:application\/json,/.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(e)||/^data:application\/json;base64,/.test(e))return t=e.substr(RegExp.lastMatch.length),Buffer?Buffer.from(t,"base64").toString():window.atob(t);var t;let r=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+r)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return"object"==typeof e&&("string"==typeof e.mappings||"string"==typeof e._mappings||Array.isArray(e.sections))}loadAnnotation(e){let t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(!t)return;let r=e.lastIndexOf(t.pop()),n=e.indexOf("*/",r);r>-1&&n>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,n)))}loadFile(e){if(this.root=q(e),J(e))return this.mapFile=e,K(e,"utf-8").toString().trim()}loadMap(e,t){if(!1===t)return!1;if(t){if("string"==typeof t)return t;if("function"!=typeof t){if(t instanceof Y)return X.fromSourceMap(t).toString();if(t instanceof X)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}{let r=t(e);if(r){let e=this.loadFile(r);if(!e)throw new Error("Unable to load previous source map: "+r.toString());return e}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let t=this.annotation;return e&&(t=Q(q(e),t)),this.loadFile(t)}}}startWith(e,t){return!!e&&e.substr(0,t.length)===t}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var te=ee;ee.default=ee;let{SourceMapConsumer:re,SourceMapGenerator:ne}=E,{fileURLToPath:se,pathToFileURL:ie}=E,{isAbsolute:oe,resolve:ae}=E,{nanoid:le}=W,ce=E,ue=O,he=te,pe=Symbol("fromOffsetCache"),de=Boolean(re&&ne),fe=Boolean(ae&&oe),me=class{constructor(e,t={}){if(null==e||"object"==typeof e&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!fe||/^\w+:\/\//.test(t.from)||oe(t.from)?this.file=t.from:this.file=ae(t.from)),fe&&de){let e=new he(this.css,t);if(e.text){this.map=e;let t=e.consumer().file;!this.file&&t&&(this.file=this.mapResolve(t))}}this.file||(this.id=""),this.map&&(this.map.file=this.from)}error(e,t,r,n={}){let s,i,o;if(t&&"object"==typeof t){let e=t,n=r;if("number"==typeof e.offset){let n=this.fromOffset(e.offset);t=n.line,r=n.col}else t=e.line,r=e.column;if("number"==typeof n.offset){let e=this.fromOffset(n.offset);i=e.line,o=e.col}else i=n.line,o=n.column}else if(!r){let e=this.fromOffset(t);t=e.line,r=e.col}let a=this.origin(t,r,i,o);return s=a?new ue(e,void 0===a.endLine?a.line:{column:a.column,line:a.line},void 0===a.endLine?a.column:{column:a.endColumn,line:a.endLine},a.source,a.file,n.plugin):new ue(e,void 0===i?t:{column:r,line:t},void 0===i?r:{column:o,line:i},this.css,this.file,n.plugin),s.input={column:r,endColumn:o,endLine:i,line:t,source:this.css},this.file&&(ie&&(s.input.url=ie(this.file).toString()),s.input.file=this.file),s}fromOffset(e){let t,r;if(this[pe])r=this[pe];else{let e=this.css.split("\n");r=new Array(e.length);let t=0;for(let n=0,s=e.length;n=t)n=r.length-1;else{let t,s=r.length-2;for(;n>1),e=r[t+1])){n=t;break}n=t+1}}return{col:e-r[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:ae(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,r,n){if(!this.map)return!1;let s,i,o=this.map.consumer(),a=o.originalPositionFor({column:t,line:e});if(!a.source)return!1;"number"==typeof r&&(s=o.originalPositionFor({column:n,line:r})),i=oe(a.source)?ie(a.source):new URL(a.source,this.map.consumer().sourceRoot||ie(this.map.mapFile));let l={column:a.column,endColumn:s&&s.column,endLine:s&&s.line,line:a.line,url:i.toString()};if("file:"===i.protocol){if(!se)throw new Error("file: protocol is not available in this PostCSS build");l.file=se(i)}let c=o.sourceContentFor(a.source);return c&&(l.source=c),l}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])null!=this[t]&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};var ge=me;me.default=me,ce&&ce.registerInput&&ce.registerInput(me);let{SourceMapConsumer:ye,SourceMapGenerator:we}=E,{dirname:ve,relative:be,resolve:_e,sep:Se}=E,{pathToFileURL:Ce}=E,Ee=ge,Te=Boolean(ye&&we),ke=Boolean(ve&&_e&&be&&Se);var xe=class{constructor(e,t,r,n){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=n,this.originalCSS=n,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let t="\n";this.css.includes("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"}applyPrevMaps(){for(let e of this.previous()){let t,r=this.toUrl(this.path(e.file)),n=e.root||ve(e.file);!1===this.mapOpts.sourcesContent?(t=new ye(e.text),t.sourcesContent&&(t.sourcesContent=null)):t=e.consumer(),this.map.applySourceMap(t,r,this.toUrl(this.path(n)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],"comment"===e.type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),ke&&Te&&this.isMap())return this.generateMap();{let e="";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=we.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new we({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):""});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new we({file:this.outputFile(),ignoreInvalidMapping:!0});let e,t,r=1,n=1,s="",i={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(o,a,l)=>{if(this.css+=o,a&&"end"!==l&&(i.generated.line=r,i.generated.column=n-1,a.source&&a.source.start?(i.source=this.sourcePath(a),i.original.line=a.source.start.line,i.original.column=a.source.start.column-1,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,this.map.addMapping(i))),e=o.match(/\n/g),e?(r+=e.length,t=o.lastIndexOf("\n"),n=o.length-t):n+=o.length,a&&"start"!==l){let e=a.parent||{raws:{}};("decl"===a.type||"atrule"===a.type&&!a.nodes)&&a===e.last&&!e.raws.semicolon||(a.source&&a.source.end?(i.source=this.sourcePath(a),i.original.line=a.source.end.line,i.original.column=a.source.end.column-1,i.generated.line=r,i.generated.column=n-2,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,i.generated.line=r,i.generated.column=n-1,this.map.addMapping(i)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(e=>e.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(e=>e.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(e=>e.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(e){if(this.mapOpts.absolute)return e;if(60===e.charCodeAt(0))return e;if(/^\w+:\/\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let r=this.opts.to?ve(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(r=ve(_e(r,this.mapOpts.annotation)));let n=be(r,e);return this.memoizedPaths.set(e,n),n}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new Ee(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let r=t.source.input.from;if(r&&!e[r]){e[r]=!0;let n=this.usesFileUrls?this.toFileUrl(r):this.toUrl(this.path(r));this.map.setSourceContent(n,t.source.input.css)}}});else if(this.css){let e=this.opts.from?this.toUrl(this.path(this.opts.from)):"";this.map.setSourceContent(e,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(Ce){let t=Ce(e).toString();return this.memoizedFileURLs.set(e,t),t}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;"\\"===Se&&(e=e.replace(/\\/g,"/"));let r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r}};let Oe=G,Ae=class extends Oe{constructor(e){super(e),this.type="comment"}};var Ie=Ae;Ae.default=Ae;let Re,Me,Ne,Pe,{isClean:Le,my:De}=A,Ue=$,Fe=Ie,Be=G;function je(e){return e.map(e=>(e.nodes&&(e.nodes=je(e.nodes)),delete e.source,e))}function ze(e){if(e[Le]=!1,e.proxyOf.nodes)for(let t of e.proxyOf.nodes)ze(t)}let Ve=class e extends Be{append(...e){for(let t of e){let e=this.normalize(t,this.last);for(let t of e)this.proxyOf.nodes.push(t)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t,r,n=this.getIterator();for(;this.indexes[n]"proxyOf"===t?e:e[t]?"each"===t||"string"==typeof t&&t.startsWith("walk")?(...r)=>e[t](...r.map(e=>"function"==typeof e?(t,r)=>e(t.toProxy(),r):e)):"every"===t||"some"===t?r=>e[t]((e,...t)=>r(e.toProxy(),...t)):"root"===t?()=>e.root().toProxy():"nodes"===t?e.nodes.map(e=>e.toProxy()):"first"===t||"last"===t?e[t].toProxy():e[t]:e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"name"!==t&&"params"!==t&&"selector"!==t||e.markDirty()),!0)}}index(e){return"number"==typeof e?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let r,n=this.index(e),s=this.normalize(t,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(let e of s)this.proxyOf.nodes.splice(n+1,0,e);for(let e in this.indexes)r=this.indexes[e],n(t[De]||e.rebuild(t),(t=t.proxyOf).parent&&t.parent.removeChild(t),t[Le]&&ze(t),void 0===t.raws.before&&r&&void 0!==r.raws.before&&(t.raws.before=r.raws.before.replace(/\S/g,"")),t.parent=this.proxyOf,t))}prepend(...e){e=e.reverse();for(let t of e){let e=this.normalize(t,this.first,"prepend").reverse();for(let t of e)this.proxyOf.nodes.unshift(t);for(let t in this.indexes)this.indexes[t]=this.indexes[t]+e.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){let t;e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);for(let r in this.indexes)t=this.indexes[r],t>=e&&(this.indexes[r]=t-1);return this.markDirty(),this}replaceValues(e,t,r){return r||(r=t,t={}),this.walkDecls(n=>{t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,r))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,r)=>{let n;try{n=e(t,r)}catch(e){throw t.addToError(e)}return!1!==n&&t.walk&&(n=t.walk(e)),n})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("atrule"===r.type&&e.test(r.name))return t(r,n)}):this.walk((r,n)=>{if("atrule"===r.type&&r.name===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("atrule"===e.type)return t(e,r)}))}walkComments(e){return this.walk((t,r)=>{if("comment"===t.type)return e(t,r)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("decl"===r.type&&e.test(r.prop))return t(r,n)}):this.walk((r,n)=>{if("decl"===r.type&&r.prop===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("decl"===e.type)return t(e,r)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("rule"===r.type&&e.test(r.selector))return t(r,n)}):this.walk((r,n)=>{if("rule"===r.type&&r.selector===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("rule"===e.type)return t(e,r)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Ve.registerParse=e=>{Re=e},Ve.registerRule=e=>{Me=e},Ve.registerAtRule=e=>{Ne=e},Ve.registerRoot=e=>{Pe=e};var Ge=Ve;Ve.default=Ve,Ve.rebuild=e=>{"atrule"===e.type?Object.setPrototypeOf(e,Ne.prototype):"rule"===e.type?Object.setPrototypeOf(e,Me.prototype):"decl"===e.type?Object.setPrototypeOf(e,Ue.prototype):"comment"===e.type?Object.setPrototypeOf(e,Fe.prototype):"root"===e.type&&Object.setPrototypeOf(e,Pe.prototype),e[De]=!0,e.nodes&&e.nodes.forEach(e=>{Ve.rebuild(e)})};let He,Ze,$e=Ge,We=class extends $e{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new He(new Ze,this,e).stringify()}};We.registerLazyResult=e=>{He=e},We.registerProcessor=e=>{Ze=e};var Ye=We;We.default=We;let Xe={};var Je=function(e){Xe[e]||(Xe[e]=!0,"undefined"!=typeof console&&console.warn&&console.warn(e))};let Ke=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let e=t.node.rangeBy(t);this.line=e.start.line,this.column=e.start.column,this.endLine=e.end.line,this.endColumn=e.end.column}for(let e in t)this[e]=t[e]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var qe=Ke;Ke.default=Ke;let Qe=qe,et=class{constructor(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let r=new Qe(e,t);return this.messages.push(r),r}warnings(){return this.messages.filter(e=>"warning"===e.type)}get content(){return this.css}};var tt=et;et.default=et;const rt="'".charCodeAt(0),nt='"'.charCodeAt(0),st="\\".charCodeAt(0),it="/".charCodeAt(0),ot="\n".charCodeAt(0),at=" ".charCodeAt(0),lt="\f".charCodeAt(0),ct="\t".charCodeAt(0),ut="\r".charCodeAt(0),ht="[".charCodeAt(0),pt="]".charCodeAt(0),dt="(".charCodeAt(0),ft=")".charCodeAt(0),mt="{".charCodeAt(0),gt="}".charCodeAt(0),yt=";".charCodeAt(0),wt="*".charCodeAt(0),vt=":".charCodeAt(0),bt="@".charCodeAt(0),_t=/[\t\n\f\r "#'()/;[\\\]{}]/g,St=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Ct=/.[\r\n"'(/\\]/,Et=/[\da-f]/i;let Tt=Ge,kt=class extends Tt{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};var xt=kt;kt.default=kt,Tt.registerAtRule(kt);let Ot,At,It=Ge,Rt=class extends It{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,r){let n=super.normalize(e);if(t)if("prepend"===r)this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let e of n)e.raws.before=t.raws.before;return n}removeChild(e,t){let r=this.index(e);return!t&&0===r&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[r].raws.before),super.removeChild(e)}toResult(e={}){return new Ot(new At,this,e).stringify()}};Rt.registerLazyResult=e=>{Ot=e},Rt.registerProcessor=e=>{At=e};var Mt=Rt;Rt.default=Rt,It.registerRoot(Rt);let Nt={comma:e=>Nt.split(e,[","],!0),space:e=>Nt.split(e,[" ","\n","\t"]),split(e,t,r){let n=[],s="",i=!1,o=0,a=!1,l="",c=!1;for(let r of e)c?c=!1:"\\"===r?c=!0:a?r===l&&(a=!1):'"'===r||"'"===r?(a=!0,l=r):"("===r?o+=1:")"===r?o>0&&(o-=1):0===o&&t.includes(r)&&(i=!0),i?(""!==s&&n.push(s.trim()),s="",i=!1):s+=r;return(r||""!==s)&&n.push(s.trim()),n}};var Pt=Nt;Nt.default=Nt;let Lt=Ge,Dt=Pt,Ut=class extends Lt{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Dt.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,r=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(r)}};var Ft=Ut;Ut.default=Ut,Lt.registerRule(Ut);let Bt=$,jt=function(e,t={}){let r,n,s,i,o,a,l,c,u,h,p=e.css.valueOf(),d=t.ignoreErrors,f=p.length,m=0,g=[],y=[];function w(t){throw e.error("Unclosed "+t,m)}return{back:function(e){y.push(e)},endOfFile:function(){return 0===y.length&&m>=f},nextToken:function(e){if(y.length)return y.pop();if(m>=f)return;let t=!!e&&e.ignoreUnclosed;switch(r=p.charCodeAt(m),r){case ot:case at:case ct:case ut:case lt:n=m;do{n+=1,r=p.charCodeAt(n)}while(r===at||r===ot||r===ct||r===ut||r===lt);h=["space",p.slice(m,n)],m=n-1;break;case ht:case pt:case mt:case gt:case vt:case yt:case ft:{let e=String.fromCharCode(r);h=[e,e,m];break}case dt:if(c=g.length?g.pop()[1]:"",u=p.charCodeAt(m+1),"url"===c&&u!==rt&&u!==nt&&u!==at&&u!==ot&&u!==ct&&u!==lt&&u!==ut){n=m;do{if(a=!1,n=p.indexOf(")",n+1),-1===n){if(d||t){n=m;break}w("bracket")}for(l=n;p.charCodeAt(l-1)===st;)l-=1,a=!a}while(a);h=["brackets",p.slice(m,n+1),m,n],m=n}else n=p.indexOf(")",m+1),i=p.slice(m,n+1),-1===n||Ct.test(i)?h=["(","(",m]:(h=["brackets",i,m,n],m=n);break;case rt:case nt:s=r===rt?"'":'"',n=m;do{if(a=!1,n=p.indexOf(s,n+1),-1===n){if(d||t){n=m+1;break}w("string")}for(l=n;p.charCodeAt(l-1)===st;)l-=1,a=!a}while(a);h=["string",p.slice(m,n+1),m,n],m=n;break;case bt:_t.lastIndex=m+1,_t.test(p),n=0===_t.lastIndex?p.length-1:_t.lastIndex-2,h=["at-word",p.slice(m,n+1),m,n],m=n;break;case st:for(n=m,o=!0;p.charCodeAt(n+1)===st;)n+=1,o=!o;if(r=p.charCodeAt(n+1),o&&r!==it&&r!==at&&r!==ot&&r!==ct&&r!==ut&&r!==lt&&(n+=1,Et.test(p.charAt(n)))){for(;Et.test(p.charAt(n+1));)n+=1;p.charCodeAt(n+1)===at&&(n+=1)}h=["word",p.slice(m,n+1),m,n],m=n;break;default:r===it&&p.charCodeAt(m+1)===wt?(n=p.indexOf("*/",m+2)+1,0===n&&(d||t?n=p.length:w("comment")),h=["comment",p.slice(m,n+1),m,n],m=n):(St.lastIndex=m+1,St.test(p),n=0===St.lastIndex?p.length-1:St.lastIndex-2,h=["word",p.slice(m,n+1),m,n],g.push(h),m=n)}return m++,h},position:function(){return m}}},zt=Ie,Vt=xt,Gt=Mt,Ht=Ft;const Zt={empty:!0,space:!0};var $t=class{constructor(e){this.input=e,this.root=new Gt,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t,r,n,s=new Vt;s.name=e[1].slice(1),""===s.name&&this.unnamedAtrule(s,e),this.init(s,e[2]);let i=!1,o=!1,a=[],l=[];for(;!this.tokenizer.endOfFile();){if(t=(e=this.tokenizer.nextToken())[0],"("===t||"["===t?l.push("("===t?")":"]"):"{"===t&&l.length>0?l.push("}"):t===l[l.length-1]&&l.pop(),0===l.length){if(";"===t){s.source.end=this.getPosition(e[2]),s.source.end.offset++,this.semicolon=!0;break}if("{"===t){o=!0;break}if("}"===t){if(a.length>0){for(n=a.length-1,r=a[n];r&&"space"===r[0];)r=a[--n];r&&(s.source.end=this.getPosition(r[3]||r[2]),s.source.end.offset++)}this.end(e);break}a.push(e)}else a.push(e);if(this.tokenizer.endOfFile()){i=!0;break}}s.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(s.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(s,"params",a),i&&(e=a[a.length-1],s.source.end=this.getPosition(e[3]||e[2]),s.source.end.offset++,this.spaces=s.raws.between,s.raws.between="")):(s.raws.afterName="",s.params=""),o&&(s.nodes=[],this.current=s)}checkMissedSemicolon(e){let t=this.colon(e);if(!1===t)return;let r,n=0;for(let s=t-1;s>=0&&(r=e[s],"space"===r[0]||(n+=1,2!==n));s--);throw this.input.error("Missed semicolon","word"===r[0]?r[3]+1:r[2])}colon(e){let t,r,n,s=0;for(let[i,o]of e.entries()){if(t=o,r=t[0],"("===r&&(s+=1),")"===r&&(s-=1),0===s&&":"===r){if(n){if("word"===n[0]&&"progid"===n[1])continue;return i}this.doubleColon(t)}n=t}return!1}comment(e){let t=new zt;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let r=e[1].slice(2,-2);if(/^\s*$/.test(r))t.text="",t.raws.left=r,t.raws.right="";else{let e=r.match(/^(\s*)([^]*\S)(\s*)$/);t.text=e[2],t.raws.left=e[1],t.raws.right=e[3]}}createTokenizer(){this.tokenizer=jt(this.input)}decl(e,t){let r=new Bt;this.init(r,e[0][2]);let n,s=e[e.length-1];for(";"===s[0]&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(s[3]||s[2]||function(e){for(let t=e.length-1;t>=0;t--){let r=e[t],n=r[3]||r[2];if(n)return n}}(e)),r.source.end.offset++;"word"!==e[0][0];)1===e.length&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop="";e.length;){let t=e[0][0];if(":"===t||"space"===t||"comment"===t)break;r.prop+=e.shift()[1]}for(r.raws.between="";e.length;){if(n=e.shift(),":"===n[0]){r.raws.between+=n[1];break}"word"===n[0]&&/\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1]}"_"!==r.prop[0]&&"*"!==r.prop[0]||(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));let i,o=[];for(;e.length&&(i=e[0][0],"space"===i||"comment"===i);)o.push(e.shift());this.precheckMissedSemicolon(e);for(let t=e.length-1;t>=0;t--){if(n=e[t],"!important"===n[1].toLowerCase()){r.important=!0;let n=this.stringFrom(e,t);n=this.spacesFromEnd(e)+n," !important"!==n&&(r.raws.important=n);break}if("important"===n[1].toLowerCase()){let n=e.slice(0),s="";for(let e=t;e>0;e--){let t=n[e][0];if(0===s.trim().indexOf("!")&&"space"!==t)break;s=n.pop()[1]+s}0===s.trim().indexOf("!")&&(r.important=!0,r.raws.important=s,e=n)}if("space"!==n[0]&&"comment"!==n[0])break}e.some(e=>"space"!==e[0]&&"comment"!==e[0])&&(r.raws.between+=o.map(e=>e[1]).join(""),o=[]),this.raw(r,"value",o.concat(e),t),r.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new Ht;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let e=this.current.nodes[this.current.nodes.length-1];e&&"rule"===e.type&&!e.raws.ownSemicolon&&(e.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="","comment"!==e.type&&(this.semicolon=!1)}other(e){let t=!1,r=null,n=!1,s=null,i=[],o=e[1].startsWith("--"),a=[],l=e;for(;l;){if(r=l[0],a.push(l),"("===r||"["===r)s||(s=l),i.push("("===r?")":"]");else if(o&&n&&"{"===r)s||(s=l),i.push("}");else if(0===i.length){if(";"===r){if(n)return void this.decl(a,o);break}if("{"===r)return void this.rule(a);if("}"===r){this.tokenizer.back(a.pop()),t=!0;break}":"===r&&(n=!0)}else r===i[i.length-1]&&(i.pop(),0===i.length&&(s=null));l=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),i.length>0&&this.unclosedBracket(s),t&&n){if(!o)for(;a.length&&(l=a[a.length-1][0],"space"===l||"comment"===l);)this.tokenizer.back(a.pop());this.decl(a,o)}else this.unknownWord(a)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e)}this.endFile()}precheckMissedSemicolon(){}raw(e,t,r,n){let s,i,o,a,l=r.length,c="",u=!0;for(let e=0;ee+t[1],"");e.raws[t]={raw:n,value:c}}e[t]=c}rule(e){e.pop();let t=new Ht;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t||"comment"===t);)r=e.pop()[1]+r;return r}spacesAndCommentsFromStart(e){let t,r="";for(;e.length&&(t=e[0][0],"space"===t||"comment"===t);)r+=e.shift()[1];return r}spacesFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t);)r=e.pop()[1]+r;return r}stringFrom(e,t){let r="";for(let n=t;nfr(e)),e}let mr={},gr=class e{constructor(t,r,n){let s;if(this.stringified=!1,this.processed=!1,"object"!=typeof r||null===r||"root"!==r.type&&"document"!==r.type)if(r instanceof e||r instanceof ir)s=fr(r.root),r.map&&(void 0===n.map&&(n.map={}),n.map.inline||(n.map.inline=!1),n.map.prev=r.map);else{let e=or;n.syntax&&(e=n.syntax.parse),n.parser&&(e=n.parser),e.parse&&(e=e.parse);try{s=e(r,n)}catch(e){this.processed=!0,this.error=e}s&&!s[Qt]&&rr.rebuild(s)}else s=fr(r);this.result=new ir(t,s,n),this.helpers={...mr,postcss:mr,result:this.result},this.plugins=this.processor.plugins.map(e=>"object"==typeof e&&e.prepare?{...e,...e.prepare(this.result)}:e)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let r=this.result.lastPlugin;try{if(t&&t.addToError(e),this.error=e,"CssSyntaxError"!==e.name||e.plugin){if(r.postcssVersion&&"production"!==process.env.NODE_ENV){let e=r.postcssPlugin,t=r.postcssVersion,n=this.result.processor.version,s=t.split("."),i=n.split(".");(s[0]!==i[0]||parseInt(s[1])>parseInt(i[1]))&&console.error("Unknown error from PostCSS plugin. Your current PostCSS version is "+n+", but "+e+" uses "+t+". Perhaps this is the source of the error below.")}}else e.plugin=r.postcssPlugin,e.setMessage()}catch(e){console&&console.error&&console.error(e)}return e}prepareVisitors(){this.listeners={};let e=(e,t,r)=>{this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push([e,r])};for(let t of this.plugins)if("object"==typeof t)for(let r in t){if(!cr[r]&&/^[A-Z]/.test(r))throw new Error(`Unknown event ${r} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!ur[r])if("object"==typeof t[r])for(let n in t[r])e(t,"*"===n?r:r+"-"+n.toLowerCase(),t[r][n]);else"function"==typeof t[r]&&e(t,r,t[r])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e0;){let e=this.visitTick(t);if(hr(e))try{await e}catch(e){let r=t[t.length-1].node;throw this.handleError(e,r)}}}if(this.listeners.OnceExit)for(let[t,r]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if("document"===e.type){let t=e.nodes.map(e=>r(e,this.helpers));await Promise.all(t)}else await r(e,this.helpers)}catch(e){throw this.handleError(e)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if("object"==typeof e&&e.Once){if("document"===this.result.root.type){let t=this.result.root.nodes.map(t=>e.Once(t,this.helpers));return hr(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}if("function"==typeof e)return e(this.result.root,this.result)}catch(e){throw this.handleError(e)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=tr;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new er(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){if(hr(this.runOnRoot(e)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[qt];)e[qt]=!0,this.walkSync(e);if(this.listeners.OnceExit)if("document"===e.type)for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this.opts||sr("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[r,n]of e){let e;this.result.lastPlugin=r;try{e=n(t,this.helpers)}catch(e){throw this.handleError(e,t.proxyOf)}if("root"!==t.type&&"document"!==t.type&&!t.parent)return!0;if(hr(e))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:r,visitors:n}=t;if("root"!==r.type&&"document"!==r.type&&!r.parent)return void e.pop();if(n.length>0&&t.visitorIndex{e[qt]||this.walkSync(e)});else{let t=this.listeners[r];if(t&&this.visitSync(t,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};gr.registerPostcss=e=>{mr=e};var yr=gr;gr.default=gr,ar.registerLazyResult(gr),nr.registerLazyResult(gr);let wr=xe,vr=L,br=Je,_r=Kt;const Sr=tt;let Cr=class{constructor(e,t,r){let n;t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;let s=vr;this.result=new Sr(this._processor,n,this._opts),this.result.css=t;let i=this;Object.defineProperty(this.result,"root",{get:()=>i.root});let o=new wr(s,n,this._opts,t);if(o.isMap()){let[e,t]=o.generate();e&&(this.result.css=e),t&&(this.result.map=t)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this._opts||br("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=_r;try{e=t(this._css,this._opts)}catch(e){this.error=e}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}};var Er=Cr;Cr.default=Cr;let Tr=Er,kr=yr,xr=Ye,Or=Mt,Ar=class{constructor(e=[]){this.version="8.4.38",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let r of e)if(!0===r.postcss?r=r():r.postcss&&(r=r.postcss),"object"==typeof r&&Array.isArray(r.plugins))t=t.concat(r.plugins);else if("object"==typeof r&&r.postcssPlugin)t.push(r);else if("function"==typeof r)t.push(r);else{if("object"!=typeof r||!r.parse&&!r.stringify)throw new Error(r+" is not a PostCSS plugin");if("production"!==process.env.NODE_ENV)throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.")}return t}process(e,t={}){return this.plugins.length||t.parser||t.stringifier||t.syntax?new kr(this,e,t):new Tr(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};var Ir=Ar;Ar.default=Ar,Or.registerProcessor(Ar),xr.registerProcessor(Ar);let Rr=$,Mr=te,Nr=Ie,Pr=xt,Lr=ge,Dr=Mt,Ur=Ft;function Fr(e,t){if(Array.isArray(e))return e.map(e=>Fr(e));let{inputs:r,...n}=e;if(r){t=[];for(let e of r){let r={...e,__proto__:Lr.prototype};r.map&&(r.map={...r.map,__proto__:Mr.prototype}),t.push(r)}}if(n.nodes&&(n.nodes=e.nodes.map(e=>Fr(e,t))),n.source){let{inputId:e,...r}=n.source;n.source=r,null!=e&&(n.source.input=t[e])}if("root"===n.type)return new Dr(n);if("decl"===n.type)return new Rr(n);if("rule"===n.type)return new Ur(n);if("comment"===n.type)return new Nr(n);if("atrule"===n.type)return new Pr(n);throw new Error("Unknown node type: "+e.type)}var Br=Fr;Fr.default=Fr;let jr=O,zr=$,Vr=yr,Gr=Ge,Hr=Ir,Zr=L,$r=Br,Wr=Ye,Yr=qe,Xr=Ie,Jr=xt,Kr=tt,qr=ge,Qr=Kt,en=Pt,tn=Ft,rn=Mt,nn=G;function sn(...e){return 1===e.length&&Array.isArray(e[0])&&(e=e[0]),new Hr(e)}sn.plugin=function(e,t){let r,n=!1;function s(...r){console&&console.warn&&!n&&(n=!0,console.warn(e+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226"));let s=t(...r);return s.postcssPlugin=e,s.postcssVersion=(new Hr).version,s}return Object.defineProperty(s,"postcss",{get:()=>(r||(r=s()),r)}),s.process=function(e,t,r){return sn([s(r)]).process(e,t)},s},sn.stringify=Zr,sn.parse=Qr,sn.fromJSON=$r,sn.list=en,sn.comment=e=>new Xr(e),sn.atRule=e=>new Jr(e),sn.decl=e=>new zr(e),sn.rule=e=>new tn(e),sn.root=e=>new rn(e),sn.document=e=>new Wr(e),sn.CssSyntaxError=jr,sn.Declaration=zr,sn.Container=Gr,sn.Processor=Hr,sn.Document=Wr,sn.Comment=Xr,sn.Warning=Yr,sn.AtRule=Jr,sn.Result=Kr,sn.Input=qr,sn.Rule=tn,sn.Root=rn,sn.Node=nn,Vr.registerPostcss(sn);var on=sn;sn.default=sn;const an=w(on);an.stringify,an.fromJSON,an.plugin,an.parse,an.list,an.document,an.comment,an.atRule,an.rule,an.decl,an.root,an.CssSyntaxError,an.Declaration,an.Container,an.Processor,an.Document,an.Comment,an.Warning,an.AtRule,an.Result,an.Input,an.Rule,an.Root,an.Node;var ln=Object.defineProperty,cn=(e,t,r)=>((e,t,r)=>t in e?ln(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);function un(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function hn(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var pn={exports:{}},dn=String,fn=function(){return{isColorSupported:!1,reset:dn,bold:dn,dim:dn,italic:dn,underline:dn,inverse:dn,hidden:dn,strikethrough:dn,black:dn,red:dn,green:dn,yellow:dn,blue:dn,magenta:dn,cyan:dn,white:dn,gray:dn,bgBlack:dn,bgRed:dn,bgGreen:dn,bgYellow:dn,bgBlue:dn,bgMagenta:dn,bgCyan:dn,bgWhite:dn}};pn.exports=fn(),pn.exports.createColors=fn;var mn=pn.exports;const gn=hn(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let yn=mn,wn=gn,vn=class e extends Error{constructor(t,r,n,s,i,o){super(t),this.name="CssSyntaxError",this.reason=t,i&&(this.file=i),s&&(this.source=s),o&&(this.plugin=o),void 0!==r&&void 0!==n&&("number"==typeof r?(this.line=r,this.column=n):(this.line=r.line,this.column=r.column,this.endLine=n.line,this.endColumn=n.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;null==e&&(e=yn.isColorSupported),wn&&e&&(t=wn(t));let r,n,s=t.split(/\r?\n/),i=Math.max(this.line-3,0),o=Math.min(this.line+2,s.length),a=String(o).length;if(e){let{bold:e,gray:t,red:s}=yn.createColors(!0);r=t=>e(s(t)),n=e=>t(e)}else r=n=e=>e;return s.slice(i,o).map((e,t)=>{let s=i+1+t,o=" "+(" "+s).slice(-a)+" | ";if(s===this.line){let t=n(o.replace(/\d/g," "))+e.slice(0,this.column-1).replace(/[^\t]/g," ");return r(">")+n(o)+e+"\n "+t+r("^")}return" "+n(o)+e}).join("\n")}toString(){let e=this.showSourceCode();return e&&(e="\n\n"+e+"\n"),this.name+": "+this.message+e}};var bn=vn;vn.default=vn;var _n={};_n.isClean=Symbol("isClean"),_n.my=Symbol("my");const Sn={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let Cn=class{constructor(e){this.builder=e}atrule(e,t){let r="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(void 0!==e.raws.afterName?r+=e.raws.afterName:n&&(r+=" "),e.nodes)this.block(e,r+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(r+n+s,e)}}beforeAfter(e,t){let r;r="decl"===e.type?this.raw(e,null,"beforeDecl"):"comment"===e.type?this.raw(e,null,"beforeComment"):"before"===t?this.raw(e,null,"beforeRule"):this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&"root"!==n.type;)s+=1,n=n.parent;if(r.includes("\n")){let t=this.raw(e,null,"indent");if(t.length)for(let e=0;e0&&"comment"===e.nodes[t].type;)t-=1;let r=this.raw(e,"semicolon");for(let n=0;n{if(n=e.raws[t],void 0!==n)return!1})}var o;return void 0===n&&(n=Sn[r]),i.rawCache[r]=n,n}rawBeforeClose(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length>0&&void 0!==e.raws.after)return t=e.raws.after,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let r;return e.walkComments(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeDecl"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeDecl(e,t){let r;return e.walkDecls(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeRule"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeOpen(e){let t;return e.walk(e=>{if("decl"!==e.type&&(t=e.raws.between,void 0!==t))return!1}),t}rawBeforeRule(e){let t;return e.walk(r=>{if(r.nodes&&(r.parent!==e||e.first!==r)&&void 0!==r.raws.before)return t=r.raws.before,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(e=>{if(void 0!==e.raws.between)return t=e.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(e=>{if(e.nodes&&0===e.nodes.length&&(t=e.raws.after,void 0!==t))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(r=>{let n=r.parent;if(n&&n!==e&&n.parent&&n.parent===e&&void 0!==r.raws.before){let e=r.raws.before.split("\n");return t=e[e.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length&&"decl"===e.last.type&&(t=e.raws.semicolon,void 0!==t))return!1}),t}rawValue(e,t){let r=e[t],n=e.raws[t];return n&&n.value===r?n.raw:r}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};var En=Cn;Cn.default=Cn;let Tn=En;function kn(e,t){new Tn(t).stringify(e)}var xn=kn;kn.default=kn;let{isClean:On,my:An}=_n,In=bn,Rn=En,Mn=xn;function Nn(e,t){let r=new e.constructor;for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;if("proxyCache"===n)continue;let s=e[n],i=typeof s;"parent"===n&&"object"===i?t&&(r[n]=t):"source"===n?r[n]=s:Array.isArray(s)?r[n]=s.map(e=>Nn(e,r)):("object"===i&&null!==s&&(s=Nn(s)),r[n]=s)}return r}let Pn=class{constructor(e={}){this.raws={},this[On]=!1,this[An]=!0;for(let t in e)if("nodes"===t){this.nodes=[];for(let r of e[t])"function"==typeof r.clone?this.append(r.clone()):this.append(r)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=Nn(this);for(let r in e)t[r]=e[r];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:r,start:n}=this.rangeBy(t);return this.source.input.error(e,{column:n.column,line:n.line},{column:r.column,line:r.line},t)}return new In(e)}getProxyProcessor(){return{get:(e,t)=>"proxyOf"===t?e:"root"===t?()=>e.root().toProxy():e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"prop"!==t&&"value"!==t&&"name"!==t&&"params"!==t&&"important"!==t&&"text"!==t||e.markDirty()),!0)}}markDirty(){if(this[On]){this[On]=!1;let e=this;for(;e=e.parent;)e[On]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){let n=(t=this.toString()).indexOf(e.word);-1!==n&&(r=this.positionInside(n,t))}return r}positionInside(e,t){let r=t||this.toString(),n=this.source.start.column,s=this.source.start.line;for(let t=0;t"object"==typeof e&&e.toJSON?e.toJSON(null,t):e);else if("object"==typeof n&&n.toJSON)r[e]=n.toJSON(null,t);else if("source"===e){let i=t.get(n.input);null==i&&(i=s,t.set(n.input,s),s++),r[e]={end:n.end,inputId:i,start:n.start}}else r[e]=n}return n&&(r.inputs=[...t.keys()].map(e=>e.toJSON())),r}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=Mn){e.stringify&&(e=e.stringify);let t="";return e(this,e=>{t+=e}),t}warn(e,t,r){let n={node:this};for(let e in r)n[e]=r[e];return e.warn(t,n)}get proxyOf(){return this}};var Ln=Pn;Pn.default=Pn;let Dn=Ln,Un=class extends Dn{constructor(e){e&&void 0!==e.value&&"string"!=typeof e.value&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var Fn=Un;Un.default=Un;var Bn={nanoid:(e=21)=>{let t="",r=e;for(;r--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t}};let{SourceMapConsumer:jn,SourceMapGenerator:zn}=gn,{existsSync:Vn,readFileSync:Gn}=gn,{dirname:Hn,join:Zn}=gn;let $n=class{constructor(e,t){if(!1===t.map)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let r=t.map?t.map.prev:void 0,n=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=Hn(this.mapFile)),n&&(this.text=n)}consumer(){return this.consumerCache||(this.consumerCache=new jn(this.text)),this.consumerCache}decodeInline(e){if(/^data:application\/json;charset=utf-?8,/.test(e)||/^data:application\/json,/.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(e)||/^data:application\/json;base64,/.test(e))return t=e.substr(RegExp.lastMatch.length),Buffer?Buffer.from(t,"base64").toString():window.atob(t);var t;let r=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+r)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return"object"==typeof e&&("string"==typeof e.mappings||"string"==typeof e._mappings||Array.isArray(e.sections))}loadAnnotation(e){let t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(!t)return;let r=e.lastIndexOf(t.pop()),n=e.indexOf("*/",r);r>-1&&n>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,n)))}loadFile(e){if(this.root=Hn(e),Vn(e))return this.mapFile=e,Gn(e,"utf-8").toString().trim()}loadMap(e,t){if(!1===t)return!1;if(t){if("string"==typeof t)return t;if("function"!=typeof t){if(t instanceof jn)return zn.fromSourceMap(t).toString();if(t instanceof zn)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}{let r=t(e);if(r){let e=this.loadFile(r);if(!e)throw new Error("Unable to load previous source map: "+r.toString());return e}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let t=this.annotation;return e&&(t=Zn(Hn(e),t)),this.loadFile(t)}}}startWith(e,t){return!!e&&e.substr(0,t.length)===t}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var Wn=$n;$n.default=$n;let{SourceMapConsumer:Yn,SourceMapGenerator:Xn}=gn,{fileURLToPath:Jn,pathToFileURL:Kn}=gn,{isAbsolute:qn,resolve:Qn}=gn,{nanoid:es}=Bn,ts=gn,rs=bn,ns=Wn,ss=Symbol("fromOffsetCache"),is=Boolean(Yn&&Xn),os=Boolean(Qn&&qn),as=class{constructor(e,t={}){if(null==e||"object"==typeof e&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!os||/^\w+:\/\//.test(t.from)||qn(t.from)?this.file=t.from:this.file=Qn(t.from)),os&&is){let e=new ns(this.css,t);if(e.text){this.map=e;let t=e.consumer().file;!this.file&&t&&(this.file=this.mapResolve(t))}}this.file||(this.id=""),this.map&&(this.map.file=this.from)}error(e,t,r,n={}){let s,i,o;if(t&&"object"==typeof t){let e=t,n=r;if("number"==typeof e.offset){let n=this.fromOffset(e.offset);t=n.line,r=n.col}else t=e.line,r=e.column;if("number"==typeof n.offset){let e=this.fromOffset(n.offset);i=e.line,o=e.col}else i=n.line,o=n.column}else if(!r){let e=this.fromOffset(t);t=e.line,r=e.col}let a=this.origin(t,r,i,o);return s=a?new rs(e,void 0===a.endLine?a.line:{column:a.column,line:a.line},void 0===a.endLine?a.column:{column:a.endColumn,line:a.endLine},a.source,a.file,n.plugin):new rs(e,void 0===i?t:{column:r,line:t},void 0===i?r:{column:o,line:i},this.css,this.file,n.plugin),s.input={column:r,endColumn:o,endLine:i,line:t,source:this.css},this.file&&(Kn&&(s.input.url=Kn(this.file).toString()),s.input.file=this.file),s}fromOffset(e){let t,r;if(this[ss])r=this[ss];else{let e=this.css.split("\n");r=new Array(e.length);let t=0;for(let n=0,s=e.length;n=t)n=r.length-1;else{let t,s=r.length-2;for(;n>1),e=r[t+1])){n=t;break}n=t+1}}return{col:e-r[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:Qn(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,r,n){if(!this.map)return!1;let s,i,o=this.map.consumer(),a=o.originalPositionFor({column:t,line:e});if(!a.source)return!1;"number"==typeof r&&(s=o.originalPositionFor({column:n,line:r})),i=qn(a.source)?Kn(a.source):new URL(a.source,this.map.consumer().sourceRoot||Kn(this.map.mapFile));let l={column:a.column,endColumn:s&&s.column,endLine:s&&s.line,line:a.line,url:i.toString()};if("file:"===i.protocol){if(!Jn)throw new Error("file: protocol is not available in this PostCSS build");l.file=Jn(i)}let c=o.sourceContentFor(a.source);return c&&(l.source=c),l}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])null!=this[t]&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};var ls=as;as.default=as,ts&&ts.registerInput&&ts.registerInput(as);let{SourceMapConsumer:cs,SourceMapGenerator:us}=gn,{dirname:hs,relative:ps,resolve:ds,sep:fs}=gn,{pathToFileURL:ms}=gn,gs=ls,ys=Boolean(cs&&us),ws=Boolean(hs&&ds&&ps&&fs);var vs=class{constructor(e,t,r,n){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=n,this.originalCSS=n,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let t="\n";this.css.includes("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"}applyPrevMaps(){for(let e of this.previous()){let t,r=this.toUrl(this.path(e.file)),n=e.root||hs(e.file);!1===this.mapOpts.sourcesContent?(t=new cs(e.text),t.sourcesContent&&(t.sourcesContent=null)):t=e.consumer(),this.map.applySourceMap(t,r,this.toUrl(this.path(n)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],"comment"===e.type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),ws&&ys&&this.isMap())return this.generateMap();{let e="";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=us.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new us({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):""});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new us({file:this.outputFile(),ignoreInvalidMapping:!0});let e,t,r=1,n=1,s="",i={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(o,a,l)=>{if(this.css+=o,a&&"end"!==l&&(i.generated.line=r,i.generated.column=n-1,a.source&&a.source.start?(i.source=this.sourcePath(a),i.original.line=a.source.start.line,i.original.column=a.source.start.column-1,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,this.map.addMapping(i))),e=o.match(/\n/g),e?(r+=e.length,t=o.lastIndexOf("\n"),n=o.length-t):n+=o.length,a&&"start"!==l){let e=a.parent||{raws:{}};("decl"===a.type||"atrule"===a.type&&!a.nodes)&&a===e.last&&!e.raws.semicolon||(a.source&&a.source.end?(i.source=this.sourcePath(a),i.original.line=a.source.end.line,i.original.column=a.source.end.column-1,i.generated.line=r,i.generated.column=n-2,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,i.generated.line=r,i.generated.column=n-1,this.map.addMapping(i)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(e=>e.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(e=>e.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(e=>e.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(e){if(this.mapOpts.absolute)return e;if(60===e.charCodeAt(0))return e;if(/^\w+:\/\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let r=this.opts.to?hs(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(r=hs(ds(r,this.mapOpts.annotation)));let n=ps(r,e);return this.memoizedPaths.set(e,n),n}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new gs(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let r=t.source.input.from;if(r&&!e[r]){e[r]=!0;let n=this.usesFileUrls?this.toFileUrl(r):this.toUrl(this.path(r));this.map.setSourceContent(n,t.source.input.css)}}});else if(this.css){let e=this.opts.from?this.toUrl(this.path(this.opts.from)):"";this.map.setSourceContent(e,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(ms){let t=ms(e).toString();return this.memoizedFileURLs.set(e,t),t}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;"\\"===fs&&(e=e.replace(/\\/g,"/"));let r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r}};let bs=Ln,_s=class extends bs{constructor(e){super(e),this.type="comment"}};var Ss=_s;_s.default=_s;let Cs,Es,Ts,ks,{isClean:xs,my:Os}=_n,As=Fn,Is=Ss,Rs=Ln;function Ms(e){return e.map(e=>(e.nodes&&(e.nodes=Ms(e.nodes)),delete e.source,e))}function Ns(e){if(e[xs]=!1,e.proxyOf.nodes)for(let t of e.proxyOf.nodes)Ns(t)}let Ps=class e extends Rs{append(...e){for(let t of e){let e=this.normalize(t,this.last);for(let t of e)this.proxyOf.nodes.push(t)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t,r,n=this.getIterator();for(;this.indexes[n]"proxyOf"===t?e:e[t]?"each"===t||"string"==typeof t&&t.startsWith("walk")?(...r)=>e[t](...r.map(e=>"function"==typeof e?(t,r)=>e(t.toProxy(),r):e)):"every"===t||"some"===t?r=>e[t]((e,...t)=>r(e.toProxy(),...t)):"root"===t?()=>e.root().toProxy():"nodes"===t?e.nodes.map(e=>e.toProxy()):"first"===t||"last"===t?e[t].toProxy():e[t]:e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"name"!==t&&"params"!==t&&"selector"!==t||e.markDirty()),!0)}}index(e){return"number"==typeof e?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let r,n=this.index(e),s=this.normalize(t,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(let e of s)this.proxyOf.nodes.splice(n+1,0,e);for(let e in this.indexes)r=this.indexes[e],n(t[Os]||e.rebuild(t),(t=t.proxyOf).parent&&t.parent.removeChild(t),t[xs]&&Ns(t),void 0===t.raws.before&&r&&void 0!==r.raws.before&&(t.raws.before=r.raws.before.replace(/\S/g,"")),t.parent=this.proxyOf,t))}prepend(...e){e=e.reverse();for(let t of e){let e=this.normalize(t,this.first,"prepend").reverse();for(let t of e)this.proxyOf.nodes.unshift(t);for(let t in this.indexes)this.indexes[t]=this.indexes[t]+e.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){let t;e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);for(let r in this.indexes)t=this.indexes[r],t>=e&&(this.indexes[r]=t-1);return this.markDirty(),this}replaceValues(e,t,r){return r||(r=t,t={}),this.walkDecls(n=>{t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,r))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,r)=>{let n;try{n=e(t,r)}catch(e){throw t.addToError(e)}return!1!==n&&t.walk&&(n=t.walk(e)),n})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("atrule"===r.type&&e.test(r.name))return t(r,n)}):this.walk((r,n)=>{if("atrule"===r.type&&r.name===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("atrule"===e.type)return t(e,r)}))}walkComments(e){return this.walk((t,r)=>{if("comment"===t.type)return e(t,r)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("decl"===r.type&&e.test(r.prop))return t(r,n)}):this.walk((r,n)=>{if("decl"===r.type&&r.prop===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("decl"===e.type)return t(e,r)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("rule"===r.type&&e.test(r.selector))return t(r,n)}):this.walk((r,n)=>{if("rule"===r.type&&r.selector===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("rule"===e.type)return t(e,r)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Ps.registerParse=e=>{Cs=e},Ps.registerRule=e=>{Es=e},Ps.registerAtRule=e=>{Ts=e},Ps.registerRoot=e=>{ks=e};var Ls=Ps;Ps.default=Ps,Ps.rebuild=e=>{"atrule"===e.type?Object.setPrototypeOf(e,Ts.prototype):"rule"===e.type?Object.setPrototypeOf(e,Es.prototype):"decl"===e.type?Object.setPrototypeOf(e,As.prototype):"comment"===e.type?Object.setPrototypeOf(e,Is.prototype):"root"===e.type&&Object.setPrototypeOf(e,ks.prototype),e[Os]=!0,e.nodes&&e.nodes.forEach(e=>{Ps.rebuild(e)})};let Ds,Us,Fs=Ls,Bs=class extends Fs{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new Ds(new Us,this,e).stringify()}};Bs.registerLazyResult=e=>{Ds=e},Bs.registerProcessor=e=>{Us=e};var js=Bs;Bs.default=Bs;let zs={};var Vs=function(e){zs[e]||(zs[e]=!0,"undefined"!=typeof console&&console.warn&&console.warn(e))};let Gs=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let e=t.node.rangeBy(t);this.line=e.start.line,this.column=e.start.column,this.endLine=e.end.line,this.endColumn=e.end.column}for(let e in t)this[e]=t[e]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var Hs=Gs;Gs.default=Gs;let Zs=Hs,$s=class{constructor(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let r=new Zs(e,t);return this.messages.push(r),r}warnings(){return this.messages.filter(e=>"warning"===e.type)}get content(){return this.css}};var Ws=$s;$s.default=$s;const Ys="'".charCodeAt(0),Xs='"'.charCodeAt(0),Js="\\".charCodeAt(0),Ks="/".charCodeAt(0),qs="\n".charCodeAt(0),Qs=" ".charCodeAt(0),ei="\f".charCodeAt(0),ti="\t".charCodeAt(0),ri="\r".charCodeAt(0),ni="[".charCodeAt(0),si="]".charCodeAt(0),ii="(".charCodeAt(0),oi=")".charCodeAt(0),ai="{".charCodeAt(0),li="}".charCodeAt(0),ci=";".charCodeAt(0),ui="*".charCodeAt(0),hi=":".charCodeAt(0),pi="@".charCodeAt(0),di=/[\t\n\f\r "#'()/;[\\\]{}]/g,fi=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,mi=/.[\r\n"'(/\\]/,gi=/[\da-f]/i;let yi=Ls,wi=class extends yi{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};var vi=wi;wi.default=wi,yi.registerAtRule(wi);let bi,_i,Si=Ls,Ci=class extends Si{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,r){let n=super.normalize(e);if(t)if("prepend"===r)this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let e of n)e.raws.before=t.raws.before;return n}removeChild(e,t){let r=this.index(e);return!t&&0===r&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[r].raws.before),super.removeChild(e)}toResult(e={}){return new bi(new _i,this,e).stringify()}};Ci.registerLazyResult=e=>{bi=e},Ci.registerProcessor=e=>{_i=e};var Ei=Ci;Ci.default=Ci,Si.registerRoot(Ci);let Ti={comma:e=>Ti.split(e,[","],!0),space:e=>Ti.split(e,[" ","\n","\t"]),split(e,t,r){let n=[],s="",i=!1,o=0,a=!1,l="",c=!1;for(let r of e)c?c=!1:"\\"===r?c=!0:a?r===l&&(a=!1):'"'===r||"'"===r?(a=!0,l=r):"("===r?o+=1:")"===r?o>0&&(o-=1):0===o&&t.includes(r)&&(i=!0),i?(""!==s&&n.push(s.trim()),s="",i=!1):s+=r;return(r||""!==s)&&n.push(s.trim()),n}};var ki=Ti;Ti.default=Ti;let xi=Ls,Oi=ki,Ai=class extends xi{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Oi.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,r=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(r)}};var Ii=Ai;Ai.default=Ai,xi.registerRule(Ai);let Ri=Fn,Mi=function(e,t={}){let r,n,s,i,o,a,l,c,u,h,p=e.css.valueOf(),d=t.ignoreErrors,f=p.length,m=0,g=[],y=[];function w(t){throw e.error("Unclosed "+t,m)}return{back:function(e){y.push(e)},endOfFile:function(){return 0===y.length&&m>=f},nextToken:function(e){if(y.length)return y.pop();if(m>=f)return;let t=!!e&&e.ignoreUnclosed;switch(r=p.charCodeAt(m),r){case qs:case Qs:case ti:case ri:case ei:n=m;do{n+=1,r=p.charCodeAt(n)}while(r===Qs||r===qs||r===ti||r===ri||r===ei);h=["space",p.slice(m,n)],m=n-1;break;case ni:case si:case ai:case li:case hi:case ci:case oi:{let e=String.fromCharCode(r);h=[e,e,m];break}case ii:if(c=g.length?g.pop()[1]:"",u=p.charCodeAt(m+1),"url"===c&&u!==Ys&&u!==Xs&&u!==Qs&&u!==qs&&u!==ti&&u!==ei&&u!==ri){n=m;do{if(a=!1,n=p.indexOf(")",n+1),-1===n){if(d||t){n=m;break}w("bracket")}for(l=n;p.charCodeAt(l-1)===Js;)l-=1,a=!a}while(a);h=["brackets",p.slice(m,n+1),m,n],m=n}else n=p.indexOf(")",m+1),i=p.slice(m,n+1),-1===n||mi.test(i)?h=["(","(",m]:(h=["brackets",i,m,n],m=n);break;case Ys:case Xs:s=r===Ys?"'":'"',n=m;do{if(a=!1,n=p.indexOf(s,n+1),-1===n){if(d||t){n=m+1;break}w("string")}for(l=n;p.charCodeAt(l-1)===Js;)l-=1,a=!a}while(a);h=["string",p.slice(m,n+1),m,n],m=n;break;case pi:di.lastIndex=m+1,di.test(p),n=0===di.lastIndex?p.length-1:di.lastIndex-2,h=["at-word",p.slice(m,n+1),m,n],m=n;break;case Js:for(n=m,o=!0;p.charCodeAt(n+1)===Js;)n+=1,o=!o;if(r=p.charCodeAt(n+1),o&&r!==Ks&&r!==Qs&&r!==qs&&r!==ti&&r!==ri&&r!==ei&&(n+=1,gi.test(p.charAt(n)))){for(;gi.test(p.charAt(n+1));)n+=1;p.charCodeAt(n+1)===Qs&&(n+=1)}h=["word",p.slice(m,n+1),m,n],m=n;break;default:r===Ks&&p.charCodeAt(m+1)===ui?(n=p.indexOf("*/",m+2)+1,0===n&&(d||t?n=p.length:w("comment")),h=["comment",p.slice(m,n+1),m,n],m=n):(fi.lastIndex=m+1,fi.test(p),n=0===fi.lastIndex?p.length-1:fi.lastIndex-2,h=["word",p.slice(m,n+1),m,n],g.push(h),m=n)}return m++,h},position:function(){return m}}},Ni=Ss,Pi=vi,Li=Ei,Di=Ii;const Ui={empty:!0,space:!0};var Fi=class{constructor(e){this.input=e,this.root=new Li,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t,r,n,s=new Pi;s.name=e[1].slice(1),""===s.name&&this.unnamedAtrule(s,e),this.init(s,e[2]);let i=!1,o=!1,a=[],l=[];for(;!this.tokenizer.endOfFile();){if(t=(e=this.tokenizer.nextToken())[0],"("===t||"["===t?l.push("("===t?")":"]"):"{"===t&&l.length>0?l.push("}"):t===l[l.length-1]&&l.pop(),0===l.length){if(";"===t){s.source.end=this.getPosition(e[2]),s.source.end.offset++,this.semicolon=!0;break}if("{"===t){o=!0;break}if("}"===t){if(a.length>0){for(n=a.length-1,r=a[n];r&&"space"===r[0];)r=a[--n];r&&(s.source.end=this.getPosition(r[3]||r[2]),s.source.end.offset++)}this.end(e);break}a.push(e)}else a.push(e);if(this.tokenizer.endOfFile()){i=!0;break}}s.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(s.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(s,"params",a),i&&(e=a[a.length-1],s.source.end=this.getPosition(e[3]||e[2]),s.source.end.offset++,this.spaces=s.raws.between,s.raws.between="")):(s.raws.afterName="",s.params=""),o&&(s.nodes=[],this.current=s)}checkMissedSemicolon(e){let t=this.colon(e);if(!1===t)return;let r,n=0;for(let s=t-1;s>=0&&(r=e[s],"space"===r[0]||(n+=1,2!==n));s--);throw this.input.error("Missed semicolon","word"===r[0]?r[3]+1:r[2])}colon(e){let t,r,n,s=0;for(let[i,o]of e.entries()){if(t=o,r=t[0],"("===r&&(s+=1),")"===r&&(s-=1),0===s&&":"===r){if(n){if("word"===n[0]&&"progid"===n[1])continue;return i}this.doubleColon(t)}n=t}return!1}comment(e){let t=new Ni;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let r=e[1].slice(2,-2);if(/^\s*$/.test(r))t.text="",t.raws.left=r,t.raws.right="";else{let e=r.match(/^(\s*)([^]*\S)(\s*)$/);t.text=e[2],t.raws.left=e[1],t.raws.right=e[3]}}createTokenizer(){this.tokenizer=Mi(this.input)}decl(e,t){let r=new Ri;this.init(r,e[0][2]);let n,s=e[e.length-1];for(";"===s[0]&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(s[3]||s[2]||function(e){for(let t=e.length-1;t>=0;t--){let r=e[t],n=r[3]||r[2];if(n)return n}}(e)),r.source.end.offset++;"word"!==e[0][0];)1===e.length&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop="";e.length;){let t=e[0][0];if(":"===t||"space"===t||"comment"===t)break;r.prop+=e.shift()[1]}for(r.raws.between="";e.length;){if(n=e.shift(),":"===n[0]){r.raws.between+=n[1];break}"word"===n[0]&&/\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1]}"_"!==r.prop[0]&&"*"!==r.prop[0]||(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));let i,o=[];for(;e.length&&(i=e[0][0],"space"===i||"comment"===i);)o.push(e.shift());this.precheckMissedSemicolon(e);for(let t=e.length-1;t>=0;t--){if(n=e[t],"!important"===n[1].toLowerCase()){r.important=!0;let n=this.stringFrom(e,t);n=this.spacesFromEnd(e)+n," !important"!==n&&(r.raws.important=n);break}if("important"===n[1].toLowerCase()){let n=e.slice(0),s="";for(let e=t;e>0;e--){let t=n[e][0];if(0===s.trim().indexOf("!")&&"space"!==t)break;s=n.pop()[1]+s}0===s.trim().indexOf("!")&&(r.important=!0,r.raws.important=s,e=n)}if("space"!==n[0]&&"comment"!==n[0])break}e.some(e=>"space"!==e[0]&&"comment"!==e[0])&&(r.raws.between+=o.map(e=>e[1]).join(""),o=[]),this.raw(r,"value",o.concat(e),t),r.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new Di;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let e=this.current.nodes[this.current.nodes.length-1];e&&"rule"===e.type&&!e.raws.ownSemicolon&&(e.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="","comment"!==e.type&&(this.semicolon=!1)}other(e){let t=!1,r=null,n=!1,s=null,i=[],o=e[1].startsWith("--"),a=[],l=e;for(;l;){if(r=l[0],a.push(l),"("===r||"["===r)s||(s=l),i.push("("===r?")":"]");else if(o&&n&&"{"===r)s||(s=l),i.push("}");else if(0===i.length){if(";"===r){if(n)return void this.decl(a,o);break}if("{"===r)return void this.rule(a);if("}"===r){this.tokenizer.back(a.pop()),t=!0;break}":"===r&&(n=!0)}else r===i[i.length-1]&&(i.pop(),0===i.length&&(s=null));l=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),i.length>0&&this.unclosedBracket(s),t&&n){if(!o)for(;a.length&&(l=a[a.length-1][0],"space"===l||"comment"===l);)this.tokenizer.back(a.pop());this.decl(a,o)}else this.unknownWord(a)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e)}this.endFile()}precheckMissedSemicolon(){}raw(e,t,r,n){let s,i,o,a,l=r.length,c="",u=!0;for(let e=0;ee+t[1],"");e.raws[t]={raw:n,value:c}}e[t]=c}rule(e){e.pop();let t=new Di;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t||"comment"===t);)r=e.pop()[1]+r;return r}spacesAndCommentsFromStart(e){let t,r="";for(;e.length&&(t=e[0][0],"space"===t||"comment"===t);)r+=e.shift()[1];return r}spacesFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t);)r=e.pop()[1]+r;return r}stringFrom(e,t){let r="";for(let n=t;noo(e)),e}let ao={},lo=class e{constructor(t,r,n){let s;if(this.stringified=!1,this.processed=!1,"object"!=typeof r||null===r||"root"!==r.type&&"document"!==r.type)if(r instanceof e||r instanceof Ki)s=oo(r.root),r.map&&(void 0===n.map&&(n.map={}),n.map.inline||(n.map.inline=!1),n.map.prev=r.map);else{let e=qi;n.syntax&&(e=n.syntax.parse),n.parser&&(e=n.parser),e.parse&&(e=e.parse);try{s=e(r,n)}catch(e){this.processed=!0,this.error=e}s&&!s[Zi]&&Yi.rebuild(s)}else s=oo(r);this.result=new Ki(t,s,n),this.helpers={...ao,postcss:ao,result:this.result},this.plugins=this.processor.plugins.map(e=>"object"==typeof e&&e.prepare?{...e,...e.prepare(this.result)}:e)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let r=this.result.lastPlugin;try{if(t&&t.addToError(e),this.error=e,"CssSyntaxError"!==e.name||e.plugin){if(r.postcssVersion&&"production"!==process.env.NODE_ENV){let e=r.postcssPlugin,t=r.postcssVersion,n=this.result.processor.version,s=t.split("."),i=n.split(".");(s[0]!==i[0]||parseInt(s[1])>parseInt(i[1]))&&console.error("Unknown error from PostCSS plugin. Your current PostCSS version is "+n+", but "+e+" uses "+t+". Perhaps this is the source of the error below.")}}else e.plugin=r.postcssPlugin,e.setMessage()}catch(e){console&&console.error&&console.error(e)}return e}prepareVisitors(){this.listeners={};let e=(e,t,r)=>{this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push([e,r])};for(let t of this.plugins)if("object"==typeof t)for(let r in t){if(!to[r]&&/^[A-Z]/.test(r))throw new Error(`Unknown event ${r} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!ro[r])if("object"==typeof t[r])for(let n in t[r])e(t,"*"===n?r:r+"-"+n.toLowerCase(),t[r][n]);else"function"==typeof t[r]&&e(t,r,t[r])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e0;){let e=this.visitTick(t);if(no(e))try{await e}catch(e){let r=t[t.length-1].node;throw this.handleError(e,r)}}}if(this.listeners.OnceExit)for(let[t,r]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if("document"===e.type){let t=e.nodes.map(e=>r(e,this.helpers));await Promise.all(t)}else await r(e,this.helpers)}catch(e){throw this.handleError(e)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if("object"==typeof e&&e.Once){if("document"===this.result.root.type){let t=this.result.root.nodes.map(t=>e.Once(t,this.helpers));return no(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}if("function"==typeof e)return e(this.result.root,this.result)}catch(e){throw this.handleError(e)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=Wi;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new $i(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){if(no(this.runOnRoot(e)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[Hi];)e[Hi]=!0,this.walkSync(e);if(this.listeners.OnceExit)if("document"===e.type)for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this.opts||Ji("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[r,n]of e){let e;this.result.lastPlugin=r;try{e=n(t,this.helpers)}catch(e){throw this.handleError(e,t.proxyOf)}if("root"!==t.type&&"document"!==t.type&&!t.parent)return!0;if(no(e))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:r,visitors:n}=t;if("root"!==r.type&&"document"!==r.type&&!r.parent)return void e.pop();if(n.length>0&&t.visitorIndex{e[Hi]||this.walkSync(e)});else{let t=this.listeners[r];if(t&&this.visitSync(t,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};lo.registerPostcss=e=>{ao=e};var co=lo;lo.default=lo,Qi.registerLazyResult(lo),Xi.registerLazyResult(lo);let uo=vs,ho=xn,po=Vs,fo=Gi;const mo=Ws;let go=class{constructor(e,t,r){let n;t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;let s=ho;this.result=new mo(this._processor,n,this._opts),this.result.css=t;let i=this;Object.defineProperty(this.result,"root",{get:()=>i.root});let o=new uo(s,n,this._opts,t);if(o.isMap()){let[e,t]=o.generate();e&&(this.result.css=e),t&&(this.result.map=t)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this._opts||po("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=fo;try{e=t(this._css,this._opts)}catch(e){this.error=e}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}};var yo=go;go.default=go;let wo=yo,vo=co,bo=js,_o=Ei,So=class{constructor(e=[]){this.version="8.4.38",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let r of e)if(!0===r.postcss?r=r():r.postcss&&(r=r.postcss),"object"==typeof r&&Array.isArray(r.plugins))t=t.concat(r.plugins);else if("object"==typeof r&&r.postcssPlugin)t.push(r);else if("function"==typeof r)t.push(r);else{if("object"!=typeof r||!r.parse&&!r.stringify)throw new Error(r+" is not a PostCSS plugin");if("production"!==process.env.NODE_ENV)throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.")}return t}process(e,t={}){return this.plugins.length||t.parser||t.stringifier||t.syntax?new vo(this,e,t):new wo(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};var Co=So;So.default=So,_o.registerProcessor(So),bo.registerProcessor(So);let Eo=Fn,To=Wn,ko=Ss,xo=vi,Oo=ls,Ao=Ei,Io=Ii;function Ro(e,t){if(Array.isArray(e))return e.map(e=>Ro(e));let{inputs:r,...n}=e;if(r){t=[];for(let e of r){let r={...e,__proto__:Oo.prototype};r.map&&(r.map={...r.map,__proto__:To.prototype}),t.push(r)}}if(n.nodes&&(n.nodes=e.nodes.map(e=>Ro(e,t))),n.source){let{inputId:e,...r}=n.source;n.source=r,null!=e&&(n.source.input=t[e])}if("root"===n.type)return new Ao(n);if("decl"===n.type)return new Eo(n);if("rule"===n.type)return new Io(n);if("comment"===n.type)return new ko(n);if("atrule"===n.type)return new xo(n);throw new Error("Unknown node type: "+e.type)}var Mo=Ro;Ro.default=Ro;let No=bn,Po=Fn,Lo=co,Do=Ls,Uo=Co,Fo=xn,Bo=Mo,jo=js,zo=Hs,Vo=Ss,Go=vi,Ho=Ws,Zo=ls,$o=Gi,Wo=ki,Yo=Ii,Xo=Ei,Jo=Ln;function Ko(...e){return 1===e.length&&Array.isArray(e[0])&&(e=e[0]),new Uo(e)}Ko.plugin=function(e,t){let r,n=!1;function s(...r){console&&console.warn&&!n&&(n=!0,console.warn(e+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226"));let s=t(...r);return s.postcssPlugin=e,s.postcssVersion=(new Uo).version,s}return Object.defineProperty(s,"postcss",{get:()=>(r||(r=s()),r)}),s.process=function(e,t,r){return Ko([s(r)]).process(e,t)},s},Ko.stringify=Fo,Ko.parse=$o,Ko.fromJSON=Bo,Ko.list=Wo,Ko.comment=e=>new Vo(e),Ko.atRule=e=>new Go(e),Ko.decl=e=>new Po(e),Ko.rule=e=>new Yo(e),Ko.root=e=>new Xo(e),Ko.document=e=>new jo(e),Ko.CssSyntaxError=No,Ko.Declaration=Po,Ko.Container=Do,Ko.Processor=Uo,Ko.Document=jo,Ko.Comment=Vo,Ko.Warning=zo,Ko.AtRule=Go,Ko.Result=Ho,Ko.Input=Zo,Ko.Rule=Yo,Ko.Root=Xo,Ko.Node=Jo,Lo.registerPostcss(Ko);var qo=Ko;Ko.default=Ko;const Qo=un(qo);Qo.stringify,Qo.fromJSON,Qo.plugin,Qo.parse,Qo.list,Qo.document,Qo.comment,Qo.atRule,Qo.rule,Qo.decl,Qo.root,Qo.CssSyntaxError,Qo.Declaration,Qo.Container,Qo.Processor,Qo.Document,Qo.Comment,Qo.Warning,Qo.AtRule,Qo.Result,Qo.Input,Qo.Rule,Qo.Root,Qo.Node;let ea=class e{constructor(...e){cn(this,"parentElement",null),cn(this,"parentNode",null),cn(this,"ownerDocument"),cn(this,"firstChild",null),cn(this,"lastChild",null),cn(this,"previousSibling",null),cn(this,"nextSibling",null),cn(this,"ELEMENT_NODE",1),cn(this,"TEXT_NODE",3),cn(this,"nodeType"),cn(this,"nodeName"),cn(this,"RRNodeType")}get childNodes(){const e=[];let t=this.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}contains(t){if(!(t instanceof e))return!1;if(t.ownerDocument!==this.ownerDocument)return!1;if(t===this)return!0;for(;t.parentNode;){if(t.parentNode===this)return!0;t=t.parentNode}return!1}appendChild(e){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(e,t){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(e){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}};const ta={Node:["childNodes","parentNode","parentElement","textContent"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},ra={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},na={};function sa(e){if(na[e])return na[e];const t=globalThis[e],r=t.prototype,n=e in ta?ta[e]:void 0,s=Boolean(n&&n.every(e=>{var t,n;return Boolean(null==(n=null==(t=Object.getOwnPropertyDescriptor(r,e))?void 0:t.get)?void 0:n.toString().includes("[native code]"))})),i=e in ra?ra[e]:void 0,o=Boolean(i&&i.every(e=>{var t;return"function"==typeof r[e]&&(null==(t=r[e])?void 0:t.toString().includes("[native code]"))}));if(s&&o&&!globalThis.Zone)return na[e]=t.prototype,t.prototype;try{const n=document.createElement("iframe");document.body.appendChild(n);const s=n.contentWindow;if(!s)return t.prototype;const i=s[e].prototype;return document.body.removeChild(n),i?na[e]=i:r}catch{return r}}const ia={};function oa(e,t,r){var n;const s=`${e}.${String(r)}`;if(ia[s])return ia[s].call(t);const i=sa(e),o=null==(n=Object.getOwnPropertyDescriptor(i,r))?void 0:n.get;return o?(ia[s]=o,o.call(t)):t[r]}const aa={};function la(e,t,r){const n=`${e}.${String(r)}`;if(aa[n])return aa[n].bind(t);const s=sa(e)[r];return"function"!=typeof s?t[r]:(aa[n]=s,s.bind(t))}const ca={childNodes:function(e){return oa("Node",e,"childNodes")},parentNode:function(e){return oa("Node",e,"parentNode")},parentElement:function(e){return oa("Node",e,"parentElement")},textContent:function(e){return oa("Node",e,"textContent")},contains:function(e,t){return la("Node",e,"contains")(t)},getRootNode:function(e){return la("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?oa("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?oa("Element",e,"shadowRoot"):null},querySelector:function(e,t){return oa("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return oa("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return sa("MutationObserver").constructor}};const ua="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";let ha={map:{},getId:()=>(console.error(ua),-1),getNode:()=>(console.error(ua),null),removeNodeFromMap(){console.error(ua)},has:()=>(console.error(ua),!1),reset(){console.error(ua)}};"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(ha=new Proxy(ha,{get:(e,t,r)=>("map"===t&&console.error(ua),Reflect.get(e,t,r))}));let pa=Date.now;function da(e){if(!e)return null;return e.nodeType===e.ELEMENT_NODE?e:ca.parentElement(e)}/[1-9][0-9]{12}/.test(Date.now().toString())||(pa=()=>(new Date).getTime());function fa(e){var t;let r=null;return"getRootNode"in e&&(null==(t=ca.getRootNode(e))?void 0:t.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&ca.host(ca.getRootNode(e))&&(r=ca.host(ca.getRootNode(e))),r}function ma(e){let t,r=e;for(;t=fa(r);)r=t;return r}function ga(e){const t=e.ownerDocument;if(!t)return!1;const r=ma(e);return ca.contains(t,r)}const ya=Object.freeze(Object.defineProperty({__proto__:null,StyleSheetMirror:class{constructor(){s(this,"id",1),s(this,"styleIDMap",new WeakMap),s(this,"idStyleMap",new Map)}getId(e){return this.styleIDMap.get(e)??-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let r;return r=void 0===t?this.id++:t,this.styleIDMap.set(e,r),this.idStyleMap.set(r,e),r}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}},get _mirror(){return ha},closestElementOfNode:da,getBaseDimension:function e(t,r){var n,s;const i=null==(s=null==(n=t.ownerDocument)?void 0:n.defaultView)?void 0:s.frameElement;if(!i||i===r)return{x:0,y:0,relativeScale:1,absoluteScale:1};const o=i.getBoundingClientRect(),a=e(i,r),l=o.height/i.clientHeight;return{x:o.x*a.relativeScale+a.x,y:o.y*a.relativeScale+a.y,relativeScale:l,absoluteScale:a.absoluteScale*l}},getNestedRule:function e(t,r){const n=t[r[0]];return 1===r.length?n:e(n.cssRules[r[1]].cssRules,r.slice(2))},getPositionsAndIndex:function(e){const t=[...e],r=t.pop();return{positions:t,index:r}},getRootShadowHost:ma,getShadowHost:fa,getWindowHeight:function(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight},getWindowScroll:function(e){var t,r,n,s;const i=e.document;return{left:i.scrollingElement?i.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:i.documentElement.scrollLeft||(null==i?void 0:i.body)&&(null==(t=ca.parentElement(i.body))?void 0:t.scrollLeft)||(null==(r=null==i?void 0:i.body)?void 0:r.scrollLeft)||0,top:i.scrollingElement?i.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==i?void 0:i.documentElement.scrollTop)||(null==i?void 0:i.body)&&(null==(n=ca.parentElement(i.body))?void 0:n.scrollTop)||(null==(s=null==i?void 0:i.body)?void 0:s.scrollTop)||0}},getWindowWidth:function(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth},hasShadowRoot:function(e){return!!e&&(e instanceof ea&&"shadowRoot"in e?Boolean(e.shadowRoot):Boolean(ca.shadowRoot(e)))},hookSetter:function e(t,r,n,s,i=window){const o=i.Object.getOwnPropertyDescriptor(t,r);return i.Object.defineProperty(t,r,s?n:{set(e){setTimeout(()=>{n.set.call(this,e)},0),o&&o.set&&o.set.call(this,e)}}),()=>e(t,r,o||{},!0)},inDom:function(e){const t=e.ownerDocument;return!!t&&(ca.contains(t,e)||ga(e))},isAncestorRemoved:function e(t,r){if(function(e){const t=e&&"host"in e&&"mode"in e&&m.host(e)||null;return Boolean(t&&"shadowRoot"in t&&m.shadowRoot(t)===e)}(t))return!1;const n=r.getId(t);if(!r.has(n))return!0;const s=ca.parentNode(t);return(!s||s.nodeType!==t.DOCUMENT_NODE)&&(!s||e(s,r))},isBlocked:function(e,t,r,n){if(!e)return!1;const s=da(e);if(!s)return!1;try{if("string"==typeof t){if(s.classList.contains(t))return!0;if(n&&null!==s.closest("."+t))return!0}else if(y(s,t,n))return!0}catch(e){}if(r){if(s.matches(r))return!0;if(n&&null!==s.closest(r))return!0}return!1},isIgnored:function(e,t,r){return!("TITLE"!==e.tagName||!r.headTitleMutations)||-2===t.getId(e)},isSerialized:function(e,t){return-1!==t.getId(e)},isSerializedIframe:function(e,t){return Boolean("IFRAME"===e.nodeName&&t.getMeta(e))},isSerializedStylesheet:function(e,t){return Boolean("LINK"===e.nodeName&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&"stylesheet"===e.getAttribute("rel")&&t.getMeta(e))},iterateResolveTree:function e(t,r){r(t.value);for(let n=t.children.length-1;n>=0;n--)e(t.children[n],r)},legacy_isTouchEvent:function(e){return Boolean(e.changedTouches)},get nowTimestamp(){return pa},on:function(e,t,r=document){const n={capture:!0,passive:!0};return r.addEventListener(e,t,n),()=>r.removeEventListener(e,t,n)},patch:function(e,t,r){try{if(!(t in e))return()=>{};const n=e[t],s=r(n);return"function"==typeof s&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__rrweb_original__:{enumerable:!1,value:n}})),e[t]=s,()=>{e[t]=n}}catch{return()=>{}}},polyfill:function(e=window){"NodeList"in e&&!e.NodeList.prototype.forEach&&(e.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in e&&!e.DOMTokenList.prototype.forEach&&(e.DOMTokenList.prototype.forEach=Array.prototype.forEach)},queueToResolveTrees:function(e){const t={},r=(e,r)=>{const n={value:e,parent:r,children:[]};return t[e.node.id]=n,n},n=[];for(const s of e){const{nextId:e,parentId:i}=s;if(e&&e in t){const i=t[e];if(i.parent){const e=i.parent.children.indexOf(i);i.parent.children.splice(e,0,r(s,i.parent))}else{const e=n.indexOf(i);n.splice(e,0,r(s,null))}continue}if(i in t){const e=t[i];e.children.push(r(s,e));continue}n.push(r(s,null))}return n},shadowHostInDom:ga,throttle:function(e,t,r={}){let n=null,s=0;return function(...i){const o=Date.now();s||!1!==r.leading||(s=o);const a=t-(o-s),l=this;a<=0||a>t?(n&&(clearTimeout(n),n=null),s=o,e.apply(l,i)):n||!1===r.trailing||(n=setTimeout(()=>{s=!1===r.leading?0:Date.now(),n=null,e.apply(l,i)},a))}},uniqueTextMutations:function(e){const t=new Set,r=[];for(let n=e.length;n--;){const s=e[n];t.has(s.id)||(r.push(s),t.add(s.id))}return r}},Symbol.toStringTag,{value:"Module"}));for(var wa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",va="undefined"==typeof Uint8Array?[]:new Uint8Array(256),ba=0;ba<64;ba++)va[wa.charCodeAt(ba)]=ba;var _a,Sa,Ca;"undefined"!=typeof window&&window.Blob&&new Blob([(_a="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",Uint8Array.from(atob(_a),e=>e.charCodeAt(0)))],{type:"text/javascript;charset=utf-8"});try{if(2!==Array.from([1],e=>2*e)[0]){const t=document.createElement("iframe");document.body.appendChild(t),Array.from=(null==(e=t.contentWindow)?void 0:e.Array.from)||Array.from,document.body.removeChild(t)}}catch(e){console.debug("Unable to override Array.from",e)}new g,(Ca=Sa||(Sa={}))[Ca.NotStarted=0]="NotStarted",Ca[Ca.Running=1]="Running",Ca[Ca.Stopped=2]="Stopped";class Ea{constructor(e){r(this,"fileName"),r(this,"functionName"),r(this,"lineNumber"),r(this,"columnNumber"),this.fileName=e.fileName||"",this.functionName=e.functionName||"",this.lineNumber=e.lineNumber,this.columnNumber=e.columnNumber}toString(){const e=this.lineNumber||"",t=this.columnNumber||"";return this.functionName?`${this.functionName} (${this.fileName}:${e}:${t})`:`${this.fileName}:${e}:${t}`}}const Ta=/(^|@)\S+:\d+/,ka=/^\s*at .*(\S+:\d+|\(native\))/m,xa=/^(eval@)?(\[native code])?$/,Oa={parse:function(e){return e?void 0!==e.stacktrace||void 0!==e["opera#sourceloc"]?this.parseOpera(e):e.stack&&e.stack.match(ka)?this.parseV8OrIE(e):e.stack?this.parseFFOrSafari(e):(console.warn("[console-record-plugin]: Failed to parse error object:",e),[]):[]},extractLocation:function(e){if(-1===e.indexOf(":"))return[e];const t=/(.+?)(?::(\d+))?(?::(\d+))?$/.exec(e.replace(/[()]/g,""));if(!t)throw new Error(`Cannot parse given url: ${e}`);return[t[1],t[2]||void 0,t[3]||void 0]},parseV8OrIE:function(e){return e.stack.split("\n").filter(function(e){return!!e.match(ka)},this).map(function(e){e.indexOf("(eval ")>-1&&(e=e.replace(/eval code/g,"eval").replace(/(\(eval at [^()]*)|(\),.*$)/g,""));let t=e.replace(/^\s+/,"").replace(/\(eval code/g,"(");const r=t.match(/ (\((.+):(\d+):(\d+)\)$)/);t=r?t.replace(r[0],""):t;const n=t.split(/\s+/).slice(1),s=this.extractLocation(r?r[1]:n.pop()),i=n.join(" ")||void 0,o=["eval",""].indexOf(s[0])>-1?void 0:s[0];return new Ea({functionName:i,fileName:o,lineNumber:s[1],columnNumber:s[2]})},this)},parseFFOrSafari:function(e){return e.stack.split("\n").filter(function(e){return!e.match(xa)},this).map(function(e){if(e.indexOf(" > eval")>-1&&(e=e.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,":$1")),-1===e.indexOf("@")&&-1===e.indexOf(":"))return new Ea({functionName:e});{const t=/((.*".+"[^@]*)?[^@]*)(?:@)/,r=e.match(t),n=r&&r[1]?r[1]:void 0,s=this.extractLocation(e.replace(t,""));return new Ea({functionName:n,fileName:s[0],lineNumber:s[1],columnNumber:s[2]})}},this)},parseOpera:function(e){return!e.stacktrace||e.message.indexOf("\n")>-1&&e.message.split("\n").length>e.stacktrace.split("\n").length?this.parseOpera9(e):e.stack?this.parseOpera11(e):this.parseOpera10(e)},parseOpera9:function(e){const t=/Line (\d+).*script (?:in )?(\S+)/i,r=e.message.split("\n"),n=[];for(let e=2,s=r.length;e/,"$2").replace(/\([^)]*\)/g,"")||void 0;return new Ea({functionName:n,fileName:r[0],lineNumber:r[1],columnNumber:r[2]})},this)}};function Aa(e){if(!e||!e.outerHTML)return"";let t="";for(;e.parentElement;){let r=e.localName;if(!r)break;r=r.toLowerCase();const n=e.parentElement,s=[];if(n.children&&n.children.length>0)for(let e=0;e1&&(r+=`:eq(${s.indexOf(e)})`),t=r+(t?">"+t:""),e=n}return t}function Ia(e){return"[object Object]"===Object.prototype.toString.call(e)}function Ra(e,t){if(0===t)return!0;const r=Object.keys(e);for(const n of r)if(Ia(e[n])&&Ra(e[n],t-1))return!0;return!1}function Ma(e,t){const r={numOfKeysLimit:50,depthOfLimit:4};Object.assign(r,t);const n=[],s=[];return JSON.stringify(e,function(e,t){if(n.length>0){const r=n.indexOf(this);~r?n.splice(r+1):n.push(this),~r?s.splice(r,1/0,e):s.push(e),~n.indexOf(t)&&(t=n[0]===t?"[Circular ~]":"[Circular ~."+s.slice(0,n.indexOf(t)).join(".")+"]")}else n.push(t);if(null===t)return t;if(void 0===t)return"undefined";if(function(e){if(Ia(e)&&Object.keys(e).length>r.numOfKeysLimit)return!0;if("function"==typeof e)return!0;if(Ia(e)&&Ra(e,r.depthOfLimit))return!0;return!1}(t))return function(e){let t=e.toString();r.stringLengthLimit&&t.length>r.stringLengthLimit&&(t=`${t.slice(0,r.stringLengthLimit)}...`);return t}(t);if("bigint"==typeof t)return t.toString()+"n";if(t instanceof Event){const e={};for(const r in t){const n=t[r];Array.isArray(n)?e[r]=Aa(n.length?n[0]:null):e[r]=n}return e}return t instanceof Node?t instanceof HTMLElement?t?t.outerHTML:"":t.nodeName:t instanceof Error?t.stack?t.stack+"\nEnd of stack for Error object":t.name+": "+t.message:t})}const Na={level:["assert","clear","count","countReset","debug","dir","dirxml","error","group","groupCollapsed","groupEnd","info","log","table","time","timeEnd","timeLog","trace","warn"],lengthThreshold:1e3,logger:"console"};function Pa(e,t,r){const n=r?Object.assign({},Na,r):Na,s=n.logger;if(!s)return()=>{};let i;i="string"==typeof s?t[s]:s;let o=0,a=!1;const l=[];if(n.level.includes("error")){const r=t=>{const r=t.message,s=t.error,i=Oa.parse(s).map(e=>e.toString()),o=[Ma(r,n.stringifyOptions)];e({level:"error",trace:i,payload:o})};t.addEventListener("error",r),l.push(()=>{t.removeEventListener("error",r)});const s=t=>{let r,s;t.reason instanceof Error?(r=t.reason,s=[Ma(`Uncaught (in promise) ${r.name}: ${r.message}`,n.stringifyOptions)]):(r=new Error,s=[Ma("Uncaught (in promise)",n.stringifyOptions),Ma(t.reason,n.stringifyOptions)]);const i=Oa.parse(r).map(e=>e.toString());e({level:"error",trace:i,payload:s})};t.addEventListener("unhandledrejection",s),l.push(()=>{t.removeEventListener("unhandledrejection",s)})}for(const e of n.level)l.push(c(i,e));return()=>{l.forEach(e=>e())};function c(t,r){return t[r]?ya.patch(t,r,t=>(...s)=>{if(t.apply(this,s),!("assert"===r&&s[0]||a)){a=!0;try{const t=Oa.parse(new Error).map(e=>e.toString()).splice(1),i=("assert"===r?s.slice(1):s).map(e=>Ma(e,n.stringifyOptions));o++,o{}}}var La,Da=Object.defineProperty,Ua=(e,t,r)=>((e,t,r)=>t in e?Da(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r),Fa=Object.defineProperty,Ba=(e,t,r)=>((e,t,r)=>t in e?Fa(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r),ja=(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(ja||{});const za={Node:["childNodes","parentNode","parentElement","textContent","ownerDocument"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},Va={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},Ga={};function Ha(e){if(Ga[e])return Ga[e];const t=globalThis[e],r=t.prototype,n=e in za?za[e]:void 0,s=Boolean(n&&n.every(e=>{var t,n;return Boolean(null==(n=null==(t=Object.getOwnPropertyDescriptor(r,e))?void 0:t.get)?void 0:n.toString().includes("[native code]"))})),i=e in Va?Va[e]:void 0,o=Boolean(i&&i.every(e=>{var t;return"function"==typeof r[e]&&(null==(t=r[e])?void 0:t.toString().includes("[native code]"))}));if(s&&o&&!globalThis.Zone)return Ga[e]=t.prototype,t.prototype;try{const n=document.createElement("iframe");document.body.appendChild(n);const s=n.contentWindow;if(!s)return t.prototype;const i=s[e].prototype;return document.body.removeChild(n),i?Ga[e]=i:r}catch{return r}}const Za={};function $a(e,t,r){var n;const s=`${e}.${String(r)}`;if(Za[s])return Za[s].call(t);const i=Ha(e),o=null==(n=Object.getOwnPropertyDescriptor(i,r))?void 0:n.get;return o?(Za[s]=o,o.call(t)):t[r]}const Wa={};function Ya(e,t,r){const n=`${e}.${String(r)}`;if(Wa[n])return Wa[n].bind(t);const s=Ha(e)[r];return"function"!=typeof s?t[r]:(Wa[n]=s,s.bind(t))}const Xa={ownerDocument:function(e){return $a("Node",e,"ownerDocument")},childNodes:function(e){return $a("Node",e,"childNodes")},parentNode:function(e){return $a("Node",e,"parentNode")},parentElement:function(e){return $a("Node",e,"parentElement")},textContent:function(e){return $a("Node",e,"textContent")},contains:function(e,t){return Ya("Node",e,"contains")(t)},getRootNode:function(e){return Ya("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?$a("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?$a("Element",e,"shadowRoot"):null},querySelector:function(e,t){return $a("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return $a("Element",e,"querySelectorAll")(t)},mutationObserver:function(){return Ha("MutationObserver").constructor},patch:function(e,t,r){try{if(!(t in e))return()=>{};const n=e[t],s=r(n);return"function"==typeof s&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__rrweb_original__:{enumerable:!1,value:n}})),e[t]=s,()=>{e[t]=n}}catch{return()=>{}}}};function Ja(e){return e.nodeType===e.ELEMENT_NODE}function Ka(e){const t=e&&"host"in e&&"mode"in e&&Xa.host(e)||null;return Boolean(t&&"shadowRoot"in t&&Xa.shadowRoot(t)===e)}function qa(e){return"[object ShadowRoot]"===Object.prototype.toString.call(e)}function Qa(e){try{const r=e.rules||e.cssRules;if(!r)return null;let n=e.href;!n&&e.ownerNode&&(n=e.ownerNode.baseURI);const s=Array.from(r,e=>el(e,n)).join("");return(t=s).includes(" background-clip: text;")&&!t.includes(" -webkit-background-clip: text;")&&(t=t.replace(/\sbackground-clip:\s*text;/g," -webkit-background-clip: text; background-clip: text;")),t}catch(e){return null}var t}function el(e,t){if(function(e){return"styleSheet"in e}(e)){let t;try{t=Qa(e.styleSheet)||function(e){const{cssText:t}=e;if(t.split('"').length<3)return t;const r=["@import",`url(${JSON.stringify(e.href)})`];return""===e.layerName?r.push("layer"):e.layerName&&r.push(`layer(${e.layerName})`),e.supportsText&&r.push(`supports(${e.supportsText})`),e.media.length&&r.push(e.media.mediaText),r.join(" ")+";"}(e)}catch(r){t=e.cssText}return e.styleSheet.href?hl(t,e.styleSheet.href):t}{let r=e.cssText;return function(e){return"selectorText"in e}(e)&&e.selectorText.includes(":")&&(r=function(e){const t=/(\[(?:[\w-]+)[^\\])(:(?:[\w-]+)\])/gm;return e.replace(t,"$1\\$2")}(r)),t?hl(r,t):r}}class tl{constructor(){Ba(this,"idNodeMap",new Map),Ba(this,"nodeMetaMap",new WeakMap)}getId(e){var t;if(!e)return-1;return(null==(t=this.getMeta(e))?void 0:t.id)??-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){const t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(e=>this.removeNodeFromMap(e))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){const r=t.id;this.idNodeMap.set(r,e),this.nodeMetaMap.set(e,t)}replace(e,t){const r=this.getNode(e);if(r){const e=this.nodeMetaMap.get(r);e&&this.nodeMetaMap.set(t,e)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}}function rl({element:e,maskInputOptions:t,tagName:r,type:n,value:s,maskInputFn:i}){let o=s||"";const a=n&&nl(n);return(t[r.toLowerCase()]||a&&t[a])&&(o=i?i(o,e):"*".repeat(o.length)),o}function nl(e){return e.toLowerCase()}const sl="__rrweb_original__";function il(e){const t=e.type;return e.hasAttribute("data-rr-is-password")?"password":t?nl(t):null}function ol(e,t){let r;try{r=new URL(e,t??window.location.href)}catch(e){return null}const n=r.pathname.match(/\.([0-9a-z]+)(?:$)/i);return(null==n?void 0:n[1])??null}const al=/url\((?:(')([^']*)'|(")(.*?)"|([^)]*))\)/gm,ll=/^(?:[a-z+]+:)?\/\//i,cl=/^www\..*/i,ul=/^(data:)([^,]*),(.*)/i;function hl(e,t){return(e||"").replace(al,(e,r,n,s,i,o)=>{const a=n||i||o,l=r||s||"";if(!a)return e;if(ll.test(a)||cl.test(a))return`url(${l}${a}${l})`;if(ul.test(a))return`url(${l}${a}${l})`;if("/"===a[0])return`url(${l}${function(e){let t="";return t=e.indexOf("//")>-1?e.split("/").slice(0,3).join("/"):e.split("/")[0],t=t.split("?")[0],t}(t)+a}${l})`;const c=t.split("/"),u=a.split("/");c.pop();for(const e of u)"."!==e&&(".."===e?c.pop():c.push(e));return`url(${l}${c.join("/")}${l})`})}function pl(e,t=!1){return t?e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,""):e.replace(/(\/\*[^*]*\*\/)|[\s;]/g,"").replace(/0px/g,"0")}function dl(e,t){return function(e,t,r=!1){const n=Array.from(t.childNodes),s=[];let i=0;if(n.length>1&&e&&"string"==typeof e){let t=pl(e,r);const o=t.length/e.length;for(let a=1;a2&&""===p[0]&&""!==n[a-1].textContent)d=t.indexOf(h,1);else if(1===p.length){if(h=h.substring(0,h.length-1),p=t.split(h),p.length<=1)return s.push(e),s;u=c+1}else u===l.length-1&&(d=t.indexOf(h));if(p.length>=2&&u>c){const e=n[a-1].textContent;if(e&&"string"==typeof e){const r=pl(e).length;d=t.indexOf(h,r)}-1===d&&(d=p[0].length)}if(-1!==d){let a=Math.floor(d/o);for(;a>0&&a50*n.length)return s.push(e),s;const l=pl(e.substring(0,a),r);if(l.length===d){s.push(e.substring(0,a)),e=e.substring(a),t=t.substring(d);break}l.length=t.length);){let i=n(vl);if(","===i.slice(-1))i=Sl(e,i.substring(0,i.length-1)),s.push(i);else{let n="";i=Sl(e,i);let o=!1;for(;;){const e=t.charAt(r);if(""===e){s.push((i+n).trim());break}if(o)")"===e&&(o=!1);else{if(","===e){r+=1,s.push((i+n).trim());break}"("===e&&(o=!0)}n+=e,r+=1}}}return s.join(", ")}(e,n):"style"===r?hl(n,El(e)):"object"===t&&"data"===r?Sl(e,n):n:n}function kl(e,t,r){return["video","audio"].includes(e)&&"autoplay"===t}function xl(e,t,r){if(!e)return!1;if(e.nodeType!==e.ELEMENT_NODE)return!!r&&xl(Xa.parentNode(e),t,r);for(let r=e.classList.length;r--;){const n=e.classList[r];if(t.test(n))return!0}return!!r&&xl(Xa.parentNode(e),t,r)}function Ol(e,t,r,n){let s;if(Ja(e)){if(s=e,!Xa.childNodes(s).length)return!1}else{if(null===Xa.parentElement(e))return!1;s=Xa.parentElement(e)}try{if("string"==typeof t){if(n){if(s.closest(`.${t}`))return!0}else if(s.classList.contains(t))return!0}else if(xl(s,t,n))return!0;if(r)if(n){if(s.closest(r))return!0}else if(s.matches(r))return!0}catch(e){}return!1}function Al(e,t){const{doc:r,mirror:n,blockClass:s,blockSelector:i,needsMask:o,inlineStylesheet:a,maskInputOptions:l={},maskTextFn:c,maskInputFn:u,dataURLOptions:h={},inlineImages:p,recordCanvas:d,keepIframeSrcFn:f,newlyAddedElement:m=!1,cssCaptured:g=!1}=t,y=function(e,t){if(!t.hasNode(e))return;const r=t.getId(e);return 1===r?void 0:r}(r,n);switch(e.nodeType){case e.DOCUMENT_NODE:return"CSS1Compat"!==e.compatMode?{type:ja.Document,childNodes:[],compatMode:e.compatMode}:{type:ja.Document,childNodes:[]};case e.DOCUMENT_TYPE_NODE:return{type:ja.DocumentType,name:e.name,publicId:e.publicId,systemId:e.systemId,rootId:y};case e.ELEMENT_NODE:return function(e,t){const{doc:r,blockClass:n,blockSelector:s,inlineStylesheet:i,maskInputOptions:o={},maskInputFn:a,dataURLOptions:l={},inlineImages:c,recordCanvas:u,keepIframeSrcFn:h,newlyAddedElement:p=!1,rootId:d}=t,f=function(e,t,r){try{if("string"==typeof t){if(e.classList.contains(t))return!0}else for(let r=e.classList.length;r--;){const n=e.classList[r];if(t.test(n))return!0}if(r)return e.matches(r)}catch(e){}return!1}(e,n,s),m=function(e){if(e instanceof HTMLFormElement)return"form";const t=nl(e.tagName);return ml.test(t)?"div":t}(e);let g={};const y=e.attributes.length;for(let t=0;tt.href===e.href);let n=null;t&&(n=Qa(t)),n&&(delete g.rel,delete g.href,g._cssText=n)}if("style"===m&&e.sheet){let t=Qa(e.sheet);t&&(e.childNodes.length>1&&(t=dl(t,e)),g._cssText=t)}if(["input","textarea","select"].includes(m)){const t=e.value,r=e.checked;"radio"!==g.type&&"checkbox"!==g.type&&"submit"!==g.type&&"button"!==g.type&&t?g.value=rl({element:e,type:il(e),tagName:m,value:t,maskInputOptions:o,maskInputFn:a}):r&&(g.checked=r)}"option"===m&&(e.selected&&!o.select?g.selected=!0:delete g.selected);"dialog"===m&&e.open&&(g.rr_open_mode=e.matches("dialog:modal")?"modal":"non-modal");if("canvas"===m&&u)if("2d"===e.__context)(function(e){const t=e.getContext("2d");if(!t)return!0;for(let r=0;r0!==e))return!1}return!0})(e)||(g.rr_dataURL=e.toDataURL(l.type,l.quality));else if(!("__context"in e)){const t=e.toDataURL(l.type,l.quality),n=r.createElement("canvas");n.width=e.width,n.height=e.height;t!==n.toDataURL(l.type,l.quality)&&(g.rr_dataURL=t)}if("img"===m&&c){yl||(yl=r.createElement("canvas"),wl=yl.getContext("2d"));const t=e,n=t.currentSrc||t.getAttribute("src")||"",s=t.crossOrigin,i=()=>{t.removeEventListener("load",i);try{yl.width=t.naturalWidth,yl.height=t.naturalHeight,wl.drawImage(t,0,0),g.rr_dataURL=yl.toDataURL(l.type,l.quality)}catch(e){if("anonymous"!==t.crossOrigin)return t.crossOrigin="anonymous",void(t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i));console.warn(`Cannot inline img src=${n}! Error: ${e}`)}"anonymous"===t.crossOrigin&&(s?g.crossOrigin=s:t.removeAttribute("crossorigin"))};t.complete&&0!==t.naturalWidth?i():t.addEventListener("load",i)}if(["audio","video"].includes(m)){const t=g;t.rr_mediaState=e.paused?"paused":"played",t.rr_mediaCurrentTime=e.currentTime,t.rr_mediaPlaybackRate=e.playbackRate,t.rr_mediaMuted=e.muted,t.rr_mediaLoop=e.loop,t.rr_mediaVolume=e.volume}p||(e.scrollLeft&&(g.rr_scrollLeft=e.scrollLeft),e.scrollTop&&(g.rr_scrollTop=e.scrollTop));if(f){const{width:t,height:r}=e.getBoundingClientRect();g={class:g.class,rr_width:`${t}px`,rr_height:`${r}px`}}"iframe"!==m||h(g.src)||(e.contentDocument||(g.rr_src=g.src),delete g.src);let w;try{customElements.get(m)&&(w=!0)}catch(e){}return{type:ja.Element,tagName:m,attributes:g,childNodes:[],isSVG:Cl(e)||void 0,needBlock:f,rootId:d,isCustom:w}}(e,{doc:r,blockClass:s,blockSelector:i,inlineStylesheet:a,maskInputOptions:l,maskInputFn:u,dataURLOptions:h,inlineImages:p,recordCanvas:d,keepIframeSrcFn:f,newlyAddedElement:m,rootId:y});case e.TEXT_NODE:return function(e,t){const{needsMask:r,maskTextFn:n,rootId:s,cssCaptured:i}=t,o=Xa.parentNode(e),a=o&&o.tagName;let l="";const c="STYLE"===a||void 0,u="SCRIPT"===a||void 0;u?l="SCRIPT_PLACEHOLDER":i||(l=Xa.textContent(e),c&&l&&(l=hl(l,El(t.doc))));!c&&!u&&l&&r&&(l=n?n(l,Xa.parentElement(e)):l.replace(/[\S]/g,"*"));return{type:ja.Text,textContent:l||"",rootId:s}}(e,{doc:r,needsMask:o,maskTextFn:c,rootId:y,cssCaptured:g});case e.CDATA_SECTION_NODE:return{type:ja.CDATA,textContent:"",rootId:y};case e.COMMENT_NODE:return{type:ja.Comment,textContent:Xa.textContent(e)||"",rootId:y};default:return!1}}function Il(e){return null==e?"":e.toLowerCase()}function Rl(e){return!0===e||"all"===e?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:"all"===e,headMetaDescKeywords:"all"===e,headTitleMutations:"all"===e}:e||{}}function Ml(e,t){const{doc:r,mirror:n,blockClass:s,blockSelector:i,maskTextClass:o,maskTextSelector:a,skipChild:l=!1,inlineStylesheet:c=!0,maskInputOptions:u={},maskTextFn:h,maskInputFn:p,slimDOMOptions:d,dataURLOptions:f={},inlineImages:m=!1,recordCanvas:g=!1,onSerialize:y,onIframeLoad:w,iframeLoadTimeout:v=5e3,onStylesheetLoad:b,stylesheetLoadTimeout:_=5e3,keepIframeSrcFn:S=()=>!1,newlyAddedElement:C=!1,cssCaptured:E=!1}=t;let{needsMask:T}=t,{preserveWhiteSpace:k=!0}=t;if(!T){T=Ol(e,o,a,void 0===T)}const x=Al(e,{doc:r,mirror:n,blockClass:s,blockSelector:i,needsMask:T,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,dataURLOptions:f,inlineImages:m,recordCanvas:g,keepIframeSrcFn:S,newlyAddedElement:C,cssCaptured:E});if(!x)return console.warn(e,"not serialized"),null;let O;O=n.hasNode(e)?n.getId(e):function(e,t){if(t.comment&&e.type===ja.Comment)return!0;if(e.type===ja.Element){if(t.script&&("script"===e.tagName||"link"===e.tagName&&("preload"===e.attributes.rel&&"script"===e.attributes.as||"modulepreload"===e.attributes.rel)||"link"===e.tagName&&"prefetch"===e.attributes.rel&&"string"==typeof e.attributes.href&&"js"===ol(e.attributes.href)))return!0;if(t.headFavicon&&("link"===e.tagName&&"shortcut icon"===e.attributes.rel||"meta"===e.tagName&&(Il(e.attributes.name).match(/^msapplication-tile(image|color)$/)||"application-name"===Il(e.attributes.name)||"icon"===Il(e.attributes.rel)||"apple-touch-icon"===Il(e.attributes.rel)||"shortcut icon"===Il(e.attributes.rel))))return!0;if("meta"===e.tagName){if(t.headMetaDescKeywords&&Il(e.attributes.name).match(/^description|keywords$/))return!0;if(t.headMetaSocial&&(Il(e.attributes.property).match(/^(og|twitter|fb):/)||Il(e.attributes.name).match(/^(og|twitter):/)||"pinterest"===Il(e.attributes.name)))return!0;if(t.headMetaRobots&&("robots"===Il(e.attributes.name)||"googlebot"===Il(e.attributes.name)||"bingbot"===Il(e.attributes.name)))return!0;if(t.headMetaHttpEquiv&&void 0!==e.attributes["http-equiv"])return!0;if(t.headMetaAuthorship&&("author"===Il(e.attributes.name)||"generator"===Il(e.attributes.name)||"framework"===Il(e.attributes.name)||"publisher"===Il(e.attributes.name)||"progid"===Il(e.attributes.name)||Il(e.attributes.property).match(/^article:/)||Il(e.attributes.property).match(/^product:/)))return!0;if(t.headMetaVerification&&("google-site-verification"===Il(e.attributes.name)||"yandex-verification"===Il(e.attributes.name)||"csrf-token"===Il(e.attributes.name)||"p:domain_verify"===Il(e.attributes.name)||"verify-v1"===Il(e.attributes.name)||"verification"===Il(e.attributes.name)||"shopify-checkout-api-token"===Il(e.attributes.name)))return!0}}return!1}(x,d)||!k&&x.type===ja.Text&&!x.textContent.replace(/^\s+|\s+$/gm,"").length?-2:gl();const A=Object.assign(x,{id:O});if(n.add(e,A),-2===O)return null;y&&y(e);let I=!l;if(A.type===ja.Element){I=I&&!A.needBlock,delete A.needBlock;const t=Xa.shadowRoot(e);t&&qa(t)&&(A.isShadowHost=!0)}if((A.type===ja.Document||A.type===ja.Element)&&I){d.headWhitespace&&A.type===ja.Element&&"head"===A.tagName&&(k=!1);const t={doc:r,mirror:n,blockClass:s,blockSelector:i,needsMask:T,maskTextClass:o,maskTextSelector:a,skipChild:l,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,slimDOMOptions:d,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:k,onSerialize:y,onIframeLoad:w,iframeLoadTimeout:v,onStylesheetLoad:b,stylesheetLoadTimeout:_,keepIframeSrcFn:S,cssCaptured:!1};if(A.type===ja.Element&&"textarea"===A.tagName&&void 0!==A.attributes.value);else{A.type===ja.Element&&void 0!==A.attributes._cssText&&"string"==typeof A.attributes._cssText&&(t.cssCaptured=!0);for(const r of Array.from(Xa.childNodes(e))){const e=Ml(r,t);e&&A.childNodes.push(e)}}let C=null;if(Ja(e)&&(C=Xa.shadowRoot(e)))for(const e of Array.from(Xa.childNodes(C))){const r=Ml(e,t);r&&(qa(C)&&(r.isShadow=!0),A.childNodes.push(r))}}const R=Xa.parentNode(e);return R&&Ka(R)&&qa(R)&&(A.isShadow=!0),A.type===ja.Element&&"iframe"===A.tagName&&function(e,t,r){const n=e.contentWindow;if(!n)return;let s,i=!1;try{s=n.document.readyState}catch(e){return}if("complete"!==s){const n=setTimeout(()=>{i||(t(),i=!0)},r);return void e.addEventListener("load",()=>{clearTimeout(n),i=!0,t()})}const o="about:blank";if(n.location.href!==o||e.src===o||""===e.src)return setTimeout(t,0),e.addEventListener("load",t);e.addEventListener("load",t)}(e,()=>{const t=e.contentDocument;if(t&&w){const r=Ml(t,{doc:t,mirror:n,blockClass:s,blockSelector:i,needsMask:T,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,slimDOMOptions:d,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:k,onSerialize:y,onIframeLoad:w,iframeLoadTimeout:v,onStylesheetLoad:b,stylesheetLoadTimeout:_,keepIframeSrcFn:S});r&&w(e,r)}},v),A.type===ja.Element&&"link"===A.tagName&&"string"==typeof A.attributes.rel&&("stylesheet"===A.attributes.rel||"preload"===A.attributes.rel&&"string"==typeof A.attributes.href&&"css"===ol(A.attributes.href))&&function(e,t,r){let n,s=!1;try{n=e.sheet}catch(e){return}if(n)return;const i=setTimeout(()=>{s||(t(),s=!0)},r);e.addEventListener("load",()=>{clearTimeout(i),s=!0,t()})}(e,()=>{if(b){const t=Ml(e,{doc:r,mirror:n,blockClass:s,blockSelector:i,needsMask:T,maskTextClass:o,maskTextSelector:a,skipChild:!1,inlineStylesheet:c,maskInputOptions:u,maskTextFn:h,maskInputFn:p,slimDOMOptions:d,dataURLOptions:f,inlineImages:m,recordCanvas:g,preserveWhiteSpace:k,onSerialize:y,onIframeLoad:w,iframeLoadTimeout:v,onStylesheetLoad:b,stylesheetLoadTimeout:_,keepIframeSrcFn:S});t&&b(e,t)}},_),A}function Nl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Pl(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var Ll={exports:{}},Dl=String,Ul=function(){return{isColorSupported:!1,reset:Dl,bold:Dl,dim:Dl,italic:Dl,underline:Dl,inverse:Dl,hidden:Dl,strikethrough:Dl,black:Dl,red:Dl,green:Dl,yellow:Dl,blue:Dl,magenta:Dl,cyan:Dl,white:Dl,gray:Dl,bgBlack:Dl,bgRed:Dl,bgGreen:Dl,bgYellow:Dl,bgBlue:Dl,bgMagenta:Dl,bgCyan:Dl,bgWhite:Dl}};Ll.exports=Ul(),Ll.exports.createColors=Ul;var Fl=Ll.exports;const Bl=Pl(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let jl=Fl,zl=Bl,Vl=class e extends Error{constructor(t,r,n,s,i,o){super(t),this.name="CssSyntaxError",this.reason=t,i&&(this.file=i),s&&(this.source=s),o&&(this.plugin=o),void 0!==r&&void 0!==n&&("number"==typeof r?(this.line=r,this.column=n):(this.line=r.line,this.column=r.column,this.endLine=n.line,this.endColumn=n.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;null==e&&(e=jl.isColorSupported),zl&&e&&(t=zl(t));let r,n,s=t.split(/\r?\n/),i=Math.max(this.line-3,0),o=Math.min(this.line+2,s.length),a=String(o).length;if(e){let{bold:e,gray:t,red:s}=jl.createColors(!0);r=t=>e(s(t)),n=e=>t(e)}else r=n=e=>e;return s.slice(i,o).map((e,t)=>{let s=i+1+t,o=" "+(" "+s).slice(-a)+" | ";if(s===this.line){let t=n(o.replace(/\d/g," "))+e.slice(0,this.column-1).replace(/[^\t]/g," ");return r(">")+n(o)+e+"\n "+t+r("^")}return" "+n(o)+e}).join("\n")}toString(){let e=this.showSourceCode();return e&&(e="\n\n"+e+"\n"),this.name+": "+this.message+e}};var Gl=Vl;Vl.default=Vl;var Hl={};Hl.isClean=Symbol("isClean"),Hl.my=Symbol("my");const Zl={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let $l=class{constructor(e){this.builder=e}atrule(e,t){let r="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(void 0!==e.raws.afterName?r+=e.raws.afterName:n&&(r+=" "),e.nodes)this.block(e,r+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(r+n+s,e)}}beforeAfter(e,t){let r;r="decl"===e.type?this.raw(e,null,"beforeDecl"):"comment"===e.type?this.raw(e,null,"beforeComment"):"before"===t?this.raw(e,null,"beforeRule"):this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&"root"!==n.type;)s+=1,n=n.parent;if(r.includes("\n")){let t=this.raw(e,null,"indent");if(t.length)for(let e=0;e0&&"comment"===e.nodes[t].type;)t-=1;let r=this.raw(e,"semicolon");for(let n=0;n{if(n=e.raws[t],void 0!==n)return!1})}var o;return void 0===n&&(n=Zl[r]),i.rawCache[r]=n,n}rawBeforeClose(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length>0&&void 0!==e.raws.after)return t=e.raws.after,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let r;return e.walkComments(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeDecl"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeDecl(e,t){let r;return e.walkDecls(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeRule"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeOpen(e){let t;return e.walk(e=>{if("decl"!==e.type&&(t=e.raws.between,void 0!==t))return!1}),t}rawBeforeRule(e){let t;return e.walk(r=>{if(r.nodes&&(r.parent!==e||e.first!==r)&&void 0!==r.raws.before)return t=r.raws.before,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(e=>{if(void 0!==e.raws.between)return t=e.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(e=>{if(e.nodes&&0===e.nodes.length&&(t=e.raws.after,void 0!==t))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(r=>{let n=r.parent;if(n&&n!==e&&n.parent&&n.parent===e&&void 0!==r.raws.before){let e=r.raws.before.split("\n");return t=e[e.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length&&"decl"===e.last.type&&(t=e.raws.semicolon,void 0!==t))return!1}),t}rawValue(e,t){let r=e[t],n=e.raws[t];return n&&n.value===r?n.raw:r}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};var Wl=$l;$l.default=$l;let Yl=Wl;function Xl(e,t){new Yl(t).stringify(e)}var Jl=Xl;Xl.default=Xl;let{isClean:Kl,my:ql}=Hl,Ql=Gl,ec=Wl,tc=Jl;function rc(e,t){let r=new e.constructor;for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;if("proxyCache"===n)continue;let s=e[n],i=typeof s;"parent"===n&&"object"===i?t&&(r[n]=t):"source"===n?r[n]=s:Array.isArray(s)?r[n]=s.map(e=>rc(e,r)):("object"===i&&null!==s&&(s=rc(s)),r[n]=s)}return r}let nc=class{constructor(e={}){this.raws={},this[Kl]=!1,this[ql]=!0;for(let t in e)if("nodes"===t){this.nodes=[];for(let r of e[t])"function"==typeof r.clone?this.append(r.clone()):this.append(r)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=rc(this);for(let r in e)t[r]=e[r];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:r,start:n}=this.rangeBy(t);return this.source.input.error(e,{column:n.column,line:n.line},{column:r.column,line:r.line},t)}return new Ql(e)}getProxyProcessor(){return{get:(e,t)=>"proxyOf"===t?e:"root"===t?()=>e.root().toProxy():e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"prop"!==t&&"value"!==t&&"name"!==t&&"params"!==t&&"important"!==t&&"text"!==t||e.markDirty()),!0)}}markDirty(){if(this[Kl]){this[Kl]=!1;let e=this;for(;e=e.parent;)e[Kl]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){let n=(t=this.toString()).indexOf(e.word);-1!==n&&(r=this.positionInside(n,t))}return r}positionInside(e,t){let r=t||this.toString(),n=this.source.start.column,s=this.source.start.line;for(let t=0;t"object"==typeof e&&e.toJSON?e.toJSON(null,t):e);else if("object"==typeof n&&n.toJSON)r[e]=n.toJSON(null,t);else if("source"===e){let i=t.get(n.input);null==i&&(i=s,t.set(n.input,s),s++),r[e]={end:n.end,inputId:i,start:n.start}}else r[e]=n}return n&&(r.inputs=[...t.keys()].map(e=>e.toJSON())),r}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=tc){e.stringify&&(e=e.stringify);let t="";return e(this,e=>{t+=e}),t}warn(e,t,r){let n={node:this};for(let e in r)n[e]=r[e];return e.warn(t,n)}get proxyOf(){return this}};var sc=nc;nc.default=nc;let ic=sc,oc=class extends ic{constructor(e){e&&void 0!==e.value&&"string"!=typeof e.value&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var ac=oc;oc.default=oc;var lc={nanoid:(e=21)=>{let t="",r=e;for(;r--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t}};let{SourceMapConsumer:cc,SourceMapGenerator:uc}=Bl,{existsSync:hc,readFileSync:pc}=Bl,{dirname:dc,join:fc}=Bl;let mc=class{constructor(e,t){if(!1===t.map)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let r=t.map?t.map.prev:void 0,n=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=dc(this.mapFile)),n&&(this.text=n)}consumer(){return this.consumerCache||(this.consumerCache=new cc(this.text)),this.consumerCache}decodeInline(e){if(/^data:application\/json;charset=utf-?8,/.test(e)||/^data:application\/json,/.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(e)||/^data:application\/json;base64,/.test(e))return t=e.substr(RegExp.lastMatch.length),Buffer?Buffer.from(t,"base64").toString():window.atob(t);var t;let r=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+r)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return"object"==typeof e&&("string"==typeof e.mappings||"string"==typeof e._mappings||Array.isArray(e.sections))}loadAnnotation(e){let t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(!t)return;let r=e.lastIndexOf(t.pop()),n=e.indexOf("*/",r);r>-1&&n>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,n)))}loadFile(e){if(this.root=dc(e),hc(e))return this.mapFile=e,pc(e,"utf-8").toString().trim()}loadMap(e,t){if(!1===t)return!1;if(t){if("string"==typeof t)return t;if("function"!=typeof t){if(t instanceof cc)return uc.fromSourceMap(t).toString();if(t instanceof uc)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}{let r=t(e);if(r){let e=this.loadFile(r);if(!e)throw new Error("Unable to load previous source map: "+r.toString());return e}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let t=this.annotation;return e&&(t=fc(dc(e),t)),this.loadFile(t)}}}startWith(e,t){return!!e&&e.substr(0,t.length)===t}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var gc=mc;mc.default=mc;let{SourceMapConsumer:yc,SourceMapGenerator:wc}=Bl,{fileURLToPath:vc,pathToFileURL:bc}=Bl,{isAbsolute:_c,resolve:Sc}=Bl,{nanoid:Cc}=lc,Ec=Bl,Tc=Gl,kc=gc,xc=Symbol("fromOffsetCache"),Oc=Boolean(yc&&wc),Ac=Boolean(Sc&&_c),Ic=class{constructor(e,t={}){if(null==e||"object"==typeof e&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!Ac||/^\w+:\/\//.test(t.from)||_c(t.from)?this.file=t.from:this.file=Sc(t.from)),Ac&&Oc){let e=new kc(this.css,t);if(e.text){this.map=e;let t=e.consumer().file;!this.file&&t&&(this.file=this.mapResolve(t))}}this.file||(this.id=""),this.map&&(this.map.file=this.from)}error(e,t,r,n={}){let s,i,o;if(t&&"object"==typeof t){let e=t,n=r;if("number"==typeof e.offset){let n=this.fromOffset(e.offset);t=n.line,r=n.col}else t=e.line,r=e.column;if("number"==typeof n.offset){let e=this.fromOffset(n.offset);i=e.line,o=e.col}else i=n.line,o=n.column}else if(!r){let e=this.fromOffset(t);t=e.line,r=e.col}let a=this.origin(t,r,i,o);return s=a?new Tc(e,void 0===a.endLine?a.line:{column:a.column,line:a.line},void 0===a.endLine?a.column:{column:a.endColumn,line:a.endLine},a.source,a.file,n.plugin):new Tc(e,void 0===i?t:{column:r,line:t},void 0===i?r:{column:o,line:i},this.css,this.file,n.plugin),s.input={column:r,endColumn:o,endLine:i,line:t,source:this.css},this.file&&(bc&&(s.input.url=bc(this.file).toString()),s.input.file=this.file),s}fromOffset(e){let t,r;if(this[xc])r=this[xc];else{let e=this.css.split("\n");r=new Array(e.length);let t=0;for(let n=0,s=e.length;n=t)n=r.length-1;else{let t,s=r.length-2;for(;n>1),e=r[t+1])){n=t;break}n=t+1}}return{col:e-r[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:Sc(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,r,n){if(!this.map)return!1;let s,i,o=this.map.consumer(),a=o.originalPositionFor({column:t,line:e});if(!a.source)return!1;"number"==typeof r&&(s=o.originalPositionFor({column:n,line:r})),i=_c(a.source)?bc(a.source):new URL(a.source,this.map.consumer().sourceRoot||bc(this.map.mapFile));let l={column:a.column,endColumn:s&&s.column,endLine:s&&s.line,line:a.line,url:i.toString()};if("file:"===i.protocol){if(!vc)throw new Error("file: protocol is not available in this PostCSS build");l.file=vc(i)}let c=o.sourceContentFor(a.source);return c&&(l.source=c),l}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])null!=this[t]&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};var Rc=Ic;Ic.default=Ic,Ec&&Ec.registerInput&&Ec.registerInput(Ic);let{SourceMapConsumer:Mc,SourceMapGenerator:Nc}=Bl,{dirname:Pc,relative:Lc,resolve:Dc,sep:Uc}=Bl,{pathToFileURL:Fc}=Bl,Bc=Rc,jc=Boolean(Mc&&Nc),zc=Boolean(Pc&&Dc&&Lc&&Uc);var Vc=class{constructor(e,t,r,n){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=n,this.originalCSS=n,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let t="\n";this.css.includes("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"}applyPrevMaps(){for(let e of this.previous()){let t,r=this.toUrl(this.path(e.file)),n=e.root||Pc(e.file);!1===this.mapOpts.sourcesContent?(t=new Mc(e.text),t.sourcesContent&&(t.sourcesContent=null)):t=e.consumer(),this.map.applySourceMap(t,r,this.toUrl(this.path(n)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],"comment"===e.type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),zc&&jc&&this.isMap())return this.generateMap();{let e="";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=Nc.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new Nc({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):""});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new Nc({file:this.outputFile(),ignoreInvalidMapping:!0});let e,t,r=1,n=1,s="",i={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(o,a,l)=>{if(this.css+=o,a&&"end"!==l&&(i.generated.line=r,i.generated.column=n-1,a.source&&a.source.start?(i.source=this.sourcePath(a),i.original.line=a.source.start.line,i.original.column=a.source.start.column-1,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,this.map.addMapping(i))),e=o.match(/\n/g),e?(r+=e.length,t=o.lastIndexOf("\n"),n=o.length-t):n+=o.length,a&&"start"!==l){let e=a.parent||{raws:{}};("decl"===a.type||"atrule"===a.type&&!a.nodes)&&a===e.last&&!e.raws.semicolon||(a.source&&a.source.end?(i.source=this.sourcePath(a),i.original.line=a.source.end.line,i.original.column=a.source.end.column-1,i.generated.line=r,i.generated.column=n-2,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,i.generated.line=r,i.generated.column=n-1,this.map.addMapping(i)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(e=>e.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(e=>e.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(e=>e.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(e){if(this.mapOpts.absolute)return e;if(60===e.charCodeAt(0))return e;if(/^\w+:\/\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let r=this.opts.to?Pc(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(r=Pc(Dc(r,this.mapOpts.annotation)));let n=Lc(r,e);return this.memoizedPaths.set(e,n),n}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new Bc(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let r=t.source.input.from;if(r&&!e[r]){e[r]=!0;let n=this.usesFileUrls?this.toFileUrl(r):this.toUrl(this.path(r));this.map.setSourceContent(n,t.source.input.css)}}});else if(this.css){let e=this.opts.from?this.toUrl(this.path(this.opts.from)):"";this.map.setSourceContent(e,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(Fc){let t=Fc(e).toString();return this.memoizedFileURLs.set(e,t),t}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;"\\"===Uc&&(e=e.replace(/\\/g,"/"));let r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r}};let Gc=sc,Hc=class extends Gc{constructor(e){super(e),this.type="comment"}};var Zc=Hc;Hc.default=Hc;let $c,Wc,Yc,Xc,{isClean:Jc,my:Kc}=Hl,qc=ac,Qc=Zc,eu=sc;function tu(e){return e.map(e=>(e.nodes&&(e.nodes=tu(e.nodes)),delete e.source,e))}function ru(e){if(e[Jc]=!1,e.proxyOf.nodes)for(let t of e.proxyOf.nodes)ru(t)}let nu=class e extends eu{append(...e){for(let t of e){let e=this.normalize(t,this.last);for(let t of e)this.proxyOf.nodes.push(t)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t,r,n=this.getIterator();for(;this.indexes[n]"proxyOf"===t?e:e[t]?"each"===t||"string"==typeof t&&t.startsWith("walk")?(...r)=>e[t](...r.map(e=>"function"==typeof e?(t,r)=>e(t.toProxy(),r):e)):"every"===t||"some"===t?r=>e[t]((e,...t)=>r(e.toProxy(),...t)):"root"===t?()=>e.root().toProxy():"nodes"===t?e.nodes.map(e=>e.toProxy()):"first"===t||"last"===t?e[t].toProxy():e[t]:e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"name"!==t&&"params"!==t&&"selector"!==t||e.markDirty()),!0)}}index(e){return"number"==typeof e?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let r,n=this.index(e),s=this.normalize(t,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(let e of s)this.proxyOf.nodes.splice(n+1,0,e);for(let e in this.indexes)r=this.indexes[e],n(t[Kc]||e.rebuild(t),(t=t.proxyOf).parent&&t.parent.removeChild(t),t[Jc]&&ru(t),void 0===t.raws.before&&r&&void 0!==r.raws.before&&(t.raws.before=r.raws.before.replace(/\S/g,"")),t.parent=this.proxyOf,t))}prepend(...e){e=e.reverse();for(let t of e){let e=this.normalize(t,this.first,"prepend").reverse();for(let t of e)this.proxyOf.nodes.unshift(t);for(let t in this.indexes)this.indexes[t]=this.indexes[t]+e.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){let t;e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);for(let r in this.indexes)t=this.indexes[r],t>=e&&(this.indexes[r]=t-1);return this.markDirty(),this}replaceValues(e,t,r){return r||(r=t,t={}),this.walkDecls(n=>{t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,r))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,r)=>{let n;try{n=e(t,r)}catch(e){throw t.addToError(e)}return!1!==n&&t.walk&&(n=t.walk(e)),n})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("atrule"===r.type&&e.test(r.name))return t(r,n)}):this.walk((r,n)=>{if("atrule"===r.type&&r.name===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("atrule"===e.type)return t(e,r)}))}walkComments(e){return this.walk((t,r)=>{if("comment"===t.type)return e(t,r)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("decl"===r.type&&e.test(r.prop))return t(r,n)}):this.walk((r,n)=>{if("decl"===r.type&&r.prop===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("decl"===e.type)return t(e,r)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("rule"===r.type&&e.test(r.selector))return t(r,n)}):this.walk((r,n)=>{if("rule"===r.type&&r.selector===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("rule"===e.type)return t(e,r)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};nu.registerParse=e=>{$c=e},nu.registerRule=e=>{Wc=e},nu.registerAtRule=e=>{Yc=e},nu.registerRoot=e=>{Xc=e};var su=nu;nu.default=nu,nu.rebuild=e=>{"atrule"===e.type?Object.setPrototypeOf(e,Yc.prototype):"rule"===e.type?Object.setPrototypeOf(e,Wc.prototype):"decl"===e.type?Object.setPrototypeOf(e,qc.prototype):"comment"===e.type?Object.setPrototypeOf(e,Qc.prototype):"root"===e.type&&Object.setPrototypeOf(e,Xc.prototype),e[Kc]=!0,e.nodes&&e.nodes.forEach(e=>{nu.rebuild(e)})};let iu,ou,au=su,lu=class extends au{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new iu(new ou,this,e).stringify()}};lu.registerLazyResult=e=>{iu=e},lu.registerProcessor=e=>{ou=e};var cu=lu;lu.default=lu;let uu={};var hu=function(e){uu[e]||(uu[e]=!0,"undefined"!=typeof console&&console.warn&&console.warn(e))};let pu=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let e=t.node.rangeBy(t);this.line=e.start.line,this.column=e.start.column,this.endLine=e.end.line,this.endColumn=e.end.column}for(let e in t)this[e]=t[e]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var du=pu;pu.default=pu;let fu=du,mu=class{constructor(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let r=new fu(e,t);return this.messages.push(r),r}warnings(){return this.messages.filter(e=>"warning"===e.type)}get content(){return this.css}};var gu=mu;mu.default=mu;const yu="'".charCodeAt(0),wu='"'.charCodeAt(0),vu="\\".charCodeAt(0),bu="/".charCodeAt(0),_u="\n".charCodeAt(0),Su=" ".charCodeAt(0),Cu="\f".charCodeAt(0),Eu="\t".charCodeAt(0),Tu="\r".charCodeAt(0),ku="[".charCodeAt(0),xu="]".charCodeAt(0),Ou="(".charCodeAt(0),Au=")".charCodeAt(0),Iu="{".charCodeAt(0),Ru="}".charCodeAt(0),Mu=";".charCodeAt(0),Nu="*".charCodeAt(0),Pu=":".charCodeAt(0),Lu="@".charCodeAt(0),Du=/[\t\n\f\r "#'()/;[\\\]{}]/g,Uu=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,Fu=/.[\r\n"'(/\\]/,Bu=/[\da-f]/i;let ju=su,zu=class extends ju{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};var Vu=zu;zu.default=zu,ju.registerAtRule(zu);let Gu,Hu,Zu=su,$u=class extends Zu{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,r){let n=super.normalize(e);if(t)if("prepend"===r)this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let e of n)e.raws.before=t.raws.before;return n}removeChild(e,t){let r=this.index(e);return!t&&0===r&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[r].raws.before),super.removeChild(e)}toResult(e={}){return new Gu(new Hu,this,e).stringify()}};$u.registerLazyResult=e=>{Gu=e},$u.registerProcessor=e=>{Hu=e};var Wu=$u;$u.default=$u,Zu.registerRoot($u);let Yu={comma:e=>Yu.split(e,[","],!0),space:e=>Yu.split(e,[" ","\n","\t"]),split(e,t,r){let n=[],s="",i=!1,o=0,a=!1,l="",c=!1;for(let r of e)c?c=!1:"\\"===r?c=!0:a?r===l&&(a=!1):'"'===r||"'"===r?(a=!0,l=r):"("===r?o+=1:")"===r?o>0&&(o-=1):0===o&&t.includes(r)&&(i=!0),i?(""!==s&&n.push(s.trim()),s="",i=!1):s+=r;return(r||""!==s)&&n.push(s.trim()),n}};var Xu=Yu;Yu.default=Yu;let Ju=su,Ku=Xu,qu=class extends Ju{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Ku.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,r=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(r)}};var Qu=qu;qu.default=qu,Ju.registerRule(qu);let eh=ac,th=function(e,t={}){let r,n,s,i,o,a,l,c,u,h,p=e.css.valueOf(),d=t.ignoreErrors,f=p.length,m=0,g=[],y=[];function w(t){throw e.error("Unclosed "+t,m)}return{back:function(e){y.push(e)},endOfFile:function(){return 0===y.length&&m>=f},nextToken:function(e){if(y.length)return y.pop();if(m>=f)return;let t=!!e&&e.ignoreUnclosed;switch(r=p.charCodeAt(m),r){case _u:case Su:case Eu:case Tu:case Cu:n=m;do{n+=1,r=p.charCodeAt(n)}while(r===Su||r===_u||r===Eu||r===Tu||r===Cu);h=["space",p.slice(m,n)],m=n-1;break;case ku:case xu:case Iu:case Ru:case Pu:case Mu:case Au:{let e=String.fromCharCode(r);h=[e,e,m];break}case Ou:if(c=g.length?g.pop()[1]:"",u=p.charCodeAt(m+1),"url"===c&&u!==yu&&u!==wu&&u!==Su&&u!==_u&&u!==Eu&&u!==Cu&&u!==Tu){n=m;do{if(a=!1,n=p.indexOf(")",n+1),-1===n){if(d||t){n=m;break}w("bracket")}for(l=n;p.charCodeAt(l-1)===vu;)l-=1,a=!a}while(a);h=["brackets",p.slice(m,n+1),m,n],m=n}else n=p.indexOf(")",m+1),i=p.slice(m,n+1),-1===n||Fu.test(i)?h=["(","(",m]:(h=["brackets",i,m,n],m=n);break;case yu:case wu:s=r===yu?"'":'"',n=m;do{if(a=!1,n=p.indexOf(s,n+1),-1===n){if(d||t){n=m+1;break}w("string")}for(l=n;p.charCodeAt(l-1)===vu;)l-=1,a=!a}while(a);h=["string",p.slice(m,n+1),m,n],m=n;break;case Lu:Du.lastIndex=m+1,Du.test(p),n=0===Du.lastIndex?p.length-1:Du.lastIndex-2,h=["at-word",p.slice(m,n+1),m,n],m=n;break;case vu:for(n=m,o=!0;p.charCodeAt(n+1)===vu;)n+=1,o=!o;if(r=p.charCodeAt(n+1),o&&r!==bu&&r!==Su&&r!==_u&&r!==Eu&&r!==Tu&&r!==Cu&&(n+=1,Bu.test(p.charAt(n)))){for(;Bu.test(p.charAt(n+1));)n+=1;p.charCodeAt(n+1)===Su&&(n+=1)}h=["word",p.slice(m,n+1),m,n],m=n;break;default:r===bu&&p.charCodeAt(m+1)===Nu?(n=p.indexOf("*/",m+2)+1,0===n&&(d||t?n=p.length:w("comment")),h=["comment",p.slice(m,n+1),m,n],m=n):(Uu.lastIndex=m+1,Uu.test(p),n=0===Uu.lastIndex?p.length-1:Uu.lastIndex-2,h=["word",p.slice(m,n+1),m,n],g.push(h),m=n)}return m++,h},position:function(){return m}}},rh=Zc,nh=Vu,sh=Wu,ih=Qu;const oh={empty:!0,space:!0};var ah=class{constructor(e){this.input=e,this.root=new sh,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t,r,n,s=new nh;s.name=e[1].slice(1),""===s.name&&this.unnamedAtrule(s,e),this.init(s,e[2]);let i=!1,o=!1,a=[],l=[];for(;!this.tokenizer.endOfFile();){if(t=(e=this.tokenizer.nextToken())[0],"("===t||"["===t?l.push("("===t?")":"]"):"{"===t&&l.length>0?l.push("}"):t===l[l.length-1]&&l.pop(),0===l.length){if(";"===t){s.source.end=this.getPosition(e[2]),s.source.end.offset++,this.semicolon=!0;break}if("{"===t){o=!0;break}if("}"===t){if(a.length>0){for(n=a.length-1,r=a[n];r&&"space"===r[0];)r=a[--n];r&&(s.source.end=this.getPosition(r[3]||r[2]),s.source.end.offset++)}this.end(e);break}a.push(e)}else a.push(e);if(this.tokenizer.endOfFile()){i=!0;break}}s.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(s.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(s,"params",a),i&&(e=a[a.length-1],s.source.end=this.getPosition(e[3]||e[2]),s.source.end.offset++,this.spaces=s.raws.between,s.raws.between="")):(s.raws.afterName="",s.params=""),o&&(s.nodes=[],this.current=s)}checkMissedSemicolon(e){let t=this.colon(e);if(!1===t)return;let r,n=0;for(let s=t-1;s>=0&&(r=e[s],"space"===r[0]||(n+=1,2!==n));s--);throw this.input.error("Missed semicolon","word"===r[0]?r[3]+1:r[2])}colon(e){let t,r,n,s=0;for(let[i,o]of e.entries()){if(t=o,r=t[0],"("===r&&(s+=1),")"===r&&(s-=1),0===s&&":"===r){if(n){if("word"===n[0]&&"progid"===n[1])continue;return i}this.doubleColon(t)}n=t}return!1}comment(e){let t=new rh;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let r=e[1].slice(2,-2);if(/^\s*$/.test(r))t.text="",t.raws.left=r,t.raws.right="";else{let e=r.match(/^(\s*)([^]*\S)(\s*)$/);t.text=e[2],t.raws.left=e[1],t.raws.right=e[3]}}createTokenizer(){this.tokenizer=th(this.input)}decl(e,t){let r=new eh;this.init(r,e[0][2]);let n,s=e[e.length-1];for(";"===s[0]&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(s[3]||s[2]||function(e){for(let t=e.length-1;t>=0;t--){let r=e[t],n=r[3]||r[2];if(n)return n}}(e)),r.source.end.offset++;"word"!==e[0][0];)1===e.length&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop="";e.length;){let t=e[0][0];if(":"===t||"space"===t||"comment"===t)break;r.prop+=e.shift()[1]}for(r.raws.between="";e.length;){if(n=e.shift(),":"===n[0]){r.raws.between+=n[1];break}"word"===n[0]&&/\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1]}"_"!==r.prop[0]&&"*"!==r.prop[0]||(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));let i,o=[];for(;e.length&&(i=e[0][0],"space"===i||"comment"===i);)o.push(e.shift());this.precheckMissedSemicolon(e);for(let t=e.length-1;t>=0;t--){if(n=e[t],"!important"===n[1].toLowerCase()){r.important=!0;let n=this.stringFrom(e,t);n=this.spacesFromEnd(e)+n," !important"!==n&&(r.raws.important=n);break}if("important"===n[1].toLowerCase()){let n=e.slice(0),s="";for(let e=t;e>0;e--){let t=n[e][0];if(0===s.trim().indexOf("!")&&"space"!==t)break;s=n.pop()[1]+s}0===s.trim().indexOf("!")&&(r.important=!0,r.raws.important=s,e=n)}if("space"!==n[0]&&"comment"!==n[0])break}e.some(e=>"space"!==e[0]&&"comment"!==e[0])&&(r.raws.between+=o.map(e=>e[1]).join(""),o=[]),this.raw(r,"value",o.concat(e),t),r.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new ih;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let e=this.current.nodes[this.current.nodes.length-1];e&&"rule"===e.type&&!e.raws.ownSemicolon&&(e.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="","comment"!==e.type&&(this.semicolon=!1)}other(e){let t=!1,r=null,n=!1,s=null,i=[],o=e[1].startsWith("--"),a=[],l=e;for(;l;){if(r=l[0],a.push(l),"("===r||"["===r)s||(s=l),i.push("("===r?")":"]");else if(o&&n&&"{"===r)s||(s=l),i.push("}");else if(0===i.length){if(";"===r){if(n)return void this.decl(a,o);break}if("{"===r)return void this.rule(a);if("}"===r){this.tokenizer.back(a.pop()),t=!0;break}":"===r&&(n=!0)}else r===i[i.length-1]&&(i.pop(),0===i.length&&(s=null));l=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),i.length>0&&this.unclosedBracket(s),t&&n){if(!o)for(;a.length&&(l=a[a.length-1][0],"space"===l||"comment"===l);)this.tokenizer.back(a.pop());this.decl(a,o)}else this.unknownWord(a)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e)}this.endFile()}precheckMissedSemicolon(){}raw(e,t,r,n){let s,i,o,a,l=r.length,c="",u=!0;for(let e=0;ee+t[1],"");e.raws[t]={raw:n,value:c}}e[t]=c}rule(e){e.pop();let t=new ih;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t||"comment"===t);)r=e.pop()[1]+r;return r}spacesAndCommentsFromStart(e){let t,r="";for(;e.length&&(t=e[0][0],"space"===t||"comment"===t);)r+=e.shift()[1];return r}spacesFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t);)r=e.pop()[1]+r;return r}stringFrom(e,t){let r="";for(let n=t;nAh(e)),e}let Ih={},Rh=class e{constructor(t,r,n){let s;if(this.stringified=!1,this.processed=!1,"object"!=typeof r||null===r||"root"!==r.type&&"document"!==r.type)if(r instanceof e||r instanceof bh)s=Ah(r.root),r.map&&(void 0===n.map&&(n.map={}),n.map.inline||(n.map.inline=!1),n.map.prev=r.map);else{let e=_h;n.syntax&&(e=n.syntax.parse),n.parser&&(e=n.parser),e.parse&&(e=e.parse);try{s=e(r,n)}catch(e){this.processed=!0,this.error=e}s&&!s[fh]&&yh.rebuild(s)}else s=Ah(r);this.result=new bh(t,s,n),this.helpers={...Ih,postcss:Ih,result:this.result},this.plugins=this.processor.plugins.map(e=>"object"==typeof e&&e.prepare?{...e,...e.prepare(this.result)}:e)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let r=this.result.lastPlugin;try{if(t&&t.addToError(e),this.error=e,"CssSyntaxError"!==e.name||e.plugin){if(r.postcssVersion&&"production"!==process.env.NODE_ENV){let e=r.postcssPlugin,t=r.postcssVersion,n=this.result.processor.version,s=t.split("."),i=n.split(".");(s[0]!==i[0]||parseInt(s[1])>parseInt(i[1]))&&console.error("Unknown error from PostCSS plugin. Your current PostCSS version is "+n+", but "+e+" uses "+t+". Perhaps this is the source of the error below.")}}else e.plugin=r.postcssPlugin,e.setMessage()}catch(e){console&&console.error&&console.error(e)}return e}prepareVisitors(){this.listeners={};let e=(e,t,r)=>{this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push([e,r])};for(let t of this.plugins)if("object"==typeof t)for(let r in t){if(!Eh[r]&&/^[A-Z]/.test(r))throw new Error(`Unknown event ${r} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!Th[r])if("object"==typeof t[r])for(let n in t[r])e(t,"*"===n?r:r+"-"+n.toLowerCase(),t[r][n]);else"function"==typeof t[r]&&e(t,r,t[r])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e0;){let e=this.visitTick(t);if(kh(e))try{await e}catch(e){let r=t[t.length-1].node;throw this.handleError(e,r)}}}if(this.listeners.OnceExit)for(let[t,r]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if("document"===e.type){let t=e.nodes.map(e=>r(e,this.helpers));await Promise.all(t)}else await r(e,this.helpers)}catch(e){throw this.handleError(e)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if("object"==typeof e&&e.Once){if("document"===this.result.root.type){let t=this.result.root.nodes.map(t=>e.Once(t,this.helpers));return kh(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}if("function"==typeof e)return e(this.result.root,this.result)}catch(e){throw this.handleError(e)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=gh;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new mh(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){if(kh(this.runOnRoot(e)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[dh];)e[dh]=!0,this.walkSync(e);if(this.listeners.OnceExit)if("document"===e.type)for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this.opts||vh("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[r,n]of e){let e;this.result.lastPlugin=r;try{e=n(t,this.helpers)}catch(e){throw this.handleError(e,t.proxyOf)}if("root"!==t.type&&"document"!==t.type&&!t.parent)return!0;if(kh(e))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:r,visitors:n}=t;if("root"!==r.type&&"document"!==r.type&&!r.parent)return void e.pop();if(n.length>0&&t.visitorIndex{e[dh]||this.walkSync(e)});else{let t=this.listeners[r];if(t&&this.visitSync(t,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};Rh.registerPostcss=e=>{Ih=e};var Mh=Rh;Rh.default=Rh,Sh.registerLazyResult(Rh),wh.registerLazyResult(Rh);let Nh=Vc,Ph=Jl,Lh=hu,Dh=ph;const Uh=gu;let Fh=class{constructor(e,t,r){let n;t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;let s=Ph;this.result=new Uh(this._processor,n,this._opts),this.result.css=t;let i=this;Object.defineProperty(this.result,"root",{get:()=>i.root});let o=new Nh(s,n,this._opts,t);if(o.isMap()){let[e,t]=o.generate();e&&(this.result.css=e),t&&(this.result.map=t)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this._opts||Lh("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=Dh;try{e=t(this._css,this._opts)}catch(e){this.error=e}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}};var Bh=Fh;Fh.default=Fh;let jh=Bh,zh=Mh,Vh=cu,Gh=Wu,Hh=class{constructor(e=[]){this.version="8.4.38",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let r of e)if(!0===r.postcss?r=r():r.postcss&&(r=r.postcss),"object"==typeof r&&Array.isArray(r.plugins))t=t.concat(r.plugins);else if("object"==typeof r&&r.postcssPlugin)t.push(r);else if("function"==typeof r)t.push(r);else{if("object"!=typeof r||!r.parse&&!r.stringify)throw new Error(r+" is not a PostCSS plugin");if("production"!==process.env.NODE_ENV)throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.")}return t}process(e,t={}){return this.plugins.length||t.parser||t.stringifier||t.syntax?new zh(this,e,t):new jh(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};var Zh=Hh;Hh.default=Hh,Gh.registerProcessor(Hh),Vh.registerProcessor(Hh);let $h=ac,Wh=gc,Yh=Zc,Xh=Vu,Jh=Rc,Kh=Wu,qh=Qu;function Qh(e,t){if(Array.isArray(e))return e.map(e=>Qh(e));let{inputs:r,...n}=e;if(r){t=[];for(let e of r){let r={...e,__proto__:Jh.prototype};r.map&&(r.map={...r.map,__proto__:Wh.prototype}),t.push(r)}}if(n.nodes&&(n.nodes=e.nodes.map(e=>Qh(e,t))),n.source){let{inputId:e,...r}=n.source;n.source=r,null!=e&&(n.source.input=t[e])}if("root"===n.type)return new Kh(n);if("decl"===n.type)return new $h(n);if("rule"===n.type)return new qh(n);if("comment"===n.type)return new Yh(n);if("atrule"===n.type)return new Xh(n);throw new Error("Unknown node type: "+e.type)}var ep=Qh;Qh.default=Qh;let tp=Gl,rp=ac,np=Mh,sp=su,ip=Zh,op=Jl,ap=ep,lp=cu,cp=du,up=Zc,hp=Vu,pp=gu,dp=Rc,fp=ph,mp=Xu,gp=Qu,yp=Wu,wp=sc;function vp(...e){return 1===e.length&&Array.isArray(e[0])&&(e=e[0]),new ip(e)}vp.plugin=function(e,t){let r,n=!1;function s(...r){console&&console.warn&&!n&&(n=!0,console.warn(e+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226"));let s=t(...r);return s.postcssPlugin=e,s.postcssVersion=(new ip).version,s}return Object.defineProperty(s,"postcss",{get:()=>(r||(r=s()),r)}),s.process=function(e,t,r){return vp([s(r)]).process(e,t)},s},vp.stringify=op,vp.parse=fp,vp.fromJSON=ap,vp.list=mp,vp.comment=e=>new up(e),vp.atRule=e=>new hp(e),vp.decl=e=>new rp(e),vp.rule=e=>new gp(e),vp.root=e=>new yp(e),vp.document=e=>new lp(e),vp.CssSyntaxError=tp,vp.Declaration=rp,vp.Container=sp,vp.Processor=ip,vp.Document=lp,vp.Comment=up,vp.Warning=cp,vp.AtRule=hp,vp.Result=pp,vp.Input=dp,vp.Rule=gp,vp.Root=yp,vp.Node=wp,np.registerPostcss(vp);var bp=vp;vp.default=vp;const _p=Nl(bp);_p.stringify,_p.fromJSON,_p.plugin,_p.parse,_p.list,_p.document,_p.comment,_p.atRule,_p.rule,_p.decl,_p.root,_p.CssSyntaxError,_p.Declaration,_p.Container,_p.Processor,_p.Document,_p.Comment,_p.Warning,_p.AtRule,_p.Result,_p.Input,_p.Rule,_p.Root,_p.Node;var Sp=Object.defineProperty,Cp=(e,t,r)=>((e,t,r)=>t in e?Sp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r);function Ep(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Tp(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var r=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(t){var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:function(){return e[t]}})}),r}var kp={exports:{}},xp=String,Op=function(){return{isColorSupported:!1,reset:xp,bold:xp,dim:xp,italic:xp,underline:xp,inverse:xp,hidden:xp,strikethrough:xp,black:xp,red:xp,green:xp,yellow:xp,blue:xp,magenta:xp,cyan:xp,white:xp,gray:xp,bgBlack:xp,bgRed:xp,bgGreen:xp,bgYellow:xp,bgBlue:xp,bgMagenta:xp,bgCyan:xp,bgWhite:xp}};kp.exports=Op(),kp.exports.createColors=Op;var Ap=kp.exports;const Ip=Tp(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));let Rp=Ap,Mp=Ip,Np=class e extends Error{constructor(t,r,n,s,i,o){super(t),this.name="CssSyntaxError",this.reason=t,i&&(this.file=i),s&&(this.source=s),o&&(this.plugin=o),void 0!==r&&void 0!==n&&("number"==typeof r?(this.line=r,this.column=n):(this.line=r.line,this.column=r.column,this.endLine=n.line,this.endColumn=n.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,e)}setMessage(){this.message=this.plugin?this.plugin+": ":"",this.message+=this.file?this.file:"",void 0!==this.line&&(this.message+=":"+this.line+":"+this.column),this.message+=": "+this.reason}showSourceCode(e){if(!this.source)return"";let t=this.source;null==e&&(e=Rp.isColorSupported),Mp&&e&&(t=Mp(t));let r,n,s=t.split(/\r?\n/),i=Math.max(this.line-3,0),o=Math.min(this.line+2,s.length),a=String(o).length;if(e){let{bold:e,gray:t,red:s}=Rp.createColors(!0);r=t=>e(s(t)),n=e=>t(e)}else r=n=e=>e;return s.slice(i,o).map((e,t)=>{let s=i+1+t,o=" "+(" "+s).slice(-a)+" | ";if(s===this.line){let t=n(o.replace(/\d/g," "))+e.slice(0,this.column-1).replace(/[^\t]/g," ");return r(">")+n(o)+e+"\n "+t+r("^")}return" "+n(o)+e}).join("\n")}toString(){let e=this.showSourceCode();return e&&(e="\n\n"+e+"\n"),this.name+": "+this.message+e}};var Pp=Np;Np.default=Np;var Lp={};Lp.isClean=Symbol("isClean"),Lp.my=Symbol("my");const Dp={after:"\n",beforeClose:"\n",beforeComment:"\n",beforeDecl:"\n",beforeOpen:" ",beforeRule:"\n",colon:": ",commentLeft:" ",commentRight:" ",emptyBody:"",indent:" ",semicolon:!1};let Up=class{constructor(e){this.builder=e}atrule(e,t){let r="@"+e.name,n=e.params?this.rawValue(e,"params"):"";if(void 0!==e.raws.afterName?r+=e.raws.afterName:n&&(r+=" "),e.nodes)this.block(e,r+n);else{let s=(e.raws.between||"")+(t?";":"");this.builder(r+n+s,e)}}beforeAfter(e,t){let r;r="decl"===e.type?this.raw(e,null,"beforeDecl"):"comment"===e.type?this.raw(e,null,"beforeComment"):"before"===t?this.raw(e,null,"beforeRule"):this.raw(e,null,"beforeClose");let n=e.parent,s=0;for(;n&&"root"!==n.type;)s+=1,n=n.parent;if(r.includes("\n")){let t=this.raw(e,null,"indent");if(t.length)for(let e=0;e0&&"comment"===e.nodes[t].type;)t-=1;let r=this.raw(e,"semicolon");for(let n=0;n{if(n=e.raws[t],void 0!==n)return!1})}var o;return void 0===n&&(n=Dp[r]),i.rawCache[r]=n,n}rawBeforeClose(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length>0&&void 0!==e.raws.after)return t=e.raws.after,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawBeforeComment(e,t){let r;return e.walkComments(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeDecl"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeDecl(e,t){let r;return e.walkDecls(e=>{if(void 0!==e.raws.before)return r=e.raws.before,r.includes("\n")&&(r=r.replace(/[^\n]+$/,"")),!1}),void 0===r?r=this.raw(t,null,"beforeRule"):r&&(r=r.replace(/\S/g,"")),r}rawBeforeOpen(e){let t;return e.walk(e=>{if("decl"!==e.type&&(t=e.raws.between,void 0!==t))return!1}),t}rawBeforeRule(e){let t;return e.walk(r=>{if(r.nodes&&(r.parent!==e||e.first!==r)&&void 0!==r.raws.before)return t=r.raws.before,t.includes("\n")&&(t=t.replace(/[^\n]+$/,"")),!1}),t&&(t=t.replace(/\S/g,"")),t}rawColon(e){let t;return e.walkDecls(e=>{if(void 0!==e.raws.between)return t=e.raws.between.replace(/[^\s:]/g,""),!1}),t}rawEmptyBody(e){let t;return e.walk(e=>{if(e.nodes&&0===e.nodes.length&&(t=e.raws.after,void 0!==t))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(r=>{let n=r.parent;if(n&&n!==e&&n.parent&&n.parent===e&&void 0!==r.raws.before){let e=r.raws.before.split("\n");return t=e[e.length-1],t=t.replace(/\S/g,""),!1}}),t}rawSemicolon(e){let t;return e.walk(e=>{if(e.nodes&&e.nodes.length&&"decl"===e.last.type&&(t=e.raws.semicolon,void 0!==t))return!1}),t}rawValue(e,t){let r=e[t],n=e.raws[t];return n&&n.value===r?n.raw:r}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,"selector")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,"end")}stringify(e,t){if(!this[e.type])throw new Error("Unknown AST node type "+e.type+". Maybe you need to change PostCSS stringifier.");this[e.type](e,t)}};var Fp=Up;Up.default=Up;let Bp=Fp;function jp(e,t){new Bp(t).stringify(e)}var zp=jp;jp.default=jp;let{isClean:Vp,my:Gp}=Lp,Hp=Pp,Zp=Fp,$p=zp;function Wp(e,t){let r=new e.constructor;for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;if("proxyCache"===n)continue;let s=e[n],i=typeof s;"parent"===n&&"object"===i?t&&(r[n]=t):"source"===n?r[n]=s:Array.isArray(s)?r[n]=s.map(e=>Wp(e,r)):("object"===i&&null!==s&&(s=Wp(s)),r[n]=s)}return r}let Yp=class{constructor(e={}){this.raws={},this[Vp]=!1,this[Gp]=!0;for(let t in e)if("nodes"===t){this.nodes=[];for(let r of e[t])"function"==typeof r.clone?this.append(r.clone()):this.append(r)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\n\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\n\s{4}at /,`$&${t.input.from}:${t.start.line}:${t.start.column}$&`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=Wp(this);for(let r in e)t[r]=e[r];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:r,start:n}=this.rangeBy(t);return this.source.input.error(e,{column:n.column,line:n.line},{column:r.column,line:r.line},t)}return new Hp(e)}getProxyProcessor(){return{get:(e,t)=>"proxyOf"===t?e:"root"===t?()=>e.root().toProxy():e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"prop"!==t&&"value"!==t&&"name"!==t&&"params"!==t&&"important"!==t&&"text"!==t||e.markDirty()),!0)}}markDirty(){if(this[Vp]){this[Vp]=!1;let e=this;for(;e=e.parent;)e[Vp]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){let n=(t=this.toString()).indexOf(e.word);-1!==n&&(r=this.positionInside(n,t))}return r}positionInside(e,t){let r=t||this.toString(),n=this.source.start.column,s=this.source.start.line;for(let t=0;t"object"==typeof e&&e.toJSON?e.toJSON(null,t):e);else if("object"==typeof n&&n.toJSON)r[e]=n.toJSON(null,t);else if("source"===e){let i=t.get(n.input);null==i&&(i=s,t.set(n.input,s),s++),r[e]={end:n.end,inputId:i,start:n.start}}else r[e]=n}return n&&(r.inputs=[...t.keys()].map(e=>e.toJSON())),r}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=$p){e.stringify&&(e=e.stringify);let t="";return e(this,e=>{t+=e}),t}warn(e,t,r){let n={node:this};for(let e in r)n[e]=r[e];return e.warn(t,n)}get proxyOf(){return this}};var Xp=Yp;Yp.default=Yp;let Jp=Xp,Kp=class extends Jp{constructor(e){e&&void 0!==e.value&&"string"!=typeof e.value&&(e={...e,value:String(e.value)}),super(e),this.type="decl"}get variable(){return this.prop.startsWith("--")||"$"===this.prop[0]}};var qp=Kp;Kp.default=Kp;var Qp={nanoid:(e=21)=>{let t="",r=e;for(;r--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t}};let{SourceMapConsumer:ed,SourceMapGenerator:td}=Ip,{existsSync:rd,readFileSync:nd}=Ip,{dirname:sd,join:id}=Ip;let od=class{constructor(e,t){if(!1===t.map)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,"data:");let r=t.map?t.map.prev:void 0,n=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=sd(this.mapFile)),n&&(this.text=n)}consumer(){return this.consumerCache||(this.consumerCache=new ed(this.text)),this.consumerCache}decodeInline(e){if(/^data:application\/json;charset=utf-?8,/.test(e)||/^data:application\/json,/.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(/^data:application\/json;charset=utf-?8;base64,/.test(e)||/^data:application\/json;base64,/.test(e))return t=e.substr(RegExp.lastMatch.length),Buffer?Buffer.from(t,"base64").toString():window.atob(t);var t;let r=e.match(/data:application\/json;([^,]+),/)[1];throw new Error("Unsupported source map encoding "+r)}getAnnotationURL(e){return e.replace(/^\/\*\s*# sourceMappingURL=/,"").trim()}isMap(e){return"object"==typeof e&&("string"==typeof e.mappings||"string"==typeof e._mappings||Array.isArray(e.sections))}loadAnnotation(e){let t=e.match(/\/\*\s*# sourceMappingURL=/gm);if(!t)return;let r=e.lastIndexOf(t.pop()),n=e.indexOf("*/",r);r>-1&&n>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,n)))}loadFile(e){if(this.root=sd(e),rd(e))return this.mapFile=e,nd(e,"utf-8").toString().trim()}loadMap(e,t){if(!1===t)return!1;if(t){if("string"==typeof t)return t;if("function"!=typeof t){if(t instanceof ed)return td.fromSourceMap(t).toString();if(t instanceof td)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error("Unsupported previous source map format: "+t.toString())}{let r=t(e);if(r){let e=this.loadFile(r);if(!e)throw new Error("Unable to load previous source map: "+r.toString());return e}}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let t=this.annotation;return e&&(t=id(sd(e),t)),this.loadFile(t)}}}startWith(e,t){return!!e&&e.substr(0,t.length)===t}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var ad=od;od.default=od;let{SourceMapConsumer:ld,SourceMapGenerator:cd}=Ip,{fileURLToPath:ud,pathToFileURL:hd}=Ip,{isAbsolute:pd,resolve:dd}=Ip,{nanoid:fd}=Qp,md=Ip,gd=Pp,yd=ad,wd=Symbol("fromOffsetCache"),vd=Boolean(ld&&cd),bd=Boolean(dd&&pd),_d=class{constructor(e,t={}){if(null==e||"object"==typeof e&&!e.toString)throw new Error(`PostCSS received ${e} instead of CSS string`);if(this.css=e.toString(),"\ufeff"===this.css[0]||"￾"===this.css[0]?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!bd||/^\w+:\/\//.test(t.from)||pd(t.from)?this.file=t.from:this.file=dd(t.from)),bd&&vd){let e=new yd(this.css,t);if(e.text){this.map=e;let t=e.consumer().file;!this.file&&t&&(this.file=this.mapResolve(t))}}this.file||(this.id=""),this.map&&(this.map.file=this.from)}error(e,t,r,n={}){let s,i,o;if(t&&"object"==typeof t){let e=t,n=r;if("number"==typeof e.offset){let n=this.fromOffset(e.offset);t=n.line,r=n.col}else t=e.line,r=e.column;if("number"==typeof n.offset){let e=this.fromOffset(n.offset);i=e.line,o=e.col}else i=n.line,o=n.column}else if(!r){let e=this.fromOffset(t);t=e.line,r=e.col}let a=this.origin(t,r,i,o);return s=a?new gd(e,void 0===a.endLine?a.line:{column:a.column,line:a.line},void 0===a.endLine?a.column:{column:a.endColumn,line:a.endLine},a.source,a.file,n.plugin):new gd(e,void 0===i?t:{column:r,line:t},void 0===i?r:{column:o,line:i},this.css,this.file,n.plugin),s.input={column:r,endColumn:o,endLine:i,line:t,source:this.css},this.file&&(hd&&(s.input.url=hd(this.file).toString()),s.input.file=this.file),s}fromOffset(e){let t,r;if(this[wd])r=this[wd];else{let e=this.css.split("\n");r=new Array(e.length);let t=0;for(let n=0,s=e.length;n=t)n=r.length-1;else{let t,s=r.length-2;for(;n>1),e=r[t+1])){n=t;break}n=t+1}}return{col:e-r[n]+1,line:n+1}}mapResolve(e){return/^\w+:\/\//.test(e)?e:dd(this.map.consumer().sourceRoot||this.map.root||".",e)}origin(e,t,r,n){if(!this.map)return!1;let s,i,o=this.map.consumer(),a=o.originalPositionFor({column:t,line:e});if(!a.source)return!1;"number"==typeof r&&(s=o.originalPositionFor({column:n,line:r})),i=pd(a.source)?hd(a.source):new URL(a.source,this.map.consumer().sourceRoot||hd(this.map.mapFile));let l={column:a.column,endColumn:s&&s.column,endLine:s&&s.line,line:a.line,url:i.toString()};if("file:"===i.protocol){if(!ud)throw new Error("file: protocol is not available in this PostCSS build");l.file=ud(i)}let c=o.sourceContentFor(a.source);return c&&(l.source=c),l}toJSON(){let e={};for(let t of["hasBOM","css","file","id"])null!=this[t]&&(e[t]=this[t]);return this.map&&(e.map={...this.map},e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};var Sd=_d;_d.default=_d,md&&md.registerInput&&md.registerInput(_d);let{SourceMapConsumer:Cd,SourceMapGenerator:Ed}=Ip,{dirname:Td,relative:kd,resolve:xd,sep:Od}=Ip,{pathToFileURL:Ad}=Ip,Id=Sd,Rd=Boolean(Cd&&Ed),Md=Boolean(Td&&xd&&kd&&Od);var Nd=class{constructor(e,t,r,n){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=n,this.originalCSS=n,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;e=this.isInline()?"data:application/json;base64,"+this.toBase64(this.map.toString()):"string"==typeof this.mapOpts.annotation?this.mapOpts.annotation:"function"==typeof this.mapOpts.annotation?this.mapOpts.annotation(this.opts.to,this.root):this.outputFile()+".map";let t="\n";this.css.includes("\r\n")&&(t="\r\n"),this.css+=t+"/*# sourceMappingURL="+e+" */"}applyPrevMaps(){for(let e of this.previous()){let t,r=this.toUrl(this.path(e.file)),n=e.root||Td(e.file);!1===this.mapOpts.sourcesContent?(t=new Cd(e.text),t.sourcesContent&&(t.sourcesContent=null)):t=e.consumer(),this.map.applySourceMap(t,r,this.toUrl(this.path(n)))}}clearAnnotation(){if(!1!==this.mapOpts.annotation)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],"comment"===e.type&&0===e.text.indexOf("# sourceMappingURL=")&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\n*?\/\*#[\S\s]*?\*\/$/gm,""))}generate(){if(this.clearAnnotation(),Md&&Rd&&this.isMap())return this.generateMap();{let e="";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(1===this.previous().length){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=Ed.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new Ed({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):""});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css="",this.map=new Ed({file:this.outputFile(),ignoreInvalidMapping:!0});let e,t,r=1,n=1,s="",i={generated:{column:0,line:0},original:{column:0,line:0},source:""};this.stringify(this.root,(o,a,l)=>{if(this.css+=o,a&&"end"!==l&&(i.generated.line=r,i.generated.column=n-1,a.source&&a.source.start?(i.source=this.sourcePath(a),i.original.line=a.source.start.line,i.original.column=a.source.start.column-1,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,this.map.addMapping(i))),e=o.match(/\n/g),e?(r+=e.length,t=o.lastIndexOf("\n"),n=o.length-t):n+=o.length,a&&"start"!==l){let e=a.parent||{raws:{}};("decl"===a.type||"atrule"===a.type&&!a.nodes)&&a===e.last&&!e.raws.semicolon||(a.source&&a.source.end?(i.source=this.sourcePath(a),i.original.line=a.source.end.line,i.original.column=a.source.end.column-1,i.generated.line=r,i.generated.column=n-2,this.map.addMapping(i)):(i.source=s,i.original.line=1,i.original.column=0,i.generated.line=r,i.generated.column=n-1,this.map.addMapping(i)))}})}isAnnotation(){return!!this.isInline()||(void 0!==this.mapOpts.annotation?this.mapOpts.annotation:!this.previous().length||this.previous().some(e=>e.annotation))}isInline(){if(void 0!==this.mapOpts.inline)return this.mapOpts.inline;let e=this.mapOpts.annotation;return(void 0===e||!0===e)&&(!this.previous().length||this.previous().some(e=>e.inline))}isMap(){return void 0!==this.opts.map?!!this.opts.map:this.previous().length>0}isSourcesContent(){return void 0!==this.mapOpts.sourcesContent?this.mapOpts.sourcesContent:!this.previous().length||this.previous().some(e=>e.withContent())}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):"to.css"}path(e){if(this.mapOpts.absolute)return e;if(60===e.charCodeAt(0))return e;if(/^\w+:\/\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let r=this.opts.to?Td(this.opts.to):".";"string"==typeof this.mapOpts.annotation&&(r=Td(xd(r,this.mapOpts.annotation)));let n=kd(r,e);return this.memoizedPaths.set(e,n),n}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new Id(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let r=t.source.input.from;if(r&&!e[r]){e[r]=!0;let n=this.usesFileUrls?this.toFileUrl(r):this.toUrl(this.path(r));this.map.setSourceContent(n,t.source.input.css)}}});else if(this.css){let e=this.opts.from?this.toUrl(this.path(this.opts.from)):"";this.map.setSourceContent(e,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString("base64"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(Ad){let t=Ad(e).toString();return this.memoizedFileURLs.set(e,t),t}throw new Error("`map.absolute` option is not available in this PostCSS build")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;"\\"===Od&&(e=e.replace(/\\/g,"/"));let r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r}};let Pd=Xp,Ld=class extends Pd{constructor(e){super(e),this.type="comment"}};var Dd=Ld;Ld.default=Ld;let Ud,Fd,Bd,jd,{isClean:zd,my:Vd}=Lp,Gd=qp,Hd=Dd,Zd=Xp;function $d(e){return e.map(e=>(e.nodes&&(e.nodes=$d(e.nodes)),delete e.source,e))}function Wd(e){if(e[zd]=!1,e.proxyOf.nodes)for(let t of e.proxyOf.nodes)Wd(t)}let Yd=class e extends Zd{append(...e){for(let t of e){let e=this.normalize(t,this.last);for(let t of e)this.proxyOf.nodes.push(t)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t,r,n=this.getIterator();for(;this.indexes[n]"proxyOf"===t?e:e[t]?"each"===t||"string"==typeof t&&t.startsWith("walk")?(...r)=>e[t](...r.map(e=>"function"==typeof e?(t,r)=>e(t.toProxy(),r):e)):"every"===t||"some"===t?r=>e[t]((e,...t)=>r(e.toProxy(),...t)):"root"===t?()=>e.root().toProxy():"nodes"===t?e.nodes.map(e=>e.toProxy()):"first"===t||"last"===t?e[t].toProxy():e[t]:e[t],set:(e,t,r)=>(e[t]===r||(e[t]=r,"name"!==t&&"params"!==t&&"selector"!==t||e.markDirty()),!0)}}index(e){return"number"==typeof e?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let r,n=this.index(e),s=this.normalize(t,this.proxyOf.nodes[n]).reverse();n=this.index(e);for(let e of s)this.proxyOf.nodes.splice(n+1,0,e);for(let e in this.indexes)r=this.indexes[e],n(t[Vd]||e.rebuild(t),(t=t.proxyOf).parent&&t.parent.removeChild(t),t[zd]&&Wd(t),void 0===t.raws.before&&r&&void 0!==r.raws.before&&(t.raws.before=r.raws.before.replace(/\S/g,"")),t.parent=this.proxyOf,t))}prepend(...e){e=e.reverse();for(let t of e){let e=this.normalize(t,this.first,"prepend").reverse();for(let t of e)this.proxyOf.nodes.unshift(t);for(let t in this.indexes)this.indexes[t]=this.indexes[t]+e.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){let t;e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);for(let r in this.indexes)t=this.indexes[r],t>=e&&(this.indexes[r]=t-1);return this.markDirty(),this}replaceValues(e,t,r){return r||(r=t,t={}),this.walkDecls(n=>{t.props&&!t.props.includes(n.prop)||t.fast&&!n.value.includes(t.fast)||(n.value=n.value.replace(e,r))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,r)=>{let n;try{n=e(t,r)}catch(e){throw t.addToError(e)}return!1!==n&&t.walk&&(n=t.walk(e)),n})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("atrule"===r.type&&e.test(r.name))return t(r,n)}):this.walk((r,n)=>{if("atrule"===r.type&&r.name===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("atrule"===e.type)return t(e,r)}))}walkComments(e){return this.walk((t,r)=>{if("comment"===t.type)return e(t,r)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("decl"===r.type&&e.test(r.prop))return t(r,n)}):this.walk((r,n)=>{if("decl"===r.type&&r.prop===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("decl"===e.type)return t(e,r)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((r,n)=>{if("rule"===r.type&&e.test(r.selector))return t(r,n)}):this.walk((r,n)=>{if("rule"===r.type&&r.selector===e)return t(r,n)}):(t=e,this.walk((e,r)=>{if("rule"===e.type)return t(e,r)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};Yd.registerParse=e=>{Ud=e},Yd.registerRule=e=>{Fd=e},Yd.registerAtRule=e=>{Bd=e},Yd.registerRoot=e=>{jd=e};var Xd=Yd;Yd.default=Yd,Yd.rebuild=e=>{"atrule"===e.type?Object.setPrototypeOf(e,Bd.prototype):"rule"===e.type?Object.setPrototypeOf(e,Fd.prototype):"decl"===e.type?Object.setPrototypeOf(e,Gd.prototype):"comment"===e.type?Object.setPrototypeOf(e,Hd.prototype):"root"===e.type&&Object.setPrototypeOf(e,jd.prototype),e[Vd]=!0,e.nodes&&e.nodes.forEach(e=>{Yd.rebuild(e)})};let Jd,Kd,qd=Xd,Qd=class extends qd{constructor(e){super({type:"document",...e}),this.nodes||(this.nodes=[])}toResult(e={}){return new Jd(new Kd,this,e).stringify()}};Qd.registerLazyResult=e=>{Jd=e},Qd.registerProcessor=e=>{Kd=e};var ef=Qd;Qd.default=Qd;let tf={};var rf=function(e){tf[e]||(tf[e]=!0,"undefined"!=typeof console&&console.warn&&console.warn(e))};let nf=class{constructor(e,t={}){if(this.type="warning",this.text=e,t.node&&t.node.source){let e=t.node.rangeBy(t);this.line=e.start.line,this.column=e.start.column,this.endLine=e.end.line,this.endColumn=e.end.column}for(let e in t)this[e]=t[e]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+": "+this.text:this.text}};var sf=nf;nf.default=nf;let of=sf,af=class{constructor(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let r=new of(e,t);return this.messages.push(r),r}warnings(){return this.messages.filter(e=>"warning"===e.type)}get content(){return this.css}};var lf=af;af.default=af;const cf="'".charCodeAt(0),uf='"'.charCodeAt(0),hf="\\".charCodeAt(0),pf="/".charCodeAt(0),df="\n".charCodeAt(0),ff=" ".charCodeAt(0),mf="\f".charCodeAt(0),gf="\t".charCodeAt(0),yf="\r".charCodeAt(0),wf="[".charCodeAt(0),vf="]".charCodeAt(0),bf="(".charCodeAt(0),_f=")".charCodeAt(0),Sf="{".charCodeAt(0),Cf="}".charCodeAt(0),Ef=";".charCodeAt(0),Tf="*".charCodeAt(0),kf=":".charCodeAt(0),xf="@".charCodeAt(0),Of=/[\t\n\f\r "#'()/;[\\\]{}]/g,Af=/[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)/g,If=/.[\r\n"'(/\\]/,Rf=/[\da-f]/i;let Mf=Xd,Nf=class extends Mf{constructor(e){super(e),this.type="atrule"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};var Pf=Nf;Nf.default=Nf,Mf.registerAtRule(Nf);let Lf,Df,Uf=Xd,Ff=class extends Uf{constructor(e){super(e),this.type="root",this.nodes||(this.nodes=[])}normalize(e,t,r){let n=super.normalize(e);if(t)if("prepend"===r)this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let e of n)e.raws.before=t.raws.before;return n}removeChild(e,t){let r=this.index(e);return!t&&0===r&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[r].raws.before),super.removeChild(e)}toResult(e={}){return new Lf(new Df,this,e).stringify()}};Ff.registerLazyResult=e=>{Lf=e},Ff.registerProcessor=e=>{Df=e};var Bf=Ff;Ff.default=Ff,Uf.registerRoot(Ff);let jf={comma:e=>jf.split(e,[","],!0),space:e=>jf.split(e,[" ","\n","\t"]),split(e,t,r){let n=[],s="",i=!1,o=0,a=!1,l="",c=!1;for(let r of e)c?c=!1:"\\"===r?c=!0:a?r===l&&(a=!1):'"'===r||"'"===r?(a=!0,l=r):"("===r?o+=1:")"===r?o>0&&(o-=1):0===o&&t.includes(r)&&(i=!0),i?(""!==s&&n.push(s.trim()),s="",i=!1):s+=r;return(r||""!==s)&&n.push(s.trim()),n}};var zf=jf;jf.default=jf;let Vf=Xd,Gf=zf,Hf=class extends Vf{constructor(e){super(e),this.type="rule",this.nodes||(this.nodes=[])}get selectors(){return Gf.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\s*/):null,r=t?t[0]:","+this.raw("between","beforeOpen");this.selector=e.join(r)}};var Zf=Hf;Hf.default=Hf,Vf.registerRule(Hf);let $f=qp,Wf=function(e,t={}){let r,n,s,i,o,a,l,c,u,h,p=e.css.valueOf(),d=t.ignoreErrors,f=p.length,m=0,g=[],y=[];function w(t){throw e.error("Unclosed "+t,m)}return{back:function(e){y.push(e)},endOfFile:function(){return 0===y.length&&m>=f},nextToken:function(e){if(y.length)return y.pop();if(m>=f)return;let t=!!e&&e.ignoreUnclosed;switch(r=p.charCodeAt(m),r){case df:case ff:case gf:case yf:case mf:n=m;do{n+=1,r=p.charCodeAt(n)}while(r===ff||r===df||r===gf||r===yf||r===mf);h=["space",p.slice(m,n)],m=n-1;break;case wf:case vf:case Sf:case Cf:case kf:case Ef:case _f:{let e=String.fromCharCode(r);h=[e,e,m];break}case bf:if(c=g.length?g.pop()[1]:"",u=p.charCodeAt(m+1),"url"===c&&u!==cf&&u!==uf&&u!==ff&&u!==df&&u!==gf&&u!==mf&&u!==yf){n=m;do{if(a=!1,n=p.indexOf(")",n+1),-1===n){if(d||t){n=m;break}w("bracket")}for(l=n;p.charCodeAt(l-1)===hf;)l-=1,a=!a}while(a);h=["brackets",p.slice(m,n+1),m,n],m=n}else n=p.indexOf(")",m+1),i=p.slice(m,n+1),-1===n||If.test(i)?h=["(","(",m]:(h=["brackets",i,m,n],m=n);break;case cf:case uf:s=r===cf?"'":'"',n=m;do{if(a=!1,n=p.indexOf(s,n+1),-1===n){if(d||t){n=m+1;break}w("string")}for(l=n;p.charCodeAt(l-1)===hf;)l-=1,a=!a}while(a);h=["string",p.slice(m,n+1),m,n],m=n;break;case xf:Of.lastIndex=m+1,Of.test(p),n=0===Of.lastIndex?p.length-1:Of.lastIndex-2,h=["at-word",p.slice(m,n+1),m,n],m=n;break;case hf:for(n=m,o=!0;p.charCodeAt(n+1)===hf;)n+=1,o=!o;if(r=p.charCodeAt(n+1),o&&r!==pf&&r!==ff&&r!==df&&r!==gf&&r!==yf&&r!==mf&&(n+=1,Rf.test(p.charAt(n)))){for(;Rf.test(p.charAt(n+1));)n+=1;p.charCodeAt(n+1)===ff&&(n+=1)}h=["word",p.slice(m,n+1),m,n],m=n;break;default:r===pf&&p.charCodeAt(m+1)===Tf?(n=p.indexOf("*/",m+2)+1,0===n&&(d||t?n=p.length:w("comment")),h=["comment",p.slice(m,n+1),m,n],m=n):(Af.lastIndex=m+1,Af.test(p),n=0===Af.lastIndex?p.length-1:Af.lastIndex-2,h=["word",p.slice(m,n+1),m,n],g.push(h),m=n)}return m++,h},position:function(){return m}}},Yf=Dd,Xf=Pf,Jf=Bf,Kf=Zf;const qf={empty:!0,space:!0};var Qf=class{constructor(e){this.input=e,this.root=new Jf,this.current=this.root,this.spaces="",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t,r,n,s=new Xf;s.name=e[1].slice(1),""===s.name&&this.unnamedAtrule(s,e),this.init(s,e[2]);let i=!1,o=!1,a=[],l=[];for(;!this.tokenizer.endOfFile();){if(t=(e=this.tokenizer.nextToken())[0],"("===t||"["===t?l.push("("===t?")":"]"):"{"===t&&l.length>0?l.push("}"):t===l[l.length-1]&&l.pop(),0===l.length){if(";"===t){s.source.end=this.getPosition(e[2]),s.source.end.offset++,this.semicolon=!0;break}if("{"===t){o=!0;break}if("}"===t){if(a.length>0){for(n=a.length-1,r=a[n];r&&"space"===r[0];)r=a[--n];r&&(s.source.end=this.getPosition(r[3]||r[2]),s.source.end.offset++)}this.end(e);break}a.push(e)}else a.push(e);if(this.tokenizer.endOfFile()){i=!0;break}}s.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(s.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(s,"params",a),i&&(e=a[a.length-1],s.source.end=this.getPosition(e[3]||e[2]),s.source.end.offset++,this.spaces=s.raws.between,s.raws.between="")):(s.raws.afterName="",s.params=""),o&&(s.nodes=[],this.current=s)}checkMissedSemicolon(e){let t=this.colon(e);if(!1===t)return;let r,n=0;for(let s=t-1;s>=0&&(r=e[s],"space"===r[0]||(n+=1,2!==n));s--);throw this.input.error("Missed semicolon","word"===r[0]?r[3]+1:r[2])}colon(e){let t,r,n,s=0;for(let[i,o]of e.entries()){if(t=o,r=t[0],"("===r&&(s+=1),")"===r&&(s-=1),0===s&&":"===r){if(n){if("word"===n[0]&&"progid"===n[1])continue;return i}this.doubleColon(t)}n=t}return!1}comment(e){let t=new Yf;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let r=e[1].slice(2,-2);if(/^\s*$/.test(r))t.text="",t.raws.left=r,t.raws.right="";else{let e=r.match(/^(\s*)([^]*\S)(\s*)$/);t.text=e[2],t.raws.left=e[1],t.raws.right=e[3]}}createTokenizer(){this.tokenizer=Wf(this.input)}decl(e,t){let r=new $f;this.init(r,e[0][2]);let n,s=e[e.length-1];for(";"===s[0]&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(s[3]||s[2]||function(e){for(let t=e.length-1;t>=0;t--){let r=e[t],n=r[3]||r[2];if(n)return n}}(e)),r.source.end.offset++;"word"!==e[0][0];)1===e.length&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop="";e.length;){let t=e[0][0];if(":"===t||"space"===t||"comment"===t)break;r.prop+=e.shift()[1]}for(r.raws.between="";e.length;){if(n=e.shift(),":"===n[0]){r.raws.between+=n[1];break}"word"===n[0]&&/\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1]}"_"!==r.prop[0]&&"*"!==r.prop[0]||(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));let i,o=[];for(;e.length&&(i=e[0][0],"space"===i||"comment"===i);)o.push(e.shift());this.precheckMissedSemicolon(e);for(let t=e.length-1;t>=0;t--){if(n=e[t],"!important"===n[1].toLowerCase()){r.important=!0;let n=this.stringFrom(e,t);n=this.spacesFromEnd(e)+n," !important"!==n&&(r.raws.important=n);break}if("important"===n[1].toLowerCase()){let n=e.slice(0),s="";for(let e=t;e>0;e--){let t=n[e][0];if(0===s.trim().indexOf("!")&&"space"!==t)break;s=n.pop()[1]+s}0===s.trim().indexOf("!")&&(r.important=!0,r.raws.important=s,e=n)}if("space"!==n[0]&&"comment"!==n[0])break}e.some(e=>"space"!==e[0]&&"comment"!==e[0])&&(r.raws.between+=o.map(e=>e[1]).join(""),o=[]),this.raw(r,"value",o.concat(e),t),r.value.includes(":")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error("Double colon",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new Kf;this.init(t,e[2]),t.selector="",t.raws.between="",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.spaces="",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||"")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let e=this.current.nodes[this.current.nodes.length-1];e&&"rule"===e.type&&!e.raws.ownSemicolon&&(e.raws.ownSemicolon=this.spaces,this.spaces="")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces="","comment"!==e.type&&(this.semicolon=!1)}other(e){let t=!1,r=null,n=!1,s=null,i=[],o=e[1].startsWith("--"),a=[],l=e;for(;l;){if(r=l[0],a.push(l),"("===r||"["===r)s||(s=l),i.push("("===r?")":"]");else if(o&&n&&"{"===r)s||(s=l),i.push("}");else if(0===i.length){if(";"===r){if(n)return void this.decl(a,o);break}if("{"===r)return void this.rule(a);if("}"===r){this.tokenizer.back(a.pop()),t=!0;break}":"===r&&(n=!0)}else r===i[i.length-1]&&(i.pop(),0===i.length&&(s=null));l=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),i.length>0&&this.unclosedBracket(s),t&&n){if(!o)for(;a.length&&(l=a[a.length-1][0],"space"===l||"comment"===l);)this.tokenizer.back(a.pop());this.decl(a,o)}else this.unknownWord(a)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case"space":this.spaces+=e[1];break;case";":this.freeSemicolon(e);break;case"}":this.end(e);break;case"comment":this.comment(e);break;case"at-word":this.atrule(e);break;case"{":this.emptyRule(e);break;default:this.other(e)}this.endFile()}precheckMissedSemicolon(){}raw(e,t,r,n){let s,i,o,a,l=r.length,c="",u=!0;for(let e=0;ee+t[1],"");e.raws[t]={raw:n,value:c}}e[t]=c}rule(e){e.pop();let t=new Kf;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,"selector",e),this.current=t}spacesAndCommentsFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t||"comment"===t);)r=e.pop()[1]+r;return r}spacesAndCommentsFromStart(e){let t,r="";for(;e.length&&(t=e[0][0],"space"===t||"comment"===t);)r+=e.shift()[1];return r}spacesFromEnd(e){let t,r="";for(;e.length&&(t=e[e.length-1][0],"space"===t);)r=e.pop()[1]+r;return r}stringFrom(e,t){let r="";for(let n=t;n_m(e)),e}let Sm={},Cm=class e{constructor(t,r,n){let s;if(this.stringified=!1,this.processed=!1,"object"!=typeof r||null===r||"root"!==r.type&&"document"!==r.type)if(r instanceof e||r instanceof pm)s=_m(r.root),r.map&&(void 0===n.map&&(n.map={}),n.map.inline||(n.map.inline=!1),n.map.prev=r.map);else{let e=dm;n.syntax&&(e=n.syntax.parse),n.parser&&(e=n.parser),e.parse&&(e=e.parse);try{s=e(r,n)}catch(e){this.processed=!0,this.error=e}s&&!s[om]&&cm.rebuild(s)}else s=_m(r);this.result=new pm(t,s,n),this.helpers={...Sm,postcss:Sm,result:this.result},this.plugins=this.processor.plugins.map(e=>"object"==typeof e&&e.prepare?{...e,...e.prepare(this.result)}:e)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error("Use process(css).then(cb) to work with async plugins")}handleError(e,t){let r=this.result.lastPlugin;try{if(t&&t.addToError(e),this.error=e,"CssSyntaxError"!==e.name||e.plugin){if(r.postcssVersion&&"production"!==process.env.NODE_ENV){let e=r.postcssPlugin,t=r.postcssVersion,n=this.result.processor.version,s=t.split("."),i=n.split(".");(s[0]!==i[0]||parseInt(s[1])>parseInt(i[1]))&&console.error("Unknown error from PostCSS plugin. Your current PostCSS version is "+n+", but "+e+" uses "+t+". Perhaps this is the source of the error below.")}}else e.plugin=r.postcssPlugin,e.setMessage()}catch(e){console&&console.error&&console.error(e)}return e}prepareVisitors(){this.listeners={};let e=(e,t,r)=>{this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push([e,r])};for(let t of this.plugins)if("object"==typeof t)for(let r in t){if(!gm[r]&&/^[A-Z]/.test(r))throw new Error(`Unknown event ${r} in ${t.postcssPlugin}. Try to update PostCSS (${this.processor.version} now).`);if(!ym[r])if("object"==typeof t[r])for(let n in t[r])e(t,"*"===n?r:r+"-"+n.toLowerCase(),t[r][n]);else"function"==typeof t[r]&&e(t,r,t[r])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e0;){let e=this.visitTick(t);if(wm(e))try{await e}catch(e){let r=t[t.length-1].node;throw this.handleError(e,r)}}}if(this.listeners.OnceExit)for(let[t,r]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if("document"===e.type){let t=e.nodes.map(e=>r(e,this.helpers));await Promise.all(t)}else await r(e,this.helpers)}catch(e){throw this.handleError(e)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if("object"==typeof e&&e.Once){if("document"===this.result.root.type){let t=this.result.root.nodes.map(t=>e.Once(t,this.helpers));return wm(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}if("function"==typeof e)return e(this.result.root,this.result)}catch(e){throw this.handleError(e)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=lm;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let r=new am(t,this.result.root,this.result.opts).generate();return this.result.css=r[0],this.result.map=r[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){if(wm(this.runOnRoot(e)))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[im];)e[im]=!0,this.walkSync(e);if(this.listeners.OnceExit)if("document"===e.type)for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this.opts||hm("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[r,n]of e){let e;this.result.lastPlugin=r;try{e=n(t,this.helpers)}catch(e){throw this.handleError(e,t.proxyOf)}if("root"!==t.type&&"document"!==t.type&&!t.parent)return!0;if(wm(e))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:r,visitors:n}=t;if("root"!==r.type&&"document"!==r.type&&!r.parent)return void e.pop();if(n.length>0&&t.visitorIndex{e[im]||this.walkSync(e)});else{let t=this.listeners[r];if(t&&this.visitSync(t,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return"LazyResult"}};Cm.registerPostcss=e=>{Sm=e};var Em=Cm;Cm.default=Cm,fm.registerLazyResult(Cm),um.registerLazyResult(Cm);let Tm=Nd,km=zp,xm=rf,Om=sm;const Am=lf;let Im=class{constructor(e,t,r){let n;t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;let s=km;this.result=new Am(this._processor,n,this._opts),this.result.css=t;let i=this;Object.defineProperty(this.result,"root",{get:()=>i.root});let o=new Tm(s,n,this._opts,t);if(o.isMap()){let[e,t]=o.generate();e&&(this.result.css=e),t&&(this.result.map=t)}else o.clearAnnotation(),this.result.css=o.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return"production"!==process.env.NODE_ENV&&("from"in this._opts||xm("Without `from` option PostCSS could generate wrong source map and will not find Browserslist config. Set it to CSS file path or to `undefined` to prevent this warning.")),this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=Om;try{e=t(this._css,this._opts)}catch(e){this.error=e}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return"NoWorkResult"}};var Rm=Im;Im.default=Im;let Mm=Rm,Nm=Em,Pm=ef,Lm=Bf,Dm=class{constructor(e=[]){this.version="8.4.38",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let r of e)if(!0===r.postcss?r=r():r.postcss&&(r=r.postcss),"object"==typeof r&&Array.isArray(r.plugins))t=t.concat(r.plugins);else if("object"==typeof r&&r.postcssPlugin)t.push(r);else if("function"==typeof r)t.push(r);else{if("object"!=typeof r||!r.parse&&!r.stringify)throw new Error(r+" is not a PostCSS plugin");if("production"!==process.env.NODE_ENV)throw new Error("PostCSS syntaxes cannot be used as plugins. Instead, please use one of the syntax/parser/stringifier options as outlined in your PostCSS runner documentation.")}return t}process(e,t={}){return this.plugins.length||t.parser||t.stringifier||t.syntax?new Nm(this,e,t):new Mm(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};var Um=Dm;Dm.default=Dm,Lm.registerProcessor(Dm),Pm.registerProcessor(Dm);let Fm=qp,Bm=ad,jm=Dd,zm=Pf,Vm=Sd,Gm=Bf,Hm=Zf;function Zm(e,t){if(Array.isArray(e))return e.map(e=>Zm(e));let{inputs:r,...n}=e;if(r){t=[];for(let e of r){let r={...e,__proto__:Vm.prototype};r.map&&(r.map={...r.map,__proto__:Bm.prototype}),t.push(r)}}if(n.nodes&&(n.nodes=e.nodes.map(e=>Zm(e,t))),n.source){let{inputId:e,...r}=n.source;n.source=r,null!=e&&(n.source.input=t[e])}if("root"===n.type)return new Gm(n);if("decl"===n.type)return new Fm(n);if("rule"===n.type)return new Hm(n);if("comment"===n.type)return new jm(n);if("atrule"===n.type)return new zm(n);throw new Error("Unknown node type: "+e.type)}var $m=Zm;Zm.default=Zm;let Wm=Pp,Ym=qp,Xm=Em,Jm=Xd,Km=Um,qm=zp,Qm=$m,eg=ef,tg=sf,rg=Dd,ng=Pf,sg=lf,ig=Sd,og=sm,ag=zf,lg=Zf,cg=Bf,ug=Xp;function hg(...e){return 1===e.length&&Array.isArray(e[0])&&(e=e[0]),new Km(e)}hg.plugin=function(e,t){let r,n=!1;function s(...r){console&&console.warn&&!n&&(n=!0,console.warn(e+": postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration"),process.env.LANG&&process.env.LANG.startsWith("cn")&&console.warn(e+": 里面 postcss.plugin 被弃用. 迁移指南:\nhttps://www.w3ctech.com/topic/2226"));let s=t(...r);return s.postcssPlugin=e,s.postcssVersion=(new Km).version,s}return Object.defineProperty(s,"postcss",{get:()=>(r||(r=s()),r)}),s.process=function(e,t,r){return hg([s(r)]).process(e,t)},s},hg.stringify=qm,hg.parse=og,hg.fromJSON=Qm,hg.list=ag,hg.comment=e=>new rg(e),hg.atRule=e=>new ng(e),hg.decl=e=>new Ym(e),hg.rule=e=>new lg(e),hg.root=e=>new cg(e),hg.document=e=>new eg(e),hg.CssSyntaxError=Wm,hg.Declaration=Ym,hg.Container=Jm,hg.Processor=Km,hg.Document=eg,hg.Comment=rg,hg.Warning=tg,hg.AtRule=ng,hg.Result=sg,hg.Input=ig,hg.Rule=lg,hg.Root=cg,hg.Node=ug,Xm.registerPostcss(hg);var pg=hg;hg.default=hg;const dg=Ep(pg);dg.stringify,dg.fromJSON,dg.plugin,dg.parse,dg.list,dg.document,dg.comment,dg.atRule,dg.rule,dg.decl,dg.root,dg.CssSyntaxError,dg.Declaration,dg.Container,dg.Processor,dg.Document,dg.Comment,dg.Warning,dg.AtRule,dg.Result,dg.Input,dg.Rule,dg.Root,dg.Node;class fg{constructor(...e){Cp(this,"parentElement",null),Cp(this,"parentNode",null),Cp(this,"ownerDocument"),Cp(this,"firstChild",null),Cp(this,"lastChild",null),Cp(this,"previousSibling",null),Cp(this,"nextSibling",null),Cp(this,"ELEMENT_NODE",1),Cp(this,"TEXT_NODE",3),Cp(this,"nodeType"),Cp(this,"nodeName"),Cp(this,"RRNodeType")}get childNodes(){const e=[];let t=this.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}contains(e){if(!(e instanceof fg))return!1;if(e.ownerDocument!==this.ownerDocument)return!1;if(e===this)return!0;for(;e.parentNode;){if(e.parentNode===this)return!0;e=e.parentNode}return!1}appendChild(e){throw new Error("RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.")}insertBefore(e,t){throw new Error("RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.")}removeChild(e){throw new Error("RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.")}toString(){return"RRNode"}}const mg={Node:["childNodes","parentNode","parentElement","textContent","ownerDocument"],ShadowRoot:["host","styleSheets"],Element:["shadowRoot","querySelector","querySelectorAll"],MutationObserver:[]},gg={Node:["contains","getRootNode"],ShadowRoot:["getSelection"],Element:[],MutationObserver:["constructor"]},yg={};function wg(e){if(yg[e])return yg[e];const t=globalThis[e],r=t.prototype,n=e in mg?mg[e]:void 0,s=Boolean(n&&n.every(e=>{var t,n;return Boolean(null==(n=null==(t=Object.getOwnPropertyDescriptor(r,e))?void 0:t.get)?void 0:n.toString().includes("[native code]"))})),i=e in gg?gg[e]:void 0,o=Boolean(i&&i.every(e=>{var t;return"function"==typeof r[e]&&(null==(t=r[e])?void 0:t.toString().includes("[native code]"))}));if(s&&o&&!globalThis.Zone)return yg[e]=t.prototype,t.prototype;try{const n=document.createElement("iframe");document.body.appendChild(n);const s=n.contentWindow;if(!s)return t.prototype;const i=s[e].prototype;return document.body.removeChild(n),i?yg[e]=i:r}catch{return r}}const vg={};function bg(e,t,r){var n;const s=`${e}.${String(r)}`;if(vg[s])return vg[s].call(t);const i=wg(e),o=null==(n=Object.getOwnPropertyDescriptor(i,r))?void 0:n.get;return o?(vg[s]=o,o.call(t)):t[r]}const _g={};function Sg(e,t,r){const n=`${e}.${String(r)}`;if(_g[n])return _g[n].bind(t);const s=wg(e)[r];return"function"!=typeof s?t[r]:(_g[n]=s,s.bind(t))}function Cg(){return wg("MutationObserver").constructor}function Eg(e,t,r){try{if(!(t in e))return()=>{};const n=e[t],s=r(n);return"function"==typeof s&&(s.prototype=s.prototype||{},Object.defineProperties(s,{__rrweb_original__:{enumerable:!1,value:n}})),e[t]=s,()=>{e[t]=n}}catch{return()=>{}}}const Tg={ownerDocument:function(e){return bg("Node",e,"ownerDocument")},childNodes:function(e){return bg("Node",e,"childNodes")},parentNode:function(e){return bg("Node",e,"parentNode")},parentElement:function(e){return bg("Node",e,"parentElement")},textContent:function(e){return bg("Node",e,"textContent")},contains:function(e,t){return Sg("Node",e,"contains")(t)},getRootNode:function(e){return Sg("Node",e,"getRootNode")()},host:function(e){return e&&"host"in e?bg("ShadowRoot",e,"host"):null},styleSheets:function(e){return e.styleSheets},shadowRoot:function(e){return e&&"shadowRoot"in e?bg("Element",e,"shadowRoot"):null},querySelector:function(e,t){return bg("Element",e,"querySelector")(t)},querySelectorAll:function(e,t){return bg("Element",e,"querySelectorAll")(t)},mutationObserver:Cg,patch:Eg};function kg(e,t,r=document){const n={capture:!0,passive:!0};return r.addEventListener(e,t,n),()=>r.removeEventListener(e,t,n)}const xg="Please stop import mirror directly. Instead of that,\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\r\nor you can use record.mirror to access the mirror instance during recording.";let Og={map:{},getId:()=>(console.error(xg),-1),getNode:()=>(console.error(xg),null),removeNodeFromMap(){console.error(xg)},has:()=>(console.error(xg),!1),reset(){console.error(xg)}};function Ag(e,t,r={}){let n=null,s=0;return function(...i){const o=Date.now();s||!1!==r.leading||(s=o);const a=t-(o-s),l=this;a<=0||a>t?(n&&(clearTimeout(n),n=null),s=o,e.apply(l,i)):n||!1===r.trailing||(n=setTimeout(()=>{s=!1===r.leading?0:Date.now(),n=null,e.apply(l,i)},a))}}function Ig(e,t,r,n,s=window){const i=s.Object.getOwnPropertyDescriptor(e,t);return s.Object.defineProperty(e,t,n?r:{set(e){setTimeout(()=>{r.set.call(this,e)},0),i&&i.set&&i.set.call(this,e)}}),()=>Ig(e,t,i||{},!0)}"undefined"!=typeof window&&window.Proxy&&window.Reflect&&(Og=new Proxy(Og,{get:(e,t,r)=>("map"===t&&console.error(xg),Reflect.get(e,t,r))}));let Rg=Date.now;function Mg(e){var t,r,n,s;const i=e.document;return{left:i.scrollingElement?i.scrollingElement.scrollLeft:void 0!==e.pageXOffset?e.pageXOffset:i.documentElement.scrollLeft||(null==i?void 0:i.body)&&(null==(t=Tg.parentElement(i.body))?void 0:t.scrollLeft)||(null==(r=null==i?void 0:i.body)?void 0:r.scrollLeft)||0,top:i.scrollingElement?i.scrollingElement.scrollTop:void 0!==e.pageYOffset?e.pageYOffset:(null==i?void 0:i.documentElement.scrollTop)||(null==i?void 0:i.body)&&(null==(n=Tg.parentElement(i.body))?void 0:n.scrollTop)||(null==(s=null==i?void 0:i.body)?void 0:s.scrollTop)||0}}function Ng(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Pg(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function Lg(e){if(!e)return null;return e.nodeType===e.ELEMENT_NODE?e:Tg.parentElement(e)}function Dg(e,t,r,n){if(!e)return!1;const s=Lg(e);if(!s)return!1;try{if("string"==typeof t){if(s.classList.contains(t))return!0;if(n&&null!==s.closest("."+t))return!0}else if(xl(s,t,n))return!0}catch(e){}if(r){if(s.matches(r))return!0;if(n&&null!==s.closest(r))return!0}return!1}function Ug(e,t,r){return!("TITLE"!==e.tagName||!r.headTitleMutations)||-2===t.getId(e)}function Fg(e,t){if(Ka(e))return!1;const r=t.getId(e);if(!t.has(r))return!0;const n=Tg.parentNode(e);return(!n||n.nodeType!==e.DOCUMENT_NODE)&&(!n||Fg(n,t))}function Bg(e){return Boolean(e.changedTouches)}function jg(e,t){return Boolean("IFRAME"===e.nodeName&&t.getMeta(e))}function zg(e,t){return Boolean("LINK"===e.nodeName&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&"stylesheet"===e.getAttribute("rel")&&t.getMeta(e))}function Vg(e){return!!e&&(e instanceof fg&&"shadowRoot"in e?Boolean(e.shadowRoot):Boolean(Tg.shadowRoot(e)))}/[1-9][0-9]{12}/.test(Date.now().toString())||(Rg=()=>(new Date).getTime());class Gg{constructor(){Ua(this,"id",1),Ua(this,"styleIDMap",new WeakMap),Ua(this,"idStyleMap",new Map)}getId(e){return this.styleIDMap.get(e)??-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let r;return r=void 0===t?this.id++:t,this.styleIDMap.set(e,r),this.idStyleMap.set(r,e),r}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}function Hg(e){var t;let r=null;return"getRootNode"in e&&(null==(t=Tg.getRootNode(e))?void 0:t.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&Tg.host(Tg.getRootNode(e))&&(r=Tg.host(Tg.getRootNode(e))),r}function Zg(e){const t=Tg.ownerDocument(e);if(!t)return!1;const r=function(e){let t,r=e;for(;t=Hg(r);)r=t;return r}(e);return Tg.contains(t,r)}function $g(e){const t=Tg.ownerDocument(e);return!!t&&(Tg.contains(t,e)||Zg(e))}var Wg=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(Wg||{}),Yg=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(Yg||{}),Xg=(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(Xg||{}),Jg=(e=>(e[e.Mouse=0]="Mouse",e[e.Pen=1]="Pen",e[e.Touch=2]="Touch",e))(Jg||{}),Kg=(e=>(e[e["2D"]=0]="2D",e[e.WebGL=1]="WebGL",e[e.WebGL2=2]="WebGL2",e))(Kg||{}),qg=(e=>(e[e.Play=0]="Play",e[e.Pause=1]="Pause",e[e.Seeked=2]="Seeked",e[e.VolumeChange=3]="VolumeChange",e[e.RateChange=4]="RateChange",e))(qg||{}),Qg=(e=>(e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment",e))(Qg||{});function ey(e){return"__ln"in e}class ty{constructor(){Ua(this,"length",0),Ua(this,"head",null),Ua(this,"tail",null)}get(e){if(e>=this.length)throw new Error("Position outside of list range");let t=this.head;for(let r=0;r`${e}@${t}`;class ny{constructor(){Ua(this,"frozen",!1),Ua(this,"locked",!1),Ua(this,"texts",[]),Ua(this,"attributes",[]),Ua(this,"attributeMap",new WeakMap),Ua(this,"removes",[]),Ua(this,"mapRemoves",[]),Ua(this,"movedMap",{}),Ua(this,"addedSet",new Set),Ua(this,"movedSet",new Set),Ua(this,"droppedSet",new Set),Ua(this,"removesSubTreeCache",new Set),Ua(this,"mutationCb"),Ua(this,"blockClass"),Ua(this,"blockSelector"),Ua(this,"maskTextClass"),Ua(this,"maskTextSelector"),Ua(this,"inlineStylesheet"),Ua(this,"maskInputOptions"),Ua(this,"maskTextFn"),Ua(this,"maskInputFn"),Ua(this,"keepIframeSrcFn"),Ua(this,"recordCanvas"),Ua(this,"inlineImages"),Ua(this,"slimDOMOptions"),Ua(this,"dataURLOptions"),Ua(this,"doc"),Ua(this,"mirror"),Ua(this,"iframeManager"),Ua(this,"stylesheetManager"),Ua(this,"shadowDomManager"),Ua(this,"canvasManager"),Ua(this,"processedNodeManager"),Ua(this,"unattachedDoc"),Ua(this,"processMutations",e=>{e.forEach(this.processMutation),this.emit()}),Ua(this,"emit",()=>{if(this.frozen||this.locked)return;const e=[],t=new Set,r=new ty,n=e=>{let t=e,r=-2;for(;-2===r;)t=t&&t.nextSibling,r=t&&this.mirror.getId(t);return r},s=s=>{const i=Tg.parentNode(s);if(!i||!$g(s))return;let o=!1;if(s.nodeType===Node.TEXT_NODE){const e=i.tagName;if("TEXTAREA"===e)return;"STYLE"===e&&this.addedSet.has(i)&&(o=!0)}const a=Ka(i)?this.mirror.getId(Hg(s)):this.mirror.getId(i),l=n(s);if(-1===a||-1===l)return r.addNode(s);const c=Ml(s,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:e=>{jg(e,this.mirror)&&this.iframeManager.addIframe(e),zg(e,this.mirror)&&this.stylesheetManager.trackLinkElement(e),Vg(s)&&this.shadowDomManager.addShadowRoot(Tg.shadowRoot(s),this.doc)},onIframeLoad:(e,t)=>{this.iframeManager.attachIframe(e,t),this.shadowDomManager.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{this.stylesheetManager.attachLinkElement(e,t)},cssCaptured:o});c&&(e.push({parentId:a,nextId:l,node:c}),t.add(c.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const e of this.movedSet)iy(this.removesSubTreeCache,e,this.mirror)&&!this.movedSet.has(Tg.parentNode(e))||s(e);for(const e of this.addedSet)oy(this.droppedSet,e)||iy(this.removesSubTreeCache,e,this.mirror)?oy(this.movedSet,e)?s(e):this.droppedSet.add(e):s(e);let i=null;for(;r.length;){let e=null;if(i){const t=this.mirror.getId(Tg.parentNode(i.value)),r=n(i.value);-1!==t&&-1!==r&&(e=i)}if(!e){let t=r.tail;for(;t;){const r=t;if(t=t.previous,r){const t=this.mirror.getId(Tg.parentNode(r.value));if(-1===n(r.value))continue;if(-1!==t){e=r;break}{const t=r.value,n=Tg.parentNode(t);if(n&&n.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const t=Tg.host(n);if(-1!==this.mirror.getId(t)){e=r;break}}}}}}if(!e){for(;r.head;)r.removeNode(r.head.value);break}i=e.previous,r.removeNode(e.value),s(e.value)}const o={texts:this.texts.map(e=>{const t=e.node,r=Tg.parentNode(t);return r&&"TEXTAREA"===r.tagName&&this.genTextAreaValueMutation(r),{id:this.mirror.getId(t),value:e.value}}).filter(e=>!t.has(e.id)).filter(e=>this.mirror.has(e.id)),attributes:this.attributes.map(e=>{const{attributes:t}=e;if("string"==typeof t.style){const r=JSON.stringify(e.styleDiff),n=JSON.stringify(e._unchangedStyles);r.length!t.has(e.id)).filter(e=>this.mirror.has(e.id)),removes:this.removes,adds:e};(o.texts.length||o.attributes.length||o.removes.length||o.adds.length)&&(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.removesSubTreeCache=new Set,this.movedMap={},this.mutationCb(o))}),Ua(this,"genTextAreaValueMutation",e=>{let t=this.attributeMap.get(e);t||(t={node:e,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(t),this.attributeMap.set(e,t));const r=Array.from(Tg.childNodes(e),e=>Tg.textContent(e)||"").join("");t.attributes.value=rl({element:e,maskInputOptions:this.maskInputOptions,tagName:e.tagName,type:il(e),value:r,maskInputFn:this.maskInputFn})}),Ua(this,"processMutation",e=>{if(!Ug(e.target,this.mirror,this.slimDOMOptions))switch(e.type){case"characterData":{const t=Tg.textContent(e.target);Dg(e.target,this.blockClass,this.blockSelector,!1)||t===e.oldValue||this.texts.push({value:Ol(e.target,this.maskTextClass,this.maskTextSelector,!0)&&t?this.maskTextFn?this.maskTextFn(t,Lg(e.target)):t.replace(/[\S]/g,"*"):t,node:e.target});break}case"attributes":{const t=e.target;let r=e.attributeName,n=e.target.getAttribute(r);if("value"===r){const e=il(t);n=rl({element:t,maskInputOptions:this.maskInputOptions,tagName:t.tagName,type:e,value:n,maskInputFn:this.maskInputFn})}if(Dg(e.target,this.blockClass,this.blockSelector,!1)||n===e.oldValue)return;let s=this.attributeMap.get(e.target);if("IFRAME"===t.tagName&&"src"===r&&!this.keepIframeSrcFn(n)){if(t.contentDocument)return;r="rr_src"}if(s||(s={node:e.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(s),this.attributeMap.set(e.target,s)),"type"===r&&"INPUT"===t.tagName&&"password"===(e.oldValue||"").toLowerCase()&&t.setAttribute("data-rr-is-password","true"),!kl(t.tagName,r))if(s.attributes[r]=Tl(this.doc,nl(t.tagName),nl(r),n),"style"===r){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(e){this.unattachedDoc=this.doc}const r=this.unattachedDoc.createElement("span");e.oldValue&&r.setAttribute("style",e.oldValue);for(const e of Array.from(t.style)){const n=t.style.getPropertyValue(e),i=t.style.getPropertyPriority(e);n!==r.style.getPropertyValue(e)||i!==r.style.getPropertyPriority(e)?s.styleDiff[e]=""===i?n:[n,i]:s._unchangedStyles[e]=[n,i]}for(const e of Array.from(r.style))""===t.style.getPropertyValue(e)&&(s.styleDiff[e]=!1)}else"open"===r&&"DIALOG"===t.tagName&&(t.matches("dialog:modal")?s.attributes.rr_open_mode="modal":s.attributes.rr_open_mode="non-modal");break}case"childList":if(Dg(e.target,this.blockClass,this.blockSelector,!0))return;if("TEXTAREA"===e.target.tagName)return void this.genTextAreaValueMutation(e.target);e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const r=this.mirror.getId(t),n=Ka(e.target)?this.mirror.getId(Tg.host(e.target)):this.mirror.getId(e.target);Dg(e.target,this.blockClass,this.blockSelector,!1)||Ug(t,this.mirror,this.slimDOMOptions)||!function(e,t){return-1!==t.getId(e)}(t,this.mirror)||(this.addedSet.has(t)?(sy(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&-1===r||Fg(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[ry(r,n)]?sy(this.movedSet,t):(this.removes.push({parentId:n,id:r,isShadow:!(!Ka(e.target)||!qa(e.target))||void 0}),function(e,t){const r=[e];for(;r.length;){const e=r.pop();t.has(e)||(t.add(e),Tg.childNodes(e).forEach(e=>r.push(e)))}}(t,this.removesSubTreeCache))),this.mapRemoves.push(t))})}}),Ua(this,"genAdds",(e,t)=>{if(!this.processedNodeManager.inOtherBuffer(e,this)&&!this.addedSet.has(e)&&!this.movedSet.has(e)){if(this.mirror.hasNode(e)){if(Ug(e,this.mirror,this.slimDOMOptions))return;this.movedSet.add(e);let r=null;t&&this.mirror.hasNode(t)&&(r=this.mirror.getId(t)),r&&-1!==r&&(this.movedMap[ry(this.mirror.getId(e),r)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);Dg(e,this.blockClass,this.blockSelector,!1)||(Tg.childNodes(e).forEach(e=>this.genAdds(e)),Vg(e)&&Tg.childNodes(Tg.shadowRoot(e)).forEach(t=>{this.processedNodeManager.add(t,this),this.genAdds(t,e)}))}})}init(e){["mutationCb","blockClass","blockSelector","maskTextClass","maskTextSelector","inlineStylesheet","maskInputOptions","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function sy(e,t){e.delete(t),Tg.childNodes(t).forEach(t=>sy(e,t))}function iy(e,t,r){return 0!==e.size&&function(e,t){const r=Tg.parentNode(t);return!!r&&e.has(r)}(e,t)}function oy(e,t){return 0!==e.size&&ay(e,t)}function ay(e,t){const r=Tg.parentNode(t);return!!r&&(!!e.has(r)||ay(e,r))}let ly;const cy=e=>{if(!ly)return e;return(...t)=>{try{return e(...t)}catch(e){if(ly&&!0===ly(e))return;throw e}}},uy=[];function hy(e){try{if("composedPath"in e){const t=e.composedPath();if(t.length)return t[0]}else if("path"in e&&e.path.length)return e.path[0]}catch{}return e&&e.target}function py(e,t){const r=new ny;uy.push(r),r.init(e);const n=new(Cg())(cy(r.processMutations.bind(r)));return n.observe(t,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),n}function dy({mouseInteractionCb:e,doc:t,mirror:r,blockClass:n,blockSelector:s,sampling:i}){if(!1===i.mouseInteraction)return()=>{};const o=!0===i.mouseInteraction||void 0===i.mouseInteraction?{}:i.mouseInteraction,a=[];let l=null;return Object.keys(Xg).filter(e=>Number.isNaN(Number(e))&&!e.endsWith("_Departed")&&!1!==o[e]).forEach(i=>{let o=nl(i);const c=(t=>i=>{const o=hy(i);if(Dg(o,n,s,!0))return;let a=null,c=t;if("pointerType"in i){switch(i.pointerType){case"mouse":a=Jg.Mouse;break;case"touch":a=Jg.Touch;break;case"pen":a=Jg.Pen}a===Jg.Touch?Xg[t]===Xg.MouseDown?c="TouchStart":Xg[t]===Xg.MouseUp&&(c="TouchEnd"):Jg.Pen}else Bg(i)&&(a=Jg.Touch);null!==a?(l=a,(c.startsWith("Touch")&&a===Jg.Touch||c.startsWith("Mouse")&&a===Jg.Mouse)&&(a=null)):Xg[t]===Xg.Click&&(a=l,l=null);const u=Bg(i)?i.changedTouches[0]:i;if(!u)return;const h=r.getId(o),{clientX:p,clientY:d}=u;cy(e)({type:Xg[c],id:h,x:p,y:d,...null!==a&&{pointerType:a}})})(i);if(window.PointerEvent)switch(Xg[i]){case Xg.MouseDown:case Xg.MouseUp:o=o.replace("mouse","pointer");break;case Xg.TouchStart:case Xg.TouchEnd:return}a.push(kg(o,c,t))}),cy(()=>{a.forEach(e=>e())})}function fy({scrollCb:e,doc:t,mirror:r,blockClass:n,blockSelector:s,sampling:i}){return kg("scroll",cy(Ag(cy(i=>{const o=hy(i);if(!o||Dg(o,n,s,!0))return;const a=r.getId(o);if(o===t&&t.defaultView){const r=Mg(t.defaultView);e({id:a,x:r.left,y:r.top})}else e({id:a,x:o.scrollLeft,y:o.scrollTop})}),i.scroll||100)),t)}const my=["INPUT","TEXTAREA","SELECT"],gy=new WeakMap;function yy(e){return function(e,t){if(_y("CSSGroupingRule")&&e.parentRule instanceof CSSGroupingRule||_y("CSSMediaRule")&&e.parentRule instanceof CSSMediaRule||_y("CSSSupportsRule")&&e.parentRule instanceof CSSSupportsRule||_y("CSSConditionRule")&&e.parentRule instanceof CSSConditionRule){const r=Array.from(e.parentRule.cssRules).indexOf(e);t.unshift(r)}else if(e.parentStyleSheet){const r=Array.from(e.parentStyleSheet.cssRules).indexOf(e);t.unshift(r)}return t}(e,[])}function wy(e,t,r){let n,s;return e?(e.ownerNode?n=t.getId(e.ownerNode):s=r.getId(e),{styleId:s,id:n}):{}}function vy({mirror:e,stylesheetManager:t},r){var n,s,i;let o=null;o="#document"===r.nodeName?e.getId(r):e.getId(Tg.host(r));const a="#document"===r.nodeName?null==(n=r.defaultView)?void 0:n.Document:null==(i=null==(s=r.ownerDocument)?void 0:s.defaultView)?void 0:i.ShadowRoot,l=(null==a?void 0:a.prototype)?Object.getOwnPropertyDescriptor(null==a?void 0:a.prototype,"adoptedStyleSheets"):void 0;return null!==o&&-1!==o&&a&&l?(Object.defineProperty(r,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get(){var e;return null==(e=l.get)?void 0:e.call(this)},set(e){var r;const n=null==(r=l.set)?void 0:r.call(this,e);if(null!==o&&-1!==o)try{t.adoptStyleSheets(e,o)}catch(e){}return n}}),cy(()=>{Object.defineProperty(r,"adoptedStyleSheets",{configurable:l.configurable,enumerable:l.enumerable,get:l.get,set:l.set})})):()=>{}}function by(e,t={}){const r=e.doc.defaultView;if(!r)return()=>{};let n;!function(e,t){const{mutationCb:r,mousemoveCb:n,mouseInteractionCb:s,scrollCb:i,viewportResizeCb:o,inputCb:a,mediaInteractionCb:l,styleSheetRuleCb:c,styleDeclarationCb:u,canvasMutationCb:h,fontCb:p,selectionCb:d,customElementCb:f}=e;e.mutationCb=(...e)=>{t.mutation&&t.mutation(...e),r(...e)},e.mousemoveCb=(...e)=>{t.mousemove&&t.mousemove(...e),n(...e)},e.mouseInteractionCb=(...e)=>{t.mouseInteraction&&t.mouseInteraction(...e),s(...e)},e.scrollCb=(...e)=>{t.scroll&&t.scroll(...e),i(...e)},e.viewportResizeCb=(...e)=>{t.viewportResize&&t.viewportResize(...e),o(...e)},e.inputCb=(...e)=>{t.input&&t.input(...e),a(...e)},e.mediaInteractionCb=(...e)=>{t.mediaInteaction&&t.mediaInteaction(...e),l(...e)},e.styleSheetRuleCb=(...e)=>{t.styleSheetRule&&t.styleSheetRule(...e),c(...e)},e.styleDeclarationCb=(...e)=>{t.styleDeclaration&&t.styleDeclaration(...e),u(...e)},e.canvasMutationCb=(...e)=>{t.canvasMutation&&t.canvasMutation(...e),h(...e)},e.fontCb=(...e)=>{t.font&&t.font(...e),p(...e)},e.selectionCb=(...e)=>{t.selection&&t.selection(...e),d(...e)},e.customElementCb=(...e)=>{t.customElement&&t.customElement(...e),f(...e)}}(e,t),e.recordDOM&&(n=py(e,e.doc));const s=function({mousemoveCb:e,sampling:t,doc:r,mirror:n}){if(!1===t.mousemove)return()=>{};const s="number"==typeof t.mousemove?t.mousemove:50,i="number"==typeof t.mousemoveCallback?t.mousemoveCallback:500;let o,a=[];const l=Ag(cy(t=>{const r=Date.now()-o;e(a.map(e=>(e.timeOffset-=r,e)),t),a=[],o=null}),i),c=cy(Ag(cy(e=>{const t=hy(e),{clientX:r,clientY:s}=Bg(e)?e.changedTouches[0]:e;o||(o=Rg()),a.push({x:r,y:s,id:n.getId(t),timeOffset:Rg()-o}),l("undefined"!=typeof DragEvent&&e instanceof DragEvent?Yg.Drag:e instanceof MouseEvent?Yg.MouseMove:Yg.TouchMove)}),s,{trailing:!1})),u=[kg("mousemove",c,r),kg("touchmove",c,r),kg("drag",c,r)];return cy(()=>{u.forEach(e=>e())})}(e),i=dy(e),o=fy(e),a=function({viewportResizeCb:e},{win:t}){let r=-1,n=-1;return kg("resize",cy(Ag(cy(()=>{const t=Ng(),s=Pg();r===t&&n===s||(e({width:Number(s),height:Number(t)}),r=t,n=s)}),200)),t)}(e,{win:r}),l=function({inputCb:e,doc:t,mirror:r,blockClass:n,blockSelector:s,ignoreClass:i,ignoreSelector:o,maskInputOptions:a,maskInputFn:l,sampling:c,userTriggeredOnInput:u}){function h(e){let r=hy(e);const c=e.isTrusted,h=r&&r.tagName;if(r&&"OPTION"===h&&(r=Tg.parentElement(r)),!r||!h||my.indexOf(h)<0||Dg(r,n,s,!0))return;if(r.classList.contains(i)||o&&r.matches(o))return;let d=r.value,f=!1;const m=il(r)||"";"radio"===m||"checkbox"===m?f=r.checked:(a[h.toLowerCase()]||a[m])&&(d=rl({element:r,maskInputOptions:a,tagName:h,type:m,value:d,maskInputFn:l})),p(r,u?{text:d,isChecked:f,userTriggered:c}:{text:d,isChecked:f});const g=r.name;"radio"===m&&g&&f&&t.querySelectorAll(`input[type="radio"][name="${g}"]`).forEach(e=>{if(e!==r){const t=e.value;p(e,u?{text:t,isChecked:!f,userTriggered:!1}:{text:t,isChecked:!f})}})}function p(t,n){const s=gy.get(t);if(!s||s.text!==n.text||s.isChecked!==n.isChecked){gy.set(t,n);const s=r.getId(t);cy(e)({...n,id:s})}}const d=("last"===c.input?["change"]:["input","change"]).map(e=>kg(e,cy(h),t)),f=t.defaultView;if(!f)return()=>{d.forEach(e=>e())};const m=f.Object.getOwnPropertyDescriptor(f.HTMLInputElement.prototype,"value"),g=[[f.HTMLInputElement.prototype,"value"],[f.HTMLInputElement.prototype,"checked"],[f.HTMLSelectElement.prototype,"value"],[f.HTMLTextAreaElement.prototype,"value"],[f.HTMLSelectElement.prototype,"selectedIndex"],[f.HTMLOptionElement.prototype,"selected"]];return m&&m.set&&d.push(...g.map(e=>Ig(e[0],e[1],{set(){cy(h)({target:this,isTrusted:!1})}},!1,f))),cy(()=>{d.forEach(e=>e())})}(e),c=function({mediaInteractionCb:e,blockClass:t,blockSelector:r,mirror:n,sampling:s,doc:i}){const o=cy(i=>Ag(cy(s=>{const o=hy(s);if(!o||Dg(o,t,r,!0))return;const{currentTime:a,volume:l,muted:c,playbackRate:u,loop:h}=o;e({type:i,id:n.getId(o),currentTime:a,volume:l,muted:c,playbackRate:u,loop:h})}),s.media||500)),a=[kg("play",o(qg.Play),i),kg("pause",o(qg.Pause),i),kg("seeked",o(qg.Seeked),i),kg("volumechange",o(qg.VolumeChange),i),kg("ratechange",o(qg.RateChange),i)];return cy(()=>{a.forEach(e=>e())})}(e);let u=()=>{},h=()=>{},p=()=>{},d=()=>{};e.recordDOM&&(u=function({styleSheetRuleCb:e,mirror:t,stylesheetManager:r},{win:n}){if(!n.CSSStyleSheet||!n.CSSStyleSheet.prototype)return()=>{};const s=n.CSSStyleSheet.prototype.insertRule;n.CSSStyleSheet.prototype.insertRule=new Proxy(s,{apply:cy((n,s,i)=>{const[o,a]=i,{id:l,styleId:c}=wy(s,t,r.styleMirror);return(l&&-1!==l||c&&-1!==c)&&e({id:l,styleId:c,adds:[{rule:o,index:a}]}),n.apply(s,i)})}),n.CSSStyleSheet.prototype.addRule=function(e,t,r=this.cssRules.length){const s=`${e} { ${t} }`;return n.CSSStyleSheet.prototype.insertRule.apply(this,[s,r])};const i=n.CSSStyleSheet.prototype.deleteRule;let o,a;n.CSSStyleSheet.prototype.deleteRule=new Proxy(i,{apply:cy((n,s,i)=>{const[o]=i,{id:a,styleId:l}=wy(s,t,r.styleMirror);return(a&&-1!==a||l&&-1!==l)&&e({id:a,styleId:l,removes:[{index:o}]}),n.apply(s,i)})}),n.CSSStyleSheet.prototype.removeRule=function(e){return n.CSSStyleSheet.prototype.deleteRule.apply(this,[e])},n.CSSStyleSheet.prototype.replace&&(o=n.CSSStyleSheet.prototype.replace,n.CSSStyleSheet.prototype.replace=new Proxy(o,{apply:cy((n,s,i)=>{const[o]=i,{id:a,styleId:l}=wy(s,t,r.styleMirror);return(a&&-1!==a||l&&-1!==l)&&e({id:a,styleId:l,replace:o}),n.apply(s,i)})})),n.CSSStyleSheet.prototype.replaceSync&&(a=n.CSSStyleSheet.prototype.replaceSync,n.CSSStyleSheet.prototype.replaceSync=new Proxy(a,{apply:cy((n,s,i)=>{const[o]=i,{id:a,styleId:l}=wy(s,t,r.styleMirror);return(a&&-1!==a||l&&-1!==l)&&e({id:a,styleId:l,replaceSync:o}),n.apply(s,i)})}));const l={};Sy("CSSGroupingRule")?l.CSSGroupingRule=n.CSSGroupingRule:(Sy("CSSMediaRule")&&(l.CSSMediaRule=n.CSSMediaRule),Sy("CSSConditionRule")&&(l.CSSConditionRule=n.CSSConditionRule),Sy("CSSSupportsRule")&&(l.CSSSupportsRule=n.CSSSupportsRule));const c={};return Object.entries(l).forEach(([n,s])=>{c[n]={insertRule:s.prototype.insertRule,deleteRule:s.prototype.deleteRule},s.prototype.insertRule=new Proxy(c[n].insertRule,{apply:cy((n,s,i)=>{const[o,a]=i,{id:l,styleId:c}=wy(s.parentStyleSheet,t,r.styleMirror);return(l&&-1!==l||c&&-1!==c)&&e({id:l,styleId:c,adds:[{rule:o,index:[...yy(s),a||0]}]}),n.apply(s,i)})}),s.prototype.deleteRule=new Proxy(c[n].deleteRule,{apply:cy((n,s,i)=>{const[o]=i,{id:a,styleId:l}=wy(s.parentStyleSheet,t,r.styleMirror);return(a&&-1!==a||l&&-1!==l)&&e({id:a,styleId:l,removes:[{index:[...yy(s),o]}]}),n.apply(s,i)})})}),cy(()=>{n.CSSStyleSheet.prototype.insertRule=s,n.CSSStyleSheet.prototype.deleteRule=i,o&&(n.CSSStyleSheet.prototype.replace=o),a&&(n.CSSStyleSheet.prototype.replaceSync=a),Object.entries(l).forEach(([e,t])=>{t.prototype.insertRule=c[e].insertRule,t.prototype.deleteRule=c[e].deleteRule})})}(e,{win:r}),h=vy(e,e.doc),p=function({styleDeclarationCb:e,mirror:t,ignoreCSSAttributes:r,stylesheetManager:n},{win:s}){const i=s.CSSStyleDeclaration.prototype.setProperty;s.CSSStyleDeclaration.prototype.setProperty=new Proxy(i,{apply:cy((s,o,a)=>{var l;const[c,u,h]=a;if(r.has(c))return i.apply(o,[c,u,h]);const{id:p,styleId:d}=wy(null==(l=o.parentRule)?void 0:l.parentStyleSheet,t,n.styleMirror);return(p&&-1!==p||d&&-1!==d)&&e({id:p,styleId:d,set:{property:c,value:u,priority:h},index:yy(o.parentRule)}),s.apply(o,a)})});const o=s.CSSStyleDeclaration.prototype.removeProperty;return s.CSSStyleDeclaration.prototype.removeProperty=new Proxy(o,{apply:cy((s,i,a)=>{var l;const[c]=a;if(r.has(c))return o.apply(i,[c]);const{id:u,styleId:h}=wy(null==(l=i.parentRule)?void 0:l.parentStyleSheet,t,n.styleMirror);return(u&&-1!==u||h&&-1!==h)&&e({id:u,styleId:h,remove:{property:c},index:yy(i.parentRule)}),s.apply(i,a)})}),cy(()=>{s.CSSStyleDeclaration.prototype.setProperty=i,s.CSSStyleDeclaration.prototype.removeProperty=o})}(e,{win:r}),e.collectFonts&&(d=function({fontCb:e,doc:t}){const r=t.defaultView;if(!r)return()=>{};const n=[],s=new WeakMap,i=r.FontFace;r.FontFace=function(e,t,r){const n=new i(e,t,r);return s.set(n,{family:e,buffer:"string"!=typeof t,descriptors:r,fontSource:"string"==typeof t?t:JSON.stringify(Array.from(new Uint8Array(t)))}),n};const o=Eg(t.fonts,"add",function(t){return function(r){return setTimeout(cy(()=>{const t=s.get(r);t&&(e(t),s.delete(r))}),0),t.apply(this,[r])}});return n.push(()=>{r.FontFace=i}),n.push(o),cy(()=>{n.forEach(e=>e())})}(e)));const f=function(e){const{doc:t,mirror:r,blockClass:n,blockSelector:s,selectionCb:i}=e;let o=!0;const a=cy(()=>{const e=t.getSelection();if(!e||o&&(null==e?void 0:e.isCollapsed))return;o=e.isCollapsed||!1;const a=[],l=e.rangeCount||0;for(let t=0;t{}}(e),g=[];for(const t of e.plugins)g.push(t.observer(t.callback,r,t.options));return cy(()=>{uy.forEach(e=>e.reset()),null==n||n.disconnect(),s(),i(),o(),a(),l(),c(),u(),h(),p(),d(),f(),m(),g.forEach(e=>e())})}function _y(e){return void 0!==window[e]}function Sy(e){return Boolean(void 0!==window[e]&&window[e].prototype&&"insertRule"in window[e].prototype&&"deleteRule"in window[e].prototype)}class Cy{constructor(e){Ua(this,"iframeIdToRemoteIdMap",new WeakMap),Ua(this,"iframeRemoteIdToIdMap",new WeakMap),this.generateIdFn=e}getId(e,t,r,n){const s=r||this.getIdToRemoteIdMap(e),i=n||this.getRemoteIdToIdMap(e);let o=s.get(t);return o||(o=this.generateIdFn(),s.set(t,o),i.set(o,t)),o}getIds(e,t){const r=this.getIdToRemoteIdMap(e),n=this.getRemoteIdToIdMap(e);return t.map(t=>this.getId(e,t,r,n))}getRemoteId(e,t,r){const n=r||this.getRemoteIdToIdMap(e);if("number"!=typeof t)return t;const s=n.get(t);return s||-1}getRemoteIds(e,t){const r=this.getRemoteIdToIdMap(e);return t.map(t=>this.getRemoteId(e,t,r))}reset(e){if(!e)return this.iframeIdToRemoteIdMap=new WeakMap,void(this.iframeRemoteIdToIdMap=new WeakMap);this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}}class Ey{constructor(e){Ua(this,"iframes",new WeakMap),Ua(this,"crossOriginIframeMap",new WeakMap),Ua(this,"crossOriginIframeMirror",new Cy(gl)),Ua(this,"crossOriginIframeStyleMirror"),Ua(this,"crossOriginIframeRootIdMap",new WeakMap),Ua(this,"mirror"),Ua(this,"mutationCb"),Ua(this,"wrappedEmit"),Ua(this,"loadListener"),Ua(this,"stylesheetManager"),Ua(this,"recordCrossOriginIframes"),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new Cy(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var r,n;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&(null==(r=e.contentWindow)||r.addEventListener("message",this.handleMessage.bind(this))),null==(n=this.loadListener)||n.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){const t=e;if("rrweb"!==t.data.type||t.origin!==t.data.origin)return;if(!e.source)return;const r=this.crossOriginIframeMap.get(e.source);if(!r)return;const n=this.transformCrossOriginEvent(r,t.data.event);n&&this.wrappedEmit(n,t.data.isCheckout)}transformCrossOriginEvent(e,t){var r;switch(t.type){case Wg.FullSnapshot:{this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);const r=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,r),this.patchRootIdOnNode(t.data.node,r),{timestamp:t.timestamp,type:Wg.IncrementalSnapshot,data:{source:Yg.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case Wg.Meta:case Wg.Load:case Wg.DomContentLoaded:return!1;case Wg.Plugin:return t;case Wg.Custom:return this.replaceIds(t.data.payload,e,["id","parentId","previousId","nextId"]),t;case Wg.IncrementalSnapshot:switch(t.data.source){case Yg.Mutation:return t.data.adds.forEach(t=>{this.replaceIds(t,e,["parentId","nextId","previousId"]),this.replaceIdOnNode(t.node,e);const r=this.crossOriginIframeRootIdMap.get(e);r&&this.patchRootIdOnNode(t.node,r)}),t.data.removes.forEach(t=>{this.replaceIds(t,e,["parentId","id"])}),t.data.attributes.forEach(t=>{this.replaceIds(t,e,["id"])}),t.data.texts.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case Yg.Drag:case Yg.TouchMove:case Yg.MouseMove:return t.data.positions.forEach(t=>{this.replaceIds(t,e,["id"])}),t;case Yg.ViewportResize:return!1;case Yg.MediaInteraction:case Yg.MouseInteraction:case Yg.Scroll:case Yg.CanvasMutation:case Yg.Input:return this.replaceIds(t.data,e,["id"]),t;case Yg.StyleSheetRule:case Yg.StyleDeclaration:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleId"]),t;case Yg.Font:return t;case Yg.Selection:return t.data.ranges.forEach(t=>{this.replaceIds(t,e,["start","end"])}),t;case Yg.AdoptedStyleSheet:return this.replaceIds(t.data,e,["id"]),this.replaceStyleIds(t.data,e,["styleIds"]),null==(r=t.data.styles)||r.forEach(t=>{this.replaceStyleIds(t,e,["styleId"])}),t}}return!1}replace(e,t,r,n){for(const s of n)(Array.isArray(t[s])||"number"==typeof t[s])&&(Array.isArray(t[s])?t[s]=e.getIds(r,t[s]):t[s]=e.getId(r,t[s]));return t}replaceIds(e,t,r){return this.replace(this.crossOriginIframeMirror,e,t,r)}replaceStyleIds(e,t,r){return this.replace(this.crossOriginIframeStyleMirror,e,t,r)}replaceIdOnNode(e,t){this.replaceIds(e,t,["id","rootId"]),"childNodes"in e&&e.childNodes.forEach(e=>{this.replaceIdOnNode(e,t)})}patchRootIdOnNode(e,t){e.type===Qg.Document||e.rootId||(e.rootId=t),"childNodes"in e&&e.childNodes.forEach(e=>{this.patchRootIdOnNode(e,t)})}}class Ty{constructor(e){Ua(this,"shadowDoms",new WeakSet),Ua(this,"mutationCb"),Ua(this,"scrollCb"),Ua(this,"bypassOptions"),Ua(this,"mirror"),Ua(this,"restoreHandlers",[]),this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(e,t){if(!qa(e))return;if(this.shadowDoms.has(e))return;this.shadowDoms.add(e);const r=py({...this.bypassOptions,doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},e);this.restoreHandlers.push(()=>r.disconnect()),this.restoreHandlers.push(fy({...this.bypassOptions,scrollCb:this.scrollCb,doc:e,mirror:this.mirror})),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(Tg.host(e))),this.restoreHandlers.push(vy({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e))},0)}observeAttachShadow(e){e.contentWindow&&e.contentDocument&&this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)}patchAttachShadow(e,t){const r=this;this.restoreHandlers.push(Eg(e.prototype,"attachShadow",function(e){return function(n){const s=e.call(this,n),i=Tg.shadowRoot(this);return i&&$g(this)&&r.addShadowRoot(i,t),s}}))}reset(){this.restoreHandlers.forEach(e=>{try{e()}catch(e){}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet}}for(var ky="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",xy="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Oy=0;Oy<64;Oy++)xy[ky.charCodeAt(Oy)]=Oy;const Ay=new Map;const Iy=(e,t,r)=>{if(!e||!Ny(e,t)&&"object"!=typeof e)return;const n=function(e,t){let r=Ay.get(e);return r||(r=new Map,Ay.set(e,r)),r.has(t)||r.set(t,[]),r.get(t)}(r,e.constructor.name);let s=n.indexOf(e);return-1===s&&(s=n.length,n.push(e)),s};function Ry(e,t,r){if(e instanceof Array)return e.map(e=>Ry(e,t,r));if(null===e)return e;if(e instanceof Float32Array||e instanceof Float64Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Uint8Array||e instanceof Uint16Array||e instanceof Int16Array||e instanceof Int8Array||e instanceof Uint8ClampedArray){return{rr_type:e.constructor.name,args:[Object.values(e)]}}if(e instanceof ArrayBuffer){return{rr_type:e.constructor.name,base64:function(e){var t,r=new Uint8Array(e),n=r.length,s="";for(t=0;t>2],s+=ky[(3&r[t])<<4|r[t+1]>>4],s+=ky[(15&r[t+1])<<2|r[t+2]>>6],s+=ky[63&r[t+2]];return n%3==2?s=s.substring(0,s.length-1)+"=":n%3==1&&(s=s.substring(0,s.length-2)+"=="),s}(e)}}if(e instanceof DataView){return{rr_type:e.constructor.name,args:[Ry(e.buffer,t,r),e.byteOffset,e.byteLength]}}if(e instanceof HTMLImageElement){const t=e.constructor.name,{src:r}=e;return{rr_type:t,src:r}}if(e instanceof HTMLCanvasElement){return{rr_type:"HTMLImageElement",src:e.toDataURL()}}if(e instanceof ImageData){return{rr_type:e.constructor.name,args:[Ry(e.data,t,r),e.width,e.height]}}if(Ny(e,t)||"object"==typeof e){return{rr_type:e.constructor.name,index:Iy(e,t,r)}}return e}const My=(e,t,r)=>e.map(e=>Ry(e,t,r)),Ny=(e,t)=>{const r=["WebGLActiveInfo","WebGLBuffer","WebGLFramebuffer","WebGLProgram","WebGLRenderbuffer","WebGLShader","WebGLShaderPrecisionFormat","WebGLTexture","WebGLUniformLocation","WebGLVertexArrayObject","WebGLVertexArrayObjectOES"].filter(e=>"function"==typeof t[e]);return Boolean(r.find(r=>e instanceof t[r]))};function Py(e,t,r,n){const s=[];try{const i=Eg(e.HTMLCanvasElement.prototype,"getContext",function(e){return function(s,...i){if(!Dg(this,t,r,!0)){const e=function(e){return"experimental-webgl"===e?"webgl":e}(s);if("__context"in this||(this.__context=e),n&&["webgl","webgl2"].includes(e))if(i[0]&&"object"==typeof i[0]){const e=i[0];e.preserveDrawingBuffer||(e.preserveDrawingBuffer=!0)}else i.splice(0,1,{preserveDrawingBuffer:!0})}return e.apply(this,[s,...i])}});s.push(i)}catch{console.error("failed to patch HTMLCanvasElement.prototype.getContext")}return()=>{s.forEach(e=>e())}}function Ly(e,t,r,n,s,i){const o=[],a=Object.getOwnPropertyNames(e);for(const l of a)if(!["isContextLost","canvas","drawingBufferWidth","drawingBufferHeight"].includes(l))try{if("function"!=typeof e[l])continue;const a=Eg(e,l,function(e){return function(...o){const a=e.apply(this,o);if(Iy(a,i,this),"tagName"in this.canvas&&!Dg(this.canvas,n,s,!0)){const e=My(o,i,this),n={type:t,property:l,args:e};r(this.canvas,n)}return a}});o.push(a)}catch{const n=Ig(e,l,{set(e){r(this.canvas,{type:t,property:l,args:[e],setter:!0})}});o.push(n)}return o}const Dy="KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCBieXRlc1tpMiArIDJdID4+IDZdOwogICAgICBiYXNlNjQgKz0gY2hhcnNbYnl0ZXNbaTIgKyAyXSAmIDYzXTsKICAgIH0KICAgIGlmIChsZW4gJSAzID09PSAyKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDEpICsgIj0iOwogICAgfSBlbHNlIGlmIChsZW4gJSAzID09PSAxKSB7CiAgICAgIGJhc2U2NCA9IGJhc2U2NC5zdWJzdHJpbmcoMCwgYmFzZTY0Lmxlbmd0aCAtIDIpICsgIj09IjsKICAgIH0KICAgIHJldHVybiBiYXNlNjQ7CiAgfTsKICBjb25zdCBsYXN0QmxvYk1hcCA9IC8qIEBfX1BVUkVfXyAqLyBuZXcgTWFwKCk7CiAgY29uc3QgdHJhbnNwYXJlbnRCbG9iTWFwID0gLyogQF9fUFVSRV9fICovIG5ldyBNYXAoKTsKICBhc3luYyBmdW5jdGlvbiBnZXRUcmFuc3BhcmVudEJsb2JGb3Iod2lkdGgsIGhlaWdodCwgZGF0YVVSTE9wdGlvbnMpIHsKICAgIGNvbnN0IGlkID0gYCR7d2lkdGh9LSR7aGVpZ2h0fWA7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBpZiAodHJhbnNwYXJlbnRCbG9iTWFwLmhhcyhpZCkpIHJldHVybiB0cmFuc3BhcmVudEJsb2JNYXAuZ2V0KGlkKTsKICAgICAgY29uc3Qgb2Zmc2NyZWVuID0gbmV3IE9mZnNjcmVlbkNhbnZhcyh3aWR0aCwgaGVpZ2h0KTsKICAgICAgb2Zmc2NyZWVuLmdldENvbnRleHQoIjJkIik7CiAgICAgIGNvbnN0IGJsb2IgPSBhd2FpdCBvZmZzY3JlZW4uY29udmVydFRvQmxvYihkYXRhVVJMT3B0aW9ucyk7CiAgICAgIGNvbnN0IGFycmF5QnVmZmVyID0gYXdhaXQgYmxvYi5hcnJheUJ1ZmZlcigpOwogICAgICBjb25zdCBiYXNlNjQgPSBlbmNvZGUoYXJyYXlCdWZmZXIpOwogICAgICB0cmFuc3BhcmVudEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICByZXR1cm4gYmFzZTY0OwogICAgfSBlbHNlIHsKICAgICAgcmV0dXJuICIiOwogICAgfQogIH0KICBjb25zdCB3b3JrZXIgPSBzZWxmOwogIHdvcmtlci5vbm1lc3NhZ2UgPSBhc3luYyBmdW5jdGlvbihlKSB7CiAgICBpZiAoIk9mZnNjcmVlbkNhbnZhcyIgaW4gZ2xvYmFsVGhpcykgewogICAgICBjb25zdCB7IGlkLCBiaXRtYXAsIHdpZHRoLCBoZWlnaHQsIGRhdGFVUkxPcHRpb25zIH0gPSBlLmRhdGE7CiAgICAgIGNvbnN0IHRyYW5zcGFyZW50QmFzZTY0ID0gZ2V0VHJhbnNwYXJlbnRCbG9iRm9yKAogICAgICAgIHdpZHRoLAogICAgICAgIGhlaWdodCwKICAgICAgICBkYXRhVVJMT3B0aW9ucwogICAgICApOwogICAgICBjb25zdCBvZmZzY3JlZW4gPSBuZXcgT2Zmc2NyZWVuQ2FudmFzKHdpZHRoLCBoZWlnaHQpOwogICAgICBjb25zdCBjdHggPSBvZmZzY3JlZW4uZ2V0Q29udGV4dCgiMmQiKTsKICAgICAgY3R4LmRyYXdJbWFnZShiaXRtYXAsIDAsIDApOwogICAgICBiaXRtYXAuY2xvc2UoKTsKICAgICAgY29uc3QgYmxvYiA9IGF3YWl0IG9mZnNjcmVlbi5jb252ZXJ0VG9CbG9iKGRhdGFVUkxPcHRpb25zKTsKICAgICAgY29uc3QgdHlwZSA9IGJsb2IudHlwZTsKICAgICAgY29uc3QgYXJyYXlCdWZmZXIgPSBhd2FpdCBibG9iLmFycmF5QnVmZmVyKCk7CiAgICAgIGNvbnN0IGJhc2U2NCA9IGVuY29kZShhcnJheUJ1ZmZlcik7CiAgICAgIGlmICghbGFzdEJsb2JNYXAuaGFzKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=",Uy="undefined"!=typeof window&&window.Blob&&new Blob([(e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0)))(Dy)],{type:"text/javascript;charset=utf-8"});function Fy(e){let t;try{if(t=Uy&&(window.URL||window.webkitURL).createObjectURL(Uy),!t)throw"";const r=new Worker(t,{name:null==e?void 0:e.name});return r.addEventListener("error",()=>{(window.URL||window.webkitURL).revokeObjectURL(t)}),r}catch(t){return new Worker("data:text/javascript;base64,"+Dy,{name:null==e?void 0:e.name})}finally{t&&(window.URL||window.webkitURL).revokeObjectURL(t)}}class By{constructor(e){Ua(this,"pendingCanvasMutations",new Map),Ua(this,"rafStamps",{latestId:0,invokeId:null}),Ua(this,"mirror"),Ua(this,"mutationCb"),Ua(this,"resetObservers"),Ua(this,"frozen",!1),Ua(this,"locked",!1),Ua(this,"processMutation",(e,t)=>{!(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId)&&this.rafStamps.invokeId||(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(e)||this.pendingCanvasMutations.set(e,[]),this.pendingCanvasMutations.get(e).push(t)});const{sampling:t="all",win:r,blockClass:n,blockSelector:s,recordCanvas:i,dataURLOptions:o}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,i&&"all"===t&&this.initCanvasMutationObserver(r,n,s),i&&"number"==typeof t&&this.initCanvasFPSObserver(t,r,n,s,{dataURLOptions:o})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,r,n,s){const i=Py(t,r,n,!0),o=new Map,a=new Fy;a.onmessage=e=>{const{id:t}=e.data;if(o.set(t,!1),!("base64"in e.data))return;const{base64:r,type:n,width:s,height:i}=e.data;this.mutationCb({id:t,type:Kg["2D"],commands:[{property:"clearRect",args:[0,0,s,i]},{property:"drawImage",args:[{rr_type:"ImageBitmap",args:[{rr_type:"Blob",data:[{rr_type:"ArrayBuffer",base64:r}],type:n}]},0,0]}]})};const l=1e3/e;let c,u=0;const h=e=>{u&&e-u{const e=[];return t.document.querySelectorAll("canvas").forEach(t=>{Dg(t,r,n,!0)||e.push(t)}),e})().forEach(async e=>{var t;const r=this.mirror.getId(e);if(o.get(r))return;if(0===e.width||0===e.height)return;if(o.set(r,!0),["webgl","webgl2"].includes(e.__context)){const r=e.getContext(e.__context);!1===(null==(t=null==r?void 0:r.getContextAttributes())?void 0:t.preserveDrawingBuffer)&&r.clear(r.COLOR_BUFFER_BIT)}const n=await createImageBitmap(e);a.postMessage({id:r,bitmap:n,width:e.width,height:e.height,dataURLOptions:s.dataURLOptions},[n])})),c=requestAnimationFrame(h)};c=requestAnimationFrame(h),this.resetObservers=()=>{i(),cancelAnimationFrame(c)}}initCanvasMutationObserver(e,t,r){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const n=Py(e,t,r,!1),s=function(e,t,r,n){const s=[],i=Object.getOwnPropertyNames(t.CanvasRenderingContext2D.prototype);for(const o of i)try{if("function"!=typeof t.CanvasRenderingContext2D.prototype[o])continue;const i=Eg(t.CanvasRenderingContext2D.prototype,o,function(s){return function(...i){return Dg(this.canvas,r,n,!0)||setTimeout(()=>{const r=My(i,t,this);e(this.canvas,{type:Kg["2D"],property:o,args:r})},0),s.apply(this,i)}});s.push(i)}catch{const r=Ig(t.CanvasRenderingContext2D.prototype,o,{set(t){e(this.canvas,{type:Kg["2D"],property:o,args:[t],setter:!0})}});s.push(r)}return()=>{s.forEach(e=>e())}}(this.processMutation.bind(this),e,t,r),i=function(e,t,r,n){const s=[];return s.push(...Ly(t.WebGLRenderingContext.prototype,Kg.WebGL,e,r,n,t)),void 0!==t.WebGL2RenderingContext&&s.push(...Ly(t.WebGL2RenderingContext.prototype,Kg.WebGL2,e,r,n,t)),()=>{s.forEach(e=>e())}}(this.processMutation.bind(this),e,t,r);this.resetObservers=()=>{n(),s(),i()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const r=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,r)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const r=this.pendingCanvasMutations.get(e);if(!r||-1===t)return;const n=r.map(e=>{const{type:t,...r}=e;return r}),{type:s}=r[0];this.mutationCb({id:t,type:s,commands:n}),this.pendingCanvasMutations.delete(e)}}class jy{constructor(e){Ua(this,"trackedLinkElements",new WeakSet),Ua(this,"mutationCb"),Ua(this,"adoptedStyleSheetCb"),Ua(this,"styleMirror",new Gg),this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){"_cssText"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(0===e.length)return;const r={id:t,styleIds:[]},n=[];for(const t of e){let e;this.styleMirror.has(t)?e=this.styleMirror.getId(t):(e=this.styleMirror.add(t),n.push({styleId:e,rules:Array.from(t.rules||CSSRule,(e,r)=>({rule:el(e,t.href),index:r}))})),r.styleIds.push(e)}n.length>0&&(r.styles=n),this.adoptedStyleSheetCb(r)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}}class zy{constructor(){Ua(this,"nodeMap",new WeakMap),Ua(this,"active",!1)}inOtherBuffer(e,t){const r=this.nodeMap.get(e);return r&&Array.from(r).some(e=>e!==t)}add(e,t){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||new Set).add(t))}destroy(){}}let Vy,Gy,Hy,Zy=!1;try{if(2!==Array.from([1],e=>2*e)[0]){const e=document.createElement("iframe");document.body.appendChild(e),Array.from=(null==(La=e.contentWindow)?void 0:La.Array.from)||Array.from,document.body.removeChild(e)}}catch(e){console.debug("Unable to override Array.from",e)}const $y=new tl;function Wy(e={}){const{emit:t,checkoutEveryNms:r,checkoutEveryNth:n,blockClass:s="rr-block",blockSelector:i=null,ignoreClass:o="rr-ignore",ignoreSelector:a=null,maskTextClass:l="rr-mask",maskTextSelector:c=null,inlineStylesheet:u=!0,maskAllInputs:h,maskInputOptions:p,slimDOMOptions:d,maskInputFn:f,maskTextFn:m,hooks:g,packFn:y,sampling:w={},dataURLOptions:v={},mousemoveWait:b,recordDOM:_=!0,recordCanvas:S=!1,recordCrossOriginIframes:C=!1,recordAfter:E=("DOMContentLoaded"===e.recordAfter?e.recordAfter:"load"),userTriggeredOnInput:T=!1,collectFonts:k=!1,inlineImages:x=!1,plugins:O,keepIframeSrcFn:A=()=>!1,ignoreCSSAttributes:I=new Set([]),errorHandler:R}=e;ly=R;const M=!C||window.parent===window;let N=!1;if(!M)try{window.parent.document&&(N=!1)}catch(e){N=!0}if(M&&!t)throw new Error("emit function is required");if(!M&&!N)return()=>{};void 0!==b&&void 0===w.mousemove&&(w.mousemove=b),$y.reset();const P=!0===h?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:void 0!==p?p:{password:!0},L=Rl(d);let D;!function(e=window){"NodeList"in e&&!e.NodeList.prototype.forEach&&(e.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in e&&!e.DOMTokenList.prototype.forEach&&(e.DOMTokenList.prototype.forEach=Array.prototype.forEach)}();let U=0;const F=e=>{for(const t of O||[])t.eventProcessor&&(e=t.eventProcessor(e));return y&&!N&&(e=y(e)),e};Vy=(e,s)=>{var i;const o=e;if(o.timestamp=Rg(),!(null==(i=uy[0])?void 0:i.isFrozen())||o.type===Wg.FullSnapshot||o.type===Wg.IncrementalSnapshot&&o.data.source===Yg.Mutation||uy.forEach(e=>e.unfreeze()),M)null==t||t(F(o),s);else if(N){const e={type:"rrweb",event:F(o),origin:window.location.origin,isCheckout:s};window.parent.postMessage(e,"*")}if(o.type===Wg.FullSnapshot)D=o,U=0;else if(o.type===Wg.IncrementalSnapshot){if(o.data.source===Yg.Mutation&&o.data.isAttachIframe)return;U++;const e=n&&U>=n,t=r&&o.timestamp-D.timestamp>r;(e||t)&&Gy(!0)}};const B=e=>{Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.Mutation,...e}})},j=e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.Scroll,...e}}),z=e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.CanvasMutation,...e}}),V=new jy({mutationCb:B,adoptedStyleSheetCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.AdoptedStyleSheet,...e}})}),G=new Ey({mirror:$y,mutationCb:B,stylesheetManager:V,recordCrossOriginIframes:C,wrappedEmit:Vy});for(const e of O||[])e.getMirror&&e.getMirror({nodeMirror:$y,crossOriginIframeMirror:G.crossOriginIframeMirror,crossOriginIframeStyleMirror:G.crossOriginIframeStyleMirror});const H=new zy;Hy=new By({recordCanvas:S,mutationCb:z,win:window,blockClass:s,blockSelector:i,mirror:$y,sampling:w.canvas,dataURLOptions:v});const Z=new Ty({mutationCb:B,scrollCb:j,bypassOptions:{blockClass:s,blockSelector:i,maskTextClass:l,maskTextSelector:c,inlineStylesheet:u,maskInputOptions:P,dataURLOptions:v,maskTextFn:m,maskInputFn:f,recordCanvas:S,inlineImages:x,sampling:w,slimDOMOptions:L,iframeManager:G,stylesheetManager:V,canvasManager:Hy,keepIframeSrcFn:A,processedNodeManager:H},mirror:$y});Gy=(e=!1)=>{if(!_)return;Vy({type:Wg.Meta,data:{href:window.location.href,width:Pg(),height:Ng()}},e),V.reset(),Z.init(),uy.forEach(e=>e.lock());const t=function(e,t){const{mirror:r=new tl,blockClass:n="rr-block",blockSelector:s=null,maskTextClass:i="rr-mask",maskTextSelector:o=null,inlineStylesheet:a=!0,inlineImages:l=!1,recordCanvas:c=!1,maskAllInputs:u=!1,maskTextFn:h,maskInputFn:p,slimDOM:d=!1,dataURLOptions:f,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:w,onStylesheetLoad:v,stylesheetLoadTimeout:b,keepIframeSrcFn:_=()=>!1}=t||{};return Ml(e,{doc:e,mirror:r,blockClass:n,blockSelector:s,maskTextClass:i,maskTextSelector:o,skipChild:!1,inlineStylesheet:a,maskInputOptions:!0===u?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:!1===u?{password:!0}:u,maskTextFn:h,maskInputFn:p,slimDOMOptions:Rl(d),dataURLOptions:f,inlineImages:l,recordCanvas:c,preserveWhiteSpace:m,onSerialize:g,onIframeLoad:y,iframeLoadTimeout:w,onStylesheetLoad:v,stylesheetLoadTimeout:b,keepIframeSrcFn:_,newlyAddedElement:!1})}(document,{mirror:$y,blockClass:s,blockSelector:i,maskTextClass:l,maskTextSelector:c,inlineStylesheet:u,maskAllInputs:P,maskTextFn:m,maskInputFn:f,slimDOM:L,dataURLOptions:v,recordCanvas:S,inlineImages:x,onSerialize:e=>{jg(e,$y)&&G.addIframe(e),zg(e,$y)&&V.trackLinkElement(e),Vg(e)&&Z.addShadowRoot(Tg.shadowRoot(e),document)},onIframeLoad:(e,t)=>{G.attachIframe(e,t),Z.observeAttachShadow(e)},onStylesheetLoad:(e,t)=>{V.attachLinkElement(e,t)},keepIframeSrcFn:A});if(!t)return console.warn("Failed to snapshot the document");Vy({type:Wg.FullSnapshot,data:{node:t,initialOffset:Mg(window)}},e),uy.forEach(e=>e.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&V.adoptStyleSheets(document.adoptedStyleSheets,$y.getId(document))};try{const e=[],t=e=>{var t;return cy(by)({mutationCb:B,mousemoveCb:(e,t)=>Vy({type:Wg.IncrementalSnapshot,data:{source:t,positions:e}}),mouseInteractionCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.MouseInteraction,...e}}),scrollCb:j,viewportResizeCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.ViewportResize,...e}}),inputCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.Input,...e}}),mediaInteractionCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.MediaInteraction,...e}}),styleSheetRuleCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.StyleSheetRule,...e}}),styleDeclarationCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.StyleDeclaration,...e}}),canvasMutationCb:z,fontCb:e=>Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.Font,...e}}),selectionCb:e=>{Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.Selection,...e}})},customElementCb:e=>{Vy({type:Wg.IncrementalSnapshot,data:{source:Yg.CustomElement,...e}})},blockClass:s,ignoreClass:o,ignoreSelector:a,maskTextClass:l,maskTextSelector:c,maskInputOptions:P,inlineStylesheet:u,sampling:w,recordDOM:_,recordCanvas:S,inlineImages:x,userTriggeredOnInput:T,collectFonts:k,doc:e,maskInputFn:f,maskTextFn:m,keepIframeSrcFn:A,blockSelector:i,slimDOMOptions:L,dataURLOptions:v,mirror:$y,iframeManager:G,stylesheetManager:V,shadowDomManager:Z,processedNodeManager:H,canvasManager:Hy,ignoreCSSAttributes:I,plugins:(null==(t=null==O?void 0:O.filter(e=>e.observer))?void 0:t.map(e=>({observer:e.observer,options:e.options,callback:t=>Vy({type:Wg.Plugin,data:{plugin:e.name,payload:t}})})))||[]},g)};G.addLoadListener(r=>{try{e.push(t(r.contentDocument))}catch(e){console.warn(e)}});const r=()=>{Gy(),e.push(t(document)),Zy=!0};return["interactive","complete"].includes(document.readyState)?r():(e.push(kg("DOMContentLoaded",()=>{Vy({type:Wg.DomContentLoaded,data:{}}),"DOMContentLoaded"===E&&r()})),e.push(kg("load",()=>{Vy({type:Wg.Load,data:{}}),"load"===E&&r()},window))),()=>{e.forEach(e=>{try{e()}catch(e){String(e).toLowerCase().includes("cross-origin")||console.warn(e)}}),H.destroy(),Zy=!1,ly=void 0}}catch(e){console.warn(e)}}var Yy;Wy.addCustomEvent=(e,t)=>{if(!Zy)throw new Error("please add custom event after start recording");Vy({type:Wg.Custom,data:{tag:e,payload:t}})},Wy.freezePage=()=>{uy.forEach(e=>e.freeze())},Wy.takeFullSnapshot=e=>{if(!Zy)throw new Error("please take full snapshot after start recording");Gy(e)},Wy.mirror=$y,function(e){e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped"}(Yy||(Yy={}));const Xy=5e3;class Jy{constructor(e,t,r){this.events=[],this.stopRecording=void 0,this.saveInterval=null,this.isSaving=!1,this.isConfigured=!1,this._enabled=!0,this.userAttributes={},this.tenantAttributes={},this._listenersAttached=!1,this.handleUnload=()=>this.save(!0),this.handleVisibilityChange=()=>{"hidden"===document.visibilityState&&this.save()},this.sessionId=t,this.tabId=r,this.config=e,this.setupListeners()}setupListeners(){"undefined"==typeof window||this._listenersAttached||(this._listenersAttached=!0,window.addEventListener("beforeunload",this.handleUnload),window.addEventListener("pagehide",this.handleUnload),document.addEventListener("visibilitychange",this.handleVisibilityChange))}removeListeners(){"undefined"!=typeof window&&this._listenersAttached&&(this._listenersAttached=!1,window.removeEventListener("beforeunload",this.handleUnload),window.removeEventListener("pagehide",this.handleUnload),document.removeEventListener("visibilitychange",this.handleVisibilityChange))}trimEvents(){if(this.events.length<=Xy)return;this.config.debug&&console.warn("Event queue exceeded 5000, dropping middle events (preserving snapshots)");const e=this.events.filter(e=>2===e.type),t=this.events.filter(e=>2!==e.type),r=Math.max(0,Xy-e.length);this.events=[...e,...t.slice(-r)],this.events.sort((e,t)=>e.timestamp-t.timestamp)}configure(){if("undefined"==typeof window)return;if(this.isConfigured)return;this.setupListeners();const e=Math.max(0,Math.min(1,this.config.replaySampleRate??1));if(Math.random()>=e)return this._enabled=!1,void(this.config.debug&&console.log("MonoscopeReplay: sampled out"));try{this.stopRecording=Wy({emit:e=>{this._enabled&&(this.events.push(e),this.events.length>=50&&this.save())},blockClass:"rr-block",maskAllInputs:!0,maskInputOptions:{password:!0,email:!0,tel:!0},maskTextClass:"rr-mask",checkoutEveryNms:15e3,sampling:{mouseInteraction:{MouseUp:!1,MouseDown:!1,Click:!0,ContextMenu:!1,DblClick:!0,Focus:!1,Blur:!1,TouchStart:!0,TouchEnd:!1},mousemove:!0,scroll:150,media:800,input:"last"},plugins:[(t={level:["info","log","warn","error"],lengthThreshold:1e4,stringifyOptions:{stringLengthLimit:1e3,numOfKeysLimit:100,depthOfLimit:2}},{name:"rrweb/console@1",observer:Pa,options:t})]}),this.saveInterval=setInterval(()=>this.save(),2e3),this.isConfigured=!0,this.config.debug&&console.log("MonoscopeReplay configured successfully")}catch(e){console.warn("Monoscope: failed to configure replay",e)}var t}async save(e=!1){if(this.isSaving&&!e)return;if(0===this.events.length)return;this.trimEvents(),this.isSaving=!0;const t=this.config.apiKey||this.config.projectId||"",r=`${this.config.replayEventsBaseUrl||"https://app.monoscope.tech"}/api/v1/rrweb`,n=[...this.events];this.events=[];const s={events:n,sessionId:this.sessionId,tabId:this.tabId,timestamp:(new Date).toISOString(),eventCount:n.length,user:Object.keys(this.userAttributes).length>0?this.userAttributes:void 0,tenant:Object.keys(this.tenantAttributes).length>0?this.tenantAttributes:void 0},i={"Content-Type":"application/json",Authorization:`Bearer ${t}`};try{if(e&&"undefined"!=typeof navigator&&navigator.sendBeacon){const e=new Blob([JSON.stringify(s)],{type:"application/json"});navigator.sendBeacon(r,e)||fetch(r,{method:"POST",headers:i,body:JSON.stringify(s),keepalive:!0}).catch(()=>{})}else{const e=JSON.stringify(s),t=await fetch(r,{method:"POST",headers:i,body:e,keepalive:e.length<63e3});if(!t.ok){const e=t.status;throw 401===e||403===e?console.warn("[Monoscope] Replay upload authentication failed. Your apiKey may be invalid."):console.warn(`[Monoscope] Replay upload failed (${e}). Check your apiKey and network.`),new Error(`Failed to save replay events: ${e} ${t.statusText}`)}this.config.debug&&console.log(`Successfully saved ${n.length} replay events`)}}catch(e){console.warn("Monoscope: failed to save replay events:",e),this.events=[...n,...this.events],this.trimEvents()}finally{this.isSaving=!1}}stop(){this.save(!0).catch(()=>{}),this.stopRecording&&(this.stopRecording(),this.stopRecording=void 0),this.saveInterval&&(clearInterval(this.saveInterval),this.saveInterval=null),this.removeListeners(),this.isConfigured=!1,this.config.debug&&console.log("MonoscopeReplay stopped")}setEnabled(e){this._enabled=e,e||this.stop()}setUser(e){this.userAttributes={...this.userAttributes,...e}}setTenant(e){this.tenantAttributes={...this.tenantAttributes,...e}}getEventCount(){return this.events.length}updateSessionId(e){this.sessionId=e}getSessionId(){return this.sessionId}isRecording(){return this.isConfigured&&void 0!==this.stopRecording}}const Ky="1.9.1",qy=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;const Qy=function(e){const t=new Set([e]),r=new Set,n=e.match(qy);if(!n)return()=>!1;const s=+n[1],i=+n[2],o=+n[3];if(null!=n[4])return function(t){return t===e};function a(e){return r.add(e),!1}function l(e){return t.add(e),!0}return function(e){if(t.has(e))return!0;if(r.has(e))return!1;const n=e.match(qy);if(!n)return a(e);const c=+n[1],u=+n[2],h=+n[3];return null!=n[4]||s!==c?a(e):0===s?i===u&&o<=h?l(e):a(e):i<=u?l(e):a(e)}}(Ky),ew=Ky.split(".")[0],tw=Symbol.for(`opentelemetry.js.api.${ew}`),rw="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{};function nw(e,t,r,n=!1){var s;const i=rw[tw]=null!==(s=rw[tw])&&void 0!==s?s:{version:Ky};if(!n&&i[e]){const t=new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return r.error(t.stack||t.message),!1}if(i.version!==Ky){const t=new Error(`@opentelemetry/api: Registration of version v${i.version} for ${e} does not match previously registered API v${Ky}`);return r.error(t.stack||t.message),!1}return i[e]=t,r.debug(`@opentelemetry/api: Registered a global for ${e} v${Ky}.`),!0}function sw(e){var t,r;const n=null===(t=rw[tw])||void 0===t?void 0:t.version;if(n&&Qy(n))return null===(r=rw[tw])||void 0===r?void 0:r[e]}function iw(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${Ky}.`);const r=rw[tw];r&&delete r[e]}class ow{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return aw("debug",this._namespace,e)}error(...e){return aw("error",this._namespace,e)}info(...e){return aw("info",this._namespace,e)}warn(...e){return aw("warn",this._namespace,e)}verbose(...e){return aw("verbose",this._namespace,e)}}function aw(e,t,r){const n=sw("diag");if(n)return n[e](t,...r)}var lw;!function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"}(lw||(lw={}));class cw{static instance(){return this._instance||(this._instance=new cw),this._instance}constructor(){function e(e){return function(...t){const r=sw("diag");if(r)return r[e](...t)}}const t=this;t.setLogger=(e,r={logLevel:lw.INFO})=>{var n,s,i;if(e===t){const e=new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error(null!==(n=e.stack)&&void 0!==n?n:e.message),!1}"number"==typeof r&&(r={logLevel:r});const o=sw("diag"),a=function(e,t){function r(r,n){const s=t[r];return"function"==typeof s&&e>=n?s.bind(t):function(){}}return elw.ALL&&(e=lw.ALL),t=t||{},{error:r("error",lw.ERROR),warn:r("warn",lw.WARN),info:r("info",lw.INFO),debug:r("debug",lw.DEBUG),verbose:r("verbose",lw.VERBOSE)}}(null!==(s=r.logLevel)&&void 0!==s?s:lw.INFO,e);if(o&&!r.suppressOverrideMessage){const e=null!==(i=(new Error).stack)&&void 0!==i?i:"";o.warn(`Current logger will be overwritten from ${e}`),a.warn(`Current logger will overwrite one already registered from ${e}`)}return nw("diag",a,t,!0)},t.disable=()=>{iw("diag",t)},t.createComponentLogger=e=>new ow(e),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}class uw{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){const t=this._entries.get(e);if(t)return Object.assign({},t)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,t){const r=new uw(this._entries);return r._entries.set(e,t),r}removeEntry(e){const t=new uw(this._entries);return t._entries.delete(e),t}removeEntries(...e){const t=new uw(this._entries);for(const r of e)t._entries.delete(r);return t}clear(){return new uw}}const hw=Symbol("BaggageEntryMetadata"),pw=cw.instance();function dw(e={}){return new uw(new Map(Object.entries(e)))}function fw(e){return Symbol.for(e)}class mw{constructor(e){const t=this;t._currentContext=e?new Map(e):new Map,t.getValue=e=>t._currentContext.get(e),t.setValue=(e,r)=>{const n=new mw(t._currentContext);return n._currentContext.set(e,r),n},t.deleteValue=e=>{const r=new mw(t._currentContext);return r._currentContext.delete(e),r}}}const gw=new mw;class yw{}class ww{addCallback(e){}removeCallback(e){}}const vw=new class{constructor(){}createGauge(e,t){return _w}createHistogram(e,t){return Sw}createCounter(e,t){return bw}createUpDownCounter(e,t){return Cw}createObservableGauge(e,t){return Tw}createObservableCounter(e,t){return Ew}createObservableUpDownCounter(e,t){return kw}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}},bw=new class extends yw{add(e,t){}},_w=new class extends yw{record(e,t){}},Sw=new class extends yw{record(e,t){}},Cw=new class extends yw{add(e,t){}},Ew=new class extends ww{},Tw=new class extends ww{},kw=new class extends ww{};function xw(){return vw}var Ow;!function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"}(Ow||(Ow={}));const Aw={get(e,t){if(null!=e)return e[t]},keys:e=>null==e?[]:Object.keys(e)},Iw={set(e,t,r){null!=e&&(e[t]=r)}};const Rw="context",Mw=new class{active(){return gw}with(e,t,r,...n){return t.call(r,...n)}bind(e,t){return t}enable(){return this}disable(){return this}};class Nw{constructor(){}static getInstance(){return this._instance||(this._instance=new Nw),this._instance}setGlobalContextManager(e){return nw(Rw,e,cw.instance())}active(){return this._getContextManager().active()}with(e,t,r,...n){return this._getContextManager().with(e,t,r,...n)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return sw(Rw)||Mw}disable(){this._getContextManager().disable(),iw(Rw,cw.instance())}}var Pw;!function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"}(Pw||(Pw={}));const Lw="0000000000000000",Dw="00000000000000000000000000000000",Uw={traceId:Dw,spanId:Lw,traceFlags:Pw.NONE};class Fw{constructor(e=Uw){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}const Bw=fw("OpenTelemetry Context Key SPAN");function jw(e){return e.getValue(Bw)||void 0}function zw(){return jw(Nw.getInstance().active())}function Vw(e,t){return e.setValue(Bw,t)}function Gw(e){return e.deleteValue(Bw)}function Hw(e,t){return Vw(e,new Fw(t))}function Zw(e){var t;return null===(t=jw(e))||void 0===t?void 0:t.spanContext()}const $w=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function Ww(e,t){if("string"!=typeof e||e.length!==t)return!1;let r=0;for(let t=0;tc}}var c;return{key:o,value:a,metadata:l}}class Ov{inject(e,t,r){const n=bv.getBaggage(e);if(!n||Tv(e))return;const s=function(e){return e.getAllEntries().map(([e,t])=>{let r=`${encodeURIComponent(e)}=${encodeURIComponent(t.value)}`;return void 0!==t.metadata&&(r+=";"+t.metadata.toString()),r})}(n).filter(e=>e.length<=4096).slice(0,180),i=function(e){return e.reduce((e,t)=>{const r=`${e}${""!==e?",":""}${t}`;return r.length>8192?e:r},"")}(s);i.length>0&&r.set(t,kv,i)}extract(e,t,r){const n=r.get(t,kv),s=Array.isArray(n)?n.join(","):n;if(!s)return e;const i={};if(0===s.length)return e;return s.split(",").forEach(e=>{const t=xv(e);if(t){const e={value:t.value};t.metadata&&(e.metadata=t.metadata),i[t.key]=e}}),0===Object.entries(i).length?e:bv.setBaggage(e,bv.createBaggage(i))}fields(){return[kv]}}function Av(e){const t={};if("object"!=typeof e||null==e)return t;for(const r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;if(!Iv(r)){av.warn(`Invalid attribute key: ${r}`);continue}const n=e[r];Rv(n)?Array.isArray(n)?t[r]=n.slice():t[r]=n:av.warn(`Invalid attribute value set for key: ${r}`)}return t}function Iv(e){return"string"==typeof e&&""!==e}function Rv(e){return null==e||(Array.isArray(e)?function(e){let t;for(const r of e){if(null==r)continue;const e=typeof r;if(e!==t){if(!t){if(Mv(e)){t=e;continue}return!1}return!1}}return!0}(e):Mv(typeof e))}function Mv(e){switch(e){case"number":case"boolean":case"string":return!0}return!1}let Nv=e=>{av.error(function(e){return"string"==typeof e?e:JSON.stringify(function(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}(e))}(e))};function Pv(e){try{Nv(e)}catch{}}const Lv="http.url",Dv="error.type",Uv="exception.message",Fv="exception.type",Bv="http.request.method",jv="http.request.method_original",zv="http.response.status_code",Vv="server.address",Gv="server.port",Hv="service.name",Zv="telemetry.sdk.language",$v="webjs",Wv="telemetry.sdk.name",Yv="telemetry.sdk.version",Xv="url.full",Jv="process.runtime.name",Kv={[Wv]:"opentelemetry",[Jv]:"browser",[Zv]:$v,[Yv]:"2.6.1"},qv=performance,Qv=Math.pow(10,6),eb=Math.pow(10,9);function tb(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*Qv)]}function rb(e){return ib(tb(qv.timeOrigin),tb("number"==typeof e?e:qv.now()))}function nb(e){return Array.isArray(e)&&2===e.length&&"number"==typeof e[0]&&"number"==typeof e[1]}function sb(e){return nb(e)||"number"==typeof e||e instanceof Date}function ib(e,t){const r=[e[0]+t[0],e[1]+t[1]];return r[1]>=eb&&(r[1]-=eb,r[0]+=1),r}var ob;!function(e){e[e.SUCCESS=0]="SUCCESS",e[e.FAILED=1]="FAILED"}(ob||(ob={}));class ab{_propagators;_fields;constructor(e={}){this._propagators=e.propagators??[],this._fields=Array.from(new Set(this._propagators.map(e=>"function"==typeof e.fields?e.fields():[]).reduce((e,t)=>e.concat(t),[])))}inject(e,t,r){for(const n of this._propagators)try{n.inject(e,t,r)}catch(e){av.warn(`Failed to inject with ${n.constructor.name}. Err: ${e.message}`)}}extract(e,t,r){return this._propagators.reduce((e,n)=>{try{return n.extract(e,t,r)}catch(e){av.warn(`Failed to extract with ${n.constructor.name}. Err: ${e.message}`)}return e},e)}fields(){return this._fields.slice()}}const lb="[_0-9a-z-*/]",cb=new RegExp(`^(?:${`[a-z]${lb}{0,255}`}|${`[a-z0-9]${lb}{0,240}@[a-z]${lb}{0,13}`})$`),ub=/^[ -~]{0,255}[!-~]$/,hb=/,|=/;class pb{_internalState=new Map;constructor(e){e&&this._parse(e)}set(e,t){const r=this._clone();return r._internalState.has(e)&&r._internalState.delete(e),r._internalState.set(e,t),r}unset(e){const t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return this._keys().reduce((e,t)=>(e.push(t+"="+this.get(t)),e),[]).join(",")}_parse(e){e.length>512||(this._internalState=e.split(",").reverse().reduce((e,t)=>{const r=t.trim(),n=r.indexOf("=");if(-1!==n){const s=r.slice(0,n),i=r.slice(n+1,t.length);(function(e){return cb.test(e)})(s)&&function(e){return ub.test(e)&&!hb.test(e)}(i)&&e.set(s,i)}return e},new Map),this._internalState.size>32&&(this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,32))))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){const e=new pb;return e._internalState=new Map(this._internalState),e}}const db="traceparent",fb="tracestate",mb=new RegExp("^\\s?((?!ff)[\\da-f]{2})-((?![0]{32})[\\da-f]{32})-((?![0]{16})[\\da-f]{16})-([\\da-f]{2})(-.*)?\\s?$");class gb{inject(e,t,r){const n=Cv.getSpanContext(e);if(!n||Tv(e)||!Xw(n))return;const s=`00-${n.traceId}-${n.spanId}-0${Number(n.traceFlags||Pw.NONE).toString(16)}`;r.set(t,db,s),n.traceState&&r.set(t,fb,n.traceState.serialize())}extract(e,t,r){const n=r.get(t,db);if(!n)return e;const s=Array.isArray(n)?n[0]:n;if("string"!=typeof s)return e;const i=function(e){const t=mb.exec(e);return t?"00"===t[1]&&t[5]?null:{traceId:t[2],spanId:t[3],traceFlags:parseInt(t[4],16)}:null}(s);if(!i)return e;i.isRemote=!0;const o=r.get(t,fb);if(o){const e=Array.isArray(o)?o.join(","):o;i.traceState=new pb("string"==typeof e?e:void 0)}return Cv.setSpanContext(e,i)}fields(){return[db,fb]}}const yb="[object Null]",wb="[object Undefined]",vb=Function.prototype.toString,bb=vb.call(Object),_b=Object.getPrototypeOf,Sb=Object.prototype,Cb=Sb.hasOwnProperty,Eb=Symbol?Symbol.toStringTag:void 0,Tb=Sb.toString;function kb(e){if(!function(e){return null!=e&&"object"==typeof e}(e)||"[object Object]"!==function(e){if(null==e)return void 0===e?wb:yb;return Eb&&Eb in Object(e)?function(e){const t=Cb.call(e,Eb),r=e[Eb];let n=!1;try{e[Eb]=void 0,n=!0}catch{}const s=Tb.call(e);n&&(t?e[Eb]=r:delete e[Eb]);return s}(e):function(e){return Tb.call(e)}(e)}(e))return!1;const t=_b(e);if(null===t)return!0;const r=Cb.call(t,"constructor")&&t.constructor;return"function"==typeof r&&r instanceof r&&vb.call(r)===bb}function xb(e){return Ib(e)?e.slice():e}function Ob(e,t,r=0,n){let s;if(!(r>20)){if(r++,Nb(e)||Nb(t)||Rb(t))s=xb(t);else if(Ib(e)){if(s=e.slice(),Ib(t))for(let e=0,r=t.length;e{this._resolve=e,this._reject=t})}get promise(){return this._promise}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}class Lb{_isCalled=!1;_deferred=new Pb;_callback;_that;constructor(e,t){this._callback=e,this._that=t}get isCalled(){return this._isCalled}get promise(){return this._deferred.promise}call(...e){if(!this._isCalled){this._isCalled=!0;try{Promise.resolve(this._callback.call(this._that,...e)).then(e=>this._deferred.resolve(e),e=>this._deferred.reject(e))}catch(e){this._deferred.reject(e)}}return this._deferred.promise}}let Db;function Ub(){if(void 0===Db)try{const e=globalThis.process.argv0;Db=e?`unknown_service:${e}`:"unknown_service"}catch{Db="unknown_service"}return Db}const Fb=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;let Bb=class e{_rawAttributes;_asyncAttributesPending=!1;_schemaUrl;_memoizedAttributes;static FromAttributeList(t,r){const n=new e({},r);return n._rawAttributes=zb(t),n._asyncAttributesPending=t.filter(([e,t])=>Fb(t)).length>0,n}constructor(e,t){const r=e.attributes??{};this._rawAttributes=Object.entries(r).map(([e,t])=>(Fb(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=zb(this._rawAttributes),this._schemaUrl=function(e){if("string"==typeof e||void 0===e)return e;return void av.warn("Schema URL must be string or undefined, got %s. Schema URL will be ignored.",e)}(t?.schemaUrl)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;eFb(t)?[e,t.catch(t=>{av.debug("promise rejection for resource attribute: %s - %s",e,t)})]:[e,t])}class Vb{_spanContext;kind;parentSpanContext;attributes={};links=[];events=[];startTime;resource;instrumentationScope;_droppedAttributesCount=0;_droppedEventsCount=0;_droppedLinksCount=0;_attributesCount=0;name;status={code:iv.UNSET};endTime=[0,0];_ended=!1;_duration=[-1,-1];_spanProcessor;_spanLimits;_attributeValueLengthLimit;_recordEndMetrics;_performanceStartTime;_performanceOffset;_startTimeProvided;constructor(e){const t=Date.now();if(this._spanContext=e.spanContext,this._performanceStartTime=qv.now(),this._performanceOffset=t-(this._performanceStartTime+qv.timeOrigin),this._startTimeProvided=null!=e.startTime,this._spanLimits=e.spanLimits,this._attributeValueLengthLimit=this._spanLimits.attributeValueLengthLimit??0,this._spanProcessor=e.spanProcessor,this.name=e.name,this.parentSpanContext=e.parentSpanContext,this.kind=e.kind,e.links)for(const t of e.links)this.addLink(t);this.startTime=this._getTime(e.startTime??t),this.resource=e.resource,this.instrumentationScope=e.scope,this._recordEndMetrics=e.recordEndMetrics,null!=e.attributes&&this.setAttributes(e.attributes),this._spanProcessor.onStart(this,e.context)}spanContext(){return this._spanContext}setAttribute(e,t){if(null==t||this._isSpanEnded())return this;if(0===e.length)return av.warn(`Invalid attribute key: ${e}`),this;if(!Rv(t))return av.warn(`Invalid attribute value set for key: ${e}`),this;const{attributeCountLimit:r}=this._spanLimits,n=!Object.prototype.hasOwnProperty.call(this.attributes,e);return void 0!==r&&this._attributesCount>=r&&n?(this._droppedAttributesCount++,this):(this.attributes[e]=this._truncateToSize(t),n&&this._attributesCount++,this)}setAttributes(e){for(const t in e)Object.prototype.hasOwnProperty.call(e,t)&&this.setAttribute(t,e[t]);return this}addEvent(e,t,r){if(this._isSpanEnded())return this;const{eventCountLimit:n}=this._spanLimits;if(0===n)return av.warn("No events allowed."),this._droppedEventsCount++,this;void 0!==n&&this.events.length>=n&&(0===this._droppedEventsCount&&av.debug("Dropping extra events."),this.events.shift(),this._droppedEventsCount++),sb(t)&&(sb(r)||(r=t),t=void 0);const s=Av(t),{attributePerEventCountLimit:i}=this._spanLimits,o={};let a=0,l=0;for(const e in s){if(!Object.prototype.hasOwnProperty.call(s,e))continue;const t=s[e];void 0!==i&&l>=i?a++:(o[e]=this._truncateToSize(t),l++)}return this.events.push({name:e,attributes:o,time:this._getTime(r),droppedAttributesCount:a}),this}addLink(e){if(this._isSpanEnded())return this;const{linkCountLimit:t}=this._spanLimits;if(0===t)return this._droppedLinksCount++,this;void 0!==t&&this.links.length>=t&&(0===this._droppedLinksCount&&av.debug("Dropping extra links."),this.links.shift(),this._droppedLinksCount++);const{attributePerLinkCountLimit:r}=this._spanLimits,n=Av(e.attributes),s={};let i=0,o=0;for(const e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;const t=n[e];void 0!==r&&o>=r?i++:(s[e]=this._truncateToSize(t),o++)}const a={context:e.context};return o>0&&(a.attributes=s),i>0&&(a.droppedAttributesCount=i),this.links.push(a),this}addLinks(e){for(const t of e)this.addLink(t);return this}setStatus(e){if(this._isSpanEnded())return this;if(e.code===iv.UNSET)return this;if(this.status.code===iv.OK)return this;const t={code:e.code};return e.code===iv.ERROR&&("string"==typeof e.message?t.message=e.message:null!=e.message&&av.warn(`Dropping invalid status.message of type '${typeof e.message}', expected 'string'`)),this.status=t,this}updateName(e){return this._isSpanEnded()||(this.name=e),this}end(e){this._isSpanEnded()?av.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`):(this.endTime=this._getTime(e),this._duration=function(e,t){let r=t[0]-e[0],n=t[1]-e[1];return n<0&&(r-=1,n+=eb),[r,n]}(this.startTime,this.endTime),this._duration[0]<0&&(av.warn("Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.",this.startTime,this.endTime),this.endTime=this.startTime.slice(),this._duration=[0,0]),this._droppedEventsCount>0&&av.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`),this._droppedLinksCount>0&&av.warn(`Dropped ${this._droppedLinksCount} links because linkCountLimit reached`),this._spanProcessor.onEnding&&this._spanProcessor.onEnding(this),this._recordEndMetrics?.(),this._ended=!0,this._spanProcessor.onEnd(this))}_getTime(e){if("number"==typeof e&&e<=qv.now())return rb(e+this._performanceOffset);if("number"==typeof e)return tb(e);if(e instanceof Date)return tb(e.getTime());if(nb(e))return e;if(this._startTimeProvided)return tb(Date.now());const t=qv.now()-this._performanceStartTime;return ib(this.startTime,tb(t))}isRecording(){return!1===this._ended}recordException(e,t){const r={};"string"==typeof e?r[Uv]=e:e&&(e.code?r[Fv]=e.code.toString():e.name&&(r[Fv]=e.name),e.message&&(r[Uv]=e.message),e.stack&&(r["exception.stacktrace"]=e.stack)),r[Fv]||r[Uv]?this.addEvent("exception",r,t):av.warn(`Failed to record an exception ${e}`)}get duration(){return this._duration}get ended(){return this._ended}get droppedAttributesCount(){return this._droppedAttributesCount}get droppedEventsCount(){return this._droppedEventsCount}get droppedLinksCount(){return this._droppedLinksCount}_isSpanEnded(){if(this._ended){const e=new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`);av.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`,e)}return this._ended}_truncateToLimitUtil(e,t){return e.length<=t?e:e.substring(0,t)}_truncateToSize(e){const t=this._attributeValueLengthLimit;return t<=0?(av.warn(`Attribute value limit must be positive, got ${t}`),e):"string"==typeof e?this._truncateToLimitUtil(e,t):Array.isArray(e)?e.map(e=>"string"==typeof e?this._truncateToLimitUtil(e,t):e):e}}var Gb,Hb;!function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"}(Gb||(Gb={}));class Zb{shouldSample(){return{decision:Gb.NOT_RECORD}}toString(){return"AlwaysOffSampler"}}class $b{shouldSample(){return{decision:Gb.RECORD_AND_SAMPLED}}toString(){return"AlwaysOnSampler"}}class Wb{_root;_remoteParentSampled;_remoteParentNotSampled;_localParentSampled;_localParentNotSampled;constructor(e){this._root=e.root,this._root||(Pv(new Error("ParentBasedSampler must have a root sampler configured")),this._root=new $b),this._remoteParentSampled=e.remoteParentSampled??new $b,this._remoteParentNotSampled=e.remoteParentNotSampled??new Zb,this._localParentSampled=e.localParentSampled??new $b,this._localParentNotSampled=e.localParentNotSampled??new Zb}shouldSample(e,t,r,n,s,i){const o=Cv.getSpanContext(e);return o&&Xw(o)?o.isRemote?o.traceFlags&Pw.SAMPLED?this._remoteParentSampled.shouldSample(e,t,r,n,s,i):this._remoteParentNotSampled.shouldSample(e,t,r,n,s,i):o.traceFlags&Pw.SAMPLED?this._localParentSampled.shouldSample(e,t,r,n,s,i):this._localParentNotSampled.shouldSample(e,t,r,n,s,i):this._root.shouldSample(e,t,r,n,s,i)}toString(){return`ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`}}class Yb{_ratio;_upperBound;constructor(e=0){this._ratio=this._normalize(e),this._upperBound=Math.floor(4294967295*this._ratio)}shouldSample(e,t){return{decision:Yw(t)&&this._accumulate(t)=1?1:e<=0?0:e}_accumulate(e){let t=0;for(let r=0;r>>0}return t}}!function(e){e.AlwaysOff="always_off",e.AlwaysOn="always_on",e.ParentBasedAlwaysOff="parentbased_always_off",e.ParentBasedAlwaysOn="parentbased_always_on",e.ParentBasedTraceIdRatio="parentbased_traceidratio",e.TraceIdRatio="traceidratio"}(Hb||(Hb={}));function Xb(){return{sampler:Jb(),forceFlushTimeoutMillis:3e4,generalLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128},spanLimits:{attributeValueLengthLimit:1/0,attributeCountLimit:128,linkCountLimit:128,eventCountLimit:128,attributePerEventCountLimit:128,attributePerLinkCountLimit:128}}}function Jb(){const e=Hb.ParentBasedAlwaysOn;switch(e){case Hb.AlwaysOn:return new $b;case Hb.AlwaysOff:return new Zb;case Hb.ParentBasedAlwaysOn:return new Wb({root:new $b});case Hb.ParentBasedAlwaysOff:return new Wb({root:new Zb});case Hb.TraceIdRatio:return new Yb(Kb());case Hb.ParentBasedTraceIdRatio:return new Wb({root:new Yb(Kb())});default:return av.error(`OTEL_TRACES_SAMPLER value "${e}" invalid, defaulting to "${Hb.ParentBasedAlwaysOn}".`),new Wb({root:new $b})}}function Kb(){return av.error("OTEL_TRACES_SAMPLER_ARG is blank, defaulting to 1."),1}const qb=1/0;class Qb{_maxExportBatchSize;_maxQueueSize;_scheduledDelayMillis;_exportTimeoutMillis;_exporter;_isExporting=!1;_finishedSpans=[];_timer;_shutdownOnce;_droppedSpansCount=0;constructor(e,t){this._exporter=e,this._maxExportBatchSize="number"==typeof t?.maxExportBatchSize?t.maxExportBatchSize:512,this._maxQueueSize="number"==typeof t?.maxQueueSize?t.maxQueueSize:2048,this._scheduledDelayMillis="number"==typeof t?.scheduledDelayMillis?t.scheduledDelayMillis:5e3,this._exportTimeoutMillis="number"==typeof t?.exportTimeoutMillis?t.exportTimeoutMillis:3e4,this._shutdownOnce=new Lb(this._shutdown,this),this._maxExportBatchSize>this._maxQueueSize&&(av.warn("BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize"),this._maxExportBatchSize=this._maxQueueSize)}forceFlush(){return this._shutdownOnce.isCalled?this._shutdownOnce.promise:this._flushAll()}onStart(e,t){}onEnd(e){this._shutdownOnce.isCalled||0!==(e.spanContext().traceFlags&Pw.SAMPLED)&&this._addToBuffer(e)}shutdown(){return this._shutdownOnce.call()}_shutdown(){return Promise.resolve().then(()=>this.onShutdown()).then(()=>this._flushAll()).then(()=>this._exporter.shutdown())}_addToBuffer(e){if(this._finishedSpans.length>=this._maxQueueSize)return 0===this._droppedSpansCount&&av.debug("maxQueueSize reached, dropping spans"),void this._droppedSpansCount++;this._droppedSpansCount>0&&(av.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`),this._droppedSpansCount=0),this._finishedSpans.push(e),this._maybeStartTimer()}_flushAll(){return new Promise((e,t)=>{const r=[];for(let e=0,t=Math.ceil(this._finishedSpans.length/this._maxExportBatchSize);e{e()}).catch(t)})}_flushOneBatch(){return this._clearTimer(),0===this._finishedSpans.length?Promise.resolve():new Promise((e,t)=>{const r=setTimeout(()=>{t(new Error("Timeout"))},this._exportTimeoutMillis);ov.with(function(e){return e.setValue(Ev,!0)}(ov.active()),()=>{let n;this._finishedSpans.length<=this._maxExportBatchSize?(n=this._finishedSpans,this._finishedSpans=[]):n=this._finishedSpans.splice(0,this._maxExportBatchSize);const s=()=>this._exporter.export(n,n=>{clearTimeout(r),n.code===ob.SUCCESS?e():t(n.error??new Error("BatchSpanProcessor: span export failed"))});let i=null;for(let e=0,t=n.length;e{Pv(e),t(e)})})})}_maybeStartTimer(){if(this._isExporting)return;const e=()=>{this._isExporting=!0,this._flushOneBatch().finally(()=>{this._isExporting=!1,this._finishedSpans.length>0&&(this._clearTimer(),this._maybeStartTimer())}).catch(e=>{this._isExporting=!1,Pv(e)})};if(this._finishedSpans.length>=this._maxExportBatchSize)return e();void 0===this._timer&&(this._timer=setTimeout(()=>e(),this._scheduledDelayMillis),"number"!=typeof this._timer&&this._timer.unref())}_clearTimer(){void 0!==this._timer&&(clearTimeout(this._timer),this._timer=void 0)}}class e_ extends Qb{_visibilityChangeListener;_pageHideListener;constructor(e,t){super(e,t),this.onInit(t)}onInit(e){!0!==e?.disableAutoFlushOnDocumentHide&&"undefined"!=typeof document&&(this._visibilityChangeListener=()=>{"hidden"===document.visibilityState&&this.forceFlush().catch(e=>{Pv(e)})},this._pageHideListener=()=>{this.forceFlush().catch(e=>{Pv(e)})},document.addEventListener("visibilitychange",this._visibilityChangeListener),document.addEventListener("pagehide",this._pageHideListener))}onShutdown(){"undefined"!=typeof document&&(this._visibilityChangeListener&&document.removeEventListener("visibilitychange",this._visibilityChangeListener),this._pageHideListener&&document.removeEventListener("pagehide",this._pageHideListener))}}const t_=new Uint8Array(16),r_=new Uint8Array(8),n_=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function s_(e){for(let t=0;t>>0;for(let t=0;t0)return;e[e.length-1]=1}function i_(e){let t="";for(let r=0;r{};const n={[l_]:r};return this.liveSpans.add(1,n),()=>{this.liveSpans.add(-1,n)}}}function u_(e){return e?e.isRemote?"remote":"local":"none"}class h_{_sampler;_generalLimits;_spanLimits;_idGenerator;instrumentationScope;_resource;_spanProcessor;_tracerMetrics;constructor(e,t,r,n){const s=function(e){const t={sampler:Jb()},r=Xb(),n=Object.assign({},r,t,e);return n.generalLimits=Object.assign({},r.generalLimits,e.generalLimits||{}),n.spanLimits=Object.assign({},r.spanLimits,e.spanLimits||{}),n}(t);this._sampler=s.sampler,this._generalLimits=s.generalLimits,this._spanLimits=s.spanLimits,this._idGenerator=t.idGenerator||new o_,this._resource=r,this._spanProcessor=n,this.instrumentationScope=e;const i=s.meterProvider?s.meterProvider.getMeter("@opentelemetry/sdk-trace","2.6.1"):xw();this._tracerMetrics=new c_(i)}startSpan(e,t={},r=ov.active()){t.root&&(r=Cv.deleteSpan(r));const n=Cv.getSpan(r);if(Tv(r)){av.debug("Instrumentation suppressed, returning Noop Span");return Cv.wrapSpanContext(Uw)}const s=n?.spanContext(),i=this._idGenerator.generateSpanId();let o,a,l;s&&Cv.isSpanContextValid(s)?(a=s.traceId,l=s.traceState,o=s):a=this._idGenerator.generateTraceId();const c=t.kind??sv.INTERNAL,u=(t.links??[]).map(e=>({context:e.context,attributes:Av(e.attributes)})),h=Av(t.attributes),p=this._sampler.shouldSample(r,a,e,c,h,u),d=this._tracerMetrics.startSpan(s,p.decision);l=p.traceState??l;const f={traceId:a,spanId:i,traceFlags:p.decision===nv.RECORD_AND_SAMPLED?Pw.SAMPLED:Pw.NONE,traceState:l};if(p.decision===nv.NOT_RECORD){av.debug("Recording is off, propagating context in a non-recording span");return Cv.wrapSpanContext(f)}const m=Av(Object.assign(h,p.attributes));return new Vb({resource:this._resource,scope:this.instrumentationScope,context:r,spanContext:f,name:e,kind:c,links:u,parentSpanContext:o,attributes:m,startTime:t.startTime,spanProcessor:this._spanProcessor,spanLimits:this._spanLimits,recordEndMetrics:d})}startActiveSpan(e,t,r,n){let s,i,o;if(arguments.length<2)return;2===arguments.length?o=t:3===arguments.length?(s=t,o=r):(s=t,i=r,o=n);const a=i??ov.active(),l=this.startSpan(e,s,a),c=Cv.setSpan(a,l);return ov.with(c,o,void 0,l)}getGeneralLimits(){return this._generalLimits}getSpanLimits(){return this._spanLimits}}class p_{_spanProcessors;constructor(e){this._spanProcessors=e}forceFlush(){const e=[];for(const t of this._spanProcessors)e.push(t.forceFlush());return new Promise(t=>{Promise.all(e).then(()=>{t()}).catch(e=>{Pv(e||new Error("MultiSpanProcessor: forceFlush failed")),t()})})}onStart(e,t){for(const r of this._spanProcessors)r.onStart(e,t)}onEnding(e){for(const t of this._spanProcessors)t.onEnding&&t.onEnding(e)}onEnd(e){for(const t of this._spanProcessors)t.onEnd(e)}shutdown(){const e=[];for(const t of this._spanProcessors)e.push(t.shutdown());return new Promise((t,r)=>{Promise.all(e).then(()=>{t()},r)})}}var d_,f_;!function(e){e[e.resolved=0]="resolved",e[e.timeout=1]="timeout",e[e.error=2]="error",e[e.unresolved=3]="unresolved"}(d_||(d_={}));class m_{_config;_tracers=new Map;_resource;_activeSpanProcessor;constructor(e={}){const t=function(...e){let t=e.shift();const r=new WeakMap;for(;e.length>0;)t=Ob(t,e.shift(),0,r);return t}({},Xb(),function(e){const t=Object.assign({},e.spanLimits);return t.attributeCountLimit=e.spanLimits?.attributeCountLimit??e.generalLimits?.attributeCountLimit??void 0??void 0??128,t.attributeValueLengthLimit=e.spanLimits?.attributeValueLengthLimit??e.generalLimits?.attributeValueLengthLimit??void 0??void 0??qb,Object.assign({},e,{spanLimits:t})}(e));this._resource=t.resource??jb({[Hv]:Ub(),[Zv]:Kv[Zv],[Wv]:Kv[Wv],[Yv]:Kv[Yv]}),this._config=Object.assign({},t,{resource:this._resource});const r=[];e.spanProcessors?.length&&r.push(...e.spanProcessors),this._activeSpanProcessor=new p_(r)}getTracer(e,t,r){const n=`${e}@${t||""}:${r?.schemaUrl||""}`;return this._tracers.has(n)||this._tracers.set(n,new h_({name:e,version:t,schemaUrl:r?.schemaUrl},this._config,this._resource,this._activeSpanProcessor)),this._tracers.get(n)}forceFlush(){const e=this._config.forceFlushTimeoutMillis,t=this._activeSpanProcessor._spanProcessors.map(t=>new Promise(r=>{let n;const s=setTimeout(()=>{r(new Error(`Span processor did not completed within timeout period of ${e} ms`)),n=d_.timeout},e);t.forceFlush().then(()=>{clearTimeout(s),n!==d_.timeout&&(n=d_.resolved,r(n))}).catch(e=>{clearTimeout(s),n=d_.error,r(e)})}));return new Promise((e,r)=>{Promise.all(t).then(t=>{const n=t.filter(e=>e!==d_.resolved);n.length>0?r(n):e()}).catch(e=>r([e]))})}shutdown(){return this._activeSpanProcessor.shutdown()}}class g_{_enabled=!1;_currentContext=gw;_bindFunction(e=gw,t){const r=this,n=function(...n){return r.with(e,()=>t.apply(this,n))};return Object.defineProperty(n,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),n}active(){return this._currentContext}bind(e,t){return void 0===e&&(e=this.active()),"function"==typeof t?this._bindFunction(e,t):t}disable(){return this._currentContext=gw,this._enabled=!1,this}enable(){return this._enabled||(this._enabled=!0,this._currentContext=gw),this}with(e,t,r,...n){const s=this._currentContext;this._currentContext=e||gw;try{return t.call(r,...n)}finally{this._currentContext=s}}}class y_ extends m_{constructor(e={}){super(e)}register(e={}){var t;Cv.setGlobalTracerProvider(this),null!==(t=e.propagator)&&(void 0!==t?bv.setGlobalPropagator(t):bv.setGlobalPropagator(new ab({propagators:[new gb,new Ov]}))),function(e){if(null!==e){if(void 0===e){const e=new g_;return e.enable(),void ov.setGlobalContextManager(e)}e.enable(),ov.setGlobalContextManager(e)}}(e.contextManager)}}!function(e){e.CONNECT_END="connectEnd",e.CONNECT_START="connectStart",e.DECODED_BODY_SIZE="decodedBodySize",e.DOM_COMPLETE="domComplete",e.DOM_CONTENT_LOADED_EVENT_END="domContentLoadedEventEnd",e.DOM_CONTENT_LOADED_EVENT_START="domContentLoadedEventStart",e.DOM_INTERACTIVE="domInteractive",e.DOMAIN_LOOKUP_END="domainLookupEnd",e.DOMAIN_LOOKUP_START="domainLookupStart",e.ENCODED_BODY_SIZE="encodedBodySize",e.FETCH_START="fetchStart",e.LOAD_EVENT_END="loadEventEnd",e.LOAD_EVENT_START="loadEventStart",e.NAVIGATION_START="navigationStart",e.REDIRECT_END="redirectEnd",e.REDIRECT_START="redirectStart",e.REQUEST_START="requestStart",e.RESPONSE_END="responseEnd",e.RESPONSE_START="responseStart",e.SECURE_CONNECTION_START="secureConnectionStart",e.START_TIME="startTime",e.UNLOAD_EVENT_END="unloadEventEnd",e.UNLOAD_EVENT_START="unloadEventStart"}(f_||(f_={}));function w_(e,t){return t in e}function v_(e,t,r,n=!0){if(w_(r,t)&&"number"==typeof r[t]&&(!n||0!==r[t]))return e.addEvent(t,r[t])}function b_(e,t,r=!1,n,s){void 0===n&&(n=0!==t[f_.START_TIME]),r||(v_(e,f_.FETCH_START,t,n),v_(e,f_.DOMAIN_LOOKUP_START,t,n),v_(e,f_.DOMAIN_LOOKUP_END,t,n),v_(e,f_.CONNECT_START,t,n),v_(e,f_.SECURE_CONNECTION_START,t,n),v_(e,f_.CONNECT_END,t,n),v_(e,f_.REQUEST_START,t,n),v_(e,f_.RESPONSE_START,t,n),v_(e,f_.RESPONSE_END,t,n));{const r=t[f_.ENCODED_BODY_SIZE];void 0!==r&&e.setAttribute("http.response_content_length",r);const n=t[f_.DECODED_BODY_SIZE];void 0!==n&&r!==n&&e.setAttribute("http.response_content_length_uncompressed",n)}}function __(e,t){if(e.nodeType===Node.DOCUMENT_NODE)return"/";const r=function(e){const t=e.nodeType,r=function(e){if(!e.parentNode)return 0;const t=[e.nodeType];e.nodeType===Node.CDATA_SECTION_NODE&&t.push(Node.TEXT_NODE);let r=Array.from(e.parentNode.childNodes);if(r=r.filter(r=>{const n=r.localName;return t.indexOf(r.nodeType)>=0&&n===e.localName}),r.length>=1)return r.indexOf(e)+1;return 0}(e);let n="";if(t===Node.ELEMENT_NODE){const t=e.getAttribute("id");if(t)return`//*[@id="${t}"]`;n=e.localName}else if(t===Node.TEXT_NODE||t===Node.CDATA_SECTION_NODE)n="text()";else{if(t!==Node.COMMENT_NODE)return"";n="comment()"}if(n&&r>1)return`/${n}[${r}]`;return`/${n}`}(e);if(r.indexOf("@id")>0)return r;let n="";return e.parentNode&&(n+=__(e.parentNode)),n+=r,n}let S_=class{emit(e){}};const C_=new S_;const E_=new class{getLogger(e,t,r){return new S_}};let T_=class{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider.getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):C_}},k_=class{getLogger(e,t,r){var n;return null!==(n=this.getDelegateLogger(e,t,r))&&void 0!==n?n:new T_(this,e,t,r)}getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:E_}setDelegate(e){this._delegate=e}getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}};const x_="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},O_=Symbol.for("io.opentelemetry.js.api.logs"),A_=x_;const I_=class e{constructor(){this._proxyLoggerProvider=new k_}static getInstance(){return this._instance||(this._instance=new e),this._instance}setGlobalLoggerProvider(e){return A_[O_]?this.getLoggerProvider():(A_[O_]=(t=1,r=e,n=E_,e=>e===t?r:n),this._proxyLoggerProvider.setDelegate(e),e);var t,r,n}getLoggerProvider(){var e,t;return null!==(t=null===(e=A_[O_])||void 0===e?void 0:e.call(A_,1))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete A_[O_],this._proxyLoggerProvider=new k_}}.getInstance();let R_=console.error.bind(console);function M_(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const N_=(e,t,r)=>{if(!e||!e[t])return void R_("no original function "+String(t)+" to wrap");if(!r)return R_("no wrapper function"),void R_((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void R_("original object and wrapper must be functions");const s=r(n,t);return M_(s,"__original",n),M_(s,"__unwrap",()=>{e[t]===s&&M_(e,t,n)}),M_(s,"__wrapped",!0),M_(e,t,s),s},P_=(e,t,r)=>{if(!e)return R_("must provide one or more modules to patch"),void R_((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{N_(e,t,r)})}):R_("must provide one or more functions to wrap on modules")},L_=(e,t)=>{if(!e||!e[t])return R_("no function to unwrap."),void R_((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():R_("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},D_=(e,t)=>{if(!e)return R_("must provide one or more modules to patch"),void R_((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{L_(e,t)})}):R_("must provide one or more functions to unwrap on modules")};let U_=class{instrumentationName;instrumentationVersion;_config={};_tracer;_meter;_logger;_diag;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=av.createComponentLogger({namespace:e}),this._tracer=Cv.getTracer(e,t),this._meter=hv.getMeter(e,t),this._logger=I_.getLogger(e,t),this._updateMetricInstruments()}_wrap=N_;_unwrap=L_;_massWrap=P_;_massUnwrap=D_;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}},F_=class extends U_{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}};function B_(e,t,r){let n,s;try{s=e()}catch(e){n=e}finally{return t(n,s),s}}function j_(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var z_,V_;function G_(e,t){let r=z_.OLD;const n=t?.split(",").map(e=>e.trim()).filter(e=>""!==e);for(const t of n??[]){if(t.toLowerCase()===e+"/dup"){r=z_.DUPLICATE;break}t.toLowerCase()===e&&(r=z_.STABLE)}return r}!function(e){e[e.STABLE=1]="STABLE",e[e.OLD=2]="OLD",e[e.DUPLICATE=3]="DUPLICATE"}(z_||(z_={})),function(e){e.DOCUMENT_LOAD="documentLoad",e.DOCUMENT_FETCH="documentFetch",e.RESOURCE_FETCH="resourceFetch"}(V_||(V_={}));var H_;!function(e){e.FIRST_PAINT="firstPaint",e.FIRST_CONTENTFUL_PAINT="firstContentfulPaint"}(H_||(H_={}));const Z_={"first-paint":H_.FIRST_PAINT,"first-contentful-paint":H_.FIRST_CONTENTFUL_PAINT};class $_ extends F_{component="document-load";version="1";moduleName=this.component;constructor(e={}){super("@opentelemetry/instrumentation-document-load","0.48.0",e)}init(){}_onDocumentLoaded(){window.setTimeout(()=>{this._collectPerformance()})}_addResourcesSpans(e){const t=qv.getEntriesByType?.("resource");t&&t.forEach(t=>{this._initResourceSpan(t,e)})}_collectPerformance(){const e=Array.from(document.getElementsByTagName("meta")).find(e=>e.getAttribute("name")===db),t=(()=>{const e={},t=qv.getEntriesByType?.("navigation")[0];if(t)Object.values(f_).forEach(r=>{if(w_(t,r)){const n=t[r];"number"==typeof n&&(e[r]=n)}});else{const t=qv.timing;t&&Object.values(f_).forEach(r=>{if(w_(t,r)){const n=t[r];"number"==typeof n&&(e[r]=n)}})}return e})(),r=e&&e.content||"";ov.with(bv.extract(gw,{traceparent:r}),()=>{const e=this._startSpan(V_.DOCUMENT_LOAD,f_.FETCH_START,t);e&&(ov.with(Cv.setSpan(ov.active(),e),()=>{const e=this._startSpan(V_.DOCUMENT_FETCH,f_.FETCH_START,t);e&&(e.setAttribute(Lv,location.href),ov.with(Cv.setSpan(ov.active(),e),()=>{b_(e,t,this.getConfig().ignoreNetworkEvents),this._addCustomAttributesOnSpan(e,this.getConfig().applyCustomAttributesOnSpan?.documentFetch),this._endSpan(e,f_.RESPONSE_END,t)}))}),e.setAttribute(Lv,location.href),e.setAttribute("http.user_agent",navigator.userAgent),this._addResourcesSpans(e),this.getConfig().ignoreNetworkEvents||(v_(e,f_.FETCH_START,t),v_(e,f_.UNLOAD_EVENT_START,t),v_(e,f_.UNLOAD_EVENT_END,t),v_(e,f_.DOM_INTERACTIVE,t),v_(e,f_.DOM_CONTENT_LOADED_EVENT_START,t),v_(e,f_.DOM_CONTENT_LOADED_EVENT_END,t),v_(e,f_.DOM_COMPLETE,t),v_(e,f_.LOAD_EVENT_START,t),v_(e,f_.LOAD_EVENT_END,t)),this.getConfig().ignorePerformancePaintEvents||(e=>{const t=qv.getEntriesByType?.("paint");t&&t.forEach(({name:t,startTime:r})=>{w_(Z_,t)&&e.addEvent(Z_[t],r)})})(e),this._addCustomAttributesOnSpan(e,this.getConfig().applyCustomAttributesOnSpan?.documentLoad),this._endSpan(e,f_.LOAD_EVENT_END,t))})}_endSpan(e,t,r){e&&(w_(r,t)?e.end(r[t]):e.end())}_initResourceSpan(e,t){const r=this._startSpan(V_.RESOURCE_FETCH,f_.FETCH_START,e,t);r&&(r.setAttribute(Lv,e.name),b_(r,e,this.getConfig().ignoreNetworkEvents),this._addCustomAttributesOnResourceSpan(r,e,this.getConfig().applyCustomAttributesOnSpan?.resourceFetch),this._endSpan(r,f_.RESPONSE_END,e))}_startSpan(e,t,r,n){if(w_(r,t)&&"number"==typeof r[t]){return this.tracer.startSpan(e,{startTime:r[t]},n?Cv.setSpan(ov.active(),n):void 0)}}_waitForPageLoad(){"complete"===window.document.readyState?this._onDocumentLoaded():(this._onDocumentLoaded=this._onDocumentLoaded.bind(this),window.addEventListener("load",this._onDocumentLoaded))}_addCustomAttributesOnSpan(e,t){t&&B_(()=>t(e),e=>{e&&this._diag.error("addCustomAttributesOnSpan",e)})}_addCustomAttributesOnResourceSpan(e,t,r){r&&B_(()=>r(e,t),e=>{e&&this._diag.error("addCustomAttributesOnResourceSpan",e)})}enable(){window.removeEventListener("load",this._onDocumentLoaded),this._waitForPageLoad()}disable(){window.removeEventListener("load",this._onDocumentLoaded)}}const W_="OT_ZONE_CONTEXT";class Y_{_enabled=!1;_bindFunction(e,t){const r=this,n=function(...n){return r.with(e,()=>t.apply(this,n))};return Object.defineProperty(n,"length",{enumerable:!1,configurable:!0,writable:!1,value:t.length}),n}_bindListener(e,t){const r=t;return void 0!==r.__ot_listeners||(r.__ot_listeners={},"function"==typeof r.addEventListener&&(r.addEventListener=this._patchAddEventListener(r,r.addEventListener,e)),"function"==typeof r.removeEventListener&&(r.removeEventListener=this._patchRemoveEventListener(r,r.removeEventListener))),t}_createZone(e,t){return Zone.current.fork({name:e,properties:{[W_]:t}})}_patchAddEventListener(e,t,r){const n=this;return function(s,i,o){void 0===e.__ot_listeners&&(e.__ot_listeners={});let a=e.__ot_listeners[s];void 0===a&&(a=new WeakMap,e.__ot_listeners[s]=a);const l=n.bind(r,i);return a.set(i,l),t.call(this,s,l,o)}}_patchRemoveEventListener(e,t){return function(r,n){if(void 0===e.__ot_listeners||void 0===e.__ot_listeners[r])return t.call(this,r,n);const s=e.__ot_listeners[r],i=s.get(n);return s.delete(n),t.call(this,r,i||n)}}active(){return this._enabled&&Zone.current&&Zone.current.get(W_)||gw}bind(e,t){return"function"==typeof t?this._bindFunction(e,t):("object"==typeof(r=t)&&null!==r&&"addEventListener"in r&&"function"==typeof r.addEventListener&&"removeEventListener"in r&&"function"==typeof r.removeEventListener&&this._bindListener(e,t),t);var r}disable(){return this._enabled=!1,this}enable(){return this._enabled=!0,this}with(e,t,r,...n){let s="otel:with";return t.name&&(s+=`:${t.name}`),this._createZone(s,e).run(t,r,n)}} /** * @license Angular * (c) 2010-2026 Google LLC. https://angular.dev/ * License: MIT - */var X_=Object.defineProperty,J_=Object.defineProperties,K_=Object.getOwnPropertyDescriptors,q_=Object.getOwnPropertySymbols,Q_=Object.prototype.hasOwnProperty,eS=Object.prototype.propertyIsEnumerable,tS=(e,t,r)=>t in e?X_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,rS=(e,t)=>{for(var r in t||(t={}))Q_.call(t,r)&&tS(e,r,t[r]);if(q_)for(var r of q_(t))eS.call(t,r)&&tS(e,r,t[r]);return e},nS=(e,t,r)=>(tS(e,"symbol"!=typeof t?t+"":t,r),r),sS=globalThis;function iS(e){return(sS.__Zone_symbol_prefix||"__zone_symbol__")+e}var oS=Object.getOwnPropertyDescriptor,aS=Object.defineProperty,lS=Object.getPrototypeOf,cS=Object.create,uS=Array.prototype.slice,hS="addEventListener",pS="removeEventListener",dS=iS(hS),fS=iS(pS),mS="true",gS="false",yS=iS("");function wS(e,t){return Zone.current.wrap(e,t)}function vS(e,t,r,n,s){return Zone.current.scheduleMacroTask(e,t,r,n,s)}var bS=iS,_S="undefined"!=typeof window,SS=_S?window:void 0,CS=_S&&SS||globalThis;function ES(e,t){for(let r=e.length-1;r>=0;r--)"function"==typeof e[r]&&(e[r]=wS(e[r],t+"_"+r));return e}function TS(e){return!e||!1!==e.writable&&!("function"==typeof e.get&&void 0===e.set)}var kS="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,xS=!("nw"in CS)&&void 0!==CS.process&&"[object process]"===CS.process.toString(),OS=!xS&&!kS&&!(!_S||!SS.HTMLElement),AS=void 0!==CS.process&&"[object process]"===CS.process.toString()&&!kS&&!(!_S||!SS.HTMLElement),IS={},RS=bS("enable_beforeunload"),MS=function(e){if(!(e=e||CS.event))return;let t=IS[e.type];t||(t=IS[e.type]=bS("ON_PROPERTY"+e.type));const r=this||e.target||CS,n=r[t];let s;if(OS&&r===SS&&"error"===e.type){const t=e;s=n&&n.call(this,t.message,t.filename,t.lineno,t.colno,t.error),!0===s&&e.preventDefault()}else s=n&&n.apply(this,arguments),"beforeunload"===e.type&&CS[RS]&&"string"==typeof s?e.returnValue=s:null==s||s||e.preventDefault();return s};function NS(e,t,r){let n=oS(e,t);if(!n&&r){oS(r,t)&&(n={enumerable:!0,configurable:!0})}if(!n||!n.configurable)return;const s=bS("on"+t+"patched");if(e.hasOwnProperty(s)&&e[s])return;delete n.writable,delete n.value;const i=n.get,o=n.set,a=t.slice(2);let l=IS[a];l||(l=IS[a]=bS("ON_PROPERTY"+a)),n.set=function(t){let r=this;if(r||e!==CS||(r=CS),!r)return;"function"==typeof r[l]&&r.removeEventListener(a,MS),null==o||o.call(r,null),r[l]=t,"function"==typeof t&&r.addEventListener(a,MS,!1)},n.get=function(){let r=this;if(r||e!==CS||(r=CS),!r)return null;const s=r[l];if(s)return s;if(i){let e=i.call(this);if(e)return n.set.call(this,e),"function"==typeof r.removeAttribute&&r.removeAttribute(t),e}return null},aS(e,t,n),e[s]=!0}function PS(e,t,r){if(t)for(let n=0;nfunction(t,n){const i=r(t,n);return i.cbIdx>=0&&"function"==typeof n[i.cbIdx]?vS(i.name,n[i.cbIdx],i,s):e.apply(t,n)})}function BS(e,t){e[bS("OriginalDelegate")]=t}function jS(e){return"function"==typeof e}function zS(e){return"number"==typeof e}var VS={useG:!0},GS={},HS={},ZS=new RegExp("^"+yS+"(\\w+)(true|false)$"),$S=bS("propagationStopped");function WS(e,t){const r=(t?t(e):e)+gS,n=(t?t(e):e)+mS,s=yS+r,i=yS+n;GS[e]={},GS[e][gS]=s,GS[e][mS]=i}function YS(e,t,r,n){const s=n&&n.add||hS,i=n&&n.rm||pS,o=n&&n.listeners||"eventListeners",a=n&&n.rmAll||"removeAllListeners",l=bS(s),c="."+s+":",u="prependListener",h="."+u+":",p=function(e,t,r){if(e.isRemoved)return;const n=e.callback;let s;"object"==typeof n&&n.handleEvent&&(e.callback=e=>n.handleEvent(e),e.originalDelegate=n);try{e.invoke(e,t,[r])}catch(e){s=e}const o=e.options;if(o&&"object"==typeof o&&o.once){const n=e.originalDelegate?e.originalDelegate:e.callback;t[i].call(t,r.type,n,o)}return s};function d(r,n,s){if(!(n=n||e.event))return;const i=r||n.target||e,o=i[GS[n.type][s?mS:gS]];if(o){const e=[];if(1===o.length){const t=p(o[0],i,n);t&&e.push(t)}else{const t=o.slice();for(let r=0;r{throw n})}}}const f=function(e){return d(this,e,!1)},m=function(e){return d(this,e,!0)};function g(t,r){if(!t)return!1;let n=!0;r&&void 0!==r.useG&&(n=r.useG);const p=r&&r.vh;let d=!0;r&&void 0!==r.chkDup&&(d=r.chkDup);let g=!1;r&&void 0!==r.rt&&(g=r.rt);let y=t;for(;y&&!y.hasOwnProperty(s);)y=lS(y);if(!y&&t[s]&&(y=t),!y)return!1;if(y[l])return!1;const w=r&&r.eventNameToString,v={},b=y[l]=y[s],_=y[bS(i)]=y[i],S=y[bS(o)]=y[o],C=y[bS(a)]=y[a];let E;function T(e,t){return t?"boolean"==typeof e?{capture:e,passive:!0}:e?"object"==typeof e&&!1!==e.passive?((e,t)=>J_(e,K_(t)))(rS({},e),{passive:!0}):e:{passive:!0}:e}r&&r.prepend&&(E=y[bS(r.prepend)]=y[r.prepend]);const k=function(e){return E.call(v.target,v.eventName,e.invoke,v.options)},x=n?function(e){if(!v.isExisting)return b.call(v.target,v.eventName,v.capture?m:f,v.options)}:function(e){return b.call(v.target,v.eventName,e.invoke,v.options)},O=n?function(e){if(!e.isRemoved){const t=GS[e.eventName];let r;t&&(r=t[e.capture?mS:gS]);const n=r&&e.target[r];if(n)for(let t=0;tL.zone.cancelTask(L);t.call(y,"abort",e,{once:!0}),L.removeAbortListener=()=>y.removeEventListener("abort",e)}return v.target=null,P&&(P.taskData=null),_&&(v.options.once=!0),"boolean"!=typeof L.options&&(L.options=g),L.target=c,L.capture=b,L.eventName=u,f&&(L.originalDelegate=h),l?x.unshift(L):x.push(L),a?c:void 0}};return y[s]=M(b,c,x,O,g),E&&(y[u]=M(E,h,k,O,g,!0)),y[i]=function(){const t=this||e;let n=arguments[0];r&&r.transferEventName&&(n=r.transferEventName(n));const s=arguments[2],i=!!s&&("boolean"==typeof s||s.capture),o=arguments[1];if(!o)return _.apply(this,arguments);if(p&&!p(_,o,t,arguments))return;const a=GS[n];let l;a&&(l=a[i?mS:gS]);const c=l&&t[l];if(c)for(let e=0;efunction(t,r){t[$S]=!0,e&&e.apply(t,r)})}var KS=bS("zoneTask");function qS(e,t,r,n){let s=null,i=null;r+=n;const o={};function a(t){const r=t.data;r.args[0]=function(){return t.invoke.apply(this,arguments)};const n=s.apply(e,r.args);return zS(n)?r.handleId=n:(r.handle=n,r.isRefreshable=jS(n.refresh)),t}function l(t){const{handle:r,handleId:n}=t.data;return i.call(e,null!=r?r:n)}s=US(e,t+=n,r=>function(s,i){var c;if(jS(i[0])){const e={isRefreshable:!1,isPeriodic:"Interval"===n,delay:"Timeout"===n||"Interval"===n?i[1]||0:void 0,args:i},r=i[0];i[0]=function(){try{return r.apply(this,arguments)}finally{const{handle:t,handleId:r,isPeriodic:n,isRefreshable:s}=e;n||s||(r?delete o[r]:t&&(t[KS]=null))}};const s=vS(t,i[0],e,a,l);if(!s)return s;const{handleId:u,handle:h,isRefreshable:p,isPeriodic:d}=s.data;if(u)o[u]=s;else if(h&&(h[KS]=s,p&&!d)){const e=h.refresh;h.refresh=function(){const{zone:t,state:r}=s;return"notScheduled"===r?(s._state="scheduled",t._updateTaskCount(s,1)):"running"===r&&(s._state="scheduling"),e.call(this)}}return null!=(c=null!=h?h:u)?c:s}return r.apply(e,i)}),i=US(e,r,t=>function(r,n){const s=n[0];let i;zS(s)?(i=o[s],delete o[s]):(i=null==s?void 0:s[KS],i?s[KS]=null:i=s),(null==i?void 0:i.type)?i.cancelFn&&i.zone.cancelTask(i):t.apply(e,n)})}function QS(e,t,r){if(!r||0===r.length)return t;const n=r.filter(t=>t.target===e);if(0===n.length)return t;const s=n[0].ignoreProperties;return t.filter(e=>-1===s.indexOf(e))}function eC(e,t,r,n){if(!e)return;PS(e,QS(e,t,r),n)}function tC(e){return Object.getOwnPropertyNames(e).filter(e=>e.startsWith("on")&&e.length>2).map(e=>e.substring(2))}function rC(e){e.__load_patch("ZoneAwarePromise",(e,t,r)=>{const n=Object.getOwnPropertyDescriptor,s=Object.defineProperty;const i=r.symbol,o=[],a=!1!==e[i("DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION")],l=i("Promise"),c=i("then");r.onUnhandledError=e=>{if(r.showUncaughtError()){const t=e&&e.rejection;t?console.error("Unhandled Promise rejection:",t instanceof Error?t.message:t,"; Zone:",e.zone.name,"; Task:",e.task&&e.task.source,"; Value:",t,t instanceof Error?t.stack:void 0):console.error(e)}},r.microtaskDrainDone=()=>{for(;o.length;){const e=o.shift();try{e.zone.runGuarded(()=>{if(e.throwOriginal)throw e.rejection;throw e})}catch(e){h(e)}}};const u=i("unhandledPromiseRejectionHandler");function h(e){r.onUnhandledError(e);try{const r=t[u];"function"==typeof r&&r.call(this,e)}catch(e){}}function p(e){return e&&"function"==typeof e.then}function d(e){return e}function f(e){return N.reject(e)}const m=i("state"),g=i("value"),y=i("finally"),w=i("parentPromiseValue"),v=i("parentPromiseState"),b=null,_=!0,S=!1;function C(e,t){return r=>{try{x(e,t,r)}catch(t){x(e,!1,t)}}}const E=function(){let e=!1;return function(t){return function(){e||(e=!0,t.apply(null,arguments))}}},T="Promise resolved with itself",k=i("currentTaskTrace");function x(e,n,i){const l=E();if(e===i)throw new TypeError(T);if(e[m]===b){let c=null;try{"object"!=typeof i&&"function"!=typeof i||(c=i&&i.then)}catch(t){return l(()=>{x(e,!1,t)})(),e}if(n!==S&&i instanceof N&&i.hasOwnProperty(m)&&i.hasOwnProperty(g)&&i[m]!==b)A(i),x(e,i[m],i[g]);else if(n!==S&&"function"==typeof c)try{c.call(i,l(C(e,n)),l(C(e,!1)))}catch(t){l(()=>{x(e,!1,t)})()}else{e[m]=n;const l=e[g];if(e[g]=i,e[y]===y&&n===_&&(e[m]=e[v],e[g]=e[w]),n===S&&i instanceof Error){const e=t.currentTask&&t.currentTask.data&&t.currentTask.data.__creationTrace__;e&&s(i,k,{configurable:!0,enumerable:!1,writable:!0,value:e})}for(let t=0;t{try{const n=e[g],s=!!r&&y===r[y];s&&(r[w]=n,r[v]=i);const a=t.run(o,void 0,s&&o!==f&&o!==d?[]:[n]);x(r,!0,a)}catch(e){x(r,!1,e)}},r)}const R=function(){},M=e.AggregateError;class N{static toString(){return"function ZoneAwarePromise() { [native code] }"}static resolve(e){return e instanceof N?e:x(new this(null),_,e)}static reject(e){return x(new this(null),S,e)}static withResolvers(){const e={};return e.promise=new N((t,r)=>{e.resolve=t,e.reject=r}),e}static any(e){if(!e||"function"!=typeof e[Symbol.iterator])return Promise.reject(new M([],"All promises were rejected"));const t=[];let r=0;try{for(let n of e)r++,t.push(N.resolve(n))}catch(e){return Promise.reject(new M([],"All promises were rejected"))}if(0===r)return Promise.reject(new M([],"All promises were rejected"));let n=!1;const s=[];return new N((e,i)=>{for(let o=0;o{n||(n=!0,e(t))},e=>{s.push(e),r--,0===r&&(n=!0,i(new M(s,"All promises were rejected")))})})}static race(e){let t,r,n=new this((e,n)=>{t=e,r=n});function s(e){t(e)}function i(e){r(e)}for(let t of e)p(t)||(t=this.resolve(t)),t.then(s,i);return n}static all(e){return N.allWithCallback(e)}static allSettled(e){return(this&&this.prototype instanceof N?this:N).allWithCallback(e,{thenCallback:e=>({status:"fulfilled",value:e}),errorCallback:e=>({status:"rejected",reason:e})})}static allWithCallback(e,t){let r,n,s=new this((e,t)=>{r=e,n=t}),i=2,o=0;const a=[];for(let s of e){p(s)||(s=this.resolve(s));const e=o;try{s.then(n=>{a[e]=t?t.thenCallback(n):n,i--,0===i&&r(a)},s=>{t?(a[e]=t.errorCallback(s),i--,0===i&&r(a)):n(s)})}catch(e){n(e)}i++,o++}return i-=2,0===i&&r(a),s}constructor(e){const t=this;if(!(t instanceof N))throw new Error("Must be an instanceof Promise.");t[m]=b,t[g]=[];try{const r=E();e&&e(r(C(t,_)),r(C(t,S)))}catch(e){x(t,!1,e)}}get[Symbol.toStringTag](){return"Promise"}get[Symbol.species](){return N}then(e,r){var n;let s=null==(n=this.constructor)?void 0:n[Symbol.species];s&&"function"==typeof s||(s=this.constructor||N);const i=new s(R),o=t.current;return this[m]==b?this[g].push(o,i,e,r):I(this,o,i,e,r),i}catch(e){return this.then(null,e)}finally(e){var r;let n=null==(r=this.constructor)?void 0:r[Symbol.species];n&&"function"==typeof n||(n=N);const s=new n(R);s[y]=y;const i=t.current;return this[m]==b?this[g].push(i,s,e,e):I(this,i,s,e,e),s}}N.resolve=N.resolve,N.reject=N.reject,N.race=N.race,N.all=N.all;const P=e[l]=e.Promise;e.Promise=N;const L=i("thenPatched");function D(e){const t=e.prototype,r=n(t,"then");if(r&&(!1===r.writable||!r.configurable))return;const s=t.then;t[c]=s,e.prototype.then=function(e,t){const r=new N((e,t)=>{s.call(this,e,t)});return r.then(e,t)},e[L]=!0}if(r.patchThen=D,P){D(P);const t=P.try;t&&"function"==typeof t&&(N.try=t),US(e,"fetch",e=>{return t=e,function(e,r){let n=t.apply(e,r);if(n instanceof N)return n;let s=n.constructor;return s[L]||D(s),n};var t})}return Promise[t.__symbol__("uncaughtPromiseErrors")]=o,N})}function nC(e,t,r,n,s){const i=Zone.__symbol__(n);if(t[i])return;const o=t[i]=t[n];t[n]=function(i,a,l){return a&&a.prototype&&s.forEach(function(t){const s=`${r}.${n}::`+t,i=a.prototype;try{if(i.hasOwnProperty(t)){const r=e.ObjectGetOwnPropertyDescriptor(i,t);r&&r.value?(r.value=e.wrapWithCurrentZone(r.value,s),e._redefineProperty(a.prototype,t,r)):i[t]&&(i[t]=e.wrapWithCurrentZone(i[t],s))}else i[t]&&(i[t]=e.wrapWithCurrentZone(i[t],s))}catch(e){}}),o.call(t,i,a,l)},e.attachOriginToPatched(t[n],o)}var sC,iC=function(){const e=globalThis,t=!0===e[iS("forceDuplicateZoneCheck")];if(e.Zone&&(t||"function"!=typeof e.Zone.__symbol__))throw new Error("Zone already loaded.");return null!=e.Zone||(e.Zone=function(){const e=sS.performance;function t(t){e&&e.mark&&e.mark(t)}function r(t,r){e&&e.measure&&e.measure(t,r)}t("Zone");const n=class e{constructor(e,t){nS(this,"_parent"),nS(this,"_name"),nS(this,"_properties"),nS(this,"_zoneDelegate"),this._parent=e,this._name=t?t.name||"unnamed":"",this._properties=t&&t.properties||{},this._zoneDelegate=new o(this,this._parent&&this._parent._zoneDelegate,t)}static assertZonePatched(){if(sS.Promise!==x.ZoneAwarePromise)throw new Error("Zone.js has detected that ZoneAwarePromise `(window|global).Promise` has been overwritten.\nMost likely cause is that a Promise polyfill has been loaded after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. If you must load one, do so before loading zone.js.)")}static get root(){let t=e.current;for(;t.parent;)t=t.parent;return t}static get current(){return A.zone}static get currentTask(){return I}static __load_patch(n,s,i=!1){if(x.hasOwnProperty(n)){const e=!0===sS[iS("forceDuplicateZoneCheck")];if(!i&&e)throw Error("Already loaded patch: "+n)}else if(!sS["__Zone_disable_"+n]){const i="Zone:"+n;t(i),x[n]=s(sS,e,O),r(i,i)}}get parent(){return this._parent}get name(){return this._name}get(e){const t=this.getZoneWith(e);if(t)return t._properties[e]}getZoneWith(e){let t=this;for(;t;){if(t._properties.hasOwnProperty(e))return t;t=t._parent}return null}fork(e){if(!e)throw new Error("ZoneSpec required!");return this._zoneDelegate.fork(this,e)}wrap(e,t){if("function"!=typeof e)throw new Error("Expecting function got: "+e);const r=this._zoneDelegate.intercept(this,e,t),n=this;return function(){return n.runGuarded(r,this,arguments,t)}}run(e,t,r,n){A={parent:A,zone:this};try{return this._zoneDelegate.invoke(this,e,t,r,n)}finally{A=A.parent}}runGuarded(e,t=null,r,n){A={parent:A,zone:this};try{try{return this._zoneDelegate.invoke(this,e,t,r,n)}catch(e){if(this._zoneDelegate.handleError(this,e))throw e}}finally{A=A.parent}}runTask(e,t,r){if(e.zone!=this)throw new Error("A task can only be run in the zone of creation! (Creation: "+(e.zone||y).name+"; Execution: "+this.name+")");const n=e,{type:s,data:{isPeriodic:i=!1,isRefreshable:o=!1}={}}=e;if(e.state===w&&(s===k||s===T))return;const a=e.state!=_;a&&n._transitionTo(_,b);const l=I;I=n,A={parent:A,zone:this};try{s!=T||!e.data||i||o||(e.cancelFn=void 0);try{return this._zoneDelegate.invokeTask(this,n,t,r)}catch(e){if(this._zoneDelegate.handleError(this,e))throw e}}finally{const t=e.state;if(t!==w&&t!==C)if(s==k||i||o&&t===v)a&&n._transitionTo(b,_,v);else{const e=n._zoneDelegates;this._updateTaskCount(n,-1),a&&n._transitionTo(w,_,w),o&&(n._zoneDelegates=e)}A=A.parent,I=l}}scheduleTask(e){if(e.zone&&e.zone!==this){let t=this;for(;t;){if(t===e.zone)throw Error(`can not reschedule task to ${this.name} which is descendants of the original zone ${e.zone.name}`);t=t.parent}}e._transitionTo(v,w);const t=[];e._zoneDelegates=t,e._zone=this;try{e=this._zoneDelegate.scheduleTask(this,e)}catch(t){throw e._transitionTo(C,v,w),this._zoneDelegate.handleError(this,t),t}return e._zoneDelegates===t&&this._updateTaskCount(e,1),e.state==v&&e._transitionTo(b,v),e}scheduleMicroTask(e,t,r,n){return this.scheduleTask(new a(E,e,t,r,n,void 0))}scheduleMacroTask(e,t,r,n,s){return this.scheduleTask(new a(T,e,t,r,n,s))}scheduleEventTask(e,t,r,n,s){return this.scheduleTask(new a(k,e,t,r,n,s))}cancelTask(e){if(e.zone!=this)throw new Error("A task can only be cancelled in the zone of creation! (Creation: "+(e.zone||y).name+"; Execution: "+this.name+")");if(e.state===b||e.state===_){e._transitionTo(S,b,_);try{this._zoneDelegate.cancelTask(this,e)}catch(t){throw e._transitionTo(C,S),this._zoneDelegate.handleError(this,t),t}return this._updateTaskCount(e,-1),e._transitionTo(w,S),e.runCount=-1,e}}_updateTaskCount(e,t){const r=e._zoneDelegates;-1==t&&(e._zoneDelegates=null);for(let n=0;ne.hasTask(r,n),onScheduleTask:(e,t,r,n)=>e.scheduleTask(r,n),onInvokeTask:(e,t,r,n,s,i)=>e.invokeTask(r,n,s,i),onCancelTask:(e,t,r,n)=>e.cancelTask(r,n)};class o{constructor(e,t,r){nS(this,"_zone"),nS(this,"_taskCounts",{microTask:0,macroTask:0,eventTask:0}),nS(this,"_parentDelegate"),nS(this,"_forkDlgt"),nS(this,"_forkZS"),nS(this,"_forkCurrZone"),nS(this,"_interceptDlgt"),nS(this,"_interceptZS"),nS(this,"_interceptCurrZone"),nS(this,"_invokeDlgt"),nS(this,"_invokeZS"),nS(this,"_invokeCurrZone"),nS(this,"_handleErrorDlgt"),nS(this,"_handleErrorZS"),nS(this,"_handleErrorCurrZone"),nS(this,"_scheduleTaskDlgt"),nS(this,"_scheduleTaskZS"),nS(this,"_scheduleTaskCurrZone"),nS(this,"_invokeTaskDlgt"),nS(this,"_invokeTaskZS"),nS(this,"_invokeTaskCurrZone"),nS(this,"_cancelTaskDlgt"),nS(this,"_cancelTaskZS"),nS(this,"_cancelTaskCurrZone"),nS(this,"_hasTaskDlgt"),nS(this,"_hasTaskDlgtOwner"),nS(this,"_hasTaskZS"),nS(this,"_hasTaskCurrZone"),this._zone=e,this._parentDelegate=t,this._forkZS=r&&(r&&r.onFork?r:t._forkZS),this._forkDlgt=r&&(r.onFork?t:t._forkDlgt),this._forkCurrZone=r&&(r.onFork?this._zone:t._forkCurrZone),this._interceptZS=r&&(r.onIntercept?r:t._interceptZS),this._interceptDlgt=r&&(r.onIntercept?t:t._interceptDlgt),this._interceptCurrZone=r&&(r.onIntercept?this._zone:t._interceptCurrZone),this._invokeZS=r&&(r.onInvoke?r:t._invokeZS),this._invokeDlgt=r&&(r.onInvoke?t:t._invokeDlgt),this._invokeCurrZone=r&&(r.onInvoke?this._zone:t._invokeCurrZone),this._handleErrorZS=r&&(r.onHandleError?r:t._handleErrorZS),this._handleErrorDlgt=r&&(r.onHandleError?t:t._handleErrorDlgt),this._handleErrorCurrZone=r&&(r.onHandleError?this._zone:t._handleErrorCurrZone),this._scheduleTaskZS=r&&(r.onScheduleTask?r:t._scheduleTaskZS),this._scheduleTaskDlgt=r&&(r.onScheduleTask?t:t._scheduleTaskDlgt),this._scheduleTaskCurrZone=r&&(r.onScheduleTask?this._zone:t._scheduleTaskCurrZone),this._invokeTaskZS=r&&(r.onInvokeTask?r:t._invokeTaskZS),this._invokeTaskDlgt=r&&(r.onInvokeTask?t:t._invokeTaskDlgt),this._invokeTaskCurrZone=r&&(r.onInvokeTask?this._zone:t._invokeTaskCurrZone),this._cancelTaskZS=r&&(r.onCancelTask?r:t._cancelTaskZS),this._cancelTaskDlgt=r&&(r.onCancelTask?t:t._cancelTaskDlgt),this._cancelTaskCurrZone=r&&(r.onCancelTask?this._zone:t._cancelTaskCurrZone),this._hasTaskZS=null,this._hasTaskDlgt=null,this._hasTaskDlgtOwner=null,this._hasTaskCurrZone=null;const n=r&&r.onHasTask,s=t&&t._hasTaskZS;(n||s)&&(this._hasTaskZS=n?r:i,this._hasTaskDlgt=t,this._hasTaskDlgtOwner=this,this._hasTaskCurrZone=this._zone,r.onScheduleTask||(this._scheduleTaskZS=i,this._scheduleTaskDlgt=t,this._scheduleTaskCurrZone=this._zone),r.onInvokeTask||(this._invokeTaskZS=i,this._invokeTaskDlgt=t,this._invokeTaskCurrZone=this._zone),r.onCancelTask||(this._cancelTaskZS=i,this._cancelTaskDlgt=t,this._cancelTaskCurrZone=this._zone))}get zone(){return this._zone}fork(e,t){return this._forkZS?this._forkZS.onFork(this._forkDlgt,this.zone,e,t):new s(e,t)}intercept(e,t,r){return this._interceptZS?this._interceptZS.onIntercept(this._interceptDlgt,this._interceptCurrZone,e,t,r):t}invoke(e,t,r,n,s){return this._invokeZS?this._invokeZS.onInvoke(this._invokeDlgt,this._invokeCurrZone,e,t,r,n,s):t.apply(r,n)}handleError(e,t){return!this._handleErrorZS||this._handleErrorZS.onHandleError(this._handleErrorDlgt,this._handleErrorCurrZone,e,t)}scheduleTask(e,t){let r=t;if(this._scheduleTaskZS)this._hasTaskZS&&r._zoneDelegates.push(this._hasTaskDlgtOwner),r=this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt,this._scheduleTaskCurrZone,e,t),r||(r=t);else if(t.scheduleFn)t.scheduleFn(t);else{if(t.type!=E)throw new Error("Task is missing scheduleFn.");m(t)}return r}invokeTask(e,t,r,n){return this._invokeTaskZS?this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt,this._invokeTaskCurrZone,e,t,r,n):t.callback.apply(r,n)}cancelTask(e,t){let r;if(this._cancelTaskZS)r=this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt,this._cancelTaskCurrZone,e,t);else{if(!t.cancelFn)throw Error("Task is not cancelable");r=t.cancelFn(t)}return r}hasTask(e,t){try{this._hasTaskZS&&this._hasTaskZS.onHasTask(this._hasTaskDlgt,this._hasTaskCurrZone,e,t)}catch(t){this.handleError(e,t)}}_updateTaskCount(e,t){const r=this._taskCounts,n=r[e],s=r[e]=n+t;if(s<0)throw new Error("More tasks executed then were scheduled.");if(0==n||0==s){const t={microTask:r.microTask>0,macroTask:r.macroTask>0,eventTask:r.eventTask>0,change:e};this.hasTask(this._zone,t)}}}class a{constructor(e,t,r,n,s,i){if(nS(this,"type"),nS(this,"source"),nS(this,"invoke"),nS(this,"callback"),nS(this,"data"),nS(this,"scheduleFn"),nS(this,"cancelFn"),nS(this,"_zone",null),nS(this,"runCount",0),nS(this,"_zoneDelegates",null),nS(this,"_state","notScheduled"),this.type=e,this.source=t,this.data=n,this.scheduleFn=s,this.cancelFn=i,!r)throw new Error("callback is not defined");this.callback=r;const o=this;e===k&&n&&n.useG?this.invoke=a.invokeTask:this.invoke=function(){return a.invokeTask.call(sS,o,this,arguments)}}static invokeTask(e,t,r){e||(e=this),R++;try{return e.runCount++,e.zone.runTask(e,t,r)}finally{1==R&&g(),R--}}get zone(){return this._zone}get state(){return this._state}cancelScheduleRequest(){this._transitionTo(w,v)}_transitionTo(e,t,r){if(this._state!==t&&this._state!==r)throw new Error(`${this.type} '${this.source}': can not transition to '${e}', expecting state '${t}'${r?" or '"+r+"'":""}, was '${this._state}'.`);this._state=e,e==w&&(this._zoneDelegates=null)}toString(){return this.data&&void 0!==this.data.handleId?this.data.handleId.toString():Object.prototype.toString.call(this)}toJSON(){return{type:this.type,state:this.state,source:this.source,zone:this.zone.name,runCount:this.runCount}}}const l=iS("setTimeout"),c=iS("Promise"),u=iS("then");let h,p=[],d=!1;function f(e){if(h||sS[c]&&(h=sS[c].resolve(0)),h){let t=h[u];t||(t=h.then),t.call(h,e)}else sS[l](e,0)}function m(e){0===R&&0===p.length&&f(g),e&&p.push(e)}function g(){if(!d){for(d=!0;p.length;){const e=p;p=[];for(let t=0;tA,onUnhandledError:M,microtaskDrainDone:M,scheduleMicroTask:m,showUncaughtError:()=>!s[iS("ignoreConsoleErrorUncaughtError")],patchEventTarget:()=>[],patchOnProperties:M,patchMethod:()=>M,bindArguments:()=>[],patchThen:()=>M,patchMacroTask:()=>M,patchEventPrototype:()=>M,getGlobalObjects:()=>{},ObjectDefineProperty:()=>M,ObjectGetOwnPropertyDescriptor:()=>{},ObjectCreate:()=>{},ArraySlice:()=>[],patchClass:()=>M,wrapWithCurrentZone:()=>M,filterProperties:()=>[],attachOriginToPatched:()=>M,_redefineProperty:()=>M,patchCallbacks:()=>M,nativeScheduleMicroTask:f};let A={parent:null,zone:new s(null,null)},I=null,R=0;function M(){}return r("Zone","Zone"),s}()),e.Zone}();rC(sC=iC),function(e){e.__load_patch("toString",e=>{const t=Function.prototype.toString,r=bS("OriginalDelegate"),n=bS("Promise"),s=bS("Error"),i=function(){if("function"==typeof this){const i=this[r];if(i)return"function"==typeof i?t.call(i):Object.prototype.toString.call(i);if(this===Promise){const r=e[n];if(r)return t.call(r)}if(this===Error){const r=e[s];if(r)return t.call(r)}}return t.call(this)};i[r]=t,Function.prototype.toString=i;const o=Object.prototype.toString;Object.prototype.toString=function(){return"function"==typeof Promise&&this instanceof Promise?"[object Promise]":o.call(this)}})}(sC),function(e){e.__load_patch("util",(e,t,r)=>{const n=tC(e);r.patchOnProperties=PS,r.patchMethod=US,r.bindArguments=ES,r.patchMacroTask=FS;const s=t.__symbol__("BLACK_LISTED_EVENTS"),i=t.__symbol__("UNPATCHED_EVENTS");e[i]&&(e[s]=e[i]),e[s]&&(t[s]=t[i]=e[s]),r.patchEventPrototype=JS,r.patchEventTarget=YS,r.ObjectDefineProperty=aS,r.ObjectGetOwnPropertyDescriptor=oS,r.ObjectCreate=cS,r.ArraySlice=uS,r.patchClass=DS,r.wrapWithCurrentZone=wS,r.filterProperties=QS,r.attachOriginToPatched=BS,r._redefineProperty=Object.defineProperty,r.patchCallbacks=nC,r.getGlobalObjects=()=>({globalSources:HS,zoneSymbolEventNames:GS,eventNames:n,isBrowser:OS,isMix:AS,isNode:xS,TRUE_STR:mS,FALSE_STR:gS,ZONE_SYMBOL_PREFIX:yS,ADD_EVENT_LISTENER_STR:hS,REMOVE_EVENT_LISTENER_STR:pS})})}(sC),function(e){e.__load_patch("timers",e=>{const t="set",r="clear";qS(e,t,r,"Timeout"),qS(e,t,r,"Interval"),qS(e,t,r,"Immediate")}),e.__load_patch("requestAnimationFrame",e=>{qS(e,"request","cancel","AnimationFrame"),qS(e,"mozRequest","mozCancel","AnimationFrame"),qS(e,"webkitRequest","webkitCancel","AnimationFrame")}),e.__load_patch("blocking",(e,t)=>{const r=["alert","prompt","confirm"];for(let n=0;nfunction(n,i){return t.current.run(r,e,i,s)})}}),e.__load_patch("EventTarget",(e,t,r)=>{!function(e,t){t.patchEventPrototype(e,t)}(e,r),function(e,t){if(Zone[t.symbol("patchEventTarget")])return;const{eventNames:r,zoneSymbolEventNames:n,TRUE_STR:s,FALSE_STR:i,ZONE_SYMBOL_PREFIX:o}=t.getGlobalObjects();for(let e=0;e{DS("MutationObserver"),DS("WebKitMutationObserver")}),e.__load_patch("IntersectionObserver",(e,t,r)=>{DS("IntersectionObserver")}),e.__load_patch("FileReader",(e,t,r)=>{DS("FileReader")}),e.__load_patch("on_property",(e,t,r)=>{!function(e,t){if(xS&&!AS)return;if(Zone[e.symbol("patchEvents")])return;const r=t.__Zone_ignore_on_properties;let n=[];if(OS){const e=window;n=n.concat(["Document","SVGElement","Element","HTMLElement","HTMLBodyElement","HTMLMediaElement","HTMLFrameSetElement","HTMLFrameElement","HTMLIFrameElement","HTMLMarqueeElement","Worker"]),eC(e,tC(e),r,lS(e))}n=n.concat(["XMLHttpRequest","XMLHttpRequestEventTarget","IDBIndex","IDBRequest","IDBOpenDBRequest","IDBDatabase","IDBTransaction","IDBCursor","WebSocket"]);for(let e=0;e{!function(e,t){const{isBrowser:r,isMix:n}=t.getGlobalObjects();if(!r&&!n||!e.customElements||!("customElements"in e))return;t.patchCallbacks(t,e.customElements,"customElements","define",["connectedCallback","disconnectedCallback","adoptedCallback","attributeChangedCallback","formAssociatedCallback","formDisabledCallback","formResetCallback","formStateRestoreCallback"])}(e,r)}),e.__load_patch("XHR",(e,t)=>{!function(e){const l=e.XMLHttpRequest;if(!l)return;const c=l.prototype;let u=c[dS],h=c[fS];if(!u){const t=e.XMLHttpRequestEventTarget;if(t){const e=t.prototype;u=e[dS],h=e[fS]}}const p="readystatechange",d="scheduled";function f(e){const n=e.data,o=n.target;o[i]=!1,o[a]=!1;const l=o[s];u||(u=o[dS],h=o[fS]),l&&h.call(o,p,l);const c=o[s]=()=>{if(o.readyState===o.DONE)if(!n.aborted&&o[i]&&e.state===d){const r=o[t.__symbol__("loadfalse")];if(0!==o.status&&r&&r.length>0){const s=e.invoke;e.invoke=function(){const r=o[t.__symbol__("loadfalse")];for(let t=0;tfunction(e,t){return e[n]=0==t[2],e[o]=t[1],y.apply(e,t)}),w=bS("fetchTaskAborting"),v=bS("fetchTaskScheduling"),b=US(c,"send",()=>function(e,r){if(!0===t.current[v])return b.apply(e,r);if(e[n])return b.apply(e,r);{const t={target:e,url:e[o],isPeriodic:!1,args:r,aborted:!1},n=vS("XMLHttpRequest.send",m,t,f,g);e&&!0===e[a]&&!t.aborted&&n.state===d&&n.invoke()}}),_=US(c,"abort",()=>function(e,n){const s=e[r];if(s&&"string"==typeof s.type){if(null==s.cancelFn||s.data&&s.data.aborted)return;s.zone.cancelTask(s)}else if(!0===t.current[w])return _.apply(e,n)})}(e);const r=bS("xhrTask"),n=bS("xhrSync"),s=bS("xhrListener"),i=bS("xhrScheduled"),o=bS("xhrURL"),a=bS("xhrErrorBeforeScheduled")}),e.__load_patch("geolocation",e=>{e.navigator&&e.navigator.geolocation&&function(e,t){const r=e.constructor.name;for(let n=0;n{const t=function(){return e.apply(this,ES(arguments,r+"."+s))};return BS(t,e),t})(i)}}}(e.navigator.geolocation,["getCurrentPosition","watchPosition"])}),e.__load_patch("PromiseRejectionEvent",(e,t)=>{function r(t){return function(r){XS(e,t).forEach(n=>{const s=e.PromiseRejectionEvent;if(s){const e=new s(t,{promise:r.promise,reason:r.rejection});n.invoke(e)}})}}e.PromiseRejectionEvent&&(t[bS("unhandledPromiseRejectionHandler")]=r("unhandledrejection"),t[bS("rejectionHandledHandler")]=r("rejectionhandled"))}),e.__load_patch("queueMicrotask",(e,t,r)=>{!function(e,t){t.patchMethod(e,"queueMicrotask",e=>function(e,t){Zone.current.scheduleMicroTask("queueMicrotask",t[0])})}(e,r)})}(iC);const oC=fw("OpenTelemetry SDK Context Key SUPPRESS_TRACING");let aC=e=>{av.error(function(e){return"string"==typeof e?e:JSON.stringify(function(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}(e))}(e))};function lC(e){try{aC(e)}catch{}}const cC="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},uC=performance,hC="process.runtime.name",pC={[Wv]:"opentelemetry",[hC]:"browser",[Zv]:$v,[Yv]:"2.0.1"};const dC=Math.pow(10,6),fC=Math.pow(10,9);function mC(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*dC)]}function gC(){let e=uC.timeOrigin;if("number"!=typeof e){const t=uC;e=t.timing&&t.timing.fetchStart}return e}function yC(e){return function(e,t){const r=[e[0]+t[0],e[1]+t[1]];r[1]>=fC&&(r[1]-=fC,r[0]+=1);return r}(mC(gC()),mC("number"==typeof e?e:uC.now()))}function wC(e){if(t=e,Array.isArray(t)&&2===t.length&&"number"==typeof t[0]&&"number"==typeof t[1])return e;if("number"==typeof e)return e{ov.with(function(e){return e.setValue(oC,!0)}(ov.active()),()=>{e.export(t,e=>{r(e)})})})}};const TC=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;class kC{_rawAttributes;_asyncAttributesPending=!1;_memoizedAttributes;static FromAttributeList(e){const t=new kC({});return t._rawAttributes=OC(e),t._asyncAttributesPending=e.filter(([e,t])=>TC(t)).length>0,t}constructor(e){const t=e.attributes??{};this._rawAttributes=Object.entries(t).map(([e,t])=>(TC(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=OC(this._rawAttributes)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;eTC(t)?[e,t.catch(t=>{av.debug("promise rejection for resource attribute: %s - %s",e,t)})]:[e,t])}var AC;!function(e){e.CONNECT_END="connectEnd",e.CONNECT_START="connectStart",e.DECODED_BODY_SIZE="decodedBodySize",e.DOM_COMPLETE="domComplete",e.DOM_CONTENT_LOADED_EVENT_END="domContentLoadedEventEnd",e.DOM_CONTENT_LOADED_EVENT_START="domContentLoadedEventStart",e.DOM_INTERACTIVE="domInteractive",e.DOMAIN_LOOKUP_END="domainLookupEnd",e.DOMAIN_LOOKUP_START="domainLookupStart",e.ENCODED_BODY_SIZE="encodedBodySize",e.FETCH_START="fetchStart",e.LOAD_EVENT_END="loadEventEnd",e.LOAD_EVENT_START="loadEventStart",e.NAVIGATION_START="navigationStart",e.REDIRECT_END="redirectEnd",e.REDIRECT_START="redirectStart",e.REQUEST_START="requestStart",e.RESPONSE_END="responseEnd",e.RESPONSE_START="responseStart",e.SECURE_CONNECTION_START="secureConnectionStart",e.START_TIME="startTime",e.UNLOAD_EVENT_END="unloadEventEnd",e.UNLOAD_EVENT_START="unloadEventStart"}(AC||(AC={}));let IC;function RC(e,t,r,n=!0){if(!(s=r,i=t,!(i in s)||"number"!=typeof r[t]||n&&0===r[t]))return e.addEvent(t,r[t]);var s,i}function MC(e,t,r=!1,n,s){if(void 0===n&&(n=0!==t[AC.START_TIME]),r||(RC(e,AC.FETCH_START,t,n),RC(e,AC.DOMAIN_LOOKUP_START,t,n),RC(e,AC.DOMAIN_LOOKUP_END,t,n),RC(e,AC.CONNECT_START,t,n),RC(e,AC.SECURE_CONNECTION_START,t,n),RC(e,AC.CONNECT_END,t,n),RC(e,AC.REQUEST_START,t,n),RC(e,AC.RESPONSE_START,t,n),RC(e,AC.RESPONSE_END,t,n)),!s){const r=t[AC.ENCODED_BODY_SIZE];void 0!==r&&e.setAttribute("http.response_content_length",r);const n=t[AC.DECODED_BODY_SIZE];void 0!==n&&r!==n&&e.setAttribute("http.response_content_length_uncompressed",n)}}function NC(){return"undefined"!=typeof location?location.origin:void 0}function PC(e,t,r,n,s=new WeakSet,i){const o=LC(e),a=function(e,t,r,n,s,i){const o=vC(t),a=vC(r);let l=n.filter(t=>{const r=vC(wC(t[AC.FETCH_START])),n=vC(wC(t[AC.RESPONSE_END]));return t.initiatorType.toLowerCase()===(i||"xmlhttprequest")&&t.name===e&&r>=o&&n<=a});l.length>0&&(l=l.filter(e=>!s.has(e)));return l}(e=o.toString(),t,r,n,s,i);if(0===a.length)return{mainRequest:void 0};if(1===a.length)return{mainRequest:a[0]};const l=function(e){return e.slice().sort((e,t)=>{const r=e[AC.FETCH_START],n=t[AC.FETCH_START];return r>n?1:r1){let e=l[0],t=function(e,t,r){const n=vC(r),s=vC(wC(t));let i,o=e[1];const a=e.length;for(let t=1;t=s&&(!i||lSC(e,t))}var UC;!function(e){e.METHOD_OPEN="open",e.METHOD_SEND="send",e.EVENT_ABORT="abort",e.EVENT_ERROR="error",e.EVENT_LOAD="loaded",e.EVENT_TIMEOUT="timeout"}(UC||(UC={}));const FC=av.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-xml-http-request/utils"});function BC(e){return t=e,"undefined"!=typeof Document&&t instanceof Document?(new XMLSerializer).serializeToString(document).length:"string"==typeof e?zC(e):e instanceof Blob?e.size:e instanceof FormData?function(e){let t=0;for(const[r,n]of e.entries())t+=r.length,n instanceof Blob?t+=n.size:t+=n.length;return t}(e):e instanceof URLSearchParams?zC(e.toString()):void 0!==e.byteLength?e.byteLength:void FC.warn("unknown body type");var t}const jC=new TextEncoder;function zC(e){return jC.encode(e).byteLength}function VC(e){const t=function(){void 0===HC&&(HC=GC);return HC}(),r=e.toUpperCase();return r in t?r:"_OTHER"}const GC={CONNECT:!0,DELETE:!0,GET:!0,HEAD:!0,OPTIONS:!0,PATCH:!0,POST:!0,PUT:!0,TRACE:!0};let HC;const ZC={"https:":"443","http:":"80"};const $C="0.203.0";var WC;!function(e){e.HTTP_STATUS_TEXT="http.status_text"}(WC||(WC={}));class YC extends F_{component="xml-http-request";version=$C;moduleName=this.component;_tasksCount=0;_xhrMem=new WeakMap;_usedResources=new WeakSet;_semconvStability;constructor(e={}){super("@opentelemetry/instrumentation-xml-http-request",$C,e),this._semconvStability=G_("http",e?.semconvStabilityOptIn)}init(){}_addHeaders(e,t){if(!DC(LC(t).href,this.getConfig().propagateTraceHeaderCorsUrls)){const e={};return bv.inject(ov.active(),e),void(Object.keys(e).length>0&&this._diag.debug("headers inject skipped due to CORS policy"))}const r={};bv.inject(ov.active(),r),Object.keys(r).forEach(t=>{e.setRequestHeader(t,String(r[t]))})}_addChildSpan(e,t){ov.with(Cv.setSpan(ov.active(),e),()=>{const e=this.tracer.startSpan("CORS Preflight",{startTime:t[AC.FETCH_START]}),r=!(this._semconvStability&z_.OLD);MC(e,t,this.getConfig().ignoreNetworkEvents,void 0,r),e.end(t[AC.RESPONSE_END])})}_addFinalSpanAttributes(e,t,r){if(this._semconvStability&z_.OLD){if(void 0!==t.status&&e.setAttribute("http.status_code",t.status),void 0!==t.statusText&&e.setAttribute(WC.HTTP_STATUS_TEXT,t.statusText),"string"==typeof r){const t=LC(r);e.setAttribute("http.host",t.host),e.setAttribute("http.scheme",t.protocol.replace(":",""))}e.setAttribute("http.user_agent",navigator.userAgent)}this._semconvStability&z_.STABLE&&t.status&&e.setAttribute(zv,t.status)}_applyAttributesAfterXHR(e,t){const r=this.getConfig().applyCustomAttributesOnSpan;"function"==typeof r&&B_(()=>r(e,t),e=>{e&&this._diag.error("applyCustomAttributesOnSpan",e)})}_addResourceObserver(e,t){const r=this._xhrMem.get(e);r&&"function"==typeof PerformanceObserver&&"function"==typeof PerformanceResourceTiming&&(r.createdResources={observer:new PerformanceObserver(e=>{const n=e.getEntries(),s=LC(t);n.forEach(e=>{"xmlhttprequest"===e.initiatorType&&e.name===s.href&&r.createdResources&&r.createdResources.entries.push(e)})}),entries:[]},r.createdResources.observer.observe({entryTypes:["resource"]}))}_clearResources(){0===this._tasksCount&&this.getConfig().clearTimingResources&&(uC.clearResourceTimings(),this._xhrMem=new WeakMap,this._usedResources=new WeakSet)}_findResourceAndAddNetworkEvents(e,t,r,n,s){if(!(r&&n&&s&&e.createdResources))return;let i=e.createdResources.entries;i&&i.length||(i=uC.getEntriesByType("resource"));const o=PC(LC(r).href,n,s,i,this._usedResources);if(o.mainRequest){const e=o.mainRequest;this._markResourceAsUsed(e);const r=o.corsPreFlightRequest;r&&(this._addChildSpan(t,r),this._markResourceAsUsed(r));const n=!(this._semconvStability&z_.OLD);MC(t,e,this.getConfig().ignoreNetworkEvents,void 0,n)}}_cleanPreviousSpanInformation(e){const t=this._xhrMem.get(e);if(t){const r=t.callbackToRemoveEvents;r&&r(),this._xhrMem.delete(e)}}_createSpan(e,t,r){if(CC(t,this.getConfig().ignoreUrls))return void this._diag.debug("ignoring span as url matches ignored url");let n="";const s=LC(t),i={};if(this._semconvStability&z_.OLD&&(n=r.toUpperCase(),i["http.method"]=r,i["http.url"]=s.toString()),this._semconvStability&z_.STABLE){const e=r,t=VC(r);n||(n=t),i[Bv]=t,t!==e&&(i[jv]=e),i[Xv]=s.toString(),i[Vv]=s.hostname;const o=function(e){const t=Number(e.port||ZC[e.protocol]);return t&&!isNaN(t)?t:void 0}(s);o&&(i[Gv]=o)}const o=this.tracer.startSpan(n,{kind:sv.CLIENT,attributes:i});return o.addEvent(UC.METHOD_OPEN),this._cleanPreviousSpanInformation(e),this._xhrMem.set(e,{span:o,spanUrl:t}),o}_markResourceAsUsed(e){this._usedResources.add(e)}_patchOpen(){return e=>{const t=this;return function(...r){const n=r[0],s=r[1];return t._createSpan(this,s,n),e.apply(this,r)}}}_patchSend(){const e=this;function t(t,r,n,s){const i=e._xhrMem.get(r);if(!i)return;if(i.status=r.status,i.statusText=r.statusText,e._xhrMem.delete(r),i.span){const t=i.span;e._applyAttributesAfterXHR(t,r),e._semconvStability&z_.STABLE&&(n?s&&(t.setStatus({code:iv.ERROR,message:s}),t.setAttribute(Dv,s)):i.status&&i.status>=400&&(t.setStatus({code:iv.ERROR}),t.setAttribute(Dv,String(i.status))))}const o=yC(),a=Date.now();setTimeout(()=>{!function(t,r,n,s){const i=r.callbackToRemoveEvents;"function"==typeof i&&i();const{span:o,spanUrl:a,sendStartTime:l}=r;o&&(e._findResourceAndAddNetworkEvents(r,o,a,l,n),o.addEvent(t,s),e._addFinalSpanAttributes(o,r,a),o.end(s),e._tasksCount--),e._clearResources()}(t,i,o,a)},300)}function r(){t(UC.EVENT_ERROR,this,!0,"error")}function n(){t(UC.EVENT_ABORT,this,!1)}function s(){t(UC.EVENT_TIMEOUT,this,!0,"timeout")}function i(){this.status<299?t(UC.EVENT_LOAD,this,!1):t(UC.EVENT_ERROR,this,!1)}return t=>function(...o){const a=e._xhrMem.get(this);if(!a)return t.apply(this,o);const l=a.span,c=a.spanUrl;if(l&&c){if(e.getConfig().measureRequestSize&&o?.[0]){const t=BC(o[0]);void 0!==t&&(e._semconvStability&z_.OLD&&l.setAttribute("http.request_content_length_uncompressed",t),e._semconvStability&z_.STABLE&&l.setAttribute("http.request.body.size",t))}ov.with(Cv.setSpan(ov.active(),l),()=>{e._tasksCount++,a.sendStartTime=yC(),l.addEvent(UC.METHOD_SEND),this.addEventListener("abort",n),this.addEventListener("error",r),this.addEventListener("load",i),this.addEventListener("timeout",s),a.callbackToRemoveEvents=()=>{!function(t){t.removeEventListener("abort",n),t.removeEventListener("error",r),t.removeEventListener("load",i),t.removeEventListener("timeout",s);const o=e._xhrMem.get(t);o&&(o.callbackToRemoveEvents=void 0)}(this),a.createdResources&&a.createdResources.observer.disconnect()},e._addHeaders(this,c),e._addResourceObserver(this,c)})}return t.apply(this,o)}}enable(){this._diag.debug("applying patch to",this.moduleName,this.version),j_(XMLHttpRequest.prototype.open)&&(this._unwrap(XMLHttpRequest.prototype,"open"),this._diag.debug("removing previous patch from method open")),j_(XMLHttpRequest.prototype.send)&&(this._unwrap(XMLHttpRequest.prototype,"send"),this._diag.debug("removing previous patch from method send")),this._wrap(XMLHttpRequest.prototype,"open",this._patchOpen()),this._wrap(XMLHttpRequest.prototype,"send",this._patchSend())}disable(){this._diag.debug("removing patch from",this.moduleName,this.version),this._unwrap(XMLHttpRequest.prototype,"open"),this._unwrap(XMLHttpRequest.prototype,"send"),this._tasksCount=0,this._xhrMem=new WeakMap,this._usedResources=new WeakSet}}var XC;!function(e){e.COMPONENT="component",e.HTTP_STATUS_TEXT="http.status_text"}(XC||(XC={}));var JC={};Object.defineProperty(JC,"__esModule",{value:!0});var KC=JC.ATTR_HTTP_USER_AGENT=JC.ATTR_HTTP_URL=JC.ATTR_HTTP_STATUS_CODE=JC.ATTR_HTTP_SCHEME=JC.ATTR_HTTP_RESPONSE_CONTENT_LENGTH=JC.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=JC.ATTR_HTTP_REQUEST_BODY_SIZE=JC.ATTR_HTTP_METHOD=JC.ATTR_HTTP_HOST=void 0,qC=JC.ATTR_HTTP_HOST="http.host",QC=JC.ATTR_HTTP_METHOD="http.method",eE=JC.ATTR_HTTP_REQUEST_BODY_SIZE="http.request.body.size",tE=JC.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED="http.request_content_length_uncompressed";JC.ATTR_HTTP_RESPONSE_CONTENT_LENGTH="http.response_content_length";var rE=JC.ATTR_HTTP_SCHEME="http.scheme",nE=JC.ATTR_HTTP_STATUS_CODE="http.status_code",sE=JC.ATTR_HTTP_URL="http.url";KC=JC.ATTR_HTTP_USER_AGENT="http.user_agent";const iE=av.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-fetch/utils"});function oE(...e){if(e[0]instanceof URL||"string"==typeof e[0]){const t=e[1];if(!t?.body)return Promise.resolve();if(t.body instanceof ReadableStream){const{body:e,length:r}=function(e){if(!e.pipeThrough)return iE.warn("Platform has ReadableStream but not pipeThrough!"),{body:e,length:Promise.resolve(void 0)};let t,r=0;const n=new Promise(e=>{t=e}),s=new TransformStream({start(){},async transform(e,t){const n=await e;r+=n.byteLength,t.enqueue(e)},flush(){t(r)}});return{body:e.pipeThrough(s),length:n}}(t.body);return t.body=e,r}return Promise.resolve(function(e){if(t=e,"undefined"!=typeof Document&&t instanceof Document)return(new XMLSerializer).serializeToString(document).length;var t;if("string"==typeof e)return lE(e);if(e instanceof Blob)return e.size;if(e instanceof FormData)return function(e){let t=0;for(const[r,n]of e.entries())t+=r.length,n instanceof Blob?t+=n.size:t+=n.length;return t}(e);if(e instanceof URLSearchParams)return lE(e.toString());if(void 0!==e.byteLength)return e.byteLength;return void iE.warn("unknown body type")}(t.body))}{const t=e[0];return t?.body?t.clone().text().then(e=>lE(e)):Promise.resolve()}}const aE=new TextEncoder;function lE(e){return aE.encode(e).byteLength}const cE={CONNECT:!0,DELETE:!0,GET:!0,HEAD:!0,OPTIONS:!0,PATCH:!0,POST:!0,PUT:!0,TRACE:!0};let uE;function hE(){return void 0===uE&&(uE=cE),uE}const pE={"https:":"443","http:":"80"};const dE="0.203.0",fE="object"==typeof process&&"node"===process.release?.name;class mE extends F_{component="fetch";version=dE;moduleName=this.component;_usedResources=new WeakSet;_tasksCount=0;_semconvStability;constructor(e={}){super("@opentelemetry/instrumentation-fetch",dE,e),this._semconvStability=G_("http",e?.semconvStabilityOptIn)}init(){}_addChildSpan(e,t){const r=this.tracer.startSpan("CORS Preflight",{startTime:t[AC.FETCH_START]},Cv.setSpan(ov.active(),e)),n=!(this._semconvStability&z_.OLD);MC(r,t,this.getConfig().ignoreNetworkEvents,void 0,n),r.end(t[AC.RESPONSE_END])}_addFinalSpanAttributes(e,t){const r=LC(t.url);if(this._semconvStability&z_.OLD&&(e.setAttribute(nE,t.status),null!=t.statusText&&e.setAttribute(XC.HTTP_STATUS_TEXT,t.statusText),e.setAttribute(qC,r.host),e.setAttribute(rE,r.protocol.replace(":","")),"undefined"!=typeof navigator&&e.setAttribute(KC,navigator.userAgent)),this._semconvStability&z_.STABLE){e.setAttribute(zv,t.status),e.setAttribute(Vv,r.hostname);const n=function(e){const t=Number(e.port||pE[e.protocol]);return t&&!isNaN(t)?t:void 0}(r);n&&e.setAttribute(Gv,n)}}_addHeaders(e,t){if(!DC(t,this.getConfig().propagateTraceHeaderCorsUrls)){const e={};return bv.inject(ov.active(),e),void(Object.keys(e).length>0&&this._diag.debug("headers inject skipped due to CORS policy"))}if(e instanceof Request)bv.inject(ov.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else if(e.headers instanceof Headers)bv.inject(ov.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else if(e.headers instanceof Map)bv.inject(ov.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else{const t={};bv.inject(ov.active(),t),e.headers=Object.assign({},t,e.headers||{})}}_clearResources(){0===this._tasksCount&&this.getConfig().clearTimingResources&&(performance.clearResourceTimings(),this._usedResources=new WeakSet)}_createSpan(e,t={}){if(CC(e,this.getConfig().ignoreUrls))return void this._diag.debug("ignoring span as url matches ignored url");let r="";const n={};if(this._semconvStability&z_.OLD){const s=(t.method||"GET").toUpperCase();r=`HTTP ${s}`,n[XC.COMPONENT]=this.moduleName,n[QC]=s,n[sE]=e}if(this._semconvStability&z_.STABLE){const s=t.method,i=function(e){const t=hE(),r=e.toUpperCase();return r in t?r:"_OTHER"}(t.method||"GET");r||(r=i),n[Bv]=i,i!==s&&(n[jv]=s),n[Xv]=e}return this.tracer.startSpan(r,{kind:sv.CLIENT,attributes:n})}_findResourceAndAddNetworkEvents(e,t,r){let n=t.entries;if(!n.length){if(!performance.getEntriesByType)return;n=performance.getEntriesByType("resource")}const s=PC(t.spanUrl,t.startTime,r,n,this._usedResources,"fetch");if(s.mainRequest){const t=s.mainRequest;this._markResourceAsUsed(t);const r=s.corsPreFlightRequest;r&&(this._addChildSpan(e,r),this._markResourceAsUsed(r));const n=!(this._semconvStability&z_.OLD);MC(e,t,this.getConfig().ignoreNetworkEvents,void 0,n)}}_markResourceAsUsed(e){this._usedResources.add(e)}_endSpan(e,t,r){const n=mC(Date.now()),s=yC();this._addFinalSpanAttributes(e,r),this._semconvStability&z_.STABLE&&r.status>=400&&(e.setStatus({code:iv.ERROR}),e.setAttribute(Dv,String(r.status))),setTimeout(()=>{t.observer?.disconnect(),this._findResourceAndAddNetworkEvents(e,t,s),this._tasksCount--,this._clearResources(),e.end(n)},300)}_patchConstructor(){return e=>{const t=this;return function(...r){const n=this,s=LC(r[0]instanceof Request?r[0].url:String(r[0])).href,i=r[0]instanceof Request?r[0]:r[1]||{},o=t._createSpan(s,i);if(!o)return e.apply(this,r);const a=t._prepareSpanData(s);function l(e,r){t._applyAttributesAfterFetch(e,i,r),t._endSpan(e,a,{status:r.status||0,statusText:r.message,url:s})}function c(e,r){t._applyAttributesAfterFetch(e,i,r),r.status>=200&&r.status<400?t._endSpan(e,a,r):t._endSpan(e,a,{status:r.status,statusText:r.statusText,url:s})}function u(e,t,r){try{const t=r.clone().body;if(t){const n=t.getReader(),s=()=>{n.read().then(({done:t})=>{t?c(e,r):s()},t=>{l(e,t)})};s()}else c(e,r)}finally{t(r)}}function h(e,t,r){try{l(e,r)}finally{t(r)}}return t.getConfig().measureRequestSize&&oE(...r).then(e=>{e&&(t._semconvStability&z_.OLD&&o.setAttribute(tE,e),t._semconvStability&z_.STABLE&&o.setAttribute(eE,e))}).catch(e=>{t._diag.warn("getFetchBodyLength",e)}),new Promise((r,a)=>ov.with(Cv.setSpan(ov.active(),o),()=>(t._addHeaders(i,s),t._callRequestHook(o,i),t._tasksCount++,e.apply(n,i instanceof Request?[i]:[s,i]).then(u.bind(n,o,r),h.bind(n,o,a)))))}}}_applyAttributesAfterFetch(e,t,r){const n=this.getConfig().applyCustomAttributesOnSpan;n&&B_(()=>n(e,t,r),e=>{e&&this._diag.error("applyCustomAttributesOnSpan",e)})}_callRequestHook(e,t){const r=this.getConfig().requestHook;r&&B_(()=>r(e,t),e=>{e&&this._diag.error("requestHook",e)})}_prepareSpanData(e){const t=yC(),r=[];if("function"!=typeof PerformanceObserver)return{entries:r,startTime:t,spanUrl:e};const n=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{"fetch"===t.initiatorType&&t.name===e&&r.push(t)})});return n.observe({entryTypes:["resource"]}),{entries:r,observer:n,startTime:t,spanUrl:e}}enable(){fE?this._diag.warn("this instrumentation is intended for web usage only, it does not instrument Node.js's fetch()"):(j_(fetch)&&(this._unwrap(cC,"fetch"),this._diag.debug("removing previous patch for constructor")),this._wrap(cC,"fetch",this._patchConstructor()))}disable(){fE||(this._unwrap(cC,"fetch"),this._usedResources=new WeakSet)}}class gE{emit(e){}}const yE=new gE,wE=Symbol.for("io.opentelemetry.js.api.logs"),vE=globalThis;const bE=new class{getLogger(e,t,r){return new gE}};class _E{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider._getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):yE}}class SE{getLogger(e,t,r){var n;return null!==(n=this._getDelegateLogger(e,t,r))&&void 0!==n?n:new _E(this,e,t,r)}_getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:bE}_setDelegate(e){this._delegate=e}_getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}}class CE{constructor(){this._proxyLoggerProvider=new SE}static getInstance(){return this._instance||(this._instance=new CE),this._instance}setGlobalLoggerProvider(e){return vE[wE]?this.getLoggerProvider():(vE[wE]=(t=1,r=e,n=bE,e=>e===t?r:n),this._proxyLoggerProvider._setDelegate(e),e);var t,r,n}getLoggerProvider(){var e,t;return null!==(t=null===(e=vE[wE])||void 0===e?void 0:e.call(vE,1))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete vE[wE],this._proxyLoggerProvider=new SE}}const EE=CE.getInstance();let TE=console.error.bind(console);function kE(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const xE=(e,t,r)=>{if(!e||!e[t])return void TE("no original function "+String(t)+" to wrap");if(!r)return TE("no wrapper function"),void TE((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void TE("original object and wrapper must be functions");const s=r(n,t);return kE(s,"__original",n),kE(s,"__unwrap",()=>{e[t]===s&&kE(e,t,n)}),kE(s,"__wrapped",!0),kE(e,t,s),s},OE=(e,t,r)=>{if(!e)return TE("must provide one or more modules to patch"),void TE((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{xE(e,t,r)})}):TE("must provide one or more functions to wrap on modules")},AE=(e,t)=>{if(!e||!e[t])return TE("no function to unwrap."),void TE((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():TE("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},IE=(e,t)=>{if(!e)return TE("must provide one or more modules to patch"),void TE((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{AE(e,t)})}):TE("must provide one or more functions to unwrap on modules")};class RE{_config={};_tracer;_meter;_logger;_diag;instrumentationName;instrumentationVersion;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=av.createComponentLogger({namespace:e}),this._tracer=Cv.getTracer(e,t),this._meter=hv.getMeter(e,t),this._logger=EE.getLogger(e,t),this._updateMetricInstruments()}_wrap=xE;_unwrap=AE;_massWrap=OE;_massUnwrap=IE;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}}class ME extends RE{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}}function NE(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var PE;!function(e){e.EVENT_TYPE="event_type",e.TARGET_ELEMENT="target_element",e.TARGET_XPATH="target_xpath",e.HTTP_URL="http.url"}(PE||(PE={}));const LE="0.58.0",DE=["click"];function UE(){return!1}class FE extends ME{version=LE;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(e={}){super("@opentelemetry/instrumentation-user-interaction",LE,e),this._eventNames=new Set(e?.eventNames??DE),this._shouldPreventSpanCreation="function"==typeof e?.shouldPreventSpanCreation?e.shouldPreventSpanCreation:UE}init(){}_checkForTimeout(e,t){const r=this._spansData.get(t);r&&("setTimeout"===e.source?r.hrTimeLastTimeout=rb():"Promise.then"!==e.source&&"setTimeout"!==e.source&&(r.hrTimeLastTimeout=void 0))}_allowEventName(e){return this._eventNames.has(e)}_createSpan(e,t,r){if(!(e instanceof HTMLElement))return;if(!e.getAttribute)return;if(e.hasAttribute("disabled"))return;if(!this._allowEventName(t))return;const n=__(e);try{const s=this.tracer.startSpan(t,{attributes:{[PE.EVENT_TYPE]:t,[PE.TARGET_ELEMENT]:e.tagName,[PE.TARGET_XPATH]:n,[PE.HTTP_URL]:window.location.href}},r?Cv.setSpan(ov.active(),r):void 0);if(!0===this._shouldPreventSpanCreation(t,e,s))return;return this._spansData.set(s,{taskCount:0}),s}catch(e){this._diag.error("failed to start create new user interaction span",e)}}_decrementTask(e){const t=this._spansData.get(e);t&&(t.taskCount--,0===t.taskCount&&this._tryToEndSpan(e,t.hrTimeLastTimeout))}_getCurrentSpan(e){const t=e.get("OT_ZONE_CONTEXT");return t?Cv.getSpan(t):t}_incrementTask(e){const t=this._spansData.get(e);t&&t.taskCount++}addPatchedListener(e,t,r,n){let s=this._wrappedListeners.get(r);s||(s=new Map,this._wrappedListeners.set(r,s));let i=s.get(t);return i||(i=new Map,s.set(t,i)),!i.has(e)&&(i.set(e,n),!0)}removePatchedListener(e,t,r){const n=this._wrappedListeners.get(r);if(!n)return;const s=n.get(t);if(!s)return;const i=s.get(e);return i&&(s.delete(e),0===s.size&&(n.delete(t),0===n.size&&this._wrappedListeners.delete(r))),i}_invokeListener(e,t,r){return"function"==typeof e?e.apply(t,r):e.handleEvent(r[0])}_patchAddEventListener(){const e=this;return t=>function(r,n,s){if(!n)return t.call(this,r,n,s);const i=s&&"object"==typeof s&&s.once,o=function(...t){let s;const o=t[0],a=o?.target;o&&(s=e._eventsSpanMap.get(o)),i&&e.removePatchedListener(this,r,n);const l=e._createSpan(a,r,s);return l?(o&&e._eventsSpanMap.set(o,l),ov.with(Cv.setSpan(ov.active(),l),()=>{const r=e._invokeListener(n,this,t);return l.end(),r})):e._invokeListener(n,this,t)};return e.addPatchedListener(this,r,n,o)?t.call(this,r,o,s):void 0}}_patchRemoveEventListener(){const e=this;return t=>function(r,n,s){const i=e.removePatchedListener(this,r,n);return i?t.call(this,r,i,s):t.call(this,r,n,s)}}_getPatchableEventTargets(){return window.EventTarget?[EventTarget.prototype]:[Node.prototype,Window.prototype]}_patchHistoryApi(){this._unpatchHistoryApi(),this._wrap(history,"replaceState",this._patchHistoryMethod()),this._wrap(history,"pushState",this._patchHistoryMethod()),this._wrap(history,"back",this._patchHistoryMethod()),this._wrap(history,"forward",this._patchHistoryMethod()),this._wrap(history,"go",this._patchHistoryMethod())}_patchHistoryMethod(){const e=this;return t=>function(...r){const n=`${location.pathname}${location.hash}${location.search}`,s=t.apply(this,r),i=`${location.pathname}${location.hash}${location.search}`;return n!==i&&e._updateInteractionName(i),s}}_unpatchHistoryApi(){NE(history.replaceState)&&this._unwrap(history,"replaceState"),NE(history.pushState)&&this._unwrap(history,"pushState"),NE(history.back)&&this._unwrap(history,"back"),NE(history.forward)&&this._unwrap(history,"forward"),NE(history.go)&&this._unwrap(history,"go")}_updateInteractionName(e){const t=Cv.getSpan(ov.active());t&&"function"==typeof t.updateName&&t.updateName(`Navigation: ${e}`)}_patchZoneCancelTask(){const e=this;return t=>function(r){const n=Zone.current,s=e._getCurrentSpan(n);return s&&e._shouldCountTask(r,n)&&e._decrementTask(s),t.call(this,r)}}_patchZoneScheduleTask(){const e=this;return t=>function(r){const n=Zone.current,s=e._getCurrentSpan(n);return s&&e._shouldCountTask(r,n)&&(e._incrementTask(s),e._checkForTimeout(r,s)),t.call(this,r)}}_patchZoneRunTask(){const e=this;return t=>function(r,n,s){const i=Array.isArray(s)&&s[0]instanceof Event?s[0]:void 0,o=i?.target;let a;const l=this;if(o){if(a=e._createSpan(o,r.eventName),a)return e._incrementTask(a),l.run(()=>{try{return ov.with(Cv.setSpan(ov.active(),a),()=>{const e=Zone.current;return r._zone=e,t.call(e,r,n,s)})}finally{e._decrementTask(a)}})}else a=e._getCurrentSpan(l);try{return t.call(l,r,n,s)}finally{a&&e._shouldCountTask(r,l)&&e._decrementTask(a)}}}_shouldCountTask(e,t){if(e._zone&&(t=e._zone),!t||!e.data||e.data.isPeriodic)return!1;const r=this._getCurrentSpan(t);return!!r&&(!!this._spansData.get(r)&&("macroTask"===e.type||"microTask"===e.type))}_tryToEndSpan(e,t){if(e){this._spansData.get(e)&&(e.end(t),this._spansData.delete(e))}}enable(){const e=this._getZoneWithPrototype();if(this._diag.debug("applying patch to",this.moduleName,this.version,"zone:",!!e),e)NE(e.prototype.runTask)&&(this._unwrap(e.prototype,"runTask"),this._diag.debug("removing previous patch from method runTask")),NE(e.prototype.scheduleTask)&&(this._unwrap(e.prototype,"scheduleTask"),this._diag.debug("removing previous patch from method scheduleTask")),NE(e.prototype.cancelTask)&&(this._unwrap(e.prototype,"cancelTask"),this._diag.debug("removing previous patch from method cancelTask")),this._zonePatched=!0,this._wrap(e.prototype,"runTask",this._patchZoneRunTask()),this._wrap(e.prototype,"scheduleTask",this._patchZoneScheduleTask()),this._wrap(e.prototype,"cancelTask",this._patchZoneCancelTask());else{this._zonePatched=!1;this._getPatchableEventTargets().forEach(e=>{NE(e.addEventListener)&&(this._unwrap(e,"addEventListener"),this._diag.debug("removing previous patch from method addEventListener")),NE(e.removeEventListener)&&(this._unwrap(e,"removeEventListener"),this._diag.debug("removing previous patch from method removeEventListener")),this._wrap(e,"addEventListener",this._patchAddEventListener()),this._wrap(e,"removeEventListener",this._patchRemoveEventListener())})}this._patchHistoryApi()}disable(){const e=this._getZoneWithPrototype();if(this._diag.debug("removing patch from",this.moduleName,this.version,"zone:",!!e),e&&this._zonePatched)NE(e.prototype.runTask)&&this._unwrap(e.prototype,"runTask"),NE(e.prototype.scheduleTask)&&this._unwrap(e.prototype,"scheduleTask"),NE(e.prototype.cancelTask)&&this._unwrap(e.prototype,"cancelTask");else{this._getPatchableEventTargets().forEach(e=>{NE(e.addEventListener)&&this._unwrap(e,"addEventListener"),NE(e.removeEventListener)&&this._unwrap(e,"removeEventListener")})}this._unpatchHistoryApi()}_getZoneWithPrototype(){return window.Zone}}class BE{_delegate;constructor(e){this._delegate=e}export(e,t){this._delegate.export(e,t)}forceFlush(){return this._delegate.forceFlush()}shutdown(){return this._delegate.shutdown()}}class jE extends Error{code;name="OTLPExporterError";data;constructor(e,t,r){super(e),this.data=r,this.code=t}}function zE(e){if(Number.isFinite(e)&&e>0)return e;throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${e}')`)}function VE(e){if(null!=e)return()=>e}function GE(e,t,r){return{timeoutMillis:zE(e.timeoutMillis??t.timeoutMillis??r.timeoutMillis),concurrencyLimit:e.concurrencyLimit??t.concurrencyLimit??r.concurrencyLimit,compression:e.compression??t.compression??r.compression}}class HE{_concurrencyLimit;_sendingPromises=[];constructor(e){this._concurrencyLimit=e}pushPromise(e){if(this.hasReachedLimit())throw new Error("Concurrency Limit reached");this._sendingPromises.push(e);const t=()=>{const t=this._sendingPromises.indexOf(e);this._sendingPromises.splice(t,1)};e.then(t,t)}hasReachedLimit(){return this._sendingPromises.length>=this._concurrencyLimit}async awaitAll(){await Promise.all(this._sendingPromises)}}function ZE(e){return new HE(e.concurrencyLimit)}function $E(){return{handleResponse(e){null!=e&&function(e){return Object.prototype.hasOwnProperty.call(e,"partialSuccess")}(e)&&null!=e.partialSuccess&&0!==Object.keys(e.partialSuccess).length&&av.warn("Received Partial Success response:",JSON.stringify(e.partialSuccess))}}}class WE{_transport;_serializer;_responseHandler;_promiseQueue;_timeout;_diagLogger;constructor(e,t,r,n,s){this._transport=e,this._serializer=t,this._responseHandler=r,this._promiseQueue=n,this._timeout=s,this._diagLogger=av.createComponentLogger({namespace:"OTLPExportDelegate"})}export(e,t){if(this._diagLogger.debug("items to be sent",e),this._promiseQueue.hasReachedLimit())return void t({code:_C.FAILED,error:new Error("Concurrent export limit reached")});const r=this._serializer.serializeRequest(e);null!=r?this._promiseQueue.pushPromise(this._transport.send(r,this._timeout).then(e=>{if("success"!==e.status)"failure"===e.status&&e.error?t({code:_C.FAILED,error:e.error}):"retryable"===e.status?t({code:_C.FAILED,error:new jE("Export failed with retryable status")}):t({code:_C.FAILED,error:new jE("Export failed with unknown error")});else{if(null!=e.data)try{this._responseHandler.handleResponse(this._serializer.deserializeResponse(e.data))}catch(t){this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?",t,e.data)}t({code:_C.SUCCESS})}},e=>t({code:_C.FAILED,error:e}))):t({code:_C.FAILED,error:new Error("Nothing to send")})}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started"),await this.forceFlush(),this._transport.shutdown()}}function YE(e,t,r){return n={transport:r,serializer:t,promiseHandler:ZE(e)},s={timeout:e.timeoutMillis},new WE(n.transport,n.serializer,$E(),n.promiseHandler,s.timeout);var n,s}function XE(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-87:e-55}function JE(e){const t=new Uint8Array(e.length/2);let r=0;for(let n=0;n>BigInt(32)))};var r}const QE="undefined"!=typeof BigInt?function(e){return KE(e).toString()}:vC;function eT(e){return e}function tT(e){if(void 0!==e)return JE(e)}const rT={encodeHrTime:qE,encodeSpanContext:JE,encodeOptionalSpanContext:tT};function nT(e){if(void 0===e)return rT;const t=e.useLongBits??!0,r=e.useHex??!1;return{encodeHrTime:t?qE:QE,encodeSpanContext:r?eT:JE,encodeOptionalSpanContext:r?eT:tT}}function sT(e){return{attributes:oT(e.attributes),droppedAttributesCount:0}}function iT(e){return{name:e.name,version:e.version}}function oT(e){return Object.keys(e).map(t=>aT(t,e[t]))}function aT(e,t){return{key:e,value:lT(t)}}function lT(e){const t=typeof e;return"string"===t?{stringValue:e}:"number"===t?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:"boolean"===t?{boolValue:e}:e instanceof Uint8Array?{bytesValue:e}:Array.isArray(e)?{arrayValue:{values:e.map(lT)}}:"object"===t&&null!=e?{kvlistValue:{values:Object.entries(e).map(([e,t])=>aT(e,t))}}:{}}var cT,uT,hT,pT;function dT(e){return null!=e}function fT(e){let t=Object.keys(e);return 0===t.length?"":(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(cT||(cT={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(uT||(uT={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(hT||(hT={}));class mT extends Error{constructor(e){super(e),Object.setPrototypeOf(this,mT.prototype)}}function gT(e,t){let r;const n=new Promise(function(e,n){r=setTimeout(function(){n(new mT("Operation timed out."))},t)});return Promise.race([e,n]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}function yT(e){return"rejected"===e.status}function wT(e,t){const r=[];return e.forEach(e=>{r.push(...t(e))}),r}!function(e){e[e.DROP=0]="DROP",e[e.SUM=1]="SUM",e[e.LAST_VALUE=2]="LAST_VALUE",e[e.HISTOGRAM=3]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"}(pT||(pT={}));class vT{kind=pT.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,r,n){}}class bT{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,r=!0,n=function(e){const t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=r,this._current=n}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);const t=function(e,t){let r=0,n=e.length-1,s=e.length;for(;n>=r;){const i=r+Math.trunc((n-r)/2);e[i]{const s=r.toPointValue(),i=e.type===uT.GAUGE||e.type===uT.UP_DOWN_COUNTER||e.type===uT.OBSERVABLE_GAUGE||e.type===uT.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:i?void 0:s.sum,buckets:s.buckets,count:s.count}}})}}}class ST{backing;indexBase;indexStart;indexEnd;constructor(e=new CT,t=0,r=0,n=0){this.backing=e,this.indexBase=t,this.indexStart=r,this.indexEnd=n}get offset(){return this.indexStart}get length(){return 0===this.backing.length||this.indexEnd===this.indexStart&&0===this.at(0)?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){const t=this.indexBase-this.indexStart;return e=0;e--)if(0!==this.at(e)){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();const t=1+this.indexEnd-this.indexStart,r=1<>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new ST(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){const e=this.indexBase-this.indexStart;0!==e&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}}class CT{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,r){const n=new Array(e).fill(0);n.splice(r,this._counts.length-t,...this._counts.slice(t)),n.splice(0,t,...this._counts.slice(0,t)),this._counts=n}reverse(e,t){const r=Math.floor((e+t)/2)-e;for(let n=0;n=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new CT([...this._counts])}}const ET=1023,TT=ET,kT=Math.pow(2,-1022);function xT(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);return((2146435072&t.getUint32(0))>>20)-ET}function OT(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);const r=t.getUint32(0),n=t.getUint32(4);return(1048575&r)*Math.pow(2,32)+n}function AT(e,t){return 0===e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY||Number.isNaN(e)?e:e*Math.pow(2,t)}class IT extends Error{}class RT{_shift;constructor(e){this._shift=-e}mapToIndex(e){if(e>this._shift}lowerBoundary(e){const t=this._minNormalLowerBoundaryIndex();if(er)throw new IT(`overflow: ${e} is > maximum lower boundary: ${r}`);return AT(1,e<>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return TT>>this._shift}_rightShift(e,t){return Math.floor(e*Math.pow(2,-t))}}class MT{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=AT(Math.LOG2E,e),this._inverseFactor=AT(Math.LN2,-e)}mapToIndex(e){if(e<=kT)return this._minNormalLowerBoundaryIndex()-1;if(0===OT(e)){return(xT(e)<=r?r:t}lowerBoundary(e){const t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1< maximum lower boundary: ${t}`)}const r=this._minNormalLowerBoundaryIndex();if(e<=r){if(e===r)return kT;if(e===r-1)return Math.exp((e+(1<t>10?new MT(t-10):new RT(t-10));function PT(e){if(e>20||e<-10)throw new IT(`expected scale >= -10 && <= 20, got: ${e}`);return NT[e+10]}class LT{low;high;static combine(e,t){return new LT(Math.min(e.low,t.low),Math.max(e.high,t.high))}constructor(e,t){this.low=e,this.high=t}}class DT{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e=e,t=160,r=!0,n=0,s=0,i=0,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,l=new ST,c=new ST,u=PT(20)){this.startTime=e,this._maxSize=t,this._recordMinMax=r,this._sum=n,this._count=s,this._zeroCount=i,this._min=o,this._max=a,this._positive=l,this._negative=c,this._mapping=u,this._maxSize<2&&(av.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: 2`),this._maxSize=2)}record(e){this.updateByIncrement(e,1)}setStartTime(e){this.startTime=e}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){return this._count===this._zeroCount?0:this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(e,t){Number.isNaN(e)||(e>this._max&&(this._max=e),e0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)):this._zeroCount+=t)}merge(e){0===this._count?(this._min=e.min,this._max=e.max):0!==e.count&&(e.minthis.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new DT(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,r){let n=this._mapping.mapToIndex(t),s=!1,i=0,o=0;if(0===e.length?(e.indexStart=n,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):n=this._maxSize?(s=!0,o=n,i=e.indexEnd):n>e.indexEnd&&n-e.indexStart>=this._maxSize&&(s=!0,o=e.indexStart,i=n),s){const e=this._changeScale(i,o);this._downscale(e),n=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,n,r)}_incrementIndexBy(e,t,r){if(0===r)return;if(0===e.length&&(e.indexStart=e.indexEnd=e.indexBase=t),t=e.backing.length&&this._grow(e,r+1),e.indexStart=t}else if(t>e.indexEnd){const r=t-e.indexStart;r>=e.backing.length&&this._grow(e,r+1),e.indexEnd=t}let n=t-e.indexBase;n<0&&(n+=e.backing.length),e.incrementBucket(n,r)}_grow(e,t){const r=e.backing.length,n=e.indexBase-e.indexStart,s=r-n;let i=function(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}(t);i>this._maxSize&&(i=this._maxSize);const o=i-n;e.backing.growTo(i,s,o)}_changeScale(e,t){let r=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,r++;return r}_downscale(e){if(0===e)return;if(e<0)throw new Error(`impossible change of scale: ${this.scale}`);const t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=PT(t)}_minScale(e){const t=Math.min(this.scale,e.scale),r=LT.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),n=LT.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(r.high,r.low),t-this._changeScale(n.high,n.low))}_highLowAtScale(e,t,r){if(0===e.length)return new LT(0,-1);const n=t-r;return new LT(e.indexStart>>n,e.indexEnd>>n)}_mergeBuckets(e,t,r,n){const s=r.offset,i=t.scale-n;for(let t=0;t>i,r.at(t))}_diffBuckets(e,t,r,n){const s=r.offset,i=t.scale-n;for(let t=0;t>i)-e.indexBase;n<0&&(n+=e.backing.length),e.decrementBucket(n,r.at(t))}e.trim()}}class UT{_maxSize;_recordMinMax;kind=pT.EXPONENTIAL_HISTOGRAM;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new DT(e,this._maxSize,this._recordMinMax)}merge(e,t){const r=t.clone();return r.merge(e),r}diff(e,t){const r=t.clone();return r.diff(e),r}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:hT.EXPONENTIAL_HISTOGRAM,dataPoints:r.map(([t,r])=>{const s=r.toPointValue(),i=e.type===uT.GAUGE||e.type===uT.UP_DOWN_COUNTER||e.type===uT.OBSERVABLE_GAUGE||e.type===uT.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:i?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}}}class FT{startTime;_current;sampleTime;constructor(e,t=0,r=[0,0]){this.startTime=e,this._current=t,this.sampleTime=r}record(e){this._current=e,this.sampleTime=mC(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class BT{kind=pT.LAST_VALUE;createAccumulation(e){return new FT(e)}merge(e,t){const r=bC(t.sampleTime)>=bC(e.sampleTime)?t:e;return new FT(e.startTime,r.toPointValue(),r.sampleTime)}diff(e,t){const r=bC(t.sampleTime)>=bC(e.sampleTime)?t:e;return new FT(t.startTime,r.toPointValue(),r.sampleTime)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:hT.GAUGE,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()}))}}}class jT{startTime;monotonic;_current;reset;constructor(e,t,r=0,n=!1){this.startTime=e,this.monotonic=t,this._current=r,this.reset=n}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class zT{monotonic;kind=pT.SUM;constructor(e){this.monotonic=e}createAccumulation(e){return new jT(e,this.monotonic)}merge(e,t){const r=e.toPointValue(),n=t.toPointValue();return t.reset?new jT(t.startTime,this.monotonic,n,t.reset):new jT(e.startTime,this.monotonic,r+n)}diff(e,t){const r=e.toPointValue(),n=t.toPointValue();return this.monotonic&&r>n?new jT(t.startTime,this.monotonic,n,!0):new jT(t.startTime,this.monotonic,n-r)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:hT.SUM,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()})),isMonotonic:this.monotonic}}}class VT{static DEFAULT_INSTANCE=new vT;createAggregator(e){return VT.DEFAULT_INSTANCE}}class GT{static MONOTONIC_INSTANCE=new zT(!0);static NON_MONOTONIC_INSTANCE=new zT(!1);createAggregator(e){switch(e.type){case uT.COUNTER:case uT.OBSERVABLE_COUNTER:case uT.HISTOGRAM:return GT.MONOTONIC_INSTANCE;default:return GT.NON_MONOTONIC_INSTANCE}}}class HT{static DEFAULT_INSTANCE=new BT;createAggregator(e){return HT.DEFAULT_INSTANCE}}class ZT{static DEFAULT_INSTANCE=new _T([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(e){return ZT.DEFAULT_INSTANCE}}class $T{_recordMinMax;_boundaries;constructor(e,t=!0){if(this._recordMinMax=t,null==e)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");e=(e=e.concat()).sort((e,t)=>e-t);const r=e.lastIndexOf(-1/0);let n=e.indexOf(1/0);-1===n&&(n=void 0),this._boundaries=e.slice(r+1,n)}createAggregator(e){return new _T(this._boundaries,this._recordMinMax)}}class WT{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new UT(this._maxSize,this._recordMinMax)}}const YT=new VT,XT=new GT,JT=new HT,KT=new ZT,qT=new class{_resolve(e){switch(e.type){case uT.COUNTER:case uT.UP_DOWN_COUNTER:case uT.OBSERVABLE_COUNTER:case uT.OBSERVABLE_UP_DOWN_COUNTER:return XT;case uT.GAUGE:case uT.OBSERVABLE_GAUGE:return JT;case uT.HISTOGRAM:return e.advice.explicitBucketBoundaries?new $T(e.advice.explicitBucketBoundaries):KT}return av.warn(`Unable to recognize instrument type: ${e.type}`),YT}createAggregator(e){return this._resolve(e).createAggregator(e)}};var QT;function ek(e){switch(e.type){case QT.DEFAULT:return qT;case QT.DROP:return YT;case QT.SUM:return XT;case QT.LAST_VALUE:return JT;case QT.EXPONENTIAL_HISTOGRAM:{const t=e;return new WT(t.options?.maxSize,t.options?.recordMinMax)}case QT.EXPLICIT_BUCKET_HISTOGRAM:{const t=e;return null==t.options?KT:new $T(t.options?.boundaries,t.options?.recordMinMax)}default:throw new Error("Unsupported Aggregation")}}!function(e){e[e.DEFAULT=0]="DEFAULT",e[e.DROP=1]="DROP",e[e.SUM=2]="SUM",e[e.LAST_VALUE=3]="LAST_VALUE",e[e.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"}(QT||(QT={}));const tk=e=>({type:QT.DEFAULT}),rk=e=>cT.CUMULATIVE;class nk{_shutdown=!1;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(e){this._aggregationSelector=e?.aggregationSelector??tk,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??rk,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector}setMetricProducer(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(void 0===this._sdkMetricProducer)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");const[t,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),n=t.errors.concat(wT(r,e=>e.errors)),s=t.resourceMetrics.resource,i=t.resourceMetrics.scopeMetrics.concat(wT(r,e=>e.resourceMetrics.scopeMetrics));return{resourceMetrics:{resource:s,scopeMetrics:i},errors:n}}async shutdown(e){this._shutdown?av.error("Cannot call shutdown twice."):(null==e?.timeoutMillis?await this.onShutdown():await gT(this.onShutdown(),e.timeoutMillis),this._shutdown=!0)}async forceFlush(e){this._shutdown?av.warn("Cannot forceFlush on already shutdown MetricReader."):null!=e?.timeoutMillis?await gT(this.onForceFlush(),e.timeoutMillis):await this.onForceFlush()}}class sk extends nk{_interval;_exporter;_exportInterval;_exportTimeout;constructor(e){if(super({aggregationSelector:e.exporter.selectAggregation?.bind(e.exporter),aggregationTemporalitySelector:e.exporter.selectAggregationTemporality?.bind(e.exporter),metricProducers:e.metricProducers}),void 0!==e.exportIntervalMillis&&e.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(void 0!==e.exportTimeoutMillis&&e.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(void 0!==e.exportTimeoutMillis&&void 0!==e.exportIntervalMillis&&e.exportIntervalMillis0&&av.error("PeriodicExportingMetricReader: metrics collection errors",...t),e.resource.asyncAttributesPending)try{await(e.resource.waitForAsyncAttributes?.())}catch(e){av.debug("Error while resolving async portion of resource: ",e),lC(e)}if(0===e.scopeMetrics.length)return;const r=await EC._export(this._exporter,e);if(r.code!==_C.SUCCESS)throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${r.error})`)}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),this._interval}async onForceFlush(){await this._runOnce(),await this._exporter.forceFlush()}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}class ik{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(r=>this._matchInstrument(r.instrumentSelector,e)&&this._matchMeter(r.meterSelector,t))}_matchInstrument(e,t){return(void 0===e.getType()||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(void 0===t.version||e.getVersionFilter().match(t.version))&&(void 0===t.schemaUrl||e.getSchemaUrlFilter().match(t.schemaUrl))}}function ok(e,t,r){return function(e){return null!=e.match(lk)}(e)||av.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:t,description:r?.description??"",unit:r?.unit??"",valueType:r?.valueType??Ow.DOUBLE,advice:r?.advice??{}}}function ak(e,t){return r=e.name,n=t.name,r.toLowerCase()===n.toLowerCase()&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType;var r,n}const lk=/^[a-z][a-z0-9_.\-/]{0,254}$/i;class ck{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},r=ov.active()){"number"==typeof e?(this._descriptor.valueType!==Ow.INT||Number.isInteger(e)||(av.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._writableMetricStorage.record(e,t,r,mC(Date.now())):av.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`)}}class uk extends ck{add(e,t,r){this._record(e,t,r)}}class hk extends ck{add(e,t,r){e<0?av.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class pk extends ck{record(e,t,r){this._record(e,t,r)}}class dk extends ck{record(e,t,r){e<0?av.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class fk{_observableRegistry;_metricStorages;_descriptor;constructor(e,t,r){this._observableRegistry=r,this._descriptor=e,this._metricStorages=t}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}}class mk extends fk{}class gk extends fk{}class yk extends fk{}function wk(e){return e instanceof fk}class vk{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){const r=ok(e,uT.GAUGE,t),n=this._meterSharedState.registerMetricStorage(r);return new pk(n,r)}createHistogram(e,t){const r=ok(e,uT.HISTOGRAM,t),n=this._meterSharedState.registerMetricStorage(r);return new dk(n,r)}createCounter(e,t){const r=ok(e,uT.COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new hk(n,r)}createUpDownCounter(e,t){const r=ok(e,uT.UP_DOWN_COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new uk(n,r)}createObservableGauge(e,t){const r=ok(e,uT.OBSERVABLE_GAUGE,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new gk(r,n,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){const r=ok(e,uT.OBSERVABLE_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new mk(r,n,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){const r=ok(e,uT.OBSERVABLE_UP_DOWN_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new yk(r,n,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}class bk{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=ok(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class _k{_hash;_valueMap=new Map;_keyMap=new Map;constructor(e){this._hash=e}get(e,t){return t??=this._hash(e),this._valueMap.get(t)}getOrDefault(e,t){const r=this._hash(e);if(this._valueMap.has(r))return this._valueMap.get(r);const n=t();return this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,n),n}set(e,t,r){r??=this._hash(e),this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,t)}has(e,t){return t??=this._hash(e),this._valueMap.has(t)}*keys(){const e=this._keyMap.entries();let t=e.next();for(;!0!==t.done;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){const e=this._valueMap.entries();let t=e.next();for(;!0!==t.done;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}}class Sk extends _k{constructor(){super(fT)}}class Ck{_aggregator;_activeCollectionStorage=new Sk;_cumulativeMemoStorage=new Sk;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=fT(this._overflowAttributes)}record(e,t,r,n){let s=this._activeCollectionStorage.get(t);if(!s){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const t=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(n));return void t?.record(e)}s=this._aggregator.createAccumulation(n),this._activeCollectionStorage.set(t,s)}s?.record(e)}batchCumulate(e,t){Array.from(e.entries()).forEach(([e,r,n])=>{const s=this._aggregator.createAccumulation(t);s?.record(r);let i=s;if(this._cumulativeMemoStorage.has(e,n)){const t=this._cumulativeMemoStorage.get(e,n);i=this._aggregator.diff(t,s)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,n=this._overflowHashCode,this._cumulativeMemoStorage.has(e,n))){const t=this._cumulativeMemoStorage.get(e,n);i=this._aggregator.diff(t,s)}if(this._activeCollectionStorage.has(e,n)){const t=this._activeCollectionStorage.get(e,n);i=this._aggregator.merge(t,i)}this._cumulativeMemoStorage.set(e,s,n),this._activeCollectionStorage.set(e,i,n)})}collect(){const e=this._activeCollectionStorage;return this._activeCollectionStorage=new Sk,e}}class Ek{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,t){this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(e,t,r,n){this._stashAccumulations(r);const s=this._getMergedUnreportedAccumulations(e);let i,o=s;if(this._reportHistory.has(e)){const t=this._reportHistory.get(e),r=t.collectionTime;i=t.aggregationTemporality,o=i===cT.CUMULATIVE?Ek.merge(t.accumulations,s,this._aggregator):Ek.calibrateStartTime(t.accumulations,s,r)}else i=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:o,collectionTime:n,aggregationTemporality:i});const a=(l=o,Array.from(l.entries()));var l;if(0!==a.length)return this._aggregator.toMetricData(t,i,a,n)}_stashAccumulations(e){const t=this._unreportedAccumulations.keys();for(const r of t){let t=this._unreportedAccumulations.get(r);void 0===t&&(t=[],this._unreportedAccumulations.set(r,t)),t.push(e)}}_getMergedUnreportedAccumulations(e){let t=new Sk;const r=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),void 0===r)return t;for(const e of r)t=Ek.merge(t,e,this._aggregator);return t}static merge(e,t,r){const n=e,s=t.entries();let i=s.next();for(;!0!==i.done;){const[t,o,a]=i.value;if(e.has(t,a)){const s=e.get(t,a),i=r.merge(s,o);n.set(t,i,a)}else n.set(t,o,a);i=s.next()}return n}static calibrateStartTime(e,t,r){for(const[n,s]of e.keys()){const e=t.get(n,s);e?.setStartTime(r)}return t}}class Tk extends bk{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,r,n,s){super(e),this._attributesProcessor=r,this._aggregationCardinalityLimit=s,this._deltaMetricStorage=new Ck(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ek(t,n)}record(e,t){const r=new Sk;Array.from(e.entries()).forEach(([e,t])=>{r.set(this._attributesProcessor.process(e),t)}),this._deltaMetricStorage.batchCumulate(r,t)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}function kk(e,t){let r="";return e.unit!==t.unit&&(r+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(r+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(r+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(r+=`\t- Description '${e.description}' does not match '${t.description}'\n`),r}function xk(e,t){return e.valueType!==t.valueType?function(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}(e,t):e.unit!==t.unit?function(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}(e,t):e.type!==t.type?function(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'`}(e,t):e.description!==t.description?function(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'\n \t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${n}\n \t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${n}`}(e,t):""}class Ok{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new Ok}getStorages(e){let t=[];for(const e of this._sharedRegistry.values())t=t.concat(e);const r=this._perCollectorRegistry.get(e);if(null!=r)for(const e of r.values())t=t.concat(e);return t}register(e){this._registerStorage(e,this._sharedRegistry)}registerForCollector(e,t){let r=this._perCollectorRegistry.get(e);null==r&&(r=new Map,this._perCollectorRegistry.set(e,r)),this._registerStorage(t,r)}findOrUpdateCompatibleStorage(e){const t=this._sharedRegistry.get(e.name);return void 0===t?null:this._findOrUpdateCompatibleStorage(e,t)}findOrUpdateCompatibleCollectorStorage(e,t){const r=this._perCollectorRegistry.get(e);if(void 0===r)return null;const n=r.get(t.name);return void 0===n?null:this._findOrUpdateCompatibleStorage(t,n)}_registerStorage(e,t){const r=e.getInstrumentDescriptor(),n=t.get(r.name);void 0!==n?n.push(e):t.set(r.name,[e])}_findOrUpdateCompatibleStorage(e,t){let r=null;for(const n of t){const t=n.getInstrumentDescriptor();ak(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&n.updateDescription(e.description),av.warn("A view or instrument with the name ",e.name," has already been registered, but has a different description and is incompatible with another registered view.\n","Details:\n",kk(t,e),"The longer description will be used.\nTo resolve the conflict:",xk(t,e))),r=n):av.warn("A view or instrument with the name ",e.name," has already been registered and is incompatible with another registered view.\n","Details:\n",kk(t,e),"To resolve the conflict:\n",xk(t,e))}return r}}class Ak{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,r,n){this._backingStorages.forEach(s=>{s.record(e,t,r,n)})}}class Ik{_instrumentName;_valueType;_buffer=new Sk;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,t={}){"number"==typeof e?(this._valueType!==Ow.INT||Number.isInteger(e)||(av.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._buffer.set(t,e):av.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`)}}class Rk{_buffer=new Map;observe(e,t,r={}){if(!wk(e))return;let n=this._buffer.get(e);null==n&&(n=new Sk,this._buffer.set(e,n)),"number"==typeof t?(e._descriptor.valueType!==Ow.INT||Number.isInteger(t)||(av.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),Number.isInteger(t)))&&n.set(r,t):av.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`)}}class Mk{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){const r=this._findCallback(e,t);r<0||this._callbacks.splice(r,1)}addBatchCallback(e,t){const r=new Set(t.filter(wk));if(0===r.size)return void av.error("BatchObservableCallback is not associated with valid instruments",t);this._findBatchCallback(e,r)>=0||this._batchCallbacks.push({callback:e,instruments:r})}removeBatchCallback(e,t){const r=new Set(t.filter(wk)),n=this._findBatchCallback(e,r);n<0||this._batchCallbacks.splice(n,1)}async observe(e,t){const r=this._observeCallbacks(e,t),n=this._observeBatchCallbacks(e,t),s=await async function(e){return Promise.all(e.map(async e=>{try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}))}([...r,...n]);return s.filter(yT).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:r,instrument:n})=>{const s=new Ik(n._descriptor.name,n._descriptor.valueType);let i=Promise.resolve(r(s));null!=t&&(i=gT(i,t)),await i,n._metricStorages.forEach(t=>{t.record(s._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:r,instruments:n})=>{const s=new Rk;let i=Promise.resolve(r(s));null!=t&&(i=gT(i,t)),await i,n.forEach(t=>{const r=s._buffer.get(t);null!=r&&t._metricStorages.forEach(t=>{t.record(r,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(r=>r.callback===e&&r.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(r=>r.callback===e&&function(e,t){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}(r.instruments,t))}}class Nk extends bk{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,r,n,s){super(e),this._attributesProcessor=r,this._aggregationCardinalityLimit=s,this._deltaMetricStorage=new Ck(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ek(t,n)}record(e,t,r,n){t=this._attributesProcessor.process(t,r),this._deltaMetricStorage.record(e,t,r,n)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}class Pk{_processors;constructor(e){this._processors=e}process(e,t){let r=e;for(const e of this._processors)r=e.process(r,t);return r}}function Lk(){return Dk}const Dk=new class{process(e,t){return e}};class Uk{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new Ok;observableRegistry=new Mk;meter;constructor(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.meter=new vk(this)}registerMetricStorage(e){const t=this._registerMetricStorage(e,Nk);return 1===t.length?t[0]:new Ak(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,Tk)}async collect(e,t,r){const n=await this.observableRegistry.observe(t,r?.timeoutMillis),s=this.metricStorageRegistry.getStorages(e);if(0===s.length)return null;const i=s.map(r=>r.collect(e,t)).filter(dT);return 0===i.length?{errors:n}:{scopeMetrics:{scope:this._instrumentationScope,metrics:i},errors:n}}_registerMetricStorage(e,t){let r=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(r=>{const n=function(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}(r,e),s=this.metricStorageRegistry.findOrUpdateCompatibleStorage(n);if(null!=s)return s;const i=r.aggregation.createAggregator(n),o=new t(n,i,r.attributesProcessor,this._meterProviderSharedState.metricCollectors,r.aggregationCardinalityLimit);return this.metricStorageRegistry.register(o),o});if(0===r.length){const n=this._meterProviderSharedState.selectAggregations(e.type).map(([r,n])=>{const s=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(r,e);if(null!=s)return s;const i=n.createAggregator(e),o=r.selectCardinalityLimit(e.type),a=new t(e,i,Lk(),[r],o);return this.metricStorageRegistry.registerForCollector(r,a),a});r=r.concat(n)}return r}}class Fk{resource;viewRegistry=new ik;metricCollectors=[];meterSharedStates=new Map;constructor(e){this.resource=e}getMeterSharedState(e){const t=function(e){return`${e.name}:${e.version??""}:${e.schemaUrl??""}`}(e);let r=this.meterSharedStates.get(t);return null==r&&(r=new Uk(this,e),this.meterSharedStates.set(t,r)),r}selectAggregations(e){const t=[];for(const r of this.metricCollectors)t.push([r,ek(r.selectAggregation(e))]);return t}}class Bk{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){const t=mC(Date.now()),r=[],n=[],s=Array.from(this._sharedState.meterSharedStates.values()).map(async s=>{const i=await s.collect(this,t,e);null!=i?.scopeMetrics&&r.push(i.scopeMetrics),null!=i?.errors&&n.push(...i.errors)});return await Promise.all(s),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:r},errors:n}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}const jk=/[\^$\\.+?()[\]{}|]/g;class zk{_matchAll;_regexp;constructor(e){"*"===e?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(zk.escapePattern(e)))}match(e){return!!this._matchAll||this._regexp.test(e)}static escapePattern(e){return`^${e.replace(jk,"\\$&").replace("*",".*")}$`}static hasWildcard(e){return e.includes("*")}}class Vk{_matchAll;_pattern;constructor(e){this._matchAll=void 0===e,this._pattern=e}match(e){return!!this._matchAll||e===this._pattern}}class Gk{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new zk(e?.name??"*"),this._type=e?.type,this._unitFilter=new Vk(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class Hk{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new Vk(e?.name),this._versionFilter=new Vk(e?.version),this._schemaUrlFilter=new Vk(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}class Zk{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){var t;!function(e){if(null==(t=e).instrumentName&&null==t.instrumentType&&null==t.instrumentUnit&&null==t.meterName&&null==t.meterVersion&&null==t.meterSchemaUrl)throw new Error("Cannot create view with no selector arguments supplied");var t;if(null!=e.name&&(null==e?.instrumentName||zk.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}(e),null!=e.attributesProcessors?this.attributesProcessor=(t=e.attributesProcessors,new Pk(t)):this.attributesProcessor=Lk(),this.name=e.name,this.description=e.description,this.aggregation=ek(e.aggregation??{type:QT.DEFAULT}),this.instrumentSelector=new Gk({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new Hk({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}class $k{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new Fk(e?.resource??xC()),null!=e?.views&&e.views.length>0)for(const t of e.views)this._sharedState.viewRegistry.addView(new Zk(t));if(null!=e?.readers&&e.readers.length>0)for(const t of e.readers){const e=new Bk(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,t="",r={}){return this._shutdown?(av.warn("A shutdown MeterProvider cannot provide a Meter"),xw()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:r.schemaUrl}).meter}async shutdown(e){this._shutdown?av.warn("shutdown may only be called once per MeterProvider"):(this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e))))}async forceFlush(e){this._shutdown?av.warn("invalid attempt to force flush after MeterProvider shutdown"):await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}var Wk;function Yk(e,t){return Array.from(e.map(e=>({scope:iT(e.scope),metrics:e.metrics.map(e=>function(e,t){const r={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},n=function(e){switch(e){case cT.DELTA:return Wk.AGGREGATION_TEMPORALITY_DELTA;case cT.CUMULATIVE:return Wk.AGGREGATION_TEMPORALITY_CUMULATIVE}}(e.aggregationTemporality);switch(e.dataPointType){case hT.SUM:r.sum={aggregationTemporality:n,isMonotonic:e.isMonotonic,dataPoints:Xk(e,t)};break;case hT.GAUGE:r.gauge={dataPoints:Xk(e,t)};break;case hT.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:Jk(e,t)};break;case hT.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:Kk(e,t)}}return r}(e,t)),schemaUrl:e.scope.schemaUrl})))}function Xk(e,t){return e.dataPoints.map(r=>function(e,t,r){const n={attributes:oT(e.attributes),startTimeUnixNano:r.encodeHrTime(e.startTime),timeUnixNano:r.encodeHrTime(e.endTime)};switch(t){case Ow.INT:n.asInt=e.value;break;case Ow.DOUBLE:n.asDouble=e.value}return n}(r,e.descriptor.valueType,t))}function Jk(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:oT(e.attributes),bucketCounts:r.buckets.counts,explicitBounds:r.buckets.boundaries,count:r.count,sum:r.sum,min:r.min,max:r.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function Kk(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:oT(e.attributes),count:r.count,min:r.min,max:r.max,sum:r.sum,positive:{offset:r.positive.offset,bucketCounts:r.positive.bucketCounts},negative:{offset:r.negative.offset,bucketCounts:r.negative.bucketCounts},scale:r.scale,zeroCount:r.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function qk(e,t){return{resourceMetrics:e.map(e=>function(e,t){const r=nT(t);return{resource:sT(e.resource),schemaUrl:void 0,scopeMetrics:Yk(e.scopeMetrics,r)}}(e,t))}}function Qk(e,t){const r=e.spanContext(),n=e.status,s=e.parentSpanContext?.spanId?t.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:t.encodeSpanContext(r.traceId),spanId:t.encodeSpanContext(r.spanId),parentSpanId:s,traceState:r.traceState?.serialize(),name:e.name,kind:null==e.kind?0:e.kind+1,startTimeUnixNano:t.encodeHrTime(e.startTime),endTimeUnixNano:t.encodeHrTime(e.endTime),attributes:oT(e.attributes),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>function(e,t){return{attributes:e.attributes?oT(e.attributes):[],name:e.name,timeUnixNano:t.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}(e,t)),droppedEventsCount:e.droppedEventsCount,status:{code:n.code,message:n.message},links:e.links.map(e=>function(e,t){return{attributes:e.attributes?oT(e.attributes):[],spanId:t.encodeSpanContext(e.context.spanId),traceId:t.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0}}(e,t)),droppedLinksCount:e.droppedLinksCount}}function ex(e,t){const r=function(e){const t=new Map;for(const r of e){let e=t.get(r.resource);e||(e=new Map,t.set(r.resource,e));const n=`${r.instrumentationScope.name}@${r.instrumentationScope.version||""}:${r.instrumentationScope.schemaUrl||""}`;let s=e.get(n);s||(s=[],e.set(n,s)),s.push(r)}return t}(e),n=[],s=r.entries();let i=s.next();for(;!i.done;){const[e,r]=i.value,o=[],a=r.values();let l=a.next();for(;!l.done;){const e=l.value;if(e.length>0){const r=e.map(e=>Qk(e,t));o.push({scope:iT(e[0].instrumentationScope),spans:r,schemaUrl:e[0].instrumentationScope.schemaUrl})}l=a.next()}const c={resource:sT(e),scopeSpans:o,schemaUrl:void 0};n.push(c),i=s.next()}return n}!function(e){e[e.AGGREGATION_TEMPORALITY_UNSPECIFIED=0]="AGGREGATION_TEMPORALITY_UNSPECIFIED",e[e.AGGREGATION_TEMPORALITY_DELTA=1]="AGGREGATION_TEMPORALITY_DELTA",e[e.AGGREGATION_TEMPORALITY_CUMULATIVE=2]="AGGREGATION_TEMPORALITY_CUMULATIVE"}(Wk||(Wk={}));const tx={serializeRequest:e=>{const t=qk([e],{useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{if(0===e.length)return{};const t=new TextDecoder;return JSON.parse(t.decode(e))}},rx={serializeRequest:e=>{const t={resourceSpans:ex(e,nT({useHex:!0,useLongBits:!1}))};return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{if(0===e.length)return{};const t=new TextDecoder;return JSON.parse(t.decode(e))}};function nx(){return.4*Math.random()-.2}class sx{_transport;constructor(e){this._transport=e}retry(e,t,r){return new Promise((n,s)=>{setTimeout(()=>{this._transport.send(e,t).then(n,s)},r)})}async send(e,t){const r=Date.now()+t;let n=await this._transport.send(e,t),s=5,i=1e3;for(;"retryable"===n.status&&s>0;){s--;const t=Math.max(Math.min(i,5e3)+nx(),0);i*=1.5;const o=n.retryInMillis??t,a=r-Date.now();if(o>a)return n;n=await this.retry(e,a,o)}return n}shutdown(){return this._transport.shutdown()}}function ix(e){return new sx(e.transport)}function ox(e){if(null==e)return;const t=Number.parseInt(e,10);if(Number.isInteger(t))return t>0?1e3*t:-1;const r=new Date(e).getTime()-Date.now();return r>=0?r:0}class ax{_parameters;constructor(e){this._parameters=e}send(e,t){return new Promise(r=>{const n=new XMLHttpRequest;n.timeout=t,n.open("POST",this._parameters.url);const s=this._parameters.headers();Object.entries(s).forEach(([e,t])=>{n.setRequestHeader(e,t)}),n.ontimeout=e=>{r({status:"failure",error:new Error("XHR request timed out")})},n.onreadystatechange=()=>{var e;n.status>=200&&n.status<=299?(av.debug("XHR success"),r({status:"success"})):n.status&&(e=n.status,[429,502,503,504].includes(e))?r({status:"retryable",retryInMillis:ox(n.getResponseHeader("Retry-After"))}):0!==n.status&&r({status:"failure",error:new Error("XHR request failed with non-retryable status")})},n.onabort=()=>{r({status:"failure",error:new Error("XHR request aborted")})},n.onerror=()=>{r({status:"failure",error:new Error("XHR request errored")})},n.send(e)})}shutdown(){}}class lx{_params;constructor(e){this._params=e}send(e){return new Promise(t=>{navigator.sendBeacon(this._params.url,new Blob([e],{type:this._params.blobType}))?(av.debug("SendBeacon success"),t({status:"success"})):t({status:"failure",error:new Error("SendBeacon failed")})})}shutdown(){}}function cx(e,t,r){const n={...r()},s={};return()=>(null!=t&&Object.assign(s,t()),null!=e&&Object.assign(s,e()),Object.assign(s,n))}function ux(e){if(null!=e)try{return new URL(e),e}catch{throw new Error(`Configuration: Could not parse user-provided export URL: '${e}'`)}}function hx(e,t,r){return n={url:e.url,timeoutMillis:e.timeoutMillis,headers:VE(e.headers),concurrencyLimit:e.concurrencyLimit},s={},i=function(e,t){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none",headers:()=>e,url:"http://localhost:4318/"+t,agentOptions:{keepAlive:!0}}}(r,t),{...GE(n,s,i),headers:cx((o=n.headers,()=>{const e={};return Object.entries(o?.()??{}).forEach(([t,r])=>{void 0!==r?e[t]=String(r):av.warn(`Header "${t}" has invalid value (${r}) and will be ignored`)}),e}),s.headers,i.headers),url:ux(n.url)??s.url??i.url,agentOptions:n.agentOptions??s.agentOptions??i.agentOptions};var n,s,i,o}function px(e,t,r,n){const s=!!e.headers||"function"!=typeof navigator.sendBeacon,i=hx(e,r,n);return s?function(e,t){return YE(e,t,ix({transport:(r=e,new ax(r))}));var r}(i,t):function(e,t){return YE(e,t,ix({transport:(r={url:e.url,blobType:e.headers()["Content-Type"]},new lx(r))}));var r}(i,t)}class dx extends BE{constructor(e={}){super(px(e,rx,"v1/traces",{"Content-Type":"application/json"}))}}var fx;!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE",e[e.LOWMEMORY=2]="LOWMEMORY"}(fx||(fx={}));const mx=()=>cT.CUMULATIVE,gx=e=>{switch(e){case uT.COUNTER:case uT.OBSERVABLE_COUNTER:case uT.GAUGE:case uT.HISTOGRAM:case uT.OBSERVABLE_GAUGE:return cT.DELTA;case uT.UP_DOWN_COUNTER:case uT.OBSERVABLE_UP_DOWN_COUNTER:return cT.CUMULATIVE}},yx=e=>{switch(e){case uT.COUNTER:case uT.HISTOGRAM:return cT.DELTA;case uT.GAUGE:case uT.UP_DOWN_COUNTER:case uT.OBSERVABLE_UP_DOWN_COUNTER:case uT.OBSERVABLE_COUNTER:case uT.OBSERVABLE_GAUGE:return cT.CUMULATIVE}};function wx(e){return null!=e?e===fx.DELTA?gx:e===fx.LOWMEMORY?yx:mx:function(){const e="cumulative".toLowerCase();return"cumulative"===e?mx:"delta"===e?gx:"lowmemory"===e?yx:(av.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),mx)}()}const vx=Object.freeze({type:QT.DEFAULT});class bx extends BE{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=function(e){return e?.aggregationPreference??(()=>vx)}(t),this._aggregationTemporalitySelector=wx(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}}class _x extends bx{constructor(e){super(px(e??{},tx,"v1/metrics",{"Content-Type":"application/json"}),e)}}const Sx="monoscope";function Cx(e){try{const t=new URL(e,"undefined"!=typeof location?location.href:"http://_");return t.pathname+(t.search?"?…":"")}catch{return e.slice(0,80)}}function Ex(){try{if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID()}catch{}const e=new Uint8Array(16);try{crypto.getRandomValues(e)}catch{for(let t=0;t<16;t++)e[t]=256*Math.random()|0}e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}class Tx{constructor(e,t,r){if(this.pageviewId="",this.processor=null,this.meterProvider=null,this.metricReader=null,this.vitalHistograms={},this.pageviewMaxTimer=null,this.longTaskObserver=null,this.loafObserver=null,this.resourceObserver=null,this._enabled=!0,this._configured=!1,this._firstExportLogged=!1,this.routeSpan=null,this.routeContext=null,this.routeIdleTimer=null,this.pageviewSpan=null,this.pageviewContext=null,this.flushOnHideHandler=null,this.visibilityHandler=null,this.lastInteractionAt=new WeakMap,this.onExportStatus=null,this.onSpanStart=null,this.config=e,this.sessionId=t,this.tabId=r,this.provider=this.createProvider(),!1!==e.captureWebVitals)try{this.meterProvider=this.createMeterProvider()}catch(e){console.warn("[Monoscope] Web-vital metrics disabled (init failed)",e),this.meterProvider=null}}createMeterProvider(){const{serviceName:e,resourceAttributes:t={},exporterEndpoint:r,metricsExporterEndpoint:n}=this.config,s=this.config.apiKey||this.config.projectId||"";let i;if(n)i=n;else if(r){const e=r.replace(/\/v1\/traces\b/,"/v1/metrics");if(e===r)return console.warn("[Monoscope] Web-vital metrics disabled: exporterEndpoint does not contain /v1/traces — set metricsExporterEndpoint to enable."),null;i=e}else i="https://otelcol.monoscope.tech/v1/metrics";const o=new _x({url:i,headers:{"x-api-key":s}}),a=new sk({exporter:o,exportIntervalMillis:3e4});return this.metricReader=a,new $k({resource:jb({[Hv]:e,"x-api-key":s,...t}),readers:[a]})}recordWebVital(e,t,r){if(this._enabled&&this.meterProvider)try{let n=this.vitalHistograms[e];if(!n){n=this.meterProvider.getMeter(Sx).createHistogram(`browser.web_vital.${e.toLowerCase()}`,{description:`Core Web Vital: ${e}`,unit:"CLS"===e?"1":"ms"}),this.vitalHistograms[e]=n}n.record(t,{...this.commonAttrs(),...r})}catch(t){this.config.debug&&console.warn("Monoscope: recordWebVital failed for",e,t)}}createProvider(){const{serviceName:e,resourceAttributes:t={},exporterEndpoint:r}=this.config,n=this.config.apiKey||this.config.projectId||"",s=this,i=new dx({url:r||"https://otelcol.monoscope.tech/v1/traces",headers:{"x-api-key":n}}),o=Object.create(i,{export:{value:(e,t)=>i.export(e,e=>{if(!s._firstExportLogged){s._firstExportLogged=!0;const t=0===e.code;if(s.config.debug&&(console.log(t?"%c[Monoscope] ✓ First trace sent successfully":"%c[Monoscope] ✗ First trace export failed",t?"color: #22c55e; font-weight: bold":"color: #ef4444; font-weight: bold",t?"":e.error||""),!t)){const t=String(e.error||"");t.includes("401")||t.includes("403")?console.warn("[Monoscope] Authentication failed. Your apiKey may be invalid."):console.warn("[Monoscope] Could not reach Monoscope endpoint. Check your apiKey and network.")}s.onExportStatus?.(t)}t(e)})}}),a=new e_(o);this.processor=a;const l={onStart:()=>{try{s.onSpanStart?.()}catch{}},onEnd:()=>{},shutdown:()=>Promise.resolve(),forceFlush:()=>Promise.resolve()},c=new y_({resource:jb({[Hv]:e,"x-api-key":n,...t}),spanProcessors:[a,l]}),u=c.getTracer.bind(c);return c.getTracer=(e,t,r)=>{const n=u(e,t,r);if(n.__monoscopeWrapped)return n;const i=n.startSpan.bind(n),o=n.startActiveSpan.bind(n),a=e=>{const t=e??ov.active();return Cv.getSpan(t)?t:s.pageviewContext??t};return n.startSpan=(e,t,r)=>i(e,t,a(r)),n.startActiveSpan=(e,...t)=>{let r,n,s;return 1===t.length?[s]=t:2===t.length?[r,s]=t:[r,n,s]=t,o(e,r,a(n),s)},n.__monoscopeWrapped=!0,n},c}startPageview(){if(!this.pageviewSpan)try{const e=this.provider.getTracer(Sx).startSpan("pageview",{attributes:{"monoscope.kind":"pageview","monoscope.display.label":`Pageview · ${Cx(location.href)}`}},ov.active());this.applyCommonAttrs(e),this.pageviewSpan=e,this.pageviewContext=Cv.setSpan(ov.active(),e),this.pageviewMaxTimer=setTimeout(()=>this.rollPageview(),18e5)}catch(e){console.warn("[Monoscope] startPageview failed — spans will be orphaned",e)}}endPageview(){this.pageviewMaxTimer&&(clearTimeout(this.pageviewMaxTimer),this.pageviewMaxTimer=null);try{this.pageviewSpan?.end()}catch(e){this.config.debug&&console.warn("Monoscope: endPageview failed",e)}this.pageviewSpan=null,this.pageviewContext=null}rollPageview(){this._enabled&&(this.endPageview(),this.rotatePageview(),this.startPageview())}commonAttrs(){const e={"session.id":this.sessionId,"tab.id":this.tabId,"pageview.id":this.pageviewId,"page.url":location.href,"page.title":document.title};return document.referrer&&(e["page.referrer"]=document.referrer),e}applyCommonAttrs(e){for(const[t,r]of Object.entries(this.commonAttrs()))e.setAttribute(t,r);if(this.config.user)for(const[t,r]of Object.entries(this.config.user))void 0!==r&&e.setAttribute(`user.${t}`,r)}configure(){if("undefined"==typeof window||this._configured)return;this._configured=!0;const e=Math.max(0,Math.min(1,this.config.sampleRate??1));let t;try{const r=sessionStorage.getItem("monoscope-sampled");"1"===r||"0"===r?t="1"===r:(t=Math.random(){this.applyCommonAttrs(e),e.setAttribute("monoscope.kind",t),r&&e.setAttribute("monoscope.display.label",r)},i=!1!==this.config.enableUserInteraction?[new FE({eventNames:["click","submit"],shouldPreventSpanCreation:(e,t,r)=>{const n=function(e){const t=e;return t&&"function"==typeof t.closest?t.closest("button,a[href],input,select,textarea,summary,label,[role=button],[role=link],[role=menuitem],[role=tab],[role=switch],[role=checkbox],[role=radio],[role=option],[data-monoscope-track]"):null}(t);if(!n)return!0;const i=performance.now();if(i-(this.lastInteractionAt.get(n)??0)<250)return!0;this.lastInteractionAt.set(n,i),s(r,"interaction",`${e} · ${function(e){const t=e;if(!t||!t.tagName)return"?";const r=t.getAttribute?.("aria-label");if(r)return r;const n=(t.textContent||"").trim().replace(/\s+/g," ").slice(0,40);if(n)return n;const s=t.id?`#${t.id}`:"",i=(t.getAttribute?.("class")||"").split(" ").filter(Boolean)[0];return`${t.tagName.toLowerCase()}${s}${i?`.${i}`:""}`}(n)}`),r.setAttribute("target.tag_name",n.tagName?.toLowerCase()||""),n.id&&r.setAttribute("target.id",n.id);const o=n.getAttribute("role");return o&&r.setAttribute("target.role",o),!1}})]:[];!function(e){const t=e.tracerProvider||Cv.getTracerProvider(),r=e.meterProvider||hv.getMeterProvider(),n=e.loggerProvider||I_.getLoggerProvider(),s=e.instrumentations?.flat()??[];(function(e,t,r,n){for(let s=0,i=e.length;ss(e,"page_load",`Page · ${Cx(location.href)}`),resourceFetch:e=>s(e,"resource")}}),new YC({propagateTraceHeaderCorsUrls:r,ignoreUrls:n,applyCustomAttributesOnSpan:(e,t)=>{const r=t.responseURL;s(e,"network",r?`XHR · ${Cx(r)}`:void 0)}}),new mE({propagateTraceHeaderCorsUrls:r,ignoreUrls:n,applyCustomAttributesOnSpan:(e,t)=>{let r,n="GET";"string"==typeof t?r=t:t&&"string"==typeof t.url?(r=t.url,n=t.method||"GET"):t&&"string"==typeof t.method&&(n=t.method),s(e,"network",r?`${n} · ${Cx(r)}`:void 0)}}),...i]}),!0===this.config.captureLongTasks&&this.observeLongTasks(),!1!==this.config.captureLongAnimationFrames&&this.observeLongAnimationFrames(),this.config.captureResourceTiming&&this.observeResourceTiming(),this.installFlushOnHide()}getPageviewId(){return this.pageviewId}rotatePageview(){return this.pageviewId=Ex(),this.pageviewId}startRouteChange(e,t,r){try{this.endRouteChange(),this.rollPageview();const n=this.provider.getTracer(Sx).startSpan("route.change",{attributes:{"navigation.from":e,"navigation.to":t,"navigation.method":r,"monoscope.kind":"navigation","monoscope.display.label":`Nav · ${Cx(e)} → ${Cx(t)}`}});this.applyCommonAttrs(n),this.routeSpan=n,this.routeContext=Cv.setSpan(ov.active(),n),this.routeIdleTimer=setTimeout(()=>{try{this.endRouteChange()}catch(e){this.config.debug&&console.warn("Monoscope: route idle close failed",e)}},3e3)}catch(e){this.config.debug&&console.warn("Monoscope: startRouteChange failed",e),this.routeSpan=null,this.routeContext=null,this.routeIdleTimer=null}}endRouteChange(){this.routeIdleTimer&&(clearTimeout(this.routeIdleTimer),this.routeIdleTimer=null);try{this.routeSpan?.end()}catch(e){this.config.debug&&console.warn("Monoscope: endRouteChange failed",e)}this.routeSpan=null,this.routeContext=null}installFlushOnHide(){const e=e=>t=>{this.config.debug&&console.warn(`Monoscope: ${e} failed`,t)},t=()=>{try{this.endRouteChange(),this.endPageview(),this.processor?.forceFlush().catch(e("trace flush")),this.metricReader?.forceFlush().catch(e("metric flush"))}catch(e){this.config.debug&&console.warn("Monoscope: flush on hide failed",e)}};this.flushOnHideHandler=t,this.visibilityHandler=()=>{"hidden"===document.visibilityState?t():this._enabled&&!this.pageviewSpan&&this.rollPageview()},window.addEventListener("pagehide",this.flushOnHideHandler),document.addEventListener("visibilitychange",this.visibilityHandler)}withActiveContext(e){const t=this.routeContext??this.pageviewContext;return t?ov.with(t,e):e()}emitSpan(e,t,r,n,s){if(this._enabled)try{const i=this.provider.getTracer(Sx),o=this.routeContext??this.pageviewContext??ov.active();i.startActiveSpan(e,{startTime:n},o,e=>{try{this.applyCommonAttrs(e);for(const[r,n]of Object.entries(t))e.setAttribute(r,n);r?.(e)}finally{e.end(s)}})}catch(t){this.config.debug&&console.warn("Monoscope: span emit failed for",e,t)}}observeLongTasks(){if("undefined"!=typeof PerformanceObserver)try{this.longTaskObserver=new PerformanceObserver(e=>{if(this._enabled)for(const t of e.getEntries())try{const e=Math.round(t.duration),r={"longtask.duration":t.duration,"longtask.name":t.name,"monoscope.kind":"long_task"},n=t.attribution?.[0];n?.containerType&&(r["longtask.container_type"]=n.containerType),n?.containerSrc&&(r["longtask.script"]=n.containerSrc),n?.containerName&&(r["longtask.container"]=n.containerName),n?.containerId&&(r["longtask.container_id"]=n.containerId);const s=n?.containerSrc||n?.containerName||n?.containerId,i=s?Cx(s):n?.containerType||t.name||"self";r["monoscope.display.label"]=`Long task · ${i} · ${e}ms`;const o=performance.timeOrigin+t.startTime;this.emitSpan("longtask",r,void 0,o,o+t.duration)}catch(e){this.config.debug&&console.warn("Monoscope: failed to process longtask entry",e)}}),this.longTaskObserver.observe({type:"longtask",buffered:!0})}catch(e){console.warn("Monoscope: longtask observation not supported",e)}}observeLongAnimationFrames(){if("undefined"==typeof PerformanceObserver)return;const e=PerformanceObserver.supportedEntryTypes;if(!Array.isArray(e)||e.includes("long-animation-frame"))try{this.loafObserver=new PerformanceObserver(e=>{if(this._enabled)for(const t of e.getEntries())try{const e=Math.round(t.duration),r={"loaf.duration":t.duration,"loaf.render_start":t.renderStart||0,"loaf.style_and_layout_start":t.styleAndLayoutStart||0,"loaf.blocking_duration":t.blockingDuration||0,"monoscope.kind":"long_animation_frame"},n=t.scripts||[],s=n.reduce((e,t)=>(t?.duration||0)>(e?.duration||0)?t:e,n[0]);s&&(s.invoker&&(r["loaf.invoker"]=s.invoker),s.invokerType&&(r["loaf.invoker_type"]=s.invokerType),s.sourceURL&&(r["loaf.source_url"]=s.sourceURL),s.sourceFunctionName&&(r["loaf.source_function"]=s.sourceFunctionName),"number"==typeof s.sourceCharPosition&&s.sourceCharPosition>=0&&(r["loaf.source_char_position"]=s.sourceCharPosition),"number"==typeof s.duration&&(r["loaf.script_duration"]=s.duration),"number"==typeof s.forcedStyleAndLayoutDuration&&(r["loaf.forced_style_layout_duration"]=s.forcedStyleAndLayoutDuration)),r["loaf.script_count"]=n.length;const i=s?.sourceFunctionName,o=s?.sourceURL?Cx(s.sourceURL):void 0,a=s?.invoker,l=i&&o?`${i} @ ${o}`:o||(a||"anonymous");r["monoscope.display.label"]=`LoAF · ${l} · ${e}ms`;const c=performance.timeOrigin+t.startTime;this.emitSpan("long-animation-frame",r,void 0,c,c+t.duration)}catch(e){this.config.debug&&console.warn("Monoscope: failed to process LoAF entry",e)}}),this.loafObserver.observe({type:"long-animation-frame",buffered:!0})}catch(e){this.config.debug&&console.warn("Monoscope: long-animation-frame not supported",e)}}observeResourceTiming(){if("undefined"==typeof PerformanceObserver)return;const e=this.config.resourceTimingThresholdMs??200;try{this.resourceObserver=new PerformanceObserver(t=>{if(this._enabled)for(const r of t.getEntries())if(!(r.durationr.startActiveSpan(e,e=>{this.applyCommonAttrs(e);try{const r=t(e);return r instanceof Promise?r.then(t=>(e.end(),t),t=>{throw e.setStatus({code:iv.ERROR,message:String(t)}),e.end(),t}):(e.end(),r)}catch(t){throw e.setStatus({code:iv.ERROR,message:String(t)}),e.end(),t}}))}recordEvent(e,t={}){this.emitSpan(e,t)}async forceFlush(){await Promise.all([this.processor?.forceFlush(),this.metricReader?.forceFlush()])}updateSessionId(e){this.sessionId=e}setEnabled(e){this._enabled=e}async shutdown(){this.longTaskObserver?.disconnect(),this.loafObserver?.disconnect(),this.resourceObserver?.disconnect(),this.endRouteChange(),this.endPageview(),this.flushOnHideHandler&&(window.removeEventListener("pagehide",this.flushOnHideHandler),this.flushOnHideHandler=null),this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this._configured=!1;const e=await Promise.allSettled([this.provider.shutdown(),this.meterProvider?.shutdown()??Promise.resolve()]);for(const t of e)"rejected"===t.status&&console.warn("[Monoscope] shutdown error (some telemetry may not have been exported)",t.reason);this.meterProvider=null}setUser(e){this.config={...this.config,user:{...this.config.user,...e}}}}const kx=[];function xx(e){kx.push({...e,timestamp:Date.now()}),kx.length>20&&kx.shift()}function Ox(e){try{return JSON.stringify(e)}catch{return`[unserializable: ${typeof e}]`}}const Ax=/(?:chrome|moz|safari|safari-web|ms-browser)-extension:\/\//i;class Ix{constructor(e,t={}){this.errorCount=0,this.droppedExtensionCount=0,this._active=!1,this.prevOnError=null,this.onUnhandledRejection=null,this.origConsoleError=null,this._processing=!1,this.emit=e,this.captureExtensionErrors=!!t.captureExtensionErrors,this.debug=!!t.debug}shouldDrop(e){return!this.captureExtensionErrors&&(!!function(...e){return e.some(e=>"string"==typeof e&&Ax.test(e))}(e["error.source"],e["error.stack"])&&(this.droppedExtensionCount++,this.debug&&this.origConsoleError&&this.origConsoleError.call(console,"[Monoscope] dropped extension error",{message:e["error.message"],source:e["error.source"]}),!0))}createErrorSpan(e,t,r){this.errorCount++;const n=kx.slice(),s=String(r["error.name"]||t),i=String(r["error.message"]||"").replace(/\s+/g," ").slice(0,80);this.emit(e,{"error.type":t,"error.count":this.errorCount,"monoscope.kind":"error","monoscope.display.label":i?`${s} · ${i}`:s,...r},e=>{e.setStatus({code:iv.ERROR}),n.length>0&&e.setAttribute("breadcrumbs",Ox(n))})}start(){"undefined"==typeof window||this._active||(this._active=!0,this.prevOnError=window.onerror,window.onerror=(e,t,r,n,s)=>{const i={"error.message":"string"==typeof e?e:e.type};return t&&(i["error.source"]=t),void 0!==r&&(i["error.lineno"]=r),void 0!==n&&(i["error.colno"]=n),s?.stack&&(i["error.stack"]=s.stack),s?.name&&(i["error.name"]=s.name),this.shouldDrop(i)||this.createErrorSpan("exception","uncaught_exception",i),"function"==typeof this.prevOnError?this.prevOnError.call(window,e,t,r,n,s):void 0},this.onUnhandledRejection=e=>{const t=e.reason,r={};t instanceof Error?(r["error.message"]=t.message,r["error.name"]=t.name,t.stack&&(r["error.stack"]=t.stack)):r["error.message"]=String(t),this.shouldDrop(r)||this.createErrorSpan("unhandled_rejection","unhandled_rejection",r)},this.origConsoleError=console.error,console.error=(...e)=>{if(this.origConsoleError?.apply(console,e),!this._processing){this._processing=!0;try{const t=e.map(e=>e instanceof Error?e.message:"string"==typeof e?e:Ox(e)).join(" "),r={"error.message":t},n=e.find(e=>e instanceof Error);if(n&&(r["error.name"]=n.name,n.stack&&(r["error.stack"]=n.stack)),this.shouldDrop(r))return;xx({type:"console.error",message:t}),this.createErrorSpan("console.error","console_error",r)}finally{this._processing=!1}}},window.addEventListener("unhandledrejection",this.onUnhandledRejection))}stop(){"undefined"!=typeof window&&this._active&&(this._active=!1,window.onerror=this.prevOnError,this.prevOnError=null,this.onUnhandledRejection&&window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this.origConsoleError&&(console.error=this.origConsoleError,this.origConsoleError=null))}getErrorCount(){return this.errorCount}getDroppedExtensionCount(){return this.droppedExtensionCount}}const Rx=["LCP","INP","CLS","FCP","TTFB"];class Mx{constructor(e){this._enabled=!0,this._active=!1,this.record=e}async start(){if("undefined"!=typeof window&&!this._active){this._active=!0;try{const{onCLS:e,onINP:t,onLCP:r,onFCP:n,onTTFB:s}=await Promise.resolve().then(function(){return PO}),i=e=>{this._enabled&&(e=>Rx.includes(e))(e.name)&&this.record(e.name,e.value,{"web_vital.rating":e.rating,"web_vital.id":e.id,"web_vital.navigation_type":e.navigationType})};[e,t,r,n,s].forEach(e=>e(i))}catch(e){console.warn("Monoscope: web-vitals collection failed to initialize",e)}}}setEnabled(e){this._enabled=e}}class Nx{constructor(e){this.currentUrl="",this._active=!1,this.origPushState=null,this.origReplaceState=null,this.popstateHandler=null,this.onNavigation=e}start(){if("undefined"==typeof window||this._active)return;this._active=!0,this.currentUrl=location.href,this.origPushState=history.pushState.bind(history),this.origReplaceState=history.replaceState.bind(history);const e=e=>{try{const t=this.currentUrl,r=location.href;if(t===r)return;this.currentUrl=r,xx({type:"navigation",message:`${t} → ${r}`,data:{method:e}}),this.onNavigation(t,r,e)}catch(e){try{console.warn("Monoscope: error in navigation tracking",e)}catch{}}};history.pushState=(...t)=>{this.origPushState(...t),e("pushState")},history.replaceState=(...t)=>{this.origReplaceState(...t),e("replaceState")},this.popstateHandler=()=>e("popstate"),window.addEventListener("popstate",this.popstateHandler)}stop(){"undefined"!=typeof window&&this._active&&(this._active=!1,this.origPushState&&(history.pushState=this.origPushState),this.origReplaceState&&(history.replaceState=this.origReplaceState),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),this.origPushState=null,this.origReplaceState=null,this.popstateHandler=null)}}const Px="monoscope-overlay-dismissed";class Lx{constructor(){if(this.el=null,this.eventCount=0,this.statusDot=null,this.countEl=null,this.connEl=null,"undefined"!=typeof document){try{if(sessionStorage.getItem(Px))return}catch{}this.mount()}}mount(){const e=document.createElement("div");Object.assign(e.style,{position:"fixed",bottom:"12px",right:"12px",zIndex:"2147483647",background:"#1a1a2e",color:"#e0e0e0",fontFamily:"system-ui, sans-serif",fontSize:"12px",padding:"6px 10px",borderRadius:"6px",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",display:"flex",alignItems:"center",gap:"6px",cursor:"default",userSelect:"none"}),this.statusDot=document.createElement("span"),Object.assign(this.statusDot.style,{width:"7px",height:"7px",borderRadius:"50%",background:"#22c55e",display:"inline-block"}),this.countEl=document.createElement("span"),this.countEl.textContent="0",this.countEl.style.opacity="0.7",this.connEl=document.createElement("span"),this.connEl.style.opacity="0.7";const t=document.createElement("span");t.textContent="×",Object.assign(t.style,{cursor:"pointer",marginLeft:"4px",opacity:"0.6",fontSize:"14px"}),t.onclick=()=>this.dismiss(),e.append(this.statusDot," Monoscope ",this.countEl," ",this.connEl,t),this.el=e,(document.body||document.documentElement).appendChild(e)}incrementEvents(){this.eventCount++,this.countEl&&(this.countEl.textContent=String(this.eventCount))}setConnectionStatus(e){this.connEl&&(this.connEl.textContent=e?"Connected":"Connection failed"),this.statusDot&&(this.statusDot.style.background=e?"#22c55e":"#ef4444")}dismiss(){this.el?.remove(),this.el=null;try{sessionStorage.setItem(Px,"1")}catch{}}}const Dx=18e5,Ux="monoscope-last-activity",Fx="undefined"!=typeof window;var Bx,jx,zx,Vx,Gx,Hx=-1,Zx=function(e){addEventListener("pageshow",function(t){t.persisted&&(Hx=t.timeStamp,e(t))},!0)},$x=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart=0?n="back-forward-cache":r&&(document.prerendering||Wx()>0?n="prerender":document.wasDiscarded?n="restore":r.type&&(n=r.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:n}},Xx=function(e,t,r){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var n=new PerformanceObserver(function(e){Promise.resolve().then(function(){t(e.getEntries())})});return n.observe(Object.assign({type:e,buffered:!0},r||{})),n}}catch(e){}},Jx=function(e,t,r,n){var s,i;return function(o){t.value>=0&&(o||n)&&((i=t.value-(s||0))||void 0===s)&&(s=t.value,t.delta=i,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,r),e(t))}},Kx=function(e){requestAnimationFrame(function(){return requestAnimationFrame(function(){return e()})})},qx=function(e){document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e()})},Qx=function(e){var t=!1;return function(){t||(e(),t=!0)}},eO=-1,tO=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},rO=function(e){"hidden"===document.visibilityState&&eO>-1&&(eO="visibilitychange"===e.type?e.timeStamp:0,sO())},nO=function(){addEventListener("visibilitychange",rO,!0),addEventListener("prerenderingchange",rO,!0)},sO=function(){removeEventListener("visibilitychange",rO,!0),removeEventListener("prerenderingchange",rO,!0)},iO=function(){return eO<0&&(eO=tO(),nO(),Zx(function(){setTimeout(function(){eO=tO(),nO()},0)})),{get firstHiddenTime(){return eO}}},oO=function(e){document.prerendering?addEventListener("prerenderingchange",function(){return e()},!0):e()},aO=[1800,3e3],lO=function(e,t){t=t||{},oO(function(){var r,n=iO(),s=Yx("FCP"),i=Xx("paint",function(e){e.forEach(function(e){"first-contentful-paint"===e.name&&(i.disconnect(),e.startTimet.latency){if(r)e.duration>r.latency?(r.entries=[e],r.latency=e.duration):e.duration===r.latency&&e.startTime===r.entries[0].startTime&&r.entries.push(e);else{var n={id:e.interactionId,latency:e.duration,entries:[e]};yO.set(n.id,n),gO.push(n)}gO.sort(function(e,t){return t.latency-e.latency}),gO.length>10&&gO.splice(10).forEach(function(e){return yO.delete(e.id)})}}},_O=function(e){var t=self.requestIdleCallback||self.setTimeout,r=-1;return e=Qx(e),"hidden"===document.visibilityState?e():(r=t(e),qx(e)),r},SO=[200,500],CO=[2500,4e3],EO={},TO=[800,1800],kO=function e(t){document.prerendering?oO(function(){return e(t)}):"complete"!==document.readyState?addEventListener("load",function(){return e(t)},!0):setTimeout(t,0)},xO={passive:!0,capture:!0},OO=new Date,AO=function(e,t){jx||(jx=t,zx=e,Vx=new Date,MO(removeEventListener),IO())},IO=function(){if(zx>=0&&zx1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?function(e,t){var r=function(){AO(e,t),s()},n=function(){s()},s=function(){removeEventListener("pointerup",r,xO),removeEventListener("pointercancel",n,xO)};addEventListener("pointerup",r,xO),addEventListener("pointercancel",n,xO)}(t,e):AO(t,e)}},MO=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach(function(t){return e(t,RO,xO)})},NO=[100,300],PO=Object.freeze({__proto__:null,CLSThresholds:cO,FCPThresholds:aO,FIDThresholds:NO,INPThresholds:SO,LCPThresholds:CO,TTFBThresholds:TO,onCLS:function(e,t){t=t||{},lO(Qx(function(){var r,n=Yx("CLS",0),s=0,i=[],o=function(e){e.forEach(function(e){if(!e.hadRecentInput){var t=i[0],r=i[i.length-1];s&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(s+=e.value,i.push(e)):(s=e.value,i=[e])}}),s>n.value&&(n.value=s,n.entries=i,r())},a=Xx("layout-shift",o);a&&(r=Jx(e,n,cO,t.reportAllChanges),qx(function(){o(a.takeRecords()),r(!0)}),Zx(function(){s=0,n=Yx("CLS",0),r=Jx(e,n,cO,t.reportAllChanges),Kx(function(){return r()})}),setTimeout(r,0))}))},onFCP:lO,onFID:function(e,t){t=t||{},oO(function(){var r,n=iO(),s=Yx("FID"),i=function(e){e.startTimethis.otel.emitSpan(...e),{captureExtensionErrors:e.captureExtensionErrors,debug:e.debug}),this.vitals=new Mx((e,t,r)=>this.otel.recordWebVital(e,t,r)),this.router=new Nx((e,t,r)=>this.otel.startRouteChange(e,t,r)),this._enabled&&(this.otel.configure(),this.replay.configure(),this.errors.start(),!1!==this.config.captureWebVitals&&this.vitals.start().catch(e=>{this.config.debug&&console.warn("Monoscope: web-vitals init failed",e)}),this.router.start()),this._enabled&&this.config.debug&&(this.logInitBanner(),Fx&&(this.overlay=new Lx,this.otel.onExportStatus=e=>this.overlay?.setConnectionStatus(e),this.otel.onSpanStart=()=>this.overlay?.incrementEvents())),Fx&&this.setupActivityTracking()}logInitBanner(){const e=this.config,t=e.exporterEndpoint||"https://otelcol.monoscope.tech/v1/traces",r=Math.round(100*(e.sampleRate??1)),n=Math.round(100*(e.replaySampleRate??1));console.groupCollapsed("%c[Monoscope] ✓ Initialized","color: #22c55e; font-weight: bold"),console.log(` API Key: ${e.apiKey}`),console.log(` Service: ${e.serviceName}`),console.log(` Session: ${this.sessionId}`),console.log(` Tracing: ✓ (sample rate: ${r}%)`),console.log(` Replay: ✓ (sample rate: ${n}%)`),console.log(" Errors: ✓"),console.log(` Endpoint: ${t}`),console.groupEnd()}resolveSessionId(){try{const e=sessionStorage.getItem("monoscope-session-id"),t=sessionStorage.getItem(Ux);if(e&&t){if(Date.now()-parseInt(t,10){this.config.debug&&console.warn("Monoscope: failed to save replay on session rotation",e)}),kx.length=0,this.sessionId=Ex();try{sessionStorage.setItem("monoscope-session-id",this.sessionId)}catch(e){this.config.debug&&console.warn("Monoscope: failed to persist session ID",e)}this.replay.updateSessionId(this.sessionId),this.otel.updateSessionId(this.sessionId),this.config.debug&&console.log("Monoscope: session rotated due to inactivity")}checkAndRefreshSession(){const e=Date.now();e-this.lastActivityTime>=Dx&&this.rotateSession(),this.lastActivityTime=e,this.persistActivity()}setupActivityTracking(){document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&this.checkAndRefreshSession()});let e=Date.now();const t=()=>{const t=Date.now();t-e>5e3&&(e=t,this.lastActivityTime=t,this.persistActivity())};document.addEventListener("click",e=>{t();const r=e.target;if(!r)return;const n=r.tagName?.toLowerCase()||"",s=(r.textContent||"").trim().slice(0,50),i=r.getAttribute("class")||"";xx({type:"click",message:`${n} "${s}"`,data:{selector:r.id?`#${r.id}`:i?`.${i.split(" ")[0]}`:n}})},{capture:!0,passive:!0}),document.addEventListener("keydown",t,{capture:!0,passive:!0})}getSessionId(){return this.sessionId}getTabId(){return this.tabId}setUser(e){if(this.config.debug){const t=new Set(["email","full_name","name","id","roles"]),r=Object.keys(e).filter(e=>!t.has(e));r.length&&console.warn(`Monoscope: unknown user attributes will be sent to collectors: ${r.join(", ")}`)}this.otel.setUser(e),this.replay.setUser(e)}startSpan(e,t){return this.otel.startSpan(e,t)}recordEvent(e,t){this.otel.recordEvent(e,t)}async test(){try{this.otel.emitSpan("monoscope.test",{"test.timestamp":Date.now()}),await this.otel.forceFlush();const e="Test span sent successfully.";return this.config.debug&&console.log(`[Monoscope] ${e}`),{success:!0,message:e}}catch(e){const t=`Test failed: ${e}`;return this.config.debug&&console.error(`[Monoscope] ${t}`),{success:!1,message:t}}}disable(){this._enabled=!1,this.replay.setEnabled(!1),this.otel.setEnabled(!1),this.vitals.setEnabled(!1),this.errors.stop(),this.router.stop()}enable(){this._enabled=!0,this.otel.setEnabled(!0),this.otel.configure(),this.replay.setEnabled(!0),this.replay.configure(),this.vitals.setEnabled(!0),this.vitals.start().catch(()=>{}),this.errors.start(),this.router.start()}isEnabled(){return this._enabled}async destroy(){this.errors.stop(),this.router.stop(),this.replay.stop(),this.vitals.setEnabled(!1);try{await this.otel.shutdown()}catch(e){console.warn("Monoscope: provider shutdown failed, some trace data may be lost",e)}this._enabled=!1}}}(); + */var X_=Object.defineProperty,J_=Object.defineProperties,K_=Object.getOwnPropertyDescriptors,q_=Object.getOwnPropertySymbols,Q_=Object.prototype.hasOwnProperty,eS=Object.prototype.propertyIsEnumerable,tS=(e,t,r)=>t in e?X_(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,rS=(e,t)=>{for(var r in t||(t={}))Q_.call(t,r)&&tS(e,r,t[r]);if(q_)for(var r of q_(t))eS.call(t,r)&&tS(e,r,t[r]);return e},nS=(e,t,r)=>(tS(e,"symbol"!=typeof t?t+"":t,r),r),sS=globalThis;function iS(e){return(sS.__Zone_symbol_prefix||"__zone_symbol__")+e}var oS=Object.getOwnPropertyDescriptor,aS=Object.defineProperty,lS=Object.getPrototypeOf,cS=Object.create,uS=Array.prototype.slice,hS="addEventListener",pS="removeEventListener",dS=iS(hS),fS=iS(pS),mS="true",gS="false",yS=iS("");function wS(e,t){return Zone.current.wrap(e,t)}function vS(e,t,r,n,s){return Zone.current.scheduleMacroTask(e,t,r,n,s)}var bS=iS,_S="undefined"!=typeof window,SS=_S?window:void 0,CS=_S&&SS||globalThis;function ES(e,t){for(let r=e.length-1;r>=0;r--)"function"==typeof e[r]&&(e[r]=wS(e[r],t+"_"+r));return e}function TS(e){return!e||!1!==e.writable&&!("function"==typeof e.get&&void 0===e.set)}var kS="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,xS=!("nw"in CS)&&void 0!==CS.process&&"[object process]"===CS.process.toString(),OS=!xS&&!kS&&!(!_S||!SS.HTMLElement),AS=void 0!==CS.process&&"[object process]"===CS.process.toString()&&!kS&&!(!_S||!SS.HTMLElement),IS={},RS=bS("enable_beforeunload"),MS=function(e){if(!(e=e||CS.event))return;let t=IS[e.type];t||(t=IS[e.type]=bS("ON_PROPERTY"+e.type));const r=this||e.target||CS,n=r[t];let s;if(OS&&r===SS&&"error"===e.type){const t=e;s=n&&n.call(this,t.message,t.filename,t.lineno,t.colno,t.error),!0===s&&e.preventDefault()}else s=n&&n.apply(this,arguments),"beforeunload"===e.type&&CS[RS]&&"string"==typeof s?e.returnValue=s:null==s||s||e.preventDefault();return s};function NS(e,t,r){let n=oS(e,t);if(!n&&r){oS(r,t)&&(n={enumerable:!0,configurable:!0})}if(!n||!n.configurable)return;const s=bS("on"+t+"patched");if(e.hasOwnProperty(s)&&e[s])return;delete n.writable,delete n.value;const i=n.get,o=n.set,a=t.slice(2);let l=IS[a];l||(l=IS[a]=bS("ON_PROPERTY"+a)),n.set=function(t){let r=this;if(r||e!==CS||(r=CS),!r)return;"function"==typeof r[l]&&r.removeEventListener(a,MS),null==o||o.call(r,null),r[l]=t,"function"==typeof t&&r.addEventListener(a,MS,!1)},n.get=function(){let r=this;if(r||e!==CS||(r=CS),!r)return null;const s=r[l];if(s)return s;if(i){let e=i.call(this);if(e)return n.set.call(this,e),"function"==typeof r.removeAttribute&&r.removeAttribute(t),e}return null},aS(e,t,n),e[s]=!0}function PS(e,t,r){if(t)for(let n=0;nfunction(t,n){const i=r(t,n);return i.cbIdx>=0&&"function"==typeof n[i.cbIdx]?vS(i.name,n[i.cbIdx],i,s):e.apply(t,n)})}function BS(e,t){e[bS("OriginalDelegate")]=t}function jS(e){return"function"==typeof e}function zS(e){return"number"==typeof e}var VS={useG:!0},GS={},HS={},ZS=new RegExp("^"+yS+"(\\w+)(true|false)$"),$S=bS("propagationStopped");function WS(e,t){const r=(t?t(e):e)+gS,n=(t?t(e):e)+mS,s=yS+r,i=yS+n;GS[e]={},GS[e][gS]=s,GS[e][mS]=i}function YS(e,t,r,n){const s=n&&n.add||hS,i=n&&n.rm||pS,o=n&&n.listeners||"eventListeners",a=n&&n.rmAll||"removeAllListeners",l=bS(s),c="."+s+":",u="prependListener",h="."+u+":",p=function(e,t,r){if(e.isRemoved)return;const n=e.callback;let s;"object"==typeof n&&n.handleEvent&&(e.callback=e=>n.handleEvent(e),e.originalDelegate=n);try{e.invoke(e,t,[r])}catch(e){s=e}const o=e.options;if(o&&"object"==typeof o&&o.once){const n=e.originalDelegate?e.originalDelegate:e.callback;t[i].call(t,r.type,n,o)}return s};function d(r,n,s){if(!(n=n||e.event))return;const i=r||n.target||e,o=i[GS[n.type][s?mS:gS]];if(o){const e=[];if(1===o.length){const t=p(o[0],i,n);t&&e.push(t)}else{const t=o.slice();for(let r=0;r{throw n})}}}const f=function(e){return d(this,e,!1)},m=function(e){return d(this,e,!0)};function g(t,r){if(!t)return!1;let n=!0;r&&void 0!==r.useG&&(n=r.useG);const p=r&&r.vh;let d=!0;r&&void 0!==r.chkDup&&(d=r.chkDup);let g=!1;r&&void 0!==r.rt&&(g=r.rt);let y=t;for(;y&&!y.hasOwnProperty(s);)y=lS(y);if(!y&&t[s]&&(y=t),!y)return!1;if(y[l])return!1;const w=r&&r.eventNameToString,v={},b=y[l]=y[s],_=y[bS(i)]=y[i],S=y[bS(o)]=y[o],C=y[bS(a)]=y[a];let E;function T(e,t){return t?"boolean"==typeof e?{capture:e,passive:!0}:e?"object"==typeof e&&!1!==e.passive?((e,t)=>J_(e,K_(t)))(rS({},e),{passive:!0}):e:{passive:!0}:e}r&&r.prepend&&(E=y[bS(r.prepend)]=y[r.prepend]);const k=function(e){return E.call(v.target,v.eventName,e.invoke,v.options)},x=n?function(e){if(!v.isExisting)return b.call(v.target,v.eventName,v.capture?m:f,v.options)}:function(e){return b.call(v.target,v.eventName,e.invoke,v.options)},O=n?function(e){if(!e.isRemoved){const t=GS[e.eventName];let r;t&&(r=t[e.capture?mS:gS]);const n=r&&e.target[r];if(n)for(let t=0;tL.zone.cancelTask(L);t.call(y,"abort",e,{once:!0}),L.removeAbortListener=()=>y.removeEventListener("abort",e)}return v.target=null,P&&(P.taskData=null),_&&(v.options.once=!0),"boolean"!=typeof L.options&&(L.options=g),L.target=c,L.capture=b,L.eventName=u,f&&(L.originalDelegate=h),l?x.unshift(L):x.push(L),a?c:void 0}};return y[s]=M(b,c,x,O,g),E&&(y[u]=M(E,h,k,O,g,!0)),y[i]=function(){const t=this||e;let n=arguments[0];r&&r.transferEventName&&(n=r.transferEventName(n));const s=arguments[2],i=!!s&&("boolean"==typeof s||s.capture),o=arguments[1];if(!o)return _.apply(this,arguments);if(p&&!p(_,o,t,arguments))return;const a=GS[n];let l;a&&(l=a[i?mS:gS]);const c=l&&t[l];if(c)for(let e=0;efunction(t,r){t[$S]=!0,e&&e.apply(t,r)})}var KS=bS("zoneTask");function qS(e,t,r,n){let s=null,i=null;r+=n;const o={};function a(t){const r=t.data;r.args[0]=function(){return t.invoke.apply(this,arguments)};const n=s.apply(e,r.args);return zS(n)?r.handleId=n:(r.handle=n,r.isRefreshable=jS(n.refresh)),t}function l(t){const{handle:r,handleId:n}=t.data;return i.call(e,null!=r?r:n)}s=US(e,t+=n,r=>function(s,i){var c;if(jS(i[0])){const e={isRefreshable:!1,isPeriodic:"Interval"===n,delay:"Timeout"===n||"Interval"===n?i[1]||0:void 0,args:i},r=i[0];i[0]=function(){try{return r.apply(this,arguments)}finally{const{handle:t,handleId:r,isPeriodic:n,isRefreshable:s}=e;n||s||(r?delete o[r]:t&&(t[KS]=null))}};const s=vS(t,i[0],e,a,l);if(!s)return s;const{handleId:u,handle:h,isRefreshable:p,isPeriodic:d}=s.data;if(u)o[u]=s;else if(h&&(h[KS]=s,p&&!d)){const e=h.refresh;h.refresh=function(){const{zone:t,state:r}=s;return"notScheduled"===r?(s._state="scheduled",t._updateTaskCount(s,1)):"running"===r&&(s._state="scheduling"),e.call(this)}}return null!=(c=null!=h?h:u)?c:s}return r.apply(e,i)}),i=US(e,r,t=>function(r,n){const s=n[0];let i;zS(s)?(i=o[s],delete o[s]):(i=null==s?void 0:s[KS],i?s[KS]=null:i=s),(null==i?void 0:i.type)?i.cancelFn&&i.zone.cancelTask(i):t.apply(e,n)})}function QS(e,t,r){if(!r||0===r.length)return t;const n=r.filter(t=>t.target===e);if(0===n.length)return t;const s=n[0].ignoreProperties;return t.filter(e=>-1===s.indexOf(e))}function eC(e,t,r,n){if(!e)return;PS(e,QS(e,t,r),n)}function tC(e){return Object.getOwnPropertyNames(e).filter(e=>e.startsWith("on")&&e.length>2).map(e=>e.substring(2))}function rC(e){e.__load_patch("ZoneAwarePromise",(e,t,r)=>{const n=Object.getOwnPropertyDescriptor,s=Object.defineProperty;const i=r.symbol,o=[],a=!1!==e[i("DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION")],l=i("Promise"),c=i("then");r.onUnhandledError=e=>{if(r.showUncaughtError()){const t=e&&e.rejection;t?console.error("Unhandled Promise rejection:",t instanceof Error?t.message:t,"; Zone:",e.zone.name,"; Task:",e.task&&e.task.source,"; Value:",t,t instanceof Error?t.stack:void 0):console.error(e)}},r.microtaskDrainDone=()=>{for(;o.length;){const e=o.shift();try{e.zone.runGuarded(()=>{if(e.throwOriginal)throw e.rejection;throw e})}catch(e){h(e)}}};const u=i("unhandledPromiseRejectionHandler");function h(e){r.onUnhandledError(e);try{const r=t[u];"function"==typeof r&&r.call(this,e)}catch(e){}}function p(e){return e&&"function"==typeof e.then}function d(e){return e}function f(e){return N.reject(e)}const m=i("state"),g=i("value"),y=i("finally"),w=i("parentPromiseValue"),v=i("parentPromiseState"),b=null,_=!0,S=!1;function C(e,t){return r=>{try{x(e,t,r)}catch(t){x(e,!1,t)}}}const E=function(){let e=!1;return function(t){return function(){e||(e=!0,t.apply(null,arguments))}}},T="Promise resolved with itself",k=i("currentTaskTrace");function x(e,n,i){const l=E();if(e===i)throw new TypeError(T);if(e[m]===b){let c=null;try{"object"!=typeof i&&"function"!=typeof i||(c=i&&i.then)}catch(t){return l(()=>{x(e,!1,t)})(),e}if(n!==S&&i instanceof N&&i.hasOwnProperty(m)&&i.hasOwnProperty(g)&&i[m]!==b)A(i),x(e,i[m],i[g]);else if(n!==S&&"function"==typeof c)try{c.call(i,l(C(e,n)),l(C(e,!1)))}catch(t){l(()=>{x(e,!1,t)})()}else{e[m]=n;const l=e[g];if(e[g]=i,e[y]===y&&n===_&&(e[m]=e[v],e[g]=e[w]),n===S&&i instanceof Error){const e=t.currentTask&&t.currentTask.data&&t.currentTask.data.__creationTrace__;e&&s(i,k,{configurable:!0,enumerable:!1,writable:!0,value:e})}for(let t=0;t{try{const n=e[g],s=!!r&&y===r[y];s&&(r[w]=n,r[v]=i);const a=t.run(o,void 0,s&&o!==f&&o!==d?[]:[n]);x(r,!0,a)}catch(e){x(r,!1,e)}},r)}const R=function(){},M=e.AggregateError;class N{static toString(){return"function ZoneAwarePromise() { [native code] }"}static resolve(e){return e instanceof N?e:x(new this(null),_,e)}static reject(e){return x(new this(null),S,e)}static withResolvers(){const e={};return e.promise=new N((t,r)=>{e.resolve=t,e.reject=r}),e}static any(e){if(!e||"function"!=typeof e[Symbol.iterator])return Promise.reject(new M([],"All promises were rejected"));const t=[];let r=0;try{for(let n of e)r++,t.push(N.resolve(n))}catch(e){return Promise.reject(new M([],"All promises were rejected"))}if(0===r)return Promise.reject(new M([],"All promises were rejected"));let n=!1;const s=[];return new N((e,i)=>{for(let o=0;o{n||(n=!0,e(t))},e=>{s.push(e),r--,0===r&&(n=!0,i(new M(s,"All promises were rejected")))})})}static race(e){let t,r,n=new this((e,n)=>{t=e,r=n});function s(e){t(e)}function i(e){r(e)}for(let t of e)p(t)||(t=this.resolve(t)),t.then(s,i);return n}static all(e){return N.allWithCallback(e)}static allSettled(e){return(this&&this.prototype instanceof N?this:N).allWithCallback(e,{thenCallback:e=>({status:"fulfilled",value:e}),errorCallback:e=>({status:"rejected",reason:e})})}static allWithCallback(e,t){let r,n,s=new this((e,t)=>{r=e,n=t}),i=2,o=0;const a=[];for(let s of e){p(s)||(s=this.resolve(s));const e=o;try{s.then(n=>{a[e]=t?t.thenCallback(n):n,i--,0===i&&r(a)},s=>{t?(a[e]=t.errorCallback(s),i--,0===i&&r(a)):n(s)})}catch(e){n(e)}i++,o++}return i-=2,0===i&&r(a),s}constructor(e){const t=this;if(!(t instanceof N))throw new Error("Must be an instanceof Promise.");t[m]=b,t[g]=[];try{const r=E();e&&e(r(C(t,_)),r(C(t,S)))}catch(e){x(t,!1,e)}}get[Symbol.toStringTag](){return"Promise"}get[Symbol.species](){return N}then(e,r){var n;let s=null==(n=this.constructor)?void 0:n[Symbol.species];s&&"function"==typeof s||(s=this.constructor||N);const i=new s(R),o=t.current;return this[m]==b?this[g].push(o,i,e,r):I(this,o,i,e,r),i}catch(e){return this.then(null,e)}finally(e){var r;let n=null==(r=this.constructor)?void 0:r[Symbol.species];n&&"function"==typeof n||(n=N);const s=new n(R);s[y]=y;const i=t.current;return this[m]==b?this[g].push(i,s,e,e):I(this,i,s,e,e),s}}N.resolve=N.resolve,N.reject=N.reject,N.race=N.race,N.all=N.all;const P=e[l]=e.Promise;e.Promise=N;const L=i("thenPatched");function D(e){const t=e.prototype,r=n(t,"then");if(r&&(!1===r.writable||!r.configurable))return;const s=t.then;t[c]=s,e.prototype.then=function(e,t){const r=new N((e,t)=>{s.call(this,e,t)});return r.then(e,t)},e[L]=!0}if(r.patchThen=D,P){D(P);const t=P.try;t&&"function"==typeof t&&(N.try=t),US(e,"fetch",e=>{return t=e,function(e,r){let n=t.apply(e,r);if(n instanceof N)return n;let s=n.constructor;return s[L]||D(s),n};var t})}return Promise[t.__symbol__("uncaughtPromiseErrors")]=o,N})}function nC(e,t,r,n,s){const i=Zone.__symbol__(n);if(t[i])return;const o=t[i]=t[n];t[n]=function(i,a,l){return a&&a.prototype&&s.forEach(function(t){const s=`${r}.${n}::`+t,i=a.prototype;try{if(i.hasOwnProperty(t)){const r=e.ObjectGetOwnPropertyDescriptor(i,t);r&&r.value?(r.value=e.wrapWithCurrentZone(r.value,s),e._redefineProperty(a.prototype,t,r)):i[t]&&(i[t]=e.wrapWithCurrentZone(i[t],s))}else i[t]&&(i[t]=e.wrapWithCurrentZone(i[t],s))}catch(e){}}),o.call(t,i,a,l)},e.attachOriginToPatched(t[n],o)}var sC,iC=function(){const e=globalThis,t=!0===e[iS("forceDuplicateZoneCheck")];if(e.Zone&&(t||"function"!=typeof e.Zone.__symbol__))throw new Error("Zone already loaded.");return null!=e.Zone||(e.Zone=function(){const e=sS.performance;function t(t){e&&e.mark&&e.mark(t)}function r(t,r){e&&e.measure&&e.measure(t,r)}t("Zone");const n=class e{constructor(e,t){nS(this,"_parent"),nS(this,"_name"),nS(this,"_properties"),nS(this,"_zoneDelegate"),this._parent=e,this._name=t?t.name||"unnamed":"",this._properties=t&&t.properties||{},this._zoneDelegate=new o(this,this._parent&&this._parent._zoneDelegate,t)}static assertZonePatched(){if(sS.Promise!==x.ZoneAwarePromise)throw new Error("Zone.js has detected that ZoneAwarePromise `(window|global).Promise` has been overwritten.\nMost likely cause is that a Promise polyfill has been loaded after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. If you must load one, do so before loading zone.js.)")}static get root(){let t=e.current;for(;t.parent;)t=t.parent;return t}static get current(){return A.zone}static get currentTask(){return I}static __load_patch(n,s,i=!1){if(x.hasOwnProperty(n)){const e=!0===sS[iS("forceDuplicateZoneCheck")];if(!i&&e)throw Error("Already loaded patch: "+n)}else if(!sS["__Zone_disable_"+n]){const i="Zone:"+n;t(i),x[n]=s(sS,e,O),r(i,i)}}get parent(){return this._parent}get name(){return this._name}get(e){const t=this.getZoneWith(e);if(t)return t._properties[e]}getZoneWith(e){let t=this;for(;t;){if(t._properties.hasOwnProperty(e))return t;t=t._parent}return null}fork(e){if(!e)throw new Error("ZoneSpec required!");return this._zoneDelegate.fork(this,e)}wrap(e,t){if("function"!=typeof e)throw new Error("Expecting function got: "+e);const r=this._zoneDelegate.intercept(this,e,t),n=this;return function(){return n.runGuarded(r,this,arguments,t)}}run(e,t,r,n){A={parent:A,zone:this};try{return this._zoneDelegate.invoke(this,e,t,r,n)}finally{A=A.parent}}runGuarded(e,t=null,r,n){A={parent:A,zone:this};try{try{return this._zoneDelegate.invoke(this,e,t,r,n)}catch(e){if(this._zoneDelegate.handleError(this,e))throw e}}finally{A=A.parent}}runTask(e,t,r){if(e.zone!=this)throw new Error("A task can only be run in the zone of creation! (Creation: "+(e.zone||y).name+"; Execution: "+this.name+")");const n=e,{type:s,data:{isPeriodic:i=!1,isRefreshable:o=!1}={}}=e;if(e.state===w&&(s===k||s===T))return;const a=e.state!=_;a&&n._transitionTo(_,b);const l=I;I=n,A={parent:A,zone:this};try{s!=T||!e.data||i||o||(e.cancelFn=void 0);try{return this._zoneDelegate.invokeTask(this,n,t,r)}catch(e){if(this._zoneDelegate.handleError(this,e))throw e}}finally{const t=e.state;if(t!==w&&t!==C)if(s==k||i||o&&t===v)a&&n._transitionTo(b,_,v);else{const e=n._zoneDelegates;this._updateTaskCount(n,-1),a&&n._transitionTo(w,_,w),o&&(n._zoneDelegates=e)}A=A.parent,I=l}}scheduleTask(e){if(e.zone&&e.zone!==this){let t=this;for(;t;){if(t===e.zone)throw Error(`can not reschedule task to ${this.name} which is descendants of the original zone ${e.zone.name}`);t=t.parent}}e._transitionTo(v,w);const t=[];e._zoneDelegates=t,e._zone=this;try{e=this._zoneDelegate.scheduleTask(this,e)}catch(t){throw e._transitionTo(C,v,w),this._zoneDelegate.handleError(this,t),t}return e._zoneDelegates===t&&this._updateTaskCount(e,1),e.state==v&&e._transitionTo(b,v),e}scheduleMicroTask(e,t,r,n){return this.scheduleTask(new a(E,e,t,r,n,void 0))}scheduleMacroTask(e,t,r,n,s){return this.scheduleTask(new a(T,e,t,r,n,s))}scheduleEventTask(e,t,r,n,s){return this.scheduleTask(new a(k,e,t,r,n,s))}cancelTask(e){if(e.zone!=this)throw new Error("A task can only be cancelled in the zone of creation! (Creation: "+(e.zone||y).name+"; Execution: "+this.name+")");if(e.state===b||e.state===_){e._transitionTo(S,b,_);try{this._zoneDelegate.cancelTask(this,e)}catch(t){throw e._transitionTo(C,S),this._zoneDelegate.handleError(this,t),t}return this._updateTaskCount(e,-1),e._transitionTo(w,S),e.runCount=-1,e}}_updateTaskCount(e,t){const r=e._zoneDelegates;-1==t&&(e._zoneDelegates=null);for(let n=0;ne.hasTask(r,n),onScheduleTask:(e,t,r,n)=>e.scheduleTask(r,n),onInvokeTask:(e,t,r,n,s,i)=>e.invokeTask(r,n,s,i),onCancelTask:(e,t,r,n)=>e.cancelTask(r,n)};class o{constructor(e,t,r){nS(this,"_zone"),nS(this,"_taskCounts",{microTask:0,macroTask:0,eventTask:0}),nS(this,"_parentDelegate"),nS(this,"_forkDlgt"),nS(this,"_forkZS"),nS(this,"_forkCurrZone"),nS(this,"_interceptDlgt"),nS(this,"_interceptZS"),nS(this,"_interceptCurrZone"),nS(this,"_invokeDlgt"),nS(this,"_invokeZS"),nS(this,"_invokeCurrZone"),nS(this,"_handleErrorDlgt"),nS(this,"_handleErrorZS"),nS(this,"_handleErrorCurrZone"),nS(this,"_scheduleTaskDlgt"),nS(this,"_scheduleTaskZS"),nS(this,"_scheduleTaskCurrZone"),nS(this,"_invokeTaskDlgt"),nS(this,"_invokeTaskZS"),nS(this,"_invokeTaskCurrZone"),nS(this,"_cancelTaskDlgt"),nS(this,"_cancelTaskZS"),nS(this,"_cancelTaskCurrZone"),nS(this,"_hasTaskDlgt"),nS(this,"_hasTaskDlgtOwner"),nS(this,"_hasTaskZS"),nS(this,"_hasTaskCurrZone"),this._zone=e,this._parentDelegate=t,this._forkZS=r&&(r&&r.onFork?r:t._forkZS),this._forkDlgt=r&&(r.onFork?t:t._forkDlgt),this._forkCurrZone=r&&(r.onFork?this._zone:t._forkCurrZone),this._interceptZS=r&&(r.onIntercept?r:t._interceptZS),this._interceptDlgt=r&&(r.onIntercept?t:t._interceptDlgt),this._interceptCurrZone=r&&(r.onIntercept?this._zone:t._interceptCurrZone),this._invokeZS=r&&(r.onInvoke?r:t._invokeZS),this._invokeDlgt=r&&(r.onInvoke?t:t._invokeDlgt),this._invokeCurrZone=r&&(r.onInvoke?this._zone:t._invokeCurrZone),this._handleErrorZS=r&&(r.onHandleError?r:t._handleErrorZS),this._handleErrorDlgt=r&&(r.onHandleError?t:t._handleErrorDlgt),this._handleErrorCurrZone=r&&(r.onHandleError?this._zone:t._handleErrorCurrZone),this._scheduleTaskZS=r&&(r.onScheduleTask?r:t._scheduleTaskZS),this._scheduleTaskDlgt=r&&(r.onScheduleTask?t:t._scheduleTaskDlgt),this._scheduleTaskCurrZone=r&&(r.onScheduleTask?this._zone:t._scheduleTaskCurrZone),this._invokeTaskZS=r&&(r.onInvokeTask?r:t._invokeTaskZS),this._invokeTaskDlgt=r&&(r.onInvokeTask?t:t._invokeTaskDlgt),this._invokeTaskCurrZone=r&&(r.onInvokeTask?this._zone:t._invokeTaskCurrZone),this._cancelTaskZS=r&&(r.onCancelTask?r:t._cancelTaskZS),this._cancelTaskDlgt=r&&(r.onCancelTask?t:t._cancelTaskDlgt),this._cancelTaskCurrZone=r&&(r.onCancelTask?this._zone:t._cancelTaskCurrZone),this._hasTaskZS=null,this._hasTaskDlgt=null,this._hasTaskDlgtOwner=null,this._hasTaskCurrZone=null;const n=r&&r.onHasTask,s=t&&t._hasTaskZS;(n||s)&&(this._hasTaskZS=n?r:i,this._hasTaskDlgt=t,this._hasTaskDlgtOwner=this,this._hasTaskCurrZone=this._zone,r.onScheduleTask||(this._scheduleTaskZS=i,this._scheduleTaskDlgt=t,this._scheduleTaskCurrZone=this._zone),r.onInvokeTask||(this._invokeTaskZS=i,this._invokeTaskDlgt=t,this._invokeTaskCurrZone=this._zone),r.onCancelTask||(this._cancelTaskZS=i,this._cancelTaskDlgt=t,this._cancelTaskCurrZone=this._zone))}get zone(){return this._zone}fork(e,t){return this._forkZS?this._forkZS.onFork(this._forkDlgt,this.zone,e,t):new s(e,t)}intercept(e,t,r){return this._interceptZS?this._interceptZS.onIntercept(this._interceptDlgt,this._interceptCurrZone,e,t,r):t}invoke(e,t,r,n,s){return this._invokeZS?this._invokeZS.onInvoke(this._invokeDlgt,this._invokeCurrZone,e,t,r,n,s):t.apply(r,n)}handleError(e,t){return!this._handleErrorZS||this._handleErrorZS.onHandleError(this._handleErrorDlgt,this._handleErrorCurrZone,e,t)}scheduleTask(e,t){let r=t;if(this._scheduleTaskZS)this._hasTaskZS&&r._zoneDelegates.push(this._hasTaskDlgtOwner),r=this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt,this._scheduleTaskCurrZone,e,t),r||(r=t);else if(t.scheduleFn)t.scheduleFn(t);else{if(t.type!=E)throw new Error("Task is missing scheduleFn.");m(t)}return r}invokeTask(e,t,r,n){return this._invokeTaskZS?this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt,this._invokeTaskCurrZone,e,t,r,n):t.callback.apply(r,n)}cancelTask(e,t){let r;if(this._cancelTaskZS)r=this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt,this._cancelTaskCurrZone,e,t);else{if(!t.cancelFn)throw Error("Task is not cancelable");r=t.cancelFn(t)}return r}hasTask(e,t){try{this._hasTaskZS&&this._hasTaskZS.onHasTask(this._hasTaskDlgt,this._hasTaskCurrZone,e,t)}catch(t){this.handleError(e,t)}}_updateTaskCount(e,t){const r=this._taskCounts,n=r[e],s=r[e]=n+t;if(s<0)throw new Error("More tasks executed then were scheduled.");if(0==n||0==s){const t={microTask:r.microTask>0,macroTask:r.macroTask>0,eventTask:r.eventTask>0,change:e};this.hasTask(this._zone,t)}}}class a{constructor(e,t,r,n,s,i){if(nS(this,"type"),nS(this,"source"),nS(this,"invoke"),nS(this,"callback"),nS(this,"data"),nS(this,"scheduleFn"),nS(this,"cancelFn"),nS(this,"_zone",null),nS(this,"runCount",0),nS(this,"_zoneDelegates",null),nS(this,"_state","notScheduled"),this.type=e,this.source=t,this.data=n,this.scheduleFn=s,this.cancelFn=i,!r)throw new Error("callback is not defined");this.callback=r;const o=this;e===k&&n&&n.useG?this.invoke=a.invokeTask:this.invoke=function(){return a.invokeTask.call(sS,o,this,arguments)}}static invokeTask(e,t,r){e||(e=this),R++;try{return e.runCount++,e.zone.runTask(e,t,r)}finally{1==R&&g(),R--}}get zone(){return this._zone}get state(){return this._state}cancelScheduleRequest(){this._transitionTo(w,v)}_transitionTo(e,t,r){if(this._state!==t&&this._state!==r)throw new Error(`${this.type} '${this.source}': can not transition to '${e}', expecting state '${t}'${r?" or '"+r+"'":""}, was '${this._state}'.`);this._state=e,e==w&&(this._zoneDelegates=null)}toString(){return this.data&&void 0!==this.data.handleId?this.data.handleId.toString():Object.prototype.toString.call(this)}toJSON(){return{type:this.type,state:this.state,source:this.source,zone:this.zone.name,runCount:this.runCount}}}const l=iS("setTimeout"),c=iS("Promise"),u=iS("then");let h,p=[],d=!1;function f(e){if(h||sS[c]&&(h=sS[c].resolve(0)),h){let t=h[u];t||(t=h.then),t.call(h,e)}else sS[l](e,0)}function m(e){0===R&&0===p.length&&f(g),e&&p.push(e)}function g(){if(!d){for(d=!0;p.length;){const e=p;p=[];for(let t=0;tA,onUnhandledError:M,microtaskDrainDone:M,scheduleMicroTask:m,showUncaughtError:()=>!s[iS("ignoreConsoleErrorUncaughtError")],patchEventTarget:()=>[],patchOnProperties:M,patchMethod:()=>M,bindArguments:()=>[],patchThen:()=>M,patchMacroTask:()=>M,patchEventPrototype:()=>M,getGlobalObjects:()=>{},ObjectDefineProperty:()=>M,ObjectGetOwnPropertyDescriptor:()=>{},ObjectCreate:()=>{},ArraySlice:()=>[],patchClass:()=>M,wrapWithCurrentZone:()=>M,filterProperties:()=>[],attachOriginToPatched:()=>M,_redefineProperty:()=>M,patchCallbacks:()=>M,nativeScheduleMicroTask:f};let A={parent:null,zone:new s(null,null)},I=null,R=0;function M(){}return r("Zone","Zone"),s}()),e.Zone}();rC(sC=iC),function(e){e.__load_patch("toString",e=>{const t=Function.prototype.toString,r=bS("OriginalDelegate"),n=bS("Promise"),s=bS("Error"),i=function(){if("function"==typeof this){const i=this[r];if(i)return"function"==typeof i?t.call(i):Object.prototype.toString.call(i);if(this===Promise){const r=e[n];if(r)return t.call(r)}if(this===Error){const r=e[s];if(r)return t.call(r)}}return t.call(this)};i[r]=t,Function.prototype.toString=i;const o=Object.prototype.toString;Object.prototype.toString=function(){return"function"==typeof Promise&&this instanceof Promise?"[object Promise]":o.call(this)}})}(sC),function(e){e.__load_patch("util",(e,t,r)=>{const n=tC(e);r.patchOnProperties=PS,r.patchMethod=US,r.bindArguments=ES,r.patchMacroTask=FS;const s=t.__symbol__("BLACK_LISTED_EVENTS"),i=t.__symbol__("UNPATCHED_EVENTS");e[i]&&(e[s]=e[i]),e[s]&&(t[s]=t[i]=e[s]),r.patchEventPrototype=JS,r.patchEventTarget=YS,r.ObjectDefineProperty=aS,r.ObjectGetOwnPropertyDescriptor=oS,r.ObjectCreate=cS,r.ArraySlice=uS,r.patchClass=DS,r.wrapWithCurrentZone=wS,r.filterProperties=QS,r.attachOriginToPatched=BS,r._redefineProperty=Object.defineProperty,r.patchCallbacks=nC,r.getGlobalObjects=()=>({globalSources:HS,zoneSymbolEventNames:GS,eventNames:n,isBrowser:OS,isMix:AS,isNode:xS,TRUE_STR:mS,FALSE_STR:gS,ZONE_SYMBOL_PREFIX:yS,ADD_EVENT_LISTENER_STR:hS,REMOVE_EVENT_LISTENER_STR:pS})})}(sC),function(e){e.__load_patch("timers",e=>{const t="set",r="clear";qS(e,t,r,"Timeout"),qS(e,t,r,"Interval"),qS(e,t,r,"Immediate")}),e.__load_patch("requestAnimationFrame",e=>{qS(e,"request","cancel","AnimationFrame"),qS(e,"mozRequest","mozCancel","AnimationFrame"),qS(e,"webkitRequest","webkitCancel","AnimationFrame")}),e.__load_patch("blocking",(e,t)=>{const r=["alert","prompt","confirm"];for(let n=0;nfunction(n,i){return t.current.run(r,e,i,s)})}}),e.__load_patch("EventTarget",(e,t,r)=>{!function(e,t){t.patchEventPrototype(e,t)}(e,r),function(e,t){if(Zone[t.symbol("patchEventTarget")])return;const{eventNames:r,zoneSymbolEventNames:n,TRUE_STR:s,FALSE_STR:i,ZONE_SYMBOL_PREFIX:o}=t.getGlobalObjects();for(let e=0;e{DS("MutationObserver"),DS("WebKitMutationObserver")}),e.__load_patch("IntersectionObserver",(e,t,r)=>{DS("IntersectionObserver")}),e.__load_patch("FileReader",(e,t,r)=>{DS("FileReader")}),e.__load_patch("on_property",(e,t,r)=>{!function(e,t){if(xS&&!AS)return;if(Zone[e.symbol("patchEvents")])return;const r=t.__Zone_ignore_on_properties;let n=[];if(OS){const e=window;n=n.concat(["Document","SVGElement","Element","HTMLElement","HTMLBodyElement","HTMLMediaElement","HTMLFrameSetElement","HTMLFrameElement","HTMLIFrameElement","HTMLMarqueeElement","Worker"]),eC(e,tC(e),r,lS(e))}n=n.concat(["XMLHttpRequest","XMLHttpRequestEventTarget","IDBIndex","IDBRequest","IDBOpenDBRequest","IDBDatabase","IDBTransaction","IDBCursor","WebSocket"]);for(let e=0;e{!function(e,t){const{isBrowser:r,isMix:n}=t.getGlobalObjects();if(!r&&!n||!e.customElements||!("customElements"in e))return;t.patchCallbacks(t,e.customElements,"customElements","define",["connectedCallback","disconnectedCallback","adoptedCallback","attributeChangedCallback","formAssociatedCallback","formDisabledCallback","formResetCallback","formStateRestoreCallback"])}(e,r)}),e.__load_patch("XHR",(e,t)=>{!function(e){const l=e.XMLHttpRequest;if(!l)return;const c=l.prototype;let u=c[dS],h=c[fS];if(!u){const t=e.XMLHttpRequestEventTarget;if(t){const e=t.prototype;u=e[dS],h=e[fS]}}const p="readystatechange",d="scheduled";function f(e){const n=e.data,o=n.target;o[i]=!1,o[a]=!1;const l=o[s];u||(u=o[dS],h=o[fS]),l&&h.call(o,p,l);const c=o[s]=()=>{if(o.readyState===o.DONE)if(!n.aborted&&o[i]&&e.state===d){const r=o[t.__symbol__("loadfalse")];if(0!==o.status&&r&&r.length>0){const s=e.invoke;e.invoke=function(){const r=o[t.__symbol__("loadfalse")];for(let t=0;tfunction(e,t){return e[n]=0==t[2],e[o]=t[1],y.apply(e,t)}),w=bS("fetchTaskAborting"),v=bS("fetchTaskScheduling"),b=US(c,"send",()=>function(e,r){if(!0===t.current[v])return b.apply(e,r);if(e[n])return b.apply(e,r);{const t={target:e,url:e[o],isPeriodic:!1,args:r,aborted:!1},n=vS("XMLHttpRequest.send",m,t,f,g);e&&!0===e[a]&&!t.aborted&&n.state===d&&n.invoke()}}),_=US(c,"abort",()=>function(e,n){const s=e[r];if(s&&"string"==typeof s.type){if(null==s.cancelFn||s.data&&s.data.aborted)return;s.zone.cancelTask(s)}else if(!0===t.current[w])return _.apply(e,n)})}(e);const r=bS("xhrTask"),n=bS("xhrSync"),s=bS("xhrListener"),i=bS("xhrScheduled"),o=bS("xhrURL"),a=bS("xhrErrorBeforeScheduled")}),e.__load_patch("geolocation",e=>{e.navigator&&e.navigator.geolocation&&function(e,t){const r=e.constructor.name;for(let n=0;n{const t=function(){return e.apply(this,ES(arguments,r+"."+s))};return BS(t,e),t})(i)}}}(e.navigator.geolocation,["getCurrentPosition","watchPosition"])}),e.__load_patch("PromiseRejectionEvent",(e,t)=>{function r(t){return function(r){XS(e,t).forEach(n=>{const s=e.PromiseRejectionEvent;if(s){const e=new s(t,{promise:r.promise,reason:r.rejection});n.invoke(e)}})}}e.PromiseRejectionEvent&&(t[bS("unhandledPromiseRejectionHandler")]=r("unhandledrejection"),t[bS("rejectionHandledHandler")]=r("rejectionhandled"))}),e.__load_patch("queueMicrotask",(e,t,r)=>{!function(e,t){t.patchMethod(e,"queueMicrotask",e=>function(e,t){Zone.current.scheduleMicroTask("queueMicrotask",t[0])})}(e,r)})}(iC);const oC=fw("OpenTelemetry SDK Context Key SUPPRESS_TRACING");let aC=e=>{av.error(function(e){return"string"==typeof e?e:JSON.stringify(function(e){const t={};let r=e;for(;null!==r;)Object.getOwnPropertyNames(r).forEach(e=>{if(t[e])return;const n=r[e];n&&(t[e]=String(n))}),r=Object.getPrototypeOf(r);return t}(e))}(e))};function lC(e){try{aC(e)}catch{}}const cC="object"==typeof globalThis?globalThis:"object"==typeof self?self:"object"==typeof window?window:"object"==typeof global?global:{},uC=performance,hC="process.runtime.name",pC={[Wv]:"opentelemetry",[hC]:"browser",[Zv]:$v,[Yv]:"2.0.1"};const dC=Math.pow(10,6),fC=Math.pow(10,9);function mC(e){const t=e/1e3;return[Math.trunc(t),Math.round(e%1e3*dC)]}function gC(){let e=uC.timeOrigin;if("number"!=typeof e){const t=uC;e=t.timing&&t.timing.fetchStart}return e}function yC(e){return function(e,t){const r=[e[0]+t[0],e[1]+t[1]];r[1]>=fC&&(r[1]-=fC,r[0]+=1);return r}(mC(gC()),mC("number"==typeof e?e:uC.now()))}function wC(e){if(t=e,Array.isArray(t)&&2===t.length&&"number"==typeof t[0]&&"number"==typeof t[1])return e;if("number"==typeof e)return e{ov.with(function(e){return e.setValue(oC,!0)}(ov.active()),()=>{e.export(t,e=>{r(e)})})})}};const TC=e=>null!==e&&"object"==typeof e&&"function"==typeof e.then;class kC{_rawAttributes;_asyncAttributesPending=!1;_memoizedAttributes;static FromAttributeList(e){const t=new kC({});return t._rawAttributes=OC(e),t._asyncAttributesPending=e.filter(([e,t])=>TC(t)).length>0,t}constructor(e){const t=e.attributes??{};this._rawAttributes=Object.entries(t).map(([e,t])=>(TC(t)&&(this._asyncAttributesPending=!0),[e,t])),this._rawAttributes=OC(this._rawAttributes)}get asyncAttributesPending(){return this._asyncAttributesPending}async waitForAsyncAttributes(){if(this.asyncAttributesPending){for(let e=0;eTC(t)?[e,t.catch(t=>{av.debug("promise rejection for resource attribute: %s - %s",e,t)})]:[e,t])}var AC;!function(e){e.CONNECT_END="connectEnd",e.CONNECT_START="connectStart",e.DECODED_BODY_SIZE="decodedBodySize",e.DOM_COMPLETE="domComplete",e.DOM_CONTENT_LOADED_EVENT_END="domContentLoadedEventEnd",e.DOM_CONTENT_LOADED_EVENT_START="domContentLoadedEventStart",e.DOM_INTERACTIVE="domInteractive",e.DOMAIN_LOOKUP_END="domainLookupEnd",e.DOMAIN_LOOKUP_START="domainLookupStart",e.ENCODED_BODY_SIZE="encodedBodySize",e.FETCH_START="fetchStart",e.LOAD_EVENT_END="loadEventEnd",e.LOAD_EVENT_START="loadEventStart",e.NAVIGATION_START="navigationStart",e.REDIRECT_END="redirectEnd",e.REDIRECT_START="redirectStart",e.REQUEST_START="requestStart",e.RESPONSE_END="responseEnd",e.RESPONSE_START="responseStart",e.SECURE_CONNECTION_START="secureConnectionStart",e.START_TIME="startTime",e.UNLOAD_EVENT_END="unloadEventEnd",e.UNLOAD_EVENT_START="unloadEventStart"}(AC||(AC={}));let IC;function RC(e,t,r,n=!0){if(!(s=r,i=t,!(i in s)||"number"!=typeof r[t]||n&&0===r[t]))return e.addEvent(t,r[t]);var s,i}function MC(e,t,r=!1,n,s){if(void 0===n&&(n=0!==t[AC.START_TIME]),r||(RC(e,AC.FETCH_START,t,n),RC(e,AC.DOMAIN_LOOKUP_START,t,n),RC(e,AC.DOMAIN_LOOKUP_END,t,n),RC(e,AC.CONNECT_START,t,n),RC(e,AC.SECURE_CONNECTION_START,t,n),RC(e,AC.CONNECT_END,t,n),RC(e,AC.REQUEST_START,t,n),RC(e,AC.RESPONSE_START,t,n),RC(e,AC.RESPONSE_END,t,n)),!s){const r=t[AC.ENCODED_BODY_SIZE];void 0!==r&&e.setAttribute("http.response_content_length",r);const n=t[AC.DECODED_BODY_SIZE];void 0!==n&&r!==n&&e.setAttribute("http.response_content_length_uncompressed",n)}}function NC(){return"undefined"!=typeof location?location.origin:void 0}function PC(e,t,r,n,s=new WeakSet,i){const o=LC(e),a=function(e,t,r,n,s,i){const o=vC(t),a=vC(r);let l=n.filter(t=>{const r=vC(wC(t[AC.FETCH_START])),n=vC(wC(t[AC.RESPONSE_END]));return t.initiatorType.toLowerCase()===(i||"xmlhttprequest")&&t.name===e&&r>=o&&n<=a});l.length>0&&(l=l.filter(e=>!s.has(e)));return l}(e=o.toString(),t,r,n,s,i);if(0===a.length)return{mainRequest:void 0};if(1===a.length)return{mainRequest:a[0]};const l=function(e){return e.slice().sort((e,t)=>{const r=e[AC.FETCH_START],n=t[AC.FETCH_START];return r>n?1:r1){let e=l[0],t=function(e,t,r){const n=vC(r),s=vC(wC(t));let i,o=e[1];const a=e.length;for(let t=1;t=s&&(!i||lSC(e,t))}var UC;!function(e){e.METHOD_OPEN="open",e.METHOD_SEND="send",e.EVENT_ABORT="abort",e.EVENT_ERROR="error",e.EVENT_LOAD="loaded",e.EVENT_TIMEOUT="timeout"}(UC||(UC={}));const FC=av.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-xml-http-request/utils"});function BC(e){return t=e,"undefined"!=typeof Document&&t instanceof Document?(new XMLSerializer).serializeToString(document).length:"string"==typeof e?zC(e):e instanceof Blob?e.size:e instanceof FormData?function(e){let t=0;for(const[r,n]of e.entries())t+=r.length,n instanceof Blob?t+=n.size:t+=n.length;return t}(e):e instanceof URLSearchParams?zC(e.toString()):void 0!==e.byteLength?e.byteLength:void FC.warn("unknown body type");var t}const jC=new TextEncoder;function zC(e){return jC.encode(e).byteLength}function VC(e){const t=function(){void 0===HC&&(HC=GC);return HC}(),r=e.toUpperCase();return r in t?r:"_OTHER"}const GC={CONNECT:!0,DELETE:!0,GET:!0,HEAD:!0,OPTIONS:!0,PATCH:!0,POST:!0,PUT:!0,TRACE:!0};let HC;const ZC={"https:":"443","http:":"80"};const $C="0.203.0";var WC;!function(e){e.HTTP_STATUS_TEXT="http.status_text"}(WC||(WC={}));class YC extends F_{component="xml-http-request";version=$C;moduleName=this.component;_tasksCount=0;_xhrMem=new WeakMap;_usedResources=new WeakSet;_semconvStability;constructor(e={}){super("@opentelemetry/instrumentation-xml-http-request",$C,e),this._semconvStability=G_("http",e?.semconvStabilityOptIn)}init(){}_addHeaders(e,t){if(!DC(LC(t).href,this.getConfig().propagateTraceHeaderCorsUrls)){const e={};return bv.inject(ov.active(),e),void(Object.keys(e).length>0&&this._diag.debug("headers inject skipped due to CORS policy"))}const r={};bv.inject(ov.active(),r),Object.keys(r).forEach(t=>{e.setRequestHeader(t,String(r[t]))})}_addChildSpan(e,t){ov.with(Cv.setSpan(ov.active(),e),()=>{const e=this.tracer.startSpan("CORS Preflight",{startTime:t[AC.FETCH_START]}),r=!(this._semconvStability&z_.OLD);MC(e,t,this.getConfig().ignoreNetworkEvents,void 0,r),e.end(t[AC.RESPONSE_END])})}_addFinalSpanAttributes(e,t,r){if(this._semconvStability&z_.OLD){if(void 0!==t.status&&e.setAttribute("http.status_code",t.status),void 0!==t.statusText&&e.setAttribute(WC.HTTP_STATUS_TEXT,t.statusText),"string"==typeof r){const t=LC(r);e.setAttribute("http.host",t.host),e.setAttribute("http.scheme",t.protocol.replace(":",""))}e.setAttribute("http.user_agent",navigator.userAgent)}this._semconvStability&z_.STABLE&&t.status&&e.setAttribute(zv,t.status)}_applyAttributesAfterXHR(e,t){const r=this.getConfig().applyCustomAttributesOnSpan;"function"==typeof r&&B_(()=>r(e,t),e=>{e&&this._diag.error("applyCustomAttributesOnSpan",e)})}_addResourceObserver(e,t){const r=this._xhrMem.get(e);r&&"function"==typeof PerformanceObserver&&"function"==typeof PerformanceResourceTiming&&(r.createdResources={observer:new PerformanceObserver(e=>{const n=e.getEntries(),s=LC(t);n.forEach(e=>{"xmlhttprequest"===e.initiatorType&&e.name===s.href&&r.createdResources&&r.createdResources.entries.push(e)})}),entries:[]},r.createdResources.observer.observe({entryTypes:["resource"]}))}_clearResources(){0===this._tasksCount&&this.getConfig().clearTimingResources&&(uC.clearResourceTimings(),this._xhrMem=new WeakMap,this._usedResources=new WeakSet)}_findResourceAndAddNetworkEvents(e,t,r,n,s){if(!(r&&n&&s&&e.createdResources))return;let i=e.createdResources.entries;i&&i.length||(i=uC.getEntriesByType("resource"));const o=PC(LC(r).href,n,s,i,this._usedResources);if(o.mainRequest){const e=o.mainRequest;this._markResourceAsUsed(e);const r=o.corsPreFlightRequest;r&&(this._addChildSpan(t,r),this._markResourceAsUsed(r));const n=!(this._semconvStability&z_.OLD);MC(t,e,this.getConfig().ignoreNetworkEvents,void 0,n)}}_cleanPreviousSpanInformation(e){const t=this._xhrMem.get(e);if(t){const r=t.callbackToRemoveEvents;r&&r(),this._xhrMem.delete(e)}}_createSpan(e,t,r){if(CC(t,this.getConfig().ignoreUrls))return void this._diag.debug("ignoring span as url matches ignored url");let n="";const s=LC(t),i={};if(this._semconvStability&z_.OLD&&(n=r.toUpperCase(),i["http.method"]=r,i["http.url"]=s.toString()),this._semconvStability&z_.STABLE){const e=r,t=VC(r);n||(n=t),i[Bv]=t,t!==e&&(i[jv]=e),i[Xv]=s.toString(),i[Vv]=s.hostname;const o=function(e){const t=Number(e.port||ZC[e.protocol]);return t&&!isNaN(t)?t:void 0}(s);o&&(i[Gv]=o)}const o=this.tracer.startSpan(n,{kind:sv.CLIENT,attributes:i});return o.addEvent(UC.METHOD_OPEN),this._cleanPreviousSpanInformation(e),this._xhrMem.set(e,{span:o,spanUrl:t}),o}_markResourceAsUsed(e){this._usedResources.add(e)}_patchOpen(){return e=>{const t=this;return function(...r){const n=r[0],s=r[1];return t._createSpan(this,s,n),e.apply(this,r)}}}_patchSend(){const e=this;function t(t,r,n,s){const i=e._xhrMem.get(r);if(!i)return;if(i.status=r.status,i.statusText=r.statusText,e._xhrMem.delete(r),i.span){const t=i.span;e._applyAttributesAfterXHR(t,r),e._semconvStability&z_.STABLE&&(n?s&&(t.setStatus({code:iv.ERROR,message:s}),t.setAttribute(Dv,s)):i.status&&i.status>=400&&(t.setStatus({code:iv.ERROR}),t.setAttribute(Dv,String(i.status))))}const o=yC(),a=Date.now();setTimeout(()=>{!function(t,r,n,s){const i=r.callbackToRemoveEvents;"function"==typeof i&&i();const{span:o,spanUrl:a,sendStartTime:l}=r;o&&(e._findResourceAndAddNetworkEvents(r,o,a,l,n),o.addEvent(t,s),e._addFinalSpanAttributes(o,r,a),o.end(s),e._tasksCount--),e._clearResources()}(t,i,o,a)},300)}function r(){t(UC.EVENT_ERROR,this,!0,"error")}function n(){t(UC.EVENT_ABORT,this,!1)}function s(){t(UC.EVENT_TIMEOUT,this,!0,"timeout")}function i(){this.status<299?t(UC.EVENT_LOAD,this,!1):t(UC.EVENT_ERROR,this,!1)}return t=>function(...o){const a=e._xhrMem.get(this);if(!a)return t.apply(this,o);const l=a.span,c=a.spanUrl;if(l&&c){if(e.getConfig().measureRequestSize&&o?.[0]){const t=BC(o[0]);void 0!==t&&(e._semconvStability&z_.OLD&&l.setAttribute("http.request_content_length_uncompressed",t),e._semconvStability&z_.STABLE&&l.setAttribute("http.request.body.size",t))}ov.with(Cv.setSpan(ov.active(),l),()=>{e._tasksCount++,a.sendStartTime=yC(),l.addEvent(UC.METHOD_SEND),this.addEventListener("abort",n),this.addEventListener("error",r),this.addEventListener("load",i),this.addEventListener("timeout",s),a.callbackToRemoveEvents=()=>{!function(t){t.removeEventListener("abort",n),t.removeEventListener("error",r),t.removeEventListener("load",i),t.removeEventListener("timeout",s);const o=e._xhrMem.get(t);o&&(o.callbackToRemoveEvents=void 0)}(this),a.createdResources&&a.createdResources.observer.disconnect()},e._addHeaders(this,c),e._addResourceObserver(this,c)})}return t.apply(this,o)}}enable(){this._diag.debug("applying patch to",this.moduleName,this.version),j_(XMLHttpRequest.prototype.open)&&(this._unwrap(XMLHttpRequest.prototype,"open"),this._diag.debug("removing previous patch from method open")),j_(XMLHttpRequest.prototype.send)&&(this._unwrap(XMLHttpRequest.prototype,"send"),this._diag.debug("removing previous patch from method send")),this._wrap(XMLHttpRequest.prototype,"open",this._patchOpen()),this._wrap(XMLHttpRequest.prototype,"send",this._patchSend())}disable(){this._diag.debug("removing patch from",this.moduleName,this.version),this._unwrap(XMLHttpRequest.prototype,"open"),this._unwrap(XMLHttpRequest.prototype,"send"),this._tasksCount=0,this._xhrMem=new WeakMap,this._usedResources=new WeakSet}}var XC;!function(e){e.COMPONENT="component",e.HTTP_STATUS_TEXT="http.status_text"}(XC||(XC={}));var JC={};Object.defineProperty(JC,"__esModule",{value:!0});var KC=JC.ATTR_HTTP_USER_AGENT=JC.ATTR_HTTP_URL=JC.ATTR_HTTP_STATUS_CODE=JC.ATTR_HTTP_SCHEME=JC.ATTR_HTTP_RESPONSE_CONTENT_LENGTH=JC.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED=JC.ATTR_HTTP_REQUEST_BODY_SIZE=JC.ATTR_HTTP_METHOD=JC.ATTR_HTTP_HOST=void 0,qC=JC.ATTR_HTTP_HOST="http.host",QC=JC.ATTR_HTTP_METHOD="http.method",eE=JC.ATTR_HTTP_REQUEST_BODY_SIZE="http.request.body.size",tE=JC.ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED="http.request_content_length_uncompressed";JC.ATTR_HTTP_RESPONSE_CONTENT_LENGTH="http.response_content_length";var rE=JC.ATTR_HTTP_SCHEME="http.scheme",nE=JC.ATTR_HTTP_STATUS_CODE="http.status_code",sE=JC.ATTR_HTTP_URL="http.url";KC=JC.ATTR_HTTP_USER_AGENT="http.user_agent";const iE=av.createComponentLogger({namespace:"@opentelemetry/opentelemetry-instrumentation-fetch/utils"});function oE(...e){if(e[0]instanceof URL||"string"==typeof e[0]){const t=e[1];if(!t?.body)return Promise.resolve();if(t.body instanceof ReadableStream){const{body:e,length:r}=function(e){if(!e.pipeThrough)return iE.warn("Platform has ReadableStream but not pipeThrough!"),{body:e,length:Promise.resolve(void 0)};let t,r=0;const n=new Promise(e=>{t=e}),s=new TransformStream({start(){},async transform(e,t){const n=await e;r+=n.byteLength,t.enqueue(e)},flush(){t(r)}});return{body:e.pipeThrough(s),length:n}}(t.body);return t.body=e,r}return Promise.resolve(function(e){if(t=e,"undefined"!=typeof Document&&t instanceof Document)return(new XMLSerializer).serializeToString(document).length;var t;if("string"==typeof e)return lE(e);if(e instanceof Blob)return e.size;if(e instanceof FormData)return function(e){let t=0;for(const[r,n]of e.entries())t+=r.length,n instanceof Blob?t+=n.size:t+=n.length;return t}(e);if(e instanceof URLSearchParams)return lE(e.toString());if(void 0!==e.byteLength)return e.byteLength;return void iE.warn("unknown body type")}(t.body))}{const t=e[0];return t?.body?t.clone().text().then(e=>lE(e)):Promise.resolve()}}const aE=new TextEncoder;function lE(e){return aE.encode(e).byteLength}const cE={CONNECT:!0,DELETE:!0,GET:!0,HEAD:!0,OPTIONS:!0,PATCH:!0,POST:!0,PUT:!0,TRACE:!0};let uE;function hE(){return void 0===uE&&(uE=cE),uE}const pE={"https:":"443","http:":"80"};const dE="0.203.0",fE="object"==typeof process&&"node"===process.release?.name;class mE extends F_{component="fetch";version=dE;moduleName=this.component;_usedResources=new WeakSet;_tasksCount=0;_semconvStability;constructor(e={}){super("@opentelemetry/instrumentation-fetch",dE,e),this._semconvStability=G_("http",e?.semconvStabilityOptIn)}init(){}_addChildSpan(e,t){const r=this.tracer.startSpan("CORS Preflight",{startTime:t[AC.FETCH_START]},Cv.setSpan(ov.active(),e)),n=!(this._semconvStability&z_.OLD);MC(r,t,this.getConfig().ignoreNetworkEvents,void 0,n),r.end(t[AC.RESPONSE_END])}_addFinalSpanAttributes(e,t){const r=LC(t.url);if(this._semconvStability&z_.OLD&&(e.setAttribute(nE,t.status),null!=t.statusText&&e.setAttribute(XC.HTTP_STATUS_TEXT,t.statusText),e.setAttribute(qC,r.host),e.setAttribute(rE,r.protocol.replace(":","")),"undefined"!=typeof navigator&&e.setAttribute(KC,navigator.userAgent)),this._semconvStability&z_.STABLE){e.setAttribute(zv,t.status),e.setAttribute(Vv,r.hostname);const n=function(e){const t=Number(e.port||pE[e.protocol]);return t&&!isNaN(t)?t:void 0}(r);n&&e.setAttribute(Gv,n)}}_addHeaders(e,t){if(!DC(t,this.getConfig().propagateTraceHeaderCorsUrls)){const e={};return bv.inject(ov.active(),e),void(Object.keys(e).length>0&&this._diag.debug("headers inject skipped due to CORS policy"))}if(e instanceof Request)bv.inject(ov.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else if(e.headers instanceof Headers)bv.inject(ov.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else if(e.headers instanceof Map)bv.inject(ov.active(),e.headers,{set:(e,t,r)=>e.set(t,"string"==typeof r?r:String(r))});else{const t={};bv.inject(ov.active(),t),e.headers=Object.assign({},t,e.headers||{})}}_clearResources(){0===this._tasksCount&&this.getConfig().clearTimingResources&&(performance.clearResourceTimings(),this._usedResources=new WeakSet)}_createSpan(e,t={}){if(CC(e,this.getConfig().ignoreUrls))return void this._diag.debug("ignoring span as url matches ignored url");let r="";const n={};if(this._semconvStability&z_.OLD){const s=(t.method||"GET").toUpperCase();r=`HTTP ${s}`,n[XC.COMPONENT]=this.moduleName,n[QC]=s,n[sE]=e}if(this._semconvStability&z_.STABLE){const s=t.method,i=function(e){const t=hE(),r=e.toUpperCase();return r in t?r:"_OTHER"}(t.method||"GET");r||(r=i),n[Bv]=i,i!==s&&(n[jv]=s),n[Xv]=e}return this.tracer.startSpan(r,{kind:sv.CLIENT,attributes:n})}_findResourceAndAddNetworkEvents(e,t,r){let n=t.entries;if(!n.length){if(!performance.getEntriesByType)return;n=performance.getEntriesByType("resource")}const s=PC(t.spanUrl,t.startTime,r,n,this._usedResources,"fetch");if(s.mainRequest){const t=s.mainRequest;this._markResourceAsUsed(t);const r=s.corsPreFlightRequest;r&&(this._addChildSpan(e,r),this._markResourceAsUsed(r));const n=!(this._semconvStability&z_.OLD);MC(e,t,this.getConfig().ignoreNetworkEvents,void 0,n)}}_markResourceAsUsed(e){this._usedResources.add(e)}_endSpan(e,t,r){const n=mC(Date.now()),s=yC();this._addFinalSpanAttributes(e,r),this._semconvStability&z_.STABLE&&r.status>=400&&(e.setStatus({code:iv.ERROR}),e.setAttribute(Dv,String(r.status))),setTimeout(()=>{t.observer?.disconnect(),this._findResourceAndAddNetworkEvents(e,t,s),this._tasksCount--,this._clearResources(),e.end(n)},300)}_patchConstructor(){return e=>{const t=this;return function(...r){const n=this,s=LC(r[0]instanceof Request?r[0].url:String(r[0])).href,i=r[0]instanceof Request?r[0]:r[1]||{},o=t._createSpan(s,i);if(!o)return e.apply(this,r);const a=t._prepareSpanData(s);function l(e,r){t._applyAttributesAfterFetch(e,i,r),t._endSpan(e,a,{status:r.status||0,statusText:r.message,url:s})}function c(e,r){t._applyAttributesAfterFetch(e,i,r),r.status>=200&&r.status<400?t._endSpan(e,a,r):t._endSpan(e,a,{status:r.status,statusText:r.statusText,url:s})}function u(e,t,r){try{const t=r.clone().body;if(t){const n=t.getReader(),s=()=>{n.read().then(({done:t})=>{t?c(e,r):s()},t=>{l(e,t)})};s()}else c(e,r)}finally{t(r)}}function h(e,t,r){try{l(e,r)}finally{t(r)}}return t.getConfig().measureRequestSize&&oE(...r).then(e=>{e&&(t._semconvStability&z_.OLD&&o.setAttribute(tE,e),t._semconvStability&z_.STABLE&&o.setAttribute(eE,e))}).catch(e=>{t._diag.warn("getFetchBodyLength",e)}),new Promise((r,a)=>ov.with(Cv.setSpan(ov.active(),o),()=>(t._addHeaders(i,s),t._callRequestHook(o,i),t._tasksCount++,e.apply(n,i instanceof Request?[i]:[s,i]).then(u.bind(n,o,r),h.bind(n,o,a)))))}}}_applyAttributesAfterFetch(e,t,r){const n=this.getConfig().applyCustomAttributesOnSpan;n&&B_(()=>n(e,t,r),e=>{e&&this._diag.error("applyCustomAttributesOnSpan",e)})}_callRequestHook(e,t){const r=this.getConfig().requestHook;r&&B_(()=>r(e,t),e=>{e&&this._diag.error("requestHook",e)})}_prepareSpanData(e){const t=yC(),r=[];if("function"!=typeof PerformanceObserver)return{entries:r,startTime:t,spanUrl:e};const n=new PerformanceObserver(t=>{t.getEntries().forEach(t=>{"fetch"===t.initiatorType&&t.name===e&&r.push(t)})});return n.observe({entryTypes:["resource"]}),{entries:r,observer:n,startTime:t,spanUrl:e}}enable(){fE?this._diag.warn("this instrumentation is intended for web usage only, it does not instrument Node.js's fetch()"):(j_(fetch)&&(this._unwrap(cC,"fetch"),this._diag.debug("removing previous patch for constructor")),this._wrap(cC,"fetch",this._patchConstructor()))}disable(){fE||(this._unwrap(cC,"fetch"),this._usedResources=new WeakSet)}}class gE{emit(e){}}const yE=new gE,wE=Symbol.for("io.opentelemetry.js.api.logs"),vE=globalThis;const bE=new class{getLogger(e,t,r){return new gE}};class _E{constructor(e,t,r,n){this._provider=e,this.name=t,this.version=r,this.options=n}emit(e){this._getLogger().emit(e)}_getLogger(){if(this._delegate)return this._delegate;const e=this._provider._getDelegateLogger(this.name,this.version,this.options);return e?(this._delegate=e,this._delegate):yE}}class SE{getLogger(e,t,r){var n;return null!==(n=this._getDelegateLogger(e,t,r))&&void 0!==n?n:new _E(this,e,t,r)}_getDelegate(){var e;return null!==(e=this._delegate)&&void 0!==e?e:bE}_setDelegate(e){this._delegate=e}_getDelegateLogger(e,t,r){var n;return null===(n=this._delegate)||void 0===n?void 0:n.getLogger(e,t,r)}}class CE{constructor(){this._proxyLoggerProvider=new SE}static getInstance(){return this._instance||(this._instance=new CE),this._instance}setGlobalLoggerProvider(e){return vE[wE]?this.getLoggerProvider():(vE[wE]=(t=1,r=e,n=bE,e=>e===t?r:n),this._proxyLoggerProvider._setDelegate(e),e);var t,r,n}getLoggerProvider(){var e,t;return null!==(t=null===(e=vE[wE])||void 0===e?void 0:e.call(vE,1))&&void 0!==t?t:this._proxyLoggerProvider}getLogger(e,t,r){return this.getLoggerProvider().getLogger(e,t,r)}disable(){delete vE[wE],this._proxyLoggerProvider=new SE}}const EE=CE.getInstance();let TE=console.error.bind(console);function kE(e,t,r){const n=!!e[t]&&Object.prototype.propertyIsEnumerable.call(e,t);Object.defineProperty(e,t,{configurable:!0,enumerable:n,writable:!0,value:r})}const xE=(e,t,r)=>{if(!e||!e[t])return void TE("no original function "+String(t)+" to wrap");if(!r)return TE("no wrapper function"),void TE((new Error).stack);const n=e[t];if("function"!=typeof n||"function"!=typeof r)return void TE("original object and wrapper must be functions");const s=r(n,t);return kE(s,"__original",n),kE(s,"__unwrap",()=>{e[t]===s&&kE(e,t,n)}),kE(s,"__wrapped",!0),kE(e,t,s),s},OE=(e,t,r)=>{if(!e)return TE("must provide one or more modules to patch"),void TE((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{xE(e,t,r)})}):TE("must provide one or more functions to wrap on modules")},AE=(e,t)=>{if(!e||!e[t])return TE("no function to unwrap."),void TE((new Error).stack);const r=e[t];r.__unwrap?r.__unwrap():TE("no original to unwrap to -- has "+String(t)+" already been unwrapped?")},IE=(e,t)=>{if(!e)return TE("must provide one or more modules to patch"),void TE((new Error).stack);Array.isArray(e)||(e=[e]),t&&Array.isArray(t)?e.forEach(e=>{t.forEach(t=>{AE(e,t)})}):TE("must provide one or more functions to unwrap on modules")};class RE{_config={};_tracer;_meter;_logger;_diag;instrumentationName;instrumentationVersion;constructor(e,t,r){this.instrumentationName=e,this.instrumentationVersion=t,this.setConfig(r),this._diag=av.createComponentLogger({namespace:e}),this._tracer=Cv.getTracer(e,t),this._meter=hv.getMeter(e,t),this._logger=EE.getLogger(e,t),this._updateMetricInstruments()}_wrap=xE;_unwrap=AE;_massWrap=OE;_massUnwrap=IE;get meter(){return this._meter}setMeterProvider(e){this._meter=e.getMeter(this.instrumentationName,this.instrumentationVersion),this._updateMetricInstruments()}get logger(){return this._logger}setLoggerProvider(e){this._logger=e.getLogger(this.instrumentationName,this.instrumentationVersion)}getModuleDefinitions(){const e=this.init()??[];return Array.isArray(e)?e:[e]}_updateMetricInstruments(){}getConfig(){return this._config}setConfig(e){this._config={enabled:!0,...e}}setTracerProvider(e){this._tracer=e.getTracer(this.instrumentationName,this.instrumentationVersion)}get tracer(){return this._tracer}_runSpanCustomizationHook(e,t,r,n){if(e)try{e(r,n)}catch(e){this._diag.error("Error running span customization hook due to exception in handler",{triggerName:t},e)}}}class ME extends RE{constructor(e,t,r){super(e,t,r),this._config.enabled&&this.enable()}}function NE(e){return"function"==typeof e&&"function"==typeof e.__original&&"function"==typeof e.__unwrap&&!0===e.__wrapped}var PE;!function(e){e.EVENT_TYPE="event_type",e.TARGET_ELEMENT="target_element",e.TARGET_XPATH="target_xpath",e.HTTP_URL="http.url"}(PE||(PE={}));const LE="0.58.0",DE=["click"];function UE(){return!1}class FE extends ME{version=LE;moduleName="user-interaction";_spansData=new WeakMap;_wrappedListeners=new WeakMap;_eventsSpanMap=new WeakMap;_eventNames;_shouldPreventSpanCreation;constructor(e={}){super("@opentelemetry/instrumentation-user-interaction",LE,e),this._eventNames=new Set(e?.eventNames??DE),this._shouldPreventSpanCreation="function"==typeof e?.shouldPreventSpanCreation?e.shouldPreventSpanCreation:UE}init(){}_checkForTimeout(e,t){const r=this._spansData.get(t);r&&("setTimeout"===e.source?r.hrTimeLastTimeout=rb():"Promise.then"!==e.source&&"setTimeout"!==e.source&&(r.hrTimeLastTimeout=void 0))}_allowEventName(e){return this._eventNames.has(e)}_createSpan(e,t,r){if(!(e instanceof HTMLElement))return;if(!e.getAttribute)return;if(e.hasAttribute("disabled"))return;if(!this._allowEventName(t))return;const n=__(e);try{const s=this.tracer.startSpan(t,{attributes:{[PE.EVENT_TYPE]:t,[PE.TARGET_ELEMENT]:e.tagName,[PE.TARGET_XPATH]:n,[PE.HTTP_URL]:window.location.href}},r?Cv.setSpan(ov.active(),r):void 0);if(!0===this._shouldPreventSpanCreation(t,e,s))return;return this._spansData.set(s,{taskCount:0}),s}catch(e){this._diag.error("failed to start create new user interaction span",e)}}_decrementTask(e){const t=this._spansData.get(e);t&&(t.taskCount--,0===t.taskCount&&this._tryToEndSpan(e,t.hrTimeLastTimeout))}_getCurrentSpan(e){const t=e.get("OT_ZONE_CONTEXT");return t?Cv.getSpan(t):t}_incrementTask(e){const t=this._spansData.get(e);t&&t.taskCount++}addPatchedListener(e,t,r,n){let s=this._wrappedListeners.get(r);s||(s=new Map,this._wrappedListeners.set(r,s));let i=s.get(t);return i||(i=new Map,s.set(t,i)),!i.has(e)&&(i.set(e,n),!0)}removePatchedListener(e,t,r){const n=this._wrappedListeners.get(r);if(!n)return;const s=n.get(t);if(!s)return;const i=s.get(e);return i&&(s.delete(e),0===s.size&&(n.delete(t),0===n.size&&this._wrappedListeners.delete(r))),i}_invokeListener(e,t,r){return"function"==typeof e?e.apply(t,r):e.handleEvent(r[0])}_patchAddEventListener(){const e=this;return t=>function(r,n,s){if(!n)return t.call(this,r,n,s);const i=s&&"object"==typeof s&&s.once,o=function(...t){let s;const o=t[0],a=o?.target;o&&(s=e._eventsSpanMap.get(o)),i&&e.removePatchedListener(this,r,n);const l=e._createSpan(a,r,s);return l?(o&&e._eventsSpanMap.set(o,l),ov.with(Cv.setSpan(ov.active(),l),()=>{const r=e._invokeListener(n,this,t);return l.end(),r})):e._invokeListener(n,this,t)};return e.addPatchedListener(this,r,n,o)?t.call(this,r,o,s):void 0}}_patchRemoveEventListener(){const e=this;return t=>function(r,n,s){const i=e.removePatchedListener(this,r,n);return i?t.call(this,r,i,s):t.call(this,r,n,s)}}_getPatchableEventTargets(){return window.EventTarget?[EventTarget.prototype]:[Node.prototype,Window.prototype]}_patchHistoryApi(){this._unpatchHistoryApi(),this._wrap(history,"replaceState",this._patchHistoryMethod()),this._wrap(history,"pushState",this._patchHistoryMethod()),this._wrap(history,"back",this._patchHistoryMethod()),this._wrap(history,"forward",this._patchHistoryMethod()),this._wrap(history,"go",this._patchHistoryMethod())}_patchHistoryMethod(){const e=this;return t=>function(...r){const n=`${location.pathname}${location.hash}${location.search}`,s=t.apply(this,r),i=`${location.pathname}${location.hash}${location.search}`;return n!==i&&e._updateInteractionName(i),s}}_unpatchHistoryApi(){NE(history.replaceState)&&this._unwrap(history,"replaceState"),NE(history.pushState)&&this._unwrap(history,"pushState"),NE(history.back)&&this._unwrap(history,"back"),NE(history.forward)&&this._unwrap(history,"forward"),NE(history.go)&&this._unwrap(history,"go")}_updateInteractionName(e){const t=Cv.getSpan(ov.active());t&&"function"==typeof t.updateName&&t.updateName(`Navigation: ${e}`)}_patchZoneCancelTask(){const e=this;return t=>function(r){const n=Zone.current,s=e._getCurrentSpan(n);return s&&e._shouldCountTask(r,n)&&e._decrementTask(s),t.call(this,r)}}_patchZoneScheduleTask(){const e=this;return t=>function(r){const n=Zone.current,s=e._getCurrentSpan(n);return s&&e._shouldCountTask(r,n)&&(e._incrementTask(s),e._checkForTimeout(r,s)),t.call(this,r)}}_patchZoneRunTask(){const e=this;return t=>function(r,n,s){const i=Array.isArray(s)&&s[0]instanceof Event?s[0]:void 0,o=i?.target;let a;const l=this;if(o){if(a=e._createSpan(o,r.eventName),a)return e._incrementTask(a),l.run(()=>{try{return ov.with(Cv.setSpan(ov.active(),a),()=>{const e=Zone.current;return r._zone=e,t.call(e,r,n,s)})}finally{e._decrementTask(a)}})}else a=e._getCurrentSpan(l);try{return t.call(l,r,n,s)}finally{a&&e._shouldCountTask(r,l)&&e._decrementTask(a)}}}_shouldCountTask(e,t){if(e._zone&&(t=e._zone),!t||!e.data||e.data.isPeriodic)return!1;const r=this._getCurrentSpan(t);return!!r&&(!!this._spansData.get(r)&&("macroTask"===e.type||"microTask"===e.type))}_tryToEndSpan(e,t){if(e){this._spansData.get(e)&&(e.end(t),this._spansData.delete(e))}}enable(){const e=this._getZoneWithPrototype();if(this._diag.debug("applying patch to",this.moduleName,this.version,"zone:",!!e),e)NE(e.prototype.runTask)&&(this._unwrap(e.prototype,"runTask"),this._diag.debug("removing previous patch from method runTask")),NE(e.prototype.scheduleTask)&&(this._unwrap(e.prototype,"scheduleTask"),this._diag.debug("removing previous patch from method scheduleTask")),NE(e.prototype.cancelTask)&&(this._unwrap(e.prototype,"cancelTask"),this._diag.debug("removing previous patch from method cancelTask")),this._zonePatched=!0,this._wrap(e.prototype,"runTask",this._patchZoneRunTask()),this._wrap(e.prototype,"scheduleTask",this._patchZoneScheduleTask()),this._wrap(e.prototype,"cancelTask",this._patchZoneCancelTask());else{this._zonePatched=!1;this._getPatchableEventTargets().forEach(e=>{NE(e.addEventListener)&&(this._unwrap(e,"addEventListener"),this._diag.debug("removing previous patch from method addEventListener")),NE(e.removeEventListener)&&(this._unwrap(e,"removeEventListener"),this._diag.debug("removing previous patch from method removeEventListener")),this._wrap(e,"addEventListener",this._patchAddEventListener()),this._wrap(e,"removeEventListener",this._patchRemoveEventListener())})}this._patchHistoryApi()}disable(){const e=this._getZoneWithPrototype();if(this._diag.debug("removing patch from",this.moduleName,this.version,"zone:",!!e),e&&this._zonePatched)NE(e.prototype.runTask)&&this._unwrap(e.prototype,"runTask"),NE(e.prototype.scheduleTask)&&this._unwrap(e.prototype,"scheduleTask"),NE(e.prototype.cancelTask)&&this._unwrap(e.prototype,"cancelTask");else{this._getPatchableEventTargets().forEach(e=>{NE(e.addEventListener)&&this._unwrap(e,"addEventListener"),NE(e.removeEventListener)&&this._unwrap(e,"removeEventListener")})}this._unpatchHistoryApi()}_getZoneWithPrototype(){return window.Zone}}class BE{_delegate;constructor(e){this._delegate=e}export(e,t){this._delegate.export(e,t)}forceFlush(){return this._delegate.forceFlush()}shutdown(){return this._delegate.shutdown()}}class jE extends Error{code;name="OTLPExporterError";data;constructor(e,t,r){super(e),this.data=r,this.code=t}}function zE(e){if(Number.isFinite(e)&&e>0)return e;throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${e}')`)}function VE(e){if(null!=e)return()=>e}function GE(e,t,r){return{timeoutMillis:zE(e.timeoutMillis??t.timeoutMillis??r.timeoutMillis),concurrencyLimit:e.concurrencyLimit??t.concurrencyLimit??r.concurrencyLimit,compression:e.compression??t.compression??r.compression}}class HE{_concurrencyLimit;_sendingPromises=[];constructor(e){this._concurrencyLimit=e}pushPromise(e){if(this.hasReachedLimit())throw new Error("Concurrency Limit reached");this._sendingPromises.push(e);const t=()=>{const t=this._sendingPromises.indexOf(e);this._sendingPromises.splice(t,1)};e.then(t,t)}hasReachedLimit(){return this._sendingPromises.length>=this._concurrencyLimit}async awaitAll(){await Promise.all(this._sendingPromises)}}function ZE(e){return new HE(e.concurrencyLimit)}function $E(){return{handleResponse(e){null!=e&&function(e){return Object.prototype.hasOwnProperty.call(e,"partialSuccess")}(e)&&null!=e.partialSuccess&&0!==Object.keys(e.partialSuccess).length&&av.warn("Received Partial Success response:",JSON.stringify(e.partialSuccess))}}}class WE{_transport;_serializer;_responseHandler;_promiseQueue;_timeout;_diagLogger;constructor(e,t,r,n,s){this._transport=e,this._serializer=t,this._responseHandler=r,this._promiseQueue=n,this._timeout=s,this._diagLogger=av.createComponentLogger({namespace:"OTLPExportDelegate"})}export(e,t){if(this._diagLogger.debug("items to be sent",e),this._promiseQueue.hasReachedLimit())return void t({code:_C.FAILED,error:new Error("Concurrent export limit reached")});const r=this._serializer.serializeRequest(e);null!=r?this._promiseQueue.pushPromise(this._transport.send(r,this._timeout).then(e=>{if("success"!==e.status)"failure"===e.status&&e.error?t({code:_C.FAILED,error:e.error}):"retryable"===e.status?t({code:_C.FAILED,error:new jE("Export failed with retryable status")}):t({code:_C.FAILED,error:new jE("Export failed with unknown error")});else{if(null!=e.data)try{this._responseHandler.handleResponse(this._serializer.deserializeResponse(e.data))}catch(t){this._diagLogger.warn("Export succeeded but could not deserialize response - is the response specification compliant?",t,e.data)}t({code:_C.SUCCESS})}},e=>t({code:_C.FAILED,error:e}))):t({code:_C.FAILED,error:new Error("Nothing to send")})}forceFlush(){return this._promiseQueue.awaitAll()}async shutdown(){this._diagLogger.debug("shutdown started"),await this.forceFlush(),this._transport.shutdown()}}function YE(e,t,r){return n={transport:r,serializer:t,promiseHandler:ZE(e)},s={timeout:e.timeoutMillis},new WE(n.transport,n.serializer,$E(),n.promiseHandler,s.timeout);var n,s}function XE(e){return e>=48&&e<=57?e-48:e>=97&&e<=102?e-87:e-55}function JE(e){const t=new Uint8Array(e.length/2);let r=0;for(let n=0;n>BigInt(32)))};var r}const QE="undefined"!=typeof BigInt?function(e){return KE(e).toString()}:vC;function eT(e){return e}function tT(e){if(void 0!==e)return JE(e)}const rT={encodeHrTime:qE,encodeSpanContext:JE,encodeOptionalSpanContext:tT};function nT(e){if(void 0===e)return rT;const t=e.useLongBits??!0,r=e.useHex??!1;return{encodeHrTime:t?qE:QE,encodeSpanContext:r?eT:JE,encodeOptionalSpanContext:r?eT:tT}}function sT(e){return{attributes:oT(e.attributes),droppedAttributesCount:0}}function iT(e){return{name:e.name,version:e.version}}function oT(e){return Object.keys(e).map(t=>aT(t,e[t]))}function aT(e,t){return{key:e,value:lT(t)}}function lT(e){const t=typeof e;return"string"===t?{stringValue:e}:"number"===t?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:"boolean"===t?{boolValue:e}:e instanceof Uint8Array?{bytesValue:e}:Array.isArray(e)?{arrayValue:{values:e.map(lT)}}:"object"===t&&null!=e?{kvlistValue:{values:Object.entries(e).map(([e,t])=>aT(e,t))}}:{}}var cT,uT,hT,pT;function dT(e){return null!=e}function fT(e){let t=Object.keys(e);return 0===t.length?"":(t=t.sort(),JSON.stringify(t.map(t=>[t,e[t]])))}!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE"}(cT||(cT={})),function(e){e.COUNTER="COUNTER",e.GAUGE="GAUGE",e.HISTOGRAM="HISTOGRAM",e.UP_DOWN_COUNTER="UP_DOWN_COUNTER",e.OBSERVABLE_COUNTER="OBSERVABLE_COUNTER",e.OBSERVABLE_GAUGE="OBSERVABLE_GAUGE",e.OBSERVABLE_UP_DOWN_COUNTER="OBSERVABLE_UP_DOWN_COUNTER"}(uT||(uT={})),function(e){e[e.HISTOGRAM=0]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=1]="EXPONENTIAL_HISTOGRAM",e[e.GAUGE=2]="GAUGE",e[e.SUM=3]="SUM"}(hT||(hT={}));class mT extends Error{constructor(e){super(e),Object.setPrototypeOf(this,mT.prototype)}}function gT(e,t){let r;const n=new Promise(function(e,n){r=setTimeout(function(){n(new mT("Operation timed out."))},t)});return Promise.race([e,n]).then(e=>(clearTimeout(r),e),e=>{throw clearTimeout(r),e})}function yT(e){return"rejected"===e.status}function wT(e,t){const r=[];return e.forEach(e=>{r.push(...t(e))}),r}!function(e){e[e.DROP=0]="DROP",e[e.SUM=1]="SUM",e[e.LAST_VALUE=2]="LAST_VALUE",e[e.HISTOGRAM=3]="HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=4]="EXPONENTIAL_HISTOGRAM"}(pT||(pT={}));class vT{kind=pT.DROP;createAccumulation(){}merge(e,t){}diff(e,t){}toMetricData(e,t,r,n){}}class bT{startTime;_boundaries;_recordMinMax;_current;constructor(e,t,r=!0,n=function(e){const t=e.map(()=>0);return t.push(0),{buckets:{boundaries:e,counts:t},sum:0,count:0,hasMinMax:!1,min:1/0,max:-1/0}}(t)){this.startTime=e,this._boundaries=t,this._recordMinMax=r,this._current=n}record(e){if(Number.isNaN(e))return;this._current.count+=1,this._current.sum+=e,this._recordMinMax&&(this._current.min=Math.min(e,this._current.min),this._current.max=Math.max(e,this._current.max),this._current.hasMinMax=!0);const t=function(e,t){let r=0,n=e.length-1,s=e.length;for(;n>=r;){const i=r+Math.trunc((n-r)/2);e[i]{const s=r.toPointValue(),i=e.type===uT.GAUGE||e.type===uT.UP_DOWN_COUNTER||e.type===uT.OBSERVABLE_GAUGE||e.type===uT.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:i?void 0:s.sum,buckets:s.buckets,count:s.count}}})}}}class ST{backing;indexBase;indexStart;indexEnd;constructor(e=new CT,t=0,r=0,n=0){this.backing=e,this.indexBase=t,this.indexStart=r,this.indexEnd=n}get offset(){return this.indexStart}get length(){return 0===this.backing.length||this.indexEnd===this.indexStart&&0===this.at(0)?0:this.indexEnd-this.indexStart+1}counts(){return Array.from({length:this.length},(e,t)=>this.at(t))}at(e){const t=this.indexBase-this.indexStart;return e=0;e--)if(0!==this.at(e)){this.indexEnd-=this.length-e-1;break}this._rotate()}downscale(e){this._rotate();const t=1+this.indexEnd-this.indexStart,r=1<>=e,this.indexEnd>>=e,this.indexBase=this.indexStart}clone(){return new ST(this.backing.clone(),this.indexBase,this.indexStart,this.indexEnd)}_rotate(){const e=this.indexBase-this.indexStart;0!==e&&(e>0?(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,e),this.backing.reverse(e,this.backing.length)):(this.backing.reverse(0,this.backing.length),this.backing.reverse(0,this.backing.length+e)),this.indexBase=this.indexStart)}_relocateBucket(e,t){e!==t&&this.incrementBucket(e,this.backing.emptyBucket(t))}}class CT{_counts;constructor(e=[0]){this._counts=e}get length(){return this._counts.length}countAt(e){return this._counts[e]}growTo(e,t,r){const n=new Array(e).fill(0);n.splice(r,this._counts.length-t,...this._counts.slice(t)),n.splice(0,t,...this._counts.slice(0,t)),this._counts=n}reverse(e,t){const r=Math.floor((e+t)/2)-e;for(let n=0;n=t?this._counts[e]-=t:this._counts[e]=0}clone(){return new CT([...this._counts])}}const ET=1023,TT=ET,kT=Math.pow(2,-1022);function xT(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);return((2146435072&t.getUint32(0))>>20)-ET}function OT(e){const t=new DataView(new ArrayBuffer(8));t.setFloat64(0,e);const r=t.getUint32(0),n=t.getUint32(4);return(1048575&r)*Math.pow(2,32)+n}function AT(e,t){return 0===e||e===Number.POSITIVE_INFINITY||e===Number.NEGATIVE_INFINITY||Number.isNaN(e)?e:e*Math.pow(2,t)}class IT extends Error{}class RT{_shift;constructor(e){this._shift=-e}mapToIndex(e){if(e>this._shift}lowerBoundary(e){const t=this._minNormalLowerBoundaryIndex();if(er)throw new IT(`overflow: ${e} is > maximum lower boundary: ${r}`);return AT(1,e<>this._shift;return this._shift<2&&e--,e}_maxNormalLowerBoundaryIndex(){return TT>>this._shift}_rightShift(e,t){return Math.floor(e*Math.pow(2,-t))}}class MT{_scale;_scaleFactor;_inverseFactor;constructor(e){this._scale=e,this._scaleFactor=AT(Math.LOG2E,e),this._inverseFactor=AT(Math.LN2,-e)}mapToIndex(e){if(e<=kT)return this._minNormalLowerBoundaryIndex()-1;if(0===OT(e)){return(xT(e)<=r?r:t}lowerBoundary(e){const t=this._maxNormalLowerBoundaryIndex();if(e>=t){if(e===t)return 2*Math.exp((e-(1< maximum lower boundary: ${t}`)}const r=this._minNormalLowerBoundaryIndex();if(e<=r){if(e===r)return kT;if(e===r-1)return Math.exp((e+(1<t>10?new MT(t-10):new RT(t-10));function PT(e){if(e>20||e<-10)throw new IT(`expected scale >= -10 && <= 20, got: ${e}`);return NT[e+10]}class LT{low;high;static combine(e,t){return new LT(Math.min(e.low,t.low),Math.max(e.high,t.high))}constructor(e,t){this.low=e,this.high=t}}class DT{startTime;_maxSize;_recordMinMax;_sum;_count;_zeroCount;_min;_max;_positive;_negative;_mapping;constructor(e=e,t=160,r=!0,n=0,s=0,i=0,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,l=new ST,c=new ST,u=PT(20)){this.startTime=e,this._maxSize=t,this._recordMinMax=r,this._sum=n,this._count=s,this._zeroCount=i,this._min=o,this._max=a,this._positive=l,this._negative=c,this._mapping=u,this._maxSize<2&&(av.warn(`Exponential Histogram Max Size set to ${this._maxSize}, changing to the minimum size of: 2`),this._maxSize=2)}record(e){this.updateByIncrement(e,1)}setStartTime(e){this.startTime=e}toPointValue(){return{hasMinMax:this._recordMinMax,min:this.min,max:this.max,sum:this.sum,positive:{offset:this.positive.offset,bucketCounts:this.positive.counts()},negative:{offset:this.negative.offset,bucketCounts:this.negative.counts()},count:this.count,scale:this.scale,zeroCount:this.zeroCount}}get sum(){return this._sum}get min(){return this._min}get max(){return this._max}get count(){return this._count}get zeroCount(){return this._zeroCount}get scale(){return this._count===this._zeroCount?0:this._mapping.scale}get positive(){return this._positive}get negative(){return this._negative}updateByIncrement(e,t){Number.isNaN(e)||(e>this._max&&(this._max=e),e0?this._updateBuckets(this._positive,e,t):this._updateBuckets(this._negative,-e,t)):this._zeroCount+=t)}merge(e){0===this._count?(this._min=e.min,this._max=e.max):0!==e.count&&(e.minthis.max&&(this._max=e.max)),this.startTime=e.startTime,this._sum+=e.sum,this._count+=e.count,this._zeroCount+=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._mergeBuckets(this.positive,e,e.positive,t),this._mergeBuckets(this.negative,e,e.negative,t)}diff(e){this._min=1/0,this._max=-1/0,this._sum-=e.sum,this._count-=e.count,this._zeroCount-=e.zeroCount;const t=this._minScale(e);this._downscale(this.scale-t),this._diffBuckets(this.positive,e,e.positive,t),this._diffBuckets(this.negative,e,e.negative,t)}clone(){return new DT(this.startTime,this._maxSize,this._recordMinMax,this._sum,this._count,this._zeroCount,this._min,this._max,this.positive.clone(),this.negative.clone(),this._mapping)}_updateBuckets(e,t,r){let n=this._mapping.mapToIndex(t),s=!1,i=0,o=0;if(0===e.length?(e.indexStart=n,e.indexEnd=e.indexStart,e.indexBase=e.indexStart):n=this._maxSize?(s=!0,o=n,i=e.indexEnd):n>e.indexEnd&&n-e.indexStart>=this._maxSize&&(s=!0,o=e.indexStart,i=n),s){const e=this._changeScale(i,o);this._downscale(e),n=this._mapping.mapToIndex(t)}this._incrementIndexBy(e,n,r)}_incrementIndexBy(e,t,r){if(0===r)return;if(0===e.length&&(e.indexStart=e.indexEnd=e.indexBase=t),t=e.backing.length&&this._grow(e,r+1),e.indexStart=t}else if(t>e.indexEnd){const r=t-e.indexStart;r>=e.backing.length&&this._grow(e,r+1),e.indexEnd=t}let n=t-e.indexBase;n<0&&(n+=e.backing.length),e.incrementBucket(n,r)}_grow(e,t){const r=e.backing.length,n=e.indexBase-e.indexStart,s=r-n;let i=function(e){return e--,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,++e}(t);i>this._maxSize&&(i=this._maxSize);const o=i-n;e.backing.growTo(i,s,o)}_changeScale(e,t){let r=0;for(;e-t>=this._maxSize;)e>>=1,t>>=1,r++;return r}_downscale(e){if(0===e)return;if(e<0)throw new Error(`impossible change of scale: ${this.scale}`);const t=this._mapping.scale-e;this._positive.downscale(e),this._negative.downscale(e),this._mapping=PT(t)}_minScale(e){const t=Math.min(this.scale,e.scale),r=LT.combine(this._highLowAtScale(this.positive,this.scale,t),this._highLowAtScale(e.positive,e.scale,t)),n=LT.combine(this._highLowAtScale(this.negative,this.scale,t),this._highLowAtScale(e.negative,e.scale,t));return Math.min(t-this._changeScale(r.high,r.low),t-this._changeScale(n.high,n.low))}_highLowAtScale(e,t,r){if(0===e.length)return new LT(0,-1);const n=t-r;return new LT(e.indexStart>>n,e.indexEnd>>n)}_mergeBuckets(e,t,r,n){const s=r.offset,i=t.scale-n;for(let t=0;t>i,r.at(t))}_diffBuckets(e,t,r,n){const s=r.offset,i=t.scale-n;for(let t=0;t>i)-e.indexBase;n<0&&(n+=e.backing.length),e.decrementBucket(n,r.at(t))}e.trim()}}class UT{_maxSize;_recordMinMax;kind=pT.EXPONENTIAL_HISTOGRAM;constructor(e,t){this._maxSize=e,this._recordMinMax=t}createAccumulation(e){return new DT(e,this._maxSize,this._recordMinMax)}merge(e,t){const r=t.clone();return r.merge(e),r}diff(e,t){const r=t.clone();return r.diff(e),r}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:hT.EXPONENTIAL_HISTOGRAM,dataPoints:r.map(([t,r])=>{const s=r.toPointValue(),i=e.type===uT.GAUGE||e.type===uT.UP_DOWN_COUNTER||e.type===uT.OBSERVABLE_GAUGE||e.type===uT.OBSERVABLE_UP_DOWN_COUNTER;return{attributes:t,startTime:r.startTime,endTime:n,value:{min:s.hasMinMax?s.min:void 0,max:s.hasMinMax?s.max:void 0,sum:i?void 0:s.sum,positive:{offset:s.positive.offset,bucketCounts:s.positive.bucketCounts},negative:{offset:s.negative.offset,bucketCounts:s.negative.bucketCounts},count:s.count,scale:s.scale,zeroCount:s.zeroCount}}})}}}class FT{startTime;_current;sampleTime;constructor(e,t=0,r=[0,0]){this.startTime=e,this._current=t,this.sampleTime=r}record(e){this._current=e,this.sampleTime=mC(Date.now())}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class BT{kind=pT.LAST_VALUE;createAccumulation(e){return new FT(e)}merge(e,t){const r=bC(t.sampleTime)>=bC(e.sampleTime)?t:e;return new FT(e.startTime,r.toPointValue(),r.sampleTime)}diff(e,t){const r=bC(t.sampleTime)>=bC(e.sampleTime)?t:e;return new FT(t.startTime,r.toPointValue(),r.sampleTime)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:hT.GAUGE,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()}))}}}class jT{startTime;monotonic;_current;reset;constructor(e,t,r=0,n=!1){this.startTime=e,this.monotonic=t,this._current=r,this.reset=n}record(e){this.monotonic&&e<0||(this._current+=e)}setStartTime(e){this.startTime=e}toPointValue(){return this._current}}class zT{monotonic;kind=pT.SUM;constructor(e){this.monotonic=e}createAccumulation(e){return new jT(e,this.monotonic)}merge(e,t){const r=e.toPointValue(),n=t.toPointValue();return t.reset?new jT(t.startTime,this.monotonic,n,t.reset):new jT(e.startTime,this.monotonic,r+n)}diff(e,t){const r=e.toPointValue(),n=t.toPointValue();return this.monotonic&&r>n?new jT(t.startTime,this.monotonic,n,!0):new jT(t.startTime,this.monotonic,n-r)}toMetricData(e,t,r,n){return{descriptor:e,aggregationTemporality:t,dataPointType:hT.SUM,dataPoints:r.map(([e,t])=>({attributes:e,startTime:t.startTime,endTime:n,value:t.toPointValue()})),isMonotonic:this.monotonic}}}class VT{static DEFAULT_INSTANCE=new vT;createAggregator(e){return VT.DEFAULT_INSTANCE}}class GT{static MONOTONIC_INSTANCE=new zT(!0);static NON_MONOTONIC_INSTANCE=new zT(!1);createAggregator(e){switch(e.type){case uT.COUNTER:case uT.OBSERVABLE_COUNTER:case uT.HISTOGRAM:return GT.MONOTONIC_INSTANCE;default:return GT.NON_MONOTONIC_INSTANCE}}}class HT{static DEFAULT_INSTANCE=new BT;createAggregator(e){return HT.DEFAULT_INSTANCE}}class ZT{static DEFAULT_INSTANCE=new _T([0,5,10,25,50,75,100,250,500,750,1e3,2500,5e3,7500,1e4],!0);createAggregator(e){return ZT.DEFAULT_INSTANCE}}class $T{_recordMinMax;_boundaries;constructor(e,t=!0){if(this._recordMinMax=t,null==e)throw new Error("ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array");e=(e=e.concat()).sort((e,t)=>e-t);const r=e.lastIndexOf(-1/0);let n=e.indexOf(1/0);-1===n&&(n=void 0),this._boundaries=e.slice(r+1,n)}createAggregator(e){return new _T(this._boundaries,this._recordMinMax)}}class WT{_maxSize;_recordMinMax;constructor(e=160,t=!0){this._maxSize=e,this._recordMinMax=t}createAggregator(e){return new UT(this._maxSize,this._recordMinMax)}}const YT=new VT,XT=new GT,JT=new HT,KT=new ZT,qT=new class{_resolve(e){switch(e.type){case uT.COUNTER:case uT.UP_DOWN_COUNTER:case uT.OBSERVABLE_COUNTER:case uT.OBSERVABLE_UP_DOWN_COUNTER:return XT;case uT.GAUGE:case uT.OBSERVABLE_GAUGE:return JT;case uT.HISTOGRAM:return e.advice.explicitBucketBoundaries?new $T(e.advice.explicitBucketBoundaries):KT}return av.warn(`Unable to recognize instrument type: ${e.type}`),YT}createAggregator(e){return this._resolve(e).createAggregator(e)}};var QT;function ek(e){switch(e.type){case QT.DEFAULT:return qT;case QT.DROP:return YT;case QT.SUM:return XT;case QT.LAST_VALUE:return JT;case QT.EXPONENTIAL_HISTOGRAM:{const t=e;return new WT(t.options?.maxSize,t.options?.recordMinMax)}case QT.EXPLICIT_BUCKET_HISTOGRAM:{const t=e;return null==t.options?KT:new $T(t.options?.boundaries,t.options?.recordMinMax)}default:throw new Error("Unsupported Aggregation")}}!function(e){e[e.DEFAULT=0]="DEFAULT",e[e.DROP=1]="DROP",e[e.SUM=2]="SUM",e[e.LAST_VALUE=3]="LAST_VALUE",e[e.EXPLICIT_BUCKET_HISTOGRAM=4]="EXPLICIT_BUCKET_HISTOGRAM",e[e.EXPONENTIAL_HISTOGRAM=5]="EXPONENTIAL_HISTOGRAM"}(QT||(QT={}));const tk=e=>({type:QT.DEFAULT}),rk=e=>cT.CUMULATIVE;class nk{_shutdown=!1;_metricProducers;_sdkMetricProducer;_aggregationTemporalitySelector;_aggregationSelector;_cardinalitySelector;constructor(e){this._aggregationSelector=e?.aggregationSelector??tk,this._aggregationTemporalitySelector=e?.aggregationTemporalitySelector??rk,this._metricProducers=e?.metricProducers??[],this._cardinalitySelector=e?.cardinalitySelector}setMetricProducer(e){if(this._sdkMetricProducer)throw new Error("MetricReader can not be bound to a MeterProvider again.");this._sdkMetricProducer=e,this.onInitialized()}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}selectCardinalityLimit(e){return this._cardinalitySelector?this._cardinalitySelector(e):2e3}onInitialized(){}async collect(e){if(void 0===this._sdkMetricProducer)throw new Error("MetricReader is not bound to a MetricProducer");if(this._shutdown)throw new Error("MetricReader is shutdown");const[t,...r]=await Promise.all([this._sdkMetricProducer.collect({timeoutMillis:e?.timeoutMillis}),...this._metricProducers.map(t=>t.collect({timeoutMillis:e?.timeoutMillis}))]),n=t.errors.concat(wT(r,e=>e.errors)),s=t.resourceMetrics.resource,i=t.resourceMetrics.scopeMetrics.concat(wT(r,e=>e.resourceMetrics.scopeMetrics));return{resourceMetrics:{resource:s,scopeMetrics:i},errors:n}}async shutdown(e){this._shutdown?av.error("Cannot call shutdown twice."):(null==e?.timeoutMillis?await this.onShutdown():await gT(this.onShutdown(),e.timeoutMillis),this._shutdown=!0)}async forceFlush(e){this._shutdown?av.warn("Cannot forceFlush on already shutdown MetricReader."):null!=e?.timeoutMillis?await gT(this.onForceFlush(),e.timeoutMillis):await this.onForceFlush()}}class sk extends nk{_interval;_exporter;_exportInterval;_exportTimeout;constructor(e){if(super({aggregationSelector:e.exporter.selectAggregation?.bind(e.exporter),aggregationTemporalitySelector:e.exporter.selectAggregationTemporality?.bind(e.exporter),metricProducers:e.metricProducers}),void 0!==e.exportIntervalMillis&&e.exportIntervalMillis<=0)throw Error("exportIntervalMillis must be greater than 0");if(void 0!==e.exportTimeoutMillis&&e.exportTimeoutMillis<=0)throw Error("exportTimeoutMillis must be greater than 0");if(void 0!==e.exportTimeoutMillis&&void 0!==e.exportIntervalMillis&&e.exportIntervalMillis0&&av.error("PeriodicExportingMetricReader: metrics collection errors",...t),e.resource.asyncAttributesPending)try{await(e.resource.waitForAsyncAttributes?.())}catch(e){av.debug("Error while resolving async portion of resource: ",e),lC(e)}if(0===e.scopeMetrics.length)return;const r=await EC._export(this._exporter,e);if(r.code!==_C.SUCCESS)throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${r.error})`)}onInitialized(){this._interval=setInterval(()=>{this._runOnce()},this._exportInterval),this._interval}async onForceFlush(){await this._runOnce(),await this._exporter.forceFlush()}async onShutdown(){this._interval&&clearInterval(this._interval),await this.onForceFlush(),await this._exporter.shutdown()}}class ik{_registeredViews=[];addView(e){this._registeredViews.push(e)}findViews(e,t){return this._registeredViews.filter(r=>this._matchInstrument(r.instrumentSelector,e)&&this._matchMeter(r.meterSelector,t))}_matchInstrument(e,t){return(void 0===e.getType()||t.type===e.getType())&&e.getNameFilter().match(t.name)&&e.getUnitFilter().match(t.unit)}_matchMeter(e,t){return e.getNameFilter().match(t.name)&&(void 0===t.version||e.getVersionFilter().match(t.version))&&(void 0===t.schemaUrl||e.getSchemaUrlFilter().match(t.schemaUrl))}}function ok(e,t,r){return function(e){return null!=e.match(lk)}(e)||av.warn(`Invalid metric name: "${e}". The metric name should be a ASCII string with a length no greater than 255 characters.`),{name:e,type:t,description:r?.description??"",unit:r?.unit??"",valueType:r?.valueType??Ow.DOUBLE,advice:r?.advice??{}}}function ak(e,t){return r=e.name,n=t.name,r.toLowerCase()===n.toLowerCase()&&e.unit===t.unit&&e.type===t.type&&e.valueType===t.valueType;var r,n}const lk=/^[a-z][a-z0-9_.\-/]{0,254}$/i;class ck{_writableMetricStorage;_descriptor;constructor(e,t){this._writableMetricStorage=e,this._descriptor=t}_record(e,t={},r=ov.active()){"number"==typeof e?(this._descriptor.valueType!==Ow.INT||Number.isInteger(e)||(av.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._writableMetricStorage.record(e,t,r,mC(Date.now())):av.warn(`non-number value provided to metric ${this._descriptor.name}: ${e}`)}}class uk extends ck{add(e,t,r){this._record(e,t,r)}}class hk extends ck{add(e,t,r){e<0?av.warn(`negative value provided to counter ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class pk extends ck{record(e,t,r){this._record(e,t,r)}}class dk extends ck{record(e,t,r){e<0?av.warn(`negative value provided to histogram ${this._descriptor.name}: ${e}`):this._record(e,t,r)}}class fk{_observableRegistry;_metricStorages;_descriptor;constructor(e,t,r){this._observableRegistry=r,this._descriptor=e,this._metricStorages=t}addCallback(e){this._observableRegistry.addCallback(e,this)}removeCallback(e){this._observableRegistry.removeCallback(e,this)}}class mk extends fk{}class gk extends fk{}class yk extends fk{}function wk(e){return e instanceof fk}class vk{_meterSharedState;constructor(e){this._meterSharedState=e}createGauge(e,t){const r=ok(e,uT.GAUGE,t),n=this._meterSharedState.registerMetricStorage(r);return new pk(n,r)}createHistogram(e,t){const r=ok(e,uT.HISTOGRAM,t),n=this._meterSharedState.registerMetricStorage(r);return new dk(n,r)}createCounter(e,t){const r=ok(e,uT.COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new hk(n,r)}createUpDownCounter(e,t){const r=ok(e,uT.UP_DOWN_COUNTER,t),n=this._meterSharedState.registerMetricStorage(r);return new uk(n,r)}createObservableGauge(e,t){const r=ok(e,uT.OBSERVABLE_GAUGE,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new gk(r,n,this._meterSharedState.observableRegistry)}createObservableCounter(e,t){const r=ok(e,uT.OBSERVABLE_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new mk(r,n,this._meterSharedState.observableRegistry)}createObservableUpDownCounter(e,t){const r=ok(e,uT.OBSERVABLE_UP_DOWN_COUNTER,t),n=this._meterSharedState.registerAsyncMetricStorage(r);return new yk(r,n,this._meterSharedState.observableRegistry)}addBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.addBatchCallback(e,t)}removeBatchObservableCallback(e,t){this._meterSharedState.observableRegistry.removeBatchCallback(e,t)}}class bk{_instrumentDescriptor;constructor(e){this._instrumentDescriptor=e}getInstrumentDescriptor(){return this._instrumentDescriptor}updateDescription(e){this._instrumentDescriptor=ok(this._instrumentDescriptor.name,this._instrumentDescriptor.type,{description:e,valueType:this._instrumentDescriptor.valueType,unit:this._instrumentDescriptor.unit,advice:this._instrumentDescriptor.advice})}}class _k{_hash;_valueMap=new Map;_keyMap=new Map;constructor(e){this._hash=e}get(e,t){return t??=this._hash(e),this._valueMap.get(t)}getOrDefault(e,t){const r=this._hash(e);if(this._valueMap.has(r))return this._valueMap.get(r);const n=t();return this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,n),n}set(e,t,r){r??=this._hash(e),this._keyMap.has(r)||this._keyMap.set(r,e),this._valueMap.set(r,t)}has(e,t){return t??=this._hash(e),this._valueMap.has(t)}*keys(){const e=this._keyMap.entries();let t=e.next();for(;!0!==t.done;)yield[t.value[1],t.value[0]],t=e.next()}*entries(){const e=this._valueMap.entries();let t=e.next();for(;!0!==t.done;)yield[this._keyMap.get(t.value[0]),t.value[1],t.value[0]],t=e.next()}get size(){return this._valueMap.size}}class Sk extends _k{constructor(){super(fT)}}class Ck{_aggregator;_activeCollectionStorage=new Sk;_cumulativeMemoStorage=new Sk;_cardinalityLimit;_overflowAttributes={"otel.metric.overflow":!0};_overflowHashCode;constructor(e,t){this._aggregator=e,this._cardinalityLimit=(t??2e3)-1,this._overflowHashCode=fT(this._overflowAttributes)}record(e,t,r,n){let s=this._activeCollectionStorage.get(t);if(!s){if(this._activeCollectionStorage.size>=this._cardinalityLimit){const t=this._activeCollectionStorage.getOrDefault(this._overflowAttributes,()=>this._aggregator.createAccumulation(n));return void t?.record(e)}s=this._aggregator.createAccumulation(n),this._activeCollectionStorage.set(t,s)}s?.record(e)}batchCumulate(e,t){Array.from(e.entries()).forEach(([e,r,n])=>{const s=this._aggregator.createAccumulation(t);s?.record(r);let i=s;if(this._cumulativeMemoStorage.has(e,n)){const t=this._cumulativeMemoStorage.get(e,n);i=this._aggregator.diff(t,s)}else if(this._cumulativeMemoStorage.size>=this._cardinalityLimit&&(e=this._overflowAttributes,n=this._overflowHashCode,this._cumulativeMemoStorage.has(e,n))){const t=this._cumulativeMemoStorage.get(e,n);i=this._aggregator.diff(t,s)}if(this._activeCollectionStorage.has(e,n)){const t=this._activeCollectionStorage.get(e,n);i=this._aggregator.merge(t,i)}this._cumulativeMemoStorage.set(e,s,n),this._activeCollectionStorage.set(e,i,n)})}collect(){const e=this._activeCollectionStorage;return this._activeCollectionStorage=new Sk,e}}class Ek{_aggregator;_unreportedAccumulations=new Map;_reportHistory=new Map;constructor(e,t){this._aggregator=e,t.forEach(e=>{this._unreportedAccumulations.set(e,[])})}buildMetrics(e,t,r,n){this._stashAccumulations(r);const s=this._getMergedUnreportedAccumulations(e);let i,o=s;if(this._reportHistory.has(e)){const t=this._reportHistory.get(e),r=t.collectionTime;i=t.aggregationTemporality,o=i===cT.CUMULATIVE?Ek.merge(t.accumulations,s,this._aggregator):Ek.calibrateStartTime(t.accumulations,s,r)}else i=e.selectAggregationTemporality(t.type);this._reportHistory.set(e,{accumulations:o,collectionTime:n,aggregationTemporality:i});const a=(l=o,Array.from(l.entries()));var l;if(0!==a.length)return this._aggregator.toMetricData(t,i,a,n)}_stashAccumulations(e){const t=this._unreportedAccumulations.keys();for(const r of t){let t=this._unreportedAccumulations.get(r);void 0===t&&(t=[],this._unreportedAccumulations.set(r,t)),t.push(e)}}_getMergedUnreportedAccumulations(e){let t=new Sk;const r=this._unreportedAccumulations.get(e);if(this._unreportedAccumulations.set(e,[]),void 0===r)return t;for(const e of r)t=Ek.merge(t,e,this._aggregator);return t}static merge(e,t,r){const n=e,s=t.entries();let i=s.next();for(;!0!==i.done;){const[t,o,a]=i.value;if(e.has(t,a)){const s=e.get(t,a),i=r.merge(s,o);n.set(t,i,a)}else n.set(t,o,a);i=s.next()}return n}static calibrateStartTime(e,t,r){for(const[n,s]of e.keys()){const e=t.get(n,s);e?.setStartTime(r)}return t}}class Tk extends bk{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,r,n,s){super(e),this._attributesProcessor=r,this._aggregationCardinalityLimit=s,this._deltaMetricStorage=new Ck(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ek(t,n)}record(e,t){const r=new Sk;Array.from(e.entries()).forEach(([e,t])=>{r.set(this._attributesProcessor.process(e),t)}),this._deltaMetricStorage.batchCumulate(r,t)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}function kk(e,t){let r="";return e.unit!==t.unit&&(r+=`\t- Unit '${e.unit}' does not match '${t.unit}'\n`),e.type!==t.type&&(r+=`\t- Type '${e.type}' does not match '${t.type}'\n`),e.valueType!==t.valueType&&(r+=`\t- Value Type '${e.valueType}' does not match '${t.valueType}'\n`),e.description!==t.description&&(r+=`\t- Description '${e.description}' does not match '${t.description}'\n`),r}function xk(e,t){return e.valueType!==t.valueType?function(e,t){return`\t- use valueType '${e.valueType}' on instrument creation or use an instrument name other than '${t.name}'`}(e,t):e.unit!==t.unit?function(e,t){return`\t- use unit '${e.unit}' on instrument creation or use an instrument name other than '${t.name}'`}(e,t):e.type!==t.type?function(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'`}(e,t):e.description!==t.description?function(e,t){const r={name:t.name,type:t.type,unit:t.unit},n=JSON.stringify(r);return`\t- create a new view with a name other than '${e.name}' and InstrumentSelector '${n}'\n \t- OR - create a new view with the name ${e.name} and description '${e.description}' and InstrumentSelector ${n}\n \t- OR - create a new view with the name ${t.name} and description '${e.description}' and InstrumentSelector ${n}`}(e,t):""}class Ok{_sharedRegistry=new Map;_perCollectorRegistry=new Map;static create(){return new Ok}getStorages(e){let t=[];for(const e of this._sharedRegistry.values())t=t.concat(e);const r=this._perCollectorRegistry.get(e);if(null!=r)for(const e of r.values())t=t.concat(e);return t}register(e){this._registerStorage(e,this._sharedRegistry)}registerForCollector(e,t){let r=this._perCollectorRegistry.get(e);null==r&&(r=new Map,this._perCollectorRegistry.set(e,r)),this._registerStorage(t,r)}findOrUpdateCompatibleStorage(e){const t=this._sharedRegistry.get(e.name);return void 0===t?null:this._findOrUpdateCompatibleStorage(e,t)}findOrUpdateCompatibleCollectorStorage(e,t){const r=this._perCollectorRegistry.get(e);if(void 0===r)return null;const n=r.get(t.name);return void 0===n?null:this._findOrUpdateCompatibleStorage(t,n)}_registerStorage(e,t){const r=e.getInstrumentDescriptor(),n=t.get(r.name);void 0!==n?n.push(e):t.set(r.name,[e])}_findOrUpdateCompatibleStorage(e,t){let r=null;for(const n of t){const t=n.getInstrumentDescriptor();ak(t,e)?(t.description!==e.description&&(e.description.length>t.description.length&&n.updateDescription(e.description),av.warn("A view or instrument with the name ",e.name," has already been registered, but has a different description and is incompatible with another registered view.\n","Details:\n",kk(t,e),"The longer description will be used.\nTo resolve the conflict:",xk(t,e))),r=n):av.warn("A view or instrument with the name ",e.name," has already been registered and is incompatible with another registered view.\n","Details:\n",kk(t,e),"To resolve the conflict:\n",xk(t,e))}return r}}class Ak{_backingStorages;constructor(e){this._backingStorages=e}record(e,t,r,n){this._backingStorages.forEach(s=>{s.record(e,t,r,n)})}}class Ik{_instrumentName;_valueType;_buffer=new Sk;constructor(e,t){this._instrumentName=e,this._valueType=t}observe(e,t={}){"number"==typeof e?(this._valueType!==Ow.INT||Number.isInteger(e)||(av.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`),e=Math.trunc(e),Number.isInteger(e)))&&this._buffer.set(t,e):av.warn(`non-number value provided to metric ${this._instrumentName}: ${e}`)}}class Rk{_buffer=new Map;observe(e,t,r={}){if(!wk(e))return;let n=this._buffer.get(e);null==n&&(n=new Sk,this._buffer.set(e,n)),"number"==typeof t?(e._descriptor.valueType!==Ow.INT||Number.isInteger(t)||(av.warn(`INT value type cannot accept a floating-point value for ${e._descriptor.name}, ignoring the fractional digits.`),t=Math.trunc(t),Number.isInteger(t)))&&n.set(r,t):av.warn(`non-number value provided to metric ${e._descriptor.name}: ${t}`)}}class Mk{_callbacks=[];_batchCallbacks=[];addCallback(e,t){this._findCallback(e,t)>=0||this._callbacks.push({callback:e,instrument:t})}removeCallback(e,t){const r=this._findCallback(e,t);r<0||this._callbacks.splice(r,1)}addBatchCallback(e,t){const r=new Set(t.filter(wk));if(0===r.size)return void av.error("BatchObservableCallback is not associated with valid instruments",t);this._findBatchCallback(e,r)>=0||this._batchCallbacks.push({callback:e,instruments:r})}removeBatchCallback(e,t){const r=new Set(t.filter(wk)),n=this._findBatchCallback(e,r);n<0||this._batchCallbacks.splice(n,1)}async observe(e,t){const r=this._observeCallbacks(e,t),n=this._observeBatchCallbacks(e,t),s=await async function(e){return Promise.all(e.map(async e=>{try{return{status:"fulfilled",value:await e}}catch(e){return{status:"rejected",reason:e}}}))}([...r,...n]);return s.filter(yT).map(e=>e.reason)}_observeCallbacks(e,t){return this._callbacks.map(async({callback:r,instrument:n})=>{const s=new Ik(n._descriptor.name,n._descriptor.valueType);let i=Promise.resolve(r(s));null!=t&&(i=gT(i,t)),await i,n._metricStorages.forEach(t=>{t.record(s._buffer,e)})})}_observeBatchCallbacks(e,t){return this._batchCallbacks.map(async({callback:r,instruments:n})=>{const s=new Rk;let i=Promise.resolve(r(s));null!=t&&(i=gT(i,t)),await i,n.forEach(t=>{const r=s._buffer.get(t);null!=r&&t._metricStorages.forEach(t=>{t.record(r,e)})})})}_findCallback(e,t){return this._callbacks.findIndex(r=>r.callback===e&&r.instrument===t)}_findBatchCallback(e,t){return this._batchCallbacks.findIndex(r=>r.callback===e&&function(e,t){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}(r.instruments,t))}}class Nk extends bk{_attributesProcessor;_aggregationCardinalityLimit;_deltaMetricStorage;_temporalMetricStorage;constructor(e,t,r,n,s){super(e),this._attributesProcessor=r,this._aggregationCardinalityLimit=s,this._deltaMetricStorage=new Ck(t,this._aggregationCardinalityLimit),this._temporalMetricStorage=new Ek(t,n)}record(e,t,r,n){t=this._attributesProcessor.process(t,r),this._deltaMetricStorage.record(e,t,r,n)}collect(e,t){const r=this._deltaMetricStorage.collect();return this._temporalMetricStorage.buildMetrics(e,this._instrumentDescriptor,r,t)}}class Pk{_processors;constructor(e){this._processors=e}process(e,t){let r=e;for(const e of this._processors)r=e.process(r,t);return r}}function Lk(){return Dk}const Dk=new class{process(e,t){return e}};class Uk{_meterProviderSharedState;_instrumentationScope;metricStorageRegistry=new Ok;observableRegistry=new Mk;meter;constructor(e,t){this._meterProviderSharedState=e,this._instrumentationScope=t,this.meter=new vk(this)}registerMetricStorage(e){const t=this._registerMetricStorage(e,Nk);return 1===t.length?t[0]:new Ak(t)}registerAsyncMetricStorage(e){return this._registerMetricStorage(e,Tk)}async collect(e,t,r){const n=await this.observableRegistry.observe(t,r?.timeoutMillis),s=this.metricStorageRegistry.getStorages(e);if(0===s.length)return null;const i=s.map(r=>r.collect(e,t)).filter(dT);return 0===i.length?{errors:n}:{scopeMetrics:{scope:this._instrumentationScope,metrics:i},errors:n}}_registerMetricStorage(e,t){let r=this._meterProviderSharedState.viewRegistry.findViews(e,this._instrumentationScope).map(r=>{const n=function(e,t){return{name:e.name??t.name,description:e.description??t.description,type:t.type,unit:t.unit,valueType:t.valueType,advice:t.advice}}(r,e),s=this.metricStorageRegistry.findOrUpdateCompatibleStorage(n);if(null!=s)return s;const i=r.aggregation.createAggregator(n),o=new t(n,i,r.attributesProcessor,this._meterProviderSharedState.metricCollectors,r.aggregationCardinalityLimit);return this.metricStorageRegistry.register(o),o});if(0===r.length){const n=this._meterProviderSharedState.selectAggregations(e.type).map(([r,n])=>{const s=this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(r,e);if(null!=s)return s;const i=n.createAggregator(e),o=r.selectCardinalityLimit(e.type),a=new t(e,i,Lk(),[r],o);return this.metricStorageRegistry.registerForCollector(r,a),a});r=r.concat(n)}return r}}class Fk{resource;viewRegistry=new ik;metricCollectors=[];meterSharedStates=new Map;constructor(e){this.resource=e}getMeterSharedState(e){const t=function(e){return`${e.name}:${e.version??""}:${e.schemaUrl??""}`}(e);let r=this.meterSharedStates.get(t);return null==r&&(r=new Uk(this,e),this.meterSharedStates.set(t,r)),r}selectAggregations(e){const t=[];for(const r of this.metricCollectors)t.push([r,ek(r.selectAggregation(e))]);return t}}class Bk{_sharedState;_metricReader;constructor(e,t){this._sharedState=e,this._metricReader=t}async collect(e){const t=mC(Date.now()),r=[],n=[],s=Array.from(this._sharedState.meterSharedStates.values()).map(async s=>{const i=await s.collect(this,t,e);null!=i?.scopeMetrics&&r.push(i.scopeMetrics),null!=i?.errors&&n.push(...i.errors)});return await Promise.all(s),{resourceMetrics:{resource:this._sharedState.resource,scopeMetrics:r},errors:n}}async forceFlush(e){await this._metricReader.forceFlush(e)}async shutdown(e){await this._metricReader.shutdown(e)}selectAggregationTemporality(e){return this._metricReader.selectAggregationTemporality(e)}selectAggregation(e){return this._metricReader.selectAggregation(e)}selectCardinalityLimit(e){return this._metricReader.selectCardinalityLimit?.(e)??2e3}}const jk=/[\^$\\.+?()[\]{}|]/g;class zk{_matchAll;_regexp;constructor(e){"*"===e?(this._matchAll=!0,this._regexp=/.*/):(this._matchAll=!1,this._regexp=new RegExp(zk.escapePattern(e)))}match(e){return!!this._matchAll||this._regexp.test(e)}static escapePattern(e){return`^${e.replace(jk,"\\$&").replace("*",".*")}$`}static hasWildcard(e){return e.includes("*")}}class Vk{_matchAll;_pattern;constructor(e){this._matchAll=void 0===e,this._pattern=e}match(e){return!!this._matchAll||e===this._pattern}}class Gk{_nameFilter;_type;_unitFilter;constructor(e){this._nameFilter=new zk(e?.name??"*"),this._type=e?.type,this._unitFilter=new Vk(e?.unit)}getType(){return this._type}getNameFilter(){return this._nameFilter}getUnitFilter(){return this._unitFilter}}class Hk{_nameFilter;_versionFilter;_schemaUrlFilter;constructor(e){this._nameFilter=new Vk(e?.name),this._versionFilter=new Vk(e?.version),this._schemaUrlFilter=new Vk(e?.schemaUrl)}getNameFilter(){return this._nameFilter}getVersionFilter(){return this._versionFilter}getSchemaUrlFilter(){return this._schemaUrlFilter}}class Zk{name;description;aggregation;attributesProcessor;instrumentSelector;meterSelector;aggregationCardinalityLimit;constructor(e){var t;!function(e){if(null==(t=e).instrumentName&&null==t.instrumentType&&null==t.instrumentUnit&&null==t.meterName&&null==t.meterVersion&&null==t.meterSchemaUrl)throw new Error("Cannot create view with no selector arguments supplied");var t;if(null!=e.name&&(null==e?.instrumentName||zk.hasWildcard(e.instrumentName)))throw new Error("Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.")}(e),null!=e.attributesProcessors?this.attributesProcessor=(t=e.attributesProcessors,new Pk(t)):this.attributesProcessor=Lk(),this.name=e.name,this.description=e.description,this.aggregation=ek(e.aggregation??{type:QT.DEFAULT}),this.instrumentSelector=new Gk({name:e.instrumentName,type:e.instrumentType,unit:e.instrumentUnit}),this.meterSelector=new Hk({name:e.meterName,version:e.meterVersion,schemaUrl:e.meterSchemaUrl}),this.aggregationCardinalityLimit=e.aggregationCardinalityLimit}}class $k{_sharedState;_shutdown=!1;constructor(e){if(this._sharedState=new Fk(e?.resource??xC()),null!=e?.views&&e.views.length>0)for(const t of e.views)this._sharedState.viewRegistry.addView(new Zk(t));if(null!=e?.readers&&e.readers.length>0)for(const t of e.readers){const e=new Bk(this._sharedState,t);t.setMetricProducer(e),this._sharedState.metricCollectors.push(e)}}getMeter(e,t="",r={}){return this._shutdown?(av.warn("A shutdown MeterProvider cannot provide a Meter"),xw()):this._sharedState.getMeterSharedState({name:e,version:t,schemaUrl:r.schemaUrl}).meter}async shutdown(e){this._shutdown?av.warn("shutdown may only be called once per MeterProvider"):(this._shutdown=!0,await Promise.all(this._sharedState.metricCollectors.map(t=>t.shutdown(e))))}async forceFlush(e){this._shutdown?av.warn("invalid attempt to force flush after MeterProvider shutdown"):await Promise.all(this._sharedState.metricCollectors.map(t=>t.forceFlush(e)))}}var Wk;function Yk(e,t){return Array.from(e.map(e=>({scope:iT(e.scope),metrics:e.metrics.map(e=>function(e,t){const r={name:e.descriptor.name,description:e.descriptor.description,unit:e.descriptor.unit},n=function(e){switch(e){case cT.DELTA:return Wk.AGGREGATION_TEMPORALITY_DELTA;case cT.CUMULATIVE:return Wk.AGGREGATION_TEMPORALITY_CUMULATIVE}}(e.aggregationTemporality);switch(e.dataPointType){case hT.SUM:r.sum={aggregationTemporality:n,isMonotonic:e.isMonotonic,dataPoints:Xk(e,t)};break;case hT.GAUGE:r.gauge={dataPoints:Xk(e,t)};break;case hT.HISTOGRAM:r.histogram={aggregationTemporality:n,dataPoints:Jk(e,t)};break;case hT.EXPONENTIAL_HISTOGRAM:r.exponentialHistogram={aggregationTemporality:n,dataPoints:Kk(e,t)}}return r}(e,t)),schemaUrl:e.scope.schemaUrl})))}function Xk(e,t){return e.dataPoints.map(r=>function(e,t,r){const n={attributes:oT(e.attributes),startTimeUnixNano:r.encodeHrTime(e.startTime),timeUnixNano:r.encodeHrTime(e.endTime)};switch(t){case Ow.INT:n.asInt=e.value;break;case Ow.DOUBLE:n.asDouble=e.value}return n}(r,e.descriptor.valueType,t))}function Jk(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:oT(e.attributes),bucketCounts:r.buckets.counts,explicitBounds:r.buckets.boundaries,count:r.count,sum:r.sum,min:r.min,max:r.max,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function Kk(e,t){return e.dataPoints.map(e=>{const r=e.value;return{attributes:oT(e.attributes),count:r.count,min:r.min,max:r.max,sum:r.sum,positive:{offset:r.positive.offset,bucketCounts:r.positive.bucketCounts},negative:{offset:r.negative.offset,bucketCounts:r.negative.bucketCounts},scale:r.scale,zeroCount:r.zeroCount,startTimeUnixNano:t.encodeHrTime(e.startTime),timeUnixNano:t.encodeHrTime(e.endTime)}})}function qk(e,t){return{resourceMetrics:e.map(e=>function(e,t){const r=nT(t);return{resource:sT(e.resource),schemaUrl:void 0,scopeMetrics:Yk(e.scopeMetrics,r)}}(e,t))}}function Qk(e,t){const r=e.spanContext(),n=e.status,s=e.parentSpanContext?.spanId?t.encodeSpanContext(e.parentSpanContext?.spanId):void 0;return{traceId:t.encodeSpanContext(r.traceId),spanId:t.encodeSpanContext(r.spanId),parentSpanId:s,traceState:r.traceState?.serialize(),name:e.name,kind:null==e.kind?0:e.kind+1,startTimeUnixNano:t.encodeHrTime(e.startTime),endTimeUnixNano:t.encodeHrTime(e.endTime),attributes:oT(e.attributes),droppedAttributesCount:e.droppedAttributesCount,events:e.events.map(e=>function(e,t){return{attributes:e.attributes?oT(e.attributes):[],name:e.name,timeUnixNano:t.encodeHrTime(e.time),droppedAttributesCount:e.droppedAttributesCount||0}}(e,t)),droppedEventsCount:e.droppedEventsCount,status:{code:n.code,message:n.message},links:e.links.map(e=>function(e,t){return{attributes:e.attributes?oT(e.attributes):[],spanId:t.encodeSpanContext(e.context.spanId),traceId:t.encodeSpanContext(e.context.traceId),traceState:e.context.traceState?.serialize(),droppedAttributesCount:e.droppedAttributesCount||0}}(e,t)),droppedLinksCount:e.droppedLinksCount}}function ex(e,t){const r=function(e){const t=new Map;for(const r of e){let e=t.get(r.resource);e||(e=new Map,t.set(r.resource,e));const n=`${r.instrumentationScope.name}@${r.instrumentationScope.version||""}:${r.instrumentationScope.schemaUrl||""}`;let s=e.get(n);s||(s=[],e.set(n,s)),s.push(r)}return t}(e),n=[],s=r.entries();let i=s.next();for(;!i.done;){const[e,r]=i.value,o=[],a=r.values();let l=a.next();for(;!l.done;){const e=l.value;if(e.length>0){const r=e.map(e=>Qk(e,t));o.push({scope:iT(e[0].instrumentationScope),spans:r,schemaUrl:e[0].instrumentationScope.schemaUrl})}l=a.next()}const c={resource:sT(e),scopeSpans:o,schemaUrl:void 0};n.push(c),i=s.next()}return n}!function(e){e[e.AGGREGATION_TEMPORALITY_UNSPECIFIED=0]="AGGREGATION_TEMPORALITY_UNSPECIFIED",e[e.AGGREGATION_TEMPORALITY_DELTA=1]="AGGREGATION_TEMPORALITY_DELTA",e[e.AGGREGATION_TEMPORALITY_CUMULATIVE=2]="AGGREGATION_TEMPORALITY_CUMULATIVE"}(Wk||(Wk={}));const tx={serializeRequest:e=>{const t=qk([e],{useLongBits:!1});return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{if(0===e.length)return{};const t=new TextDecoder;return JSON.parse(t.decode(e))}},rx={serializeRequest:e=>{const t={resourceSpans:ex(e,nT({useHex:!0,useLongBits:!1}))};return(new TextEncoder).encode(JSON.stringify(t))},deserializeResponse:e=>{if(0===e.length)return{};const t=new TextDecoder;return JSON.parse(t.decode(e))}};function nx(){return.4*Math.random()-.2}class sx{_transport;constructor(e){this._transport=e}retry(e,t,r){return new Promise((n,s)=>{setTimeout(()=>{this._transport.send(e,t).then(n,s)},r)})}async send(e,t){const r=Date.now()+t;let n=await this._transport.send(e,t),s=5,i=1e3;for(;"retryable"===n.status&&s>0;){s--;const t=Math.max(Math.min(i,5e3)+nx(),0);i*=1.5;const o=n.retryInMillis??t,a=r-Date.now();if(o>a)return n;n=await this.retry(e,a,o)}return n}shutdown(){return this._transport.shutdown()}}function ix(e){return new sx(e.transport)}function ox(e){if(null==e)return;const t=Number.parseInt(e,10);if(Number.isInteger(t))return t>0?1e3*t:-1;const r=new Date(e).getTime()-Date.now();return r>=0?r:0}class ax{_parameters;constructor(e){this._parameters=e}send(e,t){return new Promise(r=>{const n=new XMLHttpRequest;n.timeout=t,n.open("POST",this._parameters.url);const s=this._parameters.headers();Object.entries(s).forEach(([e,t])=>{n.setRequestHeader(e,t)}),n.ontimeout=e=>{r({status:"failure",error:new Error("XHR request timed out")})},n.onreadystatechange=()=>{var e;n.status>=200&&n.status<=299?(av.debug("XHR success"),r({status:"success"})):n.status&&(e=n.status,[429,502,503,504].includes(e))?r({status:"retryable",retryInMillis:ox(n.getResponseHeader("Retry-After"))}):0!==n.status&&r({status:"failure",error:new Error("XHR request failed with non-retryable status")})},n.onabort=()=>{r({status:"failure",error:new Error("XHR request aborted")})},n.onerror=()=>{r({status:"failure",error:new Error("XHR request errored")})},n.send(e)})}shutdown(){}}class lx{_params;constructor(e){this._params=e}send(e){return new Promise(t=>{navigator.sendBeacon(this._params.url,new Blob([e],{type:this._params.blobType}))?(av.debug("SendBeacon success"),t({status:"success"})):t({status:"failure",error:new Error("SendBeacon failed")})})}shutdown(){}}function cx(e,t,r){const n={...r()},s={};return()=>(null!=t&&Object.assign(s,t()),null!=e&&Object.assign(s,e()),Object.assign(s,n))}function ux(e){if(null!=e)try{return new URL(e),e}catch{throw new Error(`Configuration: Could not parse user-provided export URL: '${e}'`)}}function hx(e,t,r){return n={url:e.url,timeoutMillis:e.timeoutMillis,headers:VE(e.headers),concurrencyLimit:e.concurrencyLimit},s={},i=function(e,t){return{timeoutMillis:1e4,concurrencyLimit:30,compression:"none",headers:()=>e,url:"http://localhost:4318/"+t,agentOptions:{keepAlive:!0}}}(r,t),{...GE(n,s,i),headers:cx((o=n.headers,()=>{const e={};return Object.entries(o?.()??{}).forEach(([t,r])=>{void 0!==r?e[t]=String(r):av.warn(`Header "${t}" has invalid value (${r}) and will be ignored`)}),e}),s.headers,i.headers),url:ux(n.url)??s.url??i.url,agentOptions:n.agentOptions??s.agentOptions??i.agentOptions};var n,s,i,o}function px(e,t,r,n){const s=!!e.headers||"function"!=typeof navigator.sendBeacon,i=hx(e,r,n);return s?function(e,t){return YE(e,t,ix({transport:(r=e,new ax(r))}));var r}(i,t):function(e,t){return YE(e,t,ix({transport:(r={url:e.url,blobType:e.headers()["Content-Type"]},new lx(r))}));var r}(i,t)}class dx extends BE{constructor(e={}){super(px(e,rx,"v1/traces",{"Content-Type":"application/json"}))}}var fx;!function(e){e[e.DELTA=0]="DELTA",e[e.CUMULATIVE=1]="CUMULATIVE",e[e.LOWMEMORY=2]="LOWMEMORY"}(fx||(fx={}));const mx=()=>cT.CUMULATIVE,gx=e=>{switch(e){case uT.COUNTER:case uT.OBSERVABLE_COUNTER:case uT.GAUGE:case uT.HISTOGRAM:case uT.OBSERVABLE_GAUGE:return cT.DELTA;case uT.UP_DOWN_COUNTER:case uT.OBSERVABLE_UP_DOWN_COUNTER:return cT.CUMULATIVE}},yx=e=>{switch(e){case uT.COUNTER:case uT.HISTOGRAM:return cT.DELTA;case uT.GAUGE:case uT.UP_DOWN_COUNTER:case uT.OBSERVABLE_UP_DOWN_COUNTER:case uT.OBSERVABLE_COUNTER:case uT.OBSERVABLE_GAUGE:return cT.CUMULATIVE}};function wx(e){return null!=e?e===fx.DELTA?gx:e===fx.LOWMEMORY?yx:mx:function(){const e="cumulative".toLowerCase();return"cumulative"===e?mx:"delta"===e?gx:"lowmemory"===e?yx:(av.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${e}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`),mx)}()}const vx=Object.freeze({type:QT.DEFAULT});class bx extends BE{_aggregationTemporalitySelector;_aggregationSelector;constructor(e,t){super(e),this._aggregationSelector=function(e){return e?.aggregationPreference??(()=>vx)}(t),this._aggregationTemporalitySelector=wx(t?.temporalityPreference)}selectAggregation(e){return this._aggregationSelector(e)}selectAggregationTemporality(e){return this._aggregationTemporalitySelector(e)}}class _x extends bx{constructor(e){super(px(e??{},tx,"v1/metrics",{"Content-Type":"application/json"}),e)}}const Sx=["LCP","INP","CLS","FCP","TTFB"],Cx={LCP:[500,1e3,1500,2e3,2500,3e3,4e3,6e3,1e4,2e4],INP:[50,100,200,300,400,500,1e3,2e3],CLS:[.01,.05,.1,.15,.2,.25,.4,.6,1],FCP:[500,1e3,1800,2400,3e3,4e3,6e3,1e4],TTFB:[100,200,400,600,800,1200,1800,3e3,6e3]};class Ex{constructor(e){this._enabled=!0,this._active=!1,this.record=e}async start(){if("undefined"!=typeof window&&!this._active){this._active=!0;try{const{onCLS:e,onINP:t,onLCP:r,onFCP:n,onTTFB:s}=await Promise.resolve().then(function(){return LO}),i=e=>{this._enabled&&(e=>Sx.includes(e))(e.name)&&this.record(e.name,e.value,{"web_vital.rating":e.rating,"web_vital.id":e.id,"web_vital.navigation_type":e.navigationType})};[e,t,r,n,s].forEach(e=>e(i))}catch(e){console.warn("Monoscope: web-vitals collection failed to initialize",e)}}}setEnabled(e){this._enabled=e}}const Tx="monoscope";function kx(e){try{const t=new URL(e,"undefined"!=typeof location?location.href:"http://_");return t.pathname+(t.search?"?…":"")}catch{return e.slice(0,80)}}function xx(){try{if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID()}catch{}const e=new Uint8Array(16);try{crypto.getRandomValues(e)}catch{for(let t=0;t<16;t++)e[t]=256*Math.random()|0}e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}class Ox{constructor(e,t,r){if(this.pageviewId="",this.processor=null,this.meterProvider=null,this.metricReader=null,this.vitalHistograms={},this.pageviewMaxTimer=null,this.longTaskObserver=null,this.loafObserver=null,this.resourceObserver=null,this._enabled=!0,this._configured=!1,this._firstExportLogged=!1,this.routeSpan=null,this.routeContext=null,this.routeIdleTimer=null,this.pageviewSpan=null,this.pageviewContext=null,this.flushOnHideHandler=null,this.visibilityHandler=null,this.lastInteractionAt=new WeakMap,this.onExportStatus=null,this.onSpanStart=null,this.config=e,this.sessionId=t,this.tabId=r,this.provider=this.createProvider(),!1!==e.captureWebVitals)try{this.meterProvider=this.createMeterProvider()}catch(e){console.warn("[Monoscope] Web-vital metrics disabled (init failed)",e),this.meterProvider=null}}createMeterProvider(){const{serviceName:e,resourceAttributes:t={},exporterEndpoint:r,metricsExporterEndpoint:n}=this.config,s=this.config.apiKey||this.config.projectId||"";let i;if(n)i=n;else if(r){const e=r.replace(/\/v1\/traces\b/,"/v1/metrics");if(e===r)return console.warn("[Monoscope] Web-vital metrics disabled: exporterEndpoint does not contain /v1/traces — set metricsExporterEndpoint to enable."),null;i=e}else i="https://otelcol.monoscope.tech/v1/metrics";const o=new _x({url:i,headers:{"x-api-key":s},temporalityPreference:fx.DELTA}),a=new sk({exporter:o,exportIntervalMillis:3e4});return this.metricReader=a,new $k({resource:jb({[Hv]:e,"x-api-key":s,...t}),readers:[a]})}recordWebVital(e,t,r){if(this._enabled&&this.meterProvider)try{let n=this.vitalHistograms[e];if(!n){n=this.meterProvider.getMeter(Tx).createHistogram(`browser.web_vital.${e.toLowerCase()}`,{description:`Core Web Vital: ${e}`,unit:"CLS"===e?"1":"ms",advice:{explicitBucketBoundaries:Cx[e]}}),this.vitalHistograms[e]=n}n.record(t,{...this.commonAttrs(),...r})}catch(t){this.config.debug&&console.warn("Monoscope: recordWebVital failed for",e,t)}}createProvider(){const{serviceName:e,resourceAttributes:t={},exporterEndpoint:r}=this.config,n=this.config.apiKey||this.config.projectId||"",s=this,i=new dx({url:r||"https://otelcol.monoscope.tech/v1/traces",headers:{"x-api-key":n}}),o=Object.create(i,{export:{value:(e,t)=>i.export(e,e=>{if(!s._firstExportLogged){s._firstExportLogged=!0;const t=0===e.code;if(s.config.debug&&(console.log(t?"%c[Monoscope] ✓ First trace sent successfully":"%c[Monoscope] ✗ First trace export failed",t?"color: #22c55e; font-weight: bold":"color: #ef4444; font-weight: bold",t?"":e.error||""),!t)){const t=String(e.error||"");t.includes("401")||t.includes("403")?console.warn("[Monoscope] Authentication failed. Your apiKey may be invalid."):console.warn("[Monoscope] Could not reach Monoscope endpoint. Check your apiKey and network.")}s.onExportStatus?.(t)}t(e)})}}),a=new e_(o);this.processor=a;const l={onStart:()=>{try{s.onSpanStart?.()}catch{}},onEnd:()=>{},shutdown:()=>Promise.resolve(),forceFlush:()=>Promise.resolve()},c=new y_({resource:jb({[Hv]:e,"x-api-key":n,...t}),spanProcessors:[a,l]}),u=c.getTracer.bind(c);return c.getTracer=(e,t,r)=>{const n=u(e,t,r);if(n.__monoscopeWrapped)return n;const i=n.startSpan.bind(n),o=n.startActiveSpan.bind(n),a=e=>{const t=e??ov.active();return Cv.getSpan(t)?t:s.pageviewContext??t};return n.startSpan=(e,t,r)=>i(e,t,a(r)),n.startActiveSpan=(e,...t)=>{let r,n,s;return 1===t.length?[s]=t:2===t.length?[r,s]=t:[r,n,s]=t,o(e,r,a(n),s)},n.__monoscopeWrapped=!0,n},c}startPageview(){if(!this.pageviewSpan)try{const e=this.provider.getTracer(Tx).startSpan("pageview",{attributes:{"monoscope.kind":"pageview","monoscope.display.label":`Pageview · ${kx(location.href)}`}},ov.active());this.applyCommonAttrs(e),this.pageviewSpan=e;const t=bv.createBaggage({"session.id":{value:this.sessionId},"tab.id":{value:this.tabId}});this.pageviewContext=bv.setBaggage(Cv.setSpan(ov.active(),e),t),this.pageviewMaxTimer=setTimeout(()=>this.rollPageview(),18e5)}catch(e){console.warn("[Monoscope] startPageview failed — spans will be orphaned",e)}}endPageview(){this.pageviewMaxTimer&&(clearTimeout(this.pageviewMaxTimer),this.pageviewMaxTimer=null);try{this.pageviewSpan?.end()}catch(e){this.config.debug&&console.warn("Monoscope: endPageview failed",e)}this.pageviewSpan=null,this.pageviewContext=null}rollPageview(){this._enabled&&(this.endPageview(),this.rotatePageview(),this.startPageview())}commonAttrs(){const e={"session.id":this.sessionId,"tab.id":this.tabId,"pageview.id":this.pageviewId,"page.url":location.href,"page.title":document.title};return document.referrer&&(e["page.referrer"]=document.referrer),e}applyCommonAttrs(e){for(const[t,r]of Object.entries(this.commonAttrs()))e.setAttribute(t,r);if(this.config.user)for(const[t,r]of Object.entries(this.config.user))void 0!==r&&e.setAttribute(`user.${t}`,r);if(this.config.tenant)for(const[t,r]of Object.entries(this.config.tenant))void 0!==r&&e.setAttribute(`tenant.${t}`,r)}configure(){if("undefined"==typeof window||this._configured)return;this._configured=!0;const e=Math.max(0,Math.min(1,this.config.sampleRate??1));let t;try{const r=sessionStorage.getItem("monoscope-sampled");"1"===r||"0"===r?t="1"===r:(t=Math.random(){this.applyCommonAttrs(e),e.setAttribute("monoscope.kind",t),r&&e.setAttribute("monoscope.display.label",r)},i=!1!==this.config.enableUserInteraction?[new FE({eventNames:["click","submit"],shouldPreventSpanCreation:(e,t,r)=>{const n=function(e){const t=e;return t&&"function"==typeof t.closest?t.closest("button,a[href],input,select,textarea,summary,label,[role=button],[role=link],[role=menuitem],[role=tab],[role=switch],[role=checkbox],[role=radio],[role=option],[data-monoscope-track]"):null}(t);if(!n)return!0;const i=performance.now();if(i-(this.lastInteractionAt.get(n)??0)<250)return!0;this.lastInteractionAt.set(n,i),s(r,"interaction",`${e} · ${function(e){const t=e;if(!t||!t.tagName)return"?";const r=t.getAttribute?.("aria-label");if(r)return r;const n=(t.textContent||"").trim().replace(/\s+/g," ").slice(0,40);if(n)return n;const s=t.id?`#${t.id}`:"",i=(t.getAttribute?.("class")||"").split(" ").filter(Boolean)[0];return`${t.tagName.toLowerCase()}${s}${i?`.${i}`:""}`}(n)}`),r.setAttribute("target.tag_name",n.tagName?.toLowerCase()||""),n.id&&r.setAttribute("target.id",n.id);const o=n.getAttribute("role");return o&&r.setAttribute("target.role",o),!1}})]:[];!function(e){const t=e.tracerProvider||Cv.getTracerProvider(),r=e.meterProvider||hv.getMeterProvider(),n=e.loggerProvider||I_.getLoggerProvider(),s=e.instrumentations?.flat()??[];(function(e,t,r,n){for(let s=0,i=e.length;ss(e,"page_load",`Page · ${kx(location.href)}`),resourceFetch:e=>s(e,"resource")}}),new YC({propagateTraceHeaderCorsUrls:r,ignoreUrls:n,applyCustomAttributesOnSpan:(e,t)=>{const r=t.responseURL;s(e,"network",r?`XHR · ${kx(r)}`:void 0)}}),new mE({propagateTraceHeaderCorsUrls:r,ignoreUrls:n,applyCustomAttributesOnSpan:(e,t)=>{let r,n="GET";"string"==typeof t?r=t:t&&"string"==typeof t.url?(r=t.url,n=t.method||"GET"):t&&"string"==typeof t.method&&(n=t.method),s(e,"network",r?`${n} · ${kx(r)}`:void 0)}}),...i]}),!0===this.config.captureLongTasks&&this.observeLongTasks(),!1!==this.config.captureLongAnimationFrames&&this.observeLongAnimationFrames(),this.config.captureResourceTiming&&this.observeResourceTiming(),this.installFlushOnHide()}getPageviewId(){return this.pageviewId}rotatePageview(){return this.pageviewId=xx(),this.pageviewId}startRouteChange(e,t,r){try{this.endRouteChange(),this.rollPageview();const n=this.provider.getTracer(Tx).startSpan("route.change",{attributes:{"navigation.from":e,"navigation.to":t,"navigation.method":r,"monoscope.kind":"navigation","monoscope.display.label":`Nav · ${kx(e)} → ${kx(t)}`}});this.applyCommonAttrs(n),this.routeSpan=n,this.routeContext=Cv.setSpan(ov.active(),n),this.routeIdleTimer=setTimeout(()=>{try{this.endRouteChange()}catch(e){this.config.debug&&console.warn("Monoscope: route idle close failed",e)}},3e3)}catch(e){this.config.debug&&console.warn("Monoscope: startRouteChange failed",e),this.routeSpan=null,this.routeContext=null,this.routeIdleTimer=null}}endRouteChange(){this.routeIdleTimer&&(clearTimeout(this.routeIdleTimer),this.routeIdleTimer=null);try{this.routeSpan?.end()}catch(e){this.config.debug&&console.warn("Monoscope: endRouteChange failed",e)}this.routeSpan=null,this.routeContext=null}installFlushOnHide(){const e=e=>t=>{this.config.debug&&console.warn(`Monoscope: ${e} failed`,t)},t=()=>{try{this.endRouteChange(),this.endPageview(),this.processor?.forceFlush().catch(e("trace flush")),this.metricReader?.forceFlush().catch(e("metric flush"))}catch(e){this.config.debug&&console.warn("Monoscope: flush on hide failed",e)}};this.flushOnHideHandler=t,this.visibilityHandler=()=>{"hidden"===document.visibilityState?t():this._enabled&&!this.pageviewSpan&&this.rollPageview()},window.addEventListener("pagehide",this.flushOnHideHandler),document.addEventListener("visibilitychange",this.visibilityHandler)}withActiveContext(e){const t=this.routeContext??this.pageviewContext;return t?ov.with(t,e):e()}emitSpan(e,t,r,n,s){if(this._enabled)try{const i=this.provider.getTracer(Tx),o=this.routeContext??this.pageviewContext??ov.active();i.startActiveSpan(e,{startTime:n},o,e=>{try{this.applyCommonAttrs(e);for(const[r,n]of Object.entries(t))e.setAttribute(r,n);r?.(e)}finally{e.end(s)}})}catch(t){this.config.debug&&console.warn("Monoscope: span emit failed for",e,t)}}observeLongTasks(){if("undefined"!=typeof PerformanceObserver)try{this.longTaskObserver=new PerformanceObserver(e=>{if(this._enabled)for(const t of e.getEntries())try{const e=Math.round(t.duration),r={"longtask.duration":t.duration,"longtask.name":t.name,"monoscope.kind":"long_task"},n=t.attribution?.[0];n?.containerType&&(r["longtask.container_type"]=n.containerType),n?.containerSrc&&(r["longtask.script"]=n.containerSrc),n?.containerName&&(r["longtask.container"]=n.containerName),n?.containerId&&(r["longtask.container_id"]=n.containerId);const s=n?.containerSrc||n?.containerName||n?.containerId,i=s?kx(s):n?.containerType||t.name||"self";r["monoscope.display.label"]=`Long task · ${i} · ${e}ms`;const o=performance.timeOrigin+t.startTime;this.emitSpan("longtask",r,void 0,o,o+t.duration)}catch(e){this.config.debug&&console.warn("Monoscope: failed to process longtask entry",e)}}),this.longTaskObserver.observe({type:"longtask",buffered:!0})}catch(e){console.warn("Monoscope: longtask observation not supported",e)}}observeLongAnimationFrames(){if("undefined"==typeof PerformanceObserver)return;const e=PerformanceObserver.supportedEntryTypes;if(!Array.isArray(e)||e.includes("long-animation-frame"))try{this.loafObserver=new PerformanceObserver(e=>{if(this._enabled)for(const t of e.getEntries())try{const e=Math.round(t.duration),r={"loaf.duration":t.duration,"loaf.render_start":t.renderStart||0,"loaf.style_and_layout_start":t.styleAndLayoutStart||0,"loaf.blocking_duration":t.blockingDuration||0,"monoscope.kind":"long_animation_frame"},n=t.scripts||[],s=n.reduce((e,t)=>(t?.duration||0)>(e?.duration||0)?t:e,n[0]);s&&(s.invoker&&(r["loaf.invoker"]=s.invoker),s.invokerType&&(r["loaf.invoker_type"]=s.invokerType),s.sourceURL&&(r["loaf.source_url"]=s.sourceURL),s.sourceFunctionName&&(r["loaf.source_function"]=s.sourceFunctionName),"number"==typeof s.sourceCharPosition&&s.sourceCharPosition>=0&&(r["loaf.source_char_position"]=s.sourceCharPosition),"number"==typeof s.duration&&(r["loaf.script_duration"]=s.duration),"number"==typeof s.forcedStyleAndLayoutDuration&&(r["loaf.forced_style_layout_duration"]=s.forcedStyleAndLayoutDuration)),r["loaf.script_count"]=n.length;const i=s?.sourceFunctionName,o=s?.sourceURL?kx(s.sourceURL):void 0,a=s?.invoker,l=i&&o?`${i} @ ${o}`:o||(a||"anonymous");r["monoscope.display.label"]=`LoAF · ${l} · ${e}ms`;const c=performance.timeOrigin+t.startTime;this.emitSpan("long-animation-frame",r,void 0,c,c+t.duration)}catch(e){this.config.debug&&console.warn("Monoscope: failed to process LoAF entry",e)}}),this.loafObserver.observe({type:"long-animation-frame",buffered:!0})}catch(e){this.config.debug&&console.warn("Monoscope: long-animation-frame not supported",e)}}observeResourceTiming(){if("undefined"==typeof PerformanceObserver)return;const e=this.config.resourceTimingThresholdMs??200;try{this.resourceObserver=new PerformanceObserver(t=>{if(this._enabled)for(const r of t.getEntries())if(!(r.durationr.startActiveSpan(e,e=>{this.applyCommonAttrs(e);try{const r=t(e);return r instanceof Promise?r.then(t=>(e.end(),t),t=>{throw e.setStatus({code:iv.ERROR,message:String(t)}),e.end(),t}):(e.end(),r)}catch(t){throw e.setStatus({code:iv.ERROR,message:String(t)}),e.end(),t}}))}recordEvent(e,t={}){this.emitSpan(e,t)}async forceFlush(){await Promise.all([this.processor?.forceFlush(),this.metricReader?.forceFlush()])}updateSessionId(e){if(this.sessionId=e,this.pageviewSpan&&this.pageviewContext){const t=bv.createBaggage({"session.id":{value:e},"tab.id":{value:this.tabId}});this.pageviewContext=bv.setBaggage(this.pageviewContext,t)}}setEnabled(e){this._enabled=e}async shutdown(){this.longTaskObserver?.disconnect(),this.loafObserver?.disconnect(),this.resourceObserver?.disconnect(),this.endRouteChange(),this.endPageview(),this.flushOnHideHandler&&(window.removeEventListener("pagehide",this.flushOnHideHandler),this.flushOnHideHandler=null),this.visibilityHandler&&(document.removeEventListener("visibilitychange",this.visibilityHandler),this.visibilityHandler=null),this._configured=!1;const e=await Promise.allSettled([this.provider.shutdown(),this.meterProvider?.shutdown()??Promise.resolve()]);for(const t of e)"rejected"===t.status&&console.warn("[Monoscope] shutdown error (some telemetry may not have been exported)",t.reason);this.meterProvider=null}setUser(e){this.config={...this.config,user:{...this.config.user,...e}}}setTenant(e){this.config={...this.config,tenant:{...this.config.tenant,...e}}}}const Ax=[];function Ix(e){Ax.push({...e,timestamp:Date.now()}),Ax.length>20&&Ax.shift()}function Rx(e){try{return JSON.stringify(e)}catch{return`[unserializable: ${typeof e}]`}}const Mx=/(?:chrome|moz|safari|safari-web|ms-browser)-extension:\/\//i;class Nx{constructor(e,t={}){this.errorCount=0,this.droppedExtensionCount=0,this._active=!1,this.prevOnError=null,this.onUnhandledRejection=null,this.origConsoleError=null,this._processing=!1,this.emit=e,this.captureExtensionErrors=!!t.captureExtensionErrors,this.debug=!!t.debug}shouldDrop(e){return!this.captureExtensionErrors&&(!!function(...e){return e.some(e=>"string"==typeof e&&Mx.test(e))}(e["error.source"],e["error.stack"])&&(this.droppedExtensionCount++,this.debug&&this.origConsoleError&&this.origConsoleError.call(console,"[Monoscope] dropped extension error",{message:e["error.message"],source:e["error.source"]}),!0))}createErrorSpan(e,t,r){this.errorCount++;const n=Ax.slice(),s=String(r["error.name"]||t),i=String(r["error.message"]||"").replace(/\s+/g," ").slice(0,80);this.emit(e,{"error.type":t,"error.count":this.errorCount,"monoscope.kind":"error","monoscope.display.label":i?`${s} · ${i}`:s,...r},e=>{e.setStatus({code:iv.ERROR}),n.length>0&&e.setAttribute("breadcrumbs",Rx(n))})}start(){"undefined"==typeof window||this._active||(this._active=!0,this.prevOnError=window.onerror,window.onerror=(e,t,r,n,s)=>{const i={"error.message":"string"==typeof e?e:e.type};return t&&(i["error.source"]=t),void 0!==r&&(i["error.lineno"]=r),void 0!==n&&(i["error.colno"]=n),s?.stack&&(i["error.stack"]=s.stack),s?.name&&(i["error.name"]=s.name),this.shouldDrop(i)||this.createErrorSpan("exception","uncaught_exception",i),"function"==typeof this.prevOnError?this.prevOnError.call(window,e,t,r,n,s):void 0},this.onUnhandledRejection=e=>{const t=e.reason,r={};t instanceof Error?(r["error.message"]=t.message,r["error.name"]=t.name,t.stack&&(r["error.stack"]=t.stack)):r["error.message"]=String(t),this.shouldDrop(r)||this.createErrorSpan("unhandled_rejection","unhandled_rejection",r)},this.origConsoleError=console.error,console.error=(...e)=>{if(this.origConsoleError?.apply(console,e),!this._processing){this._processing=!0;try{const t=e.map(e=>e instanceof Error?e.message:"string"==typeof e?e:Rx(e)).join(" "),r={"error.message":t},n=e.find(e=>e instanceof Error);if(n&&(r["error.name"]=n.name,n.stack&&(r["error.stack"]=n.stack)),this.shouldDrop(r))return;Ix({type:"console.error",message:t}),this.createErrorSpan("console.error","console_error",r)}finally{this._processing=!1}}},window.addEventListener("unhandledrejection",this.onUnhandledRejection))}stop(){"undefined"!=typeof window&&this._active&&(this._active=!1,window.onerror=this.prevOnError,this.prevOnError=null,this.onUnhandledRejection&&window.removeEventListener("unhandledrejection",this.onUnhandledRejection),this.origConsoleError&&(console.error=this.origConsoleError,this.origConsoleError=null))}getErrorCount(){return this.errorCount}getDroppedExtensionCount(){return this.droppedExtensionCount}}class Px{constructor(e){this.currentUrl="",this._active=!1,this.origPushState=null,this.origReplaceState=null,this.popstateHandler=null,this.onNavigation=e}start(){if("undefined"==typeof window||this._active)return;this._active=!0,this.currentUrl=location.href,this.origPushState=history.pushState.bind(history),this.origReplaceState=history.replaceState.bind(history);const e=e=>{try{const t=this.currentUrl,r=location.href;if(t===r)return;this.currentUrl=r,Ix({type:"navigation",message:`${t} → ${r}`,data:{method:e}}),this.onNavigation(t,r,e)}catch(e){try{console.warn("Monoscope: error in navigation tracking",e)}catch{}}};history.pushState=(...t)=>{this.origPushState(...t),e("pushState")},history.replaceState=(...t)=>{this.origReplaceState(...t),e("replaceState")},this.popstateHandler=()=>e("popstate"),window.addEventListener("popstate",this.popstateHandler)}stop(){"undefined"!=typeof window&&this._active&&(this._active=!1,this.origPushState&&(history.pushState=this.origPushState),this.origReplaceState&&(history.replaceState=this.origReplaceState),this.popstateHandler&&window.removeEventListener("popstate",this.popstateHandler),this.origPushState=null,this.origReplaceState=null,this.popstateHandler=null)}}const Lx="monoscope-overlay-dismissed";class Dx{constructor(){if(this.el=null,this.eventCount=0,this.statusDot=null,this.countEl=null,this.connEl=null,"undefined"!=typeof document){try{if(sessionStorage.getItem(Lx))return}catch{}this.mount()}}mount(){const e=document.createElement("div");Object.assign(e.style,{position:"fixed",bottom:"12px",right:"12px",zIndex:"2147483647",background:"#1a1a2e",color:"#e0e0e0",fontFamily:"system-ui, sans-serif",fontSize:"12px",padding:"6px 10px",borderRadius:"6px",boxShadow:"0 2px 8px rgba(0,0,0,0.3)",display:"flex",alignItems:"center",gap:"6px",cursor:"default",userSelect:"none"}),this.statusDot=document.createElement("span"),Object.assign(this.statusDot.style,{width:"7px",height:"7px",borderRadius:"50%",background:"#22c55e",display:"inline-block"}),this.countEl=document.createElement("span"),this.countEl.textContent="0",this.countEl.style.opacity="0.7",this.connEl=document.createElement("span"),this.connEl.style.opacity="0.7";const t=document.createElement("span");t.textContent="×",Object.assign(t.style,{cursor:"pointer",marginLeft:"4px",opacity:"0.6",fontSize:"14px"}),t.onclick=()=>this.dismiss(),e.append(this.statusDot," Monoscope ",this.countEl," ",this.connEl,t),this.el=e,(document.body||document.documentElement).appendChild(e)}incrementEvents(){this.eventCount++,this.countEl&&(this.countEl.textContent=String(this.eventCount))}setConnectionStatus(e){this.connEl&&(this.connEl.textContent=e?"Connected":"Connection failed"),this.statusDot&&(this.statusDot.style.background=e?"#22c55e":"#ef4444")}dismiss(){this.el?.remove(),this.el=null;try{sessionStorage.setItem(Lx,"1")}catch{}}}const Ux=18e5,Fx="monoscope-last-activity",Bx="undefined"!=typeof window;var jx,zx,Vx,Gx,Hx,Zx=-1,$x=function(e){addEventListener("pageshow",function(t){t.persisted&&(Zx=t.timeStamp,e(t))},!0)},Wx=function(){var e=self.performance&&performance.getEntriesByType&&performance.getEntriesByType("navigation")[0];if(e&&e.responseStart>0&&e.responseStart=0?n="back-forward-cache":r&&(document.prerendering||Yx()>0?n="prerender":document.wasDiscarded?n="restore":r.type&&(n=r.type.replace(/_/g,"-"))),{name:e,value:void 0===t?-1:t,rating:"good",delta:0,entries:[],id:"v4-".concat(Date.now(),"-").concat(Math.floor(8999999999999*Math.random())+1e12),navigationType:n}},Jx=function(e,t,r){try{if(PerformanceObserver.supportedEntryTypes.includes(e)){var n=new PerformanceObserver(function(e){Promise.resolve().then(function(){t(e.getEntries())})});return n.observe(Object.assign({type:e,buffered:!0},r||{})),n}}catch(e){}},Kx=function(e,t,r,n){var s,i;return function(o){t.value>=0&&(o||n)&&((i=t.value-(s||0))||void 0===s)&&(s=t.value,t.delta=i,t.rating=function(e,t){return e>t[1]?"poor":e>t[0]?"needs-improvement":"good"}(t.value,r),e(t))}},qx=function(e){requestAnimationFrame(function(){return requestAnimationFrame(function(){return e()})})},Qx=function(e){document.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&e()})},eO=function(e){var t=!1;return function(){t||(e(),t=!0)}},tO=-1,rO=function(){return"hidden"!==document.visibilityState||document.prerendering?1/0:0},nO=function(e){"hidden"===document.visibilityState&&tO>-1&&(tO="visibilitychange"===e.type?e.timeStamp:0,iO())},sO=function(){addEventListener("visibilitychange",nO,!0),addEventListener("prerenderingchange",nO,!0)},iO=function(){removeEventListener("visibilitychange",nO,!0),removeEventListener("prerenderingchange",nO,!0)},oO=function(){return tO<0&&(tO=rO(),sO(),$x(function(){setTimeout(function(){tO=rO(),sO()},0)})),{get firstHiddenTime(){return tO}}},aO=function(e){document.prerendering?addEventListener("prerenderingchange",function(){return e()},!0):e()},lO=[1800,3e3],cO=function(e,t){t=t||{},aO(function(){var r,n=oO(),s=Xx("FCP"),i=Jx("paint",function(e){e.forEach(function(e){"first-contentful-paint"===e.name&&(i.disconnect(),e.startTimet.latency){if(r)e.duration>r.latency?(r.entries=[e],r.latency=e.duration):e.duration===r.latency&&e.startTime===r.entries[0].startTime&&r.entries.push(e);else{var n={id:e.interactionId,latency:e.duration,entries:[e]};wO.set(n.id,n),yO.push(n)}yO.sort(function(e,t){return t.latency-e.latency}),yO.length>10&&yO.splice(10).forEach(function(e){return wO.delete(e.id)})}}},SO=function(e){var t=self.requestIdleCallback||self.setTimeout,r=-1;return e=eO(e),"hidden"===document.visibilityState?e():(r=t(e),Qx(e)),r},CO=[200,500],EO=[2500,4e3],TO={},kO=[800,1800],xO=function e(t){document.prerendering?aO(function(){return e(t)}):"complete"!==document.readyState?addEventListener("load",function(){return e(t)},!0):setTimeout(t,0)},OO={passive:!0,capture:!0},AO=new Date,IO=function(e,t){zx||(zx=t,Vx=e,Gx=new Date,NO(removeEventListener),RO())},RO=function(){if(Vx>=0&&Vx1e12?new Date:performance.now())-e.timeStamp;"pointerdown"==e.type?function(e,t){var r=function(){IO(e,t),s()},n=function(){s()},s=function(){removeEventListener("pointerup",r,OO),removeEventListener("pointercancel",n,OO)};addEventListener("pointerup",r,OO),addEventListener("pointercancel",n,OO)}(t,e):IO(t,e)}},NO=function(e){["mousedown","keydown","touchstart","pointerdown"].forEach(function(t){return e(t,MO,OO)})},PO=[100,300],LO=Object.freeze({__proto__:null,CLSThresholds:uO,FCPThresholds:lO,FIDThresholds:PO,INPThresholds:CO,LCPThresholds:EO,TTFBThresholds:kO,onCLS:function(e,t){t=t||{},cO(eO(function(){var r,n=Xx("CLS",0),s=0,i=[],o=function(e){e.forEach(function(e){if(!e.hadRecentInput){var t=i[0],r=i[i.length-1];s&&e.startTime-r.startTime<1e3&&e.startTime-t.startTime<5e3?(s+=e.value,i.push(e)):(s=e.value,i=[e])}}),s>n.value&&(n.value=s,n.entries=i,r())},a=Jx("layout-shift",o);a&&(r=Kx(e,n,uO,t.reportAllChanges),Qx(function(){o(a.takeRecords()),r(!0)}),$x(function(){s=0,n=Xx("CLS",0),r=Kx(e,n,uO,t.reportAllChanges),qx(function(){return r()})}),setTimeout(r,0))}))},onFCP:cO,onFID:function(e,t){t=t||{},aO(function(){var r,n=oO(),s=Xx("FID"),i=function(e){e.startTimethis.otel.emitSpan(...e),{captureExtensionErrors:e.captureExtensionErrors,debug:e.debug}),this.vitals=new Ex((e,t,r)=>this.otel.recordWebVital(e,t,r)),this.router=new Px((e,t,r)=>this.otel.startRouteChange(e,t,r)),this._enabled&&(this.otel.configure(),this.replay.configure(),this.errors.start(),!1!==this.config.captureWebVitals&&this.vitals.start().catch(e=>{this.config.debug&&console.warn("Monoscope: web-vitals init failed",e)}),this.router.start()),this._enabled&&this.config.debug&&(this.logInitBanner(),Bx&&(this.overlay=new Dx,this.otel.onExportStatus=e=>this.overlay?.setConnectionStatus(e),this.otel.onSpanStart=()=>this.overlay?.incrementEvents())),Bx&&this.setupActivityTracking()}logInitBanner(){const e=this.config,t=e.exporterEndpoint||"https://otelcol.monoscope.tech/v1/traces",r=Math.round(100*(e.sampleRate??1)),n=Math.round(100*(e.replaySampleRate??1));console.groupCollapsed("%c[Monoscope] ✓ Initialized","color: #22c55e; font-weight: bold"),console.log(` API Key: ${e.apiKey}`),console.log(` Service: ${e.serviceName}`),console.log(` Session: ${this.sessionId}`),console.log(` Tracing: ✓ (sample rate: ${r}%)`),console.log(` Replay: ✓ (sample rate: ${n}%)`),console.log(" Errors: ✓"),console.log(` Endpoint: ${t}`),console.groupEnd()}resolveSessionId(){try{const e=sessionStorage.getItem("monoscope-session-id"),t=sessionStorage.getItem(Fx);if(e&&t){if(Date.now()-parseInt(t,10){this.config.debug&&console.warn("Monoscope: failed to save replay on session rotation",e)}),Ax.length=0,this.sessionId=xx();try{sessionStorage.setItem("monoscope-session-id",this.sessionId)}catch(e){this.config.debug&&console.warn("Monoscope: failed to persist session ID",e)}this.replay.updateSessionId(this.sessionId),this.otel.updateSessionId(this.sessionId),this.config.debug&&console.log("Monoscope: session rotated due to inactivity")}checkAndRefreshSession(){const e=Date.now();e-this.lastActivityTime>=Ux&&this.rotateSession(),this.lastActivityTime=e,this.persistActivity()}setupActivityTracking(){document.addEventListener("visibilitychange",()=>{"visible"===document.visibilityState&&this.checkAndRefreshSession()});let e=Date.now();const t=()=>{const t=Date.now();t-e>5e3&&(e=t,this.lastActivityTime=t,this.persistActivity())};document.addEventListener("click",e=>{t();const r=e.target;if(!r)return;const n=r.tagName?.toLowerCase()||"",s=(r.textContent||"").trim().slice(0,50),i=r.getAttribute("class")||"";Ix({type:"click",message:`${n} "${s}"`,data:{selector:r.id?`#${r.id}`:i?`.${i.split(" ")[0]}`:n}})},{capture:!0,passive:!0}),document.addEventListener("keydown",t,{capture:!0,passive:!0})}getSessionId(){return this.sessionId}getTabId(){return this.tabId}setUser(e){if(this.config.debug){const t=new Set(["email","full_name","name","id","roles"]),r=Object.keys(e).filter(e=>!t.has(e));r.length&&console.warn(`Monoscope: unknown user attributes will be sent to collectors: ${r.join(", ")}`)}this.otel.setUser(e),this.replay.setUser(e)}setTenant(e){if(this.config.debug){const t=new Set(["id","name"]),r=Object.keys(e).filter(e=>!t.has(e));r.length&&console.warn(`Monoscope: unknown tenant attributes will be sent to collectors: ${r.join(", ")}`)}this.otel.setTenant(e),this.replay.setTenant(e)}startSpan(e,t){return this.otel.startSpan(e,t)}recordEvent(e,t){this.otel.recordEvent(e,t)}async test(){try{this.otel.emitSpan("monoscope.test",{"test.timestamp":Date.now()}),await this.otel.forceFlush();const e="Test span sent successfully.";return this.config.debug&&console.log(`[Monoscope] ${e}`),{success:!0,message:e}}catch(e){const t=`Test failed: ${e}`;return this.config.debug&&console.error(`[Monoscope] ${t}`),{success:!1,message:t}}}disable(){this._enabled=!1,this.replay.setEnabled(!1),this.otel.setEnabled(!1),this.vitals.setEnabled(!1),this.errors.stop(),this.router.stop()}enable(){this._enabled=!0,this.otel.setEnabled(!0),this.otel.configure(),this.replay.setEnabled(!0),this.replay.configure(),this.vitals.setEnabled(!0),this.vitals.start().catch(()=>{}),this.errors.start(),this.router.start()}isEnabled(){return this._enabled}async destroy(){this.errors.stop(),this.router.stop(),this.replay.stop(),this.vitals.setEnabled(!1);try{await this.otel.shutdown()}catch(e){console.warn("Monoscope: provider shutdown failed, some trace data may be lost",e)}this._enabled=!1}}}(); //# sourceMappingURL=monoscope.min.js.map diff --git a/static/public/dashboards/endpoint-stats.yaml b/static/public/dashboards/endpoint-stats.yaml index b998ae94b..131bc67e0 100644 --- a/static/public/dashboards/endpoint-stats.yaml +++ b/static/public/dashboards/endpoint-stats.yaml @@ -451,7 +451,7 @@ tabs: description: Estimated unique browser sessions observed in each time bucket. Use Endpoint Sessions below for the exact session list. icon: users query: | - hashes[*]=="{{var-endpointHash}}" AND (resource.telemetry.sdk.language in ("webjs", "javascript", "js") or resource.user_agent.original != "" or name in ("documentLoad", "documentFetch") or name startswith "Pageview ") AND attributes.session.id != null + hashes[*]=="{{var-endpointHash}}" AND {{browser_kql}} AND attributes.session.id != null | summarize dcount(attributes.session.id) by bin_auto(timestamp) unit: sessions summarize_by: sum @@ -461,7 +461,7 @@ tabs: title: Browser Errors icon: triangle-exclamation query: | - hashes[*]=="{{var-endpointHash}}" AND (resource.telemetry.sdk.language in ("webjs", "javascript", "js") or resource.user_agent.original != "" or name in ("documentLoad", "documentFetch") or name startswith "Pageview ") AND (status_code == "ERROR" or level in ("ERROR", "FATAL", "error", "fatal") or attributes.exception.type != null) + hashes[*]=="{{var-endpointHash}}" AND {{browser_kql}} AND (status_code == "ERROR" or level in ("ERROR", "FATAL", "error", "fatal") or attributes.exception.type != null) | summarize count() by bin_auto(timestamp) unit: errors layout: { w: 3, h: 2 } @@ -470,7 +470,7 @@ tabs: title: P75 Browser Request icon: gauge query: | - hashes[*]=="{{var-endpointHash}}" AND (resource.telemetry.sdk.language in ("webjs", "javascript", "js") or resource.user_agent.original != "" or name in ("documentLoad", "documentFetch") or name startswith "Pageview ") AND duration != null + hashes[*]=="{{var-endpointHash}}" AND {{browser_kql}} AND duration != null | summarize p75(duration) / 1000000 by bin_auto(timestamp) unit: ms layout: { w: 3, h: 2 } @@ -480,7 +480,7 @@ tabs: description: Estimated unique browser sessions that saw an error in each time bucket. icon: triangle-exclamation query: | - hashes[*]=="{{var-endpointHash}}" AND (resource.telemetry.sdk.language in ("webjs", "javascript", "js") or resource.user_agent.original != "" or name in ("documentLoad", "documentFetch") or name startswith "Pageview ") AND attributes.session.id != null AND (status_code == "ERROR" or level in ("ERROR", "FATAL", "error", "fatal") or attributes.exception.type != null) + hashes[*]=="{{var-endpointHash}}" AND {{browser_kql}} AND attributes.session.id != null AND (status_code == "ERROR" or level in ("ERROR", "FATAL", "error", "fatal") or attributes.exception.type != null) | summarize dcount(attributes.session.id) by bin_auto(timestamp) unit: sessions summarize_by: sum @@ -490,7 +490,7 @@ tabs: title: Browser Request Outcomes description: Requests made by real browsers, split into non-error requests and errors so a traffic change is not mistaken for an error change. query: | - hashes[*]=="{{var-endpointHash}}" AND (resource.telemetry.sdk.language in ("webjs", "javascript", "js") or resource.user_agent.original != "" or name in ("documentLoad", "documentFetch") or name startswith "Pageview ") + hashes[*]=="{{var-endpointHash}}" AND {{browser_kql}} | summarize count() by bin_auto(timestamp), iff(status_code == "ERROR" or level in ("ERROR", "FATAL", "error", "fatal") or attributes.exception.type != null, "Errors", "Non-error requests") | order by timestamp desc | limit 10000 @@ -532,13 +532,13 @@ tabs: - type: table title: Endpoint Sessions - description: Select a session to inspect its correlated OpenTelemetry events in Real User Monitoring; the replay workspace opens when a recording is available. + description: Select a session to inspect its correlated OpenTelemetry events in the Explorer, with its replay when one was recorded. db_source: postgres layout: { w: 12, h: 6 } columns: - field: session_id title: Session - link: '/p/{{project_id}}/rum?tab=sessions&session={{row.session_id}}' + link: '/p/{{project_id}}/log_explorer?viz_type=sessions&query=attributes.session.id%20%3D%3D%20%22{{row.session_id}}%22{{time_range}}' - field: last_page title: Last Page - field: replay @@ -672,7 +672,7 @@ tabs: description: Open a trace to inspect the browser request, session ID, and correlated server spans. layout: { w: 12, h: 12 } query: | - hashes[*]=="{{var-endpointHash}}" AND (resource.telemetry.sdk.language in ("webjs", "javascript", "js") or resource.user_agent.original != "" or name in ("documentLoad", "documentFetch") or name startswith "Pageview ") + hashes[*]=="{{var-endpointHash}}" AND {{browser_kql}} - name: Dependencies icon: sitemap diff --git a/static/public/dashboards/rum.yaml b/static/public/dashboards/rum.yaml index 1cdda3e97..134399927 100644 --- a/static/public/dashboards/rum.yaml +++ b/static/public/dashboards/rum.yaml @@ -4,6 +4,14 @@ preview: /public/assets/svgs/screens/http-stats.svg description: Browser experience, Core Web Vitals, frontend errors, and user sessions from OpenTelemetry refresh_interval: 60s +# {{browser_filter}}, {{pageview_filter}} and {{error_filter}} are Real User Monitoring's predicates +# (Pkg.Parser.browserSql and siblings). TimeFusion's `rum_*` rollups declare them verbatim and serve a +# widget only while its filter matches exactly, so they live in one place rather than here. +# +# Web Vitals P75 is read from the histogram buckets (unnest, sum per bound, interpolate within +# the bucket holding the 75th observation), never the export mean. Each series is one page view, +# so a cumulative series' newest point holds all of its observations. + variables: - key: app title: Application @@ -16,11 +24,10 @@ variables: SELECT DISTINCT resource___service___name FROM otel_logs_and_spans WHERE project_id='{{project_id}}' - AND resource___telemetry___sdk___language IN ('webjs', 'javascript', 'js') + AND {{browser_filter}} AND resource___service___name IS NOT NULL {{time_filter}} LIMIT 100 - default: '' multi: false widgets: [] @@ -34,97 +41,109 @@ tabs: description: Real browser traffic only. Backend spans and synthetic requests are excluded. layout: { w: 12, h: 4 } children: - - type: timeseries_stat + - type: stat title: Sessions icon: users - query: | - resource.telemetry.sdk.language == "webjs" and attributes.session.id != null and ("{{var-app}}" == "" or resource.service.name == "{{var-app}}") - | summarize started_at=min(timestamp) by attributes.session.id - | summarize count() by bin_auto(started_at) + query: &app '"{{var-app}}" == "" or resource.service.name == "{{var-app}}"' + sql: | + SELECT distinct_count(approx_count_distinct(attributes___session___id))::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} AND attributes___session___id IS NOT NULL unit: sessions - summarize_by: sum layout: { w: 3, h: 2 } - type: timeseries_stat title: Page views icon: file-lines - query: | - resource.telemetry.sdk.language == "webjs" and name startswith "Pageview · " and ("{{var-app}}" == "" or resource.service.name == "{{var-app}}") - | summarize count() by bin_auto(timestamp) + query: *app + sql: | + SELECT extract(epoch from time_bucket('{{rollup_interval}}', timestamp))::integer, 'value', count(*)::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{pageview_filter}} GROUP BY time_bucket('{{rollup_interval}}', timestamp) ORDER BY time_bucket('{{rollup_interval}}', timestamp) DESC unit: views summarize_by: sum layout: { w: 3, h: 2 } - - type: stat + - type: timeseries_stat title: Browser errors icon: triangle-exclamation - query: | - resource.telemetry.sdk.language == "webjs" and (status_code == "ERROR" or attributes.exception.type != null) and ("{{var-app}}" == "" or resource.service.name == "{{var-app}}") - | summarize count() + query: *app + sql: &browser_error_series | + SELECT extract(epoch from time_bucket('{{rollup_interval}}', timestamp))::integer, 'value', count(*)::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} GROUP BY time_bucket('{{rollup_interval}}', timestamp) ORDER BY time_bucket('{{rollup_interval}}', timestamp) DESC unit: errors + summarize_by: sum + series_intent: error layout: { w: 3, h: 2 } - type: stat title: P75 page load icon: gauge - query: | - resource.telemetry.sdk.language == "webjs" and name startswith "Pageview · " and duration != null and ("{{var-app}}" == "" or resource.service.name == "{{var-app}}") - | summarize p75(duration) / 1000000 + query: *app + sql: | + SELECT (approx_percentile(0.75, percentile_agg(duration)) / 1000000)::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{pageview_filter}} AND duration IS NOT NULL unit: ms layout: { w: 3, h: 2 } - type: timeseries title: Page views and errors - description: Frontend traffic with errors as a separate series. + description: A page view that errored counts in both series. layout: { w: 7, h: 5 } + query: *app sql: | - SELECT extract(epoch from time_bucket('{{rollup_interval}}', timestamp))::integer AS time, - CASE WHEN status_code = 'ERROR' OR attributes___exception___type IS NOT NULL THEN 'Errors' ELSE 'Page views' END AS series, - COUNT(*)::float AS value - FROM otel_logs_and_spans - WHERE project_id='{{project_id}}' - AND resource___telemetry___sdk___language IN ('webjs', 'javascript', 'js') - AND (name LIKE 'Pageview · %' OR status_code = 'ERROR' OR attributes___exception___type IS NOT NULL) - AND ('{{var-app}}' = '' OR resource___service___name = '{{var-app}}') - {{time_filter}} - GROUP BY time, series ORDER BY time DESC + SELECT a.time, s.series, CASE s.series WHEN 'Page views' THEN a.page_views ELSE a.errors END FROM (SELECT extract(epoch from time_bucket('{{rollup_interval}}', timestamp))::integer AS time, count(*) FILTER (WHERE {{pageview_filter}})::float AS page_views, count(*) FILTER (WHERE {{browser_filter}} AND {{error_filter}})::float AS errors FROM otel_logs_and_spans WHERE {{query_ast_filters}} GROUP BY time_bucket('{{rollup_interval}}', timestamp)) a CROSS JOIN (VALUES ('Page views'), ('Errors')) AS s(series) ORDER BY a.time DESC - type: table title: Top pages - description: Most-viewed routes and their P75 real-user load duration. + description: Routes with ids masked, and their P75 real-user load duration. layout: { w: 5, h: 5 } columns: - field: page title: Page + link: /p/{{project_id}}/log_explorer?query={{row.kql}}{{time_range}} - field: views title: Views column_type: number progress: column_percent - field: p75_ms title: P75 + description: "75th percentile page-load duration: three in four loads were at least this fast." column_type: duration unit: ms + - field: kql + title: Explorer query + hidden: true + query: *app sql: | - SELECT COALESCE(NULLIF(attributes___url___path, ''), replace(name, 'Pageview · ', '')) AS page, - COUNT(*)::text AS views, - ROUND((approx_percentile(0.75, percentile_agg(duration)) / 1000000.0)::numeric, 1)::text AS p75_ms - FROM otel_logs_and_spans - WHERE project_id='{{project_id}}' - AND resource___telemetry___sdk___language IN ('webjs', 'javascript', 'js') - AND name LIKE 'Pageview · %' AND duration IS NOT NULL - AND ('{{var-app}}' = '' OR resource___service___name = '{{var-app}}') - {{time_filter}} - GROUP BY page ORDER BY COUNT(*) DESC LIMIT 20 + WITH pages AS ( + SELECT COALESCE(NULLIF(regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace( + COALESCE(NULLIF(CASE WHEN name = 'documentLoad' THEN attributes___url___full END, ''), NULLIF(attributes___url___path, ''), NULLIF(attributes___url___full, ''), replace(name, 'Pageview · ', '')), + '^[A-Za-z][A-Za-z0-9+.-]*://[^/]+', ''), '[?#].*$', ''), + '/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[^/]*', '/:id', 'g'), '/[0-9][^/]*', '/:id', 'g'), '/[A-Z][A-Z0-9]*[0-9][A-Z0-9]*', '/:id', 'g'), ''), '/') AS page, + duration + FROM otel_logs_and_spans + WHERE {{query_ast_filters}} AND {{pageview_filter}} AND duration IS NOT NULL + ) + -- The route as an anchored regex (masked segments match any segment; metacharacters + -- escaped as one-character classes, so the KQL string needs no backslashes). + SELECT page, n::text AS views, p75_ms, + '(name == "documentLoad" or name startswith "Pageview ") and (attributes.url.path matches regex "^' || rx || '$" or attributes.url.full matches regex "^([A-Za-z][A-Za-z0-9+.-]*://[^/?#]+)?' || rx || '([?#].*)?$")' AS kql + FROM ( + SELECT page, COUNT(*) AS n, + ROUND((approx_percentile(0.75, percentile_agg(duration)) / 1000000.0)::numeric, 1)::text AS p75_ms, + replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(page, '"', ''), '\', ''), + '.', '[.]'), '+', '[+]'), '*', '[*]'), '(', '[(]'), ')', '[)]'), '$', '[$]'), '|', '[|]'), '{', '[{]'), ':id', '[^/]+') AS rx + FROM pages GROUP BY page ORDER BY COUNT(*) DESC LIMIT 20 + ) AS top ORDER BY n DESC - type: table title: Recent sessions - description: Open the RUM Sessions page for correlated replay and telemetry. + description: Open a session to see its events and, when recorded, its replay. layout: { w: 12, h: 6 } + cta: + title: All sessions + url: /p/{{project_id}}/rum/sessions columns: - - field: user_or_session - title: User / session - - field: last_page - title: Last page + - field: session + title: Session + link: /p/{{project_id}}/log_explorer?viz_type=sessions&query=attributes.session.id%20%3D%3D%20%22{{row.session}}%22{{time_range}} + - field: user + title: User - field: page_views title: Views column_type: number @@ -135,156 +154,228 @@ tabs: progress_variant: error - field: last_seen title: Last seen + query: *app sql: | - SELECT COALESCE(MAX(attributes___user___full_name), MAX(attributes___user___email), MAX(attributes___user___id), attributes___session___id) AS user_or_session, - COALESCE(MAX(attributes___url___path), 'Unknown page') AS last_page, - COUNT(*) FILTER (WHERE name LIKE 'Pageview · %')::text AS page_views, - COUNT(*) FILTER (WHERE status_code = 'ERROR' OR attributes___exception___type IS NOT NULL)::text AS errors, + SELECT attributes___session___id AS session, + COALESCE(MAX(attributes___user___full_name), MAX(attributes___user___email), MAX(attributes___user___id), '') AS "user", + COUNT(*) FILTER (WHERE {{pageview_filter}})::text AS page_views, + COUNT(*) FILTER (WHERE {{error_filter}})::text AS errors, MAX(timestamp)::text AS last_seen FROM otel_logs_and_spans - WHERE project_id='{{project_id}}' - AND resource___telemetry___sdk___language IN ('webjs', 'javascript', 'js') + WHERE {{query_ast_filters}} + AND {{browser_filter}} AND attributes___session___id IS NOT NULL - AND ('{{var-app}}' = '' OR resource___service___name = '{{var-app}}') - {{time_filter}} GROUP BY attributes___session___id ORDER BY MAX(timestamp) DESC LIMIT 50 - name: Web Vitals icon: gauge widgets: - - type: group - title: Core Web Vitals - description: Browser SDK histograms. LCP, INP, FCP, and TTFB are milliseconds; CLS is dimensionless. - layout: { w: 12, h: 4 } - children: - - type: stat - title: LCP - icon: clock - sql: | - WITH latest AS ( - SELECT COALESCE(value, distribution_sum / NULLIF(distribution_count, 0)) AS value, - row_number() OVER (PARTITION BY series_id ORDER BY timestamp DESC) AS rn - FROM otel_metrics WHERE project_id='{{project_id}}' AND metric_name='browser.web_vital.lcp' - AND ('{{var-app}}' = '' OR resource___service___name = '{{var-app}}') {{time_filter}} - ) SELECT approx_percentile(0.75, percentile_agg(value))::float FROM latest WHERE rn=1 AND value IS NOT NULL - unit: ms - layout: { w: 3, h: 2 } - - - type: stat - title: INP - icon: arrow-pointer - sql: | - WITH latest AS ( - SELECT COALESCE(value, distribution_sum / NULLIF(distribution_count, 0)) AS value, - row_number() OVER (PARTITION BY series_id ORDER BY timestamp DESC) AS rn - FROM otel_metrics WHERE project_id='{{project_id}}' AND metric_name='browser.web_vital.inp' - AND ('{{var-app}}' = '' OR resource___service___name = '{{var-app}}') {{time_filter}} - ) SELECT approx_percentile(0.75, percentile_agg(value))::float FROM latest WHERE rn=1 AND value IS NOT NULL - unit: ms - layout: { w: 3, h: 2 } - - - type: stat - title: CLS - icon: arrows-up-down - sql: | - WITH latest AS ( - SELECT COALESCE(value, distribution_sum / NULLIF(distribution_count, 0)) AS value, - row_number() OVER (PARTITION BY series_id ORDER BY timestamp DESC) AS rn - FROM otel_metrics WHERE project_id='{{project_id}}' AND metric_name='browser.web_vital.cls' - AND ('{{var-app}}' = '' OR resource___service___name = '{{var-app}}') {{time_filter}} - ) SELECT approx_percentile(0.75, percentile_agg(value))::float FROM latest WHERE rn=1 AND value IS NOT NULL - unit: score - layout: { w: 3, h: 2 } - - - type: stat - title: TTFB - icon: server - sql: | - WITH latest AS ( - SELECT COALESCE(value, distribution_sum / NULLIF(distribution_count, 0)) AS value, - row_number() OVER (PARTITION BY series_id ORDER BY timestamp DESC) AS rn - FROM otel_metrics WHERE project_id='{{project_id}}' AND metric_name='browser.web_vital.ttfb' - AND ('{{var-app}}' = '' OR resource___service___name = '{{var-app}}') {{time_filter}} - ) SELECT approx_percentile(0.75, percentile_agg(value))::float FROM latest WHERE rn=1 AND value IS NOT NULL - unit: ms - layout: { w: 3, h: 2 } - - - type: timeseries_line - title: Web Vitals over time - description: Mean value per export interval. Use the RUM Performance page for threshold assessments. - layout: { w: 12, h: 5 } - sql: | - SELECT extract(epoch from time_bucket('{{rollup_interval}}', timestamp))::integer AS time, - upper(replace(metric_name, 'browser.web_vital.', '')) AS vital, - AVG(COALESCE(value, distribution_sum / NULLIF(distribution_count, 0)))::float AS value - FROM otel_metrics - WHERE project_id='{{project_id}}' - AND metric_name LIKE 'browser.web_vital.%' - AND ('{{var-app}}' = '' OR resource___service___name = '{{var-app}}') - {{time_filter}} - GROUP BY time, vital ORDER BY time DESC - - type: table - title: Vital sample coverage - description: Confirm which field metrics the browser SDK is reporting. + title: Core Web Vitals + description: P75 of real-user observations, rated against Google's field thresholds. The bucket is the range the P75 is known to lie in. layout: { w: 12, h: 4 } columns: - field: vital title: Vital + tooltip: '{{row.about}}' + - field: p75 + title: P75 + description: "75th percentile: three in four page loads were at least this fast. ≈ marks an estimate inside a bucket that crosses a threshold." + - field: rating + title: Rating + description: Against Google's field thresholds. "Likely" ratings come from an estimate, not the bucket alone. + - field: bucket + title: Known range + description: The histogram bucket the P75 falls in. The browser SDK's bucket edges decide how precise this can be. - field: samples title: Samples + description: Real-user observations in the selected window. column_type: number progress: column_percent - - field: last_seen - title: Last seen + - field: about + title: About + hidden: true + query: &metrics_app 'metrics | where "{{var-app}}" == "" or resource.service.name == "{{var-app}}"' sql: | - SELECT upper(replace(metric_name, 'browser.web_vital.', '')) AS vital, - SUM(COALESCE(distribution_count, 1))::text AS samples, - MAX(timestamp)::text AS last_seen - FROM otel_metrics - WHERE project_id='{{project_id}}' AND metric_name LIKE 'browser.web_vital.%' - AND ('{{var-app}}' = '' OR resource___service___name = '{{var-app}}') {{time_filter}} - GROUP BY metric_name ORDER BY metric_name + WITH points AS ( + SELECT replace(metric_name, 'browser.web_vital.', '') AS vital, series_id, timestamp, hist_explicit_bounds AS bounds, hist_bucket_counts AS counts, + ROW_NUMBER() OVER (PARTITION BY series_id, start_timestamp ORDER BY timestamp DESC) AS newest + FROM otel_metrics + WHERE {{query_ast_filters}} AND metric_name IN ('browser.web_vital.lcp', 'browser.web_vital.inp', 'browser.web_vital.cls', 'browser.web_vital.fcp', 'browser.web_vital.ttfb') AND metric_type = 'HISTOGRAM' AND hist_bucket_counts IS NOT NULL + ), buckets AS ( + SELECT vital, series_id, timestamp, unnest(COALESCE(bounds, ARRAY[]::float8[]) || ARRAY[NULL]::float8[]) AS le, unnest(counts) AS n FROM points WHERE newest = 1 + ), edges AS ( + -- Each point's cumulative count at its own edges. Summed, these are exact at any edge every point + -- shares, so mixed bucket layouts (an SDK upgrade) coarsen to their common edges instead of interleaving. + SELECT vital, le, SUM(cdf) AS cum, COUNT(*) AS points FROM ( + SELECT vital, le, SUM(n) OVER (PARTITION BY series_id, timestamp ORDER BY le NULLS LAST ROWS UNBOUNDED PRECEDING) AS cdf FROM buckets + ) AS per_point GROUP BY vital, le + ), cdf AS ( + SELECT vital, le, cum, MAX(cum) OVER (PARTITION BY vital) AS total, + cum - COALESCE(LAG(cum) OVER (PARTITION BY vital ORDER BY le NULLS LAST), 0) AS n, + LAG(le) OVER (PARTITION BY vital ORDER BY le NULLS LAST) AS lo + FROM (SELECT *, MAX(points) OVER (PARTITION BY vital) AS all_points FROM edges) AS shared WHERE points = all_points + ), p75 AS ( + SELECT vital, total, lo, le, CASE WHEN le IS NOT NULL THEN COALESCE(lo, 0) + (le - COALESCE(lo, 0)) * (0.75 * total - (cum - n)) / n END AS value + FROM cdf WHERE total > 0 AND cum >= 0.75 * total AND cum - n < 0.75 * total + ), rated AS ( + -- A bucket inside one band rates exactly. One straddling a threshold but no wider than + -- twice the band gives an estimate; anything wider interpolates noise and is not shown. + SELECT t.vital, t.ord, t.good, t.poor, t.about, p.total, p.lo, p.le, p.value, + CASE WHEN p.le <= t.good THEN 'Good' WHEN COALESCE(p.lo, 0) >= t.poor THEN 'Poor' WHEN COALESCE(p.lo, 0) >= t.good AND p.le <= t.poor THEN 'Needs improvement' END AS verdict, + p.le IS NOT NULL AND p.le - COALESCE(p.lo, 0) <= 2 * (t.poor - t.good) AS estimable + FROM (VALUES ('lcp', 1, 2500.0, 4000.0, 'Largest Contentful Paint: when the main content becomes visible. Good ≤ 2.5 s, poor > 4 s.'), + ('inp', 2, 200.0, 500.0, 'Interaction to Next Paint: how quickly the page responds to clicks, taps and keys. Good ≤ 200 ms, poor > 500 ms.'), + ('cls', 3, 0.1, 0.25, 'Cumulative Layout Shift: how much content moves while loading. Good ≤ 0.1, poor > 0.25.'), + ('fcp', 4, 1800.0, 3000.0, 'First Contentful Paint: when the first text or image appears. Good ≤ 1.8 s, poor > 3 s.'), + ('ttfb', 5, 800.0, 1800.0, 'Time to First Byte: server and network time before the page starts arriving. Good ≤ 800 ms, poor > 1.8 s.') + ) AS t(vital, ord, good, poor, about) + LEFT JOIN p75 AS p ON p.vital = t.vital + ) + SELECT upper(vital) AS vital, + CASE WHEN total IS NULL OR (verdict IS NULL AND NOT estimable AND le IS NOT NULL) THEN '—' WHEN value IS NULL THEN '> ' || lo::text + ELSE CASE WHEN verdict IS NULL THEN '≈ ' ELSE '' END || CASE WHEN vital = 'cls' THEN ROUND(value::numeric, 3)::text ELSE ROUND(value::numeric)::text || ' ms' END END AS p75, + CASE WHEN total IS NULL THEN 'rating;info-weak⇒No observations in this window' WHEN verdict = 'Good' THEN 'rating;success-strong⇒Good' + WHEN verdict = 'Poor' THEN 'rating;error-strong⇒Poor' WHEN verdict = 'Needs improvement' THEN 'rating;warning-strong⇒Needs improvement' + WHEN NOT estimable THEN 'rating;info-weak⇒Buckets too coarse to rate' WHEN value <= good THEN 'rating;success-weak⇒Likely good' + WHEN value > poor THEN 'rating;error-weak⇒Likely poor' ELSE 'rating;warning-weak⇒Likely needs improvement' END AS rating, + CASE WHEN total IS NULL THEN '' ELSE COALESCE(lo, 0)::text || ' – ' || COALESCE(le::text, '∞') END AS bucket, + COALESCE(total, 0)::text AS samples, + about + FROM rated ORDER BY ord + + - type: timeseries_line + title: P75 over time + description: P75 per interval for LCP (main content visible), INP (response to input), FCP (first content) and TTFB (first byte). CLS is unitless and shown in the table above. + layout: { w: 12, h: 5 } + unit: ms + query: *metrics_app + sql: | + WITH points AS ( + SELECT time_bucket('{{rollup_interval}}', timestamp) AS t, replace(metric_name, 'browser.web_vital.', '') AS vital, series_id, timestamp, hist_explicit_bounds AS bounds, hist_bucket_counts AS counts, + ROW_NUMBER() OVER (PARTITION BY series_id, start_timestamp ORDER BY timestamp DESC) AS newest + FROM otel_metrics + WHERE {{query_ast_filters}} AND metric_name IN ('browser.web_vital.lcp', 'browser.web_vital.inp', 'browser.web_vital.fcp', 'browser.web_vital.ttfb') AND metric_type = 'HISTOGRAM' AND hist_bucket_counts IS NOT NULL + ), buckets AS ( + SELECT t, vital, series_id, timestamp, unnest(COALESCE(bounds, ARRAY[]::float8[]) || ARRAY[NULL]::float8[]) AS le, unnest(counts) AS n FROM points WHERE newest = 1 + ), edges AS ( + -- Each point's cumulative count at its own edges. Summed, these are exact at any edge every point + -- shares, so mixed bucket layouts (an SDK upgrade) coarsen to their common edges instead of interleaving. + SELECT t, vital, le, SUM(cdf) AS cum, COUNT(*) AS points FROM ( + SELECT t, vital, le, SUM(n) OVER (PARTITION BY series_id, timestamp ORDER BY le NULLS LAST ROWS UNBOUNDED PRECEDING) AS cdf FROM buckets + ) AS per_point GROUP BY t, vital, le + ), cdf AS ( + SELECT t, vital, le, cum, MAX(cum) OVER (PARTITION BY t, vital) AS total, + cum - COALESCE(LAG(cum) OVER (PARTITION BY t, vital ORDER BY le NULLS LAST), 0) AS n, + LAG(le) OVER (PARTITION BY t, vital ORDER BY le NULLS LAST) AS lo + FROM (SELECT *, MAX(points) OVER (PARTITION BY t, vital) AS all_points FROM edges) AS shared WHERE points = all_points + ), p75 AS ( + SELECT t, vital, total, lo, le, CASE WHEN le IS NOT NULL THEN COALESCE(lo, 0) + (le - COALESCE(lo, 0)) * (0.75 * total - (cum - n)) / n END AS value + FROM cdf WHERE total > 0 AND cum >= 0.75 * total AND cum - n < 0.75 * total + ) + SELECT extract(epoch from t)::integer AS time, upper(vital) AS vital, value::float AS value FROM p75 WHERE value IS NOT NULL ORDER BY time DESC + + - type: table + title: Vitals by page + description: P75 per page, busiest first. A dash marks a bucket too wide to place against the thresholds. + layout: { w: 12, h: 6 } + columns: + - field: page + title: Page + description: Page URL with ids masked, so one route groups its variants. + - field: lcp + title: LCP + description: Largest Contentful Paint, P75. When the main content becomes visible. Good ≤ 2.5 s, poor > 4 s. + - field: inp + title: INP + description: Interaction to Next Paint, P75. How quickly the page responds to input. Good ≤ 200 ms, poor > 500 ms. + - field: cls + title: CLS + description: Cumulative Layout Shift, P75. How much content moves while loading. Good ≤ 0.1, poor > 0.25. + - field: samples + title: Samples + description: Real-user observations across these three vitals. + column_type: number + progress: column_percent + query: *metrics_app + sql: | + WITH points AS ( + SELECT COALESCE(NULLIF(regexp_replace(regexp_replace(regexp_replace(regexp_replace(regexp_replace(COALESCE(attributes #>> '{page,url}', attributes->>'page.url', attributes->>'url', ''), + '^[A-Za-z][A-Za-z0-9+.-]*://[^/]+', ''), '[?#].*$', ''), + '/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[^/]*', '/:id', 'g'), '/[0-9][^/]*', '/:id', 'g'), '/[A-Z][A-Z0-9]*[0-9][A-Z0-9]*', '/:id', 'g'), ''), '/') AS page, replace(metric_name, 'browser.web_vital.', '') AS vital, series_id, timestamp, hist_explicit_bounds AS bounds, hist_bucket_counts AS counts, + ROW_NUMBER() OVER (PARTITION BY series_id, start_timestamp ORDER BY timestamp DESC) AS newest + FROM otel_metrics + WHERE {{query_ast_filters}} AND metric_name IN ('browser.web_vital.lcp', 'browser.web_vital.inp', 'browser.web_vital.cls') AND metric_type = 'HISTOGRAM' AND hist_bucket_counts IS NOT NULL + ), buckets AS ( + SELECT page, vital, series_id, timestamp, unnest(COALESCE(bounds, ARRAY[]::float8[]) || ARRAY[NULL]::float8[]) AS le, unnest(counts) AS n FROM points WHERE newest = 1 + ), edges AS ( + -- Each point's cumulative count at its own edges. Summed, these are exact at any edge every point + -- shares, so mixed bucket layouts (an SDK upgrade) coarsen to their common edges instead of interleaving. + SELECT page, vital, le, SUM(cdf) AS cum, COUNT(*) AS points FROM ( + SELECT page, vital, le, SUM(n) OVER (PARTITION BY series_id, timestamp ORDER BY le NULLS LAST ROWS UNBOUNDED PRECEDING) AS cdf FROM buckets + ) AS per_point GROUP BY page, vital, le + ), cdf AS ( + SELECT page, vital, le, cum, MAX(cum) OVER (PARTITION BY page, vital) AS total, + cum - COALESCE(LAG(cum) OVER (PARTITION BY page, vital ORDER BY le NULLS LAST), 0) AS n, + LAG(le) OVER (PARTITION BY page, vital ORDER BY le NULLS LAST) AS lo + FROM (SELECT *, MAX(points) OVER (PARTITION BY page, vital) AS all_points FROM edges) AS shared WHERE points = all_points + ), p75 AS ( + SELECT page, vital, total, lo, le, CASE WHEN le IS NOT NULL THEN COALESCE(lo, 0) + (le - COALESCE(lo, 0)) * (0.75 * total - (cum - n)) / n END AS value + FROM cdf WHERE total > 0 AND cum >= 0.75 * total AND cum - n < 0.75 * total + ), shown AS ( + -- Too coarse to place against the thresholds: wider than twice the needs-improvement band, as in Core Web Vitals. + SELECT p.page, p.vital, p.total, CASE WHEN p.le - COALESCE(p.lo, 0) > 2 * (t.poor - t.good) THEN '—' WHEN p.le IS NULL THEN '> ' || p.lo::text + WHEN p.vital = 'cls' THEN ROUND(p.value::numeric, 3)::text ELSE ROUND(p.value::numeric)::text || ' ms' END AS value + FROM p75 AS p JOIN (VALUES ('lcp', 1, 2500.0, 4000.0, 'Largest Contentful Paint: when the main content becomes visible. Good ≤ 2.5 s, poor > 4 s.'), + ('inp', 2, 200.0, 500.0, 'Interaction to Next Paint: how quickly the page responds to clicks, taps and keys. Good ≤ 200 ms, poor > 500 ms.'), + ('cls', 3, 0.1, 0.25, 'Cumulative Layout Shift: how much content moves while loading. Good ≤ 0.1, poor > 0.25.'), + ('fcp', 4, 1800.0, 3000.0, 'First Contentful Paint: when the first text or image appears. Good ≤ 1.8 s, poor > 3 s.'), + ('ttfb', 5, 800.0, 1800.0, 'Time to First Byte: server and network time before the page starts arriving. Good ≤ 800 ms, poor > 1.8 s.') + ) AS t(vital, ord, good, poor, about) ON t.vital = p.vital + ) + SELECT page, MAX(CASE WHEN vital = 'lcp' THEN value END) AS lcp, MAX(CASE WHEN vital = 'inp' THEN value END) AS inp, + MAX(CASE WHEN vital = 'cls' THEN value END) AS cls, SUM(total)::text AS samples + FROM shown GROUP BY page ORDER BY SUM(total) DESC LIMIT 50 - name: Errors icon: triangle-exclamation widgets: - type: timeseries_stat title: Browser error volume - description: Exceptions and spans marked ERROR by the browser SDK. icon: triangle-exclamation - query: | - resource.telemetry.sdk.language == "webjs" and (status_code == "ERROR" or attributes.exception.type != null) and ("{{var-app}}" == "" or resource.service.name == "{{var-app}}") - | summarize count() by bin_auto(timestamp) + query: *app + sql: *browser_error_series unit: errors summarize_by: sum + series_intent: error layout: { w: 4, h: 3 } - type: stat title: Affected sessions icon: users - query: | - resource.telemetry.sdk.language == "webjs" and attributes.session.id != null and (status_code == "ERROR" or attributes.exception.type != null) and ("{{var-app}}" == "" or resource.service.name == "{{var-app}}") - | summarize dcount(attributes.session.id) + query: *app + sql: | + SELECT COUNT(DISTINCT attributes___session___id)::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} unit: sessions layout: { w: 4, h: 3 } - type: stat title: Affected users icon: user - query: | - resource.telemetry.sdk.language == "webjs" and attributes.user.id != null and (status_code == "ERROR" or attributes.exception.type != null) and ("{{var-app}}" == "" or resource.service.name == "{{var-app}}") - | summarize dcount(attributes.user.id) + query: *app + sql: | + SELECT COUNT(DISTINCT COALESCE(attributes___user___id, attributes___user___email))::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} unit: users layout: { w: 4, h: 3 } - type: table - title: Browser error types - description: Highest-impact frontend failures, grouped by exception type and message. + title: Browser errors + description: Grouped by type and message, with numbers and ids masked. layout: { w: 12, h: 7 } columns: - field: error_type title: Type + link: /p/{{project_id}}/log_explorer?query={{row.kql}}{{time_range}} - field: message title: Message - field: events @@ -297,16 +388,63 @@ tabs: column_type: number - field: last_seen title: Last seen + - field: kql + title: Explorer query + hidden: true + query: *app sql: | - SELECT COALESCE(attributes___exception___type, status_message, 'Browser error') AS error_type, - LEFT(COALESCE(attributes___exception___message, status_message, name, 'No error message'), 300) AS message, - COUNT(*)::text AS events, - COUNT(DISTINCT attributes___session___id)::text AS sessions, - MAX(timestamp)::text AS last_seen - FROM otel_logs_and_spans - WHERE project_id='{{project_id}}' - AND resource___telemetry___sdk___language IN ('webjs', 'javascript', 'js') - AND (status_code='ERROR' OR attributes___exception___type IS NOT NULL) - AND ('{{var-app}}' = '' OR resource___service___name = '{{var-app}}') - {{time_filter}} - GROUP BY error_type, message ORDER BY COUNT(*) DESC LIMIT 50 + SELECT error_type, message, n::text AS events, sessions, last_seen, + CASE WHEN exception_type IS NOT NULL THEN 'attributes.exception.type == "' || replace(replace(exception_type, '"', ''), '\', '') || '"' + ELSE '(status_code == "ERROR" or level == "error") and name == "' || replace(replace(COALESCE(span_name, ''), '"', ''), '\', '') || '"' END AS kql + FROM ( + SELECT attributes___exception___type AS exception_type, COALESCE(NULLIF(attributes___exception___type, ''), NULLIF(status_message, ''), 'Browser error') AS error_type, + LEFT(regexp_replace(COALESCE(NULLIF(attributes___exception___message, ''), NULLIF(status_message, ''), name, 'No error message'), '[0-9a-fA-F-]{8,}|[0-9]+', '', 'g'), 300) AS message, + MIN(name) AS span_name, COUNT(*) AS n, COUNT(DISTINCT attributes___session___id)::text AS sessions, MAX(timestamp)::text AS last_seen + FROM otel_logs_and_spans + WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} + GROUP BY 1, 2, 3 ORDER BY COUNT(*) DESC LIMIT 50 + ) AS groups ORDER BY n DESC + + # User-agent families, coarse on purpose. Arm order matters: Edge and Opera embed "Chrome", + # Chrome embeds "Safari", iOS says "like Mac OS X", Android embeds "Linux". + - name: Audience + icon: users + widgets: + - type: table + title: Browsers, systems and devices + description: Sessions per user-agent family; errored counts sessions with at least one browser error. + layout: { w: 12, h: 7 } + columns: + - field: dimension + title: Dimension + - field: name + title: Name + - field: sessions + title: Sessions + column_type: number + progress: column_percent + - field: errored + title: Errored + description: Sessions with at least one browser error. + column_type: number + query: *app + sql: | + WITH sessions AS ( + SELECT COALESCE(NULLIF(attributes___user_agent___original, ''), resource___user_agent___original) AS ua, attributes___session___id AS session, + MAX(CASE WHEN {{error_filter}} THEN 1 ELSE 0 END) AS errored + FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} + GROUP BY 1, 2 + ), families AS ( + SELECT session, errored, + CASE WHEN ua LIKE '%Edg/%' OR ua LIKE '%Edge/%' THEN 'Edge' WHEN ua LIKE '%OPR/%' OR ua LIKE '%Opera%' THEN 'Opera' WHEN ua LIKE '%SamsungBrowser%' THEN 'Samsung Internet' + WHEN ua LIKE '%Firefox/%' THEN 'Firefox' WHEN ua LIKE '%Chrome/%' OR ua LIKE '%CriOS/%' THEN 'Chrome' WHEN ua LIKE '%Safari/%' THEN 'Safari' ELSE 'Other' END AS browser, + CASE WHEN ua LIKE '%Windows%' THEN 'Windows' WHEN ua LIKE '%iPhone%' OR ua LIKE '%iPad%' OR ua LIKE '%iPod%' THEN 'iOS' WHEN ua LIKE '%Mac OS X%' OR ua LIKE '%Macintosh%' THEN 'macOS' + WHEN ua LIKE '%Android%' THEN 'Android' WHEN ua LIKE '%CrOS%' THEN 'ChromeOS' WHEN ua LIKE '%Linux%' OR ua LIKE '%X11%' THEN 'Linux' ELSE 'Other' END AS os, + CASE WHEN ua LIKE '%iPad%' OR (ua LIKE '%Android%' AND ua NOT LIKE '%Mobile%') THEN 'Tablet' WHEN ua LIKE '%Mobile%' OR ua LIKE '%iPhone%' THEN 'Mobile' ELSE 'Desktop' END AS device + FROM sessions WHERE ua IS NOT NULL + ), counted AS ( + SELECT 1 AS d, 'Browser' AS dimension, browser AS name, COUNT(DISTINCT session) AS n, SUM(errored) AS errored FROM families GROUP BY browser + UNION ALL SELECT 2, 'Operating system', os, COUNT(DISTINCT session), SUM(errored) FROM families GROUP BY os + UNION ALL SELECT 3, 'Device', device, COUNT(DISTINCT session), SUM(errored) FROM families GROUP BY device + ) + SELECT dimension, name, n::text AS sessions, errored::text AS errored FROM counted ORDER BY d, n DESC diff --git a/test/integration/Pages/DashboardWidgetsSpec.hs b/test/integration/Pages/DashboardWidgetsSpec.hs index a3633bb40..40a2f4029 100644 --- a/test/integration/Pages/DashboardWidgetsSpec.hs +++ b/test/integration/Pages/DashboardWidgetsSpec.hs @@ -10,16 +10,21 @@ module Pages.DashboardWidgetsSpec (spec) where import Control.Concurrent (threadDelay) import Control.Exception qualified as E +import Control.Lens ((.~)) import Control.Monad.Trans.Except (runExceptT) import Data.Aeson qualified as AE import Data.Aeson.KeyMap qualified as KM import Data.ByteString.Lazy qualified as LBS import Data.Default (def) +import Data.List (lookup) import Data.Effectful.Hasql qualified as Hasql import Data.Map.Strict qualified as Map import Data.Pool (withResource) import Data.Text qualified as T +import Data.ProtoLens (defMessage) import Data.Time (addUTCTime) +import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) +import Data.Time.Format.ISO8601 (iso8601Show) import Data.Vector qualified as V import Database.PostgreSQL.Simple qualified as PG import Database.PostgreSQL.Simple.Newtypes (Aeson (..)) @@ -32,18 +37,25 @@ import Models.Projects.DashboardTemplates (dashboardTemplatesCompiled, loadDashb import Models.Projects.Dashboards (DashboardVM (..)) import Models.Projects.Dashboards qualified as DashboardModel import Models.Projects.Projects (Session (..)) +import Network.GRPC.Common.Protobuf (Proto (..)) +import Opentelemetry.OtlpServer qualified as OtlpServer import Pages.BodyWrapper (BWConfig (..), NavigationResponse (..), PageCtx (..)) import Pages.Charts.Charts qualified as Charts import Pages.Dashboards (DashboardFilters (..)) import Pages.Dashboards qualified as Dashboards import Pages.Issues qualified as Issues +import Pages.LogExplorer.Log qualified as Log import Pkg.Components.Widget qualified as Widget -import Pkg.Parser (parseQueryToAST) +import Pkg.Parser (browserKql, parseQueryToAST) import Pkg.QueryCache qualified as QueryCache import Pkg.TestClock (getTestTime, setTestTime) import Pkg.TestUtils +import Proto.Opentelemetry.Proto.Collector.Metrics.V1.MetricsService_Fields qualified as MSF +import Proto.Opentelemetry.Proto.Metrics.V1.Metrics qualified as PM +import Proto.Opentelemetry.Proto.Metrics.V1.Metrics_Fields qualified as PMF import Relude import Servant qualified +import Servant.API (ResponseHeader (..), lookupResponseHeader) import Servant.Types.SourceT qualified as Source import System.Config qualified as Config import System.IO.Error (userError) @@ -1088,10 +1100,10 @@ spec = sequential $ aroundAll withTestResources do snd (T.breakOn " do - let column = (def :: Widget.TableColumn){Widget.field = "session_id", Widget.title = "Session", Widget.link = Just "/p/{{project_id}}/rum?tab=sessions&session={{row.session_id}}"} + let column = (def :: Widget.TableColumn){Widget.field = "session_id", Widget.title = "Session", Widget.link = Just "/p/{{project_id}}/log_explorer?viz_type=sessions&query={{row.session_id}}"} widget = (def :: Widget.Widget){Widget.wType = Widget.WTTable, Widget.columns = Just [column], Widget._projectId = Just testPid} html = toStrict $ renderText $ Widget.renderTableWithDataAndParams widget (V.singleton $ V.singleton "session / id") [] - html `shouldSatisfy` T.isInfixOf ("/p/" <> testPid.toText <> "/rum?tab=sessions&session=session%20%2F%20id") + html `shouldSatisfy` T.isInfixOf ("/p/" <> testPid.toText <> "/log_explorer?viz_type=sessions&query=session%20%2F%20id") -- Regression: rows on a tabless dashboard had no swap target and ignored clicks. it "tableRowClick_navigatesOnTablessAndTabbedDashboards" \_ -> do @@ -1409,3 +1421,88 @@ spec = sequential $ aroundAll withTestResources do html `shouldSatisfy` T.isInfixOf "tab-active" html `shouldSatisfy` T.isInfixOf "hx-push-url=\"true\"" html `shouldNotSatisfy` T.isInfixOf " do + projectId <- createTestProject tr "RUM dashboard template" + apiKey <- createTestAPIKey tr projectId "rum-dashboard-key" + let browserSpan n name attrs ua = ingestSpanReq tr $ mkSpanRequest ("e" <> T.justifyRight 31 '0' (show @Text n)) ("e" <> T.justifyRight 15 '0' (show @Text n)) Nothing name [] Nothing (mkAttr "session.id" "dash-session" : attrs) (mkResource apiKey [mkAttr "service.name" "storefront", mkAttr "user_agent.original" ua]) frozenTime + browserSpan (1 :: Int) "documentLoad" [mkAttr "url.full" "https://shop.example/cart"] "Mozilla/5.0 (X11; Linux x86_64) Chrome/151" + browserSpan 2 "Pageview · /orders/123" [mkAttr "url.path" "/orders/123", mkAttr "exception.type" "TypeError"] "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Mobile/15E148 Safari/604.1" + -- Three DELTA exports merge to [3,9,3,1,0] over 16 observations; the 12th lands on the + -- 2500 edge of (1000, 2500], so P75 is exactly 2500 and rated Good from its bucket alone. + let at = (`addUTCTime` frozenTime) + nanos = floor . (* 1000000000) . utcTimeToPOSIXSeconds + point end start counts = defMessage & PMF.timeUnixNano .~ nanos (at end) & PMF.startTimeUnixNano .~ nanos (at start) & PMF.attributes .~ [mkAttr "page.url" "https://shop.example/checkout"] & PMF.count .~ sum counts & PMF.bucketCounts .~ counts & PMF.explicitBounds .~ [1000, 2500, 4000, 8000] + exportVital name points = void $ OtlpServer.metricsServiceExport tr.trLogger tr.trATCtx tr.trTracerProvider (Proto $ defMessage & MSF.resourceMetrics .~ [defMessage & PMF.resource .~ mkResource apiKey [mkAttr "service.name" "storefront"] & PMF.scopeMetrics .~ [defMessage & PMF.metrics .~ [defMessage & PMF.name .~ ("browser.web_vital." <> name) & PMF.histogram .~ (defMessage & PMF.aggregationTemporality .~ PM.AGGREGATION_TEMPORALITY_DELTA & PMF.dataPoints .~ points) :: PM.Metric]]]) + exportVital "lcp" [point (-30) (-40) [2, 5, 1, 0, 0], point (-20) (-30) [0, 3, 2, 1, 0], point (-10) (-20) [1, 1, 0, 0, 0 :: Word64]] + -- INP's P75 (rank 3 of 4) sits in (100, 300], straddling the 200 ms threshold but narrow + -- enough to estimate: 100 + 200·3/4. CLS in OTel's default (0, 5] bucket cannot be placed. + exportVital "inp" [point (-10) (-20) [0, 4, 0, 0] & PMF.explicitBounds .~ [100, 300, 600]] + exportVital "cls" [point (-10) (-20) [0, 4, 0] & PMF.explicitBounds .~ [0, 5]] + rum <- maybe (fail "missing rum.yaml") pure . find (\d -> d.file == Just "rum.yaml") =<< DashboardModel.readDashboardsFromDisk "static/public/dashboards" + let from = toText $ iso8601Show $ at (-3600) + to = toText $ iso8601Show $ at 3600 + dataType = \case Widget.WTTable -> Charts.DTText; Widget.WTStat -> Charts.DTFloat; _ -> Charts.DTMetric + run ws = forM ws \w -> (w.title,) <$> runQueryEffect tr (Charts.queryMetrics Nothing (Just $ dataType w.wType) (Just projectId) w.query w.sql Nothing (Just from) (Just to) Nothing Nothing []) + widgetNamed t = maybe (fail $ "missing " <> toString t) pure $ find ((== Just t) . (.title)) (DashboardModel.allWidgets rum) + table rs title = maybe V.empty (.dataText) $ lookup (Just title) rs + vitalRow rs name = V.toList . V.take 5 <$> find ((== Just name) . (V.!? 0)) (table rs "Core Web Vitals") + results <- run [w | w <- DashboardModel.allWidgets rum, isJust w.sql] + [(title, m.error) | (title, m) <- results, isJust m.error] `shouldBe` [] + vitalRow results "LCP" `shouldBe` Just ["LCP", "2500 ms", "rating;success-strong⇒Good", "1000 – 2500", "16"] + vitalRow results "INP" `shouldBe` Just ["INP", "≈ 250 ms", "rating;warning-weak⇒Likely needs improvement", "100 – 300", "4"] + vitalRow results "CLS" `shouldBe` Just ["CLS", "—", "rating;info-weak⇒Buckets too coarse to rate", "0 – 5", "4"] + -- A vital with nothing in the window says so instead of vanishing. + vitalRow results "FCP" `shouldBe` Just ["FCP", "—", "rating;info-weak⇒No observations in this window", "", "0"] + -- Abbreviations explain themselves on hover: the row's hidden description on the cell, + -- the column's on its header. + vitals <- widgetNamed "Core Web Vitals" + let vitalsHtml = toStrict $ renderText $ Widget.renderTableWithDataAndParams vitals (table results "Core Web Vitals") [] + vitalsHtml `shouldSatisfy` T.isInfixOf "data-tippy-content=\"Largest Contentful Paint: when the main content becomes visible." + vitalsHtml `shouldSatisfy` T.isInfixOf "aria-description=\"Real-user observations in the selected window.\"" + vitalsHtml `shouldNotSatisfy` T.isInfixOf ">About<" + -- An SDK upgrade mixes bucket layouts: a [2500]-bounded export coarsens every point to + -- the shared 2500 edge, giving [16, 4] over 20, so the 15th observation sits at 2500·15/16. + exportVital "lcp" [point (-5) (-10) [4, 0] & PMF.explicitBounds .~ [2500]] + mixed <- run [vitals] + vitalRow mixed "LCP" `shouldBe` Just ["LCP", "2344 ms", "rating;success-strong⇒Good", "0 – 2500", "20"] + sort [name | row <- V.toList $ table results "Browsers, systems and devices", row V.!? 0 == Just "Device", Just name <- [row V.!? 1]] `shouldBe` ["Desktop", "Mobile"] + sort (V.toList $ V.mapMaybe (V.!? 0) $ table results "Top pages") `shouldBe` ["/cart", "/orders/:id"] + -- Each page row's hidden Explorer query finds the events it counted, and the rendered + -- link carries it with the dashboard's window while the column itself stays off screen. + forM_ (table results "Top pages") \row -> do + (_, events) <- testServant tr $ Log.logExplorerDataH projectId def{Log.query = row V.!? 3, Log.from = Just from, Log.to = Just to} + (row V.!? 0, events.error, events.queryResultCount) `shouldBe` (row V.!? 0, Nothing, 1) + -- The browser filter exists twice, as SQL for widgets and KQL for the Explorer; both must + -- select the same rows, and a backend span neither. + ingestTrace tr apiKey "GET /backend-only" frozenTime + (_, sessions) <- testServant tr $ Log.logExplorerDataH projectId def{Log.query = Just browserKql, Log.from = Just from, Log.to = Just to} + viaSql <- runQueryEffect tr $ Charts.queryMetrics Nothing (Just Charts.DTFloat) (Just projectId) Nothing (Just "SELECT count(*)::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}}") Nothing (Just from) (Just to) Nothing Nothing [] + (sessions.error, sessions.queryResultCount, viaSql.dataFloat) `shouldBe` (Nothing, 2, Just 2) + topPages <- widgetNamed "Top pages" + let html = toStrict $ renderText $ Widget.renderTableWithDataAndParams topPages{Widget._projectId = Just projectId} (table results "Top pages") [("since", Just "7D")] + html `shouldNotSatisfy` T.isInfixOf "Explorer query" + map (\ps -> (lookup "since" ps, lookup "query" ps)) (linkParams ("/p/" <> projectId.toText <> "/log_explorer") html) + `shouldBe` [(Just "7D", row V.!? 3) | row <- V.toList $ table results "Top pages"] + + -- /rum and its older /rum/dashboard open the dashboard; /rum/sessions the Explorer. Links from + -- emails and alerts carry a window, which both must keep. + it "rumRedirects_openTheDashboardOrSessions_andKeepTheWindow" \tr -> do + let location view ps = runAuthHandler tr (Dashboards.rumRedirectH testPid view ps) <&> \h -> case lookupResponseHeader @"Location" h of + Header l -> l + _ -> "" + window = [("since", Just "7D"), ("environment", Just "prod")] + dashboard <- location [] window + dashboard `shouldSatisfy` T.isInfixOf ("/p/" <> testPid.toText <> "/dashboards/") + dashboard `shouldSatisfy` T.isInfixOf "since=7D" + location ["dashboard"] window `shouldReturn` dashboard + sessions <- location ["sessions"] window + linkParams ("/p/" <> testPid.toText <> "/log_explorer") ("href=\"" <> sessions <> "\"") `shouldBe` [[("since", "7D"), ("viz_type", "sessions"), ("query", browserKql)]] + -- A link shared from the old page lands on that session, not the dashboard. + legacy <- location [] [("tab", Just "sessions"), ("session", Just "abc")] + linkParams ("/p/" <> testPid.toText <> "/log_explorer") ("href=\"" <> legacy <> "\"") `shouldBe` [[("viz_type", "sessions"), ("query", "attributes.session.id == \"abc\"")]] diff --git a/test/integration/Pages/LogExplorer/LogSpec.hs b/test/integration/Pages/LogExplorer/LogSpec.hs index 0c5a8b0c2..bcf16ae5e 100644 --- a/test/integration/Pages/LogExplorer/LogSpec.hs +++ b/test/integration/Pages/LogExplorer/LogSpec.hs @@ -1032,6 +1032,18 @@ databaseSpec = do (_, poll) <- testServant tr $ Log.logSessionsH testPid Nothing fromTime Nothing toTime Nothing Nothing fromTime case poll of { Log.SessionsView _ _ summ -> summ `shouldSatisfy` isNothing } + -- The RUM page listed recordings whose spans never arrived; folding RUM into this view + -- must not lose them. They carry no attributes, so only the unfiltered or browser view holds them. + it "lists a recording-only session in the browser sessions view, with Replay" \tr -> do + pid <- createTestProject tr "sessions-recording-only" + recording <- nextRandom + void $ withPool tr.trPool $ DBT.execute [sql| INSERT INTO projects.replay_sessions (session_id, project_id, created_at, last_event_at, event_file_count, user_name) VALUES (?, ?, ?, ?, 1, 'Ada') |] (recording, pid, frozenTime, addUTCTime 30 frozenTime) + let stamp = Just . toText . formatTime defaultTimeLocale "%FT%T%QZ" . (`addUTCTime` frozenTime) + listed query = testServant tr (Log.logSessionsH pid query (stamp (-60)) Nothing (stamp 60) Nothing Nothing Nothing) <&> \(_, Log.SessionsView _ rows _) -> [(r.sessionId, r.hasReplay, r.userName) | r <- V.toList rows] + listed (Just Parser.browserKql) `shouldReturn` [(UUID.toText recording, True, Just "Ada")] + listed Nothing `shouldReturn` [(UUID.toText recording, True, Just "Ada")] + listed (Just "status_code == \"ERROR\"") `shouldReturn` [] + describe "Log Explorer page shell" do it "renders Common facets with the page and leaves other groups lazy" \tr -> do seedFacetSummary tr diff --git a/test/integration/Pages/QueryCacheSpec.hs b/test/integration/Pages/QueryCacheSpec.hs index f215e7b68..6bfdbb26a 100644 --- a/test/integration/Pages/QueryCacheSpec.hs +++ b/test/integration/Pages/QueryCacheSpec.hs @@ -19,6 +19,7 @@ import Pages.Charts.Charts qualified as Charts import Pkg.DeriveUtils (UUIDId (..)) import Pkg.Parser (currentTime, dateRange, defSqlQueryCfg, environment, parseQueryToAST, service) import Pkg.Parser.Expr (ToQueryText (..)) +import GHC.Clock (getMonotonicTimeNSec) import Pkg.QueryCache qualified as QC import Pkg.TestUtils import Relude @@ -358,3 +359,12 @@ spec = around withTestResources do -- No telemetry ingested, so the delta over (t1, t2] succeeds with 0 rows. _ <- runQueryEffect tr $ Charts.queryMetrics Nothing (Just Charts.DTMetric) (Just pid) (Just q) Nothing Nothing (Just (timeAt (-1800))) (Just (timeAt 1800)) Nothing Nothing [] cachedToFor tr key `shouldReturn` Just t2 + + describe "Shared query cache" do + it "withSharedCache_computesOnMiss_servesHits_andRecomputesAfterExpiry" \tr -> do + calls <- newIORef (0 :: Int) + key <- ("shared-cache-spec-" <>) . show <$> getMonotonicTimeNSec + let read' = runQueryEffect tr $ QC.withSharedCache key 300 (liftIO $ atomicModifyIORef' calls \n -> (n + 1, n + 1)) + (,) <$> read' <*> read' `shouldReturn` (1, 1) + withResource tr.trPool \conn -> void $ PG.execute conn "UPDATE rum_panel_cache SET expires_at = now() - interval '1 minute' WHERE cache_key = ?" (PG.Only $ toXXHash key) + read' `shouldReturn` 2 diff --git a/test/integration/Pages/RealUserMonitoringSpec.hs b/test/integration/Pages/RealUserMonitoringSpec.hs deleted file mode 100644 index 06ad22e4b..000000000 --- a/test/integration/Pages/RealUserMonitoringSpec.hs +++ /dev/null @@ -1,1114 +0,0 @@ -module Pages.RealUserMonitoringSpec (spec) where - -import Control.Concurrent (threadDelay) -import Control.Lens ((.~)) -import Data.Aeson qualified as AE -import Data.Cache qualified as Cache -import Data.Default (def) -import Data.Effectful.Hasql qualified as Hasql -import Data.List (lookup) -import Data.Pool (withResource) -import Data.ProtoLens (defMessage) -import Data.Text qualified as T -import Data.Time (NominalDiffTime, UTCTime, addUTCTime) -import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) -import Data.Time.Format.ISO8601 (iso8601Show) -import Data.UUID qualified as UUID -import Data.UUID.Quasi (uuid) -import Data.Vector qualified as V -import Database.PostgreSQL.Simple qualified as PG -import Effectful (Eff, (:>)) -import Effectful.Dispatch.Dynamic (interpose, send) -import Effectful.Labeled (Labeled (..)) -import Hasql.Interpolate qualified as HI -import Hasql.Pool qualified as HP -import Lucid qualified -import Models.Projects.Projects qualified as Projects -import Models.Telemetry.RUM qualified as RUMData -import Network.GRPC.Common.Protobuf (Proto (..)) -import Network.HTTP.Types.URI (parseQueryText) -import Opentelemetry.OtlpServer qualified as OtlpServer -import Pages.BodyWrapper (PageCtx (..)) -import Pages.Charts.Charts qualified as Charts -import Pages.Charts.Types (MetricsData) -import Pages.Components (Deferred (..)) -import Pages.LogExplorer.Log qualified as Log -import Pages.RealUserMonitoring qualified as RUM -import Pkg.Components.TimePicker qualified as TimePicker -import Pkg.Components.Widget qualified as Widget -import Pkg.TestUtils -import Proto.Opentelemetry.Proto.Collector.Metrics.V1.MetricsService_Fields qualified as MSF -import Proto.Opentelemetry.Proto.Common.V1.Common qualified as PC -import Proto.Opentelemetry.Proto.Metrics.V1.Metrics qualified as PM -import Proto.Opentelemetry.Proto.Metrics.V1.Metrics_Fields qualified as PMF -import Relude -import System.Config (AuthContext (..), EnvConfig (..)) -import System.Timeout (timeout) -import System.Types (ATAuthCtx, RespHeaders) -import Test.Hspec -import UnliftIO.Async (wait, withAsync) -import UnliftIO.Exception qualified as E -import Utils (toXXHash) - - --- TimeFusion's partition date is absent from the PostgreSQL mirror. -nativeDateColumn :: TestResources -> HI.Sql -nativeDateColumn tr = if tr.trATCtx.env.enableTimefusionWrites then [HI.sql|,date|] else mempty - - -replayUuid :: UUID.UUID -replayUuid = [uuid|00000000-0000-0000-0000-000000000042|] - - -emptyReplayUuid :: UUID.UUID -emptyReplayUuid = [uuid|00000000-0000-0000-0000-000000000043|] - - -mergedReplayUuid :: UUID.UUID -mergedReplayUuid = [uuid|00000000-0000-0000-0000-000000000044|] - - -sessionId :: Text -sessionId = UUID.toText replayUuid - - -browserSpan :: Text -> Text -> Text -> [(Text, Text)] -> Text -> Text -> Maybe Text -> Text -> TestResources -> IO () -browserSpan apiKey trId spId extras name sid parentM service = browserSpanAt apiKey trId spId extras name sid parentM service frozenTime - - -browserSpanAt :: Text -> Text -> Text -> [(Text, Text)] -> Text -> Text -> Maybe Text -> Text -> UTCTime -> TestResources -> IO () -browserSpanAt apiKey trId spId extras name sid parentM service at tr = - ingestSpanReq tr $ mkSpanRequest trId spId parentM name [] Nothing (map (uncurry mkAttr) $ ("session.id", sid) : extras) (mkResource apiKey [mkAttr "telemetry.sdk.language" "webjs", mkAttr "service.name" service]) at - - --- | A page load exactly as the OpenTelemetry browser SDK sends it, which is what production --- actually looks like: span named @documentLoad@, the page in @url.full@ rather than --- @url.path@, a user agent on the resource, and — the part that broke RUM — no --- @telemetry.sdk.language@ at all. -otelBrowserSpan :: Text -> Text -> Text -> Text -> Text -> TestResources -> IO () -otelBrowserSpan apiKey trId spId sid service tr = - ingestSpanReq tr - $ mkSpanRequest - trId - spId - Nothing - "documentLoad" - [] - Nothing - [mkAttr "session.id" sid, mkAttr "url.full" "https://shop.example/cart"] - (mkResource apiKey [mkAttr "service.name" service, mkAttr "user_agent.original" "Mozilla/5.0 (X11; Linux x86_64) Chrome/151"]) - frozenTime - - -renderPage :: TestResources -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> IO Text -renderPage tr tab query sessionFilterM selected = renderScoped tr tab query sessionFilterM selected Nothing - - --- | Every panel fetches itself, so the page a user ends up looking at is the concatenation of --- the panel responses. Asserting against that keeps these tests about what is on screen rather --- than about which request delivered it. -renderScoped :: TestResources -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> IO Text -renderScoped tr tab query sessionFilterM selected service = - fmap fold . forM ["pulse", "pages", "vitals", "errors", "sessions", "audience"] $ \panel -> - renderPanel tr tab query sessionFilterM selected service (Just panel) - - -renderPanel :: TestResources -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> IO Text -renderPanel tr tab query sessionFilterM selected service panel = - shellHtml (withService service tr) $ RUM.rumGetH testPid tab query sessionFilterM Nothing Nothing (Just "24H") selected Nothing panel (Just "1") Nothing - - -withService :: Maybe Text -> TestResources -> TestResources -withService service tr = tr{trSessAndHeader = fmap (\session -> session{Projects.service = service}) tr.trSessAndHeader} - - -htmlOf :: Lucid.ToHtml a => a -> Text -htmlOf = toStrict . Lucid.renderText . Lucid.toHtml - - --- | The loaded panel body of a RUM response. -rumBody :: TestResources -> ATAuthCtx (RespHeaders RUM.RumGet) -> IO RUM.RumData -rumBody tr action = testServant tr action >>= \(_, RUM.RumGet (PageCtx _ body)) -> deferredBody body - - --- | Every TimeFusion read fails to acquire a connection. -tfUnavailable :: Labeled "timefusion" Hasql.Hasql :> es => Eff es a -> Eff es a -tfUnavailable = interpose @(Labeled "timefusion" Hasql.Hasql) \_ (Labeled effect) -> case effect of - Hasql.UseStatement{} -> pure $ Left HP.AcquisitionTimeoutUsageError - Hasql.UseSession{} -> pure $ Left HP.AcquisitionTimeoutUsageError - Hasql.UseLabeledSession{} -> pure $ Left HP.AcquisitionTimeoutUsageError - - -execSql :: TestResources -> PG.Query -> IO () -execSql tr sql = withResource tr.trPool $ \conn -> void $ PG.execute_ conn sql - - --- | Counts rum_panel_cache inserts made while the action runs. -withCacheWriteCounter :: TestResources -> Text -> (IO Int64 -> IO a) -> IO a -withCacheWriteCounter tr name body = E.bracket_ (execSql tr create) (execSql tr remove) (body count) - where - sequenceName = name <> "_writes" - function = "count_" <> name <> "_write" - create = fromString $ toString $ "CREATE SEQUENCE " <> sequenceName <> "; CREATE FUNCTION " <> function <> "() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM nextval('" <> sequenceName <> "'); RETURN NEW; END $$; CREATE TRIGGER " <> function <> " BEFORE INSERT ON rum_panel_cache FOR EACH ROW EXECUTE FUNCTION " <> function <> "()" - remove = fromString $ toString $ "DROP TRIGGER " <> function <> " ON rum_panel_cache; DROP FUNCTION " <> function <> "(); DROP SEQUENCE " <> sequenceName - count = withResource tr.trPool \conn -> do - [(lastValue, isCalled)] <- PG.query_ conn (fromString $ toString $ "SELECT last_value, is_called FROM " <> sequenceName) :: IO [(Int64, Bool)] - pure $ if isCalled then lastValue else 0 - - -loadVitalPanel :: TestResources -> Projects.ProjectId -> Maybe Text -> Text -> IO RUM.RumData -loadVitalPanel tr projectId refresh = loadPerformance tr projectId Nothing Nothing (Just "24H") refresh . Just - - --- | The loaded Performance tab body for a window, or for one panel of it. -loadPerformance :: TestResources -> Projects.ProjectId -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> IO RUM.RumData -loadPerformance tr projectId from to since refresh panel = rumBody tr $ RUM.rumGetH projectId (Just "performance") Nothing Nothing from to since Nothing Nothing panel (Just "1") refresh - - -measured :: RUMData.VitalMeasurement -> (Maybe Double, Natural) -measured measurement = (RUMData.measurementValue measurement, RUMData.measurementSamples measurement) - - --- | Both vital panels report LCP unavailable, in the summary and in every trend/page point. -lcpUnavailable :: TestResources -> Projects.ProjectId -> Natural -> RUMData.VitalCoverage -> Expectation -lcpUnavailable tr projectId count issue = forM_ ["vitals", "vital_trend"] \panel -> do - page <- loadVitalPanel tr projectId Nothing panel - page.degradedPanels `shouldBe` [] - (if panel == "vitals" then [vital.measurement | vital <- page.vitals, vital.name == "lcp"] else map (.measurement) page.vitalTrend <> map (.measurement) page.pageVitals) - `shouldBe` replicate (if panel == "vitals" then 1 else 2) (RUMData.Unavailable count issue) - - -nanos :: UTCTime -> Word64 -nanos = floor . (* 1000000000) . utcTimeToPOSIXSeconds - - -histogramPoint :: Text -> UTCTime -> UTCTime -> Word64 -> [Word64] -> [Double] -> PM.HistogramDataPoint -histogramPoint url end start count counts bounds = defMessage & PMF.timeUnixNano .~ nanos end & PMF.startTimeUnixNano .~ nanos start & PMF.attributes .~ [mkAttr "page.url" url] & PMF.count .~ count & PMF.bucketCounts .~ counts & PMF.explicitBounds .~ bounds - - -lcpHistogram :: PM.AggregationTemporality -> [PM.HistogramDataPoint] -> PM.Metric -lcpHistogram temporality points = defMessage & PMF.name .~ "browser.web_vital.lcp" & PMF.histogram .~ (defMessage & PMF.aggregationTemporality .~ temporality & PMF.dataPoints .~ points) - - -exportMetrics :: TestResources -> Text -> [PC.KeyValue] -> [PM.Metric] -> IO () -exportMetrics tr apiKey resourceAttrs metrics = - void $ OtlpServer.metricsServiceExport tr.trLogger tr.trATCtx tr.trTracerProvider (Proto $ defMessage & MSF.resourceMetrics .~ [defMessage & PMF.resource .~ mkResource apiKey resourceAttrs & PMF.scopeMetrics .~ [defMessage & PMF.metrics .~ metrics]]) - - --- | Both cache layers: the shared rum_panel_cache table outlives a memory purge by design, --- which is exactly what these examples must not inherit from each other. -purgeRumCaches :: TestResources -> IO () -purgeRumCaches tr = do - Cache.purge tr.trATCtx.rumCache - withResource tr.trPool \conn -> void $ PG.execute_ conn "DELETE FROM rum_panel_cache" - - -spec :: Spec -spec = sequential $ aroundAll withTestResources do - describe "Real User Monitoring" do - it "emptyProject_explainsBrowserTelemetryAndOffersTheDashboard" \tr -> do - shell <- shellHtml tr $ RUM.rumGetH testPid Nothing Nothing Nothing Nothing Nothing (Just "24H") Nothing Nothing Nothing Nothing Nothing - shell `shouldContainAll` ["hx-trigger=\"load\"", "deferred=1", "skeleton-shimmer", "tabs tabs-box tabs-outline"] - -- The shell stands in for the tab it is loading, so switching tabs does not reflow. - sessionsShell <- shellHtml tr $ RUM.rumGetH testPid (Just "sessions") Nothing Nothing Nothing Nothing (Just "24H") Nothing Nothing Nothing Nothing Nothing - sessionsShell `shouldContainAll` ["Loading sessions", "skeleton-shimmer"] - html <- renderPage tr Nothing Nothing Nothing Nothing - html `shouldContainAll` ["No browser telemetry yet", "Install the browser SDK", "Open RUM dashboard", "empty-state"] - - it "scalarVitals_summaryAndDetail_shareTheContinuousPopulationQuantile" \tr -> do - projectId <- createTestProject tr "RUM scalar quantile" - apiKey <- createTestAPIKey tr projectId "rum-scalar-key" - forM_ (zip [1, 10, 20, 30] [-10, -9, -8, -7]) \(value, seconds) -> - ingestMetric tr apiKey [] [mkAttr "page.url" "/scalar"] (if value == 30 then "k6.browser_web_vital_lcp" else "browser.web_vital.lcp") value (addUTCTime seconds frozenTime) - detail <- loadVitalPanel tr projectId Nothing "vital_trend" - summary <- loadVitalPanel tr projectId Nothing "vitals" - (mapMaybe (RUMData.measurementValue . (.measurement)) detail.vitalTrend, [measured point.measurement | point <- detail.pageVitals], [measured vital.measurement | vital <- summary.vitals, vital.name == "lcp"]) - `shouldBe` ([22.5], [(Just 22.5, 4)], [(Just 22.5, 4)]) - - it "syntheticHistograms_doNotOverwhelmRealUserVitals" \tr -> do - projectId <- createTestProject tr "RUM synthetic histogram isolation" - apiKey <- createTestAPIKey tr projectId "rum-synthetic-key" - let at = (`addUTCTime` frozenTime) - point count buckets = histogramPoint "/real" (at (-10)) (at (-60)) count buckets [100, 200] - exportMetrics tr apiKey [] - [ lcpHistogram PM.AGGREGATION_TEMPORALITY_DELTA [point 10 [10, 0, 0]] - , lcpHistogram PM.AGGREGATION_TEMPORALITY_DELTA [point 1000 [0, 1000, 0]] & PMF.name .~ "k6.browser_web_vital_lcp" - ] - page <- loadVitalPanel tr projectId Nothing "vitals" - [measured vital.measurement | vital <- page.vitals, vital.name == "lcp"] `shouldBe` [(Just 75, 10)] - - it "vitalTrend_partialFirstBucket_staysInsideTheSelectedAxis" \tr -> do - projectId <- createTestProject tr "RUM partial trend bucket" - apiKey <- createTestAPIKey tr projectId "rum-partial-bucket-key" - ingestMetric tr apiKey [] [mkAttr "page.url" "/partial-bucket"] "browser.web_vital.lcp" 175 (addUTCTime (-10) frozenTime) - let fromQuery = Just $ toText $ iso8601Show $ addUTCTime (-31.125) frozenTime - toQuery = Just $ toText $ iso8601Show $ addUTCTime (-1.25) frozenTime - forM_ ([(Nothing, Nothing, Just "30S", -30, 0), (fromQuery, toQuery, Nothing, -31.125, -1.25), (Nothing, Nothing, Just "1H", -3600, 0)] :: [(Maybe Text, Maybe Text, Maybe Text, NominalDiffTime, NominalDiffTime)]) \(from, to, since, start, end) -> do - page <- loadPerformance tr projectId from to since Nothing (Just "vital_trend") - page.degradedPanels `shouldBe` [] - [measured vital.measurement | vital <- page.vitals, vital.name == "lcp"] `shouldBe` [(Just 175, 1)] - widget <- renderedWidget $ htmlOf page - let millis seconds = floor (1000 * utcTimeToPOSIXSeconds (addUTCTime seconds frozenTime)) :: Int - plottedStart = max (millis start) (millis (-300)) - [(dataset.from, dataset.to, dataset.source) | dataset <- maybeToList widget.dataset] - `shouldBe` [(Just $ millis start, Just $ millis end, AE.toJSON ([AE.toJSON (["timestamp", "P75"] :: [Text]), AE.toJSON (plottedStart, 175 :: Int)] :: [AE.Value]))] - - it "histogramVitals_useObservationBuckets_insteadOfExportMeans" \tr -> do - let point end start count total low high counts = histogramPoint "/histogram" end start count counts [100, 200, 10000] & PMF.sum .~ total & PMF.min .~ low & PMF.max .~ high - at = (`addUTCTime` frozenTime) - delta = [point (at (-10)) (at (-60)) 100 7000 0 200 [80, 20, 0, 0], point (at (-9)) (at (-10)) 1 9000 9000 9000 [0, 0, 1, 0]] - -- The previous export is outside the selected 24H window. The repeated export - -- contributes nothing; a new start timestamp starts a fresh cumulative epoch. - cumulative = - [ point (at (-86401)) (at (-90000)) 100 7000 0 200 [80, 20, 0, 0] - , point (at (-10)) (at (-90000)) 101 16000 0 9000 [80, 20, 1, 0] - , point (at (-9)) (at (-90000)) 101 16000 0 9000 [80, 20, 1, 0] - , point (at (-7)) (at (-8)) 100 7000 0 200 [80, 20, 0, 0] - ] - schemaDelta = - [ point (at (-10)) (at (-60)) 100 7000 0 200 [80, 20, 0] & PMF.explicitBounds .~ [100, 200] - , point (at (-9)) (at (-10)) 100 12000 0 200 [10, 90, 0] & PMF.explicitBounds .~ [50, 200] - ] - schemaCumulative = - [ point (at (-86401)) (at (-90000)) 100 7000 0 200 [40, 60, 0] & PMF.explicitBounds .~ [50, 200] - , point (at (-10)) (at (-90000)) 120 10000 0 200 [80, 40, 0] & PMF.explicitBounds .~ [100, 200] - ] - mixed = [point (at (-10)) (at (-60)) 100 7000 0 200 [80, 20, 0, 0]] - mixedInside = [point (at (-10)) (at (-60)) 20 1000 0 100 [20, 0, 0, 0]] - mixedOverflow = [point (at (-10)) (at (-60)) 20 1000 0 100 [20] & PMF.explicitBounds .~ []] - disjoint = [point (at (-10)) (at (-60)) 100 7000 0 200 [80, 20] & PMF.explicitBounds .~ [100], point (at (-9)) (at (-10)) 100 7000 0 200 [80, 20] & PMF.explicitBounds .~ [200]] - invalidReset = [point (at (-86401)) (at (-90000)) 100 7000 0 200 [80, 20, 0, 0], point (at (-10)) (at (-90000)) 90 6000 0 200 [70, 20, 0, 0]] - missing = [point (at (-10)) (at (-90000)) 100 7000 0 200 [80, 20, 0, 0], point (at (-9)) (at (-90000)) 101 16000 0 9000 [80, 20, 1, 0]] - unknownMarker = [point (at (-10)) (at (-10)) 100 7000 0 200 [80, 20, 0, 0], point (at (-9)) (at (-10)) 101 7100 0 200 [81, 20, 0, 0]] - overflow = [point (at (-10)) (at (-60)) 100 1500000 10001 20000 [0, 0, 0, 100]] - unknownStart = [point (at (-10)) (at (-60)) 100 7000 0 200 [80, 20, 0, 0] & PMF.startTimeUnixNano .~ 0] - staleResume = - [ point (at (-86401)) (at (-90000)) 100 7000 0 200 [80, 20, 0, 0] - , point (at (-10)) (at (-90000)) 101 7100 0 200 [81, 20, 0, 0] - , point (at (-9)) (at (-90000)) 1000 70000 0 200 [980, 20, 0, 0] & PMF.flags .~ 1 - , point (at (-8)) (at (-90000)) 102 7200 0 200 [82, 20, 0, 0] - , point (at (-7)) (at (-90000)) 103 7300 0 200 [83, 20, 0, 0] - ] - staleNoEpoch = take 2 staleResume <> [point (at (-9)) (at (-90000)) 1000 70000 0 200 [980, 20, 0, 0] & PMF.flags .~ 1 & PMF.startTimeUnixNano .~ 0] <> drop 3 staleResume - staleBeforeWindow = - [ point (at (-86403)) (at (-90000)) 100 7000 0 200 [80, 20, 0, 0] - , point (at (-86401)) (at (-90000)) 1000 70000 0 200 [980, 20, 0, 0] & PMF.flags .~ 1 & PMF.startTimeUnixNano .~ 0 - , point (at (-10)) (at (-90000)) 101 7100 0 200 [81, 20, 0, 0] - , point (at (-9)) (at (-90000)) 102 7200 0 200 [82, 20, 0, 0] - ] - staleReset = take 3 staleNoEpoch <> [point (at (-7)) (at (-8)) 100 7000 0 200 [80, 20, 0, 0]] - staleUnknownReset = take 3 staleNoEpoch <> [point (at (-8)) (at (-8)) 100 7000 0 200 [80, 20, 0, 0], point (at (-7)) (at (-8)) 101 7100 0 200 [81, 20, 0, 0]] - cases = - [ (PM.AGGREGATION_TEMPORALITY_DELTA, delta, [], (Just 94.6875, 101)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, cumulative, [], (Just 94.6875, 101)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, schemaDelta, [], (Just 150, 200)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, schemaCumulative, [], (Just 150, 20)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, mixed, [9000], (Just 94.6875, 101)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, missing, [], (Nothing, 1)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, unknownMarker, [], (Just 75, 1)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, overflow, [], (Nothing, 100)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, unknownStart, [], (Nothing, 0)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, staleResume, [], (Nothing, 2)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, staleNoEpoch, [], (Nothing, 2)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, staleBeforeWindow, [], (Nothing, 1)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, staleReset, [], (Just (75.75 / 81 * 100), 101)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, staleUnknownReset, [], (Just 75, 2)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, mixedInside, replicate 80 90, (Just 90, 100)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, mixedOverflow, replicate 70 90 <> replicate 10 100, (Nothing, 100)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, disjoint, [], (Nothing, 200)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, invalidReset, [], (Nothing, 0)) - , (PM.AGGREGATION_TEMPORALITY_UNSPECIFIED, mixed, [], (Nothing, 0)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, [point (at (-10)) (at (-60)) 100 7000 0 200 [80, 10, 0, 0]], [], (Nothing, 0)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, [point (at (-10)) (at (-60)) 100 7000 0 200 [80, 20, 0, 0], point (at (-9)) (at (-20)) 100 7000 0 200 [80, 20, 0, 0]], [], (Nothing, 100)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, [point (at (-10)) (at (-60)) 0 0 0 0 [0, 0, 0, 0]], [], (Nothing, 0)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, [point (at (-10)) (at (-60)) 1 50 0 100 [1, 0] & PMF.explicitBounds .~ [100]], [9000], (Just 9000, 2)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, schemaDelta, [150], (Just 150, 201)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, unknownStart, [], (Just 93.75, 100)) - , (PM.AGGREGATION_TEMPORALITY_DELTA, [point (at (-10)) (at (-9)) 100 7000 0 200 [80, 20, 0, 0]], [], (Nothing, 0)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, take 1 invalidReset <> [point (at (-10)) (at (-90000)) 0 0 0 0 [0, 0, 0, 0]], [], (Nothing, 0)) - , (PM.AGGREGATION_TEMPORALITY_CUMULATIVE, [point (at (-86401)) (at (-90000)) 0 0 0 0 [0, 0, 0, 0], point (at (-11)) (at (-90000)) 0 0 0 0 [0, 0, 0, 0], point (at (-10)) (at (-90000)) 4000000000000000000 4000000000000000000 0 100 [4000000000000000000, 0, 0, 0]], [], (Just 75, 4000000000000000000)) - ] - pages <- forM cases \(temporality, points, scalars, _) -> do - projectId <- createTestProject tr "RUM histogram" - apiKey <- createTestAPIKey tr projectId "rum-histogram-key" - let scoped = withService (Just "histogram-ui") tr - exportMetrics tr apiKey [mkAttr "service.name" "histogram-ui"] [lcpHistogram temporality points] - when (temporality == PM.AGGREGATION_TEMPORALITY_UNSPECIFIED) - $ runTestBg frozenTime tr - $ Hasql.withHasqlTimefusion True - $ Hasql.interpExecute_ - $ [HI.sql|INSERT INTO otel_metrics(project_id,timestamp,ingested_at,metric_unit,dropped_attributes_count,message_size_bytes,id,series_id,start_timestamp,metric_name,metric_type, - distribution_count,hist_bucket_counts,hist_explicit_bounds,attributes,resource,resource___service___name,flags|] - <> nativeDateColumn tr - <> [HI.sql|) - SELECT project_id,timestamp-INTERVAL '1 second',ingested_at,metric_unit,dropped_attributes_count,message_size_bytes,id,series_id,start_timestamp,metric_name,metric_type, - distribution_count,hist_bucket_counts,hist_explicit_bounds,attributes,resource,resource___service___name,flags|] - <> nativeDateColumn tr - <> [HI.sql| - FROM otel_metrics WHERE project_id=#{projectId.toText}|] - forM_ (zip scalars [0 :: Int ..]) \(value, index) -> ingestMetric tr apiKey [mkAttr "service.name" "histogram-ui"] [mkAttr "page.url" "/histogram"] "browser.web_vital.lcp" value (at (-6 + fromIntegral index / 1000)) - purgeRumCaches tr - detail <- loadVitalPanel scoped projectId Nothing "vital_trend" - summary <- loadVitalPanel scoped projectId Nothing "vitals" - pure (detail, summary) - map (\(detail, summary) -> (detail.degradedPanels, summary.degradedPanels)) pages `shouldBe` replicate (length cases) ([], []) - forM_ (zip cases pages) \((_, _, _, (value, count)), (_, summary)) -> - forM_ (lookup (isJust value, count) [((False, 1), "1 known observation"), ((True, 1), "1 observation"), ((True, 100), "100 observations")]) \label -> - htmlOf summary `shouldContainAll` [">" <> label <> ""] - -- Explicit/custom buckets use uniform within-bucket interpolation; scalar observations - -- remain exact. Missing baselines retain known counts without a full-population P75. - map (\(detail, summary) -> (map (measured . (.measurement)) detail.vitalTrend, [(value.page, measured value.measurement) | value <- detail.pageVitals], [measured value.measurement | value <- summary.vitals, value.name == "lcp"])) pages - `shouldBe` [([expected], [("/histogram", expected)], [expected]) | (_, _, _, expected) <- cases] - let lcpMeasurements = [value.measurement | (_, summary) <- pages, value <- summary.vitals, value.name == "lcp"] - [issue | RUMData.Unavailable _ issue <- lcpMeasurements] `shouldBe` [RUMData.MissingBaseline, RUMData.UnboundedBucket, RUMData.UnknownStart, RUMData.InterruptedSeries, RUMData.InterruptedSeries, RUMData.InterruptedSeries, RUMData.UnboundedBucket, RUMData.UnboundedBucket, RUMData.InvalidReset, RUMData.UnknownTemporality, RUMData.InvalidBuckets, RUMData.OverlappingIntervals, RUMData.UnknownStart, RUMData.InvalidReset] - [estimate.bounds | RUMData.Measured _ estimate <- lcpMeasurements] - `shouldBe` [Just (0, 100), Just (0, 100), Just (0, 200), Just (0, 200), Just (0, 100), Just (0, 100), Just (0, 100), Just (0, 100), Just (0, 100), Nothing, Just (0, 200), Just (0, 100), Just (0, 100)] - - it "vitalPopulation_gaugeAndDelta_useOneCurrentWindowRead" \tr -> do - projectId <- createTestProject tr "RUM one-read population" - apiKey <- createTestAPIKey tr projectId "rum-one-read-key" - let at = (`addUTCTime` frozenTime) - exportMetrics tr apiKey [] [lcpHistogram PM.AGGREGATION_TEMPORALITY_DELTA [histogramPoint "/one-read" (at (-10)) (at (-60)) 100 [80, 20, 0] [100, 200]]] - forM_ (zip [10, 30] [-11, -10]) \(value, seconds) -> ingestMetric tr apiKey [] [mkAttr "page.url" "/one-read"] "browser.web_vital.fcp" value (at seconds) - queries <- newIORef (0 :: Int) - let database = interpose @(Labeled "timefusion" Hasql.Hasql) \_ (Labeled effect) -> do - modifyIORef' queries (+ 1) - case effect of - Hasql.UseStatement params statement -> send $ Labeled @"timefusion" $ Hasql.UseStatement params statement - Hasql.UseSession session -> send $ Labeled @"timefusion" $ Hasql.UseSession session - Hasql.UseLabeledSession label attributes session -> send $ Labeled @"timefusion" $ Hasql.UseLabeledSession label attributes session - -- Unrelated native traffic must not affect the handler-local count. - when tr.trATCtx.env.enableTimefusionReads - $ void - $ runQueryEffect tr - $ Hasql.withHasqlTimefusion True - $ Hasql.interpOne @(HI.OneColumn Int64) [HI.sql|SELECT 1::bigint|] - page <- rumBody tr $ database $ RUM.rumGetH projectId (Just "performance") Nothing Nothing Nothing Nothing (Just "24H") Nothing Nothing (Just "vital_trend") (Just "1") Nothing - page.degradedPanels `shouldBe` [] - let expected = [("fcp", (Just 25, 2)), ("lcp", (Just 93.75, 100))] - sort [(vital.name, measured vital.measurement) | vital <- page.vitals, vital.name `elem` ["fcp", "lcp"]] `shouldBe` expected - sort [(vital.metricName, measured vital.measurement) | vital <- page.vitalTrend] `shouldBe` expected - sort [(vital.metricName, measured vital.measurement) | vital <- page.pageVitals] `shouldBe` expected - when tr.trATCtx.env.enableTimefusionReads $ readIORef queries `shouldReturn` 1 - - it "histogramVitals_missingCount_retainsUnavailableCoverage" \tr -> do - projectId <- createTestProject tr "RUM missing histogram count" - apiKey <- createTestAPIKey tr projectId "rum-missing-count-key" - exportMetrics tr apiKey [] [lcpHistogram PM.AGGREGATION_TEMPORALITY_DELTA [histogramPoint "/missing-count" (addUTCTime (-10) frozenTime) (addUTCTime (-60) frozenTime) 100 [80, 20, 0] [100, 200]]] - runTestBg frozenTime tr - $ Hasql.withHasqlTimefusion True - $ Hasql.interpExecute_ - $ [HI.sql| - INSERT INTO otel_metrics(project_id,timestamp,ingested_at,metric_unit,dropped_attributes_count,message_size_bytes,id,series_id,start_timestamp,metric_name,metric_type,aggregation_temporality, - hist_bucket_counts,hist_explicit_bounds,attributes,resource,flags|] - <> nativeDateColumn tr - <> [HI.sql|) - SELECT project_id,timestamp-INTERVAL '1 minute',ingested_at,metric_unit,dropped_attributes_count,message_size_bytes,id,series_id,start_timestamp-INTERVAL '1 minute',metric_name,metric_type,aggregation_temporality, - hist_bucket_counts,hist_explicit_bounds,attributes,resource,flags|] - <> nativeDateColumn tr - <> [HI.sql| FROM otel_metrics WHERE project_id=#{projectId.toText} - |] - lcpUnavailable tr projectId 100 RUMData.InvalidBuckets - - it "denseHistogramVitals_keepCompleteCounts_andBoundCachedPages" \tr -> do - projectId <- createTestProject tr "RUM dense histogram" - apiKey <- createTestAPIKey tr projectId "rum-dense-key" - let at = (`addUTCTime` frozenTime) - points = - [ histogramPoint ("https://dense.example/" <> show series) (at end) (at (-90000)) (100 + fromIntegral ordinal) [80 + fromIntegral ordinal, 20, 0] [100, 200] - | series <- [0 .. 199 :: Int] - , (ordinal, end) <- [(0, -86401)] <> [(n, -4800 + 30 * fromIntegral n) | n <- [1 .. 160 :: Int]] - ] - scalar = - defMessage & PMF.name - .~ "browser.web_vital.fcp" - & PMF.gauge - .~ (defMessage & PMF.dataPoints .~ [defMessage & PMF.timeUnixNano .~ nanos (at (-10)) & PMF.attributes .~ [mkAttr "page.url" ("https://dense.example/" <> show series)] & PMF.asDouble .~ 25 | series <- [0 .. 199 :: Int]]) - exportMetrics tr apiKey [] [lcpHistogram PM.AGGREGATION_TEMPORALITY_CUMULATIVE points, scalar] - forM_ ([Just "1", Nothing] :: [Maybe Text]) \refresh -> do - when (isNothing refresh) $ Cache.purge tr.trATCtx.rumCache - page <- loadVitalPanel tr projectId refresh "vital_trend" - page.degradedPanels `shouldBe` [] - forM_ ([("lcp", 75, 32000), ("fcp", 25, 200)] :: [(Text, Double, Natural)]) \(name, value, count) -> do - [measured vital.measurement | vital <- page.vitals, vital.name == name] `shouldBe` [(Just value, count)] - let trend = filter ((== name) . (.metricName)) page.vitalTrend - sum (map (RUMData.measurementSamples . (.measurement)) trend) `shouldBe` count - map (RUMData.measurementValue . (.measurement)) trend `shouldSatisfy` all (== Just value) - let selectedPages = take 150 (sort ["https://dense.example/" <> show series | series <- [0 .. 199 :: Int]]) - forM_ ([("lcp", 160), ("fcp", 1)] :: [(Text, Natural)]) \(name, count) -> do - let metricPages = filter ((== name) . (.metricName)) page.pageVitals - map (RUMData.measurementSamples . (.measurement)) metricPages `shouldBe` replicate 150 count - map (.page) metricPages `shouldBe` selectedPages - - it "invalidScalarVitals_areUnavailableWithoutHistogramBucketErrors" \tr -> do - forM_ [-1, 1 / 0, 0 / 0] \value -> do - projectId <- createTestProject tr "RUM invalid scalar" - apiKey <- createTestAPIKey tr projectId "rum-invalid-key" - ingestMetric tr apiKey [] [mkAttr "page.url" "/invalid"] "browser.web_vital.lcp" value (addUTCTime (-10) frozenTime) - lcpUnavailable tr projectId 0 RUMData.InvalidValue - - it "unsupportedVitals_doNotPresentSumOrOtherDistributionMeansAsObservations" \tr -> do - let end = nanos $ addUTCTime (-10) frozenTime - start = nanos $ addUTCTime (-60) frozenTime - attributes = [mkAttr "page.url" "/unsupported"] - number :: PM.NumberDataPoint - number = defMessage & PMF.timeUnixNano .~ end & PMF.startTimeUnixNano .~ start & PMF.attributes .~ attributes & PMF.asDouble .~ 2200 - distribution :: PM.ExponentialHistogramDataPoint - distribution = defMessage & PMF.timeUnixNano .~ end & PMF.startTimeUnixNano .~ start & PMF.attributes .~ attributes & PMF.count .~ 100 & PMF.sum .~ 220000 - summaryPoint :: PM.SummaryDataPoint - summaryPoint = defMessage & PMF.timeUnixNano .~ end & PMF.attributes .~ attributes & PMF.count .~ 100 & PMF.sum .~ 220000 - base :: PM.Metric - base = defMessage & PMF.name .~ "browser.web_vital.lcp" - metrics = - [ base & PMF.sum .~ (defMessage & PMF.aggregationTemporality .~ PM.AGGREGATION_TEMPORALITY_CUMULATIVE & PMF.dataPoints .~ [number]) - , base & PMF.exponentialHistogram .~ (defMessage & PMF.aggregationTemporality .~ PM.AGGREGATION_TEMPORALITY_DELTA & PMF.dataPoints .~ [distribution]) - , base & PMF.summary .~ (defMessage & PMF.dataPoints .~ [summaryPoint]) - ] - forM_ metrics \metric -> do - projectId <- createTestProject tr "RUM unsupported populations" - apiKey <- createTestAPIKey tr projectId "rum-unsupported-key" - exportMetrics tr apiKey [] [metric] - lcpUnavailable tr projectId 0 RUMData.UnsupportedPopulation - - it "histogramVitals_exclusiveBucketLowerBounds_preserveKnownRatingBands" \tr -> do - ratings <- forM [[2500, 4000], [4000, 5000], [2000, 4000]] \bounds -> do - projectId <- createTestProject tr "RUM histogram bands" - apiKey <- createTestAPIKey tr projectId "rum-band-key" - exportMetrics tr apiKey [] [lcpHistogram PM.AGGREGATION_TEMPORALITY_DELTA [histogramPoint "/bands" (addUTCTime (-10) frozenTime) (addUTCTime (-60) frozenTime) 100 [0, 100, 0] bounds & PMF.sum .~ 300000]] - page <- loadVitalPanel tr projectId Nothing "vitals" - pure $ fst $ T.breakOn "" $ snd $ T.breakOn "Largest Contentful Paint" $ htmlOf page - zipWithM_ shouldContainAll ratings [["Needs improvement"], ["Poor"], ["Not assessed"]] - - it "pageVitals_distinctExactUrls_doNotMergeRoutePercentiles" \tr -> do - projectId <- createTestProject tr "RUM exact page populations" - apiKey <- createTestAPIKey tr projectId "rum-page-key" - let low = "https://shop.example/item/ABCDEF12?variant=low" - high = "https://shop.example/item/DEADBEEF?variant=high" - forM_ ([(low, 10, -10), (low, 20, -9), (high, 1000, -8), (high, 2000, -7)] :: [(Text, Double, Int)]) \(url, value, seconds) -> - ingestMetric tr apiKey [] [mkAttr "page.url" url] "browser.web_vital.lcp" value (addUTCTime (fromIntegral seconds) frozenTime) - page <- shellHtml tr $ RUM.rumGetH projectId (Just "performance") Nothing Nothing Nothing Nothing (Just "24H") Nothing Nothing (Just "vital_trend") (Just "1") Nothing - page `shouldContainAll` [low, high, "17.5 ms", "1.8 s", "attributes.url.full%20%3D%3D%20%22https"] - page `shouldSatisfy` (not . T.isInfixOf "/item/{hex}") - - it "explicitTimeWindow_withoutSince_survivesSharedNavigation" \tr -> do - let from = addUTCTime (-5400) frozenTime - to = addUTCTime (-5) frozenTime - fromQuery = Just $ toText $ iso8601Show from - toQuery = Just $ toText $ iso8601Show to - (_, RUM.RumGet (PageCtx _ shell)) <- testServant tr $ RUM.rumGetH testPid (Just "performance") Nothing Nothing fromQuery toQuery Nothing Nothing Nothing Nothing Nothing Nothing - case shell of - DeferredShell _ url _ -> url `shouldNotSatisfy` T.isInfixOf "since=24H" - DeferredBody{} -> fail "Expected initial shared-window shell" - forM_ [(fromQuery, toQuery, from, to, Nothing), (fromQuery, Nothing, from, frozenTime, Nothing), (Nothing, toQuery, addUTCTime (-300) frozenTime, to, Nothing), (Nothing, Nothing, addUTCTime (-86400) frozenTime, frozenTime, Just ("24H" :: Text))] \(fromM, toM, expectedFrom, expectedTo, expectedSince) -> do - page <- loadPerformance tr testPid fromM toM Nothing Nothing Nothing - let window :: TimePicker.TimeWindow - window = page.links.window - (window.fromTime, window.toTime, window.sinceQuery) `shouldBe` (expectedFrom, expectedTo, expectedSince) - - it "singletonVitalTrend_keepsTheSelectedTimeWindow" \tr -> do - projectId <- createTestProject tr "RUM singleton time window" - apiKey <- createTestAPIKey tr projectId "rum-singleton-window-key" - ingestMetric tr apiKey [] [] "browser.web_vital.lcp" 1200 (addUTCTime (-10) frozenTime) - let millis :: UTCTime -> Int - millis = floor . (* 1000) . utcTimeToPOSIXSeconds - explicitFrom = addUTCTime (-5400) frozenTime - explicitTo = addUTCTime (-5) frozenTime - forM_ [(Nothing, Nothing, Just ("1H" :: Text), addUTCTime (-3600) frozenTime, frozenTime), (Just $ toText $ iso8601Show explicitFrom, Just $ toText $ iso8601Show explicitTo, Just "", explicitFrom, explicitTo)] \(from, to, since, expectedFrom, expectedTo) -> do - page <- loadPerformance tr projectId from to since Nothing (Just "vital_trend") - length page.vitalTrend `shouldBe` 1 - htmlOf page `shouldContainAll` [""from":" <> show (millis expectedFrom), ""to":" <> show (millis expectedTo)] - - it "browserTelemetry_correlatesExperienceVitalsErrorsAndReplaySessions" \tr -> do - apiKey <- createTestAPIKey tr testPid "rum-browser-key" - browserSpan apiKey "10000000000000000000000000000001" "1000000000000001" [("url.path", "/checkout"), ("user.id", "usr-42"), ("user.full_name", "Ada Lovelace")] "Pageview · /checkout" sessionId Nothing "storefront" tr - browserSpan apiKey "10000000000000000000000000000001" "1000000000000002" [("url.path", "/checkout"), ("error.type", "TypeError"), ("error.message", "Cannot read cart")] "TypeError · /checkout" sessionId (Just "1000000000000001") "storefront" tr - browserSpan apiKey "20000000000000000000000000000002" "2000000000000001" [("url.path", "/search"), ("user.id", "usr-9")] "Pageview · /search" "session-search" Nothing "storefront" tr - ingestTrace tr apiKey "GET /backend-only" frozenTime - ingestMetric tr apiKey [] [] "browser.web_vital.lcp" 2200 frozenTime - ingestMetric tr apiKey [] [] "browser.web_vital.cls" 0.08 frozenTime - - withResource tr.trPool \conn -> do - void $ PG.execute conn "INSERT INTO projects.replay_sessions (session_id, project_id, created_at, last_event_at, event_file_count, user_id, user_name) VALUES (?, ?, ?, ?, 1, ?, ?) ON CONFLICT (session_id) DO UPDATE SET created_at = EXCLUDED.created_at, last_event_at = EXCLUDED.last_event_at" (replayUuid, testPid, frozenTime, addUTCTime 60 frozenTime, "usr-42" :: Text, "Ada Lovelace" :: Text) - void $ PG.execute conn "INSERT INTO projects.replay_sessions (session_id, project_id, created_at, last_event_at, event_file_count, user_name) VALUES (?, ?, ?, ?, 0, ?) ON CONFLICT (session_id) DO UPDATE SET created_at = EXCLUDED.created_at, last_event_at = EXCLUDED.last_event_at, event_file_count = 0, file_keys = '{}', shard_keys = '{}'" (emptyReplayUuid, testPid, frozenTime, addUTCTime 60 frozenTime, "No recording" :: Text) - void $ PG.execute conn "INSERT INTO projects.replay_sessions (session_id, project_id, created_at, last_event_at, event_file_count, shard_keys, user_name) VALUES (?, ?, ?, ?, 0, ARRAY['00000000-0000-0000-0000-000000000044/merged.json.gz'], ?) ON CONFLICT (session_id) DO UPDATE SET created_at = EXCLUDED.created_at, last_event_at = EXCLUDED.last_event_at, event_file_count = 0, shard_keys = EXCLUDED.shard_keys" (mergedReplayUuid, testPid, frozenTime, addUTCTime 60 frozenTime, "Merged replay" :: Text) - - -- The summary widgets send raw SQL (so TimeFusion can serve them from rollup measures); - -- run it through the chart pipeline exactly as the widgets do. Two page views and two - -- sessions from the browser spans; the backend span is in neither. - let widget dataType sql = runQueryEffect tr $ Charts.queryMetrics Nothing (Just dataType) (Just testPid) Nothing (Just sql) Nothing (Just $ stamp (-3600)) (Just $ stamp 3600) (Just "spans") Nothing [] - stamp s = toText $ iso8601Show $ addUTCTime s frozenTime - series :: Text -> MetricsData -> Double - series name m = sum $ maybe [] (\i -> mapMaybe (join . (V.!? i)) (V.toList m.dataset)) (V.elemIndex name m.headers) - pageViews <- widget Charts.DTMetric $ RUM.binnedSql "count(*)" RUM.pageViewSql - sessionCount <- widget Charts.DTFloat RUM.sessionsSql - errors <- widget Charts.DTMetric $ RUM.binnedSql "count(*)" (RUM.browserSql <> " AND " <> RUM.errorSql) - activity <- widget Charts.DTMetric RUM.activitySql - p75 <- widget Charts.DTFloat RUM.p75Sql - forM_ (zip ["pageViews", "sessions", "errors", "activity", "p75" :: Text] [pageViews, sessionCount, errors, activity, p75]) \(name, m) -> (name, m.error) `shouldBe` (name, Nothing) - (series "value" pageViews, sessionCount.dataFloat) `shouldBe` (2, Just (2 :: Double)) - (series "Page views" activity, series "Errors" activity) `shouldBe` (2 :: Double, series "value" errors) - isJust p75.dataFloat `shouldBe` True - - overviewData <- rumBody tr $ RUM.rumGetH testPid Nothing Nothing Nothing Nothing Nothing (Just "24H") Nothing Nothing (Just "pulse") (Just "1") Nothing - (\p -> (p.sessions, isJust p.p75LoadMs)) <$> overviewData.pulse `shouldBe` Just (2, True) - overviewData.degradedPanels `shouldBe` [] - overview <- renderPage tr Nothing Nothing Nothing Nothing - -- The unscoped read caches under an unscoped key; `service` is part of that key so a - -- scoped page can never be served these rows. - isJust <$> Cache.lookup tr.trATCtx.rumCache (RUMData.RumCacheKey testPid (RUMData.VitalPopulationQuery RUMData.OneHour) Nothing Nothing Nothing Nothing (Just "24H")) `shouldReturn` True - -- The numbers and activity chart are dashboard Widget components that fetch their own - -- data through the chart pipeline; the page ships their queries. The session and P75 - -- tiles also arrive with their value from the pulse row above. - overview `shouldContainAll` ["Page views", "Browser errors", "{{query_ast_filters}}", "rum-activity", "Largest Contentful Paint", "2.2 s", "/checkout", "Ada Lovelace"] - -- The LIVE badge is only honest if something listens for the time transport's tick, and - -- the panels hold every number on this page. Each re-fetches itself in place. - overview `shouldContainAll` ["hx-trigger=\"update-query[", "from:window\"", "hx-sync=\"#rum-panel-pages:replace\""] - -- The tab strip and time picker must not wait on six 24-hour scans: the request that - -- paints the page answers with a skeleton that fetches the panels itself. Panel data - -- appearing here again would mean a tab click is back to seconds of blank page. - shell <- shellHtml tr $ RUM.rumGetH testPid Nothing Nothing Nothing Nothing Nothing (Just "24H") Nothing Nothing Nothing Nothing Nothing - shell `shouldContainAll` ["Real User Monitoring", "tabs tabs-box tabs-outline", "id=\"rum-page\"", "hx-trigger=\"load\"", "deferred=1"] - T.isInfixOf "Ada Lovelace" shell `shouldBe` False - - sessions <- renderPage tr (Just "sessions") Nothing (Just "errors") (Just sessionId) - sessions `shouldContainAll` ["With errors", "Ada Lovelace", "Watch replay", "initialSession=\"00000000-0000-0000-0000-000000000042\"", "hx-target=\"#rum-replay-workspace\"", "hx-sync=\"#rum-replay-workspace:replace\""] - T.isInfixOf "/search" sessions `shouldBe` False - -- A row click must fetch the sessions panel: a deferred request without a panel renders - -- only shells, hx-select finds no workspace in it, and the outerHTML swap deletes the - -- workspace from the page. - sessions `shouldContainAll` ["panel=sessions&deferred=1"] - -- And the shells a deep link renders must carry its filter and selection, or the panel - -- they fetch comes back unfiltered with nothing selected. - deepShell <- shellHtml tr $ RUM.rumGetH testPid (Just "sessions") Nothing (Just "errors") Nothing Nothing (Just "24H") (Just sessionId) Nothing Nothing (Just "1") Nothing - deepShell `shouldContainAll` ["filter=errors", "session=00000000-0000-0000-0000-000000000042"] - - replaySessions <- renderPage tr (Just "sessions") Nothing (Just "replays") Nothing - T.isInfixOf "No recording" replaySessions `shouldBe` False - T.isInfixOf "Merged replay" replaySessions `shouldBe` True - - it "deferredRUMPanel_omitsPageChrome_preservesPanelMarkup" \tr -> do - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-panel-body-key" - otelBrowserSpan apiKey "88000000000000000000000000000008" "8800000000000001" "session-panel-body" "panel-body-browser" tr - let scoped = withService (Just "panel-body-browser") tr - (_, page@(RUM.RumGet (PageCtx _ body))) <- testServant scoped $ RUM.rumGetH testPid (Just "performance") Nothing Nothing Nothing Nothing (Just "24H") Nothing Nothing (Just "pages") (Just "1") Nothing - let rendered = htmlOf page - (rendered == htmlOf body) `shouldBe` True - rendered `shouldContainAll` ["id=\"rum-page\"", "id=\"rum-panel-pages\"", "Top pages", "/cart"] - T.isInfixOf " do - purgeRumCaches tr - projectId <- createTestProject tr "RUM failed panel" - let scoped = tr{trATCtx = tr.trATCtx{env = tr.trATCtx.env{enableTimefusionReads = True}}} - forM_ ([("vitals", "rum-panel-vitals", [RUMData.VitalPopulationQuery RUMData.OneHour]), ("vital_trend", "rum-panel-vital_trend", [RUMData.VitalPopulationQuery RUMData.OneHour]), ("sessions", "rum-sessions-list", [RUMData.SessionSearchQuery Nothing RUMData.AllSessionRows, RUMData.SessionDetailQuery "selected-session"]), ("session_detail", "rum-replay-workspace", [RUMData.SessionDetailQuery "selected-session"])] :: [(Text, Text, [RUMData.RumQuery])]) \(panel, target, queries) -> do - (_, payload@(RUM.RumGet (PageCtx _ body))) <- testServant scoped $ tfUnavailable $ RUM.rumGetH projectId (Just $ if panel `elem` ["sessions", "session_detail"] then "sessions" else "performance") Nothing Nothing Nothing Nothing (Just "24H") (Just "selected-session") Nothing (Just panel) (Just "1") Nothing - page <- deferredBody body - page.degradedPanels `shouldBe` queries - let selected = snd $ T.breakOn ("id=\"" <> target <> "\"") $ htmlOf payload - T.isPrefixOf "
" selected) `shouldBe` True - selected `shouldContainAll` ["Some RUM data could not be loaded.", ">Retry", "refresh=1"] - any (`T.isInfixOf` selected) ["No data", "No web vital samples", "Choose a session", "No sessions match"] `shouldBe` False - let sid = "00000000-0000-0000-0000-000000000091" :: Text - -- refresh: a cold wide list otherwise answers with the uncached newest-3h slice. - sessions resources panel selected = testServant resources $ RUM.rumGetH projectId (Just "sessions") Nothing Nothing Nothing Nothing (Just "24H") selected Nothing (Just panel) (Just "1") (Just "1") - firstContent target = T.drop 1 . snd . T.breakOn ">" . snd . T.breakOn ("id=\"" <> target <> "\"") . htmlOf - withResource tr.trPool $ \conn -> - void $ PG.execute conn "INSERT INTO projects.replay_sessions (session_id, project_id, created_at, last_event_at, event_file_count, user_name) VALUES (?::uuid, ?, ?, ?, 1, 'Failure survivor')" (sid, projectId, frozenTime, addUTCTime 60 frozenTime) - -- A healthy cached counterpart survives the other query's acquisition failure. - forM_ ([("session_detail", Just sid, "rum-sessions-list", "rum-replay-workspace", [RUMData.SessionSearchQuery Nothing RUMData.AllSessionRows]), ("sessions", Nothing, "rum-replay-workspace", "rum-sessions-list", [RUMData.SessionDetailQuery sid])] :: [(Text, Maybe Text, Text, Text, [RUMData.RumQuery])]) $ \(warmPanel, warmSelection, failedTarget, healthyTarget, queries) -> do - purgeRumCaches tr - void $ sessions tr warmPanel warmSelection - (_, response@(RUM.RumGet (PageCtx _ body))) <- testServant scoped $ tfUnavailable $ RUM.rumGetH projectId (Just "sessions") Nothing Nothing Nothing Nothing (Just "24H") (Just sid) Nothing (Just "sessions") (Just "1") Nothing - page <- deferredBody body - page.degradedPanels `shouldBe` queries - T.isPrefixOf "
lookup "tab" params == Just "performance" && lookup "since" params == Just "7D" && all (isNothing . (`lookup` params)) ["from", "to"]) (linkParams ("/p/" <> projectId.toText <> "/rum") $ htmlOf emptyPage) `shouldBe` True - T.isInfixOf "role=\"alert\"" (htmlOf emptyPage) `shouldBe` False - apiKey <- createTestAPIKey tr projectId "rum-panel-recovery-key" - ingestMetric tr apiKey [] [] "browser.web_vital.fcp" 10 frozenTime - purgeRumCaches tr - (_, populated) <- healthy - htmlOf populated `shouldContainAll` ["10.0 ms"] - T.isInfixOf "role=\"alert\"" (htmlOf populated) `shouldBe` False - - it "panelLinks_carryKqlTheLogExplorerCanParse" \tr -> do - -- windowUrl URI-encodes every parameter it is given, so a caller that encodes first - -- ships a double-escaped query: a space arrives as %2520, the Explorer sees one - -- meaningless token, and the link silently returns nothing. - overview <- renderPage tr Nothing Nothing Nothing Nothing - -- Pinned as the property rather than one exact query string: a space encoded once as - -- %20, a quote once as %22, and no %25 anywhere on the page — %25 is the signature of a - -- second pass, since it is what a literal % becomes. - overview `shouldContainAll` ["/log_explorer?since=24H&query=", "%20and%20", "%22documentLoad%22"] - T.isInfixOf "%25" overview `shouldBe` False - - it "serviceFilter_scopesEveryPanelToOneBrowserService" \tr -> do - -- Several teams report into one project. Averaging their services together hides a - -- checkout regression behind a healthy marketing site, so the page has to be scopeable. - -- Panels are cached for 15s across requests, and earlier examples already populated the - -- unscoped key. Without this the assertions below read a snapshot taken before the span - -- this example ingests. - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-service-key" - -- Reuses the session that already has a recording, so the scoped page can be checked - -- for the replay badge as well as the rows. - browserSpan apiKey "30000000000000000000000000000003" "3000000000000001" [("url.path", "/admin/users")] "Pageview · /admin/users" (UUID.toText mergedReplayUuid) Nothing "admin-console" tr - - unscoped <- renderPage tr Nothing Nothing Nothing Nothing - unscoped `shouldContainAll` ["/admin/users", "/checkout"] - - scoped <- renderScoped tr Nothing Nothing Nothing Nothing (Just "admin-console") - scoped `shouldContainAll` ["admin-console", "/admin/users"] - -- The other team's pages are the whole point: if they survive the filter it does nothing. - T.isInfixOf "/checkout" scoped `shouldBe` False - -- Explorer receives the same global scope predicate as the SQL-backed panels. - -- The compact KQL spelling is intentional: it is parsed and URL-encoded only once. - scoped `shouldContainAll` ["service%3D%3D%22admin-console%22"] - T.isInfixOf "&service=admin-console" scoped `shouldBe` False - T.isInfixOf "?service=admin-console" scoped `shouldBe` False - -- A recording carries no service, so it can only be trusted where a span already places - -- the session in this service — attached to that row, never added as a row of its own. - scoped `shouldContainAll` ["Replay"] - T.isInfixOf "No recording" scoped `shouldBe` False - - -- A stale global selection still resolves, and an empty result must read as "this filter - -- matched nothing", never as "you never installed the SDK". - ghost <- renderScoped tr Nothing Nothing Nothing Nothing (Just "ghost-service") - ghost `shouldContainAll` ["No browser telemetry for ghost-service in this range", "global scope picker"] - T.isInfixOf "Install the browser SDK" ghost `shouldBe` False - - it "sharedRumLinks_keepTheirEnvironmentInsteadOfUsingTheRecipientDefault" \tr -> do - -- An alert recipient may have a different sticky environment selected. A RUM link is - -- investigation evidence, so its explicit environment has to win and remain present on - -- the deferred request and every self-link it renders. - purgeRumCaches tr - scopedHtml <- shellHtml tr $ RUM.rumGetScopedH testPid Nothing Nothing Nothing Nothing Nothing (Just "24H") Nothing (Just "admin-console") Nothing (Just "1") Nothing (Just "missing-environment") - scopedHtml `shouldContainAll` ["environment=missing-environment"] - T.isInfixOf "&service=admin-console" scopedHtml `shouldBe` False - T.isInfixOf "?service=admin-console" scopedHtml `shouldBe` False - - pulse <- rumBody tr $ RUM.rumGetScopedH testPid Nothing Nothing Nothing Nothing Nothing (Just "24H") Nothing (Just "admin-console") (Just "pulse") (Just "1") Nothing (Just "missing-environment") - -- The project has browser telemetry from the preceding examples. It must not leak into - -- a link scoped to another environment merely because this test session's default is - -- unscoped. - pulse.pulse `shouldBe` Nothing - - loaded <- rumBody tr $ RUM.rumGetScopedH testPid (Just "sessions") Nothing Nothing Nothing Nothing (Just "24H") (Just sessionId) Nothing (Just "sessions") (Just "1") Nothing (Just "missing-environment") - loaded.sessions `shouldBe` [] - loaded.selectedSessionData `shouldBe` Nothing - - it "environmentSessionCache_ignoresLegacyUnattributedRecordings" \tr -> do - purgeRumCaches tr - let sid = "00000000-0000-0000-0000-000000000046" - environment = Just "cache-environment" - load env refreshM = rumBody tr $ RUM.rumGetScopedH testPid (Just "sessions") (Just "Legacy replay") Nothing Nothing Nothing (Just "24H") (Just sid) Nothing (Just "sessions") (Just "1") refreshM env - legacyKey query = toXXHash $ show $ RUMData.RumCacheKey testPid query environment Nothing Nothing Nothing (Just "24H") - withResource tr.trPool $ \conn -> - void $ PG.execute conn "INSERT INTO projects.replay_sessions (session_id, project_id, created_at, last_event_at, event_file_count, user_name) VALUES (?::uuid, ?, ?, ?, 1, 'Legacy replay')" (sid, testPid, frozenTime, addUTCTime 60 frozenTime) - legacy <- load Nothing Nothing - map (.id) legacy.sessions `shouldBe` [sid] - runQueryEffect tr do - RUMData.rumPanelCacheSet (legacyKey $ RUMData.SessionSearchQuery (Just "Legacy replay") RUMData.AllSessionRows) 300 (RUMData.SessionsResult legacy.sessions) - RUMData.rumPanelCacheSet (legacyKey $ RUMData.SessionDetailQuery sid) 300 (RUMData.SessionDetailResult legacy.selectedSessionData) - Cache.purge tr.trATCtx.rumCache - scoped <- load environment Nothing - scoped.sessions `shouldBe` [] - scoped.selectedSessionData `shouldBe` Nothing - apiKey <- createTestAPIKey tr testPid "rum-environment-cache-key" - ingestSpanReq tr $ mkSpanRequest "83000000000000000000000000000008" "8300000000000001" Nothing "documentLoad" [] Nothing [mkAttr "session.id" sid] (mkResource apiKey [mkAttr "service.name" "legacy-browser", mkAttr "telemetry.sdk.language" "webjs", mkAttr "deployment.environment.name" "cache-environment"]) frozenTime - attributed <- load environment (Just "1") - map (.events) attributed.sessions `shouldBe` [1] - map (.hasReplay) attributed.sessions `shouldBe` [True] - (.hasReplay) <$> attributed.selectedSessionData `shouldBe` Just True - - it "browserSdkWithoutSdkLanguage_isStillSeenAndGloballyScopeable" \tr -> do - -- The OpenTelemetry browser SDKs leave telemetry.sdk.language unset, and RUM used to - -- filter on that alone. Every browser application in production was therefore invisible: - -- no page views, no sessions, and nothing for the global scope to narrow to. - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-otel-browser-key" - otelBrowserSpan apiKey "40000000000000000000000000000004" "4000000000000001" "session-otel" "checkout-web" tr - - page <- renderPage tr Nothing Nothing Nothing Nothing - page `shouldContainAll` ["https://shop.example/cart"] - - -- And the global scope can narrow to it. - scoped <- renderScoped tr Nothing Nothing Nothing Nothing (Just "checkout-web") - scoped `shouldContainAll` ["checkout-web", "https://shop.example/cart"] - T.isInfixOf "/admin/users" scoped `shouldBe` False - - it "sdkPageview_fullUrlWithQueryStillGroupsByPath" \tr -> do - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-pageview-query-key" - browserSpan apiKey "41000000000000000000000000000004" "4100000000000001" [("url.path", "/cart"), ("url.full", "/cart?coupon=x")] "Pageview · /cart" "session-page-query" Nothing "pageview-query-test" tr - loaded <- rumBody (withService (Just "pageview-query-test") tr) $ RUM.rumGetH testPid Nothing Nothing Nothing Nothing Nothing (Just "24H") Nothing Nothing (Just "pages") (Just "1") Nothing - map (.path) loaded.pages `shouldBe` ["/cart"] - - it "sessionLastPage_isTheLatestPageView_notALexicographicResourceUrl" \tr -> do - -- MAX(path) over every browser span used to pick the alphabetically largest URL: on - -- real traffic that is a third-party font fetched by the page, shown as the page. - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-lastpage-key" - browserSpanAt apiKey "50000000000000000000000000000005" "5000000000000001" [("url.path", "/alpha")] "Pageview · /alpha" "session-lastpage" Nothing "storefront" (addUTCTime (-120) frozenTime) tr - browserSpanAt apiKey "50000000000000000000000000000005" "5000000000000002" [("url.full", "https://zzz-fonts.example/css2")] "HTTP GET" "session-lastpage" Nothing "storefront" (addUTCTime (-60) frozenTime) tr - browserSpanAt apiKey "50000000000000000000000000000005" "5000000000000003" [("url.path", "/beta")] "Pageview · /beta" "session-lastpage" Nothing "storefront" (addUTCTime (-30) frozenTime) tr - row <- renderPanel tr (Just "sessions") (Just "session-lastpage") Nothing Nothing Nothing (Just "sessions") - row `shouldContainAll` ["/beta"] - T.isInfixOf "zzz-fonts.example" row `shouldBe` False - T.isInfixOf "/alpha" row `shouldBe` False - - it "selectedSession_withoutRecording_keepsIdentityAndTelemetryInWorkspace" \tr -> do - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-telemetry-workspace-key" - let sid = "session-without-recording" - browserSpanAt apiKey "84000000000000000000000000000008" "8400000000000001" [("url.path", "/profile"), ("user.full_name", "Telemetry visitor")] "documentLoad" sid Nothing "workspace-browser" (addUTCTime (-65) frozenTime) tr - browserSpan apiKey "84000000000000000000000000000008" "8400000000000002" [("exception.type", "TypeError"), ("exception.message", "Form failed")] "TypeError" sid (Just "8400000000000001") "workspace-browser" tr - html <- renderPanel tr (Just "sessions") (Just sid) Nothing (Just sid) Nothing (Just "sessions") - let workspace = fst $ T.breakOn "" $ snd $ T.breakOn "
" $ snd $ T.breakOn "2" workspace `shouldBe` True - headings `shouldContainAll` ["Last page"] - T.isInfixOf "Landing page" headings `shouldBe` False - - it "selectedSession_detailPanel_doesNotRunTheFullSessionSearch" \tr -> do - purgeRumCaches tr - projectId <- createTestProject tr "RUM independent session detail" - apiKey <- createTestAPIKey tr projectId "rum-independent-detail-key" - let sid = "session-independent-detail" - query = "unrelated-full-list-search" - searchKey = RUMData.RumCacheKey projectId (RUMData.SessionSearchQuery (Just query) RUMData.ErrorSessionRows) Nothing (Just "detail-browser") Nothing Nothing (Just "24H") - scoped = withService (Just "detail-browser") tr - load refresh = shellHtml scoped $ RUM.rumGetH projectId (Just "sessions") (Just query) (Just "errors") Nothing Nothing (Just "24H") (Just sid) Nothing (Just "session_detail") (Just "1") refresh - browserSpan apiKey "85000000000000000000000000000008" "8500000000000001" [("url.path", "/independent-detail"), ("user.full_name", "Independent visitor")] "documentLoad" sid Nothing "detail-browser" tr - html <- load Nothing - html `shouldContainAll` ["rum-replay-workspace", "Independent visitor", sid, "/independent-detail", "No recording for this session", "Inspect telemetry"] - T.isInfixOf "rum-sessions-list" html `shouldBe` False - (isNothing <$> Cache.lookup tr.trATCtx.rumCache searchKey) `shouldReturn` True - [PG.Only publications] <- withResource tr.trPool $ \conn -> PG.query_ conn "SELECT count(*)::bigint FROM rum_panel_cache" - publications `shouldBe` (1 :: Int64) - Cache.purge tr.trATCtx.rumCache - withResource tr.trPool $ \conn -> void $ PG.execute_ conn "UPDATE rum_panel_cache SET expires_at=now()-interval '1 minute'" - browserSpan apiKey "85000000000000000000000000000008" "8500000000000002" [("exception.type", "TypeError")] "TypeError" sid Nothing "detail-browser" tr - stale <- load Nothing - stale `shouldContainAll` ["Independent visitor", "panel=session_detail", "refresh=1", "hx-target=\"#rum-replay-workspace\"", "hx-select=\"#rum-replay-workspace\"", "hx-sync=\"#rum-replay-workspace:abort\""] - fresh <- load $ Just "1" - T.isInfixOf ">2" fresh `shouldBe` True - T.isInfixOf "refresh=1" fresh `shouldBe` False - - it "replayOnlySessions_sayWhatTheyAre_insteadOfUnknownPageAndZeroCounts" \tr -> do - -- A recording whose session id never appears on a span is a real session; stacking - -- "Unknown page" over "0 views · 0 events" reads as broken data, not as what it is. - purgeRumCaches tr - let replayOnlyUuid = [uuid|00000000-0000-0000-0000-000000000045|] - withResource tr.trPool \conn -> - void $ PG.execute conn "INSERT INTO projects.replay_sessions (session_id, project_id, created_at, last_event_at, event_file_count, user_name) VALUES (?, ?, ?, ?, 1, ?) ON CONFLICT (session_id) DO UPDATE SET created_at = EXCLUDED.created_at, last_event_at = EXCLUDED.last_event_at" (replayOnlyUuid, testPid, frozenTime, addUTCTime 45 frozenTime, "Replay only user" :: Text) - rows <- renderPanel tr (Just "sessions") (Just "Replay only user") Nothing Nothing Nothing (Just "sessions") - rows `shouldContainAll` ["Replay only user", "Recording only", "No telemetry"] - T.isInfixOf "Unknown page" rows `shouldBe` False - T.isInfixOf "0 views" rows `shouldBe` False - - it "browserErrors_groupBySignature_withOccurrenceAndSessionCounts" \tr -> do - -- Twenty copies of the loudest error used to fill the whole panel; issues with masked - -- identifiers keep every distinct failure visible with its blast radius. - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-errors-key" - browserSpan apiKey "60000000000000000000000000000006" "6000000000000001" [("exception.type", "TypeError"), ("exception.message", "Cannot read cart item 123")] "TypeError" "session-err-a" Nothing "storefront" tr - browserSpan apiKey "60000000000000000000000000000006" "6000000000000002" [("exception.type", "TypeError"), ("exception.message", "Cannot read cart item 456")] "TypeError" "session-err-b" Nothing "storefront" tr - panel <- renderPanel tr Nothing Nothing Nothing Nothing Nothing (Just "errors") - panel `shouldContainAll` ["TypeError", "×2", "2 sessions", "View session", "Telemetry"] - panel `shouldSatisfy` T.isInfixOf "tab=sessions" - -- Grouped, not listed: the message renders once for the pair. - T.count "Cannot read cart item" panel `shouldBe` 1 - - it "panelCache_writeFailure_preservesFreshTelemetry" \tr -> do - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-cache-write-key" - otelBrowserSpan apiKey "81000000000000000000000000000008" "8100000000000001" "session-cache-write" "cache-write-browser" tr - E.bracket_ - (execSql tr "ALTER TABLE rum_panel_cache ADD CONSTRAINT reject_panel_cache_write CHECK (false)") - (execSql tr "ALTER TABLE rum_panel_cache DROP CONSTRAINT reject_panel_cache_write") - do - loaded <- rumBody tr $ RUM.rumGetH testPid Nothing Nothing Nothing Nothing Nothing (Just "24H") Nothing Nothing (Just "pages") (Just "1") Nothing - loaded.degradedPanels `shouldBe` [] - map (.path) loaded.pages `shouldSatisfy` elem "https://shop.example/cart" - - it "panelCache_concurrentColdRequests_shareOneLookupAndPublication" \tr -> do - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-flight-key" - otelBrowserSpan apiKey "82000000000000000000000000000008" "8200000000000001" "session-flight" "flight-browser" tr - let fetch = renderPanel tr Nothing Nothing Nothing Nothing (Just "flight-browser") (Just "pages") - waitForReaders expected = do - [PG.Only readers] <- withResource tr.trPool $ \conn -> PG.query_ conn "SELECT count(*)::bigint FROM pg_stat_activity WHERE datname = current_database() AND wait_event_type = 'Lock' AND query LIKE '%rum_panel_cache%'" - unless (readers >= (expected :: Int64)) $ threadDelay 10000 >> waitForReaders expected - withCacheWriteCounter tr "rum_flight" \writes -> - withResource tr.trPool \conn -> - E.bracket_ - (void $ PG.execute_ conn "BEGIN; LOCK TABLE rum_panel_cache IN ACCESS EXCLUSIVE MODE") - (void $ PG.execute_ conn "ROLLBACK") - $ withAsync fetch \leader -> withAsync fetch \follower -> do - observed <- - E.finally - ((,) <$> timeout 5000000 (waitForReaders 1) <*> timeout 1000000 (waitForReaders 2)) - (void $ PG.execute_ conn "ROLLBACK") - responses <- traverse wait [leader, follower] - observed `shouldBe` (Just (), Nothing) - map (T.isInfixOf "/cart") responses `shouldBe` [True, True] - writes `shouldReturn` 1 - - it "emptySessionSearch_isBrieflyShared_andRefreshOrExpiryShowsNewTelemetry" \tr -> do - purgeRumCaches tr - let load query refreshM = do - page <- rumBody tr $ RUM.rumGetH testPid (Just "sessions") (Just query) Nothing Nothing Nothing (Just "24H") Nothing Nothing (Just "sessions") (Just "1") refreshM - map (.id) page.sessions <$ (page.degradedPanels `shouldBe` []) - refreshSearch = "session-negative-refresh" - expirySearch = "session-negative-expiry" - withCacheWriteCounter tr "rum_search" \writes -> do - load refreshSearch Nothing `shouldReturn` [] - -- A fresh replica must reuse the empty result without scanning telemetry. - observed <- withResource tr.trPool \conn -> - E.bracket_ - (void $ PG.execute_ conn "BEGIN; LOCK TABLE otel_logs_and_spans IN ACCESS EXCLUSIVE MODE") - (void $ PG.execute_ conn "ROLLBACK") - $ withAsync (do memory <- load refreshSearch Nothing; Cache.purge tr.trATCtx.rumCache; shared <- load refreshSearch Nothing; pure (memory, shared)) \request -> do - result <- E.finally (timeout 2000000 $ wait request) (void $ PG.execute_ conn "ROLLBACK") - void $ wait request - pure result - observed `shouldBe` Just ([], []) - writes `shouldReturn` 1 - -- The one entry sits under the versioned key, never under an older replica's spelling. - let searchKey = RUMData.rumCacheDbKey $ RUMData.RumCacheKey testPid (RUMData.SessionSearchQuery (Just refreshSearch) RUMData.AllSessionRows) Nothing Nothing Nothing Nothing (Just "24H") - [PG.Only versionedEntries] <- withResource tr.trPool $ \conn -> PG.query conn "SELECT count(*)::bigint FROM rum_panel_cache WHERE cache_key = ?" (PG.Only searchKey) - versionedEntries `shouldBe` (1 :: Int64) - [PG.Only shortExpiry] <- withResource tr.trPool $ \conn -> PG.query_ conn "SELECT expires_at > now() AND expires_at <= now() + interval '30 seconds' FROM rum_panel_cache" - shortExpiry `shouldBe` True - purgeRumCaches tr - load refreshSearch Nothing `shouldReturn` [] - apiKey <- createTestAPIKey tr testPid "rum-negative-search-key" - otelBrowserSpan apiKey "85000000000000000000000000000008" "8500000000000001" refreshSearch "negative-search-browser" tr - load refreshSearch Nothing `shouldReturn` [] - load refreshSearch (Just "1") `shouldReturn` [refreshSearch] - [PG.Only positiveExpiry] <- withResource tr.trPool $ \conn -> PG.query_ conn "SELECT expires_at > now() + interval '4 minutes' FROM rum_panel_cache" - positiveExpiry `shouldBe` True - load expirySearch Nothing `shouldReturn` [] - otelBrowserSpan apiKey "86000000000000000000000000000008" "8600000000000001" expirySearch "negative-search-browser" tr - Cache.purge tr.trATCtx.rumCache - execSql tr "UPDATE rum_panel_cache SET expires_at = now() - interval '1 minute'" - load expirySearch Nothing `shouldReturn` [expirySearch] - - it "emptySessionList_withoutSearch_doesNotHideNewSdkTelemetry" \tr -> do - purgeRumCaches tr - let service = "negative-cache-onboarding" - fetch = renderPanel tr (Just "sessions") Nothing Nothing Nothing (Just service) (Just "sessions") - forM_ ([Nothing, Just " \t "] :: [Maybe Text]) $ \query -> void $ renderPanel tr (Just "sessions") query Nothing Nothing (Just service) (Just "sessions") - [PG.Only entries] <- withResource tr.trPool $ \conn -> PG.query_ conn "SELECT count(*)::bigint FROM rum_panel_cache" - entries `shouldBe` (0 :: Int64) - apiKey <- createTestAPIKey tr testPid "rum-negative-onboarding-key" - otelBrowserSpan apiKey "87000000000000000000000000000008" "8700000000000001" "session-first-sdk-arrival" service tr - fetch >>= (`shouldContainAll` ["session-first-sdk-arrival", "/cart"]) - - it "vitalPanelCache_blankWindowFields_reuseThePrewarmedPopulation" \tr -> do - projectId <- createTestProject tr "RUM canonical cache window" - apiKey <- createTestAPIKey tr projectId "rum-canonical-window-key" - let ingest value seconds = ingestMetric tr apiKey [] [mkAttr "page.url" "/canonical-window"] "browser.web_vital.lcp" value (addUTCTime seconds frozenTime) - load from to since panel = do - page <- loadPerformance tr projectId from to since Nothing (Just panel) - [measured vital.measurement | vital <- page.vitals, vital.name == "lcp"] <$ (page.degradedPanels `shouldBe` []) - ingest 1000 (-10) - withCacheWriteCounter tr "rum_window" \publications -> do - warm <- load Nothing Nothing (Just "24H") "vital_trend" - ingest 9000 (-9) - hits <- forM [(Just "", Just "", Just "24H"), (Nothing, Nothing, Nothing)] \(from, to, since) -> do - Cache.purge tr.trATCtx.rumCache - load from to since "vitals" - warm : hits `shouldBe` replicate 3 [(Just 1000, 1)] - let fromQuery = Just $ toText $ iso8601Show $ addUTCTime (-60) frozenTime - toQuery = Just $ toText $ iso8601Show frozenTime - explicit <- load fromQuery toQuery Nothing "vital_trend" - ingest 10000 (-8) - Cache.purge tr.trATCtx.rumCache - blankSince <- load fromQuery toQuery (Just "") "vitals" - publications `shouldReturn` 2 - [explicit, blankSince] `shouldBe` replicate 2 [(Just 7000, 2)] - Cache.purge tr.trATCtx.rumCache - load (Just "") (Just "") (Just "") "vitals" `shouldReturn` [(Just 9500, 3)] - Cache.purge tr.trATCtx.rumCache - load Nothing Nothing Nothing "vitals" `shouldReturn` [(Just 1000, 1)] - publications `shouldReturn` 3 - - it "panelCache_isSharedAcrossReplicas_notPerProcessMemory" \tr -> do - -- A fresh replica has an empty memory cache; the shared rum_panel_cache table must - -- still answer, proven by deleting the underlying rows so a recompute could not. - -- The span is documentLoad-shaped: TimeFusion's text-index prefilter currently loses - -- LIKE-matched ("Pageview \183 ") names inside narrow windows, which is a store bug - -- this example must not depend on. - apiKey <- createTestAPIKey tr testPid "rum-l2-key" - ingestSpanReq tr $ mkSpanRequest "80000000000000000000000000000008" "8000000000000001" Nothing "documentLoad" [] Nothing [mkAttr "session.id" "session-l2", mkAttr "url.full" "https://l2.example/cached"] (mkResource apiKey [mkAttr "service.name" "storefront", mkAttr "user_agent.original" "Mozilla/5.0 L2"]) frozenTime - -- A window no earlier example used, so the shared table has no entry yet for this key. - let renderPages since refreshM = shellHtml tr $ RUM.rumGetH testPid Nothing Nothing Nothing Nothing Nothing (Just since) Nothing Nothing (Just "pages") (Just "1") refreshM - firstRender <- renderPages "6H" Nothing - -- Top pages renders path-only routes ('pageRoute'), so the host is stripped. - firstRender `shouldContainAll` ["/cached"] - -- Memory only — the shared table entry is exactly what a fresh replica would find. - Cache.purge tr.trATCtx.rumCache - withResource tr.trPool \conn -> - void $ PG.execute conn "DELETE FROM otel_logs_and_spans WHERE project_id = ? AND attributes___session___id = ?" (testPid, "session-l2" :: Text) - secondRender <- renderPages "6H" Nothing - secondRender `shouldContainAll` ["/cached"] - -- A fresh entry answers and asks for nothing more; only a stale one may schedule a refetch. - T.isInfixOf "refresh=1" secondRender `shouldBe` False - - -- Past expiry but inside the prune horizon: the panel must still paint its last-known - -- data rather than a cold scan, and carry the hidden refresh trigger that revalidates - -- it. Without the trigger the page would show aged data forever. - Cache.purge tr.trATCtx.rumCache - withResource tr.trPool \conn -> - void $ PG.execute_ conn "UPDATE rum_panel_cache SET expires_at = now() - interval '1 minute'" - staleRender <- renderPages "6H" Nothing - staleRender `shouldContainAll` ["/cached", "refresh=1"] - -- And the revalidation terminates: refresh bypasses the stale band, so its response - -- carries no trigger of its own. - Cache.purge tr.trATCtx.rumCache - refreshRender <- renderPages "6H" (Just "1") - T.isInfixOf "refresh=1" refreshRender `shouldBe` False - - it "wideColdSessionList_paintsTheNewestThreeHours_thenRevalidatesTheFullWindow" \tr -> do - purgeRumCaches tr - projectId <- createTestProject tr "RUM wide cold list" - apiKey <- createTestAPIKey tr projectId "rum-wide-cold-key" - let load since refreshM = do - (_, response@(RUM.RumGet (PageCtx _ body))) <- testServant tr $ RUM.rumGetH projectId (Just "sessions") Nothing Nothing Nothing Nothing (Just since) Nothing Nothing (Just "sessions") (Just "1") refreshM - (,htmlOf response) <$> deferredBody body - browserSpanAt apiKey "8a000000000000000000000000000008" "8a00000000000001" [("url.path", "/old")] "documentLoad" "session-wide-old" Nothing "wide-ui" (addUTCTime (-10 * 3600) frozenTime) tr - browserSpanAt apiKey "8b000000000000000000000000000008" "8b00000000000001" [("url.path", "/new")] "documentLoad" "session-wide-new" Nothing "wide-ui" (addUTCTime (-60) frozenTime) tr - (quick, quickHtml) <- load "24H" Nothing - map (.id) quick.sessions `shouldBe` ["session-wide-new"] - quick.servedStale `shouldBe` True - quickHtml `shouldContainAll` ["refresh=1", "Refreshing the full time range"] - -- The slice is never cached: a failed revalidation degrades instead of serving it as final. - failed <- rumBody tr{trATCtx = tr.trATCtx{env = tr.trATCtx.env{enableTimefusionReads = True}}} $ tfUnavailable $ RUM.rumGetH projectId (Just "sessions") Nothing Nothing Nothing Nothing (Just "24H") Nothing Nothing (Just "sessions") (Just "1") (Just "1") - failed.degradedPanels `shouldBe` [RUMData.SessionSearchQuery Nothing RUMData.AllSessionRows] - (full, fullHtml) <- load "24H" (Just "1") - (map (.id) full.sessions, full.servedStale) `shouldBe` (["session-wide-new", "session-wide-old"], False) - T.isInfixOf "Refreshing the full time range" fullHtml `shouldBe` False - -- The full result is what got cached, so the next cold-free load is complete at once. - fst <$> load "24H" Nothing >>= \cached -> (map (.id) cached.sessions, cached.servedStale) `shouldBe` (["session-wide-new", "session-wide-old"], False) - -- Last night's list still paints first the next morning, then revalidates. - Cache.purge tr.trATCtx.rumCache - withResource tr.trPool $ \conn -> void $ PG.execute_ conn "UPDATE rum_panel_cache SET expires_at = now() - interval '9 hours'" - fst <$> load "24H" Nothing >>= \overnight -> (map (.id) overnight.sessions, overnight.servedStale) `shouldBe` (["session-wide-new", "session-wide-old"], True) - -- Narrow windows scan themselves in one read. - purgeRumCaches tr - fst <$> load "6H" Nothing >>= \narrow -> (map (.id) narrow.sessions, narrow.servedStale) `shouldBe` (["session-wide-new"], False) - - it "staleSessionList_liveSelection_keepsRevalidationInsideTheSwappedChild" \tr -> do - purgeRumCaches tr - projectId <- createTestProject tr "RUM stale live selection" - apiKey <- createTestAPIKey tr projectId "rum-live-stale-key" - let ingest trId spId sid path at = ingestSpanReq tr $ mkSpanRequest trId spId Nothing "documentLoad" [] Nothing [mkAttr "session.id" sid, mkAttr "url.path" path, mkAttr "error.type" "LiveError"] (mkResource apiKey [mkAttr "service.name" "live-stale-browser", mkAttr "deployment.environment.name" "preview"]) at - scoped = withService (Just "live-stale-browser") tr - load refreshM = do - (_, response@(RUM.RumGet (PageCtx _ body))) <- testServant scoped $ RUM.rumGetScopedH projectId (Just "sessions") (Just "session-live") (Just "errors") Nothing Nothing (Just "6H") (Just "session-live-old") Nothing (Just "sessions") (Just "1") refreshM (Just "preview") - (,htmlOf response) <$> deferredBody body - -- HTMX's hx-select retains this section and discards its siblings. - selectedList = fst . T.breakOn "
" . snd . T.breakOn "id=\"rum-sessions-list\"" - ingest "88000000000000000000000000000008" "8800000000000001" "session-live-old" "/old" (addUTCTime (-1) frozenTime) - (initial, _) <- load Nothing - map (.id) initial.sessions `shouldBe` ["session-live-old"] - initial.servedStale `shouldBe` False - ingest "89000000000000000000000000000008" "8900000000000001" "session-live-new" "/new" frozenTime - Cache.purge tr.trATCtx.rumCache - withResource tr.trPool $ \conn -> void $ PG.execute_ conn "UPDATE rum_panel_cache SET expires_at = now() - interval '1 minute'" - (stale, staleHtml) <- load Nothing - stale.servedStale `shouldBe` True - map (.id) stale.sessions `shouldBe` ["session-live-old"] - selectedList staleHtml `shouldContainAll` ["refresh=1", "load delay:600ms", "hx-target=\"#rum-sessions-list\"", "hx-select=\"#rum-sessions-list\"", "hx-swap=\"outerMorph\"", "hx-sync=\"#rum-session-search-form:abort\"", "hx-include=\"#rum-session-search-form\"", "q=session-live", "filter=errors", "session=session-live-old", "environment=preview", "since=6H"] - T.isInfixOf "id=\"rum-replay-workspace\"" (selectedList staleHtml) `shouldBe` False - (fresh, freshHtml) <- load (Just "1") - fresh.servedStale `shouldBe` False - map (.id) fresh.sessions `shouldBe` ["session-live-new", "session-live-old"] - selectedList freshHtml `shouldContainAll` ["/new", "/old", "aria-current=\"true\""] - T.isInfixOf "refresh=1" (selectedList freshHtml) `shouldBe` False - (.id) <$> fresh.selectedSessionData `shouldBe` Just "session-live-old" - - it "audiencePanel_classifiesUserAgentsIntoBrowserOsAndDevice" \tr -> do - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-audience-key" - let chromeUa = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/151.0.0.0 Safari/537.36" - iphoneUa = "Mozilla/5.0 (iPhone; CPU iPhone OS 17_5 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Mobile/15E148 Safari/604.1" - browserSpan apiKey "70000000000000000000000000000007" "7000000000000001" [("url.path", "/a"), ("user_agent.original", chromeUa)] "Pageview · /a" "session-ua-1" Nothing "storefront" tr - browserSpan apiKey "70000000000000000000000000000007" "7000000000000002" [("url.path", "/a"), ("user_agent.original", chromeUa)] "Pageview · /a" "session-ua-2" Nothing "storefront" tr - browserSpan apiKey "70000000000000000000000000000007" "7000000000000003" [("url.path", "/b"), ("user_agent.original", iphoneUa)] "Pageview · /b" "session-ua-3" Nothing "storefront" tr - panel <- renderPanel tr Nothing Nothing Nothing Nothing Nothing (Just "audience") - panel `shouldContainAll` ["Audience", "Chrome", "Windows", "Safari", "iOS", "Mobile", "Desktop", "2 sessions"] - - it "sessionSearch_matchesBeforeLimits_andKeepsCrossStoreContext" \tr -> do - purgeRumCaches tr - apiKey <- createTestAPIKey tr testPid "rum-search-limit-key" - let oldId = "00000000-0000-0000-000b-000000000001" - oldTime = addUTCTime (-3600) frozenTime - recentId :: Int -> Text - recentId n = "00000000-0000-0000-000a-" <> T.justifyRight 12 '0' (show n) - browserSpanAt apiKey "e0000000000000000000000000000001" "e000000000000001" [("url.path", "/needle%_path")] "documentLoad" oldId Nothing "bulk-ui" oldTime tr - browserSpanAt apiKey "e0000000000000000000000000000001" "e000000000000002" [("url.path", "/checkout"), ("exception.type", "TypeError")] "documentLoad" oldId Nothing "bulk-ui" (addUTCTime 1 oldTime) tr - forM_ ([1 .. 201] :: [Int]) $ \n -> - browserSpan apiKey ("f" <> T.justifyRight 31 '0' (show n)) (T.justifyRight 16 '0' (show n)) [("url.path", "/recent")] "documentLoad" (recentId n) Nothing "bulk-ui" tr - withResource tr.trPool $ \conn -> do - void $ PG.execute conn "INSERT INTO projects.replay_sessions (session_id, project_id, created_at, last_event_at, event_file_count, user_name) VALUES (?::uuid, ?, ?, ?, 1, 'Archive analyst')" (oldId, testPid, oldTime, addUTCTime 60 oldTime) - void $ PG.execute conn "INSERT INTO projects.replay_sessions (session_id, project_id, created_at, last_event_at, event_file_count, user_name) SELECT ('00000000-0000-0000-000a-' || lpad(i::text, 12, '0'))::uuid, ?, ?, ?, 1, 'Recent shopper' FROM generate_series(1, 201) i" (testPid, frozenTime, addUTCTime 60 frozenTime) - -- Both a historical page and recording-only identity must find the old session, - -- retain all its events, and attach its recording, despite 201 newer rows. - forM_ ["needle%_path", "ARCHIVE ANALYST", oldId] $ \query -> do - rows <- renderPanel tr (Just "sessions") (Just query) Nothing Nothing (Just "bulk-ui") (Just "sessions") - rows `shouldContainAll` ["Archive analyst", "2 views", "2 events", "Replay", "/checkout"] - T.count "class=\"rum-session-link" rows `shouldBe` 1 - errors <- renderPanel tr (Just "sessions") Nothing (Just "errors") Nothing (Just "bulk-ui") (Just "sessions") - errors `shouldContainAll` ["Archive analyst", "1 error"] - -- Selecting an old deep link does not depend on it surviving the list's limit. - detail <- renderPanel tr (Just "sessions") Nothing Nothing (Just oldId) (Just "bulk-ui") (Just "sessions") - detail `shouldContainAll` ["Newest 200 sessions", "initialSession=\"" <> oldId <> "\""] - - it "pageLinks_findAbsoluteUrlEventsWithoutWideningTheirRouteOrScope" \tr -> do - apiKey <- createTestAPIKey tr testPid "rum-page-links-key" - let service = "route-links" - environment = "route-links-env" - ingest index attribute url svc env at = - ingestSpanReq tr $ mkSpanRequest ("d" <> T.justifyRight 31 '0' (show index)) ("d" <> T.justifyRight 15 '0' (show index)) Nothing "documentLoad" [] Nothing [mkAttr attribute url] (mkResource apiKey [mkAttr "service.name" svc, mkAttr "user_agent.original" "Mozilla/5.0", mkAttr "deployment.environment.name" env]) at - forM_ (zip ([1 ..] :: [Int]) ["/cart", "/cart?coupon=x", "/cart#section", "/cartoon", "/other/cart", "/search?q=/cart", "/Cart", "/cart/"]) \(index, path) -> - ingest index "url.full" ("https://shop.example" <> path) service environment frozenTime - ingest 9 "url.path" "/cart" service environment frozenTime - ingest 10 "url.full" "https://shop.example/cart" "other-service" environment frozenTime - ingest 11 "url.full" "https://shop.example/cart" service "other-environment" frozenTime - ingest 12 "url.full" "https://shop.example/cart" service environment $ addUTCTime (-120) frozenTime - ingestMetric tr apiKey [mkAttr "service.name" service, mkAttr "deployment.environment.name" environment] [mkAttr "page.url" "https://shop.example/cart"] "browser.web_vital.lcp" 1200 frozenTime - forM_ (zip ([13 ..] :: [Int]) ["https://shop.example", "https://shop.example/", "/?q=x", "/cart", "https://shop.example/a.b+(x)", "https://shop.example/aZbxxx", "https://shop.example/literal%2Fsegment"]) \(index, url) -> - ingest index "url.full" url service environment frozenTime - forM_ ["/", "/cart/", "/a.b+(x)", "/literal%2Fsegment"] \route -> - ingestMetric tr apiKey [mkAttr "service.name" service, mkAttr "deployment.environment.name" environment] [mkAttr "page.url" $ "https://shop.example" <> route] "browser.web_vital.lcp" 1200 frozenTime - let from = toText $ iso8601Show $ addUTCTime (-60) frozenTime - to = toText $ iso8601Show $ addUTCTime 60 frozenTime - scoped = withService (Just service) tr - forM_ ["pages", "vital_trend"] \panel -> do - html <- shellHtml scoped $ RUM.rumGetScopedH testPid (Just "performance") Nothing Nothing (Just from) (Just to) Nothing Nothing (Just service) (Just panel) (Just "1") Nothing (Just environment) - forM_ ([("/cart", 5), ("/", 3), ("/cart/", 1), ("/a.b+(x)", 1), ("/literal%2Fsegment", 1)] :: [(Text, Int)]) \(route, count) -> do - let label = if panel == "pages" then ">" <> route <> "" else "aria-label=\"https://shop.example" <> route <> "\"" - html `shouldContainAll` [label] - let href = T.takeWhile (/= '"') $ snd $ T.breakOnEnd "href=\"" $ fst $ T.breakOn label html - params = parseQueryText $ encodeUtf8 $ T.replace "&" "&" $ snd $ T.breakOn "?" href - lookup "from" params `shouldBe` Just (Just from) - lookup "to" params `shouldBe` Just (Just to) - query <- maybe (fail "RUM page link omitted its Explorer query") pure $ join $ lookup "query" params - (_, events) <- testServant tr $ Log.logExplorerDataH testPid def{Log.query = Just query, Log.from = Just from, Log.to = Just to} - events.error `shouldBe` Nothing - events.queryResultCount `shouldBe` if panel == "pages" then count else 1 - forM_ [events.nextUrl, events.resetLogsUrl, events.recentUrl] \url -> - join (lookup "query" $ parseQueryText $ encodeUtf8 $ snd $ T.breakOn "?" url) `shouldBe` Just query diff --git a/test/unit/Models/DashboardTemplatesSpec.hs b/test/unit/Models/DashboardTemplatesSpec.hs index 889aad855..ef560515a 100644 --- a/test/unit/Models/DashboardTemplatesSpec.hs +++ b/test/unit/Models/DashboardTemplatesSpec.hs @@ -6,7 +6,7 @@ import Data.Text qualified as T import Models.Projects.Dashboards qualified as Dashboards import Models.Projects.GitSync qualified as GitSync import Pkg.Components.Widget qualified as Widget -import Pkg.Parser (parseQueryToAST) +import Pkg.Parser (browserKql, parseQueryToAST) import Relude import System.Directory (listDirectory) import Test.Hspec (Spec, describe, expectationFailure, it, runIO, shouldBe, shouldSatisfy) @@ -18,7 +18,7 @@ templatesDir = "static/public/dashboards" -- | Replace {{placeholder}} spans with a literal so template queries parse standalone. stripPlaceholders :: Text -> Text -stripPlaceholders t = case T.splitOn "{{" $ T.replace "{{const-endpointFilter}}" "hashes[*] == \"x\"" t of +stripPlaceholders t = case T.splitOn "{{" $ T.replace "{{browser_kql}}" browserKql $ T.replace "{{const-endpointFilter}}" "hashes[*] == \"x\"" t of (prefix : rest) -> prefix <> mconcat [(\(_, after) -> "x" <> T.drop 2 after) (T.breakOn "}}" seg) | seg <- rest] [] -> t @@ -71,16 +71,13 @@ spec = describe "dashboard templates" do let metricQueries = [q | w <- Dashboards.allWidgets d, Just q <- [w.query], "metrics" `T.isPrefixOf` T.strip q] metricQueries `shouldSatisfy` (not . null) - it "RUM scopes Web Vitals by application and counts each session once" do + it "RUM widgets all carry the environment and application scope" do case find (\d -> d.file == Just "rum.yaml") templates of Nothing -> expectationFailure "missing template: rum.yaml" Just d -> do - let widgets = Dashboards.allWidgets d - metricSql = [sql | w <- widgets, Just sql <- [w.sql], "FROM otel_metrics" `T.isInfixOf` sql] - sessionQueries = [q | w <- widgets, w.title == Just "Sessions", Just q <- [w.query]] - metricSql `shouldSatisfy` (not . null) - forM_ metricSql (`shouldSatisfy` T.isInfixOf "resource___service___name = '{{var-app}}'") - sessionQueries `shouldSatisfy` (not . any (T.isInfixOf "dcount")) + let sqlWidgets = [w | w <- Dashboards.allWidgets d, isJust w.sql] + sqlWidgets `shouldSatisfy` (not . null) + forM_ sqlWidgets \w -> (w.title, any (T.isInfixOf "{{query_ast_filters}}") w.sql, any (T.isInfixOf "{{var-app}}") w.query) `shouldBe` (w.title, True, True) it "endpoint latency summaries average percentile buckets and declare milliseconds" $ withEndpointTemplate \d -> do let flatten w = w : maybe [] (concatMap flatten) w.children diff --git a/web-components/src/widgets.ts b/web-components/src/widgets.ts index 75b2629a4..17e11e835 100644 --- a/web-components/src/widgets.ts +++ b/web-components/src/widgets.ts @@ -531,8 +531,7 @@ export const chartDataUrl = ({ return `/chart_data?${params}`; }; -// A widget whose data the server computed and embedded has no project to query — RUM's -// Web Vitals trends are one (Pages.RealUserMonitoring.vitalTrendPanel_). Fetching for one +// A widget whose data the server computed and embedded has no project to query. Fetching for one // asks /chart_data for a default `count(*)` against `pid=null`, which answers 401, and a // 401 on a chart fetch reloads the page: the 15s live tick was rebuilding the entire page // — skeletons and all — instead of updating data in place. From 4b09e5fc5d272d0f1af7fc74fc7b4a01e48f2394 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Sun, 25 Oct 2026 14:36:28 +0200 Subject: [PATCH 003/203] Treat /rum/sessions/ like /rum/sessions (#710) A trailing slash captures an empty last path segment, which fell through to the 404 arm. Empty segments are now ignored. --- src/Pages/Dashboards.hs | 2 +- test/integration/Pages/DashboardWidgetsSpec.hs | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Pages/Dashboards.hs b/src/Pages/Dashboards.hs index ce6f4084c..71d24ae37 100644 --- a/src/Pages/Dashboards.hs +++ b/src/Pages/Dashboards.hs @@ -2269,7 +2269,7 @@ entrypointRedirectGetH baseTemplate title tags pid qparams = do -- Explorer sessions view over browser telemetry, keeping the window. Shared links from the old -- page (@/rum?tab=sessions&session=…@) land on the same view, narrowed to that session. rumRedirectH :: Projects.ProjectId -> [Text] -> [(Text, Maybe Text)] -> ATAuthCtx (Headers '[Header "Location" Text] NoContent) -rumRedirectH pid segments params = case (segments, param "tab") of +rumRedirectH pid segments params = case (filter (not . T.null) segments, param "tab") of (["sessions"], _) -> sessions ([], Just "sessions") -> sessions ([], _) -> dashboard diff --git a/test/integration/Pages/DashboardWidgetsSpec.hs b/test/integration/Pages/DashboardWidgetsSpec.hs index 40a2f4029..475e093e5 100644 --- a/test/integration/Pages/DashboardWidgetsSpec.hs +++ b/test/integration/Pages/DashboardWidgetsSpec.hs @@ -1502,6 +1502,8 @@ spec = sequential $ aroundAll withTestResources do dashboard `shouldSatisfy` T.isInfixOf "since=7D" location ["dashboard"] window `shouldReturn` dashboard sessions <- location ["sessions"] window + -- A trailing slash captures an empty last segment; it must not turn into a 404. + location ["sessions", ""] window `shouldReturn` sessions linkParams ("/p/" <> testPid.toText <> "/log_explorer") ("href=\"" <> sessions <> "\"") `shouldBe` [[("since", "7D"), ("viz_type", "sessions"), ("query", browserKql)]] -- A link shared from the old page lands on that session, not the dashboard. legacy <- location [] [("tab", Just "sessions"), ("session", Just "abc")] From 8890344e9603c7fedff36e0182ff8d7b9b04124c Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Sun, 25 Oct 2026 14:40:21 +0200 Subject: [PATCH 004/203] Share local CI caches across checkouts (#711) * Share local CI dependency caches across checkouts Each checkout path got its own cabal/npm/playwright volume set, so every worktree and signoff clone leaked ~8GB of content-keyed caches; 35 sets had piled up. Share those. dist-newstyle stays per checkout: sharing it was tried and weeder then reported live functions as dead, because unchanged modules lost their .hie files after another branch built into the volume. * Note that local sign-off must stay fast * Share dist-newstyle across checkouts; weeder repairs missing .hie files After another branch built into a shared dist, GHC can leave a live module compiled without its .hie, so weeder misses every reference it makes and reports live functions dead. The weeder check now recompiles any tracked module missing one (dropping cabal's build stamp, since a touch leaves the source hash unchanged) instead of every checkout paying a cold build. --- AGENTS.md | 9 +++++++++ ci/compose.yml | 12 ++++++++---- docs/local-ci.md | 10 +++++----- scripts/ci/ci.sh | 30 +++++++++++++++++++++++------- 4 files changed, 45 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6954406ef..25c3bcbd2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -219,6 +219,15 @@ each burning ~85 minutes of wall clock before reporting an e2e expectation that local run would have shown in minutes. Never treat "push it and see what CI says" as a way to test a change. +**Sign-off must stay fast, every time — treat a slower sign-off as a regression.** +The cabal store, `dist-newstyle`, npm and Playwright caches are docker volumes shared +by every checkout (`ci/compose.yml`), so a new worktree or sign-off clone builds +incrementally. Never key a cache per checkout: that leaked ~400GB of volumes and made +every clone a cold build. If one check misbehaves on shared state, fix that check — +never slow every check down for it. The precedent: after another branch built into +the shared `dist`, GHC left some live modules without `.hie` files and weeder reported +their callees dead, so the weeder check recompiles any tracked module missing one. + **`make ship` is the whole deploy from here** — checks, image, push, CapRover — so the slow half stops being a queue you wait on: diff --git a/ci/compose.yml b/ci/compose.yml index 571f98715..077146130 100644 --- a/ci/compose.yml +++ b/ci/compose.yml @@ -128,10 +128,14 @@ services: # would start Postgres and MinIO even for frontend-only signoff. volumes: - cabal: - npm: - dist: + # Shared by every checkout, so a new worktree or signoff clone starts warm + # instead of adding another ~12GB set; ci.sh creates them. Every checkout mounts + # at /build, so dist is incremental across branches; the weeder check repairs + # the .hie files another branch's build leaves behind. + cabal: {external: true, name: monoscope-ci_cabal} + npm: {external: true, name: monoscope-ci_npm} + dist: {external: true, name: monoscope-ci_dist} + playwright: {external: true, name: monoscope-ci_playwright} node: wc-node: e2e-node: - playwright: diff --git a/docs/local-ci.md b/docs/local-ci.md index 842d2650d..a574ed34b 100644 --- a/docs/local-ci.md +++ b/docs/local-ci.md @@ -100,11 +100,11 @@ Two deliberate differences from your normal `make test`: - **Build directories are container-private.** `dist-newstyle`, all three `node_modules` directories, npm's download cache, and Playwright's browser download are named volumes. Your host's macOS/arm64 artifacts would corrupt the Linux build. - Volumes are separate for each worktree and persist, so the second `make ci` there is - fast — but the **first one is a cold build** and takes as long as a cold CI - run. Start it and go do something else; every run after that is incremental. - `make ci-down` keeps them; `make ci-clean` deletes them and buys you the cold - build back. + The cabal store, `dist-newstyle`, and the npm and Playwright caches are shared + by every checkout (only `node_modules` stays per worktree) and persist, so only + the first `make ci` on a machine is a cold build; a new worktree or sign-off + clone builds incrementally from whatever branch built last. `make ci-down` keeps + them; `make ci-clean` deletes them for every checkout. Each `integration-tests` invocation recreates only the ephemeral Postgres, MinIO, and TimeFusion service containers, so deterministic fixture IDs and telemetry rows never leak into the next run. The build-cache volumes remain. diff --git a/scripts/ci/ci.sh b/scripts/ci/ci.sh index 63c672bcf..7ec498228 100755 --- a/scripts/ci/ci.sh +++ b/scripts/ci/ci.sh @@ -359,14 +359,26 @@ run_body() { # unit-tests) if [ -n "${CI_UNIT_BIN:-}" ]; then "$CI_UNIT_BIN"; else cabal test unit-tests -j $CABAL_FLAGS "$CABAL_OPTS" --test-show-details=direct; fi ;; cli-tests) if [ -n "${CI_CLI_BIN:-}" ]; then "$CI_CLI_BIN"; else cabal test monoscope-cli:cli-tests -j $CABAL_FLAGS "$CABAL_OPTS" --test-show-details=direct; fi ;; weeder) + # dist-newstyle is shared with other branches' checkouts, so it can hold .hie files for + # modules this tree lacks (reported dead) and lack them for modules it has (GHC can + # recompile a module without rewriting its .hie, hiding every reference it makes). + srcs=$(git ls-files '*.hs' | sed -E 'h; s#^(src|shared/src|cli/exe|cli/test|cli|test/[a-z]+|app)/##; s#\.hs$##; G; s#\n# #') + src_of() { printf '%s\n' "$srcs" | awk -v m="$1" '$1 == m { print $2; exit }'; } + cabal build integration-tests unit-tests -j $CABAL_FLAGS "$CABAL_OPTS" + find dist-newstyle -name '*.o' | while read -r o; do + b=${o%%-tmp/*}-tmp; [ "$b" = "$o-tmp" ] && b=${o%/build/*}/build + m=${o#"$b"/}; m=${m%.o} + # cabal skips GHC while its sources hash the same, so drop its build stamp too. + if [ -d "$b/extra-compilation-artifacts/hie" ] && [ ! -e "$b/extra-compilation-artifacts/hie/$m.hie" ] && [ -n "$(src_of "$m")" ]; then + rm -f "${b%/build*}/cache/build" "$b/$m".{o,hi,dyn_o,dyn_hi} + fi + done cabal build integration-tests unit-tests -j $CABAL_FLAGS "$CABAL_OPTS" command -v weeder >/dev/null 2>&1 || cabal install weeder --install-method=copy --installdir=/usr/local/bin --overwrite-policy=always - # A restored dist-newstyle keeps .hie files of deleted modules, which weeder reports as dead. - mods=$(git ls-files '*.hs' | sed -E 's#^(src|shared/src|cli/exe|cli/test|cli|test/[a-z]+|app)/##; s#\.hs$##') find dist-newstyle -name '*.hie' | while read -r f; do m=${f%.hie}; m=${m##*/build/}; m=${m##*/hie/}; m=${m##*-tmp/} case $m in Proto/* | Paths_* | */autogen/*) continue ;; esac - printf '%s\n' "$mods" | grep -qxF "$m" || rm -f "$f" + [ -n "$(src_of "$m")" ] || rm -f "$f" done weeder --config weeder.toml --hie-directory dist-newstyle ;; @@ -602,14 +614,18 @@ cmd_gc() { COMPOSE_FILE=ci/compose.yml COMPOSE_PROJECT="monoscope-ci-$(printf '%s' "$ROOT" | sha256 | cut -c1-12)" -compose() { docker compose -f "$COMPOSE_FILE" --project-name "$COMPOSE_PROJECT" "$@"; } +SHARED_VOLUMES=(monoscope-ci_cabal monoscope-ci_npm monoscope-ci_dist monoscope-ci_playwright) +compose() { + local v; for v in "${SHARED_VOLUMES[@]}"; do docker volume create "$v" >/dev/null; done + docker compose -f "$COMPOSE_FILE" --project-name "$COMPOSE_PROJECT" "$@" +} # Wait for a host check started in the background and replay its output. collect_host() { [ -n "$1" ] || return 0; local r=0; wait "$1" || r=$?; cat "$2"; rm -f "$2"; return "$r"; } cmd_local() { - # Serialize local runs to avoid oversubscribing the host. Each worktree has its - # own volumes so a checkout on another branch cannot replace this one's HIE files. + # Serialize local runs: they oversubscribe the host, and every checkout shares the + # cabal store and dist (`shell` takes no lock, so a hand build there can race a run). if [ "${CI_LOCAL_LOCKED:-}" != true ]; then python3 -c ' import fcntl, os, sys @@ -740,7 +756,7 @@ cmd_shell() { # Volumes survive `down` on purpose: they hold the cabal store and dist-newstyle, # and losing them means the next `make ci` is a cold build. `clean` is the nuke. cmd_down() { compose down --remove-orphans; } -cmd_clean() { compose down -v --remove-orphans; } +cmd_clean() { compose down -v --remove-orphans && docker volume rm "${SHARED_VOLUMES[@]}"; } # ---------------------------------------------------------------- deploy image From e0d24e9e3cc4fb7dcd66bb378d02ab97619129d7 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Sun, 25 Oct 2026 15:54:42 +0200 Subject: [PATCH 005/203] Release sessions display, dependency updates, and Stripe reactivation (#713) Combine the functional changes from #612, #556, #712, #557, #559 and #526. Keep the sessions PR's unrelated Slack plan out of this train. Require complete invoice reads, confirmed payment and retryable settlement for Stripe reactivation. Cover the failure paths through signed webhook and checkout handlers. --- e2e/tests/project-notices.spec.ts | 2 +- package-lock.json | 6 +- src/BackgroundJobs.hs | 55 +++-- src/Pages/BodyWrapper.hs | 5 +- src/Pages/Components.hs | 35 ++-- src/Pages/LogExplorer/Log.hs | 16 +- src/Pages/Onboarding.hs | 14 +- src/Pages/Projects.hs | 16 +- src/Pages/Settings.hs | 194 +++++++++++------- src/Pkg/EmailTemplates.hs | 16 ++ test/integration/Pages/BusinessFlowsSpec.hs | 149 ++++++++++++-- ...=12_subscription=sub_test123_get_with.json | 4 +- web-components/package-lock.json | 166 ++++++++------- web-components/package.json | 12 +- web-components/src/log-list.ts | 2 +- 15 files changed, 450 insertions(+), 242 deletions(-) diff --git a/e2e/tests/project-notices.spec.ts b/e2e/tests/project-notices.spec.ts index 022be26a3..8ed63a6c8 100644 --- a/e2e/tests/project-notices.spec.ts +++ b/e2e/tests/project-notices.spec.ts @@ -19,7 +19,7 @@ test("customer notices keep fullscreen panels and sidebar flyouts aligned", asyn await page.goto(`/p/${pid}/log_explorer?fullscreen=trace&showTrace=test-trace`); const admin = page.locator("#super-admin-banner"), billing = page.locator("#billing-downgrade-banner"); await expect(admin).toContainText("You are a super admin in a customer's project"); - await expect(billing.getByRole("link", { name: "Update payment method" })).toBeVisible(); + await expect(billing.getByRole("link", { name: "Reactivate subscription" })).toBeVisible(); await expect(page.locator("#apiLogsPage")).toHaveAttribute("data-fullscreen", "trace"); const noticeBottom = (await billing.boundingBox())!; const panel = await page.locator("#trace_expanded_view").boundingBox(); diff --git a/package-lock.json b/package-lock.json index 557156597..2c2f54945 100644 --- a/package-lock.json +++ b/package-lock.json @@ -5891,9 +5891,9 @@ ] }, "node_modules/baseline-browser-mapping": { - "version": "2.10.25", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.25.tgz", - "integrity": "sha512-QO/VHsXCQdnzADMfmkeOPvHdIAkoB7i0/rGjINPJEetLx75hNttVWGQ/jycHUDP9zZ9rupbm60WRxcwViB0MiA==", + "version": "2.11.21", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.21.tgz", + "integrity": "sha512-uh8vpY/1/YyFkunIDFH/12p7/7VdPKA1hejMVEbdkEaWnUz0Hesvx5EbiU6XxjyHZIOju+ZMbQJkRh+es3/spQ==", "dev": true, "license": "Apache-2.0", "bin": { diff --git a/src/BackgroundJobs.hs b/src/BackgroundJobs.hs index 52d2734da..79efbc7c7 100644 --- a/src/BackgroundJobs.hs +++ b/src/BackgroundJobs.hs @@ -1,6 +1,6 @@ {-# LANGUAGE StrictData #-} -module BackgroundJobs (jobsWorkerInit, jobsRunner, ensureDailyJobScheduled, processBackgroundJob, enqueueAIRoutine, enqueueJobs, runAIRoutineWith, BgJobs (..), jobTypeName, runHourlyJob, runNotificationDigest, runNotificationSweep, runSlackIncidentDeliveries, expireLapsedAcks, generateOtelFacetsBatch, throwParsePayload, checkTriggeredQueryMonitors, evaluateQueryMonitorValue, monitorStatus, detectSpikeOrDrop, aboveVolumeFloor, isAlertableLogLevel, isIssueWorthy, spikeZScoreThreshold, spikeMinAbsoluteDelta, spikeMinBaselineRate, dropMinBaselineRate, calculateLogPatternBaselines, detectLogPatternSpikes, processNewLogPatterns, pruneStaleLogPatterns, calculateErrorBaselines, detectErrorSpikes, detectPerformanceIssues, detectFrontendIssues, detectFeedback, applyUptimeResult, evaluateCronMonitor, notifyErrorSubscriptions, sweepErrorSubscriptions, consumeNotificationToken, endpointTemplateDiscovery, notifyDiscoveredEndpoints, sendNewEndpointAlerts, runHostRetentionSweep, autoAckProvenEndpoints, endpointAutoAckLockName, provenEndpointMinRequests, provenEndpointMinHours, collapseEndpointAlertFamilies, newEndpointAlertsPerHour, endpointMergeCleanup, reviewResidualEndpointGroups, residualGroups, mergeEvidenceMet, routeWordFraction, looksLikeRouteWord, recheckQuarantinedMerges, sharedIdPrefix, promoteConfirmedIdRules, shapeAgreementOk, autoApplyTrusted, proposePathTemplates, runShape, patternEmbeddingAndMerge, reviewErrorGroups, errorGroupEvidenceMet, processProjectErrors, maskCollapsesDistinctShapes, promoteErrorMask, processEagerBatch, flushDrainTask, runErrorDecayFiber, runDrainFlusher, runDrainAgeFlushTimer, runSchemaFlusherFiber, runSessionBackfillTimer, backfillSessionAttributes, getStripeSubDetails, getStripeInvoices, scheduleTrialReminders, StripeSubDetails (..), StripeInvoice (..), errorTrendChartUrl) where +module BackgroundJobs (jobsWorkerInit, jobsRunner, ensureDailyJobScheduled, processBackgroundJob, enqueueAIRoutine, enqueueJobs, runAIRoutineWith, BgJobs (..), jobTypeName, runHourlyJob, runNotificationDigest, runNotificationSweep, runSlackIncidentDeliveries, expireLapsedAcks, generateOtelFacetsBatch, throwParsePayload, checkTriggeredQueryMonitors, evaluateQueryMonitorValue, monitorStatus, detectSpikeOrDrop, aboveVolumeFloor, isAlertableLogLevel, isIssueWorthy, spikeZScoreThreshold, spikeMinAbsoluteDelta, spikeMinBaselineRate, dropMinBaselineRate, calculateLogPatternBaselines, detectLogPatternSpikes, processNewLogPatterns, pruneStaleLogPatterns, calculateErrorBaselines, detectErrorSpikes, detectPerformanceIssues, detectFrontendIssues, detectFeedback, applyUptimeResult, evaluateCronMonitor, notifyErrorSubscriptions, sweepErrorSubscriptions, consumeNotificationToken, endpointTemplateDiscovery, notifyDiscoveredEndpoints, sendNewEndpointAlerts, runHostRetentionSweep, autoAckProvenEndpoints, endpointAutoAckLockName, provenEndpointMinRequests, provenEndpointMinHours, collapseEndpointAlertFamilies, newEndpointAlertsPerHour, endpointMergeCleanup, reviewResidualEndpointGroups, residualGroups, mergeEvidenceMet, routeWordFraction, looksLikeRouteWord, recheckQuarantinedMerges, sharedIdPrefix, promoteConfirmedIdRules, shapeAgreementOk, autoApplyTrusted, proposePathTemplates, runShape, patternEmbeddingAndMerge, reviewErrorGroups, errorGroupEvidenceMet, processProjectErrors, maskCollapsesDistinctShapes, promoteErrorMask, processEagerBatch, flushDrainTask, runErrorDecayFiber, runDrainFlusher, runDrainAgeFlushTimer, runSchemaFlusherFiber, runSessionBackfillTimer, backfillSessionAttributes, getStripeSubDetails, getStripeInvoices, scheduleTrialReminders, StripeSubDetails (..), StripeInvoice (..), StripeInvoiceScope (..), errorTrendChartUrl) where import BackgroundJobs.Types (BgJobs (..)) import BackgroundJobs.Types qualified as Jobs @@ -12,6 +12,7 @@ import Control.Monad.Extra (whileM) import Data.Aeson qualified as AE import Data.Aeson.Lens qualified as AL import Data.Aeson.QQ (aesonQQ) +import Data.Aeson.Types (parseEither) import Data.CaseInsensitive qualified as CI import Data.Char (isAsciiLower, isAsciiUpper, isDigit) import Data.Default (def) @@ -42,6 +43,8 @@ import Data.Vector qualified as V import Data.Vector.Algorithms.Intro qualified as VA import Database.PostgreSQL.Simple qualified as SimplePG import Database.PostgreSQL.Simple.SqlQQ (sql) +import Deriving.Aeson qualified as DAE +import Deriving.Aeson.Stock qualified as DAE import Effectful (Eff, IOE, (:>)) import Effectful.Concurrent.Async (concurrently, concurrently_, forConcurrently, forConcurrently_) import Effectful.Ki qualified as Ki @@ -2949,16 +2952,24 @@ data StripeSubDetails = StripeSubDetails -- | One Stripe invoice. `periodStart`/`periodEnd` (POSIX seconds) are the usage -- window the invoice bills for — contiguous with the subscription item's period, -- which is why they, and not our own month arithmetic, define a past cycle. --- `total` is in cents; `hostedUrl` is absent on drafts. +-- `total` and `amountRemaining` (still owed) are in cents; `hostedUrl` is absent on drafts. data StripeInvoice = StripeInvoice - { periodStart :: Int + { invoiceId :: Text + , periodStart :: Int , periodEnd :: Int , total :: Int + , amountRemaining :: Int + , currency :: Text , status :: Text , hostedUrl :: Maybe Text , number :: Maybe Text } - deriving stock (Eq, Show) + deriving stock (Eq, Generic, Show) + deriving (AE.FromJSON) via DAE.CustomJSON '[DAE.FieldLabelModifier '[DAE.Rename "invoiceId" "id", DAE.Rename "hostedUrl" "hosted_invoice_url", DAE.CamelToSnake]] StripeInvoice + + +data StripeInvoiceScope = RecentInvoices | OpenInvoices + deriving stock (Eq) -- | Returns Nothing on HTTP/network/TLS error or JSON decode miss. Callers @@ -2982,24 +2993,24 @@ getStripeSubDetails apiKey subId = do pure StripeSubDetails{..} --- | A subscription's invoices, newest first. Empty on any HTTP/decode failure — --- this only enriches the billing page, so a Stripe outage must degrade it, not fail it. -getStripeInvoices :: (IOE :> es, W.HTTP :> es) => Text -> Text -> Eff es [StripeInvoice] -getStripeInvoices apiKey subId = do - respE <- tryAny $ W.getWith (bearerAuth apiKey) ("https://api.stripe.com/v1/invoices?limit=12&subscription=" <> toString subId) - pure $ fromMaybe [] do - resp <- rightToMaybe respE - v <- AE.decode @AE.Value (resp ^. W.responseBody) - pure - [ StripeInvoice{periodStart, periodEnd, total, status, hostedUrl, number} - | inv <- v ^.. AL.key "data" . AL.values - , let total = maybe 0 fromInteger $ inv ^? AL.key "total" . AL._Integer - status = fromMaybe "" $ inv ^? AL.key "status" . AL._String - hostedUrl = inv ^? AL.key "hosted_invoice_url" . AL._String - number = inv ^? AL.key "number" . AL._String - , Just periodStart <- [fromInteger <$> inv ^? AL.key "period_start" . AL._Integer] - , Just periodEnd <- [fromInteger <$> inv ^? AL.key "period_end" . AL._Integer] - ] +-- | The billing page needs recent invoices; reactivation must read every open invoice. +-- A failed or malformed lookup must not be mistaken for a zero outstanding balance. +getStripeInvoices :: (IOE :> es, W.HTTP :> es) => Text -> StripeInvoiceScope -> Text -> Eff es (Either Text [StripeInvoice]) +getStripeInvoices apiKey scope subId = fetch Nothing + where + fetch cursor = do + response <- tryAny $ W.getWith (bearerAuth apiKey) ("https://api.stripe.com/v1/invoices?limit=12&subscription=" <> toString subId <> bool "" "&status=open" (scope == OpenInvoices) <> foldMap (("&starting_after=" <>) . toString) cursor) + let decoded = do + resp <- first (const "Stripe invoice request failed") response + value <- first toText $ AE.eitherDecode @AE.Value (resp ^. W.responseBody) + first toText $ parseEither (AE.withObject "Stripe invoices" \o -> (,) <$> o AE..: "data" <*> (o AE..:? "has_more" AE..!= False)) value + case decoded of + Left err -> pure $ Left err + Right (invoices, hasMore) + | scope == OpenInvoices && hasMore -> case listToMaybe (reverse invoices) of + Just invoice -> fmap (invoices <>) <$> fetch (Just invoice.invoiceId) + Nothing -> pure $ Left "Stripe returned an empty invoice page with more results" + | otherwise -> pure $ Right invoices -- | Enqueues TrialEndingReminder jobs at T-7d and T-3d. Enqueue failures are diff --git a/src/Pages/BodyWrapper.hs b/src/Pages/BodyWrapper.hs index 818cfcba7..95638a5dc 100644 --- a/src/Pages/BodyWrapper.hs +++ b/src/Pages/BodyWrapper.hs @@ -481,7 +481,10 @@ bodyWrapper bcfg child = do $ div_ [id_ "billing-downgrade-banner", role_ "alert", class_ "flex shrink-0 flex-wrap items-center justify-center gap-x-3 gap-y-1 border-b border-strokeWarning-strong bg-fillWarning-weak px-4 py-2 text-xs text-textStrong"] do span_ "Your paid subscription is no longer active. This project has been downgraded to Free." a_ [href_ $ "/p/" <> project.id.toText <> "/manage_billing", class_ "font-medium text-textBrand underline underline-offset-2"] "Review billing or change plan" - a_ [href_ $ "/p/" <> project.id.toText <> "/manage_billing", hxGet_ $ "/p/" <> project.id.toText <> "/manage_subscription", term "hx-preload" "false", class_ "font-medium text-textBrand underline underline-offset-2"] "Update payment method" + -- A cancelled Stripe sub can't be revived from the portal; checkout starts a new one and collects what's owed. + let stripe = Projects.projectProvider project == Projects.StripeProvider + a_ ([href_ $ "/p/" <> project.id.toText <> "/manage_billing", class_ "font-medium text-textBrand underline underline-offset-2"] <> bool [hxGet_ $ "/p/" <> project.id.toText <> "/manage_subscription", term "hx-preload" "false"] [] stripe) + $ bool "Update payment method" "Reactivate subscription" stripe -- Keep fixed fullscreen panels and drawers below the project notices. section_ [class_ "relative flex flex-row flex-1 min-h-0 overflow-hidden", style_ "contain: layout"] do when (isJust bcfg.currProject) diff --git a/src/Pages/Components.hs b/src/Pages/Components.hs index 36225b6a8..a488f8782 100644 --- a/src/Pages/Components.hs +++ b/src/Pages/Components.hs @@ -1,4 +1,4 @@ -module Pages.Components (drawer_, PanelStyle (..), PanelCfg (..), panel_, entityHeader_, detailSection_, pivotLinks_, disclosure_, settingsSection_, settingsH2_, sectionLabel_, fieldLabel_, headerRow_, navBar, brandLogo_, resizer_, resizerWith_, detailTab_, httpTab_, tabPanel_, segmented_, periodToggle_, Deferred (..), RefreshingDeferred (..), withDeferredBody, deferredShell_, lazyPanel_, timeRefreshListener_, drawerLoadingSkeleton_, tableSkeleton_, chartSkeleton_, EmptyStateCfg (..), EmptyStateSize (..), EmptyStateAction (..), emptyState_, callout_, BadgeColor (..), IconBadgeSize (..), iconBadge_, tonePill_, colorChip_, metadataChip_, metaChip_, connectionBadge_, silenceBadge_, statFigure_, factGrid_, kvList_, sparkline_, eventsCountCell_, lastSeenCell_, dateTime, localTimeFmt_, FieldSize (..), FieldCfg (..), formField_, formSelectField_, formCheckbox_, options_, roleOptions_, tagInput_, toggleRow_, searchInput_, copyField_, copyButton_, facetRail_, facetSection_, facetOption_, ModalCfg (..), modalWith_, formActionsModal_, dangerAction_, floatingDialog_, dialogField_, kbdHints_, durationMenu_, primaryButton_, inlineIconBtn_, RowAction (..), rowActions_, externalLink_, installationSettingsLink_, dirtyFormSaveAttr_, resetFormOnSuccessAttr_, detailsClosedBelowAttr_, keyboardActivateAttr_, listboxNavAttr_, copySourceAttr_, filterInputAttr_, TraceFrame (..), stackTrace_, stackFrames_, codeContextUrl, curlCommand, getTargetPage, abbreviateUnit, agoText, durationQuery, untilLabel, paymentPlanPicker) where +module Pages.Components (drawer_, PanelStyle (..), PanelCfg (..), panel_, entityHeader_, detailSection_, pivotLinks_, disclosure_, settingsSection_, settingsH2_, sectionLabel_, fieldLabel_, headerRow_, navBar, brandLogo_, resizer_, resizerWith_, detailTab_, httpTab_, tabPanel_, segmented_, periodToggle_, Deferred (..), RefreshingDeferred (..), withDeferredBody, deferredShell_, lazyPanel_, timeRefreshListener_, drawerLoadingSkeleton_, tableSkeleton_, chartSkeleton_, EmptyStateCfg (..), EmptyStateSize (..), EmptyStateAction (..), emptyState_, callout_, BadgeColor (..), IconBadgeSize (..), iconBadge_, tonePill_, colorChip_, metadataChip_, metaChip_, connectionBadge_, silenceBadge_, statFigure_, factGrid_, kvList_, sparkline_, eventsCountCell_, lastSeenCell_, dateTime, localTimeFmt_, FieldSize (..), FieldCfg (..), formField_, formSelectField_, formCheckbox_, options_, roleOptions_, tagInput_, toggleRow_, searchInput_, copyField_, copyButton_, facetRail_, facetSection_, facetOption_, ModalCfg (..), modalWith_, formActionsModal_, dangerAction_, floatingDialog_, dialogField_, kbdHints_, durationMenu_, primaryButton_, inlineIconBtn_, RowAction (..), rowActions_, externalLink_, installationSettingsLink_, dirtyFormSaveAttr_, resetFormOnSuccessAttr_, detailsClosedBelowAttr_, keyboardActivateAttr_, listboxNavAttr_, copySourceAttr_, filterInputAttr_, TraceFrame (..), stackTrace_, stackFrames_, codeContextUrl, curlCommand, getTargetPage, abbreviateUnit, agoText, durationQuery, untilLabel, grantsTrial, paymentPlanPicker) where import Data.Default (Default (..)) import Data.List (elemIndex, findIndex, lookup) @@ -291,8 +291,8 @@ localTimeFmt_ dfFmt ts = (toHtml $ formatTime defaultTimeLocale "%b %d, %H:%M:%S UTC" ts) -paymentPlanPicker :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Bool -> Projects.BillingProvider -> Html () -paymentPlanPicker pid lemonUrl criticalUrl currentPlan freePricingEnabled basicAuthEnabled isOnboarding provider = do +paymentPlanPicker :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Bool -> Bool -> Projects.BillingProvider -> Html () +paymentPlanPicker pid lemonUrl criticalUrl currentPlan freePricingEnabled basicAuthEnabled trialEligible isOnboarding provider = do let useStripe = provider /= Projects.LemonSqueezyProvider div_ ([class_ "flex flex-col gap-8 w-full"] <> [hxVals_ "{\"isOnboarding\": true}" | isOnboarding]) do unless basicAuthEnabled $ div_ [class_ "flex flex-col gap-2 w-full"] do @@ -307,8 +307,8 @@ paymentPlanPicker pid lemonUrl criticalUrl currentPlan freePricingEnabled basicA then openSourcePricing pid (isCurrent "Open Source") >> enterprisePricing else do when freePricingEnabled $ freePricing pid (isCurrent "Free") - popularPricing pid lemonUrl (isCurrent "Bring nothing") freePricingEnabled useStripe - systemsPricing pid criticalUrl (isCurrent "Bring your own storage") useStripe + popularPricing pid lemonUrl (isCurrent "Bring nothing") freePricingEnabled trialEligible useStripe + systemsPricing pid criticalUrl (isCurrent "Bring your own storage") trialEligible useStripe unless useStripe do script_ [src_ "https://assets.lemonsqueezy.com/lemon.js"] ("" :: Text) script_ @@ -381,11 +381,18 @@ pricingButton_ isCurrent normalCls attrs label = $ bool label "Current plan" isCurrent +-- | Whether a Stripe checkout for @plan@ comes with the 30-day trial: first-time buyers only, +-- and never on Bring-your-own-storage. +grantsTrial :: Bool -> Text -> Bool +grantsTrial trialEligible plan = trialEligible && plan /= "SystemsPricing" + + -- | Plan CTA: inert when already the current plan, else a Stripe checkout POST or a LemonSqueezy popup. -pricingCta_ :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Html () -pricingCta_ pid plan normalCls lemonUrl isCurrent useStripe = +pricingCta_ :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Bool -> Html () +pricingCta_ pid plan normalCls lemonUrl isCurrent trialEligible useStripe = div_ [[__|on click halt|]] - $ pricingButton_ isCurrent normalCls (type_ "button" : attrs) "Start 30 day free trial" + $ pricingButton_ isCurrent normalCls (type_ "button" : attrs) + $ bool "Subscribe" "Start 30 day free trial" (not useStripe || grantsTrial trialEligible plan) where attrs :: [Attribute] attrs @@ -415,8 +422,8 @@ freePricing pid isCurrent = "What's included:" -popularPricing :: Projects.ProjectId -> Text -> Bool -> Bool -> Bool -> Html () -popularPricing pid lemonUrl isCurrent freeTierEnabled useStripe = +popularPricing :: Projects.ProjectId -> Text -> Bool -> Bool -> Bool -> Bool -> Html () +popularPricing pid lemonUrl isCurrent freeTierEnabled trialEligible useStripe = div_ [class_ "relative"] $ div_ (pricingPostAttrs pid "GraduatedPricing" "outline-strokeWeak shadow-[0px_3px_3px_-1.5px_rgba(10,13,18,0.04)] shadow-[0px_8px_8px_-4px_rgba(10,13,18,0.03)] shadow-[0px_20px_24px_-4px_rgba(10,13,18,0.08)]" [hxVals_ "js:{orderIdM: document.querySelector('#popularPricing').value}"]) do div_ [class_ "pricing-gradient-slate-wide"] pass @@ -426,13 +433,13 @@ popularPricing pid lemonUrl isCurrent freeTierEnabled useStripe = "Bring nothing" "This plan can be adjusted" (priceDisplay_ [term "hx-live:text" "(v => v <= 2e7 ? 29 : 29 + (v - 2e7) / 1e6)(+q('#price_range').value)"] "29" "/per month") - (pricingCta_ pid "GraduatedPricing" "btn-primary" lemonUrl isCurrent useStripe) + (pricingCta_ pid "GraduatedPricing" "btn-primary" lemonUrl isCurrent trialEligible useStripe) ["Fully managed cloud service", "Predictable usage-based pricing", "Intelligent incident alerts", "Query your data in english", "30 days data retention included"] (span_ [] $ when freeTierEnabled $ "Everything in " >> span_ [class_ "text-textBrand"] "free" >> " plus...") -systemsPricing :: Projects.ProjectId -> Text -> Bool -> Bool -> Html () -systemsPricing pid critical isCurrent useStripe = +systemsPricing :: Projects.ProjectId -> Text -> Bool -> Bool -> Bool -> Html () +systemsPricing pid critical isCurrent trialEligible useStripe = pricingBadge_ (span_ [class_ "text-sm font-medium leading-tight"] "🌟" >> span_ [class_ "leading-tight text-sm"] "MOST POPULAR") $ div_ (pricingPostAttrs pid "SystemsPricing" "outline-strokeBrand-strong" [hxVals_ "js:{orderIdM: document.querySelector('#systemsPricing').value}"]) $ div_ [class_ "flex flex-col gap-2"] do @@ -442,7 +449,7 @@ systemsPricing pid critical isCurrent useStripe = "Bring your own storage" "Business plan" (priceDisplay_ [term "hx-live:text" "(v => v <= 1e8 ? 199 : 199 + (v - 1e8) / 1e6)(+q('#price_range').value)"] "199" "/per month") - (pricingCta_ pid "SystemsPricing" "bg-fillStrong text-textInverse-strong" critical isCurrent useStripe) + (pricingCta_ pid "SystemsPricing" "bg-fillStrong text-textInverse-strong" critical isCurrent trialEligible useStripe) ["Own and control all your data", "Save all your data to any S3-compatible bucket", "Unlimited data retention period", "Query years of data via monoscope", "No extra cost for data retention"] (span_ [] $ "Everything in " >> span_ [class_ "text-textBrand"] "bring nothing" >> " plus...") diff --git a/src/Pages/LogExplorer/Log.hs b/src/Pages/LogExplorer/Log.hs index 923cbd8f4..878c30142 100644 --- a/src/Pages/LogExplorer/Log.hs +++ b/src/Pages/LogExplorer/Log.hs @@ -1130,19 +1130,15 @@ lookupAlert :: DB es => Maybe Text -> Eff es (Maybe Monitors.QueryMonitor) lookupAlert = maybe (pure Nothing) (Monitors.queryMonitorById . Monitors.QueryMonitorId) . (>>= UUID.fromText) --- | One-decimal percent formatter. +-- | One-decimal percent formatter; positive rates never round down to zero. -- -- >>> import "monoscope" Pages.LogExplorer.Log qualified as LL --- >>> LL.fmtPct1 0 --- "0.0%" --- >>> LL.fmtPct1 5.24 --- "5.2%" --- >>> LL.fmtPct1 100 --- "100.0%" --- >>> LL.fmtPct1 (-1.25) --- "-1.2%" +-- >>> map LL.fmtPct1 [0, 0.03, 0.05, 5.24, 100, -1.25] +-- ["0.0%","<0.1%","0.1%","5.2%","100.0%","-1.2%"] fmtPct1 :: Double -> Text -fmtPct1 x = showFFloat' 1 x <> "%" +fmtPct1 x + | x > 0 && x < 0.05 = "<0.1%" + | otherwise = showFFloat' 1 x <> "%" -- | Shimmer placeholder mirroring 'sessionsHeader_' (6-KPI grid + over-time bar diff --git a/src/Pages/Onboarding.hs b/src/Pages/Onboarding.hs index 5340417e6..de2c6b512 100644 --- a/src/Pages/Onboarding.hs +++ b/src/Pages/Onboarding.hs @@ -74,9 +74,10 @@ onboardingGetH pid stepM = do discordUrl = "https://discord.com/oauth2/authorize?response_type=code&client_id=" <> appCtx.config.discordClientId <> "&permissions=277025392640&integration_type=0&scope=bot+applications.commands&state=" <> pid.toText <> "__onboarding&redirect_uri=" <> appCtx.env.discordRedirectUri pure $ NotifChannelStep pid slackUrl discordUrl phone (maybe mempty (.notify_emails) everyoneTeamM) hasSlack hasDiscord Integration -> IntegrationStep pid . maybe "" (.keyPrefix) . listToMaybe <$> ProjectApiKeys.projectApiKeysByProjectId pid - Pricing -> + Pricing -> do + billing <- Projects.userBilling sess.user.id let checkout u = u <> "&checkout[custom][project_id]=" <> pid.toText - in pure $ PricingStep pid (checkout appCtx.config.lemonSqueezyUrl) (checkout appCtx.config.lemonSqueezyCriticalUrl) project.paymentPlan appCtx.config.enableFreetier appCtx.config.basicAuthEnabled + pure $ PricingStep pid (checkout appCtx.config.lemonSqueezyUrl) (checkout appCtx.config.lemonSqueezyCriticalUrl) project.paymentPlan appCtx.config.enableFreetier appCtx.config.basicAuthEnabled (not billing.hasSubscribedBefore) Info -> pure $ InfoStep pid sess.user.firstName sess.user.lastName (q "companyName") (q "companySize") (q "foundUsFrom") addRespHeaders $ OnboardingGet $ PageCtx bw{currProject = Nothing, hideNavbar = True} stepData @@ -142,6 +143,7 @@ data OnboardingStepData , paymentPlan :: Text , enableFreetier :: Bool , basicAuthEnabled :: Bool + , trialEligible :: Bool } | CompleteStep { stepPid :: Projects.ProjectId @@ -162,7 +164,7 @@ instance ToHtml OnboardingGet where SurveyStep{..} -> onboardingConfigBody stepPid location functionality NotifChannelStep{..} -> notifChannelsWithUrls slackUrl discordUrl stepPid phoneNumber emails hasDiscord hasSlack IntegrationStep{..} -> integrationsPage stepPid apiKey - PricingStep{..} -> pricingPage stepPid lemonUrl criticalUrl paymentPlan enableFreetier basicAuthEnabled + PricingStep{..} -> pricingPage stepPid lemonUrl criticalUrl paymentPlan enableFreetier basicAuthEnabled trialEligible InfoStep{..} -> onboardingInfoBody stepPid firstName lastName companyName companySize foundUsFrom toHtmlRaw = toHtml @@ -272,12 +274,12 @@ onboardingCompleteBody pid = do script_ [src_ "/public/assets/js/confetti.js"] ("" :: Text) -pricingPage :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Html () -pricingPage pid lemon critical paymentPlan freeTierEnabled basicAuthEnabled = +pricingPage :: Projects.ProjectId -> Text -> Text -> Text -> Bool -> Bool -> Bool -> Html () +pricingPage pid lemon critical paymentPlan freeTierEnabled basicAuthEnabled trialEligible = div_ [class_ "w-full max-w-[1100px] mx-auto mt-[70px] mb-10 px-4 md:px-0"] $ do div_ [class_ "flex-col gap-4 flex w-full"] $ do div_ [class_ "w-full md:w-1/2"] $ stepIndicator 5 "Please pick a plan" $ stepUrl pid Integration - paymentPlanPicker pid lemon critical paymentPlan freeTierEnabled basicAuthEnabled True Projects.NoBillingProvider + paymentPlanPicker pid lemon critical paymentPlan freeTierEnabled basicAuthEnabled trialEligible True Projects.NoBillingProvider div_ [class_ "flex flex-col gap-2 w-full pb-20"] do span_ [class_ "text-textStrong text-2xl mt-20"] "FAQ" div_ [class_ "join join-vertical w-full mt-4"] do diff --git a/src/Pages/Projects.hs b/src/Pages/Projects.hs index fccdbfbe8..443e10708 100644 --- a/src/Pages/Projects.hs +++ b/src/Pages/Projects.hs @@ -96,8 +96,9 @@ import Relude hiding (ask, asks) import Servant (addHeader) import Servant.API (Header) import Servant.API.ResponseHeaders (Headers) -import Servant.Server (err302, err500, errBody, errHeaders) +import Servant.Server (err302, err500, err503, errBody, errHeaders) import System.Config (AuthContext (..), EnvConfig (..)) +import System.Logging qualified as Log import System.Types (ATAuthCtx, RespHeaders, addErrorToast, addRespHeaders, addReswap, addSuccessToast, addTriggerEvent, redirectCS, toastError) import Utils (LoadingSize (..), encodeText, faSprite_, htmxIndicator_, isDemoAndNotSudo, lookupValueText) import Web.FormUrlEncoded (FromForm) @@ -1159,9 +1160,19 @@ newtype StripeCheckoutForm = StripeCheckoutForm {plan :: Text} stripeCheckoutInitH :: Projects.ProjectId -> StripeCheckoutForm -> ATAuthCtx (RespHeaders (Html ())) stripeCheckoutInitH pid form = do - (sess, _) <- Projects.sessionAndProject pid + (sess, project) <- Projects.sessionAndProject pid appCtx <- ask @AuthContext let envCfg = appCtx.config + lapsedSubId = guard (Projects.isFreeTier project.paymentPlan && Projects.projectProvider project == Projects.StripeProvider) *> mfilter (not . T.null) project.subId + debts <- + maybe + (pure []) + ( BackgroundJobs.getStripeInvoices envCfg.stripeSecretKey BackgroundJobs.OpenInvoices + >=> either + (\err -> Log.logAttention "Stripe reactivation invoice lookup failed" (pid.toText, err) >> throwError err503{errBody = "Unable to verify outstanding invoices. Please retry."}) + (pure . filter (\i -> i.status == "open" && i.amountRemaining > 0)) + ) + lapsedSubId -- Keyed to the buyer, not the project: people run several projects, and each one -- used to mint its own Stripe customer and hand out its own 30-day trial. billing <- Projects.userBilling sess.user.id @@ -1169,6 +1180,7 @@ stripeCheckoutInitH pid form = do =<< Settings.createStripeCheckoutSession (not billing.hasSubscribedBefore) billing.stripeCustomerId + debts envCfg.stripeSecretKey envCfg.hostUrl pid diff --git a/src/Pages/Settings.hs b/src/Pages/Settings.hs index b8dc063a7..c85390e8f 100644 --- a/src/Pages/Settings.hs +++ b/src/Pages/Settings.hs @@ -60,7 +60,7 @@ module Pages.Settings ( billingUrl, ) where -import Control.Lens ((.~), (^.)) +import Control.Lens ((.~), (?~), (^.)) import Data.Aeson qualified as AE import Data.Aeson.Types (parseMaybe) import Data.ByteArray qualified as BA @@ -110,14 +110,14 @@ import Network.HTTP.Types (urlEncode) import Network.Minio qualified as Minio import Network.Wreq qualified as Wreq import Pages.BodyWrapper (BWConfig (..), PageCtx (..), mkPageCtx, settingsContentTarget) -import Pages.Components (BadgeColor (..), EmptyStateCfg (..), EmptyStateSize (..), FieldCfg (..), FieldSize (..), IconBadgeSize (..), ModalCfg (..), callout_, connectionBadge_, copyField_, copySourceAttr_, dangerAction_, disclosure_, emptyState_, filterInputAttr_, formActionsModal_, formCheckbox_, formField_, headerRow_, iconBadge_, keyboardActivateAttr_, localTimeFmt_, modalWith_, options_, paymentPlanPicker, searchInput_, sectionLabel_, settingsH2_, settingsSection_, tonePill_) +import Pages.Components (BadgeColor (..), EmptyStateCfg (..), EmptyStateSize (..), FieldCfg (..), FieldSize (..), IconBadgeSize (..), ModalCfg (..), callout_, connectionBadge_, copyField_, copySourceAttr_, dangerAction_, disclosure_, emptyState_, filterInputAttr_, formActionsModal_, formCheckbox_, formField_, grantsTrial, headerRow_, iconBadge_, keyboardActivateAttr_, localTimeFmt_, modalWith_, options_, paymentPlanPicker, searchInput_, sectionLabel_, settingsH2_, settingsSection_, tonePill_) import Pkg.Components.Table qualified as Table import Pkg.DeriveUtils (DB, UUIDId (..), WrappedEnumSC (..)) import Pkg.EmailTemplates qualified as ET import Pkg.Mail (NotificationAlerts (..), sampleAlertByIssueTypeText, sampleReport, sendDiscordAlert, sendPagerdutyAlertToService, sendRenderedEmail, sendSlackAlert, sendWhatsAppAlert) import Pkg.Prometheus qualified as Prom import Relude hiding (ask, asks) -import Servant (FromHttpApiData (..), err400, errBody) +import Servant (FromHttpApiData (..), err400, err503, errBody) import System.Config import System.Types (ATAuthCtx, ATBaseCtx, RespHeaders, addErrorToast, addRespHeaders, addReswap, addSuccessToast, addTriggerEvent) import Text.Printf (printf) @@ -1185,6 +1185,7 @@ data BillingData = BillingData , paymentPlan :: Text , enableFreetier :: Bool , basicAuthEnabled :: Bool + , trialEligible :: Bool , provider :: Projects.BillingProvider , dailyUsage :: [Projects.DailyUsage] -- ^ (day, total_requests, metrics, eventBytes, metricBytes); events = total_requests - metrics @@ -1223,7 +1224,8 @@ instance ToHtml BillingGet where manageBillingGetH :: Projects.ProjectId -> ATAuthCtx (RespHeaders BillingGet) manageBillingGetH pid = do - (_, project, bw) <- mkPageCtx pid + (sess, project, bw) <- mkPageCtx pid + billing <- Projects.userBilling sess.user.id let dat = fromMaybe project.createdAt project.billingDay envCfg = bw.config currentTime <- Time.currentTime @@ -1273,7 +1275,7 @@ manageBillingGetH pid = do lemonUrl = envCfg.lemonSqueezyUrl <> "&checkout[custom][project_id]=" <> pid.toText critical = envCfg.lemonSqueezyCriticalUrl <> "&checkout[custom][project_id]=" <> pid.toText provider = Projects.projectProvider project - addRespHeaders $ BillingGet $ PageCtx bwconf BillingData{pid, totalReqs = totalRequests, totalBytes, aiInputTokens, aiOutputTokens, aiCostMicrousd, aiInputRate = envCfg.aiInputMicrousdPerMillionTokens, aiOutputRate = envCfg.aiOutputMicrousdPerMillionTokens, lastReported, lemonUrl, critical, paymentPlan = project.paymentPlan, enableFreetier = envCfg.enableFreetier, basicAuthEnabled = envCfg.basicAuthEnabled, provider, dailyUsage, cycleStart = utctDay cycleStart, cycleEnd, currentInvoice, pastCycles} + addRespHeaders $ BillingGet $ PageCtx bwconf BillingData{pid, totalReqs = totalRequests, totalBytes, aiInputTokens, aiOutputTokens, aiCostMicrousd, aiInputRate = envCfg.aiInputMicrousdPerMillionTokens, aiOutputRate = envCfg.aiOutputMicrousdPerMillionTokens, lastReported, lemonUrl, critical, paymentPlan = project.paymentPlan, enableFreetier = envCfg.enableFreetier, basicAuthEnabled = envCfg.basicAuthEnabled, trialEligible = not billing.hasSubscribedBefore, provider, dailyUsage, cycleStart = utctDay cycleStart, cycleEnd, currentInvoice, pastCycles} where epochDay :: Int -> Day epochDay = utctDay . posixSecondsToUTCTime . fromIntegral @@ -1306,7 +1308,11 @@ stripeBillingPeriods envCfg project Log.logAttention "Billing page: Stripe period unavailable, falling back to local cycle" (project.id.toText, subId) pure Nothing Just (start, end) -> do - invoices <- BJ.getStripeInvoices envCfg.stripeSecretKey subId + invoices <- + BJ.getStripeInvoices envCfg.stripeSecretKey BJ.RecentInvoices subId + >>= either + (\err -> Log.logAttention "Billing page: Stripe invoice lookup failed" (project.id.toText, err) $> []) + pure pure $ Just StripePeriods{periodStart = posixSecondsToUTCTime (fromIntegral start), periodEnd = posixSecondsToUTCTime (fromIntegral end), invoices} @@ -1381,7 +1387,7 @@ billingPage d = div_ [] do span_ [class_ "text-textStrong text-2xl font-semibold"] "Compare Plans" p_ [class_ "mt-2 mb-4"] "Drag the slider to estimate costs at different usage levels." -- Free upgrades use Stripe; billing recovery keeps the existing provider. - paymentPlanPicker d.pid d.lemonUrl d.critical d.paymentPlan d.enableFreetier d.basicAuthEnabled False (bool d.provider Projects.NoBillingProvider isFree) + paymentPlanPicker d.pid d.lemonUrl d.critical d.paymentPlan d.enableFreetier d.basicAuthEnabled d.trialEligible False (bool d.provider Projects.NoBillingProvider isFree) usd :: Double -> Text @@ -1556,8 +1562,11 @@ stripeSessionUrl apiKey endpoint params = do -- `customerM` is the buyer's existing Stripe customer, when they have one. Omitting -- it makes Stripe mint a fresh Customer per session, so one person upgrading a second -- project became a second unrelated customer on the same card. -createStripeCheckoutSession :: W.HTTP :> es => Bool -> Maybe Text -> Text -> Text -> Projects.ProjectId -> Text -> Text -> Text -> Text -> Eff es (Maybe Text) -createStripeCheckoutSession trialEligible customerM apiKey hostUrl pid plan priceIdGraduated priceIdOverage priceIdBYOS = do +-- +-- `debts` are open invoices of the project's lapsed subscription: each becomes a +-- one-time line on the first payment, and 'handleStripeCheckout' marks them paid. +createStripeCheckoutSession :: W.HTTP :> es => Bool -> Maybe Text -> [BJ.StripeInvoice] -> Text -> Text -> Projects.ProjectId -> Text -> Text -> Text -> Text -> Eff es (Maybe Text) +createStripeCheckoutSession trialEligible customerM debts apiKey hostUrl pid plan priceIdGraduated priceIdOverage priceIdBYOS = do let basePrice = case plan of "SystemsPricing" -> priceIdBYOS _ -> priceIdGraduated @@ -1566,12 +1575,25 @@ createStripeCheckoutSession trialEligible customerM apiKey hostUrl pid plan pric , ("line_items[0][quantity]", "1") , ("line_items[1][price]", encodeUtf8 priceIdOverage) ] - trialParams = [("subscription_data[trial_period_days]", "30") | trialEligible && plan /= "SystemsPricing"] + trialParams = [("subscription_data[trial_period_days]", "30") | grantsTrial trialEligible plan] -- Stripe Managed Payments (MoR): Stripe becomes merchant of record and handles -- tax/address collection itself, so the automatic_tax + tax_id params are disallowed. managedPaymentsParams = [("managed_payments[enabled]", "true")] + debtParams = + concat + [ [ (item "[price_data][currency]", encodeUtf8 inv.currency) + , (item "[price_data][unit_amount]", show inv.amountRemaining) + , (item "[price_data][product_data][name]", encodeUtf8 $ "Outstanding balance" <> foldMap (", invoice " <>) inv.number) + , (item "[price_data][product_data][tax_code]", "txcd_10103001") + , (item "[quantity]", "1") + ] + | (i, inv) <- zip [2 :: Int ..] debts + , let item k = "line_items[" <> show i <> "]" <> k + ] + <> [("metadata[settles_invoices]", encodeUtf8 $ T.intercalate "," $ map (.invoiceId) debts) | not (null debts)] params = prices + <> debtParams <> trialParams <> managedPaymentsParams <> [("customer", encodeUtf8 c) | c <- maybeToList customerM] @@ -1604,9 +1626,12 @@ lemonSqueezyOpts apiKey = -- not block the deletion the user asked for, so failures are logged, not thrown. cancelProjectSubscription :: (Log.Log :> es, W.HTTP :> es) => EnvConfig -> Projects.Project -> Eff es () cancelProjectSubscription envConfig project = whenJust target \(opts, url) -> do - res <- trySync $ W.deleteWith opts url - whenLeft_ res \e -> - Log.logAttention "Subscription cancellation failed; subscription may still be billing" (project.id.toText, project.subId, show @Text e) + res <- trySync $ W.deleteWith (opts & Wreq.checkResponse ?~ \_ _ -> pass) url + case (^. Wreq.responseStatus . Wreq.statusCode) <$> res of + -- A sub that already ended (e.g. cancelled by dunning) 404s: nothing left to stop. + Right 404 -> Log.logInfo "Subscription already ended; nothing to cancel" (project.id.toText, project.subId) + Right code | code < 300 -> pass + failure -> Log.logAttention "Subscription cancellation failed; subscription may still be billing" (project.id.toText, project.subId, either (toText . displayException) (("HTTP " <>) . show @Text) failure) where target = do subId <- mfilter (not . T.null) project.subId @@ -1642,11 +1667,11 @@ stripeWebhookPostH sigHeaderM rawBody = do sessionObj = jsonField "data" event >>= jsonField "object" :: Maybe AE.Value handlers = [ ("checkout.session.completed", handleStripeCheckout envConfig) + , ("checkout.session.async_payment_succeeded", handleStripeCheckout envConfig) , ("customer.subscription.deleted", handleStripeDowngrade envConfig "subscription.deleted" "was cancelled") - , ("customer.subscription.updated", handleStripeSubUpdated) - , ("customer.subscription.paused", handleStripeDowngrade envConfig "subscription.paused" "was paused") - , ("customer.subscription.resumed", handleStripeSubResumed envConfig) + , ("customer.subscription.updated", handleStripeSubUpdated envConfig) , ("invoice.payment_failed", handleStripePaymentFailed envConfig) + , ("invoice.paid", handleStripeInvoicePaid envConfig) ] case (,) <$> (eventType >>= flip lookup handlers) <*> sessionObj of Just (handle, obj) -> handle obj @@ -1670,33 +1695,50 @@ handleStripeCheckout envConfig obj = do let pidM = jsonField "client_reference_id" obj :: Maybe Text subIdM = jsonField "subscription" obj :: Maybe Text customerIdM = jsonField "customer" obj :: Maybe Text - planFromMetadata = (jsonField "metadata" obj :: Maybe AE.Value) >>= jsonField "plan" :: Maybe Text + metadata = jsonField "metadata" obj :: Maybe AE.Value + planFromMetadata = metadata >>= jsonField "plan" :: Maybe Text + settledInvoices = maybe [] (T.splitOn ",") (metadata >>= jsonField "settles_invoices") case (pidM >>= Projects.projectIdFromText, subIdM, customerIdM) of + _ | not (null settledInvoices) && jsonField @Text "payment_status" obj /= Just "paid" -> pure "awaiting payment" (Just pid, Just subId, Just customerId) -> do let plan = fromMaybe "GraduatedPricing" planFromMetadata projectM <- Projects.projectById pid - -- Idempotency: skip if this subscription is already set on the project - if maybe False (\p -> p.subId == Just subId) projectM - then pure "already processed" - else do - -- Cancel whatever subscription the project held before this checkout — a - -- LemonSqueezy one (auto-migration) or an older Stripe one. The idempotency - -- guard above means project.subId is never the sub we just created, and the - -- row is about to be overwritten with the new sub, so anything left running - -- here bills the customer twice with nothing left pointing at it. - whenJust projectM $ cancelProjectSubscription envConfig - subDetails <- BJ.getStripeSubDetails envConfig.stripeSecretKey subId - when (isNothing subDetails) $ Log.logAttention "Stripe sub fetch failed after checkout" (pid.toText, subId) - let subItemId = maybe "" (.subItemId) subDetails - void $ Projects.updateStripeProjectBilling pid (Projects.PlanName plan) (Projects.SubId subId) (Projects.SubItemId subItemId) (Projects.CustomerId customerId) - void $ ProjectMembers.activateAllMembers pid - case subDetails of - Just BJ.StripeSubDetails{trialEnd = Just epoch} -> BJ.scheduleTrialReminders pid epoch - Just BJ.StripeSubDetails{status = "trialing"} -> Log.logAttention "Stripe sub trialing but trial_end missing; no reminders scheduled" (pid.toText, subId) - _ -> pass - whenJust projectM \project -> - Notify.runNotifyProduction $ notifyPlanChange envConfig project (ET.planUpgradedEmail plan) - pure "checkout processed" + -- Idempotency: skip if this subscription is already set on the project. Settling runs + -- on both paths, so a retry after a crash past the sub_id write still settles; it runs + -- after that write so the invoice.paid it triggers no longer matches the project. + res <- + if maybe False (\p -> p.subId == Just subId) projectM + then pure "already processed" + else do + -- Cancel whatever subscription the project held before this checkout — a + -- LemonSqueezy one (auto-migration) or an older Stripe one. The idempotency + -- guard above means project.subId is never the sub we just created, and the + -- row is about to be overwritten with the new sub, so anything left running + -- here bills the customer twice with nothing left pointing at it. + whenJust projectM $ cancelProjectSubscription envConfig + subDetails <- BJ.getStripeSubDetails envConfig.stripeSecretKey subId + when (isNothing subDetails) $ Log.logAttention "Stripe sub fetch failed after checkout" (pid.toText, subId) + let subItemId = maybe "" (.subItemId) subDetails + void $ Projects.updateStripeProjectBilling pid (Projects.PlanName plan) (Projects.SubId subId) (Projects.SubItemId subItemId) (Projects.CustomerId customerId) + void $ ProjectMembers.activateAllMembers pid + case subDetails of + Just BJ.StripeSubDetails{trialEnd = Just epoch} -> BJ.scheduleTrialReminders pid epoch + Just BJ.StripeSubDetails{status = "trialing"} -> Log.logAttention "Stripe sub trialing but trial_end missing; no reminders scheduled" (pid.toText, subId) + _ -> pass + whenJust projectM \project -> + Notify.runNotifyProduction $ notifyPlanChange envConfig project (ET.planUpgradedEmail plan) + pure "checkout processed" + forM_ settledInvoices \invId -> do + let url = "https://api.stripe.com/v1/invoices/" <> toString invId + opts = stripeOpts envConfig.stripeSecretKey + settled <- trySync do + invoice <- W.getWith opts url + let status = AE.decode @AE.Value (invoice ^. Wreq.responseBody) >>= jsonField @Text "status" + unless (status == Just "paid") $ void $ W.postWith opts (url <> "/pay") ([("paid_out_of_band", "true")] :: [(ByteString, ByteString)]) + whenLeft_ settled \_ -> do + Log.logAttention "Stripe checkout invoice settlement failed; requesting webhook retry" (pid.toText, invId) + throwError err503{errBody = "Invoice settlement failed. Please retry."} + pure res _ -> do Log.logAttention "Stripe checkout missing project/sub/customer" (pidM, subIdM, customerIdM) pure "missing fields" @@ -1719,19 +1761,47 @@ handleStripeDowngrade envConfig event reason obj = pure "missing sub id" -handleStripeSubUpdated :: AE.Value -> ATBaseCtx (Html ()) -handleStripeSubUpdated obj = do - let subIdM = jsonField "id" obj :: Maybe Text - newItemIdM = (jsonField "items" obj >>= jsonField "data" :: Maybe [AE.Value]) >>= listToMaybe >>= jsonField "id" :: Maybe Text - case (subIdM, newItemIdM) of - (Just subId, Just newItemId) -> - void $ Projects.updateSubItemIdBySubId newItemId subId - _ -> Log.logAttention "Stripe subscription.updated missing sub_id or item_id" (subIdM, newItemIdM) +-- | Keeps the item id current and mirrors the sub's status onto the plan: dunning that ends at +-- @unpaid@ (or a pause) downgrades, and paying the invoice by any route returns the same sub to +-- @active@, which restores the plan its price maps to. Guarded on the current plan so repeat +-- updates don't re-notify. +handleStripeSubUpdated :: EnvConfig -> AE.Value -> ATBaseCtx (Html ()) +handleStripeSubUpdated envConfig obj = do + let item0 = (jsonField "items" obj >>= jsonField "data" :: Maybe [AE.Value]) >>= listToMaybe + itemIdM = item0 >>= jsonField "id" :: Maybe Text + case (jsonField "id" obj :: Maybe Text, itemIdM) of + (Just subId, Just itemId) -> do + void $ Projects.updateSubItemIdBySubId itemId subId + whenJustM (Projects.projectBySubId subId) \project -> case (jsonField "status" obj :: Maybe Text, Projects.isFreeTier project.paymentPlan) of + (Just "unpaid", False) -> void $ handleStripeDowngrade envConfig "subscription.unpaid" "is unpaid" obj + (Just "paused", False) -> void $ handleStripeDowngrade envConfig "subscription.paused" "was paused" obj + (Just status, True) | status `elem` ["active", "trialing"] -> do + let plan = bool "GraduatedPricing" "SystemsPricing" ((item0 >>= jsonField "price" >>= jsonField "id") == Just envConfig.stripePriceIdByos) + void $ Projects.setPlanBySubId (Projects.PlanName plan) (Projects.SubItemId itemId) (Projects.SubId subId) + Notify.runNotifyProduction $ notifyPlanChange envConfig project (ET.planUpgradedEmail plan) + _ -> pass + ids -> Log.logAttention "Stripe subscription.updated missing sub_id or item_id" ids pure "subscription updated" +-- | A cancelled sub can't be revived, so paying its leftover invoice outside our checkout +-- (hosted link, email, portal) leaves the project on Free: point the payer at checkout. +-- An @unpaid@ sub's revival arrives as customer.subscription.updated instead. +handleStripeInvoicePaid :: EnvConfig -> AE.Value -> ATBaseCtx (Html ()) +handleStripeInvoicePaid envConfig obj = do + let subIdM = (jsonField "parent" obj >>= jsonField "subscription_details" >>= jsonField "subscription") <|> jsonField "subscription" obj :: Maybe Text + whenJust subIdM \subId -> whenJustM (Projects.projectBySubId subId) \project -> + when (Projects.isFreeTier project.paymentPlan) $ BJ.getStripeSubDetails envConfig.stripeSecretKey subId >>= \case + Just BJ.StripeSubDetails{status = "canceled"} -> do + Log.logInfo "Stripe invoice paid on a cancelled subscription; asking the payer to reactivate" (project.id.toText, subId) + Notify.runNotifyProduction $ notifyPlanChange envConfig project ET.invoiceSettledEmail + Just _ -> pass + Nothing -> Log.logAttention "Stripe invoice.paid: sub fetch failed; a lapsed payer may not be told to reactivate" (project.id.toText, subId) + pure "invoice paid handled" + + -- Notification only — Stripe retries payments automatically over its dunning period. --- Downgrade happens via customer.subscription.deleted when Stripe gives up. +-- Downgrade happens when Stripe gives up: subscription.deleted, or .updated to unpaid. handleStripePaymentFailed :: EnvConfig -> AE.Value -> ATBaseCtx (Html ()) handleStripePaymentFailed envConfig obj = do let attemptCount = jsonField "attempt_count" obj :: Maybe Int @@ -1741,31 +1811,3 @@ handleStripePaymentFailed envConfig obj = do Log.logAttention "Stripe invoice.payment_failed" (project.id, attemptCount, nextAttempt) Notify.runNotifyProduction $ notifyPlanChange envConfig project ET.paymentFailedEmail pure "payment failed handled" - - --- Look up the sub's price via the Stripe API, reverse-map to our plan name, and re-upgrade. --- (Pause preserved the IDs, so resume never needs a re-checkout.) -handleStripeSubResumed :: EnvConfig -> AE.Value -> ATBaseCtx (Html ()) -handleStripeSubResumed envConfig obj = - case jsonField "id" obj :: Maybe Text of - Just subId -> do - subDetailsM <- BJ.getStripeSubDetails envConfig.stripeSecretKey subId - case subDetailsM of - -- the price id reverse-maps to our internal plan name - Just BJ.StripeSubDetails{subItemId = itemId, priceId} -> do - let plan - | priceId == envConfig.stripePriceIdByos = "SystemsPricing" - | otherwise = "GraduatedPricing" - rows <- Projects.setPlanBySubId (Projects.PlanName plan) (Projects.SubItemId itemId) (Projects.SubId subId) - when (rows == 0) $ Log.logAttention "Stripe subscription.resumed: no project for sub_id" (subId, plan) - when (rows > 1) $ Log.logAttention "Stripe subscription.resumed touched multiple rows" (subId, rows) - when (rows > 0) - $ whenJustM (Projects.projectBySubId subId) \project -> - Notify.runNotifyProduction $ notifyPlanChange envConfig project (ET.planUpgradedEmail plan) - pure "subscription resumed" - Nothing -> do - Log.logAttention "Stripe subscription.resumed: could not fetch sub items" subId - pure "missing items" - Nothing -> do - Log.logAttention "Stripe subscription.resumed: missing sub id" () - pure "missing sub id" diff --git a/src/Pkg/EmailTemplates.hs b/src/Pkg/EmailTemplates.hs index 21fc63209..c2be85697 100644 --- a/src/Pkg/EmailTemplates.hs +++ b/src/Pkg/EmailTemplates.hs @@ -33,6 +33,7 @@ module Pkg.EmailTemplates ( freeTierUsageEmail, planUpgradedEmail, planDowngradedEmail, + invoiceSettledEmail, paymentFailedEmail, trialEndingEmail, @@ -1249,6 +1250,21 @@ planDowngradedEmail reason projectName = "Upgrade Plan" +-- | A cancelled subscription's leftover invoice was paid outside checkout: the money is in, but +-- nothing reactivated, since a cancelled subscription can't be revived. +invoiceSettledEmail :: Text -> Text -> (Text, Html ()) +invoiceSettledEmail projectName = + ctaEmail + ("[···] Payment received - " <> projectName) + True + ( do + h1_ "Payment Received" + richP_ ["Thanks, your outstanding invoice for ", projectName, " is paid. The subscription it belonged to had already ended, so the project is still on the Free plan."] + p_ "Reactivate from the billing page to restore full access." + ) + "Reactivate Subscription" + + -- | Provider dunning is still retrying, so nothing has changed yet; the downgrade only follows -- if every retry fails. paymentFailedEmail :: Text -> Text -> (Text, Html ()) diff --git a/test/integration/Pages/BusinessFlowsSpec.hs b/test/integration/Pages/BusinessFlowsSpec.hs index 37b698fe2..2896d19e5 100644 --- a/test/integration/Pages/BusinessFlowsSpec.hs +++ b/test/integration/Pages/BusinessFlowsSpec.hs @@ -8,7 +8,8 @@ import Data.ByteString.Base16 qualified as B16 import Data.ByteString.Lazy qualified as BL import Data.Default (def) import Data.Effectful.Hasql qualified as Hasql -import Data.Effectful.Wreq (HTTP) +import Data.Effectful.Wreq (HTTP, Options) +import Data.List (lookup) import Data.Pool (Pool, withResource) import Data.Text qualified as T import Data.Text.Lazy qualified as TL @@ -27,8 +28,10 @@ import Hasql.Interpolate qualified as HI import Lucid (renderText, toHtml) import Models.Apis.Issues qualified as Issues import Models.Projects.Projects qualified as Projects +import Network.HTTP.Types.URI (parseSimpleQuery) import OpenTelemetry.Instrumentation.Hasql qualified as OHasql import Pages.BodyWrapper (PageCtx (..)) +import Pages.Bots.BotTestHelpers (withHTTPResponses) import Pages.Dashboards qualified as Dashboards import Pages.LogExplorer.Log qualified as Log import Pages.Monitors qualified as Monitors @@ -314,6 +317,8 @@ settingsTests = do html `shouldSatisfy` TL.isInfixOf "id=\"billing-downgrade-banner\"" html `shouldSatisfy` TL.isInfixOf "Your paid subscription is no longer active. This project has been downgraded to Free." html `shouldSatisfy` TL.isInfixOf ("href=\"/p/" <> toLazy testPid.toText <> "/manage_billing\"") + -- A cancelled Stripe sub can't be revived from the portal, only by a new checkout. + html `shouldSatisfy` TL.isInfixOf (bool "Update payment method" "Reactivate subscription" (provider == Projects.StripeProvider)) session <- refreshSession tr.trPool tr.trATCtx.hasqlPool tr.trSessAndHeader (_, billing) <- testServant tr{trSessAndHeader = session} $ Settings.manageBillingGetH testPid renderText (toHtml billing) `shouldSatisfy` TL.isInfixOf ("hx-get=\"/p/" <> toLazy testPid.toText <> "/manage_subscription\"") @@ -517,7 +522,9 @@ stripeBillingTests = do let checkout = runAsBaseRecordingHTTP tr . atAuthToBase tr.trSessAndHeader . flip CreateProject.stripeCheckoutInitH (CreateProject.StripeCheckoutForm "GraduatedPricing") sessionBody reqs = snd <$> find ((== "https://api.stripe.com/v1/checkout/sessions") . fst) reqs - -- First ever upgrade: no customer to reuse, trial granted. + -- First ever upgrade: no customer to reuse, trial granted, and the plan button says so. + (_, LemonSqueezy.BillingGet (PageCtx _ fresh)) <- testServant tr $ LemonSqueezy.manageBillingGetH testPid + renderText (LemonSqueezy.billingPage fresh) `shouldSatisfy` TL.isInfixOf "Start 30 day free trial" (firstReqs, _) <- checkout testPid case sessionBody firstReqs of Nothing -> fail "no checkout session request recorded" @@ -540,28 +547,126 @@ stripeBillingTests = do -- that the cancel reads the OLD sub_id, i.e. that it stays ahead of the write. it "stripe checkout webhook cancels the subscription the project held before" \TestContext{tcResources = tr, tcProjectId = testPid} -> do _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "GraduatedPricing") (Projects.SubId "sub_old") (Projects.SubItemId "si_old") (Projects.CustomerId "cus_test") - now <- getTestTime tr.trTestClock - let body = - BL.toStrict - $ AE.encode - $ AE.object - [ "type" AE..= ("checkout.session.completed" :: Text) - , "data" - AE..= AE.object - [ "object" - AE..= AE.object - [ "client_reference_id" AE..= testPid.toText - , "subscription" AE..= ("sub_new" :: Text) - , "customer" AE..= ("cus_test" :: Text) - ] - ] - ] - ts = show @Text @Integer $ round $ utcTimeToPOSIXSeconds now - mac = HMAC.hmac (encodeUtf8 @Text @ByteString tr.trATCtx.env.stripeWebhookSecret) (encodeUtf8 @Text @ByteString ts <> "." <> body) :: HMAC.HMAC SHA256 - sigHeader = "t=" <> ts <> ",v1=" <> decodeUtf8 (B16.encode $ BA.convert mac) - (reqs, _) <- runAsBaseRecordingHTTP tr $ LemonSqueezy.stripeWebhookPostH (Just sigHeader) body + reqs <- stripeCheckoutCompleted tr testPid [] map fst reqs `shouldContain` ["https://api.stripe.com/v1/subscriptions/sub_old"] + -- Stripe cancels a subscription whose payments keep failing, and a cancelled one can't + -- be revived. Paying the leftover invoice in the portal left the project on Free, so + -- reactivating is one Managed Payments checkout that also carries that invoice + -- (Shipbubble, 2026-10-23: $68.37 open on a sub cancelled 2026-09-29). + it "stripeReactivation_lapsedSubscription_settlesOpenInvoiceAndUpgrades" \TestContext{tcResources = tr, tcProjectId = testPid} -> do + _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "GraduatedPricing") (Projects.SubId "sub_lapsed") (Projects.SubItemId "si_lapsed") (Projects.CustomerId "cus_lapsed") + _ <- runQueryEffect tr $ Projects.downgradeToFreeBySubId "sub_lapsed" + session <- refreshSession tr.trPool tr.trATCtx.hasqlPool tr.trSessAndHeader + -- Checkout withholds a repeat trial, so the button must not promise one. + (_, LemonSqueezy.BillingGet (PageCtx _ lapsed)) <- testServant tr{trSessAndHeader = session} $ LemonSqueezy.manageBillingGetH testPid + renderText (LemonSqueezy.billingPage lapsed) `shouldNotSatisfy` TL.isInfixOf "free trial" + let invoices = AE.encode $ AE.object ["has_more" AE..= True, "data" AE..= ([invoice "in_owed" "open" 6837] :: [AE.Value])] + invoice id' status remaining = AE.object ["id" AE..= (id' :: Text), "currency" AE..= ("usd" :: Text), "status" AE..= (status :: Text), "number" AE..= ("MONO-0003" :: Text), "total" AE..= (6837 :: Int), "amount_remaining" AE..= (remaining :: Int), "period_start" AE..= (1786787328 :: Int), "period_end" AE..= (1789465728 :: Int)] + lapsedInvoices _ url = pure do + guard $ "https://api.stripe.com/v1/invoices?" `T.isPrefixOf` toText url + pure + $ if "starting_after=in_owed" `T.isInfixOf` toText url + then AE.encode $ AE.object ["has_more" AE..= False, "data" AE..= ([invoice "in_older" "open" 100] :: [AE.Value])] + else invoices + (reqs, _) <- runAsBaseRecordingHTTP tr $ withHTTPResponses lapsedInvoices $ atAuthToBase session $ CreateProject.stripeCheckoutInitH testPid (CreateProject.StripeCheckoutForm "GraduatedPricing") + form <- maybe (fail "no checkout session request recorded") (pure . parseSimpleQuery . toStrict . snd) $ find ((== "https://api.stripe.com/v1/checkout/sessions") . fst) reqs + map (`lookup` form) ["line_items[2][price_data][unit_amount]", "line_items[3][price_data][unit_amount]", "line_items[4][price_data][unit_amount]", "metadata[settles_invoices]", "managed_payments[enabled]"] + `shouldBe` ([Just "6837", Just "100", Nothing, Just "in_owed,in_older", Just "true"] :: [Maybe ByteString]) + + paid <- stripeCheckoutCompleted tr testPid [("settles_invoices", "in_owed")] + lookup "https://api.stripe.com/v1/invoices/in_owed/pay" paid `shouldBe` Just "paid_out_of_band=true" + fmap (.paymentPlan) <$> runQueryEffect tr (Projects.projectById testPid) `shouldReturn` Just "GraduatedPricing" + + it "stripeReactivation_invoiceLookupFailure_doesNotCreateACheckoutWithoutTheDebt" \TestContext{tcResources = tr, tcProjectId = testPid} -> do + _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "Free") (Projects.SubId "sub_lapsed") (Projects.SubItemId "si_lapsed") (Projects.CustomerId "cus_test") + session <- refreshSession tr.trPool tr.trATCtx.hasqlPool tr.trSessAndHeader + let unavailable _ url + | "https://api.stripe.com/v1/invoices?" `T.isPrefixOf` toText url = throwIO $ userError "Stripe temporarily unavailable" + | otherwise = pure Nothing + (requests, status) <- + runAsBaseRecordingHTTP tr + $ catchError @ServantS.ServerError + (withHTTPResponses unavailable (atAuthToBase session $ CreateProject.stripeCheckoutInitH testPid (CreateProject.StripeCheckoutForm "GraduatedPricing")) $> 200) + (\_ err -> pure err.errHTTPCode) + status `shouldBe` 503 + map fst requests `shouldNotContain` ["https://api.stripe.com/v1/checkout/sessions"] + + it "stripeReactivation_settlementFailure_requestsRetryAfterTheProjectUpgrade" \TestContext{tcResources = tr, tcProjectId = testPid} -> do + _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "Free") (Projects.SubId "sub_lapsed") (Projects.SubItemId "si_lapsed") (Projects.CustomerId "cus_test") + let obj = AE.object ["client_reference_id" AE..= testPid.toText, "subscription" AE..= ("sub_new" :: Text), "customer" AE..= ("cus_test" :: Text), "payment_status" AE..= ("paid" :: Text), "metadata" AE..= AE.object ["settles_invoices" AE..= ("in_settled,in_owed" :: Text)]] + responses failPayment _ url + | url == "https://api.stripe.com/v1/invoices/in_settled" = pure $ Just "{\"status\":\"paid\"}" + | failPayment && url == "https://api.stripe.com/v1/invoices/in_owed/pay" = throwIO $ userError "Stripe temporarily unavailable" + | otherwise = pure Nothing + (_, failedStatus) <- stripeWebhook tr (responses True) "checkout.session.completed" obj + failedStatus `shouldBe` 503 + fmap (.subId) <$> runQueryEffect tr (Projects.projectById testPid) `shouldReturn` Just (Just "sub_new") + (retried, retryStatus) <- stripeWebhook tr (responses False) "checkout.session.completed" obj + retryStatus `shouldBe` 200 + lookup "https://api.stripe.com/v1/invoices/in_owed/pay" retried `shouldBe` Just "paid_out_of_band=true" + map fst retried `shouldNotContain` ["https://api.stripe.com/v1/subscriptions/sub_new", "https://api.stripe.com/v1/invoices/in_settled/pay"] + + it "stripeReactivation_unpaidCheckout_waitsForThePaymentToSucceed" \TestContext{tcResources = tr, tcProjectId = testPid} -> do + _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "Free") (Projects.SubId "sub_lapsed") (Projects.SubItemId "si_lapsed") (Projects.CustomerId "cus_test") + let checkout status = AE.object ["client_reference_id" AE..= testPid.toText, "subscription" AE..= ("sub_new" :: Text), "customer" AE..= ("cus_test" :: Text), "payment_status" AE..= (status :: Text), "metadata" AE..= AE.object ["settles_invoices" AE..= ("in_owed" :: Text)]] + (unpaidRequests, pendingStatus) <- stripeWebhook tr (\_ _ -> pure Nothing) "checkout.session.completed" (checkout "unpaid") + pendingStatus `shouldBe` 200 + map fst unpaidRequests `shouldNotContain` ["https://api.stripe.com/v1/invoices/in_owed/pay"] + fmap (.paymentPlan) <$> runQueryEffect tr (Projects.projectById testPid) `shouldReturn` Just "Free" + (paid, paidStatus) <- stripeWebhook tr (\_ _ -> pure Nothing) "checkout.session.async_payment_succeeded" (checkout "paid") + paidStatus `shouldBe` 200 + lookup "https://api.stripe.com/v1/invoices/in_owed/pay" paid `shouldBe` Just "paid_out_of_band=true" + fmap (.paymentPlan) <$> runQueryEffect tr (Projects.projectById testPid) `shouldReturn` Just "GraduatedPricing" + + -- Dunning that ends at `unpaid` keeps the subscription: paying its invoice by any route + -- (hosted link, email, portal) makes Stripe flip it back to `active`, and only + -- customer.subscription.updated says so — the project must follow both ways. + it "stripeDunning_unpaidThenPaidAnywhere_followsSubscriptionStatus" \TestContext{tcResources = tr, tcProjectId = testPid} -> do + _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "GraduatedPricing") (Projects.SubId "sub_dun") (Projects.SubItemId "si_dun") (Projects.CustomerId "cus_dun") + let plan = fmap (.paymentPlan) <$> runQueryEffect tr (Projects.projectById testPid) + sub status = AE.object ["id" AE..= ("sub_dun" :: Text), "status" AE..= (status :: Text), "items" AE..= AE.object ["data" AE..= ([AE.object ["id" AE..= ("si_dun" :: Text), "price" AE..= AE.object ["id" AE..= ("price_graduated" :: Text)]]] :: [AE.Value])]] + _ <- stripeWebhook tr (\_ _ -> pure Nothing) "customer.subscription.updated" (sub "unpaid") + plan `shouldReturn` Just "Free" + _ <- stripeWebhook tr (\_ _ -> pure Nothing) "customer.subscription.updated" (sub "active") + plan `shouldReturn` Just "GraduatedPricing" + + -- A sub Stripe already cancelled can't come back, so paying its leftover invoice outside + -- our checkout must not pretend to reactivate; the payer is pointed back at checkout. + it "stripeInvoicePaid_cancelledSubscription_staysFree" \TestContext{tcResources = tr, tcProjectId = testPid} -> do + _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "GraduatedPricing") (Projects.SubId "sub_gone") (Projects.SubItemId "si_gone") (Projects.CustomerId "cus_gone") + _ <- runQueryEffect tr $ Projects.downgradeToFreeBySubId "sub_gone" + let cancelled _ url = pure $ AE.encode (AE.object ["status" AE..= ("canceled" :: Text), "items" AE..= AE.object ["data" AE..= ([AE.object ["id" AE..= ("si_gone" :: Text), "price" AE..= AE.object ["id" AE..= ("price_graduated" :: Text)]]] :: [AE.Value])]]) <$ guard (url == "https://api.stripe.com/v1/subscriptions/sub_gone") + (reqs, status) <- stripeWebhook tr cancelled "invoice.paid" $ AE.object ["id" AE..= ("in_gone" :: Text), "customer" AE..= ("cus_gone" :: Text), "parent" AE..= AE.object ["subscription_details" AE..= AE.object ["subscription" AE..= ("sub_gone" :: Text)]]] + status `shouldBe` 200 + map fst reqs `shouldContain` ["https://api.stripe.com/v1/subscriptions/sub_gone"] + fmap (.paymentPlan) <$> runQueryEffect tr (Projects.projectById testPid) `shouldReturn` Just "Free" + + +-- | Deliver a signed checkout.session.completed for @pid@ (new sub @sub_new@) carrying +-- the given session metadata; returns the outgoing Stripe requests. +stripeCheckoutCompleted :: TestResources -> Projects.ProjectId -> [(AE.Key, Text)] -> IO [(Text, LByteString)] +stripeCheckoutCompleted tr pid metadata = do + (requests, status) <- + stripeWebhook tr (\_ _ -> pure Nothing) "checkout.session.completed" + $ AE.object ["client_reference_id" AE..= pid.toText, "subscription" AE..= ("sub_new" :: Text), "customer" AE..= ("cus_test" :: Text), "payment_status" AE..= ("paid" :: Text), "metadata" AE..= AE.object (map (fmap AE.toJSON) metadata)] + status `shouldBe` 200 + pure requests + + +-- | Deliver a signed Stripe event of @eventType@ wrapping @obj@, answering Stripe calls from +-- @responses@; returns the outgoing Stripe requests and HTTP status. +stripeWebhook :: TestResources -> (Options -> String -> IO (Maybe LByteString)) -> Text -> AE.Value -> IO ([(Text, LByteString)], Int) +stripeWebhook tr responses eventType obj = do + let appCtx = tr.trATCtx + isolated = tr{trATCtx = appCtx{System.Config.config = appCtx.config{System.Config.smtpHost = "127.0.0.1", System.Config.smtpPort = 1, System.Config.smtpUsername = "", System.Config.smtpPassword = "", System.Config.postmarkToken = ""}}} + now <- getTestTime tr.trTestClock + let body = toStrict $ AE.encode $ AE.object ["type" AE..= eventType, "data" AE..= AE.object ["object" AE..= obj]] + ts = show @Text @Integer $ round $ utcTimeToPOSIXSeconds now + mac = HMAC.hmac (encodeUtf8 @Text @ByteString tr.trATCtx.env.stripeWebhookSecret) (encodeUtf8 @Text @ByteString ts <> "." <> body) :: HMAC.HMAC SHA256 + sigHeader = "t=" <> ts <> ",v1=" <> decodeUtf8 (B16.encode $ BA.convert mac) + runAsBaseRecordingHTTP isolated $ catchError @ServantS.ServerError (withHTTPResponses (\opts url -> (<|> ("{\"status\":\"open\"}" <$ guard ("https://api.stripe.com/v1/invoices/" `T.isPrefixOf` toText url))) <$> responses opts url) (LemonSqueezy.stripeWebhookPostH (Just sigHeader) body) $> 200) (\_ err -> pure err.errHTTPCode) + -- | LemonSqueezy Webhook Tests - Table-driven testing for all webhook events lemonSqueezyWebhookTests :: SpecWith TestContext diff --git a/tests/golden/https___api.stripe.com_v1_invoices_limit=12_subscription=sub_test123_get_with.json b/tests/golden/https___api.stripe.com_v1_invoices_limit=12_subscription=sub_test123_get_with.json index 87858fe59..733eae19c 100644 --- a/tests/golden/https___api.stripe.com_v1_invoices_limit=12_subscription=sub_test123_get_with.json +++ b/tests/golden/https___api.stripe.com_v1_invoices_limit=12_subscription=sub_test123_get_with.json @@ -1,7 +1,7 @@ { "statusCode": 200, "statusMessage": "OK", - "respBody": "{\"object\": \"list\", \"data\": [{\"object\": \"invoice\", \"number\": null, \"status\": \"draft\", \"total\": 4150, \"amount_paid\": 0, \"period_start\": 1710498600, \"period_end\": 1713177000, \"hosted_invoice_url\": null, \"lines\": {\"data\": [{\"description\": \"1 x Graduated\", \"period\": {\"start\": 1710498600, \"end\": 1713177000}}]}}, {\"object\": \"invoice\", \"number\": \"MONO-0002\", \"status\": \"paid\", \"total\": 3400, \"amount_paid\": 3400, \"period_start\": 1707993000, \"period_end\": 1710498600, \"hosted_invoice_url\": \"https://invoice.stripe.com/i/inv_two\", \"lines\": {\"data\": [{\"description\": \"1 x Graduated\", \"period\": {\"start\": 1707993000, \"end\": 1710498600}}]}}, {\"object\": \"invoice\", \"number\": \"MONO-0001\", \"status\": \"paid\", \"total\": 2900, \"amount_paid\": 2900, \"period_start\": 1705314600, \"period_end\": 1707993000, \"hosted_invoice_url\": \"https://invoice.stripe.com/i/inv_one\", \"lines\": {\"data\": [{\"description\": \"1 x Graduated\", \"period\": {\"start\": 1705314600, \"end\": 1707993000}}]}}, {\"object\": \"invoice\", \"number\": \"MONO-0000\", \"status\": \"paid\", \"total\": 0, \"amount_paid\": 0, \"period_start\": 1705314600, \"period_end\": 1705314600, \"hosted_invoice_url\": \"https://invoice.stripe.com/i/inv_zero\", \"lines\": {\"data\": [{\"description\": \"Trial start\", \"period\": {\"start\": 1705314600, \"end\": 1705314600}}]}}]}", + "respBody": "{\"object\":\"list\",\"data\":[{\"object\":\"invoice\",\"currency\":\"usd\",\"id\":\"in_draft\",\"number\":null,\"status\":\"draft\",\"total\":4150,\"amount_paid\":0,\"period_start\":1710498600,\"period_end\":1713177000,\"hosted_invoice_url\":null,\"lines\":{\"data\":[{\"description\":\"1 x Graduated\",\"period\":{\"start\":1710498600,\"end\":1713177000}}]},\"amount_remaining\":4150},{\"object\":\"invoice\",\"currency\":\"usd\",\"number\":\"MONO-0002\",\"status\":\"paid\",\"total\":3400,\"amount_paid\":3400,\"period_start\":1707993000,\"period_end\":1710498600,\"id\":\"in_two\",\"hosted_invoice_url\":\"https://invoice.stripe.com/i/inv_two\",\"lines\":{\"data\":[{\"description\":\"1 x Graduated\",\"period\":{\"start\":1707993000,\"end\":1710498600}}]},\"amount_remaining\":0},{\"object\":\"invoice\",\"currency\":\"usd\",\"number\":\"MONO-0001\",\"status\":\"paid\",\"total\":2900,\"amount_paid\":2900,\"period_start\":1705314600,\"period_end\":1707993000,\"id\":\"in_one\",\"hosted_invoice_url\":\"https://invoice.stripe.com/i/inv_one\",\"lines\":{\"data\":[{\"description\":\"1 x Graduated\",\"period\":{\"start\":1705314600,\"end\":1707993000}}]},\"amount_remaining\":0},{\"object\":\"invoice\",\"currency\":\"usd\",\"number\":\"MONO-0000\",\"status\":\"paid\",\"total\":0,\"amount_paid\":0,\"period_start\":1705314600,\"period_end\":1705314600,\"id\":\"in_zero\",\"hosted_invoice_url\":\"https://invoice.stripe.com/i/inv_zero\",\"lines\":{\"data\":[{\"description\":\"Trial start\",\"period\":{\"start\":1705314600,\"end\":1705314600}}]},\"amount_remaining\":0}]}", "responseHeaders": [ [ "Content-Type", @@ -10,4 +10,4 @@ ], "originalRequest": "", "responseEarlyHints": [] -} \ No newline at end of file +} diff --git a/web-components/package-lock.json b/web-components/package-lock.json index d547c6496..a6e0139d7 100644 --- a/web-components/package-lock.json +++ b/web-components/package-lock.json @@ -29,7 +29,7 @@ "date-fns": "^4.3.0", "echarts": "^6.1.0", "elkjs": "^0.12.0", - "js-yaml": "^4.2.0", + "js-yaml": "^4.3.2", "jsonpath": "^1.3.0", "lit": "^3.3.3", "lodash": "^4.17.23", @@ -37,18 +37,18 @@ "vite": "^8.0.16" }, "devDependencies": { - "@types/bun": "^1.3.14", + "@types/bun": "^1.4.0", "@types/js-yaml": "^4.0.9", "@types/jsonpath": "^0.2.4", "@types/node": "^25.9.1", - "@vitest/browser": "^4.1.8", - "happy-dom": "^20.7.0", + "@vitest/browser": "^4.1.11", + "happy-dom": "^20.14.0", "jsdom": "^29.1.1", "typescript": "^6.0.3", "vite-plugin-monaco-editor": "^1.1.0", "vite-plugin-node-polyfills": "^0.28.0", - "vitest": "^4.0.16", - "vitest-canvas-mock": "^1.1.4" + "vitest": "^4.1.11", + "vitest-canvas-mock": "^1.1.5" } }, "node_modules/@asamuzakjp/css-color": { @@ -1973,13 +1973,13 @@ } }, "node_modules/@types/bun": { - "version": "1.3.14", - "resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.3.14.tgz", - "integrity": "sha512-h1hFqFVcvAvD9j9K7ZW7vd82aSA+rTdznZa+5bwvCwqSB1jmmfLcbIWhOLx1/+boy/xmjgCs/OMUL8hRJSmnPw==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.4.0.tgz", + "integrity": "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ==", "dev": true, "license": "MIT", "dependencies": { - "bun-types": "1.3.14" + "bun-types": "1.4.0" } }, "node_modules/@types/chai": { @@ -2111,15 +2111,15 @@ } }, "node_modules/@vitest/browser": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/browser/-/browser-4.1.8.tgz", - "integrity": "sha512-u21VzX07HzlJYpFgkxmjEXar/tG2UqWGgyGG/46SrrPc7rSdCTPw5vuowopO9CIqF8UCUQzDFdbVnNpw6N0BfQ==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/browser/-/browser-4.1.11.tgz", + "integrity": "sha512-bwMovvAeuTFOK5kIFevw4VEf+1gVEICv4SYK4k3knJOxl6b1zEWud8mYKD73e1B0odAn174h1MofURy2TPWf3w==", "dev": true, "license": "MIT", "dependencies": { "@blazediff/core": "1.9.1", - "@vitest/mocker": "4.1.8", - "@vitest/utils": "4.1.8", + "@vitest/mocker": "4.1.11", + "@vitest/utils": "4.1.11", "magic-string": "^0.30.21", "pngjs": "^7.0.0", "sirv": "^3.0.2", @@ -2130,20 +2130,20 @@ "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "vitest": "4.1.8" + "vitest": "4.1.11" } }, "node_modules/@vitest/expect": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.8.tgz", - "integrity": "sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", + "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", "dev": true, "license": "MIT", "dependencies": { "@standard-schema/spec": "^1.1.0", "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.8", - "@vitest/utils": "4.1.8", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", "chai": "^6.2.2", "tinyrainbow": "^3.1.0" }, @@ -2152,13 +2152,13 @@ } }, "node_modules/@vitest/mocker": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.8.tgz", - "integrity": "sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", + "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/spy": "4.1.8", + "@vitest/spy": "4.1.11", "estree-walker": "^3.0.3", "magic-string": "^0.30.21" }, @@ -2189,9 +2189,9 @@ } }, "node_modules/@vitest/pretty-format": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.8.tgz", - "integrity": "sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", + "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", "dev": true, "license": "MIT", "dependencies": { @@ -2202,13 +2202,13 @@ } }, "node_modules/@vitest/runner": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.8.tgz", - "integrity": "sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", + "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/utils": "4.1.8", + "@vitest/utils": "4.1.11", "pathe": "^2.0.3" }, "funding": { @@ -2216,14 +2216,14 @@ } }, "node_modules/@vitest/snapshot": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.8.tgz", - "integrity": "sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", + "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.8", - "@vitest/utils": "4.1.8", + "@vitest/pretty-format": "4.1.11", + "@vitest/utils": "4.1.11", "magic-string": "^0.30.21", "pathe": "^2.0.3" }, @@ -2232,9 +2232,9 @@ } }, "node_modules/@vitest/spy": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.8.tgz", - "integrity": "sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", + "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", "dev": true, "license": "MIT", "funding": { @@ -2242,13 +2242,13 @@ } }, "node_modules/@vitest/utils": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.8.tgz", - "integrity": "sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", + "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.8", + "@vitest/pretty-format": "4.1.11", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" }, @@ -2642,6 +2642,19 @@ "ieee754": "^1.1.13" } }, + "node_modules/buffer-image-size": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/buffer-image-size/-/buffer-image-size-0.6.4.tgz", + "integrity": "sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + }, + "engines": { + "node": ">=4.0" + } + }, "node_modules/buffer-xor": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/buffer-xor/-/buffer-xor-1.0.3.tgz", @@ -2655,9 +2668,9 @@ "dev": true }, "node_modules/bun-types": { - "version": "1.3.14", - "resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.3.14.tgz", - "integrity": "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.4.0.tgz", + "integrity": "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q==", "dev": true, "license": "MIT", "dependencies": { @@ -3435,18 +3448,19 @@ } }, "node_modules/happy-dom": { - "version": "20.9.0", - "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.9.0.tgz", - "integrity": "sha512-GZZ9mKe8r646NUAf/zemnGbjYh4Bt8/MqASJY+pSm5ZDtc3YQox+4gsLI7yi1hba6o+eCsGxpHn5+iEVn31/FQ==", + "version": "20.14.0", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.14.0.tgz", + "integrity": "sha512-4bRh1KzRvKDnFNTlLhzT1RZTpkKhQbQDl9j+7GXszWsvuspYdo29k6OHRf4PwiM6oLb8r/pMWeYiJjkfod5AvQ==", "dev": true, "license": "MIT", "dependencies": { "@types/node": ">=20.0.0", "@types/whatwg-mimetype": "^3.0.2", "@types/ws": "^8.18.1", + "buffer-image-size": "^0.6.4", "entities": "^7.0.1", "whatwg-mimetype": "^3.0.0", - "ws": "^8.18.3" + "ws": "^8.21.0" }, "engines": { "node": ">=20.0.0" @@ -3748,9 +3762,9 @@ } }, "node_modules/js-yaml": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz", - "integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==", + "version": "4.3.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.2.tgz", + "integrity": "sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==", "funding": [ { "type": "github", @@ -6693,19 +6707,19 @@ } }, "node_modules/vitest": { - "version": "4.1.8", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.8.tgz", - "integrity": "sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==", + "version": "4.1.11", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", + "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/expect": "4.1.8", - "@vitest/mocker": "4.1.8", - "@vitest/pretty-format": "4.1.8", - "@vitest/runner": "4.1.8", - "@vitest/snapshot": "4.1.8", - "@vitest/spy": "4.1.8", - "@vitest/utils": "4.1.8", + "@vitest/expect": "4.1.11", + "@vitest/mocker": "4.1.11", + "@vitest/pretty-format": "4.1.11", + "@vitest/runner": "4.1.11", + "@vitest/snapshot": "4.1.11", + "@vitest/spy": "4.1.11", + "@vitest/utils": "4.1.11", "es-module-lexer": "^2.0.0", "expect-type": "^1.3.0", "magic-string": "^0.30.21", @@ -6733,12 +6747,12 @@ "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.8", - "@vitest/browser-preview": "4.1.8", - "@vitest/browser-webdriverio": "4.1.8", - "@vitest/coverage-istanbul": "4.1.8", - "@vitest/coverage-v8": "4.1.8", - "@vitest/ui": "4.1.8", + "@vitest/browser-playwright": "4.1.11", + "@vitest/browser-preview": "4.1.11", + "@vitest/browser-webdriverio": "4.1.11", + "@vitest/coverage-istanbul": "4.1.11", + "@vitest/coverage-v8": "4.1.11", + "@vitest/ui": "4.1.11", "happy-dom": "*", "jsdom": "*", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" @@ -6783,9 +6797,9 @@ } }, "node_modules/vitest-canvas-mock": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/vitest-canvas-mock/-/vitest-canvas-mock-1.1.4.tgz", - "integrity": "sha512-4boWHY+STwAxGl1+uwakNNoQky5EjPLC8HuponXNoAscYyT1h/F7RUvTkl4IyF/MiWr3V8Q626je3Iel3eArqA==", + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/vitest-canvas-mock/-/vitest-canvas-mock-1.1.5.tgz", + "integrity": "sha512-PWtzolkO/GsG9I9qsLxJ8HzdXQKNz1iRVUcCDJbNBiDuxMp50NC1MWwz2UmDYS4vJqNeKyoLWm7RgjfKWIoQOQ==", "dev": true, "license": "MIT", "dependencies": { @@ -6912,9 +6926,9 @@ } }, "node_modules/ws": { - "version": "8.20.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.20.0.tgz", - "integrity": "sha512-sAt8BhgNbzCtgGbt2OxmpuryO63ZoDk/sqaB/znQm94T4fCEsy/yV+7CdC1kJhOU9lboAEU7R3kquuycDoibVA==", + "version": "8.21.3", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", + "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", "dev": true, "license": "MIT", "engines": { diff --git a/web-components/package.json b/web-components/package.json index 41f385fc5..6a8161c0d 100644 --- a/web-components/package.json +++ b/web-components/package.json @@ -42,7 +42,7 @@ "date-fns": "^4.3.0", "echarts": "^6.1.0", "elkjs": "^0.12.0", - "js-yaml": "^4.2.0", + "js-yaml": "^4.3.2", "jsonpath": "^1.3.0", "lit": "^3.3.3", "lodash": "^4.17.23", @@ -50,18 +50,18 @@ "vite": "^8.0.16" }, "devDependencies": { - "@types/bun": "^1.3.14", + "@types/bun": "^1.4.0", "@types/js-yaml": "^4.0.9", "@types/jsonpath": "^0.2.4", "@types/node": "^25.9.1", - "@vitest/browser": "^4.1.8", - "happy-dom": "^20.7.0", + "@vitest/browser": "^4.1.11", + "happy-dom": "^20.14.0", "jsdom": "^29.1.1", "typescript": "^6.0.3", "vite-plugin-monaco-editor": "^1.1.0", "vite-plugin-node-polyfills": "^0.28.0", - "vitest": "^4.0.16", - "vitest-canvas-mock": "^1.1.4" + "vitest": "^4.1.11", + "vitest-canvas-mock": "^1.1.5" }, "overrides": { "dompurify": "^3.3.2", diff --git a/web-components/src/log-list.ts b/web-components/src/log-list.ts index 15033dee7..9f3165854 100644 --- a/web-components/src/log-list.ts +++ b/web-components/src/log-list.ts @@ -3955,7 +3955,7 @@ export class LogList extends LitElement { parts.push(content); }; - if (user) add(html`${user}`); + if (user) add(html`${user}`); if (url) { // Middle-truncate: keep the last path segment visible since it usually // identifies the page ("/checkout/cart" is more useful than "/api/v2/…"). From f2a7d9658a45d7e6681db3938e07971f18c8b2ef Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Sun, 25 Oct 2026 19:38:51 +0100 Subject: [PATCH 006/203] Allow promotion codes at Stripe checkout (#716) * Allow promotion codes at Stripe checkout * Keep positive rates off 0.0% whatever showFFloat's rounding fmtPct1 promised positive rates never round to zero, but its 0.05 threshold assumed half-up rounding; showFFloat rounds half to even, so 0.05 rendered 0.0% and the doctest from #713 failed. Key on the rendered text instead. --- src/Pages/LogExplorer/Log.hs | 9 +++++---- src/Pages/Settings.hs | 1 + test/integration/Pages/BusinessFlowsSpec.hs | 1 + 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/Pages/LogExplorer/Log.hs b/src/Pages/LogExplorer/Log.hs index 878c30142..4f9256b18 100644 --- a/src/Pages/LogExplorer/Log.hs +++ b/src/Pages/LogExplorer/Log.hs @@ -1133,12 +1133,13 @@ lookupAlert = maybe (pure Nothing) (Monitors.queryMonitorById . Monitors.QueryMo -- | One-decimal percent formatter; positive rates never round down to zero. -- -- >>> import "monoscope" Pages.LogExplorer.Log qualified as LL --- >>> map LL.fmtPct1 [0, 0.03, 0.05, 5.24, 100, -1.25] +-- >>> map LL.fmtPct1 [0, 0.03, 0.06, 5.24, 100, -1.25] -- ["0.0%","<0.1%","0.1%","5.2%","100.0%","-1.2%"] fmtPct1 :: Double -> Text -fmtPct1 x - | x > 0 && x < 0.05 = "<0.1%" - | otherwise = showFFloat' 1 x <> "%" +fmtPct1 x = bool shown "<0.1%" (x > 0 && shown == "0.0%") + where + -- Keyed on the rendered text, not a threshold: showFFloat rounds half to even, so 0.05 shows 0.0. + shown = showFFloat' 1 x <> "%" -- | Shimmer placeholder mirroring 'sessionsHeader_' (6-KPI grid + over-time bar diff --git a/src/Pages/Settings.hs b/src/Pages/Settings.hs index c85390e8f..10e08ba25 100644 --- a/src/Pages/Settings.hs +++ b/src/Pages/Settings.hs @@ -1598,6 +1598,7 @@ createStripeCheckoutSession trialEligible customerM debts apiKey hostUrl pid pla <> managedPaymentsParams <> [("customer", encodeUtf8 c) | c <- maybeToList customerM] <> [ ("mode", "subscription") + , ("allow_promotion_codes", "true") , ("client_reference_id", encodeUtf8 pid.toText) , ("metadata[project_id]", encodeUtf8 pid.toText) , ("metadata[plan]", encodeUtf8 plan) diff --git a/test/integration/Pages/BusinessFlowsSpec.hs b/test/integration/Pages/BusinessFlowsSpec.hs index 2896d19e5..f37e86460 100644 --- a/test/integration/Pages/BusinessFlowsSpec.hs +++ b/test/integration/Pages/BusinessFlowsSpec.hs @@ -531,6 +531,7 @@ stripeBillingTests = do Just b -> do decodeUtf8 @Text b `shouldSatisfy` T.isInfixOf "trial_period_days" decodeUtf8 @Text b `shouldNotSatisfy` T.isInfixOf "customer=" + decodeUtf8 @Text b `shouldSatisfy` T.isInfixOf "allow_promotion_codes=true" -- Once that buyer has any billing history, a further checkout reuses their -- customer and withholds the trial — this is what a second project now hits. From ba59c123d75cfdd26cb0949f6de2ee44e3a9a0ed Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Sun, 25 Oct 2026 21:18:02 +0100 Subject: [PATCH 007/203] Ack capped OTLP payloads instead of dead-lettering them (#714) * Ack capped OTLP payloads instead of dead-lettering them A payload whose every project resolved but is over the free-tier cap converts to zero rows by design. The unresolved-project guard treated it as lost data and sent it to the DLQ, which redelivered it through every retry tier: ~10k attention logs an hour since the cap started tripping on 2026-10-22. Unresolved keys still DLQ. * Dead-letter capped payloads that also name an unresolved key Review follow-up: a zero-row payload is a deliberate drop only when every key it names resolved and every project is capped; a mixed payload is lost data again. * Dead-letter any payload naming an unresolved API key Simpler and general: one unresolved key poisons the whole payload, so a payload mixing it with a capped (or any resolved) key no longer loses the unresolved part. Rows left out on purpose come from resolved keys and are acked. * Pin the 0.05 case and say why only API keys can fail to resolve Review follow-ups: fmtPct1's doctest keeps the half-to-even 0.05 case it exists for; the poison comment is trimmed to its invariant and notes that at-project-ids always get a cache. * Keep the zero-rows safety net for uncapped projects and check at-project-ids Review follow-ups: a payload is dead-lettered when it names an unresolved key or an at-project-id with no cache, or converts to zero rows unless every project it names is capped; only deliberate cap drops are acked. * State the ack condition once: every project resolved, and rows or a cap Review follow-up: traverse the key lookups instead of comparing lengths. --- src/Opentelemetry/OtlpServer.hs | 18 +++++++----------- src/Pages/LogExplorer/Log.hs | 4 ++-- .../BackgroundJobs/ReportUsageSpec.hs | 17 ++++++++++++++++- 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/src/Opentelemetry/OtlpServer.hs b/src/Opentelemetry/OtlpServer.hs index d17beb03c..b49c3a225 100644 --- a/src/Opentelemetry/OtlpServer.hs +++ b/src/Opentelemetry/OtlpServer.hs @@ -462,18 +462,14 @@ processBatchPipeline !label msgs appCtx fallbackTime extractKeys extractIds inva !checked = [(ackId, raw, req, invalidReason req) | (ackId, raw, Right req) <- decodedMsgs] !invalidPoison = [(ackId, raw, err) | (ackId, raw, _, Just err) <- checked] !converted = [(ackId, raw, req, convert fallbackTime projectCachesMap keyToIdMap req) | (ackId, raw, req, Nothing) <- checked] - -- "Converted to zero rows" is NOT proof there was nothing to write. - -- A payload that carried an API key or an at-project-id but produced no - -- rows was DROPPED: its project never resolved (a cached negative entry, - -- a key racing its own creation, a lookup that returned no rows). Acking - -- that commits the offset and destroys the data with no DLQ entry — the - -- 2026-07-27 loss (~200k rows / 10 tenants / 9 min, zero failure signal - -- anywhere in the pipeline). Route it to the DLQ so the bytes survive. + -- DLQ, never ack, a payload naming an unresolved project, or one converting to zero rows + -- unless every project it names is capped (2026-07-27: an ack lost ~200k rows). !dropPoison = - [ (ackId, raw, "unresolved project: payload carried telemetry but converted to zero rows") + [ (ackId, raw, "unresolved project: payload carried telemetry but did not resolve or convert") | (ackId, raw, req, recs) <- converted - , V.null recs - , not (V.null (extractKeys req)) || not (null (extractIds req)) + , let accounted pids = all (`HM.member` projectCachesMap) pids && (not (V.null recs) || all capped pids) + capped p = any overFreeTierQuota (HM.lookup p projectCachesMap) + , not $ maybe False (accounted . (<> extractIds req)) (traverse (`HM.lookup` keyToIdMap) (V.toList (extractKeys req))) ] !dropAckIds = HS.fromList [ackId | (ackId, _, _) <- dropPoison] !writeReady = [(ackId, raw, recs) | (ackId, raw, _, recs) <- converted, not (HS.member ackId dropAckIds)] @@ -484,7 +480,7 @@ processBatchPipeline !label msgs appCtx fallbackTime extractKeys extractIds inva forM_ (decodePoison <> invalidPoison) \(_, raw, err) -> recordProtoError label (toString err) raw unless (null dropPoison) $ Log.logAttention - "processList: payload carried telemetry but resolved to zero rows — routing to DLQ instead of acking" + "processList: payload did not resolve or converted to zero rows — routing to DLQ instead of acking" (AE.object ["label" AE..= label, "dropped_messages" AE..= length dropPoison, "ack_ids" AE..= [a | (a, _, _) <- dropPoison]]) if allEmpty diff --git a/src/Pages/LogExplorer/Log.hs b/src/Pages/LogExplorer/Log.hs index 4f9256b18..654716a09 100644 --- a/src/Pages/LogExplorer/Log.hs +++ b/src/Pages/LogExplorer/Log.hs @@ -1133,8 +1133,8 @@ lookupAlert = maybe (pure Nothing) (Monitors.queryMonitorById . Monitors.QueryMo -- | One-decimal percent formatter; positive rates never round down to zero. -- -- >>> import "monoscope" Pages.LogExplorer.Log qualified as LL --- >>> map LL.fmtPct1 [0, 0.03, 0.06, 5.24, 100, -1.25] --- ["0.0%","<0.1%","0.1%","5.2%","100.0%","-1.2%"] +-- >>> map LL.fmtPct1 [0, 0.03, 0.05, 0.06, 5.24, 100, -1.25] +-- ["0.0%","<0.1%","<0.1%","0.1%","5.2%","100.0%","-1.2%"] fmtPct1 :: Double -> Text fmtPct1 x = bool shown "<0.1%" (x > 0 && shown == "0.0%") where diff --git a/test/integration/BackgroundJobs/ReportUsageSpec.hs b/test/integration/BackgroundJobs/ReportUsageSpec.hs index 5e359741a..045ef78b9 100644 --- a/test/integration/BackgroundJobs/ReportUsageSpec.hs +++ b/test/integration/BackgroundJobs/ReportUsageSpec.hs @@ -10,8 +10,9 @@ module BackgroundJobs.ReportUsageSpec (spec) where -- thing and re-submit chunks that already succeeded. import BackgroundJobs qualified -import Control.Lens ((^.)) +import Control.Lens (_1, (%~), (^.)) import Data.Cache qualified as Cache +import Data.HashMap.Strict qualified as HM import Data.List qualified as L import Data.Pool (withResource) import Data.ProtoLens (decodeMessage, encodeMessage) @@ -537,6 +538,20 @@ spec = around (\f -> withTestResources \tr -> createTestProject tr "report-usage Cache.purge tr.trATCtx.projectCache ingestLog tr key "over the cap" frozenTime logCount tr pid `shouldReturn` 1 + -- Capped data is dropped and acked, not dead-lettered as an unresolved project: that + -- misclassification looped ~10k capped messages/hour through the DLQ tiers (2026-10-22). + -- An unresolved key still is: those bytes are a customer's data with nowhere to land yet. + -- So is a payload mixing the capped key with an unresolved one, and zero rows from a + -- project that is not capped. + uncappedKey <- createTestProject tr "uncapped" >>= \p -> createTestAPIKey tr p "uncapped-key" + let logs k = createOtelLogAtTime k ["capped?"] frozenTime + mixed = logs key & LSF.resourceLogs %~ (<> (logs "no-such-key" ^. LSF.resourceLogs)) + Right (acks, poison) <- + runTestBg frozenTime tr + $ OtlpServer.processList + [("capped-ack", encodeMessage $ logs key), ("unknown-ack", encodeMessage $ logs "no-such-key"), ("mixed-ack", encodeMessage mixed), ("empty-ack", encodeMessage $ createOtelLogAtTime uncappedKey [] frozenTime)] + (HM.singleton "ce-type" "org.opentelemetry.otlp.logs.v1") + (acks, map (^. _1) poison) `shouldBe` (["capped-ack"], ["unknown-ack", "mixed-ack", "empty-ack"]) Right body <- OtlpServer.httpLogsExport tr.trLogger tr.trATCtx tr.trTracerProvider (Just key) (encodeMessage $ createOtelLogAtTime key ["rejected"] frozenTime) Right (res :: LS.ExportLogsServiceResponse) <- pure $ decodeMessage body From 8ee005927d86770d9a32d21cc37c2cfc20ade2c8 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Sun, 25 Oct 2026 22:38:10 +0100 Subject: [PATCH 008/203] Sample free-tier ingest across the day instead of cutting off at the cap (#715) * Sample free-tier ingest across the day instead of cutting off at the cap A capped project used to keep everything until 10k events, then nothing until 00:00 UTC. Now each pool keeps with probability (budget left) / (traffic still expected today), paced from yesterday's hourly shape or the last hour's rate, with 20% of the budget reserved for errors. Decisions hash the trace id (or record id, or metric series), so a kept trace or series stays whole; kept spans and logs carry attributes.monoscope.sample_weight. Counters live in projects.ingest_sampling. Past 1.2x the budget nothing is kept and the OTLP edge rejects with partial success, as before. The banner, notices and emails say 'sampled' instead of 'dropped'. count() does not yet sum weights; that touches KQL compilation, rollups and monitors. * Key free-tier sampling by project text and keep pacing policy pure Review follow-ups: uncapped records in a mixed batch cost one lookup; metrics reuse metricSeriesId as the series key; the error reserve and ceiling move into Pkg.Sampling.rates with doctests. * Keep error traces whole and make sampling counters best-effort Review follow-ups for free-tier sampling: - a key with any error in the batch is judged at the error rate, so a trace with an error span is kept or dropped whole - a counter write failure is logged, not thrown, so it cannot fail the ingest batch - counters are one row per (project, hour, is_error) with seen/kept, halving the schema, the tally SQL and SampleCounts; an hour index serves the daily cleanup - Pkg.Sampling.rates also takes the hourly meter, so both caps live in one pure place; ceiling is renamed hardCap - the weight is stamped with the module's lodashMerge pattern - tests: error traces kept whole while the rest is thinned, metric series kept whole * Cheaper weight stamp, documented per-batch wholeness, clearer DLQ guard Review follow-ups: stamp the weight into the monoscope key only; note that trace wholeness and pacing are per batch / approximate; doctest an exhausted error reserve; drop the magic hash range; name the resolved projects in the DLQ guard. --- monoscope.cabal | 3 + src/BackgroundJobs.hs | 22 +++-- src/Models/Projects/Projects.hs | 65 +++++++++++- src/Models/Telemetry/Telemetry.hs | 1 + src/Opentelemetry/OtlpServer.hs | 40 ++++---- src/Pages/BodyWrapper.hs | 2 +- src/Pkg/EmailTemplates.hs | 18 ++-- src/Pkg/Metrics.hs | 9 +- src/Pkg/Sampling.hs | 99 +++++++++++++++++++ src/ProcessMessage.hs | 85 ++++++++++++++-- src/Utils.hs | 25 ++--- static/migrations/0254_ingest_sampling.sql | 11 +++ .../BackgroundJobs/ReportUsageSpec.hs | 61 +++++++++++- 13 files changed, 374 insertions(+), 67 deletions(-) create mode 100644 src/Pkg/Sampling.hs create mode 100644 static/migrations/0254_ingest_sampling.sql diff --git a/monoscope.cabal b/monoscope.cabal index 379e44720..3fabfca8b 100644 --- a/monoscope.cabal +++ b/monoscope.cabal @@ -268,6 +268,7 @@ extra-source-files: static/migrations/0251_project_memory_paths.sql static/migrations/0252_project_memory_page_identity.sql static/migrations/0253_project_memory_legacy_writes.sql + static/migrations/0254_ingest_sampling.sql test/fixtures/github-app-test.pem test/fixtures/wiki-browser.mjs static/public/assets/web-components/dist/manifest.json @@ -411,6 +412,7 @@ library Pkg.Prometheus Pkg.QueryCache Pkg.Queue + Pkg.Sampling Pkg.SchemaLearning.Catalog Pkg.SchemaLearning.Hot Pkg.SchemaLearning.Worker @@ -1054,6 +1056,7 @@ test-suite test-dev Pkg.Prometheus Pkg.QueryCache Pkg.Queue + Pkg.Sampling Pkg.SchemaLearning.Catalog Pkg.SchemaLearning.Hot Pkg.SchemaLearning.Worker diff --git a/src/BackgroundJobs.hs b/src/BackgroundJobs.hs index 79efbc7c7..f5ddc7317 100644 --- a/src/BackgroundJobs.hs +++ b/src/BackgroundJobs.hs @@ -1406,6 +1406,8 @@ runHourlyJob scheduledTime hour = do QueryCache.cleanupExpiredCache >>= logDeleted "Cleaned up expired query cache entries" Hasql.interpExecute [HI.sql| DELETE FROM users.device_auth_codes WHERE expires_at < now() - interval '1 hour' |] >>= logDeleted "Cleaned up expired device auth codes" Hasql.interpExecute [HI.sql| DELETE FROM otel_metrics_meta WHERE last_seen_at < now() - interval '3 months' |] >>= logDeleted "Cleaned up stale metrics metadata" + -- Pacing reads today and yesterday only. + Hasql.interpExecute [HI.sql| DELETE FROM projects.ingest_sampling WHERE hour < now() - interval '3 days' |] >>= logDeleted "Cleaned up old free-tier sampling counters" enqueueJobs ctx [Jobs.CompressReplaySessions, Jobs.DashboardsAutoProvision scheduledTime] @@ -1450,28 +1452,28 @@ autoProvisionDashboards scheduledTime = do Log.logInfo "Auto-provisioned dashboard from detected metrics" (AE.object ["project_id" AE..= pid, "template" AE..= file]) --- | For each active capped project, send a system log + email at 80% and 100% of today's cap, --- at most once per level per UTC day ('Projects.claimFreeTierNotice'). +-- | For each active capped project, send a system log + email when sampling starts and when the +-- hard ceiling is reached, at most once per level per UTC day ('Projects.claimFreeTierNotice'). checkFreeTierUsageNotifications :: [Projects.ProjectId] -> UTCTime -> ATBackgroundCtx () checkFreeTierUsageNotifications pids now = forM_ pids \pid -> tryStep "free-tier-check" do ctx <- ask @Config.AuthContext whenJustM (Projects.projectById pid) \project -> whenJust (Projects.freeTierDailyLimit ctx.config.enableFreetier project.paymentPlan) \limit -> do - count <- Projects.dailyUsageOfDay pid now - let notice = case freeTierUsageStatus count limit of + (seen, kept) <- Projects.samplingToday pid now + let notice = case freeTierUsageStatus limit (seen, kept) of FreeTierExceeded{} -> Just Projects.NoticeExceeded - FreeTierWarning{} -> Just Projects.NoticeWarning + FreeTierSampled{} -> Just Projects.NoticeSampling FreeTierOk -> Nothing NotFreeTier -> Nothing whenJust notice \n -> whenM (Projects.claimFreeTierNotice pid n) do (sev, eventName, bodyMsg) :: (SeverityLevel, Text, Text) <- case n of Projects.NoticeExceeded -> - (SLError, "system.free_tier.exceeded", "Daily event limit reached — new events are dropped until 00:00 UTC.") - <$ Log.logAttention "Free tier cap reached; ingestion is being dropped" ("project_id", pid.toText, "used", count, "limit", limit) - Projects.NoticeWarning -> pure (SLWarn, "system.free_tier.warning", "Approaching daily event limit (" <> show count <> " of " <> show limit <> " events used).") - let attrs = Map.fromList [("used", AE.toJSON count), ("limit", AE.toJSON limit), ("payment_plan", AE.String project.paymentPlan)] + (SLError, "system.free_tier.exceeded", "Daily event ceiling reached — new events are dropped until 00:00 UTC.") + <$ Log.logAttention "Free tier ceiling reached; ingestion is being dropped" ("project_id", pid.toText, "kept", kept, "limit", limit) + Projects.NoticeSampling -> pure (SLWarn, "system.free_tier.sampling", "Events are now sampled to fit the daily budget (" <> show kept <> " of " <> show seen <> " kept so far today).") + let attrs = Map.fromList [("seen", AE.toJSON seen), ("kept", AE.toJSON kept), ("limit", AE.toJSON limit), ("payment_plan", AE.String project.paymentPlan)] insertSystemLog (Telemetry.writeTargetFor ctx.env Nothing) ctx.hasqlTimefusionUsesPgTypes $ mkSystemLog pid eventName sev bodyMsg attrs Nothing now users <- Projects.usersByProjectId pid - let mail = ET.freeTierUsageEmail project.title (projectUrl ctx pid <> "/manage_billing") count limit n + let mail = ET.freeTierUsageEmail project.title (projectUrl ctx pid <> "/manage_billing") seen kept limit n forM_ users \user -> renderAndSend (CI.original user.email) mail diff --git a/src/Models/Projects/Projects.hs b/src/Models/Projects/Projects.hs index 8df06de54..bff57b415 100644 --- a/src/Models/Projects/Projects.hs +++ b/src/Models/Projects/Projects.hs @@ -52,6 +52,10 @@ module Models.Projects.Projects ( updateSubItemIdBySubId, projectCacheById, dailyUsageOfDay, + samplingTallies, + recordSampling, + SampleCounts (..), + samplingToday, freeTierDailyMaxEvents, freeTierDailyLimit, claimFreeTierNotice, @@ -150,6 +154,8 @@ import Data.Char (isDigit) import Data.Default import Data.Effectful.Hasql qualified as EHasql import Data.Effectful.UUID (UUIDEff, genUUID) +import Data.HashMap.Strict qualified as HM +import Data.List (unzip4) import Data.Map.Strict qualified as Map import Data.OpenApi (ToSchema) import Data.Text qualified as T @@ -167,12 +173,14 @@ import Effectful import Effectful.Error.Static qualified as EffError import Effectful.Reader.Static qualified as EffReader import Effectful.Time (Time, currentTime) +import GHC.Generics (Generically (..)) import Hasql.Interpolate qualified as HI import Hasql.Statement (Statement) import Hasql.Transaction qualified as Tx import Hasql.Transaction.Sessions qualified as TxS import Pkg.DeriveUtils (DB, SnakeSchema (..), UUIDId (..), WrappedEnumSC (..), idFromText, selectFrom) import Pkg.Parser.Stats (Section) +import Pkg.Sampling qualified as Sampling import Relude import Servant (FromHttpApiData (..), Header, Headers, ServerError, addHeader, err302, errHeaders, getResponse) import System.Envy (Var) @@ -475,6 +483,56 @@ dailyUsageOfDay :: DB es => ProjectId -> UTCTime -> Eff es Int dailyUsageOfDay pid t = fromMaybe 0 <$> EHasql.interpOne (dailyUsageOfDaySql pid t) +-- | One pool of a capped project ('Sampling.Tally' plus its key), for the UTC hour containing @now@. +data SamplingTally = SamplingTally {projectId :: ProjectId, isError :: Bool, keptToday, seenYesterdayAhead, seenLastHour, seenThisHour :: Int} + deriving stock (Generic) + deriving anyclass (HI.DecodeRow) + + +samplingTallies :: DB es => UTCTime -> V.Vector ProjectId -> Eff es (HM.HashMap (ProjectId, Bool) Sampling.Tally) +samplingTallies now pids = + HM.fromList + . map (\(t :: SamplingTally) -> ((t.projectId, t.isError), Sampling.Tally t.keptToday t.seenYesterdayAhead t.seenLastHour t.seenThisHour)) + <$> EHasql.interp + [HI.sql| WITH b AS (SELECT date_trunc('hour', #{now}::timestamptz, 'UTC') AS h, date_trunc('day', #{now}::timestamptz, 'UTC') AS d) + SELECT s.project_id, s.is_error, + COALESCE(SUM(s.kept) FILTER (WHERE s.hour >= b.d), 0)::bigint, + COALESCE(SUM(s.seen) FILTER (WHERE s.hour >= b.h - interval '1 day' AND s.hour < b.d), 0)::bigint, + COALESCE(SUM(s.seen) FILTER (WHERE s.hour = b.h - interval '1 hour'), 0)::bigint, + COALESCE(SUM(s.seen) FILTER (WHERE s.hour = b.h), 0)::bigint + FROM projects.ingest_sampling s, b + WHERE s.project_id = ANY(#{pids}) AND s.hour >= b.d - interval '1 day' + GROUP BY s.project_id, s.is_error |] + + +-- | One batch's sampling outcome for one pool of a project. +data SampleCounts = SampleCounts {seen, kept :: Sum Int} + deriving stock (Generic) + deriving (Monoid, Semigroup) via Generically SampleCounts + + +-- | Add one batch's counts per (project, is_error) pool to the hour containing @now@. +recordSampling :: DB es => UTCTime -> [((ProjectId, Bool), SampleCounts)] -> Eff es () +recordSampling _ [] = pass +recordSampling now counts = + EHasql.interpExecute_ + [HI.sql| INSERT INTO projects.ingest_sampling AS s (project_id, hour, is_error, seen, kept) + SELECT p, date_trunc('hour', #{now}::timestamptz, 'UTC'), e, a, k + FROM unnest(#{V.fromList pids}::uuid[], #{V.fromList errs}::bool[], #{V.fromList seen}::bigint[], #{V.fromList kept}::bigint[]) u(p, e, a, k) + ON CONFLICT (project_id, hour, is_error) DO UPDATE SET seen = s.seen + EXCLUDED.seen, kept = s.kept + EXCLUDED.kept |] + where + (pids, errs, seen, kept) = unzip4 [(pid, err, getSum c.seen, getSum c.kept) | ((pid, err), c) <- counts] + + +-- | (seen, kept) today for one project: what its sampling looks like to the people reading it. +samplingToday :: DB es => ProjectId -> UTCTime -> Eff es (Int, Int) +samplingToday pid now = + fromMaybe (0, 0) + <$> EHasql.interpOne + [HI.sql| SELECT COALESCE(SUM(seen), 0)::bigint, COALESCE(SUM(kept), 0)::bigint FROM projects.ingest_sampling + WHERE project_id = #{pid} AND hour >= date_trunc('day', #{now}::timestamptz, 'UTC') |] + + freeTierDailyMaxEvents :: Int freeTierDailyMaxEvents = 10000 @@ -488,8 +546,9 @@ freeTierDailyLimit :: Bool -> Text -> Maybe Int freeTierDailyLimit enabled plan = freeTierDailyMaxEvents <$ guard (enabled && not (isPaidPlan (parsePlan plan))) --- | A free-tier usage email; exceeding supersedes an earlier warning the same day. -data FreeTierNotice = NoticeWarning | NoticeExceeded +-- | A free-tier usage email: sampling started today, or the hard ceiling was reached (which +-- supersedes the sampling notice the same day). +data FreeTierNotice = NoticeSampling | NoticeExceeded deriving stock (Eq, Show) @@ -500,7 +559,7 @@ claimFreeTierNotice pid notice = do today <- utctDay <$> currentTime -- Spelled out (not 'fromEnum') so reordering the constructors can't change what stored rows mean. let level :: Int = case notice of - NoticeWarning -> 1 + NoticeSampling -> 1 NoticeExceeded -> 2 (== 1) <$> EHasql.interpExecute diff --git a/src/Models/Telemetry/Telemetry.hs b/src/Models/Telemetry/Telemetry.hs index 4a720437a..2aaf20a64 100644 --- a/src/Models/Telemetry/Telemetry.hs +++ b/src/Models/Telemetry/Telemetry.hs @@ -61,6 +61,7 @@ module Models.Telemetry.Telemetry ( metricExemplars, bulkInsertOtelMetrics, mintMetricIds, + metricSeriesId, bulkInsertOtelLogsAndSpansTF, insertAndHandOff, redactJSON, diff --git a/src/Opentelemetry/OtlpServer.hs b/src/Opentelemetry/OtlpServer.hs index b49c3a225..61a75cc79 100644 --- a/src/Opentelemetry/OtlpServer.hs +++ b/src/Opentelemetry/OtlpServer.hs @@ -80,7 +80,7 @@ import Pkg.ErrorMetrics (wireTypeErrorsRef) import Pkg.LiveTail qualified as LiveTail import Pkg.Metrics qualified as Metrics import Pkg.TraceSessionCache qualified as TSC -import ProcessMessage (fetchIngestCaches, overFreeTierQuota, stampHashesAtIngest, urlPathFromRawUrl) +import ProcessMessage (fetchIngestCaches, overFreeTierQuota, sampleMetrics, sampleSpans, stampHashesAtIngest, urlPathFromRawUrl) import Proto.Opentelemetry.Proto.Collector.Logs.V1.LogsService qualified as LS import Proto.Opentelemetry.Proto.Collector.Logs.V1.LogsService_Fields qualified as LSF import Proto.Opentelemetry.Proto.Collector.Metrics.V1.MetricsService qualified as MS @@ -268,7 +268,7 @@ ingestOtelRecords appCtx target caches records = do stamped <- stampOrPassthrough appCtx records -- Mint before route normalization: records without a span ID hash their raw attributes, -- so retry IDs stay independent of the current endpoint-template cache. - let minted = stampHashesAtIngest caches $ Telemetry.mintOtelLogIds stamped + minted <- sampleSpans caches $ stampHashesAtIngest caches $ Telemetry.mintOtelLogIds stamped -- Live Tail, before the durable write: the whole point is that a browser sees the log -- sooner than a query could return it. Runs after minting so the streamed row carries the -- same id the stored row will, and so "open the full record" resolves once the write lands. @@ -410,10 +410,11 @@ processList msgs !attrs = !pid2M = Projects.projectIdFromText =<< getMetricAttributeValue "at-project-id" rms in maybe V.empty (\pid -> V.fromList $ convertResourceMetricsToMetricRecords ft caches pid rms) (pidM <|> pid2M) ) - ( \_caches perMsg -> + ( \caches perMsg -> checkpoint "processList:metrics:bulkInsert" $ Telemetry.bulkInsertOtelMetrics appCtx.metricCatalogBuffer appCtx.hasqlTimefusionUsesPgTypes target - $ Telemetry.mintMetricIds (concatRecs perMsg) + . Telemetry.mintMetricIds + =<< sampleMetrics caches (concatRecs perMsg) ) _ -> do Log.logAttention "processList: unsupported opentelemetry data type" (AE.object ["ce-type" AE..= HM.lookup "ce-type" attrs]) @@ -463,13 +464,16 @@ processBatchPipeline !label msgs appCtx fallbackTime extractKeys extractIds inva !invalidPoison = [(ackId, raw, err) | (ackId, raw, _, Just err) <- checked] !converted = [(ackId, raw, req, convert fallbackTime projectCachesMap keyToIdMap req) | (ackId, raw, req, Nothing) <- checked] -- DLQ, never ack, a payload naming an unresolved project, or one converting to zero rows - -- unless every project it names is capped (2026-07-27: an ack lost ~200k rows). + -- unless every project it names is capped (2026-07-27: an ack lost ~200k rows). A mixed + -- payload goes whole, resolved rows included, so the unresolved part survives. !dropPoison = [ (ackId, raw, "unresolved project: payload carried telemetry but did not resolve or convert") | (ackId, raw, req, recs) <- converted - , let accounted pids = all (`HM.member` projectCachesMap) pids && (not (V.null recs) || all capped pids) + , let resolved = (<> extractIds req) <$> traverse (`HM.lookup` keyToIdMap) (V.toList (extractKeys req)) + -- 'all capped []' holds, so a payload naming nothing is accounted for either way. + accounted pids = all (`HM.member` projectCachesMap) pids && (not (V.null recs) || all capped pids) capped p = any overFreeTierQuota (HM.lookup p projectCachesMap) - , not $ maybe False (accounted . (<> extractIds req)) (traverse (`HM.lookup` keyToIdMap) (V.toList (extractKeys req))) + , maybe True (not . accounted) resolved ] !dropAckIds = HS.fromList [ackId | (ackId, _, _) <- dropPoison] !writeReady = [(ackId, raw, recs) | (ackId, raw, _, recs) <- converted, not (HS.member ackId dropAckIds)] @@ -480,7 +484,7 @@ processBatchPipeline !label msgs appCtx fallbackTime extractKeys extractIds inva forM_ (decodePoison <> invalidPoison) \(_, raw, err) -> recordProtoError label (toString err) raw unless (null dropPoison) $ Log.logAttention - "processList: payload did not resolve or converted to zero rows — routing to DLQ instead of acking" + "processList: unresolved or zero-row payload — routing to DLQ instead of acking" (AE.object ["label" AE..= label, "dropped_messages" AE..= length dropPoison, "ack_ids" AE..= [a | (a, _, _) <- dropPoison]]) if allEmpty @@ -976,12 +980,10 @@ severityMap = base <> Map.mapMaybe (`Map.lookup` base) aliases aliases = Map.fromList [("WARNING", "WARN" :: Text), ("INFORMATION", "INFO"), ("CRITICAL", "FATAL")] --- | Gate a project's converted records on its cache: unknown project or a --- free-tier project past its daily event+metric budget yields nothing. -withinQuota :: HM.HashMap Projects.ProjectId Projects.ProjectCache -> Projects.ProjectId -> [a] -> [a] -withinQuota projectCaches pid records = case HM.lookup pid projectCaches of - Just cache | not (overFreeTierQuota cache) -> records - _ -> [] +-- | Gate a project's converted records on its cache: an unknown project yields nothing, so +-- 'processBatchPipeline' can tell it from a project whose rows sampling later leaves out. +forKnownProject :: HM.HashMap Projects.ProjectId Projects.ProjectCache -> Projects.ProjectId -> [a] -> [a] +forKnownProject projectCaches pid records = bool [] records (HM.member pid projectCaches) -- | Convert ResourceLogs to OtelLogsAndSpans @@ -991,7 +993,7 @@ convertResourceLogsToOtelLogs !fallbackTime !projectCaches !pids resourceLogs = projectId = (snd <$> find ((== projectKey) . fst) pids) <|> (Projects.projectIdFromText =<< (V.!? 0) (getLogAttributeValue "at-project-id" (V.singleton resourceLogs))) - in maybe [] (\pid -> withinQuota projectCaches pid $ convertScopeLogsToOtelLogs fallbackTime pid (Just $ resourceLogs ^. PLF.resource) resourceLogs) projectId + in maybe [] (\pid -> forKnownProject projectCaches pid $ convertScopeLogsToOtelLogs fallbackTime pid (Just $ resourceLogs ^. PLF.resource) resourceLogs) projectId filterEmptyEvents :: OtelLogsAndSpans -> Bool @@ -1081,7 +1083,7 @@ convertResourceSpansToOtelLogs !fallbackTime !projectCaches !pids !resourceSpans -- single project). Picking V.head of a multi-project batch silently -- mis-attributes spans to the wrong project (cross-tenant leak). <|> (case V.toList pids of [(_, sole)] -> Just sole; _ -> Nothing) - in maybe [] (\pid -> withinQuota projectCaches pid $ convertScopeSpansToOtelLogs fallbackTime pid (Just $ rs ^. PTF.resource) rs) projectId + in maybe [] (\pid -> forKnownProject projectCaches pid $ convertScopeSpansToOtelLogs fallbackTime pid (Just $ rs ^. PTF.resource) rs) projectId -- | Convert ScopeSpans to OtelLogsAndSpansF @@ -1265,7 +1267,7 @@ metricRequestHasOverflow req = -- | Convert ResourceMetrics to MetricRecords convertResourceMetricsToMetricRecords :: UTCTime -> HM.HashMap Projects.ProjectId Projects.ProjectCache -> Projects.ProjectId -> V.Vector PM.ResourceMetrics -> [Telemetry.MetricRecord] convertResourceMetricsToMetricRecords !fallbackTime !projectCaches !pid !resourceMetrics = - withinQuota + forKnownProject projectCaches pid [ record @@ -1528,8 +1530,8 @@ processMetricsRequest metadataApiKey req = do (AE.object ["metric_count" AE..= length metricRecords]) unless (null metricRecords) do - let records = Telemetry.mintMetricIds $ V.fromList metricRecords - target = Telemetry.writeTargetFor appCtx.env Nothing + records <- Telemetry.mintMetricIds <$> sampleMetrics projectCaches (V.fromList metricRecords) + let target = Telemetry.writeTargetFor appCtx.env Nothing Telemetry.bulkInsertOtelMetrics appCtx.metricCatalogBuffer appCtx.hasqlTimefusionUsesPgTypes target records >>= throwOnWriteFailure Log.logTrace "Metrics: Successfully inserted metrics into database" diff --git a/src/Pages/BodyWrapper.hs b/src/Pages/BodyWrapper.hs index 95638a5dc..09baa8d9a 100644 --- a/src/Pages/BodyWrapper.hs +++ b/src/Pages/BodyWrapper.hs @@ -1322,4 +1322,4 @@ checkFreeTierStatus pid paymentPlan = do enabled <- EffReader.asks @AuthContext (.config.enableFreetier) case Projects.freeTierDailyLimit enabled paymentPlan of Nothing -> pure NotFreeTier - Just limit -> (`freeTierUsageStatus` limit) <$> (Projects.dailyUsageOfDay pid =<< Time.currentTime) + Just limit -> freeTierUsageStatus limit <$> (Projects.samplingToday pid =<< Time.currentTime) diff --git a/src/Pkg/EmailTemplates.hs b/src/Pkg/EmailTemplates.hs index c2be85697..748813ee6 100644 --- a/src/Pkg/EmailTemplates.hs +++ b/src/Pkg/EmailTemplates.hs @@ -1170,8 +1170,8 @@ monitorRecoveryEmail projectName monitorTitle = "View Monitor" -freeTierUsageEmail :: Text -> Text -> Int -> Int -> Projects.FreeTierNotice -> (Text, Html ()) -freeTierUsageEmail projectName billingUrl used limit notice = +freeTierUsageEmail :: Text -> Text -> Int -> Int -> Int -> Projects.FreeTierNotice -> (Text, Html ()) +freeTierUsageEmail projectName billingUrl seen kept limit notice = ctaEmail ("[···] " <> subject <> " - " <> projectName) True @@ -1179,17 +1179,17 @@ freeTierUsageEmail projectName billingUrl used limit notice = h1_ $ toHtml $ T.toTitle subject richP_ ["Your ", projectName, sentence] emailStatRow - [ ("Events Today", formatWithCommas (fromIntegral used), Just colour) - , ("Daily Limit", formatWithCommas (fromIntegral limit), Nothing) - , ("Usage", show ((used * 100) `div` max 1 limit) <> "%", Just colour) + [ ("Events Today", formatWithCommas (fromIntegral seen), Nothing) + , ("Kept", formatWithCommas (fromIntegral kept), Just colour) + , ("Daily Budget", formatWithCommas (fromIntegral limit), Nothing) ] ) "Upgrade Plan" billingUrl where (subject, sentence, colour) :: (Text, Text, Text) = case notice of - Projects.NoticeWarning -> ("Approaching daily event limit", " project is approaching its daily free tier limit.", "#bf8700") - Projects.NoticeExceeded -> ("Daily event limit reached", " project has hit its daily free tier limit. New events are dropped until the limit resets at 00:00 UTC.", "#cf222e") + Projects.NoticeSampling -> ("Events are being sampled", " project is sending more than its free tier budget, so today's events are sampled to spread that budget across the day. Errors are kept first, and a kept trace is kept whole.", "#bf8700") + Projects.NoticeExceeded -> ("Daily event ceiling reached", " project has hit its daily free tier ceiling. New events are dropped until it resets at 00:00 UTC.", "#cf222e") -- | Paragraph alternating plain and bold runs: @richP_ ["Your ", project, " is ready."]@. @@ -1245,7 +1245,7 @@ planDowngradedEmail reason projectName = ( do h1_ "Plan Downgraded to Free" richP_ ["Your ", projectName, " project has been downgraded to the Free plan because your subscription " <> reason <> "."] - p_ $ toHtml $ "On the Free plan, ingestion is capped at " <> freeTierCap <> " events per day (resetting at 00:00 UTC); anything beyond that is dropped. Additional team members will be deactivated. You can re-subscribe at any time to restore full access." + p_ $ toHtml $ "On the Free plan, ingestion is budgeted at " <> freeTierCap <> " events per day (resetting at 00:00 UTC); beyond that, events are sampled to fit. Additional team members will be deactivated. You can re-subscribe at any time to restore full access." ) "Upgrade Plan" @@ -1275,7 +1275,7 @@ paymentFailedEmail projectName = ( do h1_ "Payment Failed" richP_ ["We couldn't charge the card for your ", projectName, " project. Your plan is unchanged while we retry over the next few days."] - p_ $ toHtml $ "Please update your payment method. If every retry fails, the project moves to the Free plan and ingestion is capped at " <> freeTierCap <> " events per day." + p_ $ toHtml $ "Please update your payment method. If every retry fails, the project moves to the Free plan and ingestion is budgeted at " <> freeTierCap <> " events per day." ) "Update Payment Method" diff --git a/src/Pkg/Metrics.hs b/src/Pkg/Metrics.hs index 408d6ccbe..8822ea3ff 100644 --- a/src/Pkg/Metrics.hs +++ b/src/Pkg/Metrics.hs @@ -34,6 +34,7 @@ module Pkg.Metrics ( ingestSpansProcessed, extractionBatchesDropped, freeTierBatchesDropped, + freeTierSampledOut, drainFlushesCompleted, drainSpansFlushed, drainPatternsPersisted, @@ -292,12 +293,18 @@ extractionBatchesDropped = mkCounter "monoscope.extraction.batches.dropped" Noth -- | Per-project slices of telemetry batches not ingested (or rejected at the OTLP edge) because --- the project is past its free-tier daily cap. Which project is in the hourly attention log. +-- the project is past the hard ceiling of its free-tier daily budget. freeTierBatchesDropped :: Counter Int64 freeTierBatchesDropped = mkCounter "monoscope.ingest.free_tier.batches_dropped" Nothing {-# NOINLINE freeTierBatchesDropped #-} +-- | Records dropped by free-tier sampling ("Pkg.Sampling"). +freeTierSampledOut :: Counter Int64 +freeTierSampledOut = mkCounter "monoscope.ingest.free_tier.sampled_out" Nothing +{-# NOINLINE freeTierSampledOut #-} + + drainFlushesCompleted :: Counter Int64 drainFlushesCompleted = mkCounter "monoscope.drain.flushes.completed" Nothing {-# NOINLINE drainFlushesCompleted #-} diff --git a/src/Pkg/Sampling.hs b/src/Pkg/Sampling.hs new file mode 100644 index 000000000..3296f5a22 --- /dev/null +++ b/src/Pkg/Sampling.hs @@ -0,0 +1,99 @@ +-- | Free-tier sampling: spread a capped project's daily event budget across the UTC day +-- instead of keeping everything until the cap and nothing after it. +-- +-- Pacing is ad-budget pacing: each pool keeps with probability (budget left) / (traffic +-- still expected today). Decisions hash a stable key (trace id, record id, metric series), +-- so every record sharing a key gets the same answer and a kept trace stays whole. Pacing is +-- approximate: pods read counters a batch apart, and 'hardCap' bounds the overshoot. +module Pkg.Sampling (Tally (..), hardCap, rates, pace, keeps) where + +import Data.Default (Default) +import Data.Digest.XXHash (xxHash) +import Data.Fixed (mod') +import Data.Time (UTCTime (..)) +import Relude + + +-- | One pool's counters for a capped project, read from @projects.ingest_sampling@. +-- @seen@ counts before sampling, so yesterday's hours are a usable forecast of today's. +data Tally = Tally + { keptToday :: Int + , seenYesterdayAhead :: Int + -- ^ yesterday's seen events from this hour of day onward + , seenLastHour :: Int + , seenThisHour :: Int + } + deriving stock (Eq, Generic, Show) + deriving anyclass (Default) + + +-- $setup +-- >>> import Data.Time (fromGregorian) +-- >>> let noon = UTCTime (fromGregorian 2026 10 25) 43200 + + +-- | Hard stop: past this many kept events in a day nothing more is kept, whatever the forecast. +-- +-- >>> hardCap 10000 +-- 12000 +hardCap :: Int -> Int +hardCap budget = budget + budget `div` 5 + + +-- | Keep probabilities (events, errors) for a project with a daily @budget@, from the hourly +-- usage meter and its two pools' tallies. A fifth of the budget is reserved for errors, so a +-- noisy success path can't crowd them out; at the hard cap by either count nothing is kept. +-- +-- >>> rates noon 10000 0 (Tally 0 16000 0 0, Tally 0 0 0 0) +-- (0.5,1.0) +-- >>> rates noon 10000 0 (Tally 10000 0 0 0, Tally 2000 0 0 0) +-- (0.0,0.0) +-- >>> rates noon 10000 0 (Tally 10000 0 0 0, Tally 1999 0 0 0) -- one short of the cap +-- (0.0,1.0) +-- >>> rates noon 10000 12000 (Tally 0 0 0 0, Tally 0 0 0 0) -- the meter alone reached it +-- (0.0,0.0) +-- >>> rates noon 10000 0 (Tally 0 16000 0 0, Tally 2000 9000 0 0) -- error reserve spent +-- (0.5,0.0) +rates :: UTCTime -> Int -> Int -> (Tally, Tally) -> (Double, Double) +rates now budget metered (events, errors) + | max metered (events.keptToday + errors.keptToday) >= hardCap budget = (0, 0) + | otherwise = (pace now (budget - reserve) events, pace now reserve errors) + where + reserve = budget `div` 5 + + +-- | Keep probability for one pool: budget left over traffic still expected before 00:00 UTC. +-- The forecast is yesterday's traffic from this hour on, falling back to the recent hourly +-- rate; with no history at all, everything is kept until counters exist. +-- +-- >>> pace noon 8000 (Tally 0 0 0 0) +-- 1.0 +-- >>> pace noon 8000 (Tally 4000 40000 0 0) -- half the budget left, 10x that still coming +-- 0.1 +-- >>> pace noon 8000 (Tally 4000 0 3600 0) -- no yesterday: 3600/h for the 12h left +-- 9.259259259259259e-2 +-- >>> pace noon 8000 (Tally 8000 40000 0 0) -- spent +-- 0.0 +pace :: UTCTime -> Int -> Tally -> Double +pace now budget t + | left <= 0 = 0 + | forecast <= 0 = 1 + | otherwise = min 1 (fromIntegral left / forecast) + where + left = budget - t.keptToday + secondOfDay = realToFrac (utctDayTime now) :: Double + perSecond + | t.seenLastHour > 0 = fromIntegral t.seenLastHour / 3600 + | otherwise = fromIntegral t.seenThisHour / max 60 (secondOfDay `mod'` 3600) + forecast = if t.seenYesterdayAhead > 0 then fromIntegral t.seenYesterdayAhead else perSecond * (86400 - secondOfDay) + + +-- | Consistent keep decision: the key's hash, scaled to [0,1), against the probability. +-- Raising @p@ only adds keys, so a trace kept at a lower rate is kept at every higher one. +-- +-- >>> keeps 1 "trace-a" && not (keeps 0 "trace-a") +-- True +-- >>> let n = length (filter (keeps 0.25 . show) [1 .. 10000 :: Int]) in n > 2300 && n < 2700 +-- True +keeps :: Double -> Text -> Bool +keeps p key = fromIntegral (xxHash (encodeUtf8 key)) < p * (fromIntegral (maxBound :: Word32) + 1) diff --git a/src/ProcessMessage.hs b/src/ProcessMessage.hs index 3445c667e..5179db15d 100644 --- a/src/ProcessMessage.hs +++ b/src/ProcessMessage.hs @@ -41,12 +41,14 @@ module ProcessMessage ( hostFromRawUrl, urlPathFromRawUrl, overFreeTierQuota, + sampleSpans, + sampleMetrics, fetchProjectCache, fetchIngestCaches, ) where -import Control.Lens ((^?)) +import Control.Lens ((.~), (^?)) import Control.Monad.ST (ST, runST) import Data.Aeson qualified as AE import Data.Aeson.Extra (lodashMerge) @@ -57,14 +59,17 @@ import Data.Aeson.Types qualified as AE import Data.ByteString qualified as BS import Data.Cache qualified as Cache import Data.Char (digitToInt, isAlpha, isAlphaNum, isDigit, isHexDigit) +import Data.Default (def) import Data.Effectful.Hasql qualified as Hasql import Data.Effectful.Sleep (Sleep) import Data.Effectful.UUID qualified as UUID +import Data.Generics.Product.Fields (field) import Data.HashMap.Strict qualified as HM import Data.HashSet qualified as HashSet import Data.HashTable.Class qualified as HTC import Data.HashTable.ST.Cuckoo qualified as HT import Data.List qualified as L +import Data.Map.Strict qualified as Map import Data.Text qualified as T import Data.Time (addUTCTime, zonedTimeToUTC) import Data.Time.LocalTime (ZonedTime) @@ -76,7 +81,7 @@ import Effectful.Ki qualified as Ki import Effectful.Labeled (Labeled (..)) import Effectful.Log (Log) import Effectful.Reader.Static qualified as Eff -import Effectful.Time (Time) +import Effectful.Time (Time, currentTime) import Models.Apis.Endpoints qualified as Endpoints import Models.Apis.ErrorPatterns qualified as ErrorPatterns import Models.Apis.LogQueries qualified as LogQueries @@ -86,6 +91,7 @@ import Models.Telemetry.Telemetry (Context (trace_state), OtelLogsAndSpans (..), import Models.Telemetry.Telemetry qualified as Telemetry import Pkg.DeriveUtils (AesonText (..), UUIDId (..), unAesonTextMaybe) import Pkg.Metrics qualified as Metrics +import Pkg.Sampling qualified as Sampling import Pkg.SchemaLearning.Catalog qualified as Catalog import Pkg.SchemaLearning.Hot qualified as SchemaHot import Relude hiding (ask) @@ -97,6 +103,7 @@ import System.Tracing (Tracing, batchSpanAttrs, withSpan_) import System.Types (DB) import Text.RE.TDFA (RE, re, reRegex) import Text.Regex.TDFA qualified as TDFA +import UnliftIO.Exception (tryAny) import Utils (b64ToJson, jsonToMap, nestedJsonFromDotNotation, replaceAllFormats, toXXHash) @@ -129,8 +136,7 @@ processMessages msgs attrs = paired <- forM rMsgs \(ackId, raw, msg) -> runMaybeT do let pid = UUIDId msg.projectId !msgSize = fromIntegral (BS.length raw) - cache <- hoistMaybe $ HM.lookup pid projectCaches - guard $ not (overFreeTierQuota cache) + guard $ HM.member pid projectCaches let (spanId, trId) = requestEventIds msg pure $! (ackId, raw, convertRequestMessageToSpan msg msgSize (spanId, trId)) @@ -140,26 +146,87 @@ processMessages msgs attrs = Nothing -> pure (Right ()) Just (projectCaches, paired) -> Metrics.timed Metrics.ingestWriteHist [] - $ Telemetry.insertAndHandOff appCtx.hasqlTimefusionUsesPgTypes (Telemetry.writeTargetFor appCtx.env Nothing) appCtx.extractionWorker projectCaches (stampHashesAtIngest projectCaches $ V.map (\(_, _, s) -> s) paired) + . Telemetry.insertAndHandOff appCtx.hasqlTimefusionUsesPgTypes (Telemetry.writeTargetFor appCtx.env Nothing) appCtx.extractionWorker projectCaches + =<< sampleSpans projectCaches (stampHashesAtIngest projectCaches $ V.map (\(_, _, s) -> s) paired) -- On success the whole batch landed on every store (no per-row poison); the -- only DLQ entries are the decode failures collected upstream in `poison`. pure $ writeRes $> (rAckIds, poison) --- | A capped project past its daily event+metric budget: its telemetry is not ingested. +-- | A capped project at the hard cap of its daily budget ('Sampling.hardCap') by the hourly +-- meter: the OTLP edge rejects its exports outright. Sampling also checks its own counters. overFreeTierQuota :: Projects.ProjectCache -> Bool -overFreeTierQuota cache = any (cache.row.dailyUsage >=) cache.dailyLimit +overFreeTierQuota cache = any ((cache.row.dailyUsage >=) . Sampling.hardCap) cache.dailyLimit + + +-- | Keep a capped project's share of the batch ("Pkg.Sampling") and record what it saw; records +-- of uncapped or unknown projects pass through. Records sharing a key share a verdict: a key +-- with any error in the batch is judged at the error rate, so a trace stays whole within a +-- batch (one split across batches can be judged at two rates). A sampled +-- record is stamped with its weight (1/p), so what it stands for can be counted back up. +sampleCapped + :: (DB es, IOE :> es, Log :> es, Time :> es) + => (r -> Text) + -> (r -> Bool) + -> (r -> Text) + -> (Double -> r -> r) + -> HM.HashMap Projects.ProjectId Projects.ProjectCache + -> V.Vector r + -> Eff es (V.Vector r) +sampleCapped projectOf isError keyOf stamp caches records + | HM.null capped = pure records + | otherwise = do + now <- currentTime + tallies <- Projects.samplingTallies now (V.fromList $ HM.keys capped) + -- Keyed by the id's text, which records carry, so uncapped records cost one lookup. + let rateOf = HM.fromList [(pid.toText, (pid, Sampling.rates now budget cache.row.dailyUsage (tally pid False, tally pid True))) | (pid, (cache, budget)) <- HM.toList capped] + tally pid err = HM.findWithDefault def (pid, err) tallies + errorKeys = HashSet.fromList [keyOf r | r <- V.toList records, HM.member (projectOf r) rateOf, isError r] + judge r = case HM.lookup (projectOf r) rateOf of + Nothing -> (Just r, Nothing) + Just (pid, (pEvents, pErrors)) -> + let p = bool pEvents (max pEvents pErrors) (HashSet.member (keyOf r) errorKeys) + keep = Sampling.keeps p (keyOf r) + in (bool r (stamp (1 / p) r) (p < 1) <$ guard keep, Just ((pid, isError r), Projects.SampleCounts 1 (Sum (fromEnum keep)))) + judged = V.map judge records + counts = HM.fromListWith (<>) (mapMaybe snd $ V.toList judged) + total = fold counts + -- Counters only steer pacing: losing a batch's worth must not fail the ingest. + whenLeftM_ (tryAny $ Projects.recordSampling now (HM.toList counts)) + $ Log.logAttention "Free-tier sampling counters not recorded; pacing may drift" + . show @Text + Metrics.count Metrics.freeTierSampledOut (getSum $ total.seen - total.kept) [] + pure $ V.mapMaybe fst judged + where + capped = HM.mapMaybe (\c -> (c,) <$> c.dailyLimit) caches + + +-- | 'sampleCapped' for spans and logs: a trace is kept or dropped whole, and a kept record +-- carries @monoscope.sample_weight@. +sampleSpans :: (DB es, IOE :> es, Log :> es, Time :> es) => HM.HashMap Projects.ProjectId Projects.ProjectCache -> V.Vector Telemetry.OtelLogsAndSpans -> Eff es (V.Vector Telemetry.OtelLogsAndSpans) +sampleSpans = + sampleCapped + (.project_id) + Telemetry.isErrorRecord + (\r -> fromMaybe r.id (Telemetry.traceIdOf r)) + (\w r -> r & field @"attributes" .~ Just (AesonText $ Map.insertWith (flip lodashMerge) "monoscope" (AE.object ["sample_weight" AE..= w]) (maybeToMonoid $ unAesonTextMaybe r.attributes))) + + +-- | 'sampleCapped' for metrics: a series is kept or dropped whole, so no kept series has holes. +-- Points carry no weight; a series stands for itself. +sampleMetrics :: (DB es, IOE :> es, Log :> es, Time :> es) => HM.HashMap Projects.ProjectId Projects.ProjectCache -> V.Vector Telemetry.MetricRecord -> Eff es (V.Vector Telemetry.MetricRecord) +sampleMetrics = sampleCapped (UUID.toText . (.projectId)) (const False) Telemetry.metricSeriesId (\_ r -> r) -- | Project cache lookup, memoized in the shared cache. A capped entry expires after 5 minutes --- rather than 30, so a customer who upgrades is uncapped promptly on every pod. +-- rather than 30, so a customer who upgrades stops being sampled promptly on every pod. fetchProjectCache :: (DB es, Eff.Reader AuthContext :> es, IOE :> es, Time :> es) => Projects.ProjectId -> Eff es Projects.ProjectCache fetchProjectCache pid = do appCtx <- Eff.ask @AuthContext whenNothingM (liftIO $ Cache.lookup appCtx.projectCache pid) do c <- Projects.projectCacheById appCtx.config.enableFreetier pid - c <$ liftIO (bool (Cache.insert appCtx.projectCache) (Cache.insert' appCtx.projectCache (Just $ TimeSpec 300 0)) (overFreeTierQuota c) pid c) + c <$ liftIO (bool (Cache.insert appCtx.projectCache) (Cache.insert' appCtx.projectCache (Just $ TimeSpec 300 0)) (isJust c.dailyLimit) pid c) -- | The caches an ingest batch converts against. Every ingest path drops a capped project's diff --git a/src/Utils.hs b/src/Utils.hs index dc67fb1d9..8ce2380fc 100644 --- a/src/Utils.hs +++ b/src/Utils.hs @@ -136,6 +136,7 @@ import Network.HTTP.Types.URI qualified as URI import Network.URI (escapeURIString, isUnescapedInURI) import Numeric (showFFloat, showHex) import Pkg.Icons qualified as Icons +import Pkg.Sampling qualified as Sampling import Relude hiding (notElem) import Relude.Extra.Tuple (toSnd) import Servant hiding ((:>)) @@ -701,17 +702,18 @@ encodeText :: AE.ToJSON a => a -> Text encodeText = decodeUtf8 . AE.encode -data FreeTierStatus = NotFreeTier | FreeTierOk | FreeTierWarning Int Int | FreeTierExceeded Int Int +-- | @FreeTierSampled oneIn limit@: today's events are being kept about one in @oneIn@. +data FreeTierStatus = NotFreeTier | FreeTierOk | FreeTierSampled Int Int | FreeTierExceeded Int Int deriving stock (Eq, Generic, Show) deriving anyclass (Default) freeTierUsageBanner :: Text -> FreeTierStatus -> Html () freeTierUsageBanner pid = \case - FreeTierWarning used limit -> + FreeTierSampled oneIn limit -> div_ [class_ "flex w-full text-center items-center px-4 gap-4 py-1 bg-fillWarning-weak text-textWarning rounded-lg justify-center"] do - strong_ $ "You\x2019ve used " <> toHtml (formatWithCommas $ fromIntegral used) <> " of " <> toHtml (formatWithCommas $ fromIntegral limit) <> " daily events." - a_ [class_ "underline underline-offset-2 link font-medium", href_ $ "/p/" <> pid <> "/manage_billing"] "Compare plans \x2192" + strong_ $ "Free tier: today\x2019s events are sampled, about 1 in " <> toHtml (formatWithCommas $ fromIntegral oneIn) <> " kept, to stay within " <> toHtml (formatWithCommas $ fromIntegral limit) <> " a day." + a_ [class_ "underline underline-offset-2 link font-medium", href_ $ "/p/" <> pid <> "/manage_billing"] "Upgrade to keep every event \x2192" FreeTierExceeded{} -> div_ [class_ "flex w-full text-center items-center px-4 gap-4 py-1 bg-fillError-weak text-textError rounded-lg justify-center"] do strong_ "Daily cap reached \x2014 new events are dropped until 00:00 UTC." @@ -720,14 +722,15 @@ freeTierUsageBanner pid = \case FreeTierOk -> pass --- | Warn at 80% of the cap, stop at 100%. +-- | From today's (seen, kept) under a daily @limit@: sampling once anything was left out, and +-- exceeded at the hard ceiling, where nothing more is kept. -- --- >>> map (`freeTierUsageStatus` 100) [79, 80, 100] --- [FreeTierOk,FreeTierWarning 80 100,FreeTierExceeded 100 100] -freeTierUsageStatus :: Int -> Int -> FreeTierStatus -freeTierUsageStatus used limit - | used >= limit = FreeTierExceeded used limit - | used >= (limit * 80) `div` 100 = FreeTierWarning used limit +-- >>> map (freeTierUsageStatus 100) [(50, 50), (400, 100), (401, 100), (900, 120)] +-- [FreeTierOk,FreeTierSampled 4 100,FreeTierSampled 5 100,FreeTierExceeded 120 100] +freeTierUsageStatus :: Int -> (Int, Int) -> FreeTierStatus +freeTierUsageStatus limit (seen, kept) + | kept >= Sampling.hardCap limit = FreeTierExceeded kept limit + | seen > kept = FreeTierSampled ((seen + kept - 1) `div` max 1 kept) limit | otherwise = FreeTierOk diff --git a/static/migrations/0254_ingest_sampling.sql b/static/migrations/0254_ingest_sampling.sql new file mode 100644 index 000000000..ee66e27d2 --- /dev/null +++ b/static/migrations/0254_ingest_sampling.sql @@ -0,0 +1,11 @@ +-- Free-tier sampling counters per capped project, UTC hour and pool (see Pkg.Sampling). `seen` is +-- counted before sampling, so yesterday's hours forecast today's traffic; `kept` is what landed. +CREATE TABLE IF NOT EXISTS projects.ingest_sampling ( + project_id uuid NOT NULL REFERENCES projects.projects(id) ON DELETE CASCADE, + hour timestamptz NOT NULL, + is_error boolean NOT NULL, + seen bigint NOT NULL DEFAULT 0, + kept bigint NOT NULL DEFAULT 0, + PRIMARY KEY (project_id, hour, is_error) +); +CREATE INDEX IF NOT EXISTS ingest_sampling_hour_idx ON projects.ingest_sampling (hour); diff --git a/test/integration/BackgroundJobs/ReportUsageSpec.hs b/test/integration/BackgroundJobs/ReportUsageSpec.hs index 045ef78b9..6303f12d9 100644 --- a/test/integration/BackgroundJobs/ReportUsageSpec.hs +++ b/test/integration/BackgroundJobs/ReportUsageSpec.hs @@ -10,21 +10,26 @@ module BackgroundJobs.ReportUsageSpec (spec) where -- thing and re-submit chunks that already succeeded. import BackgroundJobs qualified -import Control.Lens (_1, (%~), (^.)) +import Control.Lens (_1, (%~), (.~), (^.)) import Data.Cache qualified as Cache import Data.HashMap.Strict qualified as HM import Data.List qualified as L import Data.Pool (withResource) -import Data.ProtoLens (decodeMessage, encodeMessage) +import Data.ProtoLens (decodeMessage, defMessage, encodeMessage) import Data.Text qualified as T import Data.Time (UTCTime (..), addUTCTime, fromGregorian) import Database.PostgreSQL.Simple qualified as PGS import Database.PostgreSQL.Simple.SqlQQ (sql) import Models.Projects.Projects qualified as Projects +import Pkg.Sampling qualified as Sampling import Opentelemetry.OtlpServer qualified as OtlpServer import Pkg.TestUtils import Proto.Opentelemetry.Proto.Collector.Logs.V1.LogsService qualified as LS import Proto.Opentelemetry.Proto.Collector.Logs.V1.LogsService_Fields qualified as LSF +import Proto.Opentelemetry.Proto.Collector.Metrics.V1.MetricsService_Fields qualified as MSF +import Proto.Opentelemetry.Proto.Collector.Trace.V1.TraceService_Fields qualified as TSF +import Proto.Opentelemetry.Proto.Trace.V1.Trace_Fields qualified as PTF +import Proto.Opentelemetry.Proto.Trace.V1.Trace qualified as PT import Relude import System.Config qualified as Config import Test.Hspec (Spec, around, describe, it, shouldBe, shouldMatchList, shouldNotSatisfy, shouldReturn, shouldSatisfy, shouldThrow) @@ -164,6 +169,18 @@ seedUsageAt tr pid at = do logCount tr pid >>= (`shouldSatisfy` (> 0)) +-- | Turn the free tier on for @pid@ (Free plan) and seed yesterday's non-error traffic from +-- this hour on, which paces today's keep rate; returns the config and a fresh API key. +cappedExpecting :: TestResources -> Projects.ProjectId -> Int -> IO (TestResources, Text) +cappedExpecting tr0 pid seenAhead = do + let tr = tr0{trATCtx = tr0.trATCtx{Config.config = tr0.trATCtx.config{Config.enableFreetier = True}}} + setBilling tr pid "Free" Nothing Nothing frozenTime + key <- createTestAPIKey tr pid "free-tier-sampling-key" + withResource tr.trPool \conn -> + void $ PGS.execute conn [sql| INSERT INTO projects.ingest_sampling (project_id, hour, is_error, seen) VALUES (?, date_trunc('hour', ?::timestamptz, 'UTC') - interval '1 day', false, ?) |] (pid, frozenTime, seenAhead) + pure (tr, key) + + logCount :: TestResources -> Projects.ProjectId -> IO Int logCount tr pid = withResource tr.trPool \conn -> do [PGS.Only c] <- PGS.query conn [sql| SELECT COUNT(*)::INT FROM otel_logs_and_spans WHERE project_id = ?::text |] (PGS.Only pid) @@ -534,7 +551,7 @@ spec = around (\f -> withTestResources \tr -> createTestProject tr "report-usage conn [sql| INSERT INTO apis.daily_usage (project_id, total_requests, total_metrics, window_start, window_end) VALUES (?, ?, 0, now() - interval '1 minute', now()) |] - (pid, Projects.freeTierDailyMaxEvents) + (pid, Sampling.hardCap Projects.freeTierDailyMaxEvents) Cache.purge tr.trATCtx.projectCache ingestLog tr key "over the cap" frozenTime logCount tr pid `shouldReturn` 1 @@ -559,6 +576,42 @@ spec = around (\f -> withTestResources \tr -> createTestProject tr "report-usage res ^. LSF.partialSuccess . LSF.errorMessage `shouldSatisfy` T.isInfixOf "00:00 UTC" logCount tr pid `shouldReturn` 1 + -- Past its budget a capped project keeps a share paced across the day, not everything until + -- the cap and nothing after; each kept record says how many it stands for. + it "freeTierSampling_overBudget_keepsAPacedShareWithWeights" \(tr0, pid) -> do + -- Yesterday from this hour on brought twice the 8,000-event (non-error) budget: keep half. + (tr, key) <- cappedExpecting tr0 pid 16000 + runTestBg frozenTime tr $ OtlpServer.processLogsRequest Nothing (createOtelLogAtTime key [show i | i <- [1 .. 400 :: Int]] frozenTime) + kept <- logCount tr pid + kept `shouldSatisfy` \k -> k > 160 && k < 240 + withResource tr.trPool \conn -> do + PGS.query conn [sql| SELECT SUM(seen)::INT, SUM(kept)::INT FROM projects.ingest_sampling WHERE project_id = ? AND hour >= date_trunc('day', ?::timestamptz, 'UTC') |] (pid, frozenTime) + >>= (`shouldBe` [(400 :: Int, kept)]) + PGS.query conn [sql| SELECT DISTINCT (attributes->'monoscope'->>'sample_weight')::float8 FROM otel_logs_and_spans WHERE project_id = ?::text |] (PGS.Only pid) + >>= (`shouldBe` [PGS.Only (2 :: Double)]) + + -- Errors draw on their own reserve while ordinary traffic is thinned, and a trace with an + -- error in it is kept whole, not just its error span. + it "freeTierSampling_errorTracesKeptWhole_restThinned" \(tr0, pid) -> do + (tr, key) <- cappedExpecting tr0 pid 80000 -- non-errors kept at 0.1, errors (no history) at 1 + let hex n i = T.justifyRight n '0' (show i) + spanAt t s err = mkSpanRequest (hex 32 t) (hex 16 (t * 10 + s)) Nothing "op" [] ((defMessage & PTF.code .~ PT.Status'STATUS_CODE_ERROR) <$ guard err) [] (mkResource key []) frozenTime + spans = [spanAt t s (s == 1) | t <- [1 .. 20 :: Int], s <- [1 .. 3]] <> [spanAt t 1 False | t <- [101 .. 300]] + runTestBg frozenTime tr $ OtlpServer.processTraceRequest Nothing (defMessage & TSF.resourceSpans .~ concatMap (^. TSF.resourceSpans) spans) + perTrace :: [(Text, Int)] <- withResource tr.trPool \conn -> PGS.query conn [sql| SELECT context___trace_id, COUNT(*)::INT FROM otel_logs_and_spans WHERE project_id = ?::text GROUP BY 1 |] (PGS.Only pid) + let (errorTraces, okTraces) = L.partition ((`elem` map (hex 32) [1 .. 20 :: Int]) . fst) perTrace + map snd errorTraces `shouldBe` replicate 20 3 + length okTraces `shouldSatisfy` \k -> k > 5 && k < 45 + + -- A metric series is kept or dropped whole, so a kept series has no holes. + it "freeTierSampling_metricSeriesKeptWhole" \(tr0, pid) -> do + (tr, key) <- cappedExpecting tr0 pid 16000 + let points = [createGaugeMetricAtTime key [] [] ("m" <> show i) 1 t | i <- [1 .. 200 :: Int], t <- [frozenTime, addUTCTime 60 frozenTime]] + runTestBg frozenTime tr $ OtlpServer.processMetricsRequest Nothing (defMessage & MSF.resourceMetrics .~ concatMap (^. MSF.resourceMetrics) points) + perSeries :: [(Text, Int)] <- withResource tr.trPool \conn -> PGS.query conn [sql| SELECT metric_name, COUNT(*)::INT FROM otel_metrics WHERE project_id = ? GROUP BY 1 |] (PGS.Only pid) + L.nub (map snd perSeries) `shouldBe` [2] + length perSeries `shouldSatisfy` \k -> k > 60 && k < 140 + -- Hourly and daily ticks both enqueue ReportUsage at 00:00; the loser of the lease must not -- record the window again (and bill it twice). it "skips recording while another run holds the project's usage lease" \(tr, pid) -> do @@ -583,5 +636,5 @@ spec = around (\f -> withTestResources \tr -> createTestProject tr "report-usage dailyUsage tr pid >>= (`shouldBe` [(3, 0, 0)]) it "claims each usage notice level once per day" \(tr, pid) -> do - claims <- runTestBg frozenTime tr $ traverse (Projects.claimFreeTierNotice pid) [Projects.NoticeWarning, Projects.NoticeWarning, Projects.NoticeExceeded, Projects.NoticeExceeded, Projects.NoticeWarning] + claims <- runTestBg frozenTime tr $ traverse (Projects.claimFreeTierNotice pid) [Projects.NoticeSampling, Projects.NoticeSampling, Projects.NoticeExceeded, Projects.NoticeExceeded, Projects.NoticeSampling] claims `shouldBe` [True, False, True, False, False] From fb684ef32523815b9ae0c3c1c6e4c02fb980f0d7 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Sun, 25 Oct 2026 22:55:17 +0100 Subject: [PATCH 009/203] Sample before hashing and round the banner's 1-in-N (#717) Review follow-ups: hashes are no longer computed for rows sampling drops; the banner rounds the ratio and appears from about 1 in 2, so 99% kept no longer reads as '1 in 2'; note that metrics share the events pool. --- src/Opentelemetry/OtlpServer.hs | 3 ++- src/ProcessMessage.hs | 6 ++++-- src/Utils.hs | 10 ++++++---- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/Opentelemetry/OtlpServer.hs b/src/Opentelemetry/OtlpServer.hs index 61a75cc79..1d5bed42f 100644 --- a/src/Opentelemetry/OtlpServer.hs +++ b/src/Opentelemetry/OtlpServer.hs @@ -268,7 +268,8 @@ ingestOtelRecords appCtx target caches records = do stamped <- stampOrPassthrough appCtx records -- Mint before route normalization: records without a span ID hash their raw attributes, -- so retry IDs stay independent of the current endpoint-template cache. - minted <- sampleSpans caches $ stampHashesAtIngest caches $ Telemetry.mintOtelLogIds stamped + -- Sample before hashing: hashes for rows sampling drops are wasted work. + minted <- stampHashesAtIngest caches <$> sampleSpans caches (Telemetry.mintOtelLogIds stamped) -- Live Tail, before the durable write: the whole point is that a browser sees the log -- sooner than a query could return it. Runs after minting so the streamed row carries the -- same id the stored row will, and so "open the full record" resolves once the write lands. diff --git a/src/ProcessMessage.hs b/src/ProcessMessage.hs index 5179db15d..38b99e6f0 100644 --- a/src/ProcessMessage.hs +++ b/src/ProcessMessage.hs @@ -147,7 +147,8 @@ processMessages msgs attrs = Just (projectCaches, paired) -> Metrics.timed Metrics.ingestWriteHist [] . Telemetry.insertAndHandOff appCtx.hasqlTimefusionUsesPgTypes (Telemetry.writeTargetFor appCtx.env Nothing) appCtx.extractionWorker projectCaches - =<< sampleSpans projectCaches (stampHashesAtIngest projectCaches $ V.map (\(_, _, s) -> s) paired) + . stampHashesAtIngest projectCaches + =<< sampleSpans projectCaches (V.map (\(_, _, s) -> s) paired) -- On success the whole batch landed on every store (no per-row poison); the -- only DLQ entries are the decode failures collected upstream in `poison`. @@ -214,7 +215,8 @@ sampleSpans = -- | 'sampleCapped' for metrics: a series is kept or dropped whole, so no kept series has holes. --- Points carry no weight; a series stands for itself. +-- Points carry no weight; a series stands for itself. Metrics share the events pool with +-- non-error logs and spans. sampleMetrics :: (DB es, IOE :> es, Log :> es, Time :> es) => HM.HashMap Projects.ProjectId Projects.ProjectCache -> V.Vector Telemetry.MetricRecord -> Eff es (V.Vector Telemetry.MetricRecord) sampleMetrics = sampleCapped (UUID.toText . (.projectId)) (const False) Telemetry.metricSeriesId (\_ r -> r) diff --git a/src/Utils.hs b/src/Utils.hs index 8ce2380fc..b61ae769b 100644 --- a/src/Utils.hs +++ b/src/Utils.hs @@ -722,16 +722,18 @@ freeTierUsageBanner pid = \case FreeTierOk -> pass --- | From today's (seen, kept) under a daily @limit@: sampling once anything was left out, and +-- | From today's (seen, kept) under a daily @limit@: sampled once about half or more is left out, and -- exceeded at the hard ceiling, where nothing more is kept. -- --- >>> map (freeTierUsageStatus 100) [(50, 50), (400, 100), (401, 100), (900, 120)] --- [FreeTierOk,FreeTierSampled 4 100,FreeTierSampled 5 100,FreeTierExceeded 120 100] +-- >>> map (freeTierUsageStatus 100) [(50, 50), (101, 100), (149, 100), (400, 100), (900, 120)] +-- [FreeTierOk,FreeTierOk,FreeTierOk,FreeTierSampled 4 100,FreeTierExceeded 120 100] freeTierUsageStatus :: Int -> (Int, Int) -> FreeTierStatus freeTierUsageStatus limit (seen, kept) | kept >= Sampling.hardCap limit = FreeTierExceeded kept limit - | seen > kept = FreeTierSampled ((seen + kept - 1) `div` max 1 kept) limit + | oneIn >= 2 = FreeTierSampled oneIn limit | otherwise = FreeTierOk + where + oneIn = round (fromIntegral seen / fromIntegral (max 1 kept) :: Double) serviceColors :: V.Vector Text From a55d34b27319c786ce1f1fac63c4f588bb006f35 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Sun, 25 Oct 2026 22:58:08 +0100 Subject: [PATCH 010/203] Cancel the provider subscription when a project picks Free (#718) Choosing Free in the plan picker cleared sub_id but never cancelled the Stripe or LemonSqueezy subscription, so the customer kept being billed for a plan they left. --- src/Pages/Projects.hs | 2 ++ test/integration/Pages/BusinessFlowsSpec.hs | 8 ++++++++ 2 files changed, 10 insertions(+) diff --git a/src/Pages/Projects.hs b/src/Pages/Projects.hs index 443e10708..1dd6bf5f6 100644 --- a/src/Pages/Projects.hs +++ b/src/Pages/Projects.hs @@ -1419,6 +1419,8 @@ pricingUpdateH pid PricingUpdateForm{orderIdM, plan, isOnboarding} = do Settings.notifyPlanChange envCfg project (ET.planUpgradedEmail productName) _ -> addErrorToast "Something went wrong while fetching subscription id" Nothing Nothing -> do + -- Free clears sub_id below; cancel first, or the provider keeps billing a sub nothing points at. + whenJustM (Projects.projectById pid) (Settings.cancelProjectSubscription envCfg) _ <- updatePricing "Free" "" "" "" auditPlan ("Free" :: Text) handleOnboarding diff --git a/test/integration/Pages/BusinessFlowsSpec.hs b/test/integration/Pages/BusinessFlowsSpec.hs index f37e86460..469f3fb29 100644 --- a/test/integration/Pages/BusinessFlowsSpec.hs +++ b/test/integration/Pages/BusinessFlowsSpec.hs @@ -477,6 +477,14 @@ stripeBillingTests = do (reqs, _) <- runAsBaseRecordingHTTP tr $ atAuthToBase tr.trSessAndHeader $ CreateProject.deleteProjectGetH testPid map fst reqs `shouldContain` ["https://api.stripe.com/v1/subscriptions/sub_test123"] + -- Choosing Free cleared sub_id but left the Stripe sub running, still billing the customer. + it "freePlanChoice_cancelsTheRunningStripeSubscription" \TestContext{tcResources = tr, tcProjectId = testPid} -> do + _ <- runQueryEffect tr $ Projects.updateStripeProjectBilling testPid (Projects.PlanName "GraduatedPricing") (Projects.SubId "sub_test123") (Projects.SubItemId "si_test") (Projects.CustomerId "cus_test") + session <- refreshSession tr.trPool tr.trATCtx.hasqlPool tr.trSessAndHeader + (reqs, _) <- runAsBaseRecordingHTTP tr $ atAuthToBase session $ CreateProject.pricingUpdateH testPid def + map fst reqs `shouldContain` ["https://api.stripe.com/v1/subscriptions/sub_test123"] + fmap (.paymentPlan) <$> runQueryEffect tr (Projects.projectById testPid) `shouldReturn` Just "Free" + it "deleteProject cancels the project's LemonSqueezy subscription" \TestContext{tcResources = tr, tcProjectId = testPid} -> do _ <- runQueryEffect tr $ Projects.updateProjectPricing testPid (Projects.PlanName "GraduatedPricing") (Projects.SubId "987654") (Projects.SubItemId "si_test") (Projects.OrderId "ord_test") (reqs, _) <- runAsBaseRecordingHTTP tr $ atAuthToBase tr.trSessAndHeader $ CreateProject.deleteProjectGetH testPid From 65e58494d35b71dc85cba67870da531236b71137 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Sun, 25 Oct 2026 23:21:37 +0100 Subject: [PATCH 011/203] Stop hourly spike detection loading every pattern's error_data (#719) Since a7ece43bc made the hourly per-project jobs actually run, ErrorSpikeDetection loaded error_data for every open pattern: 4.3 GB of JSON for the self-monitoring project (HasqlException messages embedding whole SQL statements, up to 21 MB a row), overflowing the 14G heap and restarting a replica at ~:01 most hours since 10-22. The query no longer selects it (nothing used it), and stored message/root message/ stack trace are capped so a pattern can't grow that large again. --- src/Models/Apis/ErrorPatterns.hs | 11 ++++++++--- test/integration/Pages/ErrorPatternsSpec.hs | 3 ++- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/Models/Apis/ErrorPatterns.hs b/src/Models/Apis/ErrorPatterns.hs index 82179ff5a..9b0d19fcb 100644 --- a/src/Models/Apis/ErrorPatterns.hs +++ b/src/Models/Apis/ErrorPatterns.hs @@ -41,9 +41,11 @@ module Models.Apis.ErrorPatterns ( ) where +import Control.Lens ((%~)) import Data.Aeson qualified as AE import Data.Default import Data.Effectful.Hasql qualified as Hasql +import Data.Generics.Product.Fields (field) import Data.GeoIP2 qualified as GeoIP2 import Data.HashMap.Strict qualified as HM import Data.IP (IP) @@ -500,7 +502,6 @@ data ErrorPatternWithCurrentRate = ErrorPatternWithCurrentRate , baselineMean :: Maybe Double , baselineStddev :: Maybe Double , currentHourCount :: Int - , errorData :: ATError , stacktrace :: Text , hash :: Text , parentHash :: Maybe Text @@ -520,7 +521,8 @@ getErrorPatternsWithCurrentRates pid now = e.id, e.project_id, e.error_type, LEFT(e.message, 2000), e.service, e.state, e.baseline_state, e.baseline_error_rate_mean, e.baseline_error_rate_stddev, COALESCE(counts.event_count, 0)::BIGINT AS current_hour_count, - e.error_data, LEFT(e.stacktrace, 8000), e.hash, e.parent_hash, e.is_framework, e.slack_thread_ts, e.discord_message_id + -- No error_data: one project's was 4.3 GB of JSON, and loading it hourly overflowed the heap. + LEFT(e.stacktrace, 8000), e.hash, e.parent_hash, e.is_framework, e.slack_thread_ts, e.discord_message_id FROM apis.error_patterns e LEFT JOIN apis.error_hourly_stats counts ON counts.error_id = e.id AND counts.project_id = e.project_id @@ -642,7 +644,10 @@ batchUpsertErrorPatterns pid errors now = -- is not time-ordered) + sum count (avoids ON CONFLICT duplicate-row error). -- The bang keeps the running count forced: a hot hash otherwise accumulates one thunk per occurrence. (errs, counts) = - V.unzip $ V.fromList $ HM.elems $ HM.fromListWith (\(a, n) (b, !k) -> (bool b a (a.when >= b.when), n + k)) [(e.hash, (e, 1 :: Int)) | e <- V.toList errors] + V.unzip $ V.fromList $ HM.elems $ HM.fromListWith (\(a, n) (b, !k) -> (bool b a (a.when >= b.when), n + k)) [(e.hash, (bounded e, 1 :: Int)) | e <- V.toList errors] + -- error_data keeps one occurrence for display: a message embedding a whole SQL statement ran to + -- 21 MB a row. The hash is already taken, so trimming changes no grouping. + bounded e = e & field @"message" %~ T.take 4000 & field @"rootErrorMessage" %~ T.take 4000 & field @"stackTrace" %~ T.take 16000 -- '' would persist and pass every Maybe check downstream, sending the issue -- page off to fetch "trace ''" — every trace-less row in the window. traceIds = V.map (mfilter (not . T.null) . (.traceId)) errs diff --git a/test/integration/Pages/ErrorPatternsSpec.hs b/test/integration/Pages/ErrorPatternsSpec.hs index 4180b5bc5..8c11face5 100644 --- a/test/integration/Pages/ErrorPatternsSpec.hs +++ b/test/integration/Pages/ErrorPatternsSpec.hs @@ -530,7 +530,8 @@ spec = sequential $ aroundAll withTestResources do void $ runTestBg regressionTime tr $ ErrorPatterns.updateErrorPatternState errRate.errorId ErrorPatterns.ESResolved regressionTime runTestBg regressionTime tr $ BackgroundJobs.runHourlyJob regressionTime 0 -- Replay the selected error itself; a newly ingested event may have a different fingerprint. - runTestBg regressionTime tr $ BackgroundJobs.processProjectErrors pid (V.singleton errRate.errorData{ErrorPatterns.when = regressionTime}) regressionTime + pat <- maybe (fail "pattern vanished") pure =<< runTestBg regressionTime tr (ErrorPatterns.getErrorPatternById errRate.errorId) + runTestBg regressionTime tr $ BackgroundJobs.processProjectErrors pid (V.singleton pat.errorData{ErrorPatterns.when = regressionTime}) regressionTime regressedPat <- runTestBg regressionTime tr $ ErrorPatterns.getErrorPatternById errRate.errorId fmap (.state) regressedPat `shouldBe` Just ESRegressed From 0688d815d659b7b52c5b07ff401dbc46e5552193 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Mon, 26 Oct 2026 11:47:24 +0100 Subject: [PATCH 012/203] Run tmux watchers and dependencies in one shared services window (#729) Panes are tracked per worktree+job in session options, so any window reuses them instead of opening a new window. Adds tmux-minio-local. Co-authored-by: Claude Opus 5.5 (1M context) --- AGENTS.md | 1 + Makefile | 80 ++++++++++++++++++++++++++----------------------------- 2 files changed, 39 insertions(+), 42 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 25c3bcbd2..29442a0db 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -89,6 +89,7 @@ A `make live-reload` process is always running in a tmux pane, logging to `build **Iterate against long-lived ghcid watchers in tmux panes: `make tmux-live-reload` (server, `build.log`) and `make tmux-live-test-dev` (tests, `build-test-dev.log`).** Start each once and leave it running. After the first load, a save recompiles only the changed modules and reruns in seconds; every kill-and-restart reloads all ~220 modules and costs 5–12 minutes. On 2026-10-19 a single session lost hours to restarting `live-test-dev` once per test. - **Change which tests run by editing `.test-args`, not by restarting.** `echo '--match "LiveTail"' > .test-args` reruns the live watcher on that focus (measured: 9 s, against ~10 min for a restart). `TEST_MATCH=…` only seeds the file at startup. +- **Never `tmux new-window`/`new-session` for a watcher or dependency.** Use the `make tmux-*` targets (`tmux-live-reload`, `tmux-live-test-dev`, `tmux-web-components-watch`, `tmux-minio-local`): one pane per worktree+job in the shared `services` window, reused from any window. - Restart a watcher only when it has crashed or wedged (see below), not to change focus. - `monoscope-shared` (`shared/`) is a separate package the test watcher loads prebuilt. Edits there are invisible to a running watcher, so that is the one case that needs a restart. diff --git a/Makefile b/Makefile index 5ebdb3fd0..9d9534aa4 100644 --- a/Makefile +++ b/Makefile @@ -329,65 +329,61 @@ build-chart-cli: build-chart-cli-linux: cd web-components && bun build --compile --target=bun-linux-x64 src/chart-cli.ts --outfile ../chart-cli -# Pin a build pane once (`make tmux-pin-here` from the pane you want), then -# every tmux-live-reload* reuses it. Pin survives ghcid restarts because we -# track the pane id in a tmux user option instead of grepping for the command. -define tmux_run - @PANE=$$(tmux show-option -wv -q @build-pane 2>/dev/null); \ - if [ -n "$$PANE" ] && tmux list-panes -a -F '#{pane_id}' | grep -qx "$$PANE"; then \ - echo "Reusing pinned pane $$PANE"; \ - tmux send-keys -t "$$PANE" C-c; sleep 0.5; \ - tmux send-keys -t "$$PANE" '$(1)' Enter; \ +# Every watcher and dependency runs in one `services` window, one pane per +# worktree+job, tracked by a session option so an agent in any window reuses +# the pane instead of opening another. Panes run a shell and the job is typed +# in, so the C-c on reuse stops the job without closing the pane. +TMUX_WT := $(notdir $(CURDIR)) +define tmux_pane + @KEY=@$(1)-$(TMUX_WT); PANE=$$(tmux show-option -qv $$KEY 2>/dev/null); \ + alive() { [ -n "$$PANE" ] && tmux list-panes -a -F '#{pane_id}' | grep -qx "$$PANE"; }; \ + if alive; then tmux send-keys -t "$$PANE" C-c; sleep 0.5; fi; \ + if alive; then \ + echo "Reusing pane $$PANE for $(TMUX_WT):$(1)"; \ elif [ -n "$$TMUX" ]; then \ - PANE=$$(tmux split-window -d -h -P -F '#{pane_id}' '$(1)'); \ - tmux set-option -w @build-pane "$$PANE"; \ - echo "Pinned new pane $$PANE (use 'make tmux-unpin' to clear)"; \ + if tmux list-windows -F '#{window_name}' | grep -qx services; then \ + PANE=$$(tmux split-window -d -t :services -c "$(CURDIR)" -P -F '#{pane_id}'); \ + else \ + PANE=$$(tmux new-window -d -n services -c "$(CURDIR)" -P -F '#{pane_id}'); \ + tmux set-option -w -t :services pane-border-status top; \ + tmux set-option -w -t :services pane-border-format ' #{@job} '; \ + fi; \ + tmux set-option -p -t "$$PANE" @job "$(TMUX_WT):$(1)"; tmux select-layout -t :services tiled; \ + tmux set-option $$KEY "$$PANE"; \ + echo "Started $(TMUX_WT):$(1) in pane $$PANE (window services)"; \ else \ - echo "Not in tmux — running in foreground"; \ - $(1); \ - fi + echo "Not in tmux — running in foreground"; $(2); exit; \ + fi; \ + tmux send-keys -t "$$PANE" '$(2)' Enter endef +# Pin the build pane to the current one instead (`make tmux-unpin` to clear). tmux-pin-here: - @tmux set-option -w @build-pane "$$TMUX_PANE" && echo "Pinned build pane to $$TMUX_PANE" + @tmux set-option @build-$(TMUX_WT) "$$TMUX_PANE" && echo "Pinned build pane to $$TMUX_PANE" tmux-unpin: - @tmux set-option -wu @build-pane && echo "Unpinned build pane" + @tmux set-option -u @build-$(TMUX_WT) && echo "Unpinned build pane" tmux-live-reload: - $(call tmux_run,make live-reload 2>&1 | tee build.log) + $(call tmux_pane,build,make live-reload 2>&1 | tee build.log) tmux-live-reload-cli: - $(call tmux_run,make live-reload-cli 2>&1 | tee build-cli.log) - -# The Vite watcher gets its own pane rather than the pinned build pane, which -# tmux_run C-c's on reuse — sharing it would kill live-reload. Worth supervising: -# when this dies the server keeps serving the last-built bundle, so server-side -# changes appear and client-side ones silently do not. -# A watcher in its own long-lived pane, tracked by the tmux option $(1): `make $(2)`. -define tmux_own_pane - @PANE=$$(tmux show-option -wv -q $(1) 2>/dev/null); \ - if [ -n "$$PANE" ] && tmux list-panes -a -F '#{pane_id}' | grep -qx "$$PANE"; then \ - tmux send-keys -t "$$PANE" C-c; sleep 0.5; \ - tmux send-keys -t "$$PANE" 'make $(2)' Enter; \ - echo "Reusing pane $$PANE for $(2)"; \ - elif [ -n "$$TMUX" ]; then \ - PANE=$$(tmux split-window -d -v -P -F '#{pane_id}' 'make $(2)'); \ - tmux set-option -w $(1) "$$PANE"; \ - echo "Started $(2) in pane $$PANE"; \ - else \ - echo "Not in tmux — run 'make $(2)' in its own terminal"; \ - fi -endef + $(call tmux_pane,build,make live-reload-cli 2>&1 | tee build-cli.log) +# The Vite watcher gets its own pane, not the build pane, whose reuse C-c's +# live-reload. Worth supervising: when this dies the server keeps serving the +# last-built bundle, so server-side changes appear and client-side ones silently do not. tmux-web-components-watch: - $(call tmux_own_pane,@wc-pane,web-components-watch) + $(call tmux_pane,wc,make web-components-watch) # Start once and leave running: every reload after the first recompiles only what changed. # Refocus it by editing .test-args (see live-test-dev) — never by restarting, which reloads # all ~220 modules. tmux-live-test-dev: - $(call tmux_own_pane,@test-pane,live-test-dev) + $(call tmux_pane,test,make live-test-dev) + +tmux-minio-local: + $(call tmux_pane,minio,make minio-local) e2e-install: @test -x e2e/node_modules/.bin/playwright || (cd e2e && npm install && npx playwright install chromium) @@ -556,4 +552,4 @@ builder-rm: .PHONY: ci ci-signoff ci-status ci-shell ci-down ci-clean ci-selftest deploy-image ship kafka-topics deploy-app rollback-app deploy-status builder-setup builder-status builder-rm tf-image -.PHONY: all test fmt fmt-check lint fix-lint live-reload kill-live-reload live-reload-cli live-reload-doctests live-test-dev tmux-live-test-dev build-chart-cli build-chart-cli-linux tmux-live-reload tmux-live-reload-cli tmux-pin-here tmux-unpin kill-web-components-watch web-components-watch e2e-install test-e2e test-e2e-real test-e2e-ui gen-proto sync-otel-proto update-otel-proto minio-local timefusion-start timefusion-stop test-integration-tf +.PHONY: all test fmt fmt-check lint fix-lint live-reload kill-live-reload live-reload-cli live-reload-doctests live-test-dev tmux-live-test-dev build-chart-cli build-chart-cli-linux tmux-live-reload tmux-live-reload-cli tmux-pin-here tmux-unpin tmux-web-components-watch tmux-minio-local kill-web-components-watch web-components-watch e2e-install test-e2e test-e2e-real test-e2e-ui gen-proto sync-otel-proto update-otel-proto minio-local timefusion-start timefusion-stop test-integration-tf From 8689e1de1f0340edcf9064ee674c66bd358957be Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:52:58 +0100 Subject: [PATCH 013/203] chore(ci): bump the github-actions group across 1 directory with 5 updates (#728) Bumps the github-actions group with 5 updates in the / directory: | Package | From | To | | --- | --- | --- | | [actions/checkout](https://github.com/actions/checkout) | `6` | `7` | | [actions/cache](https://github.com/actions/cache) | `5` | `6` | | [docker/setup-buildx-action](https://github.com/docker/setup-buildx-action) | `3` | `4` | | [docker/build-push-action](https://github.com/docker/build-push-action) | `6` | `7` | | [actions/setup-node](https://github.com/actions/setup-node) | `6` | `7` | Updates `actions/checkout` from 6 to 7 - [Release notes](https://github.com/actions/checkout/releases) - [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md) - [Commits](https://github.com/actions/checkout/compare/v6...v7) Updates `actions/cache` from 5 to 6 - [Release notes](https://github.com/actions/cache/releases) - [Changelog](https://github.com/actions/cache/blob/main/RELEASES.md) - [Commits](https://github.com/actions/cache/compare/v5...v6) Updates `docker/setup-buildx-action` from 3 to 4 - [Release notes](https://github.com/docker/setup-buildx-action/releases) - [Commits](https://github.com/docker/setup-buildx-action/compare/v3...v4) Updates `docker/build-push-action` from 6 to 7 - [Release notes](https://github.com/docker/build-push-action/releases) - [Commits](https://github.com/docker/build-push-action/compare/v6...v7) Updates `actions/setup-node` from 6 to 7 - [Release notes](https://github.com/actions/setup-node/releases) - [Commits](https://github.com/actions/setup-node/compare/v6...v7) --- updated-dependencies: - dependency-name: actions/checkout dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: actions/cache dependency-version: '6' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: docker/setup-buildx-action dependency-version: '4' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: docker/build-push-action dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions - dependency-name: actions/setup-node dependency-version: '7' dependency-type: direct:production update-type: version-update:semver-major dependency-group: github-actions ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/ci-attest-gc.yml | 2 +- .github/workflows/claude-code-review.yml | 2 +- .github/workflows/claude.yml | 2 +- .github/workflows/cli-release.yml | 12 ++++++------ .github/workflows/deps-image.yml | 6 +++--- .github/workflows/fourmolu.yml | 4 ++-- .github/workflows/haskell.yml | 18 +++++++++--------- .github/workflows/production-image.yml | 10 +++++----- .github/workflows/pullrequest.yml | 20 ++++++++++---------- 9 files changed, 38 insertions(+), 38 deletions(-) diff --git a/.github/workflows/ci-attest-gc.yml b/.github/workflows/ci-attest-gc.yml index 9704b57dd..5e14ae330 100644 --- a/.github/workflows/ci-attest-gc.yml +++ b/.github/workflows/ci-attest-gc.yml @@ -20,5 +20,5 @@ jobs: name: Prune runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - run: scripts/ci/ci.sh gc "${{ github.event.inputs.days || 30 }}" diff --git a/.github/workflows/claude-code-review.yml b/.github/workflows/claude-code-review.yml index 862118bc9..d46f9b1d5 100644 --- a/.github/workflows/claude-code-review.yml +++ b/.github/workflows/claude-code-review.yml @@ -25,7 +25,7 @@ jobs: steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 1 diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 5e5d1312c..4f4826a3a 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -26,7 +26,7 @@ jobs: actions: read # Required for Claude to read CI results on PRs steps: - name: Checkout repository - uses: actions/checkout@v6 + uses: actions/checkout@v7 with: fetch-depth: 1 diff --git a/.github/workflows/cli-release.yml b/.github/workflows/cli-release.yml index 750044db6..1d8b24faf 100644 --- a/.github/workflows/cli-release.yml +++ b/.github/workflows/cli-release.yml @@ -43,10 +43,10 @@ jobs: env: CABAL_DIR: /root/.cabal steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Cache dist-newstyle - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: dist-newstyle key: cli-linux-${{ matrix.arch }}-${{ hashFiles('cli/*.cabal', 'shared/*.cabal', 'cabal.project*') }}-${{ github.sha }} @@ -89,7 +89,7 @@ jobs: - arch: x86_64 runner: macos-15-intel steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Read GHC version from cabal.project id: ghc @@ -102,14 +102,14 @@ jobs: cabal-version: '3.14' - name: Cache Cabal - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: ~/.cabal key: cli-macos-${{ matrix.arch }}-cabal-${{ hashFiles('cli/*.cabal', 'shared/*.cabal', 'cabal.project*') }} restore-keys: cli-macos-${{ matrix.arch }}-cabal- - name: Cache dist-newstyle - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: dist-newstyle key: cli-macos-${{ matrix.arch }}-dist-${{ hashFiles('cli/*.cabal', 'shared/*.cabal', 'cabal.project*') }} @@ -156,7 +156,7 @@ jobs: permissions: contents: write steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Download all artifacts uses: actions/download-artifact@v8 diff --git a/.github/workflows/deps-image.yml b/.github/workflows/deps-image.yml index 7149af548..7b0352794 100644 --- a/.github/workflows/deps-image.yml +++ b/.github/workflows/deps-image.yml @@ -29,7 +29,7 @@ jobs: - platform: linux/arm64 runner: ubuntu-24.04-arm steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Free Disk Space run: | @@ -40,7 +40,7 @@ jobs: sudo docker image prune --all --force - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 + uses: docker/setup-buildx-action@v4 - name: Login to Container Registry uses: docker/login-action@v4 @@ -50,7 +50,7 @@ jobs: password: ${{ secrets.GH_TOKEN }} - name: Build and push platform image - uses: docker/build-push-action@v6 + uses: docker/build-push-action@v7 with: context: . file: ./Dockerfile.deps diff --git a/.github/workflows/fourmolu.yml b/.github/workflows/fourmolu.yml index d16db65c7..422b84603 100644 --- a/.github/workflows/fourmolu.yml +++ b/.github/workflows/fourmolu.yml @@ -14,13 +14,13 @@ jobs: permissions: contents: write steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: token: ${{ secrets.GITHUB_TOKEN }} # `make fmt` downloads the version the Makefile pins, so laptops and this bot agree. - name: Cache fourmolu - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: .ci/fourmolu-* key: fourmolu-${{ hashFiles('Makefile') }} diff --git a/.github/workflows/haskell.yml b/.github/workflows/haskell.yml index 45ff07dcf..98b445b89 100644 --- a/.github/workflows/haskell.yml +++ b/.github/workflows/haskell.yml @@ -34,7 +34,7 @@ jobs: skip_e2e: ${{ steps.checks.outputs.skip_e2e }} skip_haskell: ${{ steps.haskell.outputs.skip_all }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - id: checks run: scripts/ci/ci.sh gate # Whether the whole container job (image pull + service containers + cabal @@ -49,10 +49,10 @@ jobs: if: needs.gate.outputs.skip_haskell != 'true' runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@v7 with: node-version: '22' cache: 'npm' @@ -179,10 +179,10 @@ jobs: CI_SHARDS: '4' CI_FINGERPRINTS: .ci/fingerprints.tsv steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 - name: Cache dist-newstyle - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: dist-newstyle key: ${{ runner.os }}-container-cabal-${{ hashFiles('**/*.cabal', '**/cabal.project*') }}-${{ github.sha }} @@ -302,8 +302,8 @@ jobs: env: FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true steps: - - uses: actions/checkout@v6 - - uses: docker/setup-buildx-action@v3 + - uses: actions/checkout@v7 + - uses: docker/setup-buildx-action@v4 - uses: docker/login-action@v4 with: registry: ghcr.io @@ -372,8 +372,8 @@ jobs: name: Release regression tests runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v6 - - uses: actions/setup-node@v6 + - uses: actions/checkout@v7 + - uses: actions/setup-node@v7 with: node-version: '22' - run: scripts/ci/ci.sh run release-tests diff --git a/.github/workflows/production-image.yml b/.github/workflows/production-image.yml index d9ea91202..e40023dfd 100644 --- a/.github/workflows/production-image.yml +++ b/.github/workflows/production-image.yml @@ -24,25 +24,25 @@ jobs: outputs: digest: ${{ steps.image.outputs.digest }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: ref: ${{ inputs.revision }} - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v7 with: node-version: '22' - - uses: docker/setup-buildx-action@v3 + - uses: docker/setup-buildx-action@v4 # The Dockerfile's dist-newstyle cache mount dies with each fresh runner, so every # build recompiled all of monoscope (~57 min). Carry it in the Actions cache: master # saves, PRs restore master's and stay read-only so they can't evict it. Paths sit # outside the checkout because release.sh refuses a dirty tree. - if: github.ref == 'refs/heads/master' - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: ${{ runner.temp }}/dist-newstyle key: prod-dist-${{ inputs.revision }} restore-keys: prod-dist- - if: github.ref != 'refs/heads/master' - uses: actions/cache/restore@v5 + uses: actions/cache/restore@v6 with: path: ${{ runner.temp }}/dist-newstyle key: prod-dist-${{ inputs.revision }} diff --git a/.github/workflows/pullrequest.yml b/.github/workflows/pullrequest.yml index a03610dc9..9f97d528e 100644 --- a/.github/workflows/pullrequest.yml +++ b/.github/workflows/pullrequest.yml @@ -36,7 +36,7 @@ jobs: skip_e2e: ${{ steps.checks.outputs.skip_e2e }} skip_haskell: ${{ steps.haskell.outputs.skip_all }} steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: ref: ${{ github.event.pull_request.head.sha }} - id: checks @@ -53,12 +53,12 @@ jobs: if: needs.gate.outputs.skip_haskell != 'true' runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: ref: ${{ github.event.pull_request.head.sha }} - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@v7 with: node-version: '22' cache: 'npm' @@ -189,12 +189,12 @@ jobs: CI_SHARDS: '4' CI_FINGERPRINTS: .ci/fingerprints.tsv steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: ref: ${{ github.event.pull_request.head.sha }} - name: Cache dist-newstyle - uses: actions/cache@v5 + uses: actions/cache@v6 with: path: dist-newstyle key: ${{ runner.os }}-container-cabal-${{ hashFiles('**/*.cabal', '**/cabal.project*') }}-${{ github.sha }} @@ -282,7 +282,7 @@ jobs: # Pin to the PR head SHA instead of head_ref: head_ref is the branch name, # which checkout fetches with a glob refspec that 404s on deleted or fork # branches (see i18n-yaml PR fetch failure). - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: ref: ${{ github.event.pull_request.head.sha }} token: ${{ secrets.GITHUB_TOKEN }} @@ -329,11 +329,11 @@ jobs: if: needs.gate.outputs.skip_ui_tests != 'true' runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: ref: ${{ github.event.pull_request.head.sha }} - name: Setup Node.js - uses: actions/setup-node@v6 + uses: actions/setup-node@v7 with: node-version: '22' cache: 'npm' @@ -362,10 +362,10 @@ jobs: name: Release regression tests runs-on: ubuntu-24.04 steps: - - uses: actions/checkout@v6 + - uses: actions/checkout@v7 with: ref: ${{ github.event.pull_request.head.sha }} - - uses: actions/setup-node@v6 + - uses: actions/setup-node@v7 with: node-version: '22' - run: scripts/ci/ci.sh run release-tests From dd4d5c1fa105d7687d4a3c126566aafeccfec70e Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 11:56:43 +0100 Subject: [PATCH 014/203] chore(deps): bump golang.org/x/crypto in /scripts/local/dlq-redrive (#459) Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.28.0 to 0.52.0. - [Commits](https://github.com/golang/crypto/compare/v0.28.0...v0.52.0) --- updated-dependencies: - dependency-name: golang.org/x/crypto dependency-version: 0.52.0 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- scripts/local/dlq-redrive/go.mod | 4 ++-- scripts/local/dlq-redrive/go.sum | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/scripts/local/dlq-redrive/go.mod b/scripts/local/dlq-redrive/go.mod index b25374a0c..fa1320efd 100644 --- a/scripts/local/dlq-redrive/go.mod +++ b/scripts/local/dlq-redrive/go.mod @@ -1,6 +1,6 @@ module dlq-redrive -go 1.22 +go 1.25.0 require ( github.com/twmb/franz-go v1.18.0 @@ -11,5 +11,5 @@ require ( github.com/klauspost/compress v1.17.11 // indirect github.com/pierrec/lz4/v4 v4.1.21 // indirect github.com/twmb/franz-go/pkg/kmsg v1.9.0 // indirect - golang.org/x/crypto v0.28.0 // indirect + golang.org/x/crypto v0.52.0 // indirect ) diff --git a/scripts/local/dlq-redrive/go.sum b/scripts/local/dlq-redrive/go.sum index afb62cce4..3643ee32f 100644 --- a/scripts/local/dlq-redrive/go.sum +++ b/scripts/local/dlq-redrive/go.sum @@ -8,5 +8,5 @@ github.com/twmb/franz-go/pkg/kadm v1.14.0 h1:nAn1co1lXzJQocpzyIyOFOjUBf4WHWs5/fT github.com/twmb/franz-go/pkg/kadm v1.14.0/go.mod h1:XjOPz6ZaXXjrW2jVCfLuucP8H1w2TvD6y3PT2M+aAM4= github.com/twmb/franz-go/pkg/kmsg v1.9.0 h1:JojYUph2TKAau6SBtErXpXGC7E3gg4vGZMv9xFU/B6M= github.com/twmb/franz-go/pkg/kmsg v1.9.0/go.mod h1:CMbfazviCyY6HM0SXuG5t9vOwYDHRCSrJJyBAe5paqg= -golang.org/x/crypto v0.28.0 h1:GBDwsMXVQi34v5CCYUm2jkJvu4cbtru2U4TN2PSyQnw= -golang.org/x/crypto v0.28.0/go.mod h1:rmgy+3RHxRZMyY0jjAJShp2zgEdOqj2AO7U0pYmeQ7U= +golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988= +golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc= From 4d4d00d8691269c5d478844ca8de1480c99524c3 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Mon, 26 Oct 2026 12:48:15 +0100 Subject: [PATCH 015/203] Bump npm dependencies and move monaco imports to 0.57 export paths (#734) Consolidates dependabot #721 #727 #726 #725 #724 #723 #722 #558 #529 #505 #504 #499 #488 #480 #478 #477 #476 #464. Monaco 0.57 added an exports map and moved YAML to languages/definitions, so the deep esm imports and their vite aliases no longer resolve. --- package-lock.json | 3284 +++++++++++++++------------ package.json | 12 +- web-components/package-lock.json | 1376 ++++++----- web-components/package.json | 36 +- web-components/src/monaco-yaml.d.ts | 2 +- web-components/src/types/types.ts | 2 +- web-components/src/yaml-editor.ts | 6 +- web-components/vite.config.mjs | 13 +- 8 files changed, 2687 insertions(+), 2044 deletions(-) diff --git a/package-lock.json b/package-lock.json index 2c2f54945..348b62045 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,22 +1,22 @@ { - "name": "monoscope-2", + "name": "m3-deps", "lockfileVersion": 3, "requires": true, "packages": { "": { "dependencies": { - "@opentelemetry/auto-instrumentations-node": "^0.77.0", + "@opentelemetry/auto-instrumentations-node": "^0.82.0", "@tailwindcss/cli": "^4.3.3", "ansi-up": "^1.0.0", "html2canvas": "^1.4.1" }, "devDependencies": { - "@playwright/test": "^1.62.1", + "@playwright/test": "^1.64.1", "@tailwindcss/typography": "^0.5.20", - "autoprefixer": "^10.5.0", - "daisyui": "^5.7.16", - "jest": "^30.4.2", - "postcss": "^8.5.15", + "autoprefixer": "^10.6.1", + "daisyui": "^5.7.50", + "jest": "^30.5.2", + "postcss": "^8.5.31", "tailwindcss": "^4.3.3", "workbox-cli": "^7.4.1" } @@ -69,7 +69,6 @@ "integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/code-frame": "^7.29.0", "@babel/generator": "^7.29.0", @@ -268,9 +267,9 @@ } }, "node_modules/@babel/helper-plugin-utils": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz", - "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz", + "integrity": "sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==", "dev": true, "license": "MIT", "engines": { @@ -629,13 +628,13 @@ } }, "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.28.6.tgz", - "integrity": "sha512-wgEmr06G6sIpqr8YDwA2dSRTE3bJ+V0IfpzfSY3Lfgd7YWOaAdlykvJi13ZKBt8cZHfgH1IXN+CL656W3uUa4w==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", + "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.28.6" + "@babel/helper-plugin-utils": "^7.29.7" }, "engines": { "node": ">=6.9.0" @@ -755,13 +754,13 @@ } }, "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.28.6", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.28.6.tgz", - "integrity": "sha512-+nDNmQye7nlnuuHDboPbGm00Vqg3oO8niRRL27/4LYHUsHYh0zJ1xWOz0uRwNFmM1Avzk8wZbc6rdiYhomzv/A==", + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.29.7.tgz", + "integrity": "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==", "dev": true, "license": "MIT", "dependencies": { - "@babel/helper-plugin-utils": "^7.28.6" + "@babel/helper-plugin-utils": "^7.29.7" }, "engines": { "node": ">=6.9.0" @@ -1810,13 +1809,14 @@ "license": "MIT" }, "node_modules/@emnapi/core": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.0.tgz", - "integrity": "sha512-l9Oo58x0HOP5znGzVhYW9U3e5wVuA4LAZU2AGezTmkhO1CgQRFDhDg4nneHsu/t3WniXg9QrG2nIXL/ZS8ln8Q==", + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", + "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", + "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/wasi-threads": "1.2.2", + "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, @@ -1824,13 +1824,15 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, "license": "0BSD", "optional": true }, "node_modules/@emnapi/runtime": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.0.tgz", - "integrity": "sha512-55coeOFKHv1ywEcUXJtWU5f+Jr/W5tZDvZig8DLKSwUN1JpROQ4rk/SNOQiFWmaR/VKF4zuFyW1B8JduOSv6Pg==", + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", + "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", + "dev": true, "license": "MIT", "optional": true, "dependencies": { @@ -1841,13 +1843,15 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, "license": "0BSD", "optional": true }, "node_modules/@emnapi/wasi-threads": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz", - "integrity": "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", + "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", + "dev": true, "license": "MIT", "optional": true, "dependencies": { @@ -1858,13 +1862,14 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, "license": "0BSD", "optional": true }, "node_modules/@grpc/grpc-js": { - "version": "1.14.4", - "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.4.tgz", - "integrity": "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==", + "version": "1.14.6", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.6.tgz", + "integrity": "sha512-SgC/B3/VZ8lTyOZ4Cwk6f1skWhmkNAaVfiX90qd5u1rRXGKk1//8FTUEN9GvOUq7rfWIqAYkA3CoyumYVpOS6g==", "license": "Apache-2.0", "dependencies": { "@grpc/proto-loader": "^0.8.0", @@ -1930,17 +1935,17 @@ } }, "node_modules/@jest/console": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-30.4.1.tgz", - "integrity": "sha512-v3bhyxUh9Hgmo5p6hAOXe14/R3ZxZDOsvHleh4B07z3m/x4/ngPUXEm9XwK4sF4u+f+P2ORb0Ge+MgpaqRMVDA==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/console/-/console-30.5.2.tgz", + "integrity": "sha512-e8sQC4pCMHPBrPX7Hk8TJr+DM5dkUnImSTNag8SEWFAFAF6xIz4AJvCKapnrdHnZxep4bxw4PhG+ZbimYBMyKw==", "dev": true, "license": "MIT", "dependencies": { - "@jest/types": "30.4.1", + "@jest/types": "30.5.1", "@types/node": "*", "chalk": "^4.1.2", - "jest-message-util": "30.4.1", - "jest-util": "30.4.1", + "jest-message-util": "30.5.1", + "jest-util": "30.5.1", "slash": "^3.0.0" }, "engines": { @@ -1948,18 +1953,18 @@ } }, "node_modules/@jest/core": { - "version": "30.4.2", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-30.4.2.tgz", - "integrity": "sha512-TZJA6cPJUFxoWhxaLo8t0VX/MZX2wPWr0uIDvLSHIvN4gu9h02vSzqI2kBADG1ExqQlC+cY09xKMSreivvrChQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/core/-/core-30.5.2.tgz", + "integrity": "sha512-/jqvFWoJF7LV1a6AUpYMbMm+2yIYsHJfR474H0SCzr9k8tnO/jl9wRg6zSG6lxgf6EozNlCG4amFzWsbZSvvZA==", "dev": true, "license": "MIT", "dependencies": { - "@jest/console": "30.4.1", - "@jest/pattern": "30.4.0", - "@jest/reporters": "30.4.1", - "@jest/test-result": "30.4.1", - "@jest/transform": "30.4.1", - "@jest/types": "30.4.1", + "@jest/console": "30.5.2", + "@jest/pattern": "30.5.0", + "@jest/reporters": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/transform": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", "ansi-escapes": "^4.3.2", "chalk": "^4.1.2", @@ -1967,20 +1972,20 @@ "exit-x": "^0.2.2", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.11", - "jest-changed-files": "30.4.1", - "jest-config": "30.4.2", - "jest-haste-map": "30.4.1", - "jest-message-util": "30.4.1", - "jest-regex-util": "30.4.0", - "jest-resolve": "30.4.1", - "jest-resolve-dependencies": "30.4.2", - "jest-runner": "30.4.2", - "jest-runtime": "30.4.2", - "jest-snapshot": "30.4.1", - "jest-util": "30.4.1", - "jest-validate": "30.4.1", - "jest-watcher": "30.4.1", - "pretty-format": "30.4.1", + "jest-changed-files": "30.5.1", + "jest-config": "30.5.2", + "jest-haste-map": "30.5.1", + "jest-message-util": "30.5.1", + "jest-regex-util": "30.5.0", + "jest-resolve": "30.5.1", + "jest-resolve-dependencies": "30.5.2", + "jest-runner": "30.5.2", + "jest-runtime": "30.5.2", + "jest-snapshot": "30.5.2", + "jest-util": "30.5.1", + "jest-validate": "30.5.1", + "jest-watcher": "30.5.2", + "pretty-format": "30.5.1", "slash": "^3.0.0" }, "engines": { @@ -1996,9 +2001,9 @@ } }, "node_modules/@jest/diff-sequences": { - "version": "30.4.0", - "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.4.0.tgz", - "integrity": "sha512-zOpzlfUs45l6u7jm39qr87JCHUDsaeCtvL+kQe/Vn9jSnRB4/5IPXISm0h9I1vZW/o00Kn4UTJ2MOlhnUGwv3g==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.5.0.tgz", + "integrity": "sha512-OsqBjHXCn8cadasoAZBP6nWYvMsRhpMzGXTpxJ5aO04NlbdhIz+FVe3q49l0AwVhsz/cEmIpBes6gAFl1/dWQg==", "dev": true, "license": "MIT", "engines": { @@ -2006,70 +2011,70 @@ } }, "node_modules/@jest/environment": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-30.4.1.tgz", - "integrity": "sha512-AK9yNRqgKxiabqMoe4oW+3/TSSeV8vkdC7BGaxZdU0AFXfOpofTLqdru2GXKZghP3sdgwE9XXpnVwfZ8JnFV4w==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-30.5.2.tgz", + "integrity": "sha512-nwFPOUMbmsjNNRCpnJpB9HbSZu4C07wDDds++5j+j1MezzPLxMPDdbdUVjr2o4RULDOValnDd70taPFI1EtxAg==", "dev": true, "license": "MIT", "dependencies": { - "@jest/fake-timers": "30.4.1", - "@jest/types": "30.4.1", + "@jest/fake-timers": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "jest-mock": "30.4.1" + "jest-mock": "30.5.2" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/expect": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-30.4.1.tgz", - "integrity": "sha512-ginrj6TMgh2GshLUGCjO94Ptx9HhdZA/I6A9iUfyeLKFtdAjnKzHDgzgP9HYQgbxM1lbXScQ2eUBz2lGeVDPWA==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-30.5.2.tgz", + "integrity": "sha512-2E+1Pg6jJxbRjLNLpciC71iri/3qsKJL222/aXJEFwC0VdUSvfS+JZQQLEVjUYYc8t8pQu2MGE3cF2+bNTYRsg==", "dev": true, "license": "MIT", "dependencies": { - "expect": "30.4.1", - "jest-snapshot": "30.4.1" + "expect": "30.5.2", + "jest-snapshot": "30.5.2" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/expect-utils": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-30.4.1.tgz", - "integrity": "sha512-ZBn5CglH8fBsQsvs4VWNzD4aWfUYks+IdOOQU3MEK71ol/BcVm+P+rtb1KpiFBpSWSCE27uOahyyf1vfqOVbcQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-30.5.2.tgz", + "integrity": "sha512-d/HOLSrJUlBIl6n3LzOa7cjW3xdePm5H5gQw2lixZ/0h157l9sw3mLblzFqnPcTbhDzhRQdBOX3A3KcG73nm5Q==", "dev": true, "license": "MIT", "dependencies": { - "@jest/get-type": "30.1.0" + "@jest/get-type": "30.5.0" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/fake-timers": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-30.4.1.tgz", - "integrity": "sha512-iW5umdmfPeWzehrVhugFQZqCchSCud5S1l2YT0O9ZhjRR0ExclANDZkiSBwzqtnlOn0J1JXvO+HZ6rkuyOVOgQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-30.5.2.tgz", + "integrity": "sha512-GKk0h0tKT5SpDPxDhPg3r9mm5s8/YCBzVNMOGdRiQXwUiMsjU10mVPlMaQstH6/cu50vOb8N9oQUMETHuwwxKw==", "dev": true, "license": "MIT", "dependencies": { - "@jest/types": "30.4.1", + "@jest/types": "30.5.1", "@sinonjs/fake-timers": "^15.4.0", "@types/node": "*", - "jest-message-util": "30.4.1", - "jest-mock": "30.4.1", - "jest-util": "30.4.1" + "jest-message-util": "30.5.1", + "jest-mock": "30.5.2", + "jest-util": "30.5.1" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/get-type": { - "version": "30.1.0", - "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.1.0.tgz", - "integrity": "sha512-eMbZE2hUnx1WV0pmURZY9XoXPkUYjpc55mb0CrhtdWLtzMQPFvu/rZkTLZFTsdaVQa+Tr4eWAteqcUzoawq/uA==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.5.0.tgz", + "integrity": "sha512-9/2VUPitAjmBzbvDvqrxmvB7BzWsBW0WmkkojX1ODuxX1NLGxx9gfaZpHB0z8DtJ9uhGNmZG/VXBhf8uO0OV8Q==", "dev": true, "license": "MIT", "engines": { @@ -2077,62 +2082,78 @@ } }, "node_modules/@jest/globals": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-30.4.1.tgz", - "integrity": "sha512-ZbuY4cmXC8DkxYjfvT2DbcHWL2T6vmsMhXCDcmTB2T0y0gaezBI77ufq5ZAIdcRkYZ7NEQEDg1xFeKbxUJ5v5Q==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-30.5.2.tgz", + "integrity": "sha512-62zfS+dL+M5aTNHXCNLyqD+j4oqxTIzDYrZbpqMP8Yn+gvlAGyzC6BSPNb1ZmFOakV1RtFYX/O3FCQXSWmQdgg==", "dev": true, "license": "MIT", "dependencies": { - "@jest/environment": "30.4.1", - "@jest/expect": "30.4.1", - "@jest/types": "30.4.1", - "jest-mock": "30.4.1" + "@jest/environment": "30.5.2", + "@jest/expect": "30.5.2", + "@jest/types": "30.5.1", + "jest-mock": "30.5.2" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/@jest/pattern": { - "version": "30.4.0", - "resolved": "https://registry.npmjs.org/@jest/pattern/-/pattern-30.4.0.tgz", - "integrity": "sha512-RAWn3+f9u8BsHijKJ71uHcFp6vmyEt6VvoWXkl6hKF3qVIuWNmudVjg12DlBPGup/frIl5UcUlH5HfEuvHpEXg==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/pattern/-/pattern-30.5.0.tgz", + "integrity": "sha512-HdNQYSdRTEBNrginaqzQtTjG0HRMfrra/z6Ok7uL3S87vSlarIVohEsJsSj5edu3MiHoHjAkvPROz5ZjoKai+w==", "dev": true, "license": "MIT", "dependencies": { "@types/node": "*", - "jest-regex-util": "30.4.0" + "jest-regex-util": "30.5.0" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, + "node_modules/@jest/react-is-18": { + "name": "react-is", + "version": "18.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", + "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jest/react-is-19": { + "name": "react-is", + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz", + "integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@jest/reporters": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-30.4.1.tgz", - "integrity": "sha512-/SnkPCzEQpUaBH81kjdEdDdo2WZl5hxw+BmLDGWjRkm8o7XlhjwsU36cqwe5PGBE5WYpBvDzRSdXx9rbGuJtNA==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-30.5.2.tgz", + "integrity": "sha512-ev6E9iG73twQcfAfoTnviuYkr3yOrYbzAtMFCimv2fxHXPIp9PBt2u1wNMt0aYWgl8FPwIcS8oqRJg6alnht4Q==", "dev": true, "license": "MIT", "dependencies": { "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "30.4.1", - "@jest/test-result": "30.4.1", - "@jest/transform": "30.4.1", - "@jest/types": "30.4.1", - "@jridgewell/trace-mapping": "^0.3.25", + "@jest/console": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/transform": "30.5.2", + "@jest/types": "30.5.1", + "@jridgewell/trace-mapping": "^0.3.31", "@types/node": "*", "chalk": "^4.1.2", "collect-v8-coverage": "^1.0.2", "exit-x": "^0.2.2", - "glob": "^10.5.0", + "glob": "^13.0.6", "graceful-fs": "^4.2.11", "istanbul-lib-coverage": "^3.0.0", "istanbul-lib-instrument": "^6.0.0", "istanbul-lib-report": "^3.0.0", "istanbul-lib-source-maps": "^5.0.0", "istanbul-reports": "^3.1.3", - "jest-message-util": "30.4.1", - "jest-util": "30.4.1", - "jest-worker": "30.4.1", + "jest-message-util": "30.5.1", + "jest-util": "30.5.1", + "jest-worker": "30.5.1", "slash": "^3.0.0", "string-length": "^4.0.2", "v8-to-istanbul": "^9.0.1" @@ -2149,10 +2170,67 @@ } } }, + "node_modules/@jest/reporters/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/@jest/reporters/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/@jest/reporters/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@jest/reporters/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/@jest/schemas": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.4.1.tgz", - "integrity": "sha512-i6b4qw5qnP8c5FEeBJg/uZQ4ddrkN6Ca8qISJh0pr7a5hfn3h3v5x60BEbOC7OYAGZNMs1LfFLwnW2CuK8F57Q==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.5.0.tgz", + "integrity": "sha512-/hunigyNpc4RCjC0VaW3f5RCUZVM2+WQ65qP7z083Gmvac7or2LI50XVNOtE4YPgBpV0yxYiAgorAPGniCoJmg==", "dev": true, "license": "MIT", "dependencies": { @@ -2163,13 +2241,13 @@ } }, "node_modules/@jest/snapshot-utils": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/snapshot-utils/-/snapshot-utils-30.4.1.tgz", - "integrity": "sha512-ObY4ljvQ95mt6iwKtVLetR/4yXiAgl3H4nJxhztr0MTjrN97TwDYrnCp/kF60Ec9HdhkWTHSu+Hg05aXfngpOA==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/@jest/snapshot-utils/-/snapshot-utils-30.5.1.tgz", + "integrity": "sha512-V3wnxNtiVmw5PPVg433Cn3VdXnsOeu/ofLw3KC04Bn2y1wIlU5kozXQn48rhrgj/02LrCVtntTEF1yBha0XSUw==", "dev": true, "license": "MIT", "dependencies": { - "@jest/types": "30.4.1", + "@jest/types": "30.5.1", "chalk": "^4.1.2", "graceful-fs": "^4.2.11", "natural-compare": "^1.4.0" @@ -2179,14 +2257,15 @@ } }, "node_modules/@jest/source-map": { - "version": "30.0.1", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-30.0.1.tgz", - "integrity": "sha512-MIRWMUUR3sdbP36oyNyhbThLHyJ2eEDClPCiHVbrYAe5g3CHRArIVpBw7cdSB5fr+ofSfIb2Tnsw8iEHL0PYQg==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-30.5.2.tgz", + "integrity": "sha512-c5CehvkbfHX6yyNg7bMn2ylqlp9AHXuZ/3hPH/Lh5bxD/vefd/lV9HBjMqXef9yQNqkdwyZvkLSVSwB38hy8Qw==", "dev": true, "license": "MIT", "dependencies": { - "@jridgewell/trace-mapping": "^0.3.25", + "@jridgewell/trace-mapping": "^0.3.31", "callsites": "^3.1.0", + "convert-source-map": "^2.0.0", "graceful-fs": "^4.2.11" }, "engines": { @@ -2194,14 +2273,14 @@ } }, "node_modules/@jest/test-result": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-30.4.1.tgz", - "integrity": "sha512-/ZG7pgEiOmmWkN9TplKbOu4id2N5lh7FHwRwlkgBVAzGdRH+OkkQ8wX/kIxg4zmd3ZQvAL1RwL2yWsvNYYECTw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-30.5.2.tgz", + "integrity": "sha512-eO6YU5rsLfs60ne694e0IAmRgeBnoA8mu0nlxXDbl/1j5km0o2vO9/VbbUIKIH+WRKKEI+ELgwraRGn2Lhep8g==", "dev": true, "license": "MIT", "dependencies": { - "@jest/console": "30.4.1", - "@jest/types": "30.4.1", + "@jest/console": "30.5.2", + "@jest/types": "30.5.1", "@types/istanbul-lib-coverage": "^2.0.6", "collect-v8-coverage": "^1.0.2" }, @@ -2210,15 +2289,15 @@ } }, "node_modules/@jest/test-sequencer": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-30.4.1.tgz", - "integrity": "sha512-PeYE+4td5rKjoRPxztObrXU+H8hsjZfxKMXOcmrr34JerSyB/ROOxbbicz8B7A5j9R9VayDnVPvBmedqCsFCdw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-30.5.2.tgz", + "integrity": "sha512-bmij8jZyYAC47ExT2GeP7PcrlwSNS+Bp3KeRuBH88gpcxqDv6fljN8PemS4J/lLZ79xb6mpaennQTTq0zUAVVg==", "dev": true, "license": "MIT", "dependencies": { - "@jest/test-result": "30.4.1", + "@jest/test-result": "30.5.2", "graceful-fs": "^4.2.11", - "jest-haste-map": "30.4.1", + "jest-haste-map": "30.5.1", "slash": "^3.0.0" }, "engines": { @@ -2226,23 +2305,23 @@ } }, "node_modules/@jest/transform": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-30.4.1.tgz", - "integrity": "sha512-Wz0LyktlTvRefoymh+n64hQ84KNXsRGcwdoZ8CSa0Ea+fgYcHZlnk+hDP7v2MS7il2bQ5uTEIxf4/NNfhMN4KQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-30.5.2.tgz", + "integrity": "sha512-LBGwmaE886C41jDZ65eqR1YbXM7642MK3ZhTowZd5+xDlrDLuf4ePuDdDmVSvcr8NTVJ3MqxLkMbUCzuigUaoQ==", "dev": true, "license": "MIT", "dependencies": { "@babel/core": "^7.27.4", - "@jest/types": "30.4.1", - "@jridgewell/trace-mapping": "^0.3.25", - "babel-plugin-istanbul": "^7.0.1", + "@jest/types": "30.5.1", + "@jridgewell/trace-mapping": "^0.3.31", + "babel-plugin-istanbul": "^8.0.0", "chalk": "^4.1.2", "convert-source-map": "^2.0.0", "fast-json-stable-stringify": "^2.1.0", "graceful-fs": "^4.2.11", - "jest-haste-map": "30.4.1", - "jest-regex-util": "30.4.0", - "jest-util": "30.4.1", + "jest-haste-map": "30.5.1", + "jest-regex-util": "30.5.0", + "jest-util": "30.5.1", "pirates": "^4.0.7", "slash": "^3.0.0", "write-file-atomic": "^5.0.1" @@ -2252,14 +2331,14 @@ } }, "node_modules/@jest/types": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-30.4.1.tgz", - "integrity": "sha512-f1x/vJXIfjOlEmejYpbkbgw1gOqpPECwMvMEtBqe47j7H2Hg8h8w3o3ikhSXq3MI15kg+oQ0exWO0uCtTNJLoQ==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/@jest/types/-/types-30.5.1.tgz", + "integrity": "sha512-LvVYn83nnXPl+Rg98nvcFgjx6nRMTArhSn6RAX/w3ELn54S8A42TYZvsCMdGUqTM8S0wyXbtlQdU6Hi6dykj9g==", "dev": true, "license": "MIT", "dependencies": { - "@jest/pattern": "30.4.0", - "@jest/schemas": "30.4.1", + "@jest/pattern": "30.5.0", + "@jest/schemas": "30.5.0", "@types/istanbul-lib-coverage": "^2.0.6", "@types/istanbul-reports": "^3.0.4", "@types/node": "*", @@ -2333,1390 +2412,1318 @@ } }, "node_modules/@napi-rs/wasm-runtime": { - "version": "0.2.12", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz", - "integrity": "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==", + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", + "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", + "dev": true, "license": "MIT", "optional": true, "dependencies": { - "@emnapi/core": "^1.4.3", - "@emnapi/runtime": "^1.4.3", - "@tybys/wasm-util": "^0.10.0" + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", + "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" } }, "node_modules/@opentelemetry/api": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz", - "integrity": "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==", + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz", + "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==", "license": "Apache-2.0", "peer": true, "engines": { "node": ">=8.0.0" } }, - "node_modules/@opentelemetry/api-logs": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/api-logs/-/api-logs-0.219.0.tgz", - "integrity": "sha512-FFx7YnaYJlIjqWW/AG/yAZ0L/NEY724PipXXXQLdtZPbLwBGbUMTGL1i/esI56TWfTUXxhLfpgrnWJCG8aUJyg==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/api": "^1.3.0" - }, - "engines": { - "node": ">=8.0.0" - } - }, "node_modules/@opentelemetry/auto-instrumentations-node": { - "version": "0.77.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/auto-instrumentations-node/-/auto-instrumentations-node-0.77.0.tgz", - "integrity": "sha512-LkF930Cs+v+ZO/qV6LolbocvFkJJ812BBDyRNjQpwllBA+rFvGtP/voXPuh24QV3JKl5/3c3GulLHvMn8spqkQ==", + "version": "0.82.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/auto-instrumentations-node/-/auto-instrumentations-node-0.82.0.tgz", + "integrity": "sha512-WL4U3IZ9a0lHPj9l+c7IWJN+G2LPlM1/Otk15a5qrIkByEw9XCmZ2SwCf8fNZnCf5MNOP0D8LMaR8kv1MWtaFQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", - "@opentelemetry/instrumentation-amqplib": "^0.66.0", - "@opentelemetry/instrumentation-aws-lambda": "^0.71.0", - "@opentelemetry/instrumentation-aws-sdk": "^0.74.0", - "@opentelemetry/instrumentation-bunyan": "^0.64.0", - "@opentelemetry/instrumentation-cassandra-driver": "^0.64.0", - "@opentelemetry/instrumentation-connect": "^0.62.0", - "@opentelemetry/instrumentation-cucumber": "^0.35.0", - "@opentelemetry/instrumentation-dataloader": "^0.36.0", - "@opentelemetry/instrumentation-dns": "^0.62.0", - "@opentelemetry/instrumentation-express": "^0.67.0", - "@opentelemetry/instrumentation-fs": "^0.38.0", - "@opentelemetry/instrumentation-generic-pool": "^0.62.0", - "@opentelemetry/instrumentation-graphql": "^0.67.0", - "@opentelemetry/instrumentation-grpc": "^0.219.0", - "@opentelemetry/instrumentation-hapi": "^0.65.0", - "@opentelemetry/instrumentation-host-metrics": "^0.2.0", - "@opentelemetry/instrumentation-http": "^0.219.0", - "@opentelemetry/instrumentation-ioredis": "^0.67.0", - "@opentelemetry/instrumentation-kafkajs": "^0.28.0", - "@opentelemetry/instrumentation-knex": "^0.63.0", - "@opentelemetry/instrumentation-koa": "^0.67.0", - "@opentelemetry/instrumentation-lru-memoizer": "^0.63.0", - "@opentelemetry/instrumentation-memcached": "^0.62.0", - "@opentelemetry/instrumentation-mongodb": "^0.72.0", - "@opentelemetry/instrumentation-mongoose": "^0.65.0", - "@opentelemetry/instrumentation-mysql": "^0.65.0", - "@opentelemetry/instrumentation-mysql2": "^0.65.0", - "@opentelemetry/instrumentation-nestjs-core": "^0.65.0", - "@opentelemetry/instrumentation-net": "^0.63.0", - "@opentelemetry/instrumentation-openai": "^0.17.0", - "@opentelemetry/instrumentation-oracledb": "^0.44.0", - "@opentelemetry/instrumentation-pg": "^0.71.0", - "@opentelemetry/instrumentation-pino": "^0.65.0", - "@opentelemetry/instrumentation-redis": "^0.67.0", - "@opentelemetry/instrumentation-restify": "^0.64.0", - "@opentelemetry/instrumentation-router": "^0.63.0", - "@opentelemetry/instrumentation-runtime-node": "^0.32.0", - "@opentelemetry/instrumentation-socket.io": "^0.66.0", - "@opentelemetry/instrumentation-tedious": "^0.38.0", - "@opentelemetry/instrumentation-undici": "^0.29.0", - "@opentelemetry/instrumentation-winston": "^0.63.0", - "@opentelemetry/resource-detector-alibaba-cloud": "^0.34.0", - "@opentelemetry/resource-detector-aws": "^2.19.0", - "@opentelemetry/resource-detector-azure": "^0.27.0", - "@opentelemetry/resource-detector-container": "^0.8.10", - "@opentelemetry/resource-detector-gcp": "^0.54.0", - "@opentelemetry/resources": "^2.0.0", - "@opentelemetry/sdk-node": "^0.219.0" + "@opentelemetry/instrumentation": "^0.300.0", + "@opentelemetry/instrumentation-amqplib": "^0.71.0", + "@opentelemetry/instrumentation-aws-lambda": "^0.76.0", + "@opentelemetry/instrumentation-aws-sdk": "^0.79.0", + "@opentelemetry/instrumentation-bunyan": "^0.69.0", + "@opentelemetry/instrumentation-cassandra-driver": "^0.69.0", + "@opentelemetry/instrumentation-connect": "^0.67.0", + "@opentelemetry/instrumentation-cucumber": "^0.40.0", + "@opentelemetry/instrumentation-dataloader": "^0.41.0", + "@opentelemetry/instrumentation-dns": "^0.67.0", + "@opentelemetry/instrumentation-express": "^0.72.0", + "@opentelemetry/instrumentation-fs": "^0.43.0", + "@opentelemetry/instrumentation-generic-pool": "^0.67.0", + "@opentelemetry/instrumentation-graphql": "^0.72.0", + "@opentelemetry/instrumentation-grpc": "^0.300.0", + "@opentelemetry/instrumentation-hapi": "^0.70.0", + "@opentelemetry/instrumentation-host-metrics": "^0.7.0", + "@opentelemetry/instrumentation-http": "^0.300.0", + "@opentelemetry/instrumentation-ioredis": "^0.72.0", + "@opentelemetry/instrumentation-kafkajs": "^0.33.0", + "@opentelemetry/instrumentation-knex": "^0.68.0", + "@opentelemetry/instrumentation-koa": "^0.72.0", + "@opentelemetry/instrumentation-lru-memoizer": "^0.68.0", + "@opentelemetry/instrumentation-memcached": "^0.67.0", + "@opentelemetry/instrumentation-mongodb": "^0.77.0", + "@opentelemetry/instrumentation-mongoose": "^0.70.0", + "@opentelemetry/instrumentation-mysql": "^0.70.0", + "@opentelemetry/instrumentation-mysql2": "^0.70.0", + "@opentelemetry/instrumentation-nestjs-core": "^0.71.0", + "@opentelemetry/instrumentation-net": "^0.68.0", + "@opentelemetry/instrumentation-openai": "^0.22.0", + "@opentelemetry/instrumentation-oracledb": "^0.49.0", + "@opentelemetry/instrumentation-pg": "^0.77.0", + "@opentelemetry/instrumentation-pino": "^0.70.0", + "@opentelemetry/instrumentation-redis": "^0.72.0", + "@opentelemetry/instrumentation-restify": "^0.69.0", + "@opentelemetry/instrumentation-router": "^0.68.0", + "@opentelemetry/instrumentation-runtime-node": "^0.37.0", + "@opentelemetry/instrumentation-socket.io": "^0.71.0", + "@opentelemetry/instrumentation-tedious": "^0.43.0", + "@opentelemetry/instrumentation-undici": "^0.34.0", + "@opentelemetry/instrumentation-winston": "^0.69.0", + "@opentelemetry/resource-detector-alibaba-cloud": "^0.39.0", + "@opentelemetry/resource-detector-aws": "^3.0.0", + "@opentelemetry/resource-detector-azure": "^0.32.0", + "@opentelemetry/resource-detector-container": "^0.9.0", + "@opentelemetry/resource-detector-gcp": "^0.59.0", + "@opentelemetry/resources": "^3.0.0", + "@opentelemetry/sdk-node": "^0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.4.1", - "@opentelemetry/core": "^2.0.0" + "@opentelemetry/api": "^1.10.0", + "@opentelemetry/core": "^3.0.0" } }, "node_modules/@opentelemetry/configuration": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/configuration/-/configuration-0.219.0.tgz", - "integrity": "sha512-wXZUYv4ngu43nA4WEhuXNacm46LW+17LRM8nKyIhBzroRA24PBYjMnakwzR/w777nFUB5xlgsYTTeuXxumZM1Q==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/configuration/-/configuration-0.300.0.tgz", + "integrity": "sha512-vflvT+be02dmKt430t+XAQ2QvcPzjZODdVqMqbpuakuGk4i0zCZ7SyM9VOFHGuBV/HxfVlf3EvgHBGKob2P8TQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "yaml": "^2.0.0" + "@opentelemetry/core": "3.0.0", + "yaml": "^2.8.3" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0" } }, "node_modules/@opentelemetry/context-async-hooks": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-2.8.0.tgz", - "integrity": "sha512-/3FIraneMcng67SUJCxvyInk/oxzwsxyadufk0wwfOBLf5wqtAGX4MoQASwSbndBPeARzBryUM9Azr5kHIdWLw==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/context-async-hooks/-/context-async-hooks-3.0.0.tgz", + "integrity": "sha512-qDZeKSgTT+qTaL99eRbpvWO5+oZ0MKvMH4pqvzi6xYKyhiMTDBxBeTLI6BpdeMt58T5TpxHJvFl9P52i6CDWGA==", "license": "Apache-2.0", "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" + "@opentelemetry/api": ">=1.0.0 <1.11.0" } }, "node_modules/@opentelemetry/core": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-2.8.0.tgz", - "integrity": "sha512-hd1Lfh8p545nNz+jq1Ejfz+Mn1hyLuxYn1YzTfFNrxr8urEWMNQLPf1Th8kjOH+HxwawCrtgBp8JpBUR4ZSgww==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/core/-/core-3.0.0.tgz", + "integrity": "sha512-whOLlww0R/RLtCWGBXhK1fdvL9t2/TL0fqdjZvcaoUUuNilRPjXecqQdzyVwV68s6XEDA5oYbm7/bZT62GXF4A==", "license": "Apache-2.0", - "peer": true, "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" + "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "node_modules/@opentelemetry/exporter-logs-otlp-grpc": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-grpc/-/exporter-logs-otlp-grpc-0.219.0.tgz", - "integrity": "sha512-7SvzDCIclHWAcCwZ1MTOLcwn4BVNPGI3QxS/DJraPNe1TTL+4TvUBq5zeQV8tsnYvtDN7wKW2qocVmaCP2l7sQ==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-grpc/-/exporter-logs-otlp-grpc-0.300.0.tgz", + "integrity": "sha512-y4BAcN2UBSBs+esuIyXonpV44oeENKdit1BVKvjHf/61KvZVf7u1sTRz2VGwBpGJvUD7rNPjOZnb4PpG3vFEvg==", "license": "Apache-2.0", "dependencies": { - "@grpc/grpc-js": "^1.14.3", - "@opentelemetry/core": "2.8.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-grpc-exporter-base": "0.219.0", - "@opentelemetry/otlp-transformer": "0.219.0", - "@opentelemetry/sdk-logs": "0.219.0" + "@opentelemetry/otlp-exporter-base": "0.300.0", + "@opentelemetry/otlp-grpc-exporter-base": "0.300.0", + "@opentelemetry/otlp-transformer": "0.300.0", + "@opentelemetry/sdk-logs": "3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-logs-otlp-http": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-http/-/exporter-logs-otlp-http-0.219.0.tgz", - "integrity": "sha512-mhl2HL6GmZI8b8PwPfqMws/5ovJfbRTxwc9Y5agVVHiQ+e5SL1btsFr/kJDgt7YCexDtsUn5HAreHQO9szFS0A==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-http/-/exporter-logs-otlp-http-0.300.0.tgz", + "integrity": "sha512-S8yP9Fg33CU9+0fr1pnh/afPfgEpSyxQO4JRUZvmDMhAzgR/RLzvYg93MjWjbC1c2VrXffXROMO68RZ1P/ebgQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "0.219.0", - "@opentelemetry/core": "2.8.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-transformer": "0.219.0", - "@opentelemetry/sdk-logs": "0.219.0" + "@opentelemetry/otlp-exporter-base": "0.300.0", + "@opentelemetry/otlp-transformer": "0.300.0", + "@opentelemetry/sdk-logs": "3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-logs-otlp-proto": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-proto/-/exporter-logs-otlp-proto-0.219.0.tgz", - "integrity": "sha512-Ayw4Gf71PS9jhBVaYywa4WsajnqfDehMkTdVH3TSAVHqPcsAv/AhH/wTNRYNt99szeYr6Gbd/D6RjZD77wAxHg==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-logs-otlp-proto/-/exporter-logs-otlp-proto-0.300.0.tgz", + "integrity": "sha512-i9EqF1mvD0IrL6yBAqb2Cnv61WIYjkBxb36MulHf6/iAb/c653onKVWRJbpexBOHq+fd0VjH+1mhn+AtpFIZwQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "0.219.0", - "@opentelemetry/core": "2.8.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-transformer": "0.219.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-logs": "0.219.0", - "@opentelemetry/sdk-trace-base": "2.8.0" + "@opentelemetry/otlp-exporter-base": "0.300.0", + "@opentelemetry/otlp-transformer": "0.300.0", + "@opentelemetry/sdk-logs": "3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-metrics-otlp-grpc": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-grpc/-/exporter-metrics-otlp-grpc-0.219.0.tgz", - "integrity": "sha512-6LaaSrPxK5L55bXevWajvOMxGOpNm0n12tG53TeZaUeNzXwLPg6d2KCC1zAlGsojan+xRG71mA4Qqs9K2VVrKQ==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-grpc/-/exporter-metrics-otlp-grpc-0.300.0.tgz", + "integrity": "sha512-Kbfh2eVuj19WxByTI+UOhzjsyhNnl4lovjl9DYr0QsEpAPDyzWxGQmBDaTgIq1Tv3/Zc9ZDczAa//T2bjzac3w==", "license": "Apache-2.0", "dependencies": { - "@grpc/grpc-js": "^1.14.3", - "@opentelemetry/core": "2.8.0", - "@opentelemetry/exporter-metrics-otlp-http": "0.219.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-grpc-exporter-base": "0.219.0", - "@opentelemetry/otlp-transformer": "0.219.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-metrics": "2.8.0" + "@opentelemetry/exporter-metrics-otlp-http": "0.300.0", + "@opentelemetry/otlp-grpc-exporter-base": "0.300.0", + "@opentelemetry/otlp-transformer": "0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-metrics-otlp-http": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-http/-/exporter-metrics-otlp-http-0.219.0.tgz", - "integrity": "sha512-6CaDRbMVHZSDWzNXwrR8y/H4B/Z1eMNnkHiPQlTx3Ojz2OHY4X/aff/UC4P/3pHUQSuTfi3oh2UsPPZppw+Vrg==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-http/-/exporter-metrics-otlp-http-0.300.0.tgz", + "integrity": "sha512-y8KYKyM69l9PG4Ax9DKlKH5jaVJCJo9hXOpT6v0/PDX+uC302AhHVitEz8M600ljqLGdPYodnyn+wbYIYXPh6g==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-transformer": "0.219.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-metrics": "2.8.0" + "@opentelemetry/core": "3.0.0", + "@opentelemetry/otlp-exporter-base": "0.300.0", + "@opentelemetry/otlp-transformer": "0.300.0", + "@opentelemetry/sdk-metrics": "3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-metrics-otlp-proto": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-proto/-/exporter-metrics-otlp-proto-0.219.0.tgz", - "integrity": "sha512-DUS7XyIiEnoeccQUvuKy0G2/YqeKhpN8FVIrGbrLNIVMj10yeIFLRzRv0tibCI2kXXvlTTABVexGAk78wHk2ug==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-metrics-otlp-proto/-/exporter-metrics-otlp-proto-0.300.0.tgz", + "integrity": "sha512-tCL75kJ0JgLmbNCcpYgYpsRht8HgQJwd6LatK9g19O2nTd2GE3v2d38I1m1cVjKw1NRR+vtqei8AzGrznYtm9A==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "@opentelemetry/exporter-metrics-otlp-http": "0.219.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-transformer": "0.219.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-metrics": "2.8.0" + "@opentelemetry/exporter-metrics-otlp-http": "0.300.0", + "@opentelemetry/otlp-exporter-base": "0.300.0", + "@opentelemetry/otlp-transformer": "0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-prometheus": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-prometheus/-/exporter-prometheus-0.219.0.tgz", - "integrity": "sha512-TxOnJ85eWJY5JyOJsNMXiRTYlkDcOv0u3KbXEzWCc+tUS9sjL/BC6BcdxZ0B9r2OFVqsrZFXUzSD2sZUy42Ucw==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-prometheus/-/exporter-prometheus-0.300.0.tgz", + "integrity": "sha512-x8MCVBUPYZeQcL14HJUiYuF6IL4/YZ5OtR5ObnznUaTrhPdZUEvOQ4EpkLvfFph/nvk4lEs0cJ6uK5oMrFyjGQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-metrics": "2.8.0", + "@opentelemetry/core": "3.0.0", + "@opentelemetry/resources": "3.0.0", + "@opentelemetry/sdk-metrics": "3.0.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.3.0" + "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-grpc": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-grpc/-/exporter-trace-otlp-grpc-0.219.0.tgz", - "integrity": "sha512-BkDNv1UD6BscW19MxbAxVmSYSSFuyeqR6buV2/HTYqA7GrR0EbTFzqG6h86T3PtXmpdbsWjMGLDdjG2rikG27Q==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-grpc/-/exporter-trace-otlp-grpc-0.300.0.tgz", + "integrity": "sha512-I0/XvL7lLsn8aU8wnoIjIbcjcFfltEHsgf56s1vzAxB7CLRKzv/MUpTbIHWY5Eeci1448cAqiDSuj5GU5OcfKg==", "license": "Apache-2.0", "dependencies": { - "@grpc/grpc-js": "^1.14.3", - "@opentelemetry/core": "2.8.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-grpc-exporter-base": "0.219.0", - "@opentelemetry/otlp-transformer": "0.219.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-trace-base": "2.8.0" + "@opentelemetry/otlp-exporter-base": "0.300.0", + "@opentelemetry/otlp-grpc-exporter-base": "0.300.0", + "@opentelemetry/otlp-transformer": "0.300.0", + "@opentelemetry/sdk-trace": "3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-http": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.219.0.tgz", - "integrity": "sha512-9t6SvBXXBEjOBcIzgozvBbd3jWrv3Gt3ngGhl1fhdZ/zRc7oZDVOFEqbi2zlBpW9BXhgDMKv422J0DL/3iQWfw==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-http/-/exporter-trace-otlp-http-0.300.0.tgz", + "integrity": "sha512-Dwdagba93cdhROlFGbkU4yK4hvd3l0k7WV9nvTWIoN6KwxFP+HCvy9EkgIpyfN11fVdIWxY3XqOwWOq83OPfcA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-transformer": "0.219.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-trace-base": "2.8.0" + "@opentelemetry/otlp-exporter-base": "0.300.0", + "@opentelemetry/otlp-transformer": "0.300.0", + "@opentelemetry/sdk-trace": "3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-trace-otlp-proto": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-proto/-/exporter-trace-otlp-proto-0.219.0.tgz", - "integrity": "sha512-lF/LUBfhOFmxJa+SQsLN7ziV4MHa2pyKgOM6JNehSOfU+npjM4gwm9oIKEJrzrWcexMcqydiyoFy0XCb1Ql3wQ==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-trace-otlp-proto/-/exporter-trace-otlp-proto-0.300.0.tgz", + "integrity": "sha512-ZCWrexCUsfp5o5Eti91uvTlXMfszknzrPt3VM+jAk/Q5T53S/ix6mF07ndSHAhreQ5bKmBg3r1Ar4wkqQ1XlPQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-transformer": "0.219.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-trace-base": "2.8.0" + "@opentelemetry/otlp-exporter-base": "0.300.0", + "@opentelemetry/otlp-transformer": "0.300.0", + "@opentelemetry/sdk-trace": "3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/exporter-zipkin": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-zipkin/-/exporter-zipkin-2.8.0.tgz", - "integrity": "sha512-Mj84UkEa17BK2o903VTXW3wM8CrSZexGs4tRGVZVIMM9ni1T6TuGx5IrRfoWKAbshx42D5/kc7YV+axypLPYyA==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/exporter-zipkin/-/exporter-zipkin-3.0.0.tgz", + "integrity": "sha512-swgbcj76LgjoLPCYyyX0G27kW2+V8PifDeXRVpQ7vokwldKgLrw7GkDo5A2wD3yAWZKDvSWWjMigC3RT7xsuMA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-trace-base": "2.8.0", + "@opentelemetry/core": "3.0.0", + "@opentelemetry/sdk-trace": "3.0.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "node_modules/@opentelemetry/instrumentation": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.219.0.tgz", - "integrity": "sha512-X5t7I8GyIO9rmGHwoedZLREpQqrF1WW2nxzNNym6HOKpFiE+rvqV3ngC0xcZVO2YwIGf3KKmRdWrYwdwz3H9RQ==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation/-/instrumentation-0.300.0.tgz", + "integrity": "sha512-8ugx3X75uK2+rFZ9pX252ruDRELE2F7T3Zwazyll21aXksm+d2JLc9Np9SPS48K4ohGeaaXXHSX4ghxuNQ/gMg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "0.219.0", "import-in-the-middle": "^3.0.0", "require-in-the-middle": "^8.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.3.0" + "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "node_modules/@opentelemetry/instrumentation-amqplib": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-amqplib/-/instrumentation-amqplib-0.66.0.tgz", - "integrity": "sha512-lyJgobzP0Ce+tRGOkdnrb60apfqU89xB9FeMTmo1TJU007KTMLiLFd4iCfTiBEXzBsVplx7kwrVN4FqGBUcD2Q==", + "version": "0.71.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-amqplib/-/instrumentation-amqplib-0.71.0.tgz", + "integrity": "sha512-udno0udqQshCVP1I+rMWtV66NOCEn6WBTtRvdBAiDMvGwojwPDiCX6QshMZbjdW/qisbojubizAdWdjx4mUp3w==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.33.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-aws-lambda": { - "version": "0.71.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-aws-lambda/-/instrumentation-aws-lambda-0.71.0.tgz", - "integrity": "sha512-9Sv6flQDeNNF6ZbiLgn+NYJa220yRZdDSIdgDZsqNubpDnYAPF33OHcQDlE8mFiaOq14mngoPS48JnYc8JT+Ug==", + "version": "0.76.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-aws-lambda/-/instrumentation-aws-lambda-0.76.0.tgz", + "integrity": "sha512-hsaeVoaGS44qXfe23ebEVA9XsE4D/pukhfT4SeNKlhyOBeHDVFnCc2RLOa6t9v5tNTbS3D4cUXc04gjSBZAy3g==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", - "@opentelemetry/propagator-aws-xray": "^2.1.4", + "@opentelemetry/instrumentation": "^0.300.0", + "@opentelemetry/propagator-aws-xray": "^3.0.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/aws-lambda": "^8.10.155" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-aws-sdk": { - "version": "0.74.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-aws-sdk/-/instrumentation-aws-sdk-0.74.0.tgz", - "integrity": "sha512-EMLUGgx2wJSXdwMEFdwd3IaW+mkUF8PENdzDFQ1FRdztzMG1d1XN76ORIjAMsXcKQISlRRcz93AWPQeBPn4EKA==", + "version": "0.79.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-aws-sdk/-/instrumentation-aws-sdk-0.79.0.tgz", + "integrity": "sha512-B8dcjI9eNwHPJWRUIROcsuiXwsHNxa05J9Uy6ahlN9qUEMyBdK3sPzCsDKC5YbGFPGiC8aN9m5mSjGQdXoswwQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.34.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-bunyan": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-bunyan/-/instrumentation-bunyan-0.64.0.tgz", - "integrity": "sha512-jrRNFvpREutmpoWhk1T8n9q/RYdxbViXwSUPHN8yQR1bzgtwfOl/y8G/p8Xfudlky9GGsqw5WRc6q6QrfgF3pw==", + "version": "0.69.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-bunyan/-/instrumentation-bunyan-0.69.0.tgz", + "integrity": "sha512-Q+ur3anFLSWa28aQJg/hvjgBv81ju65qBQXj5s/bL1Xpza3wysrKGwA4gx8106Nil9iwdm+KQZF9hge8heROwQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "^0.219.0", - "@opentelemetry/instrumentation": "^0.219.0", - "@types/bunyan": "1.8.11" + "@opentelemetry/instrumentation": "^0.300.0", + "@opentelemetry/semantic-conventions": "^1.41.1" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.3.0" + "@opentelemetry/api": "^1.10.0" } }, "node_modules/@opentelemetry/instrumentation-cassandra-driver": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-cassandra-driver/-/instrumentation-cassandra-driver-0.64.0.tgz", - "integrity": "sha512-KN+iOsmPI0nkX2lfgNgHBrHNaDuxDwIbwFrlvyrZ4bAT8bTKcCOXhne70O9qihM8+T1F4tjvPXpCfhKZbmsYiw==", + "version": "0.69.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-cassandra-driver/-/instrumentation-cassandra-driver-0.69.0.tgz", + "integrity": "sha512-fdFuSVEW1QRm5wfyvHew3RseIXuPK3Fk9OhMQbgbik37Rc0tUuYf9aLUuUANu1qQlMfXr0lhLTaUekUKnUg8vg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.37.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-connect": { - "version": "0.62.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-connect/-/instrumentation-connect-0.62.0.tgz", - "integrity": "sha512-ZGV2sOyeffqMiqoh4RpsPTs/TUI5cCS+cEWvC9wUfvaEekR5omR6P/ClG+QDwasGBlKx2zfFPjSYPpzUo81XAw==", + "version": "0.67.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-connect/-/instrumentation-connect-0.67.0.tgz", + "integrity": "sha512-Y7Vh+iKuOAEwUJ4JOI5OvNK56E1PixoDpK+Bfj4QnBivkqHEZEUqbnYRhvHFVXYisP/xeJKOh3pU+iOnxJHedA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.27.0", "@types/connect": "3.4.38" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-cucumber": { - "version": "0.35.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-cucumber/-/instrumentation-cucumber-0.35.0.tgz", - "integrity": "sha512-H9NsbcFiVOFOcOu40+VOOjxdTeonu0VHI3mte5ie5ka/bazzIPGncQoHpL6su53C3/sgMdKjE6ZuwsB7Y8gQpA==", + "version": "0.40.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-cucumber/-/instrumentation-cucumber-0.40.0.tgz", + "integrity": "sha512-CQ6UlOpTdDEvBlEWsYIeQ0A1zk89bJLhY9WEG7jrOrFXoLYW8Zicvxa1MaMq0xiEooagTrPoV6+Gtwkd28Ekzw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "node_modules/@opentelemetry/instrumentation-dataloader": { - "version": "0.36.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-dataloader/-/instrumentation-dataloader-0.36.0.tgz", - "integrity": "sha512-gE0mTk+EnVaBN0mPRM1V6FqzQ9VckTp6ZFIssU5hxy+e3sqspYILBhV/0IHZ33qxGa3B9buLVZnuzVjUISfyoQ==", + "version": "0.41.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-dataloader/-/instrumentation-dataloader-0.41.0.tgz", + "integrity": "sha512-Y6wQwsfCgUW0oie1MCaK+nvx4zIN8BHV0rozno5QbmNZN/Td1N5jG0D+Y5Y6bt8Oo7Wyxz8Q8aw6Y5pz3q+iyg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0" + "@opentelemetry/instrumentation": "^0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-dns": { - "version": "0.62.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-dns/-/instrumentation-dns-0.62.0.tgz", - "integrity": "sha512-6v0X8wEqhIyv2b7MXhmipyCitJfm0vnF5mLBTWXojovoHp7P1EpN5sb12LgdhVlozhGwRZdzb6OvKUVsxKMD8g==", + "version": "0.67.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-dns/-/instrumentation-dns-0.67.0.tgz", + "integrity": "sha512-ENj4hL4w2ilMdq3jhf9dDg5CDzjCuTsshTRTse7j0AjIIFS1knP75BQR0Qmx2URPttW6NbwU61jW1v9vxJ4vfA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0" + "@opentelemetry/instrumentation": "^0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-express": { - "version": "0.67.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-express/-/instrumentation-express-0.67.0.tgz", - "integrity": "sha512-1WTWX2YNZIV+jPmEqdf/Vd1gHMT92TKA/0pf/iIItWhV6+RhzhnUUW4kSWQn8L3qVcgWEzQ860/ZOwaIwayi8A==", + "version": "0.72.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-express/-/instrumentation-express-0.72.0.tgz", + "integrity": "sha512-YV1T099/8acoA7giEBWm8NJJy+zyMElFkf5DGGcNsBftrA1TLVpctAKBUaV97TOXa+RlglwmxqtOPsF5+KCbzA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-fs": { - "version": "0.38.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-fs/-/instrumentation-fs-0.38.0.tgz", - "integrity": "sha512-6OBofWODg0RcPkl3bA+7yPf0e4Vi3O7ZxlFGY5QHPMMLxWVMnjWPEXQ2NlLBk19Sr8LcvEyyZOStdLJrT5o2dQ==", + "version": "0.43.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-fs/-/instrumentation-fs-0.43.0.tgz", + "integrity": "sha512-8Q4DmSloluXR4L+nJ91IbmvvBLw3ubc06jG+AN9S+munVJCzA+b9gLm3VCzj3wyh+ZN5C08+5EaTvShnR8bEMQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0" + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-generic-pool": { - "version": "0.62.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-generic-pool/-/instrumentation-generic-pool-0.62.0.tgz", - "integrity": "sha512-IhO2y/MaK1oZ4EbUgdkSVT+XViPq86IAz4lwPe9jaba00M2yDWs8+f9xjcH3tK5IC3dZuAxXmifGmfvuJp92jw==", + "version": "0.67.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-generic-pool/-/instrumentation-generic-pool-0.67.0.tgz", + "integrity": "sha512-IE8Zws++d8de9Nv1Zb32eaFfXIv7PCsV+YyvwIEb0jpkWjfh2ZqmrgZsHzGOeLvgStFY4tN380lbcMR67FdSGw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0" + "@opentelemetry/instrumentation": "^0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-graphql": { - "version": "0.67.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-graphql/-/instrumentation-graphql-0.67.0.tgz", - "integrity": "sha512-NMUmuhtYvv3AwkK4zsHQbTCXS81QS63hbNZRKfXc7W8f4KbWeKLmqKqvnfjUcqZoGS0eAw2kNKNYcbtbQ7baAg==", + "version": "0.72.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-graphql/-/instrumentation-graphql-0.72.0.tgz", + "integrity": "sha512-kyDJXU6t3rPYkY94riEk8MuhTZZ9stNzd5vQ3EYRpFSCdrRwP8gWSSoFnRJVhFWIruC6d5/JdqVFKUjmJ65p+g==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0" + "@opentelemetry/instrumentation": "^0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-grpc": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-grpc/-/instrumentation-grpc-0.219.0.tgz", - "integrity": "sha512-GyW1Kfbf7uiJXeBZovB/uXPUdkaZYWzB2ZPCdY2CU7+6V207u8wlCM+zVd3UwhEjOBrMbZAGq+m38aBEI/EVtA==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-grpc/-/instrumentation-grpc-0.300.0.tgz", + "integrity": "sha512-znZl9LN1Dqg2rqSBRnARApBUlG7vz4FZavWoZ4TxFA7gIIqHfsbImkX/QJCNCiCGEBD8Stji9Ix6Ev25NptK9Q==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "0.219.0", + "@opentelemetry/instrumentation": "0.300.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-hapi": { - "version": "0.65.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-hapi/-/instrumentation-hapi-0.65.0.tgz", - "integrity": "sha512-Whhas9iU0SfK/7XBcgCwfW5c9AaxjxtZpzW21t3Ml8XZ6Irc3hF36JDolMmFa7nUjML9n9bSUAZjwCgrK+2UdQ==", + "version": "0.70.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-hapi/-/instrumentation-hapi-0.70.0.tgz", + "integrity": "sha512-ech8E3/hv6fuTxUfA3QKPpNaRL5/s75C7+/JDMMbff0jMG4wGkAiLJqDjyfaOvP6cqW9EiHqaznZ8/uhrloJsw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-host-metrics": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-host-metrics/-/instrumentation-host-metrics-0.2.0.tgz", - "integrity": "sha512-NIttCEOLdg1ebbDiJpCf0Ly1OGIa10isesik+K2dnXy2P99q4muUFjpaLtTnhkENrt9SmR0Zrxzq7B+W/VNWyw==", + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-host-metrics/-/instrumentation-host-metrics-0.7.0.tgz", + "integrity": "sha512-S5BbKqXWDYMxWyvsIMNYfPcGfwsODg/xHnBI0SylG3yBnZuQ7Su3EMUK+pY2mBgkqtUAFPXv7P285/AmF7j+xg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "systeminformation": "^5.31.6" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-http": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-http/-/instrumentation-http-0.219.0.tgz", - "integrity": "sha512-nNt1fqpyah/OKjNHdEOu8xLwISppRU2qJuF8aR+fCcftVwdFkPgtworBLA+TI1HU2iF508jcQBF2gerWczJAXg==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-http/-/instrumentation-http-0.300.0.tgz", + "integrity": "sha512-kAU01q92leb1rMuF5fhuQKjP3MkdCxSiUT/IWo409YrQMbQdLGmM4EyH6RoSmInNSulSgKWkja+IyglnZSPYXg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "@opentelemetry/instrumentation": "0.219.0", + "@opentelemetry/core": "3.0.0", + "@opentelemetry/instrumentation": "0.300.0", "@opentelemetry/semantic-conventions": "^1.29.0", "forwarded-parse": "2.1.2" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-ioredis": { - "version": "0.67.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-ioredis/-/instrumentation-ioredis-0.67.0.tgz", - "integrity": "sha512-dv64vQ4aXbJvRMMAFrMUSzDeJrNv/uQMLjfaav4LHAOar7Xn08W3pkoYoYEnzq/n2+fGgG96rp9S0gQ+VnLDiw==", + "version": "0.72.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-ioredis/-/instrumentation-ioredis-0.72.0.tgz", + "integrity": "sha512-Z3btRN3tAVKbc48h4LuHTfOOnQdrhJ5PdtYAhvXkbdH2neBo8FSvpr4PIt4nvqk6XO5Gyqba3CeP48zaOmrYkQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", - "@opentelemetry/redis-common": "^0.38.3", + "@opentelemetry/instrumentation": "^0.300.0", + "@opentelemetry/redis-common": "^0.39.0", "@opentelemetry/semantic-conventions": "^1.33.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-kafkajs": { - "version": "0.28.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-kafkajs/-/instrumentation-kafkajs-0.28.0.tgz", - "integrity": "sha512-dztkg70nJds3Uc0Xo3NFlRqL5iYgGYWh8myuuGfRC6NnXJchY0Kw9QnBjTZxBSldXU+P6nv2snDVMmlxuy6fEw==", + "version": "0.33.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-kafkajs/-/instrumentation-kafkajs-0.33.0.tgz", + "integrity": "sha512-b1fUlGKB4xAQhAABxUDxINTPIUptC/fa4E5CSmVBNvd/Vr+orFbnXLCz3PWuTH8hR0Ewucwzzll3W6wJmIh1Lw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.30.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-knex": { - "version": "0.63.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-knex/-/instrumentation-knex-0.63.0.tgz", - "integrity": "sha512-XrpRahI/9vTrfSUfkhy8jGX8KMRKecQIPU9GyEZ8gkR030iJwQYsMmKGO5TK9R80cQGUopXwDvV55zmVNEkcPg==", + "version": "0.68.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-knex/-/instrumentation-knex-0.68.0.tgz", + "integrity": "sha512-sCXpcMsx4Qbg5WZ+vzmaGDJnlUjrVee+cQ812xYkcmjRoYCcQH1L631rqHfUOu9OqqCwtt2/iRIzRcJYUx5lKg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.33.1" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-koa": { - "version": "0.67.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-koa/-/instrumentation-koa-0.67.0.tgz", - "integrity": "sha512-QOGY4mjqvF85LDcrzwrQXMcsu1wMTALeL1OHyTkLpN/7cnoDtv0W/qMBjHVq4IKYK6yDH4ZDNdwlonJPhwCGcw==", + "version": "0.72.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-koa/-/instrumentation-koa-0.72.0.tgz", + "integrity": "sha512-tldfHvVxFHK/K8PcRQjegk2md0YWbkRQepU0/7rnQV/bvTD2oGu9JeNByBSk/Ckk5rH3qq7wdXSRoIajbQIjxw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.36.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.9.0" } }, "node_modules/@opentelemetry/instrumentation-lru-memoizer": { - "version": "0.63.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-lru-memoizer/-/instrumentation-lru-memoizer-0.63.0.tgz", - "integrity": "sha512-DlZRNXfiosmREoLbEGbYuxF70cYXjrYqoaO1sJE167i1+ARWXTq0YMPJ97i53Ws/xkZWllJNYU4mpY2LM2yTlA==", + "version": "0.68.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-lru-memoizer/-/instrumentation-lru-memoizer-0.68.0.tgz", + "integrity": "sha512-zNcs1A+FISUHhZuKnlfuCxKn8hgYA80qHVdxFyNCMmxdZyShGRP1KA8HGrGYk0JqQK391IYCgisyt+7TI+3crA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0" + "@opentelemetry/instrumentation": "^0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-memcached": { - "version": "0.62.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-memcached/-/instrumentation-memcached-0.62.0.tgz", - "integrity": "sha512-kAajd/MtdRBh9PCrMM4fnusFRNPJDU1dv5w9cgnKtMfutRE6K03wBbGSeT3FD1M56sMYWVqPhiKUhfSZCMZrLg==", + "version": "0.67.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-memcached/-/instrumentation-memcached-0.67.0.tgz", + "integrity": "sha512-EnjSnkxp7P/DGD3f/D/Uwa/BrsKWkRkEhR7OdTVyTnu1zk1p/vSTBnvLXVAqRqundONyWeHNeRrwDHBryFyR9Q==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.33.0", "@types/memcached": "^2.2.6" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-mongodb": { - "version": "0.72.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongodb/-/instrumentation-mongodb-0.72.0.tgz", - "integrity": "sha512-WYgGzvlHzdoxHlrhysYtjxE4RC23j/iFZ66hdMJuAoczOWoD/xb6LhRwaz4CM+LKyKtcSIadAjSUyGv2B+SNwg==", + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongodb/-/instrumentation-mongodb-0.77.0.tgz", + "integrity": "sha512-dC5tcoI/jrFvlS6CVayQ8nIU4OlTdRW6qFsCKI/C7UXRmXq7mPNA5DzwS0Pn2+KEMDGTuLamNRB9SNkFgraMVg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.33.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-mongoose": { - "version": "0.65.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongoose/-/instrumentation-mongoose-0.65.0.tgz", - "integrity": "sha512-P0iT4oKuinEFZlTIKPJC5hhnmiV9De9lEiLkGzSwnNLdkyHIWug8BfRp5ZROrYAQ9mm47H+WLB/ozvUvgzEvEA==", + "version": "0.70.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mongoose/-/instrumentation-mongoose-0.70.0.tgz", + "integrity": "sha512-cJSZVLCyozcoC+lDz3vhJgv6MtcppCZuZI5BpJlCxc15zR81AZ/807dyCSb7WEr5j15WkV1kLhYdJpS8Ugnwdg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.33.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-mysql": { - "version": "0.65.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql/-/instrumentation-mysql-0.65.0.tgz", - "integrity": "sha512-sh1wRjFaTt+8DOhJ0134rFtJoHVUXKI8faIWTbj4zZNw847dzUgmkO8xOluJ9Css0JzT4vCeZofJmq9mQmmESA==", + "version": "0.70.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql/-/instrumentation-mysql-0.70.0.tgz", + "integrity": "sha512-zr+Tc6bSlqfDT+7am7iwCYVFUwI0omf7BWPBdSCcmJBY9Wzp9L4wk8LAzAWgJ4Q6kIM0Ntx4RR+lY8llGMIFTQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", - "@opentelemetry/semantic-conventions": "^1.33.0", - "@types/mysql": "2.15.27" + "@opentelemetry/instrumentation": "^0.300.0", + "@opentelemetry/semantic-conventions": "^1.33.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-mysql2": { - "version": "0.65.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql2/-/instrumentation-mysql2-0.65.0.tgz", - "integrity": "sha512-Om6BJ/bmFBzNkGbAzj/UV5sCKX6jCGzhTl1Gqgtim/O0dnPE7F2zN65u16Fq3JgyypGAwT2iwh13tYdWkc8/RA==", + "version": "0.70.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-mysql2/-/instrumentation-mysql2-0.70.0.tgz", + "integrity": "sha512-c+wyti8w8xZuXRUsmMBzKXpnTxrafCITnm+UiWIq5oyOpp+Y6n03+ASEP7K+EBLIMQZR6U3EX0iYTlUF7S3hBw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.33.0", - "@opentelemetry/sql-common": "^0.42.0" + "@opentelemetry/sql-common": "^0.43.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-nestjs-core": { - "version": "0.65.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-nestjs-core/-/instrumentation-nestjs-core-0.65.0.tgz", - "integrity": "sha512-/q8fN2M2zGl+gQRaF79dzqvyvVqHAI11c7xAQZy9W1eAtQScNwaQtPm0EUo5+aOgakaTksBrsiHUF0rQS24NsQ==", + "version": "0.71.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-nestjs-core/-/instrumentation-nestjs-core-0.71.0.tgz", + "integrity": "sha512-EGqspwpbOdarPoXz2TQfvxiKvYujCW2REJM65/pr9SnuF+kW9oWHbJLypKAoxF14SF0SWHIwD7T8OrTmmfqcMQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.30.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-net": { - "version": "0.63.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-net/-/instrumentation-net-0.63.0.tgz", - "integrity": "sha512-fvmVdL4SlsYZf74mq6iLBPd6JJHRAe5utzN7Wt9e4nwa2S3pgExA9poOEmBL1CvIR47MceTA/A8vgVCF23ebbw==", + "version": "0.68.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-net/-/instrumentation-net-0.68.0.tgz", + "integrity": "sha512-SUwiNYcKWq5CVJC4CluReoDqnJdoNbwIcfJbqL0YVQN4gDWAi8vzeQMDAPfgIu4g0uuPEQV5/OTPjq4iGMgALg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.33.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-openai": { - "version": "0.17.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-openai/-/instrumentation-openai-0.17.0.tgz", - "integrity": "sha512-X3aEZnzj7SJkn1nmqEoD9IljmqENnGrd0vcJngcEApT8uqhFaeimONqKeIzKYvUgC7k4OkAUxC7yfXzxIK1KlA==", + "version": "0.22.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-openai/-/instrumentation-openai-0.22.0.tgz", + "integrity": "sha512-1TIMdTkdUYpqN1Sv1kBGMJcs7kaV2j9LqblHTBpmGHd+HDVNmxmBeM9/+T7HUrICWGPYy7xvFi004N+0vLVytg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "^0.219.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.36.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.3.0" + "@opentelemetry/api": "^1.10.0" } }, "node_modules/@opentelemetry/instrumentation-oracledb": { - "version": "0.44.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-oracledb/-/instrumentation-oracledb-0.44.0.tgz", - "integrity": "sha512-ncEfP4rzuZXBHJJtzWLYctK4Pq/FvZRiASxlFY9CJG9kGjaFTfzBUys0NiP27alYPvpjj0uDAMheDk9nihO8ZA==", + "version": "0.49.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-oracledb/-/instrumentation-oracledb-0.49.0.tgz", + "integrity": "sha512-JsnPQM3ifh/8n+BKIlo1WA+r0K6DgcaEkD9+m2+r6zNQz2pyS9H2F3WYtmyNoH+FnAuHtwrUTQgapLfwiaZNag==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", - "@opentelemetry/semantic-conventions": "^1.34.0", - "@types/oracledb": "6.5.2" + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", + "@opentelemetry/semantic-conventions": "^1.34.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-pg": { - "version": "0.71.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-pg/-/instrumentation-pg-0.71.0.tgz", - "integrity": "sha512-jAhfyZeOkEKh3cQ5nm1tNWqHg7HFARyAe+p4BSoDHnB79c1woyEvDKqS11Hj/DjtceP+vrurIfcDs7Fqiy11mQ==", + "version": "0.77.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-pg/-/instrumentation-pg-0.77.0.tgz", + "integrity": "sha512-eeM+nAWZqgwrSmGy/yt4wL8CSSXuHZXKyOOKiP0m6x7oA4AQ1Kl5bbHqdr1OkXu5LIXCnIWa6Cmw9tLdzCMLJA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.34.0", - "@opentelemetry/sql-common": "^0.42.0", + "@opentelemetry/sql-common": "^0.43.0", "@types/pg": "8.15.6", "@types/pg-pool": "2.0.7" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-pino": { - "version": "0.65.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-pino/-/instrumentation-pino-0.65.0.tgz", - "integrity": "sha512-p6eh+NRmzi1F+/4QG7XDqRk4ICdCNTsM5vdcwUPnpMie2MddgY1/ENmWvCF9r0Kh6QQRA2kkpnhoJFaiRQ5kVw==", + "version": "0.70.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-pino/-/instrumentation-pino-0.70.0.tgz", + "integrity": "sha512-JbxLZ5PhLJU0B1IWPX9/O14de8YGatiRLrlYz+cUy0no/rz6QLH8l6Bk+rF7geun4LHGqQlALIL/9SRDs+yuLg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "^0.219.0", - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0" + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", + "@opentelemetry/semantic-conventions": "^1.41.1" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.3.0" + "@opentelemetry/api": "^1.10.0" } }, "node_modules/@opentelemetry/instrumentation-redis": { - "version": "0.67.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-redis/-/instrumentation-redis-0.67.0.tgz", - "integrity": "sha512-TBjO4bPvfGH6bRjJJ+KrJhEqpHg3SWCFZ84MqsTWF639RQZmvkMhT2/DJsBAqqkq33IvHoDJysserqAfZN1s+Q==", + "version": "0.72.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-redis/-/instrumentation-redis-0.72.0.tgz", + "integrity": "sha512-e9S4dMYpwq1pllqr7supmEC7ZziAzCB/D24X7+VbDbcpl7J+C0Md6RDtcE7BQcsW7428P10lxrYAxWcNIP0GrA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", - "@opentelemetry/redis-common": "^0.38.3", + "@opentelemetry/instrumentation": "^0.300.0", + "@opentelemetry/redis-common": "^0.39.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-restify": { - "version": "0.64.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-restify/-/instrumentation-restify-0.64.0.tgz", - "integrity": "sha512-X+gL4KpfPAx7Y07zKQVtyJPckhCcYJdSlEz0Kq0iR5nkQ8/AVWJ05/txl4voZbZdCuNdn+uLZTtJ60bAQwputQ==", + "version": "0.69.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-restify/-/instrumentation-restify-0.69.0.tgz", + "integrity": "sha512-76fmH5TQd4V6lpou7AVy2hYi0KfS+VV2zA6PWW9kuFAN/yq0hAr16l7+bHPtM2ae4MY3TSO56gkFNpAjOHXWDg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-router": { - "version": "0.63.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-router/-/instrumentation-router-0.63.0.tgz", - "integrity": "sha512-zIpsZSHGvbaqiEazwUm1X0FkPnLXIwZcL/llu/UplkeGNU58bsw70l2uMqNqTb7J+tzsBC09CLVPty5BhW3X9Q==", + "version": "0.68.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-router/-/instrumentation-router-0.68.0.tgz", + "integrity": "sha512-EPc/e+ccOqYkIX4HRktNClgARaWoAsEjc4dAPt8V3bLySUktx+/Ew/+MZNtNS+CUE4n+J1BvGGdwh4+ZaHgb7A==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-runtime-node": { - "version": "0.32.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-runtime-node/-/instrumentation-runtime-node-0.32.0.tgz", - "integrity": "sha512-Jo1jSgrHlah3lPpGNPsIpF0q52D5uSLRJrztWUoPc1/Tli2ZWZ+cArgNtcdmiLuKhW21MwYbbcrNw1fbOPeR3A==", + "version": "0.37.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-runtime-node/-/instrumentation-runtime-node-0.37.0.tgz", + "integrity": "sha512-2QZ7M1OUTbowoExKX4eTrMAo0gO5dmxV91cARmkpHs2jzo6oFFLDTRfXluYMtNAhAhReswAsQ7BaKo7O7fo/rw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "^0.219.0", - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0" + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.3.0" + "@opentelemetry/api": "^1.10.0" } }, "node_modules/@opentelemetry/instrumentation-socket.io": { - "version": "0.66.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-socket.io/-/instrumentation-socket.io-0.66.0.tgz", - "integrity": "sha512-XrZmLkFJktVLd3biQiP8BAhupRwPWLHGIiDCfyDAnWI6borIL0wD6BpwFKKPT/etpu4/5OaeAQ7qs/S+FY9nhQ==", + "version": "0.71.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-socket.io/-/instrumentation-socket.io-0.71.0.tgz", + "integrity": "sha512-12dOOiqCwgaQYMR7A2S4aAScn4ZTznCZdzoKiQS9AVHFOYasADgNaiYs6C1odOehnOfNMwt4Z02d5tfhauqy/A==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0" + "@opentelemetry/instrumentation": "^0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-tedious": { - "version": "0.38.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-tedious/-/instrumentation-tedious-0.38.0.tgz", - "integrity": "sha512-9sRWyIMBHDqJvxRVZ+eQ7jHJ9Iu+DapO27WLZbQF1nyD8xIvEMuDonQ/HnlQiaRdwnqFknXSQTFusJUT3mNVyQ==", + "version": "0.43.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-tedious/-/instrumentation-tedious-0.43.0.tgz", + "integrity": "sha512-x+v44lSHbe2a3HCxXWy57jybInwKRNHcMOArycdsHPEw+8YzH2DzQZViTO/J165qbSF0o+q9F1OtTJvr88Q45Q==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/instrumentation": "^0.219.0", - "@opentelemetry/semantic-conventions": "^1.33.0", - "@types/tedious": "^4.0.14" + "@opentelemetry/instrumentation": "^0.300.0", + "@opentelemetry/semantic-conventions": "^1.33.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/instrumentation-undici": { - "version": "0.29.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-undici/-/instrumentation-undici-0.29.0.tgz", - "integrity": "sha512-SnA+0XgGc595jtnwFVfWy7Vgfr5hle4D5YKIlm0U4z8aK9YoCZVUn1xAkVZ2evaJyykiDF50FBzr1XZ0uj8CPA==", + "version": "0.34.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-undici/-/instrumentation-undici-0.34.0.tgz", + "integrity": "sha512-RcAEj8opdr/9BVZyEzJatN7sHQCgmdCLvb8Tvf5CNxRmdWbR3FaLN0h7JaI2ganW78MKAX2lM7O5isNIweabnA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/instrumentation": "^0.219.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/instrumentation": "^0.300.0", "@opentelemetry/semantic-conventions": "^1.24.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.7.0" } }, "node_modules/@opentelemetry/instrumentation-winston": { - "version": "0.63.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-winston/-/instrumentation-winston-0.63.0.tgz", - "integrity": "sha512-NFMHLYODph0rWGfT/QLv75hCsu1sxVAV79L8HduBCMo181jOTSRZHaqxfrvDtFOsvgYBaiUBa7Ga50w47wM3FA==", + "version": "0.69.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/instrumentation-winston/-/instrumentation-winston-0.69.0.tgz", + "integrity": "sha512-O+zFASmPbEd1hIx5Y/VGQsbf9/OFU4KtZXI1qFig/WYeY4YZeTKiMN2nn1UGDBoxeBahbXMkt26ZCMWF/PbGIQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "^0.219.0", - "@opentelemetry/instrumentation": "^0.219.0" + "@opentelemetry/instrumentation": "^0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.3.0" + "@opentelemetry/api": "^1.10.0" } }, "node_modules/@opentelemetry/otlp-exporter-base": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.219.0.tgz", - "integrity": "sha512-zvIxQX/AZUVKDU+hCuYx+7UkiP7GRdnk1ZbFQRYzHvYp47cAWR4j3IhoPhV9KaeXEv2xdGq3IA6PnpzDmLcmSA==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-exporter-base/-/otlp-exporter-base-0.300.0.tgz", + "integrity": "sha512-D+PhzYURtv6p7Kk1rUrilLtV+ZvS218tI0jiKTV5z1agOeELw78C+cFd3o9UUshUx1j+EIpFM62yGk8BuydQvg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "@opentelemetry/otlp-transformer": "0.219.0" + "@opentelemetry/core": "3.0.0", + "@opentelemetry/otlp-transformer": "0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/otlp-grpc-exporter-base": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-grpc-exporter-base/-/otlp-grpc-exporter-base-0.219.0.tgz", - "integrity": "sha512-iIk/s8QQu39zpTrRRmsW/Eg3SE2+Hg8tLWepr2FLRgmwUpNd0IpCTLJEHJ77hpt4hgIS8MAh44UYI4xQPZwWlw==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-grpc-exporter-base/-/otlp-grpc-exporter-base-0.300.0.tgz", + "integrity": "sha512-0C6rf7vVQrT7ZCUYJRZ1P4TsauCfSc4qXSpwqBWW5Ztt/4gxt5uHfLw2nTirSuPpz0sSeeRPW+Z0HyKJXB/CTQ==", "license": "Apache-2.0", "dependencies": { - "@grpc/grpc-js": "^1.14.3", - "@opentelemetry/core": "2.8.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-transformer": "0.219.0" + "@grpc/grpc-js": "^1.14.5", + "@opentelemetry/core": "3.0.0", + "@opentelemetry/otlp-exporter-base": "0.300.0", + "@opentelemetry/otlp-transformer": "0.300.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "node_modules/@opentelemetry/otlp-transformer": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.219.0.tgz", - "integrity": "sha512-aaYKAyXhw9VchKZVGOopD3Gw/kPsyrX2c6IQ0AW32mTjqmZOh5Y6Gf5OYqTNqVktAeBjmFinhyFaCwW6GYK9YQ==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/otlp-transformer/-/otlp-transformer-0.300.0.tgz", + "integrity": "sha512-T55lRmjRwvXWyTFdy/BbJ3T5RRsq3bAwQgxxA7qHFxgRd4+pZzRk02ZwOFsYK5072OXGYjYFNJcp68eQV4i0Ig==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "0.219.0", - "@opentelemetry/core": "2.8.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-logs": "0.219.0", - "@opentelemetry/sdk-metrics": "2.8.0", - "@opentelemetry/sdk-trace-base": "2.8.0" + "@opentelemetry/core": "3.0.0", + "@opentelemetry/resources": "3.0.0", + "@opentelemetry/sdk-logs": "3.0.0", + "@opentelemetry/sdk-metrics": "3.0.0", + "@opentelemetry/sdk-trace": "3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": "^1.3.0" + "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "node_modules/@opentelemetry/propagator-aws-xray": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-aws-xray/-/propagator-aws-xray-2.2.0.tgz", - "integrity": "sha512-Yjvt2EjL+tfpkVOdKbhTPgpM4SIAez9nG6Q/QjQ3yfcJcjIWp59ph70SLfvmkSL6++3DCnuBG3iWcB18PwWavQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-aws-xray/-/propagator-aws-xray-3.0.0.tgz", + "integrity": "sha512-5RHIXJFFPsX2e5Z2lUjcsCOkouW08PuFb9Vfg5l22E0PZ01tapU11wH/gb8RCGckjlvgoc+HrWmYtu/VqI2kAQ==", "license": "Apache-2.0", "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" + "@opentelemetry/api": ">=1.0.0 <1.11.0" } }, "node_modules/@opentelemetry/propagator-b3": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-b3/-/propagator-b3-2.8.0.tgz", - "integrity": "sha512-SazlvuSKi5533rPHTW2TwBwdMakhjZST4SYs0YauuvfGDkT13KbG1gJS75hV0uWVeevhtVP9sAIlaZLTHdSbMg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-b3/-/propagator-b3-3.0.0.tgz", + "integrity": "sha512-pmG16s+UYAobPmtWfkR1/UK233qdl79WO04GnNzr7aoG/P+Aafbn8+5OJg2zl107WvLPYelCUKFiI18GksGbqg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0" + "@opentelemetry/core": "3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" - } - }, - "node_modules/@opentelemetry/propagator-jaeger": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/propagator-jaeger/-/propagator-jaeger-2.8.0.tgz", - "integrity": "sha512-Xnz9zZvvQzUw+9DrOn0MomR7BxFCkA2pcfXBQuHC28ndJpSbjLs7knzYb05kw5SyCjSsEWombkZMgGcJSk8JVg==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/core": "2.8.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" + "@opentelemetry/api": ">=1.0.0 <1.11.0" } }, "node_modules/@opentelemetry/redis-common": { - "version": "0.38.3", - "resolved": "https://registry.npmjs.org/@opentelemetry/redis-common/-/redis-common-0.38.3.tgz", - "integrity": "sha512-VCghU1JYs/4gP6Gqf/xro9MEsZ7LrMv2uONVsaESKL38ZOB9BqnI98FfS23wjMnHlpuE+TTaWSoAVNpTwYXzjw==", + "version": "0.39.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/redis-common/-/redis-common-0.39.0.tgz", + "integrity": "sha512-LwhsURMcyCigjnQHni9RAt0ezrVRxcb6kIE2UTbVI1cxxteeH8mTpPV7xBOVEG2GEm1GniEPLeVkXFHgiIw3xg==", "license": "Apache-2.0", "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" } }, "node_modules/@opentelemetry/resource-detector-alibaba-cloud": { - "version": "0.34.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/resource-detector-alibaba-cloud/-/resource-detector-alibaba-cloud-0.34.0.tgz", - "integrity": "sha512-hUs4CK7MbRfffw8y5zR4Mo37MJRR3Zt8Ub4rgMkIk7gL8jozjV7k+zwIk9grz5kGAuD406BDDIghaY8090K4Zw==", + "version": "0.39.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resource-detector-alibaba-cloud/-/resource-detector-alibaba-cloud-0.39.0.tgz", + "integrity": "sha512-QRVfll/M50DqDeVawyIonXtxDBhyPiEuxtTvCuQ5t+PML7jP73p4Y9vIggAZanzdvMOKcYZfsiPmBzXUc16Oug==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/resources": "^2.0.0" + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/resources": "^3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "node_modules/@opentelemetry/resource-detector-aws": { - "version": "2.19.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/resource-detector-aws/-/resource-detector-aws-2.19.0.tgz", - "integrity": "sha512-ELKQCtbc7g2ghbteLftKzXvI3MkIfENrRjAaYd2h9cWNj8g/Dx3oDzpxfcv9mBigtwwWCZwQRr8R//uxREpdrg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resource-detector-aws/-/resource-detector-aws-3.0.0.tgz", + "integrity": "sha512-wYUmvswkL6LzoHgu2cObFkZPLE95hkXCEmnfz+ejf0ZEHRBj1PIIudpDjldGMxxRwk0nJyDiYOoPcUPtXnIHjg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/resources": "^2.0.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/resources": "^3.0.0", "@opentelemetry/semantic-conventions": "^1.27.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "node_modules/@opentelemetry/resource-detector-azure": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/resource-detector-azure/-/resource-detector-azure-0.27.0.tgz", - "integrity": "sha512-m6HCEmK12QpEcWbKtvGpQtoDVceXtpB14AaaW/t5f6gHeLuGq1QivkuohkvKMkxgAdwIHxEQ8qof3whWBpd8JA==", + "version": "0.32.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resource-detector-azure/-/resource-detector-azure-0.32.0.tgz", + "integrity": "sha512-uVtFH5rAbD0vDnmghJHCZKllhGPifVn5Cf1XZDSPEZDxB0fD3JND+a1qTyJ088RLM959P558wFqnxp1TU8RiTw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/resources": "^2.0.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/resources": "^3.0.0", "@opentelemetry/semantic-conventions": "^1.37.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "node_modules/@opentelemetry/resource-detector-container": { - "version": "0.8.10", - "resolved": "https://registry.npmjs.org/@opentelemetry/resource-detector-container/-/resource-detector-container-0.8.10.tgz", - "integrity": "sha512-aMU2wG4ktcqy6zEotdbIkkX5ACKRxEZLX1ZlMH0dea0M2+2KfabJc1lHPqAIFaa+CD37fCION55e69QmYwqX4A==", + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resource-detector-container/-/resource-detector-container-0.9.0.tgz", + "integrity": "sha512-FQnWEjNgAgVZ9Vd3p9yC2cqrB/vOmCm/YPUpayYIuuAiURHZHiqhR424H4j/XSVAlvgUQrrcyjgZJjJnlcoP/w==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/resources": "^2.0.0" + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/resources": "^3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "node_modules/@opentelemetry/resource-detector-gcp": { - "version": "0.54.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/resource-detector-gcp/-/resource-detector-gcp-0.54.0.tgz", - "integrity": "sha512-u+6sBzQO03QQGFhxjzFa7uNbH6iQpWTcrpWyomxuppH3AN/+1mm3DRVseS1CiRq9VBKrFO0UosWAdD7fWVUrrg==", + "version": "0.59.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resource-detector-gcp/-/resource-detector-gcp-0.59.0.tgz", + "integrity": "sha512-zcZyAT9tkZIWCVRd84ivwNNZiBF2iW3HPe02LZfkRLfYaGzaRueh2imKjvjiwhhxpQHfWUREATk4oflVMAqr+A==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0", - "@opentelemetry/resources": "^2.0.0", + "@opentelemetry/core": "^3.0.0", + "@opentelemetry/resources": "^3.0.0", "gcp-metadata": "^8.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0" } }, "node_modules/@opentelemetry/resources": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-2.8.0.tgz", - "integrity": "sha512-qmXQ27ilDbUK/vGMqwL8D4/rhn76C+sherM4wTbjlfknR8Nvfc/hCxjRJPhkzZzUsPiNg16SA31NxMabwttRjg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/resources/-/resources-3.0.0.tgz", + "integrity": "sha512-4762KVmlDroRIt+4Ra8AnwcQqdXlkAR55jDrhzna8bzhJx1mUzvHW/Lh/OemFuY9+ouM4xaDc6CbUmoJmM6BFg==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", + "@opentelemetry/core": "3.0.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.3.0 <1.10.0" + "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "node_modules/@opentelemetry/sdk-logs": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-0.219.0.tgz", - "integrity": "sha512-s6lTKRakaPClvKoWHRChxnXjDMkM/TQ30ff78jN6EBGf7MI7VzANE5PU3f4z9qDUudWjvZjOLHG0rBnBKYvoXA==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-logs/-/sdk-logs-3.0.0.tgz", + "integrity": "sha512-IysNZWrBk2PqYw4qU9PZcC7pjrZLa+KLk7vcLmPPNBUr97MgeamWhX0DUHsmxwJv3dnjYM6mLRmP8mw69ld+dA==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "0.219.0", - "@opentelemetry/core": "2.8.0", - "@opentelemetry/resources": "2.8.0", + "@opentelemetry/core": "3.0.0", + "@opentelemetry/resources": "3.0.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.4.0 <1.10.0" + "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "node_modules/@opentelemetry/sdk-metrics": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-2.8.0.tgz", - "integrity": "sha512-UDBGaj6W0Rgy5rTTaoxs8gVGF/aGkAKyjurJv7se6wjRxJu7FoquTLT/vt54DZfo4crbprYfhX/SOK9+BPw1qg==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-metrics/-/sdk-metrics-3.0.0.tgz", + "integrity": "sha512-YozyS2rIlizvUNLZwcWxH0x2FhX02/mcZwzM8hsl8yvQk+xeKmAc7vcSieWiO4oSwIB20B8eS/zwdopAd/J5zQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "@opentelemetry/resources": "2.8.0" + "@opentelemetry/core": "3.0.0", + "@opentelemetry/resources": "3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.9.0 <1.10.0" + "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "node_modules/@opentelemetry/sdk-node": { - "version": "0.219.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-node/-/sdk-node-0.219.0.tgz", - "integrity": "sha512-NWLpWLEb8gV3+JBHYoIrktbM385wyHpRJoh3J/4Q52d4PR+AlPMNGJT3DzBUrDSUEVbKAXoHR+EDAPxtiNcj8g==", + "version": "0.300.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-node/-/sdk-node-0.300.0.tgz", + "integrity": "sha512-yRaNP91ilq0m5fBCXSo7ZTR1NDd/GPu02uq0Rur2kMw7VheHwkV8i68oYt4/vM+eofRFKYCGS5B2QrgcZS/rmw==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/api-logs": "0.219.0", - "@opentelemetry/configuration": "0.219.0", - "@opentelemetry/context-async-hooks": "2.8.0", - "@opentelemetry/core": "2.8.0", - "@opentelemetry/exporter-logs-otlp-grpc": "0.219.0", - "@opentelemetry/exporter-logs-otlp-http": "0.219.0", - "@opentelemetry/exporter-logs-otlp-proto": "0.219.0", - "@opentelemetry/exporter-metrics-otlp-grpc": "0.219.0", - "@opentelemetry/exporter-metrics-otlp-http": "0.219.0", - "@opentelemetry/exporter-metrics-otlp-proto": "0.219.0", - "@opentelemetry/exporter-prometheus": "0.219.0", - "@opentelemetry/exporter-trace-otlp-grpc": "0.219.0", - "@opentelemetry/exporter-trace-otlp-http": "0.219.0", - "@opentelemetry/exporter-trace-otlp-proto": "0.219.0", - "@opentelemetry/exporter-zipkin": "2.8.0", - "@opentelemetry/instrumentation": "0.219.0", - "@opentelemetry/otlp-exporter-base": "0.219.0", - "@opentelemetry/otlp-grpc-exporter-base": "0.219.0", - "@opentelemetry/propagator-b3": "2.8.0", - "@opentelemetry/propagator-jaeger": "2.8.0", - "@opentelemetry/resources": "2.8.0", - "@opentelemetry/sdk-logs": "0.219.0", - "@opentelemetry/sdk-metrics": "2.8.0", - "@opentelemetry/sdk-trace-base": "2.8.0", - "@opentelemetry/sdk-trace-node": "2.8.0", + "@opentelemetry/configuration": "0.300.0", + "@opentelemetry/context-async-hooks": "3.0.0", + "@opentelemetry/core": "3.0.0", + "@opentelemetry/exporter-logs-otlp-grpc": "0.300.0", + "@opentelemetry/exporter-logs-otlp-http": "0.300.0", + "@opentelemetry/exporter-logs-otlp-proto": "0.300.0", + "@opentelemetry/exporter-metrics-otlp-grpc": "0.300.0", + "@opentelemetry/exporter-metrics-otlp-http": "0.300.0", + "@opentelemetry/exporter-metrics-otlp-proto": "0.300.0", + "@opentelemetry/exporter-prometheus": "0.300.0", + "@opentelemetry/exporter-trace-otlp-grpc": "0.300.0", + "@opentelemetry/exporter-trace-otlp-http": "0.300.0", + "@opentelemetry/exporter-trace-otlp-proto": "0.300.0", + "@opentelemetry/exporter-zipkin": "3.0.0", + "@opentelemetry/instrumentation": "0.300.0", + "@opentelemetry/otlp-exporter-base": "0.300.0", + "@opentelemetry/otlp-grpc-exporter-base": "0.300.0", + "@opentelemetry/propagator-b3": "3.0.0", + "@opentelemetry/resources": "3.0.0", + "@opentelemetry/sdk-logs": "3.0.0", + "@opentelemetry/sdk-metrics": "3.0.0", + "@opentelemetry/sdk-trace": "3.0.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.3.0 <1.10.0" + "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, - "node_modules/@opentelemetry/sdk-trace-base": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-base/-/sdk-trace-base-2.8.0.tgz", - "integrity": "sha512-mhU4jp+vW0mGbFRd+GeXHvmfA4aDqWjBjLC3pE5XMpLs0IE2ryYb019Ts2AQrOq67gaTF25D91+fgvEHDZEnuQ==", + "node_modules/@opentelemetry/sdk-trace": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace/-/sdk-trace-3.0.0.tgz", + "integrity": "sha512-4T0DbDGdtsjNmYK5/lNalHro4fsMZ0UZ3JE+C8fcqYP25xaJC22FHg8kdJNJ21srjJY5XoT7WNFCtj88NNTl4Q==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "2.8.0", - "@opentelemetry/resources": "2.8.0", + "@opentelemetry/core": "3.0.0", + "@opentelemetry/resources": "3.0.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { - "@opentelemetry/api": ">=1.3.0 <1.10.0" - } - }, - "node_modules/@opentelemetry/sdk-trace-node": { - "version": "2.8.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/sdk-trace-node/-/sdk-trace-node-2.8.0.tgz", - "integrity": "sha512-nZt9OGufioAc3AfoLTqA9bsAeaMJAictYDdI2VcNQ+PmT+3rfKjAZDZvgPfd8VPX0O5Bw1hdQF6kDK8VSpZiWg==", - "license": "Apache-2.0", - "dependencies": { - "@opentelemetry/context-async-hooks": "2.8.0", - "@opentelemetry/core": "2.8.0", - "@opentelemetry/sdk-trace-base": "2.8.0" - }, - "engines": { - "node": "^18.19.0 || >=20.6.0" - }, - "peerDependencies": { - "@opentelemetry/api": ">=1.0.0 <1.10.0" + "@opentelemetry/api": ">=1.10.0 <1.11.0" } }, "node_modules/@opentelemetry/semantic-conventions": { - "version": "1.41.1", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.41.1.tgz", - "integrity": "sha512-/UhIkaZgPutTFmQ7RnIJGgDXZmtEJ7Dvi86xNTFWcnRxVRNk/aotsqDJYeEvDP+FSMB2SdW+pQzNMcWP0rwuNA==", + "version": "1.43.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.43.0.tgz", + "integrity": "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==", "license": "Apache-2.0", "engines": { "node": ">=14" } }, "node_modules/@opentelemetry/sql-common": { - "version": "0.42.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/sql-common/-/sql-common-0.42.0.tgz", - "integrity": "sha512-nwUwUU+8O8a4bnLqk6CodWeegGMEANgC94KTAhXcpGWLrW/2/hek/0ajNbjXnSOoNuCX+nteUPs46HFHhou9Xw==", + "version": "0.43.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/sql-common/-/sql-common-0.43.0.tgz", + "integrity": "sha512-r5FfJFAbRIW+7YkXkD8XBEuExf1RyesrLrzyB1If/hTqxEAUaGPZihgrPLPX+UFq4b20YtHDmFBptNffPAJXjQ==", "license": "Apache-2.0", "dependencies": { - "@opentelemetry/core": "^2.0.0" + "@opentelemetry/core": "^3.0.0" }, "engines": { - "node": "^18.19.0 || >=20.6.0" + "node": ">=22.15.0" }, "peerDependencies": { "@opentelemetry/api": "^1.1.0" @@ -4014,26 +4021,26 @@ } }, "node_modules/@pkgr/core": { - "version": "0.2.9", - "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.2.9.tgz", - "integrity": "sha512-QNqXyfVS2wm9hweSYD2O7F0G06uurj9kZ96TRQE5Y9hU7+tgdZwIkbAKc5Ocy1HxEY2kuDQa6cQ1WRs/O5LFKA==", + "version": "0.3.6", + "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz", + "integrity": "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==", "dev": true, "license": "MIT", "engines": { - "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + "node": "^14.18.0 || >=16.0.0" }, "funding": { "url": "https://opencollective.com/pkgr" } }, "node_modules/@playwright/test": { - "version": "1.62.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.62.1.tgz", - "integrity": "sha512-DTcUc8qii+cpHvtOwggMtBRMjKZHXYWdw8syRYu2vtzuq4Wxphqq4NfCs5Zt44L6mA8rfDfj+PHnxFc/FeK6mQ==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright": "1.62.1" + "playwright": "1.64.1" }, "bin": { "playwright": "cli.js" @@ -4139,9 +4146,9 @@ "license": "BSD-3-Clause" }, "node_modules/@protobufjs/utf8": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.1.tgz", - "integrity": "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.2.tgz", + "integrity": "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug==", "license": "BSD-3-Clause" }, "node_modules/@rollup/plugin-babel": { @@ -4628,9 +4635,9 @@ ] }, "node_modules/@sinclair/typebox": { - "version": "0.34.49", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.49.tgz", - "integrity": "sha512-brySQQs7Jtn0joV8Xh9ZV/hZb9Ozb0pmazDIASBkYKCjXrXU3mpcFahmK/z4YDhGkQvP9mWJbVyahdtU5wQA+A==", + "version": "0.34.52", + "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.52.tgz", + "integrity": "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==", "dev": true, "license": "MIT" }, @@ -4883,6 +4890,66 @@ "node": ">=14.0.0" } }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.1", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.2", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.1", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.2", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.4", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.1" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.2", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "inBundle": true, + "license": "0BSD", + "optional": true + }, "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { "version": "4.3.3", "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz", @@ -4945,9 +5012,10 @@ } }, "node_modules/@tybys/wasm-util": { - "version": "0.10.2", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz", - "integrity": "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==", + "version": "0.10.4", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", + "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", + "dev": true, "license": "MIT", "optional": true, "dependencies": { @@ -4958,13 +5026,14 @@ "version": "2.8.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, "license": "0BSD", "optional": true }, "node_modules/@types/aws-lambda": { - "version": "8.10.162", - "resolved": "https://registry.npmjs.org/@types/aws-lambda/-/aws-lambda-8.10.162.tgz", - "integrity": "sha512-Fn658grtLOci1oxi1391vvDWJRKNGWRSqfxRkmN/Iy3c0tQH1USMKEXcPYHLvope+ZgTFocx9FRQJx1muBL6qw==", + "version": "8.10.164", + "resolved": "https://registry.npmjs.org/@types/aws-lambda/-/aws-lambda-8.10.164.tgz", + "integrity": "sha512-XOnrazWcOd6yWPnR7DxqCBPPYciDjHq+NN8LPwwqBCJNXLyPJgKo47fZpJ113+oyAn9Zti0Cf6H4k6yPcE3WFg==", "license": "MIT" }, "node_modules/@types/babel__core": { @@ -5008,15 +5077,6 @@ "@babel/types": "^7.20.7" } }, - "node_modules/@types/bunyan": { - "version": "1.8.11", - "resolved": "https://registry.npmjs.org/@types/bunyan/-/bunyan-1.8.11.tgz", - "integrity": "sha512-758fRH7umIMk5qt5ELmRMff4mLDlN+xyYzC+dkPTdKwbSkJFvz6xwyScrytPU0QIBbRRwbiE8/BIg8bpajerNQ==", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/connect": { "version": "3.4.38", "resolved": "https://registry.npmjs.org/@types/connect/-/connect-3.4.38.tgz", @@ -5075,15 +5135,6 @@ "integrity": "sha512-hov8bUuiLiyFPGyFPE1lwWhmzYbirOXQNNo40+y3zow8aFVTeyn3VWL0VFFfdNddA8S4Vf0Tc062rzyNr7Paag==", "dev": true }, - "node_modules/@types/mysql": { - "version": "2.15.27", - "resolved": "https://registry.npmjs.org/@types/mysql/-/mysql-2.15.27.tgz", - "integrity": "sha512-YfWiV16IY0OeBfBCk8+hXKmdTKrKlwKN1MNKAPBu5JYxLwBEZl7QzeEpGnlZb3VMGJrrGmB84gXiH+ofs/TezA==", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/node": { "version": "20.13.0", "resolved": "https://registry.npmjs.org/@types/node/-/node-20.13.0.tgz", @@ -5098,15 +5149,6 @@ "integrity": "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA==", "dev": true }, - "node_modules/@types/oracledb": { - "version": "6.5.2", - "resolved": "https://registry.npmjs.org/@types/oracledb/-/oracledb-6.5.2.tgz", - "integrity": "sha512-kK1eBS/Adeyis+3OlBDMeQQuasIDLUYXsi2T15ccNJ0iyUpQ4xDF7svFu3+bGVrI0CMBUclPciz+lsQR3JX3TQ==", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/pg": { "version": "8.15.6", "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.15.6.tgz", @@ -5141,15 +5183,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/tedious": { - "version": "4.0.14", - "resolved": "https://registry.npmjs.org/@types/tedious/-/tedious-4.0.14.tgz", - "integrity": "sha512-KHPsfX/FoVbUGbyYvk1q9MMQHLPeRZhRJZdO45Q4YjvFkv4hMNghCWTvy7rdKessBsmtz4euWCWAB6/tVpI1Iw==", - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/trusted-types": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", @@ -5175,16 +5208,16 @@ "license": "MIT" }, "node_modules/@ungap/structured-clone": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.1.tgz", - "integrity": "sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", + "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==", "dev": true, "license": "ISC" }, "node_modules/@unrs/resolver-binding-android-arm-eabi": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz", - "integrity": "sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.12.2.tgz", + "integrity": "sha512-g5T90pqg1bo/7mytQx6F4iBNC0Wsh9cu+z9veDbFjc7HjpesJFWD7QMS0NGStXM075+7dJPPVvBbpZlnrdpi/w==", "cpu": [ "arm" ], @@ -5196,9 +5229,9 @@ ] }, "node_modules/@unrs/resolver-binding-android-arm64": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.11.1.tgz", - "integrity": "sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.12.2.tgz", + "integrity": "sha512-YGCRZv/9GLhwmz6mYDeTsm/92BAyR28l6c2ReweVW5pWgfsitWLY8upvfRlGdoyD8HjeTHSYJWyZGD4KJA/nFQ==", "cpu": [ "arm64" ], @@ -5210,9 +5243,9 @@ ] }, "node_modules/@unrs/resolver-binding-darwin-arm64": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.11.1.tgz", - "integrity": "sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.12.2.tgz", + "integrity": "sha512-u9DiNT1auQMO20A9SyTuG3wUgQWB9Z7KjAg0uFuCDR1FsAY8A0CG2S6JpHS1xwm/w1G08bjXZDcyOCjv1WAm2w==", "cpu": [ "arm64" ], @@ -5224,9 +5257,9 @@ ] }, "node_modules/@unrs/resolver-binding-darwin-x64": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz", - "integrity": "sha512-cFzP7rWKd3lZaCsDze07QX1SC24lO8mPty9vdP+YVa3MGdVgPmFc59317b2ioXtgCMKGiCLxJ4HQs62oz6GfRQ==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.12.2.tgz", + "integrity": "sha512-f7rPLi/T1HVKZu/u6t87lroib16n8vrSzcyxI7lg4BGO9UF26KhQL44sd9eOUgrTYhvRXtWOIZT5PejdPyJfUA==", "cpu": [ "x64" ], @@ -5238,9 +5271,9 @@ ] }, "node_modules/@unrs/resolver-binding-freebsd-x64": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.11.1.tgz", - "integrity": "sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.12.2.tgz", + "integrity": "sha512-BpcOjWCJub6nRZUS2zA20pmLvjtqAtGejETaIyRLiZiQf++cbrjltLA5NN/xaXfqeOBOSlMFbemIl5/S5tljmg==", "cpu": [ "x64" ], @@ -5252,9 +5285,9 @@ ] }, "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.11.1.tgz", - "integrity": "sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.12.2.tgz", + "integrity": "sha512-vZTDvdSISZjJx66OzJqtsOhzifbqRjbmI1Mnu49fQDwog5GtDI4QidRiEAYbZCRj9C8YZEW+3ZjqsyS9GR4k2A==", "cpu": [ "arm" ], @@ -5266,9 +5299,9 @@ ] }, "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.11.1.tgz", - "integrity": "sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.12.2.tgz", + "integrity": "sha512-BiPI+IrIlwcW4nLLMM21+B1dFPzd55yAVgVGrdgDjNef+ch03GdxrcyaIz8X9SsQirh/kCQ7mviyWlMxdh2D7g==", "cpu": [ "arm" ], @@ -5280,9 +5313,9 @@ ] }, "node_modules/@unrs/resolver-binding-linux-arm64-gnu": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.11.1.tgz", - "integrity": "sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.12.2.tgz", + "integrity": "sha512-zJc0H99FEPoFfSrNpa91HYfxzfAJCr502oxNK1cfdC9hlaFI43RT+JFCann9JUgZmLzzntChHyn13Sgn9ljHNg==", "cpu": [ "arm64" ], @@ -5294,9 +5327,9 @@ ] }, "node_modules/@unrs/resolver-binding-linux-arm64-musl": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.11.1.tgz", - "integrity": "sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.12.2.tgz", + "integrity": "sha512-KQ3Lki6l+Pz1k/eBipN41ES+YUK30beLGb9YqcB1O542cyLCNE6GaxrfcY3T6EezmGGk84wb5XyO9loTM9tkcA==", "cpu": [ "arm64" ], @@ -5307,10 +5340,38 @@ "linux" ] }, + "node_modules/@unrs/resolver-binding-linux-loong64-gnu": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-loong64-gnu/-/resolver-binding-linux-loong64-gnu-1.12.2.tgz", + "integrity": "sha512-3SJGEh1DborhG6pyxvhPzCT4bbSIVihsvgJc13P1bHG7KLdNDaF9T3gsTwFc7Jw/5Y5/iWOjkEx7Zy0NvCGX3Q==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-loong64-musl": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-loong64-musl/-/resolver-binding-linux-loong64-musl-1.12.2.tgz", + "integrity": "sha512-jiuG/Obbel7uw1PwHNFfrkiKhLAF6mnyZ6aWlOAVN9WqKm8v0OFGnciJIHu8+CMvXLQ8AD51LPzAoUfT21D5Ew==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.11.1.tgz", - "integrity": "sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.12.2.tgz", + "integrity": "sha512-q7xRvVpmcfeL+LlZg8Pbbo6QaTZwDU5BaGZbwfhkEsXJn3Was8xYfE0RBH266xZt0rM6B7i8xAYIvjthuUIWHg==", "cpu": [ "ppc64" ], @@ -5322,9 +5383,9 @@ ] }, "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.11.1.tgz", - "integrity": "sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.12.2.tgz", + "integrity": "sha512-0CVdx6lcnT3Q9inOH8tsMIOJ6ImndllMjqJHg8RLVdB7Vq4SfkEXl9mCSsVNuNA4MCYycRicCUxPCabVHJRr6A==", "cpu": [ "riscv64" ], @@ -5336,9 +5397,9 @@ ] }, "node_modules/@unrs/resolver-binding-linux-riscv64-musl": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.11.1.tgz", - "integrity": "sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.12.2.tgz", + "integrity": "sha512-iOwlRo9vnp6R6ohHQS11n0NnfdXx/omhkocmIfaPRpQhKZ+3BDMkkdRVh53qjkFkpPddf+FETA28NwGN7l5l+w==", "cpu": [ "riscv64" ], @@ -5350,9 +5411,9 @@ ] }, "node_modules/@unrs/resolver-binding-linux-s390x-gnu": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.11.1.tgz", - "integrity": "sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.12.2.tgz", + "integrity": "sha512-HYJtLfXq94q8iZNFT1lknx258wlkkWhZeUXJRqzKBBUJ00CvZ+N33zgbCqimLjsyw5Va6uUxhVa12mI+kaveEw==", "cpu": [ "s390x" ], @@ -5364,9 +5425,9 @@ ] }, "node_modules/@unrs/resolver-binding-linux-x64-gnu": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.11.1.tgz", - "integrity": "sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.12.2.tgz", + "integrity": "sha512-mPsUhunKKDih5O96Y6enDQyHc1SqBPlY1E/SfMWDM3EdJ95Z9CArPeCVwCCqbP45ljvivdEk8Fxn+SIb1rDAJQ==", "cpu": [ "x64" ], @@ -5378,9 +5439,9 @@ ] }, "node_modules/@unrs/resolver-binding-linux-x64-musl": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.11.1.tgz", - "integrity": "sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.12.2.tgz", + "integrity": "sha512-azrt6+5ydLd8Vt210AAFis/lZevSfPw93EJRIJG+xPu4WCJ8K0kppCTpMyLPcKT7H15M4Jnt2tMp5bOvCkRC6A==", "cpu": [ "x64" ], @@ -5391,10 +5452,24 @@ "linux" ] }, + "node_modules/@unrs/resolver-binding-openharmony-arm64": { + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-openharmony-arm64/-/resolver-binding-openharmony-arm64-1.12.2.tgz", + "integrity": "sha512-YZ9hP4O0X9PQb8eO980qmLNGH4zT3I9+SZTdt0Pr0YyuGQhYKoOZkV02VzrzyOZJ5xIJ3UFIenKkUkGg8GjgWQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ] + }, "node_modules/@unrs/resolver-binding-wasm32-wasi": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.11.1.tgz", - "integrity": "sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.12.2.tgz", + "integrity": "sha512-tYFDIkMxSflfEc/h92ZWNsZlHSwgimbNHSO3PL2JWQHfCuC2q316jMyYU9TIWZsFK2bQwyK5VAdYgn8ygPj69A==", "cpu": [ "wasm32" ], @@ -5402,16 +5477,18 @@ "license": "MIT", "optional": true, "dependencies": { - "@napi-rs/wasm-runtime": "^0.2.11" + "@emnapi/core": "1.10.0", + "@emnapi/runtime": "1.10.0", + "@napi-rs/wasm-runtime": "^1.1.4" }, "engines": { "node": ">=14.0.0" } }, "node_modules/@unrs/resolver-binding-win32-arm64-msvc": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.11.1.tgz", - "integrity": "sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.12.2.tgz", + "integrity": "sha512-qzNyg3xL0VPQmCaUh+N5jSitce6k+uCBfMDesWRnlULOZaqUkaJ0ybdT+UqlAWJoQjuqfIU/0Ptx9bteN4D82g==", "cpu": [ "arm64" ], @@ -5423,9 +5500,9 @@ ] }, "node_modules/@unrs/resolver-binding-win32-ia32-msvc": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.11.1.tgz", - "integrity": "sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.12.2.tgz", + "integrity": "sha512-WD9sY00OfpHVGfsnHZoA8jVT+esS/Bg8z8jzxp5BnDCjjwsuKsPQrzswwpFy4J1AUJbXPRfkpcX0mXrzeXW79g==", "cpu": [ "ia32" ], @@ -5437,9 +5514,9 @@ ] }, "node_modules/@unrs/resolver-binding-win32-x64-msvc": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.11.1.tgz", - "integrity": "sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.12.2.tgz", + "integrity": "sha512-nAB74NfSNKknqQ1RrYj6uz8FcXEomu/MATJZxh/x+BArzN2U3JbOYC0APYzUIGhVY3m5hRxA8VPNdPBoG8txlA==", "cpu": [ "x64" ], @@ -5454,7 +5531,7 @@ "version": "8.15.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", - "peer": true, + "dev": true, "bin": { "acorn": "bin/acorn" }, @@ -5462,15 +5539,6 @@ "node": ">=0.4.0" } }, - "node_modules/acorn-import-attributes": { - "version": "1.9.5", - "resolved": "https://registry.npmjs.org/acorn-import-attributes/-/acorn-import-attributes-1.9.5.tgz", - "integrity": "sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==", - "license": "MIT", - "peerDependencies": { - "acorn": "^8" - } - }, "node_modules/agent-base": { "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", @@ -5486,7 +5554,6 @@ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -5664,9 +5731,9 @@ } }, "node_modules/autoprefixer": { - "version": "10.5.0", - "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.5.0.tgz", - "integrity": "sha512-FMhOoZV4+qR6aTUALKX2rEqGG+oyATvwBt9IIzVR5rMa2HRWPkxf+P+PAJLD1I/H5/II+HuZcBJYEFBpq39ong==", + "version": "10.6.1", + "resolved": "https://registry.npmjs.org/autoprefixer/-/autoprefixer-10.6.1.tgz", + "integrity": "sha512-cL1Qz6ADZhcEbny/8HPfe99J6HhNoYtpX2LFLIbhgGE7Q1hlQVkYFdetDN7Id3KiQxhDrHwzlHr/YQCnZ8+xSA==", "dev": true, "funding": [ { @@ -5684,8 +5751,8 @@ ], "license": "MIT", "dependencies": { - "browserslist": "^4.28.2", - "caniuse-lite": "^1.0.30001787", + "browserslist": "^4.28.9", + "caniuse-lite": "^1.0.30001810", "fraction.js": "^5.3.4", "picocolors": "^1.1.1", "postcss-value-parser": "^4.2.0" @@ -5717,16 +5784,16 @@ } }, "node_modules/babel-jest": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-30.4.1.tgz", - "integrity": "sha512-fATAbM8piYxkiXQp3RBXmZHxZVNJZAVXXfyeyCN2Tida3+qJ8ea9UxhiJ2y4fLO90ZImKt6k9FlcH2+rLkJGhw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-30.5.2.tgz", + "integrity": "sha512-ES8WeJ2fNWPEDunyAtUfJ12nHyaWUloCHdkfK2oW5uSoQSUmjNKdWiGaXJITJwvFEWoD/evHEg/QoCXAvLaQqQ==", "dev": true, "license": "MIT", "dependencies": { - "@jest/transform": "30.4.1", + "@jest/transform": "30.5.2", "@types/babel__core": "^7.20.5", - "babel-plugin-istanbul": "^7.0.1", - "babel-preset-jest": "30.4.0", + "babel-plugin-istanbul": "^8.0.0", + "babel-preset-jest": "30.5.0", "chalk": "^4.1.2", "graceful-fs": "^4.2.11", "slash": "^3.0.0" @@ -5739,9 +5806,9 @@ } }, "node_modules/babel-plugin-istanbul": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-7.0.1.tgz", - "integrity": "sha512-D8Z6Qm8jCvVXtIRkBnqNHX0zJ37rQcFJ9u8WOS6tkYOsRdHBzypCstaxWiu5ZIlqQtviRYbgnRLSoCEvjqcqbA==", + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-8.0.0.tgz", + "integrity": "sha512-18wCskrN3DgbuBmp1gr7LBGT8xdz5xhQQqFvFhVxbkl8VBCrMKQ2YtqBWtUal1Zrc1HTuX0011+Brjw78TCFkg==", "dev": true, "license": "BSD-3-Clause", "workspaces": [ @@ -5752,16 +5819,16 @@ "@istanbuljs/load-nyc-config": "^1.0.0", "@istanbuljs/schema": "^0.1.3", "istanbul-lib-instrument": "^6.0.2", - "test-exclude": "^6.0.0" + "test-exclude": "^7.0.1" }, "engines": { - "node": ">=12" + "node": ">=18" } }, "node_modules/babel-plugin-jest-hoist": { - "version": "30.4.0", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-30.4.0.tgz", - "integrity": "sha512-9EdtWM/sSfXLOGLwSn+GS6pIXyBnL07/8gyJlwFXjWy4DxMOyItqyUT29d4lQiS380EZwYlX7/At4PgBS+m2aA==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-30.5.0.tgz", + "integrity": "sha512-gtGo1B+u14jrZQv6TdSWIWkTqclboo7Qn+dFAGUOIuXLFuJKAdg3U5MIWzZnW4vfUb4dX9skmAMiby86e/SF4A==", "dev": true, "license": "MIT", "dependencies": { @@ -5841,20 +5908,20 @@ } }, "node_modules/babel-preset-jest": { - "version": "30.4.0", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-30.4.0.tgz", - "integrity": "sha512-lBY4jxsNmCnSiu7kquw8ZC9F4+XLMOKypT3RnNHPvU2Kpd4W0xaPuLr5ZkRyOsvLYAY4yaW1ZwTW4xB7NIiZzg==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-30.5.0.tgz", + "integrity": "sha512-ZGPn5ClP4lBDpuOK8W1yQIOy359HmbnZv3suucAlIe+SEE9yDsxV4S2PjSbH2Vc97U+WmzYD7vw3kr8NsQ/i6w==", "dev": true, "license": "MIT", "dependencies": { - "babel-plugin-jest-hoist": "30.4.0", + "babel-plugin-jest-hoist": "30.5.0", "babel-preset-current-node-syntax": "^1.2.0" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" }, "peerDependencies": { - "@babel/core": "^7.11.0 || ^8.0.0-beta.1" + "@babel/core": "^7.11.0 || ^8.0.0-beta.1 || ^8.0.0" } }, "node_modules/balanced-match": { @@ -5891,9 +5958,9 @@ ] }, "node_modules/baseline-browser-mapping": { - "version": "2.11.21", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.21.tgz", - "integrity": "sha512-uh8vpY/1/YyFkunIDFH/12p7/7VdPKA1hejMVEbdkEaWnUz0Hesvx5EbiU6XxjyHZIOju+ZMbQJkRh+es3/spQ==", + "version": "2.11.33", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.33.tgz", + "integrity": "sha512-yiVKDX+qCMRKBE084lXvq9EcwFUhKZ2nU8TK1EQQuOgPNR/lmbGxXOeDdlGUqC2Zz11Cs9rk1d/8NfgBmlkt0w==", "dev": true, "license": "Apache-2.0", "bin": { @@ -6083,9 +6150,9 @@ } }, "node_modules/brace-expansion": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.0.tgz", - "integrity": "sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==", + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", + "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" @@ -6103,9 +6170,9 @@ } }, "node_modules/browserslist": { - "version": "4.28.2", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", - "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", + "version": "4.29.4", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.4.tgz", + "integrity": "sha512-2TcbbiwXEq+N0kD36tykpCfyyQigUXmuwNQbnPp4Xk4PX9JOqVIKjJlIDjpH7uY6tmRGoAd+apeT1p60T8wsdA==", "dev": true, "funding": [ { @@ -6122,13 +6189,12 @@ } ], "license": "MIT", - "peer": true, "dependencies": { - "baseline-browser-mapping": "^2.10.12", - "caniuse-lite": "^1.0.30001782", - "electron-to-chromium": "^1.5.328", - "node-releases": "^2.0.36", - "update-browserslist-db": "^1.2.3" + "baseline-browser-mapping": "^2.11.29", + "caniuse-lite": "^1.0.30001816", + "electron-to-chromium": "^1.5.459", + "node-releases": "^2.0.59", + "update-browserslist-db": "^1.3.4" }, "bin": { "browserslist": "cli.js" @@ -6138,11 +6204,11 @@ } }, "node_modules/bser": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.1.tgz", - "integrity": "sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ==", + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.2.tgz", + "integrity": "sha512-V2o8YS2EhrKMO9AumnkK0ynynfFlsajpYupwq7S46H5mhcanwxDkNTw3K67wPIcKTH1ffkA4vhMOtAc7gRmPZw==", "dev": true, - "license": "Apache-2.0", + "license": "MIT", "dependencies": { "node-int64": "^0.4.0" } @@ -6264,9 +6330,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001791", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001791.tgz", - "integrity": "sha512-yk0l/YSrOnFZk3UROpDLQD9+kC1l4meK/wed583AXrzoarMGJcbRi2Q4RaUYbKxYAsZ8sWmaSa/DsLmdBeI1vQ==", + "version": "1.0.30001819", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001819.tgz", + "integrity": "sha512-LFUqIIAwpzsIuevnKnsR9qnStBcgzPShTX61lBwN9uFkkf8o8zLiebEjbW8AYtZiF+1YKDWfdt/pWDtMuG8Xwg==", "dev": true, "funding": [ { @@ -6493,13 +6559,6 @@ "node": ">=4.0.0" } }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "dev": true, - "license": "MIT" - }, "node_modules/config-chain": { "version": "1.1.13", "resolved": "https://registry.npmjs.org/config-chain/-/config-chain-1.1.13.tgz", @@ -6601,9 +6660,9 @@ } }, "node_modules/daisyui": { - "version": "5.7.16", - "resolved": "https://registry.npmjs.org/daisyui/-/daisyui-5.7.16.tgz", - "integrity": "sha512-V9CJxvrWIXTDuP/0tpijjWaKaKJNYo2IrULJfTWs3/DjW9rPqswk1n8NCLQRLrTutmlG2Ech7nkJDpCnF+6Dzw==", + "version": "5.7.50", + "resolved": "https://registry.npmjs.org/daisyui/-/daisyui-5.7.50.tgz", + "integrity": "sha512-+/LRqnTCoc7s/bJEKKwtJSwzeXCVdAmRdNmZeZzgHCaQ9PJyl7j+2V2U32GQDMyD+VDkP9e/+JGoC72Y1hLk7w==", "dev": true, "license": "MIT", "funding": { @@ -6893,9 +6952,9 @@ } }, "node_modules/electron-to-chromium": { - "version": "1.5.349", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.349.tgz", - "integrity": "sha512-QsWVGyRuY07Aqb234QytTfwd5d9AJlfNIQ5wIOl1L+PZDzI9d9+Fn0FRale/QYlFxt/bUnB0/nLd1jFPGxGK1A==", + "version": "1.5.464", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.464.tgz", + "integrity": "sha512-nRa65aFge40viPAKxMKULIY8tcXKwKboJWNn4RoKwyWXJ6SP7BnrDGKUTzc64818jIciH0PK7LSF8QzZes19GA==", "dev": true, "license": "ISC" }, @@ -7028,6 +7087,12 @@ "node": ">= 0.4" } }, + "node_modules/es-module-lexer": { + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-3.0.4.tgz", + "integrity": "sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA==", + "license": "MIT" + }, "node_modules/es-object-atoms": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", @@ -7185,18 +7250,18 @@ } }, "node_modules/expect": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/expect/-/expect-30.4.1.tgz", - "integrity": "sha512-PMARsyh/JtqC20HoGqlFcIlQAyqUtW4PlI1rup1uhYJtKuwAjbvWi3GQMAn+STdHum/dk8xrKfUM1+5SAwpolA==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/expect/-/expect-30.5.2.tgz", + "integrity": "sha512-0LNuMvs8/5mRYhnCR4k+lGV7fqPMs6Bnksda4S3zsCUmdxBpAn4zU4NNzXdq1pMKe/H4W5t/zVIDSJ/H3e0vDA==", "dev": true, "license": "MIT", "dependencies": { - "@jest/expect-utils": "30.4.1", - "@jest/get-type": "30.1.0", - "jest-matcher-utils": "30.4.1", - "jest-message-util": "30.4.1", - "jest-mock": "30.4.1", - "jest-util": "30.4.1" + "@jest/expect-utils": "30.5.2", + "@jest/get-type": "30.5.0", + "jest-matcher-utils": "30.5.2", + "jest-message-util": "30.5.1", + "jest-mock": "30.5.2", + "jest-util": "30.5.1" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" @@ -7236,9 +7301,9 @@ "dev": true }, "node_modules/fast-uri": { - "version": "3.1.2", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz", - "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, "funding": [ { @@ -7253,13 +7318,13 @@ "license": "BSD-3-Clause" }, "node_modules/fb-watchman": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.2.tgz", - "integrity": "sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.4.tgz", + "integrity": "sha512-tGQtaoYisPDriJBN0mT5yZSyNETnJGA1gTYxaVRAE5KUO3LI9kPUc9WIu8JXcxaIci+faIKlzXqXyPgrmubtBQ==", "dev": true, - "license": "Apache-2.0", + "license": "MIT", "dependencies": { - "bser": "2.1.1" + "bser": "2.1.2" } }, "node_modules/fetch-blob": { @@ -7448,13 +7513,6 @@ "node": ">=10" } }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "dev": true, - "license": "ISC" - }, "node_modules/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -7525,9 +7583,9 @@ } }, "node_modules/gcp-metadata": { - "version": "8.1.3", - "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.3.tgz", - "integrity": "sha512-ziTrzUhhpL9Zk5k0HHzgP/KIpWDJT0VMBC/ynt/QIBvTW+UUcSivQRl6VlwTf/EilDxtSWklHoRsKy1c4k+59w==", + "version": "8.1.4", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-8.1.4.tgz", + "integrity": "sha512-iJ9KMsiu+xKtNRX0PmGLSaIU3bUBAyzWTyqKemKPzNPsmmsBCQYmlNg+brEbES7IHSXtdVwzBPzx1vz3FAaipw==", "license": "Apache-2.0", "dependencies": { "gaxios": "7.1.3", @@ -8068,14 +8126,13 @@ ] }, "node_modules/import-in-the-middle": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.0.2.tgz", - "integrity": "sha512-LGLYRl0A2gtyUJb2WDliBHmk6TtlHwdDjxonacZ8QrEs/ZW+YDgNv2QAfjRQWpS8HqvNcq6GGnN6jrOa5FysDQ==", + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/import-in-the-middle/-/import-in-the-middle-3.5.2.tgz", + "integrity": "sha512-WseIA/4o56+GYO3RmlOPvejYi771OFeJEeK/ejROsr9bdjW+E5NXTOD1Di8TL40Qgg3JJX9aa97Hf8iiSVIKZw==", "license": "Apache-2.0", "dependencies": { - "acorn": "^8.15.0", - "acorn-import-attributes": "^1.9.5", "cjs-module-lexer": "^2.2.0", + "es-module-lexer": "^3.0.2", "module-details-from-path": "^1.0.4" }, "engines": { @@ -8121,18 +8178,6 @@ "node": ">=8" } }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "dev": true, - "license": "ISC", - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -8777,9 +8822,9 @@ } }, "node_modules/istanbul-lib-instrument/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", "dev": true, "license": "ISC", "bin": { @@ -8868,16 +8913,16 @@ } }, "node_modules/jest": { - "version": "30.4.2", - "resolved": "https://registry.npmjs.org/jest/-/jest-30.4.2.tgz", - "integrity": "sha512-Yi1jqNC/Oq0N4hBgNH/YvBpP1P57QqundgytzYqy3yqAa7NZPNjSoi4SGbRAXDMdBzNE6xBCi5U7RgfrvMEUVQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest/-/jest-30.5.2.tgz", + "integrity": "sha512-3gnpdBIza8ijCl3iMV9ChE3hSt1+46865qqod863gQtJr1DixOkAU5DoGbi3u+XlRcw++BhZQMu/y4xBdHBvSQ==", "dev": true, "license": "MIT", "dependencies": { - "@jest/core": "30.4.2", - "@jest/types": "30.4.1", + "@jest/core": "30.5.2", + "@jest/types": "30.5.1", "import-local": "^3.2.0", - "jest-cli": "30.4.2" + "jest-cli": "30.5.2" }, "bin": { "jest": "bin/jest.js" @@ -8895,14 +8940,14 @@ } }, "node_modules/jest-changed-files": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-30.4.1.tgz", - "integrity": "sha512-IuctmYrxi21iOSOaIXpJWalHyPAsVv0GeBHKDn8C1CA4W5htHn7INL+wdnL4Bo0+olEndvAFkmb++tIQJG+vvg==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-30.5.1.tgz", + "integrity": "sha512-0+bvMM/ENhDI29Z8q1r4HxiDIi4G5tnBmSw4esfPQoj9q8Nik7KIyuxHkTVnnniJQf05SxpGaKDQ+4h28ynGPg==", "dev": true, "license": "MIT", "dependencies": { "execa": "^5.1.1", - "jest-util": "30.4.1", + "jest-util": "30.5.1", "p-limit": "^3.1.0" }, "engines": { @@ -8910,29 +8955,29 @@ } }, "node_modules/jest-circus": { - "version": "30.4.2", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-30.4.2.tgz", - "integrity": "sha512-rvHH7VlY6LgbJXJTQ87GW62g1FntOtbhh0zT+v04kC+pgL6aBKyYINXxWukCpj3dcIBMw5/XUbtDS9dU9JTXeQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-30.5.2.tgz", + "integrity": "sha512-vffFgjs5JSJ9q4ds1vNW3klKYPJfYfIY61LT/zaZgvTeASJOWZUt8LBfHgIcV4rwxlPBLl/ePBGccHEclS4PlQ==", "dev": true, "license": "MIT", "dependencies": { - "@jest/environment": "30.4.1", - "@jest/expect": "30.4.1", - "@jest/test-result": "30.4.1", - "@jest/types": "30.4.1", + "@jest/environment": "30.5.2", + "@jest/expect": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", "chalk": "^4.1.2", "co": "^4.6.0", "dedent": "^1.6.0", "is-generator-fn": "^2.1.0", - "jest-each": "30.4.1", - "jest-matcher-utils": "30.4.1", - "jest-message-util": "30.4.1", - "jest-runtime": "30.4.2", - "jest-snapshot": "30.4.1", - "jest-util": "30.4.1", + "jest-each": "30.5.2", + "jest-matcher-utils": "30.5.2", + "jest-message-util": "30.5.1", + "jest-runtime": "30.5.2", + "jest-snapshot": "30.5.2", + "jest-util": "30.5.1", "p-limit": "^3.1.0", - "pretty-format": "30.4.1", + "pretty-format": "30.5.1", "pure-rand": "^7.0.0", "slash": "^3.0.0", "stack-utils": "^2.0.6" @@ -8942,21 +8987,21 @@ } }, "node_modules/jest-cli": { - "version": "30.4.2", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-30.4.2.tgz", - "integrity": "sha512-jfA2ocvVHMXS2QijrJ0d31ektP+d/W0T5RpcTX2Pq+3sVqHlsXVCM2+FmwpL+bdY8OfHpIg9xMxLF17Zg0U49Q==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-30.5.2.tgz", + "integrity": "sha512-YYYxUUVjFgPvgEleKNKMaYGIFgR3l3832Cl0kRL/oCiDZ03v7wImUtquHl2OOBCCNgprjZgBN5bczS/JklPBDg==", "dev": true, "license": "MIT", "dependencies": { - "@jest/core": "30.4.2", - "@jest/test-result": "30.4.1", - "@jest/types": "30.4.1", + "@jest/core": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/types": "30.5.1", "chalk": "^4.1.2", "exit-x": "^0.2.2", "import-local": "^3.2.0", - "jest-config": "30.4.2", - "jest-util": "30.4.1", - "jest-validate": "30.4.1", + "jest-config": "30.5.2", + "jest-util": "30.5.1", + "jest-validate": "30.5.1", "yargs": "^17.7.2" }, "bin": { @@ -8975,33 +9020,33 @@ } }, "node_modules/jest-config": { - "version": "30.4.2", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-30.4.2.tgz", - "integrity": "sha512-rNHAShJQqQwFNoL0hbf3BphSBOWnpOUAKvidLS/AjNVLPfoj5mSf4jQMfW3cYOs6hXeZC7nF7mDHaBnbxELOzg==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-30.5.2.tgz", + "integrity": "sha512-U6221OZekabePvGcGPf4raIBKMvYQWFHvhobDJRojOYaFMj2HaGytAdknjDhYc6JTz2fdHW9+6k0wWUDaNeOFQ==", "dev": true, "license": "MIT", "dependencies": { "@babel/core": "^7.27.4", - "@jest/get-type": "30.1.0", - "@jest/pattern": "30.4.0", - "@jest/test-sequencer": "30.4.1", - "@jest/types": "30.4.1", - "babel-jest": "30.4.1", + "@jest/get-type": "30.5.0", + "@jest/pattern": "30.5.0", + "@jest/test-sequencer": "30.5.2", + "@jest/types": "30.5.1", + "babel-jest": "30.5.2", "chalk": "^4.1.2", "ci-info": "^4.2.0", "deepmerge": "^4.3.1", - "glob": "^10.5.0", + "glob": "^13.0.6", "graceful-fs": "^4.2.11", - "jest-circus": "30.4.2", - "jest-docblock": "30.4.0", - "jest-environment-node": "30.4.1", - "jest-regex-util": "30.4.0", - "jest-resolve": "30.4.1", - "jest-runner": "30.4.2", - "jest-util": "30.4.1", - "jest-validate": "30.4.1", + "jest-circus": "30.5.2", + "jest-docblock": "30.5.0", + "jest-environment-node": "30.5.2", + "jest-regex-util": "30.5.0", + "jest-resolve": "30.5.1", + "jest-runner": "30.5.2", + "jest-util": "30.5.1", + "jest-validate": "30.5.1", "parse-json": "^5.2.0", - "pretty-format": "30.4.1", + "pretty-format": "30.5.1", "slash": "^3.0.0", "strip-json-comments": "^3.1.1" }, @@ -9025,26 +9070,83 @@ } } }, - "node_modules/jest-diff": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.4.1.tgz", - "integrity": "sha512-CRpFK0RtLriVDGcPPAnR6HMVI8bSR2jnUIgralhauzYQZIb4RH9AtEInTuQr65LmmGggGcRT6HIASxwqsVsmlA==", + "node_modules/jest-config/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/jest-config/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "dev": true, "license": "MIT", "dependencies": { - "@jest/diff-sequences": "30.4.0", - "@jest/get-type": "30.1.0", + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jest-config/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-config/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-diff": { + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.5.2.tgz", + "integrity": "sha512-rBtHnI6BWTiWj3lM7fOLVfChx7R9B0u9VV3PRHawKs79x6ZjW1QoSrKenaigNGWlvhtoi2BqvDbABDie+Os3xQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jest/diff-sequences": "30.5.0", + "@jest/get-type": "30.5.0", "chalk": "^4.1.2", - "pretty-format": "30.4.1" + "pretty-format": "30.5.1" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-docblock": { - "version": "30.4.0", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-30.4.0.tgz", - "integrity": "sha512-ZPMabUZCx5MpbZ2eBYSvZ0J8fvo3dR9oM+eeUpb3aKNQFuS2tu3Duw1TNlMoP8k3WQgKGJuhcMFvwcVuq6T7oA==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-30.5.0.tgz", + "integrity": "sha512-NwDqcxtoZi33RhuW+zJS/RVA3rmheQ8BnwpYZuc/Eruaz6seQb7+aoCeDZu/3X7W2XmD8DbSo9Pn72DbKsBFYw==", "dev": true, "license": "MIT", "dependencies": { @@ -9055,70 +9157,384 @@ } }, "node_modules/jest-each": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-30.4.1.tgz", - "integrity": "sha512-/8MJbH6fuj48TstjrMf+u/pd06Qezz5xOXvZA6442heNOWr8bdeoGZX2d9fCn028CoMgYmroH9//zky5GfyYmA==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-30.5.2.tgz", + "integrity": "sha512-GRrW+7fmmgmkvyfEBqc1QFdWnF1Ex5yG6Y6AWL4TTxnkWlKIT98dsKh3P3UuWm6v4XsQwVE6DEzXIPMzWJ3ZbA==", "dev": true, "license": "MIT", "dependencies": { - "@jest/get-type": "30.1.0", - "@jest/types": "30.4.1", + "@jest/get-type": "30.5.0", + "@jest/types": "30.5.1", "chalk": "^4.1.2", - "jest-util": "30.4.1", - "pretty-format": "30.4.1" + "jest-regex-util": "30.5.0", + "jest-util": "30.5.1", + "pretty-format": "30.5.1" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-environment-node": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-30.4.1.tgz", - "integrity": "sha512-4FZYVOk85hz2AyT6BbarKy9u37g6DbrDyCdFhsnDdXqyrueYQvB+0zO4f/kqLCRD0BsPRXPMNJeQwihKZV8naw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-30.5.2.tgz", + "integrity": "sha512-Ciz4KgTGIbojxSKpuFImgWJj5EyqfE8xMq9NxWmOXnQywHHS03H9Mv+vaCB29J5pr3JBrY27WbRV18rBdjh8Dg==", "dev": true, "license": "MIT", "dependencies": { - "@jest/environment": "30.4.1", - "@jest/fake-timers": "30.4.1", - "@jest/types": "30.4.1", + "@jest/environment": "30.5.2", + "@jest/fake-timers": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "jest-mock": "30.4.1", - "jest-util": "30.4.1", - "jest-validate": "30.4.1" + "jest-mock": "30.5.2", + "jest-util": "30.5.1", + "jest-validate": "30.5.1" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-haste-map": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-30.4.1.tgz", - "integrity": "sha512-rFrcONd8jeFsyw+Z9CrScJgglRf2+NFmNam8dKu7n+SoHqNYT47mn0DdEcVUZJpvh7Iz6/si7f7yUH7GJHVgnw==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-30.5.1.tgz", + "integrity": "sha512-VIFgt67jW480YDxKfEv9IYQKrFpYt7bOCMn3VsnjK7AK9qo7p6acpnA1DHwsVOULE3dTaYew/6JaTD/d0VDHoQ==", "dev": true, "license": "MIT", "dependencies": { - "@jest/types": "30.4.1", + "@jest/types": "30.5.1", + "@parcel/watcher": "^2.6.0", "@types/node": "*", "anymatch": "^3.1.3", "fb-watchman": "^2.0.2", + "fdir": "^6.5.0", "graceful-fs": "^4.2.11", - "jest-regex-util": "30.4.0", - "jest-util": "30.4.1", - "jest-worker": "30.4.1", - "picomatch": "^4.0.3", - "walker": "^1.0.8" + "jest-regex-util": "30.5.0", + "jest-util": "30.5.1", + "jest-worker": "30.5.1", + "picomatch": "^4.0.3" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", + "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.3", + "is-glob": "^4.0.3", + "node-addon-api": "^7.0.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" }, "optionalDependencies": { - "fsevents": "^2.3.3" + "@parcel/watcher-android-arm64": "2.6.0", + "@parcel/watcher-darwin-arm64": "2.6.0", + "@parcel/watcher-darwin-x64": "2.6.0", + "@parcel/watcher-freebsd-x64": "2.6.0", + "@parcel/watcher-linux-arm-glibc": "2.6.0", + "@parcel/watcher-linux-arm-musl": "2.6.0", + "@parcel/watcher-linux-arm64-glibc": "2.6.0", + "@parcel/watcher-linux-arm64-musl": "2.6.0", + "@parcel/watcher-linux-x64-glibc": "2.6.0", + "@parcel/watcher-linux-x64-musl": "2.6.0", + "@parcel/watcher-win32-arm64": "2.6.0", + "@parcel/watcher-win32-x64": "2.6.0" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-android-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz", + "integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-darwin-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz", + "integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-darwin-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz", + "integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-freebsd-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz", + "integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-arm-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz", + "integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-arm-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz", + "integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-arm64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz", + "integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-arm64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz", + "integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-x64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz", + "integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-x64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz", + "integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-win32-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz", + "integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/@parcel/watcher-win32-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", + "integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/jest-haste-map/node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/jest-haste-map/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } } }, "node_modules/jest-haste-map/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", "engines": { @@ -9129,50 +9545,50 @@ } }, "node_modules/jest-leak-detector": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-30.4.1.tgz", - "integrity": "sha512-IpmyiioeHxiWDhesHnUFmOxcTzwCwKpgACgWajtAP+nYQXiY7DakTxB6Bx9JFiRMljr0AX1PvnQdaU1KFoz6NQ==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-30.5.1.tgz", + "integrity": "sha512-gt4GT2aWgEoCNTcBe4rqS74xTIUJxi+UD9SNSu9aOk5LmTEd6fS5KSTmAKAfitCCktQHNN+upUuL6EkBfFbMDQ==", "dev": true, "license": "MIT", "dependencies": { - "@jest/get-type": "30.1.0", - "pretty-format": "30.4.1" + "@jest/get-type": "30.5.0", + "pretty-format": "30.5.1" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-matcher-utils": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-30.4.1.tgz", - "integrity": "sha512-zvYfX5CaeEkFrrLS9suWe9rvJrm9J1Iv3ua8kIBv9GEPzcnsfBf0bob37la7s67fs0nlBC3EuvkOLnXQKxtx4A==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-30.5.2.tgz", + "integrity": "sha512-lFkB365PTIHOhPzwrb9T6gvlDnPpOZ7/c3ewOKKB7bzztqjVrtlyRL2MkyfJXpyY2u2SKw001JKrTx14fBUFcQ==", "dev": true, "license": "MIT", "dependencies": { - "@jest/get-type": "30.1.0", + "@jest/get-type": "30.5.0", "chalk": "^4.1.2", - "jest-diff": "30.4.1", - "pretty-format": "30.4.1" + "jest-diff": "30.5.2", + "pretty-format": "30.5.1" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-message-util": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-30.4.1.tgz", - "integrity": "sha512-kwCKIvq0MCW1HzLoGola9Te6JUdzgV0loyKJ3Qghrkz9i5/RRIHsL95BMQc2HBBhlBKC4j22K9p11TGHH8RBpQ==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-30.5.1.tgz", + "integrity": "sha512-UdQlLdd9wL/Ys7xRErckqwD6wPlSZYueosSWuHc1r2ztGLwlgPvtSJq2+BPEgaEY13WLvfFbmhTj8pba0Sd1jg==", "dev": true, "license": "MIT", "dependencies": { "@babel/code-frame": "^7.27.1", - "@jest/types": "30.4.1", + "@jest/types": "30.5.1", "@types/stack-utils": "^2.0.3", "chalk": "^4.1.2", "graceful-fs": "^4.2.11", - "jest-util": "30.4.1", + "jest-util": "30.5.1", "picomatch": "^4.0.3", - "pretty-format": "30.4.1", + "pretty-format": "30.5.1", "slash": "^3.0.0", "stack-utils": "^2.0.6" }, @@ -9181,9 +9597,9 @@ } }, "node_modules/jest-message-util/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", "engines": { @@ -9194,42 +9610,25 @@ } }, "node_modules/jest-mock": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-30.4.1.tgz", - "integrity": "sha512-/i8SVb8/NSB7RfNi8gfqu8gxLV23KaL5EpAttyb9iz8qWRIqXRLflycz/32wXsYkOnaUlx8NAKnJYtpsmXUmfw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-30.5.2.tgz", + "integrity": "sha512-KTHb37Fhj8xY8qPFvTFaFJHcdsumQp+ExsUlgoX232Agmc706gagBs53+CYvulV7MVQo9AgXOUxsqzzVBoJlrA==", "dev": true, "license": "MIT", "dependencies": { - "@jest/types": "30.4.1", + "@jest/expect-utils": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", - "jest-util": "30.4.1" + "jest-util": "30.5.1" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, - "node_modules/jest-pnp-resolver": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz", - "integrity": "sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - }, - "peerDependencies": { - "jest-resolve": "*" - }, - "peerDependenciesMeta": { - "jest-resolve": { - "optional": true - } - } - }, "node_modules/jest-regex-util": { - "version": "30.4.0", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-30.4.0.tgz", - "integrity": "sha512-mWlvLviKIgIQ8VCuM1xRdD0TWp3zlzionlmDBjuXVBs+VkmXq6FgW9T4Emr7oGz/Rk6feDCGyiugolcQEyp3mg==", + "version": "30.5.0", + "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-30.5.0.tgz", + "integrity": "sha512-Mg0WK7A6xRHLSA1udJ8y9f3lM0uUhFTBnLKzwPmqB9AylvpleJ6BLemR8K9dK27DY+cesDryoA7yLZCAHsPG1A==", "dev": true, "license": "MIT", "engines": { @@ -9237,100 +9636,100 @@ } }, "node_modules/jest-resolve": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-30.4.1.tgz", - "integrity": "sha512-Zry8Yq/yJcNAZ7dJ5F2heic8AheXvbFZ7XI5V+h28nrYZ7Qoyy4dItq8OodjnYD270mvX+ZudmrNV9cysqhW5Q==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-30.5.1.tgz", + "integrity": "sha512-wprhLejRtwN6h8ZgaqC0eYjGJ1uMdGPT/+b3eFncbG4NWuuP9QL+vWwRinu9waw7hkOLcpMJGVJAMgBwsPssMQ==", "dev": true, "license": "MIT", "dependencies": { "chalk": "^4.1.2", "graceful-fs": "^4.2.11", - "jest-haste-map": "30.4.1", - "jest-pnp-resolver": "^1.2.3", - "jest-util": "30.4.1", - "jest-validate": "30.4.1", + "jest-haste-map": "30.5.1", + "jest-util": "30.5.1", + "jest-validate": "30.5.1", "slash": "^3.0.0", - "unrs-resolver": "^1.7.11" + "unrs-resolver": "^1.12.1" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-resolve-dependencies": { - "version": "30.4.2", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-30.4.2.tgz", - "integrity": "sha512-gDiVh1I+GxYzz9oXlyw+1wv6VOYX1WYxMOfjsA3iGKePV2oxmbHhwxfkALxNxYy1ciw6APWwkW2zZONwP97aEQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-30.5.2.tgz", + "integrity": "sha512-GMI0DP5enX9Z2qW2zFy1bOkrCfWAOPRJQ7qHt0pdfrxBPsgWxglMPrRSK2TX/wRWYxcPRSLFg3Z88qPOzHx7FQ==", "dev": true, "license": "MIT", "dependencies": { - "jest-regex-util": "30.4.0", - "jest-snapshot": "30.4.1" + "jest-regex-util": "30.5.0", + "jest-snapshot": "30.5.2" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-runner": { - "version": "30.4.2", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-30.4.2.tgz", - "integrity": "sha512-2dw0PslVYXxffXGpLo+Ejad+KcI1Qkjn7f4X4619gf21oCUmL+SPfjqIa/losUem3yEOvfNZe/F1HWUcNpODcg==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-30.5.2.tgz", + "integrity": "sha512-/B6px7hiiNhVSRwuv9AGn0nawYvwsHeQZ3ItTd5Gp2diFd0EOKaWVeWqcbw3L88vx1GfpCKjQkxWItZCTl11Rw==", "dev": true, "license": "MIT", "dependencies": { - "@jest/console": "30.4.1", - "@jest/environment": "30.4.1", - "@jest/test-result": "30.4.1", - "@jest/transform": "30.4.1", - "@jest/types": "30.4.1", + "@jest/console": "30.5.2", + "@jest/environment": "30.5.2", + "@jest/source-map": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/transform": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", "chalk": "^4.1.2", "emittery": "^0.13.1", "exit-x": "^0.2.2", "graceful-fs": "^4.2.11", - "jest-docblock": "30.4.0", - "jest-environment-node": "30.4.1", - "jest-haste-map": "30.4.1", - "jest-leak-detector": "30.4.1", - "jest-message-util": "30.4.1", - "jest-resolve": "30.4.1", - "jest-runtime": "30.4.2", - "jest-util": "30.4.1", - "jest-watcher": "30.4.1", - "jest-worker": "30.4.1", - "p-limit": "^3.1.0", - "source-map-support": "0.5.13" + "jest-docblock": "30.5.0", + "jest-environment-node": "30.5.2", + "jest-haste-map": "30.5.1", + "jest-leak-detector": "30.5.1", + "jest-message-util": "30.5.1", + "jest-resolve": "30.5.1", + "jest-runtime": "30.5.2", + "jest-util": "30.5.1", + "jest-watcher": "30.5.2", + "jest-worker": "30.5.1", + "p-limit": "^3.1.0" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, "node_modules/jest-runtime": { - "version": "30.4.2", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-30.4.2.tgz", - "integrity": "sha512-3/5e8iPz2k/VLqlr8DgTftYyLUv8Su3FkCAO2/Od81UsUTpSxOrS6O5x5KkoQwyUjmpYyDJKeyAvg2T2nvpNkQ==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-30.5.2.tgz", + "integrity": "sha512-0paUAHBlheai10A3XSy9Xh+YBG0IROy+/qzcDPzQ/nbbXrznQzeWy5qniICWK6d3W3scaRQCVAbXdcK0ibBq4w==", "dev": true, "license": "MIT", "dependencies": { - "@jest/environment": "30.4.1", - "@jest/fake-timers": "30.4.1", - "@jest/globals": "30.4.1", - "@jest/source-map": "30.0.1", - "@jest/test-result": "30.4.1", - "@jest/transform": "30.4.1", - "@jest/types": "30.4.1", + "@jest/environment": "30.5.2", + "@jest/fake-timers": "30.5.2", + "@jest/globals": "30.5.2", + "@jest/source-map": "30.5.2", + "@jest/test-result": "30.5.2", + "@jest/transform": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", "chalk": "^4.1.2", - "cjs-module-lexer": "^2.1.0", + "cjs-module-lexer": "^2.2.0", "collect-v8-coverage": "^1.0.2", - "glob": "^10.5.0", + "es-module-lexer": "^2.1.0", + "glob": "^13.0.6", "graceful-fs": "^4.2.11", - "jest-haste-map": "30.4.1", - "jest-message-util": "30.4.1", - "jest-mock": "30.4.1", - "jest-regex-util": "30.4.0", - "jest-resolve": "30.4.1", - "jest-snapshot": "30.4.1", - "jest-util": "30.4.1", + "jest-haste-map": "30.5.1", + "jest-message-util": "30.5.1", + "jest-mock": "30.5.2", + "jest-regex-util": "30.5.0", + "jest-resolve": "30.5.1", + "jest-snapshot": "30.5.2", + "jest-util": "30.5.1", "slash": "^3.0.0", "strip-bom": "^4.0.0" }, @@ -9338,10 +9737,74 @@ "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" } }, + "node_modules/jest-runtime/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/jest-runtime/node_modules/brace-expansion": { + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "20 || >=22" + } + }, + "node_modules/jest-runtime/node_modules/es-module-lexer": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", + "dev": true, + "license": "MIT" + }, + "node_modules/jest-runtime/node_modules/glob": { + "version": "13.0.6", + "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", + "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "minimatch": "^10.2.2", + "minipass": "^7.1.3", + "path-scurry": "^2.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/jest-runtime/node_modules/minimatch": { + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.8" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, "node_modules/jest-snapshot": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-30.4.1.tgz", - "integrity": "sha512-tEOkkfOMppUyeiHwjZswOQ3lcnoTnws/q5FnGIaeIh/jmoU0ZlgMYRR8sTlTj+nNGCoJ0RDq6SfxGxCsyMTPmw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-30.5.2.tgz", + "integrity": "sha512-jKIdes25AnAH73dOCi2qE6J6vHJ6L2vyBS11M89kT50DVJcLTf2AOjvcc+2vVaN8lUbY5v2R83aqXo3Ro9fqYA==", "dev": true, "license": "MIT", "dependencies": { @@ -9350,20 +9813,20 @@ "@babel/plugin-syntax-jsx": "^7.27.1", "@babel/plugin-syntax-typescript": "^7.27.1", "@babel/types": "^7.27.3", - "@jest/expect-utils": "30.4.1", - "@jest/get-type": "30.1.0", - "@jest/snapshot-utils": "30.4.1", - "@jest/transform": "30.4.1", - "@jest/types": "30.4.1", + "@jest/expect-utils": "30.5.2", + "@jest/get-type": "30.5.0", + "@jest/snapshot-utils": "30.5.1", + "@jest/transform": "30.5.2", + "@jest/types": "30.5.1", "babel-preset-current-node-syntax": "^1.2.0", "chalk": "^4.1.2", - "expect": "30.4.1", + "expect": "30.5.2", "graceful-fs": "^4.2.11", - "jest-diff": "30.4.1", - "jest-matcher-utils": "30.4.1", - "jest-message-util": "30.4.1", - "jest-util": "30.4.1", - "pretty-format": "30.4.1", + "jest-diff": "30.5.2", + "jest-matcher-utils": "30.5.2", + "jest-message-util": "30.5.1", + "jest-util": "30.5.1", + "pretty-format": "30.5.1", "semver": "^7.7.2", "synckit": "^0.11.8" }, @@ -9372,9 +9835,9 @@ } }, "node_modules/jest-snapshot/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", "dev": true, "license": "ISC", "bin": { @@ -9385,13 +9848,13 @@ } }, "node_modules/jest-util": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-30.4.1.tgz", - "integrity": "sha512-vjQb1sACEiv13DKJMDToJpzVW0joCsIQrmbg0fi7CyOOt+g9jTuQl2A216pWRBYhOVt53XbL/2LbMKg1BECWOw==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-30.5.1.tgz", + "integrity": "sha512-yKuxmNy2rSbTXw+3SIPanJo+nV4/BS1p26v44IYBFMsswSQySfMMcPHErnOncda7i9HEz0q605rIhSTBVgrZTg==", "dev": true, "license": "MIT", "dependencies": { - "@jest/types": "30.4.1", + "@jest/types": "30.5.1", "@types/node": "*", "chalk": "^4.1.2", "ci-info": "^4.2.0", @@ -9403,9 +9866,9 @@ } }, "node_modules/jest-util/node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "dev": true, "license": "MIT", "engines": { @@ -9416,18 +9879,18 @@ } }, "node_modules/jest-validate": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-30.4.1.tgz", - "integrity": "sha512-PDWi4SOwLnwqNDfHZjOcsEFyZ4fc/2W2gVL3DEoyqnB6jCQMLRtfBong8s6omIw3lI0HWOus12xfnFmQtjW3fw==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-30.5.1.tgz", + "integrity": "sha512-i/buJ56wTpxihE93hQYNMfdOThS87+HGvLZzZJmU4xggPcdTYQq051iwALLCHp3q+SkCGH+EFejQZz5EbBSkkg==", "dev": true, "license": "MIT", "dependencies": { - "@jest/get-type": "30.1.0", - "@jest/types": "30.4.1", + "@jest/get-type": "30.5.0", + "@jest/types": "30.5.1", "camelcase": "^6.3.0", "chalk": "^4.1.2", "leven": "^3.1.0", - "pretty-format": "30.4.1" + "pretty-format": "30.5.1" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" @@ -9447,19 +9910,19 @@ } }, "node_modules/jest-watcher": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-30.4.1.tgz", - "integrity": "sha512-/l9UonmvCwjHH7d2h3iAwIloLc1H0S8mJZ/LNK3i86hqwPAz8otUJjP9MfYtz9Tt77Su5FD2xGjZn8d31IZHlw==", + "version": "30.5.2", + "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-30.5.2.tgz", + "integrity": "sha512-rqRgg4R11GA9m1UsEZwQeixHsgZReCn6TOHAHtIH33yXrIvoX0OGPA20Yzzjkz7X40fZvcRSxEpQppYPcWzmcQ==", "dev": true, "license": "MIT", "dependencies": { - "@jest/test-result": "30.4.1", - "@jest/types": "30.4.1", + "@jest/test-result": "30.5.2", + "@jest/types": "30.5.1", "@types/node": "*", "ansi-escapes": "^4.3.2", "chalk": "^4.1.2", "emittery": "^0.13.1", - "jest-util": "30.4.1", + "jest-util": "30.5.1", "string-length": "^4.0.2" }, "engines": { @@ -9467,15 +9930,15 @@ } }, "node_modules/jest-worker": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-30.4.1.tgz", - "integrity": "sha512-SHynN/q/QD++iNyvMdy+WMmbCGk8jIsNcRxycXbWubSOhvo6T+j2afcfUSl+3hYsiBebOTo0cT7c2H7CXugu1g==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-30.5.1.tgz", + "integrity": "sha512-Cbxh5v7AoLuFRmFJSM4/aHdQ68rjXvUWr716EE0Dh3I7T+T/3FgFKhOERGXHcU2Meftq9+9zxPM3TSNyI9D+HA==", "dev": true, "license": "MIT", "dependencies": { "@types/node": "*", "@ungap/structured-clone": "^1.3.0", - "jest-util": "30.4.1", + "jest-util": "30.5.1", "merge-stream": "^2.0.0", "supports-color": "^8.1.1" }, @@ -9516,9 +9979,9 @@ "license": "MIT" }, "node_modules/js-yaml": { - "version": "3.14.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz", - "integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==", + "version": "3.15.2", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", + "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", "dev": true, "license": "MIT", "dependencies": { @@ -10005,9 +10468,9 @@ } }, "node_modules/make-dir/node_modules/semver": { - "version": "7.8.0", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", - "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", + "version": "7.8.5", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", + "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", "dev": true, "license": "ISC", "bin": { @@ -10017,16 +10480,6 @@ "node": ">=10" } }, - "node_modules/makeerror": { - "version": "1.0.12", - "resolved": "https://registry.npmjs.org/makeerror/-/makeerror-1.0.12.tgz", - "integrity": "sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "tmpl": "1.0.5" - } - }, "node_modules/map-obj": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-4.3.0.tgz", @@ -10163,10 +10616,10 @@ } }, "node_modules/minipass": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", - "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", - "license": "ISC", + "version": "7.1.3", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", + "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "license": "BlueOak-1.0.0", "engines": { "node": ">=16 || 14 >=14.17" } @@ -10197,9 +10650,9 @@ "dev": true }, "node_modules/nanoid": { - "version": "3.3.12", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz", - "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==", + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", "dev": true, "funding": [ { @@ -10216,12 +10669,13 @@ } }, "node_modules/napi-postinstall": { - "version": "0.3.4", - "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz", - "integrity": "sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==", + "version": "0.3.7", + "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.7.tgz", + "integrity": "sha512-jyU4cU4kVAmy/3qjP+DcoQTNXfINHc+dFw54gGqWC8nu0mpV0kOnk7kff+J+Q18SbX0k3Np8Rm7yFjd3phatNQ==", "dev": true, "license": "MIT", "bin": { + "napi-patch": "lib/patch.js", "napi-postinstall": "lib/cli.js" }, "engines": { @@ -10289,11 +10743,14 @@ "license": "MIT" }, "node_modules/node-releases": { - "version": "2.0.38", - "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.38.tgz", - "integrity": "sha512-3qT/88Y3FbH/Kx4szpQQ4HzUbVrHPKTLVpVocKiLfoYvw9XSGOX2FmD2d6DrXbVYyAQTF2HeF6My8jmzx7/CRw==", + "version": "2.0.60", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.60.tgz", + "integrity": "sha512-OmO8+GM1JUZqXET720VrJCwkjUCXmCMQm0Z3UDDRbfNLHS4NEAvY60j5jiFv0tkKw2PNNlqOLhahVmwJIOLDIQ==", "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=18" + } }, "node_modules/normalize-package-data": { "version": "2.5.0", @@ -10382,16 +10839,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "dev": true, - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, "node_modules/onetime": { "version": "5.1.2", "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", @@ -10565,16 +11012,6 @@ "node": ">=8" } }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/path-key": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", @@ -10590,9 +11027,9 @@ "dev": true }, "node_modules/path-scurry": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.1.tgz", - "integrity": "sha512-oWyT4gICAu+kaA7QWk/jvCHWarMKNs6pXOGWKDTr7cw4IGcUbW+PeTfbaQiLGheFRpjo6O9J0PmyMfQPjH71oA==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-2.0.2.tgz", + "integrity": "sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { @@ -10600,7 +11037,7 @@ "minipass": "^7.1.2" }, "engines": { - "node": "20 || >=22" + "node": "18 || 20 || >=22" }, "funding": { "url": "https://github.com/sponsors/isaacs" @@ -10626,9 +11063,9 @@ } }, "node_modules/pg-protocol": { - "version": "1.14.0", - "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.14.0.tgz", - "integrity": "sha512-n5taZ1kO3s9ngDTVxsEznOqCyToTgz0FLuPq0B33COy5pPpuWJpY3/2oRBVETuOgzdqRXfWpM9HIhp2LBBT1BA==", + "version": "1.16.1", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz", + "integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==", "license": "MIT" }, "node_modules/pg-types": { @@ -10688,28 +11125,25 @@ } }, "node_modules/playwright": { - "version": "1.62.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.62.1.tgz", - "integrity": "sha512-0M+L3LAD8/nm554LOla9Ayx0j0tmFZ0FBcoQ7F1VuVHpM/XpiC8RcDzBQB8W5+hA8L22THxELzeF+2WcUzvcLg==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.62.1" + "playwright-core": "1.64.1" }, "bin": { "playwright": "cli.js" }, "engines": { "node": ">=20" - }, - "optionalDependencies": { - "fsevents": "2.3.2" } }, "node_modules/playwright-core": { - "version": "1.62.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.62.1.tgz", - "integrity": "sha512-wPYSwEBJY9GHraISXqyqtx0na0LpO3XEX7jNDhntbex7tzUS7kLnZsOlFruFJB4Hi/rhDMjXGqHewDZ68nYZVw==", + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", "dev": true, "license": "Apache-2.0", "bin": { @@ -10719,21 +11153,6 @@ "node": ">=20" } }, - "node_modules/playwright/node_modules/fsevents": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", - "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" - } - }, "node_modules/possible-typed-array-names": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", @@ -10745,9 +11164,9 @@ } }, "node_modules/postcss": { - "version": "8.5.15", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz", - "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==", + "version": "8.5.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", + "integrity": "sha512-YUbWYCgErwnMAVkjUnYa+KlMBzGpHwiIt/DE7f0G33AuX2LH9UcTk6KgWxd3zRU+pN3u/C+Xl3EnMLM4Hea7Sg==", "dev": true, "funding": [ { @@ -10764,11 +11183,10 @@ } ], "license": "MIT", - "peer": true, "dependencies": { - "nanoid": "^3.3.12", + "nanoid": "^3.3.20", "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" + "source-map-js": "^1.2.2" }, "engines": { "node": "^10 || ^12 || >=14" @@ -10846,16 +11264,16 @@ } }, "node_modules/pretty-format": { - "version": "30.4.1", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.4.1.tgz", - "integrity": "sha512-K6KiKMHTL4jjX4u3Kir2EW07nRfcqVTXIImx50wbjHQTcZPgg+gjVeNTIT3l3L1Rd4UefxfogquC9J37SoFyyw==", + "version": "30.5.1", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.1.tgz", + "integrity": "sha512-byhRAPguVKMQIj4kjJwJ5lAskVhfuiSdiYl/aLTWpgkGEmic2jYhJh1yE9ih8Ox44Xg9ccCT11/S6QrzSJuNrg==", "dev": true, "license": "MIT", "dependencies": { - "@jest/schemas": "30.4.1", - "ansi-styles": "^5.2.0", - "react-is-18": "npm:react-is@^18.3.1", - "react-is-19": "npm:react-is@^19.2.5" + "@jest/react-is-18": "npm:react-is@^18.3.1", + "@jest/react-is-19": "npm:react-is@^19.2.5", + "@jest/schemas": "30.5.0", + "ansi-styles": "^5.2.0" }, "engines": { "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" @@ -10882,9 +11300,9 @@ "license": "ISC" }, "node_modules/protobufjs": { - "version": "7.6.4", - "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.4.tgz", - "integrity": "sha512-RJJPTTpvFfHcWLkIa2JFWK4XvtSzS0yEWDmunqHXli1h3JlkbcQZXDZdcWxv+JK3Xsl5/UFDPZ0iGm7DAengYw==", + "version": "7.6.6", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.6.tgz", + "integrity": "sha512-dYDWdjSl5RNb7SgPxGQcRU+GtvP7s2fpkrY0r432PcOIaZ0/rBcxEZnQN67iJhFuQiVw754JDoPruPCNdGsbjg==", "hasInstallScript": true, "license": "BSD-3-Clause", "dependencies": { @@ -10989,22 +11407,6 @@ "node": ">=0.10.0" } }, - "node_modules/react-is-18": { - "name": "react-is", - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "dev": true, - "license": "MIT" - }, - "node_modules/react-is-19": { - "name": "react-is", - "version": "19.2.6", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.2.6.tgz", - "integrity": "sha512-XjBR15BhXuylgWGuslhDKqlSayuqvqBX91BP8pauG8kd1zY8kotkNWbXksTCNRarse4kuGbe2kIY05ARtwNIvw==", - "dev": true, - "license": "MIT" - }, "node_modules/read-pkg": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/read-pkg/-/read-pkg-5.2.0.tgz", @@ -11334,7 +11736,6 @@ "integrity": "sha512-pAQK9HalE84QSm4Po3EmWIZPd3FnjkShVkiMlz1iligWYkWQ7wHYd1PF/T7QZ5TVSD6uSTon5gBVMSM4JfBV+A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@types/estree": "1.0.8" }, @@ -11682,24 +12083,14 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", + "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" } }, - "node_modules/source-map-support": { - "version": "0.5.13", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.13.tgz", - "integrity": "sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w==", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, "node_modules/spdx-correct": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/spdx-correct/-/spdx-correct-3.2.0.tgz", @@ -12040,13 +12431,13 @@ } }, "node_modules/synckit": { - "version": "0.11.12", - "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.12.tgz", - "integrity": "sha512-Bh7QjT8/SuKUIfObSXNHNSK6WHo6J1tHCqJsuaFDP7gP0fkzSfTxI8y85JrppZ0h8l0maIgc2tfuZQ6/t3GtnQ==", + "version": "0.11.13", + "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.13.tgz", + "integrity": "sha512-eNRKgb3z66Yp3D2CixVujOUvXLFUTij/zVnV8KRyvFdQwpz7I5DS8UfRkTeLzb64u+dkzDSdelE24izu+zSSUg==", "dev": true, "license": "MIT", "dependencies": { - "@pkgr/core": "^0.2.9" + "@pkgr/core": "^0.3.6" }, "engines": { "node": "^14.18.0 || >=16.0.0" @@ -12056,9 +12447,9 @@ } }, "node_modules/systeminformation": { - "version": "5.31.7", - "resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.31.7.tgz", - "integrity": "sha512-/8NC53e5nP9nmhn42/ncdOkyJnOoue/Vy+tJOyUGd1Yv66G069wK4rrziwhrqDETgk78CudTQupw5z19S5uoZw==", + "version": "5.33.16", + "resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.33.16.tgz", + "integrity": "sha512-R+Lh69IJXfJj6bfyH1In5cIR9FTr4hBS39YvlZHZjsK1p9cuELPq7hplZZIb56ZESMMb+DzdKqqE6Iomi01Mvg==", "license": "MIT", "os": [ "darwin", @@ -12074,7 +12465,7 @@ "systeminformation": "lib/cli.js" }, "engines": { - "node": ">=8.0.0" + "node": ">=10.0.0" }, "funding": { "type": "Buy me a coffee", @@ -12085,8 +12476,7 @@ "version": "4.3.3", "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.3.tgz", "integrity": "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ==", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/tapable": { "version": "2.3.3", @@ -12174,64 +12564,57 @@ } }, "node_modules/test-exclude": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-6.0.0.tgz", - "integrity": "sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w==", + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.2.tgz", + "integrity": "sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==", "dev": true, "license": "ISC", "dependencies": { "@istanbuljs/schema": "^0.1.2", - "glob": "^7.1.4", - "minimatch": "^3.0.4" + "glob": "^10.4.1", + "minimatch": "^10.2.2" }, "engines": { - "node": ">=8" + "node": ">=18" + } + }, + "node_modules/test-exclude/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" } }, "node_modules/test-exclude/node_modules/brace-expansion": { - "version": "1.1.14", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.14.tgz", - "integrity": "sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "dev": true, "license": "MIT", "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/test-exclude/node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "dev": true, - "license": "ISC", - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" + "balanced-match": "^4.0.2" }, "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" + "node": "20 || >=22" } }, "node_modules/test-exclude/node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", + "version": "10.2.6", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", + "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", "dev": true, - "license": "ISC", + "license": "BlueOak-1.0.0", "dependencies": { - "brace-expansion": "^1.1.7" + "brace-expansion": "^5.0.8" }, "engines": { - "node": "*" + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" } }, "node_modules/text-segmentation": { @@ -12258,13 +12641,6 @@ "node": ">=14.14" } }, - "node_modules/tmpl": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/tmpl/-/tmpl-1.0.5.tgz", - "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", - "dev": true, - "license": "BSD-3-Clause" - }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -12299,7 +12675,7 @@ "version": "1.14.1", "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz", "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", - "devOptional": true + "dev": true }, "node_modules/type-detect": { "version": "4.0.8", @@ -12493,38 +12869,41 @@ } }, "node_modules/unrs-resolver": { - "version": "1.11.1", - "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.11.1.tgz", - "integrity": "sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==", + "version": "1.12.2", + "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.12.2.tgz", + "integrity": "sha512-dmlRxBJJayXjqTwC+JtF1HhJmgf3ftQ3YejFcZrf4+KKtJv0qDsK1pjqaaVjG7wJ5NJ6UVP1OqRMQ71Z4C3rxQ==", "dev": true, "hasInstallScript": true, "license": "MIT", "dependencies": { - "napi-postinstall": "^0.3.0" + "napi-postinstall": "^0.3.4" }, "funding": { "url": "https://opencollective.com/unrs-resolver" }, "optionalDependencies": { - "@unrs/resolver-binding-android-arm-eabi": "1.11.1", - "@unrs/resolver-binding-android-arm64": "1.11.1", - "@unrs/resolver-binding-darwin-arm64": "1.11.1", - "@unrs/resolver-binding-darwin-x64": "1.11.1", - "@unrs/resolver-binding-freebsd-x64": "1.11.1", - "@unrs/resolver-binding-linux-arm-gnueabihf": "1.11.1", - "@unrs/resolver-binding-linux-arm-musleabihf": "1.11.1", - "@unrs/resolver-binding-linux-arm64-gnu": "1.11.1", - "@unrs/resolver-binding-linux-arm64-musl": "1.11.1", - "@unrs/resolver-binding-linux-ppc64-gnu": "1.11.1", - "@unrs/resolver-binding-linux-riscv64-gnu": "1.11.1", - "@unrs/resolver-binding-linux-riscv64-musl": "1.11.1", - "@unrs/resolver-binding-linux-s390x-gnu": "1.11.1", - "@unrs/resolver-binding-linux-x64-gnu": "1.11.1", - "@unrs/resolver-binding-linux-x64-musl": "1.11.1", - "@unrs/resolver-binding-wasm32-wasi": "1.11.1", - "@unrs/resolver-binding-win32-arm64-msvc": "1.11.1", - "@unrs/resolver-binding-win32-ia32-msvc": "1.11.1", - "@unrs/resolver-binding-win32-x64-msvc": "1.11.1" + "@unrs/resolver-binding-android-arm-eabi": "1.12.2", + "@unrs/resolver-binding-android-arm64": "1.12.2", + "@unrs/resolver-binding-darwin-arm64": "1.12.2", + "@unrs/resolver-binding-darwin-x64": "1.12.2", + "@unrs/resolver-binding-freebsd-x64": "1.12.2", + "@unrs/resolver-binding-linux-arm-gnueabihf": "1.12.2", + "@unrs/resolver-binding-linux-arm-musleabihf": "1.12.2", + "@unrs/resolver-binding-linux-arm64-gnu": "1.12.2", + "@unrs/resolver-binding-linux-arm64-musl": "1.12.2", + "@unrs/resolver-binding-linux-loong64-gnu": "1.12.2", + "@unrs/resolver-binding-linux-loong64-musl": "1.12.2", + "@unrs/resolver-binding-linux-ppc64-gnu": "1.12.2", + "@unrs/resolver-binding-linux-riscv64-gnu": "1.12.2", + "@unrs/resolver-binding-linux-riscv64-musl": "1.12.2", + "@unrs/resolver-binding-linux-s390x-gnu": "1.12.2", + "@unrs/resolver-binding-linux-x64-gnu": "1.12.2", + "@unrs/resolver-binding-linux-x64-musl": "1.12.2", + "@unrs/resolver-binding-openharmony-arm64": "1.12.2", + "@unrs/resolver-binding-wasm32-wasi": "1.12.2", + "@unrs/resolver-binding-win32-arm64-msvc": "1.12.2", + "@unrs/resolver-binding-win32-ia32-msvc": "1.12.2", + "@unrs/resolver-binding-win32-x64-msvc": "1.12.2" } }, "node_modules/upath": { @@ -12539,9 +12918,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", - "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "version": "1.3.4", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.3.4.tgz", + "integrity": "sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==", "dev": true, "funding": [ { @@ -12659,16 +13038,6 @@ "spdx-expression-parse": "^3.0.0" } }, - "node_modules/walker": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/walker/-/walker-1.0.8.tgz", - "integrity": "sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "makeerror": "1.0.12" - } - }, "node_modules/wcwidth": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.1.tgz", @@ -12967,16 +13336,16 @@ } }, "node_modules/workbox-build/node_modules/brace-expansion": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", - "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "dev": true, "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" } }, "node_modules/workbox-build/node_modules/glob": { @@ -13083,16 +13452,16 @@ } }, "node_modules/workbox-cli/node_modules/brace-expansion": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", - "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "version": "5.0.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", + "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", "dev": true, "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" }, "engines": { - "node": "18 || 20 || >=22" + "node": "20 || >=22" } }, "node_modules/workbox-cli/node_modules/glob": { @@ -13297,13 +13666,6 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "dev": true, - "license": "ISC" - }, "node_modules/write-file-atomic": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-5.0.1.tgz", @@ -13368,9 +13730,9 @@ "dev": true }, "node_modules/yaml": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz", - "integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==", + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", "license": "ISC", "bin": { "yaml": "bin.mjs" diff --git a/package.json b/package.json index 158266205..7ae5adffb 100644 --- a/package.json +++ b/package.json @@ -1,16 +1,16 @@ { "devDependencies": { - "@playwright/test": "^1.62.1", + "@playwright/test": "^1.64.1", "@tailwindcss/typography": "^0.5.20", - "autoprefixer": "^10.5.0", - "daisyui": "^5.7.16", - "jest": "^30.4.2", - "postcss": "^8.5.15", + "autoprefixer": "^10.6.1", + "daisyui": "^5.7.50", + "jest": "^30.5.2", + "postcss": "^8.5.31", "tailwindcss": "^4.3.3", "workbox-cli": "^7.4.1" }, "dependencies": { - "@opentelemetry/auto-instrumentations-node": "^0.77.0", + "@opentelemetry/auto-instrumentations-node": "^0.82.0", "@tailwindcss/cli": "^4.3.3", "ansi-up": "^1.0.0", "html2canvas": "^1.4.1" diff --git a/web-components/package-lock.json b/web-components/package-lock.json index a6e0139d7..47ffc292e 100644 --- a/web-components/package-lock.json +++ b/web-components/package-lock.json @@ -9,46 +9,46 @@ "version": "1.0.0", "license": "ISC", "dependencies": { - "@codemirror/autocomplete": "^6.20.3", - "@codemirror/commands": "^6.11.0", + "@codemirror/autocomplete": "^6.20.4", + "@codemirror/commands": "^6.11.1", "@codemirror/lang-sql": "^6.10.0", - "@codemirror/language": "^6.12.4", + "@codemirror/language": "^6.13.1", "@codemirror/lint": "^6.9.7", - "@codemirror/state": "^6.7.4", - "@codemirror/view": "^6.43.11", - "@lezer/highlight": "^1.2.3", + "@codemirror/state": "^6.7.6", + "@codemirror/view": "^6.43.15", + "@lezer/highlight": "^1.2.5", "@lit-labs/virtualizer": "^2.1.1", "@milkdown/crepe": "7.22.3", "@milkdown/kit": "7.22.3", - "@napi-rs/canvas": "^1.0.0", - "@rrweb/replay": "^2.0.0", + "@napi-rs/canvas": "^1.0.13", + "@rrweb/replay": "^2.1.7", "@rrweb/types": "^2.0.0-alpha.18", - "@types/lodash": "^4.17.24", + "@types/lodash": "^4.17.27", "ansi-up": "^1.0.0", "clsx": "^2.1.1", - "date-fns": "^4.3.0", + "date-fns": "^4.4.0", "echarts": "^6.1.0", "elkjs": "^0.12.0", "js-yaml": "^4.3.2", "jsonpath": "^1.3.0", "lit": "^3.3.3", "lodash": "^4.17.23", - "monaco-editor": "^0.55.1", - "vite": "^8.0.16" + "monaco-editor": "^0.57.0", + "vite": "^8.3.5" }, "devDependencies": { - "@types/bun": "^1.4.0", + "@types/bun": "^1.4.4", "@types/js-yaml": "^4.0.9", "@types/jsonpath": "^0.2.4", "@types/node": "^25.9.1", - "@vitest/browser": "^4.1.11", - "happy-dom": "^20.14.0", + "@vitest/browser": "^5.0.5", + "happy-dom": "^21.0.4", "jsdom": "^29.1.1", - "typescript": "^6.0.3", + "typescript": "^7.0.2", "vite-plugin-monaco-editor": "^1.1.0", "vite-plugin-node-polyfills": "^0.28.0", - "vitest": "^4.1.11", - "vitest-canvas-mock": "^1.1.5" + "vitest": "^5.0.5", + "vitest-canvas-mock": "^1.2.0" } }, "node_modules/@asamuzakjp/css-color": { @@ -145,9 +145,9 @@ } }, "node_modules/@blazediff/core": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/@blazediff/core/-/core-1.9.1.tgz", - "integrity": "sha512-ehg3jIkYKulZh+8om/O25vkvSsXXwC+skXmyA87FFx6A/45eqOkZsBltMw/TVteb0mloiGT8oGRTcjRAz66zaA==", + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@blazediff/core/-/core-1.10.0.tgz", + "integrity": "sha512-AOQff0zgR7cGsZL+4E7hVkmujoPUpm0J9xzWGWZj5wCjd3gmxESXAPfKyuzs93VdpQNFhHlBhfOjrcZ+XTERtQ==", "dev": true, "license": "MIT" }, @@ -165,9 +165,10 @@ } }, "node_modules/@codemirror/autocomplete": { - "version": "6.20.3", - "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.3.tgz", - "integrity": "sha512-tlosUqb+3BbxCxZdu4tKeRghPFC+QM7q4X5YhKV2eCmPG+1r2F3f4AaSz5sCrFqUtX4Jh20VFTKecl16MgiV9g==", + "version": "6.20.4", + "resolved": "https://registry.npmjs.org/@codemirror/autocomplete/-/autocomplete-6.20.4.tgz", + "integrity": "sha512-yF8RhOf2SXlg00+qtupzLhrglcas61boqaONiNcbPIebHCpJocpqTBA6dyrtUrQO47hqyTdeob/3XnYilT7TaQ==", + "license": "MIT", "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.0.0", @@ -176,9 +177,10 @@ } }, "node_modules/@codemirror/commands": { - "version": "6.11.0", - "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.0.tgz", - "integrity": "sha512-/K4Rl5BN0OtTiPWmJCdqODu38XnDMsDxKY5rgrPnCkutPTJf2wVbkoixLfealF5Kwse/s8P8M5jAiURiwSwnFA==", + "version": "6.11.1", + "resolved": "https://registry.npmjs.org/@codemirror/commands/-/commands-6.11.1.tgz", + "integrity": "sha512-O/4hG3SC1YwcmQ0d2UVNDs+AsaNWd1iHVxbTeEBuqH+6bExAiPK3iS/BvpY6rZGURALv4ZD3sIgcCmRvw3ehBg==", + "license": "MIT", "dependencies": { "@codemirror/language": "^6.0.0", "@codemirror/state": "^6.7.0", @@ -446,11 +448,13 @@ } }, "node_modules/@codemirror/language": { - "version": "6.12.4", - "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.12.4.tgz", - "integrity": "sha512-1q4PaT+o6PbgpkJt4Q8Fv5XJxTy4FUZ4MWETtyiDw3J0Pyr9E2vqcKL+k9wcvjNTIsauxvE7OfmWj3FRPHQ76A==", + "version": "6.13.1", + "resolved": "https://registry.npmjs.org/@codemirror/language/-/language-6.13.1.tgz", + "integrity": "sha512-zfvU2r3TyylQLMj/te+5CnQ0rSqZi8B1oTCBbQkagcLW4Xc6imab6qN+pEJhsuNOLaJqiRyBXp9UhWA1DhVvDw==", + "license": "MIT", "dependencies": { "@codemirror/state": "^6.0.0", + "@codemirror/streamparser": "^6.0.0", "@codemirror/view": "^6.23.0", "@lezer/common": "^1.5.0", "@lezer/highlight": "^1.0.0", @@ -517,9 +521,10 @@ } }, "node_modules/@codemirror/state": { - "version": "6.7.4", - "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.4.tgz", - "integrity": "sha512-QhQIVRY+xHZDxwOSFrJ1eUMapJBUID3IdeAjf7dHO7zBUzSkyooHiodnalz5MG3iHzwixKMlAAyn7244y537EA==", + "version": "6.7.6", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.7.6.tgz", + "integrity": "sha512-kAz+AncRtKuIknedxT1bq4XwXv4UowhbkHU1myPrtVb/jZtImWuV5BXzv5vK6i3kYACsdiZiQKFQQ5Mq7elW8w==", + "license": "MIT", "dependencies": { "@marijn/find-cluster-break": "^1.0.0" } @@ -541,9 +546,10 @@ } }, "node_modules/@codemirror/view": { - "version": "6.43.11", - "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.11.tgz", - "integrity": "sha512-2+esucbQX6wB2JYi1eDvdCPFTA31BN8oSy6xCmk3G6CloV11yOvEjYk+gH7kLrP0MuHG94E8WDhjs5oMiu3+Wg==", + "version": "6.43.15", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.43.15.tgz", + "integrity": "sha512-HHsfpqFeHyXLs983pSRe38Xajs0vFWZQ2BuX0m7Ki8w3jZ5iD8cuR3lBz2/5/X53Dhf32SBHKh6rtSTB6tKeGw==", + "license": "MIT", "dependencies": { "@codemirror/state": "^6.7.0", "crelt": "^1.0.6", @@ -691,40 +697,6 @@ "node": ">=20.19.0" } }, - "node_modules/@emnapi/core": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.3.tgz", - "integrity": "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg==", - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.3", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime": { - "version": "1.11.3", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.3.tgz", - "integrity": "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==", - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/wasi-threads": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.3.tgz", - "integrity": "sha512-ELEBe8PsLvvJ6QMr0zLt8ffvOHW/dc1m3CEzNMg7aJUv3bMaoDtw2TXyDAwkYBuroxxuHEwhRTLJSe5sya547g==", - "license": "MIT", - "optional": true, - "peer": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, "node_modules/@exodus/bytes": { "version": "1.15.0", "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.15.0.tgz", @@ -765,12 +737,33 @@ "resolved": "https://registry.npmjs.org/@floating-ui/utils/-/utils-0.2.12.tgz", "integrity": "sha512-HpCo8tmWzLVad5s2d19EhAz5zqrrQ6s69qd6moPMQvkOuSwDT1YgRfWSVuc4ennqrgv3OHppiOGMQ7oC13yIww==" }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", - "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", "license": "MIT" }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, "node_modules/@lezer/common": { "version": "1.5.2", "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.2.tgz", @@ -807,9 +800,10 @@ } }, "node_modules/@lezer/highlight": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.3.tgz", - "integrity": "sha512-qXdH7UqTvGfdVBINrgKhDsVTJTxactNNxLk7+UMwZhU13lMHaOBlJe9Vqp907ya56Y3+ed2tlqzys7jDkTmW0g==", + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/@lezer/highlight/-/highlight-1.2.5.tgz", + "integrity": "sha512-O1GMVKgtf5YspFaRzpmqkVgMtIk2HG9uMAbH6wdAIdNh3TVzCsch/+cRi+6l2//UGDKe6NB9BW3cvuR5ezMQ0w==", + "license": "MIT", "dependencies": { "@lezer/common": "^1.3.0" } @@ -1320,9 +1314,9 @@ } }, "node_modules/@napi-rs/canvas": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.0.0.tgz", - "integrity": "sha512-Jqxcy1XOIqj+lH9sl1GT+il6GR3uQv13vI2mrwubP3uT8Olak2ClDrK2RnxlQKjwv8BRr4b3ug0YR7c6hBX8wg==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas/-/canvas-1.0.13.tgz", + "integrity": "sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==", "license": "MIT", "workspaces": [ "e2e/*" @@ -1335,23 +1329,23 @@ "url": "https://github.com/sponsors/Brooooooklyn" }, "optionalDependencies": { - "@napi-rs/canvas-android-arm64": "1.0.0", - "@napi-rs/canvas-darwin-arm64": "1.0.0", - "@napi-rs/canvas-darwin-x64": "1.0.0", - "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.0", - "@napi-rs/canvas-linux-arm64-gnu": "1.0.0", - "@napi-rs/canvas-linux-arm64-musl": "1.0.0", - "@napi-rs/canvas-linux-riscv64-gnu": "1.0.0", - "@napi-rs/canvas-linux-x64-gnu": "1.0.0", - "@napi-rs/canvas-linux-x64-musl": "1.0.0", - "@napi-rs/canvas-win32-arm64-msvc": "1.0.0", - "@napi-rs/canvas-win32-x64-msvc": "1.0.0" + "@napi-rs/canvas-android-arm64": "1.0.13", + "@napi-rs/canvas-darwin-arm64": "1.0.13", + "@napi-rs/canvas-darwin-x64": "1.0.13", + "@napi-rs/canvas-linux-arm-gnueabihf": "1.0.13", + "@napi-rs/canvas-linux-arm64-gnu": "1.0.13", + "@napi-rs/canvas-linux-arm64-musl": "1.0.13", + "@napi-rs/canvas-linux-riscv64-gnu": "1.0.13", + "@napi-rs/canvas-linux-x64-gnu": "1.0.13", + "@napi-rs/canvas-linux-x64-musl": "1.0.13", + "@napi-rs/canvas-win32-arm64-msvc": "1.0.13", + "@napi-rs/canvas-win32-x64-msvc": "1.0.13" } }, "node_modules/@napi-rs/canvas-android-arm64": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.0.0.tgz", - "integrity": "sha512-3hNKJObUK7JsCF9aJlVCs1J0/KE/gGfZNeK8MO1ge6bB3aicr5walGme9t9No1f/oyk9GgvdAT/rjSdsx3gbIw==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-android-arm64/-/canvas-android-arm64-1.0.13.tgz", + "integrity": "sha512-trn7AaDzQ+yeeA0ezhkC7cB1ZDPtp4UYk0EvB5F8qtYL9jEVWtVrU30WOpI52DszoTxaTsCgf5PP4ZVaOlOIHQ==", "cpu": [ "arm64" ], @@ -1369,9 +1363,9 @@ } }, "node_modules/@napi-rs/canvas-darwin-arm64": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.0.0.tgz", - "integrity": "sha512-ZIja19/BiGz2puhki+WUYSRriwFeFJ8Mi9eK3hZdSS85w4Y60cuEAJVhMCfKwswQkKkUtrnzdKMBuO7TupvexA==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-arm64/-/canvas-darwin-arm64-1.0.13.tgz", + "integrity": "sha512-6Y2djEetL8copxfNK6hg7oig/xqTwOchv19hBOm+zBNdKc/02Z3kjZN5wrLzv/l5O04/bAQS6I/AlQpwBlXgPg==", "cpu": [ "arm64" ], @@ -1389,9 +1383,9 @@ } }, "node_modules/@napi-rs/canvas-darwin-x64": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.0.0.tgz", - "integrity": "sha512-hImggWc82jqZVpEsFR9S7PE9OQYjq/H/D7vwCGB6X1jRH+UVBP1+1niJTPBOat1B154T6GKK7/kcFtoWgjgFzQ==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-darwin-x64/-/canvas-darwin-x64-1.0.13.tgz", + "integrity": "sha512-OZoPwwu4TMMg8GTCFBrg8UFExwQTU/55i3uTC/izDat6PHE+ro9dimyQoOboFf91+NY7Pnn70ScR8f8I8+eZXw==", "cpu": [ "x64" ], @@ -1409,9 +1403,9 @@ } }, "node_modules/@napi-rs/canvas-linux-arm-gnueabihf": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.0.0.tgz", - "integrity": "sha512-hlJRy6d+kWLKVOG/+1rEvNQVURZ0DxxRPJsLmEWwhwiXZUJc0BF5o9esALHSEP4CoJK4wChRtj3hnyBgVx2oWA==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm-gnueabihf/-/canvas-linux-arm-gnueabihf-1.0.13.tgz", + "integrity": "sha512-dZSYaKROuswU2eUWG5aBKndNVe68elo1YX93xtRax7q658tj8rYE+HwduovWJgs6qwv1r1/CLR60nDeBbyjvyg==", "cpu": [ "arm" ], @@ -1429,9 +1423,9 @@ } }, "node_modules/@napi-rs/canvas-linux-arm64-gnu": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.0.0.tgz", - "integrity": "sha512-5Hru4T3RXkosRQafcjelv7AUzw9mXqmGYsxnzeDDOWveFCJyEPMSJltvGCM+jfH98seOCbfwm9KyFg6Jm5FhAA==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-gnu/-/canvas-linux-arm64-gnu-1.0.13.tgz", + "integrity": "sha512-W6FzYE8ADHI93In1vi80KBL6btDtAMuj50Ch5ptkWS8xuntyzbR4h5JDUmXoakxZn2yMInksudTEqVSWoFqFGg==", "cpu": [ "arm64" ], @@ -1449,9 +1443,9 @@ } }, "node_modules/@napi-rs/canvas-linux-arm64-musl": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.0.0.tgz", - "integrity": "sha512-LTUl9jS8WsLSUGaxQZKQkxfluOJRpgvBuxxdM4pYcjib+di8AU4OzQc6+L6SzGMLcKc9H0RAjojRatBhTMqYdg==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-arm64-musl/-/canvas-linux-arm64-musl-1.0.13.tgz", + "integrity": "sha512-+6fQ+rR49hkAa4voh2stLIwQ+4t+gmoseM8Bc53/DlMXb73IKymDPWK9A/NtWeqTW4ijWppYuyuxS2hPI8tzNA==", "cpu": [ "arm64" ], @@ -1469,9 +1463,9 @@ } }, "node_modules/@napi-rs/canvas-linux-riscv64-gnu": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.0.0.tgz", - "integrity": "sha512-Iz931SAZf+WVDzpjk52Q3ffW3zw0YflFwEZMgs036Wfu1kX/LrwT9wGjsuSqyduqefUkl91/vTdAjn8hQu5ezA==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-riscv64-gnu/-/canvas-linux-riscv64-gnu-1.0.13.tgz", + "integrity": "sha512-17XEMO3t9RW/TtHtSFf2AkaSWuCWdzbPeidz7zrOFawHxoLSJCnpTI1hN5aUvrZNnkNNmt/vZVJCh0ryUaik3A==", "cpu": [ "riscv64" ], @@ -1489,9 +1483,9 @@ } }, "node_modules/@napi-rs/canvas-linux-x64-gnu": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.0.0.tgz", - "integrity": "sha512-pFEQ5eFK4JusgN1K6KkO9DKP/Hi1WMJOkF8Ch03/khTc4bFbCKkCCsJG4YcOMOW9bI4XbT2/eMAWxhO0xaWgPA==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-gnu/-/canvas-linux-x64-gnu-1.0.13.tgz", + "integrity": "sha512-lc48IwknVHBsNzXn9Xs5OkUsRX38Ml3Z1aOybQ51mMEzZckm8+4A0qROlyYHEoBPzr1kL3IU8ZUAqDb7wtdX8w==", "cpu": [ "x64" ], @@ -1509,9 +1503,9 @@ } }, "node_modules/@napi-rs/canvas-linux-x64-musl": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.0.0.tgz", - "integrity": "sha512-jnvr8NrLHiZ3NCiOKWqDbkI4Ah+QDrqtZ+sddPZBltEb1mQ2coSvCSJYfict+oAwcm0c970oTmVySpjKP/lnaA==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-linux-x64-musl/-/canvas-linux-x64-musl-1.0.13.tgz", + "integrity": "sha512-bGY1r26S2bs8UNFJcPWcCSNdCFbKep5PATsvtgtC9A5u6SRgr2/jJE/RlhHL5m9ZpixNDhVkLY/5h16Kx5V9YA==", "cpu": [ "x64" ], @@ -1529,9 +1523,9 @@ } }, "node_modules/@napi-rs/canvas-win32-arm64-msvc": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.0.0.tgz", - "integrity": "sha512-y2j9/Gfd5joqiqxdP/L1smqjQ+uAx3C4N0EC7bDHrnZEEH8ToM/OC5p3uHvtj4Lq591aHj+ArL01UDLNwT5HgQ==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-arm64-msvc/-/canvas-win32-arm64-msvc-1.0.13.tgz", + "integrity": "sha512-2vRPBZoaIvJrUkDhZTE2Hn0YrnpJRCWVM3EJACoBKjuWI6WgPxGtUoRMsxRviCsyks8bKTSFdyw14CellnG2qA==", "cpu": [ "arm64" ], @@ -1549,9 +1543,9 @@ } }, "node_modules/@napi-rs/canvas-win32-x64-msvc": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.0.0.tgz", - "integrity": "sha512-qwdhh9N6Gge/hC4pL9S1tQp0iKwhSl/dYjg7+RGp9k26iRGRi5MqqUyKGOXIWli0zOcuy5Y2wIH/jk2ry6i/jA==", + "version": "1.0.13", + "resolved": "https://registry.npmjs.org/@napi-rs/canvas-win32-x64-msvc/-/canvas-win32-x64-msvc-1.0.13.tgz", + "integrity": "sha512-DUlW3lZPz63kYsf8mxgyyZuevhlH0T3/BGP9l+NazhB0F1+gL6D4hqZdnhZpw24DlWmTpATDcyYSZlJOi+DdfQ==", "cpu": [ "x64" ], @@ -1568,24 +1562,6 @@ "url": "https://github.com/sponsors/Brooooooklyn" } }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz", - "integrity": "sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==", - "license": "MIT", - "optional": true, - "dependencies": { - "@tybys/wasm-util": "^0.10.2" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "peerDependencies": { - "@emnapi/core": "^1.7.1", - "@emnapi/runtime": "^1.7.1" - } - }, "node_modules/@ocavue/utils": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/@ocavue/utils/-/utils-1.9.0.tgz", @@ -1595,12 +1571,12 @@ } }, "node_modules/@oxc-project/types": { - "version": "0.133.0", - "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.133.0.tgz", - "integrity": "sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==", + "version": "0.155.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.155.0.tgz", + "integrity": "sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==", "license": "MIT", "funding": { - "url": "https://github.com/sponsors/Boshen" + "url": "https://github.com/sponsors/oxc-project" } }, "node_modules/@polka/url": { @@ -1610,10 +1586,26 @@ "dev": true, "license": "MIT" }, + "node_modules/@rolldown/binding-android-arm-eabi": { + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.15.tgz", + "integrity": "sha512-aLcgK9gIJ3YRvrrtfSBbRa27F5WrpiTaPulnFpsHPxpUHgFlSgnU4854MHwoRGEBhfRJDWCS2WQ7lIjskE9Olw==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, "node_modules/@rolldown/binding-android-arm64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz", - "integrity": "sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.15.tgz", + "integrity": "sha512-xD7DdZCrbThKuxNg7ooQmvp07ys4J/pnSEMTG3/OdOWl6daC67m/Q4fL78sRHMxTH/N4fGUbYhcPM0MF5WFHkg==", "cpu": [ "arm64" ], @@ -1627,9 +1619,9 @@ } }, "node_modules/@rolldown/binding-darwin-arm64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.3.tgz", - "integrity": "sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.15.tgz", + "integrity": "sha512-m2WuQ6r0B4OTYxyPpNLtXaMRbRDUbG8YQV2Q3KTdSSK8Th6KHCnC8jVCJt8bvYeSB5WivkkNbc85mKadaSdOxA==", "cpu": [ "arm64" ], @@ -1643,9 +1635,9 @@ } }, "node_modules/@rolldown/binding-darwin-x64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.3.tgz", - "integrity": "sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.15.tgz", + "integrity": "sha512-5RtnsHM36nodM9WbMy+zip0LGS/G+y5wro5RHrpOlr4ac24+1zSi9kiV2MP1myZeZ/ifEHfulQcWjnAXzc2C2A==", "cpu": [ "x64" ], @@ -1659,9 +1651,9 @@ } }, "node_modules/@rolldown/binding-freebsd-x64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.3.tgz", - "integrity": "sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.15.tgz", + "integrity": "sha512-g3l09pyFqhu+135JKkbkwiKGQmwU5hUMUPJ4VdBADvuqR8d33L6H578rh8m7rtxbdp+VmX/+nzI7nvhSZlzpUQ==", "cpu": [ "x64" ], @@ -1675,9 +1667,9 @@ } }, "node_modules/@rolldown/binding-linux-arm-gnueabihf": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.3.tgz", - "integrity": "sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.15.tgz", + "integrity": "sha512-nIe3VugI97nGQtspPxDqA4sXMUpeiocKIP/CqpY/u/vgbT+alX+cVxu1C/oVBPKg4feNTmYovE91v4DgXvXNwQ==", "cpu": [ "arm" ], @@ -1691,9 +1683,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.3.tgz", - "integrity": "sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.15.tgz", + "integrity": "sha512-iTBjXx+B5QSvgI89lJfmqh4wTh8NabR1YZIIN3hNx4zSG0EVfVqkOvLulNpG4251pbd6/IAmZ/LefVk1Y4rPhw==", "cpu": [ "arm64" ], @@ -1707,9 +1699,9 @@ } }, "node_modules/@rolldown/binding-linux-arm64-musl": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.3.tgz", - "integrity": "sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.15.tgz", + "integrity": "sha512-uN26XOnVR7rqQupG3V9oAG2EGGatWjcJHOeDOHUFCh4TBWmP2tHTFoVN13aYbwfm0aHqJAEmcwhAu6sooIjfqQ==", "cpu": [ "arm64" ], @@ -1723,9 +1715,9 @@ } }, "node_modules/@rolldown/binding-linux-ppc64-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.3.tgz", - "integrity": "sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.15.tgz", + "integrity": "sha512-9nWkcdd+H+XhaA3fQIwpHnKIrfx/PQ6rO0pivr78Og07tXlUlctBBJoEYLPfhTmCR/QxEVdn6uPjHV5SymPhdw==", "cpu": [ "ppc64" ], @@ -1739,9 +1731,9 @@ } }, "node_modules/@rolldown/binding-linux-s390x-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.3.tgz", - "integrity": "sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.15.tgz", + "integrity": "sha512-Ggh0ciFjLwIusLSLz7LZYEaGdxOAUJXI+Qu5JCbhPJJHEt8vP+IjRATTJheiJsdzzTYgUiHUiw3X1Ea3ZpMBdA==", "cpu": [ "s390x" ], @@ -1755,9 +1747,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-gnu": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.3.tgz", - "integrity": "sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.15.tgz", + "integrity": "sha512-FHg60rS6DBePAYZ9X9F67x+JObFdmgn6tupA1C/a3B+CufFmTD4mX+e8M75tCiAO3foR/6xwVBI0KQiI7sn/rw==", "cpu": [ "x64" ], @@ -1771,9 +1763,9 @@ } }, "node_modules/@rolldown/binding-linux-x64-musl": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.3.tgz", - "integrity": "sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.15.tgz", + "integrity": "sha512-/cvV/7v5VGz/moiz0XKRj2dE8DzsKyhIu1KpOvJGPjRywg3yscON889UGvAe8zfiJLHup7VLjBduoGWi3HusWQ==", "cpu": [ "x64" ], @@ -1787,9 +1779,9 @@ } }, "node_modules/@rolldown/binding-openharmony-arm64": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.3.tgz", - "integrity": "sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.15.tgz", + "integrity": "sha512-MyzC5Hrv/sm+Z7TSGKP/j8001RO2xQm1zOpCNVL4j0cY/VhBZviludA2YFQ7i4lH6ZAXxQm0lcMdBzM+99mE7w==", "cpu": [ "arm64" ], @@ -1802,59 +1794,10 @@ "node": "^20.19.0 || >=22.12.0" } }, - "node_modules/@rolldown/binding-wasm32-wasi": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.3.tgz", - "integrity": "sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==", - "cpu": [ - "wasm32" - ], - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "1.10.0", - "@emnapi/runtime": "1.10.0", - "@napi-rs/wasm-runtime": "^1.1.4" - }, - "engines": { - "node": "^20.19.0 || >=22.12.0" - } - }, - "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/core": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", - "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.1", - "tslib": "^2.4.0" - } - }, - "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/runtime": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", - "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@rolldown/binding-wasm32-wasi/node_modules/@emnapi/wasi-threads": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", - "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, "node_modules/@rolldown/binding-win32-arm64-msvc": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.3.tgz", - "integrity": "sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.15.tgz", + "integrity": "sha512-+PgYiS+AH5omy6L45ZLxybasauJaj3M8buoT83D+nzPmCayXlxUV9hydhciCKVyIg0B/v0BtXPDE1uGqNwCPpg==", "cpu": [ "arm64" ], @@ -1868,9 +1811,9 @@ } }, "node_modules/@rolldown/binding-win32-x64-msvc": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.3.tgz", - "integrity": "sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.15.tgz", + "integrity": "sha512-HFZd2QNQYn1JbIi+Hpd7H+r/lkWxcfIu28nirZ6eCn2LafuvmExMlb/P96Sfx5tf7pPArw39IdhmCF8vmV+NhQ==", "cpu": [ "x64" ], @@ -1934,52 +1877,35 @@ } }, "node_modules/@rrweb/replay": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@rrweb/replay/-/replay-2.0.0.tgz", - "integrity": "sha512-7sc2y/jz5psKDxdHuLPJjmMm1vvv8P9KaAhSBaWIgT8zn6xkKgPP7KkkB22PzAAyC0RqXmztxj/us6+XHLoHjg==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@rrweb/replay/-/replay-2.2.0.tgz", + "integrity": "sha512-dKug7wlnM2nlIhhHKUjHaz4+1b0duMe6wgo+97eU6CjV0R7yoKvW6NDKlSQQdWx99VMOZMvHTbMbwDQl5CRM1w==", "license": "MIT", "dependencies": { - "@rrweb/types": "^2.0.0", - "rrweb": "^2.0.0" + "@rrweb/types": "^2.2.0", + "rrweb": "^2.2.0" } }, "node_modules/@rrweb/types": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@rrweb/types/-/types-2.0.0.tgz", - "integrity": "sha512-p76i3Bdm/cjb/6NGqmFj0LkGXqC2dXs70AwirgVAsE1ndIa00TJo48La5yobHLsBOk5bfRHy6Yd+9O9VFKhAwQ==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@rrweb/types/-/types-2.2.0.tgz", + "integrity": "sha512-2gTA/pRpIbuET123oSdX5ZUDZfWCOIMYBvpSai3fr5pk9LcbccPqqaXflX+roP4oKenLjNtJPGpFK3BfYeBKnA==", "license": "MIT" }, "node_modules/@rrweb/utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@rrweb/utils/-/utils-2.0.0.tgz", - "integrity": "sha512-0Q9djyxlwG1fs1TxT7VnKtt33tHku6PENlUAKSXZg8QSSI6aUXdCNZkkBt3JAgbBYVrGhQsYrz+DkCdAXqxs1w==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@rrweb/utils/-/utils-2.2.0.tgz", + "integrity": "sha512-e8FEp8wLswqgjDHpQNUUVfEXeDsrRMOVouvqIGKvnPxKYonjLlh0mU3O/17QNvCixFG5eUFR1B2jgTdiLlZxeQ==", "license": "MIT" }, - "node_modules/@standard-schema/spec": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz", - "integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@tybys/wasm-util": { - "version": "0.10.2", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz", - "integrity": "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==", - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, "node_modules/@types/bun": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.4.0.tgz", - "integrity": "sha512-K+lZULY23vRgK/CfTjFIV+tyifaNdSMlPh9j+6mQ/cLfpOznLyAuzgV/JQysyECpkBQLVMSyvjlr2fBUSA9wFQ==", + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/@types/bun/-/bun-1.4.4.tgz", + "integrity": "sha512-9wkRDXUXK124pEnAutE6n/l18j+i9GC5IAHK8TmX/2nlySETmky0OU6yL5U8pW1AoKh++AN9auDCr647BfurjQ==", "dev": true, "license": "MIT", "dependencies": { - "bun-types": "1.4.0" + "bun-types": "1.4.4" } }, "node_modules/@types/chai": { @@ -2047,9 +1973,9 @@ "integrity": "sha512-trgaNyfU+Xh2Tc+ABIb44a5AYUpicB3uwirOioeOkNPPbmgRNtcWyDeeFRzjPZENO9Vq8gvVqfhaaXWLlevVwg==" }, "node_modules/@types/lodash": { - "version": "4.17.24", - "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.24.tgz", - "integrity": "sha512-gIW7lQLZbue7lRSWEFql49QJJWThrTFFeIMJdp3eH4tKoxm1OvEPg02rm4wCCSHS0cL3/Fizimb35b7k8atwsQ==", + "version": "4.17.27", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.27.tgz", + "integrity": "sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew==", "license": "MIT" }, "node_modules/@types/lodash-es": { @@ -2110,63 +2036,397 @@ "@types/node": "*" } }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, "node_modules/@vitest/browser": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/browser/-/browser-4.1.11.tgz", - "integrity": "sha512-bwMovvAeuTFOK5kIFevw4VEf+1gVEICv4SYK4k3knJOxl6b1zEWud8mYKD73e1B0odAn174h1MofURy2TPWf3w==", + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/browser/-/browser-5.0.5.tgz", + "integrity": "sha512-IDMoZX/iZ8rkilw7weaSgN8tJ7iZ9hUv0wYoKXyiyjWjWFwLSWAY707DcVTgxTYOudWC1E3HA9LYn7kVa9a7uQ==", "dev": true, "license": "MIT", "dependencies": { - "@blazediff/core": "1.9.1", - "@vitest/mocker": "4.1.11", - "@vitest/utils": "4.1.11", - "magic-string": "^0.30.21", + "@blazediff/core": "1.10.0", + "@vitest/mocker": "5.0.5", + "@vitest/ui": "5.0.5", + "@vitest/utils": "5.0.5", + "magic-string": "^1.4.3", "pngjs": "^7.0.0", "sirv": "^3.0.2", - "tinyrainbow": "^3.1.0", - "ws": "^8.19.0" + "tinyrainbow": "^3.2.0", + "ws": "^8.22.0" }, "funding": { "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "vitest": "4.1.11" + "vitest": "5.0.5" } }, - "node_modules/@vitest/expect": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz", - "integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==", + "node_modules/@vitest/browser/node_modules/magic-string": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.4.tgz", + "integrity": "sha512-jQz9sVhrZuphH4NrAIHSgkDJCluQO7Ioi4KGRLa7aTUjAODQ13hENX0YIytqYE/rIkO485gQG2LeBxJaW53kkQ==", "dev": true, "license": "MIT", "dependencies": { - "@standard-schema/spec": "^1.1.0", - "@types/chai": "^5.2.2", - "@vitest/spy": "4.1.11", - "@vitest/utils": "4.1.11", - "chai": "^6.2.2", - "tinyrainbow": "^3.1.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" + "@jridgewell/sourcemap-codec": "^1.6.0" } }, "node_modules/@vitest/mocker": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz", - "integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==", + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.5.tgz", + "integrity": "sha512-xLL3lkDegJZw+MGoGaCCsFayDZthGgpAtr3Vziyfc4p7xH89K7KRPcRBBh/kEYm0Aqkt5DtTmkYpBtRV/FrHZg==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/spy": "4.1.11", + "@jridgewell/trace-mapping": "0.3.31", + "@vitest/spy": "5.0.5", "estree-walker": "^3.0.3", - "magic-string": "^0.30.21" + "magic-string": "^1.4.3" }, "funding": { "url": "https://opencollective.com/vitest" }, "peerDependencies": { - "msw": "^2.4.9", + "msw": "^2.4.9 || ^3.0.0", "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" }, "peerDependenciesMeta": { @@ -2188,69 +2448,70 @@ "@types/estree": "^1.0.0" } }, + "node_modules/@vitest/mocker/node_modules/magic-string": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.4.tgz", + "integrity": "sha512-jQz9sVhrZuphH4NrAIHSgkDJCluQO7Ioi4KGRLa7aTUjAODQ13hENX0YIytqYE/rIkO485gQG2LeBxJaW53kkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, "node_modules/@vitest/pretty-format": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz", - "integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==", + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-5.0.5.tgz", + "integrity": "sha512-24sSdIlMA9DVPXnYiB9siwU0bTd887Y9jX3+vabztCSsvHwo7ipvJ/a2L3Rljw8+2rK1f5fCj3h5U9I/Jsqgbw==", "dev": true, "license": "MIT", "dependencies": { - "tinyrainbow": "^3.1.0" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/runner": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz", - "integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/utils": "4.1.11", - "pathe": "^2.0.3" - }, - "funding": { - "url": "https://opencollective.com/vitest" - } - }, - "node_modules/@vitest/snapshot": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz", - "integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==", - "dev": true, - "license": "MIT", - "dependencies": { - "@vitest/pretty-format": "4.1.11", - "@vitest/utils": "4.1.11", - "magic-string": "^0.30.21", - "pathe": "^2.0.3" + "tinyrainbow": "^3.2.0" }, "funding": { "url": "https://opencollective.com/vitest" } }, "node_modules/@vitest/spy": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz", - "integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==", + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.5.tgz", + "integrity": "sha512-lwJRExuH417257Q5wv9QYugN9IMJkoxcrKrYxGPQkBzl7wlNpTUxD/5yNX4ESKVUIShKPgkGchYPFMWOOk0wzw==", "dev": true, "license": "MIT", "funding": { "url": "https://opencollective.com/vitest" } }, - "node_modules/@vitest/utils": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz", - "integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==", + "node_modules/@vitest/ui": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/ui/-/ui-5.0.5.tgz", + "integrity": "sha512-dCoGUOdgmCaSB2g+WQ/spPCBkytAWdNUkFSXY4z+eYp2d8JEOY8v0uDRaJTG9qf/kTlTVZ4CuYMYMz/f1HS/qQ==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/pretty-format": "4.1.11", + "@vitest/utils": "5.0.5", + "fflate": "^0.8.3", + "flatted": "^3.4.4", + "pathe": "^2.0.3", + "sirv": "^3.0.2", + "tinyrainbow": "^3.2.0" + }, + "funding": { + "url": "https://opencollective.com/vitest" + }, + "peerDependencies": { + "vitest": "5.0.5" + } + }, + "node_modules/@vitest/utils": { + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-5.0.5.tgz", + "integrity": "sha512-/rBu7gzLDQI/SC79Tn98b5DwOgaHU/Gt4I9OVeP3YofzNaYtbImRCOJQmT1S6vOJg9gEIlWC+r3QxKkjuSa1nQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@vitest/pretty-format": "5.0.5", "convert-source-map": "^2.0.0", - "tinyrainbow": "^3.1.0" + "tinyrainbow": "^3.2.0" }, "funding": { "url": "https://opencollective.com/vitest" @@ -2668,13 +2929,14 @@ "dev": true }, "node_modules/bun-types": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.4.0.tgz", - "integrity": "sha512-iIKw23BspnQQYd3prITOBxeUsxBHnwzX6YJfGMuNOZzeNcMmVqzIIVGRm1l69ogaPQmb4wB6BN8mA5bE9YuC5Q==", + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.4.4.tgz", + "integrity": "sha512-yjrJh5oGX7mMPKGd19YXyIjmEuj4G4zNC30bs7PM9Az7NQ3ndF3j6hbeRdvJTRQEhJ/FYQwW0a2moweEi2hMxQ==", "dev": true, "license": "MIT", "dependencies": { - "@types/node": "*" + "@types/node": "*", + "undici-types": "*" } }, "node_modules/call-bind": { @@ -2734,9 +2996,9 @@ } }, "node_modules/chai": { - "version": "6.2.2", - "resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz", - "integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==", + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz", + "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==", "dev": true, "license": "MIT", "engines": { @@ -2950,9 +3212,9 @@ } }, "node_modules/date-fns": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.3.0.tgz", - "integrity": "sha512-OYcL+3N/jyWbYdFGqoMAhytDgxP9pbYPUUiRCOgn4Fewaadk9l/Wam4Avciiyp2BgkpfQyBV9B+ehnVJych+eQ==", + "version": "4.4.0", + "resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.4.0.tgz", + "integrity": "sha512-+1UMbeh68lH1SegH83CGWwpb6OHHbpSgr3+s5Eww5M4CAgswBpoWS0AjTOfEJ33HiYKz1hdj/KTFprzXHmq/6w==", "license": "MIT", "funding": { "type": "github", @@ -3196,9 +3458,9 @@ } }, "node_modules/es-module-lexer": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.1.0.tgz", - "integrity": "sha512-n27zTYMjYu1aj4MjCWzSP7G9r75utsaoc8m61weK+W8JMBGGQybd43GstCXZ3WNmSFtGT9wi59qQTW6mhTR5LQ==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", "dev": true, "license": "MIT" }, @@ -3314,9 +3576,9 @@ } }, "node_modules/expect-type": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz", - "integrity": "sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz", + "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==", "dev": true, "license": "Apache-2.0", "engines": { @@ -3345,6 +3607,13 @@ } } }, + "node_modules/fflate": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz", + "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==", + "dev": true, + "license": "MIT" + }, "node_modules/find-up": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", @@ -3361,6 +3630,13 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/flatted": { + "version": "3.4.4", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.4.tgz", + "integrity": "sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q==", + "dev": true, + "license": "ISC" + }, "node_modules/for-each": { "version": "0.3.5", "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", @@ -3448,9 +3724,9 @@ } }, "node_modules/happy-dom": { - "version": "20.14.0", - "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-20.14.0.tgz", - "integrity": "sha512-4bRh1KzRvKDnFNTlLhzT1RZTpkKhQbQDl9j+7GXszWsvuspYdo29k6OHRf4PwiM6oLb8r/pMWeYiJjkfod5AvQ==", + "version": "21.0.4", + "resolved": "https://registry.npmjs.org/happy-dom/-/happy-dom-21.0.4.tgz", + "integrity": "sha512-tFm+GaLBgo6o0awHnvHaNoraVo27qJ+2tZEtZ+cIa08hXbeitrxAJajLI05hsUy/2/YTKcUjQYzHe5mCcraLBw==", "dev": true, "license": "MIT", "dependencies": { @@ -3851,9 +4127,9 @@ } }, "node_modules/lightningcss": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", - "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "license": "MPL-2.0", "dependencies": { "detect-libc": "^2.0.3" @@ -3866,23 +4142,23 @@ "url": "https://opencollective.com/parcel" }, "optionalDependencies": { - "lightningcss-android-arm64": "1.32.0", - "lightningcss-darwin-arm64": "1.32.0", - "lightningcss-darwin-x64": "1.32.0", - "lightningcss-freebsd-x64": "1.32.0", - "lightningcss-linux-arm-gnueabihf": "1.32.0", - "lightningcss-linux-arm64-gnu": "1.32.0", - "lightningcss-linux-arm64-musl": "1.32.0", - "lightningcss-linux-x64-gnu": "1.32.0", - "lightningcss-linux-x64-musl": "1.32.0", - "lightningcss-win32-arm64-msvc": "1.32.0", - "lightningcss-win32-x64-msvc": "1.32.0" + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" } }, "node_modules/lightningcss-android-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", - "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", "cpu": [ "arm64" ], @@ -3900,9 +4176,9 @@ } }, "node_modules/lightningcss-darwin-arm64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", - "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", "cpu": [ "arm64" ], @@ -3920,9 +4196,9 @@ } }, "node_modules/lightningcss-darwin-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", - "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", "cpu": [ "x64" ], @@ -3940,9 +4216,9 @@ } }, "node_modules/lightningcss-freebsd-x64": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", - "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", "cpu": [ "x64" ], @@ -3960,9 +4236,9 @@ } }, "node_modules/lightningcss-linux-arm-gnueabihf": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", - "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", "cpu": [ "arm" ], @@ -3980,9 +4256,9 @@ } }, "node_modules/lightningcss-linux-arm64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", - "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", "cpu": [ "arm64" ], @@ -4000,9 +4276,9 @@ } }, "node_modules/lightningcss-linux-arm64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", - "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", "cpu": [ "arm64" ], @@ -4020,9 +4296,9 @@ } }, "node_modules/lightningcss-linux-x64-gnu": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", - "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", "cpu": [ "x64" ], @@ -4040,9 +4316,9 @@ } }, "node_modules/lightningcss-linux-x64-musl": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", - "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", "cpu": [ "x64" ], @@ -4060,9 +4336,9 @@ } }, "node_modules/lightningcss-win32-arm64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", - "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", "cpu": [ "arm64" ], @@ -4080,9 +4356,9 @@ } }, "node_modules/lightningcss-win32-x64-msvc": { - "version": "1.32.0", - "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", - "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", "cpu": [ "x64" ], @@ -5076,12 +5352,12 @@ "license": "MIT" }, "node_modules/monaco-editor": { - "version": "0.55.1", - "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.55.1.tgz", - "integrity": "sha512-jz4x+TJNFHwHtwuV9vA9rMujcZRb0CEilTEwG2rRSpe/A7Jdkuj8xPKttCgOh+v/lkHy7HsZ64oj+q3xoAFl9A==", + "version": "0.57.0", + "resolved": "https://registry.npmjs.org/monaco-editor/-/monaco-editor-0.57.0.tgz", + "integrity": "sha512-5BkI9KGoqrNvBGUe15/QlZq3OooZ8WLg1AxTpaqHRCP3HNpzPPZKE2EDz8M7c+VRmCeUw1Brp4cx/PWm3kI/5A==", "license": "MIT", "dependencies": { - "dompurify": "3.2.7", + "dompurify": "3.4.15", "marked": "14.0.0" } }, @@ -5223,15 +5499,18 @@ } }, "node_modules/obug": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/obug/-/obug-2.1.1.tgz", - "integrity": "sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/obug/-/obug-3.0.0.tgz", + "integrity": "sha512-5vvB5+W7ePv+p3uqxi+RcW1XAzLW0/hxt3/4X4Lc4qHudzOhmBiBwOY6DRob4WnanAEGvNcLjF+KNOufrUoEQw==", "dev": true, "funding": [ "https://github.com/sponsors/sxzz", "https://opencollective.com/debug" ], - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=12.20.0" + } }, "node_modules/orderedmap": { "version": "2.1.1", @@ -5362,9 +5641,9 @@ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" }, "node_modules/picomatch": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", - "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", "license": "MIT", "engines": { "node": ">=12" @@ -5898,12 +6177,12 @@ "license": "MIT" }, "node_modules/rolldown": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.3.tgz", - "integrity": "sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==", + "version": "1.2.15", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.15.tgz", + "integrity": "sha512-6odND+fel5zVw3I4Yc2e69gvguDnX0CAAGiNDZSq4ik5WUcaLrkD2GLuog0XcODbor31hZ5ayEMgVDno+KPV5g==", "license": "MIT", "dependencies": { - "@oxc-project/types": "=0.133.0", + "@oxc-project/types": "=0.155.0", "@rolldown/pluginutils": "^1.0.0" }, "bin": { @@ -5913,21 +6192,21 @@ "node": "^20.19.0 || >=22.12.0" }, "optionalDependencies": { - "@rolldown/binding-android-arm64": "1.0.3", - "@rolldown/binding-darwin-arm64": "1.0.3", - "@rolldown/binding-darwin-x64": "1.0.3", - "@rolldown/binding-freebsd-x64": "1.0.3", - "@rolldown/binding-linux-arm-gnueabihf": "1.0.3", - "@rolldown/binding-linux-arm64-gnu": "1.0.3", - "@rolldown/binding-linux-arm64-musl": "1.0.3", - "@rolldown/binding-linux-ppc64-gnu": "1.0.3", - "@rolldown/binding-linux-s390x-gnu": "1.0.3", - "@rolldown/binding-linux-x64-gnu": "1.0.3", - "@rolldown/binding-linux-x64-musl": "1.0.3", - "@rolldown/binding-openharmony-arm64": "1.0.3", - "@rolldown/binding-wasm32-wasi": "1.0.3", - "@rolldown/binding-win32-arm64-msvc": "1.0.3", - "@rolldown/binding-win32-x64-msvc": "1.0.3" + "@rolldown/binding-android-arm-eabi": "1.2.15", + "@rolldown/binding-android-arm64": "1.2.15", + "@rolldown/binding-darwin-arm64": "1.2.15", + "@rolldown/binding-darwin-x64": "1.2.15", + "@rolldown/binding-freebsd-x64": "1.2.15", + "@rolldown/binding-linux-arm-gnueabihf": "1.2.15", + "@rolldown/binding-linux-arm64-gnu": "1.2.15", + "@rolldown/binding-linux-arm64-musl": "1.2.15", + "@rolldown/binding-linux-ppc64-gnu": "1.2.15", + "@rolldown/binding-linux-s390x-gnu": "1.2.15", + "@rolldown/binding-linux-x64-gnu": "1.2.15", + "@rolldown/binding-linux-x64-musl": "1.2.15", + "@rolldown/binding-openharmony-arm64": "1.2.15", + "@rolldown/binding-win32-arm64-msvc": "1.2.15", + "@rolldown/binding-win32-x64-msvc": "1.2.15" } }, "node_modules/rope-sequence": { @@ -5936,34 +6215,34 @@ "integrity": "sha512-UT5EDe2cu2E/6O4igUr5PSFs23nvvukicWHx6GnOPlHAiiYbzNuCRQCuiUdHJQcqKalLKlrYJnjY0ySGsXNQXQ==" }, "node_modules/rrdom": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/rrdom/-/rrdom-2.0.0.tgz", - "integrity": "sha512-Yv+T/IBngNEjhbRv6yJzKdbhgMOiRCV+UA3R0HOpx4yySc8vl4I11Xr5BxCYrnt00l7CGjHbFB9VULEvcg1u6w==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/rrdom/-/rrdom-2.2.0.tgz", + "integrity": "sha512-gxcBJWVtS/Xz+Ys8xcjPoWqr+C7wz/MS8NgmKw136I47Xygy17FYOGZqoGwEyvBn724jRDK1ljS+8w9FsZStOg==", "license": "MIT", "dependencies": { - "rrweb-snapshot": "^2.0.0" + "rrweb-snapshot": "^2.2.0" } }, "node_modules/rrweb": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/rrweb/-/rrweb-2.0.0.tgz", - "integrity": "sha512-ID7NE8OdfAbxZKlTPc/EdL/8sLhTOVB1aZKoQ/M0peKGYB7dIDj0hsdJo+OVXfpiYMTtGzXnKfnMVUj4LnsrhQ==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/rrweb/-/rrweb-2.2.0.tgz", + "integrity": "sha512-ofVzPq11/yIQ7WhVb++rJGI2LoPPrxdqu0QAvRA4KGeXJ7LH52jQ0VlRH4+VXn5PA/7pz85/rRkQyBUqT1LraQ==", "license": "MIT", "dependencies": { - "@rrweb/types": "^2.0.0", - "@rrweb/utils": "^2.0.0", + "@rrweb/types": "^2.2.0", + "@rrweb/utils": "^2.2.0", "@types/css-font-loading-module": "0.0.7", "@xstate/fsm": "^1.4.0", "base64-arraybuffer": "^1.0.1", "mitt": "^3.0.0", - "rrdom": "^2.0.0", - "rrweb-snapshot": "^2.0.0" + "rrdom": "^2.2.0", + "rrweb-snapshot": "^2.2.0" } }, "node_modules/rrweb-snapshot": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/rrweb-snapshot/-/rrweb-snapshot-2.0.0.tgz", - "integrity": "sha512-mDYvvHVXYUD6wZj2AGz5UuupnYnhrWUmF+Hm+haZtVPx8bK3hpAMpu7YjPAoHVluv6KZJNJvVb/6HeBKwXTAvA==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/rrweb-snapshot/-/rrweb-snapshot-2.2.0.tgz", + "integrity": "sha512-Tg/PiCLy+zV9C0Jfb4IAGABtt5l/UOvwW5xjFk41ZQhBfUjeqPP1rZ9HMDrFPc7cawCUEenWw54+g/4vluO5lg==", "license": "MIT", "dependencies": { "postcss": "^8.4.38" @@ -6134,12 +6413,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/siginfo": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz", - "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==", - "dev": true - }, "node_modules/sirv": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/sirv/-/sirv-3.0.2.tgz", @@ -6173,12 +6446,6 @@ "node": ">=0.10.0" } }, - "node_modules/stackback": { - "version": "0.0.2", - "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", - "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==", - "dev": true - }, "node_modules/static-eval": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/static-eval/-/static-eval-2.1.1.tgz", @@ -6189,9 +6456,9 @@ } }, "node_modules/std-env": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.1.0.tgz", - "integrity": "sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==", + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz", + "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==", "dev": true, "license": "MIT" }, @@ -6262,15 +6529,19 @@ } }, "node_modules/tinybench": { - "version": "2.9.0", - "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", - "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==", - "dev": true + "version": "6.2.2", + "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.2.tgz", + "integrity": "sha512-nIZ2N2dFpjBsg2hgitKu7mA+FvsIJuGJOwysRngmVRRmWgR/UyPjwJj8c/fT/dhm8EkHnF5EOogRf+0Z2qrimA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20.0.0" + } }, "node_modules/tinyexec": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.0.2.tgz", - "integrity": "sha512-W/KYk+NFhkmsYpuHq5JykngiOCnxeVL8v8dFnqxSD8qEEdRfXk1SDM6JzNqcERbcGYj9tMrDQBYV9cjgnunFIg==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz", + "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==", "dev": true, "license": "MIT", "engines": { @@ -6294,9 +6565,9 @@ } }, "node_modules/tinyrainbow": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.0.tgz", - "integrity": "sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==", + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.2.0.tgz", + "integrity": "sha512-LgO3D9yZJjApUiuUfl9iFAwrtaX4+lok3wJIqttGoKCHlWUqHqbQpnxCf82L8FjgKsh4iGo78hqJwgL8F6To2A==", "dev": true, "license": "MIT", "engines": { @@ -6427,17 +6698,38 @@ } }, "node_modules/typescript": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", - "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", "devOptional": true, "license": "Apache-2.0", "bin": { - "tsc": "bin/tsc", - "tsserver": "bin/tsserver" + "tsc": "bin/tsc" }, "engines": { - "node": ">=14.17" + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" } }, "node_modules/underscore": { @@ -6447,9 +6739,9 @@ "license": "MIT" }, "node_modules/undici": { - "version": "7.25.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.25.0.tgz", - "integrity": "sha512-xXnp4kTyor2Zq+J1FfPI6Eq3ew5h6Vl0F/8d9XU5zZQf1tX9s2Su1/3PiMmUANFULpmksxkClamIZcaUqryHsQ==", + "version": "7.30.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.1.tgz", + "integrity": "sha512-03KrMbjIFDWQR5RNPrSw3bd1r12JpyFQl9/yxjUbJtqkjmllqC5lFjZh6ujeuJCKr8EOQvRW872Oy/az+nLYxg==", "dev": true, "license": "MIT", "engines": { @@ -6604,15 +6896,15 @@ } }, "node_modules/vite": { - "version": "8.0.16", - "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.16.tgz", - "integrity": "sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==", + "version": "8.3.5", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.5.tgz", + "integrity": "sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==", "license": "MIT", "dependencies": { - "lightningcss": "^1.32.0", - "picomatch": "^4.0.4", - "postcss": "^8.5.15", - "rolldown": "1.0.3", + "lightningcss": "^1.33.0", + "picomatch": "^4.0.7", + "postcss": "^8.5.30", + "rolldown": "~1.2.14", "tinyglobby": "^0.2.17" }, "bin": { @@ -6629,7 +6921,7 @@ }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", - "@vitejs/devtools": "^0.1.18", + "@vitejs/devtools": "^0.7.1 || ^0.8.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", @@ -6707,38 +6999,31 @@ } }, "node_modules/vitest": { - "version": "4.1.11", - "resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz", - "integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==", + "version": "5.0.5", + "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.5.tgz", + "integrity": "sha512-cPODOMF8YnkiiYtDdHo6n4wWmBrOBBbOIYH2d33M4l3CdNn72h+qMmO6uXffUN6A5AZFXNND/d+krS9mgkXRfg==", "dev": true, "license": "MIT", "dependencies": { - "@vitest/expect": "4.1.11", - "@vitest/mocker": "4.1.11", - "@vitest/pretty-format": "4.1.11", - "@vitest/runner": "4.1.11", - "@vitest/snapshot": "4.1.11", - "@vitest/spy": "4.1.11", - "@vitest/utils": "4.1.11", - "es-module-lexer": "^2.0.0", - "expect-type": "^1.3.0", - "magic-string": "^0.30.21", - "obug": "^2.1.1", - "pathe": "^2.0.3", - "picomatch": "^4.0.3", - "std-env": "^4.0.0-rc.1", - "tinybench": "^2.9.0", - "tinyexec": "^1.0.2", - "tinyglobby": "^0.2.15", - "tinyrainbow": "^3.1.0", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0", - "why-is-node-running": "^2.3.0" + "@types/chai": "^5.2.2", + "@vitest/mocker": "5.0.5", + "chai": "^6.3.0", + "es-module-lexer": "^2.3.2", + "expect-type": "^1.4.0", + "magic-string": "^1.4.3", + "obug": "^3.0.0", + "picomatch": "^4.0.7", + "std-env": "^4.3.0", + "tinybench": "^6.2.2", + "tinyexec": "^1.3.1", + "tinyglobby": "^0.2.17", + "why-is-node-running": "3.2.1" }, "bin": { "vitest": "vitest.mjs" }, "engines": { - "node": "^20.0.0 || ^22.0.0 || >=24.0.0" + "node": "^22.12.0 || ^24.0.0 || >=26.0.0" }, "funding": { "url": "https://opencollective.com/vitest" @@ -6746,16 +7031,16 @@ "peerDependencies": { "@edge-runtime/vm": "*", "@opentelemetry/api": "^1.9.0", - "@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0", - "@vitest/browser-playwright": "4.1.11", - "@vitest/browser-preview": "4.1.11", - "@vitest/browser-webdriverio": "4.1.11", - "@vitest/coverage-istanbul": "4.1.11", - "@vitest/coverage-v8": "4.1.11", - "@vitest/ui": "4.1.11", + "@types/node": "^22.0.0 || >=24.0.0", + "@vitest/browser-playwright": "5.0.5", + "@vitest/browser-preview": "5.0.5", + "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0", + "@vitest/coverage-istanbul": "5.0.5", + "@vitest/coverage-v8": "5.0.5", + "@vitest/ui": "5.0.5", "happy-dom": "*", "jsdom": "*", - "vite": "^6.0.0 || ^7.0.0 || ^8.0.0" + "vite": "^6.4.0 || ^7.0.0 || ^8.0.0" }, "peerDependenciesMeta": { "@edge-runtime/vm": { @@ -6797,9 +7082,9 @@ } }, "node_modules/vitest-canvas-mock": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/vitest-canvas-mock/-/vitest-canvas-mock-1.1.5.tgz", - "integrity": "sha512-PWtzolkO/GsG9I9qsLxJ8HzdXQKNz1iRVUcCDJbNBiDuxMp50NC1MWwz2UmDYS4vJqNeKyoLWm7RgjfKWIoQOQ==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/vitest-canvas-mock/-/vitest-canvas-mock-1.2.0.tgz", + "integrity": "sha512-gTy8+dL7aDFZq2EOGCk5krSVsvszTW/M+58efNzybehZNakON2HiPfi3bDBAp85L8DL+D+f/cNtQ5N60rZEL7A==", "dev": true, "license": "MIT", "dependencies": { @@ -6807,7 +7092,17 @@ "moo-color": "^1.0.3" }, "peerDependencies": { - "vitest": "^3.0.0 || ^4.0.0" + "vitest": "^3.0.0 || ^4.0.0 || ^5.0.0" + } + }, + "node_modules/vitest/node_modules/magic-string": { + "version": "1.4.4", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.4.tgz", + "integrity": "sha512-jQz9sVhrZuphH4NrAIHSgkDJCluQO7Ioi4KGRLa7aTUjAODQ13hENX0YIytqYE/rIkO485gQG2LeBxJaW53kkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" } }, "node_modules/vm-browserify": { @@ -6910,25 +7205,22 @@ } }, "node_modules/why-is-node-running": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz", - "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==", + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz", + "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==", "dev": true, - "dependencies": { - "siginfo": "^2.0.0", - "stackback": "0.0.2" - }, + "license": "MIT", "bin": { "why-is-node-running": "cli.js" }, "engines": { - "node": ">=8" + "node": ">=20.11" } }, "node_modules/ws": { - "version": "8.21.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", - "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", + "version": "8.22.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.0.tgz", + "integrity": "sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==", "dev": true, "license": "MIT", "engines": { diff --git a/web-components/package.json b/web-components/package.json index 6a8161c0d..3580fe252 100644 --- a/web-components/package.json +++ b/web-components/package.json @@ -22,46 +22,46 @@ "author": "", "license": "ISC", "dependencies": { - "@codemirror/autocomplete": "^6.20.3", - "@codemirror/commands": "^6.11.0", + "@codemirror/autocomplete": "^6.20.4", + "@codemirror/commands": "^6.11.1", "@codemirror/lang-sql": "^6.10.0", - "@codemirror/language": "^6.12.4", + "@codemirror/language": "^6.13.1", "@codemirror/lint": "^6.9.7", - "@codemirror/state": "^6.7.4", - "@codemirror/view": "^6.43.11", - "@lezer/highlight": "^1.2.3", + "@codemirror/state": "^6.7.6", + "@codemirror/view": "^6.43.15", + "@lezer/highlight": "^1.2.5", "@lit-labs/virtualizer": "^2.1.1", "@milkdown/crepe": "7.22.3", "@milkdown/kit": "7.22.3", - "@napi-rs/canvas": "^1.0.0", - "@rrweb/replay": "^2.0.0", + "@napi-rs/canvas": "^1.0.13", + "@rrweb/replay": "^2.1.7", "@rrweb/types": "^2.0.0-alpha.18", - "@types/lodash": "^4.17.24", + "@types/lodash": "^4.17.27", "ansi-up": "^1.0.0", "clsx": "^2.1.1", - "date-fns": "^4.3.0", + "date-fns": "^4.4.0", "echarts": "^6.1.0", "elkjs": "^0.12.0", "js-yaml": "^4.3.2", "jsonpath": "^1.3.0", "lit": "^3.3.3", "lodash": "^4.17.23", - "monaco-editor": "^0.55.1", - "vite": "^8.0.16" + "monaco-editor": "^0.57.0", + "vite": "^8.3.5" }, "devDependencies": { - "@types/bun": "^1.4.0", + "@types/bun": "^1.4.4", "@types/js-yaml": "^4.0.9", "@types/jsonpath": "^0.2.4", "@types/node": "^25.9.1", - "@vitest/browser": "^4.1.11", - "happy-dom": "^20.14.0", + "@vitest/browser": "^5.0.5", + "happy-dom": "^21.0.4", "jsdom": "^29.1.1", - "typescript": "^6.0.3", + "typescript": "^7.0.2", "vite-plugin-monaco-editor": "^1.1.0", "vite-plugin-node-polyfills": "^0.28.0", - "vitest": "^4.1.11", - "vitest-canvas-mock": "^1.1.5" + "vitest": "^5.0.5", + "vitest-canvas-mock": "^1.2.0" }, "overrides": { "dompurify": "^3.3.2", diff --git a/web-components/src/monaco-yaml.d.ts b/web-components/src/monaco-yaml.d.ts index 2877b1774..4ade32d7e 100644 --- a/web-components/src/monaco-yaml.d.ts +++ b/web-components/src/monaco-yaml.d.ts @@ -1,4 +1,4 @@ -declare module 'monaco-editor/esm/vs/basic-languages/yaml/yaml.js' { +declare module 'monaco-editor/languages/definitions/yaml/yaml.js' { export const conf: unknown; export const language: unknown; } diff --git a/web-components/src/types/types.ts b/web-components/src/types/types.ts index e5334007a..70ea706f4 100644 --- a/web-components/src/types/types.ts +++ b/web-components/src/types/types.ts @@ -49,7 +49,7 @@ declare global { getAttributes: (tagData: TagifyTagData) => string; }; - var monaco: typeof import('monaco-editor/esm/vs/editor/editor.api.js'); + var monaco: typeof import('monaco-editor/editor/editor.api.js'); function updateUrlState(key: string | string[], value: string, action?: 'set' | 'delete'): void; } diff --git a/web-components/src/yaml-editor.ts b/web-components/src/yaml-editor.ts index b49f29874..e416a1672 100644 --- a/web-components/src/yaml-editor.ts +++ b/web-components/src/yaml-editor.ts @@ -1,9 +1,9 @@ import { LitElement, html } from 'lit'; import { customElement, query } from 'lit/decorators.js'; import type * as Monaco from 'monaco-editor'; -import * as monacoInstance from 'monaco-editor/esm/vs/editor/editor.api.js'; -import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker'; -import { conf, language } from 'monaco-editor/esm/vs/basic-languages/yaml/yaml.js'; +import * as monacoInstance from 'monaco-editor/editor/editor.api.js'; +import EditorWorker from 'monaco-editor/editor/editor.worker.js?worker'; +import { conf, language } from 'monaco-editor/languages/definitions/yaml/yaml.js'; (self as any).MonacoEnvironment ||= { getWorker: () => new EditorWorker() }; monacoInstance.languages.register({ id: 'yaml' }); monacoInstance.languages.setMonarchTokensProvider('yaml', language as Monaco.languages.IMonarchLanguage); diff --git a/web-components/vite.config.mjs b/web-components/vite.config.mjs index 55c650bc9..5a562a211 100644 --- a/web-components/vite.config.mjs +++ b/web-components/vite.config.mjs @@ -1,9 +1,5 @@ import { defineConfig } from 'vite'; import { nodePolyfills } from 'vite-plugin-node-polyfills'; -import { resolve } from 'path'; -import { fileURLToPath } from 'url'; - -const __dirname = fileURLToPath(new URL('.', import.meta.url)); export default defineConfig(({ mode }) => ({ base: '/public/assets/web-components/dist/', @@ -22,16 +18,9 @@ export default defineConfig(({ mode }) => ({ plugins: [ nodePolyfills({ overrides: { fs: null } }), // for @kusto/language-service ], - resolve: { - alias: [ - // Fix the monaco-editor alias to properly resolve imports - { find: 'monaco-editor', replacement: resolve(__dirname, 'node_modules/monaco-editor') }, - { find: /^monaco-editor\/esm\/vs\/(.*)/, replacement: resolve(__dirname, 'node_modules/monaco-editor/esm/vs/$1') }, - ], - }, optimizeDeps: { include: ['monaco-editor', 'xregexp'], - exclude: ['monaco-editor/esm/vs/editor/editor.worker'], + exclude: ['monaco-editor/editor/editor.worker.js'], }, build: { target: 'esnext', From 8306eace25e7f9ee26fb193e0a611b9062e67350 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:12:28 +0100 Subject: [PATCH 016/203] chore(deps): bump serialize-javascript from 7.0.5 to 7.1.4 (#731) Bumps [serialize-javascript](https://github.com/yahoo/serialize-javascript) from 7.0.5 to 7.1.4. - [Release notes](https://github.com/yahoo/serialize-javascript/releases) - [Commits](https://github.com/yahoo/serialize-javascript/compare/v7.0.5...v7.1.4) --- updated-dependencies: - dependency-name: serialize-javascript dependency-version: 7.1.4 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- package-lock.json | 6 +++--- package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 348b62045..40a7d5d07 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11894,9 +11894,9 @@ } }, "node_modules/serialize-javascript": { - "version": "7.0.5", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.0.5.tgz", - "integrity": "sha512-F4LcB0UqUl1zErq+1nYEEzSHJnIwb3AF2XWB94b+afhrekOUijwooAYqFyRbjYkm2PAKBabx6oYv/xDxNi8IBw==", + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.4.tgz", + "integrity": "sha512-FqlEuoTq/zRmA4Lg6aOqyH3lCHbUtCB0bmHCeFniX2GBdDqMJM3FwdvEhlE5Pim1dlt2FfBdVPmUNNiGhhKqpw==", "dev": true, "license": "BSD-3-Clause", "engines": { diff --git a/package.json b/package.json index 7ae5adffb..c86d80ed9 100644 --- a/package.json +++ b/package.json @@ -20,7 +20,7 @@ "test:gridstack-parity": "playwright test test/browser/dashboard-grid-parity.spec.js --reporter=line" }, "overrides": { - "serialize-javascript": "^7.0.5", + "serialize-javascript": "^7.1.4", "tmp": "^0.2.4" } } From 4a8e70cff59bf911f4663d61f2dc62e9fb81ab10 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 26 Oct 2026 13:13:13 +0100 Subject: [PATCH 017/203] chore(deps): bump github.com/klauspost/compress (#735) Bumps [github.com/klauspost/compress](https://github.com/klauspost/compress) from 1.17.11 to 1.18.7. - [Release notes](https://github.com/klauspost/compress/releases) - [Commits](https://github.com/klauspost/compress/compare/v1.17.11...v1.18.7) --- updated-dependencies: - dependency-name: github.com/klauspost/compress dependency-version: 1.18.7 dependency-type: indirect ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- scripts/local/dlq-redrive/go.mod | 2 +- scripts/local/dlq-redrive/go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/scripts/local/dlq-redrive/go.mod b/scripts/local/dlq-redrive/go.mod index fa1320efd..e33e6a5c7 100644 --- a/scripts/local/dlq-redrive/go.mod +++ b/scripts/local/dlq-redrive/go.mod @@ -8,7 +8,7 @@ require ( ) require ( - github.com/klauspost/compress v1.17.11 // indirect + github.com/klauspost/compress v1.18.7 // indirect github.com/pierrec/lz4/v4 v4.1.21 // indirect github.com/twmb/franz-go/pkg/kmsg v1.9.0 // indirect golang.org/x/crypto v0.52.0 // indirect diff --git a/scripts/local/dlq-redrive/go.sum b/scripts/local/dlq-redrive/go.sum index 3643ee32f..0a77d0046 100644 --- a/scripts/local/dlq-redrive/go.sum +++ b/scripts/local/dlq-redrive/go.sum @@ -1,5 +1,5 @@ -github.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc= -github.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0= +github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw= +github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ= github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= github.com/twmb/franz-go v1.18.0 h1:25FjMZfdozBywVX+5xrWC2W+W76i0xykKjTdEeD2ejw= From b09f00330275a58064b844147a62b1926d7fe104 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Mon, 26 Oct 2026 14:25:22 +0100 Subject: [PATCH 018/203] Share Explorer facets and infrastructure table controls (#720) * Share Explorer facets and infrastructure table controls * Verify shared controls across namespaces and responsive layouts * Remove orphaned time inputs and await browser state * Classify facet content exhaustively * Consolidate inventory defaults and overlapping regression scenarios * Share Clear all across facet rails and demote facet glue to CSS Clear all lives in the shared rail for both Explorer and inventories and only shows while a facet is ticked. Column choices restore without a sync event, filter inputs skip re-filtering swaps while empty, and the collapsible rail opens on desktop via ::details-content instead of a resize script. * Cover Explorer facet Clear all end to end * Clear facets through their own checkboxes; re-filter swaps only while searching * Skip the facet Clear all e2e quickly when the fixture has no facet values * Distill grouped rendering and align facet controls with selection semantics --- AGENTS.md | 7 + e2e/tests/container-identity.spec.ts | 190 +++-------- e2e/tests/dashboard-add-widget.spec.ts | 1 + e2e/tests/infrastructure-time-window.spec.ts | 102 +++++- e2e/tests/query-editor.spec.ts | 15 + e2e/tests/repositories.spec.ts | 2 +- monoscope.cabal | 2 + src/Pages/Components.hs | 53 +-- src/Pages/Containers.hs | 32 +- src/Pages/Infrastructure.hs | 202 +++++------- src/Pages/LogExplorer/Log.hs | 183 +++++------ src/Pkg/Components/Facets.hs | 112 +++++++ src/Pkg/Components/Table.hs | 324 +++++++++++-------- src/Pkg/Components/TimePicker.hs | 6 - test/integration/Pages/ContainersSpec.hs | 203 +++++------- web-components/src/main.ts | 5 +- web-components/test/table-export.test.ts | 14 +- 17 files changed, 725 insertions(+), 728 deletions(-) create mode 100644 src/Pkg/Components/Facets.hs diff --git a/AGENTS.md b/AGENTS.md index 29442a0db..016456627 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -204,6 +204,13 @@ without having run them. ### Sign off locally before updating the pull request — never push and wait on CI +**Run sign-off only at the end, after all requested work, reviews, and focused +verification are complete. Sign-off is expensive: do not start or queue +`make ci-signoff`, full CI, or deploy-image builds while implementation or UI +iteration is still in progress. Use the existing watchers and focused tests +during development. If more work is requested after sign-off starts, stop that +run and finish the work before starting the final sign-off again.** + **A push to `master` IS a deploy, and remote CI is far too slow to be a feedback loop: an image build alone runs ~85 minutes.** So `make ci-signoff` must be green *before* you push the branch. It runs the checks locally and publishes diff --git a/e2e/tests/container-identity.spec.ts b/e2e/tests/container-identity.spec.ts index 809fd5414..55a34eed5 100644 --- a/e2e/tests/container-identity.spec.ts +++ b/e2e/tests/container-identity.spec.ts @@ -61,94 +61,7 @@ test("navbar refresh menu applies Off and interval options", async ({ page }) => } }); -test("changing the container time preset refreshes inventory and drawer windows", async ({ page }) => { - test.setTimeout(90_000); // Includes a real 15s live tick, repeated presets and held initial arrival. - test.skip(!process.env.E2E_BASE_URL, "Requires a disposable fixture database"); - const namespace = "e2e-container-preset"; - const cleanup = `DELETE FROM otel_metrics WHERE project_id='${DEMO_PROJECT}' AND resource->'k8s'->'namespace'->>'name'='${namespace}';`; - sql(cleanup + [30, 600].map(age => `INSERT INTO otel_metrics (project_id,id,series_id,timestamp,metric_name,metric_type,value,resource___k8s___container___name,resource___k8s___pod___name,resource___k8s___namespace___name,resource) - VALUES ('${DEMO_PROJECT}',gen_random_uuid(),'preset-${age}','${new Date(Date.now() - age * 1000).toISOString()}','container.cpu.usage','GAUGE',1,'preset-${age}','preset-pod-${age}','${namespace}', - '${JSON.stringify({ k8s: { container: { name: `preset-${age}` }, pod: { name: `preset-pod-${age}` }, namespace: { name: namespace }, cluster: { uid: CLUSTER }, node: { name: "preset-node" } } })}');`).join("")); - try { - await page.setViewportSize({ width: 390, height: 900 }); - await page.goto(`/p/${DEMO_PROJECT}/infrastructure/containers?namespace=${namespace}&cluster=${CLUSTER}&since=5M`, { waitUntil: "domcontentloaded" }); - const rows = page.locator('#containersContainer tr[role="button"]'); - await expect(rows).toHaveCount(1); - await expect(page.getByText(/containers reporting in the final 5m of this range/)).toBeVisible(); - const refresh = page.waitForRequest(request => new URL(request.url()).searchParams.get("deferred") === "1" && new URL(request.url()).searchParams.get("since") === "1H"); - await page.locator('[popovertarget="n-timepicker-popover"]').click(); - await page.locator('#n-timepicker-popover button[data-value="1H"]').click(); - const requested = new URL((await refresh).url()).searchParams; - expect(requested.getAll("since")).toEqual(["1H"]); - expect(requested.get("namespace")).toBe(namespace); - expect(requested.get("cluster")).toBe(CLUSTER); - await expect(page).toHaveURL(/since=1H/); - await expect(rows).toHaveCount(2); - await expect(page.getByText(/containers reporting in the final 15m of this range/)).toBeVisible(); - expect(await rows.evaluateAll(rows => rows.every(row => { - const params = new URL(row.getAttribute("data-hx-get")!, location.origin).searchParams; - return params.get("since") === "1H" && params.get("namespace") === "e2e-container-preset" && params.get("cluster") === "8b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d"; - }))).toBe(true); - const search = page.getByRole("searchbox", { name: "Search containers", exact: true }); - await search.fill("preset-600"); - await expect(page.locator('#containersContainer tr[role="button"]:visible')).toHaveCount(1); - for (const [preset, count] of [["5M", 1], ["1H", 2]] as const) { - await page.locator('[popovertarget="n-timepicker-popover"]').click(); - await page.locator(`#n-timepicker-popover button[data-value="${preset}"]`).click(); - await expect(rows).toHaveCount(count); - await expect(search).toHaveValue("preset-600"); - await expect(page.locator('#containersContainer tr[role="button"]:visible')).toHaveCount(preset === "1H" ? 1 : 0); - expect(new URL((await rows.first().getAttribute("data-hx-get"))!, page.url()).searchParams.get("since")).toBe(preset); - } - await search.focus(); - await page.evaluate(() => new Promise(resolve => document.getElementById("containersContainer")!.addEventListener("htmx:afterSwap", () => resolve(), { once: true }))); - await expect(search).toBeFocused(); - await expect(search).toHaveValue("preset-600"); - await expect(page.locator('#containersContainer tr[role="button"]:visible')).toHaveCount(1); - await search.fill(""); - await page.locator('[popovertarget="n-timepicker-popover"]').click(); - await page.getByRole("button", { name: "Previous time window", exact: true }).click(); - await expect.poll(() => new URL(page.url()).searchParams.get("from")).toBeTruthy(); - await expect(rows).toHaveCount(0); - await page.locator('#n-timepicker-popover button[data-value="1H"]').click(); - await expect(rows).toHaveCount(2); - const restored = new URL((await rows.first().getAttribute("data-hx-get"))!, page.url()).searchParams; - expect(restored.get("since")).toBe("1H"); - expect(restored.get("from") || restored.get("to")).toBeFalsy(); - await page.reload({ waitUntil: "domcontentloaded" }); - await expect(rows).toHaveCount(2); - await rows.filter({ hasText: "preset-600" }).focus(); - await page.keyboard.press("Enter"); - const drawer = page.locator("#global-data-drawer-content"); - await expect(drawer.getByText(/^Pod:\s*preset-pod-600$/)).toBeVisible(); - expect(new URL((await drawer.getByRole("link", { name: "View logs", exact: true }).getAttribute("href"))!, page.url()).searchParams.get("since")).toBe("1H"); - let release = () => {}; - const held = new Promise(resolve => { release = resolve; }); - await page.route("**/infrastructure/containers?**", async route => { - const params = new URL(route.request().url()).searchParams; - if (params.get("deferred") === "1" && params.get("since") === "5M") await held; - await route.continue(); - }); - try { - const initial = page.waitForRequest(request => new URL(request.url()).searchParams.get("deferred") === "1"); - await page.goto(`/p/${DEMO_PROJECT}/infrastructure/containers?namespace=${namespace}&cluster=${CLUSTER}&since=5M`, { waitUntil: "domcontentloaded" }); - await initial; - await page.locator('[popovertarget="n-timepicker-popover"]').click(); - await page.locator("[data-mobile-live-toggle]").click(); - await expect(page.locator("[data-time-transport]")).toHaveAttribute("data-interval", "0"); - await page.locator('#n-timepicker-popover button[data-value="1H"]').click(); - release(); - await expect(rows).toHaveCount(2); - expect(new URL((await rows.first().getAttribute("data-hx-get"))!, page.url()).searchParams.get("since")).toBe("1H"); - } finally { - release(); - } - } finally { - sql(cleanup); - } -}); - -for (const width of [390, 1280]) { +for (const width of [390, 1280, 1920]) { test(`duplicate containers expose their identity before opening a drawer at ${width}px`, async ({ page }) => { await page.setViewportSize({ width, height: 900 }); await page.goto(`/p/${DEMO_PROJECT}/infrastructure/containers?from=2024-12-31T23:00:00Z&to=2025-01-01T00:00:00Z`, { waitUntil: "domcontentloaded" }); @@ -163,7 +76,7 @@ for (const width of [390, 1280]) { return value ? value.getClientRects().length > 0 : null; }); })); - expect(visible).toEqual(Array(identities.length * 4).fill(width < 1024)); + expect(visible).toEqual(Array(identities.length * 4).fill(width < 1536)); await expect.poll(() => page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); }); } @@ -213,38 +126,30 @@ for (const width of [390, 1280]) { expect(data.error ?? null).toBeNull(); expect(data.dataset.map((row: number[]) => row.slice(1))).toEqual([[2]]); await expect(drawer.locator("#container-detail-cpu canvas")).toBeVisible(); - }); -} - -for (const theme of ["dark", "light"]) { - test(`a lone container metric observation has a visible point in ${theme} appearance`, async ({ page }) => { - await page.setViewportSize({ width: 1280, height: 900 }); - await page.goto(`/p/${DEMO_PROJECT}/infrastructure/containers?namespace=identity-b&from=2024-12-31T23:00:00Z&to=2025-01-01T00:00:00Z`, { waitUntil: "domcontentloaded" }); - await expect(page.locator("[data-deferred-shell]")).toHaveCount(0); - if (await page.locator("body").getAttribute("data-theme") !== theme) await page.evaluate(() => (window as any).toggleDarkMode()); - await page.locator(`tr[role="button"][data-hx-get*="container=${CONTAINER}"] td`).first().click(); - await expect(page.locator("#global-data-drawer-content #container-detail-cpu canvas")).toBeVisible(); - await expect(page.locator("#container-detail-cpu")).toHaveAttribute("aria-busy", "false"); - const rendered = await page.evaluate(() => { - const chart = (window as any).echarts.getInstanceByDom(document.getElementById("container-detail-cpu")); - const data = chart.getModel().getSeriesByIndex(0)?.getData(); - if (!data) return { values: [], symbols: 0 }; - const dimension = data.mapDimension("y"); - const values = Array.from({ length: data.count() }, (_, index) => data.get(dimension, index)).filter(Number.isFinite); - const symbols = Array.from({ length: data.count() }, (_, index) => data.getItemGraphicEl(index)).filter(element => element && !element.ignore && element.getBoundingRect().width > 0 && element.getBoundingRect().height > 0).length; - return { values, symbols }; - }); - expect(rendered.values).toEqual([2]); - expect(rendered.symbols).toBe(1); - const point = await page.evaluate(() => { - const element = document.getElementById("container-detail-cpu")!; - const chart = (window as any).echarts.getInstanceByDom(element); - const pixel = chart.convertToPixel({ seriesIndex: 0 }, chart.getOption().dataset[0].source[1]); - const bounds = element.getBoundingClientRect(); - return { x: bounds.left + pixel[0], y: bounds.top + pixel[1] }; - }); - await page.mouse.move(point.x, point.y + 1); - await expect(page.getByText("2 cores", { exact: true })).toBeVisible(); + for (const theme of width === 1280 ? ["dark", "light"] : []) { + if (await page.locator("body").getAttribute("data-theme") !== theme) await page.evaluate(() => (window as any).toggleDarkMode()); + await expect(page.locator("#container-detail-cpu")).toHaveAttribute("aria-busy", "false"); + const rendered = await page.evaluate(() => { + const chart = (window as any).echarts.getInstanceByDom(document.getElementById("container-detail-cpu")); + const data = chart.getModel().getSeriesByIndex(0)?.getData(); + if (!data) return { values: [], symbols: 0 }; + const dimension = data.mapDimension("y"); + const values = Array.from({ length: data.count() }, (_, index) => data.get(dimension, index)).filter(Number.isFinite); + const symbols = Array.from({ length: data.count() }, (_, index) => data.getItemGraphicEl(index)).filter(element => element && !element.ignore && element.getBoundingRect().width > 0 && element.getBoundingRect().height > 0).length; + return { values, symbols }; + }); + expect(rendered.values).toEqual([2]); + expect(rendered.symbols).toBe(1); + const point = await page.evaluate(() => { + const element = document.getElementById("container-detail-cpu")!; + const chart = (window as any).echarts.getInstanceByDom(element); + const pixel = chart.convertToPixel({ seriesIndex: 0 }, chart.getOption().dataset[0].source[1]); + const bounds = element.getBoundingClientRect(); + return { x: bounds.left + pixel[0], y: bounds.top + pixel[1] }; + }); + await page.mouse.move(point.x, point.y + 1); + await expect(page.getByText("2 cores", { exact: true })).toBeVisible(); + } }); } @@ -255,13 +160,12 @@ test("mobile namespace facet preserves the selected cluster", async ({ page }) = const rows = page.locator(`tr[role="button"][data-hx-get*="container=${CONTAINER}"]`); await expect(rows).toHaveCount(4); expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); - await page.locator("#containersContainer summary").filter({ hasText: /^Filters$/ }).focus(); - await page.keyboard.press("Enter"); - await page.locator('[data-component="facet-section"] summary').filter({ hasText: /^Namespace$/ }).focus(); + await page.locator("#containersContainer summary").filter({ hasText: /^Filters$/ }).press("Enter"); + await page.locator('[data-component="facet-section"] summary').filter({ hasText: /^Namespace$/ }).press("Enter"); + await expect(page.getByRole("radio", { name: "identity-a", exact: true })).toBeHidden(); await page.keyboard.press("Enter"); const changed = page.waitForResponse(response => new URL(response.url()).searchParams.get("namespace") === "identity-a"); - await page.getByRole("radio", { name: "identity-a", exact: true }).focus(); - await page.keyboard.press("Space"); + await page.getByRole("radio", { name: "identity-a", exact: true }).press("Space"); const url = new URL((await changed).url()); await expect(rows).toHaveCount(3); expect(url.searchParams.getAll("cluster")).toEqual([CLUSTER]); @@ -269,24 +173,19 @@ test("mobile namespace facet preserves the selected cluster", async ({ page }) = expect(url.searchParams.get("from")).toBe("2024-12-31T23:00:00Z"); expect(url.searchParams.get("to")).toBe("2025-01-01T00:00:00Z"); expect(await rows.evaluateAll((rows, cluster) => rows.every(row => new URL(row.getAttribute("data-hx-get")!, "http://localhost").searchParams.get("cluster") === cluster), CLUSTER)).toBe(true); - await page.locator("#containersContainer summary").filter({ hasText: /^Filters$/ }).focus(); - await page.keyboard.press("Enter"); + await page.locator("#containersContainer summary").filter({ hasText: /^Filters$/ }).press("Enter"); const replaced = page.waitForResponse(response => new URL(response.url()).searchParams.get("namespace") === "identity-b"); - await page.getByRole("radio", { name: "identity-b", exact: true }).focus(); - await page.keyboard.press("Space"); + await page.getByRole("radio", { name: "identity-b", exact: true }).press("Space"); const replacedUrl = new URL((await replaced).url()); await expect(rows).toHaveCount(1); expect(replacedUrl.searchParams.getAll("namespace")).toEqual(["identity-b"]); expect(replacedUrl.searchParams.getAll("cluster")).toEqual([CLUSTER]); - await page.getByRole("button", { name: "Remove filter Namespace: identity-b", exact: true }).focus(); - await page.keyboard.press("Enter"); + await page.getByRole("button", { name: "Remove filter Namespace: identity-b", exact: true }).press("Enter"); await expect(rows).toHaveCount(4); await expect(page.getByRole("button", { name: `Remove filter Cluster: ${CLUSTER}`, exact: true })).toBeVisible(); - await page.locator("#containersContainer summary").filter({ hasText: /^Filters$/ }).focus(); - await page.keyboard.press("Enter"); + await page.locator("#containersContainer summary").filter({ hasText: /^Filters$/ }).press("Enter"); const cleared = page.waitForResponse(response => new URL(response.url()).pathname.endsWith("/infrastructure/containers")); - await page.getByRole("button", { name: "Clear all", exact: true }).focus(); - await page.keyboard.press("Enter"); + await page.getByRole("button", { name: "Clear all", exact: true }).press("Enter"); const clearUrl = new URL((await cleared).url()); await expect(rows).toHaveCount(5); for (const key of ["runtime", "cluster", "namespace", "node", "image"]) expect(clearUrl.searchParams.has(key)).toBe(false); @@ -301,6 +200,9 @@ test("mobile container search remains reachable and preserves drawer identity", await expect(page.locator("[data-deferred-shell]")).toHaveCount(0); const rows = page.locator(`tr[role="button"][data-hx-get*="container=${CONTAINER}"]:visible`); await expect(rows).toHaveCount(4); + const cpu = rows.filter({ hasText: "Node / host: identity-node-b" }).locator("td").nth(4).locator("span"); + await expect(cpu).toHaveText("4.000"); + await expect(cpu).toBeInViewport({ ratio: 0.95 }); const search = page.getByPlaceholder("Search containers", { exact: true }); await expect(search).toBeVisible(); expect(await search.evaluate(input => parseFloat(getComputedStyle(input).fontSize))).toBeGreaterThanOrEqual(16); @@ -319,27 +221,13 @@ test("mobile container search remains reachable and preserves drawer identity", expect(url.searchParams.get("from")).toBe("2024-12-31T23:00:00Z"); expect(url.searchParams.get("to")).toBe("2025-01-01T00:00:00Z"); expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); - await rows.focus(); - await page.keyboard.press("Enter"); + await rows.press("Enter"); const drawer = page.locator("#global-data-drawer-content"); await expect(drawer.getByText(/^Node \/ host:\s*identity-node-b$/)).toBeVisible(); await expect(drawer.getByText(/^Namespace:\s*identity-a$/)).toBeVisible(); }); -test("mobile container CPU fits initially with an active cluster filter", async ({ page }) => { - await page.setViewportSize({ width: 390, height: 900 }); - await page.goto(`/p/${DEMO_PROJECT}/infrastructure/containers?cluster=${CLUSTER}&from=2024-12-31T23:00:00Z&to=2025-01-01T00:00:00Z`, { waitUntil: "domcontentloaded" }); - await expect(page.locator("[data-deferred-shell]")).toHaveCount(0); - const rows = page.locator(`tr[role="button"][data-hx-get*="container=${CONTAINER}"]`); - await expect(rows).toHaveCount(4); - const cpu = rows.filter({ hasText: "Node / host: identity-node-b" }).locator("td").nth(4).locator("span"); - await expect(cpu).toHaveText("4.000"); - await expect(cpu).toBeInViewport({ ratio: 0.95 }); - expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true); -}); - - for (const width of [390, 1280]) { test(`container CPU fits initially with collector image and workload metadata at ${width}px`, async ({ page }) => { test.skip(!process.env.E2E_BASE_URL, "Requires a disposable fixture server"); diff --git a/e2e/tests/dashboard-add-widget.spec.ts b/e2e/tests/dashboard-add-widget.spec.ts index 8f0ec2572..3cc3f53d5 100644 --- a/e2e/tests/dashboard-add-widget.spec.ts +++ b/e2e/tests/dashboard-add-widget.spec.ts @@ -43,6 +43,7 @@ async function openFixture(page: Page): Promise { async function openWidgetDrawer(page: Page) { await page.locator('[aria-label="Add a new widget"]').first().click(); await expect(page.locator("#visualizationTabs")).toBeVisible({ timeout: 20000 }); + await expect(page.getByRole("textbox", { name: "Query", exact: true })).toBeVisible(); } test("a slow avatar does not block dashboard initialization", async ({ page }) => { diff --git a/e2e/tests/infrastructure-time-window.spec.ts b/e2e/tests/infrastructure-time-window.spec.ts index bf07abd29..acf2816f0 100644 --- a/e2e/tests/infrastructure-time-window.spec.ts +++ b/e2e/tests/infrastructure-time-window.spec.ts @@ -24,8 +24,92 @@ const views = [ ["hosts", "hostsContainer", { provider, group: "region" }, "Search hosts"], ["images", "imagesContainer", { registry: "registry.example", runtime: "kubernetes" }, "Search images"], ["kubernetes", "kubernetesContainer", { resource: "pods", namespace, cluster }, "Search pods"], + ["containers", "containersContainer", { namespace, cluster }, "Search containers"], ["host-map", "hostMapContainer", { provider, group: "region", fill: "memory" }, ""], ] as const; + +for (const width of [390, 1440]) { + test(`shared host controls preserve filters, columns and grouped exports at ${width}px`, async ({ page }) => { + test.skip(!process.env.E2E_BASE_URL, "Requires a disposable fixture database"); + await page.setViewportSize({ width, height: 900 }); + await page.goto(`/p/${DEMO_PROJECT}/infrastructure/hosts?${new URLSearchParams({ provider, since: "1H" })}`); + const container = page.locator('#hostsContainer'); + await expect(container.locator('tr[role="button"]')).toHaveCount(2); + if (width === 1440) { + await container.evaluate(async (target, url) => { await (window as any).htmx.ajax('GET', url, { target, swap: 'beforeend', select: '#imagesContainer-facets' }); }, `/p/${DEMO_PROJECT}/infrastructure/images?since=1H&deferred=1`); + const other = page.locator('#imagesContainer-facets'); + await expect(other.getByRole('radio', { name: 'kubernetes', exact: true })).toBeVisible(); + const search = container.locator('#hostsContainer-facets').getByRole('searchbox'); + await search.fill(provider); + await expect(other.getByRole('radio', { name: 'kubernetes', exact: true })).toBeVisible(); + await search.fill(''); + await other.evaluate(rail => rail.remove()); + } + await expect(container.getByRole('button', { name: 'Customize', exact: true })).toBeInViewport(); + await expect(container.getByRole('button', { name: 'Export', exact: true })).toBeInViewport(); + await container.getByRole('button', { name: 'Customize', exact: true }).click(); + await container.locator('[data-column-toggle="CPU"]').uncheck(); + await container.getByRole('button', { name: 'Customize', exact: true }).click(); + await container.getByRole('combobox', { name: 'Group by', exact: true }).selectOption('region'); + await expect(page).toHaveURL(/group=region/); + expect(new URL(page.url()).searchParams.get('provider')).toBe(provider); + expect(new URL(page.url()).searchParams.get('since')).toBe('1H'); + expect(new URL(page.url()).searchParams.has('deferred')).toBe(false); + await expect(container.locator('[data-table-group]')).toHaveCount(1); + await expect(container.locator('td[data-column-key="CPU"]').first()).toBeHidden(); + const search = container.getByRole('searchbox', { name: 'Search hosts', exact: true }); + await search.fill('no-such-host'); + await expect(container.locator('[data-table-group]')).toBeHidden(); + await search.fill(''); + await expect(container.locator('[data-table-group]')).toBeVisible(); + const download = page.waitForEvent('download'); + await container.getByRole('button', { name: 'Export', exact: true }).click(); + const stream = await (await download).createReadStream(); + const chunks: Buffer[] = []; + for await (const chunk of stream!) chunks.push(Buffer.from(chunk)); + const csv = Buffer.concat(chunks).toString(); + expect(csv.split('\n')).toHaveLength(3); + expect(csv).not.toContain('"CPU"'); + expect(csv).toContain('infra-preset-host-30'); + expect(csv).toContain('infra-preset-host-600'); + await page.reload(); + await expect(container.locator('tr[role="button"]')).toHaveCount(2); + await expect(container.locator('td[data-column-key="CPU"]').first()).toBeHidden(); + await container.getByRole('button', { name: 'Customize', exact: true }).click(); + await container.getByRole('button', { name: 'Reset columns', exact: true }).click(); + await expect(container.locator('td[data-column-key="CPU"]').first()).toBeVisible(); + if (width === 390) { + const system = container.locator('[data-column-toggle="System"]'); + await expect(system).not.toBeChecked(); + await system.check(); + await expect(container.locator('td[data-column-key="System"]').first()).toBeVisible(); + await container.getByRole('button', { name: 'Reset columns', exact: true }).click(); + await expect(container.locator('td[data-column-key="System"]').first()).toBeHidden(); + await page.setViewportSize({ width: 1440, height: 900 }); + await expect(container.locator('td[data-column-key="System"]').first()).toBeVisible(); + await expect(system).toBeChecked(); + } + }); +} + +test('shared Kubernetes tabs preserve scoped filters and column choices', async ({ page }) => { + test.skip(!process.env.E2E_BASE_URL, "Requires a disposable fixture database"); + await page.goto(`/p/${DEMO_PROJECT}/infrastructure/kubernetes?${new URLSearchParams({ resource: 'pods', namespace, cluster, since: '1H' })}`); + const container = page.locator('#kubernetesContainer'); + await expect(container.locator('tr[role="button"]')).toHaveCount(2); + await container.getByRole('button', { name: 'Customize', exact: true }).click(); + await container.locator('[data-column-toggle="Memory"]').uncheck(); + await container.getByRole('button', { name: 'Customize', exact: true }).click(); + await container.getByRole('tab', { name: 'Nodes', exact: true }).click(); + await expect(page).toHaveURL(/resource=nodes/); + const params = new URL(page.url()).searchParams; + expect(params.get('namespace')).toBe(namespace); + expect(params.get('cluster')).toBe(cluster); + expect(params.get('since')).toBe('1H'); + await expect(container.locator('tr[role="button"]')).toHaveCount(2); + await expect(container.locator('td[data-column-key="Memory"]').first()).toBeHidden(); +}); + for (const [route, container, filters, searchName] of views) { test(`${route} time presets refresh scoped inventory`, async ({ page }) => { test.skip(!process.env.E2E_BASE_URL, "Requires a disposable fixture database"); @@ -33,8 +117,9 @@ for (const [route, container, filters, searchName] of views) { const url = `/p/${DEMO_PROJECT}/infrastructure/${route}?${new URLSearchParams({ ...filters, from: "", to: "", since: "5m" })}`; await page.goto(url, { waitUntil: "domcontentloaded" }); await expect(page.locator("[data-deferred-shell]")).toHaveCount(0, { timeout: 5_000 }); - const entries = page.locator(`#${container} ${route === "host-map" ? "button[data-hx-get]" : 'tr[role="button"]'}`); + const entries = page.locator(`#${container} ${route === "host-map" ? 'button[data-hx-get*="/infrastructure/hosts/detail"]' : 'tr[role="button"]'}`); await expect(entries).toHaveCount(1); + if (route === "containers") await expect(page.getByText(/containers reporting in the final 5m of this range/)).toBeVisible(); await page.locator('[popovertarget="n-timepicker-popover"]').click(); await page.locator("[data-mobile-live-toggle]").click(); await expect(page.locator("[data-time-transport]")).toHaveAttribute("data-interval", "0"); @@ -43,6 +128,7 @@ for (const [route, container, filters, searchName] of views) { await page.locator('#n-timepicker-popover button[data-value="1H"]').click(); await expect(page).toHaveURL(/since=1H/); await expect(entries).toHaveCount(2); + if (route === "containers") await expect(page.getByText(/containers reporting in the final 15m of this range/)).toBeVisible(); const params = new URL((await refresh).url()).searchParams; expect(params.getAll("since")).toEqual(["1H"]); expect(params.getAll("from")).toEqual([""]); @@ -86,6 +172,14 @@ for (const [route, container, filters, searchName] of views) { const restored = new URL((await entries.first().getAttribute("data-hx-get"))!, page.url()).searchParams; expect(restored.get("since")).toBe("1H"); expect(restored.get("from") || restored.get("to")).toBeFalsy(); + if (route === "containers") { + await page.reload({ waitUntil: "domcontentloaded" }); + await expect(entries).toHaveCount(2); + await entries.filter({ hasText: "600" }).press("Enter"); + const drawer = page.locator("#global-data-drawer-content"); + await expect(drawer.getByText(/^Pod:\s*infra-preset-pod-600$/)).toBeVisible(); + expect(new URL((await drawer.getByRole("link", { name: "View logs", exact: true }).getAttribute("href"))!, page.url()).searchParams.get("since")).toBe("1H"); + } }); test(`${route} time presets replace held initial inventory`, async ({ page }) => { test.skip(!process.env.E2E_BASE_URL, "Requires a disposable fixture database"); @@ -107,14 +201,14 @@ for (const [route, container, filters, searchName] of views) { await page.locator('#n-timepicker-popover button[data-value="1H"]').click(); release(); await expect(page.locator("[data-deferred-shell]")).toHaveCount(0, { timeout: 5_000 }); - const entries = page.locator(`#${container} ${route === "host-map" ? "button[data-hx-get]" : 'tr[role="button"]'}`); + const entries = page.locator(`#${container} ${route === "host-map" ? 'button[data-hx-get*="/infrastructure/hosts/detail"]' : 'tr[role="button"]'}`); await expect(entries).toHaveCount(2); expect(new URL((await entries.first().getAttribute("data-hx-get"))!, page.url()).searchParams.get("since")).toBe("1H"); } finally { release(); } }); } -for (const [route, container, filters] of [...views, ["containers", "containersContainer", { namespace, cluster }]] as const) { +for (const [route, container, filters] of views) { test(`${route} initial inventory does not wait for application script arrival`, async ({ page }) => { test.skip(!process.env.E2E_BASE_URL, "Requires a disposable fixture database"); let release = () => {}; @@ -122,7 +216,7 @@ for (const [route, container, filters] of [...views, ["containers", "containersC await page.route(/\/public\/assets\/(?:js\/main\.|web-components\/dist\/js\/index\.).*\.js$/, async route => { await held; await route.continue(); }); try { await page.goto(`/p/${DEMO_PROJECT}/infrastructure/${route}?${new URLSearchParams({ ...filters, from: "", to: "", since: "5M" })}&since=5m`, { waitUntil: "commit" }); - const entries = page.locator(`#${container} ${route === "host-map" ? "button[data-hx-get]" : 'tr[role="button"]'}`); + const entries = page.locator(`#${container} ${route === "host-map" ? 'button[data-hx-get*="/infrastructure/hosts/detail"]' : 'tr[role="button"]'}`); await page.waitForFunction(() => Boolean((window as any).htmx)); await expect.poll(() => page.evaluate(() => typeof (window as any).params)).toBe("undefined"); // The shell may have loaded automatically before this test reaches it. diff --git a/e2e/tests/query-editor.spec.ts b/e2e/tests/query-editor.spec.ts index 4b892ebc5..eb5205e3e 100644 --- a/e2e/tests/query-editor.spec.ts +++ b/e2e/tests/query-editor.spec.ts @@ -145,6 +145,21 @@ test.describe("Query editor", () => { for (const tab of ["Popular", "Saved", "Recent"]) await expect(library.getByRole("tab", { name: tab })).toBeVisible(); }); + + test("facet Clear all removes facet clauses and keeps typed ones", async ({ page }) => { + const facets = page.locator(".facet-rail .facet-item input[data-field]"); + const clear = page.locator(".facet-rail button", { hasText: "Clear all" }); + await facets.first().waitFor({ state: "attached", timeout: 10_000 }).catch(() => {}); + test.skip((await facets.count()) < 2, "no facet values in this database"); + await page.locator("#filterElement").evaluate((el: any) => el.setValue("duration > 1000")); + await expect(clear).toBeHidden(); + await facets.nth(0).check(); + await facets.nth(1).check(); + await expect(clear).toBeVisible(); + await clear.click(); + await expect.poll(() => page.locator("#filterElement").evaluate((el: any) => el.getValue())).toBe("duration > 1000"); + await expect(clear).toBeHidden(); + }); }); // Regression: the explorer ships without Tagify, so the monitor panel's teams picker threw diff --git a/e2e/tests/repositories.spec.ts b/e2e/tests/repositories.spec.ts index a6e19a8ba..a030fbc5c 100644 --- a/e2e/tests/repositories.spec.ts +++ b/e2e/tests/repositories.spec.ts @@ -197,7 +197,7 @@ test('one repository list owns service links and independent capabilities in bot expect(sql(`SELECT count(*) FROM projects.code_mappings WHERE project_id = '${pid}'`).toString().trim()).toBe('2'); await page.getByRole('button', { name: 'Save review settings', exact: true }).press('Enter'); await expect(page.locator('#repository-detail')).toHaveCount(1); - expect(sql(`SELECT enabled FROM projects.pr_review_settings WHERE project_id = '${pid}' AND owner = 'team-a'`).toString().trim()).toBe('t'); + await expect.poll(() => sql(`SELECT enabled FROM projects.pr_review_settings WHERE project_id = '${pid}' AND owner = 'team-a'`).toString().trim()).toBe('t'); await page.getByText('Move existing resources into this folder', { exact: true }).click(); await page.getByRole('combobox', { name: /Cron/ }).selectOption(cron); await page.getByRole('combobox', { name: /Cron/ }).locator('..').locator('..').getByRole('button', { name: 'Move into folder', exact: true }).press('Enter'); diff --git a/monoscope.cabal b/monoscope.cabal index 3fabfca8b..8c712899d 100644 --- a/monoscope.cabal +++ b/monoscope.cabal @@ -386,6 +386,7 @@ library Pages.Telemetry Pkg.AI Pkg.AssetManifestFingerprint + Pkg.Components.Facets Pkg.Components.LogQueryBox Pkg.Components.ServiceMap Pkg.Components.Table @@ -1030,6 +1031,7 @@ test-suite test-dev Pages.Telemetry Pkg.AI Pkg.AssetManifestFingerprint + Pkg.Components.Facets Pkg.Components.LogQueryBox Pkg.Components.ServiceMap Pkg.Components.Table diff --git a/src/Pages/Components.hs b/src/Pages/Components.hs index a488f8782..fd3204785 100644 --- a/src/Pages/Components.hs +++ b/src/Pages/Components.hs @@ -1,4 +1,4 @@ -module Pages.Components (drawer_, PanelStyle (..), PanelCfg (..), panel_, entityHeader_, detailSection_, pivotLinks_, disclosure_, settingsSection_, settingsH2_, sectionLabel_, fieldLabel_, headerRow_, navBar, brandLogo_, resizer_, resizerWith_, detailTab_, httpTab_, tabPanel_, segmented_, periodToggle_, Deferred (..), RefreshingDeferred (..), withDeferredBody, deferredShell_, lazyPanel_, timeRefreshListener_, drawerLoadingSkeleton_, tableSkeleton_, chartSkeleton_, EmptyStateCfg (..), EmptyStateSize (..), EmptyStateAction (..), emptyState_, callout_, BadgeColor (..), IconBadgeSize (..), iconBadge_, tonePill_, colorChip_, metadataChip_, metaChip_, connectionBadge_, silenceBadge_, statFigure_, factGrid_, kvList_, sparkline_, eventsCountCell_, lastSeenCell_, dateTime, localTimeFmt_, FieldSize (..), FieldCfg (..), formField_, formSelectField_, formCheckbox_, options_, roleOptions_, tagInput_, toggleRow_, searchInput_, copyField_, copyButton_, facetRail_, facetSection_, facetOption_, ModalCfg (..), modalWith_, formActionsModal_, dangerAction_, floatingDialog_, dialogField_, kbdHints_, durationMenu_, primaryButton_, inlineIconBtn_, RowAction (..), rowActions_, externalLink_, installationSettingsLink_, dirtyFormSaveAttr_, resetFormOnSuccessAttr_, detailsClosedBelowAttr_, keyboardActivateAttr_, listboxNavAttr_, copySourceAttr_, filterInputAttr_, TraceFrame (..), stackTrace_, stackFrames_, codeContextUrl, curlCommand, getTargetPage, abbreviateUnit, agoText, durationQuery, untilLabel, grantsTrial, paymentPlanPicker) where +module Pages.Components (drawer_, PanelStyle (..), PanelCfg (..), panel_, entityHeader_, detailSection_, pivotLinks_, disclosure_, settingsSection_, settingsH2_, sectionLabel_, fieldLabel_, headerRow_, navBar, brandLogo_, resizer_, resizerWith_, detailTab_, httpTab_, tabPanel_, segmented_, periodToggle_, Deferred (..), RefreshingDeferred (..), withDeferredBody, deferredShell_, lazyPanel_, timeRefreshListener_, drawerLoadingSkeleton_, tableSkeleton_, chartSkeleton_, EmptyStateCfg (..), EmptyStateSize (..), EmptyStateAction (..), emptyState_, callout_, BadgeColor (..), IconBadgeSize (..), iconBadge_, tonePill_, colorChip_, metadataChip_, metaChip_, connectionBadge_, silenceBadge_, statFigure_, factGrid_, kvList_, sparkline_, eventsCountCell_, lastSeenCell_, dateTime, localTimeFmt_, FieldSize (..), FieldCfg (..), formField_, formSelectField_, formCheckbox_, options_, roleOptions_, tagInput_, toggleRow_, searchInput_, copyField_, copyButton_, ModalCfg (..), modalWith_, formActionsModal_, dangerAction_, floatingDialog_, dialogField_, kbdHints_, durationMenu_, primaryButton_, inlineIconBtn_, RowAction (..), rowActions_, externalLink_, installationSettingsLink_, dirtyFormSaveAttr_, resetFormOnSuccessAttr_, detailsClosedBelowAttr_, keyboardActivateAttr_, listboxNavAttr_, copySourceAttr_, filterInputAttr_, TraceFrame (..), stackTrace_, stackFrames_, codeContextUrl, curlCommand, getTargetPage, abbreviateUnit, agoText, durationQuery, untilLabel, grantsTrial, paymentPlanPicker) where import Data.Default (Default (..)) import Data.List (elemIndex, findIndex, lookup) @@ -77,55 +77,6 @@ searchInput_ extra ph attrs = label_ [class_ $ "input input-sm flex items-center input_ $ [type_ "search", class_ "min-w-0 grow bg-transparent max-md:text-base", placeholder_ ph, Aria.label_ (T.dropWhileEnd (== '…') ph)] <> attrs --- | Shared shell for searchable facet trees. The content decides how filters change --- (query-editor operations in Explorer, URL parameters in inventories); search, --- accessibility, and disclosure markers stay identical. -facetRail_ :: Maybe Text -> Text -> Text -> Maybe (Html ()) -> Html () -> Html () -facetRail_ elemId extraClass searchLabel actions content = - div_ ([class_ $ "facet-rail flex flex-col gap-2 " <> extraClass, data_ "component" "facet-rail"] <> [id_ x | x <- maybeToList elemId]) do - searchInput_ - "sticky top-0 z-10 h-9 w-[calc(100%-1rem)] mx-2 border-strokeStrong bg-bgBase" - searchLabel - [ name_ "facet-search" - , oninput_ "const q=this.value.toLowerCase();this.closest('[data-component=\"facet-rail\"]').querySelectorAll('[data-component=\"facet-option\"],[data-component=\"facet-section\"]').forEach(el=>el.classList.toggle('hidden',!el.textContent.toLowerCase().includes(q)))" - , onkeydown_ "if(event.key==='Escape'){this.value='';this.dispatchEvent(new Event('input',{bubbles:true}))}" - ] - whenJust actions id - content - - --- | Native details/summary facet disclosure shared by Explorer's lazy hierarchy --- and inventory filter menus. Extra attributes must not include @class@. -facetSection_ :: Bool -> Text -> [Attribute] -> Html () -> Html () -> Html () -facetSection_ startOpen extraClass attrs title content = - details_ - ( [ class_ $ "facet-section block border-t border-strokeWeak [&[open]>summary_.facet-chevron]:rotate-0 " <> extraClass - , data_ "component" "facet-section" - ] - <> attrs - <> [open_ "" | startOpen] - ) - do - summary_ [class_ "flex cursor-pointer list-none items-center gap-2 rounded px-2 py-2 text-xs font-semibold text-textStrong hover:bg-fillWeak [&::-webkit-details-marker]:hidden"] do - faSprite_ "chevron-down" "regular" "facet-chevron h-2.5 w-2.5 shrink-0 -rotate-90 transition-transform" - div_ [class_ "min-w-0 flex-1"] title - content - - --- | Shared option row. Callers provide the control/label body and optional count. -facetOption_ :: Text -> [Attribute] -> Html () -> Html () -> Html () -facetOption_ extraClass attrs body trailing = - label_ - ( [ class_ $ "flex min-h-7 cursor-pointer items-center justify-between gap-2 rounded px-2 py-1 hover:bg-fillWeak " <> extraClass - , data_ "component" "facet-option" - ] - <> attrs - ) - do - div_ [class_ "flex min-w-0 flex-1 items-center gap-2"] body - trailing - - -- | Header of an entity detail drawer: icon and title with inline @badges@, then the -- identity @chips@ row. Its sections go in a @main_@ that owns their rules -- (@[&>*+*]:border-t [&>*+*]:pt-4@), so 'detailSection_' and 'pivotLinks_' carry none. @@ -1116,7 +1067,7 @@ curlCommand method url headers body = T.intercalate " \\\n " $ ("curl -X " <> m -- server-generated ids, never from user input. Pair with @type_ "search"@ so Escape -- clears the box and refilters natively. filterInputAttr_ :: Text -> Attribute -filterInputAttr_ sel = term "_" [text|on input or htmx:after:swap from document set v to my value.toLowerCase() then repeat for el in <${sel}/> if (el.dataset.filter or el.textContent).toLowerCase().includes(v) remove .hidden from el else add .hidden to el end end|] +filterInputAttr_ sel = term "_" [text|on input set v to my value.toLowerCase() then repeat for el in <${sel}/> if (el.dataset.filter or el.textContent).toLowerCase().includes(v) remove .hidden from el else add .hidden to el end end on htmx:after:swap from document if my value is not '' send input to me end on keydown[key is 'Escape'] set my value to '' then send input to me|] -- | Toned icon + label chip. diff --git a/src/Pages/Containers.hs b/src/Pages/Containers.hs index 34f02a95f..5d681cddd 100644 --- a/src/Pages/Containers.hs +++ b/src/Pages/Containers.hs @@ -22,8 +22,8 @@ import Lucid import Models.Projects.Projects qualified as Projects import Models.Telemetry.Containers (ContainerRow (..), Runtime (..), Scope (..), containersInWindowCached, cpuPctOfLimit, freshnessWindow, memPctOfLimit, runtimeOf) import Pages.BodyWrapper (BWConfig (..), PageCtx (..), mkPageCtx) -import Pages.Components (BadgeColor (..), Deferred (..), EmptyStateAction (..), EmptyStateCfg (..), RefreshingDeferred (..), callout_, detailSection_, emptyState_, entityHeader_, factGrid_, metaChip_, pivotLinks_, tableSkeleton_, timeRefreshListener_, withDeferredBody) -import Pkg.Components.Table (Column, Config (..), Features (..), SearchMode (..), Table (..), ZeroState (..), col, facetActions, facetValues, singleSelectFilter, withAttrs, withColHeaderExtra) +import Pages.Components (BadgeColor (..), Deferred (..), EmptyStateAction (..), EmptyStateCfg (..), RefreshingDeferred (..), callout_, detailSection_, emptyState_, entityHeader_, factGrid_, metaChip_, pivotLinks_, tableSkeleton_, withDeferredBody) +import Pkg.Components.Table (Column, Features (..), Table (..), ZeroState (..), col, countedFilter, facetActions, inventoryTable, withAttrs, withColHeaderExtra) import Pkg.Components.TimePicker qualified as TimePicker import Pkg.Components.Widget qualified as Widget import Relude @@ -145,22 +145,16 @@ containersGetH pid runtimeM namespaceM nodeM imageM clusterM fromParam toParam s rows = sortOn (Down . (.cpuCores)) $ V.toList $ applyFilters filters allRows -- Facet values come from the unfiltered result, so choosing a namespace never empties -- the node or image menus — the way a facet bar is expected to behave. - menu label param selected fromRow = singleSelectFilter label param selected $ facetValues fromRow allRows + menu label param selected fromRow = countedFilter label param selected (maybeToList . fromRow) allRows + let table = inventoryTable "containers" deferredUrl pure - Table - { -- bulkActionsInHeader is what puts the header action group — and with it the whole - -- filter dropdown — into a column header. Leaving it unset renders no facet menus - -- at all, however many are configured. - config = def{elemID = "containersForm", containerId = Just "containersContainer", addPadding = True, renderAsTable = True, bulkActionsInHeader = Just 0} - , columns = containerColumns + table + { columns = containerColumns , rows = V.fromList $ map (ContainerVM pid window) rows , features = - def - { header = Just $ timeRefreshListener_ "containersContainer" deferredUrl - , search = Just ClientSide - , searchPlaceholder = Just "Search containers" - , rowAttrs = Just $ drawerRowAttrs_ . detailUrl - , tableHeaderActions = + table.features + { rowAttrs = Just $ drawerRowAttrs_ . detailUrl + , facets = Just $ facetActions (infraUrl pid "/infrastructure/containers" [] window) @@ -173,9 +167,7 @@ containersGetH pid runtimeM namespaceM nodeM imageM clusterM fromParam toParam s , menu "Node" "node" filters.node (.nodeName) , menu "Image" "image" filters.image (.image) ] - , showFilterRail = True , resultSummary = Just $ "Showing " <> show (length rows) <> " of " <> show (V.length allRows) <> " containers reporting in the final " <> freshnessLabel window <> " of this range" - , exportName = Just "containers" , zeroState = Just ZeroState @@ -191,8 +183,8 @@ containersGetH pid runtimeM namespaceM nodeM imageM clusterM fromParam toParam s containerColumns :: [Column ContainerVM] containerColumns = [ col "Container" renderNameCol & withAttrs [class_ "w-80 max-w-80 overflow-hidden max-md:w-auto max-md:max-w-none"] - , col "Pod" (textCell (.podName)) & withAttrs [class_ "w-72 max-w-72 overflow-hidden max-lg:hidden"] - , col "Namespace" (textCell (.namespace)) & withAttrs [class_ "w-32 max-lg:hidden"] + , col "Pod" (textCell (.podName)) & withAttrs [class_ "w-72 max-w-72 overflow-hidden max-2xl:hidden"] + , col "Namespace" (textCell (.namespace)) & withAttrs [class_ "w-32 max-2xl:hidden"] , col "Node" (textCell (.nodeName)) & withAttrs [class_ "w-36 max-md:hidden"] , col "CPU (cores)" (numCell (showFFloat' 3) (.cpuCores)) & withAttrs [class_ "w-24 text-right"] , col "CPU limit used" (pctCell "CPU limit used" cpuPctOfLimit) & withAttrs [class_ "w-36 max-md:hidden"] @@ -248,7 +240,7 @@ containersGetH pid runtimeM namespaceM nodeM imageM clusterM fromParam toParam s in span_ [class_ "min-w-0 flex-1 truncate", data_ "tippy-content" $ "Image: " <> image] $ toHtml image -- The badge is a flex box, so the ellipsis has to live on an inner block or the name clips at its start. whenJust vm.row.workload \workload -> span_ [class_ "badge badge-xs badge-ghost min-w-0 max-w-36 truncate", data_ "tippy-content" $ "Workload: " <> workload] $ span_ [class_ "min-w-0 truncate"] $ toHtml workload - div_ [class_ "hidden max-lg:flex flex-col gap-0.5 text-xs leading-normal text-textWeak"] + div_ [class_ "hidden max-2xl:flex flex-col gap-0.5 text-xs leading-normal text-textWeak"] $ forM_ ([("Pod", vm.row.podName), ("Namespace", vm.row.namespace), ("Cluster", vm.row.cluster), ("Node / host", vm.row.nodeName)] :: [(Text, Maybe Text)]) \(label, value) -> whenJust value \v -> span_ [class_ "whitespace-normal break-all"] $ toHtml $ label <> ": " <> v diff --git a/src/Pages/Infrastructure.hs b/src/Pages/Infrastructure.hs index 591e26be8..bb4082410 100644 --- a/src/Pages/Infrastructure.hs +++ b/src/Pages/Infrastructure.hs @@ -32,14 +32,14 @@ import Pages.Components (BadgeColor (..), Deferred (..), EmptyStateAction (..), import Pages.Containers (deferUrl, infraSnapshot, infraUrl, infrastructureBW, matchesAny, matchesFilter, mkWindow, pctText) import Pages.Containers qualified as Containers import Pages.LogExplorer.Log qualified as Log -import Pkg.Components.Table (Config (..), Features (..), SearchMode (..), Table (..), ZeroState (..), col, facetActions, facetValues, singleSelectFilter, withAttrs) +import Pkg.Components.Facets qualified as Facets +import Pkg.Components.Table (Features (..), SelectControl (..), Table (..), TableTabs (..), ZeroState (..), col, countedFilter, facetActions, facetsConfig, inventoryTable, selectControl_, withAttrs) import Pkg.Components.TimePicker qualified as TimePicker import Pkg.Components.Widget qualified as Widget import Pkg.DeriveUtils (WrappedEnumSC (..)) import Relude -import Relude.Extra.Tuple (dup) import System.Types (ATAuthCtx, RespHeaders, addRespHeaders) -import Utils (TabStrip (..), drawerLoadAttrs_, drawerRowAttrs_, faSprite_, formatBytes, navTabStrip_, showFFloat') +import Utils (drawerLoadAttrs_, drawerRowAttrs_, faSprite_, formatBytes, showFFloat') -- | Group by an optional key, dropping rows without one. Per-key lists come out in reverse @@ -139,19 +139,13 @@ hostGroupOption = \case GroupIntegration -> ("integration", "Integration") --- | Bucket every host falls into. @GroupNone@ collapses to a single bucket, which the table --- skips entirely and the map renders as one section. -groupHosts :: HostGroup -> V.Vector HostRow -> [(Text, [HostRow])] -groupHosts grouping = groupRows \host -> - Just case grouping of - GroupNone -> "All hosts" - GroupProvider -> fromMaybe "Unknown provider" host.provider - GroupRegion -> fromMaybe "Unknown region" host.region - GroupOS -> fromMaybe "Unknown OS" host.osType - GroupIntegration -> maybe "OpenTelemetry" integrationLabel $ listToMaybe $ drop 1 host.integrations - - -data HostListRow = HostGroupRow Text Int | HostItem HostRow +hostGroupLabel :: HostGroup -> HostRow -> Text +hostGroupLabel grouping host = case grouping of + GroupNone -> "All hosts" + GroupProvider -> fromMaybe "Unknown provider" host.provider + GroupRegion -> fromMaybe "Unknown region" host.region + GroupOS -> fromMaybe "Unknown OS" host.osType + GroupIntegration -> maybe "OpenTelemetry" integrationLabel $ listToMaybe $ drop 1 host.integrations hostsGetH :: Projects.ProjectId -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> ATAuthCtx (RespHeaders HostsGet) @@ -167,42 +161,30 @@ hostsGetH pid providerM regionM osM integrationM groupM fromParam toParam sinceP addRespHeaders $ HostsPage $ PageCtx (infrastructureBW pid "Hosts" window bw) body -newtype HostsGet = HostsPage (PageCtx (Deferred (Table HostListRow))) - deriving (ToHtml) via (PageCtx (RefreshingDeferred (Table HostListRow))) +newtype HostsGet = HostsPage (PageCtx (Deferred (Table HostRow))) + deriving (ToHtml) via (PageCtx (RefreshingDeferred (Table HostRow))) -hostsTable :: Projects.ProjectId -> TimePicker.TimeWindow -> Text -> HostFilters -> HostGroup -> V.Vector HostRow -> V.Vector HostRow -> Table HostListRow +hostsTable :: Projects.ProjectId -> TimePicker.TimeWindow -> Text -> HostFilters -> HostGroup -> V.Vector HostRow -> V.Vector HostRow -> Table HostRow hostsTable pid window url filters grouping hosts allHosts = - Table - { config = - def - { elemID = "hostsForm" - , containerId = Just "hostsContainer" - , addPadding = True - , renderAsTable = True - , bulkActionsInHeader = Just 0 - , containerClasses = "w-full mx-auto space-y-2 group/columns" - } - , columns = hostColumns - , rows = hostEntries grouping hosts + table + { columns = hostColumns + , rows = V.fromList $ sortOn (\h -> (hostGroupLabel grouping h, h.name)) $ V.toList hosts , features = - def - { search = Just ClientSide - , searchPlaceholder = Just "Search hosts" - , rowAttrs = Just $ \case HostGroupRow _ _ -> []; HostItem host -> drawerRowAttrs_ $ hostDetailUrl pid window host.name - , header = Just $ timeRefreshListener_ "hostsContainer" url >> hostGroupControl - , showFilterRail = True + table.features + { rowAttrs = Just $ drawerRowAttrs_ . hostDetailUrl pid window . (.name) + , rowGroup = if grouping == GroupNone then Nothing else Just $ Just . hostGroupLabel grouping + , grouping = Just $ SelectControl "group" "Group by" (hostGroupParam grouping) (map hostGroupOption [minBound ..]) url "hostsContainer" , resultSummary = Just $ "Showing " <> show (V.length hosts) <> " of " <> show (V.length allHosts) <> " hosts" - , exportName = Just "hosts" - , tableHeaderActions = + , facets = Just $ facetActions (infraUrl pid "/infrastructure/hosts" [("group", hostGroupParam grouping) | grouping /= GroupNone] window) "hostsContainer" - [ singleSelectFilter "Provider" "provider" filters.provider $ facetValues (.provider) allHosts - , singleSelectFilter "Region" "region" filters.region $ facetValues (.region) allHosts - , singleSelectFilter "OS" "os" filters.osType $ facetValues (.osType) allHosts - , singleSelectFilter "Integration" "integration" filters.integration $ map integrationLabel $ ordNub $ concatMap (.integrations) $ V.toList allHosts + [ countedFilter "Provider" "provider" filters.provider (maybeToList . (.provider)) allHosts + , countedFilter "Region" "region" filters.region (maybeToList . (.region)) allHosts + , countedFilter "OS" "os" filters.osType (maybeToList . (.osType)) allHosts + , countedFilter "Integration" "integration" filters.integration (map integrationLabel . (.integrations)) allHosts ] , zeroState = Just @@ -215,17 +197,7 @@ hostsTable pid window url filters grouping hosts allHosts = } } where - hostEntries GroupNone = V.map HostItem - hostEntries g = V.fromList . concatMap (\(label, hs) -> HostGroupRow label (length hs) : map HostItem (sortOn (.name) hs)) . groupHosts g - hostGroupControl = - form_ [method_ "get", action_ $ "/p/" <> pid.toText <> "/infrastructure/hosts", class_ "ml-auto mr-3 flex w-fit items-center gap-2 whitespace-nowrap"] do - TimePicker.timeHiddenInputs_ window.fromQuery window.toQuery window.sinceQuery - forM_ [(field, value) | (field, Just value) <- [("provider", filters.provider), ("region", filters.region), ("os", filters.osType), ("integration", filters.integration)]] \(field, value) -> - input_ [type_ "hidden", name_ field, value_ value] - label_ [Lucid.for_ "hosts-group", class_ "shrink-0 text-xs text-textWeak"] "Group by" - select_ [id_ "hosts-group", name_ "group", class_ "select select-xs w-auto cursor-pointer border-strokeWeak bg-bgBase", onchange_ "this.form.requestSubmit()"] - $ forM_ (map hostGroupOption [minBound ..]) \(value, label) -> - option_ ([value_ value] <> [selected_ "" | value == hostGroupParam grouping]) $ toHtml label + table = inventoryTable "hosts" url -- Configuration only earns its width when some host reports a provider or region; it is -- decided over the unfiltered inventory so a facet never toggles a column. hostColumns = @@ -235,29 +207,26 @@ hostsTable pid window url filters grouping hosts allHosts = , col "CPU" (metricCell (.cpuPct)) & withAttrs [class_ "w-32"] , col "Memory" (metricCell (.memoryPct)) & withAttrs [class_ "w-32"] , col "Storage" (metricCell (.storagePct)) & withAttrs [class_ "host-col-storage w-32 max-lg:hidden"] - , col "Load (1m)" (itemOnly $ plainCell . fmap (showFFloat' 2) . (.load1)) & withAttrs [class_ "host-col-load w-24 text-right max-xl:hidden"] + , col "Load (1m)" (plainCell . fmap (showFFloat' 2) . (.load1)) & withAttrs [class_ "host-col-load w-24 text-right max-xl:hidden"] , col "Uptime" uptimeCell & withAttrs [class_ "w-24 max-xl:hidden"] , col "Containers" containersCell & withAttrs [class_ "w-24 text-right"] , col "Integrations" integrationsCell & withAttrs [class_ "w-56 max-md:hidden"] ] where -- The row itself opens the drawer; a button in the name would be a second tab stop for the same action. - nameCell = \case - HostGroupRow label count -> div_ [class_ "flex items-center gap-2 py-1 font-semibold text-textStrong"] $ toHtml label >> span_ [class_ "badge badge-xs badge-ghost"] (toHtml $ show count) - HostItem host -> div_ [class_ "flex min-w-0 items-center gap-2 font-medium text-textStrong"] do - faSprite_ "server" "solid" "h-3.5 w-3.5 shrink-0 text-iconNeutral" - span_ [class_ "truncate"] $ toHtml host.name - configCell = itemOnly \host -> div_ [class_ "flex flex-wrap gap-1"] do + nameCell host = div_ [class_ "flex min-w-0 items-center gap-2 font-medium text-textStrong"] do + faSprite_ "server" "solid" "h-3.5 w-3.5 shrink-0 text-iconNeutral" + span_ [class_ "truncate"] $ toHtml host.name + configCell host = div_ [class_ "flex flex-wrap gap-1"] do whenJust host.provider $ metadataChip "cloud" . T.toTitle whenJust host.region $ metadataChip "location-dot" - systemCell = itemOnly \host -> span_ [class_ "text-xs text-textWeak"] $ toHtml $ T.intercalate " · " $ catMaybes [host.osType, host.architecture] - metricCell getter = itemOnly $ utilizationCell . getter - uptimeCell = itemOnly $ plainCell . fmap formatUptime . (.uptime) - containersCell = itemOnly $ span_ [class_ "tabular-nums text-textStrong"] . toHtml . show . (.containers) - integrationsCell = itemOnly \host -> div_ [class_ "flex flex-nowrap gap-1"] $ forM_ host.integrations \integration -> span_ [class_ "inline-flex items-center gap-1 whitespace-nowrap rounded-md border border-strokeWeak bg-fillWeak px-1.5 py-0.5 text-xs text-textWeak"] do + systemCell host = span_ [class_ "text-xs text-textWeak"] $ toHtml $ T.intercalate " · " $ catMaybes [host.osType, host.architecture] + metricCell getter = utilizationCell . getter + uptimeCell = plainCell . fmap formatUptime . (.uptime) + containersCell = span_ [class_ "tabular-nums text-textStrong"] . toHtml . show . (.containers) + integrationsCell host = div_ [class_ "flex flex-nowrap gap-1"] $ forM_ host.integrations \integration -> span_ [class_ "inline-flex items-center gap-1 whitespace-nowrap rounded-md border border-strokeWeak bg-fillWeak px-1.5 py-0.5 text-xs text-textWeak"] do faSprite_ (case integration of OpenTelemetryIntegration -> "arrows-turn-right"; KubernetesIntegration -> "cube"; DockerIntegration -> "layer-group") "regular" "h-3 w-3" toHtml $ integrationLabel integration - itemOnly render = \case HostGroupRow _ _ -> mempty; HostItem host -> render host metadataChip icon value = span_ [class_ "inline-flex items-center gap-1 rounded bg-fillWeak px-1.5 py-0.5 text-xs text-textWeak"] $ faSprite_ icon "regular" "h-3 w-3" >> toHtml value @@ -410,9 +379,8 @@ newtype ImagesGet = ImagesPage (PageCtx (Deferred (Table ImageRow))) imagesTable :: Projects.ProjectId -> TimePicker.TimeWindow -> Text -> Maybe Text -> Maybe Text -> V.Vector ImageRow -> V.Vector ImageRow -> Table ImageRow imagesTable pid window url runtimeM registryM images allImages = - Table - { config = def{elemID = "imagesForm", containerId = Just "imagesContainer", addPadding = True, renderAsTable = True, bulkActionsInHeader = Just 0} - , columns = + table + { columns = [ col "Image" (\image -> div_ [class_ "flex items-center gap-2 min-w-0"] $ faSprite_ "layer-group" "solid" "h-3.5 w-3.5 shrink-0 text-iconNeutral" >> span_ [class_ "truncate font-medium text-textStrong"] (toHtml image.image)) & withAttrs [class_ "min-w-72 w-full"] , col "Running" (\image -> span_ [class_ "tabular-nums text-textStrong"] $ toHtml $ show image.running) & withAttrs [class_ "w-24 text-right"] , col "Source" (\image -> span_ [class_ "whitespace-nowrap text-textWeak"] $ toHtml image.registry) & withAttrs [class_ "w-36"] @@ -424,26 +392,23 @@ imagesTable pid window url runtimeM registryM images allImages = ] , rows = images , features = - def - { header = Just $ timeRefreshListener_ "imagesContainer" url - , search = Just ClientSide - , searchPlaceholder = Just "Search images" - , rowAttrs = Just \image -> drawerRowAttrs_ $ infraUrl pid "/infrastructure/images/detail" [("image", image.image)] window - , tableHeaderActions = + table.features + { rowAttrs = Just \image -> drawerRowAttrs_ $ infraUrl pid "/infrastructure/images/detail" [("image", image.image)] window + , facets = Just $ facetActions (infraUrl pid "/infrastructure/images" [] window) "imagesContainer" - [ singleSelectFilter "Runtime" "runtime" runtimeM $ sortNub $ map Containers.runtimeLabel $ concatMap (.runtimes) $ V.toList allImages - , singleSelectFilter "Registry" "registry" registryM $ facetValues (Just . (.registry)) allImages + [ countedFilter "Runtime" "runtime" runtimeM (map Containers.runtimeLabel . (.runtimes)) allImages + , countedFilter "Registry" "registry" registryM (one . (.registry)) allImages ] , zeroState = Just $ ZeroState "layer-group" "No container images reporting" "Images appear when container telemetry includes container.image.name." (ESLink "https://monoscope.tech/docs/sdks/infrastructure/kubernetes" "Container setup guide") - , showFilterRail = True , resultSummary = Just $ "Showing " <> show (V.length images) <> " of " <> show (V.length allImages) <> " images" , exportName = Just "container-images" } } where + table = inventoryTable "images" url -- Two tags and a "+N" pill wrap rather than clip: a long tag used to cut the pill to "(". renderTags image = div_ [class_ "flex max-w-72 flex-wrap gap-1"] do forM_ (take 2 image.tags) $ \tag -> span_ [class_ "badge badge-xs badge-ghost shrink-0"] $ toHtml tag @@ -568,8 +533,9 @@ kubernetesGetH pid resourceM clusterM namespaceM statusM fromParam toParam since let resource = parseParam KubePods display resourceM url = deferUrl pid "/infrastructure/kubernetes" [("resource", resourceM), ("cluster", clusterM), ("namespace", namespaceM), ("status", statusM)] window body <- withDeferredBody deferredM "kubernetesContainer" url (tableSkeleton_ 8) do - allRows <- kubeRowsFromRows resource <$> infraSnapshot pid window - let rows = V.filter (\row -> matchesFilter clusterM row.cluster && matchesFilter namespaceM row.namespace && matchesFilter statusM (Just $ kubeStatusLabel row.status)) allRows + snapshot <- infraSnapshot pid window + let allRows = kubeRowsFromRows resource snapshot + rows = V.filter (\row -> matchesFilter clusterM row.cluster && matchesFilter statusM (Just $ kubeStatusLabel row.status)) $ kubeRowsFromRows resource $ V.filter (matchesFilter namespaceM . (.namespace)) snapshot pure $ kubernetesTable pid window url resource clusterM namespaceM statusM rows allRows addRespHeaders $ KubernetesPage $ PageCtx (infrastructureBW pid "Kubernetes" window bw) body @@ -580,9 +546,8 @@ newtype KubernetesGet = KubernetesPage (PageCtx (Deferred (Table KubeRow))) kubernetesTable :: Projects.ProjectId -> TimePicker.TimeWindow -> Text -> KubeResource -> Maybe Text -> Maybe Text -> Maybe Text -> V.Vector KubeRow -> V.Vector KubeRow -> Table KubeRow kubernetesTable pid window url resource clusterM namespaceM statusM rows allRows = - Table - { config = def{elemID = "kubernetesForm", containerId = Just "kubernetesContainer", addPadding = True, renderAsTable = True, bulkActionsInHeader = Just 0} - , columns = + table + { columns = [ col (resourceLabel resource) (\row -> div_ [class_ "flex min-w-0 items-center gap-2"] $ faSprite_ (kubeIcon resource) "solid" "h-3.5 w-3.5 shrink-0 text-iconNeutral" >> span_ [class_ "min-w-0 truncate font-medium text-textStrong", term "data-tippy-content" row.name] (toHtml $ bool id clusterLabel (resource == KubeClusters) row.name)) & withAttrs [class_ "min-w-56 w-full"] , col "Status" (statusBadge . (.status)) & withAttrs [class_ "w-28"] , col "Cluster" (\row -> maybe Containers.emDash_ (\value -> span_ [class_ "block truncate whitespace-nowrap text-textStrong", term "data-tippy-content" value] $ toHtml $ clusterLabel value) row.cluster) & withAttrs [class_ "w-36 max-lg:hidden"] @@ -597,27 +562,26 @@ kubernetesTable pid window url resource clusterM namespaceM statusM rows allRows ] , rows , features = - def - { search = Just ClientSide - , searchPlaceholder = Just $ "Search " <> display resource + table.features + { searchPlaceholder = Just $ "Search " <> display resource , rowAttrs = Just $ drawerRowAttrs_ . kubeDetailUrl - , header = Just $ timeRefreshListener_ "kubernetesContainer" url >> navTabStrip_ ViewTabs "Kubernetes resource" "tabs-sm mx-3 w-fit" [(toHtml $ resourceLabel r <> "s", infraUrl pid "/infrastructure/kubernetes" [("resource", display r)] window, r == resource) | r <- [minBound ..]] - , showFilterRail = True + , tabs = Just $ TableTabs "Kubernetes resource" [(resourceLabel r <> "s", infraUrl pid "/infrastructure/kubernetes" ([("resource", display r)] <> mapMaybe sequenceA [("cluster", clusterM), ("namespace", namespaceM), ("status", statusM)]) window, r == resource) | r <- [minBound ..]] , resultSummary = Just $ "Showing " <> show (V.length rows) <> " resources" , exportName = Just $ "kubernetes-" <> display resource - , tableHeaderActions = + , facets = Just $ facetActions (infraUrl pid "/infrastructure/kubernetes" [("resource", display resource)] window) "kubernetesContainer" - [ singleSelectFilter "Cluster" "cluster" clusterM $ facetValues (.cluster) allRows - , singleSelectFilter "Namespace" "namespace" namespaceM $ facetValues (.namespace) allRows - , singleSelectFilter "Status" "status" statusM $ facetValues (Just . kubeStatusLabel . (.status)) allRows + [ countedFilter "Cluster" "cluster" clusterM (maybeToList . (.cluster)) allRows + , countedFilter "Namespace" "namespace" namespaceM (maybeToList . (.namespace)) allRows + , countedFilter "Status" "status" statusM (one . kubeStatusLabel . (.status)) allRows ] , zeroState = Just $ ZeroState "cube" "No Kubernetes resources reporting" "Enable kubeletstats and k8s_cluster receivers to populate pods, workloads, and nodes." (ESLink "https://monoscope.tech/docs/sdks/infrastructure/kubernetes" "Kubernetes setup guide") } } where + table = inventoryTable "kubernetes" url kubeDetailUrl row = infraUrl pid "/infrastructure/kubernetes/detail" ([("resource", display resource), ("name", row.name)] <> mapMaybe sequenceA [("cluster", row.cluster), ("namespace", row.namespace)]) window @@ -702,7 +666,7 @@ hostMapGetH pid fillM groupM providerM regionM osM fromParam toParam sinceParam url = deferUrl pid "/infrastructure/host-map" [("fill", fillM), ("group", groupM), ("provider", providerM), ("region", regionM), ("os", osM)] window body <- withDeferredBody deferredM "hostMapContainer" url hostMapSkeleton_ do allHosts <- hostsFromRows <$> infraSnapshot pid window - let groups = groupHosts grouping $ applyHostFilters filters allHosts + let groups = groupRows (Just . hostGroupLabel grouping) $ applyHostFilters filters allHosts pure HostMapData{pid, window, fill = parseParam FillCPU display fillM, grouping, filters, allHosts, groups} addRespHeaders $ HostMapPage $ PageCtx (infrastructureBW pid "Host Map" window bw) body where @@ -714,36 +678,40 @@ hostMapGetH pid fillM groupM providerM regionM osM fromParam toParam sinceParam hostMap_ :: HostMapData -> Html () hostMap_ page = div_ [id_ "hostMapContainer", class_ "flex min-h-full flex-col bg-bgBase"] do timeRefreshListener_ "hostMapContainer" (deferUrl page.pid "/infrastructure/host-map" [("fill", Just $ display page.fill), ("group", Just $ hostGroupParam page.grouping), ("provider", page.filters.provider), ("region", page.filters.region), ("os", page.filters.osType)] page.window) - form_ [method_ "get", action_ $ "/p/" <> page.pid.toText <> "/infrastructure/host-map", class_ "flex flex-wrap items-end gap-3 border-b border-strokeWeak bg-bgRaised px-4 py-3 max-sm:grid max-sm:grid-cols-2"] do - TimePicker.timeHiddenInputs_ page.window.fromQuery page.window.toQuery page.window.sinceQuery - mapSelect "fill" "Fill by" (display page.fill) [(display f, case f of FillCPU -> "CPU usage"; FillMemory -> "Memory usage"; FillStorage -> "Storage usage") | f <- [minBound ..]] - mapSelect "group" "Group by" (hostGroupParam page.grouping) (map hostGroupOption [minBound ..]) - mapSelect "provider" "Provider" (fromMaybe "" page.filters.provider) $ ("", "All") : map dup (facetValues (.provider) page.allHosts) - mapSelect "region" "Region" (fromMaybe "" page.filters.region) $ ("", "All") : map dup (facetValues (.region) page.allHosts) - mapSelect "os" "Operating system" (fromMaybe "" page.filters.osType) $ ("", "All") : map dup (facetValues (.osType) page.allHosts) + div_ [class_ "flex flex-wrap items-center gap-3 border-b border-strokeWeak bg-bgRaised px-4 py-3 max-sm:grid max-sm:grid-cols-2"] do + selectControl_ $ SelectControl "fill" "Fill by" (display page.fill) [(display f, case f of { FillCPU -> "CPU usage"; FillMemory -> "Memory usage"; FillStorage -> "Storage usage" }) | f <- [minBound ..]] mapUrl "hostMapContainer" + selectControl_ $ SelectControl "group" "Group by" (hostGroupParam page.grouping) (map hostGroupOption [minBound ..]) mapUrl "hostMapContainer" div_ [class_ "ml-auto flex flex-wrap items-center gap-3 text-xs text-textWeak max-sm:col-span-2 max-sm:ml-0", Aria.label_ "Utilization legend"] do legend "bg-fillSuccess-strong" "Below 60%" legend "bg-fillWarning-strong" "60–85%" legend "bg-fillError-strong" "Above 85%" legend "bg-fillNeutral-strong" "No data" - if null page.groups - then - div_ [class_ "m-auto"] - $ emptyState_ - def{icon = Just "server", action = ESLink "https://monoscope.tech/docs/sdks/infrastructure/" "Set up host monitoring"} - "No hosts reporting" - "Enable host metrics or Kubernetes node telemetry to populate the map." - else div_ [class_ "flex flex-wrap items-start gap-4 p-4"] $ forM_ page.groups \(label, hosts) -> - let enlarged = length hosts <= 12 - in section_ [class_ $ "rounded-lg border border-strokeWeak bg-bgRaised p-3 shadow-sm " <> bool "min-w-80 flex-1" "w-fit min-w-72" enlarged] do - h2_ [class_ "mb-3 flex items-center gap-2 text-sm font-semibold text-textStrong"] $ toHtml label >> span_ [class_ "badge badge-xs badge-ghost"] (toHtml $ show (length hosts) <> " hosts") - div_ [class_ $ "flex flex-wrap " <> bool "gap-1" "gap-2" enlarged] $ forM_ (sortOn (.name) hosts) $ hostHex enlarged + div_ [class_ "flex items-start gap-4 p-4 max-lg:flex-col"] do + Facets.sidebar_ + . facetsConfig + $ facetActions + mapUrl + "hostMapContainer" + [ countedFilter "Provider" "provider" page.filters.provider (maybeToList . (.provider)) page.allHosts + , countedFilter "Region" "region" page.filters.region (maybeToList . (.region)) page.allHosts + , countedFilter "OS" "os" page.filters.osType (maybeToList . (.osType)) page.allHosts + ] + div_ [class_ "min-w-0 w-full flex-1"] do + if null page.groups + then + div_ [class_ "m-auto"] + $ emptyState_ + def{icon = Just "server", action = ESLink "https://monoscope.tech/docs/sdks/infrastructure/" "Set up host monitoring"} + "No hosts reporting" + "Enable host metrics or Kubernetes node telemetry to populate the map." + else div_ [class_ "flex flex-wrap items-start gap-4"] $ forM_ page.groups \(label, hosts) -> + let enlarged = length hosts <= 12 + in section_ [class_ $ "rounded-lg border border-strokeWeak bg-bgRaised p-3 shadow-sm " <> bool "min-w-80 flex-1" "w-fit min-w-72" enlarged] do + h2_ [class_ "mb-3 flex items-center gap-2 text-sm font-semibold text-textStrong"] $ toHtml label >> span_ [class_ "badge badge-xs badge-ghost"] (toHtml $ show (length hosts) <> " hosts") + div_ [class_ $ "flex flex-wrap " <> bool "gap-1" "gap-2" enlarged] $ forM_ (sortOn (.name) hosts) $ hostHex enlarged where + mapUrl = infraUrl page.pid "/infrastructure/host-map" ([("fill", display page.fill), ("group", hostGroupParam page.grouping)] <> mapMaybe sequenceA [("provider", page.filters.provider), ("region", page.filters.region), ("os", page.filters.osType)]) page.window legend colour label = span_ [class_ "inline-flex items-center gap-1.5"] $ span_ [class_ $ "h-3 w-3 " <> colour, style_ hexClipPath] mempty >> toHtml label - mapSelect :: Text -> Text -> Text -> [(Text, Text)] -> Html () - mapSelect field label current options = label_ [class_ "flex flex-col gap-1 text-xs text-textWeak"] do - toHtml label - select_ [name_ field, class_ "select select-sm min-w-44 border-strokeWeak bg-bgBase text-sm text-textStrong max-sm:h-11 max-sm:min-w-0 max-sm:w-full", onchange_ "this.form.requestSubmit()"] $ forM_ options \(value, title) -> option_ ([value_ value] <> [selected_ "" | value == current]) $ toHtml title hostHex enlarged host = div_ [class_ $ "flex flex-col items-center gap-1 " <> bool "" "w-24" enlarged] do let value = case page.fill of FillCPU -> host.cpuPct; FillMemory -> host.memoryPct; FillStorage -> host.storagePct button_ diff --git a/src/Pages/LogExplorer/Log.hs b/src/Pages/LogExplorer/Log.hs index 654716a09..53be42433 100644 --- a/src/Pages/LogExplorer/Log.hs +++ b/src/Pages/LogExplorer/Log.hs @@ -39,7 +39,6 @@ import Data.Aeson.Types qualified as AET import Data.Default (Default, def) import Data.Effectful.Hasql (Hasql) import Data.Effectful.Hasql qualified as Hasql -import Data.Foldable.WithIndex (iforM_) import Data.HashMap.Strict qualified as HM import Data.List qualified as L import Data.Map.Strict qualified as Map @@ -75,10 +74,12 @@ import Models.Telemetry.Schema qualified as Schema import Models.Telemetry.Telemetry qualified as Telemetry import NeatInterpolation (text) import Pages.BodyWrapper (BWConfig (..), PageCtx (..), checkFreeTierStatus, mkPageCtx, pageActions, pageTitle) -import Pages.Components (FieldCfg (..), FieldSize (..), facetOption_, facetRail_, facetSection_, formField_, keyboardActivateAttr_, lazyPanel_, localTimeFmt_, resetFormOnSuccessAttr_, resizer_) +import Pages.Components (FieldCfg (..), FieldSize (..), formField_, keyboardActivateAttr_, lazyPanel_, localTimeFmt_, resetFormOnSuccessAttr_, resizer_) import Pages.LogExplorer.LogItem qualified as LogItem import Pages.Monitors qualified as AlertUI import Pkg.AI qualified as AI +import Pkg.Components.Facets (FacetChoice (..), FacetContent (..), FacetNode (..), FacetOverflow (..), facetHeadCount, facetNode_, facetTail_) +import Pkg.Components.Facets qualified as Facets import Pkg.Components.LogQueryBox (LogQueryBoxConfig (..), VizSurface (..), VizType (..), enrichSchemaWithFacets, logQueryBox_, visTypes) import Pkg.Components.TimePicker qualified as Components import Pkg.Components.Widget (WidgetAxis (..), WidgetType (WTTimeseries, WTTimeseriesLine)) @@ -99,7 +100,7 @@ import System.Types import Text.Casing (fromAny, toKebab) import Text.Megaparsec (parseMaybe) import Text.Slugify (slugify) -import Utils (FieldAction (..), FieldMenuCtx (..), LoadingSize (..), LoadingType (..), encodeText, explorerNavTabs_, faSprite_, fieldContextMenuItems_, fieldMenuPanel_, getDurationNSMS, getServiceColors, levelFillColor, listToIndexHashMap, loadingIndicator_, lookupVecBy, lookupVecNonEmptyText, lookupVecTextByKey, methodFillColor, nonEmptyT, popoverTrigger_, prettyPrintCount, sanitizeBackendError, serviceFillColor, showFFloat', statusFillColorText, toUriStr) +import Utils (FieldAction (..), FieldMenuCtx (..), encodeText, explorerNavTabs_, faSprite_, fieldContextMenuItems_, fieldMenuPanel_, getDurationNSMS, getServiceColors, levelFillColor, listToIndexHashMap, lookupVecBy, lookupVecNonEmptyText, lookupVecTextByKey, methodFillColor, nonEmptyT, popoverTrigger_, prettyPrintCount, sanitizeBackendError, serviceFillColor, showFFloat', statusFillColorText, toUriStr) import Web.FormUrlEncoded (FromForm) import Web.HttpApiData (parseUrlPiece) @@ -513,105 +514,72 @@ facetGroupPaths g = map (.path) $ Map.findWithDefault [] g facetsByGroup -- | Render facet data for Log Explorer sidebar in a compact format. -- The facet counts are scaled in the upstream summary based on the selected time range. renderFacets :: FacetSummary -> Html () -renderFacets facetSummary = - forM_ (universe :: [FacetGroup]) \facetGroup -> renderFacetGroup (facetGroup == FGCommon) facetGroup facetSummary +renderFacets = mapM_ facetNode_ . facetGroups --- | A group shell is cheap enough for the initial sidebar. Only Common Filters --- includes its fields immediately; every closed group fetches and replaces --- its shell with the server-rendered Lucid fragment on first open. -renderFacetGroup :: Bool -> FacetGroup -> FacetSummary -> Html () -renderFacetGroup loaded facetGroup facetSummary = - facetSection_ loaded "facet-section-group" attrs (span_ [class_ "font-medium text-sm"] $ toHtml $ facetGroupLabel facetGroup) body - where - attrs = - if loaded - then [] - else - [ hxGet_ url - , hxTrigger_ "toggle[target.open] once" - , hxTarget_ "this" - , hxSwap_ "outerHTML" - , hxIndicator_ "find .facet-group-loader" - ] - body - | loaded = div_ [class_ "facets-container"] $ renderFacetFields facetGroup facetSummary - | otherwise = div_ [class_ "facet-group-loader htmx-indicator flex h-8 items-center justify-center"] $ loadingIndicator_ LdXS LdSpinner - url = "/p/" <> facetSummary.projectId <> "/log_explorer/facets?group=" <> facetGroupParam facetGroup +facetGroups :: FacetSummary -> [FacetNode] +facetGroups summary = [facetGroupNode (g == FGCommon) g summary | g <- universe] --- | Facet values shown before the "+ More" fold. 'renderFacetFields' takes this --- many and 'renderFacetTail' drops exactly the same many — two different numbers --- here would make the tail repeat or skip values. -facetHeadCount :: Int -facetHeadCount = 5 - - -renderFacetFields :: FacetGroup -> FacetSummary -> Html () -renderFacetFields facetGroup facetSummary = do - let (FacetData facetMap) = facetSummary.facetJson - facets = Map.findWithDefault [] facetGroup facetsByGroup - -- Checkbox↔query sync lives in web-components/src/main.ts (syncFacetCheckboxes), - -- wired to `update-query` + `htmx:after:swap` so swapped-in facets re-sync. - iforM_ facets \idx facet -> do - let values = HM.lookupDefault [] facet.path facetMap - open = facetGroup == FGCommon && idx < 5 && not (null values) - (visibleValues, hiddenValues) = splitAt facetHeadCount values - hiddenCount = length hiddenValues - facetSection_ - open - "" - [] - ( div_ [class_ "flex items-center justify-between gap-2"] do - span_ [class_ "truncate text-sm font-normal", term "data-tippy-content" facet.path] $ toHtml facet.label - -- Bubble-halt so the ⋮ popover (and its menu items) don't toggle the
. - div_ [class_ "inline-block", [__|on click halt the event's bubbling|]] do - button_ ([type_ "button", class_ "cursor-pointer rounded p-1 hover:bg-fillWeak", Aria.label_ "Facet options"] <> popoverTrigger_ (slugify facet.path)) - $ faSprite_ "ellipsis-vertical" "regular" "w-3 h-3" - ul_ ([class_ "dropdown menu p-2 shadow-sm bg-bgRaised rounded-box w-96 border border-strokeWeak z-50", term "data-field-path" facet.path] <> fieldMenuPanel_ (slugify facet.path)) - $ fieldContextMenuItems_ (StaticField facet.path Nothing) [FCopyField, FDivider, FGroupBy, FViewPatterns, FDivider, FAddColumn] - ) - $ div_ [class_ "facet-values pl-5 pr-1 mb-1 space-y-1"] do - if null values - then div_ [class_ "facet-empty px-1 py-1 text-xs italic text-textWeak"] "no values in window" - else forM_ visibleValues (renderFacetValue facet) - when (hiddenCount > 0) - $ div_ [class_ "facet-tail"] - $ button_ - [ type_ "button" - , class_ "facet-more text-textBrand text-xs px-1 py-0.5 cursor-pointer hover:underline" - , hxGet_ $ "/p/" <> facetSummary.projectId <> "/log_explorer/facets?field=" <> toUriStr facet.path - , hxTarget_ "closest .facet-tail" +facetGroupNode :: Bool -> FacetGroup -> FacetSummary -> FacetNode +facetGroupNode loaded facetGroup summary = + FacetNode + { label = facetGroupLabel facetGroup + , path = Nothing + , expanded = loaded + , attrs = + if loaded + then [] + else + [ hxGet_ $ "/p/" <> summary.projectId <> "/log_explorer/facets?group=" <> facetGroupParam facetGroup + , hxTrigger_ "toggle[target.open] once" + , hxTarget_ "this" , hxSwap_ "outerHTML" + , hxIndicator_ "find .facet-group-loader" ] - $ toHtml - $ "+ More (" - <> prettyPrintCount hiddenCount - <> ")" + , actions = Nothing + , content = if loaded then FacetChildren fields else FacetLoading + } + where + (FacetData valuesByPath) = summary.facetJson + fields = + [ FacetNode + { label = facet.label + , path = Just facet.path + , expanded = facetGroup == FGCommon && index < 5 && not (null values) + , attrs = [] + , actions = Just do + button_ ([type_ "button", class_ "cursor-pointer rounded p-1 hover:bg-fillWeak", Aria.label_ "Facet options"] <> popoverTrigger_ (slugify facet.path)) $ faSprite_ "ellipsis-vertical" "regular" "w-3 h-3" + ul_ ([class_ "dropdown menu p-2 shadow-sm bg-bgRaised rounded-box w-96 border border-strokeWeak z-50", term "data-field-path" facet.path] <> fieldMenuPanel_ (slugify facet.path)) + $ fieldContextMenuItems_ (StaticField facet.path Nothing) [FCopyField, FDivider, FGroupBy, FViewPatterns, FDivider, FAddColumn] + , content = + FacetValues (map (facetChoice facet) values) + $ FetchValues + [ hxGet_ $ "/p/" <> summary.projectId <> "/log_explorer/facets?field=" <> toUriStr facet.path + , hxTarget_ "closest .facet-tail" + , hxSwap_ "outerHTML" + ] + } + | (index, facet) <- zip [0 :: Int ..] $ Map.findWithDefault [] facetGroup facetsByGroup + , let values = HM.lookupDefault [] facet.path valuesByPath + ] -renderFacetValue :: Facet -> FacetValue -> Html () -renderFacetValue f (FacetValue val count) = - facetOption_ - "facet-item max-md:min-h-9" - [] - ( do - input_ - [ type_ "checkbox" - , class_ "checkbox checkbox-xs max-md:checkbox-sm" - , -- Via queryEditorCall, not the element directly: Monaco is loaded lazily, so on a fresh - -- page load is still un-upgraded and `.toggleSubQuery` doesn't exist yet. - term "hx-on:click" "window.queryEditorCall('toggleSubQuery', this.dataset.field, this.dataset.value)" - , Aria.label_ (f.path <> " equals " <> val) - , term "data-tippy-content" (f.path <> " == \"" <> val <> "\"") - , term "data-field" f.path - , term "data-value" val - ] - let colorClass = f.color val - unless (T.null colorClass) $ span_ [class_ $ colorClass <> " shrink-0 w-0.5 h-3 rounded-sm"] "" - span_ [class_ "facet-value truncate text-xs", term "data-tippy-content" val] $ toHtml val - ) - (span_ [class_ "facet-count shrink-0 text-xs tabular-nums text-textWeak"] $ toHtml $ prettyPrintCount count) +facetChoice :: Facet -> FacetValue -> FacetChoice +facetChoice f (FacetValue val count) = + FacetChoice + { label = val + , multiSelect = True + , inputAttrs = + [ term "hx-on:click" "window.queryEditorCall('toggleSubQuery', this.dataset.field, this.dataset.value)" + , Aria.label_ (f.path <> " equals " <> val) + , term "data-tippy-content" (f.path <> " == \"" <> val <> "\"") + , term "data-field" f.path + , term "data-value" val + ] + , marker = if T.null (f.color val) then Nothing else Just $ span_ [class_ $ f.color val <> " shrink-0 w-0.5 h-3 rounded-sm"] "" + , count = Just $ prettyPrintCount count + } -- | Descendants of a page of rows, for the trace tree: seed from each row's own @@ -1022,7 +990,7 @@ logExplorerFacetsH pid fieldM groupM = do (div_ [class_ "px-1 py-4 text-xs italic text-textWeak"] "Filters are still being built for this project.") ( \summary -> case (fieldM, facetGroupM) of (Just field, _) -> renderFacetTail field summary - (_, Just facetGroup) -> renderFacetGroup True facetGroup summary + (_, Just facetGroup) -> facetNode_ $ facetGroupNode True facetGroup summary _ -> renderFacets summary ) facetSummary @@ -1032,12 +1000,7 @@ logExplorerFacetsH pid fieldM groupM = do whenJust (find ((== field) . (.path)) facetDefs) \facet -> do let (FacetData facetMap) = facetSummary.facetJson values = drop facetHeadCount $ HM.lookupDefault [] field facetMap - count = prettyPrintCount $ length values - details_ [class_ "facet-tail group", open_ ""] do - summary_ [class_ "list-none cursor-pointer text-textBrand text-xs px-1 py-0.5 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-strokeBrand-strong"] do - span_ [class_ "group-open:hidden"] $ toHtml $ "+ More (" <> count <> ")" - span_ [class_ "hidden group-open:inline"] $ toHtml $ "− Less (" <> count <> ")" - div_ [class_ "space-y-1"] $ forM_ values (renderFacetValue facet) + facetTail_ True $ map (facetChoice facet) values -- | Structured verdict for the query editor. It underlines @column@..@width@ and @@ -1689,16 +1652,14 @@ apiLogsPage page = do -- No `contain:layout` here: it makes this a containing block for fixed/anchored -- descendants, which clips the facet action popover (top layer) to the sidebar. facetsPanel = - facetRail_ - (Just "facets-container") - "w-68 will-change-[width] text-sm text-textWeak shrink-0 h-full overflow-y-scroll max-md:w-full max-md:shrink max-md:max-h-[55vh] max-md:border-b max-md:border-strokeWeak group-has-[.toggle-filters:checked]/pg:max-w-0 group-has-[.toggle-filters:checked]/pg:overflow-hidden max-md:group-has-[.toggle-filters:checked]/pg:max-h-0" - "Search filters" - Nothing - $ div_ [id_ "facets-list"] - $ maybe - (div_ [class_ "px-1 py-4 text-xs italic text-textWeak"] "Filters are still being built for this project.") - renderFacets - page.facetSummary + Facets.sidebar_ + Facets.Config + { elemId = "facets-container" + , extraClass = "will-change-[width] h-full overflow-y-scroll max-md:shrink max-md:max-h-[55vh] max-md:border-b max-md:border-strokeWeak group-has-[.toggle-filters:checked]/pg:max-w-0 group-has-[.toggle-filters:checked]/pg:overflow-hidden max-md:group-has-[.toggle-filters:checked]/pg:max-h-0" + , clear = Just [[__|on click repeat for cb in in closest .facet-rail call cb.click() end|]] + , content = facetGroups <$> page.facetSummary + , layout = Facets.Plain + } logsListPanel = div_ [class_ "@container grow will-change-[width] contain-[layout_style] relative flex flex-col shrink-1 min-w-0 w-full h-full ", id_ "logs_list_container"] do rowCountHeader diff --git a/src/Pkg/Components/Facets.hs b/src/Pkg/Components/Facets.hs new file mode 100644 index 000000000..bb4628dce --- /dev/null +++ b/src/Pkg/Components/Facets.hs @@ -0,0 +1,112 @@ +module Pkg.Components.Facets (Config (..), Layout (..), FacetNode (..), FacetContent (..), FacetOverflow (..), FacetChoice (..), sidebar_, facetNode_, facetChoice_, facetTail_, facetHeadCount) where + +import Lucid +import Lucid.Hyperscript (__) +import Pages.Components (filterInputAttr_, searchInput_) +import Relude +import Utils (LoadingSize (..), LoadingType (..), faSprite_, loadingIndicator_, prettyPrintCount) + + +data Layout = Plain | Collapsible + + +data Config = Config + { elemId :: Text + , extraClass :: Text + , clear :: Maybe [Attribute] + , content :: Maybe [FacetNode] + , layout :: Layout + } + + +-- | Explorer's facet sidebar, also embedded by inventory tables and the host map. +sidebar_ :: Config -> Html () +sidebar_ cfg = case cfg.layout of + Plain -> rail "" + Collapsible -> details_ [class_ "w-68 shrink-0 max-lg:w-full lg:[&::details-content]:block lg:[&::details-content]:[content-visibility:visible]"] do + summary_ [class_ "flex cursor-pointer list-none items-center gap-2 rounded px-2 py-2 text-xs font-semibold text-textStrong hover:bg-fillWeak lg:hidden [&::-webkit-details-marker]:hidden"] "Filters" + rail " max-lg:w-full" + where + rail extra = div_ [class_ $ "facet-rail group/rail flex w-68 shrink-0 flex-col gap-2 text-sm text-textWeak max-md:w-full " <> cfg.extraClass <> extra, data_ "component" "facet-rail", id_ cfg.elemId] do + searchInput_ + "sticky top-0 z-10 h-9 w-[calc(100%-1rem)] mx-2 border-strokeStrong bg-bgBase" + "Search filters" + [name_ "facet-search", filterInputAttr_ $ "#" <> cfg.elemId <> " :is(.facet-item,.facet-section)"] + forM_ cfg.clear $ \attrs -> button_ ([type_ "button", class_ "hidden items-center justify-between rounded px-2 py-1.5 text-xs text-textBrand hover:bg-fillWeak group-has-[.facet-item_input:checked]/rail:flex"] <> attrs) $ "Clear all" >> faSprite_ "xmark" "regular" "h-3 w-3" + div_ [class_ "facets-container"] $ maybe (div_ [class_ "px-1 py-4 text-xs italic text-textWeak"] "Filters are still being built for this project.") (mapM_ facetNode_) cfg.content + + +data FacetNode = FacetNode + { label :: Text + , path :: Maybe Text + , expanded :: Bool + , attrs :: [Attribute] + , actions :: Maybe (Html ()) + , content :: FacetContent + } + + +data FacetContent + = FacetValues [FacetChoice] FacetOverflow + | FacetChildren [FacetNode] + | FacetLoading + + +facetNode_ :: FacetNode -> Html () +facetNode_ node = do + let grouped = case node.content of FacetValues{} -> False; FacetChildren{} -> True; FacetLoading -> True + details_ ([class_ $ "facet-section block border-t border-strokeWeak [&[open]>summary_.facet-chevron]:rotate-0 " <> bool "" "facet-section-group" grouped, data_ "component" "facet-section"] <> node.attrs <> [open_ "" | node.expanded]) do + summary_ [class_ "flex cursor-pointer list-none items-center gap-2 rounded px-2 py-2 text-textStrong hover:bg-fillWeak [&::-webkit-details-marker]:hidden"] do + faSprite_ "chevron-down" "regular" "facet-chevron h-2.5 w-2.5 shrink-0 -rotate-90 transition-transform" + div_ [class_ "flex min-w-0 flex-1 items-center justify-between gap-2"] do + span_ ([class_ $ "truncate text-sm " <> bool "font-normal" "font-medium" grouped] <> [term "data-tippy-content" p | p <- maybeToList node.path]) $ toHtml node.label + forM_ node.actions $ \actions -> div_ [class_ "inline-block", [__|on click halt the event's bubbling|]] actions + case node.content of + FacetChildren children -> div_ [class_ "facets-container"] $ mapM_ facetNode_ children + FacetLoading -> div_ [class_ "facet-group-loader htmx-indicator flex h-8 items-center justify-center"] $ loadingIndicator_ LdXS LdSpinner + FacetValues choices overflow -> div_ [class_ "facet-values pl-5 pr-1 mb-1 space-y-1"] do + let (visible, hidden) = splitAt facetHeadCount choices + moreLabel = "+ More (" <> prettyPrintCount (length hidden) <> ")" + if null choices + then div_ [class_ "facet-empty px-1 py-1 text-xs italic text-textWeak"] "no values in window" + else forM_ visible facetChoice_ + unless (null hidden) $ case overflow of + ExpandValues -> facetTail_ False hidden + FetchValues attrs -> div_ [class_ "facet-tail"] $ button_ ([type_ "button", class_ "facet-more text-textBrand text-xs px-1 py-0.5 cursor-pointer hover:underline"] <> attrs) $ toHtml moreLabel + + +facetTail_ :: Bool -> [FacetChoice] -> Html () +facetTail_ expanded choices = details_ ([class_ "facet-tail group/tail"] <> [open_ "" | expanded]) do + summary_ [class_ "list-none cursor-pointer text-textBrand text-xs px-1 py-0.5 hover:underline focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-strokeBrand-strong"] do + span_ [class_ "group-open/tail:hidden"] $ toHtml $ "+ More (" <> count <> ")" + span_ [class_ "hidden group-open/tail:inline"] $ toHtml $ "− Less (" <> count <> ")" + div_ [class_ "space-y-1"] $ mapM_ facetChoice_ choices + where + count = prettyPrintCount $ length choices + + +-- | Local inventories expand in place; Explorer fetches the tail lazily. +data FacetOverflow = ExpandValues | FetchValues [Attribute] + + +-- | The initial field and its lazy tail must use the same cutoff. +facetHeadCount :: Int +facetHeadCount = 5 + + +data FacetChoice = FacetChoice + { label :: Text + , multiSelect :: Bool + , inputAttrs :: [Attribute] + , marker :: Maybe (Html ()) + , count :: Maybe Text + } + + +facetChoice_ :: FacetChoice -> Html () +facetChoice_ choice = label_ [class_ "facet-item flex min-h-7 cursor-pointer items-center justify-between gap-2 rounded px-2 py-1 hover:bg-fillWeak max-md:min-h-9", data_ "component" "facet-option"] do + div_ [class_ "flex min-w-0 flex-1 items-center gap-2"] do + input_ $ [type_ $ bool "radio" "checkbox" choice.multiSelect, class_ $ bool "radio radio-xs max-md:radio-sm" "checkbox checkbox-xs max-md:checkbox-sm" choice.multiSelect] <> choice.inputAttrs + sequence_ choice.marker + span_ [class_ "facet-value truncate text-xs", term "data-tippy-content" choice.label] $ toHtml choice.label + forM_ choice.count $ \n -> span_ [class_ "facet-count shrink-0 text-xs tabular-nums text-textWeak"] $ toHtml n diff --git a/src/Pkg/Components/Table.hs b/src/Pkg/Components/Table.hs index b76bc4f1d..55f1ff97c 100644 --- a/src/Pkg/Components/Table.hs +++ b/src/Pkg/Components/Table.hs @@ -1,11 +1,16 @@ module Pkg.Components.Table ( Table (..), + inventoryTable, TableRows (..), TableResponse (..), Column (..), Config (..), Features (..), - defaultFeaturesAreInert, + SelectControl (..), + TableTabs (..), + selectControl_, + facetsConfig, + countedFilter, SearchMode (..), BulkAction (..), TabFilter (..), @@ -21,8 +26,6 @@ module Pkg.Components.Table ( TableHeaderActions (..), FilterMenu (..), FilterOption (..), - facetValues, - singleSelectFilter, multiSelectFilter, facetActions, -- Sorting types and utilities @@ -37,8 +40,10 @@ module Pkg.Components.Table ( ) where import Data.Default (Default (..)) +import Data.Foldable.WithIndex (iforM_) import Data.List (lookup) import Data.List.NonEmpty qualified as NE +import Data.Map.Strict qualified as Map import Data.Text qualified as T import Data.Text.Lazy qualified as TL import Data.Vector qualified as V @@ -48,9 +53,11 @@ import Lucid.Aria qualified as Aria import Lucid.Htmx import Lucid.Hyperscript (__) import Pages.BodyWrapper (PageCtx) -import Pages.Components (EmptyStateAction (..), EmptyStateCfg (..), detailsClosedBelowAttr_, emptyState_, facetOption_, facetRail_, facetSection_, filterInputAttr_, keyboardActivateAttr_, searchInput_) +import Pages.Components (EmptyStateAction (..), EmptyStateCfg (..), emptyState_, filterInputAttr_, keyboardActivateAttr_, searchInput_, timeRefreshListener_) +import Pkg.Components.Facets (FacetChoice (..), FacetContent (..), FacetNode (..), FacetOverflow (..), facetChoice_) +import Pkg.Components.Facets qualified as Facets import Relude -import Utils (TabStrip (..), deleteParam, faSprite_, navTabAttrs, navTabStrip_, popoverPanel_, popoverTrigger_, toUriStr) +import Utils (TabStrip (..), deleteParam, faSprite_, navTabAttrs, navTabStrip_, popoverPanel_, popoverTrigger_, prettyPrintCount, toUriStr) -- Core Types @@ -77,6 +84,18 @@ data Table a = Table } +inventoryTable :: Text -> Text -> Table a +inventoryTable name url = + Table + { config = def{elemID = name <> "Form", containerId = Just target, addPadding = True, renderAsTable = True} + , columns = [] + , rows = V.empty + , features = def{header = Just $ timeRefreshListener_ target url, search = Just ClientSide, searchPlaceholder = Just $ "Search " <> name, customizeColumns = True, exportName = Just name} + } + where + target = name <> "Container" + + -- TableRows for pagination - renders rows + pagination footer type role TableRows nominal data TableRows a = TableRows @@ -104,6 +123,11 @@ data Pagination = Pagination data SearchMode = ClientSide | ServerSide Text +-- | Features default to no optional behavior. +-- +-- >>> let html = renderText $ toHtml (Table def [] V.empty def :: Table ()) +-- >>> any @[] (`TL.isInfixOf` html) ["facet-rail", " Text) , rowId :: Maybe (a -> Text) @@ -121,42 +145,23 @@ data Features a = Features , zeroState :: Maybe ZeroState , header :: Maybe (Html ()) , treeConfig :: Maybe (TreeConfig a) - , showFilterRail :: Bool + , facets :: Maybe TableHeaderActions , resultSummary :: Maybe Text , exportName :: Maybe Text + , customizeColumns :: Bool + , grouping :: Maybe SelectControl + , tabs :: Maybe TableTabs } - -- Every field's default is the generic one (Nothing / [] / False). The - -- hand-written instance was 21 lines that had to be edited in lockstep with the - -- record; derived, a newly added field cannot be forgotten. The doctest on - -- 'defaultFeaturesAreInert' pins that the derived defaults match what the - -- hand-written instance produced — every table's behaviour depends on it. deriving stock (Generic) deriving anyclass (Default) -- $setup --- >>> :set -XTypeApplications +-- >>> :set -XTypeApplications -XOverloadedRecordDot -XOverloadedStrings -- >>> import Data.Default (def) - - --- | The derived 'Default' for 'Features' must stay inert: no row link, no bulk --- actions, no filter rail. This is what the hand-written instance guaranteed, and --- what every @def{...}@ table construction in the codebase assumes. --- --- >>> defaultFeaturesAreInert --- True -defaultFeaturesAreInert :: Bool -defaultFeaturesAreInert = - and - [ isNothing d.rowLink - , isNothing d.search - , isNothing d.pagination - , isNothing d.rowGroup - , null d.bulkActions - , not d.showFilterRail - ] - where - d = def @(Features ()) +-- >>> import Data.Vector qualified as V +-- >>> import Data.Text.Lazy qualified as TL +-- >>> import Lucid (renderText, toHtml) data Config = Config @@ -183,6 +188,22 @@ data Config = Config } +data SelectControl = SelectControl + { name :: Text + , label :: Text + , current :: Text + , options :: [(Text, Text)] -- (value, label) + , baseUrl :: Text + , targetId :: Text + } + + +data TableTabs = TableTabs + { label :: Text + , options :: [(Text, Text, Bool)] -- (label, url, active) + } + + -- Supporting Types -- | A toolbar action over the checked rows. With @choices@ it opens a menu and each @@ -280,38 +301,30 @@ data FilterOption = FilterOption { label :: Text , value :: Text , isActive :: Bool + , count :: Maybe Int } deriving stock (Eq, Show) --- | Sorted distinct values from the unfiltered result, so choosing one facet does --- not empty the menus of the others. --- --- >>> facetValues snd (V.fromList [("a", Just "b"), ("c", Just "a"), ("d", Nothing)]) --- ["a","b"] -facetValues :: (a -> Maybe Text) -> V.Vector a -> [Text] -facetValues getter = sortNub . filter (not . T.null) . mapMaybe getter . V.toList - - --- | A facet menu over @values@, marking those in @selected@ active. Single-select is the --- same menu with at most one selection, so both go through here rather than each call site --- assembling 'FilterMenu'/'FilterOption' by hand. -filterMenu :: Bool -> Text -> Text -> [Text] -> [Text] -> FilterMenu -filterMenu multiSelect label paramName selected values = +multiSelectFilter :: Text -> Text -> [Text] -> [Text] -> FilterMenu +multiSelectFilter label paramName selected values = FilterMenu { label , paramName - , options = [FilterOption value value (value `elem` selected) | value <- values] - , multiSelect + , options = [FilterOption value value (value `elem` selected) Nothing | value <- values] + , multiSelect = True } -singleSelectFilter :: Text -> Text -> Maybe Text -> [Text] -> FilterMenu -singleSelectFilter label paramName selected = filterMenu False label paramName (maybeToList selected) - - -multiSelectFilter :: Text -> Text -> [Text] -> [Text] -> FilterMenu -multiSelectFilter = filterMenu True +-- | Count each inventory row once per value, before applying any filters. +-- +-- >>> map (\o -> (o.value, o.count)) (countedFilter "Runtime" "runtime" Nothing id (V.fromList [["a", "a"], ["a", "b"], [""]])).options +-- [("a",Just 2),("b",Just 1)] +countedFilter :: Text -> Text -> Maybe Text -> (a -> [Text]) -> V.Vector a -> FilterMenu +countedFilter label paramName selected valuesOf rows = FilterMenu label paramName options False + where + counts = Map.fromListWith (+) [(value, 1) | row <- V.toList rows, value <- ordNub (valuesOf row), not (T.null value)] + options = [FilterOption value value (Just value == selected) (Just count) | (value, count) <- Map.toAscList counts] -- | Header actions for a filter-only inventory table. The active-filter chips are read back @@ -465,7 +478,8 @@ renderTable tbl = let isEmpty = V.null tbl.rows && isJust tbl.features.zeroState tableMain = do sequence_ tbl.features.header - when (isJust tbl.features.resultSummary || isJust tbl.features.exportName) $ renderResultToolbar tbl + forM_ tbl.features.tabs $ \tabs -> navTabStrip_ ViewTabs tabs.label "tabs-sm mx-3 w-fit" [(toHtml label, url, active) | (label, url, active) <- tabs.options] + when (isJust tbl.features.resultSummary || isJust tbl.features.exportName || tbl.features.customizeColumns || isJust tbl.features.grouping || isJust tbl.features.facets) $ renderResultToolbar tbl -- Scrolls horizontally rather than clipping. `overflow-hidden` silently cut off whatever -- did not fit: Containers, Kubernetes and Images each need 1460-1820px and get ~1250 -- with the facet rail open, so 200-570px of columns were unreachable — no scrollbar, no @@ -485,13 +499,13 @@ renderTable tbl = whenJust tbl.features.search \_ -> span_ [id_ "searchIndicator", class_ "htmx-indicator loading loading-sm loading-dots mx-auto"] "" div_ [id_ "rowsContainer", class_ divCls] do renderRows tbl - tableContent = div_ [class_ $ tbl.config.containerClasses <> bool " pb-24" "" isEmpty, id_ $ tbl.config.elemID <> "_page"] do + tableContent = div_ ([class_ $ tbl.config.containerClasses <> bool " pb-24" "" isEmpty, id_ $ tbl.config.elemID <> "_page"] <> [data_ "table-columns" tbl.config.elemID | tbl.features.customizeColumns]) do unless isEmpty $ whenJust tbl.features.search $ renderSearch tbl.config.elemID (fromMaybe "Search" tbl.features.searchPlaceholder) - if tbl.features.showFilterRail - then div_ [class_ "flex items-start gap-4 max-lg:flex-col"] do - whenJust tbl.features.tableHeaderActions renderFilterRail - div_ [class_ "min-w-0 flex-1 space-y-3"] tableMain - else tableMain + case tbl.features.facets of + Just facets -> div_ [class_ "flex items-start gap-4 max-lg:flex-col"] do + Facets.sidebar_ $ facetsConfig facets + div_ [class_ "min-w-0 w-full flex-1 space-y-3"] tableMain + Nothing -> tableMain -- Pagination footer outside the raised surface whenJust tbl.features.pagination renderPaginationFooter when (isJust tbl.features.treeConfig) treeScript @@ -527,7 +541,7 @@ renderRows tbl thAttrs = [class_ $ " " <> tbl.config.thClasses <> " " <> fromMaybe "" c.align <> bool "" " cursor-pointer hover:bg-fillWeak" (isJust sortable)] sortAttrs = foldMap (\(field, cfg) -> swapTarget_ cfg.targetId (toggleSortUrl cfg field)) sortable sortOrder = sortable >>= \(field, cfg) -> lookup cfg.currentSort [("-" <> field, Desc), ("+" <> field, Asc)] - th_ (c.attrs <> thAttrs <> sortAttrs <> [data_ "column-index" $ show idx]) do + th_ (c.attrs <> thAttrs <> sortAttrs <> [data_ "column-key" c.name]) do span_ [class_ $ "flex items-center gap-2 min-w-0" <> bool "" " flex-wrap" (tbl.config.bulkActionsInHeader == Just idx)] do span_ [class_ $ bool "max-md:hidden" "" (idx > 0)] $ toHtml c.name sequence_ c.headerExtra @@ -550,24 +564,32 @@ renderRows tbl -- so htmx-swapped pages stay markup-identical to page 1. renderBody :: [Attribute] -> Table a -> Html () renderBody extra tbl - | tbl.config.renderAsTable = tbody_ (extra <> [class_ "stagger-fade"]) $ maybe (V.mapM_ (renderTableRow tbl) tbl.rows) groupedRows tbl.features.rowGroup - | otherwise = div_ [class_ "stagger-fade"] $ V.mapM_ (renderListRow tbl) tbl.rows + | not tbl.config.renderAsTable = div_ [class_ "stagger-fade"] $ V.mapM_ (renderListRow tbl) tbl.rows + | Just groupOf <- tbl.features.rowGroup = + if isJust tbl.features.grouping then groupedRows groupOf else body $ groupedRows groupOf + | otherwise = body $ V.mapM_ (renderTableRow tbl) tbl.rows where - groupedRows groupOf = - forM_ (sortWith (fst . head) $ NE.groupAllWith (\(idx, row) -> maybeToRight idx $ groupOf row) $ zip [0 :: Int ..] (V.toList tbl.rows)) \((_, row) :| siblings) -> - case (groupOf row, siblings) of - (Just label, _ : _) -> tr_ [class_ "not-has-[.itemsListItem:not(.hidden)]:hidden"] - $ td_ [colspan_ $ show $ length tbl.columns + bool 0 1 (isJust tbl.features.rowId)] - $ details_ [class_ "group/disclosure", [__|on input from closest <[id$='_page']/> if event.target.type is "search" set my.open to true end|]] do - summary_ [class_ "cursor-pointer px-4 py-3 text-sm font-medium text-textStrong focus-visible:outline-offset-[-2px]"] do - toHtml label - span_ [class_ "ms-2 text-xs font-normal text-textWeak tabular-nums"] $ toHtml $ show (1 + length siblings) <> " items on this page" - table_ [class_ tbl.config.tableClasses] do - thead_ [class_ "sr-only"] $ tr_ do - when (isJust tbl.features.rowId) $ th_ [scope_ "col"] "Select issue" - forM_ tbl.columns $ \c -> th_ [scope_ "col"] $ toHtml c.name - tbody_ $ mapM_ (renderTableRow tbl) (row : map snd siblings) - _ -> renderTableRow tbl row + body = tbody_ (extra <> [class_ "stagger-fade"]) + columnCount = length tbl.columns + bool 0 1 (isJust tbl.features.rowId) + groups groupOf = sortWith (fst . head) $ NE.groupAllWith (\(idx, row) -> maybeToRight idx $ groupOf row) $ zip [0 :: Int ..] (V.toList tbl.rows) + groupedRows groupOf = iforM_ (groups groupOf) $ \idx ((_, row) :| siblings) -> + let renderedRows = mapM_ (renderTableRow tbl) (row : map snd siblings) + groupLabel label suffix = toHtml label >> span_ [class_ "ms-2 text-xs font-normal text-textWeak tabular-nums"] (toHtml $ show (1 + length siblings) <> suffix) + in if isJust tbl.features.grouping + then tbody_ ([class_ "stagger-fade not-has-[.itemsListItem:not(.hidden)]:hidden"] <> if idx == 0 then extra else []) do + forM_ (groupOf row) $ \label -> tr_ [data_ "table-group" label] $ td_ [colspan_ $ show columnCount, class_ "px-4 py-3 text-sm font-medium text-textStrong"] $ groupLabel label " items" + renderedRows + else case (groupOf row, siblings) of + (Just label, _ : _) -> tr_ [class_ "not-has-[.itemsListItem:not(.hidden)]:hidden"] + $ td_ [colspan_ $ show columnCount] + $ details_ [class_ "group/disclosure", [__|on input from closest <[id$='_page']/> if event.target.type is "search" set my.open to true end|]] do + summary_ [class_ "cursor-pointer px-4 py-3 text-sm font-medium text-textStrong focus-visible:outline-offset-[-2px]"] $ groupLabel label " items on this page" + table_ [class_ tbl.config.tableClasses] do + thead_ [class_ "sr-only"] $ tr_ do + when (isJust tbl.features.rowId) $ th_ [scope_ "col"] "Select issue" + forM_ tbl.columns $ \c -> th_ [scope_ "col", data_ "column-key" c.name] $ toHtml c.name + tbody_ renderedRows + _ -> renderedRows treeRowAttrs :: a -> TreeConfig a -> [Attribute] @@ -608,7 +630,7 @@ renderTableRow tbl row = $ input_ $ [term "aria-label" $ "Select " <> maybe "Item" ($ row) tbl.features.rowLabel, class_ "bulkactionItemCheckbox checkbox checkbox-md checked:checkbox-primary", type_ "checkbox", name_ "itemId", value_ $ getId row] <> [checked_ | maybe False ($ row) tbl.features.selectRow] - forM_ (zip [0 :: Int ..] tbl.columns) \(idx, c) -> td_ (c.attrs <> (class_ <$> maybeToList c.align) <> [data_ "column-index" $ show idx]) $ c.render row + forM_ tbl.columns $ \c -> td_ (c.attrs <> (class_ <$> maybeToList c.align) <> [data_ "column-key" c.name]) $ c.render row where rowAttrs = maybe [] ($ row) tbl.features.rowAttrs treeAttrs = maybe [] (treeRowAttrs row) tbl.features.treeConfig @@ -638,32 +660,38 @@ renderHeaderTableActions :: TableHeaderActions -> Html () renderHeaderTableActions actions = span_ [class_ "inline-flex flex-wrap items-center gap-2 ml-2"] do unless (null actions.sortOptions) $ renderSortDropdown actions unless (null actions.filterMenus) $ renderFilterDropdown actions - -- Each active filter as a removable chip, Sentry-search style: "Type: runtime_exception ×". - forM_ actions.filterMenus \menu -> forM_ (filter (.isActive) menu.options) \opt -> - button_ ([type_ "button", class_ "inline-flex items-center gap-1 rounded-md border border-strokeWeak bg-fillWeak px-2 py-0.5 text-xs text-textStrong hover:bg-fillWeaker max-md:whitespace-normal", Aria.label_ $ "Remove filter " <> menu.label <> ": " <> opt.label] <> swapTarget_ actions.targetId (deleteParamValue menu.paramName opt.value actions.baseUrl)) do - span_ [class_ "text-textWeak"] $ toHtml $ menu.label <> ":" - toHtml opt.label - faSprite_ "xmark" "regular" "w-2.5 h-2.5 text-textWeak" + renderFilterChips actions + + +renderFilterChips :: TableHeaderActions -> Html () +renderFilterChips actions = forM_ actions.filterMenus \menu -> forM_ (filter (.isActive) menu.options) \opt -> + button_ ([type_ "button", class_ "inline-flex items-center gap-1 rounded-md border border-strokeWeak bg-fillWeak px-2 py-0.5 text-xs text-textStrong hover:bg-fillWeaker max-md:whitespace-normal", Aria.label_ $ "Remove filter " <> menu.label <> ": " <> opt.label] <> swapTarget_ actions.targetId (deleteParamValue menu.paramName opt.value actions.baseUrl)) do + span_ [class_ "text-textWeak"] $ toHtml $ menu.label <> ":" + toHtml opt.label + faSprite_ "xmark" "regular" "w-2.5 h-2.5 text-textWeak" clearFiltersUrl :: TableHeaderActions -> Text clearFiltersUrl actions = foldl' (\url menu -> deleteParam menu.paramName url) actions.baseUrl actions.filterMenus -renderFilterRail :: TableHeaderActions -> Html () -renderFilterRail actions = - details_ [open_ "", class_ "w-60 shrink-0 max-lg:w-full", detailsClosedBelowAttr_ 1024] do - summary_ [class_ "flex cursor-pointer list-none items-center gap-2 rounded px-2 py-2 text-xs font-semibold text-textStrong hover:bg-fillWeak [&::-webkit-details-marker]:hidden"] "Filters" - facetRail_ Nothing "p-2" "Search filters" (Just clearAll) $ forM_ (zip [0 :: Int ..] actions.filterMenus) \(index, menu) -> - facetSection_ (index == 0 || any (.isActive) menu.options) "" [] (toHtml menu.label) - $ div_ [class_ "max-h-48 overflow-y-auto"] - $ forM_ menu.options (renderFilterOption actions menu) +-- | Adapt URL filters to the same sidebar data Explorer supplies. +facetsConfig :: TableHeaderActions -> Facets.Config +facetsConfig actions = Facets.Config (actions.targetId <> "-facets") "" (Just $ swapTarget_ actions.targetId $ clearFiltersUrl actions) (Just [common]) Facets.Collapsible where - clearAll = - button_ - ([type_ "button", class_ "flex items-center justify-between rounded px-2 py-1.5 text-xs text-textBrand hover:bg-fillWeak"] <> swapTarget_ actions.targetId (clearFiltersUrl actions)) - $ "Clear all" - >> faSprite_ "xmark" "regular" "h-3 w-3" + common = + FacetNode "Common Filters" Nothing True [] Nothing + $ FacetChildren + [ FacetNode + { label = menu.label + , path = Just menu.paramName + , expanded = (index < 5 && not (null menu.options)) || any (.isActive) menu.options + , attrs = [] + , actions = Nothing + , content = FacetValues (map (filterChoice actions menu) $ sortOn (not . (.isActive)) menu.options) ExpandValues + } + | (index, menu) <- zip [0 :: Int ..] actions.filterMenus + ] renderSortDropdown :: TableHeaderActions -> Html () @@ -706,29 +734,26 @@ renderFilterMenuItem actions menu = div_ [class_ "relative"] do ] do div_ [class_ "px-3 py-2 text-sm font-semibold text-textStrong border-b border-strokeWeak"] $ toHtml menu.label - div_ [class_ "p-1"] $ forM_ menu.options (renderFilterOption actions menu) + div_ [class_ "p-1"] $ forM_ menu.options (facetChoice_ . filterChoice actions menu) -renderFilterOption :: TableHeaderActions -> FilterMenu -> FilterOption -> Html () -renderFilterOption actions menu opt = facetOption_ "" [] optionBody pass +filterChoice :: TableHeaderActions -> FilterMenu -> FilterOption -> FacetChoice +filterChoice actions menu opt = FacetChoice{label = opt.label, multiSelect = menu.multiSelect, inputAttrs, marker = Nothing, count = prettyPrintCount <$> opt.count} where paramVal = menu.paramName <> "=" <> toUriStr opt.value -- For multi-select: toggle this value; for single-select: replace all with this value url - | menu.multiSelect && opt.isActive = deleteParamValue menu.paramName opt.value actions.baseUrl + | opt.isActive = deleteParamValue menu.paramName opt.value actions.baseUrl | menu.multiSelect = withQuery actions.baseUrl paramVal | otherwise = withQuery (deleteParam menu.paramName actions.baseUrl) paramVal - optionBody = do - input_ - $ [ type_ $ bool "radio" "checkbox" menu.multiSelect - , class_ $ bool "radio radio-xs" "checkbox checkbox-xs" menu.multiSelect - , value_ opt.value - , name_ $ "filter_" <> menu.paramName -- group radios by param name - , hxTrigger_ "change" - ] + inputAttrs = + [ Aria.label_ opt.label + , value_ opt.value + , name_ $ actions.targetId <> "_filter_" <> menu.paramName + , hxTrigger_ "change" + ] <> swapTarget_ actions.targetId url <> [checked_ | opt.isActive] - span_ [class_ "truncate text-sm"] $ toHtml opt.label -- | Remove a specific param=value pair from a URL (for multi-select filter toggle) @@ -772,23 +797,64 @@ renderSortMenu sortCfg = do renderResultToolbar :: Table a -> Html () renderResultToolbar tbl = div_ [class_ "flex min-h-9 flex-wrap items-center justify-between gap-2"] do whenJust tbl.features.resultSummary $ \summary -> span_ [class_ "text-sm text-textWeak", role_ "status", Aria.live_ "polite"] $ toHtml summary - whenJust tbl.features.exportName $ \name -> div_ [class_ "flex items-center gap-2"] do - button_ - [ type_ "button" - , class_ "btn btn-xs border border-strokeWeak bg-transparent font-normal text-textWeak shadow-none" - , onclick_ $ "window.exportTableCsv('#" <> tbl.config.elemID <> "_grid table','" <> name <> ".csv')" - ] - do - faSprite_ "download" "solid" "h-3 w-3" - "Export" - button_ ([type_ "button", class_ "btn btn-xs border border-strokeWeak bg-transparent font-normal text-textWeak shadow-none"] <> popoverTrigger_ (tbl.config.elemID <> "-columns")) do - faSprite_ "table-columns" "regular" "h-3 w-3" - "Customize" - div_ (popoverPanel_ (tbl.config.elemID <> "-columns") <> [class_ "dropdown dropdown-end z-50 mt-1 w-56 rounded-md border border-strokeWeak bg-bgRaised p-2 text-sm shadow-lg"]) do - span_ [class_ "block px-2 pb-1 text-xs font-semibold text-textStrong"] "Visible columns" - forM_ (zip [0 :: Int ..] tbl.columns) \(idx, column) -> label_ [class_ "flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 hover:bg-fillWeak"] do - input_ [type_ "checkbox", checked_, class_ "checkbox checkbox-xs", onchange_ $ "document.querySelectorAll('#" <> tbl.config.elemID <> "_grid [data-column-index=\"" <> show idx <> "\"]').forEach((element)=>element.classList.toggle('hidden',!this.checked))"] - toHtml column.name + forM_ tbl.features.facets $ \facets -> div_ [class_ "flex flex-wrap gap-2"] $ renderFilterChips facets + div_ [class_ "ml-auto flex flex-wrap items-center gap-2"] do + forM_ tbl.features.grouping selectControl_ + forM_ tbl.features.exportName $ \name -> + button_ + [ type_ "button" + , class_ "btn btn-xs border border-strokeWeak bg-transparent font-normal text-textWeak shadow-none" + , onclick_ $ "window.exportTableCsv('#" <> tbl.config.elemID <> "_grid table','" <> name <> ".csv')" + ] + $ faSprite_ "download" "solid" "h-3 w-3" + >> "Export" + when tbl.features.customizeColumns do + button_ ([type_ "button", class_ "btn btn-xs border border-strokeWeak bg-transparent font-normal text-textWeak shadow-none"] <> popoverTrigger_ (tbl.config.elemID <> "-columns")) do + faSprite_ "table-columns" "regular" "h-3 w-3" + "Customize" + -- CSS owns visibility; the checkbox only restores a stored choice. @data-forced@ marks a + -- user choice, so ticking a column that a breakpoint hides shows it. + style_ $ flip foldMap tbl.columns \c -> + let rule toggle display = "#" <> tbl.config.elemID <> "_page:has([data-column-toggle=\"" <> c.name <> "\"]" <> toggle <> ") [data-column-key=\"" <> c.name <> "\"]{display:" <> display <> "}" + in rule "[data-forced]:not(:checked)" "none" <> rule "[data-forced]:checked" "table-cell" + div_ + ( popoverPanel_ (tbl.config.elemID <> "-columns") + <> [ class_ "dropdown dropdown-end z-50 mt-1 w-56 rounded-md border border-strokeWeak bg-bgRaised p-2 text-sm shadow-lg" + , [__|on beforetoggle if event.newState is 'open' send syncColumn to <[data-column-toggle]/> in me end + on resize from window if me.matches(':popover-open') send syncColumn to <[data-column-toggle]/> in me end|] + ] + ) + do + span_ [class_ "block px-2 pb-1 text-xs font-semibold text-textStrong"] "Visible columns" + forM_ tbl.columns $ \column -> label_ [class_ "flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 hover:bg-fillWeak"] do + input_ + [ type_ "checkbox" + , checked_ + , class_ "checkbox checkbox-xs" + , data_ "column-toggle" column.name + , data_ "column-storage" $ "table-columns:" <> tbl.config.elemID <> ":" <> column.name + , [__|init set saved to localStorage.getItem(@data-column-storage) if saved is not null set @data-forced to 'true' then set my.checked to saved is 'true' end + on syncColumn if not @data-forced + set cell to (closest <[data-table-columns]/>).querySelector('[data-column-key="' + @data-column-toggle + '"]') + if cell set my.checked to getComputedStyle(cell).display is not 'none' end + end + on change set @data-forced to 'true' then call localStorage.setItem(@data-column-storage, my.checked)|] + ] + toHtml column.name + button_ + [ type_ "button" + , class_ "btn btn-xs btn-ghost mt-1 w-full font-normal" + , [__|on click repeat for t in <[data-column-toggle]/> in closest <[data-table-columns]/> call localStorage.removeItem(t.getAttribute('data-column-storage')) then remove @data-forced from t then send syncColumn to t end|] + ] + "Reset columns" + + +selectControl_ :: SelectControl -> Html () +selectControl_ cfg = label_ [class_ "flex items-center gap-2 whitespace-nowrap text-xs text-textWeak"] do + toHtml cfg.label + select_ ([name_ cfg.name, class_ "select select-xs w-auto cursor-pointer border-strokeWeak bg-bgBase max-md:min-h-11 max-md:text-base", hxTrigger_ "change"] <> swapTarget_ cfg.targetId (deleteParam "deferred" $ deleteParam cfg.name cfg.baseUrl)) + $ forM_ cfg.options + $ \(value, label) -> option_ ([value_ value] <> [selected_ "" | value == cfg.current]) $ toHtml label renderPaginationFooter :: Pagination -> Html () diff --git a/src/Pkg/Components/TimePicker.hs b/src/Pkg/Components/TimePicker.hs index ef4c27653..bcf875aae 100644 --- a/src/Pkg/Components/TimePicker.hs +++ b/src/Pkg/Components/TimePicker.hs @@ -3,7 +3,6 @@ module Pkg.Components.TimePicker ( parseTimeRange, LiveDataMode (..), liveDataControls_, - timeHiddenInputs_, TimePicker (..), rangePairs, rangeJson, @@ -489,11 +488,6 @@ windowUrl :: Text -> [(Text, Text)] -> TimeWindow -> Text windowUrl base extras window = timeScopedUrl base extras window.fromQuery window.toQuery window.sinceQuery -timeHiddenInputs_ :: Maybe Text -> Maybe Text -> Maybe Text -> Html () -timeHiddenInputs_ fromM toM sinceM = forM_ ([("from", fromM), ("to", toM), ("since", sinceM)] :: [(Text, Maybe Text)]) \(name, valueM) -> - input_ [type_ "hidden", name_ name, value_ $ fromMaybe "" valueM, term "_" "on 'update-query' from window set my.value to window.params()[my.name] or ''"] - - refreshOptions :: [(Text, Text, Text)] refreshOptions = [ ("Off", "Turn off automatic refresh", "0") diff --git a/test/integration/Pages/ContainersSpec.hs b/test/integration/Pages/ContainersSpec.hs index c43ca7b91..cc68f0e01 100644 --- a/test/integration/Pages/ContainersSpec.hs +++ b/test/integration/Pages/ContainersSpec.hs @@ -7,7 +7,6 @@ import Data.Cache qualified as Cache import Data.Effectful.Hasql qualified as Hasql import Data.List (lookup) import Data.Text qualified as T -import Data.Text.Lazy qualified as LT import Data.Time (NominalDiffTime, addUTCTime) import Data.Vector qualified as V import Lucid qualified @@ -16,7 +15,7 @@ import Pages.BodyWrapper (BWConfig (..), PageCtx (..)) import Pages.Charts.Charts qualified as Charts import Pages.Containers qualified as Containers import Pages.Infrastructure qualified as Infrastructure -import Pkg.Components.Table (Table (..)) +import Pkg.Components.Table (Features (customizeColumns, exportName, resultSummary), Table (..)) import Pkg.Components.Widget qualified as Widget import Pkg.Icons qualified as Icons import Pkg.TestUtils @@ -99,59 +98,19 @@ ingestFixture tr key = do k8sOther = k8sResource "kube-system" "coredns-c6d9fc49c-bj5sw" "coredns" k8sStateful = mkAttr "k8s.statefulset.name" "postgres" : k8sPodResource "data" "postgres-0" "postgres" - -- 0.5 cores against a 2-core limit and 512 MiB against 1 GiB: both percentages land on - -- round numbers so a unit slip anywhere in the pipeline is obvious rather than plausible. + -- Mixed receiver families, absent limits, controller fallback, pod-only telemetry, + -- and a pod rollup that must lose to its reporting containers. forM_ - ( [ ("container.cpu.usage", 0.5) - , ("container.memory.working_set", 536870912) - , ("k8s.container.cpu_limit", 2) - , ("k8s.container.cpu_request", 1) - , ("k8s.container.memory_limit", 1073741824) - , ("k8s.container.memory_request", 268435456) - , ("k8s.container.restarts", 3) - , ("k8s.container.ready", 1) + ( [ (k8sChecked, [("container.cpu.usage", 0.5), ("container.memory.working_set", 536870912), ("k8s.container.cpu_limit", 2), ("k8s.container.cpu_request", 1), ("k8s.container.memory_limit", 1073741824), ("k8s.container.memory_request", 268435456), ("k8s.container.restarts", 3), ("k8s.container.ready", 1)]) + , (k8sOther, [("container.cpu.usage", 0.25), ("container.memory.working_set", 33554432), ("k8s.container.ready", 0)]) + , (dockerResource "srv-captain--redpanda-0.1.tt13bkp5", [("container.cpu.utilization", 80), ("container.memory.usage.total", 3221225472), ("container.memory.usage.limit", 4294967296)]) + , (k8sStateful, [("container.cpu.usage", 0.1), ("container.memory.usage", 16777216)]) + , (mkAttr "k8s.deployment.name" "frontend" : k8sPodResource "shop" "frontend-544d9b6f4-2xk7z" "frontend", [("k8s.pod.cpu.usage", 0.75), ("k8s.pod.memory.working_set", 268435456)]) + , (k8sChecked, [("k8s.pod.cpu.usage", 9.9), ("k8s.pod.memory.working_set", 9999999)]) ] - :: [(Text, Double)] + :: [([PC.KeyValue], [(Text, Double)])] ) - (emit k8sChecked) - - -- A second namespace, and deliberately no CPU limit — the case Datadog documents as - -- "cannot infer the usage percentage", which must stay blank rather than become 0%. - forM_ - ( [ ("container.cpu.usage", 0.25) - , ("container.memory.working_set", 33554432) - , ("k8s.container.ready", 0) - ] - :: [(Text, Double)] - ) - (emit k8sOther) - - -- Docker: 80 means 0.8 cores under Docker's own formula, and the memory limit arrives on a - -- different metric name from the Kubernetes one. - forM_ - ( [ ("container.cpu.utilization", 80) - , ("container.memory.usage.total", 3221225472) - , ("container.memory.usage.limit", 4294967296) - ] - :: [(Text, Double)] - ) - (emit $ dockerResource "srv-captain--redpanda-0.1.tt13bkp5") - - -- A StatefulSet pod, and memory on kubeletstats' container.memory.usage rather than - -- working_set: neither the workload nor the memory reading survives without a fallback. - forM_ ([("container.cpu.usage", 0.1), ("container.memory.usage", 16777216)] :: [(Text, Double)]) (emit k8sStateful) - - -- A pod whose collector runs kubeletstats without the container metric group: only - -- k8s.pod.* arrives, so the pod itself has to stand in for its containers. - forM_ - ([("k8s.pod.cpu.usage", 0.75), ("k8s.pod.memory.working_set", 268435456)] :: [(Text, Double)]) - (emit $ mkAttr "k8s.deployment.name" "frontend" : k8sPodResource "shop" "frontend-544d9b6f4-2xk7z" "frontend") - - -- The same pod metrics for a pod that DOES report container metrics: the rollup must lose - -- to its containers rather than appear beside them. - forM_ - ([("k8s.pod.cpu.usage", 9.9), ("k8s.pod.memory.working_set", 9999999)] :: [(Text, Double)]) - (emit k8sChecked) + \(resource, metrics) -> mapM_ (emit resource) metrics -- A bare node. Four logical cores, each reporting idle and user; 0.25 busy on each of two -- of them is 0.5 cores of a 4-core box. Memory is per state and the limit is their sum. @@ -208,11 +167,11 @@ spec = sequential $ aroundAll withTfChartResources do conf.pageTitle `shouldBe` "Infrastructure" conf.prePageTitle `shouldBe` Nothing V.length table.rows `shouldBe` 0 - let html = LT.toStrict $ Lucid.renderText $ Lucid.toHtml page + let html = toText $ Lucid.renderText $ Lucid.toHtml page html `shouldContainAll` ["No containers reporting"] (_, hostMap) <- testServant tr $ Infrastructure.hostMapGetH testPid Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing (Just "1") - LT.toStrict (Lucid.renderText $ Lucid.toHtml hostMap) + toText (Lucid.renderText $ Lucid.toHtml hostMap) `shouldContainAll` ["No hosts reporting", "Set up host monitoring"] it "kubernetesAndDockerContainers_landInOneListWithNormalisedCpuAndMemory" \tr -> do @@ -315,17 +274,17 @@ spec = sequential $ aroundAll withTfChartResources do let Containers.ContainersPage (PageCtx _ body) = page table <- deferredBody body V.length table.rows `shouldBe` 8 - let html = LT.toStrict $ Lucid.renderText $ Lucid.toHtml page + let html = toText $ Lucid.renderText $ Lucid.toHtml page cacheKey = (testPid, Nothing, Nothing, Just "5M") :: ContainerSnapshotKey cached <- Cache.lookup tr.trATCtx.infrastructureCache cacheKey :: IO (Maybe (V.Vector ContainerRow)) V.length <$> cached `shouldBe` Just 8 -- Both runtimes in one table, with the facet menus the filter dropdown is built from. - html `shouldContainAll` ["checkout", "srv-captain--redpanda-0.1.tt13bkp5", "kube-system", "namespace=", "runtime=", "cluster=", "otel-demo", "vps-bare-01", "Search containers", "CPU limit used", "Memory limit used", "data-live-mode=\"refresh-only\"", "data-component=\"facet-rail\"", "data-component=\"facet-section\"", "data-component=\"facet-option\"", "Last 5 mins", "bg-bgAlternate sticky", "bg-fillWarning-strong", "hidden max-md:inline-flex", "data-header-actions", "/infrastructure/containers/detail?since=5M"] + html `shouldContainAll` ["checkout", "srv-captain--redpanda-0.1.tt13bkp5", "kube-system", "namespace=", "runtime=", "cluster=", "otel-demo", "vps-bare-01", "Search containers", "CPU limit used", "Memory limit used", "data-live-mode=\"refresh-only\"", "data-component=\"facet-rail\"", "data-component=\"facet-section\"", "data-component=\"facet-option\"", "Common Filters", "facet-count", "Last 5 mins", "bg-bgAlternate sticky", "bg-fillWarning-strong", "hidden max-md:inline-flex", "data-header-actions", "/infrastructure/containers/detail?since=5M"] T.isInfixOf "group/summary" html `shouldBe` False T.isInfixOf "Usage over time" html `shouldBe` False T.isInfixOf "min-height:" html `shouldBe` False T.isInfixOf "data-widget=" html `shouldBe` False - T.count "data-component=\"facet-section\" open>" html `shouldBe` 1 + T.count "data-component=\"facet-section\" open>" html `shouldBe` 6 -- The screenshot regression: "Not ready" wrapped onto two lines in the narrow status -- column, crossing the badge border. The label is one indivisible status. html `shouldContainAll` ["Not ready", "class=\"badge badge-sm badge-error whitespace-nowrap\""] @@ -333,6 +292,30 @@ spec = sequential $ aroundAll withTfChartResources do -- as a clipped stroke. The table export uses the correctly framed Font Awesome symbol. html `shouldContainAll` ["M288 32c0-17.7-14.3-32-32-32s-32 14.3-32 32"] + html + `shouldContainAll` [ "w-80 max-w-80 overflow-hidden" + , "w-72 max-w-72 overflow-hidden" + , "min-w-0 flex-1 truncate" + , "max-w-36 truncate" + , "data-tip=\"Runtime: kubernetes\"" + , "data-tippy-content=\"Container: checkout\"" + , "data-tippy-content=\"Image: demo:2.2.0\"" + , "data-tippy-content=\"Workload: checkout\"" + , "data-tippy-content=\"CPU limit used: " + , "data-tippy-content=\"Memory limit used: " + , "data-tippy-content=\"Latest reported readiness: Ready\"" + , "Latest cumulative restart count reported within the selected time range. This is not the number of restarts during the range." + ] + + let render features = toText $ Lucid.renderText $ Lucid.toHtml table{features} + customizeOnly = render table.features{resultSummary = Nothing, exportName = Nothing, customizeColumns = True} + exportOnly = render table.features{resultSummary = Nothing, exportName = Just "containers", customizeColumns = False} + render table.features `shouldContainAll` ["type=\"radio\"", "id=\"containersContainer-facets\"", "name=\"containersContainer_filter_namespace\""] + customizeOnly `shouldContainAll` ["Customize", "Reset columns", "data-column-key=", "data-column-toggle=", "[data-forced]:not(:checked)) [data-column-key=\"Pod\"]{display:none}"] + customizeOnly `shouldNotSatisfy` T.isInfixOf ">Export" + exportOnly `shouldContainAll` ["Export", "containers.csv"] + exportOnly `shouldNotSatisfy` T.isInfixOf "Customize" + -- Each facet narrows independently, and an unknown value yields an empty list rather -- than silently falling back to "all". let listWith f = do @@ -352,31 +335,18 @@ spec = sequential $ aroundAll withTfChartResources do -- A bare node is its own runtime, so it is reachable and does not pollute the others. listWith (containersPage noContainerFilters{runtime = Just "host"}) >>= (`shouldMatchList` ["vps-bare-01", "vps-d6d7e318"]) - -- Keep both identity columns readable when image and workload names are long. - it "longContainerMetadata_doesNotOverlapPodColumn" \tr -> do - (_, page) <- testServant tr $ containersPage noContainerFilters - let html = LT.toStrict $ Lucid.renderText $ Lucid.toHtml page - html - `shouldContainAll` [ "w-80 max-w-80 overflow-hidden" - , "w-72 max-w-72 overflow-hidden" - , "min-w-0 flex-1 truncate" - , "max-w-36 truncate" - , "data-tip=\"Runtime: kubernetes\"" - , "data-tippy-content=\"Container: checkout\"" - , "data-tippy-content=\"Image: demo:2.2.0\"" - , "data-tippy-content=\"Workload: checkout\"" - , "data-tippy-content=\"CPU limit used: " - , "data-tippy-content=\"Memory limit used: " - , "data-tippy-content=\"Latest reported readiness: Ready\"" - , "Latest cumulative restart count reported within the selected time range. This is not the number of restarts during the range." - ] - it "infrastructureViews_projectTheSameTelemetryIntoHostsImagesKubernetesAndMap" \tr -> do - (_, hosts@(Infrastructure.HostsPage (PageCtx hostsBW _))) <- testServant tr $ Infrastructure.hostsGetH testPid Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing (Just "1") + (_, hosts@(Infrastructure.HostsPage (PageCtx hostsBW body))) <- testServant tr $ Infrastructure.hostsGetH testPid Nothing Nothing Nothing Nothing (Just "integration") Nothing Nothing Nothing (Just "1") V.null hostsBW.serviceOptions `shouldBe` True hostsBW.pageTitle `shouldBe` "Infrastructure" hostsBW.prePageTitle `shouldBe` Nothing - let hostsHtml = LT.toStrict $ Lucid.renderText $ Lucid.toHtml hosts + let hostsHtml = toText $ Lucid.renderText $ Lucid.toHtml hosts + table <- deferredBody body + V.length table.rows `shouldBe` 3 + let tableHtml = toText $ Lucid.renderText $ Lucid.toHtml table + hostsHtml `shouldContainAll` ["data-table-group=\"Docker\"", "data-table-group=\"Kubernetes\"", "data-table-group=\"OpenTelemetry\"", "data-hx-trigger=\"change\"", "name=\"group\"", "data-column-key=\"CPU\""] + T.count "role=\"button\"" tableHtml `shouldBe` 3 + T.count " clusterUid <> "\""] (_, hostMap) <- testServant tr $ Infrastructure.hostMapGetH testPid (Just "storage") Nothing Nothing Nothing Nothing Nothing Nothing Nothing (Just "1") - let hostMapHtml = LT.toStrict $ Lucid.renderText $ Lucid.toHtml hostMap + let hostMapHtml = toText $ Lucid.renderText $ Lucid.toHtml hostMap hostMapHtml - `shouldContainAll` ["Host Map", "Fill by", "Group by", "vps-bare-01", "clip-path:polygon", "bg-fillNeutral-strong", "onchange=\"this.form.requestSubmit()\"", "name=\"os\""] + `shouldContainAll` ["Host Map", "Fill by", "Group by", "vps-bare-01", "clip-path:polygon", "bg-fillNeutral-strong", "name=\"fill\"", "data-hx-trigger=\"change\"", "data-component=\"facet-rail\"", "Provider", "Region", "OS"] hostMapHtml `shouldNotSatisfy` T.isInfixOf ">Apply" (_, hostDetail) <- testServant tr $ Infrastructure.hostDetailGetH testPid (Just "vps-bare-01") Nothing Nothing Nothing - LT.toStrict (Lucid.renderText $ Lucid.toHtml hostDetail) + toText (Lucid.renderText $ Lucid.toHtml hostDetail) `shouldContainAll` [ "Host summary" , "CPU usage" , "Memory usage" @@ -418,11 +388,11 @@ spec = sequential $ aroundAll withTfChartResources do ] (_, imageDetail) <- testServant tr $ Infrastructure.imageDetailGetH testPid (Just "ghcr.io/open-telemetry/demo") Nothing Nothing Nothing - LT.toStrict (Lucid.renderText $ Lucid.toHtml imageDetail) + toText (Lucid.renderText $ Lucid.toHtml imageDetail) `shouldContainAll` ["Image summary", "Running containers", "Security coverage", "View containers"] (_, kubeDetail) <- testServant tr $ Infrastructure.kubernetesDetailGetH testPid (Just "pods") (Just "checkout-7fb5b4f859-nlcjs") (Just "otel-demo") (Just "default") Nothing Nothing Nothing - LT.toStrict (Lucid.renderText $ Lucid.toHtml kubeDetail) + toText (Lucid.renderText $ Lucid.toHtml kubeDetail) `shouldContainAll` ["Pod summary", "CPU / limit", "View containers", "View logs", "View metrics"] it "hostCpuChart_normalizesAcrossLogicalCoresAndRepeatedSamples" \tr -> do @@ -432,17 +402,20 @@ spec = sequential $ aroundAll withTfChartResources do forM_ ([("idle", 0.875), ("user", 0.125)] :: [(Text, Double)]) \(mode, value) -> ingestMetric tr key [mkAttr "host.name" "four-core-host"] [mkAttr "cpu.logical_number" core, mkAttr "cpu.mode" mode] "system.cpu.utilization" value (addUTCTime offset frozenTime) ingestMetric tr key [mkAttr "host.name" "host-without-idle"] [mkAttr "cpu.logical_number" "cpu0", mkAttr "cpu.mode" "user"] "system.cpu.utilization" 0.5 (addUTCTime (-60) frozenTime) - forM_ ([("four-core-host", Just 12.5), ("vps-d6d7e318", Just 25), ("host-without-idle", Nothing)] :: [(Text, Maybe Double)]) \(host, expected) -> do + forM_ ([("four-core-host", Just 12.5), ("vps-d6d7e318", Just 25), ("host-without-idle", Nothing), ("0ce201583b04", Nothing)] :: [(Text, Maybe Double)]) \(host, expected) -> do html <- shellHtml tr $ Infrastructure.hostDetailGetH testPid (Just host) Nothing Nothing (Just "2H") case expected of Just percentage -> chartPlotsOnly tr testPid "host-cpu" percentage html Nothing -> do - html `shouldContainAll` ["No host metrics in this time range", "Metrics coverage: 0 of 4"] + html `shouldContainAll` ["No host metrics in this time range", "Try last 1 hour", "Set up host metrics", "View logs", "Metrics coverage: 0 of 4"] html `shouldNotSatisfy` T.isInfixOf "host-cpu" it "infrastructureDrawer_drilldownsKeepTheSelectedTimeWindow" \tr -> do containerHtml <- shellHtml tr $ Containers.containerDetailGetH testPid (Just "checkout") (Just "checkout-7fb5b4f859-nlcjs") Nothing Nothing Nothing Nothing Nothing Nothing (Just "24H") containerHtml `shouldContainAll` ["/log_explorer?since=24H&query=", "/metrics?since=24H&metric_prefix=k8s."] + containerHtml `shouldContainAll` ["Requests and limits", "vps-d6d7e318", "View logs", "resource.k8s.pod.name", "data-tippy-content=\"Pod: checkout-7fb5b4f859-nlcjs\"", ""hide_value":true", "text-textWeak widget-subtitle", "\\"bottom\\":0", "\\"tooltip\\":{\\"show\\":true}"] + gone <- shellHtml tr $ Containers.containerDetailGetH testPid (Just "ghost") Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing + gone `shouldContainAll` ["no longer reporting"] historicalContainer <- shellHtml tr $ Containers.containerDetailGetH testPid (Just "checkout") (Just "checkout-7fb5b4f859-nlcjs") Nothing Nothing Nothing Nothing (Just "2024-12-31T23:00:00Z") (Just "2025-01-01T00:00:00Z") Nothing historicalContainer `shouldContainAll` ["/log_explorer?from=2024-12-31T23%3A00%3A00Z&to=2025-01-01T00%3A00%3A00Z&query=", "/metrics?from=2024-12-31T23%3A00%3A00Z&to=2025-01-01T00%3A00%3A00Z&metric_prefix=k8s."] hostHtml <- shellHtml tr $ Infrastructure.hostDetailGetH testPid (Just "vps-bare-01") Nothing Nothing (Just "24H") @@ -481,36 +454,19 @@ spec = sequential $ aroundAll withTfChartResources do param "since" `shouldBe` Just "4H" it "firstRequest_rendersChromeAndASelfFetchingSkeleton_notRows" \tr -> do - -- Every infrastructure view is one multi-second metrics pivot. The request that paints - -- the page must not wait for it: it answers with nav, tabs and a skeleton that fetches - -- the body itself. Rows appearing here again would mean the deferral was undone and - -- navigating the section is back to seconds per click. - hostsShell <- shellHtml tr $ Infrastructure.hostsGetH testPid Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing - hostsShell `shouldContainAll` ["Infrastructure", "Hosts", "id=\"hostsContainer\"", "hx-trigger=\"load, update-query from:window\"", "/infrastructure/hosts?", "deferred=1"] - hostsShell `shouldNotSatisfy` T.isInfixOf "vps-bare-01" - - containersShell <- shellHtml tr $ Containers.containersGetH testPid Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing - containersShell `shouldContainAll` ["id=\"containersContainer\"", "hx-trigger=\"load, update-query from:window\"", "deferred=1"] - containersShell `shouldNotSatisfy` T.isInfixOf "checkout-7fb5b4f859-nlcjs" - - -- The filters the shell was asked for have to survive the round trip, or the rows that - -- arrive would not be the rows the visible filter chips claim. - filteredShell <- shellHtml tr $ Infrastructure.kubernetesGetH testPid (Just "pods") (Just "otel-demo") (Just "default") Nothing Nothing Nothing Nothing Nothing - filteredShell `shouldContainAll` ["resource=pods", "cluster=otel-demo", "namespace=default", "deferred=1", "hx-trigger=\"load, update-query from:window\""] - - imagesShell <- shellHtml tr $ Infrastructure.imagesGetH testPid Nothing Nothing Nothing Nothing Nothing Nothing - imagesShell `shouldContainAll` ["id=\"imagesContainer\"", "data-deferred-shell", "hx-trigger=\"load, update-query from:window\""] - mapShell <- shellHtml tr $ Infrastructure.hostMapGetH testPid Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing - mapShell `shouldContainAll` ["id=\"hostMapContainer\"", "Loading host map", "hx-trigger=\"load, update-query from:window\""] - mapShell `shouldNotSatisfy` T.isInfixOf "data-visible-host-label" - - it "hostDetail_withoutHostMetrics_collapsesChartsIntoRecoveryState" \tr -> do - -- The Docker host: containers report against it but no system.* series does. - -- (vps-d6d7e318 no longer qualifies — the in-cluster agent gives it host CPU.) - (_, hostWithoutMetrics) <- testServant tr $ Infrastructure.hostDetailGetH testPid (Just "0ce201583b04") Nothing Nothing Nothing - let html = LT.toStrict $ Lucid.renderText $ Lucid.toHtml hostWithoutMetrics - html `shouldContainAll` ["No host metrics in this time range", "Try last 1 hour", "Set up host metrics", "View logs", "Metrics coverage: 0 of 4"] - html `shouldNotSatisfy` T.isInfixOf "host-cpu" + forM_ + ( [ (shellHtml tr $ Infrastructure.hostsGetH testPid Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing, ["Infrastructure", "Hosts", "id=\"hostsContainer\"", "/infrastructure/hosts?", "deferred=1"], ["vps-bare-01"]) + , (shellHtml tr $ Containers.containersGetH testPid Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing, ["id=\"containersContainer\"", "deferred=1"], ["checkout-7fb5b4f859-nlcjs"]) + , (shellHtml tr $ Infrastructure.kubernetesGetH testPid (Just "pods") (Just "otel-demo") (Just "default") Nothing Nothing Nothing Nothing Nothing, ["resource=pods", "cluster=otel-demo", "namespace=default", "deferred=1"], []) + , (shellHtml tr $ Infrastructure.imagesGetH testPid Nothing Nothing Nothing Nothing Nothing Nothing, ["id=\"imagesContainer\"", "data-deferred-shell"], []) + , (shellHtml tr $ Infrastructure.hostMapGetH testPid Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing, ["id=\"hostMapContainer\"", "Loading host map"], ["data-visible-host-label"]) + ] + :: [(IO Text, [Text], [Text])] + ) + \(render, expected, absent) -> do + html <- render + html `shouldContainAll` ("hx-trigger=\"load, update-query from:window\"" : expected) + forM_ absent $ \value -> html `shouldNotSatisfy` T.isInfixOf value it "containerDrawer_sameNamesRemainDistinctAndKeepTheirMetricScope" \tr -> do pid <- createTestProject tr "container-scoped-drawer" @@ -550,19 +506,6 @@ spec = sequential $ aroundAll withTfChartResources do victim <- createTestProject tr "victim" assertNonMemberDenied tr victim $ Containers.containerDetailGetH victim (Just "checkout") Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing - it "detailDrawer_showsRequestsAndLimitsAndPivots" \tr -> do - (_, html') <- testServant tr $ Containers.containerDetailGetH testPid (Just "checkout") (Just "checkout-7fb5b4f859-nlcjs") Nothing Nothing Nothing Nothing Nothing Nothing Nothing - let html = LT.toStrict $ Lucid.renderText $ Lucid.toHtml html' - html `shouldContainAll` ["Requests and limits", "vps-d6d7e318", "View logs", "resource.k8s.pod.name", "data-tippy-content=\"Pod: checkout-7fb5b4f859-nlcjs\""] - - -- The chart options ride as a JSON string inside data-chart-config, so their quotes are - -- JSON-escaped and then attribute-escaped; the bare form would mean a broken JSON.parse. - html `shouldContainAll` [""hide_value":true", "text-textWeak widget-subtitle", "\\"bottom\\":0", "\\"tooltip\\":{\\"show\\":true}"] - - -- A container that stopped reporting must say so, not render a blank panel. - (_, gone) <- testServant tr $ Containers.containerDetailGetH testPid (Just "ghost") Nothing Nothing Nothing Nothing Nothing Nothing Nothing Nothing - LT.toStrict (Lucid.renderText $ Lucid.toHtml gone) `shouldContainAll` ["no longer reporting"] - -- The pivot reads the newest datapoint per series, so scanning the picker's whole window -- can only turn up older points it then discards -- while paying to sort every one. Over a -- day that cost the statement timeout, which meant the snapshot never cached and every load diff --git a/web-components/src/main.ts b/web-components/src/main.ts index 8755d0f9e..322e7915c 100644 --- a/web-components/src/main.ts +++ b/web-components/src/main.ts @@ -391,9 +391,12 @@ window.exportTableCsv = (selector, filename) => { if (!table) return; const quote = (value: string) => `"${value.replaceAll('"', '""')}"`; const csv = Array.from(table.querySelectorAll('tr')) + .filter(row => !row.hasAttribute('data-table-group') && + (!row.closest('thead') || row.parentElement === table.tHead) && + !Array.from(row.cells).some(cell => cell.querySelector('table'))) .filter((row) => getComputedStyle(row).display !== 'none') .map((row) => - Array.from(row.querySelectorAll('th,td')) + Array.from(row.cells) .filter((cell) => getComputedStyle(cell).display !== 'none') .map((cell) => quote(cell.innerText.trim().replaceAll(/\s+/g, ' '))) .join(',') diff --git a/web-components/test/table-export.test.ts b/web-components/test/table-export.test.ts index 1577b9673..bbc5d3367 100644 --- a/web-components/test/table-export.test.ts +++ b/web-components/test/table-export.test.ts @@ -18,13 +18,13 @@ beforeEach(() => { afterEach(() => vi.restoreAllMocks()); describe('table CSV export', () => { - test('downloads escaped visible cells with the requested filename', async () => { - document.body.innerHTML = ` - - - - -
HostNoteSecret
api-1ready, "primary"token
hiddenrow
`; + test.each([false, true])('downloads escaped visible cells, grouped=%s', async (grouped) => { + const header = 'HostNoteSecret'; + const rows = `api-1ready, "primary"token + hiddenrow`; + document.body.innerHTML = `${header}${grouped + ? `` + : rows}
Europe: 2 hosts${header}${rows}
`; document.querySelectorAll('th,td').forEach((cell) => (cell.innerText = cell.textContent ?? '')); const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined); From d5deee79ee5127b72f02e08a92b919b696448fe5 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Mon, 26 Oct 2026 15:58:09 +0100 Subject: [PATCH 019/203] Group vitest with @vitest/* in dependabot and drop unused root jest (#736) The vite group's "vite*" pattern also matched vitest, so vitest and @vitest/browser landed in different groups and each major bump failed to install alone (#723, #727). Root jest had no tests of its own; it only picked up web-components' vitest files. --- .github/dependabot.yml | 11 +- package-lock.json | 3156 +--------------------------------------- package.json | 2 - 3 files changed, 16 insertions(+), 3153 deletions(-) diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 818e5b0af..6ffd75a75 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -43,14 +43,17 @@ updates: patterns: - "lit*" - "@lit*" + # Exact names: a bare "vite*" also claims vitest, splitting it from @vitest/* across groups. vite-ecosystem: patterns: - - "vite*" - - "@vite*" + - "vite" + - "vite-plugin-*" + - "@vitejs/*" vitest-ecosystem: patterns: - - "vitest*" - - "@vitest*" + - "vitest" + - "vitest-*" + - "@vitest/*" commit-message: prefix: "chore(deps)" diff --git a/package-lock.json b/package-lock.json index 40a7d5d07..484410928 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,5 +1,5 @@ { - "name": "m3-deps", + "name": "m3-chore", "lockfileVersion": 3, "requires": true, "packages": { @@ -15,7 +15,6 @@ "@tailwindcss/typography": "^0.5.20", "autoprefixer": "^10.6.1", "daisyui": "^5.7.50", - "jest": "^30.5.2", "postcss": "^8.5.31", "tailwindcss": "^4.3.3", "workbox-cli": "^7.4.1" @@ -514,61 +513,6 @@ "@babel/core": "^7.0.0-0" } }, - "node_modules/@babel/plugin-syntax-async-generators": { - "version": "7.8.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz", - "integrity": "sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-bigint": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz", - "integrity": "sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-properties": { - "version": "7.12.13", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz", - "integrity": "sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.12.13" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-class-static-block": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz", - "integrity": "sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, "node_modules/@babel/plugin-syntax-import-assertions": { "version": "7.28.6", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-assertions/-/plugin-syntax-import-assertions-7.28.6.tgz", @@ -601,174 +545,6 @@ "@babel/core": "^7.0.0-0" } }, - "node_modules/@babel/plugin-syntax-import-meta": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz", - "integrity": "sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-json-strings": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz", - "integrity": "sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-jsx": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz", - "integrity": "sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-logical-assignment-operators": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz", - "integrity": "sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-nullish-coalescing-operator": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz", - "integrity": "sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-numeric-separator": { - "version": "7.10.4", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz", - "integrity": "sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.10.4" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-object-rest-spread": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz", - "integrity": "sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-catch-binding": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz", - "integrity": "sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-optional-chaining": { - "version": "7.8.3", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz", - "integrity": "sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.8.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-private-property-in-object": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz", - "integrity": "sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-top-level-await": { - "version": "7.14.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz", - "integrity": "sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.14.5" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, - "node_modules/@babel/plugin-syntax-typescript": { - "version": "7.29.7", - "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.29.7.tgz", - "integrity": "sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/helper-plugin-utils": "^7.29.7" - }, - "engines": { - "node": ">=6.9.0" - }, - "peerDependencies": { - "@babel/core": "^7.0.0-0" - } - }, "node_modules/@babel/plugin-syntax-unicode-sets-regex": { "version": "7.18.6", "resolved": "https://registry.npmjs.org/@babel/plugin-syntax-unicode-sets-regex/-/plugin-syntax-unicode-sets-regex-7.18.6.tgz", @@ -1801,71 +1577,6 @@ "node": ">=6.9.0" } }, - "node_modules/@bcoe/v8-coverage": { - "version": "0.2.3", - "resolved": "https://registry.npmjs.org/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz", - "integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@emnapi/core": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", - "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/wasi-threads": "1.2.1", - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/core/node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, - "license": "0BSD", - "optional": true - }, - "node_modules/@emnapi/runtime": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", - "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/runtime/node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, - "license": "0BSD", - "optional": true - }, - "node_modules/@emnapi/wasi-threads": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", - "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@emnapi/wasi-threads/node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, - "license": "0BSD", - "optional": true - }, "node_modules/@grpc/grpc-js": { "version": "1.14.6", "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.6.tgz", @@ -1907,448 +1618,6 @@ "node": ">=18" } }, - "node_modules/@istanbuljs/load-nyc-config": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz", - "integrity": "sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ==", - "dev": true, - "license": "ISC", - "dependencies": { - "camelcase": "^5.3.1", - "find-up": "^4.1.0", - "get-package-type": "^0.1.0", - "js-yaml": "^3.13.1", - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@istanbuljs/schema": { - "version": "0.1.6", - "resolved": "https://registry.npmjs.org/@istanbuljs/schema/-/schema-0.1.6.tgz", - "integrity": "sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/@jest/console": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/console/-/console-30.5.2.tgz", - "integrity": "sha512-e8sQC4pCMHPBrPX7Hk8TJr+DM5dkUnImSTNag8SEWFAFAF6xIz4AJvCKapnrdHnZxep4bxw4PhG+ZbimYBMyKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "30.5.1", - "@types/node": "*", - "chalk": "^4.1.2", - "jest-message-util": "30.5.1", - "jest-util": "30.5.1", - "slash": "^3.0.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/core": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/core/-/core-30.5.2.tgz", - "integrity": "sha512-/jqvFWoJF7LV1a6AUpYMbMm+2yIYsHJfR474H0SCzr9k8tnO/jl9wRg6zSG6lxgf6EozNlCG4amFzWsbZSvvZA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/console": "30.5.2", - "@jest/pattern": "30.5.0", - "@jest/reporters": "30.5.2", - "@jest/test-result": "30.5.2", - "@jest/transform": "30.5.2", - "@jest/types": "30.5.1", - "@types/node": "*", - "ansi-escapes": "^4.3.2", - "chalk": "^4.1.2", - "ci-info": "^4.2.0", - "exit-x": "^0.2.2", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.11", - "jest-changed-files": "30.5.1", - "jest-config": "30.5.2", - "jest-haste-map": "30.5.1", - "jest-message-util": "30.5.1", - "jest-regex-util": "30.5.0", - "jest-resolve": "30.5.1", - "jest-resolve-dependencies": "30.5.2", - "jest-runner": "30.5.2", - "jest-runtime": "30.5.2", - "jest-snapshot": "30.5.2", - "jest-util": "30.5.1", - "jest-validate": "30.5.1", - "jest-watcher": "30.5.2", - "pretty-format": "30.5.1", - "slash": "^3.0.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/diff-sequences": { - "version": "30.5.0", - "resolved": "https://registry.npmjs.org/@jest/diff-sequences/-/diff-sequences-30.5.0.tgz", - "integrity": "sha512-OsqBjHXCn8cadasoAZBP6nWYvMsRhpMzGXTpxJ5aO04NlbdhIz+FVe3q49l0AwVhsz/cEmIpBes6gAFl1/dWQg==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/environment": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/environment/-/environment-30.5.2.tgz", - "integrity": "sha512-nwFPOUMbmsjNNRCpnJpB9HbSZu4C07wDDds++5j+j1MezzPLxMPDdbdUVjr2o4RULDOValnDd70taPFI1EtxAg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/fake-timers": "30.5.2", - "@jest/types": "30.5.1", - "@types/node": "*", - "jest-mock": "30.5.2" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/expect": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/expect/-/expect-30.5.2.tgz", - "integrity": "sha512-2E+1Pg6jJxbRjLNLpciC71iri/3qsKJL222/aXJEFwC0VdUSvfS+JZQQLEVjUYYc8t8pQu2MGE3cF2+bNTYRsg==", - "dev": true, - "license": "MIT", - "dependencies": { - "expect": "30.5.2", - "jest-snapshot": "30.5.2" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/expect-utils": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/expect-utils/-/expect-utils-30.5.2.tgz", - "integrity": "sha512-d/HOLSrJUlBIl6n3LzOa7cjW3xdePm5H5gQw2lixZ/0h157l9sw3mLblzFqnPcTbhDzhRQdBOX3A3KcG73nm5Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/get-type": "30.5.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/fake-timers": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/fake-timers/-/fake-timers-30.5.2.tgz", - "integrity": "sha512-GKk0h0tKT5SpDPxDhPg3r9mm5s8/YCBzVNMOGdRiQXwUiMsjU10mVPlMaQstH6/cu50vOb8N9oQUMETHuwwxKw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "30.5.1", - "@sinonjs/fake-timers": "^15.4.0", - "@types/node": "*", - "jest-message-util": "30.5.1", - "jest-mock": "30.5.2", - "jest-util": "30.5.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/get-type": { - "version": "30.5.0", - "resolved": "https://registry.npmjs.org/@jest/get-type/-/get-type-30.5.0.tgz", - "integrity": "sha512-9/2VUPitAjmBzbvDvqrxmvB7BzWsBW0WmkkojX1ODuxX1NLGxx9gfaZpHB0z8DtJ9uhGNmZG/VXBhf8uO0OV8Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/globals": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/globals/-/globals-30.5.2.tgz", - "integrity": "sha512-62zfS+dL+M5aTNHXCNLyqD+j4oqxTIzDYrZbpqMP8Yn+gvlAGyzC6BSPNb1ZmFOakV1RtFYX/O3FCQXSWmQdgg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "30.5.2", - "@jest/expect": "30.5.2", - "@jest/types": "30.5.1", - "jest-mock": "30.5.2" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/pattern": { - "version": "30.5.0", - "resolved": "https://registry.npmjs.org/@jest/pattern/-/pattern-30.5.0.tgz", - "integrity": "sha512-HdNQYSdRTEBNrginaqzQtTjG0HRMfrra/z6Ok7uL3S87vSlarIVohEsJsSj5edu3MiHoHjAkvPROz5ZjoKai+w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "jest-regex-util": "30.5.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/react-is-18": { - "name": "react-is", - "version": "18.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-18.3.1.tgz", - "integrity": "sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jest/react-is-19": { - "name": "react-is", - "version": "19.3.1", - "resolved": "https://registry.npmjs.org/react-is/-/react-is-19.3.1.tgz", - "integrity": "sha512-RRieF6IyxQBkcK6pP8xOHprLTPW6QjRkbGdImtqNme+/hYVwCZkLQLdlZGOhUqXwkS9IEynaGvPJtv6XB/cz0Q==", - "dev": true, - "license": "MIT" - }, - "node_modules/@jest/reporters": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/reporters/-/reporters-30.5.2.tgz", - "integrity": "sha512-ev6E9iG73twQcfAfoTnviuYkr3yOrYbzAtMFCimv2fxHXPIp9PBt2u1wNMt0aYWgl8FPwIcS8oqRJg6alnht4Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "@bcoe/v8-coverage": "^0.2.3", - "@jest/console": "30.5.2", - "@jest/test-result": "30.5.2", - "@jest/transform": "30.5.2", - "@jest/types": "30.5.1", - "@jridgewell/trace-mapping": "^0.3.31", - "@types/node": "*", - "chalk": "^4.1.2", - "collect-v8-coverage": "^1.0.2", - "exit-x": "^0.2.2", - "glob": "^13.0.6", - "graceful-fs": "^4.2.11", - "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^6.0.0", - "istanbul-lib-report": "^3.0.0", - "istanbul-lib-source-maps": "^5.0.0", - "istanbul-reports": "^3.1.3", - "jest-message-util": "30.5.1", - "jest-util": "30.5.1", - "jest-worker": "30.5.1", - "slash": "^3.0.0", - "string-length": "^4.0.2", - "v8-to-istanbul": "^9.0.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/@jest/reporters/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/@jest/reporters/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/@jest/reporters/node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "minimatch": "^10.2.2", - "minipass": "^7.1.3", - "path-scurry": "^2.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@jest/reporters/node_modules/minimatch": { - "version": "10.2.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", - "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.8" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/@jest/schemas": { - "version": "30.5.0", - "resolved": "https://registry.npmjs.org/@jest/schemas/-/schemas-30.5.0.tgz", - "integrity": "sha512-/hunigyNpc4RCjC0VaW3f5RCUZVM2+WQ65qP7z083Gmvac7or2LI50XVNOtE4YPgBpV0yxYiAgorAPGniCoJmg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@sinclair/typebox": "^0.34.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/snapshot-utils": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/@jest/snapshot-utils/-/snapshot-utils-30.5.1.tgz", - "integrity": "sha512-V3wnxNtiVmw5PPVg433Cn3VdXnsOeu/ofLw3KC04Bn2y1wIlU5kozXQn48rhrgj/02LrCVtntTEF1yBha0XSUw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "30.5.1", - "chalk": "^4.1.2", - "graceful-fs": "^4.2.11", - "natural-compare": "^1.4.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/source-map": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/source-map/-/source-map-30.5.2.tgz", - "integrity": "sha512-c5CehvkbfHX6yyNg7bMn2ylqlp9AHXuZ/3hPH/Lh5bxD/vefd/lV9HBjMqXef9yQNqkdwyZvkLSVSwB38hy8Qw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.31", - "callsites": "^3.1.0", - "convert-source-map": "^2.0.0", - "graceful-fs": "^4.2.11" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/test-result": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/test-result/-/test-result-30.5.2.tgz", - "integrity": "sha512-eO6YU5rsLfs60ne694e0IAmRgeBnoA8mu0nlxXDbl/1j5km0o2vO9/VbbUIKIH+WRKKEI+ELgwraRGn2Lhep8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/console": "30.5.2", - "@jest/types": "30.5.1", - "@types/istanbul-lib-coverage": "^2.0.6", - "collect-v8-coverage": "^1.0.2" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/test-sequencer": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/test-sequencer/-/test-sequencer-30.5.2.tgz", - "integrity": "sha512-bmij8jZyYAC47ExT2GeP7PcrlwSNS+Bp3KeRuBH88gpcxqDv6fljN8PemS4J/lLZ79xb6mpaennQTTq0zUAVVg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/test-result": "30.5.2", - "graceful-fs": "^4.2.11", - "jest-haste-map": "30.5.1", - "slash": "^3.0.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/transform": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/@jest/transform/-/transform-30.5.2.tgz", - "integrity": "sha512-LBGwmaE886C41jDZ65eqR1YbXM7642MK3ZhTowZd5+xDlrDLuf4ePuDdDmVSvcr8NTVJ3MqxLkMbUCzuigUaoQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.27.4", - "@jest/types": "30.5.1", - "@jridgewell/trace-mapping": "^0.3.31", - "babel-plugin-istanbul": "^8.0.0", - "chalk": "^4.1.2", - "convert-source-map": "^2.0.0", - "fast-json-stable-stringify": "^2.1.0", - "graceful-fs": "^4.2.11", - "jest-haste-map": "30.5.1", - "jest-regex-util": "30.5.0", - "jest-util": "30.5.1", - "pirates": "^4.0.7", - "slash": "^3.0.0", - "write-file-atomic": "^5.0.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/@jest/types": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/@jest/types/-/types-30.5.1.tgz", - "integrity": "sha512-LvVYn83nnXPl+Rg98nvcFgjx6nRMTArhSn6RAX/w3ELn54S8A42TYZvsCMdGUqTM8S0wyXbtlQdU6Hi6dykj9g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/pattern": "30.5.0", - "@jest/schemas": "30.5.0", - "@types/istanbul-lib-coverage": "^2.0.6", - "@types/istanbul-reports": "^3.0.4", - "@types/node": "*", - "@types/yargs": "^17.0.33", - "chalk": "^4.1.2" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, "node_modules/@jridgewell/gen-mapping": { "version": "0.3.13", "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", @@ -2411,28 +1680,6 @@ "url": "https://opencollective.com/js-sdsl" } }, - "node_modules/@napi-rs/wasm-runtime": { - "version": "1.2.6", - "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.2.6.tgz", - "integrity": "sha512-mRyDmEw9/fCDXCGfL1sbgIw/GUK0PVxRW4YwgPN61F3LQ+fSyoBFarJVzgGyhF6kRzEQZ0FejDqm4WLXSeqQmw==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@tybys/wasm-util": "^0.10.3" - }, - "engines": { - "node": "^20.19.0 || ^22.13.0 || >=23.5.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/Brooooooklyn" - }, - "peerDependencies": { - "@emnapi/core": "^1.7.1 || 2.0.0-beta.2", - "@emnapi/runtime": "^1.7.1 || 2.0.0-beta.2" - } - }, "node_modules/@opentelemetry/api": { "version": "1.10.0", "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.10.0.tgz", @@ -4020,19 +3267,6 @@ "node": ">=14" } }, - "node_modules/@pkgr/core": { - "version": "0.3.6", - "resolved": "https://registry.npmjs.org/@pkgr/core/-/core-0.3.6.tgz", - "integrity": "sha512-SEeaJLb3qBNF/OaXnaR1NmmBbFYk1zC0ZH/52fATcRPLFg/p791YrcyFFy44Bo9sLaGuSuLp5Q6axbb/O+v/RA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/pkgr" - } - }, "node_modules/@playwright/test": { "version": "1.64.1", "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", @@ -4634,33 +3868,6 @@ "win32" ] }, - "node_modules/@sinclair/typebox": { - "version": "0.34.52", - "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.34.52.tgz", - "integrity": "sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw==", - "dev": true, - "license": "MIT" - }, - "node_modules/@sinonjs/commons": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@sinonjs/commons/-/commons-3.0.1.tgz", - "integrity": "sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "type-detect": "4.0.8" - } - }, - "node_modules/@sinonjs/fake-timers": { - "version": "15.4.0", - "resolved": "https://registry.npmjs.org/@sinonjs/fake-timers/-/fake-timers-15.4.0.tgz", - "integrity": "sha512-DsG+8/LscQIQg68J6Ef3dv10u6nVyetYn923s3/sus5eaGfTo1of5WMZSLf0UJc9KDuKPilPH0UDJCjvNbDNCA==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@sinonjs/commons": "^3.0.1" - } - }, "node_modules/@tailwindcss/cli": { "version": "4.3.3", "resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.3.3.tgz", @@ -5011,25 +4218,6 @@ "node": ">=12" } }, - "node_modules/@tybys/wasm-util": { - "version": "0.10.4", - "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.4.tgz", - "integrity": "sha512-W3c4gRigFS0T/Ma4qIYF3GDAc5AQdHb1yL5znJT1Zv1YaD9Kitx656wBjvr19qbiosmZT8lWDM5BEMynUqX65A==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "tslib": "^2.4.0" - } - }, - "node_modules/@tybys/wasm-util/node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "dev": true, - "license": "0BSD", - "optional": true - }, "node_modules/@types/aws-lambda": { "version": "8.10.164", "resolved": "https://registry.npmjs.org/@types/aws-lambda/-/aws-lambda-8.10.164.tgz", @@ -5041,6 +4229,8 @@ "resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz", "integrity": "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==", "dev": true, + "optional": true, + "peer": true, "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", @@ -5054,6 +4244,8 @@ "resolved": "https://registry.npmjs.org/@types/babel__generator/-/babel__generator-7.6.8.tgz", "integrity": "sha512-ASsj+tpEDsEiFr1arWrlN6V3mdfjRMZt6LtK/Vp/kreFLnr5QH5+DhvD5nINYZXzwJvXeGq+05iUXcAzVrqWtw==", "dev": true, + "optional": true, + "peer": true, "dependencies": { "@babel/types": "^7.0.0" } @@ -5063,6 +4255,8 @@ "resolved": "https://registry.npmjs.org/@types/babel__template/-/babel__template-7.4.4.tgz", "integrity": "sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==", "dev": true, + "optional": true, + "peer": true, "dependencies": { "@babel/parser": "^7.1.0", "@babel/types": "^7.0.0" @@ -5073,6 +4267,8 @@ "resolved": "https://registry.npmjs.org/@types/babel__traverse/-/babel__traverse-7.20.6.tgz", "integrity": "sha512-r1bzfrm0tomOI8g1SzvCaQHo6Lcv6zu0EA+W2kHrt8dyrHQxGzBBL4kdkzIS+jBMV+EYcMAEAqXqYaLJq5rOZg==", "dev": true, + "optional": true, + "peer": true, "dependencies": { "@babel/types": "^7.20.7" } @@ -5093,33 +4289,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/istanbul-lib-coverage": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz", - "integrity": "sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==", - "dev": true, - "license": "MIT" - }, - "node_modules/@types/istanbul-lib-report": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz", - "integrity": "sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/istanbul-lib-coverage": "*" - } - }, - "node_modules/@types/istanbul-reports": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz", - "integrity": "sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/istanbul-lib-report": "*" - } - }, "node_modules/@types/memcached": { "version": "2.2.10", "resolved": "https://registry.npmjs.org/@types/memcached/-/memcached-2.2.10.tgz", @@ -5176,13 +4345,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/stack-utils": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/@types/stack-utils/-/stack-utils-2.0.3.tgz", - "integrity": "sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/trusted-types": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", @@ -5190,343 +4352,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/yargs": { - "version": "17.0.35", - "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.35.tgz", - "integrity": "sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/yargs-parser": "*" - } - }, - "node_modules/@types/yargs-parser": { - "version": "21.0.3", - "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz", - "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/@ungap/structured-clone": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.4.0.tgz", - "integrity": "sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/@unrs/resolver-binding-android-arm-eabi": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.12.2.tgz", - "integrity": "sha512-g5T90pqg1bo/7mytQx6F4iBNC0Wsh9cu+z9veDbFjc7HjpesJFWD7QMS0NGStXM075+7dJPPVvBbpZlnrdpi/w==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@unrs/resolver-binding-android-arm64": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.12.2.tgz", - "integrity": "sha512-YGCRZv/9GLhwmz6mYDeTsm/92BAyR28l6c2ReweVW5pWgfsitWLY8upvfRlGdoyD8HjeTHSYJWyZGD4KJA/nFQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ] - }, - "node_modules/@unrs/resolver-binding-darwin-arm64": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.12.2.tgz", - "integrity": "sha512-u9DiNT1auQMO20A9SyTuG3wUgQWB9Z7KjAg0uFuCDR1FsAY8A0CG2S6JpHS1xwm/w1G08bjXZDcyOCjv1WAm2w==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@unrs/resolver-binding-darwin-x64": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.12.2.tgz", - "integrity": "sha512-f7rPLi/T1HVKZu/u6t87lroib16n8vrSzcyxI7lg4BGO9UF26KhQL44sd9eOUgrTYhvRXtWOIZT5PejdPyJfUA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ] - }, - "node_modules/@unrs/resolver-binding-freebsd-x64": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.12.2.tgz", - "integrity": "sha512-BpcOjWCJub6nRZUS2zA20pmLvjtqAtGejETaIyRLiZiQf++cbrjltLA5NN/xaXfqeOBOSlMFbemIl5/S5tljmg==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ] - }, - "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.12.2.tgz", - "integrity": "sha512-vZTDvdSISZjJx66OzJqtsOhzifbqRjbmI1Mnu49fQDwog5GtDI4QidRiEAYbZCRj9C8YZEW+3ZjqsyS9GR4k2A==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.12.2.tgz", - "integrity": "sha512-BiPI+IrIlwcW4nLLMM21+B1dFPzd55yAVgVGrdgDjNef+ch03GdxrcyaIz8X9SsQirh/kCQ7mviyWlMxdh2D7g==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-arm64-gnu": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.12.2.tgz", - "integrity": "sha512-zJc0H99FEPoFfSrNpa91HYfxzfAJCr502oxNK1cfdC9hlaFI43RT+JFCann9JUgZmLzzntChHyn13Sgn9ljHNg==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-arm64-musl": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.12.2.tgz", - "integrity": "sha512-KQ3Lki6l+Pz1k/eBipN41ES+YUK30beLGb9YqcB1O542cyLCNE6GaxrfcY3T6EezmGGk84wb5XyO9loTM9tkcA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-loong64-gnu": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-loong64-gnu/-/resolver-binding-linux-loong64-gnu-1.12.2.tgz", - "integrity": "sha512-3SJGEh1DborhG6pyxvhPzCT4bbSIVihsvgJc13P1bHG7KLdNDaF9T3gsTwFc7Jw/5Y5/iWOjkEx7Zy0NvCGX3Q==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-loong64-musl": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-loong64-musl/-/resolver-binding-linux-loong64-musl-1.12.2.tgz", - "integrity": "sha512-jiuG/Obbel7uw1PwHNFfrkiKhLAF6mnyZ6aWlOAVN9WqKm8v0OFGnciJIHu8+CMvXLQ8AD51LPzAoUfT21D5Ew==", - "cpu": [ - "loong64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.12.2.tgz", - "integrity": "sha512-q7xRvVpmcfeL+LlZg8Pbbo6QaTZwDU5BaGZbwfhkEsXJn3Was8xYfE0RBH266xZt0rM6B7i8xAYIvjthuUIWHg==", - "cpu": [ - "ppc64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.12.2.tgz", - "integrity": "sha512-0CVdx6lcnT3Q9inOH8tsMIOJ6ImndllMjqJHg8RLVdB7Vq4SfkEXl9mCSsVNuNA4MCYycRicCUxPCabVHJRr6A==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-riscv64-musl": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.12.2.tgz", - "integrity": "sha512-iOwlRo9vnp6R6ohHQS11n0NnfdXx/omhkocmIfaPRpQhKZ+3BDMkkdRVh53qjkFkpPddf+FETA28NwGN7l5l+w==", - "cpu": [ - "riscv64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-s390x-gnu": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.12.2.tgz", - "integrity": "sha512-HYJtLfXq94q8iZNFT1lknx258wlkkWhZeUXJRqzKBBUJ00CvZ+N33zgbCqimLjsyw5Va6uUxhVa12mI+kaveEw==", - "cpu": [ - "s390x" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-x64-gnu": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.12.2.tgz", - "integrity": "sha512-mPsUhunKKDih5O96Y6enDQyHc1SqBPlY1E/SfMWDM3EdJ95Z9CArPeCVwCCqbP45ljvivdEk8Fxn+SIb1rDAJQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-linux-x64-musl": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.12.2.tgz", - "integrity": "sha512-azrt6+5ydLd8Vt210AAFis/lZevSfPw93EJRIJG+xPu4WCJ8K0kppCTpMyLPcKT7H15M4Jnt2tMp5bOvCkRC6A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ] - }, - "node_modules/@unrs/resolver-binding-openharmony-arm64": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-openharmony-arm64/-/resolver-binding-openharmony-arm64-1.12.2.tgz", - "integrity": "sha512-YZ9hP4O0X9PQb8eO980qmLNGH4zT3I9+SZTdt0Pr0YyuGQhYKoOZkV02VzrzyOZJ5xIJ3UFIenKkUkGg8GjgWQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "openharmony" - ] - }, - "node_modules/@unrs/resolver-binding-wasm32-wasi": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.12.2.tgz", - "integrity": "sha512-tYFDIkMxSflfEc/h92ZWNsZlHSwgimbNHSO3PL2JWQHfCuC2q316jMyYU9TIWZsFK2bQwyK5VAdYgn8ygPj69A==", - "cpu": [ - "wasm32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@emnapi/core": "1.10.0", - "@emnapi/runtime": "1.10.0", - "@napi-rs/wasm-runtime": "^1.1.4" - }, - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/@unrs/resolver-binding-win32-arm64-msvc": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.12.2.tgz", - "integrity": "sha512-qzNyg3xL0VPQmCaUh+N5jSitce6k+uCBfMDesWRnlULOZaqUkaJ0ybdT+UqlAWJoQjuqfIU/0Ptx9bteN4D82g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@unrs/resolver-binding-win32-ia32-msvc": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.12.2.tgz", - "integrity": "sha512-WD9sY00OfpHVGfsnHZoA8jVT+esS/Bg8z8jzxp5BnDCjjwsuKsPQrzswwpFy4J1AUJbXPRfkpcX0mXrzeXW79g==", - "cpu": [ - "ia32" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, - "node_modules/@unrs/resolver-binding-win32-x64-msvc": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.12.2.tgz", - "integrity": "sha512-nAB74NfSNKknqQ1RrYj6uz8FcXEomu/MATJZxh/x+BArzN2U3JbOYC0APYzUIGhVY3m5hRxA8VPNdPBoG8txlA==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ] - }, "node_modules/acorn": { "version": "8.15.0", "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", @@ -5634,16 +4459,6 @@ "node": ">= 8" } }, - "node_modules/argparse": { - "version": "1.0.10", - "resolved": "https://registry.npmjs.org/argparse/-/argparse-1.0.10.tgz", - "integrity": "sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "sprintf-js": "~1.0.2" - } - }, "node_modules/array-buffer-byte-length": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", @@ -5783,61 +4598,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/babel-jest": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/babel-jest/-/babel-jest-30.5.2.tgz", - "integrity": "sha512-ES8WeJ2fNWPEDunyAtUfJ12nHyaWUloCHdkfK2oW5uSoQSUmjNKdWiGaXJITJwvFEWoD/evHEg/QoCXAvLaQqQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/transform": "30.5.2", - "@types/babel__core": "^7.20.5", - "babel-plugin-istanbul": "^8.0.0", - "babel-preset-jest": "30.5.0", - "chalk": "^4.1.2", - "graceful-fs": "^4.2.11", - "slash": "^3.0.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.11.0 || ^8.0.0-0" - } - }, - "node_modules/babel-plugin-istanbul": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/babel-plugin-istanbul/-/babel-plugin-istanbul-8.0.0.tgz", - "integrity": "sha512-18wCskrN3DgbuBmp1gr7LBGT8xdz5xhQQqFvFhVxbkl8VBCrMKQ2YtqBWtUal1Zrc1HTuX0011+Brjw78TCFkg==", - "dev": true, - "license": "BSD-3-Clause", - "workspaces": [ - "test/babel-8" - ], - "dependencies": { - "@babel/helper-plugin-utils": "^7.0.0", - "@istanbuljs/load-nyc-config": "^1.0.0", - "@istanbuljs/schema": "^0.1.3", - "istanbul-lib-instrument": "^6.0.2", - "test-exclude": "^7.0.1" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/babel-plugin-jest-hoist": { - "version": "30.5.0", - "resolved": "https://registry.npmjs.org/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-30.5.0.tgz", - "integrity": "sha512-gtGo1B+u14jrZQv6TdSWIWkTqclboo7Qn+dFAGUOIuXLFuJKAdg3U5MIWzZnW4vfUb4dX9skmAMiby86e/SF4A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/babel__core": "^7.20.5" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, "node_modules/babel-plugin-polyfill-corejs2": { "version": "0.4.17", "resolved": "https://registry.npmjs.org/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.17.tgz", @@ -5880,50 +4640,6 @@ "@babel/core": "^7.4.0 || ^8.0.0-0 <8.0.0" } }, - "node_modules/babel-preset-current-node-syntax": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.2.0.tgz", - "integrity": "sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/plugin-syntax-async-generators": "^7.8.4", - "@babel/plugin-syntax-bigint": "^7.8.3", - "@babel/plugin-syntax-class-properties": "^7.12.13", - "@babel/plugin-syntax-class-static-block": "^7.14.5", - "@babel/plugin-syntax-import-attributes": "^7.24.7", - "@babel/plugin-syntax-import-meta": "^7.10.4", - "@babel/plugin-syntax-json-strings": "^7.8.3", - "@babel/plugin-syntax-logical-assignment-operators": "^7.10.4", - "@babel/plugin-syntax-nullish-coalescing-operator": "^7.8.3", - "@babel/plugin-syntax-numeric-separator": "^7.10.4", - "@babel/plugin-syntax-object-rest-spread": "^7.8.3", - "@babel/plugin-syntax-optional-catch-binding": "^7.8.3", - "@babel/plugin-syntax-optional-chaining": "^7.8.3", - "@babel/plugin-syntax-private-property-in-object": "^7.14.5", - "@babel/plugin-syntax-top-level-await": "^7.14.5" - }, - "peerDependencies": { - "@babel/core": "^7.0.0 || ^8.0.0-0" - } - }, - "node_modules/babel-preset-jest": { - "version": "30.5.0", - "resolved": "https://registry.npmjs.org/babel-preset-jest/-/babel-preset-jest-30.5.0.tgz", - "integrity": "sha512-ZGPn5ClP4lBDpuOK8W1yQIOy359HmbnZv3suucAlIe+SEE9yDsxV4S2PjSbH2Vc97U+WmzYD7vw3kr8NsQ/i6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "babel-plugin-jest-hoist": "30.5.0", - "babel-preset-current-node-syntax": "^1.2.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - }, - "peerDependencies": { - "@babel/core": "^7.11.0 || ^8.0.0-beta.1 || ^8.0.0" - } - }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -6203,16 +4919,6 @@ "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" } }, - "node_modules/bser": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/bser/-/bser-2.1.2.tgz", - "integrity": "sha512-V2o8YS2EhrKMO9AumnkK0ynynfFlsajpYupwq7S46H5mhcanwxDkNTw3K67wPIcKTH1ffkA4vhMOtAc7gRmPZw==", - "dev": true, - "license": "MIT", - "dependencies": { - "node-int64": "^0.4.0" - } - }, "node_modules/buffer": { "version": "5.7.1", "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", @@ -6293,16 +4999,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/callsites": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", - "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/camelcase": { "version": "5.3.1", "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", @@ -6366,16 +5062,6 @@ "url": "https://github.com/chalk/chalk?sponsor=1" } }, - "node_modules/char-regex": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/char-regex/-/char-regex-1.0.2.tgz", - "integrity": "sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - } - }, "node_modules/chardet": { "version": "0.7.0", "resolved": "https://registry.npmjs.org/chardet/-/chardet-0.7.0.tgz", @@ -6418,22 +5104,6 @@ "node": ">= 6" } }, - "node_modules/ci-info": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", - "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/cjs-module-lexer": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/cjs-module-lexer/-/cjs-module-lexer-2.2.0.tgz", @@ -6508,24 +5178,6 @@ "node": ">=0.8" } }, - "node_modules/co": { - "version": "4.6.0", - "resolved": "https://registry.npmjs.org/co/-/co-4.6.0.tgz", - "integrity": "sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ==", - "dev": true, - "license": "MIT", - "engines": { - "iojs": ">= 1.0.0", - "node": ">= 0.12.0" - } - }, - "node_modules/collect-v8-coverage": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz", - "integrity": "sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw==", - "dev": true, - "license": "MIT" - }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -6782,21 +5434,6 @@ "node": ">=0.10.0" } }, - "node_modules/dedent": { - "version": "1.7.2", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.2.tgz", - "integrity": "sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA==", - "dev": true, - "license": "MIT", - "peerDependencies": { - "babel-plugin-macros": "^3.1.0" - }, - "peerDependenciesMeta": { - "babel-plugin-macros": { - "optional": true - } - } - }, "node_modules/deep-extend": { "version": "0.6.0", "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", @@ -6875,16 +5512,6 @@ "node": ">=0.10" } }, - "node_modules/detect-newline": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/detect-newline/-/detect-newline-3.1.0.tgz", - "integrity": "sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/dot-prop": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/dot-prop/-/dot-prop-9.0.0.tgz", @@ -6958,19 +5585,6 @@ "dev": true, "license": "ISC" }, - "node_modules/emittery": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/emittery/-/emittery-0.13.1.tgz", - "integrity": "sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sindresorhus/emittery?sponsor=1" - } - }, "node_modules/emoji-regex": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", @@ -7161,30 +5775,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/escape-string-regexp": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", - "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/esprima": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", - "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", - "dev": true, - "license": "BSD-2-Clause", - "bin": { - "esparse": "bin/esparse.js", - "esvalidate": "bin/esvalidate.js" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/estree-walker": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz", @@ -7215,58 +5805,6 @@ "url": "https://github.com/bgub/eta?sponsor=1" } }, - "node_modules/execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "license": "MIT", - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" - } - }, - "node_modules/exit-x": { - "version": "0.2.2", - "resolved": "https://registry.npmjs.org/exit-x/-/exit-x-0.2.2.tgz", - "integrity": "sha512-+I6B/IkJc1o/2tiURyz/ivu/O0nKNEArIUB5O7zBrlDVJr22SCLH3xTeEry428LvFhRzIA1g8izguxJ/gbNcVQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/expect": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/expect/-/expect-30.5.2.tgz", - "integrity": "sha512-0LNuMvs8/5mRYhnCR4k+lGV7fqPMs6Bnksda4S3zsCUmdxBpAn4zU4NNzXdq1pMKe/H4W5t/zVIDSJ/H3e0vDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/expect-utils": "30.5.2", - "@jest/get-type": "30.5.0", - "jest-matcher-utils": "30.5.2", - "jest-message-util": "30.5.1", - "jest-mock": "30.5.2", - "jest-util": "30.5.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, "node_modules/extend": { "version": "3.0.2", "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", @@ -7317,16 +5855,6 @@ ], "license": "BSD-3-Clause" }, - "node_modules/fb-watchman": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/fb-watchman/-/fb-watchman-2.0.4.tgz", - "integrity": "sha512-tGQtaoYisPDriJBN0mT5yZSyNETnJGA1gTYxaVRAE5KUO3LI9kPUc9WIu8JXcxaIci+faIKlzXqXyPgrmubtBQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "bser": "2.1.2" - } - }, "node_modules/fetch-blob": { "version": "3.2.0", "resolved": "https://registry.npmjs.org/fetch-blob/-/fetch-blob-3.2.0.tgz", @@ -7668,16 +6196,6 @@ "dev": true, "license": "ISC" }, - "node_modules/get-package-type": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/get-package-type/-/get-package-type-0.1.0.tgz", - "integrity": "sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8.0.0" - } - }, "node_modules/get-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", @@ -7692,19 +6210,6 @@ "node": ">= 0.4" } }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/get-symbol-description": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", @@ -8044,13 +6549,6 @@ "integrity": "sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==", "dev": true }, - "node_modules/html-escaper": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/html-escaper/-/html-escaper-2.0.2.tgz", - "integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==", - "dev": true, - "license": "MIT" - }, "node_modules/html2canvas": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/html2canvas/-/html2canvas-1.4.1.tgz", @@ -8076,16 +6574,6 @@ "node": ">= 14" } }, - "node_modules/human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=10.17.0" - } - }, "node_modules/iconv-lite": { "version": "0.4.24", "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", @@ -8139,36 +6627,6 @@ "node": ">=18" } }, - "node_modules/import-local": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", - "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "pkg-dir": "^4.2.0", - "resolve-cwd": "^3.0.0" - }, - "bin": { - "import-local-fixture": "fixtures/cli.js" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/imurmurhash": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", - "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.8.19" - } - }, "node_modules/indent-string": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-4.0.0.tgz", @@ -8417,16 +6875,6 @@ "node": ">=8" } }, - "node_modules/is-generator-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-generator-fn/-/is-generator-fn-2.1.0.tgz", - "integrity": "sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/is-generator-function": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", @@ -8794,90 +7242,6 @@ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" }, - "node_modules/istanbul-lib-coverage": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz", - "integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=8" - } - }, - "node_modules/istanbul-lib-instrument": { - "version": "6.0.3", - "resolved": "https://registry.npmjs.org/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz", - "integrity": "sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@babel/core": "^7.23.9", - "@babel/parser": "^7.23.9", - "@istanbuljs/schema": "^0.1.3", - "istanbul-lib-coverage": "^3.2.0", - "semver": "^7.5.4" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-instrument/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-report": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz", - "integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "istanbul-lib-coverage": "^3.0.0", - "make-dir": "^4.0.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-lib-source-maps": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/istanbul-lib-source-maps/-/istanbul-lib-source-maps-5.0.6.tgz", - "integrity": "sha512-yg2d+Em4KizZC5niWhQaIomgf5WlL4vOOjZ5xGCmF8SnPE/mDWWXgvRExdcpCgh9lLRRa1/fSYp2ymmbJ1pI+A==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.23", - "debug": "^4.1.1", - "istanbul-lib-coverage": "^3.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/istanbul-reports": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/istanbul-reports/-/istanbul-reports-3.2.0.tgz", - "integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==", - "dev": true, - "license": "BSD-3-Clause", - "dependencies": { - "html-escaper": "^2.0.0", - "istanbul-lib-report": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/jackspeak": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/jackspeak/-/jackspeak-4.2.3.tgz", @@ -8912,1056 +7276,6 @@ "node": ">=10" } }, - "node_modules/jest": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest/-/jest-30.5.2.tgz", - "integrity": "sha512-3gnpdBIza8ijCl3iMV9ChE3hSt1+46865qqod863gQtJr1DixOkAU5DoGbi3u+XlRcw++BhZQMu/y4xBdHBvSQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/core": "30.5.2", - "@jest/types": "30.5.1", - "import-local": "^3.2.0", - "jest-cli": "30.5.2" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-changed-files": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/jest-changed-files/-/jest-changed-files-30.5.1.tgz", - "integrity": "sha512-0+bvMM/ENhDI29Z8q1r4HxiDIi4G5tnBmSw4esfPQoj9q8Nik7KIyuxHkTVnnniJQf05SxpGaKDQ+4h28ynGPg==", - "dev": true, - "license": "MIT", - "dependencies": { - "execa": "^5.1.1", - "jest-util": "30.5.1", - "p-limit": "^3.1.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-circus": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-circus/-/jest-circus-30.5.2.tgz", - "integrity": "sha512-vffFgjs5JSJ9q4ds1vNW3klKYPJfYfIY61LT/zaZgvTeASJOWZUt8LBfHgIcV4rwxlPBLl/ePBGccHEclS4PlQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "30.5.2", - "@jest/expect": "30.5.2", - "@jest/test-result": "30.5.2", - "@jest/types": "30.5.1", - "@types/node": "*", - "chalk": "^4.1.2", - "co": "^4.6.0", - "dedent": "^1.6.0", - "is-generator-fn": "^2.1.0", - "jest-each": "30.5.2", - "jest-matcher-utils": "30.5.2", - "jest-message-util": "30.5.1", - "jest-runtime": "30.5.2", - "jest-snapshot": "30.5.2", - "jest-util": "30.5.1", - "p-limit": "^3.1.0", - "pretty-format": "30.5.1", - "pure-rand": "^7.0.0", - "slash": "^3.0.0", - "stack-utils": "^2.0.6" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-cli": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-cli/-/jest-cli-30.5.2.tgz", - "integrity": "sha512-YYYxUUVjFgPvgEleKNKMaYGIFgR3l3832Cl0kRL/oCiDZ03v7wImUtquHl2OOBCCNgprjZgBN5bczS/JklPBDg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/core": "30.5.2", - "@jest/test-result": "30.5.2", - "@jest/types": "30.5.1", - "chalk": "^4.1.2", - "exit-x": "^0.2.2", - "import-local": "^3.2.0", - "jest-config": "30.5.2", - "jest-util": "30.5.1", - "jest-validate": "30.5.1", - "yargs": "^17.7.2" - }, - "bin": { - "jest": "bin/jest.js" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - }, - "peerDependencies": { - "node-notifier": "^8.0.1 || ^9.0.0 || ^10.0.0" - }, - "peerDependenciesMeta": { - "node-notifier": { - "optional": true - } - } - }, - "node_modules/jest-config": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-config/-/jest-config-30.5.2.tgz", - "integrity": "sha512-U6221OZekabePvGcGPf4raIBKMvYQWFHvhobDJRojOYaFMj2HaGytAdknjDhYc6JTz2fdHW9+6k0wWUDaNeOFQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.27.4", - "@jest/get-type": "30.5.0", - "@jest/pattern": "30.5.0", - "@jest/test-sequencer": "30.5.2", - "@jest/types": "30.5.1", - "babel-jest": "30.5.2", - "chalk": "^4.1.2", - "ci-info": "^4.2.0", - "deepmerge": "^4.3.1", - "glob": "^13.0.6", - "graceful-fs": "^4.2.11", - "jest-circus": "30.5.2", - "jest-docblock": "30.5.0", - "jest-environment-node": "30.5.2", - "jest-regex-util": "30.5.0", - "jest-resolve": "30.5.1", - "jest-runner": "30.5.2", - "jest-util": "30.5.1", - "jest-validate": "30.5.1", - "parse-json": "^5.2.0", - "pretty-format": "30.5.1", - "slash": "^3.0.0", - "strip-json-comments": "^3.1.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - }, - "peerDependencies": { - "@types/node": "*", - "esbuild-register": ">=3.4.0", - "ts-node": ">=9.0.0" - }, - "peerDependenciesMeta": { - "@types/node": { - "optional": true - }, - "esbuild-register": { - "optional": true - }, - "ts-node": { - "optional": true - } - } - }, - "node_modules/jest-config/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/jest-config/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/jest-config/node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "minimatch": "^10.2.2", - "minipass": "^7.1.3", - "path-scurry": "^2.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/jest-config/node_modules/minimatch": { - "version": "10.2.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", - "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.8" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/jest-diff": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-diff/-/jest-diff-30.5.2.tgz", - "integrity": "sha512-rBtHnI6BWTiWj3lM7fOLVfChx7R9B0u9VV3PRHawKs79x6ZjW1QoSrKenaigNGWlvhtoi2BqvDbABDie+Os3xQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/diff-sequences": "30.5.0", - "@jest/get-type": "30.5.0", - "chalk": "^4.1.2", - "pretty-format": "30.5.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-docblock": { - "version": "30.5.0", - "resolved": "https://registry.npmjs.org/jest-docblock/-/jest-docblock-30.5.0.tgz", - "integrity": "sha512-NwDqcxtoZi33RhuW+zJS/RVA3rmheQ8BnwpYZuc/Eruaz6seQb7+aoCeDZu/3X7W2XmD8DbSo9Pn72DbKsBFYw==", - "dev": true, - "license": "MIT", - "dependencies": { - "detect-newline": "^3.1.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-each": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-each/-/jest-each-30.5.2.tgz", - "integrity": "sha512-GRrW+7fmmgmkvyfEBqc1QFdWnF1Ex5yG6Y6AWL4TTxnkWlKIT98dsKh3P3UuWm6v4XsQwVE6DEzXIPMzWJ3ZbA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/get-type": "30.5.0", - "@jest/types": "30.5.1", - "chalk": "^4.1.2", - "jest-regex-util": "30.5.0", - "jest-util": "30.5.1", - "pretty-format": "30.5.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-environment-node": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-environment-node/-/jest-environment-node-30.5.2.tgz", - "integrity": "sha512-Ciz4KgTGIbojxSKpuFImgWJj5EyqfE8xMq9NxWmOXnQywHHS03H9Mv+vaCB29J5pr3JBrY27WbRV18rBdjh8Dg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "30.5.2", - "@jest/fake-timers": "30.5.2", - "@jest/types": "30.5.1", - "@types/node": "*", - "jest-mock": "30.5.2", - "jest-util": "30.5.1", - "jest-validate": "30.5.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-haste-map": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/jest-haste-map/-/jest-haste-map-30.5.1.tgz", - "integrity": "sha512-VIFgt67jW480YDxKfEv9IYQKrFpYt7bOCMn3VsnjK7AK9qo7p6acpnA1DHwsVOULE3dTaYew/6JaTD/d0VDHoQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "30.5.1", - "@parcel/watcher": "^2.6.0", - "@types/node": "*", - "anymatch": "^3.1.3", - "fb-watchman": "^2.0.2", - "fdir": "^6.5.0", - "graceful-fs": "^4.2.11", - "jest-regex-util": "30.5.0", - "jest-util": "30.5.1", - "jest-worker": "30.5.1", - "picomatch": "^4.0.3" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", - "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "dependencies": { - "detect-libc": "^2.0.3", - "is-glob": "^4.0.3", - "node-addon-api": "^7.0.0", - "picomatch": "^4.0.4" - }, - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - }, - "optionalDependencies": { - "@parcel/watcher-android-arm64": "2.6.0", - "@parcel/watcher-darwin-arm64": "2.6.0", - "@parcel/watcher-darwin-x64": "2.6.0", - "@parcel/watcher-freebsd-x64": "2.6.0", - "@parcel/watcher-linux-arm-glibc": "2.6.0", - "@parcel/watcher-linux-arm-musl": "2.6.0", - "@parcel/watcher-linux-arm64-glibc": "2.6.0", - "@parcel/watcher-linux-arm64-musl": "2.6.0", - "@parcel/watcher-linux-x64-glibc": "2.6.0", - "@parcel/watcher-linux-x64-musl": "2.6.0", - "@parcel/watcher-win32-arm64": "2.6.0", - "@parcel/watcher-win32-x64": "2.6.0" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-android-arm64": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz", - "integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "android" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-darwin-arm64": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz", - "integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-darwin-x64": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz", - "integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-freebsd-x64": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz", - "integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "freebsd" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-arm-glibc": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz", - "integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-arm-musl": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz", - "integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==", - "cpu": [ - "arm" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-arm64-glibc": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz", - "integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-arm64-musl": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz", - "integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-x64-glibc": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz", - "integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-linux-x64-musl": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz", - "integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-win32-arm64": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz", - "integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==", - "cpu": [ - "arm64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/@parcel/watcher-win32-x64": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", - "integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==", - "cpu": [ - "x64" - ], - "dev": true, - "license": "MIT", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 10.0.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/parcel" - } - }, - "node_modules/jest-haste-map/node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/jest-haste-map/node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/jest-haste-map/node_modules/picomatch": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", - "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/jest-leak-detector": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/jest-leak-detector/-/jest-leak-detector-30.5.1.tgz", - "integrity": "sha512-gt4GT2aWgEoCNTcBe4rqS74xTIUJxi+UD9SNSu9aOk5LmTEd6fS5KSTmAKAfitCCktQHNN+upUuL6EkBfFbMDQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/get-type": "30.5.0", - "pretty-format": "30.5.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-matcher-utils": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-matcher-utils/-/jest-matcher-utils-30.5.2.tgz", - "integrity": "sha512-lFkB365PTIHOhPzwrb9T6gvlDnPpOZ7/c3ewOKKB7bzztqjVrtlyRL2MkyfJXpyY2u2SKw001JKrTx14fBUFcQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/get-type": "30.5.0", - "chalk": "^4.1.2", - "jest-diff": "30.5.2", - "pretty-format": "30.5.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-message-util": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/jest-message-util/-/jest-message-util-30.5.1.tgz", - "integrity": "sha512-UdQlLdd9wL/Ys7xRErckqwD6wPlSZYueosSWuHc1r2ztGLwlgPvtSJq2+BPEgaEY13WLvfFbmhTj8pba0Sd1jg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/code-frame": "^7.27.1", - "@jest/types": "30.5.1", - "@types/stack-utils": "^2.0.3", - "chalk": "^4.1.2", - "graceful-fs": "^4.2.11", - "jest-util": "30.5.1", - "picomatch": "^4.0.3", - "pretty-format": "30.5.1", - "slash": "^3.0.0", - "stack-utils": "^2.0.6" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-message-util/node_modules/picomatch": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", - "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/jest-mock": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-mock/-/jest-mock-30.5.2.tgz", - "integrity": "sha512-KTHb37Fhj8xY8qPFvTFaFJHcdsumQp+ExsUlgoX232Agmc706gagBs53+CYvulV7MVQo9AgXOUxsqzzVBoJlrA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/expect-utils": "30.5.2", - "@jest/types": "30.5.1", - "@types/node": "*", - "jest-util": "30.5.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-regex-util": { - "version": "30.5.0", - "resolved": "https://registry.npmjs.org/jest-regex-util/-/jest-regex-util-30.5.0.tgz", - "integrity": "sha512-Mg0WK7A6xRHLSA1udJ8y9f3lM0uUhFTBnLKzwPmqB9AylvpleJ6BLemR8K9dK27DY+cesDryoA7yLZCAHsPG1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-resolve": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/jest-resolve/-/jest-resolve-30.5.1.tgz", - "integrity": "sha512-wprhLejRtwN6h8ZgaqC0eYjGJ1uMdGPT/+b3eFncbG4NWuuP9QL+vWwRinu9waw7hkOLcpMJGVJAMgBwsPssMQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "chalk": "^4.1.2", - "graceful-fs": "^4.2.11", - "jest-haste-map": "30.5.1", - "jest-util": "30.5.1", - "jest-validate": "30.5.1", - "slash": "^3.0.0", - "unrs-resolver": "^1.12.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-resolve-dependencies": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-resolve-dependencies/-/jest-resolve-dependencies-30.5.2.tgz", - "integrity": "sha512-GMI0DP5enX9Z2qW2zFy1bOkrCfWAOPRJQ7qHt0pdfrxBPsgWxglMPrRSK2TX/wRWYxcPRSLFg3Z88qPOzHx7FQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "jest-regex-util": "30.5.0", - "jest-snapshot": "30.5.2" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-runner": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-runner/-/jest-runner-30.5.2.tgz", - "integrity": "sha512-/B6px7hiiNhVSRwuv9AGn0nawYvwsHeQZ3ItTd5Gp2diFd0EOKaWVeWqcbw3L88vx1GfpCKjQkxWItZCTl11Rw==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/console": "30.5.2", - "@jest/environment": "30.5.2", - "@jest/source-map": "30.5.2", - "@jest/test-result": "30.5.2", - "@jest/transform": "30.5.2", - "@jest/types": "30.5.1", - "@types/node": "*", - "chalk": "^4.1.2", - "emittery": "^0.13.1", - "exit-x": "^0.2.2", - "graceful-fs": "^4.2.11", - "jest-docblock": "30.5.0", - "jest-environment-node": "30.5.2", - "jest-haste-map": "30.5.1", - "jest-leak-detector": "30.5.1", - "jest-message-util": "30.5.1", - "jest-resolve": "30.5.1", - "jest-runtime": "30.5.2", - "jest-util": "30.5.1", - "jest-watcher": "30.5.2", - "jest-worker": "30.5.1", - "p-limit": "^3.1.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-runtime": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-runtime/-/jest-runtime-30.5.2.tgz", - "integrity": "sha512-0paUAHBlheai10A3XSy9Xh+YBG0IROy+/qzcDPzQ/nbbXrznQzeWy5qniICWK6d3W3scaRQCVAbXdcK0ibBq4w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/environment": "30.5.2", - "@jest/fake-timers": "30.5.2", - "@jest/globals": "30.5.2", - "@jest/source-map": "30.5.2", - "@jest/test-result": "30.5.2", - "@jest/transform": "30.5.2", - "@jest/types": "30.5.1", - "@types/node": "*", - "chalk": "^4.1.2", - "cjs-module-lexer": "^2.2.0", - "collect-v8-coverage": "^1.0.2", - "es-module-lexer": "^2.1.0", - "glob": "^13.0.6", - "graceful-fs": "^4.2.11", - "jest-haste-map": "30.5.1", - "jest-message-util": "30.5.1", - "jest-mock": "30.5.2", - "jest-regex-util": "30.5.0", - "jest-resolve": "30.5.1", - "jest-snapshot": "30.5.2", - "jest-util": "30.5.1", - "slash": "^3.0.0", - "strip-bom": "^4.0.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-runtime/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/jest-runtime/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/jest-runtime/node_modules/es-module-lexer": { - "version": "2.3.2", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", - "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", - "dev": true, - "license": "MIT" - }, - "node_modules/jest-runtime/node_modules/glob": { - "version": "13.0.6", - "resolved": "https://registry.npmjs.org/glob/-/glob-13.0.6.tgz", - "integrity": "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "minimatch": "^10.2.2", - "minipass": "^7.1.3", - "path-scurry": "^2.0.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/jest-runtime/node_modules/minimatch": { - "version": "10.2.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", - "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.8" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/jest-snapshot": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-snapshot/-/jest-snapshot-30.5.2.tgz", - "integrity": "sha512-jKIdes25AnAH73dOCi2qE6J6vHJ6L2vyBS11M89kT50DVJcLTf2AOjvcc+2vVaN8lUbY5v2R83aqXo3Ro9fqYA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@babel/core": "^7.27.4", - "@babel/generator": "^7.27.5", - "@babel/plugin-syntax-jsx": "^7.27.1", - "@babel/plugin-syntax-typescript": "^7.27.1", - "@babel/types": "^7.27.3", - "@jest/expect-utils": "30.5.2", - "@jest/get-type": "30.5.0", - "@jest/snapshot-utils": "30.5.1", - "@jest/transform": "30.5.2", - "@jest/types": "30.5.1", - "babel-preset-current-node-syntax": "^1.2.0", - "chalk": "^4.1.2", - "expect": "30.5.2", - "graceful-fs": "^4.2.11", - "jest-diff": "30.5.2", - "jest-matcher-utils": "30.5.2", - "jest-message-util": "30.5.1", - "jest-util": "30.5.1", - "pretty-format": "30.5.1", - "semver": "^7.7.2", - "synckit": "^0.11.8" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-snapshot/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/jest-util": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/jest-util/-/jest-util-30.5.1.tgz", - "integrity": "sha512-yKuxmNy2rSbTXw+3SIPanJo+nV4/BS1p26v44IYBFMsswSQySfMMcPHErnOncda7i9HEz0q605rIhSTBVgrZTg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/types": "30.5.1", - "@types/node": "*", - "chalk": "^4.1.2", - "ci-info": "^4.2.0", - "graceful-fs": "^4.2.11", - "picomatch": "^4.0.3" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-util/node_modules/picomatch": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", - "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, - "node_modules/jest-validate": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/jest-validate/-/jest-validate-30.5.1.tgz", - "integrity": "sha512-i/buJ56wTpxihE93hQYNMfdOThS87+HGvLZzZJmU4xggPcdTYQq051iwALLCHp3q+SkCGH+EFejQZz5EbBSkkg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/get-type": "30.5.0", - "@jest/types": "30.5.1", - "camelcase": "^6.3.0", - "chalk": "^4.1.2", - "leven": "^3.1.0", - "pretty-format": "30.5.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-validate/node_modules/camelcase": { - "version": "6.3.0", - "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", - "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/jest-watcher": { - "version": "30.5.2", - "resolved": "https://registry.npmjs.org/jest-watcher/-/jest-watcher-30.5.2.tgz", - "integrity": "sha512-rqRgg4R11GA9m1UsEZwQeixHsgZReCn6TOHAHtIH33yXrIvoX0OGPA20Yzzjkz7X40fZvcRSxEpQppYPcWzmcQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/test-result": "30.5.2", - "@jest/types": "30.5.1", - "@types/node": "*", - "ansi-escapes": "^4.3.2", - "chalk": "^4.1.2", - "emittery": "^0.13.1", - "jest-util": "30.5.1", - "string-length": "^4.0.2" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-worker": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/jest-worker/-/jest-worker-30.5.1.tgz", - "integrity": "sha512-Cbxh5v7AoLuFRmFJSM4/aHdQ68rjXvUWr716EE0Dh3I7T+T/3FgFKhOERGXHcU2Meftq9+9zxPM3TSNyI9D+HA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "@ungap/structured-clone": "^1.3.0", - "jest-util": "30.5.1", - "merge-stream": "^2.0.0", - "supports-color": "^8.1.1" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/jest-worker/node_modules/supports-color": { - "version": "8.1.1", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", - "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", - "dev": true, - "license": "MIT", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/supports-color?sponsor=1" - } - }, "node_modules/jiti": { "version": "2.7.0", "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", @@ -9978,20 +7292,6 @@ "dev": true, "license": "MIT" }, - "node_modules/js-yaml": { - "version": "3.15.2", - "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.2.tgz", - "integrity": "sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==", - "dev": true, - "license": "MIT", - "dependencies": { - "argparse": "^1.0.7", - "esprima": "^4.0.0" - }, - "bin": { - "js-yaml": "bin/js-yaml.js" - } - }, "node_modules/jsesc": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", @@ -10451,35 +7751,6 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, - "node_modules/make-dir": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-4.0.0.tgz", - "integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==", - "dev": true, - "license": "MIT", - "dependencies": { - "semver": "^7.5.3" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/make-dir/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "dev": true, - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/map-obj": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/map-obj/-/map-obj-4.3.0.tgz", @@ -10539,13 +7810,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/merge-stream": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", - "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==", - "dev": true, - "license": "MIT" - }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", @@ -10668,30 +7932,6 @@ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" } }, - "node_modules/napi-postinstall": { - "version": "0.3.7", - "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.7.tgz", - "integrity": "sha512-jyU4cU4kVAmy/3qjP+DcoQTNXfINHc+dFw54gGqWC8nu0mpV0kOnk7kff+J+Q18SbX0k3Np8Rm7yFjd3phatNQ==", - "dev": true, - "license": "MIT", - "bin": { - "napi-patch": "lib/patch.js", - "napi-postinstall": "lib/cli.js" - }, - "engines": { - "node": "^12.20.0 || ^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/napi-postinstall" - } - }, - "node_modules/natural-compare": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", - "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", - "dev": true, - "license": "MIT" - }, "node_modules/node-addon-api": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", @@ -10735,13 +7975,6 @@ "url": "https://opencollective.com/node-fetch" } }, - "node_modules/node-int64": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", - "integrity": "sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==", - "dev": true, - "license": "MIT" - }, "node_modules/node-releases": { "version": "2.0.60", "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.60.tgz", @@ -10782,19 +8015,6 @@ "node": ">=0.10.0" } }, - "node_modules/npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/object-inspect": { "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", @@ -10895,22 +8115,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/p-limit": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", - "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "yocto-queue": "^0.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/p-locate": { "version": "4.1.0", "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", @@ -11101,29 +8305,6 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/pirates": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/pirates/-/pirates-4.0.7.tgz", - "integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 6" - } - }, - "node_modules/pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "find-up": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/playwright": { "version": "1.64.1", "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", @@ -11263,35 +8444,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/pretty-format": { - "version": "30.5.1", - "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-30.5.1.tgz", - "integrity": "sha512-byhRAPguVKMQIj4kjJwJ5lAskVhfuiSdiYl/aLTWpgkGEmic2jYhJh1yE9ih8Ox44Xg9ccCT11/S6QrzSJuNrg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jest/react-is-18": "npm:react-is@^18.3.1", - "@jest/react-is-19": "npm:react-is@^19.2.5", - "@jest/schemas": "30.5.0", - "ansi-styles": "^5.2.0" - }, - "engines": { - "node": "^18.14.0 || ^20.0.0 || ^22.0.0 || >=24.0.0" - } - }, - "node_modules/pretty-format/node_modules/ansi-styles": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-5.2.0.tgz", - "integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, "node_modules/proto-list": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/proto-list/-/proto-list-1.2.4.tgz", @@ -11348,23 +8500,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/pure-rand": { - "version": "7.0.1", - "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-7.0.1.tgz", - "integrity": "sha512-oTUZM/NAZS8p7ANR3SHh30kXB+zK2r2BPcEn/awJIbOvq82WoMN4p62AWWp3Hhw50G0xMsw1mhIBLqHw64EcNQ==", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/dubzzz" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fast-check" - } - ], - "license": "MIT" - }, "node_modules/quick-lru": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/quick-lru/-/quick-lru-4.0.1.tgz", @@ -11679,29 +8814,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", - "dev": true, - "license": "MIT", - "dependencies": { - "resolve-from": "^5.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/restore-cursor": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", @@ -12053,16 +9165,6 @@ "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", "dev": true }, - "node_modules/slash": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz", - "integrity": "sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/smob": { "version": "1.6.1", "resolved": "https://registry.npmjs.org/smob/-/smob-1.6.1.tgz", @@ -12123,26 +9225,6 @@ "integrity": "sha512-xxRs31BqRYHwiMzudOrpSiHtZ8i/GeionCBDSilhYRj+9gIcI8wCZTlXZKu9vZIVqViP3dcp9qE5G6AlIaD+TQ==", "dev": true }, - "node_modules/sprintf-js": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.0.3.tgz", - "integrity": "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==", - "dev": true, - "license": "BSD-3-Clause" - }, - "node_modules/stack-utils": { - "version": "2.0.6", - "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", - "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "escape-string-regexp": "^2.0.0" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/stop-iteration-iterator": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", @@ -12166,20 +9248,6 @@ "safe-buffer": "~5.2.0" } }, - "node_modules/string-length": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/string-length/-/string-length-4.0.2.tgz", - "integrity": "sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "char-regex": "^1.0.2", - "strip-ansi": "^6.0.0" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -12334,16 +9402,6 @@ "node": ">=8" } }, - "node_modules/strip-bom": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-4.0.0.tgz", - "integrity": "sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/strip-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-comments/-/strip-comments-2.0.1.tgz", @@ -12354,16 +9412,6 @@ "node": ">=10" } }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/strip-indent": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/strip-indent/-/strip-indent-3.0.0.tgz", @@ -12376,19 +9424,6 @@ "node": ">=8" } }, - "node_modules/strip-json-comments": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", - "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/stubborn-fs": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/stubborn-fs/-/stubborn-fs-2.0.0.tgz", @@ -12430,22 +9465,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/synckit": { - "version": "0.11.13", - "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.11.13.tgz", - "integrity": "sha512-eNRKgb3z66Yp3D2CixVujOUvXLFUTij/zVnV8KRyvFdQwpz7I5DS8UfRkTeLzb64u+dkzDSdelE24izu+zSSUg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@pkgr/core": "^0.3.6" - }, - "engines": { - "node": "^14.18.0 || >=16.0.0" - }, - "funding": { - "url": "https://opencollective.com/synckit" - } - }, "node_modules/systeminformation": { "version": "5.33.16", "resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.33.16.tgz", @@ -12563,60 +9582,6 @@ "source-map": "^0.6.0" } }, - "node_modules/test-exclude": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/test-exclude/-/test-exclude-7.0.2.tgz", - "integrity": "sha512-u9E6A+ZDYdp7a4WnarkXPZOx8Ilz46+kby6p1yZ8zsGTz9gYa6FIS7lj2oezzNKmtdyyJNNmmXDppga5GB7kSw==", - "dev": true, - "license": "ISC", - "dependencies": { - "@istanbuljs/schema": "^0.1.2", - "glob": "^10.4.1", - "minimatch": "^10.2.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/test-exclude/node_modules/balanced-match": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", - "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", - "dev": true, - "license": "MIT", - "engines": { - "node": "18 || 20 || >=22" - } - }, - "node_modules/test-exclude/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "balanced-match": "^4.0.2" - }, - "engines": { - "node": "20 || >=22" - } - }, - "node_modules/test-exclude/node_modules/minimatch": { - "version": "10.2.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.6.tgz", - "integrity": "sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "brace-expansion": "^5.0.8" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/text-segmentation": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/text-segmentation/-/text-segmentation-1.0.3.tgz", @@ -12677,16 +9642,6 @@ "integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==", "dev": true }, - "node_modules/type-detect": { - "version": "4.0.8", - "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", - "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=4" - } - }, "node_modules/type-fest": { "version": "0.21.3", "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.21.3.tgz", @@ -12868,44 +9823,6 @@ "node": ">= 10.0.0" } }, - "node_modules/unrs-resolver": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.12.2.tgz", - "integrity": "sha512-dmlRxBJJayXjqTwC+JtF1HhJmgf3ftQ3YejFcZrf4+KKtJv0qDsK1pjqaaVjG7wJ5NJ6UVP1OqRMQ71Z4C3rxQ==", - "dev": true, - "hasInstallScript": true, - "license": "MIT", - "dependencies": { - "napi-postinstall": "^0.3.4" - }, - "funding": { - "url": "https://opencollective.com/unrs-resolver" - }, - "optionalDependencies": { - "@unrs/resolver-binding-android-arm-eabi": "1.12.2", - "@unrs/resolver-binding-android-arm64": "1.12.2", - "@unrs/resolver-binding-darwin-arm64": "1.12.2", - "@unrs/resolver-binding-darwin-x64": "1.12.2", - "@unrs/resolver-binding-freebsd-x64": "1.12.2", - "@unrs/resolver-binding-linux-arm-gnueabihf": "1.12.2", - "@unrs/resolver-binding-linux-arm-musleabihf": "1.12.2", - "@unrs/resolver-binding-linux-arm64-gnu": "1.12.2", - "@unrs/resolver-binding-linux-arm64-musl": "1.12.2", - "@unrs/resolver-binding-linux-loong64-gnu": "1.12.2", - "@unrs/resolver-binding-linux-loong64-musl": "1.12.2", - "@unrs/resolver-binding-linux-ppc64-gnu": "1.12.2", - "@unrs/resolver-binding-linux-riscv64-gnu": "1.12.2", - "@unrs/resolver-binding-linux-riscv64-musl": "1.12.2", - "@unrs/resolver-binding-linux-s390x-gnu": "1.12.2", - "@unrs/resolver-binding-linux-x64-gnu": "1.12.2", - "@unrs/resolver-binding-linux-x64-musl": "1.12.2", - "@unrs/resolver-binding-openharmony-arm64": "1.12.2", - "@unrs/resolver-binding-wasm32-wasi": "1.12.2", - "@unrs/resolver-binding-win32-arm64-msvc": "1.12.2", - "@unrs/resolver-binding-win32-ia32-msvc": "1.12.2", - "@unrs/resolver-binding-win32-x64-msvc": "1.12.2" - } - }, "node_modules/upath": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/upath/-/upath-1.2.0.tgz", @@ -13013,21 +9930,6 @@ "base64-arraybuffer": "^1.0.2" } }, - "node_modules/v8-to-istanbul": { - "version": "9.3.0", - "resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz", - "integrity": "sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==", - "dev": true, - "license": "ISC", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.12", - "@types/istanbul-lib-coverage": "^2.0.1", - "convert-source-map": "^2.0.0" - }, - "engines": { - "node": ">=10.12.0" - } - }, "node_modules/validate-npm-package-license": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz", @@ -13666,33 +10568,6 @@ "url": "https://github.com/chalk/wrap-ansi?sponsor=1" } }, - "node_modules/write-file-atomic": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-5.0.1.tgz", - "integrity": "sha512-+QU2zd6OTD8XWIJCbffaiQeH9U73qIqafo1x6V1snCWYGJf6cVE0cDR4D8xRzcEnfI21IFrUPzPGtcPf8AC+Rw==", - "dev": true, - "license": "ISC", - "dependencies": { - "imurmurhash": "^0.1.4", - "signal-exit": "^4.0.1" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/write-file-atomic/node_modules/signal-exit": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", - "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", - "dev": true, - "license": "ISC", - "engines": { - "node": ">=14" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/xdg-basedir": { "version": "5.1.0", "resolved": "https://registry.npmjs.org/xdg-basedir/-/xdg-basedir-5.1.0.tgz", @@ -13781,19 +10656,6 @@ "engines": { "node": ">=12" } - }, - "node_modules/yocto-queue": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", - "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } } } } diff --git a/package.json b/package.json index c86d80ed9..e0eb04d40 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,6 @@ "@tailwindcss/typography": "^0.5.20", "autoprefixer": "^10.6.1", "daisyui": "^5.7.50", - "jest": "^30.5.2", "postcss": "^8.5.31", "tailwindcss": "^4.3.3", "workbox-cli": "^7.4.1" @@ -16,7 +15,6 @@ "html2canvas": "^1.4.1" }, "scripts": { - "test": "jest", "test:gridstack-parity": "playwright test test/browser/dashboard-grid-parity.spec.js --reporter=line" }, "overrides": { From f3a3a9ce89902ac05bfda67b9a43dc1e62f1ce8d Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Mon, 26 Oct 2026 17:35:20 +0100 Subject: [PATCH 020/203] Add RUM audience breakdowns and reusable segments (#740) * Highlight the selected visualization tab with brand colors * Add RUM audience breakdowns, investigation filters, and saved segments * Declare form decoding dependency for integration tests * Check expanded RUM templates for query scoping * Supply required summaries in RUM browser fixtures * Prepare shared npm dependencies before parallel CI lanes * Target the segment disclosure explicitly in browser coverage --- ci/checks.tsv | 2 + e2e/playwright.config.ts | 4 +- e2e/tests/rum-audience.spec.ts | 62 +++++ monoscope.cabal | 6 + package.yaml | 1 + scripts/ci/ci.sh | 32 ++- src/Pages/Charts/Charts.hs | 6 +- src/Pages/Dashboards.hs | 32 +-- src/Pages/Rum.hs | 88 +++++++ src/Pkg/Components/LogQueryBox.hs | 2 +- src/Pkg/Components/Widget.hs | 16 +- src/Pkg/Parser.hs | 7 + src/Pkg/Rum.hs | 93 ++++++++ src/Web/Routes.hs | 7 + static/migrations/0254_rum_segments.sql | 6 + static/public/assets/css/tailwind.css | 37 +++ static/public/dashboards/rum.yaml | 221 +++++++++++++++--- .../integration/Pages/DashboardWidgetsSpec.hs | 58 ++++- test/unit/Models/DashboardTemplatesSpec.hs | 5 +- 19 files changed, 620 insertions(+), 65 deletions(-) create mode 100644 e2e/tests/rum-audience.spec.ts create mode 100644 src/Pages/Rum.hs create mode 100644 src/Pkg/Rum.hs create mode 100644 static/migrations/0254_rum_segments.sql diff --git a/ci/checks.tsv b/ci/checks.tsv index 272160e71..306948386 100644 --- a/ci/checks.tsv +++ b/ci/checks.tsv @@ -16,6 +16,8 @@ # # Narrow `inputs` only where it is provably sound. A too-wide set costs a rerun; # a too-narrow one ships an untested change. +# Parallel integration, UI, and e2e lanes share dependency installs prepared by +# the runner before launch; each check still declares its own source inputs. frontend node @fe @uisrc build ghc @hs @fe doctests ghc @hs @fe diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts index 2adc7700c..480151656 100644 --- a/e2e/playwright.config.ts +++ b/e2e/playwright.config.ts @@ -18,7 +18,7 @@ export default defineConfig({ trace: "on-first-retry", }, projects: [ - { name: "chromium", use: { ...devices["Desktop Chrome"] }, testIgnore: /(container-identity|endpoint-analytics|host-map|infrastructure-time-window|metric-exemplars|metrics-catalog|tabs)\.spec\.ts$/ }, - { name: "chromium-fixtures", use: { ...devices["Desktop Chrome"] }, testMatch: /(container-identity|endpoint-analytics|host-map|infrastructure-time-window|metric-exemplars|metrics-catalog|tabs)\.spec\.ts$/, dependencies: ["chromium"], workers: 1 }, + { name: "chromium", use: { ...devices["Desktop Chrome"] }, testIgnore: /(container-identity|endpoint-analytics|host-map|infrastructure-time-window|metric-exemplars|metrics-catalog|tabs|rum-audience)\.spec\.ts$/ }, + { name: "chromium-fixtures", use: { ...devices["Desktop Chrome"] }, testMatch: /(container-identity|endpoint-analytics|host-map|infrastructure-time-window|metric-exemplars|metrics-catalog|tabs|rum-audience)\.spec\.ts$/, dependencies: ["chromium"], workers: 1 }, ], }); diff --git a/e2e/tests/rum-audience.spec.ts b/e2e/tests/rum-audience.spec.ts new file mode 100644 index 000000000..6f825e694 --- /dev/null +++ b/e2e/tests/rum-audience.spec.ts @@ -0,0 +1,62 @@ +import { test, expect } from "@playwright/test"; +import { DEMO_PROJECT, sql } from "./helpers"; + +test("audience groups filter sessions, search users, and persist named segments", async ({ page }) => { + const app = `e2e-rum-audience-${Date.now()}`; + const segment = `${app} Mobile Safari`; + const cleanup = () => sql(`DELETE FROM otel_logs_and_spans WHERE project_id='${DEMO_PROJECT}' AND resource___service___name='${app}'; DELETE FROM projects.rum_segments WHERE project_id='${DEMO_PROJECT}' AND name='${segment}';`); + sql(`INSERT INTO otel_logs_and_spans (project_id,summary,name,timestamp,start_time,end_time,resource___service___name,resource___user_agent___original,attributes___session___id,attributes___user___id,attributes___user___email,attributes___exception___type) + VALUES + ('${DEMO_PROJECT}',ARRAY['RUM audience'],'documentLoad',now(),now(),now(),'${app}','iPhone Mobile Safari/604','${app}-alice','alice','alice@example.com',NULL), + ('${DEMO_PROJECT}',ARRAY['RUM audience'],'browser error',now(),now(),now(),'${app}','iPhone Mobile Safari/604','${app}-alice','alice','alice@example.com','TypeError'), + ('${DEMO_PROJECT}',ARRAY['RUM audience'],'documentLoad',now(),now(),now(),'${app}','Windows Chrome/151 Safari/537','${app}-bob','bob','bob@example.com',NULL), + ('${DEMO_PROJECT}',ARRAY['RUM audience'],'documentLoad',now(),now(),now(),'${app}',NULL,'${app}-anonymous',NULL,NULL,NULL);`); + try { + const errors: string[] = []; + page.on("pageerror", error => errors.push(error.message)); + page.on("console", message => { if (message.type() === "error" && /SyntaxError|parse error/i.test(message.text())) errors.push(message.text()); }); + await page.goto(`/p/${DEMO_PROJECT}/rum?tab=audience&var-app=${app}&since=1H`); + const toolbar = page.locator("#rum-segments"); + await expect(toolbar.getByRole("link", { name: "View sessions", exact: true })).toBeVisible(); + const browsers = page.getByRole("table").filter({ has: page.getByRole("columnheader", { name: "Browser", exact: true }) }); + const systems = page.getByRole("table").filter({ has: page.getByRole("columnheader", { name: "Operating system", exact: true }) }); + await expect(browsers.getByText("Unknown", { exact: true })).toBeVisible(); + await expect(browsers.locator("tbody tr").filter({ hasText: "Safari" })).toContainText("100 %"); + for (const width of [1920, 1280, 390]) { + await page.setViewportSize({ width, height: 1000 }); + await expect.poll(async () => { + const [browser, system] = await Promise.all([browsers.boundingBox(), systems.boundingBox()]); + return !!browser && !!system && (width === 1920 ? Math.abs(browser.y - system.y) < 3 : system.y > browser.y + browser.height); + }).toBe(true); + for (const table of [browsers, systems]) { + expect(await table.evaluate(el => el.getBoundingClientRect().right <= innerWidth && el.scrollWidth <= el.clientWidth + 1)).toBe(true); + } + } + await page.setViewportSize({ width: 1280, height: 1000 }); + await page.locator("[data-widget]").filter({ has: page.getByText("Identified users", { exact: true }) }).scrollIntoViewIfNeeded(); + const users = page.getByRole("table").filter({ has: page.getByRole("columnheader", { name: "User", exact: true }) }); + await expect(users.getByRole("link", { name: "alice@example.com" })).toBeVisible(); + await page.getByRole("searchbox", { name: "Search Identified users" }).fill("bob"); + await expect(users.locator("tbody tr").filter({ visible: true })).toHaveCount(1); + await expect(users.locator("tbody tr").filter({ visible: true })).toContainText("bob@example.com"); + await page.getByRole("searchbox", { name: "Search Identified users" }).fill(""); + await expect(users.locator("tbody tr").filter({ visible: true })).toHaveCount(2); + const safari = browsers.locator("tbody tr").filter({ hasText: "Safari" }); + await safari.focus(); + await safari.press("Enter"); + await expect(page).toHaveURL(/var-browser=Safari/); + await toolbar.locator("summary").filter({ hasText: "Save segment" }).click(); + await toolbar.getByLabel("Segment name").fill(segment); + await toolbar.getByRole("button", { name: "Save segment", exact: true }).click(); + await expect(toolbar.getByRole("link", { name: segment, exact: true })).toBeVisible(); + await page.reload(); + await expect(toolbar.getByRole("link", { name: segment, exact: true })).toBeVisible(); + await toolbar.getByRole("link", { name: "View errors", exact: true }).click(); + await expect(page).toHaveURL(/\/tab\/errors/); + await expect(page).toHaveURL(/var-browser=Safari/); + await toolbar.getByRole("link", { name: "View sessions", exact: true }).click(); + await expect(page).toHaveURL(/viz_type=sessions/); + expect(new URL(page.url()).searchParams.get("query")).toContain("Safari/"); + expect(errors).toEqual([]); + } finally { cleanup(); } +}); diff --git a/monoscope.cabal b/monoscope.cabal index 8c712899d..5f0710fae 100644 --- a/monoscope.cabal +++ b/monoscope.cabal @@ -269,6 +269,7 @@ extra-source-files: static/migrations/0252_project_memory_page_identity.sql static/migrations/0253_project_memory_legacy_writes.sql static/migrations/0254_ingest_sampling.sql + static/migrations/0254_rum_segments.sql test/fixtures/github-app-test.pem test/fixtures/wiki-browser.mjs static/public/assets/web-components/dist/manifest.json @@ -380,6 +381,7 @@ library Pages.Projects Pages.Replay Pages.Reports + Pages.Rum Pages.ServiceMap Pages.Settings Pages.Share @@ -413,6 +415,7 @@ library Pkg.Prometheus Pkg.QueryCache Pkg.Queue + Pkg.Rum Pkg.Sampling Pkg.SchemaLearning.Catalog Pkg.SchemaLearning.Hot @@ -895,6 +898,7 @@ test-suite integration-tests , hs-opentelemetry-instrumentation-auto , hs-opentelemetry-instrumentation-hasql , hspec + , http-api-data , http-client , http-client-tls , http-types @@ -1025,6 +1029,7 @@ test-suite test-dev Pages.Projects Pages.Replay Pages.Reports + Pages.Rum Pages.ServiceMap Pages.Settings Pages.Share @@ -1058,6 +1063,7 @@ test-suite test-dev Pkg.Prometheus Pkg.QueryCache Pkg.Queue + Pkg.Rum Pkg.Sampling Pkg.SchemaLearning.Catalog Pkg.SchemaLearning.Hot diff --git a/package.yaml b/package.yaml index 420c91a9f..dd2281e47 100644 --- a/package.yaml +++ b/package.yaml @@ -296,6 +296,7 @@ tests: - unix - lucid - http-types + - http-api-data - wai - wai-extra - unordered-containers diff --git a/scripts/ci/ci.sh b/scripts/ci/ci.sh index 7ec498228..e120449d4 100755 --- a/scripts/ci/ci.sh +++ b/scripts/ci/ci.sh @@ -332,9 +332,17 @@ CABAL_OPTS="--ghc-options=-O0 -j$CI_CORES +RTS -A64m -n2m -RTS" CABAL_FLAGS='-f-devtest' prepare_browser() { + [ "${CI_BROWSER_PREPARED:-}" != true ] || return 0 (cd e2e && npm ci --prefer-offline --no-audit && \ { [ -e /usr/local/share/monoscope-playwright-deps ] || npx playwright install-deps chromium; } && \ npx playwright install chromium) + export CI_BROWSER_PREPARED=true +} + +prepare_web_deps() { + [ "${CI_WEB_DEPS_PREPARED:-}" != true ] || return 0 + (cd web-components && npm ci --prefer-offline --no-audit) + export CI_WEB_DEPS_PREPARED=true } run_body() { # @@ -384,7 +392,7 @@ run_body() { # ;; release-tests) node --test scripts/ci/release-test.mjs ;; hlint) hlint -j src/ shared/src cli ;; - ui-tests) (cd web-components && npm ci --prefer-offline --no-audit && npm test) ;; + ui-tests) prepare_web_deps; (cd web-components && npm test) ;; # Drives the real server in a real browser. scripts/e2e.sh starts that server itself on # 8081 against a throwaway database, so this only has to supply the binary and chromium. e2e) @@ -410,7 +418,7 @@ run_integration() { # reached under CI_ALLOW_DEGRADED — cmd_run refuses this check otherwise. case " ${CAPS:-} " in *" tf-real "*) ;; *) unset TIMEFUSION_PG_TEST_URL ;; esac export USE_EXTERNAL_DB=true LOG_LEVEL=${LOG_LEVEL:-warn} - (cd web-components && npm ci --prefer-offline --no-audit) + prepare_web_deps prepare_browser make build-chart-cli [ -n "${CI_INTEGRATION_BIN:-}" ] || cabal build integration-tests -j $CABAL_FLAGS "$CABAL_OPTS" @@ -484,6 +492,11 @@ stop_early() { [ "$1" -ne 0 ] && [ "${CI_KEEP_GOING:-}" != true ]; } # Background lanes live in $BG_DIR as .{pid,log,result}. start_background() { # + # npm ci removes node_modules: finish installs before any parallel consumer. + case "$1" in + integration-tests) prepare_web_deps; prepare_browser ;; + e2e) prepare_browser ;; + esac CI_ATTEST_OUT="$BG_DIR/$1.result" "$0" run "$1" > "$BG_DIR/$1.log" 2>&1 & echo $! > "$BG_DIR/$1.pid" } @@ -1013,6 +1026,21 @@ cmd_selftest() { assert "background failure propagates" 1 "$body_rc" assert "background diagnostics retained" yes "$([ -f "$BG_DIR/failing.log" ] && echo yes || echo no)" rm -rf "$BG_DIR" + BG_DIR=$(mktemp -d -t ci-selftest-browser.XXXXXX) + printf '#!/bin/sh\necho install >> "%s/calls"\n' "$BG_DIR" > "$BG_DIR/npm" + printf '#!/bin/sh\nexit 0\n' > "$BG_DIR/npx" + chmod +x "$BG_DIR/npm" "$BG_DIR/npx" + ( + export PATH="$BG_DIR:$PATH" + unset CI_BROWSER_PREPARED CI_WEB_DEPS_PREPARED + prepare_browser + prepare_web_deps + prepare_browser & browser_one=$! + prepare_web_deps & browser_two=$! + wait "$browser_one" "$browser_two" + ) + assert "parallel lanes install each dependency tree once" 2 "$(wc -l < "$BG_DIR/calls" | tr -d ' ')" + rm -rf "$BG_DIR" # kafka-topics.sh under macOS /bin/bash 3.2 with no SASL user: an empty array under # `set -u` killed it silently (2026-10-20). A stub rpk records what it was asked to do. # Only bash < 4.4 reproduces the bug, so on Linux CI this checks the happy path alone. diff --git a/src/Pages/Charts/Charts.hs b/src/Pages/Charts/Charts.hs index 0cdaeae2f..6f8e140ee 100644 --- a/src/Pages/Charts/Charts.hs +++ b/src/Pages/Charts/Charts.hs @@ -183,7 +183,7 @@ runQueryAST authCtx dbSource respDataType pid source binDensity environment serv case querySQLM of Just querySQL - | Just message <- rawSqlScopeError environment service querySQL -> + | Just message <- rawSqlScopeError environment service (fillQueryTemplate mappngSQL querySQL) -> pure (emptyMetricsFor now fromD toD){error = Just message} Just querySQL -> do let tbl = sourceTable source @@ -223,7 +223,7 @@ runRawQuery authCtx dbSource decoder cfg ast kql template mapping liveRange prog (from, to) = bounds canonical = M.fromList [("query_ast_filters", rawAstFilters cacheCfg components)] - <> variablePresets cfg.binDensity cfg.pid.toText from to [] cfg.currentTime + <> variablePresets cfg.binDensity cfg.pid.toText from to [(key, Just value) | (key, value) <- M.toList mapping, "var-" `T.isPrefixOf` key || key == "table-search"] cfg.currentTime <> mapping sql = fillQueryTemplate canonical template fetch = liftIO $ fetchMetricsDataWithProgress progress decoder sql cfg.currentTime from to authCtx dbSource >>= either throwIO pure @@ -755,7 +755,7 @@ queryMetricsStream dbSource dataTypeM pidM queryM querySQLM sinceM fromM toM sou maybe (first queryErrorText $ parseQueryDiagnosed source $ fillQueryTemplate mappingKQL $ maybeToMonoid $ Utils.nonEmptyT queryM) Left - (raw >>= rawSqlScopeError environment service) + (raw >>= rawSqlScopeError environment service . fillQueryTemplate mapping) scope = mkScopedQuery pid (fromD, toD) environment service cfg = (applyScopedQuery scope $ defSqlQueryCfg pid now source Nothing){binDensity = density, targetsTimefusion = usesTimefusionBackend authCtx.env.enableTimefusionReads dbSource} run emit = case parsed of diff --git a/src/Pages/Dashboards.hs b/src/Pages/Dashboards.hs index 71d24ae37..3e68f8aae 100644 --- a/src/Pages/Dashboards.hs +++ b/src/Pages/Dashboards.hs @@ -105,6 +105,7 @@ import Pages.GitSync qualified as GitSyncPage import Pages.Issues qualified as IssuesPage import Pages.LogExplorer.LogItem qualified as LogItem import Pages.Monitors qualified as Alerts +import Pages.Rum qualified as Rum import Pkg.Components.LogQueryBox (LogQueryBoxConfig (..), logQueryBox_) import Pkg.Components.ServiceMap (endpointDependencyMapPanel_) import Pkg.Components.Table (Table (..)) @@ -115,6 +116,7 @@ import Pkg.DeriveUtils (UUIDId (..), WrappedEnumSC (..), assetUrl, bulkActionSlu import Pkg.Metrics qualified as Metrics import Pkg.Parser (QueryComponents (..), SqlQueryCfg (..), applyScopedQuery, binDensityFor, browserKql, constantToKQLList, constantToSQLList, defSqlQueryCfg, fillQueryTemplate, fixedUTCTime, mkScopedQuery, parseQueryToComponents, variablePresetsKQL) import Pkg.Parser.Expr (sqlStringLit) +import Pkg.Rum qualified import Pkg.SchemaLearning.Catalog qualified as Catalog import Relude hiding (ask) import Servant (NoContent (..), ServerError, err302, err400, err404, errBody, errHeaders) @@ -328,7 +330,7 @@ dashboardPage_ pid dashId dash dashVM allParams = do dashboardTabStrip_ pidText dashIdText activeTabIdx tabs queryStr [] -- Variables section (pushed to the right, collapsible on mobile) - whenJust dash.variables \variables -> dashboardVariables_ pid dashId (isJust dash.tabs) variables [] + whenJust dash.variables \_ -> dashboardVariables_ pid dashId (isJust dash.tabs) (Rum.variablesForTab dash renderTabSlug) [] let widgetOrderUrl = "/p/" <> pidText <> "/dashboards/" <> dashIdText <> "/widgets_order" <> maybe "" ("?tab=" <>) renderTabSlug constants = constantsJson allParams @@ -347,11 +349,14 @@ dashboardPage_ pid dashId dash dashVM allParams = do -- Tab system with htmx lazy loading - only render active tab content. -- Grid re-init after a swap is the document-level listener's job (see this page's script). div_ - [ class_ "dashboard-tabs-container" - , id_ "dashboard-tabs-content" - , data_ "constants" constants - ] - $ whenJust (tabs !!? activeTabIdx) \activeTab -> + ( [ class_ "dashboard-tabs-container" + , id_ "dashboard-tabs-content" + , data_ "constants" constants + ] + <> [data_ "rum-audience" "" | dash.file == Just "rum.yaml" && renderTabSlug == Just "audience"] + ) + $ whenJust (tabs !!? activeTabIdx) \activeTab -> do + when (dash.file == Just "rum.yaml" && slugify activeTab.name `elem` ["audience", "errors"]) $ Rum.segmentToolbar_ pid allParams -- An unanswered required variable IS the tab's content, not a modal over -- it. Rendering the widgets underneath meant every one of them ran with -- the variable interpolated to '' and reported "no data in the selected @@ -452,7 +457,7 @@ dashboardPage_ pid dashId dash dashVM allParams = do animate: false, columnOpts: { breakpointForWindow: false, - breakpoints: [{w: 800, c: 6}, {w: 400, c: 1}], + breakpoints: gridEl.closest('[data-rum-audience]') ? [{w: 1500, c: 1}] : [{w: 800, c: 6}, {w: 400, c: 1}], layout: 'list' }, }, gridEl); @@ -512,7 +517,7 @@ dashboardPage_ pid dashId dash dashVM allParams = do animate: false, columnOpts: { breakpointForWindow: false, - breakpoints: [{w: 600, c: 6}, {w: 400, c: 1}], + breakpoints: nestedEl.closest('[data-rum-audience]') ? [{w: 600, c: 6}, {w: 320, c: 1}] : [{w: 600, c: 6}, {w: 400, c: 1}], layout: 'list' }, }, nestedEl); @@ -1255,7 +1260,7 @@ dashboardGetH pid dashId fileM fromDStr toDStr sinceStr hxRequest allParams = do (dashVM, dash) <- getDashAndVM pid dashId fileM -- Deep links to a widget must open its tab, rather than the default tab. - case (join (lookup "expand" allParams) >>= \wid -> fst =<< findWidgetInDashboard wid dash) <|> (slugify . (.name) <$> (dash.tabs >>= viaNonEmpty head)) of + case (join (lookup "expand" allParams) >>= \wid -> fst =<< findWidgetInDashboard wid dash) <|> (join (lookup "tab" allParams) >>= \slug -> slug <$ findTabBySlug (fold dash.tabs) slug) <|> (slugify . (.name) <$> (dash.tabs >>= viaNonEmpty head)) of Just tabSlug -> do let redirectUrl = "/p/" <> pid.toText <> "/dashboards/" <> dashId.toText <> "/tab/" <> tabSlug <> queryStringFrom allParams throwError $ err302{errHeaders = [("Location", encodeUtf8 redirectUrl)]} @@ -2278,7 +2283,7 @@ rumRedirectH pid segments params = case (filter (not . T.null) segments, param " where param k = join $ lookup k params dashboard = entrypointRedirectGetH "rum.yaml" "Real User Monitoring" ["rum", "browser", "frontend", "web-vitals"] pid params - query = maybe browserKql (("attributes.session.id == " <>) . kqlQuoted) (param "session") + query = T.intercalate " and " $ filter (not . T.null) [maybe browserKql (("attributes.session.id == " <>) . kqlQuoted) (param "session"), Pkg.Rum.audienceKql $ Pkg.Rum.audienceFilters params] sessions = pure $ addHeader (timeScopedUrl ("/p/" <> pid.toText <> "/log_explorer") [("viz_type", "sessions"), ("query", query)] (param "from") (param "to") (param "since")) NoContent @@ -2805,15 +2810,16 @@ dashboardTabGetH pid dashId tabSlug fileM fromDStr toDStr sinceStr hxRequest hxT queryStr = queryStringFrom $ filter (\(k, _) -> k `notElem` [activeTabSlugKey, "expand"]) paramsWithTab fragment = do dashboardTabStrip_ pid.toText dashId.toText activeTabIdx (fold dash''.tabs) queryStr [hxSwapOob_ "outerMorph"] - when (hxTriggerName == Just "dashboard-variable-option") - $ whenJust dash''.variables \variables -> dashboardVariables_ pid dashId True variables [hxSwapOob_ "true"] - div_ [class_ "dashboard-tabs-container", id_ "dashboard-tabs-content", data_ "constants" $ constantsJson paramsWithTab] + when (hxTriggerName == Just "dashboard-variable-option" || dash''.file == Just "rum.yaml") + $ whenJust dash''.variables \_ -> dashboardVariables_ pid dashId True (Rum.variablesForTab dash'' $ Just tabSlug) [hxSwapOob_ "true"] + div_ ([class_ "dashboard-tabs-container", id_ "dashboard-tabs-content", data_ "constants" $ constantsJson paramsWithTab] <> [data_ "rum-audience" "" | dash''.file == Just "rum.yaml" && tabSlug == "audience"]) $ case findVarToPrompt (snd <$> activeTabInfo) (fold dash''.variables) of Just v -> do whenJust activeTabName breadcrumbSuffixOob_ variablePickerModal_ pid dashId (Just tabSlug) paramsWithTab v Nothing -> whenJust (dash''.tabs >>= (!!? activeTabIdx)) \activeTab -> do breadcrumbSuffixOob_ activeTab.name + when (dash''.file == Just "rum.yaml" && tabSlug `elem` ["audience", "errors"]) $ Rum.segmentToolbar_ pid paramsWithTab widgetCanvas_ pid ("tab-panel-" <> dashId.toText <> "-" <> show activeTabIdx) activeTab.widgets addRespHeaders $ navigationResponse hxRequest page fragment diff --git a/src/Pages/Rum.hs b/src/Pages/Rum.hs new file mode 100644 index 000000000..e119f7206 --- /dev/null +++ b/src/Pages/Rum.hs @@ -0,0 +1,88 @@ +module Pages.Rum (SegmentForm (..), segmentsGetH, segmentsPostH, segmentsDeleteH, segmentToolbar_, variablesForTab) where + +import Data.Effectful.Hasql qualified as Hasql +import Data.List (lookup) +import Data.Text qualified as T +import Effectful.Error.Static (throwError) +import Hasql.Interpolate qualified as HI +import Lucid +import Lucid.Aria qualified as Aria +import Lucid.Htmx +import Models.Projects.Dashboards qualified as Dashboards +import Models.Projects.Projects qualified as Projects +import Pkg.Rum (AudienceFilters (..), audienceFilters, audienceParams) +import Relude +import Servant (err400, errBody) +import System.Types +import Utils (faSprite_, queryStringFrom, toUriStr) +import Web.FormUrlEncoded (FromForm (..), parseUnique) + + +data SegmentForm = SegmentForm {name :: Text, filters :: AudienceFilters} + deriving stock (Generic, Show) + + +instance FromForm SegmentForm where + fromForm form = SegmentForm <$> parseUnique "name" form <*> fromForm form + + +variablesForTab :: Dashboards.Dashboard -> Maybe Text -> [Dashboards.Variable] +variablesForTab dash tab = filter (\v -> dash.file /= Just "rum.yaml" || tab == Just "audience" || tab == Just "errors" || v.key == "app") $ fold dash.variables + + +segmentToolbar_ :: Projects.ProjectId -> [(Text, Maybe Text)] -> Html () +segmentToolbar_ pid params = + div_ + [ id_ "rum-segments" + , hxGet_ $ "/p/" <> pid.toText <> "/rum/segments" <> queryStringFrom params + , hxTrigger_ "load, update-query from:window" + , hxVals_ "js:{...Object.fromEntries(new URLSearchParams(location.search))}" + , hxSwap_ "innerHTML" + , class_ "px-4 py-2 border-b border-strokeWeak" + ] + mempty + + +segmentsGetH :: Projects.ProjectId -> [(Text, Maybe Text)] -> ATAuthCtx (RespHeaders (Html ())) +segmentsGetH pid params = do + _ <- Projects.sessionAndProject pid + segments <- Hasql.interp @[(Text, HI.AsJsonb AudienceFilters)] [HI.sql|SELECT name, filters FROM projects.rum_segments WHERE project_id = #{pid} ORDER BY name|] + let current = audienceFilters params + root = "/p/" <> pid.toText <> "/rum" + window = filter (\(key, _) -> key `elem` ["from", "to", "since", "environment"]) params + tab = [("tab", Just $ fromMaybe "audience" $ join (lookup "activeTabSlug" params) <|> join (lookup "tab" params))] + addRespHeaders $ div_ [class_ "flex flex-wrap items-center gap-x-4 gap-y-2 text-sm"] do + nav_ [Aria.label_ "Saved audience segments", class_ "flex flex-wrap items-center gap-2"] do + span_ [class_ "text-textWeak"] "Segments" + forM_ segments \(name, HI.AsJsonb filters) -> do + a_ [href_ $ root <> queryStringFrom (tab <> audienceParams filters <> window), class_ $ "rounded px-2 py-1 hover:bg-fillWeak " <> if filters == current then "bg-fillBrand-weak text-textBrand font-semibold" else "text-textStrong"] $ toHtml name + button_ [type_ "button", class_ "btn btn-ghost btn-xs", Aria.label_ $ "Delete segment " <> name, hxDelete_ $ root <> "/segments/" <> toUriStr name <> queryStringFrom params, hxTarget_ "#rum-segments", hxSwap_ "innerHTML"] $ faSprite_ "xmark" "regular" "h-3 w-3" + details_ [class_ "relative"] do + summary_ [class_ "cursor-pointer text-textBrand"] "Save segment" + form_ [class_ "absolute z-20 mt-2 p-3 w-64 rounded-lg border border-strokeWeak bg-bgRaised shadow-lg flex flex-col gap-3", hxPost_ $ root <> "/segments" <> queryStringFrom params, hxTarget_ "#rum-segments", hxSwap_ "innerHTML"] do + label_ [class_ "flex flex-col gap-1"] do + "Segment name" + input_ [name_ "name", required_ "", maxlength_ "100", class_ "input input-sm w-full", placeholder_ "Mobile Safari"] + forM_ ([("app", current.app), ("browser", current.browser), ("os", current.os), ("device", current.device), ("errored", Just $ if current.errored then "true" else "false")] :: [(Text, Maybe Text)]) \(key, value) -> input_ [type_ "hidden", name_ key, value_ $ fromMaybe "" value] + button_ [type_ "submit", class_ "btn btn-primary btn-sm"] "Save segment" + a_ [class_ "text-textBrand hover:underline", href_ $ root <> "/sessions" <> queryStringFrom (audienceParams current <> window)] "View sessions" + a_ [class_ "text-textBrand hover:underline", href_ $ root <> queryStringFrom ([("tab", Just "errors")] <> audienceParams current <> window)] "View errors" + when (any isJust [current.app, current.browser, current.os, current.device] || current.errored) + $ a_ [class_ "text-textWeak hover:underline", href_ $ root <> queryStringFrom (tab <> window)] "Clear filters" + + +segmentsPostH :: Projects.ProjectId -> [(Text, Maybe Text)] -> SegmentForm -> ATAuthCtx (RespHeaders (Html ())) +segmentsPostH pid params form = do + _ <- Projects.sessionAndProject pid + let name = T.strip form.name + filters = audienceFilters $ audienceParams form.filters + when (T.null name || T.length name > 100) $ throwError err400{errBody = "Segment name must contain 1–100 characters."} + Hasql.interpExecute_ [HI.sql|INSERT INTO projects.rum_segments (project_id, name, filters) VALUES (#{pid}, #{name}, #{HI.AsJsonb filters}) ON CONFLICT (project_id, name) DO UPDATE SET filters = EXCLUDED.filters|] + segmentsGetH pid params + + +segmentsDeleteH :: Projects.ProjectId -> Text -> [(Text, Maybe Text)] -> ATAuthCtx (RespHeaders (Html ())) +segmentsDeleteH pid name params = do + _ <- Projects.sessionAndProject pid + Hasql.interpExecute_ [HI.sql|DELETE FROM projects.rum_segments WHERE project_id = #{pid} AND name = #{name}|] + segmentsGetH pid params diff --git a/src/Pkg/Components/LogQueryBox.hs b/src/Pkg/Components/LogQueryBox.hs index 038b9c848..c22e8283e 100644 --- a/src/Pkg/Components/LogQueryBox.hs +++ b/src/Pkg/Components/LogQueryBox.hs @@ -342,7 +342,7 @@ logQueryBox_ config = do $ filter (not . hiddenHere) visTypes forM_ visible \v -> do let vizType = v.key - label_ [data_ "value" vizType, class_ "tab !shadow-none !border-strokeWeak flex gap-1 whitespace-nowrap"] do + label_ [data_ "value" vizType, class_ "tab !shadow-none !border-strokeWeak has-[:checked]:bg-fillBrand-weak! has-[:checked]:border-strokeBrand-strong! has-[:checked]:text-textBrand! flex gap-1 whitespace-nowrap"] do input_ $ [ type_ "radio" , name_ "visualization" diff --git a/src/Pkg/Components/Widget.hs b/src/Pkg/Components/Widget.hs index 3faa8d15a..c4c12a0d3 100644 --- a/src/Pkg/Components/Widget.hs +++ b/src/Pkg/Components/Widget.hs @@ -37,7 +37,7 @@ import Models.Apis.Monitors qualified as Monitors import Models.Projects.Projects qualified as Projects import NeatInterpolation import Pages.Charts.Charts qualified as Charts -import Pages.Components (copyButton_, headerRow_) +import Pages.Components (copyButton_, headerRow_, searchInput_) import Pkg.Components.TimePicker qualified as TimePicker import Pkg.DeriveUtils (JsonValueSchema (..), WrappedEnumSC (..)) import Pkg.Parser (ToQueryText (..), parseQueryToAST, replacePlaceholders) @@ -311,6 +311,7 @@ data Widget = Widget , standalone :: Maybe Bool -- Not used in a grid stack , allowZoom :: Maybe Bool -- Allow zooming in the chart , columns :: Maybe [TableColumn] -- Table columns + , searchable :: Maybe Bool , onRowClick :: Maybe RowClickAction -- Action when table row is clicked -- Alert fields (populated from QueryMonitor at render time) , alertId :: Maybe Text -- Linked QueryMonitor ID @@ -1190,17 +1191,19 @@ renderTable widget = do $ div_ [ class_ "h-full overflow-auto p-3" , hxGet_ $ widgetFetchUrl eagerWidget - , hxTrigger_ $ bool "intersect once, update-query from:window, table-sort" "update-query from:window, table-sort" (isJust widget.html) + , hxTrigger_ $ bool "intersect once, update-query from:window, table-sort" "update-query from:window, table-sort" (isJust widget.html) <> memptyIfFalse (widget.searchable == Just True) ", input delay:250ms, search" , hxTarget_ $ "#" <> tableId , hxSelect_ $ "#" <> tableId , hxSwap_ "outerHTML" , term "hx-sync" "this:replace" - , term "hx-vals" "js:{...Object.fromEntries(new URLSearchParams(location.search)), ...JSON.parse(this.closest('[data-constants]')?.dataset.constants || '{}'), 'table-sort': this.dataset.tableSort || ''}" + , term "hx-vals" "js:{...Object.fromEntries(new URLSearchParams(location.search)), ...JSON.parse(this.closest('[data-constants]')?.dataset.constants || '{}'), 'table-sort': this.dataset.tableSort || '', 'table-search': this.querySelector('input[type=search]')?.value || ''}" , data_ "table-fetch" "" ] - $ case widget.html of - Just html -> toHtmlRaw html - Nothing -> div_ [class_ "flex h-full min-h-32 items-center justify-center", id_ tableId] $ loadingIndicator_ LdSM LdSpinner + $ do + when (widget.searchable == Just True) $ searchInput_ "" ("Search " <> fromMaybe "rows" widget.title) [] + case widget.html of + Just html -> toHtmlRaw html + Nothing -> div_ [class_ "flex h-full min-h-32 items-center justify-center", id_ tableId] $ loadingIndicator_ LdSM LdSpinner -- | Render stat widget content with HTMX lazy loading support @@ -1635,6 +1638,7 @@ renderTableWithDataAndParams widget dataRows params = do ( [class_ $ "hover" <> memptyIfFalse (isJust widget.onRowClick) " cursor-pointer" <> memptyIfFalse isCurrent " bg-fillBrand-weak font-semibold"] <> [term "aria-current" "true" | isCurrent] <> rowNavAttrs rowValue + <> memptyIfFalse (isJust widget.onRowClick) [tabindex_ "0", Aria.label_ $ "Filter by " <> rowValue, term "_" " on keydown[key=='Enter' or key==' '] halt the event then call me.click() end "] ) $ ifor_ columns \idx col -> unless (or col.hidden) diff --git a/src/Pkg/Parser.hs b/src/Pkg/Parser.hs index d70cc0616..55cce765d 100644 --- a/src/Pkg/Parser.hs +++ b/src/Pkg/Parser.hs @@ -14,6 +14,7 @@ import Models.Projects.Projects qualified as Projects import Pkg.Deriving (WrappedEnumSC (..)) import Pkg.Parser.Expr import Pkg.Parser.Stats +import Pkg.Rum qualified as Rum import PyF (fmt) import Relude import Relude.Extra.Foldable1 (minimumOn1) @@ -964,6 +965,8 @@ variablePresets :: BinDensity -> Text -> Maybe UTCTime -> Maybe UTCTime -> [(Tex variablePresets density pid mf mt allParams currentTime = let fmtUTC = maybe "" formatUTC andPrefix = (" AND " <>) + audience = Rum.audienceFilters allParams + audienceSessions = Rum.audienceSessionsSql browserSql errorSql audience bound op t field' = field' <> " " <> op <> " '" <> formatUTC t <> "'" clause field = case catMaybes [bound ">=" <$> mf, bound "<=" <$> mt] of [] -> "" @@ -979,6 +982,10 @@ variablePresets density pid mf mt allParams currentTime = , ("pageview_filter", pageViewSql) , ("error_filter", errorSql) , ("browser_kql", browserKql) + , ("audience_sessions", audienceSessions) + , ("audience_kql_literal", sqlStringLit $ Rum.audienceKql audience) + , ("table_search", sqlStringLit $ maybeToMonoid $ join $ Map.lookup "table-search" $ Map.fromList allParams) + , ("audience_filter", if any isJust [audience.browser, audience.os, audience.device] || audience.errored then "attributes___session___id IN (" <> audienceSessions <> "SELECT session FROM audience_sessions)" else "TRUE") ] <> (allParams <&> second maybeToMonoid) diff --git a/src/Pkg/Rum.hs b/src/Pkg/Rum.hs new file mode 100644 index 000000000..dfdc1d6d2 --- /dev/null +++ b/src/Pkg/Rum.hs @@ -0,0 +1,93 @@ +module Pkg.Rum (AudienceFilters (..), audienceFilters, audienceParams, audienceSessionsSql, audienceKql) where + +import Data.Aeson qualified as AE +import Data.List (lookup) +import Data.Text qualified as T +import Pkg.Parser.Expr (sqlStringLit) +import Relude +import Utils (kqlQuoted, nonEmptyT) +import Web.FormUrlEncoded (FromForm) + + +data AudienceFilters = AudienceFilters + { app :: Maybe Text + , browser :: Maybe Text + , os :: Maybe Text + , device :: Maybe Text + , errored :: Bool + } + deriving stock (Eq, Generic, Show) + deriving anyclass (AE.FromJSON, AE.ToJSON, FromForm) + + +audienceFilters :: [(Text, Maybe Text)] -> AudienceFilters +audienceFilters params = AudienceFilters (param "app") (param "browser") (param "os") (param "device") (param "errors" == Just "true") + where + param key = nonEmptyT $ join $ lookup ("var-" <> key) params + + +audienceParams :: AudienceFilters -> [(Text, Maybe Text)] +audienceParams f = [("var-app", f.app), ("var-browser", f.browser), ("var-os", f.os), ("var-device", f.device), ("var-errors", Just $ if f.errored then "true" else "false")] + + +-- Ordered rules: embedded browser/OS names must not win over their host family. +data AgentRule = Contains (NonEmpty Text) | Tablet | AnyAgent + + +families :: [(Text, [(Text, AgentRule)])] +families = + [ ("browser", [("Edge", Contains ("Edg/" :| ["Edge/", "EdgiOS/", "EdgA/"])), ("Opera", Contains ("OPR/" :| ["Opera", "OPiOS/"])), ("Samsung Internet", Contains ("SamsungBrowser" :| [])), ("Firefox", Contains ("Firefox/" :| ["FxiOS/"])), ("Chrome", Contains ("Chrome/" :| ["CriOS/"])), ("Safari", Contains ("Safari/" :| []))]) + , ("os", [("Windows", Contains ("Windows" :| [])), ("iOS", Contains ("iPhone" :| ["iPad", "iPod"])), ("macOS", Contains ("Mac OS X" :| ["Macintosh"])), ("Android", Contains ("Android" :| [])), ("ChromeOS", Contains ("CrOS" :| [])), ("Linux", Contains ("Linux" :| ["X11"]))]) + , ("device", [("Tablet", Tablet), ("Mobile", Contains ("Mobile" :| ["iPhone", "iPod"])), ("Desktop", AnyAgent)]) + ] + + +audienceSessionsSql :: Text -> Text -> AudienceFilters -> Text +audienceSessionsSql browserSql errorSql f = + "WITH rum_session_events AS (SELECT attributes___session___id AS session, " + <> "MAX(COALESCE(NULLIF(attributes___user_agent___original, ''), NULLIF(resource___user_agent___original, ''), '')) AS ua, " + <> "MAX(NULLIF(attributes___user___id, '')) AS user_id, MAX(NULLIF(attributes___user___email, '')) AS email, MAX(NULLIF(attributes___user___full_name, '')) AS full_name, " + <> "MAX(timestamp) AS last_seen, MAX(CASE WHEN " + <> errorSql + <> " THEN 1 ELSE 0 END) AS errored " + <> "FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND " + <> browserSql + <> " AND NULLIF(attributes___session___id, '') IS NOT NULL GROUP BY attributes___session___id), " + <> "rum_sessions AS (SELECT *, " + <> T.intercalate ", " [classify rules <> " AS " <> key | (key, rules) <- families] + <> " FROM rum_session_events), " + <> "audience_sessions AS (SELECT * FROM rum_sessions WHERE " + <> T.intercalate " AND " ("TRUE" : [key <> " = " <> sqlStringLit val | (key, Just val) <- [("browser", f.browser), ("os", f.os), ("device", f.device)]] <> ["errored = 1" | f.errored]) + <> ") " + where + classify rules = "CASE WHEN ua = '' THEN 'Unknown' " <> T.concat ["WHEN " <> match rule <> " THEN " <> sqlStringLit label <> " " | (label, rule) <- rules] <> "ELSE 'Other' END" + match Tablet = "(ua ILIKE '%iPad%' OR (ua ILIKE '%Android%' AND ua NOT ILIKE '%Mobile%'))" + match AnyAgent = "TRUE" + match (Contains tokens) = "(" <> T.intercalate " OR " ["ua ILIKE " <> sqlStringLit ("%" <> token <> "%") | token <- toList tokens] <> ")" + + +-- The same ordered family rules drive session Explorer links. +audienceKql :: AudienceFilters -> Text +audienceKql f = + T.intercalate " and " + $ ["resource.service.name == " <> kqlQuoted value | value <- toList f.app] + <> [predicate rules value | (key, rules) <- families, Just value <- [join $ lookup key [("browser", f.browser), ("os", f.os), ("device", f.device)]]] + <> ["(status_code == \"ERROR\" or level matches /^error$/ or attributes.exception.type != null)" | f.errored] + where + attribute = "attributes.user_agent.original" + resource = "resource.user_agent.original" + predicate rules value + | value == "Unknown" = "(isempty(" <> attribute <> ") and isempty(" <> resource <> "))" + | value /= "Other" && isNothing (lookup value rules) = "1 == 0" + | otherwise = "((isnotempty(" <> attribute <> ") and " <> select attribute <> ") or (isempty(" <> attribute <> ") and isnotempty(" <> resource <> ") and " <> select resource <> "))" + where + (before, rest) = break ((== value) . fst) rules + select field = "(" <> T.intercalate " and " ([test False field rule | (_, rule) <- before] <> [maybe "1 == 1" (test True field . snd) $ listToMaybe rest]) <> ")" + test positive field (Contains tokens) = "(" <> T.intercalate (if positive then " or " else " and ") [field <> (if positive then " contains " else " !contains ") <> kqlQuoted token | token <- toList tokens] <> ")" + test positive _ AnyAgent = if positive then "1 == 1" else "1 == 0" + test positive field Tablet = + let has token = field <> " contains " <> kqlQuoted token + lacks token = field <> " !contains " <> kqlQuoted token + in if positive + then "(" <> has "iPad" <> " or (" <> has "Android" <> " and " <> lacks "Mobile" <> "))" + else "(" <> lacks "iPad" <> " and (" <> lacks "Android" <> " or " <> has "Mobile" <> "))" diff --git a/src/Web/Routes.hs b/src/Web/Routes.hs index 1b6968462..d7449ff08 100644 --- a/src/Web/Routes.hs +++ b/src/Web/Routes.hs @@ -77,6 +77,7 @@ import Pages.Projects qualified as ListProjects import Pages.Projects qualified as ManageMembers import Pages.Replay qualified as Replay import Pages.Reports qualified as Reports +import Pages.Rum qualified as Rum import Pages.ServiceMap qualified as ServiceMap import Pages.Settings qualified as Settings import Pages.Share qualified as Share @@ -473,6 +474,9 @@ data CookieProtectedRoutes mode = CookieProtectedRoutes , slackIdentityPost :: mode :- "slack" :> "link" :> Capture "linkId" (UUIDId "slack_link") :> ReqBody '[FormUrlEncoded] Slack.SlackLinkForm :> Post '[HTML] (RespHeaders (Html ())) , slackLinkProjectGet :: mode :- "slack" :> "oauth" :> "callback" :> QPT "code" :> QPT "state" :> LocationRedirect BotUtils.BotResponse , endpointDetailsRedirect :: mode :- "p" :> ProjectId :> "endpoints" :> "details" :> AllQueryParams :> LocationRedirect NoContent + , rumSegmentsGet :: mode :- "p" :> ProjectId :> "rum" :> "segments" :> AllQueryParams :> Get '[HTML] (RespHeaders (Html ())) + , rumSegmentsPost :: mode :- "p" :> ProjectId :> "rum" :> "segments" :> AllQueryParams :> ReqBody '[FormUrlEncoded] Rum.SegmentForm :> Post '[HTML] (RespHeaders (Html ())) + , rumSegmentsDelete :: mode :- "p" :> ProjectId :> "rum" :> "segments" :> Capture "name" Text :> AllQueryParams :> Delete '[HTML] (RespHeaders (Html ())) , rumRedirect :: mode :- "p" :> ProjectId :> "rum" :> CaptureAll "view" Text :> AllQueryParams :> LocationRedirect NoContent , dashboardNewGet :: mode :- "p" :> ProjectId :> "dashboards" :> "new" :> Get '[HTML] (RespHeaders Dashboards.DashboardNew) , dashboardsGet :: mode :- "p" :> ProjectId :> "dashboards" :> Capture "dashboard_id" Dashboards.DashboardId :> QPT "file" :> QPT "from" :> QPT "to" :> QPT "since" :> HXRequest :> AllQueryParams :> Get '[HTML] (RespHeaders (PageCtx Dashboards.DashboardGet)) @@ -977,6 +981,9 @@ cookieProtectedServer = , slackLinkProjectGet = Slack.linkProjectGetH , endpointDetailsRedirect = Dashboards.entrypointRedirectGetH "endpoint-stats.yaml" "Endpoint Analytics" ["endpoints", "http", "events"] , rumRedirect = Dashboards.rumRedirectH + , rumSegmentsGet = Rum.segmentsGetH + , rumSegmentsPost = Rum.segmentsPostH + , rumSegmentsDelete = Rum.segmentsDeleteH , dashboardsGet = Dashboards.dashboardGetH , dashboardNewGet = Dashboards.dashboardNewGetH , dashboardsGetList = Dashboards.dashboardsGetH diff --git a/static/migrations/0254_rum_segments.sql b/static/migrations/0254_rum_segments.sql new file mode 100644 index 000000000..90d78c861 --- /dev/null +++ b/static/migrations/0254_rum_segments.sql @@ -0,0 +1,6 @@ +CREATE TABLE projects.rum_segments ( + project_id uuid NOT NULL REFERENCES projects.projects(id) ON DELETE CASCADE, + name text NOT NULL CHECK (length(btrim(name)) BETWEEN 1 AND 100), + filters jsonb NOT NULL, + PRIMARY KEY (project_id, name) +); diff --git a/static/public/assets/css/tailwind.css b/static/public/assets/css/tailwind.css index b5caafa36..1463f542e 100644 --- a/static/public/assets/css/tailwind.css +++ b/static/public/assets/css/tailwind.css @@ -2588,6 +2588,43 @@ table td a[href]:not(.btn):not([data-no-preview]) { --tooltip-z: 100; --tooltip- container: dashboard / inline-size; } +[data-rum-audience] table { + table-layout: fixed; +} +[data-rum-audience] :is(th, td) { + overflow-wrap: anywhere; + white-space: normal; +} +[data-rum-audience] th > div, +[data-rum-audience] th > div > span { + min-width: 0; +} +@container dashboard (max-width: 400px) { + [data-rum-audience] > .grid-stack { + width: 100%; + margin-inline: 0 !important; + } + [data-rum-audience] .grid-stack-item > .grid-stack-item-content { + inset: auto !important; + } + [data-rum-audience] :is(th, td) { + padding-inline: 0.375rem; + } + [data-rum-audience] .nested-grid { + display: grid !important; + grid-template-columns: repeat(2, minmax(0, 1fr)); + width: 100% !important; + height: auto !important; + margin-inline: 0 !important; + } + [data-rum-audience] .nested-grid.grid-stack > .grid-stack-item:not([data-mobile-autofit]) { + width: auto !important; + min-width: 0; + height: 7.5rem !important; + min-height: 7.5rem !important; + } +} + .stat-widget { container: stat / inline-size; } diff --git a/static/public/dashboards/rum.yaml b/static/public/dashboards/rum.yaml index 134399927..063b1dd1d 100644 --- a/static/public/dashboards/rum.yaml +++ b/static/public/dashboards/rum.yaml @@ -30,6 +30,31 @@ variables: LIMIT 100 multi: false + - key: browser + title: Browser + type: values + multi: false + options: [[Chrome], [Edge], [Firefox], [Opera], [Safari], [Samsung Internet], [Other], [Unknown]] + + - key: os + title: Operating system + type: values + multi: false + options: [[Windows], [iOS], [macOS], [Android], [ChromeOS], [Linux], [Other], [Unknown]] + + - key: device + title: Device + type: values + multi: false + options: [[Desktop], [Mobile], [Tablet], [Other], [Unknown]] + + - key: errors + title: Session health + type: values + multi: false + options: [["false", All sessions], ["true", Sessions with errors]] + value: "false" + widgets: [] tabs: @@ -344,7 +369,8 @@ tabs: title: Browser error volume icon: triangle-exclamation query: *app - sql: *browser_error_series + sql: | + SELECT extract(epoch from time_bucket('{{rollup_interval}}', timestamp))::integer, 'value', count(*)::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} AND {{audience_filter}} GROUP BY time_bucket('{{rollup_interval}}', timestamp) ORDER BY time_bucket('{{rollup_interval}}', timestamp) DESC unit: errors summarize_by: sum series_intent: error @@ -355,7 +381,7 @@ tabs: icon: users query: *app sql: | - SELECT COUNT(DISTINCT attributes___session___id)::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} + SELECT COUNT(DISTINCT attributes___session___id)::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} AND {{audience_filter}} unit: sessions layout: { w: 4, h: 3 } @@ -364,7 +390,7 @@ tabs: icon: user query: *app sql: | - SELECT COUNT(DISTINCT COALESCE(attributes___user___id, attributes___user___email))::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} + SELECT COUNT(DISTINCT COALESCE(attributes___user___id, attributes___user___email))::float FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} AND {{audience_filter}} unit: users layout: { w: 4, h: 3 } @@ -401,50 +427,177 @@ tabs: LEFT(regexp_replace(COALESCE(NULLIF(attributes___exception___message, ''), NULLIF(status_message, ''), name, 'No error message'), '[0-9a-fA-F-]{8,}|[0-9]+', '', 'g'), 300) AS message, MIN(name) AS span_name, COUNT(*) AS n, COUNT(DISTINCT attributes___session___id)::text AS sessions, MAX(timestamp)::text AS last_seen FROM otel_logs_and_spans - WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} + WHERE {{query_ast_filters}} AND {{browser_filter}} AND {{error_filter}} AND {{audience_filter}} GROUP BY 1, 2, 3 ORDER BY COUNT(*) DESC LIMIT 50 ) AS groups ORDER BY n DESC - # User-agent families, coarse on purpose. Arm order matters: Edge and Opera embed "Chrome", - # Chrome embeds "Safari", iOS says "like Mac OS X", Android embeds "Linux". - name: Audience icon: users widgets: + - type: group + title: Audience in this window + description: Each session counts once. Unknown means no user agent was supplied; identified users exclude anonymous sessions. + layout: { w: 12, h: 3 } + children: + - type: stat + title: Audience sessions + query: *app + sql: "{{audience_sessions}} SELECT COUNT(*)::float FROM audience_sessions" + unit: sessions + layout: { w: 3, h: 2 } + - type: stat + title: Identified audience users + query: *app + sql: "{{audience_sessions}} SELECT COUNT(DISTINCT COALESCE('id:' || user_id, 'email:' || email))::float FROM audience_sessions" + unit: users + layout: { w: 3, h: 2 } + - type: stat + title: Sessions with errors + query: *app + sql: "{{audience_sessions}} SELECT COALESCE(SUM(errored), 0)::float FROM audience_sessions" + unit: sessions + series_intent: error + layout: { w: 3, h: 2 } + - type: stat + title: Session error rate + description: Sessions with at least one browser error divided by all sessions in the selected audience. + query: *app + sql: "{{audience_sessions}} SELECT (100.0 * SUM(errored) / NULLIF(COUNT(*), 0))::float FROM audience_sessions" + unit: '%' + series_intent: error + layout: { w: 3, h: 2 } + - type: table - title: Browsers, systems and devices - description: Sessions per user-agent family; errored counts sessions with at least one browser error. - layout: { w: 12, h: 7 } + title: Browsers + description: Select a row to filter this audience. Share is within the current filters; error rate is within each group. + layout: { x: 0, w: 4, h: 5 } + on_row_click: + set_variable: browser + navigate_to_tab: Audience columns: - - field: dimension - title: Dimension - field: name - title: Name + title: Browser - field: sessions title: Sessions column_type: number - progress: column_percent - - field: errored - title: Errored + - field: share + title: Share + unit: '%' + column_type: number + - field: affected + title: Affected description: Sessions with at least one browser error. column_type: number + - field: error_rate + title: Error rate + unit: '%' + column_type: number query: *app sql: | - WITH sessions AS ( - SELECT COALESCE(NULLIF(attributes___user_agent___original, ''), resource___user_agent___original) AS ua, attributes___session___id AS session, - MAX(CASE WHEN {{error_filter}} THEN 1 ELSE 0 END) AS errored - FROM otel_logs_and_spans WHERE {{query_ast_filters}} AND {{browser_filter}} - GROUP BY 1, 2 - ), families AS ( - SELECT session, errored, - CASE WHEN ua LIKE '%Edg/%' OR ua LIKE '%Edge/%' THEN 'Edge' WHEN ua LIKE '%OPR/%' OR ua LIKE '%Opera%' THEN 'Opera' WHEN ua LIKE '%SamsungBrowser%' THEN 'Samsung Internet' - WHEN ua LIKE '%Firefox/%' THEN 'Firefox' WHEN ua LIKE '%Chrome/%' OR ua LIKE '%CriOS/%' THEN 'Chrome' WHEN ua LIKE '%Safari/%' THEN 'Safari' ELSE 'Other' END AS browser, - CASE WHEN ua LIKE '%Windows%' THEN 'Windows' WHEN ua LIKE '%iPhone%' OR ua LIKE '%iPad%' OR ua LIKE '%iPod%' THEN 'iOS' WHEN ua LIKE '%Mac OS X%' OR ua LIKE '%Macintosh%' THEN 'macOS' - WHEN ua LIKE '%Android%' THEN 'Android' WHEN ua LIKE '%CrOS%' THEN 'ChromeOS' WHEN ua LIKE '%Linux%' OR ua LIKE '%X11%' THEN 'Linux' ELSE 'Other' END AS os, - CASE WHEN ua LIKE '%iPad%' OR (ua LIKE '%Android%' AND ua NOT LIKE '%Mobile%') THEN 'Tablet' WHEN ua LIKE '%Mobile%' OR ua LIKE '%iPhone%' THEN 'Mobile' ELSE 'Desktop' END AS device - FROM sessions WHERE ua IS NOT NULL - ), counted AS ( - SELECT 1 AS d, 'Browser' AS dimension, browser AS name, COUNT(DISTINCT session) AS n, SUM(errored) AS errored FROM families GROUP BY browser - UNION ALL SELECT 2, 'Operating system', os, COUNT(DISTINCT session), SUM(errored) FROM families GROUP BY os - UNION ALL SELECT 3, 'Device', device, COUNT(DISTINCT session), SUM(errored) FROM families GROUP BY device - ) - SELECT dimension, name, n::text AS sessions, errored::text AS errored FROM counted ORDER BY d, n DESC + {{audience_sessions}} + SELECT browser AS name, COUNT(*)::text AS sessions, + ROUND(100.0 * COUNT(*) / NULLIF(SUM(COUNT(*)) OVER (), 0), 1)::text AS share, + SUM(errored)::text AS affected, + ROUND(100.0 * SUM(errored) / NULLIF(COUNT(*), 0), 1)::text AS error_rate + FROM audience_sessions GROUP BY browser ORDER BY COUNT(*) DESC, browser + + - type: table + title: Operating systems + description: Select a row to filter this audience. Share is within the current filters; error rate is within each group. + layout: { x: 4, w: 4, h: 5 } + on_row_click: + set_variable: os + navigate_to_tab: Audience + columns: + - field: name + title: Operating system + - field: sessions + title: Sessions + column_type: number + - field: share + title: Share + unit: '%' + column_type: number + - field: affected + title: Affected + description: Sessions with at least one browser error. + column_type: number + - field: error_rate + title: Error rate + unit: '%' + column_type: number + query: *app + sql: | + {{audience_sessions}} + SELECT os AS name, COUNT(*)::text AS sessions, + ROUND(100.0 * COUNT(*) / NULLIF(SUM(COUNT(*)) OVER (), 0), 1)::text AS share, + SUM(errored)::text AS affected, + ROUND(100.0 * SUM(errored) / NULLIF(COUNT(*), 0), 1)::text AS error_rate + FROM audience_sessions GROUP BY os ORDER BY COUNT(*) DESC, os + + - type: table + title: Devices + description: Select a row to filter this audience. Share is within the current filters; error rate is within each group. + layout: { x: 8, w: 4, h: 5 } + on_row_click: + set_variable: device + navigate_to_tab: Audience + columns: + - field: name + title: Device + - field: sessions + title: Sessions + column_type: number + - field: share + title: Share + unit: '%' + column_type: number + - field: affected + title: Affected + description: Sessions with at least one browser error. + column_type: number + - field: error_rate + title: Error rate + unit: '%' + column_type: number + query: *app + sql: | + {{audience_sessions}} + SELECT device AS name, COUNT(*)::text AS sessions, + ROUND(100.0 * COUNT(*) / NULLIF(SUM(COUNT(*)) OVER (), 0), 1)::text AS share, + SUM(errored)::text AS affected, + ROUND(100.0 * SUM(errored) / NULLIF(COUNT(*), 0), 1)::text AS error_rate + FROM audience_sessions GROUP BY device ORDER BY COUNT(*) DESC, device + + - type: table + title: Identified users + description: Search all identified users in this audience by name, email or id. Shows up to 200 matches, most recently active first. + searchable: true + layout: { w: 12, h: 7 } + columns: + - field: user + title: User + link: /p/{{project_id}}/log_explorer?viz_type=sessions&query={{row.kql}}{{time_range}} + - field: sessions + title: Sessions + column_type: number + - field: affected + title: Affected sessions + column_type: number + - field: last_seen + title: Last seen + - field: kql + title: Session query + hidden: true + query: *app + sql: | + {{audience_sessions}} + SELECT COALESCE(MAX(email), MAX(full_name), MAX(user_id)) AS "user", COUNT(*)::text AS sessions, + SUM(errored)::text AS affected, MAX(last_seen)::text AS last_seen, + '{{browser_kql}}' || CASE WHEN {{audience_kql_literal}} = '' THEN '' ELSE ' and ' || {{audience_kql_literal}} END || + CASE WHEN MAX(user_id) IS NOT NULL THEN ' and attributes.user.id == "' || replace(replace(MAX(user_id), '\', '\\'), '"', '\"') || '"' + ELSE ' and attributes.user.email == "' || replace(replace(MAX(email), '\', '\\'), '"', '\"') || '"' END AS kql + FROM audience_sessions WHERE user_id IS NOT NULL OR email IS NOT NULL + GROUP BY COALESCE('id:' || user_id, 'email:' || email) + HAVING {{table_search}} = '' OR strpos(lower(COALESCE(MAX(email), '') || ' ' || COALESCE(MAX(full_name), '') || ' ' || COALESCE(MAX(user_id), '')), lower({{table_search}})) > 0 + ORDER BY 4 DESC LIMIT 200 diff --git a/test/integration/Pages/DashboardWidgetsSpec.hs b/test/integration/Pages/DashboardWidgetsSpec.hs index 475e093e5..614614cb9 100644 --- a/test/integration/Pages/DashboardWidgetsSpec.hs +++ b/test/integration/Pages/DashboardWidgetsSpec.hs @@ -45,6 +45,7 @@ import Pages.Dashboards (DashboardFilters (..)) import Pages.Dashboards qualified as Dashboards import Pages.Issues qualified as Issues import Pages.LogExplorer.Log qualified as Log +import Pages.Rum qualified as Rum import Pkg.Components.Widget qualified as Widget import Pkg.Parser (browserKql, parseQueryToAST) import Pkg.QueryCache qualified as QueryCache @@ -68,6 +69,7 @@ import Utils qualified import Web.ApiHandlers qualified as Api import Web.ApiTypes qualified as ApiTypes import Web.Auth qualified as Auth +import Web.FormUrlEncoded (urlDecodeAsForm) import Web.Routes qualified as Routes @@ -1430,7 +1432,7 @@ spec = sequential $ aroundAll withTestResources do it "rumDashboard_everyWidgetRuns_andVitalsReadHistogramBuckets" \tr -> do projectId <- createTestProject tr "RUM dashboard template" apiKey <- createTestAPIKey tr projectId "rum-dashboard-key" - let browserSpan n name attrs ua = ingestSpanReq tr $ mkSpanRequest ("e" <> T.justifyRight 31 '0' (show @Text n)) ("e" <> T.justifyRight 15 '0' (show @Text n)) Nothing name [] Nothing (mkAttr "session.id" "dash-session" : attrs) (mkResource apiKey [mkAttr "service.name" "storefront", mkAttr "user_agent.original" ua]) frozenTime + let browserSpan n name attrs ua = ingestSpanReq tr $ mkSpanRequest ("e" <> T.justifyRight 31 '0' (show @Text n)) ("e" <> T.justifyRight 15 '0' (show @Text n)) Nothing name [] Nothing (mkAttr "session.id" ("dash-session-" <> show n) : attrs) (mkResource apiKey [mkAttr "service.name" "storefront", mkAttr "user_agent.original" ua]) frozenTime browserSpan (1 :: Int) "documentLoad" [mkAttr "url.full" "https://shop.example/cart"] "Mozilla/5.0 (X11; Linux x86_64) Chrome/151" browserSpan 2 "Pageview · /orders/123" [mkAttr "url.path" "/orders/123", mkAttr "exception.type" "TypeError"] "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) Mobile/15E148 Safari/604.1" -- Three DELTA exports merge to [3,9,3,1,0] over 16 observations; the 12th lands on the @@ -1471,7 +1473,7 @@ spec = sequential $ aroundAll withTestResources do exportVital "lcp" [point (-5) (-10) [4, 0] & PMF.explicitBounds .~ [2500]] mixed <- run [vitals] vitalRow mixed "LCP" `shouldBe` Just ["LCP", "2344 ms", "rating;success-strong⇒Good", "0 – 2500", "20"] - sort [name | row <- V.toList $ table results "Browsers, systems and devices", row V.!? 0 == Just "Device", Just name <- [row V.!? 1]] `shouldBe` ["Desktop", "Mobile"] + sort [name | row <- V.toList $ table results "Devices", Just name <- [row V.!? 0]] `shouldBe` ["Desktop", "Mobile"] sort (V.toList $ V.mapMaybe (V.!? 0) $ table results "Top pages") `shouldBe` ["/cart", "/orders/:id"] -- Each page row's hidden Explorer query finds the events it counted, and the rendered -- link carries it with the dashboard's window while the column itself stays off screen. @@ -1490,6 +1492,58 @@ spec = sequential $ aroundAll withTestResources do map (\ps -> (lookup "since" ps, lookup "query" ps)) (linkParams ("/p/" <> projectId.toText <> "/log_explorer") html) `shouldBe` [(Just "7D", row V.!? 3) | row <- V.toList $ table results "Top pages"] + it "audience_countsEachSessionOnce_keepsUnknown_andFiltersCohorts" \tr -> do + pid <- createTestProject tr "RUM audience" + apiKey <- createTestAPIKey tr pid "audience-key" + let emit n session ua attrs = ingestSpanReq tr $ mkSpanRequest ("a" <> T.justifyRight 31 '0' (show @Text n)) ("a" <> T.justifyRight 15 '0' (show @Text n)) Nothing "documentLoad" [] Nothing (mkAttr "session.id" session : attrs) (mkResource apiKey $ mkAttr "service.name" "storefront" : [mkAttr "user_agent.original" agent | agent <- toList ua]) frozenTime + emit (1 :: Int) "safari" (Just "iPhone Mobile Safari/604") [mkAttr "user.id" "alice", mkAttr "user.email" "alice@example.com"] + emit 2 "safari" (Just "iPhone Mobile Safari/604") [mkAttr "user.id" "alice", mkAttr "exception.type" "TypeError"] + emit 3 "chrome" (Just "Windows Chrome/151 Safari/537") [mkAttr "user.id" "bob"] + emit 4 "unknown" Nothing [] + emit 5 "" (Just "Windows Chrome/151") [mkAttr "exception.type" "TypeError"] + rum <- maybe (fail "missing rum.yaml") pure . find (\d -> d.file == Just "rum.yaml") =<< DashboardModel.readDashboardsFromDisk "static/public/dashboards" + let from = toText $ iso8601Show $ addUTCTime (-3600) frozenTime + to = toText $ iso8601Show $ addUTCTime 3600 frozenTime + readTable params title = do + w <- maybe (fail $ "missing " <> toString title) pure $ find ((== Just title) . (.title)) (DashboardModel.allWidgets rum) + result <- runQueryEffect tr $ Charts.queryMetrics Nothing (Just Charts.DTText) (Just pid) w.query w.sql Nothing (Just from) (Just to) Nothing Nothing params + result.error `shouldBe` Nothing + pure result.dataText + browsers <- readTable [] "Browsers" + sort (map (V.toList . V.take 5) $ V.toList browsers) `shouldBe` [["Chrome", "1", "33.3", "0", "0.0"], ["Safari", "1", "33.3", "1", "100.0"], ["Unknown", "1", "33.3", "0", "0.0"]] + filtered <- readTable [("var-browser", Just "Safari")] "Devices" + map (V.toList . V.take 5) (V.toList filtered) `shouldBe` [["Mobile", "1", "100.0", "1", "100.0"]] + users <- readTable [("var-errors", Just "true")] "Identified users" + map (V.toList . V.take 3) (V.toList users) `shouldBe` [["alice@example.com", "1", "1"]] + forM_ ([([("var-browser", Just "Safari")], 2), ([("var-os", Just "iOS"), ("var-device", Just "Mobile")], 2), ([("var-browser", Just "Unknown")], 1), ([("var-errors", Just "true")], 2)] :: [([(Text, Maybe Text)], Int)]) \(params, expected) -> do + headers <- runAuthHandler tr $ Dashboards.rumRedirectH pid ["sessions"] params + let location = case lookupResponseHeader @"Location" headers of Header url -> url; _ -> "" + query = lookup "query" =<< listToMaybe (linkParams ("/p/" <> pid.toText <> "/log_explorer") ("href=\"" <> location <> "\"")) + (_, events) <- testServant tr $ Log.logExplorerDataH pid def{Log.query = query, Log.from = Just from, Log.to = Just to} + (events.error, events.queryResultCount) `shouldBe` (Nothing, expected) + readTable [("var-app", Just "missing-app")] "Browsers" `shouldReturn` V.empty + readTable [("environment", Just "prod")] "Browsers" `shouldReturn` V.empty + found <- readTable [("table-search", Just "ALICE")] "Identified users" + map (V.toList . V.take 3) (V.toList found) `shouldBe` [["alice@example.com", "1", "1"]] + readTable [("table-search", Just "missing-user")] "Identified users" `shouldReturn` V.empty + + it "audienceSegments_persistFilters_keepTheWindow_andStayProjectScoped" \tr -> do + pid <- createTestProject tr "RUM segments" + otherPid <- createTestProject tr "Other RUM segments" + let params = [("var-app", Just "storefront"), ("var-browser", Just "Safari"), ("var-device", Just "Mobile"), ("since", Just "7D"), ("tab", Just "errors")] + root = "/p/" <> pid.toText <> "/rum" + render = toStrict . renderText + form <- either (fail . toString) pure $ urlDecodeAsForm @Rum.SegmentForm "name=Mobile+Safari&app=storefront&browser=Safari&device=Mobile&os=&errored=false" + (_, saved) <- testServant tr $ Rum.segmentsPostH pid params form + let links = linkParams root (render saved) + links `shouldSatisfy` any (\ps -> lookup "var-browser" ps == Just "Safari" && lookup "since" ps == Just "7D" && lookup "tab" ps == Just "errors") + (_, reloaded) <- testServant tr $ Rum.segmentsGetH pid [] + render reloaded `shouldSatisfy` T.isInfixOf ">Mobile Safari" + (_, other) <- testServant tr $ Rum.segmentsGetH otherPid [] + render other `shouldNotSatisfy` T.isInfixOf ">Mobile Safari" + (_, deleted) <- testServant tr $ Rum.segmentsDeleteH pid "Mobile Safari" [] + render deleted `shouldNotSatisfy` T.isInfixOf ">Mobile Safari" + -- /rum and its older /rum/dashboard open the dashboard; /rum/sessions the Explorer. Links from -- emails and alerts carry a window, which both must keep. it "rumRedirects_openTheDashboardOrSessions_andKeepTheWindow" \tr -> do diff --git a/test/unit/Models/DashboardTemplatesSpec.hs b/test/unit/Models/DashboardTemplatesSpec.hs index ef560515a..6ec319ea5 100644 --- a/test/unit/Models/DashboardTemplatesSpec.hs +++ b/test/unit/Models/DashboardTemplatesSpec.hs @@ -6,7 +6,7 @@ import Data.Text qualified as T import Models.Projects.Dashboards qualified as Dashboards import Models.Projects.GitSync qualified as GitSync import Pkg.Components.Widget qualified as Widget -import Pkg.Parser (browserKql, parseQueryToAST) +import Pkg.Parser (BinDensity (BarDensity), browserKql, fillQueryTemplate, fixedUTCTime, parseQueryToAST, variablePresets) import Relude import System.Directory (listDirectory) import Test.Hspec (Spec, describe, expectationFailure, it, runIO, shouldBe, shouldSatisfy) @@ -76,8 +76,9 @@ spec = describe "dashboard templates" do Nothing -> expectationFailure "missing template: rum.yaml" Just d -> do let sqlWidgets = [w | w <- Dashboards.allWidgets d, isJust w.sql] + expand = fillQueryTemplate $ variablePresets BarDensity "project" Nothing Nothing [] fixedUTCTime sqlWidgets `shouldSatisfy` (not . null) - forM_ sqlWidgets \w -> (w.title, any (T.isInfixOf "{{query_ast_filters}}") w.sql, any (T.isInfixOf "{{var-app}}") w.query) `shouldBe` (w.title, True, True) + forM_ sqlWidgets \w -> (w.title, any (T.isInfixOf "{{query_ast_filters}}" . expand) w.sql, any (T.isInfixOf "{{var-app}}") w.query) `shouldBe` (w.title, True, True) it "endpoint latency summaries average percentile buckets and declare milliseconds" $ withEndpointTemplate \d -> do let flatten w = w : maybe [] (concatMap flatten) w.children From ac55bb7e4a4d55286edd6d23ed45dccd4867ba73 Mon Sep 17 00:00:00 2001 From: Anthony Alaribe Date: Tue, 27 Oct 2026 12:07:29 +0100 Subject: [PATCH 021/203] Issues responsive log details, API-change service labels, repositories redesign (#742) * Issues: responsive log details, API change service labels, code context cleanup * Simplify review fixes: fix unparsed hyperscript in trace divider and review rows * Match htmx 4 HX-Target on dashboard tabs; align tests with the redesigned repositories and issue pages * Close the review dialog on rerun; align repositories e2e with the table view * Align repositories e2e with the shared empty state and tab navigation * Host map e2e: the inspector drawer is modal --- e2e/tests/host-map.spec.ts | 7 +- e2e/tests/repositories.spec.ts | 19 +- hpack-includes/lib-deps.yaml | 1 + monoscope.cabal | 7 +- src/BackgroundJobs.hs | 15 +- src/Models/Apis/ApiChanges.hs | 52 +- src/Models/Apis/IssueEnhancement.hs | 38 +- src/Models/Apis/Issues.hs | 52 +- src/Models/Projects/ImpactReviews.hs | 3 +- src/Models/Projects/ProjectMemory.hs | 20 +- src/Pages/BodyWrapper.hs | 25 +- src/Pages/CodeContext.hs | 732 +++++++++++------- src/Pages/Components.hs | 42 +- src/Pages/Dashboards.hs | 18 +- src/Pages/GitSync.hs | 7 +- src/Pages/Issues.hs | 642 ++++++++++----- src/Pages/LogExplorer/Log.hs | 3 +- src/Pages/LogExplorer/LogItem.hs | 6 +- src/Pages/Monitors.hs | 94 +-- src/Pages/Replay.hs | 2 +- src/Pages/Telemetry.hs | 80 +- src/Pkg/Components/Table.hs | 47 +- src/Pkg/Parser.hs | 7 +- src/Web/Routes.hs | 21 +- .../0255_api_change_recorded_service.sql | 9 + static/public/assets/css/tailwind.css | 28 +- .../public/assets/svgs/fa-sprites/regular.svg | 3 + test/fixtures/wiki-browser.mjs | 30 +- test/integration/Pages/Bots/AgenticSpec.hs | 4 +- test/integration/Pages/CodeContextSpec.hs | 36 +- .../integration/Pages/DashboardWidgetsSpec.hs | 39 +- test/integration/Pages/ErrorPatternsSpec.hs | 2 +- test/integration/Pages/IssuesSpec.hs | 70 +- test/integration/Pages/TelemetrySpec.hs | 9 +- web-components/package-lock.json | 15 + web-components/package.json | 2 + web-components/src/index.ts | 6 +- web-components/src/log-list.ts | 42 +- web-components/src/log-worker-functions.ts | 8 + web-components/src/main.ts | 5 +- web-components/src/page-chrome.ts | 28 +- web-components/src/session-replay.ts | 277 ++++--- web-components/src/wiki-editor.css | 8 +- web-components/src/wiki-editor.ts | 73 +- web-components/test/log-list-bugs.test.ts | 2 +- web-components/test/log-list-embedded.test.ts | 5 +- web-components/test/page-chrome.test.ts | 36 +- .../test/session-replay-progressive.test.ts | 8 +- web-components/test/time-picker-state.test.ts | 17 + 49 files changed, 1698 insertions(+), 1004 deletions(-) create mode 100644 static/migrations/0255_api_change_recorded_service.sql diff --git a/e2e/tests/host-map.spec.ts b/e2e/tests/host-map.spec.ts index e0cfb1fe4..0c530ebfe 100644 --- a/e2e/tests/host-map.spec.ts +++ b/e2e/tests/host-map.spec.ts @@ -23,7 +23,7 @@ async function openHostMap(page: import("@playwright/test").Page) { test.describe("Host map", () => { test.describe.configure({ mode: "serial" }); - test("the desktop host inspector stays labelled and leaves the map interactive", async ({ page }) => { + test("the desktop host inspector is a labelled modal that returns focus on close", async ({ page }) => { await openHostMap(page); await expect(page.locator(`[data-visible-host-label="${HOST}"]`)).toBeVisible(); const host = page.getByRole("button", { name: new RegExp(`${HOST}, CPU usage:`) }); @@ -31,7 +31,7 @@ test.describe("Host map", () => { const dialog = page.getByRole("dialog"); await expect(dialog).toBeVisible(); - await expect(dialog).not.toHaveAttribute("aria-modal", "true"); + await expect(dialog).toHaveAttribute("aria-modal", "true"); await expect(dialog).toHaveAccessibleName(/vps-|host/i); const header = dialog.locator("header"); await expect(header).toBeVisible(); @@ -39,9 +39,6 @@ test.describe("Host map", () => { panel.querySelector('[aria-label="Close drawer"]')!.getBoundingClientRect().right - panel.querySelector('header')!.getBoundingClientRect().right, )).toBeLessThanOrEqual(-12); - await expect - .poll(() => page.locator("#main-content").evaluate((element) => (element as HTMLElement).inert)) - .toBe(false); await page.keyboard.press("Escape"); await expect(dialog).toBeHidden(); diff --git a/e2e/tests/repositories.spec.ts b/e2e/tests/repositories.spec.ts index a030fbc5c..211aee761 100644 --- a/e2e/tests/repositories.spec.ts +++ b/e2e/tests/repositories.spec.ts @@ -75,14 +75,14 @@ test('rerunning a pull request review replaces its view without nesting content' try { await page.context().addCookies([{ name: 'monoscope_session', value: sid, url: baseURL! }]); await page.goto(`/p/${pid}/repositories?tab=reviews`); - await page.getByText('team/checkout #1', { exact: true }).click(); + await page.getByRole('button', { name: 'View review for team/checkout #1', exact: true }).click(); await page.getByRole('button', { name: 'Rerun review', exact: true }).click(); await expect(page.locator('#repository-content').getByText('Queued', { exact: true })).toBeVisible(); await expect(page.locator('#repository-content')).toHaveCount(1); await expect(page.getByText('Review unavailable', { exact: true })).toHaveCount(0); await page.getByRole('navigation', { name: 'Repository views' }).getByRole('link', { name: 'Repositories', exact: true }).click(); await expect(page.locator('#repository-content')).toHaveCount(1); - await expect(page.getByRole('heading', { name: 'Connect the repositories behind your services', exact: true })).toBeVisible(); + await expect(page.getByText('Connect the repositories behind your services', { exact: true })).toBeVisible(); } finally { sql(`DELETE FROM background_jobs WHERE payload->>'contents' = '${run}'; DELETE FROM projects.projects WHERE id = '${pid}'; DELETE FROM users.users WHERE id = '${uid}';`); @@ -93,7 +93,7 @@ test('repositories are discoverable and their views survive navigation and histo await page.goto(`${project}/settings/integrations`); await page.locator('#main-sidenav').getByRole('link', { name: 'Repositories', exact: true }).click(); await expect(page).toHaveURL(`${project}/repositories`); - await expect(page.locator('#main-content').getByRole('heading', { name: 'Repositories', exact: true })).toBeVisible(); + await expect(page.getByRole('heading', { level: 1, name: 'Repositories', exact: true })).toBeVisible(); const views = page.getByRole('navigation', { name: 'Repository views' }); await views.getByRole('link', { name: 'Pull requests', exact: true }).click(); await expect(page).toHaveURL(/repositories\?tab=reviews/); @@ -487,9 +487,9 @@ test('service investigations reach only applicable repositories by keyboard in b const link = menu.getByRole('link', { name: 'View repositories', exact: true }); await link.focus(); await page.keyboard.press('Enter'); - await expect(page.getByRole('heading', { name: `Repositories for ${service}`, exact: true })).toBeVisible(); + await expect(page.getByRole('heading', { level: 1, name: `Repositories ${service}`, exact: true })).toBeVisible(); const content = page.locator('#repository-content'); - await expect(content.locator('article')).toHaveCount(2); + await expect(content.locator('tr.itemsListItem')).toHaveCount(2); await expect(content.getByRole('link', { name: 'acme/checkout', exact: true })).toHaveAttribute('href', `/p/${pid}/repositories/${repositories[0]}`); await expect(content.getByText('All services', { exact: true })).toBeVisible(); await expect(page.getByRole('link', { name: 'Add repositories', exact: true })).toHaveCount(0); @@ -497,14 +497,15 @@ test('service investigations reach only applicable repositories by keyboard in b await expect.poll(() => page.evaluate(() => document.documentElement.scrollWidth)).toBe(320); await expect.poll(() => page.locator('#side-nav-menu').evaluate(element => element.getBoundingClientRect().right)).toBeLessThanOrEqual(0); await page.screenshot({ path: testInfo.outputPath(`service-repositories-${theme}.png`) }); - await page.getByRole('link', { name: 'All repositories', exact: true }).click(); - await expect(page.locator('#repository-content article')).toHaveCount(4); + await page.setViewportSize({ width: 1200, height: 900 }); + await page.getByRole('navigation', { name: 'Repository views' }).getByRole('link', { name: 'Repositories', exact: true }).click(); + await expect(page.locator('#repository-content tr.itemsListItem')).toHaveCount(4); await page.goBack(); - await expect(page.getByRole('heading', { name: `Repositories for ${service}`, exact: true })).toBeVisible(); + await expect(page.getByRole('heading', { level: 1, name: `Repositories ${service}`, exact: true })).toBeVisible(); } sql(`DELETE FROM projects.code_mappings WHERE project_id = '${pid}' AND service IS NULL;`); await page.goto(`/p/${pid}/repositories/services/unmapped`); - await expect(page.getByRole('heading', { name: 'No repositories linked to this service', exact: true })).toBeVisible(); + await expect(page.getByText('No repositories linked to this service', { exact: true })).toBeVisible(); await expect(page.getByText('Ask a project editor to link services to their source repositories.', { exact: true })).toBeVisible(); await expect(page.getByRole('link', { name: 'Choose a repository', exact: true })).toHaveCount(0); } finally { diff --git a/hpack-includes/lib-deps.yaml b/hpack-includes/lib-deps.yaml index a22c19b9d..2bf02beff 100644 --- a/hpack-includes/lib-deps.yaml +++ b/hpack-includes/lib-deps.yaml @@ -56,6 +56,7 @@ - mmark - commonmark >= 0.2.6.1 && < 0.3 - commonmark-extensions >= 0.2.6 && < 0.3 +- Diff >= 1.0 && < 1.1 - parsec >= 3.1 && < 3.2 - xss-sanitize >= 0.3.7.2 && < 0.4 - extra diff --git a/monoscope.cabal b/monoscope.cabal index 5f0710fae..fd9759057 100644 --- a/monoscope.cabal +++ b/monoscope.cabal @@ -270,6 +270,7 @@ extra-source-files: static/migrations/0253_project_memory_legacy_writes.sql static/migrations/0254_ingest_sampling.sql static/migrations/0254_rum_segments.sql + static/migrations/0255_api_change_recorded_service.sql test/fixtures/github-app-test.pem test/fixtures/wiki-browser.mjs static/public/assets/web-components/dist/manifest.json @@ -510,7 +511,8 @@ library build-tool-depends: proto-lens-protoc:proto-lens-protoc build-depends: - PyF + Diff ==1.0.* + , PyF , Unique , aeson , aeson-extra @@ -1233,7 +1235,8 @@ test-suite test-dev hspec-discover:hspec-discover , proto-lens-protoc:proto-lens-protoc build-depends: - PyF + Diff ==1.0.* + , PyF , Unique , aeson , aeson-extra diff --git a/src/BackgroundJobs.hs b/src/BackgroundJobs.hs index f5ddc7317..9391a1a9f 100644 --- a/src/BackgroundJobs.hs +++ b/src/BackgroundJobs.hs @@ -3799,13 +3799,14 @@ enhanceIssuesWithLLM pid issueIds = do enhancement.enhancedTitle enhancement.recommendedAction enhancement.migrationComplexity - -- Also classify and update criticality - criticalityResult <- Enhancement.classifyIssueCriticality ctx issue - case criticalityResult of - Left err -> Log.logAttention "Failed to classify issue criticality" (issueId, err) - Right (isCritical, breakingCount, _incrementalCount) -> do - void $ Enhancement.updateIssueClassification issue.id isCritical breakingCount - Log.logInfo "Successfully enhanced and classified issue" (issueId, isCritical, breakingCount) + -- Schema observations do not establish consumer compatibility or urgency. + when (issue.issueType /= Issues.ApiChange) do + criticalityResult <- Enhancement.classifyIssueCriticality ctx issue + case criticalityResult of + Left err -> Log.logAttention "Failed to classify issue criticality" (issueId, err) + Right (isCritical, breakingCount, _incrementalCount) -> do + void $ Enhancement.updateIssueClassification issue.id isCritical breakingCount + Log.logInfo "Successfully enhanced and classified issue" (issueId, isCritical, breakingCount) -- Analyze error patterns for root cause and category. -- Left = not a runtime exception, or the LLM call failed. diff --git a/src/Models/Apis/ApiChanges.hs b/src/Models/Apis/ApiChanges.hs index 5a6f0576b..3ff1a8f30 100644 --- a/src/Models/Apis/ApiChanges.hs +++ b/src/Models/Apis/ApiChanges.hs @@ -8,6 +8,9 @@ -- that nothing ever read back. module Models.Apis.ApiChanges ( AnomalyVM (..), + SchemaSubject (..), + schemaSubject, + spanSchemaTitle, FieldEvidence (..), FieldSnapshot (..), fieldSnapshot, @@ -19,7 +22,6 @@ module Models.Apis.ApiChanges ( FieldChange (..), FieldChangeKind (..), parseAnomalyTypes, - detectService, getAnomaliesVM, ) where @@ -28,7 +30,6 @@ import Data.Aeson qualified as AE import Data.Default (Default, def) import Data.Effectful.Hasql qualified as Hasql import Data.HashMap.Strict qualified as HM -import Data.Text qualified as T import Data.Text.Display (Display) import Data.Time import Data.Vector qualified as V @@ -88,6 +89,9 @@ data AnomalyVM = AnomalyVM , endpointMethod :: Maybe Text , endpointUrlPath :: Maybe Text , endpointHost :: Maybe Text + , serviceName :: Maybe Text + , keyKind :: Maybe Catalog.KeyKind + , scope :: Maybe (Aeson Catalog.Scope) , newFields :: V.Vector Text , modifiedFields :: V.Vector Text , fieldEvidence :: Aeson (V.Vector FieldEvidence) @@ -96,6 +100,21 @@ data AnomalyVM = AnomalyVM deriving anyclass (HI.DecodeRow) +-- | HTTP and non-HTTP schema observations have different telemetry identities. +data SchemaSubject = EndpointSchema Catalog.Scope | SpanSchema Catalog.Scope + deriving stock (Generic, Show) + deriving anyclass (AE.FromJSON, AE.ToJSON, NFData) + + +schemaSubject :: Catalog.KeyKind -> Catalog.Scope -> SchemaSubject +schemaSubject Catalog.HttpEndpoint = EndpointSchema +schemaSubject Catalog.SpanIdentity = SpanSchema + + +spanSchemaTitle :: Catalog.Scope -> Text +spanSchemaTitle scope = "Span schema changed" <> foldMap (": " <>) scope.spanName + + -- | Immutable observations at detection time; absence of a prior snapshot means a new field. data FieldEvidence = FieldEvidence { path :: !Text @@ -143,6 +162,9 @@ SELECT COALESCE(an.method, endpoints.method), COALESCE(an.url_path, endpoints.url_path), COALESCE(an.host, endpoints.host), + COALESCE(NULLIF(btrim(c.scope->>'service'), ''), NULLIF(btrim(endpoints.service_name), '')), + c.key_kind, + c.scope, an.new_fields, an.modified_fields, an.field_evidence @@ -150,6 +172,8 @@ from apis.anomalies an LEFT JOIN apis.endpoints ON an.project_id = endpoints.project_id AND endpoints.hash = split_part(an.target_hash, ':', 1) + LEFT JOIN apis.schema_catalog c ON c.project_id = an.project_id + AND c.key_hash = split_part(an.target_hash, ':', 1) where an.project_id=#{pid} AND an.target_hash=ANY(#{hash}) |] @@ -203,29 +227,5 @@ data FieldChangeKind = Modified | Added | Removed deriving anyclass (AE.FromJSON, AE.ToJSON, NFData) --- | Derive a service name from the path (@\/api\/v1\/auth\/login@ → @auth-service@), falling back to the host. --- --- The @api@ form skips the version segment, so @\/api\/v1\/auth\/…@ and @\/api\/v2\/auth\/…@ are --- one service rather than two: --- --- >>> detectService Nothing (Just "/api/v1/auth/login") --- "auth-service" --- >>> detectService Nothing (Just "/billing/invoices") --- "billing-service" --- --- Anything with no usable first segment — no path, a bare @\/@, or an @\/api@ too short to --- carry a service — falls back to the host, then to a constant: --- --- >>> detectService (Just "checkout.internal") (Just "/") --- "checkout.internal" --- >>> detectService Nothing Nothing --- "api-service" -detectService :: Maybe Text -> Maybe Text -> Text -detectService hostM endpointPathM = case maybe [] (T.splitOn "/" . T.dropWhile (== '/')) endpointPathM of - ("api" : _ : service : _) -> service <> "-service" - (service : _) | service /= "" -> service <> "-service" - _ -> fromMaybe "api-service" hostM - - -- $setup -- >>> :set -XOverloadedStrings diff --git a/src/Models/Apis/IssueEnhancement.hs b/src/Models/Apis/IssueEnhancement.hs index ec063b9d8..9a258cc84 100644 --- a/src/Models/Apis/IssueEnhancement.hs +++ b/src/Models/Apis/IssueEnhancement.hs @@ -114,20 +114,7 @@ buildTitlePrompt issue = |] case issue.issueType of Issues.ApiChange -> - withIssueData @Issues.APIChangeData issue "Generate a concise title for this API change." \d -> - if V.null d.newFields && V.null d.deletedFields && V.null d.modifiedFields - then - [fmtTrim|Generate a concise title for this newly discovered API endpoint. - Endpoint: {d.endpointMethod} {d.endpointPath} - Service: {Issues.serviceLabel issue.service} - This is a brand new endpoint that was just detected for the first time.|] - else - [fmtTrim|Generate a concise, descriptive title for this API change. - Endpoint: {d.endpointMethod} {d.endpointPath} - New fields: {V.length d.newFields} - Deleted fields: {V.length d.deletedFields} - Modified fields: {V.length d.modifiedFields} - Service: {Issues.serviceLabel issue.service}|] + withIssueData @Issues.APIChangeData issue "Generate a concise title for this schema observation." schemaObservationPrompt Issues.RuntimeException -> withIssueData @Issues.RuntimeExceptionData issue "Generate a concise title for this runtime exception." \d -> [fmtTrim|Generate a concise title for this runtime exception. @@ -218,21 +205,7 @@ buildDescriptionPrompt issue = |] case issue.issueType of Issues.ApiChange -> - withIssueData @Issues.APIChangeData issue "Describe this API change and its implications." \d -> - if V.null d.newFields && V.null d.deletedFields && V.null d.modifiedFields - then - [fmtTrim|Describe this newly discovered API endpoint. - Endpoint: {d.endpointMethod} {d.endpointPath} - Service: {Issues.serviceLabel issue.service} - This endpoint was just detected for the first time. Summarize what it likely does based on its path and method.|] - else - [fmtTrim|Describe this API change and its impact. - Endpoint: {d.endpointMethod} {d.endpointPath} - New fields: {show $ V.toList d.newFields} - Deleted fields: {show $ V.toList d.deletedFields} - Modified fields: {show $ V.toList d.modifiedFields} - Total anomalies grouped: {V.length d.anomalyHashes} - Service: {Issues.serviceLabel issue.service}|] + withIssueData @Issues.APIChangeData issue "Describe this schema observation." schemaObservationPrompt Issues.RuntimeException -> withIssueData @Issues.RuntimeExceptionData issue "Analyze this runtime exception." \d -> [fmtTrim|Analyze this runtime exception and provide debugging guidance. @@ -314,6 +287,13 @@ buildDescriptionPrompt issue = An error occurred in the same trace: {related}|] +schemaObservationPrompt :: Issues.APIChangeData -> Text +schemaObservationPrompt observation = + "Describe the observed schema data below. Use its subject to distinguish an HTTP endpoint from a span. " + <> "Do not invent HTTP details for a span, infer consumer breakage from sample/format changes, or infer required fields. " + <> decodeUtf8 (AE.encode observation) + + -- | Classify issue as critical/safe and count breaking/incremental changes classifyIssueCriticality :: ELLM.LLM :> es => AuthContext -> Issues.Issue -> Eff es (Either Text (Bool, Int, Int)) classifyIssueCriticality authCtx issue = (parse =<<) <$> askLLMLines authCtx (buildCriticalityPrompt issue) diff --git a/src/Models/Apis/Issues.hs b/src/Models/Apis/Issues.hs index b177f42aa..122cefbc6 100644 --- a/src/Models/Apis/Issues.hs +++ b/src/Models/Apis/Issues.hs @@ -34,6 +34,8 @@ module Models.Apis.Issues ( APIChangeData (..), apiChangeDataFrom, hasFieldDrift, + knownMethod, + knownHost, RuntimeExceptionData (..), QueryAlertData (..), ThresholdDirection (..), @@ -460,7 +462,9 @@ serviceLabel = fromMaybe "unknown-service" isNewEndpointOnly :: Issue -> Bool isNewEndpointOnly issue = case issuePayload issue of - Just (ApiChangeP d) -> not $ hasFieldDrift d + Just (ApiChangeP d) -> case d.subject of + Just (ApiChanges.SpanSchema _) -> False + _ -> not $ hasFieldDrift d _ -> False @@ -468,9 +472,16 @@ hasFieldDrift :: APIChangeData -> Bool hasFieldDrift d = not $ all V.null ([d.newFields, d.deletedFields, d.modifiedFields] :: [V.Vector Text]) +-- | The endpoint's method and host, absent the placeholders 'apiChangeDataFrom' stores for missing values. +knownMethod, knownHost :: APIChangeData -> Maybe Text +knownMethod d = mfilter (`notElem` ["", "UNKNOWN"]) $ Just $ T.strip d.endpointMethod +knownHost d = mfilter (`notElem` ["", "Unknown"]) $ Just $ T.strip d.endpointHost + + -- | API Change issue data data APIChangeData = APIChangeData - { endpointMethod :: Text + { subject :: Maybe ApiChanges.SchemaSubject + , endpointMethod :: Text , endpointPath :: Text , endpointHost :: Text , anomalyHashes :: V.Vector Text @@ -490,7 +501,8 @@ data APIChangeData = APIChangeData instance Semigroup APIChangeData where a <> b = b - { anomalyHashes = u (.anomalyHashes) + { subject = b.subject <|> a.subject + , anomalyHashes = u (.anomalyHashes) , shapeChanges = a.shapeChanges <> b.shapeChanges , formatChanges = a.formatChanges <> b.formatChanges , newFields = u (.newFields) @@ -858,6 +870,11 @@ selectIssues pid projection f = do AND ((^{col}is_framework AND ep.parent_hash = ^{col}target_hash) OR (NOT ^{col}is_framework AND ep.hash = ^{col}target_hash))), (^{col}issue_data->>'last_seen')::timestamptz) + WHEN ^{col}issue_type = ^{enumLit ApiChange} THEN COALESCE( + (SELECT MAX(an.created_at) FROM apis.anomalies an + WHERE an.project_id = ^{col}project_id + AND an.target_hash IN (SELECT jsonb_array_elements_text(^{col}issue_data->'anomaly_hashes'))), + ^{col}created_at) END, ^{col}updated_at) |] orderBy pfx | f.order == Just "-last_seen" = lastSeenAt pfx <> [HI.sql| DESC, ^{rawSql pfx}id DESC|] orderBy pfx = rawSql case T.uncons =<< f.order of @@ -946,13 +963,12 @@ selectIssues pid projection f = do pure (issues, total) --- | Fold an anomaly group's drift into an open API-change issue, escalating it on a breaking change. +-- | Fold observed schema drift into an open issue without inferring consumer compatibility. -- The row lock keeps concurrent jobs folding into the same issue from dropping each other's drift. updateIssueWithNewAnomaly :: (DB es, Time :> es) => IssueId -> NonEmpty ApiChanges.AnomalyVM -> Eff es () updateIssueWithNewAnomaly issueId anomalies = do now <- Time.currentTime let new = apiChangeDataFrom anomalies - breaking = not (V.null new.deletedFields && V.null new.modifiedFields) Hasql.transaction TxS.ReadCommitted TxS.Write do old <- Hasql.queryTx @[HI.OneColumn (Aeson AE.Value)] @@ -962,8 +978,7 @@ updateIssueWithNewAnomaly issueId anomalies = do [HI.sql| UPDATE apis.issues SET issue_data = issue_data || #{Aeson merged}::jsonb, - critical = critical OR #{breaking}, - severity = CASE WHEN #{breaking} THEN #{Critical} ELSE severity END, + service = #{(head anomalies).serviceName}, affected_requests = affected_requests + 1, updated_at = #{now} WHERE id = #{issueId} |] @@ -1327,7 +1342,8 @@ autoArchiveStaleDiscoveryIssues pid now days = apiChangeDataFrom :: NonEmpty ApiChanges.AnomalyVM -> APIChangeData apiChangeDataFrom anomalies@(a :| _) = APIChangeData - { endpointMethod = fromMaybe "UNKNOWN" a.endpointMethod + { subject = ApiChanges.schemaSubject <$> a.keyKind <*> (getAeson <$> a.scope) + , endpointMethod = fromMaybe "UNKNOWN" a.endpointMethod , endpointPath = fromMaybe "/" a.endpointUrlPath , endpointHost = fromMaybe "Unknown" a.endpointHost , anomalyHashes = V.fromList $ toList $ fmap (.targetHash) anomalies @@ -1346,23 +1362,23 @@ createAPIChangeIssue :: (Time :> es, UUIDEff :> es) => Projects.ProjectId -> Tex createAPIChangeIssue projectId endpointHash anomalies = do let firstAnomaly = head anomalies apiChangeData = apiChangeDataFrom anomalies - breakingChanges = V.length apiChangeData.deletedFields + V.length apiChangeData.modifiedFields - isCritical = breakingChanges > 0 mkIssue MkIssueOpts { projectId , targetHash = endpointHash , parentHash = Nothing , isFramework = False - , service = Just $ ApiChanges.detectService Nothing firstAnomaly.endpointUrlPath - , critical = isCritical - , severity = if isCritical then Critical else Warning - , title = - if any ((== ApiChanges.ATEndpoint) . (.anomalyType)) anomalies - then "New endpoint detected: " <> apiChangeData.endpointMethod <> " " <> apiChangeData.endpointPath <> " on " <> apiChangeData.endpointHost - else "API structure has changed" + , service = firstAnomaly.serviceName + , critical = False + , severity = Warning + , title = case apiChangeData.subject of + Just (ApiChanges.SpanSchema scope) -> ApiChanges.spanSchemaTitle scope + _ -> + if any ((== ApiChanges.ATEndpoint) . (.anomalyType)) anomalies + then "New endpoint detected: " <> apiChangeData.endpointMethod <> " " <> apiChangeData.endpointPath <> " on " <> apiChangeData.endpointHost + else "API schema changed" , recommendedAction = defaultRecommendedAction - , migrationComplexity = if breakingChanges > 5 then "high" else if breakingChanges > 0 then "medium" else "low" + , migrationComplexity = "low" , payload = ApiChangeP apiChangeData , timestamp = Just firstAnomaly.createdAt } diff --git a/src/Models/Projects/ImpactReviews.hs b/src/Models/Projects/ImpactReviews.hs index 0f79664fc..bfb25f375 100644 --- a/src/Models/Projects/ImpactReviews.hs +++ b/src/Models/Projects/ImpactReviews.hs @@ -68,6 +68,7 @@ data ReviewRun = ReviewRun , error :: Maybe Text , commentId :: Maybe Int64 , latestRevision :: Text + , createdAt :: UTCTime } deriving stock (Generic, Show) deriving anyclass (AE.FromJSON, HI.DecodeRow) @@ -179,7 +180,7 @@ selectRuns :: DB es => Maybe ProjectId -> Maybe ReviewId -> Eff es [ReviewRun] selectRuns pid rid = Hasql.interp [HI.sql|SELECT r.id, t.id, t.project_id, t.owner, t.repo, t.number::bigint, r.revision, - r.state, r.result, r.error, t.comment_id, t.latest_revision + r.state, r.result, r.error, t.comment_id, t.latest_revision, r.created_at FROM projects.pr_review_runs r JOIN projects.pr_review_threads t ON t.id = r.thread_id WHERE (#{pid}::uuid IS NULL OR t.project_id = #{pid}) AND (#{rid}::uuid IS NULL OR r.id = #{rid}) ORDER BY r.created_at DESC LIMIT 20|] diff --git a/src/Models/Projects/ProjectMemory.hs b/src/Models/Projects/ProjectMemory.hs index 554cc3dfe..6efbfb75c 100644 --- a/src/Models/Projects/ProjectMemory.hs +++ b/src/Models/Projects/ProjectMemory.hs @@ -1,4 +1,4 @@ -module Models.Projects.ProjectMemory (PagePath, mkPagePath, pagePathText, WriteError (..), pageAtPath, pageWindow, PageId, MemoryText, mkMemoryText, memoryText, Document (..), Author (..), Page (..), pageLimit, latestPages, pageHistory, writePage) where +module Models.Projects.ProjectMemory (PagePath, mkPagePath, pagePathText, WriteError (..), PageFilter (..), pageAtPath, pageWindow, PageId, MemoryText, mkMemoryText, memoryText, Document (..), Author (..), Page (..), pageLimit, latestPages, pageHistory, writePage) where import Data.Aeson qualified as AE import Data.Char (isAlphaNum, isAscii) @@ -161,15 +161,25 @@ pageAtPath :: DB es => UUIDId "project" -> PagePath -> Eff es (Maybe PageId) pageAtPath pid path = fmap HI.getOneColumn <$> Hasql.interpOne [HI.sql| SELECT page_id FROM projects.memory_pages WHERE project_id = #{pid} AND path = #{path} |] -pageWindow :: DB es => UUIDId "project" -> Maybe PagePath -> Eff es [Page] -pageWindow pid after = - Hasql.interp - [HI.sql| +-- | 'LinkingTo' matches both @[[path]]@ and @[[path|title]]@ wikilinks; 'Matching' is a case-insensitive substring of path, title or body. +data PageFilter = AllPages | Matching Text | LinkingTo PagePath + + +pageWindow :: DB es => UUIDId "project" -> PageFilter -> Maybe PagePath -> Eff es [Page] +pageWindow pid scope after = + let (search, target) = case scope of + AllPages -> (Nothing, Nothing) + Matching term -> (Just $ T.toLower term, Nothing) + LinkingTo path -> (Nothing, Just path) + in Hasql.interp + [HI.sql| SELECT p.page_id, r.version, r.document, r.author, r.created_at, p.path FROM projects.memory_pages p CROSS JOIN LATERAL ( SELECT version, document, author, created_at FROM projects.memory_revisions WHERE project_id = p.project_id AND page_id = p.page_id ORDER BY version DESC LIMIT 1 ) r WHERE p.project_id = #{pid} AND (#{after}::text IS NULL OR p.path > #{after}) + AND (#{search}::text IS NULL OR strpos(lower(p.path || ' ' || (r.document->>'title') || ' ' || (r.document->>'body')), #{search}) > 0) + AND (#{target}::text IS NULL OR p.path <> #{target} AND (strpos(r.document->>'body', '[[' || #{target} || ']]') > 0 OR strpos(r.document->>'body', '[[' || #{target} || '|') > 0)) ORDER BY p.path LIMIT #{pageLimit + 1} |] diff --git a/src/Pages/BodyWrapper.hs b/src/Pages/BodyWrapper.hs index 09baa8d9a..fb9dabae1 100644 --- a/src/Pages/BodyWrapper.hs +++ b/src/Pages/BodyWrapper.hs @@ -25,6 +25,7 @@ import Models.Projects.Projects qualified as Projects import NeatInterpolation (text) import Pages.CommandPalette qualified as CommandPalette import Pages.Components qualified as Components +import Pages.LogExplorer.LogItem qualified as LogItem import Pkg.DeriveUtils (DB, UUIDId, WrappedEnumShow (..), assetUrl, viteAssetFile) import PyF import Relude hiding (ask) @@ -230,6 +231,7 @@ data BWConfig = BWConfig , currProject :: Maybe Projects.Project , prePageTitle :: Maybe Text , pageTitle :: Text + , pageTitleUrl :: Maybe Text -- Link for a parent breadcrumb with a dynamic route. , pageTitleSuffix :: Maybe Text -- Additional breadcrumb after pageTitle (e.g., tab name) , pageTitleModalId :: Maybe Text -- Modal ID for renaming page title , pageTitleSuffixModalId :: Maybe Text -- Modal ID for renaming suffix (e.g., tab) @@ -243,6 +245,7 @@ data BWConfig = BWConfig , needsGridStack :: Bool , needsTagify :: Bool , headContent :: Maybe (Html ()) -- Optional HTML content to include in the head + , pageProvidesLogDetails :: Bool -- Explorer supplies its resizable panel; other project pages use the shell drawer. , globalDrawerContent :: Maybe (Html ()) , config :: EnvConfig -- Environment configuration for telemetry , envOptions :: V.Vector Text @@ -501,6 +504,8 @@ bodyWrapper bcfg child = do if bcfg.isSettingsPage then maybe child (\p -> settingsWrapper p.id bcfg.pageTitle child) bcfg.currProject else child + unless bcfg.pageProvidesLogDetails $ forM_ bcfg.currProject \p -> + LogItem.detailsPanel_ p.id Nothing LogItem.DrawerPanel div_ [class_ "h-0 shrink"] do Components.drawer_ "global-data-drawer" (isJust bcfg.globalDrawerContent) Nothing bcfg.globalDrawerContent "" -- Modal for copying widgets to other dashboards @@ -654,7 +659,7 @@ bodyWrapper bcfg child = do "" div_ [class_ "hidden group-has-[#ai-composer-routine:checked]/dialog:flex items-center justify-between gap-3 border-b border-base-300 px-4 py-3"] do label_ [Lucid.for_ "ai-routine-interval", class_ "text-xs font-medium text-textStrong"] "Run every" - select_ [id_ "ai-routine-interval", name_ "intervalMinutes", class_ "select select-sm h-8 min-h-8 border-strokeWeak bg-bgRaised text-xs text-textStrong"] do + select_ [id_ "ai-routine-interval", name_ "intervalMinutes", disabled_ "disabled", term "hx-live:disabled" "!q('#ai-composer-routine').checked", class_ "select select-sm h-8 min-h-8 border-strokeWeak bg-bgRaised text-xs text-textStrong"] do option_ [value_ "60", class_ "bg-bgRaised text-textStrong"] "Hour" option_ [value_ "1440", selected_ "selected", class_ "bg-bgRaised text-textStrong"] "Day" option_ [value_ "10080", class_ "bg-bgRaised text-textStrong"] "Week" @@ -746,7 +751,15 @@ sideNav sess project bcfg = aside_ [class_ "group/nav relative z-40 bg-fillWeake -- Collapsed: search icon button_ ([class_ "group-has-[#sidenav-toggle:checked]/pg:hidden flex items-center justify-center p-2 rounded-lg hover:bg-fillHover text-textWeak hover:text-textStrong cursor-pointer transition-colors duration-100", searchScript, Aria.label_ "Search"] <> tippyRight_ "Search (\x2318K)") do faSprite_ "sidebar-search" "regular" "w-4 h-4" - Components.segmented_ "hidden group-has-[#sidenav-toggle:checked]/pg:grid grid-cols-2 rounded-lg bg-fillWeak p-0.5 text-xs" "Sidebar view" "nav-view" "nav-view-" [("menu", "Navigate"), ("ai", "Assistant")] + let defaultView = bool "menu" "ai" (bcfg.menuItem == Just "AI") :: Text + Components.segmentedWith_ + [class_ "hidden group-has-[#sidenav-toggle:checked]/pg:grid grid-cols-2 rounded-lg bg-fillWeak p-0.5 text-xs"] + "Sidebar view" + "nav-view" + "nav-view-" + [ (view, label, [checked_ | view == defaultView] <> [term "hx-live:checked" ("this.value === (sessionStorage.getItem('sidebar-view') || '" <> defaultView <> "')"), [__|on input call sessionStorage.setItem('sidebar-view', my.value)|]]) + | (view, label) <- [("menu", "Navigate"), ("ai", "Assistant")] + ] nav_ [id_ "main-sidenav", class_ "mt-2 min-h-0 overflow-x-hidden overflow-y-auto flex flex-col gap-1 text-textWeak group-has-[#nav-view-ai:checked]/nav:hidden [&_.main-nav-link.active]:bg-fillBrand-weak [&_.main-nav-link.active]:text-textStrong [&_.main-nav-link.active]:font-medium [&_.main-nav-link.active]:border-l-strokeBrand-strong [&_.main-nav-link.active]:border-y-transparent [&_.main-nav-link.active]:border-r-transparent [&_.main-nav-link.active_.nav-icon]:text-textBrand", [__|on click set #mobile-nav-toggle.checked to false end|]] do let pidTxt = project.id.toText flyoutLink (linkText, link) = @@ -1024,12 +1037,12 @@ navbar bcfg menuL = toHtml pt faSprite_ "chevron-right" "regular" "w-3 h-3 max-md:hidden" h1_ [class_ "flex min-w-0 items-center text-textStrong"] do - let targetPageM = Components.getTargetPage bcfg.pageTitle <* bcfg.pageTitleSuffix + let targetPageM = bcfg.pageTitleUrl <|> ((\p path -> "/p/" <> p.id.toText <> path) <$> bcfg.currProject <*> (Components.getTargetPage bcfg.pageTitle <* bcfg.pageTitleSuffix)) case targetPageM of - Just targetPage -> whenJust bcfg.currProject \p -> a_ ([class_ "max-w-48 truncate rounded-md p-1 py-2 text-xl font-semibold leading-none text-textStrong hover:bg-fillWeak max-md:max-w-24 max-md:text-sm", href_ $ "/p/" <> p.id.toText <> targetPage, id_ "pageTitleText"] <> navTabAttrs) $ toHtml bcfg.pageTitle + Just targetPage -> a_ ([class_ "max-w-[40ch] truncate rounded-md p-1 py-2 text-xl font-semibold leading-none text-textStrong hover:bg-fillWeak max-md:max-w-24 max-md:text-sm", href_ targetPage, id_ "pageTitleText", title_ bcfg.pageTitle] <> navTabAttrs) $ toHtml bcfg.pageTitle Nothing -> case bcfg.pageTitleModalId of - Just modalId -> label_ [class_ "max-w-48 truncate rounded-md p-1 py-2 text-xl font-semibold leading-none text-textStrong cursor-pointer hover:bg-fillWeak focus-visible:outline-2 focus-visible:outline-offset-2 max-md:max-w-24 max-md:text-sm", Lucid.for_ modalId, id_ "pageTitleText", role_ "button", tabindex_ "0", Aria.label_ $ "Rename " <> bcfg.pageTitle, Components.keyboardActivateAttr_] $ toHtml bcfg.pageTitle - Nothing -> span_ [class_ "max-w-48 truncate p-1 py-2 text-xl font-semibold leading-none text-textStrong max-md:max-w-24 max-md:text-sm", id_ "pageTitleText"] $ toHtml bcfg.pageTitle + Just modalId -> label_ [class_ "max-w-[40ch] truncate rounded-md p-1 py-2 text-xl font-semibold leading-none text-textStrong cursor-pointer hover:bg-fillWeak focus-visible:outline-2 focus-visible:outline-offset-2 max-md:max-w-24 max-md:text-sm", Lucid.for_ modalId, id_ "pageTitleText", title_ bcfg.pageTitle, role_ "button", tabindex_ "0", Aria.label_ $ "Rename " <> bcfg.pageTitle, Components.keyboardActivateAttr_] $ toHtml bcfg.pageTitle + Nothing -> span_ [class_ "max-w-[40ch] truncate p-1 py-2 text-xl font-semibold leading-none text-textStrong max-md:max-w-24 max-md:text-sm", id_ "pageTitleText", title_ bcfg.pageTitle] $ toHtml bcfg.pageTitle -- Show tab/suffix in breadcrumbs if present (with ID for htmx out-of-band updates) span_ [id_ "pageTitleSuffix", class_ "max-md:hidden flex items-center gap-1"] $ whenJust bcfg.pageTitleSuffix \suffix -> do faSprite_ "chevron-right" "regular" "w-3 h-3" diff --git a/src/Pages/CodeContext.hs b/src/Pages/CodeContext.hs index 71ac21806..e31cf1f22 100644 --- a/src/Pages/CodeContext.hs +++ b/src/Pages/CodeContext.hs @@ -12,11 +12,12 @@ module Pages.CodeContext (wikiGetH, memoryGetH, memoryPostH, MemoryForm (..), Wi import BackgroundJobs.Types qualified as Jobs import Commonmark qualified as Markdown import Commonmark.Blocks qualified as MarkdownBlocks -import Commonmark.Extensions (gfmExtensions) +import Commonmark.Extensions (HasWikilinks (..), TitlePosition (..), gfmExtensions, wikilinksSpec) import Commonmark.Tag qualified as MarkdownTag import Commonmark.TokParsers (symbol) import Data.Aeson qualified as AE import Data.Aeson.Types qualified as AET +import Data.Algorithm.Diff qualified as Diff import Data.Cache qualified as Cache import Data.Default (def) import Data.Effectful.Hasql qualified as Hasql @@ -27,6 +28,7 @@ import Data.Map.Strict qualified as Map import Data.Pool (withResource) import Data.Text qualified as T import Data.UUID qualified as UUID +import Data.Vector qualified as V import Data.Yaml qualified as Yaml import Effectful (Eff, IOE, (:>)) import Effectful.Error.Static (throwError) @@ -43,10 +45,10 @@ import Models.Projects.ProjectMembers qualified as ProjectMembers import Models.Projects.ProjectMemory qualified as Memory import Models.Projects.Projects qualified as Projects import Models.Projects.RepositorySync qualified as RepositorySync -import Network.HTTP.Types.URI (urlEncode) import OddJobs.Job (createJob) import Pages.BodyWrapper (BWConfig (..), PageCtx (..), bodyWrapper, mkPageCtx) -import Pages.Components (BadgeColor (..), FieldCfg (..), FieldSize (..), colorChip_, disclosure_, filterInputAttr_, formField_, formSelectField_, installationSettingsLink_, options_) +import Pages.Components (BadgeColor (..), FieldCfg (..), FieldSize (..), PanelCfg (..), PanelStyle (..), callout_, colorChip_, disclosure_, filterInputAttr_, formField_, formSelectField_, installationSettingsLink_, localTimeFmt_, options_, panel_, settingsH2_) +import Pkg.Components.Table qualified as Table import Pkg.DeriveUtils (UUIDId (..)) import Pkg.Git qualified as Git import Pkg.ImpactReview qualified as ImpactReview @@ -57,7 +59,8 @@ import System.Logging qualified as Log import System.Types (ATAuthCtx, RespHeaders, addErrorToast, addRespHeaders, addSuccessToast, redirectCS) import Text.HTML.SanitizeXSS (sanitizeBalance) import Text.Parsec qualified as Parsec -import Utils (LoadingSize (..), faSprite_, htmxIndicator_, nonEmptyT, renderMarkdown) +import Text.Slugify (slugify) +import Utils (LoadingSize (..), TabStrip (..), faSprite_, htmxIndicator_, navTabStrip_, nonEmptyT, renderMarkdown, toUriStr) import Web.Auth (demoGuestSessionId) import Web.FormUrlEncoded (FromForm) import Web.HttpApiData (FromHttpApiData (..)) @@ -92,7 +95,7 @@ codeContextH pid fileM lineM svcM revM = do toHtml msg whenJust fixPathM \path -> a_ - [ href_ ("/p/" <> pid.toText <> "/repositories?sample=" <> decodeUtf8 (urlEncode True $ encodeUtf8 path)) + [ href_ ("/p/" <> pid.toText <> "/repositories?sample=" <> toUriStr path) , class_ "not-italic text-textBrand underline shrink-0" ] "Choose a repository" @@ -142,43 +145,64 @@ data MemoryForm = MemoryForm {pageId :: Memory.PageId, version :: Word32, path : deriving anyclass (FromForm) -data WikiSelection = NewPage | ById Memory.PageId | ByPath Memory.PagePath +-- | @NewPage@ carries the path to prefill; @Landing@ is the wiki index. +data WikiSelection = Landing | NewPage Text | ById Memory.PageId | ByPath Memory.PagePath data WikiTree = WikiTree (Maybe Memory.Page) (Map Text WikiTree) -wikiGetH :: Projects.ProjectId -> [Text] -> Maybe Memory.PagePath -> ATAuthCtx (RespHeaders (PageCtx WikiGet)) -wikiGetH pid segments after = do +-- | Markdown rendered for the wiki, where @[[path|label]]@ links to another page. +data WikiDoc + + +instance Markdown.Rangeable (Markdown.Html WikiDoc) where + ranged _ = id + + +-- | Valid targets become @wiki:@ hrefs that the renderer resolves to the project wiki; others stay plain text. +instance {-# OVERLAPPING #-} HasWikilinks (Markdown.Html WikiDoc) where + wikilink target label = either (const label) (\path -> Markdown.addAttribute ("class", "wikilink") $ Markdown.link ("wiki:" <> Memory.pagePathText path) "" label) $ Memory.mkPagePath target + + +wikiGetH :: Projects.ProjectId -> [Text] -> Maybe Memory.PagePath -> Maybe Text -> Maybe Text -> Bool -> ATAuthCtx (RespHeaders (PageCtx WikiGet)) +wikiGetH pid segments after search folder edit = do when (any (T.any (== '/')) segments) $ throwError err404 - selection <- if null segments then pure NewPage else either (const $ throwError err404) (pure . ByPath) $ Memory.mkPagePath $ T.intercalate "/" segments - memoryPageH pid selection after Nothing + selection <- if null segments then pure $ maybe Landing (NewPage . (\f -> bool (f <> "/") "" $ T.null f) . T.dropAround (== '/')) folder else either (const $ throwError err404) (pure . ByPath) $ Memory.mkPagePath $ T.intercalate "/" segments + memoryPageH pid selection after (nonEmptyT $ T.strip <$> search) edit Nothing memoryGetH :: Projects.ProjectId -> Maybe Memory.PageId -> ATAuthCtx (RespHeaders (PageCtx WikiGet)) -memoryGetH pid page = memoryPageH pid (maybe NewPage ById page) Nothing Nothing +memoryGetH pid page = memoryPageH pid (maybe Landing ById page) Nothing Nothing False Nothing memoryPostH :: Projects.ProjectId -> MemoryForm -> ATAuthCtx (RespHeaders (PageCtx WikiGet)) memoryPostH pid form = do requireReviewWrite pid session <- Projects.getSession - case (,) <$> traverse Memory.mkPagePath form.path <*> (Memory.Document <$> Memory.mkMemoryText form.title <*> Memory.mkMemoryText form.body) of - Left message -> memoryPageH pid (ById form.pageId) Nothing (Just (form, message)) - Right (path, document) -> do - saved <- Memory.writePage pid form.pageId form.version path document $ Memory.Member session.user.id - case saved of - Left failure -> memoryPageH pid (ById form.pageId) Nothing (Just (form, case failure of Memory.StaleRevision -> "This page changed while you were editing. Your draft is below. Open the latest revision before saving again."; Memory.PathTaken -> "Another page already uses this path. Your draft is below. Choose a different path.")) + -- A blank path, or one ending in a folder, takes its page name from the title. + let named path = bool path (path <> slugify form.title) $ T.null path || "/" `T.isSuffixOf` path + case (,) <$> traverse (Memory.mkPagePath . named . T.strip) form.path <*> (Memory.Document <$> Memory.mkMemoryText form.title <*> Memory.mkMemoryText form.body) of + Left message -> redraft message + Right (path, document) -> + Memory.writePage pid form.pageId form.version path document (Memory.Member session.user.id) >>= \case + Left Memory.StaleRevision -> redraft "This page changed while you were editing. Your draft is below. Open the latest revision before saving again." + Left Memory.PathTaken -> redraft "Another page already uses this path. Your draft is below. Choose a different path." Right page -> do addSuccessToast "Wiki page saved" Nothing redirectCS $ "/p/" <> pid.toText <> "/wiki/" <> Memory.pagePathText page.path memoryGetH pid $ Just form.pageId + where + redraft message = memoryPageH pid (ById form.pageId) Nothing Nothing False (Just (form, message)) data WikiGet = WikiGet { projectId :: Projects.ProjectId , canEdit :: Bool + , editing :: Bool , pages :: [Memory.Page] + , search :: Maybe Text + , backlinks :: [Memory.Page] , history :: [Memory.Page] , form :: MemoryForm , message :: Maybe Text @@ -186,151 +210,190 @@ data WikiGet = WikiGet deriving stock (Generic, Show) -memoryPageH :: Projects.ProjectId -> WikiSelection -> Maybe Memory.PagePath -> Maybe (MemoryForm, Text) -> ATAuthCtx (RespHeaders (PageCtx WikiGet)) -memoryPageH pid selection after draft = do +memoryPageH :: Projects.ProjectId -> WikiSelection -> Maybe Memory.PagePath -> Maybe Text -> Bool -> Maybe (MemoryForm, Text) -> ATAuthCtx (RespHeaders (PageCtx WikiGet)) +memoryPageH pid selection after search editRequested draft = do (session, _, bw) <- mkPageCtx pid when (session.persistentSession.id == demoGuestSessionId) $ throwError err404 canEdit <- maybe False (>= ProjectMembers.PEdit) <$> ProjectMembers.getUserPermission pid session.user.id - selected <- case selection of - NewPage -> pure Nothing - ById page -> pure $ Just page - ByPath path -> Just <$> (maybe (throwError err404) pure =<< Memory.pageAtPath pid path) - pages <- Memory.pageWindow pid after + -- @newPath@ is the path a new page starts at; an editor following a link to a missing page gets one there. + (selected, newPath) <- case selection of + Landing -> pure (Nothing, Nothing) + NewPage path -> pure (Nothing, Just path) + ById page -> pure (Just page, Nothing) + ByPath path -> + Memory.pageAtPath pid path >>= \case + Just page -> pure (Just page, Nothing) + Nothing | canEdit -> pure (Nothing, Just $ Memory.pagePathText path) + Nothing -> throwError err404 + pages <- Memory.pageWindow pid (maybe Memory.AllPages Memory.Matching search) after history <- maybe (pure []) (Memory.pageHistory pid) selected let current = listToMaybe history when (isJust selected && isNothing current && isNothing draft) $ throwError err404 + backlinks <- maybe (pure []) (\page -> Memory.pageWindow pid (Memory.LinkingTo page.path) Nothing) current fresh <- maybe (UUIDId <$> UUIDEff.genUUID) pure selected - let edit = maybe (MemoryForm fresh 0 (Just "") "" "") (\page -> MemoryForm page.id (fromIntegral page.version) (Just $ Memory.pagePathText page.path) (Memory.memoryText page.document.title) (Memory.memoryText page.document.body)) current - addRespHeaders $ PageCtx bw{pageTitle = "Repositories"} $ WikiGet pid canEdit pages history (maybe edit fst draft) (snd <$> draft) + let edit = maybe (MemoryForm fresh 0 (newPath <|> Just "") "" "") (\page -> MemoryForm page.id (fromIntegral page.version) (Just $ Memory.pagePathText page.path) (Memory.memoryText page.document.title) (Memory.memoryText page.document.body)) current + let editing = canEdit && (editRequested || isJust draft || isJust newPath) + base = "/p/" <> pid.toText <> "/wiki" + pageLink page = base <> "/" <> Memory.pagePathText page.path + actions = div_ [class_ "flex items-center gap-2"] case (editing, current) of + (True, _) -> do + span_ [id_ "wiki-dirty", hidden_ "", class_ "text-xs text-textWeak", [__|on input from #wiki-form remove @hidden from me|]] "Unsaved changes" + for_ current \page -> a_ [href_ $ pageLink page, class_ "btn btn-ghost btn-sm", [__|on click if #wiki-dirty.hidden is false and not confirm('Discard unsaved changes?') halt the event|]] "Cancel" + button_ [type_ "submit", term "form" "wiki-form", title_ "Save (\x2318S)", class_ "btn btn-primary btn-sm"] "Save page" + (False, Just page) -> a_ (class_ "btn btn-primary btn-sm gap-1.5" : repositoryNavAttrs (pageLink page <> "?edit=true")) $ faSprite_ "pen-to-square" "regular" "h-3.5 w-3.5" >> "Edit" + (False, Nothing) -> a_ (class_ "btn btn-primary btn-sm gap-1.5" : repositoryNavAttrs (base <> "?folder=")) $ faSprite_ "plus" "regular" "h-3.5 w-3.5" >> "New page" + addRespHeaders $ PageCtx (repositoryBWConfig bw pid Wiki Nothing canEdit True){pageActions = actions <$ guard canEdit} $ WikiGet pid canEdit editing pages search backlinks history (maybe edit fst draft) (snd <$> draft) instance ToHtml WikiGet where - toHtml WikiGet{projectId = pid, canEdit, pages, history, form, message} = toHtmlRaw $ repositoryLayout_ pid Wiki Nothing canEdit True do + toHtml WikiGet{projectId = pid, canEdit, editing, pages, search, backlinks, history, form, message} = toHtmlRaw $ repositoryLayout_ Nothing do let current = listToMaybe history base = "/p/" <> pid.toText <> "/wiki" pageLink page = base <> "/" <> Memory.pagePathText page.path visible = take Memory.pageLimit pages displayed = visible <> [page | page <- maybeToList current, all ((/= page.id) . (.id)) visible] + title page = toHtml $ Memory.memoryText page.document.title authorName = \case Memory.Member _ -> "Project member"; Memory.Agent _ -> "Agent" - baseSyntax = gfmExtensions <> Markdown.defaultSyntaxSpec + edited page = span_ [class_ "tabular-nums"] do + toHtml @Text $ "Revision " <> show page.version <> " · " <> authorName page.author <> " · " + localTimeFmt_ "MMM d, yyyy HH:mm" page.updatedAt + baseSyntax = wikilinksSpec TitleAfterPipe <> gfmExtensions <> Markdown.defaultSyntaxSpec -- Embedded HTML is text; only Markdown constructs may create markup. syntax = baseSyntax - { Markdown.syntaxBlockSpecs = filter ((/= (MarkdownBlocks.rawHtmlSpec @Identity @(Markdown.Html ()) @(Markdown.Html ())).blockType) . (.blockType)) baseSyntax.syntaxBlockSpecs + { Markdown.syntaxBlockSpecs = filter ((/= (MarkdownBlocks.rawHtmlSpec @Identity @(Markdown.Html WikiDoc) @(Markdown.Html WikiDoc)).blockType) . (.blockType)) baseSyntax.syntaxBlockSpecs , Markdown.syntaxInlineParsers = (Markdown.str . Markdown.untokenize <$> Parsec.try ((:) <$> symbol '<' <*> MarkdownTag.htmlTag)) : baseSyntax.syntaxInlineParsers } - pageBody body = div_ [class_ "prose prose-sm max-w-none break-words text-sm text-textStrong [&_pre]:overflow-x-auto"] $ case runIdentity $ Markdown.commonmarkWith syntax "" body of + pageBody body = div_ [class_ "prose max-w-none break-words text-textStrong [&_pre]:overflow-x-auto"] $ case runIdentity $ Markdown.commonmarkWith syntax "" body of Left _ -> toHtml body - Right (parsed :: Markdown.Html ()) -> toHtmlRaw $ sanitizeBalance $ toStrict $ Markdown.renderHtml parsed - div_ [class_ "grid gap-6 md:grid-cols-[15rem_minmax(0,1fr)]"] do - nav_ [Aria.label_ "Wiki pages", class_ "space-y-3", term "preload" "mouseover"] do - when canEdit $ a_ (class_ "btn btn-sm btn-ghost" : repositoryNavAttrs base) "New page" - when (null pages) $ p_ [class_ "text-sm text-textWeak"] "No wiki pages yet. Record service context, investigation notes, or runbooks here." + Right (parsed :: Markdown.Html WikiDoc) -> toHtmlRaw $ sanitizeBalance $ T.replace "href=\"wiki:" ("href=\"" <> base <> "/") $ toStrict $ Markdown.renderHtml parsed + revisionLines page = ("Title: " <> Memory.memoryText page.document.title) : "" : lines (Memory.memoryText page.document.body) + revisionDiff old new = pre_ [class_ "overflow-x-auto rounded-lg bg-fillWeak py-2 text-xs leading-relaxed"] $ for_ (Diff.getGroupedDiff (revisionLines old) (revisionLines new)) \case + Diff.First removed -> diffLines "bg-fillError-weak text-textError" "- " removed + Diff.Second added -> diffLines "bg-fillSuccess-weak text-textSuccess" "+ " added + Diff.Both same _ -> diffLines "text-textWeak" " " $ if length same > 5 then take 2 same <> ["\x22EF " <> show (length same - 4) <> " unchanged lines"] <> drop (length same - 2) same else same + where + diffLines cls sigil = traverse_ \line -> span_ [class_ $ "block whitespace-pre-wrap break-words px-2 " <> cls] $ toHtml @Text $ sigil <> line + newPageIn folder = a_ ([Aria.label_ $ "New page in " <> folder, title_ "New page", class_ "btn btn-ghost btn-xs btn-square shrink-0 opacity-0 group-hover/row:opacity-100 focus-visible:opacity-100"] <> repositoryNavAttrs (base <> "?folder=" <> toUriStr folder)) $ faSprite_ "plus" "regular" "h-3 w-3" + div_ [class_ "grid min-h-full md:grid-cols-[16rem_minmax(0,1fr)]"] do + nav_ [Aria.label_ "Wiki pages", class_ "min-w-0 space-y-3 border-strokeWeak pb-6 md:sticky md:top-0 md:max-h-[calc(100dvh-8rem)] md:self-start md:overflow-y-auto md:border-r md:pr-3", term "preload" "mouseover"] do + div_ [class_ "flex items-center justify-between gap-2 ps-2"] do + span_ [class_ "text-xs font-semibold uppercase tracking-wider text-textWeak"] "Pages" + when canEdit $ a_ ([Aria.label_ "New page", title_ "New page", class_ "btn btn-ghost btn-sm btn-square"] <> repositoryNavAttrs (base <> "?folder=")) $ faSprite_ "plus" "regular" "h-3.5 w-3.5" + form_ [method_ "get", action_ base, role_ "search", class_ "relative"] do + faSprite_ "magnifying-glass" "regular" "pointer-events-none absolute start-2.5 top-1/2 z-10 h-3.5 w-3.5 -translate-y-1/2 text-iconNeutral" + input_ [type_ "search", id_ "wiki-search", name_ "q", value_ $ fromMaybe "" search, placeholder_ "Search pages", Aria.label_ "Search wiki pages", class_ "input input-sm w-full ps-8", hxGet_ base, hxTrigger_ "input changed delay:300ms, search", hxTarget_ "#repository-content", hxSelect_ "#repository-content", hxSwap_ "outerMorph", hxPushUrl_ "true"] + when (null pages) $ p_ [class_ "px-2 text-sm text-textWeak"] $ maybe "No pages yet." (\q -> toHtml $ "No pages match \x201C" <> q <> "\x201D.") search let insert page [] (WikiTree _ children) = WikiTree (Just page) children insert page (segment : rest) (WikiTree item children) = WikiTree item $ Map.alter (Just . insert page rest . fromMaybe (WikiTree Nothing mempty)) segment children tree = foldr (\page -> insert page $ T.splitOn "/" $ Memory.pagePathText page.path) (WikiTree Nothing mempty) displayed - renderTree prefix (WikiTree _ children) = ul_ [class_ "space-y-1 border-l border-strokeWeak pl-3"] $ for_ (Map.toAscList children) \(segment, branch@(WikiTree page descendants)) -> li_ do - let link item = a_ ([class_ $ "block rounded-md px-2 py-2 text-sm text-textBrand hover:bg-fillWeak break-words focus-visible:outline-2 focus-visible:outline-strokeBrand-strong" <> bool "" " bg-fillBrand-weak font-medium" (Just item.id == ((.id) <$> current)), title_ $ Memory.memoryText item.document.title] <> [term "aria-current" "page" | Just item.id == ((.id) <$> current)] <> repositoryNavAttrs (pageLink item)) $ toHtml segment + isCurrent item = Just item.id == ((.id) <$> current) + link item = a_ ([class_ $ "flex min-w-0 items-center gap-2 rounded-md px-2 py-1.5 text-sm focus-visible:outline-2 focus-visible:outline-strokeFocus " <> bool "text-textWeak hover:bg-fillWeak hover:text-textStrong" "bg-fillBrand-weak font-medium text-textStrong" (isCurrent item), title_ $ Memory.pagePathText item.path] <> [term "aria-current" "page" | isCurrent item] <> repositoryNavAttrs (pageLink item)) do + faSprite_ "file-lines" "regular" "h-3.5 w-3.5 shrink-0" + span_ [class_ "truncate"] $ title item + renderTree prefix (WikiTree _ children) = ul_ [class_ "space-y-px"] $ for_ (Map.toAscList children) \(segment, branch@(WikiTree page descendants)) -> li_ do + let folder = T.intercalate "/" (prefix <> [segment]) + holdsCurrent = maybe True (\item -> Memory.pagePathText item.path == folder || (folder <> "/") `T.isPrefixOf` Memory.pagePathText item.path) current if Map.null descendants then for_ page link - else details_ ([class_ "py-1"] <> [open_ "" | maybe False (\item -> let path = T.intercalate "/" (prefix <> [segment]) in Memory.pagePathText item.path == path || (path <> "/") `T.isPrefixOf` Memory.pagePathText item.path) current || isNothing current]) do - summary_ [class_ "cursor-pointer py-2 text-sm font-medium text-textStrong"] $ toHtml segment - for_ page link - renderTree (prefix <> [segment]) branch - renderTree [] tree + else details_ ([class_ "group/folder"] <> [open_ "" | holdsCurrent]) do + summary_ [class_ "group/row flex cursor-pointer list-none items-center gap-1 rounded-md py-1 ps-1 pe-1 text-sm text-textStrong hover:bg-fillWeak [&::-webkit-details-marker]:hidden"] do + faSprite_ "chevron-right" "regular" "h-3 w-3 shrink-0 text-iconNeutral transition-transform group-open/folder:rotate-90" + faSprite_ "folder" "regular" "h-3.5 w-3.5 shrink-0 text-iconNeutral" + span_ [class_ "min-w-0 flex-1 truncate"] $ toHtml segment + when canEdit $ newPageIn folder + div_ [class_ "ms-3 border-s border-strokeWeak ps-1"] do + for_ page link + renderTree (prefix <> [segment]) branch + case search of + Nothing -> renderTree [] tree + Just _ -> ul_ [class_ "space-y-px"] $ for_ visible \page -> li_ $ a_ (class_ "block rounded-md px-2 py-1.5 hover:bg-fillWeak" : repositoryNavAttrs (pageLink page)) do + span_ [class_ "block truncate text-sm text-textStrong"] $ title page + span_ [class_ "block truncate font-mono text-xs text-textWeak"] $ toHtml $ Memory.pagePathText page.path when (length pages > Memory.pageLimit) $ for_ (viaNonEmpty last visible) \page -> - a_ (class_ "block py-2 text-sm text-textBrand hover:underline" : repositoryNavAttrs (base <> "?after=" <> decodeUtf8 (urlEncode True $ encodeUtf8 $ Memory.pagePathText page.path))) "More pages" - section_ [class_ "min-w-0 space-y-5"] do - h2_ [class_ "text-lg font-semibold text-textStrong"] $ toHtml $ maybe "New wiki page" (Memory.memoryText . (.document.title)) current - for_ current \page -> nav_ [Aria.label_ "Wiki breadcrumb", class_ "flex flex-wrap gap-1 text-xs text-textWeak"] do - a_ (class_ "text-textBrand hover:underline" : repositoryNavAttrs base) "Wiki" - for_ (T.splitOn "/" $ Memory.pagePathText page.path) \segment -> do - span_ [Aria.hidden_ "true"] "/" - span_ [class_ "break-all"] $ toHtml segment - p_ [class_ "text-sm text-textWeak"] "Shared project notes and runbooks. Check dated conclusions against current source and telemetry." - for_ current \page -> do - p_ [class_ "text-xs text-textWeak"] $ toHtml @Text $ authorName page.author <> " · Revision " <> show page.version <> " · " <> show page.updatedAt - pageBody $ Memory.memoryText page.document.body - when canEdit $ details_ ([class_ "border-t border-strokeWeak pt-4"] <> [open_ "" | isNothing current || isJust message]) do - summary_ [class_ "cursor-pointer text-sm font-medium text-textStrong"] $ if isNothing current then "Write a page" else "Edit this page" - form_ [method_ "post", action_ ("/p/" <> pid.toText <> "/memories"), hxPost_ ("/p/" <> pid.toText <> "/memories"), hxTarget_ "#repository-content", hxSelect_ "#repository-content", hxSwap_ "outerHTML", class_ "mt-4 space-y-4"] do - input_ [type_ "hidden", name_ "pageId", value_ form.pageId.toText] - input_ [type_ "hidden", name_ "version", value_ $ show form.version] - for_ message $ p_ [id_ "memory-error", role_ "alert", class_ "text-sm text-textError"] . toHtml - label_ [term "for" "memory-path", class_ "block space-y-1 text-sm font-medium text-textStrong"] do - span_ "Page path (required)" - input_ ([id_ "memory-path", name_ "path", required_ "", maxlength_ "512", placeholder_ "runbooks/payments/retries", value_ $ fromMaybe "" form.path, class_ "input input-bordered w-full"] <> [Aria.describedby_ "memory-error" | isJust message]) - label_ [term "for" "memory-title", class_ "block space-y-1 text-sm font-medium text-textStrong"] do - span_ "Title (required)" - input_ ([id_ "memory-title", name_ "title", required_ "", maxlength_ "120", value_ form.title, class_ "input input-bordered w-full"] <> [Aria.describedby_ "memory-error" | isJust message]) - term "wiki-editor" [class_ "block", term "data-mode" "source"] do - div_ [hidden_ "", term "data-editor-controls" "", class_ "mb-3 space-y-2 text-sm text-textStrong"] do - label_ do - "Editing mode " - select_ [term "data-editor-mode" "", class_ "select select-bordered select-sm"] do - option_ [value_ "rich"] "Rich text" - option_ [value_ "source"] "Markdown source" - div_ [term "data-editor-formatting" "", class_ "flex flex-wrap gap-1", role_ "group", Aria.label_ "Text formatting"] - $ for_ - ( [ ("Bold", "ToggleStrong", Nothing) - , ("Italic", "ToggleEmphasis", Nothing) - , ("Inline code", "ToggleInlineCode", Nothing) - , ("Paragraph", "TurnIntoText", Nothing) - , ("Heading 1", "WrapInHeading", Just "1") - , ("Heading 2", "WrapInHeading", Just "2") - , ("Bullet list", "WrapInBulletList", Nothing) - , ("Numbered list", "WrapInOrderedList", Nothing) - , ("Quote", "WrapInBlockquote", Nothing) - , ("Code block", "CreateCodeBlock", Nothing) - , ("Undo", "Undo", Nothing) - , ("Redo", "Redo", Nothing) - ] - :: [(Text, Text, Maybe Text)] - ) - \(label, command, parameter) -> - button_ ([type_ "button", term "data-editor-command" command, class_ "btn btn-sm btn-ghost focus-visible:outline-2 focus-visible:outline-offset-2"] <> maybe [] (pure . term "data-editor-parameter") parameter) $ toHtml label - label_ [term "for" "memory-body", class_ "block space-y-1 text-sm font-medium text-textStrong"] do - span_ [id_ "memory-body-label"] "Page content (required)" - textarea_ ([id_ "memory-body", name_ "body", required_ "", maxlength_ "16000", rows_ "12", class_ "textarea textarea-bordered w-full text-sm font-normal"] <> [Aria.describedby_ "memory-error" | isJust message]) $ toHtml form.body - div_ [term "data-rich-editor" "", hidden_ "", class_ "mt-2 rounded-md border border-strokeWeak"] pass - p_ [term "data-editor-status" "", role_ "status", class_ "mt-2 text-xs text-textWeak"] "Content is saved as Markdown." - button_ [type_ "submit", class_ "btn btn-sm btn-primary"] "Save page" - unless (null history) $ details_ [class_ "border-t border-strokeWeak pt-4"] do - summary_ [class_ "cursor-pointer text-sm font-medium text-textStrong"] "Revision history" - when (length history == Memory.pageLimit) $ p_ [class_ "mt-3 text-sm text-textWeak"] $ toHtml @Text $ "Showing the " <> show Memory.pageLimit <> " most recent revisions. Older revisions remain stored." - div_ [class_ "mt-3 divide-y divide-strokeWeak"] $ for_ history \page -> details_ [class_ "py-3"] do - summary_ [class_ "cursor-pointer text-sm text-textWeak"] $ toHtml @Text $ "Revision " <> show page.version <> " · " <> authorName page.author <> " · " <> show page.updatedAt - h3_ [class_ "mt-3 text-sm font-semibold text-textStrong"] $ toHtml $ Memory.memoryText page.document.title - div_ [class_ "mt-2"] $ pageBody $ Memory.memoryText page.document.body + a_ (class_ "block px-2 py-1.5 text-sm text-textBrand hover:underline" : repositoryNavAttrs (base <> "?after=" <> toUriStr (Memory.pagePathText page.path) <> foldMap (("&q=" <>) . toUriStr) search)) "More pages" + article_ [class_ "min-w-0 pb-16 md:px-10"] do + header_ [class_ "sticky top-0 z-10 flex min-h-12 flex-wrap items-center gap-x-3 gap-y-1 border-b border-strokeWeak bg-bgBase py-2"] do + nav_ [Aria.label_ "Wiki breadcrumb", class_ "flex min-w-0 flex-1 items-center gap-1 text-sm text-textWeak"] do + a_ (class_ "hover:text-textStrong" : repositoryNavAttrs base) "Wiki" + for_ (maybe (bool [] ["New page"] editing) (T.splitOn "/" . Memory.pagePathText . (.path)) current) \segment -> do + faSprite_ "chevron-right" "regular" "h-2.5 w-2.5 shrink-0" + span_ [class_ "truncate last:text-textStrong"] $ toHtml segment + unless editing $ for_ current $ p_ [class_ "text-xs text-textWeak"] . edited + div_ [class_ "mx-auto max-w-3xl"] do + unless editing $ case current of + Just page -> div_ [class_ "space-y-6 pt-8"] do + h2_ [class_ "text-3xl font-bold tracking-tight text-balance text-textStrong"] $ title page + pageBody $ Memory.memoryText page.document.body + Nothing -> div_ [class_ "space-y-4 pt-16"] do + h2_ [class_ "text-2xl font-semibold tracking-tight text-textStrong"] "Project wiki" + p_ [class_ "max-w-prose text-sm text-textWeak"] "Shared notes and runbooks for this project. Check dated conclusions against current source and telemetry." + unless (null pages) $ section_ [Aria.labelledby_ "wiki-recent", class_ "space-y-1 pt-4"] do + h3_ [id_ "wiki-recent", class_ "text-xs font-semibold uppercase tracking-wider text-textWeak"] "Recently updated" + ul_ [class_ "divide-y divide-strokeWeak"] $ for_ (take 8 $ sortOn (Down . (.updatedAt)) visible) \page -> li_ $ a_ (class_ "flex items-baseline justify-between gap-4 py-2 hover:text-textBrand" : repositoryNavAttrs (pageLink page)) do + span_ [class_ "truncate text-sm text-textStrong"] $ title page + span_ [class_ "shrink-0 text-xs text-textWeak tabular-nums"] $ localTimeFmt_ "MMM d, HH:mm" page.updatedAt + when editing $ div_ [class_ "pt-8"] do + when (isNothing current) $ h2_ [class_ "sr-only"] "New page" + form_ [id_ "wiki-form", method_ "post", action_ ("/p/" <> pid.toText <> "/memories"), hxPost_ ("/p/" <> pid.toText <> "/memories"), hxTarget_ "#repository-content", hxSelect_ "#repository-content", hxSwap_ "outerHTML", class_ "space-y-3", [__|on keydown[(metaKey or ctrlKey) and key is 's'] from window halt the event then call me.requestSubmit()|]] do + input_ [type_ "hidden", name_ "pageId", value_ form.pageId.toText] + input_ [type_ "hidden", name_ "version", value_ $ show form.version] + for_ message $ p_ [id_ "memory-error", role_ "alert", class_ "rounded-lg bg-fillError-weak px-3 py-2 text-sm text-textError"] . toHtml + term "wiki-editor" [class_ "block space-y-3", term "data-mode" "source"] do + input_ ([id_ "memory-title", name_ "title", required_ "", maxlength_ "120", value_ form.title, placeholder_ "Untitled", Aria.label_ "Title", class_ "w-full rounded-md bg-transparent text-3xl font-bold tracking-tight text-textStrong placeholder:text-textWeak focus-visible:outline-none"] <> [Aria.describedby_ "memory-error" | isJust message]) + div_ [class_ "flex items-center gap-1.5 text-xs text-textWeak"] do + faSprite_ "folder" "regular" "h-3 w-3 shrink-0" + input_ ([id_ "memory-path", name_ "path", maxlength_ "512", placeholder_ "folder/page \x2014 blank uses the title", value_ $ fromMaybe "" form.path, Aria.label_ "Page path", class_ "min-w-0 flex-1 rounded bg-transparent px-1 py-0.5 font-mono text-xs text-textWeak placeholder:text-textWeak hover:bg-fillWeak focus-visible:bg-fillWeak focus-visible:outline-2 focus-visible:outline-strokeFocus"] <> [Aria.describedby_ "memory-error" | isJust message]) + div_ [hidden_ "", term "data-editor-controls" ""] + $ select_ [term "data-editor-mode" "", Aria.label_ "Editing mode", class_ "select select-ghost select-xs w-auto text-textWeak"] do + option_ [value_ "rich"] "Rich text" + option_ [value_ "source"] "Markdown" + label_ [term "for" "memory-body", id_ "memory-body-label", class_ "sr-only"] "Page content" + textarea_ ([id_ "memory-body", name_ "body", required_ "", maxlength_ "16000", rows_ "18", class_ "textarea w-full font-mono text-sm leading-relaxed"] <> [Aria.describedby_ "memory-error" | isJust message]) $ toHtml form.body + div_ [term "data-rich-editor" "", hidden_ "", class_ "-ms-12"] pass + p_ [term "data-editor-status" "", role_ "status", class_ "text-xs text-textWeak"] "Markdown \x00B7 / for blocks \x00B7 [[path]] or [[path|label]] links a page \x00B7 \x2318S saves" + unless (null backlinks) $ section_ [Aria.labelledby_ "wiki-backlinks", class_ "mt-12 space-y-2 border-t border-strokeWeak pt-4"] do + h3_ [id_ "wiki-backlinks", class_ "flex items-center gap-1.5 text-xs font-semibold uppercase tracking-wider text-textWeak"] $ faSprite_ "link" "regular" "h-3 w-3" >> "Linked from" + ul_ [class_ "flex flex-wrap gap-2"] $ for_ backlinks \page -> li_ $ a_ (class_ "inline-flex items-center gap-1.5 rounded-md bg-fillWeak px-2 py-1 text-sm text-textStrong hover:text-textBrand" : repositoryNavAttrs (pageLink page)) $ faSprite_ "file-lines" "regular" "h-3 w-3" >> title page + unless (null history) $ details_ [class_ "mt-6 border-t border-strokeWeak pt-4"] do + summary_ [class_ "flex cursor-pointer items-center gap-1.5 text-xs font-semibold uppercase tracking-wider text-textWeak hover:text-textStrong"] $ faSprite_ "clock-rotate-left" "regular" "h-3 w-3" >> "Revision history" + when (length history == Memory.pageLimit) $ p_ [class_ "mt-3 text-sm text-textWeak"] $ toHtml @Text $ "Showing the " <> show Memory.pageLimit <> " most recent revisions. Older revisions remain stored." + div_ [class_ "mt-3 divide-y divide-strokeWeak"] $ for_ (zip history $ map Just (drop 1 history) <> [Nothing]) \(page, previous) -> details_ [class_ "py-3"] do + summary_ [class_ "cursor-pointer text-sm text-textWeak"] $ edited page + for_ previous \old -> div_ [class_ "mt-3 space-y-1"] do + p_ [class_ "text-xs font-medium text-textWeak"] $ toHtml @Text $ "Changes from revision " <> show old.version + revisionDiff old page + h3_ [class_ "mt-3 text-sm font-semibold text-textStrong"] $ title page + div_ [class_ "mt-2"] $ pageBody $ Memory.memoryText page.document.body toHtmlRaw = toHtml -repositoryLayout_ :: Projects.ProjectId -> RepositoryTab -> Maybe Text -> Bool -> Bool -> Html () -> Html () -repositoryLayout_ pid tab serviceM canEdit canReadWiki content = +repositoryBWConfig :: BWConfig -> Projects.ProjectId -> RepositoryTab -> Maybe Text -> Bool -> Bool -> BWConfig +repositoryBWConfig bw pid tab serviceM canEdit canReadWiki = let base = "/p/" <> pid.toText <> "/repositories" - in div_ [class_ "h-full w-full overflow-y-auto"] do - section_ [class_ "mx-auto max-w-6xl space-y-6 px-4 py-6 sm:px-8 sm:py-8"] do - header_ [class_ "flex flex-col items-start gap-4 sm:flex-row sm:justify-between"] do - div_ [class_ "min-w-0 w-full flex-1 space-y-1"] do - h1_ [class_ "text-xl sm:text-2xl font-semibold tracking-tight text-textStrong break-words"] $ toHtml $ maybe "Repositories" ("Repositories for " <>) serviceM - p_ [class_ "text-sm text-textWeak max-w-2xl"] $ toHtml @Text $ maybe "Manage source context, pull request reviews, and configuration sync for each repository." (const "Source mappings that apply to this service, including mappings for all services.") serviceM - when (isJust serviceM) $ a_ [href_ base, class_ "inline-flex items-center gap-1 py-1 text-sm text-textBrand hover:underline"] "All repositories" - when canEdit $ a_ [href_ (base <> "/connect"), class_ "btn btn-sm btn-ghost gap-2"] do - faSprite_ "plus" "regular" "h-3.5 w-3.5" - "Add repositories" - when (isNothing serviceM) - $ nav_ [id_ "repository-nav", Aria.label_ "Repository views", class_ "flex flex-wrap gap-1 border-b border-strokeWeak pb-2", term "preload" "mouseover"] - $ forM_ ([(Overview, "Repositories", ""), (PullRequests, "Pull requests", "?tab=reviews"), (Wiki, "Project wiki", "?tab=wiki")] :: [(RepositoryTab, Text, Text)]) \(value, label, query) -> - when (value /= Wiki || canReadWiki) - $ a_ - ( [class_ $ "rounded-lg px-3 py-2 text-sm font-medium transition-colors " <> bool "text-textWeak hover:bg-fillWeak hover:text-textStrong" "bg-fillBrand-weak text-textBrand" (tab == value)] - <> repositoryNavAttrs (if value == Wiki then "/p/" <> pid.toText <> "/wiki" else base <> query) - <> [term "aria-current" "page" | tab == value] - ) - $ toHtml @Text label - section_ [id_ "repository-content", class_ "min-w-0"] content + in bw + { pageTitle = "Repositories" + , menuItem = Just "Repositories" + , pageTitleSuffix = serviceM + , pageActions = + a_ [href_ (base <> "/connect"), class_ "btn btn-sm btn-primary gap-2"] (faSprite_ "plus" "regular" "h-3.5 w-3.5" >> "Add repositories") <$ guard canEdit + , navTabs = + Just + $ navTabStrip_ + NavLinks + "Repository views" + "" + [(toHtml label, url, tab == value) | (value, label, url) <- [(Overview, "Repositories" :: Text, base), (PullRequests, "Pull requests", base <> "?tab=reviews"), (Wiki, "Project wiki", "/p/" <> pid.toText <> "/wiki")], value /= Wiki || canReadWiki] + } + + +repositoryLayout_ :: Maybe Text -> Html () -> Html () +repositoryLayout_ serviceM content = + div_ [class_ "h-full w-full overflow-y-auto"] do + when (isJust serviceM) $ p_ [class_ "px-4 pt-4 text-sm text-textWeak"] "Source mappings that apply to this service, including mappings for all services." + section_ [id_ "repository-content", class_ "min-w-0 p-4"] content repositoryNavAttrs :: Text -> [Attribute] @@ -339,7 +402,7 @@ repositoryNavAttrs url = , hxGet_ url , hxTarget_ "#repository-content" , hxSelect_ "#repository-content" - , term "hx-select-oob" "#repository-nav:outerMorph" + , term "hx-select-oob" "#main-navbar:outerMorph" , hxSwap_ "outerMorph" , hxPushUrl_ "true" , [__|on click set my.preloadState to 'DONE'|] @@ -384,84 +447,139 @@ repositoriesPageH pid selection = do settings <- ImpactReviews.repositorySettings pid credentials <- GitSync.getGitHubCredentials pid repositories <- GitSync.getRepositories pid - conflicts <- Hasql.interp @[HI.OneColumn GitSync.GitHubSyncId] [HI.sql| SELECT DISTINCT sync_id FROM projects.repository_resources WHERE project_id = #{pid} AND conflicted |] + conflicts <- map HI.getOneColumn <$> Hasql.interp @[HI.OneColumn GitSync.GitHubSyncId] [HI.sql| SELECT DISTINCT sync_id FROM projects.repository_resources WHERE project_id = #{pid} AND conflicted |] let applicable = filter (\m -> maybe True (\service -> isNothing m.service || m.service == Just service) serviceM) mappings visible = filter (\repository -> isNothing serviceM || any (mappingInRepository credentials repository) applicable) repositories - pure $ overview_ canEdit serviceM sampleM base applicable syncs settings credentials visible [sid | HI.OneColumn sid <- conflicts] + pure do + let linked = [((c.host, c.apiBase, m.owner, m.repo), m) | m <- applicable, c <- credentials, c.id == m.credentialId] + repositoryKey repository = (repository.host, repository.apiBase, repository.owner, repository.repo) + servicesFor repository = sort . ordNub $ mapMaybe (\(key, m) -> guard (key == repositoryKey repository) *> m.service) linked + repositoryUrl repository = base <> "/" <> repository.id.toText <> foldMap (("/source?sample=" <>) . toUriStr) sampleM + toHtml + $ Table.Table + { Table.config = def{Table.elemID = "repositoriesTable", Table.renderAsTable = True} + , Table.columns = + [ Table.col + "Repository" + ( \repository -> div_ [class_ "min-w-0 space-y-1"] do + a_ [href_ $ repositoryUrl repository, class_ "font-medium text-textStrong hover:text-textBrand hover:underline break-all"] $ toHtml (repository.owner <> "/" <> repository.repo) + p_ [class_ "text-xs text-textWeak break-all"] $ toHtml $ fromMaybe (Git.hostLabel repository.host) repository.apiBase + ) + , Table.col "Services" (\repository -> span_ [class_ "text-xs text-textWeak break-words"] $ toHtml $ if any (\(key, m) -> key == repositoryKey repository && isNothing m.service) linked then "All services" else case servicesFor repository of [] -> "No services linked"; services -> T.intercalate ", " services) + , Table.col + "Source context" + ( \repository -> + if repository.sourceEnabled && any ((== repositoryKey repository) . fst) linked + then colorChip_ SuccessBadge "circle-check" "Active" + else colorChip_ NeutralBadge "circle-info" $ if repository.sourceEnabled then "Needs setup" else "Off" + ) + , Table.col + "Production impact reviews" + ( \repository -> case find (\s -> repository.host == Git.GitHub && isNothing repository.apiBase && s.owner == T.toLower repository.owner && s.repo == T.toLower repository.repo) settings of + Just s | s.enabled && not (null $ servicesFor repository) -> colorChip_ SuccessBadge "circle-check" "Enabled" + Just s | s.enabled -> colorChip_ WarningBadge "circle-info" "Link a service" + Just _ -> colorChip_ NeutralBadge "circle-info" "Off" + Nothing -> colorChip_ NeutralBadge "circle-info" "Not configured" + ) + , Table.col + "Configuration sync" + ( \repository -> case find (\s -> (s.host, s.apiBase, s.owner, s.repo) == repositoryKey repository) syncs of + Just s | s.id `elem` conflicts -> colorChip_ WarningBadge "circle-exclamation" "Conflicts need input" + Just s | s.exportPaused -> colorChip_ WarningBadge "circle-info" "Export paused" + Just s | isJust s.lastExportHash -> colorChip_ WarningBadge "code-branch" "Changes pending" + Just s | Just err <- s.lastError -> colorChip_ ErrorBadge "circle-exclamation" "Sync failed" >> p_ [class_ "text-xs text-textError break-words"] (toHtml err.message) + Just s | not s.syncEnabled -> colorChip_ NeutralBadge "circle-info" "Paused" + Just s | isJust s.announcedRevision -> colorChip_ WarningBadge "circle-info" "Changes pending" + Just s | isJust s.lastRevision -> colorChip_ SuccessBadge "circle-check" "Synced" + Just _ -> colorChip_ NeutralBadge "circle-info" "Awaiting first sync" + Nothing -> colorChip_ NeutralBadge "circle-info" "Not configured" + ) + , Table.col "" (const $ span_ [Aria.hidden_ "true", class_ "flex justify-end text-iconNeutral"] $ faSprite_ "chevron-right" "regular" "h-3.5 w-3.5") + ] + , Table.rows = V.fromList visible + , Table.features = + def + { Table.search = Just Table.ClientSide + , Table.searchPlaceholder = Just "Search repositories" + , Table.rowLink = Just repositoryUrl + , Table.zeroState = + Just + Table.ZeroState + { Table.icon = "code-branch" + , Table.title = maybe "Connect the repositories behind your services" (const "No repositories linked to this service") serviceM + , Table.description = if canEdit then maybe "Link services to their code for source context and production impact reviews. You can also connect repositories that only contain dashboards." (const "Choose a repository, then link this service in Configure source context.") serviceM else "Ask a project editor to link services to their source repositories." + , Table.action = Table.ESCustom $ when canEdit $ a_ [href_ (base <> maybe "/connect" (const "") serviceM), class_ "btn btn-sm btn-primary"] $ toHtml @Text $ maybe "Connect repositories" (const "Choose a repository") serviceM + } + } + } ReviewsPage -> do cfg <- (.config) <$> Effectful.Reader.Static.ask @AuthContext runs <- ImpactReviews.latestRuns pid - pure $ reviewHistory_ canEdit cfg runs - addRespHeaders $ bodyWrapper bw{pageTitle = "Repositories"} $ repositoryLayout_ pid tab serviceM canEdit canReadWiki content - where - overview_ :: Bool -> Maybe Text -> Maybe Text -> Text -> [CodeContext.CodeMapping] -> [GitSync.GitHubSync] -> [ImpactReviews.ReviewSettings] -> [GitSync.GitHubCredential] -> [GitSync.Repository] -> [GitSync.GitHubSyncId] -> Html () - overview_ canEdit serviceM sampleM base mappings syncs settings credentials repositories conflicts = do - let linked = [((c.host, c.apiBase, m.owner, m.repo), m) | m <- mappings, c <- credentials, c.id == m.credentialId] - if null repositories - then div_ [class_ "rounded-xl border border-strokeWeak p-6 sm:p-8 space-y-3"] do - h2_ [class_ "font-semibold text-textStrong"] $ toHtml @Text $ maybe "Connect the repositories behind your services" (const "No repositories linked to this service") serviceM - p_ [class_ "text-sm text-textWeak max-w-xl"] - $ toHtml @Text - $ if canEdit - then maybe "Link services to their code for source context and production impact reviews. You can also connect repositories that only contain dashboards." (const "Choose a repository, then link this service in Configure source context.") serviceM - else "Ask a project editor to link services to their source repositories." - when canEdit $ a_ [href_ (base <> maybe "/connect" (const "") serviceM), class_ "btn btn-sm btn-primary"] $ toHtml @Text $ maybe "Connect repositories" (const "Choose a repository") serviceM - else div_ [class_ "divide-y divide-strokeWeak rounded-xl border border-strokeWeak"] $ forM_ repositories \repository -> do - let host = repository.host - origin = repository.apiBase - owner = repository.owner - repo = repository.repo - key = (host, origin, owner, repo) - services = sort . ordNub $ mapMaybe (\(repoKey, m) -> guard (repoKey == key) *> m.service) linked - reviewM = find (\s -> host == Git.GitHub && isNothing origin && s.owner == T.toLower owner && s.repo == T.toLower repo) settings - sync = find (\s -> (s.host, s.apiBase, s.owner, s.repo) == key) syncs - article_ [class_ "grid gap-4 p-4 sm:p-5 lg:grid-cols-[minmax(0,2fr)_repeat(3,minmax(0,1fr))]"] do - div_ [class_ "min-w-0 space-y-2"] do - a_ [href_ (base <> "/" <> repository.id.toText <> foldMap (\sample -> "/source?sample=" <> decodeUtf8 (urlEncode True $ encodeUtf8 sample)) sampleM), class_ "font-medium text-sm text-textBrand break-all hover:underline"] $ toHtml (owner <> "/" <> repo) - p_ [class_ "text-xs text-textWeak break-all"] $ toHtml $ fromMaybe (Git.hostLabel host) origin - p_ [class_ "text-xs text-textWeak break-words"] $ toHtml $ if any (\(repoKey, m) -> repoKey == key && isNothing m.service) linked then "All services" else if null services then "No services linked" else T.intercalate ", " services + pure $ div_ [class_ "space-y-4"] do + p_ [class_ "text-sm text-textWeak max-w-2xl"] "Pull request reviews connect code changes to production telemetry. Configure reviews and evidence sharing in each repository." + toHtml + $ Table.Table + { Table.config = def{Table.elemID = "pullRequestsTable", Table.renderAsTable = True} + , Table.columns = + [ Table.col "Repository" (\run -> span_ [class_ "font-medium text-textStrong break-all"] $ toHtml (run.owner <> "/" <> run.repo)) + , Table.col + "Pull request" + ( \run -> a_ [href_ $ "https://github.com/" <> run.owner <> "/" <> run.repo <> "/pull/" <> show run.number, target_ "_blank", rel_ "noopener noreferrer", class_ "inline-flex items-center gap-2 text-textBrand hover:underline whitespace-nowrap tabular-nums", Aria.label_ $ "Open pull request #" <> show run.number <> " in " <> run.owner <> "/" <> run.repo] do + toHtml @Text $ "#" <> show run.number + faSprite_ "arrow-up-right-from-square" "regular" "h-3 w-3" + ) + , Table.col + "Status" + ( \run -> case run.state of + ImpactReviews.Superseded -> span_ [class_ "inline-flex items-center gap-1.5 text-xs text-textWeak"] $ faSprite_ "clock-rotate-left" "regular" "h-3 w-3" >> "Superseded" + ImpactReviews.Completed -> colorChip_ SuccessBadge "circle-check" "Completed" + ImpactReviews.Incomplete -> colorChip_ WarningBadge "circle-exclamation" "Incomplete" + ImpactReviews.Queued -> colorChip_ NeutralBadge "clock" "Queued" + ImpactReviews.Reviewing -> colorChip_ BrandBadge "arrows-rotate" "Reviewing" + ) + , Table.col "Revision" (\run -> code_ [class_ "text-xs text-textWeak", title_ run.revision] $ toHtml $ T.take 8 run.revision) + , Table.col "Reviewed" (\run -> span_ [class_ "whitespace-nowrap text-xs text-textWeak tabular-nums"] $ localTimeFmt_ "MMM d, HH:mm" run.createdAt) + , Table.col "" (\run -> button_ [type_ "button", class_ "btn btn-sm btn-ghost btn-square -me-2", onclick_ $ "document.getElementById('review-" <> run.id.toText <> "').showModal()", Aria.label_ $ "View review for " <> run.owner <> "/" <> run.repo <> " #" <> show run.number] $ faSprite_ "chevron-right" "regular" "h-3.5 w-3.5") + ] + , Table.rows = V.fromList runs + , Table.features = + def + { Table.search = Just Table.ClientSide + , Table.searchPlaceholder = Just "Search pull requests" + , Table.rowAttrs = Just \run -> [class_ "cursor-pointer", data_ "review" ("review-" <> run.id.toText), [__|on click if not event.target.closest('a, button') call document.getElementById(@data-review).showModal() end|]] + , Table.zeroState = + Just + Table.ZeroState + { Table.icon = "code-branch" + , Table.title = "No pull requests reviewed yet" + , Table.description = "Link a GitHub repository and its services to review pull requests with production telemetry." + , Table.action = Table.ESCustom $ a_ [href_ $ "/p/" <> pid.toText <> "/repositories", class_ "btn btn-sm btn-primary"] "Configure repositories" + } + } + } + forM_ runs \run -> term "dialog" [id_ $ "review-" <> run.id.toText, Aria.labelledby_ $ "review-title-" <> run.id.toText, class_ "modal overscroll-contain"] do + div_ [class_ "modal-box w-full max-w-4xl space-y-5 p-6"] do div_ [class_ "space-y-2"] do - p_ [class_ "text-xs font-medium text-textWeak"] "Source context" - if repository.sourceEnabled && any ((== key) . fst) linked - then colorChip_ SuccessBadge "circle-check" "Active" - else colorChip_ NeutralBadge "circle-info" $ if repository.sourceEnabled then "Needs setup" else "Off" - div_ [class_ "space-y-2"] do - p_ [class_ "text-xs font-medium text-textWeak"] "Production impact reviews" - case reviewM of - Just s | s.enabled && not (null services) -> colorChip_ SuccessBadge "circle-check" "Enabled" - Just s | s.enabled -> colorChip_ WarningBadge "circle-info" "Link a service" - Just _ -> colorChip_ NeutralBadge "circle-info" "Off" - Nothing -> colorChip_ NeutralBadge "circle-info" "Not configured" - div_ [class_ "space-y-2"] do - p_ [class_ "text-xs font-medium text-textWeak"] "Configuration sync" - case sync of - Just s | s.id `elem` conflicts -> colorChip_ WarningBadge "circle-exclamation" "Conflicts need input" - Just s | s.exportPaused -> colorChip_ WarningBadge "circle-info" "Export paused" - Just s | isJust s.lastExportHash -> colorChip_ WarningBadge "code-branch" "Changes pending" - Just s | Just err <- s.lastError -> colorChip_ ErrorBadge "circle-exclamation" "Sync failed" >> p_ [class_ "text-xs text-textError break-words"] (toHtml err.message) - Just s | not s.syncEnabled -> colorChip_ NeutralBadge "circle-info" "Paused" - Just s | isJust s.announcedRevision -> colorChip_ WarningBadge "circle-info" "Changes pending" - Just s | isJust s.lastRevision -> colorChip_ SuccessBadge "circle-check" "Synced" - Just _ -> colorChip_ NeutralBadge "circle-info" "Awaiting first sync" - Nothing -> colorChip_ NeutralBadge "circle-info" "Not configured" - - reviewHistory_ :: Bool -> EnvConfig -> [ImpactReviews.ReviewRun] -> Html () - reviewHistory_ canEdit cfg runs = div_ [class_ "space-y-4"] do - h2_ [class_ "text-base font-semibold text-textStrong"] "Production impact reviews" - p_ [class_ "text-sm text-textWeak max-w-2xl"] "Advisory pull request reviews connect code changes to this project's production telemetry. Open a repository to configure reviews and evidence sharing." - when (null runs) $ div_ [class_ "rounded-xl border border-strokeWeak p-5 space-y-2"] do - p_ [class_ "text-sm font-medium text-textStrong"] "No pull requests reviewed yet" - p_ [class_ "text-sm text-textWeak"] "Link a GitHub repository and its services to receive reviews when ready pull requests are opened or updated." - forM_ runs \run -> details_ [class_ "rounded-lg border border-strokeWeak p-4"] do - summary_ [class_ "cursor-pointer flex flex-wrap items-center gap-2 text-sm text-textStrong"] do - span_ [class_ "font-medium break-all"] $ toHtml (run.owner <> "/" <> run.repo <> " #" <> show run.number) - colorChip_ (case run.state of ImpactReviews.Completed -> SuccessBadge; ImpactReviews.Incomplete -> WarningBadge; ImpactReviews.Queued -> NeutralBadge; ImpactReviews.Reviewing -> BrandBadge; ImpactReviews.Superseded -> NeutralBadge) "code-branch" (show run.state) - code_ [class_ "text-xs text-textWeak"] $ toHtml $ T.take 8 run.revision - whenJust run.error $ p_ [class_ "mt-2 text-sm text-textError break-words"] . toHtml - whenJust run.result \value -> case AE.fromJSON value of - AE.Error _ -> p_ [class_ "mt-2 text-sm text-textWeak"] "The saved review could not be displayed. Rerun the review." - AE.Success result -> div_ [class_ "prose prose-sm mt-3 max-w-none"] $ renderMarkdown (ImpactReview.renderReview cfg.hostUrl run True result) - when (canEdit && run.revision == run.latestRevision && run.state /= ImpactReviews.Reviewing) $ button_ [class_ "btn btn-sm btn-ghost mt-3", hxPost_ ("/p/" <> pid.toText <> "/settings/pr-reviews/" <> run.id.toText <> "/rerun"), hxTarget_ "#repository-content", hxSelect_ "#repository-content", hxSwap_ "outerMorph"] "Rerun review" + h2_ [id_ $ "review-title-" <> run.id.toText, class_ "text-lg font-semibold text-textStrong break-words"] $ toHtml (run.owner <> "/" <> run.repo <> " #" <> show run.number) + div_ [class_ "flex flex-wrap items-center gap-3 text-xs text-textWeak"] do + toHtml @Text $ "Review " <> show run.state + code_ [title_ run.revision] $ toHtml $ T.take 8 run.revision + whenJust run.error $ p_ [class_ "text-sm text-textError break-words"] . toHtml + case run.result of + Nothing -> p_ [class_ "text-sm text-textWeak"] $ toHtml @Text case run.state of + ImpactReviews.Queued -> "This review is queued." + ImpactReviews.Reviewing -> "This review is in progress." + ImpactReviews.Superseded -> "A newer revision replaced this review." + ImpactReviews.Completed -> "No review result is available." + ImpactReviews.Incomplete -> "No review result is available." + Just value -> case AE.fromJSON value of + AE.Error _ -> p_ [class_ "text-sm text-textWeak"] "The saved review could not be displayed. Rerun the review." + AE.Success result -> div_ [class_ "prose prose-sm max-w-none break-words [&_pre]:overflow-x-auto"] $ renderMarkdown (ImpactReview.renderReview cfg.hostUrl run True result) + div_ [class_ "flex flex-wrap justify-end gap-2 border-t border-strokeWeak pt-4"] do + form_ [method_ "dialog"] $ button_ [class_ "btn btn-sm btn-ghost", autofocus_] "Close" + when (canEdit && run.revision == run.latestRevision && run.state /= ImpactReviews.Reviewing) $ button_ [type_ "button", class_ "btn btn-sm btn-primary", hxPost_ ("/p/" <> pid.toText <> "/settings/pr-reviews/" <> run.id.toText <> "/rerun"), hxTarget_ "#repository-content", hxSelect_ "#repository-content", hxSwap_ "outerMorph", [__|on click call (closest ).close()|]] "Rerun review" + form_ [method_ "dialog", class_ "modal-backdrop"] $ button_ [Aria.label_ "Close review"] "Close" + addRespHeaders $ bodyWrapper (repositoryBWConfig bw pid tab serviceM canEdit canReadWiki) $ repositoryLayout_ serviceM content data ReviewReadiness @@ -512,7 +630,7 @@ repositoryGetH pid rid = do conflictVersions <- forM (filter (.conflicted) resources) $ \resource -> (resource.id,) <$> RepositorySync.localDefinition resource folderCandidates <- RepositorySync.folderCandidates pid analysis <- GitSync.getRepositoryAnalysis pid rid - addRespHeaders $ PageCtx bw{pageTitle = repository.owner <> "/" <> repository.repo} RepositoryGet{repository, mappings, dashboardSync, reviewReadiness, reviewSettings, resources, conflictVersions, folderCandidates, analysis, permission} + addRespHeaders $ PageCtx bw{prePageTitle = Just "Repositories", pageTitle = repository.owner <> "/" <> repository.repo, menuItem = Just "Repositories"} RepositoryGet{repository, mappings, dashboardSync, reviewReadiness, reviewSettings, resources, conflictVersions, folderCandidates, analysis, permission} newtype ConflictForm = ConflictForm {useGit :: Bool} @@ -627,94 +745,108 @@ repositoryDeleteH pid rid = do instance ToHtml RepositoryGet where - toHtml page = section_ [id_ "repository-detail", class_ "mx-auto max-w-4xl space-y-8 px-4 py-6 sm:px-8 sm:py-8"] do + toHtml page = section_ [id_ "repository-detail", class_ "@container/repository w-full min-w-0 space-y-5 p-4 sm:p-6"] do let repository = page.repository base = "/p/" <> repository.projectId.toText <> "/repositories" + self = base <> "/" <> repository.id.toText canEdit = maybe False (>= ProjectMembers.PEdit) page.permission - a_ [href_ base, class_ "inline-flex items-center gap-2 text-sm text-textBrand hover:underline"] do - faSprite_ "arrow-left" "regular" "h-3 w-3" - "All repositories" - header_ [class_ "space-y-2"] do - h1_ [class_ "text-xl font-semibold text-textStrong break-all"] $ toHtml $ repository.owner <> "/" <> repository.repo - p_ [class_ "text-sm text-textWeak break-all"] $ toHtml $ fromMaybe (Git.hostLabel repository.host) repository.apiBase + post path attrs = form_ ([method_ "post", action_ (self <> path), hxPost_ (self <> path), hxTarget_ "#repository-detail", hxSelect_ "#repository-detail", hxSwap_ "outerMorph"] <> attrs) + syncLink = a_ [href_ (self <> "/dashboards"), class_ "btn btn-sm btn-outline"] $ if canEdit then "Configure sync" else "View sync" + header_ [class_ "flex flex-wrap items-center gap-x-6 gap-y-3"] do + div_ [class_ "min-w-0 space-y-2 break-words"] do + settingsH2_ $ repository.owner <> "/" <> repository.repo + p_ [class_ "text-sm text-textWeak break-all"] $ toHtml $ fromMaybe (Git.hostLabel repository.host) repository.apiBase + when canEdit $ post "/analyze" [] $ button_ [type_ "submit", class_ "btn btn-sm btn-outline gap-2"] do + faSprite_ "arrows-rotate" "regular" "h-3.5 w-3.5" + "Analyze repository" + when canEdit $ p_ [class_ "w-full max-w-[65ch] text-xs text-textWeak"] "Analysis matches this repository to services in your telemetry. The first run can link those services and turn on dashboard sync; existing settings are kept." whenJust (page.analysis >>= (.error)) $ \err -> p_ [role_ "status", class_ "text-sm text-textError"] $ toHtml $ "Setup needs attention: " <> err whenJust (page.analysis >>= (.suggestions)) $ \suggestions -> when (null page.mappings) $ div_ [class_ "rounded-xl border border-strokeWeak p-4 space-y-2"] do p_ [class_ "text-sm font-medium text-textStrong"] "Service mapping needs input" p_ [class_ "text-sm text-textWeak break-words"] $ toHtml $ if null suggestions.services then "No service names have been observed yet. Link a service when its telemetry arrives." else "Observed services: " <> T.intercalate ", " (take 12 suggestions.services) - when canEdit $ form_ [method_ "post", action_ (base <> "/" <> repository.id.toText <> "/analyze"), hxPost_ (base <> "/" <> repository.id.toText <> "/analyze"), hxTarget_ "#repository-detail", hxSelect_ "#repository-detail", hxSwap_ "outerMorph"] $ button_ [type_ "submit", class_ "btn btn-sm btn-ghost"] "Analyze repository" - section_ [class_ "space-y-3"] do - h2_ [class_ "text-base font-semibold text-textStrong"] "Services and source context" - colorChip_ NeutralBadge "circle-info" $ if repository.sourceEnabled then "Source context enabled" else "Source context disabled" - when canEdit $ form_ [method_ "post", action_ (base <> "/" <> repository.id.toText <> "/source/enabled"), hxPost_ (base <> "/" <> repository.id.toText <> "/source/enabled"), hxTarget_ "#repository-detail", hxSelect_ "#repository-detail", hxSwap_ "outerMorph"] do - input_ [type_ "hidden", name_ "enabled", value_ (if repository.sourceEnabled then "false" else "true")] - button_ [type_ "submit", class_ "btn btn-sm btn-ghost"] $ if repository.sourceEnabled then "Disable source context" else "Enable source context" - - if null page.mappings - then p_ [class_ "text-sm text-textWeak"] "No source paths are linked. Link a service to read the failing code directly from its stack trace." - else div_ [class_ "divide-y divide-strokeWeak rounded-xl border border-strokeWeak"] $ forM_ page.mappings \mapping -> div_ [class_ "p-4 space-y-2"] do - p_ [class_ "text-sm font-medium text-textStrong break-words"] $ toHtml $ fromMaybe "All services" mapping.service - p_ [class_ "text-xs text-textWeak break-all"] $ toHtml $ scopeLabel mapping - code_ [class_ "text-xs text-textWeak break-all"] $ toHtml mapping.ref - a_ [href_ (base <> "/" <> repository.id.toText <> "/source"), class_ "btn btn-sm btn-ghost"] $ if canEdit then "Configure source context" else "View source context" - section_ [class_ "space-y-3"] do - h2_ [class_ "text-base font-semibold text-textStrong"] "Production impact reviews" - case page.reviewReadiness of - ReviewReady settings -> do - colorChip_ SuccessBadge "circle-check" "Ready for pull requests" - p_ [class_ "text-sm text-textWeak"] $ if settings.includeEvidence then "Reviews share production aggregates and links in GitHub." else "Reviews share links to production evidence in GitHub." - ReviewDisabled -> colorChip_ NeutralBadge "circle-info" "Reviews disabled" - ReviewNeedsService -> p_ [class_ "text-sm text-textWeak"] "Link a named service so reviews can find the production telemetry for this repository." - ReviewNeedsApp -> p_ [class_ "text-sm text-textWeak"] "Link source context through the GitHub App to receive automatic pull request reviews. A token connection can still provide source context and configuration sync." - ReviewNeedsServer -> p_ [class_ "text-sm text-textWeak"] "An administrator must configure the GitHub App and webhook before automatic reviews can run." - ReviewUnsupportedHost -> p_ [class_ "text-sm text-textWeak"] "Automatic pull request reviews currently support GitHub.com. Source context and configuration sync remain available for this host." - when (canEdit && repository.host == Git.GitHub && isNothing repository.apiBase) $ form_ [method_ "post", action_ (base <> "/" <> repository.id.toText <> "/source/reviews"), hxPost_ (base <> "/" <> repository.id.toText <> "/source/reviews"), hxTarget_ "#repository-detail", hxSelect_ "#repository-detail", hxSwap_ "outerMorph", class_ "flex flex-wrap items-end gap-3"] do - input_ [type_ "hidden", name_ "owner", value_ repository.owner] - input_ [type_ "hidden", name_ "repo", value_ repository.repo] - label_ [class_ "space-y-1 text-sm text-textWeak"] do - span_ [class_ "block"] "PR reviews" - select_ [name_ "enabled", class_ "select select-sm"] $ forM_ ([(True, "Enabled"), (False, "Disabled")] :: [(Bool, Text)]) \(value, label) -> option_ ([value_ (if value then "true" else "false")] <> [selected_ "selected" | value == maybe False (.enabled) page.reviewSettings]) $ toHtml @Text label - label_ [class_ "space-y-1 text-sm text-textWeak"] do - span_ [class_ "block"] "Production evidence in GitHub" - select_ [name_ "includeEvidence", class_ "select select-sm"] $ forM_ ([(False, "Links only"), (True, "Aggregates and links")] :: [(Bool, Text)]) \(value, label) -> option_ ([value_ (if value then "true" else "false")] <> [selected_ "selected" | value == maybe False (.includeEvidence) page.reviewSettings]) $ toHtml @Text label - button_ [type_ "submit", class_ "btn btn-sm btn-primary"] "Save review settings" - div_ [class_ "flex flex-wrap gap-2"] do - a_ [href_ (base <> "?tab=reviews"), class_ "btn btn-sm btn-ghost"] "Review history" - section_ [class_ "space-y-3"] do - h2_ [class_ "text-base font-semibold text-textStrong"] "Dashboards and monitors" - case page.dashboardSync of - Nothing -> p_ [class_ "text-sm text-textWeak"] "Configuration sync is not configured. This repository remains connected for your team." - Just sync -> do - whenJust sync.lastError $ p_ [role_ "status", class_ "text-sm text-textError break-words"] . toHtml . (.message) - p_ [class_ "text-sm text-textWeak break-all"] $ toHtml $ sync.branch <> " · " <> GitSync.getDashboardsPath sync - colorChip_ NeutralBadge "code-branch" $ if not sync.syncEnabled then "Disabled" else if sync.exportPaused then "Export paused" else if any (.conflicted) page.resources then "Conflicts need input" else if isJust sync.lastExportHash then "Changes proposed" else if isJust sync.lastRevision then "Synced" else "Preparing folder" - whenJust sync.pullRequestNumber $ \number -> a_ [href_ ("https://github.com/" <> sync.owner <> "/" <> sync.repo <> "/pull/" <> show number), target_ "_blank", rel_ "noopener noreferrer", class_ "text-sm text-textBrand hover:underline"] $ toHtml $ "Configuration PR #" <> show @Text number - p_ [class_ "text-sm text-textWeak"] "Monoscope edits are active immediately. Git changes apply after merge into the target branch. Dashboards and monitor definitions share this folder." - when (canEdit && sync.exportPaused) $ form_ [method_ "post", action_ (base <> "/" <> repository.id.toText <> "/resume"), hxPost_ (base <> "/" <> repository.id.toText <> "/resume"), hxTarget_ "#repository-detail", hxSelect_ "#repository-detail", hxSwap_ "outerMorph"] $ button_ [type_ "submit", class_ "btn btn-sm btn-primary"] "Resume export" - unless (null page.resources) $ ul_ [class_ "divide-y divide-strokeWeak rounded-xl border border-strokeWeak"] $ forM_ page.resources \resource -> li_ [class_ "flex flex-wrap items-center justify-between gap-3 p-3"] do - code_ [class_ "text-xs text-textStrong break-all"] $ toHtml resource.filePath - when resource.conflicted do - span_ [class_ "text-sm text-textWarning"] "Both versions changed" - details_ [class_ "w-full min-w-0 space-y-3"] do - summary_ [class_ "cursor-pointer text-sm text-textBrand"] "Compare versions" - div_ [class_ "grid min-w-0 gap-4 md:grid-cols-2"] $ for_ ([("Active in Monoscope", Yaml.encode . AE.toJSON <$> join (lookup resource.id page.conflictVersions)), ("Merged Git version", Yaml.encode <$> resource.remoteDefinition)] :: [(Text, Maybe ByteString)]) \(label, version) -> div_ [class_ "min-w-0 space-y-2"] do - h3_ [class_ "text-sm font-medium text-textStrong"] $ toHtml label - pre_ [class_ "max-h-80 overflow-auto rounded-lg bg-fillWeak p-3 text-xs text-textWeak"] $ toHtml @Text $ maybe "Deleted" decodeUtf8 version - when canEdit $ form_ [method_ "post", action_ (base <> "/" <> repository.id.toText <> "/resources/" <> resource.id.toText <> "/conflict"), hxPost_ (base <> "/" <> repository.id.toText <> "/resources/" <> resource.id.toText <> "/conflict"), hxTarget_ "#repository-detail", hxSelect_ "#repository-detail", hxSwap_ "outerMorph", class_ "flex gap-2"] do - button_ [type_ "submit", name_ "useGit", value_ "false", class_ "btn btn-sm btn-ghost"] "Keep Monoscope" - button_ [type_ "submit", name_ "useGit", value_ "true", class_ "btn btn-sm btn-ghost"] "Use Git" - when canEdit $ details_ [class_ "space-y-3"] do - summary_ [class_ "cursor-pointer text-sm text-textBrand"] "Move existing resources into this folder" - for_ ([RepositorySync.Dashboard, RepositorySync.Query, RepositorySync.Uptime, RepositorySync.Cron] :: [RepositorySync.ResourceKind]) \kind -> do - let candidates = filter ((== kind) . (.kind)) page.folderCandidates - unless (null candidates) $ form_ [method_ "post", action_ (base <> "/" <> repository.id.toText <> "/folder"), hxPost_ (base <> "/" <> repository.id.toText <> "/folder"), hxTarget_ "#repository-detail", hxSelect_ "#repository-detail", hxSwap_ "outerMorph", class_ "flex flex-wrap items-end gap-2"] do - input_ [type_ "hidden", name_ "kind", value_ $ T.toLower $ show kind] - formSelectField_ FieldSm (show kind) "localId" True $ for_ candidates \candidate -> option_ [value_ $ show candidate.localId] $ toHtml candidate.title - button_ [type_ "submit", class_ "btn btn-sm btn-ghost"] "Move into folder" - a_ [href_ (base <> "/" <> repository.id.toText <> "/dashboards"), class_ "btn btn-sm btn-ghost"] $ if canEdit then "Configure sync" else "View sync" - when canEdit $ section_ [class_ "space-y-3 border-t border-strokeWeak pt-6"] do - h2_ [class_ "text-base font-semibold text-textStrong"] "Remove connection" - p_ [class_ "max-w-2xl text-sm text-textWeak"] "Stop using this repository for source context, pull request reviews, and configuration sync. Dashboards and monitors stay local and review history is retained. Shared repository accounts remain connected." - button_ [type_ "button", onclick_ "document.getElementById('remove-repository-dialog').showModal()", class_ "btn btn-sm btn-ghost text-textError hover:bg-fillError-weak"] "Remove repository" + div_ [class_ "grid min-w-0 items-start gap-5 @min-[64rem]/repository:grid-cols-2"] do + section_ [class_ "min-w-0 @min-[64rem]/repository:col-start-1 @min-[64rem]/repository:row-start-1", Aria.label_ "Services and source context"] + $ panel_ Raised def{icon = Just "code-branch"} "Services and source context" + $ div_ [class_ "space-y-4"] do + bool (colorChip_ NeutralBadge "circle-info" "Disabled") (colorChip_ SuccessBadge "circle-check" "Enabled") repository.sourceEnabled + if null page.mappings + then p_ [class_ "text-sm text-textWeak"] "No source paths are linked. Link a service to read the failing code directly from its stack trace." + else div_ [class_ "divide-y divide-strokeWeak rounded-lg bg-fillWeak"] $ forM_ page.mappings \mapping -> div_ [class_ "flex flex-wrap items-start justify-between gap-3 p-3"] do + div_ [class_ "min-w-0 space-y-1"] do + p_ [class_ "text-sm font-medium text-textStrong break-words"] $ toHtml $ fromMaybe "All services" mapping.service + p_ [class_ "text-xs text-textWeak break-all"] $ toHtml $ scopeLabel mapping + code_ [class_ "rounded bg-bgBase px-2 py-1 text-xs text-textWeak break-all"] $ toHtml mapping.ref + div_ [class_ "flex flex-wrap items-center gap-2"] do + a_ [href_ (self <> "/source"), class_ "btn btn-sm btn-outline"] $ if canEdit then "Configure source context" else "View source context" + when canEdit $ post "/source/enabled" [] do + input_ [type_ "hidden", name_ "enabled", value_ (if repository.sourceEnabled then "false" else "true")] + button_ [type_ "submit", class_ "btn btn-sm btn-ghost"] $ if repository.sourceEnabled then "Disable source context" else "Enable source context" + section_ [class_ "min-w-0 @min-[64rem]/repository:col-start-2 @min-[64rem]/repository:row-start-1 @min-[64rem]/repository:row-span-2", Aria.label_ "Production impact reviews"] + $ panel_ Raised def{icon = Just "code-pull-request"} "Production impact reviews" + $ div_ [class_ "space-y-4"] do + let setupRequired = (,True) . callout_ WarningBadge (Just "Setup required") + (readiness, blocked) = case page.reviewReadiness of + ReviewReady settings -> (,False) do + colorChip_ SuccessBadge "circle-check" "Ready for pull requests" + p_ [class_ "text-sm text-textWeak"] $ if settings.includeEvidence then "Reviews share production aggregates and links in GitHub." else "Reviews share links to production evidence in GitHub." + ReviewDisabled -> (colorChip_ NeutralBadge "circle-info" "Reviews disabled", False) + ReviewNeedsService -> setupRequired "Link a named service so reviews can find the production telemetry for this repository." + ReviewNeedsApp -> setupRequired "Link source context through the GitHub App to receive automatic pull request reviews. A token connection can still provide source context and configuration sync." + ReviewNeedsServer -> setupRequired "An administrator must configure the GitHub App and webhook before automatic reviews can run." + ReviewUnsupportedHost -> (callout_ NeutralBadge (Just "Unavailable") "Automatic pull request reviews currently support GitHub.com. Source context and configuration sync remain available for this host.", True) + readiness + when (canEdit && repository.host == Git.GitHub && isNothing repository.apiBase) $ post "/source/reviews" [class_ "flex flex-wrap items-end gap-3"] do + input_ [type_ "hidden", name_ "owner", value_ repository.owner] + input_ [type_ "hidden", name_ "repo", value_ repository.repo] + formSelectField_ FieldSm "Automatic pull request reviews" "enabled" False + $ options_ (Just $ bool "false" "true" $ maybe False (.enabled) page.reviewSettings) [("true", "On"), ("false", "Off")] + formSelectField_ FieldSm "Production evidence in GitHub" "includeEvidence" False + $ options_ (Just $ bool "false" "true" $ maybe False (.includeEvidence) page.reviewSettings) [("false", "Links only"), ("true", "Aggregates and links")] + button_ [type_ "submit", class_ $ "btn btn-sm mb-1 " <> bool "btn-primary" "btn-outline" blocked] "Save review settings" + when blocked $ p_ [class_ "w-full text-xs text-textWeak"] "Saved settings take effect once setup is complete." + a_ [href_ (base <> "?tab=reviews"), class_ "btn btn-sm btn-outline"] "Review history" + section_ [class_ "min-w-0 @min-[64rem]/repository:col-start-1 @min-[64rem]/repository:row-start-2", Aria.label_ "Dashboards and monitors"] + $ panel_ Raised def{icon = Just "dashboard"} "Dashboards and monitors" + $ div_ [class_ "space-y-4"] do + case page.dashboardSync of + Nothing -> div_ [class_ "space-y-3"] do + p_ [class_ "text-sm text-textWeak"] "Keep dashboards and monitors as files in this repository. Monoscope proposes changes as pull requests, and merged changes apply automatically." + syncLink + Just sync -> do + whenJust sync.lastError $ p_ [role_ "status", class_ "text-sm text-textError break-words"] . toHtml . (.message) + p_ [class_ "text-sm text-textWeak break-all"] $ toHtml $ sync.branch <> " · " <> GitSync.getDashboardsPath sync + colorChip_ NeutralBadge "code-branch" $ if not sync.syncEnabled then "Disabled" else if sync.exportPaused then "Export paused" else if any (.conflicted) page.resources then "Conflicts need input" else if isJust sync.lastExportHash then "Changes proposed" else if isJust sync.lastRevision then "Synced" else "Preparing folder" + whenJust sync.pullRequestNumber $ \number -> a_ [href_ ("https://github.com/" <> sync.owner <> "/" <> sync.repo <> "/pull/" <> show number), target_ "_blank", rel_ "noopener noreferrer", class_ "text-sm text-textBrand hover:underline"] $ toHtml $ "Configuration PR #" <> show @Text number + p_ [class_ "text-sm text-textWeak"] "Monoscope edits are active immediately. Git changes apply after merge into the target branch. Dashboards and monitor definitions share this folder." + syncLink + when (canEdit && sync.exportPaused) $ post "/resume" [] $ button_ [type_ "submit", class_ "btn btn-sm btn-primary"] "Resume export" + when canEdit $ details_ [class_ "space-y-3"] do + summary_ [class_ "cursor-pointer text-sm text-textBrand"] "Move existing resources into this folder" + for_ ([RepositorySync.Dashboard, RepositorySync.Query, RepositorySync.Uptime, RepositorySync.Cron] :: [RepositorySync.ResourceKind]) \kind -> do + let candidates = filter ((== kind) . (.kind)) page.folderCandidates + unless (null candidates) $ post "/folder" [class_ "flex flex-wrap items-end gap-2"] do + input_ [type_ "hidden", name_ "kind", value_ $ T.toLower $ show kind] + formSelectField_ FieldSm (show kind) "localId" True $ for_ candidates \candidate -> option_ [value_ $ show candidate.localId] $ toHtml candidate.title + button_ [type_ "submit", class_ "btn btn-sm btn-ghost"] "Move into folder" + unless (null page.resources) + $ panel_ Raised def{icon = Just "dashboard"} "Synced resources" + $ ul_ [class_ "divide-y divide-strokeWeak"] + $ forM_ page.resources \resource -> li_ [class_ "flex flex-wrap items-center justify-between gap-3 p-3"] do + code_ [class_ "text-xs text-textStrong break-all"] $ toHtml resource.filePath + when resource.conflicted do + span_ [class_ "text-sm text-textWarning"] "Both versions changed" + details_ [class_ "w-full min-w-0 space-y-3"] do + summary_ [class_ "cursor-pointer text-sm text-textBrand"] "Compare versions" + div_ [class_ "grid min-w-0 gap-4 md:grid-cols-2"] $ for_ ([("Active in Monoscope", Yaml.encode . AE.toJSON <$> join (lookup resource.id page.conflictVersions)), ("Merged Git version", Yaml.encode <$> resource.remoteDefinition)] :: [(Text, Maybe ByteString)]) \(label, version) -> div_ [class_ "min-w-0 space-y-2"] do + h3_ [class_ "text-sm font-medium text-textStrong"] $ toHtml label + pre_ [class_ "max-h-80 overflow-auto rounded-lg bg-fillWeak p-3 text-xs text-textWeak"] $ toHtml @Text $ maybe "Deleted" decodeUtf8 version + when canEdit $ post ("/resources/" <> resource.id.toText <> "/conflict") [class_ "flex gap-2"] do + button_ [type_ "submit", name_ "useGit", value_ "false", class_ "btn btn-sm btn-ghost"] "Keep Monoscope" + button_ [type_ "submit", name_ "useGit", value_ "true", class_ "btn btn-sm btn-ghost"] "Use Git" + when canEdit $ panel_ Raised def{icon = Just "link-slash"} "Remove connection" $ do + div_ [class_ "space-y-3"] do + p_ [class_ "max-w-[65ch] text-sm leading-relaxed text-textWeak"] "Stop using this repository for source context, pull request reviews, and configuration sync. Dashboards and monitors stay local and review history is retained. Shared repository accounts remain connected." + button_ [type_ "button", onclick_ "document.getElementById('remove-repository-dialog').showModal()", class_ "btn btn-sm btn-outline text-textError hover:bg-fillError-weak"] "Remove repository" term "dialog" [id_ "remove-repository-dialog", Aria.labelledby_ "remove-repository-title", Aria.describedby_ "remove-repository-description", class_ "modal overscroll-contain"] do div_ [class_ "modal-box space-y-4 p-6"] do h2_ [id_ "remove-repository-title", class_ "text-lg font-semibold text-textStrong break-all"] $ toHtml $ "Remove " <> repository.owner <> "/" <> repository.repo <> "?" @@ -722,7 +854,7 @@ instance ToHtml RepositoryGet where div_ [id_ "remove-repository-feedback"] "" div_ [class_ "flex flex-wrap justify-end gap-2"] do form_ [method_ "dialog"] $ button_ [class_ "btn btn-sm btn-ghost", autofocus_] "Cancel" - button_ [type_ "button", hxDelete_ (base <> "/" <> repository.id.toText), hxTarget_ "#remove-repository-feedback", hxSwap_ "innerHTML", term "hx-disable" "this", hxIndicator_ "#remove-repository-indicator", class_ "btn btn-sm bg-fillError-strong text-textInverse-strong hover:opacity-90 gap-2"] do + button_ [type_ "button", hxDelete_ self, hxTarget_ "#remove-repository-feedback", hxSwap_ "innerHTML", term "hx-disable" "this", hxIndicator_ "#remove-repository-indicator", class_ "btn btn-sm bg-fillError-strong text-textInverse-strong hover:opacity-90 gap-2"] do "Remove repository" htmxIndicator_ "remove-repository-indicator" LdXS form_ [method_ "dialog", class_ "modal-backdrop"] $ button_ [Aria.label_ "Cancel removal"] "Close" @@ -741,8 +873,7 @@ repositorySourceGetH pid rid cid sample = do (_, _, bw) <- mkPageCtx pid repository <- GitSync.getRepository pid rid >>= maybe (throwError err404) pure content <- codeMappingsContent pid sample cid (Just repository) - addRespHeaders $ bodyWrapper bw{pageTitle = "Source context"} $ section_ [class_ "mx-auto max-w-4xl space-y-6 px-4 py-6 sm:px-8 sm:py-8"] do - a_ [href_ ("/p/" <> pid.toText <> "/repositories/" <> rid.toText), class_ "text-sm text-textBrand hover:underline"] $ toHtml $ repository.owner <> "/" <> repository.repo + addRespHeaders $ bodyWrapper bw{prePageTitle = Just "Repositories", pageTitle = repository.owner <> "/" <> repository.repo, pageTitleUrl = Just $ "/p/" <> pid.toText <> "/repositories/" <> rid.toText, pageTitleSuffix = Just "Source context", menuItem = Just "Repositories"} $ section_ [class_ "w-full min-w-0 space-y-6 p-4 sm:p-6"] do header_ [class_ "space-y-2"] do h1_ [class_ "text-xl font-semibold text-textStrong"] "Source context" p_ [class_ "text-sm text-textWeak max-w-2xl"] "Link this repository to the services it builds. Stack traces and pull request reviews use these mappings to find the right code and production telemetry." @@ -821,7 +952,9 @@ codeMappingsContent pid sampleM credentialM repositoryM = do authConfig <- (.config) <$> Effectful.Reader.Static.ask @AuthContext pure $ div_ [class_ "space-y-6"] do unless canEdit $ p_ [class_ "text-sm text-textWeak"] "A project editor can configure source context and pull request reviews." - unless (null mappings) $ div_ [class_ "divide-y divide-strokeWeak rounded-xl border border-strokeWeak"] $ forM_ mappings (mappingRow_ canEdit) + unless (null mappings) $ section_ [class_ "space-y-3 rounded-xl border border-strokeWeak p-4 sm:p-5"] do + h2_ [class_ "text-base font-semibold text-textStrong"] "Linked services" + div_ [class_ "divide-y divide-strokeWeak rounded-lg bg-fillWeak"] $ forM_ mappings (mappingRow_ canEdit) when (canEdit && not (null accounts) && isNothing repositoryM) $ form_ ( [ action_ editorUrl @@ -919,7 +1052,7 @@ codeMappingsContent pid sampleM credentialM repositoryM = do addMappingForm_ :: [Git.GitRepo] -> GitSync.GitHubCredential -> Html () addMappingForm_ repos credential = form_ - ( [ class_ "pt-4 space-y-3 border-t border-strokeWeak" + ( [ class_ "space-y-4 rounded-xl border border-strokeWeak bg-bgBase p-4 sm:p-5" , hxPost_ postUrl , hxTarget_ "#code-mappings-content" , hxIndicator_ "#code-mapping-indicator" @@ -927,8 +1060,9 @@ codeMappingsContent pid sampleM credentialM repositoryM = do <> scopedSwap ) $ do + h2_ [class_ "text-base font-semibold text-textStrong"] "Link a service" input_ [type_ "hidden", name_ "credentialId", value_ credential.id.toText] - div_ [class_ "grid grid-cols-1 gap-3 md:grid-cols-3"] do + div_ [class_ "grid grid-cols-1 gap-4 sm:grid-cols-2"] do -- Each option carries its own default branch, so the Branch field below can fill -- itself in and a repo whose trunk is not called "main" needs no correction. case repositoryM of @@ -1027,7 +1161,7 @@ repositoryConnectPage projectId cid = do selectedAccount <- codeContextCredential projectId cid repositories <- maybe (pure $ Right []) (credentialRepos Nothing) selectedAccount let credential = find (\account -> Just account.id == ((.id) <$> selectedAccount)) accounts - pure $ PageCtx bw{pageTitle = "Connect repositories"} RepositoryConnectGet{projectId, accounts, credential, repositories, selected = [], connectionError = Nothing} + pure $ PageCtx bw{prePageTitle = Just "Repositories", pageTitle = "Connect repositories", menuItem = Just "Repositories"} RepositoryConnectGet{projectId, accounts, credential, repositories, selected = [], connectionError = Nothing} repositoryConnectPostH :: Projects.ProjectId -> Maybe GitSync.GitHubCredentialId -> RepositoryConnectForm -> ATAuthCtx (RespHeaders (PageCtx RepositoryConnectGet)) @@ -1056,14 +1190,13 @@ repositoryConnectPostH pid cid form = do instance ToHtml RepositoryConnectGet where - toHtml page = section_ [class_ "mx-auto max-w-4xl space-y-6 px-4 py-6 sm:px-8 sm:py-8"] do + toHtml page = section_ [class_ "w-full min-w-0 space-y-6 p-4 sm:p-6"] do let base = "/p/" <> page.projectId.toText <> "/repositories" connectionUrl = base <> "/connect" <> foldMap (\c -> "?credentialId=" <> c.id.toText) page.credential - a_ [href_ base, class_ "text-sm text-textBrand hover:underline"] "All repositories" header_ [class_ "space-y-2"] do h1_ [class_ "text-xl font-semibold text-textStrong"] "Connect repositories" p_ [class_ "text-sm text-textWeak max-w-2xl"] "Choose repositories to add. Monoscope analyzes their services and enables source context, PR reviews, and dashboard and monitor sync where setup is clear. This can post reviews and open configuration PRs. You can disable each capability at any time." - div_ [id_ "repository-connect-content", class_ "space-y-5"] do + div_ [id_ "repository-connect-content", class_ "space-y-5 rounded-xl border border-strokeWeak bg-bgBase p-4 sm:p-5"] do unless (null page.accounts) $ form_ [action_ (base <> "/connect"), method_ "get", hxGet_ (base <> "/connect"), hxTrigger_ "change", hxPushUrl_ "true", hxTarget_ "#repository-connect-content", hxSelect_ "#repository-connect-content", hxSwap_ "outerMorph", hxIndicator_ "#repository-account-indicator", class_ "space-y-2"] do @@ -1093,8 +1226,8 @@ instance ToHtml RepositoryConnectGet where "Connect selected repositories" htmxIndicator_ "repository-connect-indicator" LdXS whenJust account.installationId $ installationSettingsLink_ . GitSync.installationSettingsUrl - a_ [href_ ("/p/" <> page.projectId.toText <> "/settings/git-sync/install?to=code"), class_ "btn btn-sm btn-ghost"] "Connect GitHub account" - p_ [class_ "text-xs text-textWeak"] do + a_ [href_ ("/p/" <> page.projectId.toText <> "/settings/git-sync/install?to=code"), class_ "btn btn-sm btn-outline"] "Connect GitHub account" + p_ [class_ "border-t border-strokeWeak pt-4 text-xs text-textWeak"] do "Using another Git host or a repository token? " a_ [href_ (base <> "/connect/token"), class_ "text-textBrand underline underline-offset-2"] "Connect with a token" toHtmlRaw = toHtml @@ -1125,7 +1258,7 @@ repositoryTokenPage :: Projects.ProjectId -> ATAuthCtx (PageCtx RepositoryTokenG repositoryTokenPage pid = do requireReviewWrite pid (_, _, bw) <- mkPageCtx pid - pure $ PageCtx bw{pageTitle = "Connect with a token"} $ RepositoryTokenGet pid Git.GitHub Nothing "" Nothing + pure $ PageCtx bw{prePageTitle = Just "Repositories", pageTitle = "Connect repositories", pageTitleUrl = Just $ "/p/" <> pid.toText <> "/repositories/connect", pageTitleSuffix = Just "Token", menuItem = Just "Repositories"} $ RepositoryTokenGet pid Git.GitHub Nothing "" Nothing repositoryTokenGetH :: Projects.ProjectId -> ATAuthCtx (RespHeaders (PageCtx RepositoryTokenGet)) @@ -1171,13 +1304,12 @@ repositoryTokenPostH pid form = do instance ToHtml RepositoryTokenGet where - toHtml page = section_ [class_ "mx-auto max-w-2xl space-y-6 px-4 py-6 sm:px-8 sm:py-8"] do + toHtml page = section_ [class_ "w-full min-w-0 space-y-6 p-4 sm:p-6"] do let base = "/p/" <> page.projectId.toText <> "/repositories/connect" - a_ [href_ base, class_ "text-sm text-textBrand hover:underline"] "Back to repository connections" header_ [class_ "space-y-2"] do h1_ [class_ "text-xl font-semibold text-textStrong"] "Connect with a token" p_ [class_ "text-sm text-textWeak"] "Monoscope analyzes this repository and configures source context and configuration sync where supported. Automatic PR reviews require the GitHub App. You can disable each capability later." - div_ [id_ "repository-token-content", class_ "space-y-4"] do + div_ [id_ "repository-token-content", class_ "space-y-4 rounded-xl border border-strokeWeak bg-bgBase p-4 sm:p-5"] do whenJust page.connectionError $ p_ [role_ "alert", class_ "text-sm text-textError break-words"] . toHtml form_ [action_ (base <> "/token"), method_ "post", hxPost_ (base <> "/token"), hxTarget_ "#repository-token-content", hxSelect_ "#repository-token-content", hxSwap_ "outerMorph", hxIndicator_ "#repository-token-indicator", class_ "space-y-4"] do formSelectField_ FieldSm "Git host" "host" True $ forM_ (universe @Git.GitHost) \host -> @@ -1186,7 +1318,7 @@ instance ToHtml RepositoryTokenGet where formField_ FieldSm def{value = page.repoFullName, placeholder = "team/checkout"} "Full repository name" "repoFullName" True Nothing formField_ FieldSm def{inputType = "password", extraAttrs = [autocomplete_ "new-password"]} "Access token" "accessToken" True Nothing p_ [class_ "text-xs text-textWeak"] "The token needs read access to this repository. Dashboard sync will also need write access if you enable it later." - details_ [class_ "space-y-3"] do + details_ [class_ "space-y-3 rounded-lg bg-fillWeak p-3"] do summary_ [class_ "cursor-pointer text-sm text-textWeak"] "Replacing an existing connection?" label_ [class_ "flex items-start gap-3 text-sm text-textStrong"] do input_ [type_ "checkbox", name_ "replaceToken", value_ "true", class_ "checkbox checkbox-sm shrink-0"] diff --git a/src/Pages/Components.hs b/src/Pages/Components.hs index fd3204785..f1ce118f7 100644 --- a/src/Pages/Components.hs +++ b/src/Pages/Components.hs @@ -1,4 +1,4 @@ -module Pages.Components (drawer_, PanelStyle (..), PanelCfg (..), panel_, entityHeader_, detailSection_, pivotLinks_, disclosure_, settingsSection_, settingsH2_, sectionLabel_, fieldLabel_, headerRow_, navBar, brandLogo_, resizer_, resizerWith_, detailTab_, httpTab_, tabPanel_, segmented_, periodToggle_, Deferred (..), RefreshingDeferred (..), withDeferredBody, deferredShell_, lazyPanel_, timeRefreshListener_, drawerLoadingSkeleton_, tableSkeleton_, chartSkeleton_, EmptyStateCfg (..), EmptyStateSize (..), EmptyStateAction (..), emptyState_, callout_, BadgeColor (..), IconBadgeSize (..), iconBadge_, tonePill_, colorChip_, metadataChip_, metaChip_, connectionBadge_, silenceBadge_, statFigure_, factGrid_, kvList_, sparkline_, eventsCountCell_, lastSeenCell_, dateTime, localTimeFmt_, FieldSize (..), FieldCfg (..), formField_, formSelectField_, formCheckbox_, options_, roleOptions_, tagInput_, toggleRow_, searchInput_, copyField_, copyButton_, ModalCfg (..), modalWith_, formActionsModal_, dangerAction_, floatingDialog_, dialogField_, kbdHints_, durationMenu_, primaryButton_, inlineIconBtn_, RowAction (..), rowActions_, externalLink_, installationSettingsLink_, dirtyFormSaveAttr_, resetFormOnSuccessAttr_, detailsClosedBelowAttr_, keyboardActivateAttr_, listboxNavAttr_, copySourceAttr_, filterInputAttr_, TraceFrame (..), stackTrace_, stackFrames_, codeContextUrl, curlCommand, getTargetPage, abbreviateUnit, agoText, durationQuery, untilLabel, grantsTrial, paymentPlanPicker) where +module Pages.Components (drawer_, PanelStyle (..), PanelCfg (..), panel_, entityHeader_, detailSection_, pivotLinks_, disclosure_, settingsSection_, settingsH2_, sectionLabel_, fieldLabel_, headerRow_, navBar, brandLogo_, resizer_, resizerWith_, detailTab_, httpTab_, tabPanel_, segmented_, segmentedWith_, periodToggle_, Deferred (..), RefreshingDeferred (..), withDeferredBody, deferredShell_, lazyPanel_, timeRefreshListener_, drawerLoadingSkeleton_, tableSkeleton_, chartSkeleton_, EmptyStateCfg (..), EmptyStateSize (..), EmptyStateAction (..), emptyState_, callout_, BadgeColor (..), IconBadgeSize (..), iconBadge_, tonePill_, colorChip_, metadataChip_, metaChip_, connectionBadge_, silenceBadge_, statFigure_, factGrid_, kvList_, sparkline_, eventsCountCell_, lastSeenCell_, dateTime, localTimeFmt_, FieldSize (..), FieldCfg (..), formField_, formSelectField_, formCheckbox_, options_, roleOptions_, tagInput_, toggleRow_, searchInput_, copyField_, copyButton_, ModalCfg (..), modalWith_, formActionsModal_, dangerAction_, floatingDialog_, dialogField_, kbdHints_, durationMenu_, primaryButton_, inlineIconBtn_, RowAction (..), rowActions_, externalLink_, installationSettingsLink_, dirtyFormSaveAttr_, resetFormOnSuccessAttr_, detailsClosedBelowAttr_, keyboardActivateAttr_, listboxNavAttr_, copySourceAttr_, filterInputAttr_, TraceFrame (..), stackTrace_, stackFrames_, codeContextUrl, curlCommand, getTargetPage, abbreviateUnit, agoText, durationQuery, untilLabel, grantsTrial, paymentPlanPicker) where import Data.Default (Default (..)) import Data.List (elemIndex, findIndex, lookup) @@ -139,10 +139,10 @@ el_ n = with (makeElement n) -- >>> let h = toStrict $ renderText $ drawer_ "d" False Nothing Nothing "" -- >>> "drawer-side top-0 left-0 w-full h-full flex justify-end z-10000 overflow-y-scroll overflow-x-hidden" `T.isInfixOf` h -- True --- >>> "pointer-events-none max-md:pointer-events-auto" `T.isInfixOf` h --- True --- >>> "aria-modal" `T.isInfixOf` h +-- >>> "hidden max-md:flex" `T.isInfixOf` h -- False +-- >>> "aria-modal=\"true\"" `T.isInfixOf` h +-- True drawer_ :: Text -> Bool -> Maybe Text -> Maybe (Html ()) -> Html () -> Html () drawer_ drawerId startOpen urlM content trigger = div_ [class_ "drawer drawer-end inline-block w-auto"] do input_ @@ -154,12 +154,10 @@ drawer_ drawerId startOpen urlM content trigger = div_ [class_ "drawer drawer-en <> [checked_ | startOpen] <> [ [__|on change if my.checked then - if window.matchMedia('(max-width: 767px)').matches then - add .overflow-hidden to - set my._focusTrapCleanup to window.createFocusTrap(my.closest('.drawer').querySelector('.drawer-side > [role=dialog]')) - set :closeBtn to my.closest('.drawer').querySelector('[data-drawer-close-primary]') or my.closest('.drawer').querySelector('button[aria-label="Close drawer"]') - if :closeBtn then call :closeBtn.focus() end - end + add .overflow-hidden to + set my._focusTrapCleanup to window.createFocusTrap(my.closest('.drawer').querySelector('.drawer-side > [role=dialog]')) + set :closeBtn to my.closest('.drawer').querySelector('[data-drawer-close-primary]') or my.closest('.drawer').querySelector('button[aria-label="Close drawer"]') + if :closeBtn then call :closeBtn.focus() end else remove .overflow-hidden from if my._focusTrapCleanup then @@ -167,7 +165,7 @@ drawer_ drawerId startOpen urlM content trigger = div_ [class_ "drawer drawer-en set my._focusTrapCleanup to null end end - on keydown[key == 'Escape' and my.checked and not (the event's target matches ) and no <[popover]:popover-open/> and no ] from window + on keydown[key == 'Escape' and my.checked and not event.defaultPrevented and no <#details-open:checked/> and no <[popover]:popover-open/> and no ] from window set my.checked to false trigger change on me end @@ -177,15 +175,14 @@ drawer_ drawerId startOpen urlM content trigger = div_ [class_ "drawer drawer-en label_ [Lucid.for_ drawerId, class_ "drawer-button inline-block", Aria.label_ "Open drawer"] trigger -- The closed panel is translated beyond the viewport. Clip it here rather than letting -- its transformed width create a page-level horizontal scroll range. - -- Desktop drawers are non-modal workbench panels: the page remains interactive so - -- list rows and charts can load their next selection straight into the open drawer. - -- Mobile keeps the ordinary modal overlay because the panel occupies the viewport. - div_ [class_ "drawer-side top-0 left-0 w-full h-full flex justify-end z-10000 overflow-y-scroll overflow-x-hidden pointer-events-none max-md:pointer-events-auto"] do - label_ [Lucid.for_ drawerId, Aria.label_ "Close drawer", class_ "hidden max-md:flex w-full drawer-overlay grow flex-1"] "" + -- Standard drawers are modal. Explorer log details use their separate non-modal panel. + div_ [class_ "drawer-side top-0 left-0 w-full h-full flex justify-end z-10000 overflow-y-scroll overflow-x-hidden"] do + label_ [Lucid.for_ drawerId, Aria.label_ "Close drawer", class_ "w-full drawer-overlay grow flex-1"] "" div_ [ id_ $ drawerId <> "-panel" , class_ "pointer-events-auto fixed right-0 top-0 h-dvh w-[min(90vw,75rem)] max-sm:w-screen! overflow-y-auto overscroll-contain overflow-x-hidden bg-bgRaised border-s border-strokeWeak shadow-2xl relative [&:has(.widget-editor)>.drawer-floating-close]:hidden" , role_ "dialog" + , term "aria-modal" "true" , Aria.label_ "Details" ] do @@ -743,7 +740,7 @@ data PanelCfg = PanelCfg panel_ :: Monad m => PanelStyle -> PanelCfg -> Text -> HtmlT m () -> HtmlT m () panel_ style cfg title content = case style of Raised -> div_ [class_ "surface-raised rounded-2xl p-4 relative"] do - span_ [class_ "flex items-center gap-2 text-sm font-semibold text-textStrong mb-3"] do + h3_ [class_ "flex items-center gap-2 text-sm font-semibold text-textStrong mb-3"] do whenJust cfg.icon \ic -> faSprite_ ic "regular" "w-4 h-4 text-iconNeutral" toHtml title whenJust cfg.subtitle $ span_ [class_ "normal-case tracking-normal font-normal"] . toHtml @@ -949,11 +946,16 @@ kbdHints_ hints = div_ [class_ "cmd-palette-hints mt-3 flex items-center justify -- | Segmented two-or-more-way radio switch; the first option starts checked. Input ids are -- @idPrefix <> value@ so callers can style siblings on @:checked@. segmented_ :: Text -> Text -> Text -> Text -> [(Text, Text)] -> Html () -segmented_ cls legend grp idPrefix opts = fieldset_ [class_ cls] do +segmented_ cls legend grp idPrefix opts = + segmentedWith_ [class_ cls] legend grp idPrefix [(val, lbl, [checked_ | active]) | (active, (val, lbl)) <- zip (True : repeat False) opts] + + +segmentedWith_ :: [Attribute] -> Text -> Text -> Text -> [(Text, Text, [Attribute])] -> Html () +segmentedWith_ attrs legend grp idPrefix opts = fieldset_ attrs do legend_ [class_ "sr-only"] $ toHtml legend - forM_ (zip (True : repeat False) opts) \(active, (val, lbl)) -> + forM_ opts \(val, lbl, inputAttrs) -> label_ [class_ "cursor-pointer rounded-md px-3 py-1 text-center font-medium text-textWeak has-[:checked]:bg-bgRaised has-[:checked]:text-textStrong has-[:checked]:shadow-xs has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2 transition-[color,background-color,box-shadow] duration-100"] do - input_ $ [type_ "radio", name_ grp, id_ (idPrefix <> val), class_ "sr-only"] <> [checked_ | active] <> [value_ val] + input_ $ [type_ "radio", name_ grp, id_ (idPrefix <> val), class_ "sr-only"] <> inputAttrs <> [value_ val] toHtml lbl diff --git a/src/Pages/Dashboards.hs b/src/Pages/Dashboards.hs index 3e68f8aae..c4cd8b8ab 100644 --- a/src/Pages/Dashboards.hs +++ b/src/Pages/Dashboards.hs @@ -103,7 +103,6 @@ import Pages.Components (EmptyStateCfg (..), EmptyStateSize (..), FieldCfg (..), import Pages.Components qualified as Components import Pages.GitSync qualified as GitSyncPage import Pages.Issues qualified as IssuesPage -import Pages.LogExplorer.LogItem qualified as LogItem import Pages.Monitors qualified as Alerts import Pages.Rum qualified as Rum import Pkg.Components.LogQueryBox (LogQueryBoxConfig (..), logQueryBox_) @@ -368,10 +367,6 @@ dashboardPage_ pid dashId dash dashVM allParams = do -- Hidden form for widget order PATCH via HTMX (tab slug hardcoded in URL) widgetOrderTriggerForm_ widgetOrderUrl False - -- Where a logs widget's row click loads its details. A dashboard has no third - -- pane to give it, so it is always the drawer. - LogItem.detailsPanel_ pid Nothing LogItem.DrawerPanel - -- ?expand= opens the widget in the global drawer. drawerLoadAttrs_ already -- checks the drawer toggle and fires its change handler (body overflow + focus trap), -- and htmx processes the swapped content itself. @@ -2771,11 +2766,11 @@ processDashWidgets prefill pid dashId now timeParams paramsWithConstants widgets -- | Handler for dashboard with tab in path: /p/{pid}/dashboards/{dash_id}/tab/{tab_slug} -- This renders the full page with the specified tab active dashboardTabGetH :: Projects.ProjectId -> Dashboards.DashboardId -> Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> Maybe Text -> [(Text, Maybe Text)] -> ATAuthCtx (RespHeaders (NavigationResponse DashboardGet)) -dashboardTabGetH pid dashId tabSlug fileM fromDStr toDStr sinceStr hxRequest hxTriggerName allParams = - Metrics.timed Metrics.dashboardShellDuration [("navigation", OA.toAttribute $ if isJust hxRequest then ("tab" :: Text) else "initial")] - $ withSpan_ "dashboard.tab.render" [("monoscope.dashboard.navigation", OA.toAttribute $ if isJust hxRequest then ("tab" :: Text) else "initial")] +dashboardTabGetH pid dashId tabSlug fileM fromDStr toDStr sinceStr hxTarget hxTriggerName allParams = + Metrics.timed Metrics.dashboardShellDuration [("navigation", navigation)] + $ withSpan_ "dashboard.tab.render" [("monoscope.dashboard.navigation", navigation)] $ do - let prefill = prefillFor hxRequest + let prefill = prefillFor hxTarget (session, project, bw) <- mkPageCtx pid now <- Time.currentTime let (_fromD, _toD, currentRange) = TimePicker.parseTimeRange now (TimePicker.TimePicker sinceStr fromDStr toDStr) @@ -2821,7 +2816,10 @@ dashboardTabGetH pid dashId tabSlug fileM fromDStr toDStr sinceStr hxRequest hxT breadcrumbSuffixOob_ activeTab.name when (dash''.file == Just "rum.yaml" && tabSlug `elem` ["audience", "errors"]) $ Rum.segmentToolbar_ pid paramsWithTab widgetCanvas_ pid ("tab-panel-" <> dashId.toText <> "-" <> show activeTabIdx) activeTab.widgets - addRespHeaders $ navigationResponse hxRequest page fragment + addRespHeaders $ navigationResponse tabTarget page fragment + where + tabTarget = mfilter ("#dashboard-tabs-content" `T.isSuffixOf`) hxTarget -- htmx 4 sends `tag#id` + navigation = OA.toAttribute @Text $ bool "initial" "tab" $ isJust tabTarget -- | Dashboard URLs carry variables and time, not a second global scope authority. Internal diff --git a/src/Pages/GitSync.hs b/src/Pages/GitSync.hs index acedc7cd9..bca42cc91 100644 --- a/src/Pages/GitSync.hs +++ b/src/Pages/GitSync.hs @@ -468,7 +468,7 @@ repositoryDashboardPage pid rid = do repos <- maybe (pure Nothing) (liftIO . Cache.lookup ctx.repoListCache) repository.credentialId let branch = maybe "" (.defaultBranch) $ find ((== repository.owner <> "/" <> repository.repo) . (.fullName)) (fold repos) permission <- ProjectMembers.getUserPermission pid session.user.id - pure $ PageCtx bw{pageTitle = "Configuration sync"} RepositoryDashboardGet{repository, sync, accounts, form = RepositoryDashboardForm repository.credentialId branch Nothing, hostUrl = ctx.config.hostUrl, permission, setupError = Nothing} + pure $ PageCtx bw{prePageTitle = Just "Repositories", pageTitle = repository.owner <> "/" <> repository.repo, pageTitleUrl = Just $ "/p/" <> pid.toText <> "/repositories/" <> rid.toText, pageTitleSuffix = Just "Configuration sync", menuItem = Just "Repositories"} RepositoryDashboardGet{repository, sync, accounts, form = RepositoryDashboardForm repository.credentialId branch Nothing, hostUrl = ctx.config.hostUrl, permission, setupError = Nothing} repositoryDashboardGetH :: Projects.ProjectId -> GitSync.RepositoryId -> ATAuthCtx (RespHeaders (PageCtx RepositoryDashboardGet)) @@ -512,14 +512,13 @@ repositoryDashboardPostH pid rid form = do instance ToHtml RepositoryDashboardGet where - toHtml page = section_ [class_ "mx-auto max-w-4xl space-y-6 px-4 py-6 sm:px-8 sm:py-8"] do + toHtml page = section_ [class_ "w-full min-w-0 space-y-6 p-4 sm:p-6"] do let repository = page.repository base = "/p/" <> repository.projectId.toText <> "/repositories/" <> repository.id.toText - a_ [href_ base, class_ "text-sm text-textBrand hover:underline"] $ toHtml $ repository.owner <> "/" <> repository.repo header_ [class_ "space-y-2"] do h1_ [class_ "text-xl font-semibold text-textStrong"] "Configuration sync" p_ [class_ "text-sm text-textWeak max-w-2xl"] "Keep dashboard and monitor definitions alongside code. Monoscope edits open or update one configuration PR; merged target-branch changes update Monoscope." - div_ [id_ "repository-dashboard-content", class_ "space-y-4"] do + div_ [id_ "repository-dashboard-content", class_ "space-y-4 rounded-xl border border-strokeWeak bg-bgBase p-4 sm:p-5"] do whenJust page.setupError $ p_ [role_ "alert", class_ "text-sm text-textError"] . toHtml if not (maybe False (>= ProjectMembers.PEdit) page.permission) then do diff --git a/src/Pages/Issues.hs b/src/Pages/Issues.hs index b0b521736..bd9ef8123 100644 --- a/src/Pages/Issues.hs +++ b/src/Pages/Issues.hs @@ -49,13 +49,14 @@ where import BackgroundJobs qualified import Control.Exception qualified as Exception -import Control.Lens (preview) +import Control.Lens (preview, (%~)) import Data.Aeson qualified as AE import Data.Aeson.Types (Pair, Parser, parseMaybe) import Data.CaseInsensitive qualified as CI import Data.Char (isHexDigit) import Data.Default (def) import Data.Effectful.Hasql qualified as Hasql +import Data.Generics.Product.Fields qualified as Optics import Data.Generics.Sum.Constructors (_Ctor) import Data.HashMap.Strict qualified as HM import Data.HashSet qualified as HS @@ -109,7 +110,7 @@ import Pages.BodyWrapper (BWConfig (..), PageCtx (..), checkFreeTierStatus, mkPa import Pages.Charts.Charts qualified as Charts import Pages.Components (BadgeColor (..), EmptyStateAction (..), EmptyStateCfg (..), EmptyStateSize (..), TraceFrame (..), agoText, codeContextUrl, colorChip_, copyButton_, curlCommand, detailsClosedBelowAttr_, disclosure_, durationMenu_, durationQuery, emptyState_, eventsCountCell_, externalLink_, fieldLabel_, filterInputAttr_, inlineIconBtn_, kvList_, lastSeenCell_, metadataChip_, options_, periodToggle_, resizer_, sectionLabel_, silenceBadge_, sparkline_, stackFrames_, statFigure_, tonePill_, untilLabel) import Pages.LogExplorer.Log (virtualTable) -import Pages.LogExplorer.LogItem qualified as LogItem +import Pages.Replay qualified as Replay import Pages.Telemetry (traceFragmentUrl) import Pkg.AI qualified as AI import Pkg.Components.Table (BulkAction (..), Column (..), Config (..), Features (..), Pagination (..), SearchMode (..), TabFilter (..), TabFilterOpt (..), Table (..), TableHeaderActions (..), TableResponse (..), TableRows (..), ZeroState (..), col, multiSelectFilter, withAttrs, withColHeaderExtra) @@ -124,12 +125,13 @@ import Pkg.SchemaLearning.Catalog (FacetData (..), FacetSummary (..), FacetValue import Pkg.SchemaLearning.Catalog qualified as Catalog import PyF (fmt) import Relude hiding (ask) +import Relude.Extra.Foldable1 (minimum1) import Servant (Header, Headers, NoContent (..), addHeader) import System.Config (AuthContext (..), EnvConfig (..)) import System.IO.Error (userError) import System.Logging qualified as Log import System.Types (ATAuthCtx, RespHeaders, addErrorToast, addRespHeaders, addSuccessToast, addTriggerEvent, redirectCS, useTfReads) -import Utils (LoadingSize (..), LoadingType (..), countNoun, faSprite_, fmtDate, formatOffset, formatUTC, formatWithCommas, hostPath, isoT, loadingIndicator_, lookupValueText, popoverPanel_, popoverTrigger_, renderMarkdown, summaryWords, timeScopedUrl, toUriStr) +import Utils (LoadingSize (..), LoadingType (..), countNoun, faSprite_, fmtDate, formatOffset, formatUTC, formatWithCommas, hostPath, isoT, kqlQuoted, loadingIndicator_, lookupValueText, popoverPanel_, popoverTrigger_, renderMarkdown, summaryWords, timeScopedUrl, toUriStr) import Web.FormUrlEncoded (FromForm) import Web.HttpApiData (FromHttpApiData (..), parseQueryParamMaybe) @@ -227,11 +229,11 @@ issueTriage_ pid issue members = form_ [id_ "issue-triage", class_ "ml-auto max-md:w-full flex flex-wrap items-center gap-3 text-xs text-textWeak", hxPost_ $ "/p/" <> pid.toText <> "/issues/" <> issue.id.toText <> "/triage", hxTrigger_ "change", hxSwap_ "outerHTML"] do label_ [class_ "flex items-center gap-1.5 max-md:flex-1 min-w-0"] do "Priority" - select_ [class_ "select select-sm md:w-28 max-md:flex-1 min-w-0", name_ "severity", Aria.label_ "Priority"] + select_ [id_ "issue-triage-priority", class_ "select select-sm md:w-28 max-md:flex-1 min-w-0", name_ "severity", Aria.label_ "Priority"] $ options_ (Just $ display issue.severity) [(display sev, T.toTitle $ display sev) | sev <- [minBound .. maxBound :: Issues.IssueSeverity]] label_ [class_ "flex items-center gap-1.5 max-md:flex-1 min-w-0"] do "Assignee" - select_ [class_ "select select-sm md:w-44 max-md:flex-1 min-w-0", name_ "assigneeId", Aria.label_ "Assignee"] + select_ [id_ "issue-triage-assignee", class_ "select select-sm md:w-44 max-md:flex-1 min-w-0", name_ "assigneeId", Aria.label_ "Assignee"] $ options_ (Just $ maybe "" (.toText) issue.assigneeId) (("", "Unassigned") : [(m.userId.toText, memberLabel m) | m <- members]) @@ -436,25 +438,6 @@ issueDetailCore pid firstM eventM requestedRange fetchIssue = do Just (Issues.CronP _) -> pure Nothing Just (Issues.FeedbackP _) -> pure Nothing Nothing -> pure Nothing - let - -- +/-2h: the widest bracket that stays inside ~3s (see the table above). - bracketAround = windowAround 7200 - lastActive = zonedTimeToUTC $ maybe issue.updatedAt (.lastSeenAt) patternM - -- ~2x the issue's age so the data fills the chart, capped at 24H by the cost above. - defaultSinceRange createdAt - | ageH < 1 = "1H" :: Text - | ageH < 3 = "3H" - | ageH < 6 = "6H" - | otherwise = "24H" - where - ageH = diffUTCTime now (zonedTimeToUTC createdAt) / 3600 - -- The URL's range drives the picker, sample lookup and log links together. - -- Previously only widgets saw absolute dates; the server silently used defaults. - tp = case Issues.issuePayload issue of - _ | any (maybe False (not . T.null)) [requestedRange.since, requestedRange.from, requestedRange.to] -> requestedRange - Just (Issues.QueryAlertP d) -> bracketAround d.triggeredAt - _ | diffUTCTime now lastActive > 43200 -> bracketAround lastActive - _ -> TimePicker.TimePicker (Just $ defaultSinceRange issue.createdAt) Nothing Nothing stateEvent <- enriching "latest_state_event" $ Issues.selectLatestStateEvent issue.id errorM <- bool (pure Nothing) (ErrorPatterns.getErrorPatternLByHash pid issue.targetHash now) (issue.issueType == Issues.RuntimeException) canResolve <- case errorM of @@ -491,7 +474,9 @@ issueDetailCore pid firstM eventM requestedRange fetchIssue = do recordedAt = guard (isJust selectedTraceId && selectedTraceId == base.errorData.traceId) $> base.errorData.when approximateAt = zonedTimeToUTC $ if isFirst || selectedTraceId == base.firstTraceId then base.createdAt else base.updatedAt pure $ (,fromMaybe approximateAt (recordedAt <|> capturedAt)) <$> selectedTraceId - Just (Issues.ApiChangeP d) -> Telemetry.getEndpointTraceId pid d.endpointMethod d.endpointPath isFirst now + Just (Issues.ApiChangeP d) -> case d.subject of + Just (ApiChanges.SpanSchema _) -> pure Nothing + _ -> Telemetry.getEndpointTraceId pid d.endpointMethod d.endpointPath isFirst now Just (Issues.QueryAlertP _) -> pure Nothing Just (Issues.LogPatternP _) -> pure Nothing Just (Issues.LogPatternRateChangeP _) -> pure Nothing @@ -502,6 +487,30 @@ issueDetailCore pid firstM eventM requestedRange fetchIssue = do Just (Issues.FeedbackP d) -> pure $ (,d.observedAt) <$> d.traceId Nothing -> pure Nothing mTraceRef <- maybe defaultTraceRef (\ev -> pure $ Just (ev.traceId, ev.at)) eventM + let recordedAt = case Issues.issuePayload issue of + Just (Issues.RuntimeExceptionP d) -> maybe (if isFirst then d.firstSeen else d.lastSeen) (\e -> zonedTimeToUTC $ if isFirst then e.base.createdAt else e.base.updatedAt) errorM + Just (Issues.LogPatternP d) -> maybe d.firstSeenAt (zonedTimeToUTC . (.lastSeenAt)) patternM + Just (Issues.LogPatternRateChangeP d) -> d.detectedAt + Just (Issues.QueryAlertP d) -> d.triggeredAt + Just (Issues.PerformanceP d) -> d.observedAt + Just (Issues.FrontendP d) -> d.observedAt + Just (Issues.FeedbackP d) -> d.observedAt + Just (Issues.UptimeP d) -> d.downSince + Just (Issues.CronP d) -> d.expectedBy + Just (Issues.ApiChangeP _) -> zonedTimeToUTC issue.createdAt + Nothing -> zonedTimeToUTC issue.createdAt + selectedAt = maybe recordedAt snd mTraceRef + defaultSinceRange + | ageH < 1 = "1H" :: Text + | ageH < 3 = "3H" + | ageH < 6 = "6H" + | otherwise = "24H" + where + ageH = diffUTCTime now selectedAt / 3600 + tp + | any (maybe False (not . T.null)) [requestedRange.since, requestedRange.from, requestedRange.to] = requestedRange + | isFirst || isJust eventM || issue.issueType == Issues.QueryAlert || diffUTCTime now selectedAt > 43200 = windowAround 7200 selectedAt + | otherwise = TimePicker.TimePicker (Just defaultSinceRange) Nothing Nothing -- The trace is supporting evidence, not the page. It used to be fetched here -- and a cold read of a multi-thousand-span trace took >56s, so the gateway -- 504'd the whole issue. The Trace section now pulls it as its own @@ -524,9 +533,11 @@ issueDetailCore pid firstM eventM requestedRange fetchIssue = do -- without setSession, where the session is derived from user identity) -- can never have one, so it never reaches the lookup. let sessionM = tracedSession <|> listToMaybe ([sid | Just (Issues.FrontendP d) <- [Issues.issuePayload issue], Just sid <- [d.sessionId]] <> [sid | Just (Issues.FeedbackP d) <- [Issues.issuePayload issue], Just sid <- [d.sessionId]]) - replaySession <- enriching "replay_recording" $ flip foldMapM (UUID.fromText =<< sessionM) \sid -> - listToMaybe @Text - <$> Hasql.interp [HI.sql| SELECT session_id::text FROM projects.replay_sessions WHERE project_id = #{pid} AND session_id = #{sid} LIMIT 1 |] + replaySession <- + enriching "replay_recording" + $ join + <$> forM (UUID.fromText =<< sessionM) \sid -> + fmap (UUID.toText sid,) <$> Replay.sessionMetadata pid sid (one ("issue_id", issue.id.toText)) apiEvidence <- enriching "api_change_evidence" $ forM (apiChangeData issue) \d -> do changes <- ApiChanges.getAnomaliesVM pid d.anomalyHashes schemas <- SchemaCatalog.getByKeysBatch (V.singleton (pid, issue.targetHash)) @@ -534,7 +545,7 @@ issueDetailCore pid firstM eventM requestedRange fetchIssue = do addRespHeaders $ PageCtx bwconf $ issueDetailPage - IssueView{pid, issue, apiEvidence, traceRef = mTraceRef, replaySession, errM = errorM, patternM, now, isFirst, tp, stateEvent, canResolve, members, tagCounts, errHourlyFrom} + IssueView{pid, issue, apiEvidence, traceRef = mTraceRef, selectedAt, replaySession, errM = errorM, patternM, now, isFirst, tp, stateEvent, canResolve, members, tagCounts, errHourlyFrom} where -- A lookup that only decides whether an optional panel renders: a throw or a 10s stall -- degrades to Nothing. A transient TF error used to 500 the whole issue, precisely @@ -628,15 +639,15 @@ issueSampleCard_ pid snapshot result = case result of a_ [href_ $ "/p/" <> pid.toText <> "/traces/" <> toUriStr tid <> "?timestamp=" <> toUriStr (formatUTC at), class_ "text-textBrand underline underline-offset-2"] "View trace" div_ [class_ "flex flex-wrap items-center gap-1 p-4 max-h-80 overflow-y-auto"] $ V.mapM_ (summaryToken_ True) summary SampleLoading -> withSnapshot "Looking for an event in the selected range…" - SampleEmpty -> withSnapshot "No matching event in the selected range. Try another range or inspect the logs below." + SampleEmpty -> withSnapshot "No occurrences in this range. Try another range; older raw events may no longer be retained." SampleUnavailable -> withSnapshot do "The event sample could not be loaded. " button_ [type_ "button", class_ "text-textBrand underline underline-offset-2", [__|on click send retryIssueSample to #issue-sample|]] "Retry" where withSnapshot message = do div_ [class_ "px-4 py-3 text-sm text-textWeak", role_ "status"] message - whenJust (mfilter (not . T.null . T.strip) snapshot) \stored -> do - div_ [class_ "px-4 pt-2 border-t border-strokeWeak text-xs text-textWeak"] "Stored sample · saved with this issue, outside the range filter" + whenJust (nonBlank snapshot) \stored -> do + div_ [class_ "px-4 pt-2 border-t border-strokeWeak text-xs text-textWeak"] "Stored sample · preserved with this issue independently of the date filter and raw-event retention" renderLogContent_ stored @@ -727,43 +738,48 @@ userJourneySection_ spans = whenJust (extractBreadcrumbs spans) \crumbs -> do lastIdx = total - 1 renderCrumb idx bc = do let (icn, iconColor) = breadcrumbVisual bc.kind - isTerminal = idx == lastIdx - timeLabel - | idx == 0 = fmtDate "%b %-e, %H:%M:%S" $ POSIX.posixSecondsToUTCTime $ realToFrac (fromIntegral bc.timestamp / 1000 :: Double) - | otherwise = formatOffset base bc.timestamp - div_ [class_ $ bool "crumb relative flex gap-2.5 px-4 py-2 border-l-2 border-transparent hover:bg-fillWeaker" "crumb relative flex gap-2.5 px-4 py-2 border-l-2 border-strokeError-strong bg-fillError-weak" isTerminal] do - div_ [class_ "flex flex-col items-center pt-0.5 shrink-0"] do + message = nonBlank bc.message + payload = nonBlank (bc.payload >>= breadcrumbDataSummary) + rowHeader expandable = span_ [class_ "flex items-start gap-2 min-w-0 min-h-6"] do + span_ [class_ "w-7 shrink-0 font-mono text-2xs leading-5 tabular-nums text-textWeak", title_ $ fmtDate "%F %T UTC" $ POSIX.posixSecondsToUTCTime $ realToFrac (fromIntegral bc.timestamp / 1000 :: Double)] $ toHtml $ formatOffset base bc.timestamp + span_ [class_ "min-w-0 flex-1 text-xs leading-5 text-textStrong break-normal [overflow-wrap:anywhere]"] (slashBreaks_ bc.kind) + when expandable $ span_ [class_ "shrink-0 mt-1 text-textWeak", Aria.hidden_ "true"] $ faSprite_ "chevron-right" "regular" "w-3 h-3 group-open/crumb:rotate-90" + div_ [class_ "crumb flex gap-2 px-4 py-0.5 hover:bg-fillWeaker"] do + div_ [class_ "flex flex-col items-center pt-1 shrink-0"] do faSprite_ icn "regular" $ "w-3 h-3 " <> iconColor - unless isTerminal $ div_ [class_ "w-px flex-1 bg-strokeWeak mt-1"] "" - div_ [class_ "min-w-0 flex-1 flex flex-col gap-0.5"] do - div_ [class_ "flex items-center gap-2 flex-wrap"] do - span_ [class_ "text-xs tabular-nums text-textWeak shrink-0"] $ toHtml timeLabel - span_ [class_ $ "text-xs font-medium " <> iconColor] $ toHtml bc.kind - -- Long messages clamp to 3 lines; a hidden checkbox + `group-has` removes the - -- clamp, so expansion is pure CSS and survives htmx morphs with no re-init. - let expandable cls val = - label_ [class_ "group/bc cursor-pointer flex items-start gap-1"] do - input_ [type_ "checkbox", class_ "hidden"] - span_ [class_ $ cls <> " group-has-[:checked]/bc:line-clamp-none group-has-[:checked]/bc:!block min-w-0 flex-1"] $ toHtml val - faSprite_ "chevron-down" "regular" "w-3 h-3 text-textWeak shrink-0 mt-1 group-has-[:checked]/bc:rotate-180 transition-transform" - whenJust bc.message - $ expandable "text-sm text-textStrong line-clamp-3 break-words whitespace-pre-wrap" - whenJust (bc.payload >>= breadcrumbDataSummary) - $ expandable "font-mono text-xs text-textWeak line-clamp-2 break-all" + unless (idx == lastIdx) $ div_ [class_ "w-px flex-1 bg-strokeWeak mt-1"] "" + if isNothing message && isNothing payload + then div_ [class_ "min-w-0 flex-1"] $ rowHeader False + else details_ [class_ "group/crumb min-w-0 flex-1"] do + summary_ [class_ "cursor-pointer list-none [&::-webkit-details-marker]:hidden rounded focus-visible:outline-2 focus-visible:outline-offset-2"] $ rowHeader True + div_ [class_ "pl-9 pt-1 space-y-1"] do + whenJust message $ p_ [class_ "text-xs leading-relaxed text-textWeak whitespace-pre-wrap break-words"] . toHtml + whenJust payload $ p_ [class_ "font-mono text-2xs leading-relaxed text-textWeak whitespace-pre-wrap break-normal [overflow-wrap:anywhere]"] . toHtml + renderCrumbs rows = div_ [class_ "py-0.5 flex flex-col group-has-[.crumb-rev:checked]/journey:flex-col-reverse"] $ traverse_ (uncurry renderCrumb) rows + indexedCrumbs = zip [0 :: Int ..] crumbList div_ [id_ "issue-journey", class_ "border-t border-strokeWeak group/journey"] do div_ [class_ "px-4 py-2 flex flex-wrap items-center gap-2 bg-fillWeaker/40"] do faSprite_ "route" "regular" "w-3 h-3 text-textWeak" fieldLabel_ "" "User journey" span_ [class_ "text-2xs text-textWeak"] $ toHtml $ countNoun total "event" <> " before error" - div_ [class_ "ml-auto flex items-center gap-2"] do - input_ [type_ "search", placeholder_ "Search", Aria.label_ "Search the user journey", class_ "input input-xs w-32", filterInputAttr_ "#issue-journey .crumb"] - label_ [class_ "btn btn-xs btn-ghost gap-1 has-[:checked]:text-textBrand", term "data-tippy-content" "Newest first"] do - input_ [type_ "checkbox", class_ "crumb-rev sr-only"] + div_ ([class_ "w-full min-w-0 flex items-center gap-1.5"] <> [[__|on input from #issue-journey-search set #issue-journey-events.open to true|] | total > 5]) do + input_ [id_ "issue-journey-search", type_ "search", placeholder_ "Search", Aria.label_ "Search the user journey", class_ "input input-xs w-full min-w-0 flex-1 text-base sm:text-xs", filterInputAttr_ "#issue-journey .crumb"] + label_ [class_ "btn btn-xs btn-ghost shrink-0 gap-1 has-[:checked]:text-textBrand has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-offset-2", term "data-tippy-content" "Newest first"] do + input_ [type_ "checkbox", class_ "crumb-rev sr-only", Aria.label_ "Newest events first"] faSprite_ "arrows-up-down" "regular" "w-3 h-3" copyButton_ "btn btn-xs btn-ghost" "w-3 h-3" "#issue-journey-text's textContent" [] pre_ [id_ "issue-journey-text", class_ "hidden"] $ toHtml $ unlines [bc.kind <> foldMap (" " <>) bc.message | bc <- crumbList] - div_ [class_ "py-1 flex flex-col group-has-[.crumb-rev:checked]/journey:flex-col-reverse"] - $ traverse_ (uncurry renderCrumb) (zip [0 :: Int ..] crumbList) + if total <= 5 + then renderCrumbs indexedCrumbs + else do + div_ [class_ "group-has-[#issue-journey-events[open]]/journey:hidden"] do + p_ [class_ "px-4 pt-2 pb-1 text-2xs text-textWeak"] "Last 5 events" + renderCrumbs $ drop (total - 5) indexedCrumbs + details_ [id_ "issue-journey-events", class_ "group/events"] do + summary_ [class_ "px-4 py-1 text-xs text-textBrand cursor-pointer hover:bg-fillWeaker list-none [&::-webkit-details-marker]:hidden focus-visible:outline-2 focus-visible:outline-offset-[-2px]"] do + span_ [class_ "group-open/events:hidden"] $ toHtml $ "View all " <> countNoun total "event" + span_ [class_ "hidden group-open/events:inline"] "Show fewer" + renderCrumbs indexedCrumbs where -- Every breadcrumb the trace can yield, deduped across overlapping -- instrumentation (an SDK may ship both the legacy attribute and OTel events) and @@ -855,18 +871,31 @@ railSection_ title body = section_ [class_ "py-4 border-b border-strokeWeak last -- environment set is not an issue in an environment called Unknown. issueFactRow_ :: UTCTime -> Issues.Issue -> Maybe ErrorPatterns.ErrorPattern -> Maybe LogPatterns.LogPattern -> Html () issueFactRow_ now issue errM patternM = - railSection_ "Seen" $ kvList_ "text-sm" [(lbl, span_ [class_ "font-medium", term "data-tippy-content" tip] $ toHtml value) | (lbl, value, tip) <- facts] + railSection_ "Issue details" + $ kvList_ "text-sm" + $ [ ( lbl + , time_ + [ datetime_ $ isoT at + , tabindex_ "0" + , class_ "font-medium rounded-sm focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-strokeBrand-strong" + , Aria.label_ $ lbl <> ": " <> agoText now at <> " (" <> formatUTC at <> ")" + , term "data-tippy-content" $ formatUTC at + ] + $ toHtml + $ agoText now at + ) + | (lbl, at) <- [("Last seen", lastSeen), ("First seen", firstSeen)] + ] + <> [(lbl, span_ [class_ "font-medium", term "data-tippy-content" value] $ toHtml value) | (lbl, value) <- facts] where - nonBlank = mfilter (not . T.null . T.strip) (firstSeen, lastSeen) = bimap zonedTimeToUTC zonedTimeToUTC $ fromMaybe (issue.createdAt, issue.updatedAt) $ ((\e -> (e.createdAt, e.updatedAt)) <$> errM) <|> ((\p -> (p.firstSeenAt, p.lastSeenAt)) <$> patternM) facts = - [("Last seen", agoText now lastSeen, formatUTC lastSeen), ("First seen", agoText now firstSeen, formatUTC firstSeen)] - <> catMaybes - [ (\r -> ("First release", r, r)) <$> (errM >>= (.firstRelease)) - , (\r -> ("Last release", r, r)) <$> (errM >>= (.lastRelease)) - , (\sv -> ("Service", sv, sv)) <$> nonBlank issue.service - , (\e -> ("Environment", e, e)) <$> nonBlank issue.environment - ] + catMaybes + [ ("First release",) <$> (errM >>= (.firstRelease)) + , ("Last release",) <$> (errM >>= (.lastRelease)) + , issueSource issue + , ("Environment",) <$> nonBlank issue.environment + ] -- | Everything the issue detail page's sections read. Bundled because the @@ -882,7 +911,8 @@ data IssueView = IssueView , issue :: Issues.Issue , apiEvidence :: Maybe ([ApiChanges.AnomalyVM], Maybe Catalog.CatalogEntry) , traceRef :: Maybe (Text, UTCTime) - , replaySession :: Maybe Text + , selectedAt :: UTCTime + , replaySession :: Maybe (Text, Replay.SessionMeta) , errM :: Maybe ErrorPatterns.ErrorPatternL , patternM :: Maybe LogPatterns.LogPattern , now :: UTCTime @@ -910,6 +940,32 @@ data IssueSection = IssueSection } +schemaSubjectFor :: IssueView -> Maybe ApiChanges.SchemaSubject +schemaSubjectFor v = (apiChangeData v.issue >>= (.subject)) <|> fromCatalog <|> fromEndpoint + where + fromCatalog = do + (_, Just entry) <- v.apiEvidence + pure $ ApiChanges.schemaSubject entry.template.keyKind entry.scope + fromEndpoint = do + d <- apiChangeData v.issue + method <- Issues.knownMethod d + pure $ ApiChanges.EndpointSchema Catalog.emptyScope{Catalog.method = Just method, Catalog.urlPath = Just d.endpointPath, Catalog.host = Issues.knownHost d, Catalog.service = v.issue.service} + + +-- | KQL for the issue's events: its span hash, or a span schema's service, name and kind. +-- A schema observation with no recorded source has neither. +issueEventsQuery :: IssueView -> Maybe Text +issueEventsQuery v = case schemaSubjectFor v of + Just (ApiChanges.SpanSchema scope) -> do + service <- nonBlank scope.service + name <- nonBlank scope.spanName + pure $ "resource.service.name==" <> kqlQuoted service <> " AND name==" <> kqlQuoted name <> foldMap ((" AND kind==" <>) . kqlQuoted) scope.kind + Just (ApiChanges.EndpointSchema _) -> hashQuery + Nothing -> hashQuery <* guard (v.issue.issueType /= Issues.ApiChange) + where + hashQuery = ("hashes[*]==" <>) . kqlQuoted <$> issueHashKey v.issue + + -- | Sentry's issue layout in our visual language: a full-width title block with the -- workflow bar under it, then the evidence column beside a rail. In the evidence -- column the aggregate band (range, chart, context) comes first, then one event card @@ -924,36 +980,45 @@ issueDetailPage v@IssueView{..} = div_ [class_ "flex h-full overflow-hidden rela -- standalone chart widgets read the window the picker shows. A query alert -- defaults to an absolute from/to, so seeding `since` would override it. let seedParams = TimePicker.rangeJson tp - script_ [fmt|document.addEventListener('DOMContentLoaded',function(){{const p=new URLSearchParams(location.search);if(!p.get('since')&&!p.get('from')&&!p.get('to'))window.setParams({seedParams})}});|] + script_ [fmt|(() => {{const seed=()=>{{const p=new URLSearchParams(location.search);if(!p.get('since')&&!p.get('from')&&!p.get('to'))window.setParams({seedParams})}};if(document.readyState==='loading')document.addEventListener('DOMContentLoaded',seed,{{once:true}});else seed()}})();|] issueAggregate_ v eventCard_ v - aside_ [class_ "min-w-0 max-md:px-3 px-4 xl:border-l max-xl:border-t border-strokeWeak"] do + aside_ [class_ "min-w-0 px-4 xl:border-l max-xl:border-t border-strokeWeak"] do issueFactRow_ now issue ((.base) <$> errM) patternM railSection_ "AI analysis" do -- The background analysis job's verdict, when it has run for this error. case errM >>= \errL -> (,errL.base.errorCategory) <$> errL.base.rootCause of - Just (rootCause, categoryM) -> div_ [class_ "mb-3 rounded-lg border border-strokeWeak p-3 space-y-1.5"] do + Just (rootCause, categoryM) -> div_ [class_ "mb-2 rounded-lg bg-fillWeaker/60 p-3 space-y-2"] do div_ [class_ "flex items-center gap-2"] do - span_ [class_ "text-xs font-semibold text-textStrong"] "Root cause" - whenJust categoryM $ span_ [class_ "badge badge-sm badge-ghost"] . toHtml - p_ [class_ "text-sm text-textStrong"] $ toHtml rootCause + span_ [class_ "text-xs font-semibold text-textStrong"] "Likely cause" + whenJust categoryM $ \category -> span_ [class_ "rounded bg-fillWeak px-1.5 py-0.5 text-2xs text-textWeak"] $ toHtml $ if T.toLower category == "data" then "Data handling" else T.toTitle category + details_ [class_ "group/analysis"] do + summary_ [class_ "cursor-pointer list-none [&::-webkit-details-marker]:hidden rounded focus-visible:outline-2 focus-visible:outline-offset-2"] do + span_ [class_ "text-sm leading-relaxed text-textStrong break-words line-clamp-3 group-open/analysis:hidden"] $ toHtml rootCause + span_ [class_ "block mt-2 text-xs text-textBrand"] do + span_ [class_ "group-open/analysis:hidden"] "Read full analysis" + span_ [class_ "hidden group-open/analysis:inline"] "Show less" + p_ [class_ "mt-2 text-sm leading-relaxed text-textStrong break-words"] $ toHtml rootCause Nothing -> p_ [class_ "text-sm text-textWeak mb-2"] "Ask about the cause, the blast radius, or a fix — answered from this issue's telemetry." div_ [class_ "flex gap-2"] do - label_ [Lucid.for_ "ai-panel-toggle", class_ "btn btn-sm btn-outline flex-1 gap-1.5"] do - faSprite_ "sparkles" "regular" "w-3.5 h-3.5" - "Investigate" button_ - [ type_ "button" - , class_ "btn btn-sm btn-outline flex-1 gap-1.5" - , [__|on click set #ai-panel-toggle's checked to true then send change to #ai-panel-toggle + (class_ "btn btn-sm btn-ghost bg-fillBrand-weak text-textBrand hover:bg-fillBrand-weak hover:brightness-110 flex-1 min-w-0 gap-1.5" : aiPanelOpenerAttrs) + do + faSprite_ "sparkles" "regular" "w-3.5 h-3.5" + "Investigate" + button_ + ( aiPanelToggleAttrs + <> [ class_ "btn btn-sm btn-ghost bg-fillWeaker flex-1 min-w-0 gap-1.5" + , [__|on click set #ai-panel-toggle's opener to me then set #ai-panel-toggle's checked to true then send change to #ai-panel-toggle then set #ai-chat-input's value to 'Propose a step-by-step fix plan for this issue, with the code changes, citing the files and lines from the stack trace.' then call (#ai-chat-input).form.requestSubmit()|] - ] + ] + ) do faSprite_ "code" "regular" "w-3.5 h-3.5" "Plan a fix" whenJust errM \errL -> - div_ [hxGet_ $ "/p/" <> pid.toText <> "/issues/errors/" <> UUID.toText errL.base.id.unErrorPatternId <> "/group_members", hxTrigger_ "load", hxSwap_ "innerHTML"] pass + div_ [hxGet_ $ "/p/" <> pid.toText <> "/issues/errors/" <> UUID.toText errL.base.id.unErrorPatternId <> "/group_members", hxTrigger_ "load, issuePatternGroupChanged from:body", hxSwap_ "innerHTML"] pass activityPanel_ pid issue.id.toText traceRef aiSidePanel_ pid issue.id @@ -961,12 +1026,13 @@ issueDetailPage v@IssueView{..} = div_ [class_ "flex h-full overflow-hidden rela -- | Title, culprit, the state line, the Events figure, then the workflow bar — the -- zone that identifies the issue and acts on it, full width above both columns. issueHeader_ :: IssueView -> Html () -issueHeader_ IssueView{..} = header_ [class_ "max-md:px-3 px-4 max-md:pt-4 pt-6 pb-3 border-b border-strokeWeak space-y-3"] do +issueHeader_ v@IssueView{..} = header_ [class_ "max-md:px-3 px-4 max-md:pt-4 pt-6 pb-3 border-b border-strokeWeak space-y-3"] do issueStatusStrip_ -- h2, not h3: the shell's breadcrumb owns h1, and an h3 here ranked below the -- empty-state h2s further down the page. - let detailTitle = case Issues.issuePayload issue of - Just (Issues.QueryAlertP alertData) | not (T.null $ T.strip alertData.queryName) -> alertData.queryName + let detailTitle = case (Issues.issuePayload issue, schemaSubjectFor v) of + (Just (Issues.QueryAlertP alertData), _) | not (T.null $ T.strip alertData.queryName) -> alertData.queryName + (_, Just (ApiChanges.SpanSchema scope)) -> ApiChanges.spanSchemaTitle scope _ -> issue.title div_ [class_ "flex gap-6 items-start pr-10"] do div_ [class_ "min-w-0 flex-1 space-y-1.5"] do @@ -975,7 +1041,7 @@ issueHeader_ IssueView{..} = header_ [class_ "max-md:px-3 px-4 max-md:pt-4 pt-6 $ p_ [class_ "text-sm text-textWeak max-w-3xl border-l-2 border-strokeError-strong pl-2"] $ toHtml issue.recommendedAction div_ [class_ "flex flex-wrap gap-x-3 gap-y-1.5 items-center"] do - issueTypeChip_ False issue.issueType issue.critical + issueTypeChip_ False issue.issueType issueStateBadge_ stateEvent -- Only what is peculiar to the type belongs here; service, environment and -- first/last seen are common to every issue and live in the rail. @@ -1005,10 +1071,10 @@ issueHeader_ IssueView{..} = header_ [class_ "max-md:px-3 px-4 max-md:pt-4 pt-6 -- The chart's own total, hoisted: `naked` suppresses the widget's value slot, so -- this is the only place it renders and it cannot disagree with the chart. div_ [class_ "shrink-0 flex gap-6"] do - when (isJust $ Issues.hashPrefix issue.issueType) - $ statFigure_ "items-end" [term "data-tippy-content" "Events in the selected range"] "Events" (Widget.widgetValueSlotAs_ (issueChartId issue) Nothing) + when (isJust $ issueEventsQuery v) + $ statFigure_ "items-end" [term "data-tippy-content" "Events in the selected range"] "Events · this range" (Widget.widgetValueSlotAs_ (issueChartId issue) Nothing) -- Distinct users by user.id / user.email / client.address, all time. - whenJust errM \errL -> statFigure_ "items-end" [term "data-tippy-content" "Distinct users affected, all time"] "Users" $ toHtml $ formatWithCommas (fromIntegral errL.base.usersCount :: Double) + whenJust errM \errL -> statFigure_ "items-end" [term "data-tippy-content" "Distinct users affected, all time"] "Users · all time" $ toHtml $ formatWithCommas (fromIntegral errL.base.usersCount :: Double) div_ [class_ "flex flex-wrap items-center gap-2"] do issueAcknowledgeButton pid issue.id now ackUntil issueArchiveButton pid issue.id (isJust issue.archivedAt) @@ -1044,23 +1110,33 @@ issueHeader_ IssueView{..} = header_ [class_ "max-md:px-3 px-4 max-md:pt-4 pt-6 issueChartId :: Issues.Issue -> Text -issueChartId issue = issue.id.toText <> "-pattern-volume" +issueChartId issue = issue.id.toText <> if issue.issueType == Issues.ApiChange then "-schema-activity" else "-pattern-volume" -- | A chart series over one key of an hourly stats table, bounded by the chart's window. hourlyRollupSql :: Text -> Text -> Text -hourlyRollupSql tbl key = "SELECT * FROM (SELECT hour_bucket AS timestamp, 'value', event_count::float FROM " <> tbl <> " WHERE project_id = '{{project_id}}' AND " <> key <> ") s WHERE TRUE{{time_filter}} ORDER BY 1" +hourlyRollupSql tbl key = "SELECT * FROM (SELECT hour_bucket AS timestamp, 'value', event_count::float FROM " <> tbl <> " WHERE project_id = '{{project_id}}' AND " <> key <> ") s WHERE TRUE{{rollup_time_filter}} ORDER BY 1" -- | The aggregate band: the range every panel below reads, then the chart beside the -- type's context panel. issueAggregate_ :: IssueView -> Html () -issueAggregate_ IssueView{..} = do - let (_, _, currentRange) = TimePicker.parseTimeRange now tp +issueAggregate_ v@IssueView{..} = do + let (rangeFrom, rangeTo, currentRange) = TimePicker.parseTimeRange now tp + eventWindow = windowAround 7200 selectedAt refreshId = "anomaly-chart-refresh" div_ [id_ refreshId, class_ "hidden", [__|on submit trigger 'update-query' on window|]] "" div_ [class_ "flex flex-wrap items-center gap-2 [&>button]:max-md:basis-full"] $ TimePicker.liveDataControls_ (Just refreshId) currentRange (Just $ "issue-" <> issueChartId issue) TimePicker.RefreshOnly + p_ [class_ "flex flex-wrap items-center gap-x-2 text-xs text-textWeak"] do + span_ $ if issue.issueType == Issues.ApiChange then "Change detected" else "Selected event" + time_ [datetime_ $ isoT selectedAt] $ toHtml $ fmtDate "%F %T UTC" selectedAt + when (tp.from == eventWindow.from && tp.to == eventWindow.to && isNothing tp.since) + $ span_ "· Around selected event · ±2 hours" + when (any (> selectedAt) rangeFrom || any (< selectedAt) rangeTo) + $ p_ [class_ "text-sm text-textWeak"] do + "Selected event is outside this range. " + a_ [href_ $ "/p/" <> pid.toText <> "/issues/" <> issue.id.toText, class_ "text-textBrand hover:underline"] "Jump to latest occurrence" case Issues.issuePayload issue of Nothing -> unparsablePayload_ Just (Issues.LogPatternP _) -> issueVolumeChart_ "Pattern Volume" @@ -1104,15 +1180,19 @@ issueAggregate_ IssueView{..} = do detailRow_ [("bolt", "text-fillWarning-strong", "Recorded", agoText now d.triggeredAt)] whenJust (monitorIdFromStored d.queryId) \mid_ -> externalLink_ [href_ $ "/p/" <> pid.toText <> "/monitors/" <> mid_ <> "/overview"] "View monitor" Just (Issues.ApiChangeP d) -> do - div_ [class_ "flex flex-wrap items-center gap-3"] do - span_ [class_ $ "cbadge-sm whitespace-nowrap " <> Telemetry.methodStyle d.endpointMethod] $ toHtml d.endpointMethod - span_ [class_ "font-mono bg-fillWeaker px-2 py-1 rounded text-sm text-textStrong"] $ toHtml d.endpointPath - span_ [class_ "flex items-center gap-1.5 text-sm text-textWeak"] do - faSprite_ "server" "regular" "h-3 w-3" - toHtml d.endpointHost - sideBySide_ (issueVolumeChart_ "Request Trend") - $ contextCard_ "p-4 flex flex-col gap-3" "Endpoint Details" - $ detailRow_ [("hashtag", "text-fillBrand-strong", "Requests", formatWithCommas (fromIntegral issue.affectedRequests :: Double))] + div_ [class_ "flex flex-wrap items-center gap-x-4 gap-y-2 text-sm text-textStrong"] do + case schemaSubjectFor v of + Just (ApiChanges.SpanSchema scope) -> do + span_ [class_ "text-textWeak"] "Span schema" + whenJust scope.service $ span_ . toHtml + whenJust scope.spanName $ code_ [class_ "font-mono break-normal [overflow-wrap:anywhere]"] . toHtml + Just (ApiChanges.EndpointSchema scope) -> do + whenJust scope.method $ \method -> span_ [class_ $ "cbadge-sm " <> Telemetry.methodStyle method] $ toHtml method + whenJust scope.urlPath $ code_ [class_ "font-mono break-normal [overflow-wrap:anywhere]"] . toHtml + whenJust scope.host $ span_ . toHtml + Nothing -> span_ [class_ "text-textWeak"] "Schema observation · source details unavailable" + span_ [class_ "text-textWeak"] $ toHtml $ countNoun (length $ ordNub $ V.toList $ d.newFields <> d.deletedFields <> d.modifiedFields) "changed field" + p_ [class_ "text-xs text-textWeak"] "Observed changes describe recorded data. They do not by themselves confirm a breaking API change." where figures_ :: [(Text, Text)] -> Html () figures_ = mapM_ \(lbl, val) -> statFigure_ "" [] lbl (toHtml val) @@ -1204,10 +1284,10 @@ issueAggregate_ IssueView{..} = do eventCard_ :: IssueView -> Html () -- @--event-nav-h@ is the navigator's height (h-10 + h-9 + its 1px border); the trace -- waterfall's sticky rows and the jump-link landing offset read it. -eventCard_ IssueView{..} = div_ [class_ "surface-raised rounded-2xl overflow-clip [--event-nav-h:77px]"] do +eventCard_ view@IssueView{..} = div_ [class_ "surface-raised rounded-2xl overflow-clip [--event-nav-h:77px]"] do let occurrenceUrl useFirst = "/p/" <> pid.toText <> "/issues/" <> issue.id.toText <> "?" <> T.drop 1 (mconcat ["&first_occurrence=true" | useFirst] <> TimePicker.rangeQuery tp) -- Only issues keyed by an event hash have a stream of occurrences to step through. - hasOccurrences = isJust (Issues.hashPrefix issue.issueType) && not isLogPatternIssue + hasOccurrences = isJust (Issues.hashPrefix issue.issueType) && not isLogPatternIssue && issue.issueType /= Issues.ApiChange nav_ [id_ "issue-event-nav", class_ "sticky top-0 z-20 bg-bgRaised border-b border-strokeWeak", Aria.label_ "Issue evidence"] do div_ [class_ "max-md:px-3 px-4 h-10 flex items-center gap-3 overflow-x-auto whitespace-nowrap"] do span_ [class_ "text-sm font-semibold text-textStrong"] $ bool "Evidence" "Event" hasOccurrences @@ -1252,19 +1332,36 @@ eventCard_ IssueView{..} = div_ [class_ "surface-raised rounded-2xl overflow-cli <> foldMap (\errL -> let e = errL.base.errorData in ["- Release: " <> r | Just r <- [e.release]] <> ["", "```", e.errorType <> ": " <> e.message, errL.base.stacktrace, "```"]) errM -- The type's own evidence, then trace, logs and replay when the issue has them. -- A section with nothing to show is left out rather than rendered as an empty state. - sections = typeSections <> traceSection <> logsSection <> eventsSection <> replaySection + sections = typeSections <> apiActivitySection <> traceSection <> logsSection <> eventsSection <> replaySection -- Every event of the issue in the page's range, from its own hash; picking one's -- trace re-opens the page on that event. + apiActivitySection = + [ section "issue-schema-activity" "chart-line" "Matching span activity" + $ div_ [class_ "h-32 px-4"] + $ Widget.widget_ + (def :: Widget.Widget) + { Widget.standalone = Just True + , Widget.naked = Just True + , Widget.id = Just $ issueChartId issue + , Widget.wType = Widget.WTTimeseries + , Widget.query = Just $ query <> " | summarize count(*) by bin_auto(timestamp)" + , Widget._projectId = Just pid + , Widget.hideLegend = Just True + , Widget.hideSubtitle = Just True + } + | issue.issueType == Issues.ApiChange + , Just query <- [issueEventsQuery view] + ] eventsSection = - [ section "issue-events" "list-check" "All events" + [ section "issue-events" "list-check" (if issue.issueType == Issues.ApiChange then "Matching events" else "All events") $ div_ [class_ "max-md:px-1 px-2 flex flex-col max-h-[50vh]"] - $ virtualTable pid (Just ("/p/" <> pid.toText <> "/log_explorer/data?json=true&query=" <> toUriStr ("hashes[*]==\"" <> key <> "\"") <> TimePicker.rangeQuery tp)) Nothing + $ virtualTable pid (Just ("/p/" <> pid.toText <> "/log_explorer/data?json=true&query=" <> toUriStr query <> TimePicker.rangeQuery tp)) Nothing | not isLogPatternIssue - , Just key <- [issueHashKey issue] + , Just query <- [issueEventsQuery view] ] section = IssueSection Nothing [] evidence anchor glyph heading = pure . section anchor glyph heading . kvRows_ "max-md:px-3 px-4" . present - present = mapMaybe \(k, v) -> (k,) <$> mfilter (not . T.null . T.strip) v + present = mapMaybe \(k, v) -> (k,) <$> nonBlank v kvRows_ :: Text -> [(Text, Text)] -> Html () kvRows_ cls rows = dl_ [class_ $ "grid gap-y-0.5 font-mono text-xs " <> cls] $ forM_ rows \(k, val) -> div_ [class_ "flex gap-3 px-2 py-1 rounded odd:bg-fillWeaker min-w-0"] do dt_ [class_ "w-28 shrink-0 text-textWeak"] $ toHtml k @@ -1280,6 +1377,9 @@ eventCard_ IssueView{..} = div_ [class_ "surface-raised rounded-2xl overflow-cli runtimeM = errM >>= (.base.errorData.runtime) field :: (ErrorPatterns.ATError -> Maybe a) -> Maybe a field f = errM >>= f . (.base.errorData) + userContext = case replaySession of + Just (_, meta) | rows@(_ : _) <- present [("name", meta.userName), ("email", meta.userEmail), ("id", meta.userId)] -> rows + _ -> present [("name", field (.userName)), ("email", field (.userEmail)), ("id", field (.userId)), ("location", place), ("ip", field (.userIp)), ("tenant", field (.tenantName))] highlights = present [ ("handled", bool "no" "yes" <$> field (.handled)) @@ -1294,7 +1394,7 @@ eventCard_ IssueView{..} = div_ [class_ "surface-raised rounded-2xl overflow-cli contexts = filter (not . null . snd) - [ ("User", present [("id", field (.userId)), ("email", field (.userEmail)), ("name", field (.userName)), ("location", place), ("ip", field (.userIp)), ("tenant", field (.tenantName))]) + [ ("User", userContext) , ("Client", present [("browser", field (.browser)), ("os", field (.os)), ("device", field (.device)), ("user_agent", field (.userAgent))]) , ("Runtime", present [("runtime", runtimeM), ("service", field (.serviceName) <|> issue.service), ("release", field (.release)), ("thread", field (.threadName) <|> field (.threadId)), ("mechanism", display <$> field (.mechanism))]) , ("Trace", present [("trace.id", fst <$> traceRef), ("span.id", field (.spanId)), ("parent_span.id", field (.parentSpanId)), ("session.id", field (.sessionId))]) @@ -1456,61 +1556,92 @@ eventCard_ IssueView{..} = div_ [class_ "surface-raised rounded-2xl overflow-cli Just (Issues.ApiChangeP d) | Just (apiChanges, apiSchema) <- apiEvidence -> let snapshots = [(zonedTimeToUTC a.createdAt, change) | a <- apiChanges, change <- V.toList $ getAeson a.fieldEvidence] - snapshotCell :: Maybe ApiChanges.FieldSnapshot -> Html () - snapshotCell Nothing = span_ [class_ "text-textWeak"] "Not previously observed" - snapshotCell (Just snapshot) = do - div_ [class_ "font-mono text-xs break-words"] $ toHtml $ T.intercalate ", " $ Relude.sort $ (.toText) <$> HS.toList snapshot.structure.types - unless (HS.null snapshot.structure.formats) - $ div_ [class_ "text-xs text-textWeak break-words"] + snapshotCell :: Bool -> Bool -> Maybe ApiChanges.FieldSnapshot -> Html () + snapshotCell _ _ Nothing = span_ [class_ "text-textWeak"] "Not previously observed" + snapshotCell typeChanged formatChanged (Just snapshot) = do + div_ [class_ $ "font-mono text-xs break-words " <> bool "text-textWeak" "text-textStrong font-medium" typeChanged] $ toHtml - $ "Formats: " - <> T.intercalate ", " (Relude.sort $ HS.toList snapshot.structure.formats) + $ T.intercalate ", " + $ Relude.sort + $ (.toText) + <$> HS.toList snapshot.structure.types + when (formatChanged || not (HS.null snapshot.structure.formats)) $ div_ [class_ "text-xs text-textWeak break-words"] do + "Inferred format: " + span_ [class_ $ bool "text-textWeak" "text-textStrong font-medium" formatChanged] + $ toHtml + $ if HS.null snapshot.structure.formats then "None inferred" else T.intercalate ", " (Relude.sort $ map (T.dropAround (`elem` ['{', '}'])) $ HS.toList snapshot.structure.formats) unless (V.null snapshot.examples) do - let samples values = pre_ [class_ "mt-1 text-xs font-mono whitespace-pre-wrap break-all"] $ toHtml (decodeUtf8 (AE.encode values) :: Text) + div_ [class_ "mt-2 text-2xs text-textWeak"] "Sample values" + let samples values = div_ [class_ "mt-1 space-y-1"] $ forM_ values $ \value -> + pre_ [class_ "text-xs font-mono whitespace-pre-wrap break-normal [overflow-wrap:anywhere]"] $ case value of + AE.String text -> slashBreaks_ text + _ -> toHtml $ decodeUtf8 @Text (AE.encode value) samples (V.take 3 snapshot.examples) when (V.length snapshot.examples > 3) $ details_ do summary_ [class_ "cursor-pointer text-xs text-textBrand py-1"] $ toHtml $ "Show " <> show (V.length snapshot.examples - 3) <> " more sample values" samples (V.drop 3 snapshot.examples) + -- One tbody per detection time, headed by that time. + detectedBatches :: [(Maybe UTCTime, a)] -> (a -> Html ()) -> Html () + detectedBatches rows row = forM_ (NE.groupAllWith fst rows) \batch@((timestamp, _) :| _) -> tbody_ do + tr_ + $ th_ [scope_ "rowgroup", colspan_ "4", class_ "px-2 py-2 text-xs font-normal text-textWeak bg-fillWeaker/40 border-t border-strokeWeak"] + $ case timestamp of + Nothing -> "Detection time not recorded" + Just at -> do + "Detected " + time_ [datetime_ $ isoT at] $ toHtml $ fmtDate "%b %-e, %H:%M:%S UTC" at + traverse_ (row . snd) batch kindOf change = bool ApiChanges.Modified ApiChanges.Added (isNothing change.before) legacyFields = [(kind, path) | (kind, paths) <- [(ApiChanges.Added, d.newFields), (ApiChanges.Removed, d.deletedFields), (ApiChanges.Modified, d.modifiedFields)], path <- V.toList paths, (kind, path) `notElem` [(kindOf c, c.path) | (_, c) <- snapshots]] in [ section "issue-fields" "list-check" "Field changes" $ if Issues.hasFieldDrift d then div_ [class_ "max-md:px-3 px-4 space-y-3"] do - p_ [class_ "text-xs text-textWeak"] "Before and after show the types, formats and sample values observed at detection time." - div_ [class_ "overflow-x-auto"] $ table_ [class_ "w-full min-w-[48rem] text-left text-sm"] do - thead_ $ tr_ $ forM_ (["Field", "Change", "Before", "After", "Detected"] :: [Text]) $ th_ [scope_ "col", class_ "p-2 font-medium text-textWeak"] . toHtml - tbody_ do - forM_ (sortWith fst snapshots) \(detectedAt, change) -> tr_ [class_ "border-t border-strokeWeak align-top"] do - th_ [scope_ "row", class_ "p-2 font-mono text-xs font-normal break-all"] $ toHtml change.path - td_ [class_ "p-2"] $ toHtml $ show @Text $ kindOf change - td_ [class_ "p-2 min-w-40"] $ snapshotCell change.before - td_ [class_ "p-2 min-w-40"] $ snapshotCell (Just change.after) - td_ [class_ "p-2 text-xs whitespace-nowrap"] $ time_ [datetime_ $ isoT detectedAt] $ toHtml $ isoT detectedAt - forM_ legacyFields \(kind, path) -> tr_ [class_ "border-t border-strokeWeak align-top"] do - th_ [scope_ "row", class_ "p-2 font-mono text-xs font-normal break-all"] $ toHtml path - td_ [class_ "p-2"] $ toHtml $ show @Text kind - td_ [class_ "p-2 text-xs text-textWeak"] "Historical types and values were not captured for this change." - td_ [class_ "p-2 min-w-40"] $ case apiSchema >>= ApiChanges.fieldSnapshot path of - Nothing -> span_ [class_ "text-xs text-textWeak"] "No current samples available" - Just current -> do - div_ [class_ "text-xs text-textWeak mb-1"] "Current observations" - snapshotCell (Just current) - td_ [class_ "p-2 text-xs whitespace-nowrap"] - $ maybe "Not recorded" (toHtml . isoT) - $ listToMaybe - $ Relude.sort - [ zonedTimeToUTC a.createdAt - | a <- apiChanges - , path `V.elem` case kind of - ApiChanges.Added -> a.newFields - ApiChanges.Modified -> a.modifiedFields - ApiChanges.Removed -> V.empty - ] + p_ [class_ "text-xs text-textWeak"] "Formats are inferred from sample values and may be inaccurate." + div_ [class_ "overflow-x-auto"] $ table_ [class_ "w-full min-w-[40rem] table-fixed text-left text-sm"] do + colgroup_ do + col_ [class_ "w-[22%]"] + col_ [class_ "w-[14%]"] + col_ [class_ "w-[32%]"] + col_ [class_ "w-[32%]"] + thead_ $ tr_ $ forM_ (["Field", "Change", "Before", "After"] :: [Text]) $ th_ [scope_ "col", class_ "p-2 font-medium text-textWeak"] . toHtml + detectedBatches (first Just <$> snapshots) \change -> tr_ [class_ "border-t border-strokeWeak align-top"] do + let typeChanged = maybe True ((/= change.after.structure.types) . (.structure.types)) change.before + formatChanged = maybe True ((/= change.after.structure.formats) . (.structure.formats)) change.before + th_ [scope_ "row", class_ "p-2 font-mono text-xs font-normal break-normal [overflow-wrap:anywhere]"] $ toHtml change.path + td_ [class_ "p-2 text-xs text-textWeak break-words"] $ toHtml $ case change.before of + Just _ | not typeChanged && formatChanged -> "Format changed" + _ -> show @Text $ kindOf change + td_ [class_ "p-2"] $ snapshotCell typeChanged formatChanged change.before + td_ [class_ "p-2"] $ snapshotCell typeChanged formatChanged (Just change.after) + let legacyRows = + [ ( viaNonEmpty + minimum1 + [ zonedTimeToUTC a.createdAt + | a <- apiChanges + , path `V.elem` case kind of + ApiChanges.Added -> a.newFields + ApiChanges.Modified -> a.modifiedFields + ApiChanges.Removed -> V.empty + ] + , (kind, path) + ) + | (kind, path) <- legacyFields + ] + detectedBatches legacyRows \(kind, path) -> tr_ [class_ "border-t border-strokeWeak align-top"] do + th_ [scope_ "row", class_ "p-2 font-mono text-xs font-normal break-normal [overflow-wrap:anywhere]"] $ toHtml path + td_ [class_ "p-2 text-xs text-textWeak break-words"] $ toHtml $ show @Text kind + td_ [class_ "p-2 text-xs text-textWeak"] "Historical types and values were not captured for this change." + td_ [class_ "p-2"] $ case apiSchema >>= ApiChanges.fieldSnapshot path of + Nothing -> span_ [class_ "text-xs text-textWeak"] "No current samples available" + Just current -> do + div_ [class_ "text-xs text-textWeak mb-1"] "Current observations" + snapshotCell False False (Just current) else - emptyState_ - def{icon = Just "rocket", size = ESCompact} - "New endpoint discovered" - "This endpoint started receiving traffic. Inspect the originating request in the Trace section to see headers, body, and call site." + let (heading, message) = case schemaSubjectFor view of + Just (ApiChanges.SpanSchema _) -> ("Span schema observed", "Matching events below show the recorded spans.") + Just (ApiChanges.EndpointSchema _) -> ("New endpoint discovered", "This endpoint started receiving traffic. Matching events below show its recorded requests.") + Nothing -> ("Schema observed", "Source identity was not recorded for this observation.") + in emptyState_ def{icon = Just "list-check", size = ESCompact} heading message ] -- The log-pattern types differ only in their chip row, which the header owns. patternSections sourceField logPattern sampleMessage = @@ -1573,7 +1704,10 @@ eventCard_ IssueView{..} = div_ [class_ "surface-raised rounded-2xl overflow-cli ] -- A query alert is a threshold crossing on an aggregate — no originating request, -- so no trace-scoped logs (and 'traceRef' is always Nothing, so no Trace either). - logsSection = [logs | issue.issueType /= Issues.QueryAlert] + logsSection + | issue.issueType == Issues.ApiChange && isNothing traceRef = + [section "issue-logs" "list-view" "Related logs" $ p_ [class_ "px-4 text-sm text-textWeak"] "Related logs are unavailable because this observation has no recorded trace."] + | otherwise = [logs | issue.issueType /= Issues.QueryAlert] where -- A trace happens at an instant, so trace- and service-scoped reads get a -- +/-5min window rather than the page's range: 0.37s for the same 14 rows @@ -1598,17 +1732,20 @@ eventCard_ IssueView{..} = div_ [class_ "surface-raised rounded-2xl overflow-cli div_ [id_ "log-content", class_ "max-md:px-1 px-2 flex flex-col lg:flex-row w-full lg:max-h-[70vh]"] do div_ [class_ "grow min-w-0 min-h-0 flex flex-col"] $ virtualTable pid (Just ("/p/" <> pid.toText <> "/log_explorer/data?json=true&query=" <> toUriStr logsQuery <> logsParams)) Nothing - -- Starts hidden alongside the collapsed pane; the swap handler reveals - -- both together, and closeDetailPanel puts them back. - div_ [class_ "transition-opacity duration-200 mx-1 hidden lg:block opacity-0 pointer-events-none", id_ "resizer-details_width-wrapper"] $ resizer_ "log_details_container" "details_width" False - LogItem.detailsPanel_ pid Nothing LogItem.IssuesPanel + replaySection = [ section "replay-section" "video" "Session replay" $ termRaw "session-replay" [id_ "sessionReplay", term "initialSession" sessionId, term "consoleOpen" "true", term "fullWidth" "true", class_ "block w-full", term "projectId" pid.toText, term "containerId" "sessionPlayerWrapper"] ("" :: Text) - | Just sessionId <- [replaySession] + | Just (sessionId, _) <- [replaySession] ] +-- | A button that opens the AI panel; @opener@ is where closing returns focus. +aiPanelToggleAttrs, aiPanelOpenerAttrs :: [Attribute] +aiPanelToggleAttrs = [type_ "button", Aria.controls_ "ai_chat_container", term "aria-expanded" "false", term "hx-live:aria-expanded" "q('#ai-panel-toggle').checked ? 'true' : 'false'"] +aiPanelOpenerAttrs = aiPanelToggleAttrs <> [[__|on click set #ai-panel-toggle's opener to me then set #ai-panel-toggle's checked to true then send change to #ai-panel-toggle then call (#ai-chat-input).focus({preventScroll: true})|]] + + -- | Collapsible AI chat, open-state in localStorage and driven by a checkbox + -- group-has variants so it survives htmx swaps. aiSidePanel_ :: Projects.ProjectId -> Issues.IssueId -> Html () @@ -1627,7 +1764,13 @@ aiSidePanel_ pid issueId = do if my.checked trigger 'load-chat' on #ai-response-container end end|] ] - label_ [Lucid.for_ "ai-panel-toggle", class_ "absolute right-0 top-3 z-10 flex items-center gap-1.5 bg-fillBrand-strong text-white px-2 py-2.5 rounded-l-lg cursor-pointer shadow-md hover:opacity-90 transition-opacity group-has-[#ai-panel-toggle:checked]/ai:hidden", Aria.label_ "Open AI Assistant"] + button_ + ( [ id_ "issue-ai-launcher" + , class_ "absolute right-0 top-3 z-10 flex items-center gap-1.5 bg-fillBrand-strong text-white px-2 py-2.5 rounded-l-lg cursor-pointer shadow-md hover:opacity-90 transition-opacity group-has-[#ai-panel-toggle:checked]/ai:hidden" + , Aria.label_ "Open AI Assistant" + ] + <> aiPanelOpenerAttrs + ) $ faSprite_ "sparkles" "regular" "w-3.5 h-3.5" div_ [class_ "hidden group-has-[#ai-panel-toggle:checked]/ai:block"] $ resizer_ "ai_chat_container" "ai_width" False div_ [id_ "ai_chat_container", class_ "hidden group-has-[#ai-panel-toggle:checked]/ai:flex w-[420px] shrink-0 h-full overflow-hidden flex-col bg-bgBase border-l border-t border-strokeWeak"] do @@ -1635,7 +1778,13 @@ aiSidePanel_ pid issueId = do div_ [class_ "flex items-center gap-2"] do faSprite_ "sparkles" "regular" "w-3.5 h-3.5 text-fillBrand-strong" sectionLabel_ "AI Assistant" - label_ [Lucid.for_ "ai-panel-toggle", class_ "p-1.5 rounded-lg hover:bg-fillWeaker cursor-pointer transition-colors tap-target", Aria.label_ "Close AI Assistant"] + button_ + [ type_ "button" + , class_ "p-1.5 rounded-lg hover:bg-fillWeaker cursor-pointer transition-colors tap-target" + , Aria.label_ "Close AI Assistant" + , Aria.controls_ "ai_chat_container" + , [__|on click set #ai-panel-toggle's checked to false then send change to #ai-panel-toggle then if #ai-panel-toggle's opener call (#ai-panel-toggle).opener.focus({preventScroll: true}) else call (#issue-ai-launcher).focus({preventScroll: true}) end|] + ] $ faSprite_ "xmark" "regular" "w-3 h-3 text-textWeak" let baseUrl = "/p/" <> pid.toText <> "/issues/" <> issueId.toText div_ @@ -2255,6 +2404,26 @@ issueListGetH pid filterTM sortM _since pageM perPageM loadM periodM serviceFilt (Hasql.interp [HI.sql| SELECT DISTINCT issue_type::text FROM apis.issues WHERE project_id = #{pid} |]) ) + -- Recover source identity for issues written before subjects were stored. + schemas <- SchemaCatalog.getByKeysBatch $ V.fromList [(pid, row.base.targetHash) | row <- issues, row.base.issueType == Issues.ApiChange] + let withSchema row = case (apiChangeData row.base, HM.lookup (pid, row.base.targetHash) schemas) of + (Just d, Just entry) -> + row + & Optics.field @"base" + %~ \base -> + base + { Issues.service = entry.scope.service <|> base.service + , Issues.issueData = + Aeson + $ AE.toJSON + d + { Issues.subject = Just $ ApiChanges.schemaSubject entry.template.keyKind entry.scope + , Issues.endpointMethod = fromMaybe d.endpointMethod entry.scope.method + , Issues.endpointPath = fromMaybe d.endpointPath entry.scope.urlPath + , Issues.endpointHost = fromMaybe d.endpointHost entry.scope.host + } + } + _ -> row let listQuery types = "filter=" <> currentFilterTab <> "&sort=" <> currentSort <> "&period=" <> period <> foldMap ("&service=" <>) serviceFilters <> foldMap ("&type=" <>) types listUrl = (("/p/" <> pid.toText <> "/issues?") <>) . listQuery baseUrl = listUrl typeFilters @@ -2268,7 +2437,7 @@ issueListGetH pid filterTM sortM _since pageM perPageM loadM periodM serviceFilt } serviceMenu = multiSelectFilter "Service" "service" serviceFilters availableServices typeMenu = multiSelectFilter "Type" "type" typeFilters availableTypes - issuesVM = V.fromList $ map (IssueVM currTime period) issues + issuesVM = V.fromList $ map (IssueVM currTime . withSchema) issues tableActions = TableHeaderActions { baseUrl @@ -2278,7 +2447,7 @@ issueListGetH pid filterTM sortM _since pageM perPageM loadM periodM serviceFilt , ("Oldest", "Oldest issues first", "+created_at") , ("Recently Updated", "Most recently updated", "-updated_at") , ("Recently Active", "Most recently seen", "-last_seen") - , ("Most events", "Most events in the period", "-event_count") + , ("Highest count", "Counts use the time range shown in each row", "-event_count") , ("Most users", "Most distinct users affected", "-users_count") , ("Name (A-Z)", "Sort alphabetically", "+title") , ("Name (Z-A)", "Sort reverse alphabetically", "-title") @@ -2351,7 +2520,12 @@ issueListGetH pid filterTM sortM _since pageM perPageM loadM periodM serviceFilt else TablePage $ PageCtx bwconf issuesTable where apiChangeGroup :: IssueVM -> Maybe Text - apiChangeGroup (IssueVM _ _ issue) = (\d -> foldMap (<> " · ") issue.base.service <> d.endpointHost <> " · " <> bool "Incremental API changes" "Breaking API changes" issue.base.critical) <$> apiChangeData issue.base + apiChangeGroup (IssueVM _ issue) = do + d <- apiChangeData issue.base + let label = case d.subject of + Just (ApiChanges.SpanSchema _) -> "Span schema changes" + _ -> "API changes" + pure $ label <> " · " <> maybe "Source unavailable" snd (issueSource issue.base) -- Inbox additionally hides severity='low' so demoted silent drops don't clutter it. tabIssueFilters :: IssueTab -> Issues.IssueFilters @@ -2445,7 +2619,7 @@ issueZeroState pid = \case issueRowAttrs :: IssueVM -> [Attribute] -issueRowAttrs (IssueVM _ _ issue) = class_ ("group/row hover:bg-fillWeaker " <> bg) : sty +issueRowAttrs (IssueVM _ issue) = class_ ("group/row hover:bg-fillWeaker " <> bg) : sty where -- Matched on the constructor, not on @display@: severity is typed everywhere -- else on this page, and a Text round-trip would drop both tints silently if a @@ -2461,8 +2635,25 @@ apiChangeData :: Issues.Issue -> Maybe Issues.APIChangeData apiChangeData issue = Issues.issuePayload issue >>= preview (_Ctor @"ApiChangeP") +-- API-change ownership is the monitored host; telemetry scopes still use the recorded service. +issueSource :: Issues.Issue -> Maybe (Text, Text) +issueSource issue = case apiChangeData issue of + Just d | Just (ApiChanges.SpanSchema scope) <- d.subject -> ("Service",) <$> (scope.service <|> issue.service) + Just d | Just host <- Issues.knownHost d -> Just ("Host", host) + _ -> ("Service",) <$> nonBlank issue.service + + +nonBlank :: Maybe Text -> Maybe Text +nonBlank = mfilter (not . T.null . T.strip) + + +-- | A @@ after each @/@ so long paths can wrap. +slashBreaks_ :: Text -> Html () +slashBreaks_ = sequence_ . intersperse (toHtml @Text "/" >> wbr_ []) . map toHtml . T.splitOn "/" + + issueRowId :: IssueVM -> Text -issueRowId (IssueVM _ _ issue) = issue.base.id.toText +issueRowId (IssueVM _ issue) = issue.base.id.toText -- | (icon, colorClass, tooltip) — uses shape+color so status isn't color-only. @@ -2483,29 +2674,37 @@ anomalyStatusIndicator issue active = ("circle-exclamation", "text-iconNeutral", "Active") -data IssueVM = IssueVM UTCTime Text Issues.IssueL +data IssueVM = IssueVM UTCTime Issues.IssueL deriving stock (Show) issueColumns :: Projects.ProjectId -> Text -> Map.Map Projects.UserId Text -> Maybe (Html ()) -> [Column IssueVM] issueColumns pid period names toggleM = [ col "Issue" renderIssueMainCol & withAttrs [class_ "min-w-0 max-w-0 w-full"] - , col "Last seen" (\(IssueVM now _ issue) -> lastSeenCell_ now (Just issue.lastSeen)) & withAttrs [class_ "w-24 max-md:hidden"] + , col "Last seen" (\(IssueVM now issue) -> lastSeenCell_ now (Just issue.lastSeen)) & withAttrs [class_ "w-24 max-md:hidden"] , col "Activity" activityCol & withAttrs [class_ "w-40 max-md:hidden"] & maybe identity withColHeaderExtra toggleM - , col ("Events (" <> period <> ")") (\(IssueVM _ _ issue) -> eventsCountCell_ issue.eventCount) & withAttrs [class_ "w-24 max-md:hidden"] + , col "Count" countCol & withAttrs [class_ "w-36 min-w-36 max-md:hidden"] , col "Users" usersCol & withAttrs [class_ "w-16 max-md:hidden"] ] where - usersCol (IssueVM _ _ issue) = span_ [class_ $ "tabular-nums text-sm " <> bool "text-textStrong" "text-textWeak" (issue.usersCount == 0)] $ toHtml $ bool (formatWithCommas (fromIntegral issue.usersCount :: Double)) "\x2014" (issue.usersCount == 0) - activityCol (IssueVM _ _ issue) = sparkline_ $ V.toList issue.activityBuckets - renderIssueMainCol (IssueVM currTime countPeriod issue) = do + countContext issue = + ( if issue.base.issueType == Issues.ApiChange then "detection" else "event" + , if issue.base.issueType `elem` [Issues.RuntimeException, Issues.LogPattern, Issues.LogPatternRateChange] then period else "all time" + ) + countCol (IssueVM _ issue) = do + let (noun, scope) = countContext issue + eventsCountCell_ issue.eventCount + span_ [class_ "block text-2xs text-textWeak whitespace-nowrap"] $ toHtml $ noun <> (if issue.eventCount == 1 then "" else "s") <> " · " <> scope + usersCol (IssueVM _ issue) = span_ [class_ $ "tabular-nums text-sm " <> bool "text-textStrong" "text-textWeak" (issue.usersCount == 0)] $ toHtml $ bool (formatWithCommas (fromIntegral issue.usersCount :: Double)) "\x2014" (issue.usersCount == 0) + activityCol (IssueVM _ issue) = sparkline_ $ V.toList issue.activityBuckets + renderIssueMainCol (IssueVM currTime issue) = do let b = issue.base isAcknowledged = isJust b.acknowledgedAt isArchived = isJust b.archivedAt (icon, iconColor, tooltip) = anomalyStatusIndicator b issueUrl = "/p/" <> pid.toText <> "/issues/" <> b.id.toText stateBadges = do - severityBadge_ b.severity + issuePriorityBadge_ b issueStateBadge_ issue.latestStateEvent -- Silence has an end, and the list is where you need to see it without opening anything. whenJust (zonedTimeToUTC <$> b.acknowledgedUntil <* b.acknowledgedAt) $ silenceBadge_ "Ack'd" "Acknowledged" currTime @@ -2527,7 +2726,7 @@ issueColumns pid period names toggleM = div_ [class_ "max-md:hidden"] $ issuePreview_ (Just currTime) issue div_ [class_ "hidden max-md:flex items-center justify-between text-xs text-textWeak"] do div_ [class_ "flex items-center gap-1.5"] do - span_ [class_ $ "tabular-nums" <> bool "" " font-medium text-textStrong" (issue.eventCount > 100)] $ toHtml $ countNoun issue.eventCount "event" <> " (" <> countPeriod <> ")" + span_ [class_ $ "tabular-nums" <> bool "" " font-medium text-textStrong" (issue.eventCount > 100)] $ toHtml $ let (noun, scope) = countContext issue in countNoun issue.eventCount noun <> " · " <> scope span_ [class_ "opacity-30"] "·" span_ [] $ toHtml $ agoText currTime $ zonedTimeToUTC b.createdAt div_ [class_ "flex items-center gap-3"] do @@ -2578,6 +2777,12 @@ renderSummaryText_ = traverse_ (summaryToken_ False) . summaryWords renderIssueTitle_ :: Issues.IssueL -> Html () renderIssueTitle_ Issues.IssueL{base} + | Just d <- apiChangeData base = + let sourceTitle = case d.subject of + Just (ApiChanges.SpanSchema scope) -> fromMaybe "Span schema observation" scope.spanName + _ | Just method <- Issues.knownMethod d -> method <> " " <> d.endpointPath + _ -> "Schema observation" + in span_ [class_ "font-mono", term "data-tippy-content" sourceTitle] $ toHtml sourceTitle | T.null title = "(Untitled)" | "⇒" `T.isInfixOf` title = renderSummaryText_ title | looksLikeRawPattern title = span_ [class_ "font-mono text-xs break-all"] $ renderWithPlaceholders_ title @@ -2606,11 +2811,18 @@ issueCardCompact_ pid now issue = do span_ [class_ $ "shrink-0 " <> iconColor, title_ tooltip, Aria.label_ tooltip] $ faSprite_ icon "regular" "w-3.5 h-3.5" span_ [class_ "text-xs text-textWeak shrink-0 tabular-nums"] $ toHtml $ "#" <> show b.seqNum span_ [class_ "text-sm font-medium text-textStrong truncate min-w-0"] $ renderIssueTitle_ issue - severityBadge_ b.severity + issuePriorityBadge_ b span_ [class_ "text-xs text-textWeak shrink-0 ml-auto"] $ toHtml $ agoText now $ zonedTimeToUTC b.createdAt issuePreview_ Nothing issue +issuePriorityBadge_ :: Issues.Issue -> Html () +issuePriorityBadge_ issue + | issue.issueType == Issues.ApiChange = + tonePill_ (case issue.severity of Issues.Critical -> ErrorBadge; Issues.Warning -> WarningBadge; Issues.Info -> NeutralBadge; Issues.Low -> NeutralBadge) $ "Priority: " <> T.toTitle (display issue.severity) + | otherwise = severityBadge_ issue.severity + + -- | Only Critical and Warning carry a badge; Info and Low are deliberately unbadged. -- -- Took 'Text' and matched @"critical"@/@"warning"@ with a fall-through, while all three @@ -2639,8 +2851,8 @@ issueStateBadge_ = \case -- | Type, service, age (when given the render clock) and a payload snippet on one line. issuePreview_ :: Maybe UTCTime -> Issues.IssueL -> Html () issuePreview_ nowM Issues.IssueL{base} = div_ [class_ "flex items-center gap-2 min-w-0 overflow-hidden text-xs text-textWeak"] do - issueTypeChip_ True base.issueType base.critical - whenJust base.service $ span_ [class_ "shrink-0", term "data-tippy-content" "Service"] . toHtml + issueTypeChip_ True base.issueType + whenJust (issueSource base) $ \(label, value) -> span_ [class_ "shrink-0", term "data-tippy-content" label] $ toHtml value whenJust nowM \now -> do let created = zonedTimeToUTC base.createdAt; age = agoText now created span_ [class_ "shrink-0 opacity-40"] "·" @@ -2659,7 +2871,11 @@ issuePreview_ nowM Issues.IssueL{base} = div_ [class_ "flex items-center gap-2 m Just (Issues.UptimeP d) -> previewSnippet $ d.url <> " \x2014 " <> d.reason Just (Issues.FrontendP d) -> previewSnippet $ d.element <> foldMap (" on " <>) d.pageUrl Just (Issues.ApiChangeP d) -> - previewSnippet $ d.endpointMethod <> " " <> d.endpointPath <> if T.null d.endpointHost then "" else " on " <> d.endpointHost + previewSnippet $ case [countNoun (V.length fs) "field" <> " " <> verb | (verb, fs) <- [("added", d.newFields), ("modified", d.modifiedFields), ("removed", d.deletedFields)], not (V.null fs)] of + [] -> case d.subject of + Just (ApiChanges.SpanSchema _) -> "Span schema observed" + _ -> "New endpoint observed" + changes -> T.intercalate " · " changes Nothing -> unparsablePayload_ previewSnippet txt = span_ [class_ "font-mono truncate min-w-0", term "data-tippy-content" txt] $ renderWithPlaceholders_ $ unescSummary txt logPatternPreview pat sampleMsg @@ -2726,8 +2942,8 @@ issueArchiveButton pid aid archived = div_ [id_ ctlId, class_ "inline-flex"] do -- | The issue's type as icon + label. @compact@ is the list\'s chip: tighter, -- abbreviated where the full label would not fit in a row, with the full text on -- hover. The detail header takes the roomier form. -issueTypeChip_ :: Bool -> Issues.IssueType -> Bool -> Html () -issueTypeChip_ compact issueType critical = +issueTypeChip_ :: Bool -> Issues.IssueType -> Html () +issueTypeChip_ compact issueType = span_ ( [class_ $ bool "flex items-center gap-1.5 text-xs font-medium " "flex items-center gap-1 text-2xs whitespace-nowrap " compact <> color] <> [term "data-tippy-content" fullTxt | compact] @@ -2747,8 +2963,7 @@ issueTypeChip_ compact issueType critical = Issues.Uptime -> ("text-fillError-strong", "heart-pulse", "Uptime") Issues.Cron -> ("text-fillError-strong", "clock", "Cron") Issues.Feedback -> ("text-fillBrand-strong", "comment", "Feedback") - Issues.ApiChange | critical -> ("text-fillError-strong", "exclamation-triangle", "Breaking") - Issues.ApiChange -> ("text-fillInformation-strong", "info", "Incremental") + Issues.ApiChange -> ("text-fillInformation-strong", "info", "Schema change") shortTxt = case issueType of Issues.LogPattern -> "Log" Issues.LogPatternRateChange -> "Rate" @@ -2806,9 +3021,9 @@ issueActivityGetH pid issueId traceIdM traceTsM = do links = [(url, fromMaybe url (lookupValueText m "title")) | a <- timeline, a.event == Issues.Lifecycle Issues.IELinked, Just m <- [a.metadata], Just url <- [lookupValueText m "url"]] issueUrl = "/p/" <> pid.toText <> "/issues/" <> issueId.toText addRespHeaders do - form_ [class_ "px-4 pb-3 flex flex-col gap-2", hxPost_ $ issueUrl <> "/comment", hxSwap_ "none"] do - textarea_ [name_ "body", required_ "", rows_ "2", placeholder_ "Add a comment\x2026", Aria.label_ "Comment", class_ "textarea textarea-sm w-full"] "" - button_ [type_ "submit", class_ "btn btn-xs btn-outline self-end"] "Comment" + form_ [class_ "mx-4 mb-3 p-2 rounded-lg border border-strokeWeak bg-fillWeaker/40 flex flex-col gap-2 focus-within:border-strokeBrand-strong", hxPost_ $ issueUrl <> "/comment", hxSwap_ "none"] do + textarea_ [name_ "body", required_ "", rows_ "2", placeholder_ "Add a comment\x2026", Aria.label_ "Comment", class_ "textarea textarea-ghost textarea-sm w-full min-h-16 border-0 bg-transparent shadow-none focus:outline-none text-base sm:text-sm"] "" + button_ [type_ "submit", class_ "btn btn-xs btn-ghost bg-fillWeak border-0 shadow-none self-end"] "Comment" unless (null links) $ div_ [class_ "px-4 pb-3 space-y-1"] do h4_ [class_ "text-2xs font-semibold text-textWeak uppercase tracking-wide"] "External links" forM_ links \(url, title) -> a_ [href_ url, target_ "_blank", rel_ "noopener", class_ "flex items-center gap-1.5 text-sm text-textBrand hover:underline truncate"] do @@ -2821,10 +3036,17 @@ issueActivityGetH pid issueId traceIdM traceTsM = do input_ [type_ "url", name_ "url", required_ "", placeholder_ "https://github.com/org/repo/issues/42", Aria.label_ "Issue URL", class_ "input input-sm w-full"] input_ [type_ "text", name_ "title", placeholder_ "Title (optional)", Aria.label_ "Link title", class_ "input input-sm w-full"] button_ [type_ "submit", class_ "btn btn-xs self-end"] "Link" - unless (null participants && null viewers) $ div_ [class_ "px-4 pb-3 space-y-1 text-xs text-textWeak"] do + unless (null participants && null viewers) $ div_ [class_ "px-4 pb-3 space-y-1 text-xs leading-relaxed text-textWeak break-words"] do h4_ [class_ "text-2xs font-semibold uppercase tracking-wide"] "People" - unless (null participants) $ p_ $ toHtml $ "Participating: " <> T.intercalate ", " (name <$> participants) - unless (null viewers) $ p_ $ toHtml $ "Viewed: " <> T.intercalate ", " (name <$> viewers) + details_ [class_ "group/people"] do + summary_ [class_ "flex items-center gap-2 cursor-pointer list-none [&::-webkit-details-marker]:hidden rounded focus-visible:outline-2 focus-visible:outline-offset-2"] do + span_ [class_ "flex -space-x-1"] $ forM_ (take 5 $ participants <> viewers) \uid -> + img_ [src_ $ "/api/avatar/" <> uid.toText, alt_ $ name uid, title_ $ name uid, loading_ "lazy", width_ "24", height_ "24", class_ "h-6 w-6 rounded-full bg-fillWeak outline outline-1 outline-black/10 dark:outline-white/10"] + span_ $ toHtml $ let n = length participants + length viewers in show n <> bool " people" " person" (n == 1) + faSprite_ "chevron-down" "regular" "w-3 h-3 group-open/people:rotate-180" + div_ [class_ "pt-2 space-y-1"] do + unless (null participants) $ p_ $ toHtml $ "Participating: " <> T.intercalate ", " (name <$> participants) + unless (null viewers) $ p_ $ toHtml $ "Viewed: " <> T.intercalate ", " (name <$> viewers) div_ [class_ "border-t border-strokeWeak"] do div_ [class_ "px-4 py-2 flex items-center gap-2 bg-fillWeaker/40"] do faSprite_ "circle-info" "regular" "w-3 h-3 text-textWeak" @@ -2839,7 +3061,7 @@ issueActivityTimeline_ userMap now activities | otherwise = div_ [class_ "p-4 flex flex-col gap-0"] $ forM_ activities \a -> do let (icon, color, label) = eventDisplay a.event actorText = foldMap (\uid -> foldMap (\u -> " by " <> CI.original u.email) $ Map.lookup uid userMap) a.createdBy - div_ [class_ "flex items-start gap-3 relative pl-4 pb-4 border-l-2 border-strokeWeak ml-2"] do + div_ [class_ "flex items-start gap-3 relative pl-4 pb-4 last:pb-0 border-l border-strokeWeak ml-2"] do div_ [class_ $ "absolute -left-[9px] top-0.5 w-4 h-4 rounded-full flex items-center justify-center " <> color] $ faSprite_ icon "regular" "w-2.5 h-2.5" div_ [class_ "flex flex-col gap-0.5 min-w-0"] do @@ -2961,20 +3183,27 @@ errorGroupMembersGetH pid errorId = do forM_ members \member -> do let memberId = UUID.toText member.id.unErrorPatternId unmergeUrl = "/p/" <> pid.toText <> "/issues/errors/" <> memberId <> "/unmerge" - div_ [class_ "flex items-center justify-between p-3 bg-fillWeaker rounded-lg", id_ $ "member-" <> memberId] do - div_ [class_ "flex flex-col gap-1 min-w-0"] do - span_ [class_ "text-sm font-medium text-textStrong truncate"] $ toHtml $ member.errorType <> ": " <> member.message - span_ [class_ "text-xs text-textWeak"] $ toHtml $ "Hash: " <> member.hash - button_ - [ class_ "btn btn-xs btn-ghost tap-target" - , Aria.label_ "Unmerge pattern" - , hxPost_ unmergeUrl - , hxTarget_ $ "#member-" <> memberId - , hxSwap_ "outerHTML" - ] - do - faSprite_ "code-branch" "regular" "w-3 h-3" - "Unmerge" + div_ [class_ "p-3 bg-fillWeaker rounded-lg space-y-2", id_ $ "member-" <> memberId] do + div_ [class_ "flex items-center justify-between gap-2"] do + span_ [class_ "text-xs font-medium text-textWeak min-w-0 break-words"] $ toHtml member.errorType + button_ + [ type_ "button" + , class_ "btn btn-xs btn-ghost tap-target shrink-0" + , Aria.label_ $ "Unmerge pattern " <> member.hash + , hxPost_ unmergeUrl + , hxSwap_ "none" + ] + do + faSprite_ "code-branch" "regular" "w-3 h-3" + "Unmerge" + details_ [class_ "group/pattern"] do + summary_ [class_ "cursor-pointer list-none [&::-webkit-details-marker]:hidden rounded focus-visible:outline-2 focus-visible:outline-offset-2"] do + span_ [class_ "text-sm text-textStrong break-normal [overflow-wrap:anywhere] line-clamp-2 group-open/pattern:hidden"] $ toHtml member.message + span_ [class_ "block mt-1 text-xs text-textBrand"] do + span_ [class_ "group-open/pattern:hidden"] "Read full message" + span_ [class_ "hidden group-open/pattern:inline"] "Show less" + p_ [class_ "mt-2 text-sm text-textStrong whitespace-pre-wrap break-normal [overflow-wrap:anywhere]"] $ toHtml member.message + span_ [class_ "block font-mono text-2xs text-textWeak"] $ toHtml $ "Hash: " <> member.hash errorUnmergePostH :: Projects.ProjectId -> UUID.UUID -> ATAuthCtx (RespHeaders (Html ())) @@ -2982,4 +3211,5 @@ errorUnmergePostH pid errorId = do _ <- Projects.sessionAndProject pid void $ PatternMerge.unmergePattern pid (ErrorPatternId errorId) addSuccessToast "Pattern unmerged" Nothing - addRespHeaders $ div_ [class_ "p-3 bg-fillSuccess-weak rounded-lg text-sm text-fillSuccess-strong"] "Pattern unmerged successfully" + addTriggerEvent "issuePatternGroupChanged" AE.Null + addRespHeaders mempty diff --git a/src/Pages/LogExplorer/Log.hs b/src/Pages/LogExplorer/Log.hs index 53be42433..c4ff22c17 100644 --- a/src/Pages/LogExplorer/Log.hs +++ b/src/Pages/LogExplorer/Log.hs @@ -787,6 +787,7 @@ apiLogH pid queryM' cols' sinceM fromM toM sourceM targetSpansM targetEventM sho let bwconf = bw { pageTitle = "Explorer" + , pageProvidesLogDetails = True , docsLink = Just "https://monoscope.tech/docs/dashboard/dashboard-pages/api-log-explorer/" , freeTierStatus = freeTierStatus , headContent = Nothing @@ -1548,7 +1549,7 @@ apiLogsPage page = do <> ", {headers: {Accept: \"application/json\"}, credentials: \"include\"}).then(r => r.json()); window.logDataPromise = load().catch(load);}" sectionWrapper_ do template_ [id_ "trace-loading-skeleton"] traceLoadingSkeleton_ - div_ [class_ "fixed z-[9999] hidden right-0 w-max h-max border border-strokeWeak rounded top-32 bg-bgBase shadow-2xl", id_ "sessionPlayerWrapper"] do + div_ [class_ "fixed z-10030 hidden right-4 w-max h-max rounded-2xl top-32 border-2 border-strokeStrong p-0.5 bg-bgRaised shadow-lg [&_#replayerOuterContainer]:shadow-none", id_ "sessionPlayerWrapper"] do termRaw "session-replay" [id_ "sessionReplay", class_ "shrink-1 flex flex-col", term "projectId" pidTxt, term "containerId" "sessionPlayerWrapper"] ("" :: Text) queryControlsSection facetsAndLogListSection diff --git a/src/Pages/LogExplorer/LogItem.hs b/src/Pages/LogExplorer/LogItem.hs index d5daaaac4..45e9f9b9b 100644 --- a/src/Pages/LogExplorer/LogItem.hs +++ b/src/Pages/LogExplorer/LogItem.hs @@ -204,7 +204,7 @@ detailsPanel_ pid targetEventM layout = div_ [class_ $ "contents group/details " $ label_ [ Lucid.for_ "details-open" , Aria.label_ "Close item details" - , class_ "fixed inset-0 z-40 bg-transparent pointer-events-none max-md:bg-black/40 max-md:pointer-events-auto hidden group-has-[#details-open:checked]/details:block" + , class_ "fixed inset-0 z-10010 bg-transparent pointer-events-none max-md:bg-black/40 max-md:pointer-events-auto hidden group-has-[#details-open:checked]/details:block" ] "" div_ @@ -212,7 +212,7 @@ detailsPanel_ pid targetEventM layout = div_ [class_ $ "contents group/details " $ memptyIfFalse (layout == IssuesPanel) "peer-checked/open:max-w-full! max-lg:peer-checked/open:w-full! " <> "details-panel grow-0 relative shrink-0 overflow-y-auto overflow-x-hidden h-full c-scroll w-0 max-w-0 overflow-hidden " <> "group-has-[#viz-logs:checked]/pg:max-w-full group-has-[#viz-logs:checked]/pg:overflow-y-auto group-has-[#viz-sessions:checked]/pg:max-w-full group-has-[#viz-sessions:checked]/pg:overflow-y-auto " - <> "max-md:hidden max-md:[&.details-open]:block! max-md:[&.details-open]:fixed max-md:[&.details-open]:inset-0 max-md:[&.details-open]:z-40 max-md:[&.details-open]:w-full max-md:[&.details-open]:max-w-full max-md:[&.details-open]:bg-bgBase " + <> "max-md:hidden max-md:[&.details-open]:block! max-md:[&.details-open]:fixed max-md:[&.details-open]:inset-0 max-md:[&.details-open]:z-10020 max-md:[&.details-open]:w-full max-md:[&.details-open]:max-w-full max-md:[&.details-open]:bg-bgBase " -- Drawer geometry. `!` on width/max-width beats the inline style the -- resizer leaves behind when the reader switches modes mid-session. -- @@ -220,7 +220,7 @@ detailsPanel_ pid targetEventM layout = div_ [class_ $ "contents group/details " -- containing block for every `position: fixed` descendant, which is what put the -- Share-link modal (fixed inset-0, meant to centre on the viewport) half off the -- screen when it opened inside the drawer. - <> "peer-checked/drawer:fixed peer-checked/drawer:top-0 peer-checked/drawer:bottom-0 peer-checked/drawer:z-50 peer-checked/drawer:h-full peer-checked/drawer:w-[min(56rem,94vw)]! peer-checked/drawer:max-w-full! peer-checked/drawer:bg-bgBase peer-checked/drawer:border-l peer-checked/drawer:border-strokeWeak peer-checked/drawer:shadow-2xl peer-checked/drawer:overflow-y-auto peer-checked/drawer:transition-[right] peer-checked/drawer:right-[-100vw] " + <> "peer-checked/drawer:fixed peer-checked/drawer:top-0 peer-checked/drawer:bottom-0 peer-checked/drawer:z-10020 peer-checked/drawer:h-full peer-checked/drawer:w-[min(56rem,94vw)]! peer-checked/drawer:max-w-full! peer-checked/drawer:bg-bgBase peer-checked/drawer:border-l peer-checked/drawer:border-strokeWeak peer-checked/drawer:shadow-2xl peer-checked/drawer:overflow-y-auto peer-checked/drawer:transition-[right] peer-checked/drawer:right-[-100vw] " -- Open state. Inline mode never positions the panel, so this is inert there. <> "peer-checked/open:right-0! peer-checked/open:block!" , data_ "inline-width" (if layout == IssuesPanel then "33.333333%" else "") diff --git a/src/Pages/Monitors.hs b/src/Pages/Monitors.hs index 36897d582..069363cf0 100644 --- a/src/Pages/Monitors.hs +++ b/src/Pages/Monitors.hs @@ -363,7 +363,7 @@ notificationSettingsSection_ allTeams selectedTeamIds formId monitorM = do stopEnabled = maybe False (isJust . (.stopAfterCount)) monitorM stopVal = maybe "5" show $ monitorM >>= (.stopAfterCount) panel_ (Collapsible False) def{icon = Just "envelope"} "Notification Settings" do - formField_ FieldSm def{hint = Just "@everyone includes all project members and project notification channels."} "Teams" (formId <> "-teams") False + formField_ FieldSm def{hint = Just "All project members and notification channels."} "Teams" (formId <> "-teams") False $ Just $ tagInput_ (formId <> "-teams") "" [name_ "teams", data_ "tagify-text-prop" "name", data_ "tagify-whitelist" teamList, data_ "tagify-initial" existingTeams, Aria.describedby_ (formId <> "-teams-hint")] details_ [class_ "mt-4 border-t border-strokeWeak pt-3"] do @@ -764,14 +764,15 @@ unifiedOverviewPage pid alert currTime teams = do div_ [class_ "max-md:hidden w-78 shrink-0"] $ alertSidebar_ display alert currTime -- Which tab is open is DOM state (radio), so no script is needed and it survives a morph. - div_ [role_ "tablist", class_ "w-full group/mt", id_ "monitor-tabs"] do - div_ [class_ "w-full flex border-b border-strokeWeak"] do + div_ [class_ "w-full group/mt", id_ "monitor-tabs"] do + fieldset_ [class_ "w-full min-w-0 flex border-b border-strokeWeak"] do + legend_ [class_ "sr-only"] "Monitor detail view" detailTab_ "monitor-tabs" "tab-exec-history" "shrink-0 font-medium text-textWeak" True "Execution History" detailTab_ "monitor-tabs" "tab-notif-channels" "shrink-0 font-medium text-textWeak" False "Notification Channels" - div_ [role_ "tabpanel", class_ "overflow-y-auto hidden group-has-[.tab-exec-history:checked]/mt:block"] + div_ [class_ "overflow-y-auto hidden group-has-[.tab-exec-history:checked]/mt:block"] $ div_ [class_ "mt-2 p-2 border border-strokeWeak rounded-lg overflow-x-auto flex flex-col max-h-[400px] max-md:max-h-[300px]"] $ termRaw "log-list" [id_ "resultTable", class_ "w-full divide-y shrink-1 flex flex-col h-full min-h-0 min-w-0 rr-block", term "windowTarget" "logList", term "projectId" pid.toText, term "initialFetchUrl" historyUrl] ("" :: Text) - div_ [role_ "tabpanel", class_ "overflow-y-auto hidden group-has-[.tab-notif-channels:checked]/mt:block"] $ alertNotificationsTab_ alert teams + div_ [class_ "overflow-y-auto hidden group-has-[.tab-notif-channels:checked]/mt:block"] $ alertNotificationsTab_ alert teams where display = maybe (MDStatus alert.currentStatus) (const MDDeactivated) alert.deactivatedAt historyUrl = "/p/" <> pid.toText <> "/log_explorer/data?json=true&query=" <> toUriStr ("kind==\"alert\" and parent_id==\"" <> alert.id.toText <> "\"") @@ -826,46 +827,51 @@ alertSidebar_ display alert currTime = do alertNotificationsTab_ :: Monitors.QueryMonitor -> V.Vector ManageMembers.Team -> Html () -alertNotificationsTab_ alert teams = do - div_ [class_ "pt-6 pb-3"] do - div_ [class_ "mb-6"] do - h4_ [class_ "text-base font-medium text-textStrong mb-2 flex items-center"] $ faSprite_ "users" "regular" "h-4 w-4 mr-2" >> "Teams" +alertNotificationsTab_ alert teams = + div_ [class_ "py-6 grid grid-cols-1 lg:grid-cols-[minmax(0,22rem)_minmax(0,1fr)] gap-6 items-start max-w-6xl"] do + section_ [Aria.labelledby_ "monitor-recipients-heading", class_ "min-w-0 space-y-3"] do + h3_ [id_ "monitor-recipients-heading", class_ "text-base font-medium text-textStrong flex items-center gap-2"] do + faSprite_ "users" "regular" "h-4 w-4" + "Recipients" if V.null teams - then do - div_ [class_ "text-sm text-textWeak"] "No teams configured for this monitor." - div_ [class_ "pt-2 flex items-center gap-1"] do - span_ [class_ "text-sm text-textWeak"] "Project level notification integrations will be used." - a_ [href_ $ "/p/" <> alert.projectId.toText <> "/settings/integrations", class_ "text-sm text-textBrand hover:underline"] "Configure integrations" - else div_ [class_ "flex flex-wrap gap-4 mb-4"] $ forM_ teams \team -> - div_ [class_ "flex flex-col border rounded-lg gap-4 border-strokeWeak p-6 relative w-96", id_ team.handle] do - unless team.is_everyone - $ button_ - [ type_ "button" - , class_ "absolute top-3 cursor-pointer right-3 text-iconNeutral hover:text-iconBrand transition-colors" - , Aria.label_ $ "Remove " <> team.name <> " team" - , term "data-tippy-content" "Remove team" - , hxDelete_ $ "/p/" <> alert.projectId.toText <> "/monitors/alerts/" <> alert.id.toText <> "/teams/" <> team.id.toText - , hxTarget_ $ "#" <> team.handle - , hxSwap_ "outerHTML" - ] - $ faSprite_ "trash" "regular" "h-3 w-3" - span_ [class_ "text-sm font-medium"] $ toHtml team.name - forM_ ([("envelope", "regular", team.notify_emails), ("slack", "solid", ("#" <>) <$> team.slack_channels), ("discord", "brand", ("#" <>) <$> team.discord_channels)] :: [(Text, Text, V.Vector Text)]) \(icon, style, entries) -> - forM_ entries \entry -> - div_ [class_ "flex items-center gap-2"] - $ span_ [class_ "text-sm text-textWeak"] - $ faSprite_ icon style "h-3 w-3 mr-2 text-iconNeutral" - >> toHtml entry - - div_ [class_ "pt-6 pb-3"] do - h4_ [class_ "font-medium text-textStrong mb-2"] "Notification Template" - div_ [class_ "rounded-lg py-2 space-y-2"] do - div_ [class_ "flex items-center gap-1"] do - span_ [class_ "text-sm font-medium text-textStrong"] "Subject: " - span_ [class_ "text-sm text-textWeak"] $ toHtml alert.alertConfig.subject - div_ [class_ "flex flex-col gap-1"] do - span_ [class_ "text-sm font-medium text-textStrong"] "Message" - p_ [class_ "text-sm text-textWeak mt-1"] $ toHtml alert.alertConfig.message + then div_ [class_ "rounded-xl border border-strokeWeak bg-bgRaised p-4 space-y-2"] do + p_ [class_ "text-sm text-textWeak"] "No teams configured for this monitor. Project notification integrations will be used." + a_ [href_ $ "/p/" <> alert.projectId.toText <> "/settings/integrations", class_ "text-sm text-textBrand hover:underline"] "Configure integrations" + else forM_ teams \team -> + article_ [class_ "rounded-xl border border-strokeWeak bg-bgRaised p-4 space-y-4 min-w-0", id_ team.handle] do + div_ [class_ "space-y-1"] do + div_ [class_ "flex items-center justify-between gap-2"] do + h4_ [class_ "text-sm font-semibold text-textStrong min-w-0 break-words"] $ toHtml team.name + unless team.is_everyone + $ button_ + [ type_ "button" + , class_ "btn btn-xs btn-ghost min-h-6 min-w-6 shrink-0 text-textWeak" + , Aria.label_ $ "Remove " <> team.name <> " team" + , term "data-tippy-content" "Remove team" + , hxDelete_ $ "/p/" <> alert.projectId.toText <> "/monitors/alerts/" <> alert.id.toText <> "/teams/" <> team.id.toText + , hxTarget_ $ "#" <> team.handle + , hxSwap_ "outerHTML" + ] + $ faSprite_ "trash" "regular" "h-3 w-3" + when team.is_everyone $ p_ [class_ "text-xs leading-relaxed text-textWeak"] "All project members and notification channels." + let destinations = filter (not . V.null . snd) [("Email", team.notify_emails), ("Slack", ("#" <>) <$> team.slack_channels), ("Discord", ("#" <>) <$> team.discord_channels)] :: [(Text, V.Vector Text)] + when (null destinations) $ p_ [class_ "text-sm text-textWeak"] "No destinations configured for this team." + forM_ destinations \(provider, entries) -> div_ [class_ "space-y-1.5"] do + h5_ [class_ "text-xs font-medium text-textWeak"] $ toHtml $ provider <> " (" <> show (V.length entries) <> ")" + ul_ [class_ "space-y-1 text-sm text-textStrong break-normal [overflow-wrap:anywhere]"] $ forM_ entries $ li_ . toHtml + section_ [Aria.labelledby_ "monitor-message-heading", class_ "min-w-0 space-y-3"] do + h3_ [id_ "monitor-message-heading", class_ "text-base font-medium text-textStrong"] "Message preview" + div_ [class_ "rounded-xl border border-strokeWeak bg-bgRaised p-4 space-y-4"] do + div_ [class_ "space-y-1"] do + h4_ [class_ "text-xs font-medium text-textWeak"] "Subject" + p_ [class_ "text-base font-semibold text-textStrong break-normal [overflow-wrap:anywhere] max-w-[65ch]"] + $ toHtml + $ if T.null (T.strip alert.alertConfig.subject) then "No subject configured" else alert.alertConfig.subject + div_ [class_ "space-y-1"] do + h4_ [class_ "text-xs font-medium text-textWeak"] "Message" + p_ [class_ "text-sm leading-relaxed text-textStrong whitespace-pre-wrap break-normal [overflow-wrap:anywhere] max-w-[65ch]"] + $ toHtml + $ if T.null (T.strip alert.alertConfig.message) then "No message configured" else alert.alertConfig.message -- | Uptime checks: URLs Monoscope probes on a schedule. They share the scrape-target diff --git a/src/Pages/Replay.hs b/src/Pages/Replay.hs index cf74f4788..ec2be0f1b 100644 --- a/src/Pages/Replay.hs +++ b/src/Pages/Replay.hs @@ -1,4 +1,4 @@ -module Pages.Replay (replayPostH, ReplayPost (..), processReplayEvents, replaySessionGetH, fetchReplaySession, ReplaySessionResp (..), RawJson (..), compressAndMergeReplaySessions, mergeReplaySession, expireOldReplayData, replayObjectPrefix, migratedReplayKey, concatRawJsonArrays, sessionFileKeys, splitReplayPayload, ReplayPayload (..), firstEventTimestampRaw, claimMergeLease, releaseMergeLease, ReplayManifest (..), ReplaySegment (..), replaySessionManifestGetH, replaySessionShardGetH, buildReplayManifest, fetchReplayShard, projectMinioConn) where +module Pages.Replay (SessionMeta (..), sessionMetadata, replayPostH, ReplayPost (..), processReplayEvents, replaySessionGetH, fetchReplaySession, ReplaySessionResp (..), RawJson (..), compressAndMergeReplaySessions, mergeReplaySession, expireOldReplayData, replayObjectPrefix, migratedReplayKey, concatRawJsonArrays, sessionFileKeys, splitReplayPayload, ReplayPayload (..), firstEventTimestampRaw, claimMergeLease, releaseMergeLease, ReplayManifest (..), ReplaySegment (..), replaySessionManifestGetH, replaySessionShardGetH, buildReplayManifest, fetchReplayShard, projectMinioConn) where import Codec.Compression.GZip qualified as GZip import Conduit (runConduit) diff --git a/src/Pages/Telemetry.hs b/src/Pages/Telemetry.hs index ab9f79946..8ee5e6d15 100644 --- a/src/Pages/Telemetry.hs +++ b/src/Pages/Telemetry.hs @@ -22,7 +22,9 @@ module Pages.Telemetry ( ) where import Data.Aeson qualified as AE +import Data.Char (isSpace) import Data.Default +import Data.List qualified as L import Data.Map qualified as Map import Data.Set qualified as S import Data.Text qualified as T @@ -189,18 +191,38 @@ resizeDivider_ cssVar minPct maxPct resizeEvt extraCls = if pct < $minT set pct to $minT end if pct > $maxT set pct to $maxT end call container.style.setProperty($qVar, pct + '%') + set @aria-valuenow to Math.round(pct) send $resizeEvt to window end set document.body.style.userSelect to '' set document.body.style.cursor to '' + on keydown[key is 'ArrowLeft' or key is 'ArrowRight'] + halt the event + set container to the closest parent + if no container exit end + set delta to -2 + if event.key is 'ArrowRight' set delta to 2 end + set pct to Math.max($minT, Math.min($maxT, (((my.offsetLeft + 4) / container.clientWidth) * 100) + delta)) + call container.style.setProperty($qVar, pct + '%') + set @aria-valuenow to Math.round(pct) + send $resizeEvt to window + on focus + set container to the closest parent + if container set @aria-valuenow to Math.round(((my.offsetLeft + 4) / container.clientWidth) * 100) end |] in div_ - [ class_ $ "absolute top-0 bottom-0 w-2 cursor-col-resize z-20 flex justify-center group " <> extraCls + [ class_ $ "absolute top-0 bottom-0 w-2 cursor-col-resize z-20 flex justify-center group focus-visible:outline-2 focus-visible:outline-strokeBrand-strong " <> extraCls , style_ $ "left:calc(var(" <> cssVar <> ") - 4px)" + , tabindex_ "0" + , role_ "separator" + , Aria.label_ "Resize trace columns" + , term "aria-orientation" "vertical" + , term "aria-valuemin" minT + , term "aria-valuemax" maxT , term "_" script ] $ div_ [class_ "w-px h-full bg-strokeWeak group-hover:bg-fillBrand-strong group-active:bg-fillBrand-strong transition-colors pointer-events-none relative"] do - div_ [class_ "absolute top-1/2 -translate-y-1/2 -translate-x-[3px] w-2 h-6 flex flex-col justify-center gap-px opacity-0 group-hover:opacity-100 transition-opacity"] do + div_ [class_ "absolute top-1/2 -translate-y-1/2 -translate-x-[3px] w-2 h-6 flex flex-col justify-center gap-px opacity-50 group-hover:opacity-100 group-focus-visible:opacity-100 transition-opacity"] do forM_ ([1 .. 3] :: [Int]) \_ -> div_ [class_ "w-full h-px bg-fillBrand-strong rounded-full"] pass @@ -229,11 +251,10 @@ instance ToHtml TraceDetailsGet where toHtml (TraceDetails pid tr spanRecs openFirst moreUrl) = do toHtml $ tracePage pid tr spanRecs moreUrl when openFirst $ whenJust (spanRecs V.!? 0) \sr -> - -- Desktop only: on mobile the trace panel is a full-screen overlay, so - -- auto-opening it would bury the page behind span details on load. + -- Preload only when details fit inline; a drawer must wait for a span click. -- KeepCurrent: the panel opens when content lands rather than flashing a -- skeleton, so a re-fired preload can't wipe rendered details back to a loader. - div_ (spanDetailAttrs_ KeepCurrent pid.toText sr.uSpanId sr.timestamp <> [hxTrigger_ "load[window.innerWidth>=768]", term "hx-sync" "this:replace"]) pass + div_ (spanDetailAttrs_ KeepCurrent pid.toText sr.uSpanId sr.timestamp <> [hxTrigger_ "load[document.getElementById('trace_span_container').clientWidth >= 64 * parseFloat(getComputedStyle(document.documentElement).fontSize)]", term "hx-sync" "this:replace"]) pass toHtml (SpanDetails pid s aptSpn) = toHtml $ LogItem.expandedItemView pid s aptSpn Nothing toHtml (TraceDetailsUnavailable selfUrl explorerUrl embedded reason) = -- The id is what Retry swaps: `closest div` would only replace the button row. @@ -1162,7 +1183,7 @@ tracePage pid traceItem rawSpanRecords moreUrl = do -- reports counts and durations only. Node size comes from the duration share. (traceHops, traceDurationNs) = ServiceGraph.traceEdgeSamples spanRecords traceGraph = ServiceGraph.buildServiceGraph 0 serviceMapNodeCap ServiceGraph.CollapseOff (Just traceDurationNs) traceHops - div_ [class_ "w-full h-full flex overflow-hidden", id_ "trace_span_container"] $ do + div_ [class_ "@container/trace w-full h-full flex overflow-hidden", id_ "trace_span_container"] $ do div_ [class_ "flex flex-col grow min-w-0 gap-4 p-2 pb-4 overflow-y-auto overflow-x-hidden overscroll-y-contain c-scroll"] $ do div_ [class_ "flex flex-wrap justify-between items-center gap-y-1"] do div_ [class_ "flex items-center gap-3"] $ do @@ -1292,7 +1313,7 @@ tracePage pid traceItem rawSpanRecords moreUrl = do div_ [class_ "flex items-center gap-1.5"] do div_ [class_ $ "w-2.5 h-2.5 rounded-full shrink-0 " <> getServiceColor s serviceColors] pass span_ [class_ "truncate max-w-40"] $ toHtml s - div_ [class_ "border border-strokeWeak w-full rounded-2xl min-h-[230px] overflow-y-auto overflow-x-hidden relative", style_ "--wf-left:35%", id_ $ "waterfall-container-" <> traceItem.traceId] do + div_ [class_ "border border-strokeWeak w-full rounded-2xl min-h-[230px] overflow-y-auto overflow-x-hidden relative", style_ "--wf-left:min(60%,max(18rem,40%))", id_ $ "waterfall-container-" <> traceItem.traceId] do resizeDivider_ "--wf-left" 15 70 "waterfallResize" "waterfall-divider" div_ [class_ "h-full top-0 absolute z-30 hidden pointer-events-none", id_ $ "wf-time-indicator-" <> traceItem.traceId] do div_ [class_ "relative h-full"] do @@ -1315,10 +1336,16 @@ tracePage pid traceItem rawSpanRecords moreUrl = do serviceMapPanel_ pid ("trace-service-map-" <> traceItem.traceId) traceGraph serviceColors Nothing -- Open state is this checkbox: rows check it before loading a span, close unchecks it. input_ [type_ "checkbox", class_ "hidden peer/trace", id_ "trace-details-open"] - div_ [class_ "hidden md:peer-checked/trace:block", id_ "trace-details-resizer-wrapper"] + div_ [class_ "hidden @min-[64rem]/trace:peer-checked/trace:block", id_ "trace-details-resizer-wrapper"] $ Components.resizerWith_ [data_ "min" "260", data_ "max" "70vw"] "trace_details_container" "trace_details_width" False + label_ + [ Lucid.for_ "trace-details-open" + , Aria.label_ "Close span details" + , class_ "hidden @max-[64rem]/trace:peer-checked/trace:block fixed inset-0 z-40 bg-transparent pointer-events-none max-md:bg-black/40 max-md:pointer-events-auto" + ] + "" div_ - [ class_ "details-panel group/tdp shrink-0 h-full w-1/3 max-w-0 overflow-hidden overflow-y-auto c-scroll bg-bgBase peer-checked/trace:max-w-[70vw] peer-checked/trace:border-l border-strokeWeak max-md:fixed max-md:inset-0 max-md:z-50 max-md:w-full! max-md:peer-checked/trace:max-w-full" + [ class_ "details-panel group/tdp shrink-0 h-full w-1/3 max-w-0 overflow-hidden overflow-y-auto c-scroll bg-bgBase peer-checked/trace:max-w-[70vw] peer-checked/trace:border-l border-strokeWeak @max-[64rem]/trace:hidden @max-[64rem]/trace:peer-checked/trace:block @max-[64rem]/trace:fixed! @max-[64rem]/trace:inset-[0_0_0_auto]! @max-[64rem]/trace:z-50 @max-[64rem]/trace:w-[min(56rem,100vw)]! @max-[64rem]/trace:h-dvh! @max-[64rem]/trace:max-h-none! @max-[64rem]/trace:peer-checked/trace:max-w-full!" , id_ "trace_details_container" , -- Close buttons in the shared detail view send closeDetailPanel to their .details-panel. [__|init set my *width to localStorage.getItem('resizer-trace_details_width') or '' end @@ -1530,10 +1557,16 @@ buildSpanTree_ :: Projects.ProjectId -> SpanTree -> Int -> HashMap Text Text -> buildSpanTree_ pid sp level scol = do let hasChildren = not $ null sp.children serviceCol = getServiceColor sp.spanRecord.serviceName scol - indent = show (level * 12) <> "px" + treeIndent = min level 4 * 8 + max 0 (level - 4) * 4 + indent = show (8 + treeIndent) <> "px" isSynthetic = isNothing sp.spanRecord.uSpanId label = fromMaybe sp.spanRecord.spanName (spanDisplayLabel sp.spanRecord.attributes) - tip = sp.spanRecord.serviceName <> " — " <> label + attr k = Telemetry.atMapText k sp.spanRecord.attributes + operation = fromMaybe label (attr "db.query.text" <|> attr "db.statement") + operationLines = L.dropWhileEnd (T.all isSpace) $ dropWhile (T.all isSpace) $ lines operation + operationIndent = fromMaybe 0 $ viaNonEmpty minimum1 [T.length $ T.takeWhile isSpace line | line <- operationLines, not $ T.all isSpace line] + errorMessage = fold $ guard sp.spanRecord.hasErrors *> (attr "exception.message" <|> attr "error.message") + tip = "Service: " <> sp.spanRecord.serviceName <> "\nSpan: " <> sp.spanRecord.spanName <> (if label == sp.spanRecord.spanName then "" else "\nOperation: " <> label) <> "\nDepth: " <> show level div_ [class_ "span-filterble"] do div_ ( [ class_ $ "flex items-center w-full h-7 hover:bg-fillWeaker waterfall-row" <> bool "" " bg-fillError-weak/40 hover:bg-fillError-weak" sp.spanRecord.hasErrors <> bool " cursor-pointer" " italic text-textWeak bg-fillWeaker/50" isSynthetic @@ -1553,7 +1586,7 @@ buildSpanTree_ pid sp level scol = do sp.spanRecord.uSpanId ) do - div_ [class_ "shrink-0 flex items-center gap-1 px-2 overflow-hidden", style_ $ "width:var(--wf-left);padding-left:" <> indent] do + div_ [class_ "relative h-full shrink-0 flex items-center gap-1 px-2 overflow-hidden before:absolute before:left-2 before:inset-y-0 before:w-[min(32px,var(--wf-indent))] before:pointer-events-none before:bg-[repeating-linear-gradient(to_right,transparent_0px,transparent_7px,var(--color-strokeWeak)_7px,var(--color-strokeWeak)_8px)] after:absolute after:left-10 after:inset-y-0 after:w-[max(0px,calc(var(--wf-indent)_-_32px))] after:pointer-events-none after:bg-[repeating-linear-gradient(to_right,transparent_0px,transparent_3px,var(--color-strokeWeak)_3px,var(--color-strokeWeak)_4px)]", style_ $ "width:var(--wf-left);padding-left:" <> indent <> ";--wf-indent:" <> show treeIndent <> "px"] do if hasChildren then button_ @@ -1568,7 +1601,7 @@ buildSpanTree_ pid sp level scol = do else div_ [class_ "w-6 shrink-0"] pass if isSynthetic then faSprite_ "circle-question" "regular" "h-3 w-3 text-textWeak shrink-0" - else div_ [class_ $ "w-2.5 h-2.5 rounded-full shrink-0 " <> serviceCol, title_ sp.spanRecord.serviceName] pass + else div_ [class_ $ "w-2.5 h-2.5 rounded-full shrink-0 " <> serviceCol] pass when sp.spanRecord.hasErrors $ span_ [ class_ "shrink-0 w-3.5 h-3.5 rounded-sm bg-fillError-strong text-textInverse-strong text-2xs font-bold flex items-center justify-center leading-none" @@ -1576,8 +1609,25 @@ buildSpanTree_ pid sp level scol = do , Aria.label_ "Error span" ] $ toHtml @Text "!" - span_ [class_ "text-xs font-medium text-textStrong truncate max-w-20", title_ tip] $ toHtml sp.spanRecord.serviceName - span_ [class_ "text-xs text-textWeak truncate", title_ tip] $ toHtml label + div_ + [ class_ "min-w-0 flex-1 flex items-center gap-1" + , term "data-tippy-placement" "bottom-start" + , term "data-tippy-theme" "trace-span" + ] + do + span_ [class_ "w-20 max-w-[30%] shrink-0 text-xs text-textWeak truncate"] $ toHtml sp.spanRecord.serviceName + span_ [class_ "min-w-0 flex-1 text-xs text-textStrong truncate"] $ toHtml label + template_ [data_ "trace-tooltip" ""] $ div_ [class_ "space-y-3"] do + div_ [class_ "flex flex-wrap items-center gap-2"] do + strong_ [class_ "min-w-0 flex-1 text-sm font-semibold break-normal [overflow-wrap:anywhere] text-textStrong"] $ toHtml sp.spanRecord.serviceName + when sp.spanRecord.hasErrors $ span_ [class_ "rounded-md bg-fillError-weak px-1.5 py-0.5 text-2xs font-medium text-textError"] "Error span" + span_ [class_ "text-2xs tabular-nums text-textWeak"] $ toHtml $ getDurationNSMS sp.spanRecord.spanDurationNs + div_ [class_ "space-y-3 max-h-[min(18rem,50vh)] overflow-y-auto overscroll-contain c-scroll focus-visible:outline-2 focus-visible:outline-strokeBrand-strong", tabindex_ "0", role_ "region", Aria.label_ "Span information"] do + forM_ ([("Span", sp.spanRecord.spanName), ("Operation", if operation == sp.spanRecord.spanName then "" else T.intercalate "\n" $ map (T.drop operationIndent) operationLines), ("Error", errorMessage)] :: [(Text, Text)]) \(heading, value) -> + unless (T.null value) $ div_ do + p_ [class_ "mb-1 text-2xs font-medium text-textWeak"] $ toHtml @Text heading + p_ [class_ $ "text-xs leading-relaxed whitespace-pre-wrap break-normal [overflow-wrap:anywhere] " <> bool "font-mono text-textStrong" "text-textError" (heading == "Error")] $ toHtml value + when (sp.spanRecord.hasErrors && T.all isSpace errorMessage) $ p_ [class_ "border-t border-strokeWeak pt-3 text-xs leading-relaxed text-textWeak"] "No error message available in this preview. Select the span for details." div_ [ class_ "h-full relative grow min-w-0" , id_ $ "waterfall-bar-" <> sp.spanRecord.spanId diff --git a/src/Pkg/Components/Table.hs b/src/Pkg/Components/Table.hs index 55f1ff97c..8dce93aad 100644 --- a/src/Pkg/Components/Table.hs +++ b/src/Pkg/Components/Table.hs @@ -566,30 +566,30 @@ renderBody :: [Attribute] -> Table a -> Html () renderBody extra tbl | not tbl.config.renderAsTable = div_ [class_ "stagger-fade"] $ V.mapM_ (renderListRow tbl) tbl.rows | Just groupOf <- tbl.features.rowGroup = - if isJust tbl.features.grouping then groupedRows groupOf else body $ groupedRows groupOf + if V.null tbl.rows then body pass else groupedRows groupOf | otherwise = body $ V.mapM_ (renderTableRow tbl) tbl.rows where body = tbody_ (extra <> [class_ "stagger-fade"]) columnCount = length tbl.columns + bool 0 1 (isJust tbl.features.rowId) groups groupOf = sortWith (fst . head) $ NE.groupAllWith (\(idx, row) -> maybeToRight idx $ groupOf row) $ zip [0 :: Int ..] (V.toList tbl.rows) groupedRows groupOf = iforM_ (groups groupOf) $ \idx ((_, row) :| siblings) -> - let renderedRows = mapM_ (renderTableRow tbl) (row : map snd siblings) + let labelM = groupOf row + collapsible = isNothing tbl.features.grouping && isJust labelM && not (null siblings) groupLabel label suffix = toHtml label >> span_ [class_ "ms-2 text-xs font-normal text-textWeak tabular-nums"] (toHtml $ show (1 + length siblings) <> suffix) - in if isJust tbl.features.grouping - then tbody_ ([class_ "stagger-fade not-has-[.itemsListItem:not(.hidden)]:hidden"] <> if idx == 0 then extra else []) do - forM_ (groupOf row) $ \label -> tr_ [data_ "table-group" label] $ td_ [colspan_ $ show columnCount, class_ "px-4 py-3 text-sm font-medium text-textStrong"] $ groupLabel label " items" - renderedRows - else case (groupOf row, siblings) of - (Just label, _ : _) -> tr_ [class_ "not-has-[.itemsListItem:not(.hidden)]:hidden"] - $ td_ [colspan_ $ show columnCount] - $ details_ [class_ "group/disclosure", [__|on input from closest <[id$='_page']/> if event.target.type is "search" set my.open to true end|]] do - summary_ [class_ "cursor-pointer px-4 py-3 text-sm font-medium text-textStrong focus-visible:outline-offset-[-2px]"] $ groupLabel label " items on this page" - table_ [class_ tbl.config.tableClasses] do - thead_ [class_ "sr-only"] $ tr_ do - when (isJust tbl.features.rowId) $ th_ [scope_ "col"] "Select issue" - forM_ tbl.columns $ \c -> th_ [scope_ "col", data_ "column-key" c.name] $ toHtml c.name - tbody_ renderedRows - _ -> renderedRows + in tbody_ + ([class_ $ if collapsible then "stagger-fade bg-fillWeaker/30 not-has-[.itemsListItem:not(.hidden)]:hidden not-has-[>tr:first-child_.row-group-toggle[open]]:[&>tr:not(:first-child)]:hidden" else if isJust tbl.features.grouping then "stagger-fade not-has-[.itemsListItem:not(.hidden)]:hidden" <> bool "" " bg-fillWeaker/30" (isJust labelM) else "stagger-fade"] <> if idx == 0 then extra else []) + do + forM_ labelM $ \label -> + if isJust tbl.features.grouping + then tr_ [data_ "table-group" label] $ td_ [colspan_ $ show columnCount, class_ "px-4 py-3 text-sm font-medium text-textStrong"] $ groupLabel label " items" + else + when collapsible + $ tr_ [data_ "table-group" label] + $ td_ [colspan_ $ show columnCount, class_ "p-0"] + $ details_ [class_ "row-group-toggle group/disclosure", [__|on input from closest <[id$='_page']/> if event.target.type is "search" set my.open to true end|]] + $ summary_ [class_ "cursor-pointer px-4 py-3 text-sm font-medium text-textStrong focus-visible:outline-offset-[-2px]"] + $ groupLabel label " items on this page" + mapM_ (renderTableRow tbl) (row : map snd siblings) treeRowAttrs :: a -> TreeConfig a -> [Attribute] @@ -614,17 +614,22 @@ treeRowAttrs row tc = -- List mode: render columns in a flex container (no table wrapper/headers) {-# INLINE renderListRow #-} renderListRow :: Table a -> a -> Html () -renderListRow tbl row = div_ (treeAttrs <> rowAttrs <> [class_ "flex gap-4 md:gap-8 items-start itemsListItem py-3 hover:bg-fillWeak transition-colors duration-75"]) $ forM_ tbl.columns \c -> div_ c.attrs $ c.render row +renderListRow tbl row = div_ (treeAttrs <> rowAttrs <> [class_ " flex gap-4 md:gap-8 items-start itemsListItem py-3 hover:bg-fillWeak transition-colors duration-75 "]) $ forM_ tbl.columns \c -> div_ c.attrs $ c.render row where rowAttrs = maybe [] ($ row) tbl.features.rowAttrs treeAttrs = maybe [] (treeRowAttrs row) tbl.features.treeConfig --- Table mode: render as table rows with columns +-- | Table mode: render as table rows with columns. A @rowAttrs@ class stays separate from the row's own classes. +-- +-- >>> import Lucid (class_) +-- >>> let tbl = Table (def :: Config){renderAsTable = True} [col "c" (const "x")] (V.singleton ()) (def :: Features ()){rowAttrs = Just (const [class_ "hover:bg-fillWeaker"])} +-- >>> "hover:bg-fillWeaker hover:bg-fillWeak" `TL.isInfixOf` renderText (toHtml tbl) +-- True {-# INLINE renderTableRow #-} renderTableRow :: Table a -> a -> Html () renderTableRow tbl row = - tr_ ([class_ $ "hover:bg-fillWeak transition-colors duration-75 itemsListItem" <> bool "" " cursor-pointer" (isTreeGroup || isJust tbl.features.rowLink)] <> treeAttrs <> rowAttrs <> linkHandler) do + tr_ ([class_ $ " hover:bg-fillWeak transition-colors duration-75 itemsListItem" <> bool "" " cursor-pointer" (isTreeGroup || isJust tbl.features.rowLink) <> " "] <> treeAttrs <> rowAttrs <> linkHandler) do whenJust tbl.features.rowId \getId -> td_ [class_ "w-8 align-top pt-4 max-md:hidden"] $ input_ @@ -635,7 +640,7 @@ renderTableRow tbl row = rowAttrs = maybe [] ($ row) tbl.features.rowAttrs treeAttrs = maybe [] (treeRowAttrs row) tbl.features.treeConfig isTreeGroup = maybe False (\tc -> tc.isGroupRow row) tbl.features.treeConfig - -- single class_ attribute: Lucid concatenates duplicates with no separator + -- Lucid joins duplicate class_ attributes with no separator, so the row class is space-padded for rowAttrs classes. linkHandler = maybe [] (\getLink -> [hxGet_ (getLink row), hxPushUrl_ "true"] <> navTabAttrs) tbl.features.rowLink diff --git a/src/Pkg/Parser.hs b/src/Pkg/Parser.hs index 55cce765d..7bcfd9038 100644 --- a/src/Pkg/Parser.hs +++ b/src/Pkg/Parser.hs @@ -968,15 +968,16 @@ variablePresets density pid mf mt allParams currentTime = audience = Rum.audienceFilters allParams audienceSessions = Rum.audienceSessionsSql browserSql errorSql audience bound op t field' = field' <> " " <> op <> " '" <> formatUTC t <> "'" - clause field = case catMaybes [bound ">=" <$> mf, bound "<=" <$> mt] of + clause endOp field = case catMaybes [bound ">=" <$> mf, bound endOp <$> mt] of [] -> "" bs -> andPrefix $ "(" <> T.intercalate " AND " (map ($ field) bs) <> ")" in Map.fromList $ [ ("project_id", pid) , ("from", andPrefix $ fmtUTC mf) , ("to", andPrefix $ fmtUTC mt) - , ("time_filter", clause "timestamp") - , ("time_filter_sql_created_at", clause "created_at") + , ("time_filter", clause "<=" "timestamp") + , ("rollup_time_filter", clause "<" "timestamp") + , ("time_filter_sql_created_at", clause "<=" "created_at") , ("rollup_interval", calculateAutoBinWidth density (mf, mt) currentTime) , ("browser_filter", browserSql) , ("pageview_filter", pageViewSql) diff --git a/src/Web/Routes.hs b/src/Web/Routes.hs index d7449ff08..32d609d9b 100644 --- a/src/Web/Routes.hs +++ b/src/Web/Routes.hs @@ -500,7 +500,7 @@ data CookieProtectedRoutes mode = CookieProtectedRoutes , widgetAlertToggle :: mode :- "p" :> ProjectId :> "widgets" :> Capture "widget_id" Text :> "alert" :> "toggle_active" :> QueryParam "dashboard_id" Dashboards.DashboardId :> Post '[HTML] (RespHeaders (Html ())) , dashboardBulkActionPost :: mode :- "p" :> ProjectId :> "dashboards" :> "bulk_action" :> Capture "action" Dashboards.DashboardBulkAction :> ReqBody '[FormUrlEncoded] Dashboards.DashboardBulkActionForm :> Post '[HTML] (RespHeaders NoContent) , -- Dashboard tab routes (htmx lazy loading) - dashboardTabGet :: mode :- "p" :> ProjectId :> "dashboards" :> Capture "dashboard_id" Dashboards.DashboardId :> "tab" :> Capture "tab_slug" Text :> QPT "file" :> QPT "from" :> QPT "to" :> QPT "since" :> HXRequest :> Header "HX-Trigger-Name" Text :> AllQueryParams :> Get '[HTML] (RespHeaders (NavigationResponse Dashboards.DashboardGet)) + dashboardTabGet :: mode :- "p" :> ProjectId :> "dashboards" :> Capture "dashboard_id" Dashboards.DashboardId :> "tab" :> Capture "tab_slug" Text :> QPT "file" :> QPT "from" :> QPT "to" :> QPT "since" :> Header "HX-Target" Text :> Header "HX-Trigger-Name" Text :> AllQueryParams :> Get '[HTML] (RespHeaders (NavigationResponse Dashboards.DashboardGet)) , dashboardTabRenamePatch :: mode :- "p" :> ProjectId :> "dashboards" :> Capture "dashboard_id" Dashboards.DashboardId :> "tab" :> Capture "tab_slug" Text :> "rename" :> ReqBody '[FormUrlEncoded] Dashboards.TabRenameForm :> Patch '[HTML] (RespHeaders Dashboards.TabRenameRes) , dashboardYamlGet :: mode :- "p" :> ProjectId :> "dashboards" :> Capture "dashboard_id" Dashboards.DashboardId :> "yaml" :> Get '[HTML] (RespHeaders (Html ())) , dashboardYamlPut :: mode :- "p" :> ProjectId :> "dashboards" :> Capture "dashboard_id" Dashboards.DashboardId :> "yaml" :> ReqBody '[FormUrlEncoded] Dashboards.YamlForm :> Put '[HTML] (RespHeaders (Html ())) @@ -541,7 +541,7 @@ data CookieProtectedRoutes mode = CookieProtectedRoutes , bringS3Post :: mode :- "p" :> ProjectId :> "byob_s3" :> ReqBody '[FormUrlEncoded] Projects.ProjectS3Bucket :> Post '[HTML] (RespHeaders Settings.StorageGet) , bringS3Remove :: mode :- "p" :> ProjectId :> "byob_s3" :> Delete '[HTML] (RespHeaders Settings.StorageGet) , gitSyncSettings :: mode :- "p" :> ProjectId :> "settings" :> "git-sync" :> Get '[HTML] (RespHeaders (Html ())) - , projectWikiGet :: mode :- "p" :> ProjectId :> "wiki" :> CaptureAll "path" Text :> QueryParam "after" ProjectMemory.PagePath :> Get '[HTML] (RespHeaders (PageCtx PageCodeContext.WikiGet)) + , projectWikiGet :: mode :- "p" :> ProjectId :> "wiki" :> CaptureAll "path" Text :> QueryParam "after" ProjectMemory.PagePath :> QueryParam "q" Text :> QueryParam "folder" Text :> QueryFlag "edit" :> Get '[HTML] (RespHeaders (PageCtx PageCodeContext.WikiGet)) , projectMemoryGet :: mode :- "p" :> ProjectId :> "memories" :> QueryParam "page" (UUIDId "memory_page") :> Get '[HTML] (RespHeaders (PageCtx PageCodeContext.WikiGet)) , projectMemoryPost :: mode :- "p" :> ProjectId :> "memories" :> ReqBody '[FormUrlEncoded] PageCodeContext.MemoryForm :> Post '[HTML] (RespHeaders (PageCtx PageCodeContext.WikiGet)) , repositoriesGet :: mode :- "p" :> ProjectId :> "repositories" :> QueryParam "tab" PageCodeContext.RepositoryTab :> QueryParam "sample" Text :> Get '[HTML] (RespHeaders (Html ())) @@ -1343,9 +1343,10 @@ clientPostgresSqlRejection dbSource pidM querySqlM = case (dbSource, pidM, Utils -- | @rollup_sql@ is a Postgres statement over an hourly rollup that answers the same -- series as the chart's KQL query, for hours from @rollup_from@ on. It replaces the --- query whenever the window starts inside that coverage and no environment or service --- scope applies (the rollup has no column to honour one). Short windows included: on a --- busy project three live hours of the query took 90s, and hourly bars do not. +-- query when coverage and whole-hour boundaries permit it, with no environment or +-- service scope. A partial first hour cannot use hourly counts: filtering its bucket +-- drops in-range events, while including it counts events before the requested start. +-- A partial last hour is safe only while it is still the current hour. -- -- >>> import Data.Time (addUTCTime) -- >>> let now = Parser.fixedUTCTime; t = Utils.isoT . (`addUTCTime` now) . (* 3600); since s = TimePicker.TimePicker (Just s) Nothing Nothing; abs' a b = TimePicker.TimePicker Nothing (Just $ t a) (Just $ t b) @@ -1354,16 +1355,22 @@ clientPostgresSqlRejection dbSource pidM querySqlM = case (dbSource, pidM, Utils -- (Just SqlPostgres,Just SqlPostgres,Just SqlPostgres) -- >>> (route (since "24H") (r (-12)), route (since "24H") (("environment", Just "prod") : r (-72)), route (since "24H") (take 1 $ r (-72))) -- (Nothing,Nothing,Nothing) +-- >>> (route (abs' (-2 + 1/6) (-1)) (r (-72)), route (abs' (-2) (-1 + 1/6)) (r (-72))) +-- (Nothing,Nothing) +-- >>> fst $ rollupRoute (addUTCTime 1800 now) (since "1H") (r (-72)) (Nothing, Nothing) +-- Nothing rollupRoute :: UTCTime -> TimePicker.TimePicker -> [(Text, Maybe Text)] -> (Maybe Hasql.SqlSource, Maybe Text) -> (Maybe Hasql.SqlSource, Maybe Text) rollupRoute now tp params source = case (param "rollup_sql", iso8601ParseM . toString =<< param "rollup_from", fromM) of (Just rollup, Just covered, Just start) | all (isNothing . param) ["environment", "service"] - , start >= covered -> + , start >= covered + , start == Utils.truncateHour start + , all (\end -> end == Utils.truncateHour end || end >= now) toM -> (Just Hasql.SqlPostgres, Just rollup) _ -> source where param k = Utils.nonEmptyT $ join $ L.lookup k params - (fromM, _, _) = TimePicker.parseTimeRange now tp + (fromM, toM, _) = TimePicker.parseTimeRange now tp -- | The @/chart_data@ handler shape, shared by the buffered and the streamed route. diff --git a/static/migrations/0255_api_change_recorded_service.sql b/static/migrations/0255_api_change_recorded_service.sql new file mode 100644 index 000000000..28261abcb --- /dev/null +++ b/static/migrations/0255_api_change_recorded_service.sql @@ -0,0 +1,9 @@ +-- Replace path-inferred API-change service labels with the endpoint's recorded service. +-- Host labels are read from issue_data; service remains a valid telemetry scope. +UPDATE apis.issues i +SET service = ( + SELECT NULLIF(btrim(e.service_name), '') + FROM apis.endpoints e + WHERE e.project_id = i.project_id AND e.hash = i.target_hash +) +WHERE i.issue_type = 'api_change'; diff --git a/static/public/assets/css/tailwind.css b/static/public/assets/css/tailwind.css index 1463f542e..ab6a7d07b 100644 --- a/static/public/assets/css/tailwind.css +++ b/static/public/assets/css/tailwind.css @@ -1634,17 +1634,6 @@ code, pre, .code, .monospace { .replayer-wrapper > iframe { border: none; } -.event-container.expanded { - @apply border border-strokeBrand-strong -} -.event-container.expanded button > svg { - @apply rotate-180 -} -.event-container.expanded > .event-detail { - display: flex; -} - - /* Database-specific badges - consolidated with CSS custom properties */ .badge-postgres, .badge-mysql, .badge-redis, .badge-mongo, .badge-mongodb, .badge-elastic, .badge-elasticsearch, .badge-cassandra, .badge-dynamodb, @@ -2800,3 +2789,20 @@ table td a[href]:not(.btn):not([data-no-preview]) { --tooltip-z: 100; --tooltip- width: min(24rem, calc(100vw - 1rem)); } } + +/* Keep trace hover cards above the third-party tooltip stylesheet's unlayered defaults. */ + .tippy-box[data-theme~='trace-span'] { + color: var(--color-textStrong); + background: var(--color-bgRaised); + border: 1px solid var(--color-strokeStrong); + border-radius: var(--radius-field); + box-shadow: var(--shadow-lg); + animation: none; + } + .tippy-box[data-theme~='trace-span'] .tippy-content { + padding: 12px; + text-align: start; + } + .tippy-box[data-theme~='trace-span'] .tippy-arrow { + color: var(--color-bgRaised); + } diff --git a/static/public/assets/svgs/fa-sprites/regular.svg b/static/public/assets/svgs/fa-sprites/regular.svg index 32e12fd70..26cad0ca2 100644 --- a/static/public/assets/svgs/fa-sprites/regular.svg +++ b/static/public/assets/svgs/fa-sprites/regular.svg @@ -999,4 +999,7 @@ + + + diff --git a/test/fixtures/wiki-browser.mjs b/test/fixtures/wiki-browser.mjs index 22d9d68f9..5454e4655 100644 --- a/test/fixtures/wiki-browser.mjs +++ b/test/fixtures/wiki-browser.mjs @@ -29,8 +29,9 @@ else { return target.origin === origin && (target.pathname.includes('/memories') || target.pathname.includes('/wiki')) ? route.continue() : route.abort(); }); await load(url); - await page.getByLabel('Page path (required)').fill('runbooks/retries'); - await page.getByLabel('Title (required)').fill('Browser memory'); + await page.getByRole('link', { name: 'New page', exact: true }).first().click(); + await page.getByLabel('Page path', { exact: true }).fill('runbooks/retries'); + await page.getByLabel('Title', { exact: true }).fill('Browser memory'); const initial = 'Typed while the editor loads.'; await page.locator('textarea[name=body]').fill(initial); releaseEditor(); @@ -43,16 +44,19 @@ else { await page.waitForFunction(text => document.querySelector('textarea[name=body]').value === text, initial); await rich.press('ControlOrMeta+Shift+z'); await rich.press('ControlOrMeta+a'); - const bold = page.getByRole('button', { name: 'Bold', exact: true }); - await bold.waitFor({ timeout: 5000 }); - await bold.focus(); - await bold.press('Enter'); - await page.getByRole('button', { name: 'Heading 2', exact: true }).focus(); - await page.getByRole('button', { name: 'Heading 2', exact: true }).press('Enter'); + await rich.press('ControlOrMeta+b'); + await rich.press('ControlOrMeta+Alt+2'); assert.equal(await rich.locator('h2 strong').textContent(), 'Keep caller retry tokens.'); - await page.getByRole('button', { name: 'Paragraph', exact: true }).click(); + await rich.press('ControlOrMeta+Alt+0'); await page.getByLabel('Editing mode').selectOption('source'); assert.equal(await page.locator('textarea[name=body]').inputValue(), '**Keep caller retry tokens.**\n'); + await page.locator('textarea[name=body]').fill('See [[runbooks/retries|Retry notes]].\n'); + await page.getByLabel('Editing mode').selectOption('rich'); + await rich.locator('p').last().click(); + await rich.press('End'); + await rich.pressSequentially(' Done'); + await page.getByLabel('Editing mode').selectOption('source'); + assert.equal(await page.locator('textarea[name=body]').inputValue(), 'See [[runbooks/retries|Retry notes]]. Done\n'); await page.locator('textarea[name=body]').fill('**Keep caller retry tokens.**\n\n[Runbook][ref]\n\n[ref]: https://monoscope.tech\n'); await page.getByLabel('Editing mode').selectOption('rich'); assert.equal(await rich.locator('strong').textContent(), 'Keep caller retry tokens.'); @@ -65,16 +69,16 @@ else { const urls = [new URL(page.url()).pathname]; const targets = [await page.locator('#repository-content').count()]; await load(url); - await page.getByRole('link', { name: 'retries', exact: true }).click(); + await page.getByRole('link', { name: 'Browser memory', exact: true }).click(); await page.waitForFunction(() => document.querySelector('#repository-content h2')?.textContent === 'Browser memory'); targets.push(await page.locator('#repository-content').count()); await load(url + '?page=' + id); - await page.getByRole('link', { name: 'New page', exact: true }).click(); - await page.waitForFunction(() => document.querySelector('#repository-content h2')?.textContent === 'New wiki page'); + await page.getByRole('link', { name: 'New page', exact: true }).first().click(); + await page.waitForFunction(() => document.querySelector('#repository-content h2')?.textContent === 'New page'); targets.push(await page.locator('#repository-content').count()); urls.push(new URL(page.url()).pathname); await page.locator('wiki-editor[data-mode=rich] .ProseMirror').waitFor(); assert.equal(await page.locator('wiki-editor .ProseMirror').textContent(), ''); - process.stdout.write(JSON.stringify({ targets, urls, fields: [await page.getByLabel('Page path (required)').inputValue(), await page.getByLabel('Title (required)').inputValue(), await page.locator('textarea[name=body]').inputValue()] })); + process.stdout.write(JSON.stringify({ targets, urls, fields: [await page.getByLabel('Page path', { exact: true }).inputValue(), await page.getByLabel('Title', { exact: true }).inputValue(), await page.locator('textarea[name=body]').inputValue()] })); } finally { await browser.close(); } } diff --git a/test/integration/Pages/Bots/AgenticSpec.hs b/test/integration/Pages/Bots/AgenticSpec.hs index cd1a03ca6..759c85709 100644 --- a/test/integration/Pages/Bots/AgenticSpec.hs +++ b/test/integration/Pages/Bots/AgenticSpec.hs @@ -115,12 +115,12 @@ spec = around withTestResources do scheduledActionable `shouldContain` ["send_to_slack"] describe "Web conversation persistence" do - it "assistantPages_defaultToNavigation" \tr -> do + it "assistantPages_defaultToAssistant" \tr -> do let convId = UUIDId UUID.nil void $ runTestBg frozenTime tr $ Hasql.interpExecute [HI.sql|INSERT INTO apis.ai_conversations (project_id, conversation_id, conversation_type) VALUES (#{testPid}, #{convId}, #{Issues.CTWeb})|] (_, threadPage) <- testServant tr $ AIThreads.threadGetH testPid convId let html = LT.toStrict $ Lucid.renderText $ Lucid.toHtml threadPage - html `shouldSatisfy` T.isInfixOf "id=\"nav-view-menu\" class=\"sr-only\" checked" + html `shouldSatisfy` T.isInfixOf "id=\"nav-view-ai\" class=\"sr-only\" checked" it "issueConversation_linksBackToItsIssue" \tr -> do let issueId = UUIDId UUID.nil :: Issues.IssueId diff --git a/test/integration/Pages/CodeContextSpec.hs b/test/integration/Pages/CodeContextSpec.hs index 0fed9192a..96c617759 100644 --- a/test/integration/Pages/CodeContextSpec.hs +++ b/test/integration/Pages/CodeContextSpec.hs @@ -248,8 +248,11 @@ spec = do nested <- request H.methodGet ("/p/" <> testPid.toText <> "/wiki/runbooks/retries") [] H.statusCode nested.simpleStatus `shouldBe` 200 html nested `shouldSatisfy` T.isInfixOf "runbooks" - html nested `shouldSatisfy` T.isInfixOf " testPid.toText <> "/wiki/runbooks/retries?edit=true") [] + html editing `shouldSatisfy` T.isInfixOf " "?page=" <> page.toText) [] H.statusCode readOnly.simpleStatus `shouldBe` 200 html readOnly `shouldNotSatisfy` T.isInfixOf "Save page" + viewerMissing <- request H.methodGet ("/p/" <> testPid.toText <> "/wiki/runbooks/unwritten") [] + H.statusCode viewerMissing.simpleStatus `shouldBe` 404 refused <- save testPid 2 "Retry behavior" "Viewer must not write" H.statusCode refused.simpleStatus `shouldBe` 403 length <$> runQueryEffect tr (Memory.pageHistory testPid page) `shouldReturn` 2 @@ -353,7 +358,28 @@ spec = do moved <- request H.methodGet ("/p/" <> testPid.toText <> "/wiki/services/retries") [] H.statusCode moved.simpleStatus `shouldBe` 200 oldPath <- request H.methodGet ("/p/" <> testPid.toText <> "/wiki/runbooks/retries") [] - H.statusCode oldPath.simpleStatus `shouldBe` 404 + H.statusCode oldPath.simpleStatus `shouldBe` 200 + html oldPath `shouldSatisfy` T.isInfixOf "id=\"wiki-form\"" + html oldPath `shouldSatisfy` T.isInfixOf "value=\"runbooks/retries\"" + derived <- request H.methodPost (base testPid) [("pageId", UUID.toText (UUID.fromWords 50 0 0 99)), ("version", "0"), ("path", "runbooks/"), ("title", "Restart the Consumer"), ("body", "Steps")] + html derived `shouldSatisfy` T.isInfixOf "/wiki/runbooks/restart-the-consumer" + folderNew <- request H.methodGet ("/p/" <> testPid.toText <> "/wiki?folder=runbooks") [] + html folderNew `shouldSatisfy` T.isInfixOf "value=\"runbooks/\"" + linking <- request H.methodPost (base testPid) [("pageId", duplicate.toText), ("version", "1"), ("path", "services/other"), ("title", "Other page"), ("body", "See [[services/retries|retry notes]] and [[javascript:alert(1)]].")] + html linking `shouldSatisfy` T.isInfixOf ("href=\"/p/" <> testPid.toText <> "/wiki/services/retries\"") + html linking `shouldSatisfy` T.isInfixOf ">retry notes" + T.toLower (html linking) `shouldNotSatisfy` T.isInfixOf "href=\"javascript" + html linking `shouldNotSatisfy` T.isInfixOf "/wiki/javascript" + linked <- request H.methodGet ("/p/" <> testPid.toText <> "/wiki/services/retries") [] + html linked `shouldSatisfy` T.isInfixOf "Linked from" + html linked `shouldSatisfy` T.isInfixOf "/wiki/services/other" + searched <- request H.methodGet ("/p/" <> testPid.toText <> "/wiki?q=RETRY%20NOTES") [] + html searched `shouldSatisfy` T.isInfixOf "/wiki/services/other" + html searched `shouldNotSatisfy` T.isInfixOf "/wiki/services/retries" + changes <- request H.methodGet (base testPid <> "?page=" <> duplicate.toText) [] + html changes `shouldSatisfy` T.isInfixOf "Changes from revision 1" + html changes `shouldSatisfy` T.isInfixOf "- Other notes" + html changes `shouldSatisfy` T.isInfixOf "+ See [[services/retries|retry notes]]" legacy <- request H.methodGet (base testPid <> "?page=" <> page.toText) [] H.statusCode legacy.simpleStatus `shouldBe` 200 length <$> runQueryEffect tr (Memory.pageHistory testPid page) `shouldReturn` 3 @@ -839,8 +865,8 @@ spec = do forM_ repositories \repository -> T.isInfixOf ("/repositories/" <> repository.id.toText <> "\"") html `shouldBe` (isNothing repository.apiBase && repository.repo `elem` ["checkout-service", "shared-source"]) html `shouldSatisfy` T.isInfixOf "All services" - html `shouldSatisfy` T.isInfixOf "Repositories for team/api & jobs" - html `shouldSatisfy` T.isInfixOf "All repositories" + html `shouldSatisfy` T.isInfixOf "team/api & jobs" + html `shouldSatisfy` T.isInfixOf "Source mappings that apply to this service, including mappings for all services." html `shouldNotSatisfy` T.isInfixOf "id=\"repository-nav\"" runQueryEffect tr $ Hasql.interpExecute_ [HI.sql| DELETE FROM projects.code_mappings WHERE project_id = #{testPid} |] (_, unlinkedPage) <- testServant tr $ PageCodeContext.serviceRepositoriesGetH testPid service diff --git a/test/integration/Pages/DashboardWidgetsSpec.hs b/test/integration/Pages/DashboardWidgetsSpec.hs index 614614cb9..bdefbf436 100644 --- a/test/integration/Pages/DashboardWidgetsSpec.hs +++ b/test/integration/Pages/DashboardWidgetsSpec.hs @@ -16,12 +16,12 @@ import Data.Aeson qualified as AE import Data.Aeson.KeyMap qualified as KM import Data.ByteString.Lazy qualified as LBS import Data.Default (def) -import Data.List (lookup) import Data.Effectful.Hasql qualified as Hasql +import Data.List (lookup) import Data.Map.Strict qualified as Map import Data.Pool (withResource) -import Data.Text qualified as T import Data.ProtoLens (defMessage) +import Data.Text qualified as T import Data.Time (addUTCTime) import Data.Time.Clock.POSIX (utcTimeToPOSIXSeconds) import Data.Time.Format.ISO8601 (iso8601Show) @@ -1024,7 +1024,7 @@ spec = sequential $ aroundAll withTestResources do , Endpoints.outgoing = True } filters hash = do - (_, response) <- testServant tr $ Dashboards.dashboardTabGetH testPid dashId "overview" Nothing Nothing Nothing (Just "24H") (Just "true") Nothing [("var-host", Just "integrations.routelift.com"), ("var-endpointHash", Just hash)] + (_, response) <- testServant tr $ Dashboards.dashboardTabGetH testPid dashId "overview" Nothing Nothing Nothing (Just "24H") (Just "div#dashboard-tabs-content") Nothing [("var-host", Just "integrations.routelift.com"), ("var-endpointHash", Just hash)] let Dashboards.DashboardGet _ _ _ _ params = tabDashboard response values = Map.fromList params pure (Map.lookup "const-endpointFilter" values, Map.lookup "const-endpointFilter-kql" values) @@ -1068,7 +1068,7 @@ spec = sequential $ aroundAll withTestResources do Nothing Nothing (Just "3D") - (Just "true") + (Just "div#dashboard-tabs-content") Nothing [ ("const-endpointFilter", Just "hashes @> ARRAY['']") , ("const-endpointFilter-kql", Just "hashes[*] in (\"\")") @@ -1322,7 +1322,7 @@ spec = sequential $ aroundAll withTestResources do , Endpoints.host = "dellyman.com" , Endpoints.hash = "ba3431d5" } - let open params = snd <$> testServant tr (Dashboards.dashboardTabGetH testPid dashId "overview" Nothing Nothing Nothing (Just "24H") (Just "true") Nothing params) + let open params = snd <$> testServant tr (Dashboards.dashboardTabGetH testPid dashId "overview" Nothing Nothing Nothing (Just "24H") (Just "div#dashboard-tabs-content") Nothing params) partialHtml = \case NavigationPartial _ fragment -> pure $ toStrict $ renderText fragment NavigationFull _ -> expectationFailure "htmx picker navigation returned a full document" $> "" @@ -1349,7 +1349,7 @@ spec = sequential $ aroundAll withTestResources do Nothing Nothing (Just "24H") - (Just "true") + (Just "div#dashboard-tabs-content") (Just "dashboard-variable-option") [("var-host", Just "dellyman.com"), ("var-endpointHash", Just "ba3431d5")] case response of @@ -1377,24 +1377,34 @@ spec = sequential $ aroundAll withTestResources do -- themselves rather than blocking on the widget phase (measured 4.9s -> 1.2s). describe "Prefill on a full load, skeletons on a swap" do let openTab tr dashId hx = do - (tabDashboard . snd) <$> testServant tr (Dashboards.dashboardTabGetH testPid dashId "overview" Nothing Nothing Nothing (Just "24H") hx Nothing [("var-host", Just "dellyman.com"), ("var-endpointHash", Just "ba3431d5")]) + snd <$> testServant tr (Dashboards.dashboardTabGetH testPid dashId "overview" Nothing Nothing Nothing (Just "24H") hx Nothing [("var-host", Just "dellyman.com"), ("var-endpointHash", Just "ba3431d5")]) eagerOnes = filter (\w -> w.eager == Just True || isJust w.html || isJust w.dataset) it "keeps the server-side prefill for a full page load" \tr -> do dashId <- newDashboard tr "endpoint-stats.yaml" "Prefill Full" full <- openTab tr dashId Nothing - eagerOnes (renderedWidgets full) `shouldSatisfy` not . null + eagerOnes (renderedWidgets $ tabDashboard full) `shouldSatisfy` not . null T.count "id=\"log_details_container\"" (toStrict $ renderText $ toHtml full) `shouldBe` 1 it "hands a swap the same widgets with nothing prefilled" \tr -> do dashId <- newDashboard tr "endpoint-stats.yaml" "Prefill Swap" - swapped <- openTab tr dashId (Just "true") - let ws = renderedWidgets swapped + swapped <- openTab tr dashId (Just "div#dashboard-tabs-content") + let ws = renderedWidgets $ tabDashboard swapped ws `shouldSatisfy` not . null -- lazyWidget strips `eager` too: renderStatContent reads the flag as "data is here" -- and would otherwise spin forever. map (fromMaybe "" . (.title)) (eagerOnes ws) `shouldBe` [] + it "dashboardTab_sidebarNavigationFromSessions_keepsMainContent" \tr -> do + dashId <- newDashboard tr "rum.yaml" "RUM sidebar navigation" + (_, response) <- testServant tr $ Dashboards.dashboardTabGetH testPid dashId "overview" Nothing Nothing Nothing (Just "24H") (Just "div#main-content") Nothing [] + case response of + NavigationFull page -> do + let html = toStrict $ renderText $ toHtml page + html `shouldSatisfy` T.isInfixOf "id=\"main-content\"" + html `shouldSatisfy` T.isInfixOf "id=\"dashboardPage\"" + NavigationPartial _ _ -> expectationFailure "sidebar navigation returned a tab fragment, blanking the page" + it "returns the shared fragment contract for an htmx tab navigation" \tr -> do dashId <- newDashboard tr "endpoint-stats.yaml" "Partial navigation" (_, response) <- @@ -1407,7 +1417,7 @@ spec = sequential $ aroundAll withTestResources do Nothing Nothing (Just "24H") - (Just "true") + (Just "div#dashboard-tabs-content") Nothing [ ("var-host", Just "dellyman.com") , ("var-endpointHash", Just "ba3431d5") @@ -1547,9 +1557,10 @@ spec = sequential $ aroundAll withTestResources do -- /rum and its older /rum/dashboard open the dashboard; /rum/sessions the Explorer. Links from -- emails and alerts carry a window, which both must keep. it "rumRedirects_openTheDashboardOrSessions_andKeepTheWindow" \tr -> do - let location view ps = runAuthHandler tr (Dashboards.rumRedirectH testPid view ps) <&> \h -> case lookupResponseHeader @"Location" h of - Header l -> l - _ -> "" + let location view ps = + runAuthHandler tr (Dashboards.rumRedirectH testPid view ps) <&> \h -> case lookupResponseHeader @"Location" h of + Header l -> l + _ -> "" window = [("since", Just "7D"), ("environment", Just "prod")] dashboard <- location [] window dashboard `shouldSatisfy` T.isInfixOf ("/p/" <> testPid.toText <> "/dashboards/") diff --git a/test/integration/Pages/ErrorPatternsSpec.hs b/test/integration/Pages/ErrorPatternsSpec.hs index 8c11face5..34d35d572 100644 --- a/test/integration/Pages/ErrorPatternsSpec.hs +++ b/test/integration/Pages/ErrorPatternsSpec.hs @@ -128,7 +128,7 @@ spec = sequential $ aroundAll withTestResources do (e.browser, e.os, e.device, e.userAgent) `shouldBe` (Just "Chrome", Just "Windows", Just "Desktop", Just ua) (e.geoCountry, e.geoCity, e.threadName, e.attachments) `shouldBe` (Just "US", Just "Santa Clara", Just "main", Just ["https://cdn.example.com/shot.png"]) issue <- issueOf tr e.hash - issuePageText tr issue.id >>= (`shouldContainAll` ["id=\"issue-contexts\"", "Santa Clara, US", "26.3.1", "Chrome", "exception_event", "id=\"issue-http\"", "https://shop.example.com/api/context?cart=7&coupon=x", "coupon", "x-request-id", "curl -X GET", "id=\"issue-copy-json\"", ""release":"26.3.1"", "## ", "id=\"issue-grouping\"", "context probe", "Root cause", "The cart line has no price", "Plan a fix", "id=\"issue-tags\"", ">release", ">26.3.1", "100%", "id=\"issue-attachments\"", "src=\"https://cdn.example.com/shot.png\""]) + issuePageText tr issue.id >>= (`shouldContainAll` ["id=\"issue-contexts\"", "Santa Clara, US", "26.3.1", "Chrome", "exception_event", "id=\"issue-http\"", "https://shop.example.com/api/context?cart=7&coupon=x", "coupon", "x-request-id", "curl -X GET", "id=\"issue-copy-json\"", ""release":"26.3.1"", "## ", "id=\"issue-grouping\"", "context probe", "Likely cause", "The cart line has no price", "Plan a fix", "id=\"issue-tags\"", ">release", ">26.3.1", "100%", "id=\"issue-attachments\"", "src=\"https://cdn.example.com/shot.png\""]) it "1c. releases and distinct users are tracked, and resolve-in-next-release holds until a new release" \tr -> do apiKey <- createTestAPIKey tr pid "release-key" diff --git a/test/integration/Pages/IssuesSpec.hs b/test/integration/Pages/IssuesSpec.hs index da9eb2489..7590bb79f 100644 --- a/test/integration/Pages/IssuesSpec.hs +++ b/test/integration/Pages/IssuesSpec.hs @@ -18,6 +18,7 @@ import Database.PostgreSQL.Simple qualified as PGS import Database.PostgreSQL.Simple.SqlQQ (sql) import Hasql.Interpolate qualified as HI import Lucid (ToHtml, renderText, toHtml) +import Models.Apis.ApiChanges qualified as ApiChanges import Models.Apis.ErrorPatterns qualified as ErrorPatterns import Models.Apis.Incidents qualified as Incidents import Models.Apis.Issues qualified as Issues @@ -30,6 +31,7 @@ import Pages.Issues qualified as IssuesPage import Pages.Telemetry qualified as Trace import Pkg.Components.Table qualified as Table import Pkg.DeriveUtils (UUIDId (..)) +import Pkg.SchemaLearning.Catalog qualified as Catalog import Pkg.TestUtils import Relude import Relude.Unsafe qualified as Unsafe @@ -148,7 +150,7 @@ spec = sequential $ aroundAll withTestResources do -- Regression: since #376 dropped apis.shapes/fields/formats, getAnomaliesVM selected -- NULL drift detail, so new/changed fields never reached the issue, never updated an - -- open one, and a breaking change never marked it critical. + -- open one. Observed field drift does not establish consumer breakage. it "apiChangeIssue_fieldDrift_neverReachedIssuePayload" \tr -> do nowTxt <- nowText let ingest body = do @@ -173,7 +175,7 @@ spec = sequential $ aroundAll withTestResources do ingest "eyJ1c2VybmFtZSI6MiwicGFzc3dvcmQiOiJ4Iiwibmlja25hbWUiOjJ9" -- username, nickname: string -> number (i2, d2) <- driftIssue (hasField "password" d2.newFields, hasField "username" d2.modifiedFields, hasField "password" d2.modifiedFields) `shouldBe` (True, True, False) - (i2.id == i0.id, i2.critical) `shouldBe` (True, True) + (i2.id == i0.id, i2.critical, i2.severity) `shouldBe` (True, False, Issues.Warning) (_, detail) <- testServant tr $ IssuesPage.issueDetailGetH testPid i2.id Nothing Nothing Nothing Nothing Nothing let html = renderPage detail for_ ["Before", "After", "Detected", "a@b.co", "string", "number"] \text -> @@ -183,7 +185,7 @@ spec = sequential $ aroundAll withTestResources do for_ ["Historical types and values were not captured", "Current observations", "a@b.co"] \text -> renderPage legacyDetail `shouldSatisfy` T.isInfixOf text for_ ([("Added", "2026-01-01T00:00:00Z"), ("Modified", "2026-01-02T00:00:00Z")] :: [(Text, Text)]) \(kind, detected) -> - T.splitOn "" (renderPage legacyDetail) `shouldSatisfy` any (\row -> all (`T.isInfixOf` row) ["nickname", ">" <> kind <> "", detected]) + T.splitOn "" (renderPage legacyDetail) `shouldSatisfy` any (\batch -> all (`T.isInfixOf` batch) ["nickname", ">" <> kind <> "", detected]) it "apiChangeEvidence_unavailable_doesNotHideIssue" \tr -> do issueId <- pickApiChangeIssue tr @@ -196,7 +198,7 @@ spec = sequential $ aroundAll withTestResources do (_, detail) <- testServant tr $ IssuesPage.issueDetailGetH testPid issueId Nothing Nothing Nothing Nothing Nothing for_ ["Field changes", "Field evidence unavailable"] \text -> renderPage detail `shouldSatisfy` T.isInfixOf text - it "apiChanges_sameService_collapseWithoutLosingEndpointIssues" \tr -> do + it "apiChanges_sameHost_collapseWithoutLosingEndpointIssues" \tr -> do nowTxt <- nowText for_ ["eyJ1c2VybmFtZSI6ImFAYi5jbyJ9", "eyJ1c2VybmFtZSI6Mn0="] \body -> do processMessagesAndBackgroundJobs tr [("group", encMsg $ msgWithBody "/v1/grouped-drift" body nowTxt)] @@ -211,9 +213,9 @@ spec = sequential $ aroundAll withTestResources do do (_, page) <- testServant tr $ IssuesPage.issueListGetH testPid (Just "Inbox") Nothing Nothing Nothing Nothing Nothing Nothing [] ["api_change"] let html = renderPage page - for_ [" + for_ [" html `shouldSatisfy` T.isInfixOf text - T.splitOn "
" html `shouldSatisfy` any (\disclosure -> all (`T.isInfixOf` disclosure) ["" html `shouldSatisfy` any (\batch -> all (`T.isInfixOf` batch) [" do issueId <- pickApiChangeIssue tr - let containsIssue = V.any \(IssuesPage.IssueVM _ _ issue) -> issue.base.id == issueId + let containsIssue = V.any \(IssuesPage.IssueVM _ issue) -> issue.base.id == issueId withResource tr.trPool \conn -> do void $ PGS.execute conn [sql| UPDATE apis.issues SET archived_at=NULL, acknowledged_at=NULL, acknowledged_by=NULL WHERE id=? |] (Only issueId) @@ -547,7 +549,38 @@ spec = sequential $ aroundAll withTestResources do html `shouldSatisfy` T.isInfixOf "data-end=\"2026-09-02T10:04:43Z\"" html `shouldSatisfy` T.isInfixOf ("\"from\":\"" <> from <> "\"") html `shouldSatisfy` T.isInfixOf ("\"to\":\"" <> to <> "\"") - html `shouldSatisfy` T.isInfixOf "first_occurrence=true&from=2026-09-02T06" + html `shouldNotSatisfy` T.isInfixOf "first_occurrence=true" + html `shouldSatisfy` T.isInfixOf "Selected event is outside this range." + html `shouldSatisfy` T.isInfixOf "Jump to latest occurrence" + + it "spanSchemaIssue_doesNotLookUpTraceUsingLegacyHttpPlaceholders" \tr -> do + let subject = ApiChanges.SpanSchema Catalog.emptyScope{Catalog.service = Just "checkout", Catalog.spanName = Just "process-order"} + payload = + [aesonQQ|{ "subject": #{subject}, "endpoint_method": "UNKNOWN", "endpoint_path": "/", "endpoint_host": "Unknown", + "anomaly_hashes": [], "shape_changes": [], "format_changes": [], "new_fields": [], "deleted_fields": [], "modified_fields": [] }|] + traceIdText <- DataUUID.toText <$> UUID.nextRandom + issueId <- withResource tr.trPool \conn -> do + void + $ PGS.execute + conn + [sql| INSERT INTO otel_logs_and_spans + (id, project_id, timestamp, start_time, attributes___http___request___method, attributes___url___path, context___trace_id, summary) + VALUES (gen_random_uuid(), ?, ?, ?, 'UNKNOWN', '/', ?, '{}') |] + (testPid, frozenTime, frozenTime, traceIdText) + maybe (fail "expected schema issue") (pure . fromOnly) + . listToMaybe + =<< PGS.query + conn + [sql| INSERT INTO apis.issues + (project_id, issue_type, title, target_hash, issue_data, created_at, updated_at) + VALUES (?, 'api_change', 'Span schema changed', ?, ?::jsonb, ?, ?) RETURNING id |] + (testPid, "span-schema-" <> traceIdText, AE.encode payload, frozenTime, frozenTime) + (_, page) <- testServant tr $ IssuesPage.issueDetailGetH testPid issueId Nothing Nothing Nothing Nothing Nothing + let html = renderPage page + html `shouldSatisfy` T.isInfixOf "process-order" + html `shouldNotSatisfy` T.isInfixOf traceIdText + html `shouldSatisfy` T.isInfixOf "Span schema observed" + html `shouldNotSatisfy` T.isInfixOf "New endpoint discovered" it "log-pattern evidence loads separately and honors the shared absolute range" \tr -> do patternHash <- DataUUID.toText <$> UUID.nextRandom @@ -586,9 +619,10 @@ spec = sequential $ aroundAll withTestResources do sampleHtml `shouldSatisfy` T.isInfixOf ("/traces/" <> traceIdText <> "?timestamp=") (_, emptySample) <- testServant tr $ IssuesPage.issueSampleGetH testPid (UUIDId issueId) Nothing (Just $ iso $ addUTCTime 3600 frozenTime) (Just $ iso $ addUTCTime 3660 frozenTime) let emptyHtml = TL.toStrict $ renderText emptySample - emptyHtml `shouldSatisfy` T.isInfixOf "No matching event" + emptyHtml `shouldSatisfy` T.isInfixOf "No occurrences in this range." emptyHtml `shouldSatisfy` T.isInfixOf "Stored sample" emptyHtml `shouldSatisfy` T.isInfixOf "saved occurrence" + emptyHtml `shouldSatisfy` T.isInfixOf "independently of the date filter and raw-event retention" let otherPid = UUIDId $ DataUUID.fromWords 0x12345678 0x9abcdef0 0x12345678 0x9abcdef0 (_, otherProjectSample) <- testServant tr $ IssuesPage.issueSampleGetH otherPid (UUIDId issueId) Nothing (Just from) (Just to) TL.toStrict (renderText otherProjectSample) `shouldSatisfy` not . T.isInfixOf "occurrence" @@ -775,7 +809,7 @@ spec = sequential $ aroundAll withTestResources do it "issueList_mobileEventCount_labelsPeriodNotTimeFilter" \tr -> do void $ seedIssue tr Issues.LogPattern "mobile count probe" "mobile-count" (_, page) <- testServant tr $ IssuesPage.issueListGetH testPid (Just "Inbox") Nothing (Just "7d") Nothing (Just "100") Nothing (Just "24h") [] [] - renderPage page `shouldSatisfy` T.isInfixOf "0 events (24h)" + renderPage page `shouldSatisfy` T.isInfixOf "0 events · 24h" renderPage page `shouldNotSatisfy` T.isInfixOf "(7d)" it "the user journey offers search, newest-first ordering and copy, and skips contentless events" \tr -> do @@ -786,11 +820,11 @@ spec = sequential $ aroundAll withTestResources do apiKey <- createTestAPIKey tr testPid "journey-key" let at dt = addUTCTime dt frozenTime checkoutEvents = [mkSpanEvent "message" [("rpc.message.type", "SENT")] (at 0), mkSpanEvent "log" [("message", "checkout declined")] (at 0)] - forM_ @[] [(-2, "a1", "GET /cart", []), (-1, "a2", "cart item missing price", []), (0, "a3", "POST /checkout", checkoutEvents)] \(dt, sid, name, evs) -> + forM_ @[] [(-5, "a0", "page loaded", []), (-4, "b0", "cart opened", []), (-3, "c0", "shipping selected", []), (-2, "a1", "GET /cart", []), (-1, "a2", "cart item missing price", []), (0, "a3", "POST /checkout", checkoutEvents)] \(dt, sid, name, evs) -> ingestSpanReq tr $ mkSpanRequest traceIdText sid Nothing name evs Nothing [] (mkResource apiKey []) (at dt) issueId <- seedIssue tr Issues.RuntimeException "journey probe" "journey-probe" html <- eventually (renderPage . snd <$> testServant tr (IssuesPage.issueActivityGetH testPid issueId (Just traceIdText) (Just frozenTime))) (T.isInfixOf "checkout declined") - html `shouldContainAll` ["id=\"issue-journey\"", "Search the user journey", "crumb-rev", "issue-journey-text", "cart item missing price", "checkout declined"] + html `shouldContainAll` ["id=\"issue-journey\"", "Search the user journey", "crumb-rev", "issue-journey-text", "cart item missing price", "checkout declined", "id=\"issue-journey-events\"", "View all", "Show fewer", "Last 5 events"] html `shouldNotSatisfy` T.isInfixOf ">message" it "comments, external links and viewers show in the issue's activity" \tr -> do @@ -803,7 +837,7 @@ spec = sequential $ aroundAll withTestResources do _ <- testServant tr $ IssuesPage.linkPostH testPid iid (IssuesPage.LinkForm "javascript:alert(1)" Nothing) (_, activity) <- testServant tr $ IssuesPage.issueActivityGetH testPid iid Nothing Nothing let html = renderPage activity - html `shouldContainAll` ["Rolled back the cart service", "External links", "GitHub", "Cart crash", "Participating:", "name=\"body\""] + html `shouldContainAll` ["Rolled back the cart service", "External links", "GitHub", "Cart crash", "Participating:", "/api/avatar/", "People", "name=\"body\""] html `shouldSatisfy` not . T.isInfixOf "javascript:alert" -- Two views in a day record one, and views stay off the timeline. withResource tr.trPool (\conn -> PGS.query conn [sql| SELECT count(*)::int FROM apis.issue_activity_log WHERE issue_id = ? AND event = 'viewed' |] (Only iid)) `shouldReturn` [Only (1 :: Int)] @@ -834,8 +868,12 @@ spec = sequential $ aroundAll withTestResources do _ -> fail "no Location" eventually (stepTo Telemetry.Older (IssuesPage.EventRef tc (at 0))) (T.isInfixOf tb) >>= (`shouldSatisfy` T.isInfixOf tb) stepTo Telemetry.Older (IssuesPage.EventRef ta (at (-600))) >>= (`shouldSatisfy` T.isInfixOf ta) + -- A triage edit must not move a historical event's default investigation window. + withResource tr.trPool \conn -> void $ PGS.execute conn [sql| UPDATE apis.issues SET updated_at=? WHERE id=? |] (at 86400, iid) (_, page) <- testServant tr $ IssuesPage.issueDetailGetH testPid iid Nothing Nothing Nothing Nothing (Just $ IssuesPage.EventRef tb (at (-300))) renderPage page `shouldContainAll` [tb, "id=\"issue-events\"", "/step?dir=older", "/step?dir=recommended", "class=\"dropdown dropdown-end menu", "id=\"issue-copy-pop\""] + renderPage page `shouldContainAll` ["data-start=\"2024-12-31T21:55:00Z\"", "data-end=\"2025-01-01T01:55:00Z\"", "Around selected event", "±2 hours", "2024-12-31 23:55:00 UTC"] + renderPage page `shouldNotSatisfy` T.isInfixOf "Selected event is outside this range." it "category views, filter chips and saved views on the issue list" \tr -> do let list types = renderPage . snd <$> testServant tr (IssuesPage.issueListGetH testPid (Just "Inbox") Nothing Nothing Nothing Nothing Nothing (Just "24h") [] types) @@ -1344,11 +1382,11 @@ spec = sequential $ aroundAll withTestResources do isApiChange :: IssuesPage.IssueVM -> Bool -isApiChange (IssuesPage.IssueVM _ _ c) = c.base.issueType == Issues.ApiChange +isApiChange (IssuesPage.IssueVM _ c) = c.base.issueType == Issues.ApiChange issueOf :: IssuesPage.IssueVM -> Issues.IssueL -issueOf (IssuesPage.IssueVM _ _ issue) = issue +issueOf (IssuesPage.IssueVM _ issue) = issue issueIdOf :: IssuesPage.IssueVM -> Issues.IssueId diff --git a/test/integration/Pages/TelemetrySpec.hs b/test/integration/Pages/TelemetrySpec.hs index 44e99cf93..3ca97fbd1 100644 --- a/test/integration/Pages/TelemetrySpec.hs +++ b/test/integration/Pages/TelemetrySpec.hs @@ -155,7 +155,7 @@ spec = do ingestSpanReq tr $ withSpanStatus PT.Status'STATUS_CODE_ERROR $ withSpanKind PT.Span'SPAN_KIND_CLIENT - $ mkSpanRequest trId childSid (Just rootSid) "pg.query" [] Nothing [] (mkResource apiKey []) frozenTime + $ mkSpanRequest trId childSid (Just rootSid) "pg.query" [mkSpanEvent "exception" [] frozenTime] Nothing [mkAttr "db.statement" "\n SELECT \n FROM checkout\n \n"] (mkResource apiKey []) frozenTime traceM' <- runTestBg frozenTime tr $ Telemetry.getTraceDetailsForView False testPid trId (Just frozenTime) frozenTime Nothing spans <- maybe (fail "expected the ingested trace to be found") (\(_, sps, _) -> pure sps) traceM' @@ -173,6 +173,9 @@ spec = do let html = LT.toStrict $ Lucid.renderText $ Lucid.toHtml page for_ ["Waterfall", "GET /checkout", "pg.query", ">Errors1<"] \text -> html `shouldSatisfy` T.isInfixOf text + for_ ["